Changeset 23670
- Timestamp:
- 01/31/19 07:34:11 (6 years ago)
- Location:
- issm/trunk-jpl/src/py3
- Files:
-
- 154 edited
Legend:
- Unmodified
- Added
- Removed
-
issm/trunk-jpl/src/py3/boundaryconditions/PattynSMB.py
r21255 r23670 1 1 import os 2 import numpy as np2 import numpy as np 3 3 def PattynSMB(md,Tf): 4 4 """ -
issm/trunk-jpl/src/py3/boundaryconditions/SetIceSheetBC.py
r19895 r23670 1 1 import os 2 import numpy 2 import numpy as np 3 3 from ContourToMesh import ContourToMesh 4 4 … … 14 14 15 15 #node on Dirichlet 16 pos=n umpy.nonzero(md.mesh.vertexonboundary)17 md.stressbalance.spcvx=float('nan')*n umpy.ones(md.mesh.numberofvertices)18 md.stressbalance.spcvy=float('nan')*n umpy.ones(md.mesh.numberofvertices)19 md.stressbalance.spcvz=float('nan')*n umpy.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)) 20 20 md.stressbalance.spcvx[pos]=0 21 21 md.stressbalance.spcvy[pos]=0 22 22 md.stressbalance.spcvz[pos]=0 23 md.stressbalance.referential=float('nan')*n umpy.ones((md.mesh.numberofvertices,6))24 md.stressbalance.loadingforce=0*n umpy.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)) 25 25 26 26 #Dirichlet Values 27 if isinstance(md.inversion.vx_obs,n umpy.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: 28 28 print(" boundary conditions for stressbalance model: spc set as observed velocities") 29 29 md.stressbalance.spcvx[pos]=md.inversion.vx_obs[pos] … … 39 39 40 40 #Deal with other boundary conditions 41 if n umpy.all(numpy.isnan(md.balancethickness.thickening_rate)):42 md.balancethickness.thickening_rate=n umpy.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)) 43 43 print(" no balancethickness.thickening_rate specified: values set as zero") 44 md.masstransport.spcthickness=float('nan')*n umpy.ones((md.mesh.numberofvertices,1))45 md.balancethickness.spcthickness=float('nan')*n umpy.ones((md.mesh.numberofvertices,1))46 md.damage.spcdamage=float('nan')*n umpy.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)) 47 47 48 if isinstance(md.initialization.temperature,n umpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:49 md.thermal.spctemperature=float('nan')*n umpy.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)) 50 50 if hasattr(md.mesh,'vertexonsurface'): 51 pos=n umpy.nonzero(md.mesh.vertexonsurface)[0]51 pos=np.nonzero(md.mesh.vertexonsurface)[0] 52 52 md.thermal.spctemperature[pos]=md.initialization.temperature[pos] #impose observed temperature on surface 53 if not isinstance(md.basalforcings.geothermalflux,n umpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux)==md.mesh.numberofvertices:54 md.basalforcings.geothermalflux=50.*10**-3*n umpy.ones((md.mesh.numberofvertices,1)) #50 mW/m^253 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 55 55 else: 56 56 print(" no thermal boundary conditions created: no observed temperature found") -
issm/trunk-jpl/src/py3/boundaryconditions/SetIceShelfBC.py
r19895 r23670 1 1 import os 2 import numpy 2 import numpy as np 3 3 from ContourToMesh import ContourToMesh 4 4 import MatlabFuncs as m … … 26 26 if not os.path.exists(icefrontfile): 27 27 raise IOError("SetIceShelfBC error message: ice front file '%s' not found." % icefrontfile) 28 [nodeinsideicefront,dum]=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)29 nodeonicefront=n umpy.logical_and(md.mesh.vertexonboundary,nodeinsideicefront.reshape(-1))28 nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2) 29 nodeonicefront=np.logical_and(md.mesh.vertexonboundary,nodeinsideicefront.reshape(-1)) 30 30 else: 31 nodeonicefront=n umpy.zeros((md.mesh.numberofvertices),bool)31 nodeonicefront=np.zeros((md.mesh.numberofvertices),bool) 32 32 33 33 # pos=find(md.mesh.vertexonboundary & ~nodeonicefront); 34 pos=n umpy.nonzero(numpy.logical_and(md.mesh.vertexonboundary,numpy.logical_not(nodeonicefront)))[0]35 md.stressbalance.spcvx=float('nan')*n umpy.ones(md.mesh.numberofvertices)36 md.stressbalance.spcvy=float('nan')*n umpy.ones(md.mesh.numberofvertices)37 md.stressbalance.spcvz=float('nan')*n umpy.ones(md.mesh.numberofvertices)38 md.stressbalance.referential=float('nan')*n umpy.ones((md.mesh.numberofvertices,6))39 md.stressbalance.loadingforce=0*n umpy.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)) 40 40 41 41 #Icefront position 42 pos=n umpy.nonzero(nodeonicefront)[0]42 pos=np.nonzero(nodeonicefront)[0] 43 43 md.mask.ice_levelset[pos]=0 44 44 … … 53 53 values=md.mask.ice_levelset[md.mesh.segments[:,0:-1]-1] 54 54 segmentsfront=1-values 55 n umpy.sum(segmentsfront,axis=1)!=numbernodesfront56 segments=n umpy.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] 57 57 #Find all nodes for these segments and spc them 58 58 pos=md.mesh.segments[segments,0:-1]-1 59 59 else: 60 pos=n umpy.nonzero(md.mesh.vertexonboundary)[0]60 pos=np.nonzero(md.mesh.vertexonboundary)[0] 61 61 md.stressbalance.spcvx[pos]=0 62 62 md.stressbalance.spcvy[pos]=0 … … 64 64 65 65 #Dirichlet Values 66 if isinstance(md.inversion.vx_obs,n umpy.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: 67 67 #reshape to rank-2 if necessary to match spc arrays 68 if n umpy.ndim(md.inversion.vx_obs)==1:69 md.inversion.vx_obs=md.inversion.vx_obs.reshape(-1, 1)70 if n umpy.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,) 72 72 print(" boundary conditions for stressbalance model: spc set as observed velocities") 73 73 md.stressbalance.spcvx[pos]=md.inversion.vx_obs[pos] … … 81 81 82 82 #Deal with other boundary conditions 83 if n umpy.all(numpy.isnan(md.balancethickness.thickening_rate)):84 md.balancethickness.thickening_rate=n umpy.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)) 85 85 print(" no balancethickness.thickening_rate specified: values set as zero") 86 md.masstransport.spcthickness=float('nan')*n umpy.ones((md.mesh.numberofvertices,1))87 md.balancethickness.spcthickness=float('nan')*n umpy.ones((md.mesh.numberofvertices,1))88 md.damage.spcdamage=float('nan')*n umpy.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)) 89 89 90 if isinstance(md.initialization.temperature,n umpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:91 md.thermal.spctemperature=float('nan')*n umpy.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)) 92 92 if hasattr(md.mesh,'vertexonsurface'): 93 pos=n umpy.nonzero(md.mesh.vertexonsurface)[0]93 pos=np.nonzero(md.mesh.vertexonsurface)[0] 94 94 md.thermal.spctemperature[pos]=md.initialization.temperature[pos] #impose observed temperature on surface 95 if not isinstance(md.basalforcings.geothermalflux,n umpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux,axis=0)==md.mesh.numberofvertices:96 md.basalforcings.geothermalflux=n umpy.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)) 97 97 else: 98 98 print(" no thermal boundary conditions created: no observed temperature found") -
issm/trunk-jpl/src/py3/boundaryconditions/SetMarineIceSheetBC.py
r19895 r23670 1 1 import os 2 import numpy 2 import numpy as np 3 3 from ContourToMesh import ContourToMesh 4 4 import MatlabFuncs as m … … 28 28 if not os.path.exists(icefrontfile): 29 29 raise IOError("SetMarineIceSheetBC error message: ice front file '%s' not found." % icefrontfile) 30 [incontour,dum]=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)31 vertexonicefront=n umpy.logical_and(md.mesh.vertexonboundary,incontour.reshape(-1))30 incontour=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2) 31 vertexonicefront=np.logical_and(md.mesh.vertexonboundary,incontour.reshape(-1)) 32 32 else: 33 33 #Guess where the ice front is 34 vertexonfloatingice=n umpy.zeros((md.mesh.numberofvertices,1))35 pos=n umpy.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] 36 36 vertexonfloatingice[md.mesh.elements[pos].astype(int)-1]=1. 37 vertexonicefront=n umpy.logical_and(numpy.reshape(md.mesh.vertexonboundary,(-1,1)),vertexonfloatingice>0.)37 vertexonicefront=np.logical_and(np.reshape(md.mesh.vertexonboundary,(-1,)),vertexonfloatingice>0.) 38 38 39 39 # pos=find(md.mesh.vertexonboundary & ~vertexonicefront); 40 pos=n umpy.nonzero(numpy.logical_and(md.mesh.vertexonboundary,numpy.logical_not(vertexonicefront)))[0]41 if not n umpy.size(pos):40 pos=np.nonzero(np.logical_and(md.mesh.vertexonboundary,np.logical_not(vertexonicefront)))[0] 41 if not np.size(pos): 42 42 print("SetMarineIceSheetBC warning: ice front all around the glacier, no dirichlet found. Dirichlet must be added manually.") 43 43 44 md.stressbalance.spcvx=float('nan')*n umpy.ones(md.mesh.numberofvertices)45 md.stressbalance.spcvy=float('nan')*n umpy.ones(md.mesh.numberofvertices)46 md.stressbalance.spcvz=float('nan')*n umpy.ones(md.mesh.numberofvertices)47 md.stressbalance.referential=float('nan')*n umpy.ones((md.mesh.numberofvertices,6))48 md.stressbalance.loadingforce=0*n umpy.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)) 49 49 50 50 #Position of ice front 51 pos=n umpy.nonzero(vertexonicefront)[0]51 pos=np.nonzero(vertexonicefront)[0] 52 52 md.mask.ice_levelset[pos]=0 53 53 … … 62 62 values=md.mask.ice_levelset[md.mesh.segments[:,0:-1]-1] 63 63 segmentsfront=1-values 64 n umpy.sum(segmentsfront,axis=1)!=numbernodesfront65 segments=n umpy.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] 66 66 #Find all nodes for these segments and spc them 67 67 pos=md.mesh.segments[segments,0:-1]-1 68 68 else: 69 pos=n umpy.nonzero(md.mesh.vertexonboundary)[0]69 pos=np.nonzero(md.mesh.vertexonboundary)[0] 70 70 md.stressbalance.spcvx[pos]=0 71 71 md.stressbalance.spcvy[pos]=0 … … 73 73 74 74 #Dirichlet Values 75 if isinstance(md.inversion.vx_obs,n umpy.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: 76 76 print(" boundary conditions for stressbalance model: spc set as observed velocities") 77 77 md.stressbalance.spcvx[pos]=md.inversion.vx_obs[pos] … … 80 80 print(" boundary conditions for stressbalance model: spc set as zero") 81 81 82 md.hydrology.spcwatercolumn=n umpy.zeros((md.mesh.numberofvertices,2))83 pos=n umpy.nonzero(md.mesh.vertexonboundary)[0]82 md.hydrology.spcwatercolumn=np.zeros((md.mesh.numberofvertices,2)) 83 pos=np.nonzero(md.mesh.vertexonboundary)[0] 84 84 md.hydrology.spcwatercolumn[pos,0]=1 85 85 … … 89 89 90 90 #Deal with other boundary conditions 91 if n umpy.all(numpy.isnan(md.balancethickness.thickening_rate)):92 md.balancethickness.thickening_rate=n umpy.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)) 93 93 print(" no balancethickness.thickening_rate specified: values set as zero") 94 94 95 md.masstransport.spcthickness=float('nan')*n umpy.ones((md.mesh.numberofvertices,1))96 md.balancethickness.spcthickness=float('nan')*n umpy.ones((md.mesh.numberofvertices,1))97 md.damage.spcdamage=float('nan')*n umpy.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)) 98 98 99 if isinstance(md.initialization.temperature,n umpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:100 md.thermal.spctemperature=float('nan')*n umpy.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)) 101 101 if hasattr(md.mesh,'vertexonsurface'): 102 pos=n umpy.nonzero(md.mesh.vertexonsurface)[0]102 pos=np.nonzero(md.mesh.vertexonsurface)[0] 103 103 md.thermal.spctemperature[pos]=md.initialization.temperature[pos] #impose observed temperature on surface 104 if not isinstance(md.basalforcings.geothermalflux,n umpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux,axis=0)==md.mesh.numberofvertices:105 md.basalforcings.geothermalflux=n umpy.zeros((md.mesh.numberofvertices,1))106 md.basalforcings.geothermalflux[n umpy.nonzero(md.mask.groundedice_levelset>0.)]=50.*10.**-3 #50mW/m2104 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 107 107 else: 108 108 print(" no thermal boundary conditions created: no observed temperature found") -
issm/trunk-jpl/src/py3/classes/SMBcomponents.py
r19898 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *3 2 from checkfield import * 4 3 from project3d import * … … 39 38 def initialize(self,md): # {{{ 40 39 41 if n umpy.all(numpy.isnan(self.accumulation)):42 self.accumulation=n umpy.zeros((md.mesh.numberofvertices,1))40 if np.all(np.isnan(self.accumulation)): 41 self.accumulation=np.zeros((md.mesh.numberofvertices)) 43 42 print(" no SMB.accumulation specified: values set as zero") 44 43 45 if n umpy.all(numpy.isnan(self.runoff)):46 self.runoff=n umpy.zeros((md.mesh.numberofvertices,1))44 if np.all(np.isnan(self.runoff)): 45 self.runoff=np.zeros((md.mesh.numberofvertices)) 47 46 print(" no SMB.runoff specified: values set as zero") 48 47 49 if n umpy.all(numpy.isnan(self.evaporation)):50 self.evaporation=n umpy.zeros((md.mesh.numberofvertices,1))48 if np.all(np.isnan(self.evaporation)): 49 self.evaporation=np.zeros((md.mesh.numberofvertices)) 51 50 print(" no SMB.evaporation specified: values set as zero") 52 51 … … 55 54 def checkconsistency(self,md,solution,analyses): # {{{ 56 55 57 if MasstransportAnalysisEnum()in analyses:56 if 'MasstransportAnalysis' in analyses: 58 57 md = checkfield(md,'fieldname','smb.accumulation','timeseries',1,'NaN',1,'Inf',1) 59 58 60 if BalancethicknessAnalysisEnum()in analyses:59 if 'BalancethicknessAnalysis' in analyses: 61 60 md = checkfield(md,'fieldname','smb.accumulation','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 62 61 63 if MasstransportAnalysisEnum()in analyses:62 if 'MasstransportAnalysis' in analyses: 64 63 md = checkfield(md,'fieldname','smb.runoff','timeseries',1,'NaN',1,'Inf',1) 65 64 66 if BalancethicknessAnalysisEnum()in analyses:65 if 'BalancethicknessAnalysis' in analyses: 67 66 md = checkfield(md,'fieldname','smb.runoff','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 68 67 69 if MasstransportAnalysisEnum()in analyses:68 if 'MasstransportAnalysis' in analyses: 70 69 md = checkfield(md,'fieldname','smb.evaporation','timeseries',1,'NaN',1,'Inf',1) 71 70 72 if BalancethicknessAnalysisEnum()in analyses:71 if 'BalancethicknessAnalysis' in analyses: 73 72 md = checkfield(md,'fieldname','smb.evaporation','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 74 73 … … 77 76 return md 78 77 # }}} 79 def marshall(self, md,fid): # {{{78 def marshall(self,prefix,md,fid): # {{{ 80 79 81 yts= 365.0*24.0*3600.080 yts=md.constants.yts 82 81 83 WriteData(fid, 'enum',SmbEnum(),'data',SMBcomponentsEnum(),'format','Integer');84 WriteData(fid, 'object',self,'class','smb','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)85 WriteData(fid, 'object',self,'class','smb','fieldname','runoff','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)86 WriteData(fid, 'object',self,'class','smb','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)82 WriteData(fid,prefix,'name','md.smb.model','data',2,'format','Integer'); 83 WriteData(fid,prefix,'object',self,'class','smb','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 84 WriteData(fid,prefix,'object',self,'class','smb','fieldname','runoff','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 85 WriteData(fid,prefix,'object',self,'class','smb','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 87 86 88 87 #process requested outputs … … 92 91 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 93 92 outputs =outputscopy 94 WriteData(fid, 'data',outputs,'enum',SmbRequestedOutputsEnum(),'format','StringArray')93 WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray') 95 94 96 95 # }}} -
issm/trunk-jpl/src/py3/classes/SMBd18opdd.py
r19898 r23670 1 import numpy 1 import numpy as np 2 2 from fielddisplay import fielddisplay 3 from EnumDefinitions import *4 3 from checkfield import checkfield 5 4 from WriteData import WriteData … … 21 20 self.rlapslgm = 0. 22 21 self.dpermil = 0. 22 self.f = 0. 23 23 self.Tdiff = float('NaN') 24 24 self.sealev = float('NaN') 25 25 self.ismungsm = 0 26 26 self.isd18opd = 0 27 self.issetpddfac = 0 28 self.istemperaturescaled = 0 29 self.isprecipscaled = 0 27 30 self.delta18o = float('NaN') 28 31 self.delta18o_surface = float('NaN') 29 32 self.temperatures_presentday = float('NaN') 30 33 self.precipitations_presentday = float('NaN') 34 self.temperatures_reconstructed = float('NaN') 35 self.precipitations_reconstructed = float('NaN') 36 self.pddfac_snow = float('NaN') 37 self.pddfac_ice = float('NaN') 31 38 32 39 #set defaults … … 38 45 39 46 string="%s\n%s"%(string,fielddisplay(self,'isd18opd','is delta18o parametrisation from present day temperature and precipitation activated (0 or 1, default is 0)')) 47 string="%s\n%s"%(string,fielddisplay(self,'issetpddfac','is user passing in defined pdd factors at each vertex (0 or 1, default is 0)')) 40 48 string="%s\n%s"%(string,fielddisplay(self,'desfac','desertification elevation factor (between 0 and 1, default is 0.5) [m]')) 41 49 string="%s\n%s"%(string,fielddisplay(self,'s0p','should be set to elevation from precip source (between 0 and a few 1000s m, default is 0) [m]')) … … 45 53 string="%s\n%s"%(string,fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [K], required if delta18o/mungsm is activated')) 46 54 string="%s\n%s"%(string,fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if delta18o or mungsm is activated')) 55 string="%s\n%s"%(string,fielddisplay(self,'istemperaturescaled','if delta18o parametrisation from present day temperature and precipitation is activated, is temperature scaled to delta18o value? (0 or 1, default is 1)')) 56 string="%s\n%s"%(string,fielddisplay(self,'isprecipscaled','if delta18o parametrisation from present day temperature and precipitation is activated, is precipitation scaled to delta18o value? (0 or 1, default is 1)')) 57 58 if self.istemperaturescaled==0: 59 string="%s\n%s"%(string,fielddisplay(self,'temperatures_reconstructed','monthly historical surface temperatures [K], required if delta18o/mungsm/d18opd is activated and istemperaturescaled is not activated')) 60 61 if self.isprecipscaled==0: 62 string="%s\n%s"%(string,fielddisplay(self,'precipitations_reconstructed','monthly historical precipitation [m/yr water eq], required if delta18o/mungsm/d18opd is activated and isprecipscaled is not activated')) 63 47 64 string="%s\n%s"%(string,fielddisplay(self,'delta18o','delta18o [per mil], required if pdd is activated and delta18o activated')) 48 65 string="%s\n%s"%(string,fielddisplay(self,'dpermil','degree per mil, required if d18opd is activated')) 66 string="%s\n%s"%(string,fielddisplay(self,'f','precip/temperature scaling factor, required if d18opd is activated')) 67 68 if self.issetpddfac==1: 69 string="%s\n%s"%(string,fielddisplay(self,'pddfac_snow','Pdd factor for snow, at each vertex [mm ice equiv/day/degree C]')) 70 string="%s\n%s"%(string,fielddisplay(self,'pddfac_ice','Pdd factor for ice, at each vertex [mm ice equiv/day/degree C]')) 49 71 string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested')) 50 72 … … 55 77 if self.isd18opd: self.temperatures_presentday=project3d(md,'vector',self.temperatures_presentday,'type','node') 56 78 if self.isd18opd: self.precipitations_presentday=project3d(md,'vector',self.precipitations_presentday,'type','node') 79 if self.istemperaturescaled==0: self.temperatures_reconstructed=project3d(md,'vector',self.temperatures_reconstructed,'type','node') 80 if self.isprecipscaled==0: self.temperatures_reconstructed=project3d(md,'vector',self.precipitations_reconstructed,'type','node') 81 if self.isd18opd: self.precipitations_presentday=project3d(md,'vector',self.precipitations_presentday,'type','node') 82 if self.issetpddfac: self.pddfac_snow=project3d(md,'vector',self.pddfac_snow,'type','node') 83 if self.issetpddfac: self.pddfac_ice=project3d(md,'vector',self.pddfac_ice,'type','node') 57 84 self.s0p=project3d(md,'vector',self.s0p,'type','node') 58 85 self.s0t=project3d(md,'vector',self.s0t,'type','node') … … 65 92 def initialize(self,md): # {{{ 66 93 67 if n umpy.all(numpy.isnan(self.s0p)):68 self.s0p=n umpy.zeros((md.mesh.numberofvertices,1))94 if np.all(np.isnan(self.s0p)): 95 self.s0p=np.zeros((md.mesh.numberofvertices)) 69 96 print(" no SMBd18opdd.s0p specified: values set as zero") 70 97 71 if n umpy.all(numpy.isnan(self.s0t)):72 self.s0t=n umpy.zeros((md.mesh.numberofvertices,1))98 if np.all(np.isnan(self.s0t)): 99 self.s0t=np.zeros((md.mesh.numberofvertices)) 73 100 print(" no SMBd18opdd.s0t specified: values set as zero") 74 101 … … 80 107 self.ismungsm = 0 81 108 self.isd18opd = 1 109 self.istemperaturescaled = 1 110 self.isprecipscaled = 1 82 111 self.desfac = 0.5 83 112 self.rlaps = 6.5 84 113 self.rlapslgm = 6.5 85 114 self.dpermil = 2.4 86 115 self.f = 0.169 116 self.issetpddfac = 0 87 117 return self 88 118 #}}} 89 119 def checkconsistency(self,md,solution,analyses): # {{{ 90 120 91 if MasstransportAnalysisEnum()in analyses:121 if 'MasstransportAnalysis' in analyses: 92 122 md = checkfield(md,'fieldname','smb.desfac','<=',1,'numel',[1]) 93 md = checkfield(md,'fieldname','smb.s0p','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices ,1])94 md = checkfield(md,'fieldname','smb.s0t','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices ,1])123 md = checkfield(md,'fieldname','smb.s0p','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 124 md = checkfield(md,'fieldname','smb.s0t','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 95 125 md = checkfield(md,'fieldname','smb.rlaps','>=',0,'numel',[1]) 96 126 md = checkfield(md,'fieldname','smb.rlapslgm','>=',0,'numel',[1]) 97 127 98 128 if self.isd18opd: 129 lent=float(np.size(self.temperatures_presentday,1)) 130 lenp=float(np.size(self.precipitations_presentday,1)) 131 multt=np.ceil(lent/12.)*12. 132 multp=np.ceil(lenp/12.)*12. 99 133 md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1) 100 134 md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1) 101 md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1) 135 136 if self.istemperaturescaled==0: 137 lent=float(np.size(self.temperatures_reconstructed,1)) 138 multt=np.ceil(lent/12.)*12. 139 md = checkfield(md,'fieldname','smb.temperatures_reconstructed','size',[md.mesh.numberofvertices+1,multt],'NaN',1,'Inf',1,'timeseries',1) 140 141 if self.isprecipscaled==0: 142 lenp=float(np.size(self.precipitations_reconstructed,1)) 143 multp=np.ceil(lent/12.)*12. 144 md = checkfield(md,'fieldname','smb.precipitations_reconstructed','size',[md.mesh.numberofvertices+1,multt],'NaN',1,'Inf',1,'timeseries',1) 145 146 md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1) 102 147 md = checkfield(md,'fieldname','smb.dpermil','>=',0,'numel',[1]) 103 148 md = checkfield(md,'fieldname','smb.f','>=',0,'numel',[1]) 149 150 if self.issetpddfac: 151 md = checkfield(md,'fieldname','smb.pddfac_snow','>=',0,'NaN',1,'Inf',1) 152 md = checkfield(md,'fieldname','smb.pddfac_ice','>=',0,'NaN',1,'Inf',1) 153 104 154 md = checkfield(md,'fieldname','masstransport.requested_outputs','stringrow',1) 105 155 106 156 return md 107 157 # }}} 108 def marshall(self,md,fid): # {{{ 109 110 yts=365.0*24.0*3600.0 111 112 WriteData(fid,'enum',SmbEnum(),'data',SMBd18opddEnum(),'format','Integer') 113 114 WriteData(fid,'object',self,'class','smb','fieldname','ismungsm','format','Boolean') 115 WriteData(fid,'object',self,'class','smb','fieldname','isd18opd','format','Boolean') 116 WriteData(fid,'object',self,'class','smb','fieldname','desfac','format','Double') 117 WriteData(fid,'object',self,'class','smb','fieldname','s0p','format','DoubleMat','mattype',1); 118 WriteData(fid,'object',self,'class','smb','fieldname','s0t','format','DoubleMat','mattype',1); 119 WriteData(fid,'object',self,'class','smb','fieldname','rlaps','format','Double') 120 WriteData(fid,'object',self,'class','smb','fieldname','rlapslgm','format','Double') 121 WriteData(fid,'object',self,'class','smb','fieldname','Tdiff','format','DoubleMat','mattype',1,'timeserieslength',2) 122 WriteData(fid,'object',self,'class','smb','fieldname','sealev','format','DoubleMat','mattype',1,'timeserieslength',2) 158 def marshall(self,prefix,md,fid): # {{{ 159 160 yts=md.constants.yts 161 162 WriteData(fid,prefix,'name','md.smb.model','data',5,'format','Integer') 163 164 WriteData(fid,prefix,'object',self,'class','smb','fieldname','ismungsm','format','Boolean') 165 WriteData(fid,prefix,'object',self,'class','smb','fieldname','isd18opd','format','Boolean') 166 WriteData(fid,prefix,'object',self,'class','smb','fieldname','issetpddfac','format','Boolean'); 167 WriteData(fid,prefix,'object',self,'class','smb','fieldname','desfac','format','Double') 168 WriteData(fid,prefix,'object',self,'class','smb','fieldname','s0p','format','DoubleMat','mattype',1); 169 WriteData(fid,prefix,'object',self,'class','smb','fieldname','s0t','format','DoubleMat','mattype',1); 170 WriteData(fid,prefix,'object',self,'class','smb','fieldname','rlaps','format','Double') 171 WriteData(fid,prefix,'object',self,'class','smb','fieldname','rlapslgm','format','Double') 172 WriteData(fid,prefix,'object',self,'class','smb','fieldname','Tdiff','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts) 173 WriteData(fid,prefix,'object',self,'class','smb','fieldname','sealev','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts) 123 174 124 175 if self.isd18opd: 125 WriteData(fid,'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1) 126 WriteData(fid,'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1) 127 WriteData(fid,'object',self,'class','smb','fieldname','delta18o','format','DoubleMat','mattype',1,'timeserieslength',2) 128 WriteData(fid,'object',self,'class','smb','fieldname','dpermil','format','Double') 129 176 WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 177 WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 178 WriteData(fid,prefix,'object',self,'class','smb','fieldname','istemperaturescaled','format','Boolean') 179 WriteData(fid,prefix,'object',self,'class','smb','fieldname','isprecipscaled','format','Boolean') 180 181 if self.istemperaturescaled==0: 182 WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_reconstructed','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 183 184 if self.isprecipscaled==0: 185 WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_reconstructed','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 186 187 WriteData(fid,prefix,'object',self,'class','smb','fieldname','delta18o','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts) 188 WriteData(fid,prefix,'object',self,'class','smb','fieldname','dpermil','format','Double') 189 WriteData(fid,prefix,'object',self,'class','smb','fieldname','f','format','Double') 190 191 if self.issetpddfac: 192 WriteData(fid,prefix,'object',self,'class','smb','fieldname','pddfac_snow','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 193 WriteData(fid,prefix,'object',self,'class','smb','fieldname','pddfac_ice','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 194 130 195 #process requested outputs 131 196 outputs = self.requested_outputs … … 134 199 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 135 200 outputs =outputscopy 136 WriteData(fid, 'data',outputs,'enum',SmbRequestedOutputsEnum(),'format','StringArray')201 WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray') 137 202 138 203 # }}} -
issm/trunk-jpl/src/py3/classes/SMBforcing.py
r19898 r23670 1 import numpy 1 import numpy as np 2 2 from fielddisplay import fielddisplay 3 from EnumDefinitions import *4 3 from checkfield import checkfield 5 4 from WriteData import WriteData … … 34 33 def initialize(self,md): # {{{ 35 34 36 if n umpy.all(numpy.isnan(self.mass_balance)):37 self.mass_balance=n umpy.zeros((md.mesh.numberofvertices,1))35 if np.all(np.isnan(self.mass_balance)): 36 self.mass_balance=np.zeros((md.mesh.numberofvertices)) 38 37 print(" no SMBforcing.mass_balance specified: values set as zero") 39 38 … … 42 41 def checkconsistency(self,md,solution,analyses): # {{{ 43 42 44 if MasstransportAnalysisEnum()in analyses:43 if 'MasstransportAnalysis' in analyses: 45 44 md = checkfield(md,'fieldname','smb.mass_balance','timeseries',1,'NaN',1,'Inf',1) 46 45 47 if BalancethicknessAnalysisEnum()in analyses:46 if 'BalancethicknessAnalysis' in analyses: 48 47 md = checkfield(md,'fieldname','smb.mass_balance','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 49 48 … … 51 50 return md 52 51 # }}} 53 def marshall(self, md,fid): # {{{52 def marshall(self,prefix,md,fid): # {{{ 54 53 55 yts= 365.0*24.0*3600.054 yts=md.constants.yts 56 55 57 WriteData(fid,'enum',SmbEnum(),'data',SMBforcingEnum(),'format','Integer'); 58 WriteData(fid,'object',self,'class','smb','fieldname','mass_balance','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1) 56 WriteData(fid,prefix,'name','md.smb.model','data',1,'format','Integer'); 57 WriteData(fid,prefix,'object',self,'class','smb','fieldname','mass_balance','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 58 #WriteData(fid,prefix,'object',self,'class','smb','fieldname','mass_balance','format','CompressedMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts); 59 59 60 60 #process requested outputs … … 64 64 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 65 65 outputs =outputscopy 66 WriteData(fid, 'data',outputs,'enum',SmbRequestedOutputsEnum(),'format','StringArray')66 WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray') 67 67 68 68 # }}} -
issm/trunk-jpl/src/py3/classes/SMBgradients.py
r19898 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *3 2 from checkfield import checkfield 4 3 from WriteData import WriteData … … 48 47 def checkconsistency(self,md,solution,analyses): # {{{ 49 48 50 if MasstransportAnalysisEnum()in analyses:49 if 'MasstransportAnalysis' in analyses: 51 50 md = checkfield(md,'fieldname','smb.href','timeseries',1,'NaN',1,'Inf',1) 52 51 md = checkfield(md,'fieldname','smb.smbref','timeseries',1,'NaN',1,'Inf',1) … … 57 56 return md 58 57 # }}} 59 def marshall(self, md,fid): # {{{58 def marshall(self,prefix,md,fid): # {{{ 60 59 61 yts= 365.0*24.0*3600.060 yts=md.constants.yts 62 61 63 WriteData(fid, 'enum',SmbEnum(),'data',SMBgradientsEnum(),'format','Integer');64 WriteData(fid, 'object',self,'class','smb','fieldname','href','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)65 WriteData(fid, 'object',self,'class','smb','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)66 WriteData(fid, 'object',self,'class','smb','fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)67 WriteData(fid, 'object',self,'class','smb','fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)62 WriteData(fid,prefix,'name','md.smb.model','data',6,'format','Integer'); 63 WriteData(fid,prefix,'object',self,'class','smb','fieldname','href','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 64 WriteData(fid,prefix,'object',self,'class','smb','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 65 WriteData(fid,prefix,'object',self,'class','smb','fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 66 WriteData(fid,prefix,'object',self,'class','smb','fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 68 67 69 68 #process requested outputs … … 73 72 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 74 73 outputs =outputscopy 75 WriteData(fid, 'data',outputs,'enum',SmbRequestedOutputsEnum(),'format','StringArray')74 WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray') 76 75 77 76 # }}} -
issm/trunk-jpl/src/py3/classes/SMBmeltcomponents.py
r19898 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *3 2 from checkfield import * 4 3 from project3d import * … … 30 29 def extrude(self,md): # {{{ 31 30 32 self. mass_balance=project3d(md,'vector',self.accumulation,'type','node');33 self. mass_balance=project3d(md,'vector',self.evaporation,'type','node');34 self.m ass_balance=project3d(md,'vector',self.melt,'type','node');35 self. mass_balance=project3d(md,'vector',self.refreeze,'type','node');31 self.accumulation=project3d(md,'vector',self.accumulation,'type','node'); 32 self.evaporation=project3d(md,'vector',self.evaporation,'type','node'); 33 self.melt=project3d(md,'vector',self.melt,'type','node'); 34 self.refreeze=project3d(md,'vector',self.refreeze,'type','node'); 36 35 return self 37 36 #}}} … … 41 40 def initialize(self,md): # {{{ 42 41 43 if n umpy.all(numpy.isnan(self.accumulation)):44 self.accumulation=n umpy.zeros((md.mesh.numberofvertices,1))42 if np.all(np.isnan(self.accumulation)): 43 self.accumulation=np.zeros((md.mesh.numberofvertices)) 45 44 print(" no SMB.accumulation specified: values set as zero") 46 45 47 if n umpy.all(numpy.isnan(self.evaporation)):48 self.evaporation=n umpy.zeros((md.mesh.numberofvertices,1))46 if np.all(np.isnan(self.evaporation)): 47 self.evaporation=np.zeros((md.mesh.numberofvertices)) 49 48 print(" no SMB.evaporation specified: values set as zero") 50 49 51 if n umpy.all(numpy.isnan(self.melt)):52 self.melt=n umpy.zeros((md.mesh.numberofvertices,1))50 if np.all(np.isnan(self.melt)): 51 self.melt=np.zeros((md.mesh.numberofvertices)) 53 52 print(" no SMB.melt specified: values set as zero") 54 53 55 if n umpy.all(numpy.isnan(self.refreeze)):56 self.refreeze=n umpy.zeros((md.mesh.numberofvertices,1))54 if np.all(np.isnan(self.refreeze)): 55 self.refreeze=np.zeros((md.mesh.numberofvertices)) 57 56 print(" no SMB.refreeze specified: values set as zero") 58 57 … … 61 60 def checkconsistency(self,md,solution,analyses): # {{{ 62 61 63 if MasstransportAnalysisEnum()in analyses:62 if 'MasstransportAnalysis' in analyses: 64 63 md = checkfield(md,'fieldname','smb.accumulation','timeseries',1,'NaN',1,'Inf',1) 65 64 66 if BalancethicknessAnalysisEnum()in analyses:65 if 'BalancethicknessAnalysis' in analyses: 67 66 md = checkfield(md,'fieldname','smb.accumulation','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 68 67 69 if MasstransportAnalysisEnum()in analyses:68 if 'MasstransportAnalysis' in analyses: 70 69 md = checkfield(md,'fieldname','smb.melt','timeseries',1,'NaN',1,'Inf',1) 71 70 72 if BalancethicknessAnalysisEnum()in analyses:71 if 'BalancethicknessAnalysis' in analyses: 73 72 md = checkfield(md,'fieldname','smb.melt','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 74 73 75 if MasstransportAnalysisEnum()in analyses:74 if 'MasstransportAnalysis' in analyses: 76 75 md = checkfield(md,'fieldname','smb.refreeze','timeseries',1,'NaN',1,'Inf',1) 77 76 78 if BalancethicknessAnalysisEnum()in analyses:77 if 'BalancethicknessAnalysis' in analyses: 79 78 md = checkfield(md,'fieldname','smb.refreeze','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 80 79 81 if MasstransportAnalysisEnum()in analyses:80 if 'MasstransportAnalysis' in analyses: 82 81 md = checkfield(md,'fieldname','smb.evaporation','timeseries',1,'NaN',1,'Inf',1) 83 82 84 if BalancethicknessAnalysisEnum()in analyses:83 if 'BalancethicknessAnalysis' in analyses: 85 84 md = checkfield(md,'fieldname','smb.evaporation','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 86 85 … … 88 87 return md 89 88 # }}} 90 def marshall(self, md,fid): # {{{89 def marshall(self,prefix,md,fid): # {{{ 91 90 92 yts= 365.0*24.0*3600.091 yts=md.constants.yts 93 92 94 WriteData(fid, 'enum',SmbEnum(),'data',SMBmeltcomponentsEnum(),'format','Integer');95 WriteData(fid, 'object',self,'class','smb','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)96 WriteData(fid, 'object',self,'class','smb','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)97 WriteData(fid, 'object',self,'class','smb','fieldname','melt','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)98 WriteData(fid, 'object',self,'class','smb','fieldname','refreeze','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)99 93 WriteData(fid,prefix,'name','md.smb.model','data',3,'format','Integer'); 94 WriteData(fid,prefix,'object',self,'class','smb','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 95 WriteData(fid,prefix,'object',self,'class','smb','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 96 WriteData(fid,prefix,'object',self,'class','smb','fieldname','melt','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 97 WriteData(fid,prefix,'object',self,'class','smb','fieldname','refreeze','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 98 100 99 #process requested outputs 101 100 outputs = self.requested_outputs … … 104 103 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 105 104 outputs =outputscopy 106 WriteData(fid, 'data',outputs,'enum',SmbRequestedOutputsEnum(),'format','StringArray')105 WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray') 107 106 108 107 # }}} -
issm/trunk-jpl/src/py3/classes/SMBpdd.py
r19898 r23670 1 import numpy 1 import numpy as np 2 2 from fielddisplay import fielddisplay 3 from EnumDefinitions import *4 3 from checkfield import checkfield 5 4 from WriteData import WriteData … … 27 26 self.isdelta18o = 0 28 27 self.ismungsm = 0 28 self.issetpddfac = 0 29 29 self.delta18o = float('NaN') 30 30 self.delta18o_surface = float('NaN') … … 95 95 def initialize(self,md): # {{{ 96 96 97 if n umpy.all(numpy.isnan(self.s0p)):98 self.s0p=n umpy.zeros((md.mesh.numberofvertices,1))97 if np.all(np.isnan(self.s0p)): 98 self.s0p=np.zeros((md.mesh.numberofvertices)) 99 99 print(" no SMBpdd.s0p specified: values set as zero") 100 100 101 if n umpy.all(numpy.isnan(self.s0t)):102 self.s0t=n umpy.zeros((md.mesh.numberofvertices,1))101 if np.all(np.isnan(self.s0t)): 102 self.s0t=np.zeros((md.mesh.numberofvertices)) 103 103 print(" no SMBpdd.s0t specified: values set as zero") 104 104 … … 118 118 def checkconsistency(self,md,solution,analyses): # {{{ 119 119 120 if MasstransportAnalysisEnum()in analyses:120 if 'MasstransportAnalysis' in analyses: 121 121 md = checkfield(md,'fieldname','smb.desfac','<=',1,'numel',[1]) 122 md = checkfield(md,'fieldname','smb.s0p','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices ,1])123 md = checkfield(md,'fieldname','smb.s0t','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices ,1])122 md = checkfield(md,'fieldname','smb.s0p','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 123 md = checkfield(md,'fieldname','smb.s0t','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 124 124 md = checkfield(md,'fieldname','smb.rlaps','>=',0,'numel',[1]) 125 125 md = checkfield(md,'fieldname','smb.rlapslgm','>=',0,'numel',[1]) … … 129 129 md = checkfield(md,'fieldname','smb.precipitation','NaN',1,'Inf',1,'timeseries',1) 130 130 elif self.isdelta18o: 131 md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,n umpy.nan],'singletimeseries',1)132 md = checkfield(md,'fieldname','smb.delta18o_surface','NaN',1,'Inf',1,'size',[2,n umpy.nan],'singletimeseries',1)131 md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1) 132 md = checkfield(md,'fieldname','smb.delta18o_surface','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1) 133 133 md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1) 134 134 md = checkfield(md,'fieldname','smb.temperatures_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1) 135 135 md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1) 136 136 md = checkfield(md,'fieldname','smb.precipitations_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1) 137 md = checkfield(md,'fieldname','smb.Tdiff','NaN',1,'Inf',1,'size',[2,n umpy.nan],'singletimeseries',1)138 md = checkfield(md,'fieldname','smb.sealev','NaN',1,'Inf',1,'size',[2,n umpy.nan],'singletimeseries',1)137 md = checkfield(md,'fieldname','smb.Tdiff','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1) 138 md = checkfield(md,'fieldname','smb.sealev','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1) 139 139 elif self.ismungsm: 140 140 md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1) … … 142 142 md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1) 143 143 md = checkfield(md,'fieldname','smb.precipitations_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1) 144 md = checkfield(md,'fieldname','smb.Pfac','NaN',1,'Inf',1,'size',[2,n umpy.nan],'singletimeseries',1)145 md = checkfield(md,'fieldname','smb.Tdiff','NaN',1,'Inf',1,'size',[2,n umpy.nan],'singletimeseries',1)146 md = checkfield(md,'fieldname','smb.sealev','NaN',1,'Inf',1,'size',[2,n umpy.nan],'singletimeseries',1)144 md = checkfield(md,'fieldname','smb.Pfac','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1) 145 md = checkfield(md,'fieldname','smb.Tdiff','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1) 146 md = checkfield(md,'fieldname','smb.sealev','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1) 147 147 148 148 md = checkfield(md,'fieldname','masstransport.requested_outputs','stringrow',1) 149 149 return md 150 150 #}}} 151 def marshall(self, md,fid): # {{{151 def marshall(self,prefix,md,fid): # {{{ 152 152 153 yts= 365.0*24.0*3600.0153 yts=md.constants.yts 154 154 155 WriteData(fid, 'enum',SmbEnum(),'data',SMBpddEnum(),'format','Integer')155 WriteData(fid,prefix,'name','md.smb.model','data',4,'format','Integer') 156 156 157 WriteData(fid,'object',self,'class','smb','fieldname','isdelta18o','format','Boolean') 158 WriteData(fid,'object',self,'class','smb','fieldname','ismungsm','format','Boolean') 159 WriteData(fid,'object',self,'class','smb','fieldname','desfac','format','Double') 160 WriteData(fid,'object',self,'class','smb','fieldname','s0p','format','DoubleMat','mattype',1); 161 WriteData(fid,'object',self,'class','smb','fieldname','s0t','format','DoubleMat','mattype',1); 162 WriteData(fid,'object',self,'class','smb','fieldname','rlaps','format','Double') 163 WriteData(fid,'object',self,'class','smb','fieldname','rlapslgm','format','Double') 157 WriteData(fid,prefix,'object',self,'class','smb','fieldname','isdelta18o','format','Boolean') 158 WriteData(fid,prefix,'object',self,'class','smb','fieldname','ismungsm','format','Boolean') 159 WriteData(fid,prefix,'object',self,'class','smb','fieldname','issetpddfac','format','Boolean'); 160 WriteData(fid,prefix,'object',self,'class','smb','fieldname','desfac','format','Double') 161 WriteData(fid,prefix,'object',self,'class','smb','fieldname','s0p','format','DoubleMat','mattype',1); 162 WriteData(fid,prefix,'object',self,'class','smb','fieldname','s0t','format','DoubleMat','mattype',1); 163 WriteData(fid,prefix,'object',self,'class','smb','fieldname','rlaps','format','Double') 164 WriteData(fid,prefix,'object',self,'class','smb','fieldname','rlapslgm','format','Double') 164 165 165 166 if (self.isdelta18o==0 and self.ismungsm==0): 166 WriteData(fid, 'object',self,'class','smb','fieldname','monthlytemperatures','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)167 WriteData(fid, 'object',self,'class','smb','fieldname','precipitation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)167 WriteData(fid,prefix,'object',self,'class','smb','fieldname','monthlytemperatures','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 168 WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 168 169 elif self.isdelta18o: 169 WriteData(fid, 'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)170 WriteData(fid, 'object',self,'class','smb','fieldname','temperatures_lgm','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)171 WriteData(fid, 'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)172 WriteData(fid, 'object',self,'class','smb','fieldname','precipitations_lgm','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)173 WriteData(fid, 'object',self,'class','smb','fieldname','delta18o_surface','format','DoubleMat','mattype',1,'timeserieslength',2)174 WriteData(fid, 'object',self,'class','smb','fieldname','delta18o','format','DoubleMat','mattype',1,'timeserieslength',2)175 WriteData(fid, 'object',self,'class','smb','fieldname','Tdiff','format','DoubleMat','mattype',1,'timeserieslength',2)176 WriteData(fid, 'object',self,'class','smb','fieldname','sealev','format','DoubleMat','mattype',1,'timeserieslength',2)170 WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 171 WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_lgm','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 172 WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 173 WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_lgm','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 174 WriteData(fid,prefix,'object',self,'class','smb','fieldname','delta18o_surface','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts) 175 WriteData(fid,prefix,'object',self,'class','smb','fieldname','delta18o','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts) 176 WriteData(fid,prefix,'object',self,'class','smb','fieldname','Tdiff','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts) 177 WriteData(fid,prefix,'object',self,'class','smb','fieldname','sealev','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts) 177 178 elif self.ismungsm: 178 WriteData(fid, 'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)179 WriteData(fid, 'object',self,'class','smb','fieldname','temperatures_lgm','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)180 WriteData(fid, 'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)181 WriteData(fid, 'object',self,'class','smb','fieldname','precipitations_lgm','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)182 WriteData(fid, 'object',self,'class','smb','fieldname','Pfac','format','DoubleMat','mattype',1,'timeserieslength',2)183 WriteData(fid, 'object',self,'class','smb','fieldname','Tdiff','format','DoubleMat','mattype',1,'timeserieslength',2)184 WriteData(fid, 'object',self,'class','smb','fieldname','sealev','format','DoubleMat','mattype',1,'timeserieslength',2)179 WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 180 WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_lgm','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 181 WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 182 WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_lgm','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 183 WriteData(fid,prefix,'object',self,'class','smb','fieldname','Pfac','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts) 184 WriteData(fid,prefix,'object',self,'class','smb','fieldname','Tdiff','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts) 185 WriteData(fid,prefix,'object',self,'class','smb','fieldname','sealev','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts) 185 186 186 187 #process requested outputs … … 190 191 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 191 192 outputs =outputscopy 192 WriteData(fid, 'data',outputs,'enum',SmbRequestedOutputsEnum(),'format','StringArray')193 WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray') 193 194 194 195 # }}} -
issm/trunk-jpl/src/py3/classes/autodiff.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from dependent import dependent 3 3 from independent import independent 4 4 from fielddisplay import fielddisplay 5 from EnumDefinitions import *6 5 from checkfield import checkfield 7 6 from WriteData import WriteData … … 15 14 """ 16 15 def __init__(self,*args): # {{{ 17 self.isautodiff = False 18 self.dependents = [] 19 self.independents = [] 20 self.driver = 'fos_forward' 21 self.obufsize = float('NaN') 22 self.lbufsize = float('NaN') 23 self.cbufsize = float('NaN') 24 self.tbufsize = float('NaN') 25 self.gcTriggerMaxSize = float('NaN') 26 self.gcTriggerRatio = float('NaN') 16 self.isautodiff = False 17 self.dependents = [] 18 self.independents = [] 19 self.driver = 'fos_forward' 20 self.obufsize = float('NaN') 21 self.lbufsize = float('NaN') 22 self.cbufsize = float('NaN') 23 self.tbufsize = float('NaN') 24 self.gcTriggerMaxSize = float('NaN') 25 self.gcTriggerRatio = float('NaN') 26 self.tapeAlloc = float('NaN') 27 27 if not len(args): 28 28 self.setdefaultparameters() … … 30 30 raise RuntimeError("constructor not supported") 31 31 # }}} 32 32 33 def __repr__(self): # {{{ 33 34 s =" automatic differentiation parameters:\n" 34 35 35 s+="%s\n" % fielddisplay(self,'isautodiff',"indicates if the automatic differentiation is activated") 36 36 s+="%s\n" % fielddisplay(self,'dependents',"list of dependent variables") … … 43 43 s+="%s\n" % fielddisplay(self,'gcTriggerRatio',"free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio") 44 44 s+="%s\n" % fielddisplay(self,'gcTriggerMaxSize',"free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize)") 45 s+="%s\n" % fielddisplay(self,'tapeAlloc','Iteration count of a priori memory allocation of the AD tape'); 45 46 46 47 return s 47 48 # }}} 49 48 50 def setdefaultparameters(self): # {{{ 49 50 self. obufsize= 52428851 self. lbufsize= 52428852 self. cbufsize= 52428853 self. tbufsize = 52428854 self.gcTrigger Ratio=2.055 self. gcTriggerMaxSize=6553651 self.obufsize = 524288 52 self.lbufsize = 524288 53 self.cbufsize = 524288 54 self.tbufsize = 524288 55 self.gcTriggerRatio = 2.0 56 self.gcTriggerMaxSize = 65536 57 self.tapeAlloc = 15000000; 56 58 return self 57 59 # }}} 60 58 61 def checkconsistency(self,md,solution,analyses): # {{{ 59 60 #Early return 62 #Early return 61 63 if not self.isautodiff: 62 return md 63 64 return md 65 64 66 md = checkfield(md,'fieldname','autodiff.obufsize','>=',524288) 65 67 md = checkfield(md,'fieldname','autodiff.lbufsize','>=',524288) … … 67 69 md = checkfield(md,'fieldname','autodiff.tbufsize','>=',524288) 68 70 md = checkfield(md,'fieldname','autodiff.gcTriggerRatio','>=',2.0) 69 md = checkfield(md,'fieldname','autodiff.gcTriggerMaxSize','>=',2000000) 71 md = checkfield(md,'fieldname','autodiff.gcTriggerMaxSize','>=',65536) 72 md = checkfield(md,'fieldname','autodiff.tapeAlloc','>=',0); 70 73 71 74 #Driver value: 72 75 md = checkfield(md,'fieldname','autodiff.driver','values',['fos_forward','fov_forward','fov_forward_all','fos_reverse','fov_reverse','fov_reverse_all']) 73 76 74 #go through our dependents and independents and check consistency: 77 #go through our dependents and independents and check consistency: 75 78 for dep in self.dependents: 76 79 dep.checkconsistency(md,solution,analyses) … … 80 83 return md 81 84 # }}} 82 def marshall(self,md,fid): # {{{ 83 WriteData(fid,'object',self,'fieldname','isautodiff','format','Boolean') 84 WriteData(fid,'object',self,'fieldname','driver','format','String') 85 86 def marshall(self,prefix,md,fid): # {{{ 87 WriteData(fid,prefix,'object',self,'fieldname','isautodiff','format','Boolean') 88 WriteData(fid,prefix,'object',self,'fieldname','driver','format','String') 85 89 86 90 #early return 87 91 if not self.isautodiff: 88 WriteData(fid, 'data',False,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean')89 WriteData(fid, 'data',False,'enum',AutodiffKeepEnum(),'format','Boolean')92 WriteData(fid,prefix,'data',False,'name','md.autodiff.mass_flux_segments_present','format','Boolean') 93 WriteData(fid,prefix,'data',False,'name','md.autodiff.keep','format','Boolean') 90 94 return 91 95 92 96 #buffer sizes {{{ 93 WriteData(fid,'object',self,'fieldname','obufsize','format','Double'); 94 WriteData(fid,'object',self,'fieldname','lbufsize','format','Double'); 95 WriteData(fid,'object',self,'fieldname','cbufsize','format','Double'); 96 WriteData(fid,'object',self,'fieldname','tbufsize','format','Double'); 97 WriteData(fid,'object',self,'fieldname','gcTriggerRatio','format','Double'); 98 WriteData(fid,'object',self,'fieldname','gcTriggerMaxSize','format','Double'); 97 WriteData(fid,prefix,'object',self,'fieldname','obufsize','format','Double'); 98 WriteData(fid,prefix,'object',self,'fieldname','lbufsize','format','Double'); 99 WriteData(fid,prefix,'object',self,'fieldname','cbufsize','format','Double'); 100 WriteData(fid,prefix,'object',self,'fieldname','tbufsize','format','Double'); 101 WriteData(fid,prefix,'object',self,'fieldname','gcTriggerRatio','format','Double'); 102 WriteData(fid,prefix,'object',self,'fieldname','gcTriggerMaxSize','format','Double'); 103 WriteData(fid,prefix,'object',self,'fieldname','tapeAlloc','format','Integer'); 99 104 #}}} 100 105 #process dependent variables {{{ 101 106 num_dependent_objects=len(self.dependents) 102 WriteData(fid, 'data',num_dependent_objects,'enum',AutodiffNumDependentObjectsEnum(),'format','Integer')107 WriteData(fid,prefix,'data',num_dependent_objects,'name','md.autodiff.num_dependent_objects','format','Integer') 103 108 104 109 if num_dependent_objects: 105 110 names=[] 106 types=n umpy.zeros(num_dependent_objects)107 indices=n umpy.zeros(num_dependent_objects)111 types=np.zeros(num_dependent_objects) 112 indices=np.zeros(num_dependent_objects) 108 113 109 114 for i,dep in enumerate(self.dependents): 110 names [i]=dep.name115 names.append(dep.name) 111 116 types[i]=dep.typetoscalar() 112 117 indices[i]=dep.index 113 118 114 WriteData(fid, 'data',names,'enum',AutodiffDependentObjectNamesEnum(),'format','StringArray')115 WriteData(fid, 'data',types,'enum',AutodiffDependentObjectTypesEnum(),'format','IntMat','mattype',3)116 WriteData(fid, 'data',indices,'enum',AutodiffDependentObjectIndicesEnum(),'format','IntMat','mattype',3)119 WriteData(fid,prefix,'data',names,'name','md.autodiff.dependent_object_names','format','StringArray') 120 WriteData(fid,prefix,'data',types,'name','md.autodiff.dependent_object_types','format','IntMat','mattype',3) 121 WriteData(fid,prefix,'data',indices,'name','md.autodiff.dependent_object_indices','format','IntMat','mattype',3) 117 122 #}}} 118 123 #process independent variables {{{ 119 124 num_independent_objects=len(self.independents) 120 WriteData(fid, 'data',num_independent_objects,'enum',AutodiffNumIndependentObjectsEnum(),'format','Integer')125 WriteData(fid,prefix,'data',num_independent_objects,'name','md.autodiff.num_independent_objects','format','Integer') 121 126 122 127 if num_independent_objects: 123 names= numpy.zeros(num_independent_objects)124 types=n umpy.zeros(num_independent_objects)128 names=[None] * num_independent_objects 129 types=np.zeros(num_independent_objects) 125 130 126 131 for i,indep in enumerate(self.independents): 127 names[i]= StringToEnum(indep.name)[0]132 names[i]=indep.name 128 133 types[i]=indep.typetoscalar() 129 134 130 WriteData(fid, 'data',names,'enum',AutodiffIndependentObjectNamesEnum(),'format','IntMat','mattype',3)131 WriteData(fid, 'data',types,'enum',AutodiffIndependentObjectTypesEnum(),'format','IntMat','mattype',3)135 WriteData(fid,prefix,'data',names,'name','md.autodiff.independent_object_names','format','StringArray') 136 WriteData(fid,prefix,'data',types,'name','md.autodiff.independent_object_types','format','IntMat','mattype',3) 132 137 #}}} 133 138 #if driver is fos_forward, build index: {{{ … … 136 141 137 142 for indep in self.independents: 138 if not n umpy.isnan(indep.fos_forward_index):143 if not np.isnan(indep.fos_forward_index): 139 144 index+=indep.fos_forward_index 140 145 break … … 146 151 147 152 index-=1 #get c-index numbering going 148 WriteData(fid, 'data',index,'enum',AutodiffFosForwardIndexEnum(),'format','Integer')153 WriteData(fid,prefix,'data',index,'name','md.autodiff.fos_forward_index','format','Integer') 149 154 #}}} 150 155 #if driver is fos_reverse, build index: {{{ … … 153 158 154 159 for dep in self.dependents: 155 if not n umpy.isnan(dep.fos_reverse_index):160 if not np.isnan(dep.fos_reverse_index): 156 161 index+=dep.fos_reverse_index 157 162 break … … 163 168 164 169 index-=1 #get c-index numbering going 165 WriteData(fid, 'data',index,'enum',AutodiffFosReverseIndexEnum(),'format','Integer')170 WriteData(fid,prefix,'data',index,'name','md.autodiff.fos_reverse_index','format','Integer') 166 171 #}}} 167 172 #if driver is fov_forward, build indices: {{{ … … 180 185 181 186 indices-=1 #get c-indices numbering going 182 WriteData(fid, 'data',indices,'enum',AutodiffFovForwardIndicesEnum(),'format','IntMat','mattype',3)187 WriteData(fid,prefix,'data',indices,'name','md.autodiff.fov_forward_indices','format','IntMat','mattype',3) 183 188 #}}} 184 189 #deal with mass fluxes: {{{ … … 186 191 187 192 if mass_flux_segments: 188 WriteData(fid, 'data',mass_flux_segments,'enum',MassFluxSegmentsEnum(),'format','MatArray')193 WriteData(fid,prefix,'data',mass_flux_segments,'name','md.autodiff.mass_flux_segments','format','MatArray') 189 194 flag=True 190 195 else: 191 196 flag=False 192 WriteData(fid, 'data',flag,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean')197 WriteData(fid,prefix,'data',flag,'name','md.autodiff.mass_flux_segments_present','format','Boolean') 193 198 #}}} 194 199 #deal with trace keep on: {{{ 195 200 keep=False 196 201 197 #From ADOLC userdoc: 198 # The optional integer argument keep of trace on determines whether the numerical values of all active variables are 199 # recorded in a buffered temporary array or file called the taylor stack. This option takes effect if keep = 1 and 200 # prepares the scene for an immediately following gradient evaluation by a call to a routine implementing the reverse 201 # mode as described in the Section 4 and Section 5. 202 #From ADOLC userdoc: 203 # The optional integer argument keep of trace on determines whether the numerical values of all active variables are 204 # recorded in a buffered temporary array or file called the taylor stack. This option takes effect if keep = 1 and 205 # prepares the scene for an immediately following gradient evaluation by a call to a routine implementing the reverse 206 # mode as described in the Section 4 and Section 5. 202 207 # 203 208 204 209 if len(self.driver)<=3: 205 keep=False #there is no "_reverse" string within the driver string: 210 keep=False #there is no "_reverse" string within the driver string: 206 211 else: 207 212 if strncmpi(self.driver[3:],'_reverse',8): … … 209 214 else: 210 215 keep=False 211 WriteData(fid, 'data',keep,'enum',AutodiffKeepEnum(),'format','Boolean')216 WriteData(fid,prefix,'data',keep,'name','md.autodiff.keep','format','Boolean') 212 217 #}}} 213 218 -
issm/trunk-jpl/src/py3/classes/balancethickness.py
r19898 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *3 2 from checkfield import checkfield 4 3 from WriteData import WriteData … … 16 15 self.thickening_rate = float('NaN') 17 16 self.stabilization = 0 17 18 self.omega = float('NaN') 19 self.slopex = float('NaN') 20 self.slopey = float('NaN') 18 21 19 22 #set defaults … … 39 42 def checkconsistency(self,md,solution,analyses): # {{{ 40 43 #Early return 41 if not solution== BalancethicknessSolutionEnum():44 if not solution=='BalancethicknessSolution': 42 45 return md 43 46 … … 45 48 md = checkfield(md,'fieldname','balancethickness.thickening_rate','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 46 49 md = checkfield(md,'fieldname','balancethickness.stabilization','size',[1],'values',[0,1,2,3]) 47 50 #md = checkfield(md,'fieldname','balancethickness.omega','size', [md.mesh.numberofvertices],'NaN',1,'Inf',1,'>=',0); 48 51 return md 49 52 # }}} 50 def marshall(self, md,fid): # {{{53 def marshall(self,prefix,md,fid): # {{{ 51 54 52 yts= 365.0*24.0*3600.055 yts=md.constants.yts 53 56 54 WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1) 55 WriteData(fid,'object',self,'fieldname','thickening_rate','format','DoubleMat','mattype',1,'scale',1./yts) 56 WriteData(fid,'object',self,'fieldname','stabilization','format','Integer') 57 WriteData(fid,prefix,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1) 58 WriteData(fid,prefix,'object',self,'fieldname','thickening_rate','format','DoubleMat','mattype',1,'scale',1./yts) 59 WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Integer') 60 WriteData(fid,prefix,'object',self,'fieldname','slopex','format','DoubleMat','mattype',1) 61 WriteData(fid,prefix,'object',self,'fieldname','slopey','format','DoubleMat','mattype',1) 62 WriteData(fid,prefix,'object',self,'fieldname','omega','format','DoubleMat','mattype',1) 57 63 # }}} -
issm/trunk-jpl/src/py3/classes/bamggeom.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 3 3 class bamggeom(object): … … 10 10 11 11 def __init__(self,*args): # {{{ 12 self.Vertices=n umpy.empty((0,3))13 self.Edges=n umpy.empty((0,3))14 self.TangentAtEdges=n umpy.empty((0,4))15 self.Corners=n umpy.empty((0,1))16 self.RequiredVertices=n umpy.empty((0,1))17 self.RequiredEdges=n umpy.empty((0,1))18 self.CrackedEdges=n umpy.empty((0,0))19 self.SubDomains=n umpy.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)) 20 20 21 21 if not len(args): … … 25 25 elif len(args) == 1: 26 26 object=args[0] 27 for field in list(object.keys()):27 for field in object.keys(): 28 28 if field in vars(self): 29 29 setattr(self,field,object[field]) -
issm/trunk-jpl/src/py3/classes/bamgmesh.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 3 3 class bamgmesh(object): … … 10 10 11 11 def __init__(self,*args): # {{{ 12 self.Vertices=numpy.empty((0,3)) 13 self.Edges=numpy.empty((0,3)) 14 self.Triangles=numpy.empty((0,0)) 15 self.Quadrilaterals=numpy.empty((0,0)) 16 self.IssmEdges=numpy.empty((0,0)) 17 self.IssmSegments=numpy.empty((0,0)) 18 self.VerticesOnGeomVertex=numpy.empty((0,0)) 19 self.VerticesOnGeomEdge=numpy.empty((0,0)) 20 self.EdgesOnGeomEdge=numpy.empty((0,0)) 21 self.SubDomains=numpy.empty((0,4)) 22 self.SubDomainsFromGeom=numpy.empty((0,0)) 23 self.ElementConnectivity=numpy.empty((0,0)) 24 self.NodalConnectivity=numpy.empty((0,0)) 25 self.NodalElementConnectivity=numpy.empty((0,0)) 26 self.CrackedVertices=numpy.empty((0,0)) 27 self.CrackedEdges=numpy.empty((0,0)) 12 self.Vertices=np.empty((0,3)) 13 self.Edges=np.empty((0,3)) 14 self.Triangles=np.empty((0,0)) 15 self.IssmEdges=np.empty((0,0)) 16 self.IssmSegments=np.empty((0,0)) 17 self.VerticesOnGeomVertex=np.empty((0,0)) 18 self.VerticesOnGeomEdge=np.empty((0,0)) 19 self.EdgesOnGeomEdge=np.empty((0,0)) 20 self.SubDomains=np.empty((0,4)) 21 self.SubDomainsFromGeom=np.empty((0,0)) 22 self.ElementConnectivity=np.empty((0,0)) 23 self.NodalConnectivity=np.empty((0,0)) 24 self.NodalElementConnectivity=np.empty((0,0)) 25 self.CrackedVertices=np.empty((0,0)) 26 self.CrackedEdges=np.empty((0,0)) 28 27 29 28 if not len(args): … … 33 32 elif len(args) == 1: 34 33 object=args[0] 35 for field in list(object.keys()):34 for field in object.keys(): 36 35 if field in vars(self): 37 36 setattr(self,field,object[field]) … … 45 44 s+=" Edges: %s\n" % str(self.Edges) 46 45 s+=" Triangles: %s\n" % str(self.Triangles) 47 s+=" Quadrilaterals: %s\n" % str(self.Quadrilaterals)48 46 s+=" IssmEdges: %s\n" % str(self.IssmEdges) 49 47 s+=" IssmSegments: %s\n" % str(self.IssmSegments) -
issm/trunk-jpl/src/py3/classes/basalforcings.py
r19898 r23670 1 1 from fielddisplay import fielddisplay 2 2 from project3d import project3d 3 from EnumDefinitions import *4 3 from checkfield import checkfield 5 4 from WriteData import WriteData 6 import numpy 5 import numpy as np 7 6 8 7 class basalforcings(object): … … 39 38 def initialize(self,md): # {{{ 40 39 41 if n umpy.all(numpy.isnan(self.groundedice_melting_rate)):42 self.groundedice_melting_rate=n umpy.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)) 43 42 print(" no basalforcings.groundedice_melting_rate specified: values set as zero") 44 43 45 if n umpy.all(numpy.isnan(self.floatingice_melting_rate)):46 self.floatingice_melting_rate=n umpy.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)) 47 46 print(" no basalforcings.floatingice_melting_rate specified: values set as zero") 47 #if np.all(np.isnan(self.geothermalflux)): 48 #self.geothermalflux=np.zeros((md.mesh.numberofvertices)) 49 #print " no basalforcings.geothermalflux specified: values set as zero" 48 50 49 51 return self … … 54 56 def checkconsistency(self,md,solution,analyses): # {{{ 55 57 56 if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum()and not md.transient.ismasstransport):58 if 'MasstransportAnalysis' in analyses and not (solution=='TransientSolution' and not md.transient.ismasstransport): 57 59 md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1) 58 60 md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'Inf',1,'timeseries',1) 59 61 60 if BalancethicknessAnalysisEnum()in analyses:62 if 'BalancethicknessAnalysis' in analyses: 61 63 md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 62 64 md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 63 65 64 if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum()and not md.transient.isthermal):66 if 'ThermalAnalysis' in analyses and not (solution=='TransientSolution' and not md.transient.isthermal): 65 67 md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1) 66 68 md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'Inf',1,'timeseries',1) … … 69 71 return md 70 72 # }}} 71 def marshall(self, md,fid): # {{{73 def marshall(self,prefix,md,fid): # {{{ 72 74 73 yts= 365.0*24.0*3600.075 yts=md.constants.yts 74 76 75 WriteData(fid, 'enum',BasalforcingsEnum(),'data',FloatingMeltRateEnum(),'format','Integer');76 WriteData(fid, 'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)77 WriteData(fid, 'object',self,'fieldname','floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)78 WriteData(fid, 'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)77 WriteData(fid,prefix,'name','md.basalforcings.model','data',1,'format','Integer'); 78 WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 79 WriteData(fid,prefix,'object',self,'fieldname','floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 80 WriteData(fid,prefix,'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 79 81 # }}} -
issm/trunk-jpl/src/py3/classes/calving.py
r20465 r23670 1 1 from fielddisplay import fielddisplay 2 2 from project3d import project3d 3 from EnumDefinitions import *4 from StringToEnum import StringToEnum5 3 from checkfield import checkfield 6 4 from WriteData import WriteData … … 16 14 def __init__(self): # {{{ 17 15 18 self.stabilization = 019 self.spclevelset = float('NaN')20 16 self.calvingrate = float('NaN') 21 17 self.meltingrate = float('NaN') … … 27 23 def __repr__(self): # {{{ 28 24 string=' Calving parameters:' 29 string="%s\n%s"%(string,fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding'))30 string="%s\n%s"%(string,fielddisplay(self,'spclevelset','levelset constraints (NaN means no constraint)'))31 25 string="%s\n%s"%(string,fielddisplay(self,'calvingrate','calving rate at given location [m/a]')) 32 string="%s\n%s"%(string,fielddisplay(self,'meltingrate','melting rate at given location [m/a]'))33 26 34 27 return string 35 28 #}}} 36 29 def extrude(self,md): # {{{ 37 self.spclevelset=project3d(md,'vector',self.spclevelset,'type','node')38 30 self.calvingrate=project3d(md,'vector',self.calvingrate,'type','node') 39 self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node')40 31 return self 41 32 #}}} 42 33 def setdefaultparameters(self): # {{{ 43 44 #stabilization = 2 by default45 self.stabilization = 246 34 47 35 return self … … 50 38 51 39 #Early return 52 if (solution!= TransientSolutionEnum()) or (not md.transient.iscalving):40 if (solution!='TransientSolution') or (not md.transient.ismovingfront): 53 41 return md 54 42 55 md = checkfield(md,'fieldname','calving.spclevelset','Inf',1,'timeseries',1)56 md = checkfield(md,'fieldname','calving.stabilization','values',[0,1,2]);57 43 md = checkfield(md,'fieldname','calving.calvingrate','>=',0,'timeseries',1,'NaN',1,'Inf',1); 58 md = checkfield(md,'fieldname','calving.meltingrate','>=',0,'timeseries',1,'NaN',1,'Inf',1);59 44 60 45 return md 61 46 # }}} 62 def marshall(self, md,fid): # {{{47 def marshall(self,prefix,md,fid): # {{{ 63 48 64 yts= 365.*24.*3600.49 yts=md.constants.yts 65 50 66 WriteData(fid,'enum',CalvingLawEnum(),'data',DefaultCalvingEnum(),'format','Integer'); 67 WriteData(fid,'enum',LevelsetStabilizationEnum(),'data',self.stabilization,'format','Integer'); 68 WriteData(fid,'enum',SpclevelsetEnum(),'data',self.spclevelset,'format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1); 69 WriteData(fid,'object',self,'fieldname','calvingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts) 70 WriteData(fid,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts) 51 WriteData(fid,prefix,'name','md.calving.law','data',1,'format','Integer'); 52 WriteData(fid,prefix,'object',self,'fieldname','calvingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts,'scale',1./yts) 71 53 # }}} -
issm/trunk-jpl/src/py3/classes/calvinglevermann.py
r20465 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *3 from StringToEnum import StringToEnum4 2 from checkfield import checkfield 5 3 from WriteData import WriteData … … 15 13 def __init__(self): # {{{ 16 14 17 self.stabilization = 018 self.spclevelset = float('NaN')19 15 self.coeff = float('NaN') 20 16 self.meltingrate = float('NaN') … … 26 22 def __repr__(self): # {{{ 27 23 string=' Calving Levermann parameters:' 28 string="%s\n%s"%(string,fielddisplay(self,'spclevelset','levelset constraints (NaN means no constraint)'))29 string="%s\n%s"%(string,fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding'))30 24 string="%s\n%s"%(string,fielddisplay(self,'coeff','proportionality coefficient in Levermann model')) 31 string="%s\n%s"%(string,fielddisplay(self,'meltingrate','melting rate at given location [m/a]'))32 25 33 26 return string 34 27 #}}} 35 28 def extrude(self,md): # {{{ 36 self.spclevelset=project3d(md,'vector',self.spclevelset,'type','node')37 29 self.coeff=project3d(md,'vector',self.coeff,'type','node') 38 self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node')39 30 return self 40 31 #}}} 41 32 def setdefaultparameters(self): # {{{ 42 43 #stabilization = 2 by default44 self.stabilization = 245 33 46 34 #Proportionality coefficient in Levermann model … … 50 38 51 39 #Early return 52 if (solution!= TransientSolutionEnum()) or (not md.transient.iscalving):40 if (solution!='TransientSolution') or (not md.transient.ismovingfront): 53 41 return md 54 42 55 md = checkfield(md,'fieldname','calving.spclevelset','Inf',1,'timeseries',1)56 md = checkfield(md,'fieldname','calving.stabilization','values',[0,1,2]);57 43 md = checkfield(md,'fieldname','calving.coeff','size',[md.mesh.numberofvertices],'>',0) 58 md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices],'>=',0)59 44 return md 60 45 # }}} 61 def marshall(self,md,fid): # {{{ 62 yts=365.*24.*3600. 63 WriteData(fid,'enum',CalvingLawEnum(),'data',CalvingLevermannEnum(),'format','Integer'); 64 WriteData(fid,'enum',LevelsetStabilizationEnum(),'data',self.stabilization,'format','Integer'); 65 WriteData(fid,'enum',SpclevelsetEnum(),'data',self.spclevelset,'format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1); 66 WriteData(fid,'enum',CalvinglevermannCoeffEnum(),'data',self.coeff,'format','DoubleMat','mattype',1) 67 WriteData(fid,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts) 46 def marshall(self,prefix,md,fid): # {{{ 47 yts=md.constants.yts 48 WriteData(fid,prefix,'name','md.calving.law','data',3,'format','Integer'); 49 WriteData(fid,prefix,'object',self,'fieldname','coeff','format','DoubleMat','mattype',1) 68 50 # }}} -
issm/trunk-jpl/src/py3/classes/clusters/generic.py
r19895 r23670 4 4 import subprocess 5 5 from IssmConfig import IssmConfig 6 from EnumToString import EnumToString7 6 from issmdir import issmdir 8 7 from pairoptions import pairoptions … … 18 17 Usage: 19 18 cluster=generic('name','astrid','np',3); 20 cluster=generic('name', oshostname(),'np',3,'login','username');19 cluster=generic('name',gethostname(),'np',3,'login','username'); 21 20 """ 22 21 23 def __init__(self,* *kwargs): # {{{22 def __init__(self,*args): # {{{ 24 23 25 24 self.name='' … … 28 27 self.port=0 29 28 self.interactive=1 30 self.codepath= issmdir()+'/bin'29 self.codepath=IssmConfig('ISSM_PREFIX')[0]+'/bin' 31 30 self.executionpath=issmdir()+'/execution' 32 31 self.valgrind=issmdir()+'/externalpackages/valgrind/install/bin/valgrind' … … 35 34 36 35 #use provided options to change fields 37 options=pairoptions(* *kwargs)36 options=pairoptions(*args) 38 37 39 38 #get name … … 69 68 return md 70 69 # }}} 71 def BuildQueueScript(self,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota ): # {{{70 def BuildQueueScript(self,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota,isoceancoupling): # {{{ 72 71 73 72 executable='issm.exe'; 74 73 if isdakota: 75 version=IssmConfig('_DAKOTA_VERSION_') [0:2]76 version=float(version )74 version=IssmConfig('_DAKOTA_VERSION_') 75 version=float(version[0]) 77 76 if version>=6: 78 77 executable='issm_dakota.exe' 78 if isoceancoupling: 79 executable='issm_ocean.exe' 79 80 80 81 #write queuing script … … 86 87 if self.interactive: 87 88 if IssmConfig('_HAVE_MPI_')[0]: 88 fid.write('mpiexec -np %i %s/%s %s %s/%s %s ' % (self.np,self.codepath,executable, EnumToString(solution)[0],self.executionpath,dirname,modelname))89 fid.write('mpiexec -np %i %s/%s %s %s/%s %s ' % (self.np,self.codepath,executable,solution,self.executionpath,dirname,modelname)) 89 90 else: 90 fid.write('%s/%s %s %s/%s %s ' % (self.codepath,executable, EnumToString(solution)[0],self.executionpath,dirname,modelname))91 fid.write('%s/%s %s %s/%s %s ' % (self.codepath,executable,solution,self.executionpath,dirname,modelname)) 91 92 else: 92 93 if IssmConfig('_HAVE_MPI_')[0]: 93 fid.write('mpiexec -np %i %s/%s %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,executable, EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))94 fid.write('mpiexec -np %i %s/%s %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,executable,solution,self.executionpath,dirname,modelname,modelname,modelname)) 94 95 else: 95 fid.write('%s/%s %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.codepath,executable, EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))96 fid.write('%s/%s %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.codepath,executable,solution,self.executionpath,dirname,modelname,modelname,modelname)) 96 97 elif isgprof: 97 98 fid.write('\n gprof %s/%s gmon.out > %s.performance' % (self.codepath,executable,modelname)) … … 101 102 if IssmConfig('_HAVE_MPI_')[0]: 102 103 fid.write('mpiexec -np %i %s --leak-check=full --suppressions=%s %s/%s %s %s/%s %s 2> %s.errlog >%s.outlog ' % \ 103 (self.np,self.valgrind,self.valgrindsup,self.codepath,executable, EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))104 (self.np,self.valgrind,self.valgrindsup,self.codepath,executable,solution,self.executionpath,dirname,modelname,modelname,modelname)) 104 105 else: 105 106 fid.write('%s --leak-check=full --suppressions=%s %s/%s %s %s/%s %s 2> %s.errlog >%s.outlog ' % \ 106 (self.valgrind,self.valgrindsup,self.codepath,executable, EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))107 (self.valgrind,self.valgrindsup,self.codepath,executable,solution,self.executionpath,dirname,modelname,modelname,modelname)) 107 108 108 109 if not io_gather: #concatenate the output files: … … 115 116 fid.write('@echo off\n') 116 117 if self.interactive: 117 fid.write('"%s/%s" %s "%s/%s" %s ' % (self.codepath,executable, EnumToString(solution)[0],self.executionpath,dirname,modelname))118 fid.write('"%s/%s" %s "%s/%s" %s ' % (self.codepath,executable,solution,self.executionpath,dirname,modelname)) 118 119 else: 119 120 fid.write('"%s/%s" %s "%s/%s" %s 2> %s.errlog >%s.outlog' % \ 120 (self.codepath,executable, EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))121 (self.codepath,executable,solution,self.executionpath,dirname,modelname,modelname,modelname)) 121 122 fid.close() 122 123 … … 156 157 fid.write('@echo off\n') 157 158 if self.interactive: 158 fid.write('"%s/issm.exe" %s "%s/%s" %s ' % (self.codepath, EnumToString(solution)[0],self.executionpath,modelname,modelname))159 fid.write('"%s/issm.exe" %s "%s/%s" %s ' % (self.codepath,solution,self.executionpath,modelname,modelname)) 159 160 else: 160 161 fid.write('"%s/issm.exe" %s "%s/%s" %s 2> %s.errlog >%s.outlog' % \ 161 (self.codepath, EnumToString(solution)[0],self.executionpath,modelname,modelname,modelname,modelname))162 (self.codepath,solution,self.executionpath,modelname,modelname,modelname,modelname)) 162 163 fid.close() 163 164 … … 183 184 184 185 # }}} 185 def LaunchQueueJob(self,modelname,dirname,filelist,restart ): # {{{186 def LaunchQueueJob(self,modelname,dirname,filelist,restart,batch): # {{{ 186 187 187 188 print('launching solution sequence on remote cluster') … … 189 190 launchcommand='cd %s && cd %s chmod 777 %s.queue && ./%s.queue' % (self.executionpath,dirname,modelname,modelname) 190 191 else: 191 launchcommand='cd %s && rm -rf ./%s && mkdir %s && cd %s && mv ../%s.tar.gz ./ && tar -zxf %s.tar.gz && chmod 777 %s.queue && ./%s.queue' % \ 192 (self.executionpath,dirname,dirname,dirname,dirname,dirname,modelname,modelname) 192 if batch: 193 launchcommand='cd %s && rm -rf ./%s && mkdir %s && cd %s && mv ../%s.tar.gz ./ && tar -zxf %s.tar.gz' % \ 194 (self.executionpath,dirname,dirname,dirname,dirname,dirname) 195 else: 196 launchcommand='cd %s && rm -rf ./%s && mkdir %s && cd %s && mv ../%s.tar.gz ./ && tar -zxf %s.tar.gz && chmod 777 %s.queue && ./%s.queue' % \ 197 (self.executionpath,dirname,dirname,dirname,dirname,dirname,modelname,modelname) 193 198 issmssh(self.name,self.login,self.port,launchcommand) 194 199 # }}} -
issm/trunk-jpl/src/py3/classes/clusters/pfe.py
r19895 r23670 4 4 import subprocess 5 5 from fielddisplay import fielddisplay 6 from EnumToString import EnumToString7 6 from pairoptions import pairoptions 8 7 from issmssh import issmssh … … 25 24 """ 26 25 27 def __init__(self,* *kwargs):26 def __init__(self,*args): 28 27 # {{{ 29 28 … … 45 44 46 45 #use provided options to change fields 47 options=pairoptions(* *kwargs)46 options=pairoptions(*args) 48 47 49 48 #initialize cluster using user settings if provided … … 134 133 return self 135 134 # }}} 136 def BuildQueueScript(self,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota ):135 def BuildQueueScript(self,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota,isoceancoupling): 137 136 # {{{ 138 137 … … 143 142 if version>=6: 144 143 executable='issm_dakota.exe' 144 if isoceancoupling: 145 executable='issm_ocean.exe' 145 146 146 147 #write queuing script … … 162 163 fid.write('source $ISSM_DIR/etc/environment.sh\n') 163 164 fid.write('cd %s/%s/\n\n' % (self.executionpath,dirname)) 164 fid.write('mpiexec -np %i %s/%s %s %s/%s %s\n' % (self.nprocs(),self.codepath,executable,str( EnumToString(solution)[0]),self.executionpath,dirname,modelname))165 fid.write('mpiexec -np %i %s/%s %s %s/%s %s\n' % (self.nprocs(),self.codepath,executable,str(solution),self.executionpath,dirname,modelname)) 165 166 166 167 fid.close() … … 180 181 181 182 # }}} 182 def LaunchQueueJob(self,modelname,dirname,filelist,restart ):183 def LaunchQueueJob(self,modelname,dirname,filelist,restart,batch): 183 184 # {{{ 184 185 -
issm/trunk-jpl/src/py3/classes/constants.py
r19895 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *3 2 from checkfield import checkfield 4 3 from WriteData import WriteData … … 13 12 14 13 def __init__(self): # {{{ 15 self.g = 0 16 self.yts = 0 17 self.referencetemperature = 0 14 self.g = 0. 15 self.omega = 0. 16 self.yts = 0. 17 self.referencetemperature = 0. 18 18 19 19 #set defaults … … 25 25 26 26 string="%s\n%s"%(string,fielddisplay(self,"g","gravitational acceleration [m/s^2]")) 27 string="%s\n%s"%(string,fielddisplay(self,"omega","angular velocity of Earth [rad/s]")) 27 28 string="%s\n%s"%(string,fielddisplay(self,"yts","number of seconds in a year [s/yr]")) 28 29 string="%s\n%s"%(string,fielddisplay(self,"referencetemperature","reference temperature used in the enthalpy model [K]")) … … 35 36 self.g=9.81 36 37 38 #Earth's rotation speed 39 self.omega = 7.292*1e-5; 40 37 41 #converstion from year to seconds 38 self.yts=365 *24*360042 self.yts=365.*24.*3600. 39 43 40 44 #the reference temperature for enthalpy model (cf Aschwanden) … … 45 49 def checkconsistency(self,md,solution,analyses): # {{{ 46 50 47 md = checkfield(md,'fieldname','constants.g','>',0,'size',[1]) 48 md = checkfield(md,'fieldname','constants.yts','>',0,'size',[1]) 49 md = checkfield(md,'fieldname','constants.referencetemperature','size',[1]) 51 md = checkfield(md,'fieldname','constants.g','>=',0,'size',[1,1]) 52 md = checkfield(md,'fieldname','constants.omega','>=',0,'size',[1,1]) 53 md = checkfield(md,'fieldname','constants.yts','>',0,'size',[1,1]) 54 md = checkfield(md,'fieldname','constants.referencetemperature','size',[1,1]) 50 55 51 56 return md 52 57 # }}} 53 def marshall(self, md,fid): # {{{54 WriteData(fid, 'object',self,'fieldname','g','format','Double')55 WriteData(fid, 'object',self,'fieldname','yts','format','Double')56 WriteData(fid, 'object',self,'fieldname','referencetemperature','format','Double')58 def marshall(self,prefix,md,fid): # {{{ 59 WriteData(fid,prefix,'object',self,'fieldname','g','format','Double') 60 WriteData(fid,prefix,'object',self,'fieldname','yts','format','Double') 61 WriteData(fid,prefix,'object',self,'fieldname','referencetemperature','format','Double') 57 62 # }}} -
issm/trunk-jpl/src/py3/classes/damage.py
r19903 r23670 1 1 from fielddisplay import fielddisplay 2 2 from project3d import project3d 3 from EnumDefinitions import *4 from StringToEnum import StringToEnum5 3 from checkfield import checkfield 6 4 from WriteData import WriteData 7 import MatlabFuncs as m8 5 9 6 class damage(object): … … 16 13 17 14 def __init__(self,*args): # {{{ 18 19 #damage: 20 self.isdamage = 0. 21 self.D = float('NaN') 22 self.law = float('NaN') 23 self.spcdamage = float('NaN') 24 self.max_damage = float('NaN') 25 15 #damage: 16 self.isdamage = 0. 17 self.D = float('NaN') 18 self.law = float('NaN') 19 self.spcdamage = float('NaN') 20 self.max_damage = float('NaN') 21 26 22 #numerical 27 self.stabilization 28 self.maxiter = float('NaN')29 self.elementinterp 23 self.stabilization = float('NaN') 24 self.maxiter = float('NaN') 25 self.elementinterp = '' 30 26 31 #general parameters for evolution law: 32 self.stress_threshold 33 self.kappa 34 self.c1 35 self.c2 36 self.c3 37 self.c4 38 self.healing = float('NaN')39 self.equiv_stress 40 self.requested_outputs 27 #general parameters for evolution law: 28 self.stress_threshold = float('NaN') 29 self.kappa = float('NaN') 30 self.c1 = float('NaN') 31 self.c2 = float('NaN') 32 self.c3 = float('NaN') 33 self.c4 = float('NaN') 34 self.healing = float('NaN') 35 self.equiv_stress = float('NaN') 36 self.requested_outputs = [] 41 37 42 38 if not len(args): … … 44 40 else: 45 41 raise RuntimeError("constructor not supported") 42 # }}} 46 43 47 # }}}48 44 def __repr__(self): # {{{ 49 45 s =' Damage:\n' 50 51 46 s+="%s\n" % fielddisplay(self,"isdamage","is damage mechanics being used? [0 (default) or 1]") 52 47 if self.isdamage: … … 70 65 return s 71 66 # }}} 67 72 68 def extrude(self,md): # {{{ 73 69 self.D=project3d(md,'vector',self.D,'type','node') … … 75 71 return self 76 72 #}}} 73 77 74 def setdefaultparameters(self): # {{{ 75 #damage parameters: 76 self.isdamage = 0 77 self.D = 0 78 self.law = 0 79 self.max_damage = 1-1e-5 #if damage reaches 1, solve becomes singular, as viscosity becomes nil 78 80 79 #damage parameters:80 self.isdamage=081 self.D=082 self.law=083 84 self.max_damage=1-1e-5 #if damage reaches 1, solve becomes singular, as viscosity becomes nil85 86 81 #Type of stabilization used 87 82 self.stabilization=4 88 83 89 84 #Maximum number of iterations 90 85 self.maxiter=100 … … 93 88 self.elementinterp='P1' 94 89 95 #damage evolution parameters 90 #damage evolution parameters 96 91 self.stress_threshold=1.3e5 97 92 self.kappa=2.8 … … 108 103 return self 109 104 # }}} 105 110 106 def defaultoutputs(self,md): # {{{ 111 112 107 if md.mesh.domaintype().lower()=='2dhorizontal': 113 108 list = ['DamageDbar'] … … 115 110 list = ['DamageD'] 116 111 return list 112 #}}} 117 113 118 #}}}119 114 def checkconsistency(self,md,solution,analyses): # {{{ 120 121 115 md = checkfield(md,'fieldname','damage.isdamage','numel',[1],'values',[0,1]) 122 116 if self.isdamage: … … 139 133 md = checkfield(md,'fieldname','damage.requested_outputs','stringrow',1) 140 134 elif self.law != 0: 141 if (solution== DamageEvolutionSolutionEnum):135 if (solution=='DamageEvolutionSolution'): 142 136 raise RuntimeError('Invalid evolution law (md.damage.law) for a damage solution') 143 137 144 138 return md 145 139 # }}} 146 def marshall(self,md,fid): # {{{147 140 148 WriteData(fid,'object',self,'fieldname','isdamage','format','Boolean') 141 def marshall(self,prefix,md,fid): # {{{ 142 WriteData(fid,prefix,'object',self,'fieldname','isdamage','format','Boolean') 149 143 if self.isdamage: 150 WriteData(fid, 'object',self,'fieldname','D','format','DoubleMat','mattype',1)151 WriteData(fid, 'object',self,'fieldname','law','format','Integer')152 WriteData(fid, 'object',self,'fieldname','spcdamage','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)153 WriteData(fid, 'object',self,'fieldname','max_damage','format','Double')154 WriteData(fid, 'object',self,'fieldname','stabilization','format','Integer')155 WriteData(fid, 'object',self,'fieldname','maxiter','format','Integer')156 WriteData(fid, 'enum',DamageElementinterpEnum(),'data',StringToEnum(self.elementinterp)[0],'format','Integer')157 WriteData(fid, 'object',self,'fieldname','stress_threshold','format','Double')158 WriteData(fid, 'object',self,'fieldname','kappa','format','Double')159 WriteData(fid, 'object',self,'fieldname','c1','format','Double')160 WriteData(fid, 'object',self,'fieldname','c2','format','Double')161 WriteData(fid, 'object',self,'fieldname','c3','format','Double')162 WriteData(fid, 'object',self,'fieldname','c4','format','Double')163 WriteData(fid, 'object',self,'fieldname','healing','format','Double')164 WriteData(fid, 'object',self,'fieldname','equiv_stress','format','Integer')165 144 WriteData(fid,prefix,'object',self,'fieldname','D','format','DoubleMat','mattype',1) 145 WriteData(fid,prefix,'object',self,'fieldname','law','format','Integer') 146 WriteData(fid,prefix,'object',self,'fieldname','spcdamage','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 147 WriteData(fid,prefix,'object',self,'fieldname','max_damage','format','Double') 148 WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Integer') 149 WriteData(fid,prefix,'object',self,'fieldname','maxiter','format','Integer') 150 WriteData(fid,prefix,'name','md.damage.elementinterp','data',self.elementinterp,'format','String') 151 WriteData(fid,prefix,'object',self,'fieldname','stress_threshold','format','Double') 152 WriteData(fid,prefix,'object',self,'fieldname','kappa','format','Double') 153 WriteData(fid,prefix,'object',self,'fieldname','c1','format','Double') 154 WriteData(fid,prefix,'object',self,'fieldname','c2','format','Double') 155 WriteData(fid,prefix,'object',self,'fieldname','c3','format','Double') 156 WriteData(fid,prefix,'object',self,'fieldname','c4','format','Double') 157 WriteData(fid,prefix,'object',self,'fieldname','healing','format','Double') 158 WriteData(fid,prefix,'object',self,'fieldname','equiv_stress','format','Integer') 159 166 160 #process requested outputs 167 161 outputs = self.requested_outputs … … 170 164 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 171 165 outputs =outputscopy 172 WriteData(fid,'data',outputs,'enum',DamageEvolutionRequestedOutputsEnum(),'format','StringArray') 166 if self.isdamage: 167 WriteData(fid,prefix,'data',outputs,'name','md.damage.requested_outputs','format','StringArray') 173 168 # }}} -
issm/trunk-jpl/src/py3/classes/debug.py
r19895 r23670 30 30 return self 31 31 #}}} 32 def marshall(self, md,fid): # {{{33 WriteData(fid, 'object',self,'fieldname','profiling','format','Boolean')32 def marshall(self,prefix,md,fid): # {{{ 33 WriteData(fid,prefix,'object',self,'fieldname','profiling','format','Boolean') 34 34 # }}} -
issm/trunk-jpl/src/py3/classes/dependent.py
r19895 r23670 1 1 import os.path 2 import numpy 2 import numpy as np 3 3 from pairoptions import pairoptions 4 4 from fielddisplay import fielddisplay 5 import MatlabFuncs as m 6 from EnumDefinitions import * 5 from MatlabFuncs import * 7 6 from MeshProfileIntersection import MeshProfileIntersection 8 7 … … 28 27 29 28 #use provided options to change fields 30 options=pairoptions(* *kwargs)29 options=pairoptions(*args) 31 30 32 31 self.name=options.getfieldvalue('name','') … … 44 43 #process the file and retrieve segments 45 44 mesh=options.getfieldvalue('mesh') 46 self.segments=MeshProfileIntersection(mesh.elements,mesh.x,mesh.y,self.exp) 45 self.segments=MeshProfileIntersection(mesh.elements,mesh.x,mesh.y,self.exp)[0] 47 46 # }}} 48 47 def __repr__(self): # {{{ 49 48 s =" dependent variable:\n" 50 49 51 s+="%s\n" % fielddisplay(self,'name',"variable name (must match corresponding Enum)")50 s+="%s\n" % fielddisplay(self,'name',"variable name (must match corresponding String)") 52 51 s+="%s\n" % fielddisplay(self,'type',"type of variable ('vertex' or 'scalar')") 53 52 54 if not n umpy.isnan(self.fos_reverse_index):53 if not np.isnan(self.fos_reverse_index): 55 54 s+="%s\n" % fielddisplay(self,'fos_reverse_index',"index for fos_reverse driver of ADOLC") 56 55 if self.exp: … … 71 70 raise RuntimeError("dependent checkconsistency error: index for segments should be >=0") 72 71 73 if not n umpy.isnan(self.fos_reverse_index):72 if not np.isnan(self.fos_reverse_index): 74 73 if not strcmpi(driver,'fos_reverse'): 75 74 raise TypeError("cannot declare a dependent with a fos_reverse_index when the driver is not fos_reverse!") -
issm/trunk-jpl/src/py3/classes/flowequation.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 import copy 3 3 from project3d import project3d 4 4 from fielddisplay import fielddisplay 5 from EnumDefinitions import *6 5 from checkfield import checkfield 7 6 from WriteData import WriteData … … 17 16 18 17 def __init__(self): # {{{ 19 18 20 19 self.isSIA = 0 21 20 self.isSSA = 0 … … 50 49 string="%s\n%s"%(string,fielddisplay(self,'isFS',"are the Full-FS (FS) equations used ?")) 51 50 string="%s\n%s"%(string,fielddisplay(self,'fe_SSA',"Finite Element for SSA: 'P1', 'P1bubble' 'P1bubblecondensed' 'P2'")) 52 string="%s\n%s"%(string,fielddisplay(self,'fe_HO' ,"Finite Element for HO: 'P1' 'P1bubble' 'P1bubblecondensed' 'P1xP2' 'P2xP1' 'P2'"))51 string="%s\n%s"%(string,fielddisplay(self,'fe_HO' ,"Finite Element for HO: 'P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'")) 53 52 string="%s\n%s"%(string,fielddisplay(self,'fe_FS' ,"Finite Element for FS: 'P1P1' (debugging only) 'P1P1GLS' 'MINIcondensed' 'MINI' 'TaylorHood' 'LATaylorHood' 'XTaylorHood'")) 54 53 string="%s\n%s"%(string,fielddisplay(self,'vertex_equation',"flow equation for each vertex")) … … 83 82 84 83 #Early return 85 if ( StressbalanceAnalysisEnum() not in analyses and StressbalanceSIAAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum()and not md.transient.isstressbalance):84 if ('StressbalanceAnalysis' not in analyses and 'StressbalanceSIAAnalysis' not in analyses) or (solution=='TransientSolution' and not md.transient.isstressbalance): 86 85 return md 87 86 … … 93 92 md = checkfield(md,'fieldname','flowequation.fe_SSA','values',['P1','P1bubble','P1bubblecondensed','P2','P2bubble']) 94 93 md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',['P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4']) 95 md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',['P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood',' XTaylorHood','OneLayerP4z','CrouzeixRaviart'])94 md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',['P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','LATaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart','LACrouzeixRaviart']) 96 95 md = checkfield(md,'fieldname','flowequation.borderSSA','size',[md.mesh.numberofvertices],'values',[0,1]) 97 96 md = checkfield(md,'fieldname','flowequation.borderHO','size',[md.mesh.numberofvertices],'values',[0,1]) … … 105 104 md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[1,2]) 106 105 md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',[1,2]) 106 elif m.strcmp(md.mesh.domaintype(),'2Dvertical'): 107 md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[2,4,5]) 108 md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',[2,4,5]) 107 109 elif m.strcmp(md.mesh.domaintype(),'3D'): 108 md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',n umpy.arange(0,8+1))109 md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',n umpy.arange(0,8+1))110 md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',np.arange(0,8+1)) 111 md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',np.arange(0,8+1)) 110 112 else: 111 113 raise RuntimeError('mesh type not supported yet') … … 113 115 md.checkmessage("no element types set for this model") 114 116 115 if StressbalanceSIAAnalysisEnum()in analyses:117 if 'StressbalanceSIAAnalysis' in analyses: 116 118 if any(self.element_equation==1): 117 if n umpy.any(numpy.logical_and(self.vertex_equation,md.mask.groundedice_levelset)):119 if np.any(np.logical_and(self.vertex_equation,md.mask.groundedice_levelset)): 118 120 print("\n !!! Warning: SIA's model is not consistent on ice shelves !!!\n") 119 121 120 122 return md 121 123 # }}} 122 def marshall(self, md,fid): # {{{123 WriteData(fid, 'object',self,'fieldname','isSIA','format','Boolean')124 WriteData(fid, 'object',self,'fieldname','isSSA','format','Boolean')125 WriteData(fid, 'object',self,'fieldname','isL1L2','format','Boolean')126 WriteData(fid, 'object',self,'fieldname','isHO','format','Boolean')127 WriteData(fid, 'object',self,'fieldname','isFS','format','Boolean')128 WriteData(fid, 'enum',FlowequationFeSSAEnum(),'data',StringToEnum(self.fe_SSA)[0],'format','Integer')129 WriteData(fid, 'enum',FlowequationFeHOEnum() ,'data',StringToEnum(self.fe_HO)[0] ,'format','Integer')130 WriteData(fid, 'enum',FlowequationFeFSEnum() ,'data',StringToEnum(self.fe_FS)[0] ,'format','Integer')131 WriteData(fid, 'enum',AugmentedLagrangianREnum(),'data',self.augmented_lagrangian_r ,'format','Double')132 WriteData(fid, 'enum',AugmentedLagrangianRhopEnum(),'data',self.augmented_lagrangian_rhop ,'format','Double')133 WriteData(fid, 'enum',AugmentedLagrangianRlambdaEnum(),'data',self.augmented_lagrangian_rlambda ,'format','Double')134 WriteData(fid, 'enum',AugmentedLagrangianRholambdaEnum(),'data',self.augmented_lagrangian_rholambda ,'format','Double')135 WriteData(fid, 'enum',AugmentedLagrangianThetaEnum(),'data',self.XTH_theta ,'format','Double')136 WriteData(fid, 'object',self,'fieldname','borderSSA','format','DoubleMat','mattype',1)137 WriteData(fid, 'object',self,'fieldname','borderHO','format','DoubleMat','mattype',1)138 WriteData(fid, 'object',self,'fieldname','borderFS','format','DoubleMat','mattype',1)124 def marshall(self,prefix,md,fid): # {{{ 125 WriteData(fid,prefix,'object',self,'fieldname','isSIA','format','Boolean') 126 WriteData(fid,prefix,'object',self,'fieldname','isSSA','format','Boolean') 127 WriteData(fid,prefix,'object',self,'fieldname','isL1L2','format','Boolean') 128 WriteData(fid,prefix,'object',self,'fieldname','isHO','format','Boolean') 129 WriteData(fid,prefix,'object',self,'fieldname','isFS','format','Boolean') 130 WriteData(fid,prefix,'object',self,'fieldname','fe_SSA','data',self.fe_SSA,'format','String') 131 WriteData(fid,prefix,'object',self,'fieldname','fe_HO','data',self.fe_HO,'format','String') 132 WriteData(fid,prefix,'object',self,'fieldname','fe_FS','data',self.fe_FS ,'format','String') 133 WriteData(fid,prefix,'object',self,'fieldname','augmented_lagrangian_r','format','Double'); 134 WriteData(fid,prefix,'object',self,'fieldname','augmented_lagrangian_rhop','format','Double'); 135 WriteData(fid,prefix,'object',self,'fieldname','augmented_lagrangian_rlambda','format','Double'); 136 WriteData(fid,prefix,'object',self,'fieldname','augmented_lagrangian_rholambda','format','Double'); 137 WriteData(fid,prefix,'object',self,'fieldname','XTH_theta','data',self.XTH_theta ,'format','Double') 138 WriteData(fid,prefix,'object',self,'fieldname','borderSSA','format','DoubleMat','mattype',1) 139 WriteData(fid,prefix,'object',self,'fieldname','borderHO','format','DoubleMat','mattype',1) 140 WriteData(fid,prefix,'object',self,'fieldname','borderFS','format','DoubleMat','mattype',1) 139 141 #convert approximations to enums 140 data=copy.deepcopy(self.vertex_equation) 141 data[numpy.nonzero(data==0)]=NoneApproximationEnum() 142 data[numpy.nonzero(data==1)]=SIAApproximationEnum() 143 data[numpy.nonzero(data==2)]=SSAApproximationEnum() 144 data[numpy.nonzero(data==3)]=L1L2ApproximationEnum() 145 data[numpy.nonzero(data==4)]=HOApproximationEnum() 146 data[numpy.nonzero(data==5)]=FSApproximationEnum() 147 data[numpy.nonzero(data==6)]=SSAHOApproximationEnum() 148 data[numpy.nonzero(data==7)]=HOFSApproximationEnum() 149 data[numpy.nonzero(data==8)]=SSAFSApproximationEnum() 150 WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1) 151 data=copy.deepcopy(self.element_equation) 152 data[numpy.nonzero(data==0)]=NoneApproximationEnum() 153 data[numpy.nonzero(data==1)]=SIAApproximationEnum() 154 data[numpy.nonzero(data==2)]=SSAApproximationEnum() 155 data[numpy.nonzero(data==3)]=L1L2ApproximationEnum() 156 data[numpy.nonzero(data==4)]=HOApproximationEnum() 157 data[numpy.nonzero(data==5)]=FSApproximationEnum() 158 data[numpy.nonzero(data==6)]=SSAHOApproximationEnum() 159 data[numpy.nonzero(data==7)]=SSAFSApproximationEnum() 160 data[numpy.nonzero(data==8)]=HOFSApproximationEnum() 161 WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum(),'format','DoubleMat','mattype',2) 142 WriteData(fid,prefix,'data',self.vertex_equation,'name','md.flowequation.vertex_equation','format','DoubleMat','mattype',1) 143 WriteData(fid,prefix,'data',self.element_equation,'name','md.flowequation.element_equation','format','DoubleMat','mattype',2) 144 162 145 # }}} -
issm/trunk-jpl/src/py3/classes/friction.py
r19898 r23670 1 import numpy as np 1 2 from fielddisplay import fielddisplay 2 3 from project3d import project3d 3 from EnumDefinitions import *4 4 from checkfield import checkfield 5 5 from WriteData import WriteData … … 17 17 self.p = float('NaN') 18 18 self.q = float('NaN') 19 19 self.coupling = 0 20 self.effective_pressure = float('NaN') 20 21 #set defaults 21 22 self.setdefaultparameters() … … 23 24 #}}} 24 25 def __repr__(self): # {{{ 25 string="Basal shear stress parameters: Sigma_b = coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b,\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*b ed, r=q/p and s=1/p)"26 string="Basal shear stress parameters: Sigma_b = coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b,\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*base, r=q/p and s=1/p)" 26 27 27 28 string="%s\n%s"%(string,fielddisplay(self,"coefficient","friction coefficient [SI]")) 28 29 string="%s\n%s"%(string,fielddisplay(self,"p","p exponent")) 29 30 string="%s\n%s"%(string,fielddisplay(self,"q","q exponent")) 31 string="%s\n%s"%(string,fielddisplay(self,'coupling','Coupling flag 0: uniform sheet (negative pressure ok, default), 1: ice pressure only, 2: water pressure assuming uniform sheet (no negative pressure), 3: use provided effective_pressure, 4: used coupled model (not implemented yet)')) 32 string="%s\n%s"%(string,fielddisplay(self,'effective_pressure','Effective Pressure for the forcing if not coupled [Pa]')) 30 33 return string 31 34 #}}} … … 34 37 self.p=project3d(md,'vector',self.p,'type','element') 35 38 self.q=project3d(md,'vector',self.q,'type','element') 39 #if self.coupling==0: #doesnt work with empty loop, so just skip it? 40 if self.coupling in[3,4]: 41 self.effective_pressure=project3d(md,'vector',self.effective_pressure,'type','node','layer',1) 42 elif self.coupling > 4: 43 raise ValueError('md.friction.coupling larger than 4, not supported yet') 36 44 return self 37 45 #}}} … … 42 50 43 51 #Early return 44 if StressbalanceAnalysisEnum() not in analyses and ThermalAnalysisEnum()not in analyses:52 if 'StressbalanceAnalysis' not in analyses and 'ThermalAnalysis' not in analyses: 45 53 return md 46 54 … … 48 56 md = checkfield(md,'fieldname','friction.q','NaN',1,'Inf',1,'size',[md.mesh.numberofelements]) 49 57 md = checkfield(md,'fieldname','friction.p','NaN',1,'Inf',1,'size',[md.mesh.numberofelements]) 50 58 md = checkfield(md,'fieldname','friction.coupling','numel',[1],'values',[0,1,2,3,4]) 59 if self.coupling==3: 60 md = checkfield(md,'fieldname','friction.effective_pressure','NaN',1,'Inf',1,'timeseries',1) 61 elif self.coupling > 4: 62 raise ValueError('md.friction.coupling larger than 4, not supported yet') 51 63 return md 52 64 # }}} 53 def marshall(self,md,fid): # {{{ 54 WriteData(fid,'enum',FrictionLawEnum(),'data',1,'format','Integer') 55 WriteData(fid,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1) 56 WriteData(fid,'object',self,'fieldname','p','format','DoubleMat','mattype',2) 57 WriteData(fid,'object',self,'fieldname','q','format','DoubleMat','mattype',2) 65 def marshall(self,prefix,md,fid): # {{{ 66 WriteData(fid,prefix,'name','md.friction.law','data',1,'format','Integer') 67 WriteData(fid,prefix,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1) 68 WriteData(fid,prefix,'object',self,'fieldname','p','format','DoubleMat','mattype',2) 69 WriteData(fid,prefix,'object',self,'fieldname','q','format','DoubleMat','mattype',2) 70 WriteData(fid,prefix,'class','friction','object',self,'fieldname','coupling','format','Integer') 71 if self.coupling in[3,4]: 72 WriteData(fid,prefix,'class','friction','object',self,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 73 elif self.coupling > 4: 74 raise ValueError('md.friction.coupling larger than 4, not supported yet') 58 75 # }}} -
issm/trunk-jpl/src/py3/classes/frictioncoulomb.py
r19898 r23670 1 1 from fielddisplay import fielddisplay 2 2 from project3d import project3d 3 from EnumDefinitions import *4 3 from checkfield import checkfield 5 4 from WriteData import WriteData … … 18 17 self.p = float('NaN') 19 18 self.q = float('NaN') 20 19 self.coupling = 0 20 self.effective_pressure = float('NaN') 21 21 #set defaults 22 22 self.setdefaultparameters() … … 30 30 string="%s\n%s"%(string,fielddisplay(self,"p","p exponent")) 31 31 string="%s\n%s"%(string,fielddisplay(self,"q","q exponent")) 32 string="%s\n%s"%(string,fielddisplay(self,'coupling','Coupling flag: 0 for default, 1 for forcing(provide md.friction.effective_pressure) and 2 for coupled(not implemented yet)')) 33 string="%s\n%s"%(string,fielddisplay(self,'effective_pressure','Effective Pressure for the forcing if not coupled [Pa]')) 32 34 return string 33 35 #}}} … … 37 39 self.p=project3d(md,'vector',self.p,'type','element') 38 40 self.q=project3d(md,'vector',self.q,'type','element') 41 if self.coupling==1: 42 self.effective_pressure=project3d(md,'vector',self.effective_pressure,'type','node','layer',1) 43 elif self.coupling==2: 44 raise ValueError('coupling not supported yet') 45 elif self.coupling > 2: 46 raise ValueError('md.friction.coupling larger than 2, not supported yet') 39 47 return self 40 48 #}}} … … 45 53 46 54 #Early return 47 if StressbalanceAnalysisEnum() not in analyses and ThermalAnalysisEnum()not in analyses:55 if 'StressbalanceAnalysis' not in analyses and 'ThermalAnalysis' not in analyses: 48 56 return md 49 57 … … 52 60 md = checkfield(md,'fieldname','friction.q','NaN',1,'Inf',1,'size',[md.mesh.numberofelements]) 53 61 md = checkfield(md,'fieldname','friction.p','NaN',1,'Inf',1,'size',[md.mesh.numberofelements]) 62 if self.coupling==1: 63 md = checkfield(md,'fieldname','friction.effective_pressure','NaN',1,'Inf',1,'timeseries',1) 64 elif self.coupling==2: 65 raise ValueError('coupling not supported yet') 66 elif self.coupling > 2: 67 raise ValueError('md.friction.coupling larger than 2, not supported yet') 68 return md 54 69 55 return md56 70 # }}} 57 def marshall(self,md,fid): # {{{ 58 WriteData(fid,'enum',FrictionLawEnum(),'data',1,'format','Integer') 59 WriteData(fid,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'enum',FrictionCoefficientEnum()) 60 WriteData(fid,'object',self,'fieldname','coefficientcoulomb','format','DoubleMat','mattype',1,'enum',FrictionCoefficientcoulombEnum()) 61 WriteData(fid,'object',self,'fieldname','p','format','DoubleMat','mattype',2,'enum',FrictionPEnum()) 62 WriteData(fid,'object',self,'fieldname','q','format','DoubleMat','mattype',2,'enum',FrictionQEnum()) 71 def marshall(self,prefix,md,fid): # {{{ 72 WriteData(fid,prefix,'name','md.friction.law','data',7,'format','Integer') 73 WriteData(fid,prefix,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 74 WriteData(fid,prefix,'object',self,'fieldname','coefficientcoulomb','format','DoubleMat','mattype',1) 75 WriteData(fid,prefix,'object',self,'fieldname','p','format','DoubleMat','mattype',2) 76 WriteData(fid,prefix,'object',self,'fieldname','q','format','DoubleMat','mattype',2) 77 WriteData(fid,prefix,'class','friction','object',self,'fieldname','coupling','format','Integer') 78 if self.coupling==1: 79 WriteData(fid,prefix,'class','friction','object',self,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 80 elif self.coupling==2: 81 raise ValueError('coupling not supported yet') 82 elif self.coupling > 2: 83 raise ValueError('md.friction.coupling larger than 2, not supported yet') 63 84 # }}} -
issm/trunk-jpl/src/py3/classes/frictionweertman.py
r19898 r23670 1 1 from fielddisplay import fielddisplay 2 2 from project3d import project3d 3 from EnumDefinitions import *4 3 from checkfield import checkfield 5 4 from WriteData import WriteData … … 34 33 35 34 #Early return 36 if StressbalanceAnalysisEnum() not in analyses and ThermalAnalysisEnum()not in analyses:35 if 'StressbalanceAnalysis' not in analyses and 'ThermalAnalysis' not in analyses: 37 36 return md 38 37 … … 42 41 return md 43 42 # }}} 44 def marshall(self, md,fid): # {{{45 WriteData(fid, 'enum',FrictionLawEnum(),'data',2,'format','Integer')46 WriteData(fid, 'class','friction','object',self,'fieldname','C','format','DoubleMat','mattype',1)47 WriteData(fid, 'class','friction','object',self,'fieldname','m','format','DoubleMat','mattype',2)43 def marshall(self,prefix,md,fid): # {{{ 44 WriteData(fid,prefix,'name','md.friction.law','data',2,'format','Integer') 45 WriteData(fid,prefix,'class','friction','object',self,'fieldname','C','format','DoubleMat','mattype',1) 46 WriteData(fid,prefix,'class','friction','object',self,'fieldname','m','format','DoubleMat','mattype',2) 48 47 # }}} -
issm/trunk-jpl/src/py3/classes/geometry.py
r19898 r23670 1 1 from project3d import project3d 2 2 from fielddisplay import fielddisplay 3 from EnumDefinitions import *4 3 from checkfield import checkfield 5 4 from WriteData import WriteData … … 14 13 15 14 def __init__(self): # {{{ 16 self.surface 17 self.thickness 15 self.surface = float('NaN') 16 self.thickness = float('NaN') 18 17 self.base = float('NaN') 19 self.bed 20 self.hydrostatic_ratio 18 self.bed = float('NaN') 19 self.hydrostatic_ratio = float('NaN') 21 20 22 21 #set defaults … … 46 45 def checkconsistency(self,md,solution,analyses): # {{{ 47 46 48 md = checkfield(md,'fieldname','geometry.surface' ,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 49 md = checkfield(md,'fieldname','geometry.base' ,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 50 md = checkfield(md,'fieldname','geometry.thickness','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices],'>',0,'timeseries',1) 51 if any(abs(self.thickness-self.surface+self.base)>10**-9): 52 md.checkmessage("equality thickness=surface-base violated") 53 if solution==TransientSolutionEnum() and md.transient.isgroundingline: 54 md = checkfield(md,'fieldname','geometry.bed','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 47 if (solution=='TransientSolution' and md.transient.isgia) or (solution=='GiaSolution'): 48 md = checkfield(md,'fieldname','geometry.thickness','NaN',1,'Inf',1,'>=',0,'timeseries',1) 49 elif solution=='LoveSolution': 50 return 51 else: 52 md = checkfield(md,'fieldname','geometry.surface' ,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 53 md = checkfield(md,'fieldname','geometry.base' ,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 54 md = checkfield(md,'fieldname','geometry.thickness','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices],'>',0,'timeseries',1) 55 if any(abs(self.thickness-self.surface+self.base)>10**-9): 56 md.checkmessage("equality thickness=surface-base violated") 57 if solution=='TransientSolution' and md.transient.isgroundingline: 58 md = checkfield(md,'fieldname','geometry.bed','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 55 59 56 60 return md 57 61 # }}} 58 def marshall(self, md,fid): # {{{59 WriteData(fid, 'data',self.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum())60 WriteData(fid, 'data',self.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum(),'timeserieslength',md.mesh.numberofvertices+1)61 WriteData(fid, 'data',self.base,'format','DoubleMat','mattype',1,'enum',BaseEnum())62 WriteData(fid, 'data',self.bed,'format','DoubleMat','mattype',1,'enum',BedEnum())63 WriteData(fid, 'object',self,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1)62 def marshall(self,prefix,md,fid): # {{{ 63 WriteData(fid,prefix,'object',self,'fieldname','surface','format','DoubleMat','mattype',1) 64 WriteData(fid,prefix,'object',self,'fieldname','thickness','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 65 WriteData(fid,prefix,'object',self,'fieldname','base','format','DoubleMat','mattype',1) 66 WriteData(fid,prefix,'object',self,'fieldname','bed','format','DoubleMat','mattype',1) 67 WriteData(fid,prefix,'object',self,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1) 64 68 # }}} -
issm/trunk-jpl/src/py3/classes/groundingline.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from fielddisplay import fielddisplay 3 from EnumDefinitions import *4 from StringToEnum import StringToEnum5 3 from checkfield import checkfield 6 4 from WriteData import WriteData … … 17 15 def __init__(self): # {{{ 18 16 self.migration='' 17 self.friction_interpolation='' 18 self.melt_interpolation='' 19 19 20 20 #set defaults … … 25 25 string=' grounding line migration parameters:' 26 26 27 string="%s\n%s"%(string,fielddisplay(self,'migration','type of grounding line migration: ''SoftMigration'',''AggressiveMigration'',''SubelementMigration'',''SubelementMigration2'',''Contact'',''None''')) 27 string="%s\n%s"%(string,fielddisplay(self,'migration','type of grounding line migration: ''SoftMigration'',''SubelementMigration'',''AggressiveMigration'',''Contact'',''None''')) 28 string="%s\n%s"%(string,fielddisplay(self,'migration','type of friction interpolation on partially floating elements: ''SubelementFriction1'',''SubelementFriction2'',''NoFrictionOnPartiallyFloating''')) 29 string="%s\n%s"%(string,fielddisplay(self,'migration','type of melt interpolation on partially floating elements: ''SubelementMelt1'',''SubelementMelt2'',''NoMeltOnPartiallyFloating'',''FullMeltOnPartiallyFloating''')) 28 30 return string 29 31 #}}} … … 31 33 32 34 #Type of migration 33 self.migration='None' 35 self.migration='SubelementMigration' 36 self.friction_interpolation='SubelementFriction1' 37 self.melt_interpolation='NoMeltOnPartiallyFloating' 34 38 35 39 return self … … 37 41 def checkconsistency(self,md,solution,analyses): # {{{ 38 42 39 md = checkfield(md,fieldname='groundingline.migration',values=['None','AggressiveMigration','SoftMigration','SubelementMigration','SubelementMigration2','Contact','GroundingOnly']) 43 md = checkfield(md,'fieldname','groundingline.migration','values',['None','SubelementMigration','AggressiveMigration','SoftMigration','Contact','GroundingOnly']) 44 md = checkfield(md,'fieldname','groundingline.friction_interpolation','values',['SubelementFriction1','SubelementFriction2','NoFrictionOnPartiallyFloating']) 45 md = checkfield(md,'fieldname','groundingline.melt_interpolation','values',['SubelementMelt1','SubelementMelt2','NoMeltOnPartiallyFloating','FullMeltOnPartiallyFloating']) 40 46 41 if not m.strcmp(self.migration,'None'):42 if n umpy.any(numpy.isnan(md.geometry.bed)):47 if(not m.strcmp(self.migration,'None') and md.transient.isgroundingline and solution=='TransientSolution'): 48 if np.any(np.isnan(md.geometry.bed)): 43 49 md.checkmessage("requesting grounding line migration, but bathymetry is absent!") 44 pos=n umpy.nonzero(md.mask.groundedice_levelset>0.)[0]45 if any(n umpy.abs(md.geometry.base[pos]-md.geometry.bed[pos])>10**-10):50 pos=np.nonzero(md.mask.groundedice_levelset>0.)[0] 51 if any(np.abs(md.geometry.base[pos]-md.geometry.bed[pos])>10**-10): 46 52 md.checkmessage("base not equal to bed on grounded ice!") 47 53 if any(md.geometry.bed - md.geometry.base > 10**-9): … … 50 56 return md 51 57 # }}} 52 def marshall(self,md,fid): # {{{ 53 WriteData(fid,'data',StringToEnum(self.migration)[0],'enum',GroundinglineMigrationEnum(),'format','Integer') 58 def marshall(self,prefix,md,fid): # {{{ 59 WriteData(fid,prefix,'data',self.migration,'name','md.groundingline.migration','format','String') 60 WriteData(fid,prefix,'data',self.friction_interpolation,'name','md.groundingline.friction_interpolation','format','String') 61 WriteData(fid,prefix,'data',self.melt_interpolation,'name','md.groundingline.melt_interpolation','format','String') 54 62 # }}} -
issm/trunk-jpl/src/py3/classes/hydrologydc.py
r19903 r23670 1 import numpy 1 import numpy as np 2 2 from project3d import project3d 3 3 from fielddisplay import fielddisplay 4 from EnumDefinitions import *5 4 from checkfield import checkfield 6 5 from WriteData import WriteData … … 21 20 self.rel_tol = 0 22 21 self.max_iter = 0 22 self.steps_per_step = 0 23 23 self.sedimentlimit_flag = 0 24 24 self.sedimentlimit = 0 25 25 self.transfer_flag = 0 26 self.unconfined_flag = 0 26 27 self.leakage_factor = 0 27 self.basal_moulin_input = float('NaN') 28 29 self.spcsediment_head = float('NaN') 30 self.sediment_transmitivity = float('NaN') 28 self.basal_moulin_input = np.nan 29 self.requested_outputs = [] 30 31 self.spcsediment_head = np.nan 32 self.mask_thawed_node = np.nan 33 self.sediment_transmitivity = np.nan 31 34 self.sediment_compressibility = 0 32 35 self.sediment_porosity = 0 33 36 self.sediment_thickness = 0 34 37 35 36 self.spcepl_head = float('NaN') 37 self.mask_eplactive_node = float('NaN') 38 self.spcepl_head = np.nan 39 self.mask_eplactive_node = np.nan 38 40 self.epl_compressibility = 0 39 41 self.epl_porosity = 0 … … 44 46 self.epl_conductivity = 0 45 47 self.eplflip_lock = 0 46 48 47 49 #set defaults 48 50 self.setdefaultparameters() … … 57 59 string="%s\n%s"%(string,fielddisplay(self,'rel_tol','tolerance of the nonlinear iteration for the transfer between layers [dimensionless]')) 58 60 string="%s\n%s"%(string,fielddisplay(self,'max_iter','maximum number of nonlinear iteration')) 61 string="%s\n%s"%(string,fielddisplay(self,'steps_per_step','number of hydrology steps per time step')) 59 62 string="%s\n%s"%(string,fielddisplay(self,'basal_moulin_input','water flux at a given point [m3 s-1]')) 63 string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested')) 60 64 string="%s\n%s"%(string,fielddisplay(self,'sedimentlimit_flag','what kind of upper limit is applied for the inefficient layer')) 61 65 string="%s\n\t\t%s"%(string,'0: no limit') … … 63 67 string="%s\n\t\t%s"%(string,'2: hydrostatic pressure') 64 68 string="%s\n\t\t%s"%(string,'3: normal stress') 65 69 66 70 if self.sedimentlimit_flag==1: 67 71 string="%s\n%s"%(string,fielddisplay(self,'sedimentlimit','user defined upper limit for the inefficient layer [m]')) … … 70 74 string="%s\n\t\t%s"%(string,'0: no transfer') 71 75 string="%s\n\t\t%s"%(string,'1: constant leakage factor: leakage_factor') 72 76 73 77 if self.transfer_flag is 1: 74 78 string="%s\n%s"%(string,fielddisplay(self,'leakage_factor','user defined leakage factor [m]')) 79 80 string="%s\n%s"%(string,fielddisplay(self,'unconfined_flag','using an unconfined scheme or not (transitory)')) 81 string="%s\n\t\t%s"%(string,'0: Confined only') 82 string="%s\n\t\t%s"%(string,'1: Confined-Unconfined') 75 83 76 84 string="%s\n%s"%(string,' - for the sediment layer') … … 80 88 string="%s\n%s"%(string,fielddisplay(self,'sediment_thickness','sediment thickness [m]')) 81 89 string="%s\n%s"%(string,fielddisplay(self,'sediment_transmitivity','sediment transmitivity [m^2/s]')) 90 string="%s\n%s"%(string,fielddisplay(self,'mask_thawed_node','IDS is deactivaed (0) on frozen nodes')) 82 91 83 92 if self.isefficientlayer==1: … … 87 96 string="%s\n%s"%(string,fielddisplay(self,'epl_compressibility','epl compressibility [Pa^-1]')) 88 97 string="%s\n%s"%(string,fielddisplay(self,'epl_porosity','epl [dimensionless]')) 89 string="%s\n%s"%(string,fielddisplay(self,'epl_max_thickness','epl initial thickness [m]'))90 string="%s\n%s"%(string,fielddisplay(self,'epl_initial_thickness','epl initial thickness [m]')) 98 string="%s\n%s"%(string,fielddisplay(self,'epl_max_thickness','epl maximal thickness [m]')) 99 string="%s\n%s"%(string,fielddisplay(self,'epl_initial_thickness','epl initial thickness [m]')) 91 100 string="%s\n%s"%(string,fielddisplay(self,'epl_colapse_thickness','epl colapsing thickness [m]')) 92 101 string="%s\n%s"%(string,fielddisplay(self,'epl_thick_comp','epl thickness computation flag')) … … 97 106 def extrude(self,md): # {{{ 98 107 self.spcsediment_head=project3d(md,'vector',self.spcsediment_head,'type','node','layer',1) 99 self.spcepl_head=project3d(md,'vector',self.spcepl_head,'type','node','layer',1)100 self.mask_eplactive_node=project3d(md,'vector',self.mask_eplactive_node,'type','node','layer',1)101 108 self.sediment_transmitivity=project3d(md,'vector',self.sediment_transmitivity,'type','node','layer',1) 102 109 self.basal_moulin_input=project3d(md,'vector',self.basal_moulin_input,'type','node','layer',1) 110 self.mask_thawed_node=project3d(md,'vector',self.mask_thawed_node,'type','node','layer',1) 103 111 if self.isefficientlayer==1 : 104 112 self.spcepl_head=project3d(md,'vector',self.spcepl_head,'type','node','layer',1) 113 self.mask_eplactive_node=project3d(md,'vector',self.mask_eplactive_node,'type','node','layer',1) 105 114 return self 106 115 #}}} 107 def setdefaultparameters(self): #{{{ 108 116 def setdefaultparameters(self): #{{{ 109 117 #Parameters from de Fleurian 2014 110 118 self.water_compressibility = 5.04e-10 … … 114 122 self.rel_tol = 1.0e-06 115 123 self.max_iter = 100 124 self.steps_per_step = 1 116 125 self.sedimentlimit_flag = 0 117 126 self.sedimentlimit = 0 118 127 self.transfer_flag = 0 128 self.unconfined_flag = 0 119 129 self.leakage_factor = 10.0 130 self.requested_outputs = ['default'] 120 131 121 132 self.sediment_compressibility = 1.0e-08 … … 125 136 126 137 self.epl_compressibility = 1.0e-08 138 self.epl_conductivity = 8.0e-02 127 139 self.epl_porosity = 0.4 128 140 self.epl_initial_thickness = 1.0 129 self.epl_colapse_thickness = 1.0e-3141 self.epl_colapse_thickness = self.sediment_transmitivity/self.epl_conductivity 130 142 self.epl_thick_comp = 1 131 143 self.epl_max_thickness = 5.0 132 self.epl_conductivity = 8.0e-02133 144 self.eplflip_lock = 0 134 145 135 146 return self 136 147 # }}} 148 149 def defaultoutputs(self,md): # {{{ 150 list = ['SedimentHeadHydrostep','SedimentHeadResidual','EffectivePressureHydrostep'] 151 if self.isefficientlayer==1: 152 list.extend(['EplHeadHydrostep','HydrologydcMaskEplactiveNode','HydrologydcMaskEplactiveElt','EplHeadSlopeX','EplHeadSlopeY','HydrologydcEplThicknessHydrostep']) 153 if self.steps_per_step>1: 154 list.extend(['EffectivePressure','SedimentHead']) 155 if self.isefficientlayer==1: 156 list.extend(['EplHead','HydrologydcEplThickness']) 157 return list 158 #}}} 159 137 160 def initialize(self,md): # {{{ 138 if numpy.all(numpy.isnan(self.basal_moulin_input)): 139 self.basal_moulin_input=numpy.zeros((md.mesh.numberofvertices,1)) 161 self.epl_colapse_thickness = self.sediment_transmitivity/self.epl_conductivity 162 if np.all(np.isnan(self.basal_moulin_input)): 163 self.basal_moulin_input=np.zeros((md.mesh.numberofvertices)) 140 164 print(" no hydrology.basal_moulin_input specified: values set as zero") 141 165 142 166 return self 143 167 # }}} 144 def checkconsistency(self,md,solution,analyses): #{{{ 168 def checkconsistency(self,md,solution,analyses): #{{{ 145 169 146 170 #Early return 147 if HydrologyDCInefficientAnalysisEnum() not in analyses and HydrologyDCEfficientAnalysisEnum()not in analyses:171 if 'HydrologyDCInefficientAnalysis' not in analyses and 'HydrologyDCEfficientAnalysis' not in analyses: 148 172 return md 149 173 … … 154 178 md = checkfield(md,'fieldname','hydrology.rel_tol','>',0.,'numel',[1]) 155 179 md = checkfield(md,'fieldname','hydrology.max_iter','>',0.,'numel',[1]) 180 md = checkfield(md,'fieldname','hydrology.steps_per_step','>',0.,'numel',[1]) 156 181 md = checkfield(md,'fieldname','hydrology.sedimentlimit_flag','numel',[1],'values',[0,1,2,3]) 157 182 md = checkfield(md,'fieldname','hydrology.transfer_flag','numel',[1],'values',[0,1]) 183 md = checkfield(md,'fieldname','hydrology.unconfined_flag','numel',[1],'values',[0,1]) 184 md = checkfield(md,'fieldname','hydrology.requested_outputs','stringrow',1) 158 185 159 186 if self.sedimentlimit_flag==1: … … 168 195 md = checkfield(md,'fieldname','hydrology.sediment_porosity','>',0.,'numel',[1]) 169 196 md = checkfield(md,'fieldname','hydrology.sediment_thickness','>',0.,'numel',[1]) 170 md = checkfield(md,'fieldname','hydrology.sediment_transmitivity','>=',0,'size',[md.mesh.numberofvertices,1]) 197 md = checkfield(md,'fieldname','hydrology.sediment_transmitivity','>=',0,'size',[md.mesh.numberofvertices]) 198 md = checkfield(md,'fieldname','hydrology.mask_thawed_node','size',[md.mesh.numberofvertices],'values',[0,1]) 171 199 if self.isefficientlayer==1: 172 200 md = checkfield(md,'fieldname','hydrology.spcepl_head','Inf',1,'timeseries',1) 173 md = checkfield(md,'fieldname','hydrology.mask_eplactive_node','size',[md.mesh.numberofvertices ,1],'values',[0,1])201 md = checkfield(md,'fieldname','hydrology.mask_eplactive_node','size',[md.mesh.numberofvertices],'values',[0,1]) 174 202 md = checkfield(md,'fieldname','hydrology.epl_compressibility','>',0.,'numel',[1]) 175 203 md = checkfield(md,'fieldname','hydrology.epl_porosity','>',0.,'numel',[1]) … … 183 211 md = checkfield(md,'fieldname','hydrology.epl_conductivity','numel',[1],'>',0.) 184 212 # }}} 185 def marshall(self,md,fid): #{{{ 186 WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologydcEnum(),'format','Integer') 187 WriteData(fid,'object',self,'fieldname','water_compressibility','format','Double') 188 WriteData(fid,'object',self,'fieldname','isefficientlayer','format','Boolean') 189 WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double') 190 WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer') 191 WriteData(fid,'object',self,'fieldname','rel_tol','format','Double') 192 WriteData(fid,'object',self,'fieldname','max_iter','format','Integer') 193 WriteData(fid,'object',self,'fieldname','sedimentlimit_flag','format','Integer') 194 WriteData(fid,'object',self,'fieldname','transfer_flag','format','Integer') 213 def marshall(self,prefix,md,fid): #{{{ 214 WriteData(fid,prefix,'name','md.hydrology.model','data',1,'format','Integer') 215 WriteData(fid,prefix,'object',self,'fieldname','water_compressibility','format','Double') 216 WriteData(fid,prefix,'object',self,'fieldname','isefficientlayer','format','Boolean') 217 WriteData(fid,prefix,'object',self,'fieldname','penalty_factor','format','Double') 218 WriteData(fid,prefix,'object',self,'fieldname','penalty_lock','format','Integer') 219 WriteData(fid,prefix,'object',self,'fieldname','rel_tol','format','Double') 220 WriteData(fid,prefix,'object',self,'fieldname','max_iter','format','Integer') 221 WriteData(fid,prefix,'object',self,'fieldname','steps_per_step','format','Integer') 222 WriteData(fid,prefix,'object',self,'fieldname','sedimentlimit_flag','format','Integer') 223 WriteData(fid,prefix,'object',self,'fieldname','transfer_flag','format','Integer') 224 WriteData(fid,prefix,'object',self,'fieldname','unconfined_flag','format','Integer') 195 225 if self.sedimentlimit_flag==1: 196 WriteData(fid, 'object',self,'fieldname','sedimentlimit','format','Double')226 WriteData(fid,prefix,'object',self,'fieldname','sedimentlimit','format','Double') 197 227 198 228 if self.transfer_flag==1: 199 WriteData(fid,'object',self,'fieldname','leakage_factor','format','Double') 200 201 WriteData(fid,'object',self,'fieldname','basal_moulin_input','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1) 202 WriteData(fid,'object',self,'fieldname','spcsediment_head','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1) 203 WriteData(fid,'object',self,'fieldname','sediment_compressibility','format','Double') 204 WriteData(fid,'object',self,'fieldname','sediment_porosity','format','Double') 205 WriteData(fid,'object',self,'fieldname','sediment_thickness','format','Double') 206 WriteData(fid,'object',self,'fieldname','sediment_transmitivity','format','DoubleMat','mattype',1) 207 208 if self.isefficientlayer==1: 209 WriteData(fid,'object',self,'fieldname','spcepl_head','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1) 210 WriteData(fid,'object',self,'fieldname','mask_eplactive_node','format','DoubleMat','mattype',1) 211 WriteData(fid,'object',self,'fieldname','epl_compressibility','format','Double') 212 WriteData(fid,'object',self,'fieldname','epl_porosity','format','Double') 213 WriteData(fid,'object',self,'fieldname','epl_max_thickness','format','Double') 214 WriteData(fid,'object',self,'fieldname','epl_initial_thickness','format','Double') 215 WriteData(fid,'object',self,'fieldname','epl_colapse_thickness','format','Double') 216 WriteData(fid,'object',self,'fieldname','epl_thick_comp','format','Integer') 217 WriteData(fid,'object',self,'fieldname','epl_conductivity','format','Double') 218 WriteData(fid,'object',self,'fieldname','eplflip_lock','format','Integer') 219 # }}} 229 WriteData(fid,prefix,'object',self,'fieldname','leakage_factor','format','Double') 230 231 WriteData(fid,prefix,'object',self,'fieldname','basal_moulin_input','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 232 WriteData(fid,prefix,'object',self,'fieldname','spcsediment_head','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 233 WriteData(fid,prefix,'object',self,'fieldname','sediment_compressibility','format','Double') 234 WriteData(fid,prefix,'object',self,'fieldname','sediment_porosity','format','Double') 235 WriteData(fid,prefix,'object',self,'fieldname','sediment_thickness','format','Double') 236 WriteData(fid,prefix,'object',self,'fieldname','sediment_transmitivity','format','DoubleMat','mattype',1) 237 WriteData(fid,prefix,'object',self,'fieldname','mask_thawed_node','format','DoubleMat','mattype',1) 238 239 if self.isefficientlayer==1: 240 WriteData(fid,prefix,'object',self,'fieldname','spcepl_head','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 241 WriteData(fid,prefix,'object',self,'fieldname','mask_eplactive_node','format','DoubleMat','mattype',1) 242 WriteData(fid,prefix,'object',self,'fieldname','epl_compressibility','format','Double') 243 WriteData(fid,prefix,'object',self,'fieldname','epl_porosity','format','Double') 244 WriteData(fid,prefix,'object',self,'fieldname','epl_max_thickness','format','Double') 245 WriteData(fid,prefix,'object',self,'fieldname','epl_initial_thickness','format','Double') 246 WriteData(fid,prefix,'object',self,'fieldname','epl_colapse_thickness','format','Double') 247 WriteData(fid,prefix,'object',self,'fieldname','epl_thick_comp','format','Integer') 248 WriteData(fid,prefix,'object',self,'fieldname','epl_conductivity','format','Double') 249 WriteData(fid,prefix,'object',self,'fieldname','eplflip_lock','format','Integer') 250 251 #process requested outputs 252 outputs = self.requested_outputs 253 indices = [i for i, x in enumerate(outputs) if x == 'default'] 254 if len(indices) > 0: 255 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 256 outputs =outputscopy 257 WriteData(fid,prefix,'data',outputs,'name','md.hydrology.requested_outputs','format','StringArray') 258 # }}} -
issm/trunk-jpl/src/py3/classes/hydrologyshreve.py
r19903 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *3 2 from checkfield import checkfield 4 3 from WriteData import WriteData … … 15 14 self.spcwatercolumn = float('NaN') 16 15 self.stabilization = 0 17 16 self.requested_outputs = [] 18 17 #set defaults 19 18 self.setdefaultparameters() … … 25 24 string="%s\n%s"%(string,fielddisplay(self,'spcwatercolumn','water thickness constraints (NaN means no constraint) [m]')) 26 25 string="%s\n%s"%(string,fielddisplay(self,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.')) 26 string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested')) 27 27 return string 28 28 #}}} … … 34 34 #Type of stabilization to use 0:nothing 1:artificial_diffusivity 35 35 self.stabilization=1 36 36 self.requested_outputs= ['default'] 37 37 return self 38 38 #}}} 39 def defaultoutputs(self,md): # {{{ 40 list = ['Watercolumn','HydrologyWaterVx','HydrologyWaterVy'] 41 return list 42 #}}} 43 39 44 def checkconsistency(self,md,solution,analyses): # {{{ 40 45 41 46 #Early return 42 if HydrologyShreveAnalysisEnum()not in analyses:47 if 'HydrologyShreveAnalysis' not in analyses: 43 48 return md 44 49 45 50 md = checkfield(md,'fieldname','hydrology.spcwatercolumn','Inf',1,'timeseries',1) 46 51 md = checkfield(md,'fieldname','hydrology.stabilization','>=',0) 47 52 md = checkfield(md,'fieldname','hydrology.requested_outputs','stringrow',1) 48 53 return md 49 54 # }}} 50 def marshall(self,md,fid): # {{{ 51 WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologyshreveEnum(),'format','Integer'); 52 WriteData(fid,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1) 53 WriteData(fid,'object',self,'fieldname','stabilization','format','Double') 55 def marshall(self,prefix,md,fid): # {{{ 56 WriteData(fid,prefix,'name','md.hydrology.model','data',2,'format','Integer'); 57 WriteData(fid,prefix,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 58 WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Double') 59 #process requested outputs 60 outputs = self.requested_outputs 61 indices = [i for i, x in enumerate(outputs) if x == 'default'] 62 if len(indices) > 0: 63 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 64 outputs =outputscopy 65 WriteData(fid,prefix,'data',outputs,'name','md.hydrology.requested_outputs','format','StringArray') 66 54 67 # }}} -
issm/trunk-jpl/src/py3/classes/independent.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from pairoptions import pairoptions 3 3 from fielddisplay import fielddisplay 4 import MatlabFuncs as m 5 from EnumDefinitions import *4 from checkfield import checkfield 5 from MatlabFuncs import * 6 6 7 7 class independent(object): … … 13 13 """ 14 14 15 def __init__(self,* *kwargs): # {{{15 def __init__(self,*args): # {{{ 16 16 self.name = '' 17 17 self.type = '' 18 18 self.fos_forward_index = float('NaN') 19 self.fov_forward_indices = n umpy.array([])19 self.fov_forward_indices = np.array([]) 20 20 self.nods = 0 21 21 … … 24 24 25 25 #use provided options to change fields 26 options=pairoptions(* *kwargs)26 options=pairoptions(*args) 27 27 28 28 #OK get other fields … … 32 32 s =" independent variable:\n" 33 33 34 s+="%s\n" % fielddisplay(self,'name',"variable name (must match corresponding Enum)")34 s+="%s\n" % fielddisplay(self,'name',"variable name (must match corresponding String)") 35 35 s+="%s\n" % fielddisplay(self,'type',"type of variable ('vertex' or 'scalar')") 36 if not n umpy.isnan(self.fos_forward_index):36 if not np.isnan(self.fos_forward_index): 37 37 s+="%s\n" % fielddisplay(self,'fos_forward_index',"index for fos_foward driver of ADOLC") 38 if n umpy.any(numpy.logical_not(numpy.isnan(self.fov_forward_indices))):38 if np.any(np.logical_not(np.isnan(self.fov_forward_indices))): 39 39 s+="%s\n" % fielddisplay(self,'fov_forward_indices',"indices for fov_foward driver of ADOLC") 40 40 … … 46 46 # }}} 47 47 def checkconsistency(self,md,i,solution,analyses,driver): # {{{ 48 if not n umpy.isnan(self.fos_forward_index):48 if not np.isnan(self.fos_forward_index): 49 49 if not strcmpi(driver,'fos_forward'): 50 50 raise TypeError("cannot declare an independent with a fos_forward_index when the driver is not fos_forward!") … … 52 52 raise TypeError("independent checkconsistency error: nods should be set to the size of the independent variable") 53 53 54 if self.fov_forward_indices:54 if len(self.fov_forward_indices) > 0: 55 55 if not strcmpi(driver,'fov_forward'): 56 56 raise TypeError("cannot declare an independent with fov_forward_indices when the driver is not fov_forward!") 57 57 if self.nods==0: 58 58 raise TypeError("independent checkconsistency error: nods should be set to the size of the independent variable") 59 md = checkfield(md,'fieldname',"autodiff.independents[%d].fov_forward_indices" % i,'>=',1,'<=',self.nods ,'size',[float('NaN'),1])59 md = checkfield(md,'fieldname',"autodiff.independents[%d].fov_forward_indices" % i,'>=',1,'<=',self.nods) 60 60 61 61 return md -
issm/trunk-jpl/src/py3/classes/initialization.py
r19898 r23670 1 import numpy 1 import numpy as np 2 2 from project3d import project3d 3 3 from fielddisplay import fielddisplay 4 from EnumDefinitions import *5 4 from checkfield import checkfield 6 5 from WriteData import WriteData … … 62 61 63 62 #Lithostatic pressure by default 64 self.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z.reshape(-1,1)) 63 # self.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface[:,0]-md.mesh.z) 64 #self.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z.reshape(-1,)) 65 66 if np.ndim(md.geometry.surface)==2: 67 print('Reshaping md.geometry.surface for you convenience but you should fix it in you files') 68 self.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface.reshape(-1,)-md.mesh.z) 69 else: 70 self.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z) 71 65 72 return self 66 73 #}}} … … 69 76 #}}} 70 77 def checkconsistency(self,md,solution,analyses): # {{{ 71 if StressbalanceAnalysisEnum()in analyses:72 if not n umpy.any(numpy.logical_or(numpy.isnan(md.initialization.vx),numpy.isnan(md.initialization.vy))):78 if 'StressbalanceAnalysis' in analyses: 79 if not np.any(np.logical_or(np.isnan(md.initialization.vx),np.isnan(md.initialization.vy))): 73 80 md = checkfield(md,'fieldname','initialization.vx','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 74 81 md = checkfield(md,'fieldname','initialization.vy','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 75 if MasstransportAnalysisEnum()in analyses:82 if 'MasstransportAnalysis' in analyses: 76 83 md = checkfield(md,'fieldname','initialization.vx','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 77 84 md = checkfield(md,'fieldname','initialization.vy','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 78 if BalancethicknessAnalysisEnum()in analyses:85 if 'BalancethicknessAnalysis' in analyses: 79 86 md = checkfield(md,'fieldname','initialization.vx','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 80 87 md = checkfield(md,'fieldname','initialization.vy','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 81 88 #Triangle with zero velocity 82 if n umpy.any(numpy.logical_and(numpy.sum(numpy.abs(md.initialization.vx[md.mesh.elements-1]),axis=1)==0,\83 n umpy.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)): 84 91 md.checkmessage("at least one triangle has all its vertices with a zero velocity") 85 if ThermalAnalysisEnum()in analyses:92 if 'ThermalAnalysis' in analyses: 86 93 md = checkfield(md,'fieldname','initialization.vx','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 87 94 md = checkfield(md,'fieldname','initialization.vy','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) … … 90 97 md = checkfield(md,'fieldname','initialization.vz','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 91 98 md = checkfield(md,'fieldname','initialization.pressure','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 92 if ( EnthalpyAnalysisEnum()in analyses and md.thermal.isenthalpy):99 if ('EnthalpyAnalysis' in analyses and md.thermal.isenthalpy): 93 100 md = checkfield(md,'fieldname','initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices]) 94 101 md = checkfield(md,'fieldname','initialization.watercolumn' ,'>=',0,'size',[md.mesh.numberofvertices]) 95 if HydrologyShreveAnalysisEnum() in analyses: 102 pos = np.nonzero(md.initialization.waterfraction > 0.)[0] 103 if(pos.size): 104 md = checkfield(md,'fieldname', 'delta Tpmp', 'field', np.absolute(md.initialization.temperature[pos]-(md.materials.meltingpoint-md.materials.beta*md.initialization.pressure[pos])),'<',1e-11, 'message','set temperature to pressure melting point at locations with waterfraction>0'); 105 if 'HydrologyShreveAnalysis' in analyses: 96 106 if hasattr(md.hydrology,'hydrologyshreve'): 97 107 md = checkfield(md,'fieldname','initialization.watercolumn','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 98 if HydrologyDCInefficientAnalysisEnum()in analyses:108 if 'HydrologyDCInefficientAnalysis' in analyses: 99 109 if hasattr(md.hydrology,'hydrologydc'): 100 md = checkfield(md,'fieldname','initialization.sediment_head','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices ,1])101 if HydrologyDCEfficientAnalysisEnum()in analyses:110 md = checkfield(md,'fieldname','initialization.sediment_head','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 111 if 'HydrologyDCEfficientAnalysis' in analyses: 102 112 if hasattr(md.hydrology,'hydrologydc'): 103 113 if md.hydrology.isefficientlayer==1: 104 md = checkfield(md,'fieldname','initialization.epl_head','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices ,1])105 md = checkfield(md,'fieldname','initialization.epl_thickness','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices ,1])114 md = checkfield(md,'fieldname','initialization.epl_head','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 115 md = checkfield(md,'fieldname','initialization.epl_thickness','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 106 116 107 117 return md 108 118 # }}} 109 def marshall(self, md,fid): # {{{119 def marshall(self,prefix,md,fid): # {{{ 110 120 111 yts= 365.0*24.0*3600.0121 yts=md.constants.yts 112 122 113 WriteData(fid,'data',self.vx,'format','DoubleMat','mattype',1,'enum',VxEnum(),'scale',1./yts) 114 WriteData(fid,'data',self.vy,'format','DoubleMat','mattype',1,'enum',VyEnum(),'scale',1./yts) 115 WriteData(fid,'data',self.vz,'format','DoubleMat','mattype',1,'enum',VzEnum(),'scale',1./yts) 116 WriteData(fid,'data',self.pressure,'format','DoubleMat','mattype',1,'enum',PressureEnum()) 117 WriteData(fid,'data',self.temperature,'format','DoubleMat','mattype',1,'enum',TemperatureEnum()) 118 WriteData(fid,'data',self.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum()) 119 WriteData(fid,'data',self.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum()) 120 WriteData(fid,'data',self.sediment_head,'format','DoubleMat','mattype',1,'enum',SedimentHeadEnum()) 121 WriteData(fid,'data',self.epl_head,'format','DoubleMat','mattype',1,'enum',EplHeadEnum()) 122 WriteData(fid,'data',self.epl_thickness,'format','DoubleMat','mattype',1,'enum',HydrologydcEplThicknessEnum()) 123 123 WriteData(fid,prefix,'object',self,'fieldname','vx','format','DoubleMat','mattype',1,'scale',1./yts) 124 WriteData(fid,prefix,'object',self,'fieldname','vy','format','DoubleMat','mattype',1,'scale',1./yts) 125 WriteData(fid,prefix,'object',self,'fieldname','vz','format','DoubleMat','mattype',1,'scale',1./yts) 126 WriteData(fid,prefix,'object',self,'fieldname','pressure','format','DoubleMat','mattype',1) 127 WriteData(fid,prefix,'object',self,'fieldname','temperature','format','DoubleMat','mattype',1) 128 WriteData(fid,prefix,'object',self,'fieldname','waterfraction','format','DoubleMat','mattype',1) 129 WriteData(fid,prefix,'object',self,'fieldname','sediment_head','format','DoubleMat','mattype',1) 130 WriteData(fid,prefix,'object',self,'fieldname','epl_head','format','DoubleMat','mattype',1) 131 WriteData(fid,prefix,'object',self,'fieldname','epl_thickness','format','DoubleMat','mattype',1) 132 WriteData(fid,prefix,'object',self,'fieldname','watercolumn','format','DoubleMat','mattype',1) 124 133 125 134 if md.thermal.isenthalpy: 126 135 tpmp = md.materials.meltingpoint - md.materials.beta*md.initialization.pressure; 127 pos = n umpy.nonzero(md.initialization.temperature > tpmp)[0]136 pos = np.nonzero(md.initialization.waterfraction > 0.)[0] 128 137 enthalpy = md.materials.heatcapacity*(md.initialization.temperature-md.constants.referencetemperature); 129 enthalpy[pos] = md.materials.heatcapacity* tpmp[pos].reshape(-1,1) - md.constants.referencetemperature + md.materials.latentheat*md.initialization.waterfraction[pos].reshape(-1,1)130 WriteData(fid, 'data',enthalpy,'format','DoubleMat','mattype',1,'enum',EnthalpyEnum());138 enthalpy[pos] = md.materials.heatcapacity*(tpmp[pos].reshape(-1,) - md.constants.referencetemperature) + md.materials.latentheat*md.initialization.waterfraction[pos].reshape(-1,) 139 WriteData(fid,prefix,'data',enthalpy,'format','DoubleMat','mattype',1,'name','md.initialization.enthalpy'); 131 140 132 141 # }}} -
issm/trunk-jpl/src/py3/classes/inversion.py
r19898 r23670 1 import numpy 1 import numpy as np 2 2 from project3d import project3d 3 3 from fielddisplay import fielddisplay 4 from EnumDefinitions import *5 from StringToEnum import StringToEnum6 4 from checkfield import checkfield 7 5 from WriteData import WriteData … … 24 22 self.nsteps = 0 25 23 self.maxiter_per_step = float('NaN') 26 self.cost_functions = float('NaN')24 self.cost_functions = '' 27 25 self.cost_functions_coefficients = float('NaN') 28 26 self.gradient_scaling = float('NaN') … … 78 76 self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node') 79 77 self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node') 80 if not n umpy.any(numpy.isnan(self.cost_functions_coefficients)):78 if not np.any(np.isnan(self.cost_functions_coefficients)): 81 79 self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node') 82 if not n umpy.any(numpy.isnan(self.min_parameters)):80 if not np.any(np.isnan(self.min_parameters)): 83 81 self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node') 84 if not n umpy.any(numpy.isnan(self.max_parameters)):82 if not np.any(np.isnan(self.max_parameters)): 85 83 self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node') 86 84 return self … … 100 98 #maximum number of iteration in the optimization algorithm for 101 99 #each step 102 self.maxiter_per_step=20*n umpy.ones(self.nsteps)100 self.maxiter_per_step=20*np.ones(self.nsteps) 103 101 104 102 #the inversed parameter is updated as follows: … … 107 105 #inversed parameter (10^8 for B, 50 for drag) and can be decreased 108 106 #after the first iterations 109 self.gradient_scaling=50*n umpy.ones((self.nsteps,1))107 self.gradient_scaling=50*np.ones((self.nsteps,1)) 110 108 111 109 #several responses can be used: 112 self.cost_functions= 101110 self.cost_functions=[101,] 113 111 114 112 #step_threshold is used to speed up control method. When 115 113 #misfit(1)/misfit(0) < self.step_threshold, we go directly to 116 114 #the next step 117 self.step_threshold=.7*n umpy.ones(self.nsteps) #30 per cent decrement115 self.step_threshold=.7*np.ones(self.nsteps) #30 per cent decrement 118 116 119 117 #cost_function_threshold is a criteria to stop the control methods. … … 130 128 return md 131 129 132 num_controls=n umpy.size(md.inversion.control_parameters)133 num_costfunc=n umpy.size(md.inversion.cost_functions)130 num_controls=np.size(md.inversion.control_parameters) 131 num_costfunc=np.size(md.inversion.cost_functions) 134 132 135 133 md = checkfield(md,'fieldname','inversion.iscontrol','values',[0,1]) … … 146 144 147 145 #Only SSA, HO and FS are supported right now 148 if solution== StressbalanceSolutionEnum():146 if solution=='StressbalanceSolution': 149 147 if not (md.flowequation.isSSA or md.flowequation.isHO or md.flowequation.isFS or md.flowequation.isL1L2): 150 148 md.checkmessage("'inversion can only be performed for SSA, HO or FS ice flow models"); 151 149 152 if solution== BalancethicknessSolutionEnum():150 if solution=='BalancethicknessSolution': 153 151 md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 154 152 else: … … 158 156 return md 159 157 # }}} 160 def marshall(self, md,fid): # {{{158 def marshall(self,prefix,md,fid): # {{{ 161 159 162 yts= 365.0*24.0*3600.0160 yts=md.constants.yts 163 161 164 WriteData(fid,'enum',InversionTypeEnum(),'data',0,'format','Integer') 165 WriteData(fid,'object',self,'fieldname','iscontrol','format','Boolean') 166 WriteData(fid,'object',self,'fieldname','incomplete_adjoint','format','Boolean') 162 WriteData(fid,prefix,'name','md.inversion.type','data',0,'format','Integer') 163 WriteData(fid,prefix,'object',self,'fieldname','iscontrol','format','Boolean') 164 WriteData(fid,prefix,'object',self,'fieldname','incomplete_adjoint','format','Boolean') 165 WriteData(fid,prefix,'object',self,'fieldname','vel_obs','format','DoubleMat','mattype',1,'scale',1./yts) 167 166 if not self.iscontrol: 168 167 return 169 WriteData(fid, 'object',self,'fieldname','nsteps','format','Integer')170 WriteData(fid, 'object',self,'fieldname','maxiter_per_step','format','DoubleMat','mattype',3)171 WriteData(fid, 'object',self,'fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)172 WriteData(fid, 'object',self,'fieldname','gradient_scaling','format','DoubleMat','mattype',3)173 WriteData(fid, 'object',self,'fieldname','cost_function_threshold','format','Double')174 WriteData(fid, 'object',self,'fieldname','min_parameters','format','DoubleMat','mattype',3)175 WriteData(fid, 'object',self,'fieldname','max_parameters','format','DoubleMat','mattype',3)176 WriteData(fid, 'object',self,'fieldname','step_threshold','format','DoubleMat','mattype',3)177 WriteData(fid, 'object',self,'fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)178 WriteData(fid, 'object',self,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)179 WriteData(fid, 'object',self,'fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)180 WriteData(fid, 'object',self,'fieldname','thickness_obs','format','DoubleMat','mattype',1)181 WriteData(fid, 'object',self,'fieldname','surface_obs','format','DoubleMat','mattype',1)168 WriteData(fid,prefix,'object',self,'fieldname','nsteps','format','Integer') 169 WriteData(fid,prefix,'object',self,'fieldname','maxiter_per_step','format','DoubleMat','mattype',3) 170 WriteData(fid,prefix,'object',self,'fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1) 171 WriteData(fid,prefix,'object',self,'fieldname','gradient_scaling','format','DoubleMat','mattype',3) 172 WriteData(fid,prefix,'object',self,'fieldname','cost_function_threshold','format','Double') 173 WriteData(fid,prefix,'object',self,'fieldname','min_parameters','format','DoubleMat','mattype',3) 174 WriteData(fid,prefix,'object',self,'fieldname','max_parameters','format','DoubleMat','mattype',3) 175 WriteData(fid,prefix,'object',self,'fieldname','step_threshold','format','DoubleMat','mattype',3) 176 WriteData(fid,prefix,'object',self,'fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts) 177 WriteData(fid,prefix,'object',self,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts) 178 WriteData(fid,prefix,'object',self,'fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts) 179 WriteData(fid,prefix,'object',self,'fieldname','thickness_obs','format','DoubleMat','mattype',1) 180 WriteData(fid,prefix,'object',self,'fieldname','surface_obs','format','DoubleMat','mattype',1) 182 181 183 182 #process control parameters 184 183 num_control_parameters=len(self.control_parameters) 185 data=numpy.array([StringToEnum(control_parameter)[0] for control_parameter in self.control_parameters]).reshape(1,-1) 186 WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3) 187 WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer') 184 WriteData(fid,prefix,'object',self,'fieldname','control_parameters','format','StringArray') 185 WriteData(fid,prefix,'data',num_control_parameters,'name','md.inversion.num_control_parameters','format','Integer') 188 186 189 187 #process cost functions 190 num_cost_functions=n umpy.size(self.cost_functions)188 num_cost_functions=np.size(self.cost_functions) 191 189 data=marshallcostfunctions(self.cost_functions) 192 WriteData(fid, 'data',numpy.array(data).reshape(1,-1),'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)193 WriteData(fid, 'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')190 WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray') 191 WriteData(fid,prefix,'data',num_cost_functions,'name','md.inversion.num_cost_functions','format','Integer') 194 192 # }}} -
issm/trunk-jpl/src/py3/classes/linearbasalforcings.py
r19898 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *3 2 from checkfield import checkfield 4 3 from WriteData import WriteData 5 import numpy 4 import numpy as np 6 5 7 6 class linearbasalforcings(object): … … 52 51 def initialize(self,md): # {{{ 53 52 54 if n umpy.all(numpy.isnan(self.groundedice_melting_rate)):55 self.groundedice_melting_rate=n umpy.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)) 56 55 print(" no basalforcings.groundedice_melting_rate specified: values set as zero") 57 56 … … 68 67 def checkconsistency(self,md,solution,analyses): # {{{ 69 68 70 if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum()and not md.transient.ismasstransport):69 if 'MasstransportAnalysis' in analyses and not (solution=='TransientSolution' and not md.transient.ismasstransport): 71 70 md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1) 72 md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0 );73 md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<', md.basalforcings.upperwater_elevation);74 md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','< ',0);71 md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'singletimeseries',1) 72 md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','singletimeseries',1) 73 md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'singletimeseries',1) 75 74 76 if BalancethicknessAnalysisEnum()in analyses:75 if 'BalancethicknessAnalysis' in analyses: 77 76 md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 78 md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0 );79 md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<', md.basalforcings.upperwater_elevation);80 md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','< ',0);77 md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'singletimeseries',1) 78 md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','singletimeseries',1) 79 md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'singletimeseries',1) 81 80 82 if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum()and not md.transient.isthermal):81 if 'ThermalAnalysis' in analyses and not (solution=='TransientSolution' and not md.transient.isthermal): 83 82 md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1) 84 md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0 );85 md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<', md.basalforcings.upperwater_elevation);86 md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','< ',0);83 md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'singletimeseries',1) 84 md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','singletimeseries',1) 85 md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'singletimeseries',1) 87 86 md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'Inf',1,'timeseries',1,'>=',0) 88 87 89 88 return md 90 89 # }}} 91 def marshall(self, md,fid): # {{{90 def marshall(self,prefix,md,fid): # {{{ 92 91 93 yts= 365.0*24.0*3600.092 yts=md.constants.yts 94 93 95 floatingice_melting_rate = numpy.zeros((md.mesh.numberofvertices,1)) 96 pos=numpy.nonzero(md.geometry.base<=md.basalforcings.deepwater_elevation) 97 floatingice_melting_rate[pos]=md.basalforcings.deepwater_melting_rate 98 pos=numpy.nonzero(numpy.logical_and(md.geometry.base>md.basalforcings.deepwater_elevation,md.geometry.base<md.basalforcings.upperwater_elevation)) 99 floatingice_melting_rate[pos]=md.basalforcings.deepwater_melting_rate*(md.geometry.base[pos]-md.basalforcings.upperwater_elevation)/(md.basalforcings.deepwater_elevation-md.basalforcings.upperwater_elevation) 100 101 WriteData(fid,'enum',BasalforcingsEnum(),'data',LinearFloatingMeltRateEnum(),'format','Integer'); 102 WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','enum',BasalforcingsGroundediceMeltingRateEnum(),'format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1) 103 WriteData(fid,'data',floatingice_melting_rate,'enum',BasalforcingsFloatingiceMeltingRateEnum(),'format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1) 104 WriteData(fid,'object',self,'fieldname','geothermalflux','enum',BasalforcingsGeothermalfluxEnum(),'format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1) 105 WriteData(fid,'object',self,'fieldname','deepwater_melting_rate','enum',BasalforcingsDeepwaterMeltingRateEnum(),'format','Double','scale',1./yts) 106 WriteData(fid,'object',self,'fieldname','deepwater_elevation','enum',BasalforcingsDeepwaterElevationEnum(),'format','Double') 107 WriteData(fid,'object',self,'fieldname','upperwater_elevation','enum',BasalforcingsUpperwaterElevationEnum(),'format','Double') 94 WriteData(fid,prefix,'name','md.basalforcings.model','data',2,'format','Integer') 95 WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','name','md.basalforcings.groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 96 WriteData(fid,prefix,'object',self,'fieldname','geothermalflux','name','md.basalforcings.geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 97 WriteData(fid,prefix,'object',self,'fieldname','deepwater_melting_rate','format','DoubleMat','mattype',3,'timeserieslength',2,'name','md.basalforcings.deepwater_melting_rate','scale',1./yts,'yts',md.constants.yts) 98 WriteData(fid,prefix,'object',self,'fieldname','deepwater_elevation','format','DoubleMat','mattype',3,'name','md.basalforcings.deepwater_elevation','yts',md.constants.yts) 99 WriteData(fid,prefix,'object',self,'fieldname','upperwater_elevation','format','DoubleMat','mattype',3,'name','md.basalforcings.upperwater_elevation','yts',md.constants.yts) 108 100 # }}} -
issm/trunk-jpl/src/py3/classes/m1qn3inversion.py
r19898 r23670 1 import numpy 1 import numpy as np 2 2 from project3d import project3d 3 3 from fielddisplay import fielddisplay 4 from EnumDefinitions import *5 from StringToEnum import StringToEnum6 4 from checkfield import checkfield 7 5 from WriteData import WriteData … … 100 98 self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node') 101 99 self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node') 102 if not n umpy.any(numpy.isnan(self.cost_functions_coefficients)):100 if not np.any(np.isnan(self.cost_functions_coefficients)): 103 101 self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node') 104 if not n umpy.any(numpy.isnan(self.min_parameters)):102 if not np.any(np.isnan(self.min_parameters)): 105 103 self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node') 106 if not n umpy.any(numpy.isnan(self.max_parameters)):104 if not np.any(np.isnan(self.max_parameters)): 107 105 self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node') 108 106 return self … … 139 137 return md 140 138 141 num_controls=n umpy.size(md.inversion.control_parameters)142 num_costfunc=n umpy.size(md.inversion.cost_functions)139 num_controls=np.size(md.inversion.control_parameters) 140 num_costfunc=np.size(md.inversion.cost_functions) 143 141 144 142 md = checkfield(md,'fieldname','inversion.iscontrol','values',[0,1]) … … 155 153 md = checkfield(md,'fieldname','inversion.max_parameters','size',[md.mesh.numberofvertices,num_controls]) 156 154 157 if solution== BalancethicknessSolutionEnum():155 if solution=='BalancethicknessSolution': 158 156 md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 159 157 else: … … 163 161 return md 164 162 # }}} 165 def marshall(self, md,fid): # {{{163 def marshall(self,prefix,md,fid): # {{{ 166 164 167 yts= 365.0*24.0*3600.0165 yts=md.constants.yts 168 166 169 WriteData(fid, 'object',self,'class','inversion','fieldname','iscontrol','format','Boolean')170 WriteData(fid, 'enum',InversionTypeEnum(),'data',2,'format','Integer')167 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean') 168 WriteData(fid,prefix,'name','md.inversion.type','data',2,'format','Integer') 171 169 if not self.iscontrol: 172 170 return 173 WriteData(fid, 'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean')174 WriteData(fid, 'object',self,'class','inversion','fieldname','control_scaling_factors','format','DoubleMat','mattype',3)175 WriteData(fid, 'object',self,'class','inversion','fieldname','maxsteps','format','Integer')176 WriteData(fid, 'object',self,'class','inversion','fieldname','maxiter','format','Integer')177 WriteData(fid, 'object',self,'class','inversion','fieldname','dxmin','format','Double')178 WriteData(fid, 'object',self,'class','inversion','fieldname','gttol','format','Double')179 WriteData(fid, 'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)180 WriteData(fid, 'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3)181 WriteData(fid, 'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3)182 WriteData(fid, 'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)183 WriteData(fid, 'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)184 WriteData(fid, 'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)185 WriteData(fid, 'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1)171 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean') 172 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','control_scaling_factors','format','DoubleMat','mattype',3) 173 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxsteps','format','Integer') 174 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxiter','format','Integer') 175 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','dxmin','format','Double') 176 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gttol','format','Double') 177 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1) 178 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3) 179 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3) 180 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts) 181 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts) 182 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts) 183 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1) 186 184 187 185 #process control parameters 188 186 num_control_parameters=len(self.control_parameters) 189 data=numpy.array([StringToEnum(control_parameter)[0] for control_parameter in self.control_parameters]).reshape(1,-1) 190 WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3) 191 WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer') 187 WriteData(fid,prefix,'object',self,'fieldname','control_parameters','format','StringArray') 188 WriteData(fid,prefix,'data',num_control_parameters,'name','md.inversion.num_control_parameters','format','Integer') 192 189 193 190 #process cost functions 194 num_cost_functions=n umpy.size(self.cost_functions)191 num_cost_functions=np.size(self.cost_functions) 195 192 data=marshallcostfunctions(self.cost_functions) 196 WriteData(fid, 'data',numpy.array(data).reshape(1,-1),'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)197 WriteData(fid, 'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')193 WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray') 194 WriteData(fid,prefix,'data',num_cost_functions,'name','md.inversion.num_cost_functions','format','Integer') 198 195 # }}} -
issm/trunk-jpl/src/py3/classes/mask.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from fielddisplay import fielddisplay 3 3 from project3d import project3d 4 from EnumDefinitions import *5 4 from checkfield import checkfield 6 5 from WriteData import WriteData … … 39 38 #}}} 40 39 def checkconsistency(self,md,solution,analyses): # {{{ 40 if(solution=='LoveSolution'): 41 return 41 42 42 43 md = checkfield(md,'fieldname','mask.ice_levelset' ,'size',[md.mesh.numberofvertices]) 43 isice=n umpy.array(md.mask.ice_levelset<=0,int)44 if n umpy.sum(isice)==0:44 isice=np.array(md.mask.ice_levelset<=0,int) 45 if np.sum(isice)==0: 45 46 raise TypeError("no ice present in the domain") 46 47 icefront=numpy.sum(md.mask.ice_levelset[md.mesh.elements-1]==0,axis=1)48 if (max(icefront)==3 and m.strcmp(md.mesh.elementtype(),'Tria')) or (max(icefront==6) and m.strcmp(md.mesh.elementtype(),'Penta')):49 raise TypeError("At least one element has all nodes on ice front, change md.mask.ice_levelset to fix it")50 47 51 48 return md 52 49 # }}} 53 def marshall(self,md,fid): # {{{ 54 WriteData(fid,'object',self,'fieldname','groundedice_levelset','format','DoubleMat','mattype',1) 55 WriteData(fid,'object',self,'fieldname','ice_levelset','format','DoubleMat','mattype',1) 56 57 # get mask of vertices of elements with ice 58 isice=numpy.array(md.mask.ice_levelset<0.,int) 59 vlist = numpy.zeros((md.mesh.numberofvertices,1), dtype=int) 60 pos=numpy.nonzero(numpy.sum(isice[md.mesh.elements-1],axis=1))[0] 61 vlist[md.mesh.elements[pos,:]-1]=1 62 WriteData(fid,'data',vlist,'enum',IceMaskNodeActivationEnum(),'format','DoubleMat','mattype',1); 50 def marshall(self,prefix,md,fid): # {{{ 51 WriteData(fid,prefix,'object',self,'fieldname','groundedice_levelset','format','DoubleMat','mattype',1) 52 WriteData(fid,prefix,'object',self,'fieldname','ice_levelset','format','DoubleMat','mattype',1) 63 53 # }}} -
issm/trunk-jpl/src/py3/classes/massfluxatgate.py
r19895 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *3 2 from pairoptions import pairoptions 4 3 from checkfield import checkfield … … 15 14 """ 16 15 17 def __init__(self,* *kwargs): # {{{16 def __init__(self,*args): # {{{ 18 17 19 18 self.name = '' 20 self.definition enum = 019 self.definitionstring = '' 21 20 self.profilename = '' 22 21 self.segments = float('NaN') … … 26 25 27 26 #use provided options to change fields 28 options=pairoptions(* *kwargs)27 options=pairoptions(*args) 29 28 30 29 #OK get other fields … … 36 35 string=" Massfluxatgate:" 37 36 string="%s\n%s"%(string,fielddisplay(self,'name','identifier for this massfluxatgate response')) 38 string="%s\n%s"%(string,fielddisplay(self,'definition enum','enum that identifies this output definition uniquely, from Outputdefinition[1-10]Enum'))37 string="%s\n%s"%(string,fielddisplay(self,'definitionstring','string that identifies this output definition uniquely, from Outputdefinition[1-100]')) 39 38 string="%s\n%s"%(string,fielddisplay(self,'profilename','name of file (shapefile or argus file) defining a profile (or gate)')) 40 39 return string 41 40 #}}} 41 def extrude(self,md): # {{{ 42 return self 43 #}}} 42 44 def setdefaultparameters(self): # {{{ 43 45 return self … … 50 52 if not isinstance(self.profilename, str): 51 53 raise RuntimeError("massfluxatgate error message: 'profilename' field should be a string!") 52 53 md = checkfield(md,'field',self.definitionenum,'values',[Outputdefinition1Enum(),Outputdefinition2Enum(),Outputdefinition3Enum(),Outputdefinition4Enum(),Outputdefinition5Enum(),Outputdefinition6Enum(),Outputdefinition7Enum(),Outputdefinition8Enum(),Outputdefinition9Enum(),Outputdefinition10Enum()]) 54 55 OutputdefinitionStringArray=[] 56 for i in range(1,100): 57 x='Outputdefinition'+str(i) 58 OutputdefinitionStringArray.append(x) 59 60 md = checkfield(md,'field',self.definitionstring,'values',OutputdefinitionStringArray) 54 61 55 62 #check the profilename points to a file!: … … 59 66 return md 60 67 # }}} 61 def marshall(self, md,fid): # {{{68 def marshall(self,prefix,md,fid): # {{{ 62 69 63 70 #before marshalling, we need to create the segments out of the profilename: … … 65 72 66 73 #ok, marshall name and segments: 67 WriteData(fid, 'object',self,'fieldname','name','format','String')68 WriteData(fid, 'object',self,'fieldname','definitionenum','format','Integer')69 WriteData(fid, 'object',self,'fieldname','segments','format','DoubleMat','mattype',1)74 WriteData(fid,prefix,'data',self.name,'name','md.massfluxatgate.name','format','String'); 75 WriteData(fid,prefix,'data',self.definitionstring,'name','md.massfluxatgate.definitionstring','format','String'); 76 WriteData(fid,prefix,'data',self.segments,'name','md.massfluxatgate.segments','format','DoubleMat','mattype',1); 70 77 71 78 # }}} -
issm/trunk-jpl/src/py3/classes/masstransport.py
r19903 r23670 1 1 from fielddisplay import fielddisplay 2 2 from project3d import project3d 3 from EnumDefinitions import *4 from StringToEnum import StringToEnum5 3 from checkfield import checkfield 6 4 from WriteData import WriteData … … 69 67 70 68 #Early return 71 if ( MasstransportAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum()and not md.transient.ismasstransport):69 if ('MasstransportAnalysis' not in analyses) or (solution=='TransientSolution' and not md.transient.ismasstransport): 72 70 return md 73 71 … … 81 79 return md 82 80 # }}} 83 def marshall(self, md,fid): # {{{81 def marshall(self,prefix,md,fid): # {{{ 84 82 85 yts= 365.*24.*3600.83 yts=md.constants.yts 86 84 87 WriteData(fid, 'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)88 WriteData(fid, 'object',self,'fieldname','isfreesurface','format','Boolean')89 WriteData(fid, 'object',self,'fieldname','min_thickness','format','Double')90 WriteData(fid, 'data',StringToEnum(self.hydrostatic_adjustment)[0],'format','Integer','enum',MasstransportHydrostaticAdjustmentEnum())91 WriteData(fid, 'object',self,'fieldname','stabilization','format','Integer')92 WriteData(fid, 'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3)93 WriteData(fid, 'object',self,'fieldname','penalty_factor','format','Double')85 WriteData(fid,prefix,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 86 WriteData(fid,prefix,'object',self,'fieldname','isfreesurface','format','Boolean') 87 WriteData(fid,prefix,'object',self,'fieldname','min_thickness','format','Double') 88 WriteData(fid,prefix,'data',self.hydrostatic_adjustment,'format','String','name','md.masstransport.hydrostatic_adjustment') 89 WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Integer') 90 WriteData(fid,prefix,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3) 91 WriteData(fid,prefix,'object',self,'fieldname','penalty_factor','format','Double') 94 92 95 93 #process requested outputs … … 99 97 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 100 98 outputs =outputscopy 101 WriteData(fid, 'data',outputs,'enum',MasstransportRequestedOutputsEnum(),'format','StringArray')99 WriteData(fid,prefix,'data',outputs,'name','md.masstransport.requested_outputs','format','StringArray') 102 100 # }}} -
issm/trunk-jpl/src/py3/classes/matdamageice.py
r19895 r23670 1 1 from fielddisplay import fielddisplay 2 2 from project3d import project3d 3 from EnumDefinitions import MaterialsEnum, MatdamageiceEnum, MaterialsRheologyLawEnum, MaterialsRhoSeawaterEnum4 from StringToEnum import StringToEnum5 3 from checkfield import checkfield 6 4 from WriteData import WriteData … … 31 29 self.rheology_law = '' 32 30 33 #gia :31 #giaivins: 34 32 self.lithosphere_shear_modulus = 0. 35 33 self.lithosphere_density = 0. 36 34 self.mantle_shear_modulus = 0. 37 35 self.mantle_density = 0. 36 37 #SLR 38 self.earth_density= 5512; # average density of the Earth, (kg/m^3) 39 38 40 39 41 self.setdefaultparameters() … … 54 56 string="%s\n%s"%(string,fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]")) 55 57 string="%s\n%s"%(string,fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]")) 56 string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa /s^(1/n)]"))58 string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa s^(1/n)]")) 57 59 string="%s\n%s"%(string,fielddisplay(self,"rheology_n","Glen's flow law exponent")) 58 string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', ' Cuffey', 'Paterson', 'Arrhenius' or 'LliboutryDuval'"))60 string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'BuddJacka', 'Cuffey', 'CuffeyTemperate', 'Paterson', 'Arrhenius' or 'LliboutryDuval'")) 59 61 string="%s\n%s"%(string,fielddisplay(self,"lithosphere_shear_modulus","Lithosphere shear modulus [Pa]")) 60 62 string="%s\n%s"%(string,fielddisplay(self,"lithosphere_density","Lithosphere density [g/cm^-3]")) 61 63 string="%s\n%s"%(string,fielddisplay(self,"mantle_shear_modulus","Mantle shear modulus [Pa]")) 62 64 string="%s\n%s"%(string,fielddisplay(self,"mantle_density","Mantle density [g/cm^-3]")) 65 string="%s\n%s"%(string,fielddisplay(self,"earth_density","Mantle density [kg/m^-3]")) 66 63 67 64 68 return string … … 115 119 self.mantle_shear_modulus = 1.45*10**11 # (Pa) 116 120 self.mantle_density = 3.34 # (g/cm^-3) 121 122 #SLR 123 self.earth_density= 5512; #average density of the Earth, (kg/m^3) 124 117 125 118 126 return self … … 125 133 md = checkfield(md,'fieldname','materials.rheology_B','>',0,'size',[md.mesh.numberofvertices]) 126 134 md = checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements]) 127 md = checkfield(md,'fieldname','materials.rheology_law','values',['None', 'Cuffey','Paterson','Arrhenius','LliboutryDuval'])135 md = checkfield(md,'fieldname','materials.rheology_law','values',['None', 'BuddJacka', 'Cuffey', 'CuffeyTemperate', 'Paterson','Arrhenius','LliboutryDuval']) 128 136 md = checkfield(md,'fieldname','materials.lithosphere_shear_modulus','>',0,'numel',[1]); 129 137 md = checkfield(md,'fieldname','materials.lithosphere_density','>',0,'numel',[1]); 130 138 md = checkfield(md,'fieldname','materials.mantle_shear_modulus','>',0,'numel',[1]); 131 139 md = checkfield(md,'fieldname','materials.mantle_density','>',0,'numel',[1]); 140 md = checkfield(md,'fieldname','materials.earth_density','>',0,'numel',[1]); 141 132 142 return md 133 143 # }}} 134 def marshall(self, md,fid): # {{{135 WriteData(fid, 'enum',MaterialsEnum(),'data',MatdamageiceEnum(),'format','Integer');136 WriteData(fid, 'object',self,'class','materials','fieldname','rho_ice','format','Double')137 WriteData(fid, 'object',self,'class','materials','fieldname','rho_water','enum',MaterialsRhoSeawaterEnum(),'format','Double')138 WriteData(fid, 'object',self,'class','materials','fieldname','rho_freshwater','format','Double')139 WriteData(fid, 'object',self,'class','materials','fieldname','mu_water','format','Double')140 WriteData(fid, 'object',self,'class','materials','fieldname','heatcapacity','format','Double')141 WriteData(fid, 'object',self,'class','materials','fieldname','latentheat','format','Double')142 WriteData(fid, 'object',self,'class','materials','fieldname','thermalconductivity','format','Double')143 WriteData(fid, 'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double')144 WriteData(fid, 'object',self,'class','materials','fieldname','meltingpoint','format','Double')145 WriteData(fid, 'object',self,'class','materials','fieldname','beta','format','Double')146 WriteData(fid, 'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')147 WriteData(fid, 'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')148 WriteData(fid, 'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1)149 WriteData(fid, 'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)150 WriteData(fid, 'data',StringToEnum(self.rheology_law)[0],'enum',MaterialsRheologyLawEnum(),'format','Integer')144 def marshall(self,prefix,md,fid): # {{{ 145 WriteData(fid,prefix,'name','md.materials.type','data',1,'format','Integer'); 146 WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_ice','format','Double') 147 WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_water','format','Double') 148 WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_freshwater','format','Double') 149 WriteData(fid,prefix,'object',self,'class','materials','fieldname','mu_water','format','Double') 150 WriteData(fid,prefix,'object',self,'class','materials','fieldname','heatcapacity','format','Double') 151 WriteData(fid,prefix,'object',self,'class','materials','fieldname','latentheat','format','Double') 152 WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermalconductivity','format','Double') 153 WriteData(fid,prefix,'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double') 154 WriteData(fid,prefix,'object',self,'class','materials','fieldname','meltingpoint','format','Double') 155 WriteData(fid,prefix,'object',self,'class','materials','fieldname','beta','format','Double') 156 WriteData(fid,prefix,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double') 157 WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double') 158 WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1) 159 WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2) 160 WriteData(fid,prefix,'data',self.rheology_law,'name','md.materials.rheology_law','format','String') 151 161 152 WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double'); 153 WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.); 154 WriteData(fid,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double'); 155 WriteData(fid,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.); 162 WriteData(fid,prefix,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double'); 163 WriteData(fid,prefix,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.); 164 WriteData(fid,prefix,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double'); 165 WriteData(fid,prefix,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.); 166 WriteData(fid,prefix,'object',self,'class','materials','fieldname','earth_density','format','Double'); 167 156 168 # }}} -
issm/trunk-jpl/src/py3/classes/matice.py
r19898 r23670 1 1 from fielddisplay import fielddisplay 2 2 from project3d import project3d 3 from EnumDefinitions import *4 from StringToEnum import StringToEnum5 3 from checkfield import checkfield 6 4 from WriteData import WriteData … … 31 29 self.rheology_law = '' 32 30 33 #gia :31 #giaivins: 34 32 self.lithosphere_shear_modulus = 0. 35 33 self.lithosphere_density = 0. 36 34 self.mantle_shear_modulus = 0. 37 self.mantle_density = 0. 35 self.mantle_density = 0. 36 37 #SLR 38 self.earth_density= 5512; 39 40 38 41 39 42 self.setdefaultparameters() … … 54 57 string="%s\n%s"%(string,fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]")) 55 58 string="%s\n%s"%(string,fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]")) 56 string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa /s^(1/n)]"))59 string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa s^(1/n)]")) 57 60 string="%s\n%s"%(string,fielddisplay(self,"rheology_n","Glen's flow law exponent")) 58 string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', ' Cuffey', 'Paterson', 'Arrhenius' or 'LliboutryDuval'"))61 string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'BuddJacka', 'Cuffey', 'CuffeyTemperate', 'Paterson', 'Arrhenius' or 'LliboutryDuval'")) 59 62 string="%s\n%s"%(string,fielddisplay(self,"lithosphere_shear_modulus","Lithosphere shear modulus [Pa]")) 60 63 string="%s\n%s"%(string,fielddisplay(self,"lithosphere_density","Lithosphere density [g/cm^-3]")) 61 64 string="%s\n%s"%(string,fielddisplay(self,"mantle_shear_modulus","Mantle shear modulus [Pa]")) 62 65 string="%s\n%s"%(string,fielddisplay(self,"mantle_density","Mantle density [g/cm^-3]")) 66 string="%s\n%s"%(string,fielddisplay(self,"earth_density","Mantle density [kg/m^-3]")) 67 63 68 64 69 return string … … 115 120 self.mantle_shear_modulus = 1.45*10**11 # (Pa) 116 121 self.mantle_density = 3.34 # (g/cm^-3) 122 123 #SLR 124 self.earth_density= 5512; # average density of the Earth, (kg/m^3) 125 117 126 118 127 return self … … 125 134 md = checkfield(md,'fieldname','materials.rheology_B','>',0,'timeseries',1,'NaN',1,'Inf',1) 126 135 md = checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements]) 127 md = checkfield(md,'fieldname','materials.rheology_law','values',['None',' Cuffey','Paterson','Arrhenius','LliboutryDuval'])136 md = checkfield(md,'fieldname','materials.rheology_law','values',['None','BuddJacka','Cuffey','CuffeyTemperate','Paterson','Arrhenius','LliboutryDuval']) 128 137 md = checkfield(md,'fieldname','materials.lithosphere_shear_modulus','>',0,'numel',[1]); 129 138 md = checkfield(md,'fieldname','materials.lithosphere_density','>',0,'numel',[1]); 130 139 md = checkfield(md,'fieldname','materials.mantle_shear_modulus','>',0,'numel',[1]); 131 140 md = checkfield(md,'fieldname','materials.mantle_density','>',0,'numel',[1]); 141 md = checkfield(md,'fieldname','materials.earth_density','>',0,'numel',[1]); 142 132 143 return md 133 144 # }}} 134 def marshall(self,md,fid): # {{{ 135 WriteData(fid,'enum',MaterialsEnum(),'data',MaticeEnum(),'format','Integer'); 136 WriteData(fid,'object',self,'class','materials','fieldname','rho_ice','format','Double') 137 WriteData(fid,'object',self,'class','materials','fieldname','rho_water','enum',MaterialsRhoSeawaterEnum(),'format','Double') 138 WriteData(fid,'object',self,'class','materials','fieldname','rho_freshwater','format','Double') 139 WriteData(fid,'object',self,'class','materials','fieldname','mu_water','format','Double') 140 WriteData(fid,'object',self,'class','materials','fieldname','heatcapacity','format','Double') 141 WriteData(fid,'object',self,'class','materials','fieldname','latentheat','format','Double') 142 WriteData(fid,'object',self,'class','materials','fieldname','thermalconductivity','format','Double') 143 WriteData(fid,'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double') 144 WriteData(fid,'object',self,'class','materials','fieldname','meltingpoint','format','Double') 145 WriteData(fid,'object',self,'class','materials','fieldname','beta','format','Double') 146 WriteData(fid,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double') 147 WriteData(fid,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double') 148 WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1) 149 WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1) 150 WriteData(fid,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2) 151 WriteData(fid,'data',StringToEnum(self.rheology_law)[0],'enum',MaterialsRheologyLawEnum(),'format','Integer') 145 def marshall(self,prefix,md,fid): # {{{ 146 WriteData(fid,prefix,'name','md.materials.type','data',3,'format','Integer'); 147 WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_ice','format','Double') 148 WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_water','format','Double') 149 WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_freshwater','format','Double') 150 WriteData(fid,prefix,'object',self,'class','materials','fieldname','mu_water','format','Double') 151 WriteData(fid,prefix,'object',self,'class','materials','fieldname','heatcapacity','format','Double') 152 WriteData(fid,prefix,'object',self,'class','materials','fieldname','latentheat','format','Double') 153 WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermalconductivity','format','Double') 154 WriteData(fid,prefix,'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double') 155 WriteData(fid,prefix,'object',self,'class','materials','fieldname','meltingpoint','format','Double') 156 WriteData(fid,prefix,'object',self,'class','materials','fieldname','beta','format','Double') 157 WriteData(fid,prefix,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double') 158 WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double') 159 WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 160 WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2) 161 WriteData(fid,prefix,'data',self.rheology_law,'name','md.materials.rheology_law','format','String') 152 162 153 WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double'); 154 WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.); 155 WriteData(fid,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double'); 156 WriteData(fid,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.); 163 WriteData(fid,prefix,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double'); 164 WriteData(fid,prefix,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.); 165 WriteData(fid,prefix,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double'); 166 WriteData(fid,prefix,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.); 167 WriteData(fid,prefix,'object',self,'class','materials','fieldname','earth_density','format','Double'); 168 157 169 # }}} -
issm/trunk-jpl/src/py3/classes/mesh2d.py
r19898 r23670 1 import numpy 1 import numpy as np 2 2 from fielddisplay import fielddisplay 3 3 from checkfield import checkfield 4 import MatlabFuncs as m 4 5 from WriteData import WriteData 5 from EnumDefinitions import *6 import MatlabFuncs as m7 6 8 7 class mesh2d(object): … … 25 24 self.long = float('NaN'); 26 25 self.epsg = 0; 26 self.scale_factor = float('NaN'); 27 27 28 28 self.vertexonboundary = float('NaN'); … … 57 57 string="%s\n%s"%(string,fielddisplay(self,"segments","edges on domain boundary (vertex1 vertex2 element)")) 58 58 string="%s\n%s"%(string,fielddisplay(self,"segmentmarkers","number associated to each segment")) 59 string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of vertices connected to vertex_i"))60 string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of vertices connectedto element_i"))59 string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of elements connected to vertex_i")) 60 string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of elements adjacent to element_i")) 61 61 string="%s\n%s"%(string,fielddisplay(self,"average_vertex_connectivity","average number of vertices connected to one vertex")) 62 62 … … 69 69 string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]")) 70 70 string="%s\n%s"%(string,fielddisplay(self,"epsg","EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)")) 71 string="%s\n%s"%(string,fielddisplay(self,"scale_factor","Projection correction for volume, area, etc. computation")) 71 72 return string 72 73 #}}} … … 83 84 #}}} 84 85 def checkconsistency(self,md,solution,analyses): # {{{ 86 if(solution=='LoveSolution'): 87 return 85 88 86 89 md = checkfield(md,'fieldname','mesh.x','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 87 90 md = checkfield(md,'fieldname','mesh.y','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 88 md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',n umpy.arange(1,md.mesh.numberofvertices+1))91 md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',np.arange(1,md.mesh.numberofvertices+1)) 89 92 md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements,3]) 90 # if numpy.any(numpy.logical_not(m.ismember(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))): 91 if any(numpy.logical_not(m.ismember(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))): 92 [x for x in A if not x in B] 93 if np.any(np.logical_not(m.ismember(np.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))): 93 94 md.checkmessage("orphan nodes have been found. Check the mesh outline") 94 95 md = checkfield(md,'fieldname','mesh.numberofelements','>',0) 95 96 md = checkfield(md,'fieldname','mesh.numberofvertices','>',0) 96 97 md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',9,'message',"'mesh.average_vertex_connectivity' should be at least 9 in 2d") 97 if solution==ThermalSolutionEnum(): 98 md = checkfield(md,'fieldname','mesh.segments','NaN',1,'Inf',1,'>',0,'size',[np.nan,3]); 99 if(np.size(self.scale_factor)>1): 100 md = checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 101 102 if solution=='ThermalSolution': 98 103 md.checkmessage("thermal not supported for 2d mesh") 99 104 … … 109 114 return "Tria" 110 115 #}}} 111 def marshall(self,md,fid): # {{{ 112 WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum("Domain"+self.domaintype())[0],'format','Integer'); 113 WriteData(fid,'enum',DomainDimensionEnum(),'data',self.dimension(),'format','Integer'); 114 WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(self.elementtype())[0],'format','Integer'); 115 WriteData(fid,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1) 116 WriteData(fid,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1) 117 WriteData(fid,'enum',MeshZEnum(),'data',numpy.zeros(self.numberofvertices),'format','DoubleMat','mattype',1); 118 WriteData(fid,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2) 119 WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements','format','Integer') 120 WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer') 121 WriteData(fid,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer') 116 def marshall(self,prefix,md,fid): # {{{ 117 WriteData(fid,prefix,'name','md.mesh.domain_type','data',"Domain"+self.domaintype(),'format','String'); 118 WriteData(fid,prefix,'name','md.mesh.domain_dimension','data',self.dimension(),'format','Integer'); 119 WriteData(fid,prefix,'name','md.mesh.elementtype','data',self.elementtype(),'format','String'); 120 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1) 121 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1) 122 WriteData(fid,prefix,'name','md.mesh.z','data',np.zeros(self.numberofvertices),'format','DoubleMat','mattype',1); 123 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2) 124 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofelements','format','Integer') 125 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer') 126 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer') 127 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','vertexonboundary','format','DoubleMat','mattype',1) 128 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','segments','format','DoubleMat','mattype',3) 129 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1) 130 if md.transient.isoceancoupling: 131 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','lat','format','DoubleMat','mattype',1) 132 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','long','format','DoubleMat','mattype',1) 122 133 # }}} -
issm/trunk-jpl/src/py3/classes/mesh3dprisms.py
r19898 r23670 1 import numpy 1 import numpy as np 2 2 from fielddisplay import fielddisplay 3 from EnumDefinitions import *4 3 from checkfield import * 5 4 import MatlabFuncs as m … … 26 25 self.long = float('NaN'); 27 26 self.epsg = 0; 27 self.scale_factor = float('NaN'); 28 28 29 29 self.vertexonbase = float('NaN'); … … 74 74 string="%s\n%s"%(string,fielddisplay(self,"vertexonbase","lower vertices flags list")) 75 75 string="%s\n%s"%(string,fielddisplay(self,"vertexonsurface","upper vertices flags list")) 76 string="%s\n%s"%(string,fielddisplay(self,"uppervertex","upper vertex list ( -1for vertex on the upper surface)"))77 string="%s\n%s"%(string,fielddisplay(self,"upperelements","upper element list ( -1for element on the upper layer)"))78 string="%s\n%s"%(string,fielddisplay(self,"lowervertex","lower vertex list ( -1for vertex on the lower surface)"))79 string="%s\n%s"%(string,fielddisplay(self,"lowerelements","lower element list ( -1for element on the lower layer)"))76 string="%s\n%s"%(string,fielddisplay(self,"uppervertex","upper vertex list (NaN for vertex on the upper surface)")) 77 string="%s\n%s"%(string,fielddisplay(self,"upperelements","upper element list (NaN for element on the upper layer)")) 78 string="%s\n%s"%(string,fielddisplay(self,"lowervertex","lower vertex list (NaN for vertex on the lower surface)")) 79 string="%s\n%s"%(string,fielddisplay(self,"lowerelements","lower element list (NaN for element on the lower layer)")) 80 80 string="%s\n%s"%(string,fielddisplay(self,"vertexonboundary","vertices on the boundary of the domain flag list")) 81 string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of vertices connected to vertex_i"))82 string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of vertices connectedto element_i"))81 string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of elements connected to vertex_i")) 82 string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of elements adjacent to element_i")) 83 83 string="%s\n%s"%(string,fielddisplay(self,"average_vertex_connectivity","average number of vertices connected to one vertex")) 84 84 … … 91 91 string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]")) 92 92 string="%s\n%s"%(string,fielddisplay(self,"epsg","EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)")) 93 string="%s\n%s"%(string,fielddisplay(self,"scale_factor","Projection correction for volume, area, etc. computation")) 93 94 return string 94 95 #}}} … … 109 110 md = checkfield(md,'fieldname','mesh.y','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 110 111 md = checkfield(md,'fieldname','mesh.z','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 111 md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',n umpy.arange(1,md.mesh.numberofvertices+1))112 md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',np.arange(1,md.mesh.numberofvertices+1)) 112 113 md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements,6]) 113 if n umpy.any(numpy.logical_not(m.ismember(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):114 if np.any(np.logical_not(m.ismember(np.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))): 114 115 md.checkmessage("orphan nodes have been found. Check the mesh3dprisms outline") 115 116 md = checkfield(md,'fieldname','mesh.numberoflayers','>=',0) … … 119 120 md = checkfield(md,'fieldname','mesh.vertexonsurface','size',[md.mesh.numberofvertices],'values',[0,1]) 120 121 md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',24,'message',"'mesh.average_vertex_connectivity' should be at least 24 in 3d") 122 if(np.size(self.scale_factor)>1): 123 md = checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) 121 124 122 125 return md … … 131 134 return "Penta" 132 135 #}}} 133 def marshall(self,md,fid): # {{{ 134 WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum("Domain"+self.domaintype())[0],'format','Integer'); 135 WriteData(fid,'enum',DomainDimensionEnum(),'data',self.dimension(),'format','Integer'); 136 WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(self.elementtype())[0],'format','Integer'); 137 WriteData(fid,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1) 138 WriteData(fid,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1) 139 WriteData(fid,'object',self,'class','mesh','fieldname','z','format','DoubleMat','mattype',1) 140 WriteData(fid,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2) 141 WriteData(fid,'object',self,'class','mesh','fieldname','numberoflayers','format','Integer') 142 WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements','format','Integer') 143 WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer') 144 WriteData(fid,'object',self,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1) 145 WriteData(fid,'object',self,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1) 146 WriteData(fid,'object',self,'class','mesh','fieldname','lowerelements','format','DoubleMat','mattype',2) 147 WriteData(fid,'object',self,'class','mesh','fieldname','upperelements','format','DoubleMat','mattype',2) 148 WriteData(fid,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer') 149 WriteData(fid,'object',self,'class','mesh','fieldname','elements2d','format','DoubleMat','mattype',3) 150 WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices2d','format','Integer') 151 WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements2d','format','Integer') 136 def marshall(self,prefix,md,fid): # {{{ 137 WriteData(fid,prefix,'name','md.mesh.domain_type','data',"Domain"+self.domaintype(),'format','String'); 138 WriteData(fid,prefix,'name','md.mesh.domain_dimension','data',self.dimension(),'format','Integer'); 139 WriteData(fid,prefix,'name','md.mesh.elementtype','data',self.elementtype(),'format','String'); 140 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1) 141 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1) 142 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','z','format','DoubleMat','mattype',1) 143 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2) 144 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberoflayers','format','Integer') 145 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofelements','format','Integer') 146 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer') 147 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1) 148 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1) 149 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','lowerelements','format','DoubleMat','mattype',2) 150 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','upperelements','format','DoubleMat','mattype',2) 151 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer') 152 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','elements2d','format','DoubleMat','mattype',3) 153 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofvertices2d','format','Integer') 154 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofelements2d','format','Integer') 155 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1) 156 if md.transient.isoceancoupling: 157 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','lat','format','DoubleMat','mattype',1) 158 WriteData(fid,prefix,'object',self,'class','mesh','fieldname','long','format','DoubleMat','mattype',1) 152 159 # }}} -
issm/trunk-jpl/src/py3/classes/miscellaneous.py
r19895 r23670 1 1 from collections import OrderedDict 2 2 from fielddisplay import fielddisplay 3 from EnumDefinitions import *4 3 from checkfield import checkfield 5 4 from WriteData import WriteData … … 37 36 return md 38 37 # }}} 39 def marshall(self, md,fid): # {{{40 WriteData(fid, 'object',self,'fieldname','name','format','String')38 def marshall(self,prefix,md,fid): # {{{ 39 WriteData(fid,prefix,'object',self,'fieldname','name','format','String'); 41 40 # }}} -
issm/trunk-jpl/src/py3/classes/mismipbasalforcings.py
r19898 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *2 from project3d import project3d 3 3 from checkfield import checkfield 4 4 from WriteData import WriteData 5 import numpy 5 import numpy as np 6 6 7 7 class mismipbasalforcings(object): 8 """ 8 """ 9 9 MISMIP Basal Forcings class definition 10 10 … … 13 13 """ 14 14 15 def __init__(self ,md): # {{{15 def __init__(self): # {{{ 16 16 17 17 self.groundedice_melting_rate = float('NaN') … … 20 20 self.upperdepth_melt = float('NaN') 21 21 self.geothermalflux = float('NaN') 22 23 if numpy.all(numpy.isnan(self.groundedice_melting_rate)):24 self.groundedice_melting_rate=numpy.zeros(md.mesh.numberofvertices)25 print(' no basalforcings.groundedice_melting_rate specified: values set as zero')26 22 27 23 self.setdefaultparameters() … … 35 31 string="%s\n%s"%(string,fielddisplay(self,"upperdepth_melt","Depth above which melt rate is zero [m]")) 36 32 string="%s\n%s"%(string,fielddisplay(self,"geothermalflux","Geothermal heat flux [W/m^2]")) 37 38 33 return string 39 34 #}}} 40 35 def extrude(self,md): # {{{ 41 self.coefficient=project3d(md,'vector',self.coefficient,'type','node','layer',1) 42 self.p=project3d(md,'vector',self.p,'type','element') 43 self.q=project3d(md,'vector',self.q,'type','element') 36 self.groundedice_melting_rate=project3d(md,'vector',self.groundedice_melting_rate,'type','node','layer',1) 37 self.geothermalflux=project3d(md,'vector',self.geothermalflux,'type','node','layer',1) #bedrock only gets geothermal flux 44 38 return self 45 39 #}}} 40 def initialize(self,md): # {{{ 41 if np.all(np.isnan(self.groundedice_melting_rate)): 42 self.groundedice_melting_rate=np.zeros((md.mesh.numberofvertices)) 43 print(' no basalforcings.groundedice_melting_rate specified: values set as zero') 44 if np.all(np.isnan(self.geothermalflux)): 45 self.geothermalflux=np.zeros((md.mesh.numberofvertices)) 46 print(" no basalforcings.geothermalflux specified: values set as zero") 47 return self 48 #}}} 46 49 def setdefaultparameters(self): # {{{ 47 48 50 # default values for melting parameterization 49 51 self.meltrate_factor = 0.2 50 52 self.threshold_thickness = 75. 51 53 self.upperdepth_melt = -100. 52 53 54 return self 54 55 #}}} … … 56 57 57 58 #Early return 58 if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum()and md.transient.ismasstransport==0):59 if 'MasstransportAnalysis' in analyses and not (solution=='TransientSolution' and md.transient.ismasstransport==0): 59 60 60 61 md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1) … … 63 64 md = checkfield(md,'fieldname','basalforcings.upperdepth_melt','<=',0,'numel',[1]) 64 65 65 if BalancethicknessAnalysisEnum()in analyses:66 if 'BalancethicknessAnalysis' in analyses: 66 67 67 68 md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]) … … 70 71 md = checkfield(md,'fieldname','basalforcings.upperdepth_melt','<=',0,'numel',[1]) 71 72 72 if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum()and md.transient.isthermal==0):73 if 'ThermalAnalysis' in analyses and not (solution=='TransientSolution' and md.transient.isthermal==0): 73 74 74 75 md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1) … … 79 80 return md 80 81 # }}} 81 def marshall(self, md,fid): # {{{82 def marshall(self,prefix,md,fid): # {{{ 82 83 83 84 yts=md.constants.yts … … 85 86 print('WARNING: value of yts for MISMIP+ runs different from ISSM default!') 86 87 87 floatingice_melting_rate = numpy.zeros((md.mesh.numberofvertices,1)) 88 floatingice_melting_rate = md.basalforcings.meltrate_factor*numpy.tanh((md.geometry.base-md.geometry.bed)/md.basalforcings.threshold_thickness)*numpy.amax(md.basalforcings.upperdepth_melt-md.geometry.base,0) 89 90 WriteData(fid,'enum',BasalforcingsEnum(),'data',MismipFloatingMeltRateEnum(),'format','Integer') 91 WriteData(fid,'data',floatingice_melting_rate,'format','DoubleMat','enum',BasalforcingsFloatingiceMeltingRateEnum(),'mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1) 92 WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','enum',BasalforcingsGroundediceMeltingRateEnum(),'mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1) 93 WriteData(fid,'object',self,'fieldname','geothermalflux','enum',BasalforcingsGeothermalfluxEnum(),'format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1) 94 WriteData(fid,'object',self,'fieldname','meltrate_factor','format','Double','enum',BasalforcingsMeltrateFactorEnum(),'scale',1./yts) 95 WriteData(fid,'object',self,'fieldname','threshold_thickness','format','Double','enum',BasalforcingsThresholdThicknessEnum()) 96 WriteData(fid,'object',self,'fieldname','upperdepth_melt','format','Double','enum',BasalforcingsUpperdepthMeltEnum()) 88 WriteData(fid,prefix,'name','md.basalforcings.model','data',3,'format','Integer') 89 WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','name','md.basalforcings.groundedice_melting_rate','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 90 WriteData(fid,prefix,'object',self,'fieldname','geothermalflux','name','md.basalforcings.geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 91 WriteData(fid,prefix,'object',self,'fieldname','meltrate_factor','format','Double','scale',1./yts) 92 WriteData(fid,prefix,'object',self,'fieldname','threshold_thickness','format','Double') 93 WriteData(fid,prefix,'object',self,'fieldname','upperdepth_melt','format','Double') 97 94 98 95 # }}} -
issm/trunk-jpl/src/py3/classes/model.py
r19895 r23670 1 1 #module imports {{{ 2 import numpy 2 import numpy as np 3 3 import copy 4 4 import sys 5 import MatlabFuncs as m 5 from mesh2d import mesh2d 6 from mesh3dprisms import mesh3dprisms 7 from mask import mask 8 from geometry import geometry 9 from constants import constants 10 from SMBforcing import SMBforcing 11 from SMBpdd import SMBpdd 12 from SMBd18opdd import SMBd18opdd 13 from SMBgradients import SMBgradients 14 from SMBcomponents import SMBcomponents 15 from SMBmeltcomponents import SMBmeltcomponents 16 from basalforcings import basalforcings 17 from matice import matice 18 from levelset import levelset 19 from calving import calving 20 from fourierlove import fourierlove 21 from calvinglevermann import calvinglevermann 22 #from calvingpi import calvingpi 23 from frontalforcings import frontalforcings 24 from damage import damage 25 from friction import friction 26 from flowequation import flowequation 27 from timestepping import timestepping 28 from timesteppingadaptive import timesteppingadaptive 29 from initialization import initialization 30 from rifts import rifts 31 from slr import slr 32 from debug import debug 33 from verbose import verbose 34 from issmsettings import issmsettings 35 from toolkits import toolkits 36 from generic import generic 37 from pfe import pfe 38 from vilje import vilje 39 from hexagon import hexagon 40 from cyclone import cyclone 41 from stallo import stallo 42 from balancethickness import balancethickness 43 from stressbalance import stressbalance 44 from groundingline import groundingline 45 from hydrologyshreve import hydrologyshreve 46 from hydrologydc import hydrologydc 47 from masstransport import masstransport 48 from thermal import thermal 49 from steadystate import steadystate 50 from transient import transient 51 from giaivins import giaivins 52 from esa import esa 53 from autodiff import autodiff 54 from inversion import inversion 55 from outputdefinition import outputdefinition 56 from qmu import qmu 57 from amr import amr 58 from results import results 59 from radaroverlay import radaroverlay 60 from miscellaneous import miscellaneous 61 from private import private 62 from mumpsoptions import mumpsoptions 63 from iluasmoptions import iluasmoptions 64 from project3d import project3d 65 from project2d import project2d 66 from FlagElements import FlagElements 67 from NodeConnectivity import NodeConnectivity 68 from ElementConnectivity import ElementConnectivity 69 from contourenvelope import contourenvelope 70 from DepthAverage import DepthAverage 6 71 #}}} 7 72 8 73 class model(object): 9 74 #properties 10 def __init__(self,*filename):#{{{ 11 12 def netCDFread(filename): 13 def walktree(data): 14 keys = data.groups.keys() 15 yield keys 16 for key in keys: 17 for children in walktree(data.groups[str(key)]): 18 yield children 19 20 if path.exists(filename): 21 print ('Opening {} for reading '.format(filename)) 22 NCData=Dataset(filename, 'r') 23 class_dict={} 24 25 for children in walktree(NCData): 26 for child in children: 27 class_dict[str(child)]=str(getattr(NCData.groups[str(child)],'classtype')) 28 29 return class_dict 30 31 if filename: 32 classtype=netCDFread(filename[0]) 33 else: 34 classtype=self.properties() 35 36 VT=[v[0] for v in dict.values(classtype)] 37 classnames=[classname for classname in dict.keys(classtype)] 38 module=map(__import__,VT) 39 40 for i,mod in enumerate(module): 41 self.__dict__[classnames[i]] = getattr(mod,str(classtype[str(classnames[i])][0]))() 42 43 #}}} 44 75 def __init__(self):#{{{ 76 77 # classtype=model.properties 78 79 # for classe in dict.keys(classtype): 80 # print classe 81 # self.__dict__[classe] = classtype[str(classe)] 82 83 self.mesh = mesh2d() 84 self.mask = mask() 85 self.geometry = geometry() 86 self.constants = constants() 87 self.smb = SMBforcing() 88 self.basalforcings = basalforcings() 89 self.materials = matice() 90 self.damage = damage() 91 self.friction = friction() 92 self.flowequation = flowequation() 93 self.timestepping = timestepping() 94 self.initialization = initialization() 95 self.rifts = rifts() 96 self.slr = slr() 97 98 self.debug = debug() 99 self.verbose = verbose() 100 self.settings = issmsettings() 101 self.toolkits = toolkits() 102 self.cluster = generic() 103 104 self.balancethickness = balancethickness() 105 self.stressbalance = stressbalance() 106 self.groundingline = groundingline() 107 self.hydrology = hydrologyshreve() 108 self.masstransport = masstransport() 109 self.thermal = thermal() 110 self.steadystate = steadystate() 111 self.transient = transient() 112 self.levelset = levelset() 113 self.calving = calving() 114 self.frontalforcings = frontalforcings() 115 self.gia = giaivins() 116 self.love = fourierlove() 117 self.esa = esa() 118 self.autodiff = autodiff() 119 self.inversion = inversion() 120 self.qmu = qmu() 121 self.amr = amr() 122 123 self.results = results() 124 self.outputdefinition = outputdefinition() 125 self.radaroverlay = radaroverlay() 126 self.miscellaneous = miscellaneous() 127 self.private = private() 128 #}}} 45 129 def properties(self): # {{{ 46 130 # ordered list of properties since vars(self) is random 47 return {'mesh':['mesh2d','mesh properties'],\ 48 'mask':['mask','defines grounded and floating elements'],\ 49 'geometry':['geometry','surface elevation, bedrock topography, ice thickness,...'],\ 50 'constants':['constants','physical constants'],\ 51 'smb':['SMBpdd','surface forcings'],\ 52 'basalforcings':['basalforcings','bed forcings'],\ 53 'materials':['matice','material properties'],\ 54 'damage':['damage','damage propagation laws'],\ 55 'friction':['friction','basal friction/drag properties'],\ 56 'flowequation':['flowequation','flow equations'],\ 57 'timestepping':['timestepping','time stepping for transient models'],\ 58 'initialization':['initialization','initial guess/state'],\ 59 'rifts':['rifts','rifts properties'],\ 60 'debug':['debug','debugging tools (valgrind, gprof)'],\ 61 'verbose':['verbose','verbosity level in solve'],\ 62 'settings':['settings','settings properties'],\ 63 'toolkits':['toolkits','PETSc options for each solution'],\ 64 'cluster':['generic','cluster parameters (number of cpus...)'],\ 65 'balancethickness':['balancethickness','parameters for balancethickness solution'],\ 66 'stressbalance':['stressbalance','parameters for stressbalance solution'],\ 67 'groundingline':['groundingline','parameters for groundingline solution'],\ 68 'hydrology':['hydrologyshreve','parameters for hydrology solution'],\ 69 'masstransport':['masstransport','parameters for masstransport solution'],\ 70 'thermal':['thermal','parameters for thermal solution'],\ 71 'steadystate':['steadystate','parameters for steadystate solution'],\ 72 'transient':['transient','parameters for transient solution'],\ 73 'calving':['calving','parameters for calving'],\ 74 'gia':['gia','Parameters for gia model'],\ 75 'autodiff':['autodiff','automatic differentiation parameters'],\ 76 'flaim':['flaim','flaim parameters'],\ 77 'inversion':['inversion','parameters for inverse methods'],\ 78 'qmu':['qmu','dakota properties'],\ 79 'outputdefinition':['outputdefinition','output definition'],\ 80 'results':['results','model results'],\ 81 'radaroverlay':['radaroverlay','radar image for plot overlay'],\ 82 'miscellaneous':['miscellaneous','miscellaneous fields'],\ 83 'private':['private','...']} 131 return ['mesh', 132 'mask', 133 'geometry', 134 'constants', 135 'smb', 136 'basalforcings', 137 'materials', 138 'damage', 139 'friction', 140 'flowequation', 141 'timestepping', 142 'initialization', 143 'rifts', 144 'slr', 145 'debug', 146 'verbose', 147 'settings', 148 'toolkits', 149 'cluster', 150 'balancethickness', 151 'stressbalance', 152 'groundingline', 153 'hydrology', 154 'masstransport', 155 'thermal', 156 'steadystate', 157 'transient', 158 'levelset', 159 'calving', 160 'frontalforcings', 161 'love', 162 'gia', 163 'esa', 164 'autodiff', 165 'inversion', 166 'qmu', 167 'amr', 168 'outputdefinition', 169 'results', 170 'radaroverlay', 171 'miscellaneous', 172 'private'] 84 173 # }}} 85 86 174 def __repr__(obj): #{{{ 87 string = "Model Description" 88 for i,mod in enumerate(dict.keys(obj.properties())): 89 tmp="%19s: %-22s -- %s" % (mod,"[%s,%s]" % ("1x1",obj.__dict__[mod].__class__.__name__),obj.properties()[mod][1]) 90 string="\n".join([string, tmp]) 175 #print "Here %s the number: %d" % ("is", 37) 176 string="%19s: %-22s -- %s" % ("mesh","[%s,%s]" % ("1x1",obj.mesh.__class__.__name__),"mesh properties") 177 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("mask","[%s,%s]" % ("1x1",obj.mask.__class__.__name__),"defines grounded and floating elements")) 178 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("geometry","[%s,%s]" % ("1x1",obj.geometry.__class__.__name__),"surface elevation, bedrock topography, ice thickness,...")) 179 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("constants","[%s,%s]" % ("1x1",obj.constants.__class__.__name__),"physical constants")) 180 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("smb","[%s,%s]" % ("1x1",obj.smb.__class__.__name__),"surface mass balance")) 181 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("basalforcings","[%s,%s]" % ("1x1",obj.basalforcings.__class__.__name__),"bed forcings")) 182 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("materials","[%s,%s]" % ("1x1",obj.materials.__class__.__name__),"material properties")) 183 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("damage","[%s,%s]" % ("1x1",obj.damage.__class__.__name__),"damage propagation laws")) 184 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("friction","[%s,%s]" % ("1x1",obj.friction.__class__.__name__),"basal friction/drag properties")) 185 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flowequation","[%s,%s]" % ("1x1",obj.flowequation.__class__.__name__),"flow equations")) 186 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("timestepping","[%s,%s]" % ("1x1",obj.timestepping.__class__.__name__),"time stepping for transient models")) 187 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("initialization","[%s,%s]" % ("1x1",obj.initialization.__class__.__name__),"initial guess/state")) 188 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("rifts","[%s,%s]" % ("1x1",obj.rifts.__class__.__name__),"rifts properties")) 189 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("slr","[%s,%s]" % ("1x1",obj.slr.__class__.__name__),"slr forcings")) 190 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("debug","[%s,%s]" % ("1x1",obj.debug.__class__.__name__),"debugging tools (valgrind, gprof)")) 191 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("verbose","[%s,%s]" % ("1x1",obj.verbose.__class__.__name__),"verbosity level in solve")) 192 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("settings","[%s,%s]" % ("1x1",obj.settings.__class__.__name__),"settings properties")) 193 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("toolkits","[%s,%s]" % ("1x1",obj.toolkits.__class__.__name__),"PETSc options for each solution")) 194 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("cluster","[%s,%s]" % ("1x1",obj.cluster.__class__.__name__),"cluster parameters (number of cpus...)")) 195 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("balancethickness","[%s,%s]" % ("1x1",obj.balancethickness.__class__.__name__),"parameters for balancethickness solution")) 196 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("stressbalance","[%s,%s]" % ("1x1",obj.stressbalance.__class__.__name__),"parameters for stressbalance solution")) 197 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("groundingline","[%s,%s]" % ("1x1",obj.groundingline.__class__.__name__),"parameters for groundingline solution")) 198 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("hydrology","[%s,%s]" % ("1x1",obj.hydrology.__class__.__name__),"parameters for hydrology solution")) 199 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("masstransport","[%s,%s]" % ("1x1",obj.masstransport.__class__.__name__),"parameters for masstransport solution")) 200 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("thermal","[%s,%s]" % ("1x1",obj.thermal.__class__.__name__),"parameters for thermal solution")) 201 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("steadystate","[%s,%s]" % ("1x1",obj.steadystate.__class__.__name__),"parameters for steadystate solution")) 202 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("transient","[%s,%s]" % ("1x1",obj.transient.__class__.__name__),"parameters for transient solution")) 203 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("levelset","[%s,%s]" % ("1x1",obj.levelset.__class__.__name__),"parameters for moving boundaries (level-set method)")) 204 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("calving","[%s,%s]" % ("1x1",obj.calving.__class__.__name__),"parameters for calving")) 205 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("frontalforcings","[%s,%s]" % ("1x1",obj.frontalforcings.__class__.__name__),"parameters for frontalforcings")) 206 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("gia","[%s,%s]" % ("1x1",obj.gia.__class__.__name__),"parameters for gia solution")) 207 string="%s\n%s" % (string,'%19s: %-22s -- %s' % ("love","[%s,%s]" % ("1x1",obj.love.__class__.__name__),"parameters for love solution")) 208 string="%s\n%s" % (string,'%19s: %-22s -- %s' % ("esa","[%s,%s]" % ("1x1",obj.esa.__class__.__name__),"parameters for elastic adjustment solution")) 209 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("autodiff","[%s,%s]" % ("1x1",obj.autodiff.__class__.__name__),"automatic differentiation parameters")) 210 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("inversion","[%s,%s]" % ("1x1",obj.inversion.__class__.__name__),"parameters for inverse methods")) 211 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("qmu","[%s,%s]" % ("1x1",obj.qmu.__class__.__name__),"dakota properties")) 212 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("amr","[%s,%s]" % ("1x1",obj.amr.__class__.__name__),"adaptive mesh refinement properties")) 213 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("outputdefinition","[%s,%s]" % ("1x1",obj.outputdefinition.__class__.__name__),"output definition")) 214 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("results","[%s,%s]" % ("1x1",obj.results.__class__.__name__),"model results")) 215 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("radaroverlay","[%s,%s]" % ("1x1",obj.radaroverlay.__class__.__name__),"radar image for plot overlay")) 216 string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("miscellaneous","[%s,%s]" % ("1x1",obj.miscellaneous.__class__.__name__),"miscellaneous fields")) 91 217 return string 92 218 # }}} 93 94 219 def checkmessage(self,string): # {{{ 95 print( ("model not consistent: ", string))220 print("model not consistent: ", string) 96 221 self.private.isconsistent=False 97 222 return self 98 223 # }}} 99 100 def extract( md,area): # {{{224 #@staticmethod 225 def extract(self,area): # {{{ 101 226 """ 102 227 extract - extract a model according to an Argus contour or flag list 103 228 104 This routine extracts a submodel from a bigger model with respect to a given contour105 md must be followed by the corresponding exp file or flags list106 It can either be a domain file (argus type, .exp extension), or an array of element flags. 107 If user wants every element outside the domain to be 108 extract2d, add '~' to the name of the domain file (ex: '~HO.exp')109 an empty string '' will be considered as an empty domain110 a string 'all' will be considered as the entire domain111 112 Usage:113 md2=extract(md,area)114 115 Examples:116 md2=extract(md,'Domain.exp')117 118 See also: EXTRUDE, COLLAPSE229 This routine extracts a submodel from a bigger model with respect to a given contour 230 md must be followed by the corresponding exp file or flags list 231 It can either be a domain file (argus type, .exp extension), or an array of element flags. 232 If user wants every element outside the domain to be 233 extract2d, add '~' to the name of the domain file (ex: '~HO.exp') 234 an empty string '' will be considered as an empty domain 235 a string 'all' will be considered as the entire domain 236 237 Usage: 238 md2=extract(md,area) 239 240 Examples: 241 md2=extract(md,'Domain.exp') 242 243 See also: EXTRUDE, COLLAPSE 119 244 """ 120 245 121 246 #copy model 122 md1=copy.deepcopy( md)247 md1=copy.deepcopy(self) 123 248 124 249 #get elements that are inside area 125 250 flag_elem=FlagElements(md1,area) 126 if not n umpy.any(flag_elem):251 if not np.any(flag_elem): 127 252 raise RuntimeError("extracted model is empty") 128 253 129 254 #kick out all elements with 3 dirichlets 130 spc_elem=n umpy.nonzero(numpy.logical_not(flag_elem))[0]131 spc_node=n umpy.unique(md1.mesh.elements[spc_elem,:])-1132 flag=n umpy.ones(md1.mesh.numberofvertices)255 spc_elem=np.nonzero(np.logical_not(flag_elem))[0] 256 spc_node=np.unique(md1.mesh.elements[spc_elem,:])-1 257 flag=np.ones(md1.mesh.numberofvertices) 133 258 flag[spc_node]=0 134 pos=n umpy.nonzero(numpy.logical_not(numpy.sum(flag[md1.mesh.elements-1],axis=1)))[0]259 pos=np.nonzero(np.logical_not(np.sum(flag[md1.mesh.elements-1],axis=1)))[0] 135 260 flag_elem[pos]=0 136 261 137 262 #extracted elements and nodes lists 138 pos_elem=n umpy.nonzero(flag_elem)[0]139 pos_node=n umpy.unique(md1.mesh.elements[pos_elem,:])-1140 263 pos_elem=np.nonzero(flag_elem)[0] 264 pos_node=np.unique(md1.mesh.elements[pos_elem,:])-1 265 141 266 #keep track of some fields 142 267 numberofvertices1=md1.mesh.numberofvertices 143 268 numberofelements1=md1.mesh.numberofelements 144 numberofvertices2=n umpy.size(pos_node)145 numberofelements2=n umpy.size(pos_elem)146 flag_node=n umpy.zeros(numberofvertices1)269 numberofvertices2=np.size(pos_node) 270 numberofelements2=np.size(pos_elem) 271 flag_node=np.zeros(numberofvertices1) 147 272 flag_node[pos_node]=1 148 273 149 274 #Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements) 150 Pelem=n umpy.zeros(numberofelements1,int)151 Pelem[pos_elem]=n umpy.arange(1,numberofelements2+1)152 Pnode=n umpy.zeros(numberofvertices1,int)153 Pnode[pos_node]=n umpy.arange(1,numberofvertices2+1)154 275 Pelem=np.zeros(numberofelements1,int) 276 Pelem[pos_elem]=np.arange(1,numberofelements2+1) 277 Pnode=np.zeros(numberofvertices1,int) 278 Pnode[pos_node]=np.arange(1,numberofvertices2+1) 279 155 280 #renumber the elements (some node won't exist anymore) 156 281 elements_1=copy.deepcopy(md1.mesh.elements) … … 165 290 166 291 #OK, now create the new model! 292 167 293 #take every field from model 168 294 md2=copy.deepcopy(md1) 169 295 170 296 #automatically modify fields 297 171 298 #loop over model fields 172 299 model_fields=vars(md1) … … 174 301 #get field 175 302 field=getattr(md1,fieldi) 176 fieldsize=n umpy.shape(field)177 if hasattr(field,'__dict__') and not m.ismember(fieldi,['results'])[0]: #recursive call303 fieldsize=np.shape(field) 304 if hasattr(field,'__dict__') and not fieldi in ['results']: #recursive call 178 305 object_fields=vars(field) 179 306 for fieldj in object_fields: 180 307 #get field 181 308 field=getattr(getattr(md1,fieldi),fieldj) 182 fieldsize=n umpy.shape(field)309 fieldsize=np.shape(field) 183 310 if len(fieldsize): 184 311 #size = number of nodes * n 185 if 312 if fieldsize[0]==numberofvertices1: 186 313 setattr(getattr(md2,fieldi),fieldj,field[pos_node]) 187 314 elif fieldsize[0]==numberofvertices1+1: 188 setattr(getattr(md2,fieldi),fieldj,n umpy.vstack((field[pos_node],field[-1,:])))189 315 setattr(getattr(md2,fieldi),fieldj,np.vstack((field[pos_node],field[-1,:]))) 316 #size = number of elements * n 190 317 elif fieldsize[0]==numberofelements1: 191 318 setattr(getattr(md2,fieldi),fieldj,field[pos_elem]) … … 196 323 setattr(md2,fieldi,field[pos_node]) 197 324 elif fieldsize[0]==numberofvertices1+1: 198 setattr(md2,fieldi,n umpy.hstack((field[pos_node],field[-1,:])))199 325 setattr(md2,fieldi,np.hstack((field[pos_node],field[-1,:]))) 326 #size = number of elements * n 200 327 elif fieldsize[0]==numberofelements1: 201 328 setattr(md2,fieldi,field[pos_elem]) … … 207 334 md2.mesh.numberofvertices=numberofvertices2 208 335 md2.mesh.elements=elements_2 209 336 210 337 #mesh.uppervertex mesh.lowervertex 211 338 if md1.mesh.__class__.__name__=='mesh3dprisms': 212 339 md2.mesh.uppervertex=md1.mesh.uppervertex[pos_node] 213 pos=n umpy.nonzero(numpy.logical_not(md2.mesh.uppervertex==-1))[0]214 md2.mesh.uppervertex[pos]=Pnode[md2.mesh.uppervertex[pos] -1]215 340 pos=np.where(~np.isnan(md2.mesh.uppervertex))[0] 341 md2.mesh.uppervertex[pos]=Pnode[md2.mesh.uppervertex[pos].astype(int)-1] 342 216 343 md2.mesh.lowervertex=md1.mesh.lowervertex[pos_node] 217 pos=n umpy.nonzero(numpy.logical_not(md2.mesh.lowervertex==-1))[0]218 md2.mesh.lowervertex[pos]=Pnode[md2.mesh.lowervertex[pos] -1]219 344 pos=np.where(~np.isnan(md2.mesh.lowervertex))[0] 345 md2.mesh.lowervertex[pos]=Pnode[md2.mesh.lowervertex[pos].astype(int)-1] 346 220 347 md2.mesh.upperelements=md1.mesh.upperelements[pos_elem] 221 pos=n umpy.nonzero(numpy.logical_not(md2.mesh.upperelements==-1))[0]222 md2.mesh.upperelements[pos]=Pelem[md2.mesh.upperelements[pos] -1]223 348 pos=np.where(~np.isnan(md2.mesh.upperelements))[0] 349 md2.mesh.upperelements[pos]=Pelem[md2.mesh.upperelements[pos].astype(int)-1] 350 224 351 md2.mesh.lowerelements=md1.mesh.lowerelements[pos_elem] 225 pos=n umpy.nonzero(numpy.logical_not(md2.mesh.lowerelements==-1))[0]226 md2.mesh.lowerelements[pos]=Pelem[md2.mesh.lowerelements[pos] -1]227 228 #Initial 2d mesh 352 pos=np.where(~np.isnan(md2.mesh.lowerelements))[0] 353 md2.mesh.lowerelements[pos]=Pelem[md2.mesh.lowerelements[pos].astype(int)-1] 354 355 #Initial 2d mesh 229 356 if md1.mesh.__class__.__name__=='mesh3dprisms': 230 flag_elem_2d=flag_elem[n umpy.arange(0,md1.mesh.numberofelements2d)]231 pos_elem_2d=n umpy.nonzero(flag_elem_2d)[0]232 flag_node_2d=flag_node[n umpy.arange(0,md1.mesh.numberofvertices2d)]233 pos_node_2d=n umpy.nonzero(flag_node_2d)[0]234 235 md2.mesh.numberofelements2d=n umpy.size(pos_elem_2d)236 md2.mesh.numberofvertices2d=n umpy.size(pos_node_2d)357 flag_elem_2d=flag_elem[np.arange(0,md1.mesh.numberofelements2d)] 358 pos_elem_2d=np.nonzero(flag_elem_2d)[0] 359 flag_node_2d=flag_node[np.arange(0,md1.mesh.numberofvertices2d)] 360 pos_node_2d=np.nonzero(flag_node_2d)[0] 361 362 md2.mesh.numberofelements2d=np.size(pos_elem_2d) 363 md2.mesh.numberofvertices2d=np.size(pos_node_2d) 237 364 md2.mesh.elements2d=md1.mesh.elements2d[pos_elem_2d,:] 238 365 md2.mesh.elements2d[:,0]=Pnode[md2.mesh.elements2d[:,0]-1] 239 366 md2.mesh.elements2d[:,1]=Pnode[md2.mesh.elements2d[:,1]-1] 240 367 md2.mesh.elements2d[:,2]=Pnode[md2.mesh.elements2d[:,2]-1] 241 368 242 369 md2.mesh.x2d=md1.mesh.x[pos_node_2d] 243 370 md2.mesh.y2d=md1.mesh.y[pos_node_2d] 244 371 245 372 #Edges 246 if m.strcmp(md.mesh.domaintype(),'2Dhorizontal'): 247 if numpy.ndim(md2.mesh.edges)>1 and numpy.size(md2.mesh.edges,axis=1)>1: 248 #do not use ~isnan because there are some numpy.nans... 373 if md1.mesh.domaintype()=='2Dhorizontal': 374 if np.ndim(md2.mesh.edges)>1 and np.size(md2.mesh.edges,axis=1)>1: #do not use ~isnan because there are some np.nans... 249 375 #renumber first two columns 250 pos=n umpy.nonzero(md2.mesh.edges[:,3]!=-1)[0]251 md2.mesh.edges[: 252 md2.mesh.edges[: 253 md2.mesh.edges[: 376 pos=np.nonzero(md2.mesh.edges[:,3]!=-1)[0] 377 md2.mesh.edges[:,0]=Pnode[md2.mesh.edges[:,0]-1] 378 md2.mesh.edges[:,1]=Pnode[md2.mesh.edges[:,1]-1] 379 md2.mesh.edges[:,2]=Pelem[md2.mesh.edges[:,2]-1] 254 380 md2.mesh.edges[pos,3]=Pelem[md2.mesh.edges[pos,3]-1] 255 381 #remove edges when the 2 vertices are not in the domain. 256 md2.mesh.edges=md2.mesh.edges[n umpy.nonzero(numpy.logical_and(md2.mesh.edges[:,0],md2.mesh.edges[:,1]))[0],:]382 md2.mesh.edges=md2.mesh.edges[np.nonzero(np.logical_and(md2.mesh.edges[:,0],md2.mesh.edges[:,1]))[0],:] 257 383 #Replace all zeros by -1 in the last two columns 258 pos=n umpy.nonzero(md2.mesh.edges[:,2]==0)[0]384 pos=np.nonzero(md2.mesh.edges[:,2]==0)[0] 259 385 md2.mesh.edges[pos,2]=-1 260 pos=n umpy.nonzero(md2.mesh.edges[:,3]==0)[0]386 pos=np.nonzero(md2.mesh.edges[:,3]==0)[0] 261 387 md2.mesh.edges[pos,3]=-1 262 388 #Invert -1 on the third column with last column (Also invert first two columns!!) 263 pos=n umpy.nonzero(md2.mesh.edges[:,2]==-1)[0]389 pos=np.nonzero(md2.mesh.edges[:,2]==-1)[0] 264 390 md2.mesh.edges[pos,2]=md2.mesh.edges[pos,3] 265 391 md2.mesh.edges[pos,3]=-1 … … 268 394 md2.mesh.edges[pos,0]=values 269 395 #Finally remove edges that do not belong to any element 270 pos=n umpy.nonzero(numpy.logical_and(md2.mesh.edges[:,1]==-1,md2.mesh.edges[:,2]==-1))[0]271 md2.mesh.edges=n umpy.delete(md2.mesh.edges,pos,axis=0)396 pos=np.nonzero(np.logical_and(md2.mesh.edges[:,1]==-1,md2.mesh.edges[:,2]==-1))[0] 397 md2.mesh.edges=np.delete(md2.mesh.edges,pos,axis=0) 272 398 273 399 #Penalties 274 if n umpy.any(numpy.logical_not(numpy.isnan(md2.stressbalance.vertex_pairing))):275 for i in range(n umpy.size(md1.stressbalance.vertex_pairing,axis=0)):400 if np.any(np.logical_not(np.isnan(md2.stressbalance.vertex_pairing))): 401 for i in range(np.size(md1.stressbalance.vertex_pairing,axis=0)): 276 402 md2.stressbalance.vertex_pairing[i,:]=Pnode[md1.stressbalance.vertex_pairing[i,:]] 277 md2.stressbalance.vertex_pairing=md2.stressbalance.vertex_pairing[n umpy.nonzero(md2.stressbalance.vertex_pairing[:,0])[0],:]278 if n umpy.any(numpy.logical_not(numpy.isnan(md2.masstransport.vertex_pairing))):279 for i in range(n umpy.size(md1.masstransport.vertex_pairing,axis=0)):403 md2.stressbalance.vertex_pairing=md2.stressbalance.vertex_pairing[np.nonzero(md2.stressbalance.vertex_pairing[:,0])[0],:] 404 if np.any(np.logical_not(np.isnan(md2.masstransport.vertex_pairing))): 405 for i in range(np.size(md1.masstransport.vertex_pairing,axis=0)): 280 406 md2.masstransport.vertex_pairing[i,:]=Pnode[md1.masstransport.vertex_pairing[i,:]] 281 md2.masstransport.vertex_pairing=md2.masstransport.vertex_pairing[numpy.nonzero(md2.masstransport.vertex_pairing[:,0])[0],:]407 md2.masstransport.vertex_pairing=md2.masstransport.vertex_pairing[np.nonzero(md2.masstransport.vertex_pairing[:,0])[0],:] 282 408 283 409 #recreate segments 284 410 if md1.mesh.__class__.__name__=='mesh2d': 285 [md2.mesh.vertexconnectivity]=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)286 [md2.mesh.elementconnectivity]=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)411 md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)[0] 412 md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)[0] 287 413 md2.mesh.segments=contourenvelope(md2) 288 md2.mesh.vertexonboundary=n umpy.zeros(numberofvertices2,bool)414 md2.mesh.vertexonboundary=np.zeros(numberofvertices2,bool) 289 415 md2.mesh.vertexonboundary[md2.mesh.segments[:,0:2]-1]=True 290 416 else: 291 417 #First do the connectivity for the contourenvelope in 2d 292 [md2.mesh.vertexconnectivity]=NodeConnectivity(md2.mesh.elements2d,md2.mesh.numberofvertices2d)293 [md2.mesh.elementconnectivity]=ElementConnectivity(md2.mesh.elements2d,md2.mesh.vertexconnectivity)418 md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements2d,md2.mesh.numberofvertices2d)[0] 419 md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements2d,md2.mesh.vertexconnectivity)[0] 294 420 segments=contourenvelope(md2) 295 md2.mesh.vertexonboundary=n umpy.zeros(numberofvertices2/md2.mesh.numberoflayers,bool)421 md2.mesh.vertexonboundary=np.zeros(numberofvertices2/md2.mesh.numberoflayers,bool) 296 422 md2.mesh.vertexonboundary[segments[:,0:2]-1]=True 297 md2.mesh.vertexonboundary=n umpy.tile(md2.mesh.vertexonboundary,md2.mesh.numberoflayers)423 md2.mesh.vertexonboundary=np.tile(md2.mesh.vertexonboundary,md2.mesh.numberoflayers) 298 424 #Then do it for 3d as usual 299 [md2.mesh.vertexconnectivity]=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)300 [md2.mesh.elementconnectivity]=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)425 md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)[0] 426 md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)[0] 301 427 302 428 #Boundary conditions: Dirichlets on new boundary 303 429 #Catch the elements that have not been extracted 304 orphans_elem=n umpy.nonzero(numpy.logical_not(flag_elem))[0]305 orphans_node=n umpy.unique(md1.mesh.elements[orphans_elem,:])-1430 orphans_elem=np.nonzero(np.logical_not(flag_elem))[0] 431 orphans_node=np.unique(md1.mesh.elements[orphans_elem,:])-1 306 432 #Figure out which node are on the boundary between md2 and md1 307 nodestoflag1=n umpy.intersect1d(orphans_node,pos_node)433 nodestoflag1=np.intersect1d(orphans_node,pos_node) 308 434 nodestoflag2=Pnode[nodestoflag1].astype(int)-1 309 if n umpy.size(md1.stressbalance.spcvx)>1 and numpy.size(md1.stressbalance.spcvy)>2 and numpy.size(md1.stressbalance.spcvz)>2:310 if n umpy.size(md1.inversion.vx_obs)>1 and numpy.size(md1.inversion.vy_obs)>1:311 md2.stressbalance.spcvx[nodestoflag2]=md2.inversion.vx_obs[nodestoflag2] 435 if np.size(md1.stressbalance.spcvx)>1 and np.size(md1.stressbalance.spcvy)>2 and np.size(md1.stressbalance.spcvz)>2: 436 if np.size(md1.inversion.vx_obs)>1 and np.size(md1.inversion.vy_obs)>1: 437 md2.stressbalance.spcvx[nodestoflag2]=md2.inversion.vx_obs[nodestoflag2] 312 438 md2.stressbalance.spcvy[nodestoflag2]=md2.inversion.vy_obs[nodestoflag2] 313 439 else: 314 md2.stressbalance.spcvx[nodestoflag2]=n umpy.nan315 md2.stressbalance.spcvy[nodestoflag2]=n umpy.nan440 md2.stressbalance.spcvx[nodestoflag2]=np.nan 441 md2.stressbalance.spcvy[nodestoflag2]=np.nan 316 442 print("\n!! extract warning: spc values should be checked !!\n\n") 317 443 #put 0 for vz 318 444 md2.stressbalance.spcvz[nodestoflag2]=0 319 if n umpy.any(numpy.logical_not(numpy.isnan(md1.thermal.spctemperature))):320 md2.thermal.spctemperature[nodestoflag2 ,0]=1445 if np.any(np.logical_not(np.isnan(md1.thermal.spctemperature))): 446 md2.thermal.spctemperature[nodestoflag2]=1 321 447 322 448 #Results fields 323 449 if md1.results: 324 450 md2.results=results() 325 for solutionfield,field in list(md1.results.__dict__.items()):451 for solutionfield,field in md1.results.__dict__.items(): 326 452 if isinstance(field,list): 327 453 setattr(md2.results,solutionfield,[]) … … 332 458 fieldr=getattr(md2.results,solutionfield)[i] 333 459 #get subfields 334 for solutionsubfield,subfield in list(fieldi.__dict__.items()):335 if n umpy.size(subfield)==numberofvertices1:460 for solutionsubfield,subfield in fieldi.__dict__.items(): 461 if np.size(subfield)==numberofvertices1: 336 462 setattr(fieldr,solutionsubfield,subfield[pos_node]) 337 elif n umpy.size(subfield)==numberofelements1:463 elif np.size(subfield)==numberofelements1: 338 464 setattr(fieldr,solutionsubfield,subfield[pos_elem]) 339 465 else: … … 346 472 fieldr=getattr(md2.results,solutionfield) 347 473 #get subfields 348 for solutionsubfield,subfield in list(field.__dict__.items()):349 if n umpy.size(subfield)==numberofvertices1:474 for solutionsubfield,subfield in field.__dict__.items(): 475 if np.size(subfield)==numberofvertices1: 350 476 setattr(fieldr,solutionsubfield,subfield[pos_node]) 351 elif n umpy.size(subfield)==numberofelements1:477 elif np.size(subfield)==numberofelements1: 352 478 setattr(fieldr,solutionsubfield,subfield[pos_elem]) 353 479 else: 354 480 setattr(fieldr,solutionsubfield,subfield) 355 481 482 #OutputDefinitions fields 483 if md1.outputdefinition.definitions: 484 for solutionfield,field in md1.outputdefinition.__dict__.items(): 485 if isinstance(field,list): 486 #get each definition 487 for i,fieldi in enumerate(field): 488 if fieldi: 489 fieldr=getattr(md2.outputdefinition,solutionfield)[i] 490 #get subfields 491 for solutionsubfield,subfield in fieldi.__dict__.items(): 492 if np.size(subfield)==numberofvertices1: 493 setattr(fieldr,solutionsubfield,subfield[pos_node]) 494 elif np.size(subfield)==numberofelements1: 495 setattr(fieldr,solutionsubfield,subfield[pos_elem]) 496 else: 497 setattr(fieldr,solutionsubfield,subfield) 498 356 499 #Keep track of pos_node and pos_elem 357 500 md2.mesh.extractedvertices=pos_node+1 358 501 md2.mesh.extractedelements=pos_elem+1 502 359 503 return md2 360 504 # }}} 361 362 505 def extrude(md,*args): # {{{ 363 506 """ … … 369 512 - follow two polynomial laws, one for the lower part and one for the upper part of the mesh 370 513 - be discribed by a list of coefficients (between 0 and 1) 371 514 372 515 373 516 Usage: … … 402 545 raise TypeError("extrusionexponent must be >=0") 403 546 numlayers=args[0] 404 extrusionlist=(n umpy.arange(0.,float(numlayers-1)+1.,1.)/float(numlayers-1))**args[1]547 extrusionlist=(np.arange(0.,float(numlayers-1)+1.,1.)/float(numlayers-1))**args[1] 405 548 406 549 elif len(args)==3: #two polynomial laws … … 412 555 raise TypeError("lower and upper extrusionexponents must be >=0") 413 556 414 lowerextrusionlist=(n umpy.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**lowerexp/2.415 upperextrusionlist=(n umpy.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**upperexp/2.416 extrusionlist=n umpy.unique(numpy.concatenate((lowerextrusionlist,1.-upperextrusionlist)))557 lowerextrusionlist=(np.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**lowerexp/2. 558 upperextrusionlist=(np.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**upperexp/2. 559 extrusionlist=np.unique(np.concatenate((lowerextrusionlist,1.-upperextrusionlist))) 417 560 418 561 if numlayers<2: … … 429 572 md.mesh.numberofelements = mesh2d.numberofelements 430 573 md.mesh.numberofvertices = mesh2d.numberofvertices 431 574 432 575 md.mesh.lat = mesh2d.lat 433 576 md.mesh.long = mesh2d.long 434 577 md.mesh.epsg = mesh2d.epsg 435 578 md.mesh.scale_factor = mesh2d.scale_factor 579 436 580 md.mesh.vertexonboundary = mesh2d.vertexonboundary 437 581 md.mesh.vertexconnectivity = mesh2d.vertexconnectivity 438 582 md.mesh.elementconnectivity = mesh2d.elementconnectivity 439 583 md.mesh.average_vertex_connectivity = mesh2d.average_vertex_connectivity 440 584 441 585 md.mesh.extractedvertices = mesh2d.extractedvertices 442 586 md.mesh.extractedelements = mesh2d.extractedelements 443 444 x3d=n umpy.empty((0))445 y3d=n umpy.empty((0))446 z3d=n umpy.empty((0)) #the lower node is on the bed587 588 x3d=np.empty((0)) 589 y3d=np.empty((0)) 590 z3d=np.empty((0)) #the lower node is on the bed 447 591 thickness3d=md.geometry.thickness #thickness and bed for these nodes 448 592 bed3d=md.geometry.base … … 450 594 #Create the new layers 451 595 for i in range(numlayers): 452 x3d=n umpy.concatenate((x3d,md.mesh.x))453 y3d=n umpy.concatenate((y3d,md.mesh.y))596 x3d=np.concatenate((x3d,md.mesh.x)) 597 y3d=np.concatenate((y3d,md.mesh.y)) 454 598 #nodes are distributed between bed and surface accordingly to the given exponent 455 z3d=n umpy.concatenate((z3d,(bed3d+thickness3d*extrusionlist[i]).reshape(-1)))456 number_nodes3d=n umpy.size(x3d) #number of 3d nodes for the non extruded part of the mesh457 458 #Extrude elements 459 elements3d=n umpy.empty((0,6),int)599 z3d=np.concatenate((z3d,(bed3d+thickness3d*extrusionlist[i]).reshape(-1))) 600 number_nodes3d=np.size(x3d) #number of 3d nodes for the non extruded part of the mesh 601 602 #Extrude elements 603 elements3d=np.empty((0,6),int) 460 604 for i in range(numlayers-1): 461 elements3d=n umpy.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 part462 number_el3d=n umpy.size(elements3d,axis=0) #number of 3d nodes for the non extruded part of the mesh605 elements3d=np.vstack((elements3d,np.hstack((md.mesh.elements+i*md.mesh.numberofvertices,md.mesh.elements+(i+1)*md.mesh.numberofvertices)))) #Create the elements of the 3d mesh for the non extruded part 606 number_el3d=np.size(elements3d,axis=0) #number of 3d nodes for the non extruded part of the mesh 463 607 464 608 #Keep a trace of lower and upper nodes 465 lowervertex= -1*numpy.ones(number_nodes3d,int)466 uppervertex= -1*numpy.ones(number_nodes3d,int)467 lowervertex[md.mesh.numberofvertices:]=n umpy.arange(1,(numlayers-1)*md.mesh.numberofvertices+1)468 uppervertex[:(numlayers-1)*md.mesh.numberofvertices]=n umpy.arange(md.mesh.numberofvertices+1,number_nodes3d+1)609 lowervertex=np.nan*np.ones(number_nodes3d,int) 610 uppervertex=np.nan*np.ones(number_nodes3d,int) 611 lowervertex[md.mesh.numberofvertices:]=np.arange(1,(numlayers-1)*md.mesh.numberofvertices+1) 612 uppervertex[:(numlayers-1)*md.mesh.numberofvertices]=np.arange(md.mesh.numberofvertices+1,number_nodes3d+1) 469 613 md.mesh.lowervertex=lowervertex 470 614 md.mesh.uppervertex=uppervertex 471 615 472 616 #same for lower and upper elements 473 lowerelements= -1*numpy.ones(number_el3d,int)474 upperelements= -1*numpy.ones(number_el3d,int)475 lowerelements[md.mesh.numberofelements:]=n umpy.arange(1,(numlayers-2)*md.mesh.numberofelements+1)476 upperelements[:(numlayers-2)*md.mesh.numberofelements]=n umpy.arange(md.mesh.numberofelements+1,(numlayers-1)*md.mesh.numberofelements+1)617 lowerelements=np.nan*np.ones(number_el3d,int) 618 upperelements=np.nan*np.ones(number_el3d,int) 619 lowerelements[md.mesh.numberofelements:]=np.arange(1,(numlayers-2)*md.mesh.numberofelements+1) 620 upperelements[:(numlayers-2)*md.mesh.numberofelements]=np.arange(md.mesh.numberofelements+1,(numlayers-1)*md.mesh.numberofelements+1) 477 621 md.mesh.lowerelements=lowerelements 478 622 md.mesh.upperelements=upperelements 479 623 480 #Save old mesh 624 #Save old mesh 481 625 md.mesh.x2d=md.mesh.x 482 626 md.mesh.y2d=md.mesh.y … … 485 629 md.mesh.numberofvertices2d=md.mesh.numberofvertices 486 630 487 #Build global 3d mesh 631 #Build global 3d mesh 488 632 md.mesh.elements=elements3d 489 633 md.mesh.x=x3d … … 497 641 498 642 #bedinfo and surface info 499 md.mesh.vertexonbase=project3d(md,'vector',n umpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',1)500 md.mesh.vertexonsurface=project3d(md,'vector',n umpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',md.mesh.numberoflayers)643 md.mesh.vertexonbase=project3d(md,'vector',np.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',1) 644 md.mesh.vertexonsurface=project3d(md,'vector',np.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',md.mesh.numberoflayers) 501 645 md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node') 502 646 … … 504 648 md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node') 505 649 md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node') 650 md.mesh.scale_factor=project3d(md,'vector',md.mesh.scale_factor,'type','node') 506 651 507 652 md.geometry.extrude(md) … … 518 663 # Calving variables 519 664 md.hydrology.extrude(md) 665 md.levelset.extrude(md) 520 666 md.calving.extrude(md) 667 md.frontalforcings.extrude(md) 521 668 522 669 #connectivity 523 md.mesh.elementconnectivity=n umpy.tile(md.mesh.elementconnectivity,(numlayers-1,1))524 md.mesh.elementconnectivity[n umpy.nonzero(md.mesh.elementconnectivity==0)]=-sys.maxsize-1525 if not n umpy.isnan(md.mesh.elementconnectivity).all():670 md.mesh.elementconnectivity=np.tile(md.mesh.elementconnectivity,(numlayers-1,1)) 671 md.mesh.elementconnectivity[np.nonzero(md.mesh.elementconnectivity==0)]=-sys.maxsize-1 672 if not np.isnan(md.mesh.elementconnectivity).all(): 526 673 for i in range(1,numlayers-1): 527 674 md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:] \ 528 =md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:]+md.mesh.numberofelements2d529 md.mesh.elementconnectivity[n umpy.nonzero(md.mesh.elementconnectivity<0)]=0675 =md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:]+md.mesh.numberofelements2d 676 md.mesh.elementconnectivity[np.nonzero(md.mesh.elementconnectivity<0)]=0 530 677 531 678 md.materials.extrude(md) 532 md.damage.extrude(md) 679 if md.damage.isdamage==1: 680 md.damage.extrude(md) 533 681 md.gia.extrude(md) 534 682 md.mask.extrude(md) 535 683 md.qmu.extrude(md) 536 684 md.basalforcings.extrude(md) 685 md.outputdefinition.extrude(md) 537 686 538 687 #increase connectivity if less than 25: … … 541 690 542 691 return md 543 # }}}692 # }}} 544 693 def collapse(md): #{{{ 545 694 ''' 546 695 collapses a 3d mesh into a 2d mesh 547 696 548 697 This routine collapses a 3d model into a 2d model and collapses all 549 698 the fileds of the 3d model by taking their depth-averaged values 550 699 551 700 Usage: 552 701 md=collapse(md) 553 ''' 702 ''' 554 703 555 704 #Check that the model is really a 3d model 556 705 if md.mesh.domaintype().lower() != '3d': 557 706 raise Exception("only a 3D model can be collapsed") 558 707 708 #dealing with the friction law 559 709 #drag is limited to nodes that are on the bedrock. 560 md.friction.coefficient=project2d(md,md.friction.coefficient,1) 710 if hasattr(md.friction,'coefficient'): 711 md.friction.coefficient=project2d(md,md.friction.coefficient,1) 561 712 562 713 #p and q (same deal, except for element that are on the bedrock: ) 563 md.friction.p=project2d(md,md.friction.p,1) 564 md.friction.q=project2d(md,md.friction.q,1) 714 if hasattr(md.friction,'p'): 715 md.friction.p=project2d(md,md.friction.p,1) 716 if hasattr(md.friction,'q'): 717 md.friction.q=project2d(md,md.friction.q,1) 718 719 if hasattr(md.friction,'coefficientcoulomb'): 720 md.friction.coefficientcoulomb=project2d(md,md.friction.coefficientcoulomb,1) 721 if hasattr(md.friction,'C'): 722 md.friction.C=project2d(md,md.friction.C,1) 723 if hasattr(md.friction,'As'): 724 md.friction.As=project2d(md,md.friction.As,1) 725 if hasattr(md.friction,'effective_pressure') and not np.isnan(md.friction.effective_pressure).all(): 726 md.friction.effective_pressure=project2d(md,md.friction.effective_pressure,1) 727 if hasattr(md.friction,'water_layer'): 728 md.friction.water_layer=project2d(md,md.friction.water_layer,1) 729 if hasattr(md.friction,'m'): 730 md.friction.m=project2d(md,md.friction.m,1) 565 731 566 732 #observations 567 if not numpy.isnan(md.inversion.vx_obs).all(): md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers) 568 if not numpy.isnan(md.inversion.vy_obs).all(): md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers) 569 if not numpy.isnan(md.inversion.vel_obs).all(): md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers) 570 if not numpy.isnan(md.inversion.cost_functions_coefficients).all(): md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers) 571 if isinstance(md.inversion.min_parameters,numpy.ndarray): 572 if md.inversion.min_parameters.size>1: md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers) 573 if isinstance(md.inversion.max_parameters,numpy.ndarray): 574 if md.inversion.max_parameters.size>1: md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers) 575 if not numpy.isnan(md.smb.mass_balance).all(): 576 md.smb.mass_balance=project2d(md,md.smb.mass_balance,md.mesh.numberoflayers) 577 578 if not numpy.isnan(md.balancethickness.thickening_rate).all(): md.balancethickness.thickening_rate=project2d(md,md.balancethickness.thickening_rate,md.mesh.numberoflayers) 733 if not np.isnan(md.inversion.vx_obs).all(): 734 md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers) 735 if not np.isnan(md.inversion.vy_obs).all(): 736 md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers) 737 if not np.isnan(md.inversion.vel_obs).all(): 738 md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers) 739 if not np.isnan(md.inversion.cost_functions_coefficients).all(): 740 md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers) 741 if isinstance(md.inversion.min_parameters,np.ndarray): 742 if md.inversion.min_parameters.size>1: 743 md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers) 744 if isinstance(md.inversion.max_parameters,np.ndarray): 745 if md.inversion.max_parameters.size>1: 746 md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers) 747 if not np.isnan(md.smb.mass_balance).all(): 748 md.smb.mass_balance=project2d(md,md.smb.mass_balance,md.mesh.numberoflayers) 579 749 580 750 #results 581 if not numpy.isnan(md.initialization.vx).all(): md.initialization.vx=DepthAverage(md,md.initialization.vx) 582 if not numpy.isnan(md.initialization.vy).all(): md.initialization.vy=DepthAverage(md,md.initialization.vy) 583 if not numpy.isnan(md.initialization.vz).all(): md.initialization.vz=DepthAverage(md,md.initialization.vz) 584 if not numpy.isnan(md.initialization.vel).all(): md.initialization.vel=DepthAverage(md,md.initialization.vel) 585 if not numpy.isnan(md.initialization.temperature).all(): md.initialization.temperature=DepthAverage(md,md.initialization.temperature) 586 if not numpy.isnan(md.initialization.pressure).all(): md.initialization.pressure=project2d(md,md.initialization.pressure,1) 587 if not numpy.isnan(md.initialization.sediment_head).all(): md.initialization.sediment_head=project2d(md,md.initialization.sediment_head,1) 588 if not numpy.isnan(md.initialization.epl_head).all(): md.initialization.epl_head=project2d(md,md.initialization.epl_head,1) 589 if not numpy.isnan(md.initialization.epl_thickness).all(): md.initialization.epl_thickness=project2d(md,md.initialization.epl_thickness,1) 590 591 #gia 592 if not numpy.isnan(md.gia.mantle_viscosity).all(): md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1) 593 if not numpy.isnan(md.gia.lithosphere_thickness).all(): md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1) 751 if not np.isnan(md.initialization.vx).all(): 752 md.initialization.vx=DepthAverage(md,md.initialization.vx) 753 if not np.isnan(md.initialization.vy).all(): 754 md.initialization.vy=DepthAverage(md,md.initialization.vy) 755 if not np.isnan(md.initialization.vz).all(): 756 md.initialization.vz=DepthAverage(md,md.initialization.vz) 757 if not np.isnan(md.initialization.vel).all(): 758 md.initialization.vel=DepthAverage(md,md.initialization.vel) 759 if not np.isnan(md.initialization.temperature).all(): 760 md.initialization.temperature=DepthAverage(md,md.initialization.temperature) 761 if not np.isnan(md.initialization.pressure).all(): 762 md.initialization.pressure=project2d(md,md.initialization.pressure,1) 763 if not np.isnan(md.initialization.sediment_head).all(): 764 md.initialization.sediment_head=project2d(md,md.initialization.sediment_head,1) 765 if not np.isnan(md.initialization.epl_head).all(): 766 md.initialization.epl_head=project2d(md,md.initialization.epl_head,1) 767 if not np.isnan(md.initialization.epl_thickness).all(): 768 md.initialization.epl_thickness=project2d(md,md.initialization.epl_thickness,1) 769 770 #giaivins 771 if not np.isnan(md.gia.mantle_viscosity).all(): 772 md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1) 773 if not np.isnan(md.gia.lithosphere_thickness).all(): 774 md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1) 594 775 595 776 #elementstype 596 if not n umpy.isnan(md.flowequation.element_equation).all():777 if not np.isnan(md.flowequation.element_equation).all(): 597 778 md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1) 598 779 md.flowequation.vertex_equation=project2d(md,md.flowequation.vertex_equation,1) … … 602 783 603 784 # Hydrologydc variables 604 if hasattr(md.hydrology,'hydrologydc'):785 if type(md.hydrology) is 'hydrologydc': 605 786 md.hydrology.spcsediment_head=project2d(md,md.hydrology.spcsediment_head,1) 606 md.hydrology.mask_eplactive_node=project2d(md,md.hydrology.mask_eplactive_node,1)607 787 md.hydrology.sediment_transmitivity=project2d(md,md.hydrology.sediment_transmitivity,1) 608 788 md.hydrology.basal_moulin_input=project2d(md,md.hydrology.basal_moulin_input,1) 789 md.hydrology.mask_thawed_node=project2d(md,md.hydrology.mask_thawed_node,1) 609 790 if md.hydrology.isefficientlayer == 1: 791 md.hydrology.mask_eplactive_node=project2d(md,md.hydrology.mask_eplactive_node,1) 610 792 md.hydrology.spcepl_head=project2d(md,md.hydrology.spcepl_head,1) 611 793 … … 617 799 md.stressbalance.loadingforce=project2d(md,md.stressbalance.loadingforce,md.mesh.numberoflayers) 618 800 md.masstransport.spcthickness=project2d(md,md.masstransport.spcthickness,md.mesh.numberoflayers) 619 if not numpy.isnan(md.damage.spcdamage).all(): md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers-1)620 801 md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers-1) 802 if not np.isnan(md.damage.spcdamage).all(): 803 md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers-1) 621 804 622 805 #materials 623 806 md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B) 624 807 md.materials.rheology_n=project2d(md,md.materials.rheology_n,1) 625 626 #damage: 808 809 #damage: 627 810 if md.damage.isdamage: 628 811 md.damage.D=DepthAverage(md,md.damage.D) 629 812 630 813 #special for thermal modeling: 631 md.basalforcings.groundedice_melting_rate=project2d(md,md.basalforcings.groundedice_melting_rate,1) 632 md.basalforcings.floatingice_melting_rate=project2d(md,md.basalforcings.floatingice_melting_rate,1) 814 md.basalforcings.groundedice_melting_rate=project2d(md,md.basalforcings.groundedice_melting_rate,1) 815 md.basalforcings.floatingice_melting_rate=project2d(md,md.basalforcings.floatingice_melting_rate,1) 633 816 md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1) #bedrock only gets geothermal flux 634 817 … … 644 827 md.geometry.thickness=project2d(md,md.geometry.thickness,1) 645 828 md.geometry.base=project2d(md,md.geometry.base,1) 646 if isinstance(md.geometry.bed,n umpy.ndarray):829 if isinstance(md.geometry.bed,np.ndarray): 647 830 md.geometry.bed=project2d(md,md.geometry.bed,1) 648 md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1) 649 md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1) 650 651 #lat long 652 if isinstance(md.mesh.lat,numpy.ndarray): 653 if md.mesh.lat.size==md.mesh.numberofvertices: md.mesh.lat=project2d(md,md.mesh.lat,1) 654 if isinstance(md.mesh.long,numpy.ndarray): 655 if md.mesh.long.size==md.mesh.numberofvertices: md.mesh.long=project2d(md,md.mesh.long,1) 831 md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1) 832 md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1) 833 834 #OutputDefinitions 835 if md.outputdefinition.definitions: 836 for solutionfield,field in md.outputdefinition.__dict__.items(): 837 if isinstance(field,list): 838 #get each definition 839 for i,fieldi in enumerate(field): 840 if fieldi: 841 fieldr=getattr(md.outputdefinition,solutionfield)[i] 842 #get subfields 843 for solutionsubfield,subfield in fieldi.__dict__.items(): 844 if np.size(subfield)==md.mesh.numberofvertices: 845 setattr(fieldr,solutionsubfield,project2d(md,subfield,1)) 846 elif np.size(subfield)==md.mesh.numberofelements: 847 setattr(fieldr,solutionsubfield,project2d(md,subfield,1)) 848 656 849 657 850 #Initialize with the 2d mesh … … 662 855 mesh.numberofelements=md.mesh.numberofelements2d 663 856 mesh.elements=md.mesh.elements2d 664 if not numpy.isnan(md.mesh.vertexonboundary).all(): mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1) 665 if not numpy.isnan(md.mesh.elementconnectivity).all(): mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1) 857 if not np.isnan(md.mesh.vertexonboundary).all(): 858 mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1) 859 if not np.isnan(md.mesh.elementconnectivity).all(): 860 mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1) 861 if isinstance(md.mesh.lat,np.ndarray): 862 if md.mesh.lat.size==md.mesh.numberofvertices: 863 mesh.lat=project2d(md,md.mesh.lat,1) 864 if isinstance(md.mesh.long,np.ndarray): 865 if md.mesh.long.size==md.mesh.numberofvertices: 866 md.mesh.long=project2d(md,md.mesh.long,1) 867 mesh.epsg=md.mesh.epsg 868 if isinstance(md.mesh.scale_factor,np.ndarray): 869 if md.mesh.scale_factor.size==md.mesh.numberofvertices: 870 md.mesh.scale_factor=project2d(md,md.mesh.scale_factor,1) 666 871 md.mesh=mesh 872 md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)[0] 873 md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)[0] 874 md.mesh.segments=contourenvelope(md) 667 875 668 876 return md -
issm/trunk-jpl/src/py3/classes/organizer.py
r19895 r23670 6 6 from savevars import savevars 7 7 from model import model 8 from dbm .ndbmimport whichdb8 from dbm import whichdb 9 9 import MatlabFuncs as m 10 10 … … 26 26 """ 27 27 28 def __init__(self,* *kwargs): # {{{28 def __init__(self,*args): # {{{ 29 29 self._currentstep =0 30 30 self.repository ='./' … … 35 35 36 36 #process options 37 options=pairoptions.pairoptions(* *kwargs)37 options=pairoptions.pairoptions(*args) 38 38 39 39 #Get prefix … … 86 86 if os.path.exists(path): 87 87 struc=loadvars(path) 88 name=name=[key for key in list(struc.keys())]88 name=name=[key for key in struc.keys()] 89 89 md=struc.name[0] 90 90 else: … … 98 98 if not isinstance(string,str): 99 99 raise TypeError("argument provided is not a string") 100 path1=os.path.join(self.repository,self.prefix+ '.step#'+string+'.python')100 path1=os.path.join(self.repository,self.prefix+string+'.python') 101 101 path2=os.path.join(self.repository,string) 102 102 … … 115 115 raise IOError("Could find neither '%s' nor '%s'" % (path,path2)) 116 116 else: 117 print( ("--> Branching '%s' from trunk '%s'" % (self.prefix,self.trunkprefix)))117 print("--> Branching '%s' from trunk '%s'" % (self.prefix,self.trunkprefix)) 118 118 md=loadmodel(path2) 119 119 return md … … 142 142 if 0 in self.requestedsteps: 143 143 if self._currentstep==1: 144 print( (" prefix: %s" % self.prefix))145 print( (" step #%i : %s" % (self.steps[self._currentstep-1]['id'],self.steps[self._currentstep-1]['string'])))144 print(" prefix: %s" % self.prefix) 145 print(" step #%i : %s" % (self.steps[self._currentstep-1]['id'],self.steps[self._currentstep-1]['string'])) 146 146 147 147 #Ok, now if _currentstep is a member of steps, return true 148 148 if self._currentstep in self.requestedsteps: 149 print( ("\n step #%i : %s\n" % (self.steps[self._currentstep-1]['id'],self.steps[self._currentstep-1]['string'])))149 print("\n step #%i : %s\n" % (self.steps[self._currentstep-1]['id'],self.steps[self._currentstep-1]['string'])) 150 150 bool=True 151 151 … … 164 164 165 165 if (name=='default'): 166 name=os.path.join(self.repository,self.prefix+ 'step#'+self.steps[self._currentstep-1]['string']+'.python')167 168 169 print( ("saving model as: '%s'" % name))166 name=os.path.join(self.repository,self.prefix+self.steps[self._currentstep-1]['string']+'.python') 167 else: 168 name=os.path.join(self.repository,name) 169 print("saving model as: '%s'" % name) 170 170 171 171 #check that md is a model -
issm/trunk-jpl/src/py3/classes/outputdefinition.py
r21255 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *3 from StringToEnum import StringToEnum4 2 from checkfield import checkfield 5 3 from WriteData import WriteData 6 import numpy as np4 import numpy as np 7 5 8 6 class outputdefinition(object): … … 24 22 return string 25 23 #}}} 24 def extrude(self,md): # {{{ 25 for definition in self.definitions: 26 definition.extrude(md); 27 28 return self 29 #}}} 26 30 def setdefaultparameters(self): # {{{ 27 31 return self … … 34 38 35 39 # }}} 36 def marshall(self,md,fid): # {{{ 37 38 enums=np.zeros(len(self.definitions),) 39 40 def marshall(self,prefix,md,fid): # {{{ 41 data=[]; 40 42 for i in range(len(self.definitions)): 41 self.definitions[i].marshall( md,fid);42 classdefinition=self.definitions[i].__class__.__name__ 43 self.definitions[i].marshall(prefix,md,fid); 44 classdefinition=self.definitions[i].__class__.__name__; 43 45 classdefinition=classdefinition[0].upper()+classdefinition[1:] 44 enums[i]=StringToEnum(classdefinition)[0] 45 46 enums=np.unique(enums); 47 48 WriteData(fid,'data',enums,'enum',OutputdefinitionListEnum(),'format','DoubleMat','mattype',1); 46 data.append(classdefinition) 47 48 data=np.unique(data); 49 WriteData(fid,prefix,'data',data,'name','md.outputdefinition.list','format','StringArray'); 49 50 # }}} -
issm/trunk-jpl/src/py3/classes/pairoptions.py
r19895 r23670 11 11 """ 12 12 13 def __init__(self,* *kwargs): # {{{13 def __init__(self,*arg): # {{{ 14 14 self.functionname = '' 15 15 self.list = OrderedDict() … … 21 21 22 22 #initialize list 23 if not len( kwargs):23 if not len(arg): 24 24 pass #Do nothing, 25 25 else: 26 self.buildlist(* *kwargs)26 self.buildlist(*arg) 27 27 # }}} 28 28 def __repr__(self): # {{{ … … 30 30 if self.list: 31 31 s+=" list: (%ix%i)\n\n" % (len(self.list),2) 32 for item in list(self.list.items()):32 for item in self.list.items(): 33 33 if isinstance(item[1],str): 34 34 s+=" field: %-10s value: '%s'\n" % (item[0],item[1]) … … 41 41 return s 42 42 # }}} 43 def buildlist(self,* *kwargs): # {{{43 def buildlist(self,*arg): # {{{ 44 44 """BUILDLIST - build list of objects from input""" 45 # #check length of input46 # if len(arg) % 2:47 # raise TypeError('Invalid parameter/value pair arguments')48 # numoptions = len(arg)/249 45 50 # #go through arg and build list of objects 51 # for i in xrange(numoptions): 52 # if isinstance(arg[2*i],(str,unicode)): 53 # self.list[arg[2*i]] = arg[2*i+1]; 54 # else: 55 # #option is not a string, ignore it 56 # print "WARNING: option number %d is not a string and will be ignored." % (i+1) 46 #check length of input 47 if len(arg) % 2: 48 raise TypeError('Invalid parameter/value pair arguments') 49 numoptions = len(arg)/2 57 50 58 51 #go through arg and build list of objects 59 print(kwargs) 60 for name,value in kwargs.items(): 61 self.list[name] = value 62 # }}} 52 for i in range(numoptions): 53 if isinstance(arg[2*i],str): 54 self.list[arg[2*i]] = arg[2*i+1]; 55 else: 56 #option is not a string, ignore it 57 print("WARNING: option number %d is not a string and will be ignored." % (i+1)) 58 # }}} 63 59 def addfield(self,field,value): # {{{ 64 60 """ADDFIELD - add a field to an options list""" 65 61 if isinstance(field,str): 66 62 if field in self.list: 67 print( ("WARNING: field '%s' with value=%s exists and will be overwritten with value=%s." % (field,str(self.list[field]),str(value))))63 print("WARNING: field '%s' with value=%s exists and will be overwritten with value=%s." % (field,str(self.list[field]),str(value))) 68 64 self.list[field] = value 69 65 # }}} … … 76 72 def AssignObjectFields(self,obj2): # {{{ 77 73 """ASSIGNOBJECTFIELDS - assign object fields from options""" 78 for item in list(self.list.items()):74 for item in self.list.items(): 79 75 if item[0] in dir(obj2): 80 76 setattr(obj2,item[0],item[1]) 81 77 else: 82 print( ("WARNING: field '%s' is not a property of '%s'." % (item[0],type(obj2))))78 print("WARNING: field '%s' is not a property of '%s'." % (item[0],type(obj2))) 83 79 return obj2 84 80 # }}} … … 154 150 #warn user if requested 155 151 if warn: 156 print( ("removefield info: option '%s' has been removed from the list of options." % field))152 print("removefield info: option '%s' has been removed from the list of options." % field) 157 153 # }}} 158 154 def marshall(self,md,fid,firstindex): # {{{ … … 162 158 value = item[1] 163 159 164 #Write option name 165 WriteData(fid,'enum',(firstindex-1)+2*i+1,'data',name,'format','String') 160 raise NameError('need to sync with MATLAB') 166 161 167 #Write option value 168 if isinstance(value,str): 169 WriteData(fid,'enum',(firstindex-1)+2*i+2,'data',value,'format','String') 170 elif isinstance(value,(bool,int,float)): 171 WriteData(fid,'enum',(firstindex-1)+2*i+2,'data',value,'format','Double') 172 else: 173 raise TypeError("Cannot marshall option '%s': format not supported yet." % name) 162 ##Write option name 163 #WriteData(fid,prefix,'enum',(firstindex-1)+2*i+1,'data',name,'format','String') 164 165 ##Write option value 166 #if isinstance(value,(str,unicode)): 167 # WriteData(fid,prefix,'enum',(firstindex-1)+2*i+2,'data',value,'format','String') 168 #elif isinstance(value,(bool,int,long,float)): 169 # WriteData(fid,prefix,'enum',(firstindex-1)+2*i+2,'data',value,'format','Double') 170 #else: 171 #raise TypeError("Cannot marshall option '%s': format not supported yet." % name) 174 172 # }}} -
issm/trunk-jpl/src/py3/classes/plotoptions.py
r19895 r23670 7 7 8 8 Usage: 9 plotoptions=plotoptions(* *kwargs)9 plotoptions=plotoptions(*arg) 10 10 ''' 11 11 12 def __init__(self,* *kwargs):# {{{12 def __init__(self,*arg):# {{{ 13 13 self.numberofplots = 0 14 14 self.figurenumber = 1 15 15 self.list = OrderedDict() 16 16 17 self.buildlist(* *kwargs)17 self.buildlist(*arg) 18 18 #}}} 19 19 def __repr__(self): #{{{ … … 23 23 if self.list: 24 24 s+=" list: (%ix%i)\n" % (len(self.list),2) 25 for item in list(self.list.items()):25 for item in self.list.items(): 26 26 #s+=" options of plot number %i\n" % item 27 27 if isinstance(item[1],str): … … 35 35 return s 36 36 #}}} 37 def buildlist(self,**kwargs): #{{{ 37 def buildlist(self,*arg): #{{{ 38 #check length of input 39 if len(arg) % 2: 40 raise TypeError('Invalid parameter/value pair arguments') 38 41 39 for name,value in kwargs.items(): 40 self.rawlist[name] = value 42 #go through args and build list (like pairoptions) 43 rawoptions=pairoptions.pairoptions(*arg) 44 numoptions=len(arg)/2 45 rawlist=[] # cannot be a dict since they do not support duplicate keys 41 46 42 #get figure number 47 for i in range(numoptions): 48 if isinstance(arg[2*i],str): 49 rawlist.append([arg[2*i],arg[2*i+1]]) 50 else: 51 #option is not a string, ignore it 52 print("WARNING: option number %d is not a string and will be ignored." % (i+1)) 53 54 #get figure number 43 55 self.figurenumber=rawoptions.getfieldvalue('figure',1) 44 56 rawoptions.removefield('figure',0) 45 57 46 #get number of subplots 47 numberofplots= Counter(x for sublist in rawlist for x in sublist if isinstance(x,str))['data']58 #get number of subplots 59 numberofplots=len([1 for sublist in rawlist for x in sublist if str(x)=='data']) 48 60 self.numberofplots=numberofplots 49 61 … … 64 76 #if alloptions flag is on, apply to all plots 65 77 if (allflag and 'data' not in rawlist[i][0] and '#' not in rawlist[i][0]): 66 78 67 79 for j in range(numberofplots): 68 80 self.list[j].addfield(rawlist[i][0],rawlist[i][1]) … … 94 106 raise ValueError('error: in option i-j both i and j must be integers') 95 107 for j in range(int(nums[0])-1,int(nums[1])): 96 self.list[j].addfield(field,rawlist[i][1]) 108 self.list[j].addfield(field,rawlist[i][1]) 97 109 98 110 # Deal with #i … … 103 115 self.list[int(plotnum)-1].addfield(field,rawlist[i][1]) 104 116 else: 105 117 106 118 #go through all subplots and assign key-value pairs 107 119 j=0 … … 113 125 j=j+1 114 126 if j+1>numberofplots: 115 print( ("WARNING: too many instances of '%s' in options" % rawlist[i][0]))127 print("WARNING: too many instances of '%s' in options" % rawlist[i][0]) 116 128 #}}} -
issm/trunk-jpl/src/py3/classes/private.py
r19895 r23670 1 1 from collections import OrderedDict 2 2 from fielddisplay import fielddisplay 3 from EnumDefinitions import *4 3 from checkfield import checkfield 5 4 … … 20 19 #set defaults 21 20 self.setdefaultparameters() 21 22 22 #}}} 23 23 def __repr__(self): # {{{ -
issm/trunk-jpl/src/py3/classes/qmu.py
r19895 r23670 1 import numpy 1 import numpy as np 2 from MatlabFuncs import * 3 from IssmConfig import * 2 4 from project3d import project3d 3 5 from collections import OrderedDict 4 6 from fielddisplay import fielddisplay 5 from EnumDefinitions import *6 7 from checkfield import checkfield 7 8 from WriteData import WriteData 8 import MatlabFuncs as m 9 from helpers import * 10 from dakota_method import * 9 11 10 12 class qmu(object): … … 18 20 def __init__(self): # {{{ 19 21 self.isdakota = 0 20 self.variables = Ordered Dict()21 self.responses = Ordered Dict()22 self.variables = OrderedStruct() 23 self.responses = OrderedStruct() 22 24 self.method = OrderedDict() 23 self.params = Ordered Dict()25 self.params = OrderedStruct() 24 26 self.results = OrderedDict() 25 27 self.partition = float('NaN') … … 42 44 43 45 s+="%s\n" % fielddisplay(self,'isdakota','is qmu analysis activated?') 44 for i,variable in enumerate(self.variables.items()): 45 s+=" variables%s: (arrays of each variable class)\n" % \ 46 string_dim(self.variables,i) 47 fnames=vars(variable) 48 maxlen=0 49 for fname in fnames: 50 maxlen=max(maxlen,len(fname)) 46 maxlen = 0 47 s+=" variables: (arrays of each variable class)\n" 51 48 52 for fname in fnames: 53 s+="' %-*s: [%ix%i] '%s'\n" % \ 54 (maxlen+1,fname,size(getattr(variable,fname)),type(getattr(variable,fname))) 49 # OrderedStruct's iterator returns individual name/array-of-functions pairs 50 for variable in self.variables: 51 fname=variable[0] 52 maxlen=max(maxlen,len(fname)) 53 size = np.shape(variable[1]) 54 a = size[0] 55 b = 1 if len(size) < 2 else size[1] 56 s+=" %-*s: [%ix%i] '%s'\n" % (maxlen+1,fname,a,b,type(variable[1][0])) 55 57 56 for i,response in enumerate(self.responses.items()): 57 s+=" responses%s: (arrays of each response class)\n" % \ 58 string_dim(self.responses,i) 59 fnames=vars(response) 60 maxlen=0 61 for fname in fnames: 62 maxlen=max(maxlen,len(fname)) 58 s+=" responses: (arrays of each response class)\n" 59 for response in self.responses: 60 fname=response[0] 61 maxlen=max(maxlen,len(fname)) 62 size = np.shape(response[1]) 63 a = size[0] 64 b = 1 if len(size) < 2 else size[1] 65 s+=" %-*s: [%ix%i] '%s'\n" % (maxlen+1,fname,a,b,type(response[1][0])) 63 66 64 for fname in fnames: 65 s+=" %-*s: [%ix%i] '%s'\n" % \ 66 (maxlen+1,fname,size(getattr(response,fname)),type(getattr(response,fname))) 67 s+="%s\n" % fielddisplay(self,'numberofresponses','number of responses') 67 68 68 s+="%s\n" % fielddisplay(self,'numberofresponses','number of responses') 69 if type(self.method) != OrderedDict: 70 self.method = [self.method] 71 # self.method must be iterable 72 for method in self.method: 73 if isinstance(method,dakota_method): 74 s+=" method : '%s'\n" % (method.method) 69 75 70 for i,method in enumerate(self.method.items()): 71 if isinstance(method,'dakota_method'): 72 s+=" method%s : '%s'\n" % \ 73 (string_dim(method,i),method.method) 74 75 for i,param in enumerate(self.params.items()): 76 s+=" params%s: (array of method-independent parameters)\n" % \ 77 string_dim(self.params,i) 76 # params could be have a number of forms (mainly 1 struct or many) 77 if type(self.params) == OrderedStruct: 78 params = [self.params] 79 else: 80 params = np.hstack(np.atleast_1d(np.array(self.params))) 81 for param in params: 82 print(type(param)) 83 print(param) 84 s+=" params: (array of method-independent parameters)\n" 78 85 fnames=vars(param) 79 86 maxlen=0 … … 82 89 83 90 for fname in fnames: 84 s+=" %-*s: %s\n" % \ 85 (maxlen+1,fname,any2str(getattr(param,fname))) 91 s+=" %-*s: %s\n" % (maxlen+1,fname,str(getattr(param,fname))) 86 92 87 for i,result in enumerate(self.results.items()): 88 s+=" results%s: (information from dakota files)\n" % \ 89 string_dim(self.results,i) 93 # results could be have a number of forms (mainly 1 struct or many) 94 results = np.hstack(np.atleast_1d(np.array(self.results))) 95 for result in results: 96 s+=" results: (information from dakota files)\n" 90 97 fnames=vars(result) 91 98 maxlen=0 … … 94 101 95 102 for fname in fnames: 96 s+=" %-*s: [%ix%i] '%s'\n" % \ 97 (maxlen+1,fname,size(getattr(result,fname)),type(getattr(result,fname))) 103 size = np.shape(response[1]) 104 a = size[0] 105 b = 0 if len(size) < 2 else size[1] 106 size = np.shape(getattr(result,fname)) 107 s+=" %-*s: [%ix%i] '%s'\n" % (maxlen+1,fname,a,b,type(getattr(result,fname))) 98 108 99 109 s+="%s\n" % fielddisplay(self,'partition','user provided mesh partitioning, defaults to metis if not specified') … … 111 121 # }}} 112 122 def extrude(self,md): # {{{ 113 self.partition=project3d(md,'vector',n umpy.transpose(self.partition),'type','node')123 self.partition=project3d(md,'vector',np.transpose(self.partition),'type','node') 114 124 return self 115 125 #}}} … … 123 133 return 124 134 125 if not md.qmu.params.evaluation_concurrency==1: 126 md.checkmessage("concurrency should be set to 1 when running dakota in library mode") 127 if md.qmu.partition: 128 if not numpy.size(md.qmu.partition)==md.mesh.numberofvertices: 129 md.checkmessage("user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1") 130 if not min(md.qmu.partition)==0: 135 version=IssmConfig('_DAKOTA_VERSION_') 136 version=float(version[0]) 137 138 if version < 6: 139 if not md.qmu.params.evaluation_concurrency==1: 140 md.checkmessage("concurrency should be set to 1 when running dakota in library mode") 141 else: 142 if not strcmpi(self.params.evaluation_scheduling,'master'): 143 md.checkmessage('evaluation_scheduling in qmu.params should be set to "master"') 144 145 if md.cluster.np <= 1: 146 md.checkmessage('in parallel library mode, Dakota needs to run on at least 2 cpus, 1 cpu for the master, 1 cpu for the slave. Modify md.cluser.np accordingly.') 147 148 if self.params.processors_per_evaluation < 1: 149 md.checkmessage('in parallel library mode, Dakota needs to run at least one slave on one cpu (md.qmu.params.processors_per_evaluation >=1)!') 150 151 if np.mod(md.cluster.np-1,self.params.processors_per_evaluation): 152 md.checkmessage('in parallel library mode, the requirement is for md.cluster.np = md.qmu.params.processors_per_evaluation * number_of_slaves, where number_of_slaves will automatically be determined by Dakota. Modify md.cluster.np accordingly') 153 154 if np.size(md.qmu.partition) > 0: 155 if np.size(md.qmu.partition)!=md.mesh.numberofvertices and np.size(md.qmu.partition) != md.mesh.numberofelements: 156 md.checkmessage("user supplied partition for qmu analysis should have size (md.mesh.numberofvertices x 1) or (md.mesh.numberofelements x 1)") 157 if not min(md.qmu.partition.flatten())==0: 131 158 md.checkmessage("partition vector not indexed from 0 on") 132 if max(md.qmu.partition )>=md.qmu.numberofpartitions:159 if max(md.qmu.partition.flatten())>=md.qmu.numberofpartitions: 133 160 md.checkmessage("for qmu analysis, partitioning vector cannot go over npart, number of partition areas") 134 135 if not m.strcmpi(md.cluster.name,'none'):136 if not md.settings.waitonlock:137 md.checkmessage("waitonlock should be activated when running qmu in parallel mode!")138 161 139 162 return md 140 163 # }}} 141 def marshall(self, md,fid): # {{{142 WriteData(fid, 'object',self,'fieldname','isdakota','format','Boolean')164 def marshall(self,prefix,md,fid): # {{{ 165 WriteData(fid,prefix,'object',self,'fieldname','isdakota','format','Boolean') 143 166 if not self.isdakota: 144 WriteData(fid, 'data',False,'enum',QmuMassFluxSegmentsPresentEnum(),'format','Boolean');167 WriteData(fid,prefix,'data',False,'name','md.qmu.mass_flux_segments_present','format','Boolean'); 145 168 return 146 WriteData(fid, 'object',self,'fieldname','partition','format','DoubleMat','mattype',2)147 WriteData(fid, 'object',self,'fieldname','numberofpartitions','format','Integer')148 WriteData(fid, 'object',self,'fieldname','numberofresponses','format','Integer')149 WriteData(fid, 'object',self,'fieldname','variabledescriptors','format','StringArray')150 WriteData(fid, 'object',self,'fieldname','responsedescriptors','format','StringArray')151 if not self.mass_flux_segments:152 WriteData(fid, 'data',self.mass_flux_segments,'enum',MassFluxSegmentsEnum(),'format','MatArray');169 WriteData(fid,prefix,'object',self,'fieldname','partition','format','DoubleMat','mattype',2) 170 WriteData(fid,prefix,'object',self,'fieldname','numberofpartitions','format','Integer') 171 WriteData(fid,prefix,'object',self,'fieldname','numberofresponses','format','Integer') 172 WriteData(fid,prefix,'object',self,'fieldname','variabledescriptors','format','StringArray') 173 WriteData(fid,prefix,'object',self,'fieldname','responsedescriptors','format','StringArray') 174 if not isempty(self.mass_flux_segments): 175 WriteData(fid,prefix,'data',self.mass_flux_segments,'name','md.qmu.mass_flux_segments','format','MatArray'); 153 176 flag=True; 154 177 else: 155 178 flag=False; 156 WriteData(fid, 'data',flag,'enum',QmuMassFluxSegmentsPresentEnum(),'format','Boolean');179 WriteData(fid,prefix,'data',flag,'name','md.qmu.mass_flux_segments_present','format','Boolean'); 157 180 # }}} -
issm/trunk-jpl/src/py3/classes/results.py
r19895 r23670 1 import numpy 1 import numpy as np 2 from pairoptions import pairoptions 2 3 from fielddisplay import fielddisplay 3 4 import MatlabFuncs as m 4 from EnumDefinitions import *5 5 6 6 class results(object): … … 12 12 """ 13 13 14 def __init__(self ): # {{{14 def __init__(self,*args): # {{{ 15 15 pass 16 16 # }}} … … 25 25 s+="%s\n" % fielddisplay(self,'SolutionType',"solution type") 26 26 27 for name in list(self.__dict__.keys()):27 for name in self.__dict__.keys(): 28 28 if name not in ['step','time','SolutionType','errlog','outlog']: 29 29 if isinstance(getattr(self,name),list): … … 48 48 return md 49 49 # }}} 50 def marshall(self, md,fid): # {{{50 def marshall(self,prefix,md,fid): # {{{ 51 51 pass 52 52 # }}} -
issm/trunk-jpl/src/py3/classes/rifts.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from fielddisplay import fielddisplay 3 from EnumDefinitions import *4 3 from checkfield import checkfield 5 4 from WriteData import WriteData … … 34 33 #}}} 35 34 def checkconsistency(self,md,solution,analyses): # {{{ 36 if (not self.riftstruct) or n umpy.any(isnans(self.riftstruct)):35 if (not self.riftstruct) or np.any(isnans(self.riftstruct)): 37 36 numrifts=0 38 37 else: … … 44 43 if not isinstance(self.riftstruct,list): 45 44 md.checkmessage("rifts.riftstruct should be a structure!") 46 if n umpy.any(md.mesh.segmentmarkers>=2):45 if np.any(md.mesh.segmentmarkers>=2): 47 46 #We have segments with rift markers, but no rift structure! 48 47 md.checkmessage("model should be processed for rifts (run meshprocessrifts)!") 49 48 for i,rift in enumerate(self.riftstruct): 50 md = checkfield(md,'fieldname',"rifts.riftstruct[%d]['fill']" % i,'values',[ WaterEnum(),AirEnum(),IceEnum(),MelangeEnum()])49 md = checkfield(md,'fieldname',"rifts.riftstruct[%d]['fill']" % i,'values',['Water','Air','Ice','Melange',0,1,2,3]) 51 50 else: 52 if self.riftstruct and n umpy.any(numpy.logical_not(isnans(self.riftstruct))):51 if self.riftstruct and np.any(np.logical_not(isnans(self.riftstruct))): 53 52 md.checkmessage("riftstruct should be NaN since numrifts is 0!") 54 53 55 54 return md 56 55 # }}} 57 def marshall(self, md,fid): # {{{56 def marshall(self,prefix,md,fid): # {{{ 58 57 59 58 #Process rift info 60 if (not self.riftstruct) or n umpy.any(isnans(self.riftstruct)):59 if (not self.riftstruct) or np.any(isnans(self.riftstruct)): 61 60 numrifts=0 62 61 else: … … 65 64 numpairs=0 66 65 for rift in self.riftstruct: 67 numpairs+=numpy.size(rift['penaltypairs'],axis=0) 66 numpairs+=np.size(rift['penaltypairs'],axis=0) 67 68 # Convert strings in riftstruct to hard coded numbers 69 FillDict={'Air':0, 70 'Ice':1, 71 'Melange':2, 72 'Water':3} 73 for rift in self.riftstruct: 74 if rift['fill'] in ['Air','Ice','Melange','Water']: 75 rift['fill'] = FillDict[rift['fill']] 68 76 69 77 # 2 for nodes + 2 for elements+ 2 for normals + 1 for length + 1 for fill + 1 for friction + 1 for fraction + 1 for fractionincrement + 1 for state. 70 data=n umpy.zeros((numpairs,12))78 data=np.zeros((numpairs,12)) 71 79 count=0 72 80 for rift in self.riftstruct: 73 numpairsforthisrift=n umpy.size(rift['penaltypairs'],0)81 numpairsforthisrift=np.size(rift['penaltypairs'],0) 74 82 data[count:count+numpairsforthisrift,0:7]=rift['penaltypairs'] 75 83 data[count:count+numpairsforthisrift,7]=rift['fill'] … … 80 88 count+=numpairsforthisrift 81 89 82 WriteData(fid, 'data',numrifts,'enum',RiftsNumriftsEnum(),'format','Integer')83 WriteData(fid, 'data',data,'enum',RiftsRiftstructEnum(),'format','DoubleMat','mattype',3)90 WriteData(fid,prefix,'data',numrifts,'name','md.rifts.numrifts','format','Integer') 91 WriteData(fid,prefix,'data',data,'name','md.rifts.riftstruct','format','DoubleMat','mattype',3) 84 92 # }}} -
issm/trunk-jpl/src/py3/classes/steadystate.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from fielddisplay import fielddisplay 3 from EnumDefinitions import *4 3 from checkfield import checkfield 5 4 from WriteData import WriteData … … 49 48 50 49 #Early return 51 if not solution== SteadystateSolutionEnum():50 if not solution=='SteadystateSolution': 52 51 return md 53 52 … … 55 54 md.checkmessage("for a steadystate computation, timestepping.time_step must be zero.") 56 55 57 if n umpy.isnan(md.stressbalance.reltol):56 if np.isnan(md.stressbalance.reltol): 58 57 md.checkmessage("for a steadystate computation, stressbalance.reltol (relative convergence criterion) must be defined!") 59 58 … … 62 61 return md 63 62 # }}} 64 def marshall(self, md,fid): # {{{65 WriteData(fid, 'object',self,'fieldname','reltol','format','Double')66 WriteData(fid, 'object',self,'fieldname','maxiter','format','Integer')63 def marshall(self,prefix,md,fid): # {{{ 64 WriteData(fid,prefix,'object',self,'fieldname','reltol','format','Double') 65 WriteData(fid,prefix,'object',self,'fieldname','maxiter','format','Integer') 67 66 68 67 #process requested outputs … … 72 71 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 73 72 outputs =outputscopy 74 WriteData(fid, 'data',outputs,'enum',SteadystateRequestedOutputsEnum(),'format','StringArray')73 WriteData(fid,prefix,'data',outputs,'name','md.steadystate.requested_outputs','format','StringArray') 75 74 # }}} -
issm/trunk-jpl/src/py3/classes/stressbalance.py
r22576 r23670 1 import numpy 1 import numpy as np 2 2 import sys 3 3 import copy 4 4 from project3d import project3d 5 5 from fielddisplay import fielddisplay 6 from EnumDefinitions import *7 6 from checkfield import checkfield 8 7 from WriteData import WriteData … … 123 122 124 123 #Early return 125 if StressbalanceAnalysisEnum()not in analyses:124 if 'StressbalanceAnalysis' not in analyses: 126 125 return md 127 126 … … 142 141 #singular solution 143 142 # if ~any((~isnan(md.stressbalance.spcvx)+~isnan(md.stressbalance.spcvy))==2), 144 if not n umpy.any(numpy.logical_and(numpy.logical_not(numpy.isnan(md.stressbalance.spcvx)),numpy.logical_not(numpy.isnan(md.stressbalance.spcvy)))):143 if not np.any(np.logical_and(np.logical_not(np.isnan(md.stressbalance.spcvx)),np.logical_not(np.isnan(md.stressbalance.spcvy)))): 145 144 print("\n !!! Warning: no spc applied, model might not be well posed if no basal friction is applied, check for solution crash\n") 146 145 #CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES 147 146 # if any(sum(isnan(md.stressbalance.referential),2)~=0 & sum(isnan(md.stressbalance.referential),2)~=6), 148 if n umpy.any(numpy.logical_and(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)!=0,numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)!=6)):147 if np.any(np.logical_and(np.sum(np.isnan(md.stressbalance.referential),axis=1)!=0,np.sum(np.isnan(md.stressbalance.referential),axis=1)!=6)): 149 148 md.checkmessage("Each line of stressbalance.referential should contain either only NaN values or no NaN values") 150 149 #CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL 151 150 # if any(sum(isnan(md.stressbalance.referential),2)==0), 152 if n umpy.any(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)==0):153 pos=[i for i,item in enumerate(n umpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)) if item==0]154 # n umpy.inner (and numpy.dot) calculate all the dot product permutations, resulting in a full matrix multiply155 # if n umpy.any(numpy.abs(numpy.inner(md.stressbalance.referential[pos,0:2],md.stressbalance.referential[pos,3:5]).diagonal())>sys.float_info.epsilon):151 if np.any(np.sum(np.isnan(md.stressbalance.referential),axis=1)==0): 152 pos=[i for i,item in enumerate(np.sum(np.isnan(md.stressbalance.referential),axis=1)) if item==0] 153 # np.inner (and np.dot) calculate all the dot product permutations, resulting in a full matrix multiply 154 # if np.any(np.abs(np.inner(md.stressbalance.referential[pos,0:2],md.stressbalance.referential[pos,3:5]).diagonal())>sys.float_info.epsilon): 156 155 # md.checkmessage("Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal") 157 156 for item in md.stressbalance.referential[pos,:]: 158 if n umpy.abs(numpy.inner(item[0:2],item[3:5]))>sys.float_info.epsilon:157 if np.abs(np.inner(item[0:2],item[3:5]))>sys.float_info.epsilon: 159 158 md.checkmessage("Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal") 160 159 #CHECK THAT NO rotation specified for FS Grounded ice at base 161 160 if m.strcmp(md.mesh.domaintype(),'3D') and md.flowequation.isFS: 162 pos=n umpy.nonzero(numpy.logical_and(md.mask.groundedice_levelset,md.mesh.vertexonbase))163 if n umpy.any(numpy.logical_not(numpy.isnan(md.stressbalance.referential[pos,:]))):161 pos=np.nonzero(np.logical_and(md.mask.groundedice_levelset,md.mesh.vertexonbase)) 162 if np.any(np.logical_not(np.isnan(md.stressbalance.referential[pos,:]))): 164 163 md.checkmessage("no referential should be specified for basal vertices of grounded ice") 165 164 166 165 return md 167 166 # }}} 168 def marshall(self,md,fid): # {{{ 169 170 yts=365.0*24.0*3600.0 171 172 WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1) 173 WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1) 174 WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1) 175 WriteData(fid,'object',self,'class','stressbalance','fieldname','restol','format','Double') 176 WriteData(fid,'object',self,'class','stressbalance','fieldname','reltol','format','Double') 177 WriteData(fid,'object',self,'class','stressbalance','fieldname','abstol','format','Double','scale',1./yts) 178 WriteData(fid,'object',self,'class','stressbalance','fieldname','isnewton','format','Integer') 179 WriteData(fid,'object',self,'class','stressbalance','fieldname','FSreconditioning','format','Double') 180 WriteData(fid,'object',self,'class','stressbalance','fieldname','maxiter','format','Integer') 181 WriteData(fid,'object',self,'class','stressbalance','fieldname','shelf_dampening','format','Integer') 182 WriteData(fid,'object',self,'class','stressbalance','fieldname','vertex_pairing','format','DoubleMat','mattype',3) 183 WriteData(fid,'object',self,'class','stressbalance','fieldname','penalty_factor','format','Double') 184 WriteData(fid,'object',self,'class','stressbalance','fieldname','rift_penalty_lock','format','Integer') 185 WriteData(fid,'object',self,'class','stressbalance','fieldname','rift_penalty_threshold','format','Integer') 186 WriteData(fid,'object',self,'class','stressbalance','fieldname','referential','format','DoubleMat','mattype',1) 187 188 WriteData(fid,'data',self.loadingforce[:,0],'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum()) 189 WriteData(fid,'data',self.loadingforce[:,1],'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum()) 190 WriteData(fid,'data',self.loadingforce[:,2],'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum()) 167 def marshall(self,prefix,md,fid): # {{{ 168 169 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','vertex_pairing','format','DoubleMat','mattype',3) 170 171 yts=md.constants.yts 172 173 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 174 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 175 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 176 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','restol','format','Double') 177 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','reltol','format','Double') 178 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','abstol','format','Double','scale',1./yts) 179 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','isnewton','format','Integer') 180 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','FSreconditioning','format','Double') 181 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','maxiter','format','Integer') 182 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','shelf_dampening','format','Integer') 183 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','penalty_factor','format','Double') 184 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','rift_penalty_lock','format','Integer') 185 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','rift_penalty_threshold','format','Integer') 186 WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','referential','format','DoubleMat','mattype',1) 187 188 if isinstance(self.loadingforce, (list, tuple, np.ndarray)) and np.size(self.loadingforce,1) == 3: 189 WriteData(fid,prefix,'data',self.loadingforce[:,0],'format','DoubleMat','mattype',1,'name','md.stressbalance.loadingforcex') 190 WriteData(fid,prefix,'data',self.loadingforce[:,1],'format','DoubleMat','mattype',1,'name','md.stressbalance.loadingforcey') 191 WriteData(fid,prefix,'data',self.loadingforce[:,2],'format','DoubleMat','mattype',1,'name','md.stressbalance.loadingforcez') 191 192 192 193 #process requested outputs … … 196 197 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 197 198 outputs =outputscopy 198 WriteData(fid, 'data',outputs,'enum',StressbalanceRequestedOutputsEnum(),'format','StringArray')199 WriteData(fid,prefix,'data',outputs,'name','md.stressbalance.requested_outputs','format','StringArray') 199 200 # }}} -
issm/trunk-jpl/src/py3/classes/taoinversion.py
r19898 r23670 1 import numpy 1 import numpy as np 2 2 from project3d import project3d 3 3 from WriteData import WriteData … … 5 5 from fielddisplay import fielddisplay 6 6 from IssmConfig import IssmConfig 7 from EnumDefinitions import *8 7 from marshallcostfunctions import marshallcostfunctions 8 from supportedcontrols import * 9 from supportedcostfunctions import * 9 10 10 11 class taoinversion: 11 class taoinversion(object): 12 12 def __init__(self): 13 iscontrol = 0 14 incomplete_adjoint = 0 15 control_parameters = float('NaN') 16 maxsteps = 0 17 maxiter = 0 18 fatol = 0 19 frtol = 0 20 gatol = 0 21 grtol = 0 22 gttol = 0 23 algorithm = '' 24 cost_functions = float('NaN') 25 cost_functions_coefficients = float('NaN') 26 min_parameters = float('NaN') 27 max_parameters = float('NaN') 28 vx_obs = float('NaN') 29 vy_obs = float('NaN') 30 vz_obs = float('NaN') 31 vel_obs = float('NaN') 32 thickness_obs = float('NaN') 33 surface_obs = float('NaN') 13 self.iscontrol = 0 14 self.incomplete_adjoint = 0 15 self.control_parameters = float('NaN') 16 self.maxsteps = 0 17 self.maxiter = 0 18 self.fatol = 0 19 self.frtol = 0 20 self.gatol = 0 21 self.grtol = 0 22 self.gttol = 0 23 self.algorithm = '' 24 self.cost_functions = float('NaN') 25 self.cost_functions_coefficients = float('NaN') 26 self.min_parameters = float('NaN') 27 self.max_parameters = float('NaN') 28 self.vx_obs = float('NaN') 29 self.vy_obs = float('NaN') 30 self.vz_obs = float('NaN') 31 self.vel_obs = float('NaN') 32 self.thickness_obs = float('NaN') 33 self.surface_obs = float('NaN') 34 self.setdefaultparameters() 34 35 35 36 def __repr__(self): … … 90 91 91 92 #minimization algorithm 92 PETSCMAJOR = IssmConfig('_PETSC_MAJOR_') 93 PETSCMINOR = IssmConfig('_PETSC_MINOR_') 93 PETSCMAJOR = IssmConfig('_PETSC_MAJOR_')[0] 94 PETSCMINOR = IssmConfig('_PETSC_MINOR_')[0] 94 95 if(PETSCMAJOR>3 or (PETSCMAJOR==3 and PETSCMINOR>=5)): 95 96 self.algorithm = 'blmvm'; 96 97 else: 97 98 self.algorithm = 'tao_blmvm'; 98 99 99 100 #several responses can be used: 100 101 self.cost_functions=101; 101 102 102 return self 103 103 … … 110 110 if numel(self.cost_functions_coefficients) > 1: 111 111 self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node') 112 112 113 113 if numel(self.min_parameters) > 1: 114 114 self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node') 115 115 116 116 if numel(self.max_parameters)>1: 117 117 self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node') … … 120 120 121 121 def checkconsistency(self,md,solution,analyses): 122 if not self. control:122 if not self.iscontrol: 123 123 return md 124 if not IssmConfig('_HAVE_TAO_') :125 md = checkmessage(md,['TAO has not been installed, ISSM needs to be reconfigured and recompiled with TAO'])124 if not IssmConfig('_HAVE_TAO_')[0]: 125 md = md.checkmessage('TAO has not been installed, ISSM needs to be reconfigured and recompiled with TAO') 126 126 127 127 128 num_controls= n umpy.numel(md.inversion.control_parameters)129 num_costfunc= n umpy.size(md.inversion.cost_functions,2)128 num_controls= np.size(md.inversion.control_parameters) 129 num_costfunc= np.size(md.inversion.cost_functions) 130 130 131 131 md = checkfield(md,'fieldname','inversion.iscontrol','values',[0, 1]) 132 md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0, 132 md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0,1]) 133 133 md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',supportedcontrols()) 134 134 md = checkfield(md,'fieldname','inversion.maxsteps','numel',1,'>=',0) … … 141 141 142 142 143 PETSCMAJOR = IssmConfig('_PETSC_MAJOR_') 144 PETSCMINOR = IssmConfig('_PETSC_MINOR_') 143 PETSCMAJOR = IssmConfig('_PETSC_MAJOR_')[0] 144 PETSCMINOR = IssmConfig('_PETSC_MINOR_')[0] 145 145 if(PETSCMAJOR>3 or (PETSCMAJOR==3 and PETSCMINOR>=5)): 146 md = checkfield(md,'fieldname','inversion.algorithm','values', {'blmvm','cg','lmvm'})146 md = checkfield(md,'fieldname','inversion.algorithm','values',['blmvm','cg','lmvm']) 147 147 else: 148 md = checkfield(md,'fieldname','inversion.algorithm','values', {'tao_blmvm','tao_cg','tao_lmvm'})148 md = checkfield(md,'fieldname','inversion.algorithm','values',['tao_blmvm','tao_cg','tao_lmvm']) 149 149 150 150 151 md = checkfield(md,'fieldname','inversion.cost_functions','size', [1,num_costfunc],'values',supportedcostfunctions())151 md = checkfield(md,'fieldname','inversion.cost_functions','size', [num_costfunc],'values',supportedcostfunctions()) 152 152 md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices, num_costfunc],'>=',0) 153 153 md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices, num_controls]) … … 155 155 156 156 157 if solution== BalancethicknessSolutionEnum():158 md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices , 1],'NaN',1,'Inf',1)159 elif solution== BalancethicknessSoftSolutionEnum():160 md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices , 1],'NaN',1,'Inf',1)157 if solution=='BalancethicknessSolution': 158 md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 159 elif solution=='BalancethicknessSoftSolution': 160 md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 161 161 else: 162 md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices , 1],'NaN',1,'Inf',1)163 md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices , 1],'NaN',1,'Inf',1)162 md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 163 md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1) 164 164 165 def marshall(self, md,fid):165 def marshall(self,prefix,md,fid): 166 166 167 yts=365.0*24.0*3600.0;168 WriteData(fid,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean')169 WriteData(fid,'enum',InversionTypeEnum(),'data',1,'format','Integer')170 171 172 WriteData(fid,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean')173 WriteData(fid,'object',self,'class','inversion','fieldname','maxsteps','format','Integer')174 WriteData(fid,'object',self,'class','inversion','fieldname','maxiter','format','Integer')175 WriteData(fid,'object',self,'class','inversion','fieldname','fatol','format','Double')176 WriteData(fid,'object',self,'class','inversion','fieldname','frtol','format','Double')177 WriteData(fid,'object',self,'class','inversion','fieldname','gatol','format','Double')178 WriteData(fid,'object',self,'class','inversion','fieldname','grtol','format','Double')179 WriteData(fid,'object',self,'class','inversion','fieldname','gttol','format','Double')180 WriteData(fid,'object',self,'class','inversion','fieldname','algorithm','format','String')181 WriteData(fid,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)182 WriteData(fid,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3)183 WriteData(fid,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3)184 WriteData(fid,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)185 WriteData(fid,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)186 WriteData(fid,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)187 WriteData(fid,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1)188 WriteData(fid,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',1)167 yts=md.constants.yts; 168 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean') 169 WriteData(fid,prefix,'name','md.inversion.type','data',1,'format','Integer') 170 if not self.iscontrol: 171 return 172 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean') 173 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxsteps','format','Integer') 174 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxiter','format','Integer') 175 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','fatol','format','Double') 176 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','frtol','format','Double') 177 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gatol','format','Double') 178 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','grtol','format','Double') 179 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gttol','format','Double') 180 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','algorithm','format','String') 181 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1) 182 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3) 183 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3) 184 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts) 185 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts) 186 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts) 187 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1) 188 WriteData(fid,prefix,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',1) 189 189 190 #process control parameters 191 num_control_parameters = numpy.numel(self.control_parameters) 192 data = numpy.array([StringToEnum(self.control_parameter[0]) for control_parameter in self.control_parameters]).reshape(1,-1) 193 WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3) 194 WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer') 190 #process control parameters 191 num_control_parameters = np.size(self.control_parameters) 192 WriteData(fid,prefix,'object',self,'fieldname','control_parameters','format','StringArray') 193 WriteData(fid,prefix,'data',num_control_parameters,'name','md.inversion.num_control_parameters','format','Integer') 195 194 196 197 num_cost_functions = numpy.size(self.cost_functions,2)198 199 WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)200 WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')195 #process cost functions 196 num_cost_functions = np.size(self.cost_functions) 197 data= marshallcostfunctions(self.cost_functions) 198 WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray') 199 WriteData(fid,prefix,'data',num_cost_functions,'name','md.inversion.num_cost_functions','format','Integer') -
issm/trunk-jpl/src/py3/classes/thermal.py
r19903 r23670 1 import numpy 1 import numpy as np 2 2 from project3d import project3d 3 3 from fielddisplay import fielddisplay 4 from EnumDefinitions import *5 4 from checkfield import checkfield 6 5 from WriteData import WriteData 7 import MatlabFuncs as m8 6 9 7 class thermal(object): … … 24 22 self.penalty_factor = 0 25 23 self.isenthalpy = 0 26 self.isdynamicbasalspc = 0; 24 self.isdynamicbasalspc = 0 25 self.fe = 'P1' 27 26 self.requested_outputs = [] 28 27 … … 45 44 #}}} 46 45 def extrude(self,md): # {{{ 47 self.spctemperature=project3d(md,'vector',self.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',n umpy.nan)48 if isinstance(md.initialization.temperature,n umpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:49 self.spctemperature= numpy.nan*numpy.ones((md.mesh.numberofvertices,1))50 pos=n umpy.nonzero(md.mesh.vertexonsurface)[0]46 self.spctemperature=project3d(md,'vector',self.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',np.nan) 47 if isinstance(md.initialization.temperature,np.ndarray) and np.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices: 48 self.spctemperature=float('NaN')*np.ones((md.mesh.numberofvertices)) 49 pos=np.where(md.mesh.vertexonsurface)[0] 51 50 self.spctemperature[pos]=md.initialization.temperature[pos] #impose observed temperature on surface 52 51 return self … … 81 80 82 81 #will basal boundary conditions be set dynamically 83 self.isdynamicbasalspc=0; 82 self.isdynamicbasalspc=0 83 84 #Finite element interpolation 85 self.fe='P1' 84 86 85 87 #default output … … 91 93 92 94 #Early return 93 if ( ThermalAnalysisEnum() not in analyses and EnthalpyAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum()and not md.transient.isthermal):95 if ('ThermalAnalysis' not in analyses and 'EnthalpyAnalysis' not in analyses) or (solution=='TransientSolution' and not md.transient.isthermal): 94 96 return md 95 97 96 98 md = checkfield(md,'fieldname','thermal.stabilization','numel',[1],'values',[0,1,2]) 97 99 md = checkfield(md,'fieldname','thermal.spctemperature','Inf',1,'timeseries',1) 98 if EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy and md.mesh.dimension()==3: 99 pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices]))) 100 replicate=numpy.tile(md.geometry.surface-md.mesh.z,(1,numpy.size(md.thermal.spctemperature,axis=1))) 101 md = checkfield(md,'fieldname','thermal.spctemperature[numpy.nonzero(numpy.logical_not(numpy.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices,:])))]','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate[pos],'message',"spctemperature should be below the adjusted melting point") 100 md = checkfield(md,'fieldname','thermal.requested_outputs','stringrow',1) 101 102 if 'EnthalpyAnalysis' in analyses and md.thermal.isenthalpy and md.mesh.dimension()==3: 103 TEMP = md.thermal.spctemperature[:-1].flatten(-1) 104 pos=np.where(~np.isnan(TEMP)) 105 try: 106 spccol=np.size(md.thermal.spctemperature,1) 107 except IndexError: 108 spccol=1 109 110 replicate=np.tile(md.geometry.surface-md.mesh.z,(spccol)).flatten(-1) 111 112 control=md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate+10**-5 113 114 md = checkfield(md,'fieldname','thermal.spctemperature','field',md.thermal.spctemperature.flatten(-1)[pos],'<=',control[pos],'message',"spctemperature should be below the adjusted melting point") 102 115 md = checkfield(md,'fieldname','thermal.isenthalpy','numel',[1],'values',[0,1]) 103 116 md = checkfield(md,'fieldname','thermal.isdynamicbasalspc','numel',[1],'values',[0,1]); 104 117 if(md.thermal.isenthalpy): 105 if n umpy.isnan(md.stressbalance.reltol):118 if np.isnan(md.stressbalance.reltol): 106 119 md.checkmessage("for a steadystate computation, thermal.reltol (relative convergence criterion) must be defined!") 107 120 md = checkfield(md,'fieldname','thermal.reltol','>',0.,'message',"reltol must be larger than zero"); 108 md = checkfield(md,'fieldname','thermal.requested_outputs','stringrow',1) 121 109 122 110 123 return md 111 124 # }}} 112 def marshall(self,md,fid): # {{{ 113 WriteData(fid,'object',self,'fieldname','spctemperature','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1) 114 WriteData(fid,'object',self,'fieldname','penalty_threshold','format','Integer') 115 WriteData(fid,'object',self,'fieldname','stabilization','format','Integer') 116 WriteData(fid,'object',self,'fieldname','reltol','format','Double'); 117 WriteData(fid,'object',self,'fieldname','maxiter','format','Integer') 118 WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer') 119 WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double') 120 WriteData(fid,'object',self,'fieldname','isenthalpy','format','Boolean') 121 WriteData(fid,'object',self,'fieldname','isdynamicbasalspc','format','Boolean'); 125 def marshall(self,prefix,md,fid): # {{{ 126 WriteData(fid,prefix,'object',self,'fieldname','spctemperature','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts) 127 WriteData(fid,prefix,'object',self,'fieldname','penalty_threshold','format','Integer') 128 WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Integer') 129 WriteData(fid,prefix,'object',self,'fieldname','reltol','format','Double'); 130 WriteData(fid,prefix,'object',self,'fieldname','maxiter','format','Integer') 131 WriteData(fid,prefix,'object',self,'fieldname','penalty_lock','format','Integer') 132 WriteData(fid,prefix,'object',self,'fieldname','penalty_factor','format','Double') 133 WriteData(fid,prefix,'object',self,'fieldname','isenthalpy','format','Boolean') 134 WriteData(fid,prefix,'object',self,'fieldname','fe','format','String'); 135 WriteData(fid,prefix,'object',self,'fieldname','isdynamicbasalspc','format','Boolean'); 122 136 123 137 #process requested outputs … … 127 141 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 128 142 outputs =outputscopy 129 WriteData(fid, 'data',outputs,'enum',ThermalRequestedOutputsEnum(),'format','StringArray')143 WriteData(fid,prefix,'data',outputs,'name','md.thermal.requested_outputs','format','StringArray') 130 144 # }}} -
issm/trunk-jpl/src/py3/classes/timestepping.py
r19898 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *3 2 from checkfield import checkfield 4 3 from WriteData import WriteData … … 16 15 self.final_time = 0. 17 16 self.time_step = 0. 18 self.time_adapt = 019 self.cfl_coefficient = 0.20 17 self.interp_forcings = 1 18 self.coupling_time = 0. 21 19 22 20 #set defaults … … 29 27 string="%s\n%s"%(string,fielddisplay(self,"final_time","final time to stop the simulation [yr]")) 30 28 string="%s\n%s"%(string,fielddisplay(self,"time_step","length of time steps [yr]")) 31 string="%s\n%s"%(string,fielddisplay(self,"time_adapt","use cfl condition to define time step ? (0 or 1) "))32 string="%s\n%s"%(string,fielddisplay(self,"cfl_coefficient","coefficient applied to cfl condition"))33 29 string="%s\n%s"%(string,fielddisplay(self,"interp_forcings","interpolate in time between requested forcing values ? (0 or 1)")) 30 string="%s\n%s"%(string,fielddisplay(self,"coupling_time","length of coupling time steps with ocean model [yr]")) 34 31 return string 35 32 #}}} … … 42 39 self.final_time=10.*self.time_step 43 40 44 #time adaptation?45 self.time_adapt=046 self.cfl_coefficient=0.547 48 41 #should we interpolate forcings between timesteps? 49 42 self.interp_forcings=1 … … 56 49 md = checkfield(md,'fieldname','timestepping.final_time','numel',[1],'NaN',1,'Inf',1) 57 50 md = checkfield(md,'fieldname','timestepping.time_step','numel',[1],'>=',0,'NaN',1,'Inf',1) 58 md = checkfield(md,'fieldname','timestepping.time_adapt','numel',[1],'values',[0,1])59 md = checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1)60 51 if self.final_time-self.start_time<0: 61 52 md.checkmessage("timestepping.final_time should be larger than timestepping.start_time") 53 md = checkfield(md,'fieldname','timestepping.coupling_time','numel',[1],'>=',0,'NaN',1,'Inf',1) 62 54 md = checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0,1]) 63 55 64 56 return md 65 57 # }}} 66 def marshall(self, md,fid): # {{{58 def marshall(self,prefix,md,fid): # {{{ 67 59 68 60 yts=md.constants.yts 69 70 WriteData(fid,'object',self,'fieldname','start_time','format','Double','scale',yts) 71 WriteData(fid,'object',self,'fieldname','final_time','format','Double','scale',yts) 72 WriteData(fid,'object',self,'fieldname','time_step','format','Double','scale',yts) 73 WriteData(fid,'object',self,'fieldname','time_adapt','format','Boolean') 74 WriteData(fid,'object',self,'fieldname','cfl_coefficient','format','Double') 75 WriteData(fid,'object',self,'fieldname','interp_forcings','format','Boolean') 61 WriteData(fid,prefix,'name','md.timestepping.type','data',1,'format','Integer'); 62 WriteData(fid,prefix,'object',self,'fieldname','start_time','format','Double','scale',yts) 63 WriteData(fid,prefix,'object',self,'fieldname','final_time','format','Double','scale',yts) 64 WriteData(fid,prefix,'object',self,'fieldname','time_step','format','Double','scale',yts) 65 WriteData(fid,prefix,'object',self,'fieldname','interp_forcings','format','Boolean') 66 WriteData(fid,prefix,'object',self,'fieldname','coupling_time','format','Double','scale',yts) 76 67 # }}} -
issm/trunk-jpl/src/py3/classes/toolkits.py
r19895 r23670 2 2 from mumpsoptions import mumpsoptions 3 3 from iluasmoptions import iluasmoptions 4 from EnumToString import EnumToString5 4 from fielddisplay import fielddisplay 6 from EnumDefinitions import *7 5 from checkfield import checkfield 6 from issmgslsolver import issmgslsolver 7 from issmmumpssolver import issmmumpssolver 8 8 9 9 class toolkits(object): … … 30 30 else: 31 31 raise IOError("ToolkitsFile error: need at least Mumps or Gsl to define issm solver type") 32 32 33 #The other properties are dynamic 33 34 # }}} 34 35 def __repr__(self): # {{{ 35 print('enter repr')36 36 s ="List of toolkits options per analysis:\n\n" 37 for analysis in list(vars(self).keys()):37 for analysis in vars(self).keys(): 38 38 s+="%s\n" % fielddisplay(self,analysis,'') 39 39 … … 41 41 # }}} 42 42 def addoptions(self,analysis,*args): # {{{ 43 print('enter addoption')44 43 # Usage example: 45 # md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum(),FSoptions()); 46 # md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum()); 47 48 #Convert analysis from enum to string 49 [analysis]=EnumToString(analysis) 44 # md.toolkits=addoptions(md.toolkits,'StressbalanceAnalysis',FSoptions()); 45 # md.toolkits=addoptions(md.toolkits,'StressbalanceAnalysis'); 50 46 51 47 #Create dynamic property if property does not exist yet 52 48 if not hasattr(self,analysis): 53 # exec("self.%s = None" % analysis)54 49 setattr(self,analysis,None) 55 50 … … 61 56 # }}} 62 57 def checkconsistency(self,md,solution,analyses): # {{{ 63 print('enter check') 64 for analysis in list(vars(self).keys()): 58 for analysis in vars(self).keys(): 65 59 if not getattr(self,analysis): 66 60 md.checkmessage("md.toolkits.%s is empty" % analysis) … … 86 80 87 81 #write header 88 fid.write("%s%s%s\n" % ('% Petsc options file: ',filename,' written from Matlabtoolkits array'))82 fid.write("%s%s%s\n" % ('%Toolkits options file: ',filename,' written from Python toolkits array')) 89 83 90 84 #start writing options 91 for analysis in list(vars(self).keys()):85 for analysis in vars(self).keys(): 92 86 options=getattr(self,analysis) 93 87 94 88 #first write analysis: 95 89 fid.write("\n+%s\n" % analysis) #append a + to recognize it's an analysis enum 96 97 90 #now, write options 98 for optionname,optionvalue in list(options.items()):91 for optionname,optionvalue in options.items(): 99 92 100 93 if not optionvalue: -
issm/trunk-jpl/src/py3/classes/transient.py
r19895 r23670 1 1 from fielddisplay import fielddisplay 2 from EnumDefinitions import *3 2 from checkfield import checkfield 4 3 from WriteData import WriteData … … 13 12 14 13 def __init__(self): # {{{ 15 self.issmb = False14 self.issmb = False 16 15 self.ismasstransport = False 17 16 self.isstressbalance = False … … 19 18 self.isgroundingline = False 20 19 self.isgia = False 20 self.isesa = False 21 21 self.isdamageevolution = False 22 self.islevelset = False 23 self.iscalving = False 22 self.ismovingfront = False 24 23 self.ishydrology = False 24 self.isslr = False 25 self.iscoupler = False 26 self.amr_frequency = 0 27 self.isoceancoupling = False 25 28 self.requested_outputs = [] 26 29 … … 37 40 string="%s\n%s"%(string,fielddisplay(self,'isgroundingline','indicates if a groundingline migration is used in the transient')) 38 41 string="%s\n%s"%(string,fielddisplay(self,'isgia','indicates if a postglacial rebound is used in the transient')) 42 string="%s\n%s"%(string,fielddisplay(self,'isesa','indicates whether an elastic adjustment model is used in the transient')) 39 43 string="%s\n%s"%(string,fielddisplay(self,'isdamageevolution','indicates whether damage evolution is used in the transient')) 40 string="%s\n%s"%(string,fielddisplay(self,'islevelset','LEVELSET METHOD DESCRIPTION')) 41 string="%s\n%s"%(string,fielddisplay(self,'iscalving','indicates whether calving is used in the transient')) 44 string="%s\n%s"%(string,fielddisplay(self,'ismovingfront','indicates whether a moving front capability is used in the transient')) 42 45 string="%s\n%s"%(string,fielddisplay(self,'ishydrology','indicates whether an hydrology model is used')) 46 string="%s\n%s"%(string,fielddisplay(self,'isslr','indicates if a sea level rise solution is used in the transient')) 47 string="%s\n%s"%(string,fielddisplay(self,'isoceancoupling','indicates whether coupling with an ocean model is used in the transient')) 48 string="%s\n%s"%(string,fielddisplay(self,'iscoupler','indicates whether different models are being run with need for coupling')) 49 string="%s\n%s"%(string,fielddisplay(self,'amr_frequency','frequency at which mesh is refined in simulations with multiple time_steps')) 43 50 string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','list of additional outputs requested')) 44 51 return string … … 61 68 self.isgroundingline = False 62 69 self.isgia = False 70 self.isesa = False 63 71 self.isdamageevolution = False 64 self.islevelset = False 65 self.iscalving = False 72 self.ismovingfront = False 66 73 self.ishydrology = False 74 self.isoceancoupling = False 75 self.isslr = False 76 self.iscoupler = False 77 self.amr_frequency = 0 78 79 #default output 80 self.requested_outputs=[] 81 return self 82 #}}} 83 def deactivateall(self):#{{{ 84 self.issmb = False 85 self.ismasstransport = False 86 self.isstressbalance = False 87 self.isthermal = False 88 self.isgroundingline = False 89 self.isgia = False 90 self.isesa = False 91 self.isdamageevolution = False 92 self.ismovingfront = False 93 self.ishydrology = False 94 self.isslr = False 95 self.isoceancoupling = False 96 self.iscoupler = False 97 self.amr_frequency = 0 67 98 68 99 #default output … … 73 104 74 105 #full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now 75 self.issmb = True 76 self.ismasstransport = True 77 self.isstressbalance = True 78 self.isthermal = True 79 self.isgroundingline = False 80 self.isgia = False 106 self.issmb = True 107 self.ismasstransport = True 108 self.isstressbalance = True 109 self.isthermal = True 110 self.isgroundingline = False 111 self.isgia = False 112 self.isesa = False 81 113 self.isdamageevolution = False 82 self.islevelset = False 83 self.iscalving = False 84 self.ishydrology = False 114 self.ismovingfront = False 115 self.ishydrology = False 116 self.isslr = False 117 self.isoceancoupling = False 118 self.iscoupler = False 119 self.amr_frequency = 0 85 120 86 121 #default output … … 91 126 92 127 #Early return 93 if not solution== TransientSolutionEnum():128 if not solution=='TransientSolution': 94 129 return md 95 130 … … 100 135 md = checkfield(md,'fieldname','transient.isgroundingline','numel',[1],'values',[0,1]) 101 136 md = checkfield(md,'fieldname','transient.isgia','numel',[1],'values',[0,1]) 137 md = checkfield(md,'fieldname','transient.isesa','numel',[1],'values',[0,1]) 102 138 md = checkfield(md,'fieldname','transient.isdamageevolution','numel',[1],'values',[0,1]) 103 md = checkfield(md,'fieldname','transient.islevelset','numel',[1],'values',[0,1])104 139 md = checkfield(md,'fieldname','transient.ishydrology','numel',[1],'values',[0,1]) 105 md = checkfield(md,'fieldname','transient.iscalving','numel',[1],'values',[0,1]); 140 md = checkfield(md,'fieldname','transient.ismovingfront','numel',[1],'values',[0,1]); 141 md = checkfield(md,'fieldname','transient.isslr','numel',[1],'values',[0,1]) 142 md = checkfield(md,'fieldname','transient.isoceancoupling','numel',[1],'values',[0,1]) 143 md = checkfield(md,'fieldname','transient.iscoupler','numel',[1],'values',[0,1]) 144 md = checkfield(md,'fieldname','transient.amr_frequency','numel',[1],'>=',0,'NaN',1,'Inf',1) 106 145 md = checkfield(md,'fieldname','transient.requested_outputs','stringrow',1) 146 147 if (solution!='TransientSolution') and (md.transient.iscoupling): 148 md.checkmessage("Coupling with ocean can only be done in transient simulations!") 107 149 108 150 return md 109 151 # }}} 110 def marshall(self,md,fid): # {{{ 111 WriteData(fid,'object',self,'fieldname','issmb','format','Boolean') 112 WriteData(fid,'object',self,'fieldname','ismasstransport','format','Boolean') 113 WriteData(fid,'object',self,'fieldname','isstressbalance','format','Boolean') 114 WriteData(fid,'object',self,'fieldname','isthermal','format','Boolean') 115 WriteData(fid,'object',self,'fieldname','isgroundingline','format','Boolean') 116 WriteData(fid,'object',self,'fieldname','isgia','format','Boolean') 117 WriteData(fid,'object',self,'fieldname','isdamageevolution','format','Boolean') 118 WriteData(fid,'object',self,'fieldname','islevelset','format','Boolean') 119 WriteData(fid,'object',self,'fieldname','ishydrology','format','Boolean') 120 WriteData(fid,'object',self,'fieldname','iscalving','format','Boolean') 152 def marshall(self,prefix,md,fid): # {{{ 153 WriteData(fid,prefix,'object',self,'fieldname','issmb','format','Boolean') 154 WriteData(fid,prefix,'object',self,'fieldname','ismasstransport','format','Boolean') 155 WriteData(fid,prefix,'object',self,'fieldname','isstressbalance','format','Boolean') 156 WriteData(fid,prefix,'object',self,'fieldname','isthermal','format','Boolean') 157 WriteData(fid,prefix,'object',self,'fieldname','isgroundingline','format','Boolean') 158 WriteData(fid,prefix,'object',self,'fieldname','isgia','format','Boolean') 159 WriteData(fid,prefix,'object',self,'fieldname','isesa','format','Boolean') 160 WriteData(fid,prefix,'object',self,'fieldname','isdamageevolution','format','Boolean') 161 WriteData(fid,prefix,'object',self,'fieldname','ishydrology','format','Boolean') 162 WriteData(fid,prefix,'object',self,'fieldname','ismovingfront','format','Boolean') 163 WriteData(fid,prefix,'object',self,'fieldname','isslr','format','Boolean') 164 WriteData(fid,prefix,'object',self,'fieldname','isoceancoupling','format','Boolean') 165 WriteData(fid,prefix,'object',self,'fieldname','iscoupler','format','Boolean') 166 WriteData(fid,prefix,'object',self,'fieldname','amr_frequency','format','Integer') 121 167 122 168 #process requested outputs … … 126 172 outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:] 127 173 outputs =outputscopy 128 WriteData(fid, 'data',outputs,'enum',TransientRequestedOutputsEnum(),'format','StringArray')174 WriteData(fid,prefix,'data',outputs,'name','md.transient.requested_outputs','format','StringArray') 129 175 # }}} -
issm/trunk-jpl/src/py3/classes/verbose.py
r19895 r23670 1 1 from pairoptions import pairoptions 2 2 import MatlabFuncs as m 3 from EnumDefinitions import *4 3 from WriteData import WriteData 5 4 … … 29 28 """ 30 29 31 def __init__(self,*args ,**kwargs): # {{{30 def __init__(self,*args): # {{{ 32 31 #BEGINFIELDS 33 32 self.mprocessor = False … … 42 41 #ENDFIELDS 43 42 44 if not kwargs and not args:43 if not len(args): 45 44 #Don't do anything 46 45 self.solution=True; … … 64 63 else: 65 64 #Use options to initialize object 66 self=pairoptions(* *kwargs).AssignObjectFields(self)65 self=pairoptions(*args).AssignObjectFields(self) 67 66 68 67 #Cast to logicals 69 68 listproperties=vars(self) 70 for fieldname,fieldvalue in list (listproperties.items()):69 for fieldname,fieldvalue in listproperties.items(): 71 70 if isinstance(fieldvalue,bool) or isinstance(fieldvalue,(int,float)): 72 71 setattr(self,fieldname,bool(fieldvalue)) … … 134 133 return md 135 134 # }}} 136 def marshall(self, md,fid): # {{{137 WriteData(fid, 'data',self.VerboseToBinary(),'enum',VerboseEnum(),'format','Integer')135 def marshall(self,prefix,md,fid): # {{{ 136 WriteData(fid,prefix,'data',self.VerboseToBinary(),'name','md.verbose','format','Integer') 138 137 # }}} -
issm/trunk-jpl/src/py3/consistency/checkfield.py
r19899 r23670 1 import numpy 1 import numpy as np 2 2 import os 3 3 from pairoptions import pairoptions 4 4 import MatlabFuncs as m 5 5 6 def checkfield(md,* *kwargs):6 def checkfield(md,*args): 7 7 """ 8 8 CHECKFIELD - check field consistency 9 9 10 10 Used to check model consistency., 11 Requires: 12 'field' or 'fieldname' option. If 'fieldname' is provided, it will retrieve it from the model md. (md.(fieldname)) 11 Requires: 12 'field' or 'fieldname' option. If 'fieldname' is provided, it will retrieve it from the model md. (md.(fieldname)) 13 13 If 'field' is provided, it will assume the argument following 'field' is a numeric array. 14 14 … … 33 33 34 34 #get options 35 options=pairoptions(* *kwargs)35 options=pairoptions(*args) 36 36 37 37 #get field from model … … 40 40 fieldname=options.getfieldvalue('fieldname','no fieldname') 41 41 else: 42 fieldname=options.getfieldvalue('fieldname') 43 exec("field=md. %s" % fieldname)42 fieldname=options.getfieldvalue('fieldname') 43 exec("field=md.{}".format(fieldname)) 44 44 45 45 if isinstance(field,(bool,int,float)): 46 field=n umpy.array([field])46 field=np.array([field]) 47 47 48 48 #check empty … … 55 55 if options.exist('size'): 56 56 fieldsize=options.getfieldvalue('size') 57 if 58 if numpy.isnan(fieldsize[0]):57 if len(fieldsize) == 1: 58 if np.isnan(fieldsize[0]): 59 59 pass 60 elif not numpy.size(field,0)==fieldsize[0]: 61 md = md.checkmessage(options.getfieldvalue('message',\ 62 "field '%s' size should be %d" % (fieldname,fieldsize[0]))) 60 elif np.ndim(field)==1: 61 if not np.size(field)==fieldsize[0]: 62 md = md.checkmessage(options.getfieldvalue('message',"field {} size should be {}".format(fieldname,fieldsize[0]))) 63 else: 64 try: 65 exec("md.{}=np.squeeze(field)".format(fieldname)) 66 print(('{} had been squeezed if it was a matrix with only one column'.format(fieldname))) 67 except IndexError: 68 md = md.checkmessage(options.getfieldvalue('message',"field {} should have {} dimension".format(fieldname,len(fieldsize)))) 63 69 elif len(fieldsize) == 2: 64 if n umpy.isnan(fieldsize[0]):65 if not n umpy.size(field,1)==fieldsize[1]:66 md = md.checkmessage(options.getfieldvalue('message', \67 "field '%s' should have %d columns" % (fieldname,fieldsize[1])))68 elif numpy.isnan(fieldsize[1]):69 if not numpy.size(field,0)==fieldsize[0]:70 md = md.checkmessage(options.getfieldvalue('message',\71 "field '%s' should have %d lines" % (fieldname,fieldsize[0])))72 else:73 if (not numpy.size(field,0)==fieldsize[0]) or (not numpy.size(field,1)==fieldsize[1]):74 md = md.checkmessage(options.getfieldvalue('message',\75 76 70 if np.isnan(fieldsize[0]): 71 if not np.size(field,1)==fieldsize[1]: 72 md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have %d columns" % (fieldname,fieldsize[1]))) 73 elif np.isnan(fieldsize[1]): 74 if not np.size(field,0)==fieldsize[0]: 75 md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have %d lines" % (fieldname,fieldsize[0]))) 76 elif fieldsize[1]==1: 77 if (not np.size(field,0)==fieldsize[0]): 78 md = md.checkmessage(options.getfieldvalue('message',"field '%s' size should be %d x %d" % (fieldname,fieldsize[0],fieldsize[1]))) 79 else: 80 if (not np.size(field,0)==fieldsize[0]) or (not np.size(field,1)==fieldsize[1]): 81 md = md.checkmessage(options.getfieldvalue('message',"field '%s' size should be %d x %d" % (fieldname,fieldsize[0],fieldsize[1]))) 82 77 83 #Check numel 78 84 if options.exist('numel'): 79 85 fieldnumel=options.getfieldvalue('numel') 80 if numpy.size(field) not in fieldnumel:86 if (type(fieldnumel) == int and np.size(field) != fieldnumel) or (type(fieldnumel) == list and np.size(field) not in fieldnumel): 81 87 if len(fieldnumel)==1: 82 88 md = md.checkmessage(options.getfieldvalue('message',\ … … 91 97 #check NaN 92 98 if options.getfieldvalue('NaN',0): 93 if n umpy.any(numpy.isnan(field)):99 if np.any(np.isnan(field)): 94 100 md = md.checkmessage(options.getfieldvalue('message',\ 95 101 "NaN values found in field '%s'" % fieldname)) 102 96 103 97 104 #check Inf 98 105 if options.getfieldvalue('Inf',0): 99 if n umpy.any(numpy.isinf(field)):106 if np.any(np.isinf(field)): 100 107 md = md.checkmessage(options.getfieldvalue('message',\ 101 108 "Inf values found in field '%s'" % fieldname)) 109 102 110 103 111 #check cell … … 123 131 #check greater 124 132 if options.exist('>='): 125 lowerbound=options.getfieldvalue('>=') 126 if numpy.any(field<lowerbound): 127 md = md.checkmessage(options.getfieldvalue('message',\ 128 "field '%s' should have values above %d" % (fieldname,lowerbound))) 133 lowerbound = options.getfieldvalue('>=') 134 if np.size(lowerbound)>1: #checking elementwise 135 if any(field<upperbound): 136 md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values below %d" % (fieldname,upperbound))) 137 else: 138 minval=np.nanmin(field) 139 if options.getfieldvalue('timeseries',0): 140 minval=np.nanmin(field[:-1]) 141 elif options.getfieldvalue('singletimeseries',0): 142 if np.size(field)==1: #some singletimeseries are just one value 143 minval=field 144 else: 145 minval=np.nanmin(field[0]) 146 147 if minval<lowerbound: 148 md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values above %d" % (fieldname,lowerbound))) 149 129 150 if options.exist('>'): 130 151 lowerbound=options.getfieldvalue('>') 131 if numpy.any(field<=lowerbound): 132 md = md.checkmessage(options.getfieldvalue('message',\ 133 "field '%s' should have values above %d" % (fieldname,lowerbound))) 152 if np.size(lowerbound)>1: #checking elementwise 153 if any(field<=upperbound): 154 md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values below %d" % (fieldname,upperbound))) 155 else: 156 minval=np.nanmin(field) 157 if options.getfieldvalue('timeseries',0) : 158 minval=np.nanmin(field[:-1]) 159 elif options.getfieldvalue('singletimeseries',0): 160 if np.size(field)==1: #some singletimeseries are just one value 161 minval=field 162 else: 163 minval=np.nanmin(field[0]) 164 165 if minval<=lowerbound: 166 md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values above %d" % (fieldname,lowerbound))) 134 167 135 168 #check smaller 136 169 if options.exist('<='): 137 170 upperbound=options.getfieldvalue('<=') 138 if numpy.any(field>upperbound): 139 md = md.checkmessage(options.getfieldvalue('message',\ 140 "field '%s' should have values below %d" % (fieldname,upperbound))) 171 if np.size(upperbound)>1: #checking elementwise 172 if any(field>upperbound): 173 md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values below %d" % (fieldname,upperbound))) 174 else: 175 maxval=np.nanmax(field) 176 if options.getfieldvalue('timeseries',0): 177 maxval=np.nanmax(field[:-1]) 178 elif options.getfieldvalue('singletimeseries',0): 179 if np.size(field)==1: #some singletimeseries are just one value 180 maxval=field 181 else: 182 maxval=np.nanmax(field[0]) 183 if maxval>upperbound: 184 md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values below %d" % (fieldname,upperbound))) 185 141 186 if options.exist('<'): 142 187 upperbound=options.getfieldvalue('<') 143 if numpy.any(field>=upperbound): 144 md = md.checkmessage(options.getfieldvalue('message',\ 145 "field '%s' should have values below %d" % (fieldname,upperbound))) 188 if np.size(upperbound)>1: #checking elementwise 189 if any(field>=upperbound): 190 md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values below %d" % (fieldname,upperbound))) 191 192 else: 193 maxval=np.nanmax(field) 194 if options.getfieldvalue('timeseries',0): 195 maxval=np.nanmax(field[:-1]) 196 elif options.getfieldvalue('singletimeseries',0): 197 if np.size(field)==1: #some singletimeseries are just one value 198 maxval=field.copy() 199 else: 200 maxval=np.nanmax(field[0]) 201 202 if maxval>=upperbound: 203 md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values below %d" % (fieldname,upperbound))) 146 204 147 205 #check file … … 158 216 #Check forcings (size and times) 159 217 if options.getfieldvalue('timeseries',0): 160 if numpy.size(field,0)==md.mesh.numberofvertices:161 if n umpy.ndim(field)>1 and not numpy.size(field,1)==1:218 if np.size(field,0)==md.mesh.numberofvertices or np.size(field,0)==md.mesh.numberofelements: 219 if np.ndim(field)>1 and not np.size(field,1)==1: 162 220 md = md.checkmessage(options.getfieldvalue('message',\ 163 221 "field '%s' should have only one column as there are md.mesh.numberofvertices lines" % fieldname)) 164 elif n umpy.size(field,0)==md.mesh.numberofvertices+1 or numpy.size(field,0)==2:165 if n ot all(field[-1,:]==numpy.sort(field[-1,:])):222 elif np.size(field,0)==md.mesh.numberofvertices+1 or np.size(field,0)==md.mesh.numberofelements+1: 223 if np.ndim(field) > 1 and not all(field[-1,:]==np.sort(field[-1,:])): 166 224 md = md.checkmessage(options.getfieldvalue('message',\ 167 225 "field '%s' columns should be sorted chronologically" % fieldname)) 168 if any(field[-1,0:-1]==field[-1,1:]):226 if np.ndim(field) > 1 and any(field[-1,0:-1]==field[-1,1:]): 169 227 md = md.checkmessage(options.getfieldvalue('message',\ 170 228 "field '%s' columns must not contain duplicate timesteps" % fieldname)) … … 175 233 #Check single value forcings (size and times) 176 234 if options.getfieldvalue('singletimeseries',0): 177 if n umpy.size(field,0)==2:178 if not all(field[-1,:]==n umpy.sort(field[-1,:])):235 if np.size(field,0)==2: 236 if not all(field[-1,:]==np.sort(field[-1,:])): 179 237 md = md.checkmessage(options.getfieldvalue('message',\ 180 238 "field '%s' columns should be sorted chronologically" % fieldname)) … … 182 240 md = md.checkmessage(options.getfieldvalue('message',\ 183 241 "field '%s' columns must not contain duplicate timesteps" % fieldname)) 184 else: 185 md = md.checkmessage(options.getfieldvalue('message',\ 186 "field '%s' should have 2 lines" % fieldname)) 242 elif np.size(field,0) == 1: 243 if np.ndim(field) > 1 and not np.size(field,1) == 1: 244 md = md.checkmessage(options.getfieldvalue('message',\ 245 "field '%s' should be either a scalar or have 2 lines" % fieldname)) 246 else: 247 md = md.checkmessage(options.getfieldvalue('message',\ 248 "field '%s' should have 2 lines or be a scalar" % fieldname)) 187 249 188 250 return md 189 -
issm/trunk-jpl/src/py3/consistency/ismodelselfconsistent.py
r19895 r23670 1 from EnumDefinitions import *2 from EnumToString import EnumToString3 4 1 def AnalysisConfiguration(solutiontype): #{{{ 5 2 """ … … 10 7 """ 11 8 12 if solutiontype == StressbalanceSolutionEnum():13 analyses=[ StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),L2ProjectionBaseAnalysisEnum()]9 if solutiontype == 'StressbalanceSolution': 10 analyses=['StressbalanceAnalysis','StressbalanceVerticalAnalysis','StressbalanceSIAAnalysis','L2ProjectionBaseAnalysis'] 14 11 15 elif solutiontype == SteadystateSolutionEnum():16 analyses=[ StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),L2ProjectionBaseAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]12 elif solutiontype == 'SteadystateSolution': 13 analyses=['StressbalanceAnalysis','StressbalanceVerticalAnalysis','StressbalanceSIAAnalysis','L2ProjectionBaseAnalysis','ThermalAnalysis','MeltingAnalysis','EnthalpyAnalysis'] 17 14 18 elif solutiontype == ThermalSolutionEnum():19 analyses=[ EnthalpyAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]15 elif solutiontype == 'ThermalSolution': 16 analyses=['EnthalpyAnalysis','ThermalAnalysis','MeltingAnalysis'] 20 17 21 elif solutiontype == MasstransportSolutionEnum():22 analyses=[ MasstransportAnalysisEnum()]18 elif solutiontype == 'MasstransportSolution': 19 analyses=['MasstransportAnalysis'] 23 20 24 elif solutiontype == BalancethicknessSolutionEnum():25 analyses=[ BalancethicknessAnalysisEnum()]21 elif solutiontype == 'BalancethicknessSolution': 22 analyses=['BalancethicknessAnalysis'] 26 23 27 elif solutiontype == SurfaceSlopeSolutionEnum():28 analyses=[ L2ProjectionBaseAnalysisEnum()]24 elif solutiontype == 'SurfaceSlopeSolution': 25 analyses=['L2ProjectionBaseAnalysis'] 29 26 30 elif solutiontype == BalancevelocitySolutionEnum():31 analyses=[ BalancevelocityAnalysisEnum()]27 elif solutiontype == 'BalancevelocitySolution': 28 analyses=['BalancevelocityAnalysis'] 32 29 33 elif solutiontype == BedSlopeSolutionEnum():34 analyses=[ L2ProjectionBaseAnalysisEnum()]30 elif solutiontype == 'BedSlopeSolution': 31 analyses=['L2ProjectionBaseAnalysis'] 35 32 36 elif solutiontype == GiaSolutionEnum():37 analyses=[ GiaAnalysisEnum()]33 elif solutiontype == 'GiaSolution': 34 analyses=['GiaIvinsAnalysis'] 38 35 39 elif solutiontype == TransientSolutionEnum():40 analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),L2ProjectionBaseAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum(),EnthalpyAnalysisEnum(),MasstransportAnalysisEnum()]36 elif solutiontype == 'LoveSolution': 37 analyses=['LoveAnalysis'] 41 38 42 elif solutiontype == FlaimSolutionEnum():43 analyses=[ FlaimAnalysisEnum()]39 elif solutiontype == 'TransientSolution': 40 analyses=['StressbalanceAnalysis','StressbalanceVerticalAnalysis','StressbalanceSIAAnalysis','L2ProjectionBaseAnalysis','ThermalAnalysis','MeltingAnalysis','EnthalpyAnalysis','MasstransportAnalysis'] 44 41 45 elif solutiontype == HydrologySolutionEnum():46 analyses=[ L2ProjectionBaseAnalysisEnum(),HydrologyShreveAnalysisEnum(),HydrologyDCInefficientAnalysisEnum(),HydrologyDCEfficientAnalysisEnum()]42 elif solutiontype == 'HydrologySolution': 43 analyses=['L2ProjectionBaseAnalysis','HydrologyShreveAnalysis','HydrologyDCInefficientAnalysis','HydrologyDCEfficientAnalysis'] 47 44 48 elif DamageEvolutionSolutionEnum():49 analyses=[ DamageEvolutionAnalysisEnum()]45 elif 'DamageEvolutionSolution': 46 analyses=['DamageEvolutionAnalysis'] 50 47 51 48 else: 52 raise TypeError("solution type: '%s' not supported yet!" % EnumToString(solutiontype)[0])49 raise TypeError("solution type: '%s' not supported yet!" % solutiontype) 53 50 54 51 return analyses … … 84 81 85 82 #Check consistency of the object 86 exec("md. %s.checkconsistency(md,solution,analyses)" % field)83 exec("md.{}.checkconsistency(md,solution,analyses)".format(field)) 87 84 88 85 #error message if mode is not consistent -
issm/trunk-jpl/src/py3/contrib/bamg/YamsCall.py
r19895 r23670 29 29 #Compute Hessian 30 30 t1=time.time() 31 print( "%s" % ' computing Hessian...')31 print(("%s" % ' computing Hessian...')) 32 32 hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,field,'node') 33 33 t2=time.time() 34 print( "%s%d%s\n" % (' done (',t2-t1,' seconds)'))34 print(("%s%d%s\n" % (' done (',t2-t1,' seconds)'))) 35 35 36 36 #Compute metric 37 37 t1=time.time() 38 print( "%s" % ' computing metric...')38 print(("%s" % ' computing metric...')) 39 39 metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,numpy.empty(0,int)) 40 40 t2=time.time() 41 print( "%s%d%s\n" % (' done (',t2-t1,' seconds)'))41 print(("%s%d%s\n" % (' done (',t2-t1,' seconds)'))) 42 42 43 43 #write files 44 44 t1=time.time() 45 print( "%s" % ' writing initial mesh files...')45 print(("%s" % ' writing initial mesh files...')) 46 46 numpy.savetxt('carre0.met',metric) 47 47 … … 80 80 f.close() 81 81 t2=time.time() 82 print( "%s%d%s\n" % (' done (',t2-t1,' seconds)'))82 print(("%s%d%s\n" % (' done (',t2-t1,' seconds)'))) 83 83 84 84 #call yams 85 print( "%s\n" % ' call Yams...')85 print(("%s\n" % ' call Yams...')) 86 86 if m.ispc(): 87 87 #windows … … 96 96 #plug new mesh 97 97 t1=time.time() 98 print( "\n%s" % ' reading final mesh files...')98 print(("\n%s" % ' reading final mesh files...')) 99 99 Tria=numpy.loadtxt('carre1.tria',int) 100 100 Coor=numpy.loadtxt('carre1.coor',float) … … 107 107 numberofelements2=md.mesh.numberofelements 108 108 t2=time.time() 109 print( "%s%d%s\n\n" % (' done (',t2-t1,' seconds)'))109 print(("%s%d%s\n\n" % (' done (',t2-t1,' seconds)'))) 110 110 111 111 #display number of elements 112 print( "\n%s %i" % (' inital number of elements:',numberofelements1))113 print( "\n%s %i\n\n" % (' new number of elements:',numberofelements2))112 print(("\n%s %i" % (' inital number of elements:',numberofelements1))) 113 print(("\n%s %i\n\n" % (' new number of elements:',numberofelements2))) 114 114 115 115 #clean up: -
issm/trunk-jpl/src/py3/contrib/netCDF/export_netCDF.py
r19895 r23670 12 12 if path.exists(filename): 13 13 print(('File {} allready exist'.format(filename))) 14 newname= input('Give a new name or "delete" to replace: ')14 newname=eval(input('Give a new name or "delete" to replace: ')) 15 15 if newname=='delete': 16 16 remove(filename) … … 72 72 for field in subfields: 73 73 if str(field)!='errlog' and str(field)!='outlog' and str(field)!='SolutionType': 74 print( 'Treating '+str(group)+'.'+str(supfield)+'.'+str(field))74 print(('Treating '+str(group)+'.'+str(supfield)+'.'+str(field))) 75 75 Var=md.results.__dict__[supfield].__dict__[field] 76 76 DimDict=CreateVar(NCData,Var,field,NCgroup,DimDict,False) … … 80 80 81 81 for field in fields: 82 print( 'Treating ' +str(group)+'.'+str(field))82 print(('Treating ' +str(group)+'.'+str(field))) 83 83 NCgroup.__setattr__('classtype', md.__dict__[group].__class__.__name__) 84 84 Var=md.__dict__[group].__dict__[field] … … 119 119 charvar=stringtochar(numpy.array(var)) 120 120 print(charvar) 121 print( charvar.shape)121 print((charvar.shape)) 122 122 for elt in range(0,val_dim): 123 123 try: … … 152 152 if time!=0: 153 153 timevar=md.results.__dict__[supfield].__getitem__(time).__dict__[field] 154 print( 'Treating results.'+str(supfield)+'.'+str(field)+' for time '+str(time))154 print(('Treating results.'+str(supfield)+'.'+str(field)+' for time '+str(time))) 155 155 vartab=numpy.column_stack((vartab,timevar)) 156 print( numpy.shape(vartab))156 print((numpy.shape(vartab))) 157 157 try: 158 158 ncvar[:,:]=vartab[:,:] … … 190 190 DimDict[len(NewDim)]='Dimension'+str(index) 191 191 output=output+[str(DimDict[shape[dim]])] 192 print( 'Defining dimension ' +'Dimension'+str(index))192 print(('Defining dimension ' +'Dimension'+str(index))) 193 193 elif type(shape[0])==str:#dealling with a dictionnary 194 194 try: … … 199 199 DimDict[len(NewDim)]='Dimension'+str(index) 200 200 output=[str(DimDict[numpy.shape(dict.keys(var))[0]])]+['Dimension6'] 201 print( 'Defining dimension ' +'Dimension'+str(index))201 print(('Defining dimension ' +'Dimension'+str(index))) 202 202 break 203 203 if istime: … … 215 215 DimDict[len(NewDim)]='Dimension'+str(index) 216 216 output=output+[str(DimDict[stringlength])] 217 print( 'Defining dimension ' +'Dimension'+str(index))217 print(('Defining dimension ' +'Dimension'+str(index))) 218 218 return tuple(output), DimDict -
issm/trunk-jpl/src/py3/contrib/paraview/exportVTK.py
r19895 r23670 28 28 if os.path.exists(filename): 29 29 print(('File {} allready exist'.format(filename))) 30 newname= input('Give a new name or "delete" to replace: ')30 newname=eval(input('Give a new name or "delete" to replace: ')) 31 31 if newname=='delete': 32 32 filelist = glob.glob(filename+'/*') -
issm/trunk-jpl/src/py3/coordsystems/ll2xy.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 3 3 def ll2xy(lat,lon,sgn=-1,central_meridian=0,standard_parallel=71): -
issm/trunk-jpl/src/py3/coordsystems/xy2ll.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from math import pi 3 3 … … 37 37 raise Exception('bad usage: type "help(xy2ll)" for details') 38 38 39 # if x,y passed as lists, convert to n umpyarrays40 if type(x) != "n umpy.ndarray":39 # if x,y passed as lists, convert to np.arrays 40 if type(x) != "np.ndarray": 41 41 x=np.array(x) 42 if type(y) != "n umpy.ndarray":42 if type(y) != "np.ndarray": 43 43 y=np.array(y) 44 44 … … 73 73 res1 = np.nonzero(rho <= 0.1)[0] 74 74 if len(res1) > 0: 75 lat[res1] = 90. * sgn75 lat[res1] = pi/2. * sgn 76 76 lon[res1] = 0.0 77 77 -
issm/trunk-jpl/src/py3/dev/devpath.py
r19895 r23670 4 4 5 5 #Recover ISSM_DIR and USERNAME 6 ISSM_DIR = os.getenv('ISSM_D IRPY3')6 ISSM_DIR = os.getenv('ISSM_DEV_DIR') 7 7 USERNAME = os.getenv('USER') 8 8 JPL_SVN = os.getenv('JPL_SVN') 9 9 if(ISSM_DIR==None): 10 10 raise NameError('"ISSM_DIR" environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!') 11 if(JPL_SVN==None):12 warnings.warn('"JPL_SVN" environment variable is empty! add it to your .cshrc or .bashrc if you want to do distant computing')13 11 14 #Go through src/m and append any directory that contains a *.py file to PATH 12 #Go through src/m and append any directory that contains a *.py file to PATH 15 13 for root,dirs,files in os.walk(ISSM_DIR+ '/src/py3'): 16 14 if '.svn' in dirs: … … 21 19 if root not in sys.path: 22 20 sys.path.append(root) 23 21 22 #Also add the Nightly run directory 23 sys.path.append(ISSM_DIR + '/test/NightlyRun') 24 24 25 sys.path.append(ISSM_DIR + '/lib') 25 26 sys.path.append(ISSM_DIR + '/src/wrappers/python/.libs') … … 29 30 sys.path.append(JPL_SVN + '/usr/' + USERNAME) 30 31 else: 31 raise NameError('cluster settings should be in, '+ JPL_SVN +'/usr/' + USERNAME)32 warnings.warn('cluster settings should be in, '+ JPL_SVN +'/usr/' + USERNAME) 32 33 33 34 #Manual imports for commonly used functions 34 #from plotmodel import plotmodel 35 from runme import runme #first because plotmodel may fail 36 from plotmodel import plotmodel 35 37 36 38 #c = get_ipython().config … … 40 42 #c.InteractiveShellApp.exec_lines.append('print "Warning: disable autoreload in startup.py to improve performance." ') 41 43 42 print("\n ISSM development path correctly loaded\n\n") 44 print("\n ISSM development path correctly loaded") 45 print(("Current path is {}\n\n".format(ISSM_DIR))) -
issm/trunk-jpl/src/py3/dev/issmversion.py
r19895 r23670 15 15 print(' ') 16 16 print('Build date: '+IssmConfig('PACKAGE_BUILD_DATE')[0]) 17 print('Copyright (c) 2009-201 5California Institute of Technology')17 print('Copyright (c) 2009-2018 California Institute of Technology') 18 18 print(' ') 19 19 print(' to get started type: issmdoc') -
issm/trunk-jpl/src/py3/exp/expcoarsen.py
r21255 r23670 1 1 import os.path 2 import numpy as np2 import numpy as np 3 3 from collections import OrderedDict 4 4 from expread import expread -
issm/trunk-jpl/src/py3/exp/expdisp.py
r21255 r23670 1 1 from expread import expread 2 import numpy as np 2 import numpy as np 3 from matplotlib.path import Path 4 import matplotlib.patches as patches 3 5 4 def expdisp( domainoutline,ax,linestyle='--k',linewidth=1,unitmultiplier=1.):6 def expdisp(ax,options): 5 7 ''' 6 8 plot the contents of a domain outline file 7 9 8 This routine reads in a domain outline file and plots all of the x,y contours10 This routine reads in an exp file and plots all of the x,y points/lines/patches 9 11 10 'ax' is a handle to the current plot axes, onto which the contours are to be drawn12 'ax' is a handle to the current plot axes, onto which we want to plot 11 13 12 14 Usage: 13 expdisp( domainoutline,ax)15 expdisp(ax,options) 14 16 15 Example: 16 expdisp('domain.exp',plt.gca(),linestyle='--k',linewidth=2,unitmultiplier=1.e3) 17 List of options passable to plotmodel: 18 'expdisp' : path (or list of paths) to the exp file to be plotted 19 'explinewidth' : linewidth 20 'explinestyle' : matplotlib linestyle string 21 'explinecolor' : matplotlib color string 22 'expfill' : (True/False) fill a closed contour 23 'expfillcolor' : Color for a filled contour, only used if expfill is True 24 'expfillalpha' : alpha transparency for filled contour 25 26 All options should be passed as lists of length len(number of exp files passed) 17 27 ''' 18 28 19 domain=expread(domainoutline) 20 21 for i in range(len(domain)): 22 if domain[i]['nods']==1: 23 ax.plot(domain[i]['x']*unitmultiplier,domain[i]['y']*unitmultiplier,'o',mec='k',mfc='r',ms=10) 24 else: 25 x=domain[i]['x'].tolist() # since expread returns a string representation of the arrays 26 y=domain[i]['y'].tolist() 27 ax.plot(x*unitmultiplier,y*unitmultiplier,linestyle,linewidth=linewidth) 29 filenames=options.getfieldvalue('expdisp') 30 linewidth=options.getfieldvalue('explinewidth',[1]*len(filenames)) 31 linestyle=options.getfieldvalue('explinestyle',['-']*len(filenames)) 32 linecolor=options.getfieldvalue('explinecolor',['k']*len(filenames)) 33 fill=options.getfieldvalue('expfill',[0]*len(filenames)) 34 alpha=options.getfieldvalue('expfillalpha',[1]*len(filenames)) 35 facecolor=options.getfieldvalue('expfillcolor',['r']*len(filenames)) 36 unitmultiplier=options.getfieldvalue('unit',1) 37 for i in range(len(filenames)): 38 linestylei=linestyle[i] 39 linecolori=linecolor[i] 40 linewidthi=linewidth[i] 41 alphai=alpha[i] 42 facecolori=facecolor[i] 43 filenamei=filenames[i] 44 filli=fill[i] 45 domain=expread(filenamei) 46 for j in range(len(domain)): 47 if domain[j]['nods']==1: 48 ax.plot(domain[j]['x']*unitmultiplier,domain[j]['y']*unitmultiplier,'o',mec='k',mfc='r',ms=10) 49 elif filli: 50 verts=np.column_stack((domain[j]['x'],domain[j]['y'])) 51 codes=[Path.MOVETO] + [Path.LINETO]*(len(domain[j]['x'])-2) + [Path.CLOSEPOLY] 52 path=Path(verts, codes) 53 patch=patches.PathPatch(path,facecolor=facecolori,edgecolor=linecolori,alpha=alphai, 54 lw=linewidthi) 55 ax.add_patch(patch) 56 else: 57 x=domain[j]['x'].tolist() # since expread returns a string representation of the arrays 58 y=domain[j]['y'].tolist() 59 ax.plot(x*unitmultiplier,y*unitmultiplier,ls=linestylei,lw=linewidthi,c=linecolori) -
issm/trunk-jpl/src/py3/exp/expread.py
r19895 r23670 1 1 import os.path 2 import numpy 2 import numpy as np 3 3 from collections import OrderedDict 4 4 import MatlabFuncs as m 5 5 6 6 def expread(filename): 7 7 8 """ 9 8 10 EXPREAD - read a file exp and build a Structure 9 11 … … 23 25 24 26 See also EXPDOC, EXPWRITEASVERTICES 27 25 28 """ 26 27 29 #some checks 28 30 if not os.path.exists(filename): … … 31 33 #initialize number of profile 32 34 contours=[] 33 34 35 #open file 35 36 fid=open(filename,'r') 36 37 37 #loop over the number of profiles 38 38 while True: 39 40 39 #update number of profiles 41 40 contour=OrderedDict() 42 43 41 #Get file name 44 42 A=fid.readline() … … 50 48 if not (len(A) == 2 and m.strcmp(A[0],'##') and m.strncmp(A[1],'Name:',5)): 51 49 break 50 52 51 if len(A[1])>5: 53 52 contour['name']=A[1][5:-1] … … 59 58 if not (len(A) == 2 and m.strcmp(A[0],'##') and m.strncmp(A[1],'Icon:',5)): 60 59 break 61 62 60 #Get Info 63 61 A=fid.readline().split() … … 72 70 #Get Info 73 71 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 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')): 76 74 break 77 78 75 #Get Coordinates 79 contour['x']=n umpy.empty(contour['nods'])80 contour['y']=n umpy.empty(contour['nods'])76 contour['x']=np.empty(contour['nods']) 77 contour['y']=np.empty(contour['nods']) 81 78 for i in range(int(contour['nods'])): 82 79 A=fid.readline().split() … … 93 90 94 91 contours.append(contour) 95 96 92 #close file 97 93 fid.close() 98 99 94 return contours 100 -
issm/trunk-jpl/src/py3/exp/expwrite.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 3 3 def expwrite(contours,filename): … … 21 21 fid=open(filename,'w') 22 22 for x,y in zip(contours['x'],contours['y']): 23 #if n umpy.size(contour['x'])!=numpy.size(contour['y']):23 #if np.size(contour['x'])!=np.size(contour['y']): 24 24 if len(x)!=len(y): 25 25 raise RuntimeError("contours x and y coordinates must be of identical size") … … 36 36 fid.write("%s\n" % '## Icon:0') 37 37 fid.write("%s\n" % '# Points Count Value') 38 #fid.write("%i %f\n" % (n umpy.size(contour['x']),contour['density']))39 fid.write("%i %f\n" % (n umpy.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)) 40 40 fid.write("%s\n" % '# X pos Y pos') 41 41 #for x,y in zip(contour['x'],contour['y']): -
issm/trunk-jpl/src/py3/extrusion/DepthAverage.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from project2d import project2d 3 3 … … 46 46 47 47 if vec2d: 48 vector_average=vector_average.reshape(-1, 1)48 vector_average=vector_average.reshape(-1,) 49 49 50 50 return vector_average -
issm/trunk-jpl/src/py3/extrusion/project2d.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 3 3 def project2d(md3d,value,layer): … … 45 45 46 46 if vec2d: 47 projection_value=projection_value.reshape(-1, 1)47 projection_value=projection_value.reshape(-1,) 48 48 49 49 return projection_value -
issm/trunk-jpl/src/py3/extrusion/project3d.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from pairoptions import pairoptions 3 3 4 def project3d(md,* *kwargs):4 def project3d(md,*args): 5 5 """ 6 6 PROJECT3D - vertically project a vector from 2d mesh … … 30 30 31 31 #retrieve parameters from options. 32 options = pairoptions(* *kwargs)32 options = pairoptions(*args) 33 33 vector2d = options.getfieldvalue('vector') #mandatory 34 34 vectype = options.getfieldvalue('type') #mandatory … … 37 37 38 38 vector1d=False 39 if isinstance(vector2d,n umpy.ndarray) and numpy.ndim(vector2d)==1:39 if isinstance(vector2d,np.ndarray) and np.ndim(vector2d)==1: 40 40 vector1d=True 41 vector2d=vector2d.reshape(-1, 1)41 vector2d=vector2d.reshape(-1,) 42 42 43 if isinstance(vector2d,(bool,int,float)) or n umpy.size(vector2d)==1:43 if isinstance(vector2d,(bool,int,float)) or np.size(vector2d)==1: 44 44 projected_vector=vector2d 45 45 … … 47 47 48 48 #Initialize 3d vector 49 if vector2d.shape[0]==md.mesh.numberofvertices2d: 50 projected_vector=(paddingvalue*numpy.ones((md.mesh.numberofvertices, numpy.size(vector2d,axis=1)))).astype(vector2d.dtype) 51 elif vector2d.shape[0]==md.mesh.numberofvertices2d+1: 52 projected_vector=(paddingvalue*numpy.ones((md.mesh.numberofvertices+1,numpy.size(vector2d,axis=1)))).astype(vector2d.dtype) 53 projected_vector[-1,:]=vector2d[-1,:] 54 vector2d=vector2d[:-1,:] 49 if np.ndim(vector2d)==1: 50 if vector2d.shape[0]==md.mesh.numberofvertices2d: 51 projected_vector=(paddingvalue*np.ones((md.mesh.numberofvertices))).astype(vector2d.dtype) 52 elif vector2d.shape[0]==md.mesh.numberofvertices2d+1: 53 projected_vector=(paddingvalue*np.ones((md.mesh.numberofvertices+1))).astype(vector2d.dtype) 54 projected_vector[-1]=vector2d[-1] 55 vector2d=vector2d[:-1] 56 else: 57 raise TypeError("vector length not supported") 58 #Fill in 59 if layer==0: 60 for i in range(md.mesh.numberoflayers): 61 projected_vector[(i*md.mesh.numberofvertices2d):((i+1)*md.mesh.numberofvertices2d)]=vector2d 62 else: 63 projected_vector[((layer-1)*md.mesh.numberofvertices2d):(layer*md.mesh.numberofvertices2d)]=vector2d 55 64 else: 56 raise TypeError("vector length not supported") 65 if vector2d.shape[0]==md.mesh.numberofvertices2d: 66 projected_vector=(paddingvalue*np.ones((md.mesh.numberofvertices,np.size(vector2d,axis=1)))).astype(vector2d.dtype) 67 elif vector2d.shape[0]==md.mesh.numberofvertices2d+1: 68 projected_vector=(paddingvalue*np.ones((md.mesh.numberofvertices+1,np.size(vector2d,axis=1)))).astype(vector2d.dtype) 69 projected_vector[-1,:]=vector2d[-1,:] 70 vector2d=vector2d[:-1,:] 71 else: 72 raise TypeError("vector length not supported") 73 #Fill in 74 if layer==0: 75 for i in range(md.mesh.numberoflayers): 76 projected_vector[(i*md.mesh.numberofvertices2d):((i+1)*md.mesh.numberofvertices2d),:]=vector2d 77 else: 78 projected_vector[((layer-1)*md.mesh.numberofvertices2d):(layer*md.mesh.numberofvertices2d),:]=vector2d 57 79 58 #Fill in59 if layer==0:60 for i in range(md.mesh.numberoflayers):61 projected_vector[(i*md.mesh.numberofvertices2d):((i+1)*md.mesh.numberofvertices2d),:]=vector2d62 else:63 projected_vector[((layer-1)*md.mesh.numberofvertices2d):(layer*md.mesh.numberofvertices2d),:]=vector2d64 80 65 81 elif vectype.lower()=='element': 66 82 67 83 #Initialize 3d vector 68 if vector2d.shape[0]==md.mesh.numberofelements2d: 69 projected_vector=(paddingvalue*numpy.ones((md.mesh.numberofelements, numpy.size(vector2d,axis=1)))).astype(vector2d.dtype) 70 elif vector2d.shape[0]==md.mesh.numberofelements2d+1: 71 projected_vector=(paddingvalue*numpy.ones((md.mesh.numberofelements+1,numpy.size(vector2d,axis=1)))).astype(vector2d.dtype) 72 projected_vector[-1,:]=vector2d[-1,:] 73 vector2d=vector2d[:-1,:] 84 if np.ndim(vector2d)==1: 85 if vector2d.shape[0]==md.mesh.numberofelements2d: 86 projected_vector=(paddingvalue*np.ones((md.mesh.numberofelements))).astype(vector2d.dtype) 87 elif vector2d.shape[0]==md.mesh.numberofelements2d+1: 88 projected_vector=(paddingvalue*np.ones((md.mesh.numberofelements+1))).astype(vector2d.dtype) 89 projected_vector[-1]=vector2d[-1] 90 vector2d=vector2d[:-1] 91 else: 92 raise TypeError("vector length not supported") 93 #Fill in 94 if layer==0: 95 for i in range(md.mesh.numberoflayers-1): 96 projected_vector[(i*md.mesh.numberofelements2d):((i+1)*md.mesh.numberofelements2d)]=vector2d 97 else: 98 projected_vector[((layer-1)*md.mesh.numberofelements2d):(layer*md.mesh.numberofelements2d)]=vector2d 74 99 else: 75 raise TypeError("vector length not supported") 76 77 #Fill in 78 if layer==0: 79 for i in range(md.mesh.numberoflayers-1): 80 projected_vector[(i*md.mesh.numberofelements2d):((i+1)*md.mesh.numberofelements2d),:]=vector2d 81 else: 82 projected_vector[((layer-1)*md.mesh.numberofelements2d):(layer*md.mesh.numberofelements2d),:]=vector2d 100 if vector2d.shape[0]==md.mesh.numberofelements2d: 101 projected_vector=(paddingvalue*np.ones((md.mesh.numberofelements, np.size(vector2d,axis=1)))).astype(vector2d.dtype) 102 elif vector2d.shape[0]==md.mesh.numberofelements2d+1: 103 projected_vector=(paddingvalue*np.ones((md.mesh.numberofelements+1,np.size(vector2d,axis=1)))).astype(vector2d.dtype) 104 projected_vector[-1,:]=vector2d[-1,:] 105 vector2d=vector2d[:-1,:] 106 else: 107 raise TypeError("vector length not supported") 108 #Fill in 109 if layer==0: 110 for i in range(md.mesh.numberoflayers-1): 111 projected_vector[(i*md.mesh.numberofelements2d):((i+1)*md.mesh.numberofelements2d),:]=vector2d 112 else: 113 projected_vector[((layer-1)*md.mesh.numberofelements2d):(layer*md.mesh.numberofelements2d),:]=vector2d 83 114 84 115 else: -
issm/trunk-jpl/src/py3/geometry/FlagElements.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 import os 3 3 #from basinzoom import basinzoon … … 24 24 if isinstance(region,str): 25 25 if not region: 26 flag=n umpy.zeros(md.mesh.numberofelements,bool)26 flag=np.zeros(md.mesh.numberofelements,bool) 27 27 invert=0 28 28 elif m.strcmpi(region,'all'): 29 flag=n umpy.ones(md.mesh.numberofelements,bool)29 flag=np.ones(md.mesh.numberofelements,bool) 30 30 invert=0 31 31 else: … … 44 44 xlim,ylim=basinzoom('basin',region) 45 45 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=n umpy.prod(flag_nodes[md.mesh.elements],axis=1).astype(bool)46 flag=np.prod(flag_nodes[md.mesh.elements],axis=1).astype(bool) 47 47 else: 48 48 #ok, flag elements 49 [flag,dum]=ContourToMesh(md.mesh.elements[:,0:3].copy(),md.mesh.x,md.mesh.y,region,'element',1)49 flag=ContourToMesh(md.mesh.elements[:,0:3].copy(),md.mesh.x,md.mesh.y,region,'element',1) 50 50 flag=flag.astype(bool) 51 51 52 52 if invert: 53 flag=n umpy.logical_not(flag)53 flag=np.logical_not(flag) 54 54 55 elif isinstance(region,n umpy.ndarray) or isinstance(region,bool):56 if n umpy.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: 57 57 flag=region 58 elif n umpy.size(region,0)==md.mesh.numberofvertices:59 flag=(n umpy.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)) 60 60 else: 61 61 raise TypeError("Flaglist for region must be of same size as number of elements in model.") -
issm/trunk-jpl/src/py3/geometry/GetAreas.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 3 def GetAreas(index,x,y,z=n umpy.array([])):3 def GetAreas(index,x,y,z=np.array([])): 4 4 """ 5 5 GETAREAS - compute areas or volumes of elements … … 18 18 19 19 #get number of elements and number of nodes 20 nels=n umpy.size(index,axis=0)21 nods=n umpy.size(x)20 nels=np.size(index,axis=0) 21 nods=np.size(x) 22 22 23 23 #some checks 24 if n umpy.size(y)!=nods or (z and numpy.size(z)!=nods):24 if np.size(y)!=nods or (z and np.size(z)!=nods): 25 25 raise TypeError("GetAreas error message: x,y and z do not have the same length.") 26 if n umpy.max(index)>nods:26 if np.max(index)>nods: 27 27 raise TypeError("GetAreas error message: index should not have values above %d." % nods) 28 if (not z and n umpy.size(index,axis=1)!=3):28 if (not z and np.size(index,axis=1)!=3): 29 29 raise TypeError("GetAreas error message: index should have 3 columns for 2d meshes.") 30 if (z and n umpy.size(index,axis=1)!=6):30 if (z and np.size(index,axis=1)!=6): 31 31 raise TypeError("GetAreas error message: index should have 6 columns for 3d meshes.") 32 32 33 33 #initialization 34 areas=n umpy.zeros(nels)34 areas=np.zeros(nels) 35 35 x1=x[index[:,0]-1] 36 36 x2=x[index[:,1]-1] … … 46 46 else: 47 47 #V=area(triangle)*1/3(z1+z2+z3) 48 thickness=n umpy.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]) 49 49 areas=(0.5*((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)))*thickness 50 50 -
issm/trunk-jpl/src/py3/geometry/SegIntersect.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 3 3 def SegIntersect(seg1,seg2): … … 24 24 yD=seg2[1,1] 25 25 26 O2A=n umpy.array([xA,yA])-numpy.array([xD/2.+xC/2.,yD/2.+yC/2.])27 O2B=n umpy.array([xB,yB])-numpy.array([xD/2.+xC/2.,yD/2.+yC/2.])28 O1C=n umpy.array([xC,yC])-numpy.array([xA/2.+xB/2.,yB/2.+yA/2.])29 O1D=n umpy.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.]) 30 30 31 n1=n umpy.array([yA-yB,xB-xA]) #normal vector to segA32 n2=n umpy.array([yC-yD,xD-xC]) #normal vector to segB31 n1=np.array([yA-yB,xB-xA]) #normal vector to segA 32 n2=np.array([yC-yD,xD-xC]) #normal vector to segB 33 33 34 test1=n umpy.dot(n2,O2A)35 test2=n umpy.dot(n2,O2B)34 test1=np.dot(n2,O2A) 35 test2=np.dot(n2,O2B) 36 36 37 37 if test1*test2>0: … … 39 39 return bval 40 40 41 test3=n umpy.dot(n1,O1C)42 test4=n umpy.dot(n1,O1D)41 test3=np.dot(n1,O1C) 42 test4=np.dot(n1,O1D) 43 43 44 44 if test3*test4>0: … … 47 47 48 48 #if colinear 49 if test1*test2==0 and test3*test4==0 and n umpy.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: 50 50 51 51 #projection on the axis O1O2 52 O2O1=n umpy.array([xA/2.+xB/2.,yB/2.+yA/2.])-numpy.array([xD/2.+xC/2.,yD/2.+yC/2.])53 O1A=n umpy.dot(O2O1,(O2A-O2O1))54 O1B=n umpy.dot(O2O1,(O2B-O2O1))55 O1C=n umpy.dot(O2O1,O1C)56 O1D=n umpy.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) 57 57 58 58 #test if one point is included in the other segment (->bval=1) -
issm/trunk-jpl/src/py3/geometry/slope.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from GetNodalFunctionsCoeff import GetNodalFunctionsCoeff 3 3 … … 34 34 35 35 summation=np.array([[1],[1],[1]]) 36 sx=np.dot(surf[index-1 ]*alpha,summation).reshape(-1,)37 sy=np.dot(surf[index-1 ]*beta,summation).reshape(-1,)36 sx=np.dot(surf[index-1,0]*alpha,summation).reshape(-1,) 37 sy=np.dot(surf[index-1,0]*beta,summation).reshape(-1,) 38 38 39 39 s=np.sqrt(sx**2+sy**2) -
issm/trunk-jpl/src/py3/interp/SectionValues.py
r21255 r23670 1 1 import os 2 2 from expread import expread 3 import numpy as np3 import numpy as np 4 4 from project2d import project2d 5 5 #from InterpFromMesh2d import InterpFromMesh2d … … 127 127 128 128 #Interpolation of data on specified points 129 data_interp=InterpFromMeshToMesh3d(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,data,X3,Y3,Z3,np.nan) 129 data_interp=InterpFromMeshToMesh3d(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,data,X3,Y3,Z3,np.nan)[0] 130 130 131 131 #build outputs -
issm/trunk-jpl/src/py3/interp/averaging.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from GetAreas import GetAreas 3 from scipy.sparse import csc_matrix4 3 import MatlabFuncs as m 4 try: 5 from scipy.sparse import csc_matrix 6 except ImportError: 7 print("could not import scipy, no averaging capabilities enabled") 5 8 6 9 def averaging(md,data,iterations,layer=0): -
issm/trunk-jpl/src/py3/interp/holefiller.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from scipy.spatial import cKDTree 3 3 -
issm/trunk-jpl/src/py3/interp/interp.py
r21255 r23670 1 1 # module for inperpolating/smoothing data 2 import numpy as np2 import numpy as np 3 3 from scipy.interpolate import CloughTocher2DInterpolator, Rbf 4 4 from scipy.spatial import cKDTree -
issm/trunk-jpl/src/py3/inversions/marshallcostfunctions.py
r19895 r23670 1 1 import copy 2 from EnumDefinitions import *3 2 4 3 def marshallcostfunctions(cost_functions): 5 4 6 #copy list first 7 data=copy.deepcopy(cost_functions) 5 cfDict={101:'SurfaceAbsVelMisfit', 6 102:'SurfaceRelVelMisfit', 7 103:'SurfaceLogVelMisfit', 8 104:'SurfaceLogVxVyMisfit', 9 105:'SurfaceAverageVelMisfit', 10 201:'ThicknessAbsMisfit', 11 501:'DragCoefficientAbsGradient', 12 502:'RheologyBbarAbsGradient', 13 503:'ThicknessAbsGradient', 14 504:'ThicknessAlongGradient', 15 505:'ThicknessAcrossGradient',} 8 16 9 #convert to Enums 10 pos=[i for i,x in enumerate(cost_functions) if x==101]; 11 for i in pos: data[i]=SurfaceAbsVelMisfitEnum() 12 pos=[i for i,x in enumerate(cost_functions) if x==102]; 13 for i in pos: data[i]=SurfaceRelVelMisfitEnum() 14 pos=[i for i,x in enumerate(cost_functions) if x==103]; 15 for i in pos: data[i]=SurfaceLogVelMisfitEnum() 16 pos=[i for i,x in enumerate(cost_functions) if x==104]; 17 for i in pos: data[i]=SurfaceLogVxVyMisfitEnum() 18 pos=[i for i,x in enumerate(cost_functions) if x==105]; 19 for i in pos: data[i]=SurfaceAverageVelMisfitEnum() 20 pos=[i for i,x in enumerate(cost_functions) if x==201]; 21 for i in pos: data[i]=ThicknessAbsMisfitEnum() 22 pos=[i for i,x in enumerate(cost_functions) if x==501]; 23 for i in pos: data[i]=DragCoefficientAbsGradientEnum() 24 pos=[i for i,x in enumerate(cost_functions) if x==502]; 25 for i in pos: data[i]=RheologyBbarAbsGradientEnum() 26 pos=[i for i,x in enumerate(cost_functions) if x==503]; 27 for i in pos: data[i]=ThicknessAbsGradientEnum() 28 pos=[i for i,x in enumerate(cost_functions) if x==504]; 29 for i in pos: data[i]=ThicknessAlongGradientEnum() 30 pos=[i for i,x in enumerate(cost_functions) if x==505]; 31 for i in pos: data[i]=ThicknessAcrossGradientEnum() 17 data=[cfDict[cf] for cf in cost_functions] 18 # #copy list first 19 # data=copy.deepcopy(cost_functions) 20 21 # #convert to strings 22 # pos=[i for i,x in enumerate(cost_functions) if x==101]; 23 # for i in pos: data[i]='SurfaceAbsVelMisfit' 24 # pos=[i for i,x in enumerate(cost_functions) if x==102]; 25 # for i in pos: data[i]='SurfaceRelVelMisfit' 26 # pos=[i for i,x in enumerate(cost_functions) if x==103]; 27 # for i in pos: data[i]='SurfaceLogVelMisfit' 28 # pos=[i for i,x in enumerate(cost_functions) if x==104]; 29 # for i in pos: data[i]='SurfaceLogVxVyMisfit' 30 # pos=[i for i,x in enumerate(cost_functions) if x==105]; 31 # for i in pos: data[i]='SurfaceAverageVelMisfit' 32 # pos=[i for i,x in enumerate(cost_functions) if x==201]; 33 # for i in pos: data[i]='ThicknessAbsMisfit' 34 # pos=[i for i,x in enumerate(cost_functions) if x==501]; 35 # for i in pos: data[i]='DragCoefficientAbsGradient' 36 # pos=[i for i,x in enumerate(cost_functions) if x==502]; 37 # for i in pos: data[i]='RheologyBbarAbsGradient' 38 # pos=[i for i,x in enumerate(cost_functions) if x==503]; 39 # for i in pos: data[i]='ThicknessAbsGradient' 40 # pos=[i for i,x in enumerate(cost_functions) if x==504]; 41 # for i in pos: data[i]='ThicknessAlongGradient' 42 # pos=[i for i,x in enumerate(cost_functions) if x==505]; 43 # for i in pos: data[i]='ThicknessAcrossGradient' 32 44 33 45 return data -
issm/trunk-jpl/src/py3/inversions/parametercontroldrag.py
r21255 r23670 20 20 21 21 #process options 22 options=pairoptions(* *kwargs)22 options=pairoptions(*args) 23 23 24 24 #control type -
issm/trunk-jpl/src/py3/io/loadmodel.py
r19895 r23670 1 1 from loadvars import loadvars 2 2 from dbm import whichdb 3 from netCDF4 import Dataset 3 4 4 5 def loadmodel(path): … … 17 18 pass 18 19 else: 19 raise IOError("loadmodel error message: file '%s' does not exist" % path) 20 try: 21 NCFile=Dataset(path,mode='r') 22 NCFile.close() 23 pass 24 except RuntimeError: 25 raise IOError("loadmodel error message: file '%s' does not exist" % path) 26 # try: 27 #recover model on file and name it md 28 struc=loadvars(path) 29 name=[key for key in struc.keys()] 30 if len(name)>1: 31 raise IOError("loadmodel error message: file '%s' contains several variables. Only one model should be present." % path) 20 32 21 try: 22 #recover model on file and name it md 23 struc=loadvars(path) 24 25 name=[key for key in struc.keys()] 26 if len(name)>1: 27 raise IOError("loadmodel error message: file '%s' contains several variables. Only one model should be present." % path) 28 29 md=struc[name[0]] 30 return md 31 32 except Exception as me: 33 print(me) 34 raise IOError("could not load model '%s'" % path) 35 33 md=struc[name[0]] 34 return md -
issm/trunk-jpl/src/py3/io/loadvars.py
r19895 r23670 1 1 import shelve 2 2 import os.path 3 import numpy as np 4 from netCDF4 import Dataset 5 from netCDF4 import chartostring 6 from re import findall 7 from os import path 8 from collections import OrderedDict 3 9 from dbm import whichdb 10 from model import * 4 11 5 12 def loadvars(*args): … … 51 58 if whichdb(filename): 52 59 print("Loading variables from file '%s'." % filename) 53 else: 54 raise IOError("File '%s' not found." % filename) 55 56 my_shelf = shelve.open(filename,'r') # 'r' for read-only 57 58 if nvdict: 59 for name in nvdict.keys(): 60 try: 60 61 my_shelf = shelve.open(filename,'r') # 'r' for read-only 62 if nvdict: 63 for name in nvdict.keys(): 64 try: 65 nvdict[name] = my_shelf[name] 66 print("Variable '%s' loaded." % name) 67 except KeyError: 68 value = None 69 print("Variable '%s' not found." % name) 70 71 else: 72 for name in my_shelf.keys(): 61 73 nvdict[name] = my_shelf[name] 62 74 print("Variable '%s' loaded." % name) 63 except KeyError: 64 value = None 65 print("Variable '%s' not found." % name) 75 76 my_shelf.close() 66 77 67 78 else: 68 for name in my_shelf.keys(): 69 nvdict[name] = my_shelf[name] 70 print("Variable '%s' loaded." % name) 71 72 my_shelf.close() 73 79 try: 80 NCFile=Dataset(filename,mode='r') 81 NCFile.close() 82 except RuntimeError: 83 raise IOError("File '%s' not found." % filename) 84 85 classtype,classtree=netCDFread(filename) 86 nvdict['md']=model() 87 NCFile=Dataset(filename,mode='r') 88 for mod in dict.keys(classtype): 89 if np.size(classtree[mod])>1: 90 curclass=NCFile.groups[classtree[mod][0]].groups[classtree[mod][1]] 91 if classtype[mod][0]=='list': 92 keylist=[key for key in curclass.groups] 93 try: 94 steplist=[int(key) for key in curclass.groups] 95 except ValueError: 96 steplist=[int(findall(r'\d+',key)[0]) for key in keylist] 97 indexlist=[index*(len(curclass.groups)-1)/max(1,max(steplist)) for index in steplist] 98 listtype=curclass.groups[keylist[0]].classtype 99 if listtype=='dict': 100 nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [OrderedDict() for i in range(max(1,len(curclass.groups)))] 101 else: 102 nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [getattr(__import__(listtype),listtype)() for i in range(max(1,len(curclass.groups)))] 103 Tree=nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]][:] 104 else: 105 nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = getattr(classtype[mod][1],classtype[mod][0])() 106 Tree=nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] 107 else: 108 curclass=NCFile.groups[classtree[mod][0]] 109 nvdict['md'].__dict__[mod] = getattr(classtype[mod][1],classtype[mod][0])() 110 Tree=nvdict['md'].__dict__[classtree[mod][0]] 111 #treating groups that are lists 112 for i in range(0,max(1,len(curclass.groups))): 113 if len(curclass.groups)>0: 114 listclass=curclass.groups[keylist[i]] 115 else: 116 listclass=curclass 117 for var in listclass.variables: 118 if var not in ['errlog','outlog']: 119 varval=listclass.variables[str(var)] 120 vardim=varval.ndim 121 try: 122 val_type=str(varval.dtype) 123 except AttributeError: 124 val_type=type(varval) 125 if vardim==0: 126 if type(Tree)==list: 127 t=indexlist[i] 128 if listtype=='dict': 129 Tree[t][str(var)]=varval[0] 130 else: 131 Tree[t].__dict__[str(var)]=varval[0] 132 else: 133 if str(varval[0])=='': 134 Tree.__dict__[str(var)]=[] 135 elif varval[0]=='True': 136 Tree.__dict__[str(var)]=True 137 elif varval[0]=='False': 138 Tree.__dict__[str(var)]=False 139 else: 140 Tree.__dict__[str(var)]=varval[0] 141 142 elif vardim==1: 143 if varval.dtype==str: 144 if varval.shape[0]==1: 145 Tree.__dict__[str(var)]=[str(varval[0]),] 146 elif 'True' in varval[:] or 'False' in varval[:]: 147 Tree.__dict__[str(var)]=np.asarray([V=='True' for V in varval[:]],dtype=bool) 148 else: 149 Tree.__dict__[str(var)]=[str(vallue) for vallue in varval[:]] 150 else: 151 if type(Tree)==list: 152 t=indexlist[i] 153 if listtype=='dict': 154 Tree[t][str(var)]=varval[:] 155 else: 156 Tree[t].__dict__[str(var)]=varval[:] 157 else: 158 try: 159 #some thing specifically require a list 160 mdtype=type(Tree.__dict__[str(var)]) 161 except KeyError: 162 mdtype=float 163 if mdtype==list: 164 Tree.__dict__[str(var)]=[mdval for mdval in varval[:]] 165 else: 166 Tree.__dict__[str(var)]=varval[:] 167 elif vardim==2: 168 #dealling with dict 169 if varval.dtype==str: #that is for toolkits wich needs to be ordered 170 if any(varval[:,0]=='toolkit'): #toolkit definition have to be first 171 Tree.__dict__[str(var)]=OrderedDict([('toolkit', str(varval[np.where(varval[:,0]=='toolkit')[0][0],1]))]) 172 173 strings1=[str(arg[0]) for arg in varval if arg[0]!='toolkits'] 174 strings2=[str(arg[1]) for arg in varval if arg[0]!='toolkits'] 175 Tree.__dict__[str(var)].update(list(zip(strings1, strings2))) 176 else: 177 if type(Tree)==list: 178 #t=int(keylist[i][-1])-1 179 t=indexlist[i] 180 if listtype=='dict': 181 Tree[t][str(var)]=varval[:,:] 182 else: 183 Tree[t].__dict__[str(var)]=varval[:,:] 184 else: 185 Tree.__dict__[str(var)]=varval[:,:] 186 elif vardim==3: 187 if type(Tree)==list: 188 t=indexlist[i] 189 if listtype=='dict': 190 Tree[t][str(var)]=varval[:,:,:] 191 else: 192 Tree[t].__dict__[str(var)]=varval[:,:,:] 193 else: 194 Tree.__dict__[str(var)]=varval[:,:,:] 195 else: 196 print('table dimension greater than 3 not implemented yet') 197 for attr in listclass.ncattrs(): 198 if attr!='classtype': #classtype is for treatment, don't get it back 199 if type(Tree)==list: 200 t=indexlist[i] 201 if listtype=='dict': 202 Tree[t][str(attr).swapcase()]=str(listclass.getncattr(attr)) 203 else: 204 Tree[t].__dict__[str(attr).swapcase()]=str(listclass.getncattr(attr)) 205 else: 206 Tree.__dict__[str(attr).swapcase()]=str(listclass.getncattr(attr)) 207 if listclass.getncattr(attr)=='True': 208 Tree.__dict__[str(attr).swapcase()]=True 209 elif listclass.getncattr(attr)=='False': 210 Tree.__dict__[str(attr).swapcase()]=False 211 NCFile.close() 74 212 if len(args) >= 2 and isinstance(args[1],str): # (value) 75 213 value=[nvdict[name] for name in args[1:]] … … 83 221 return nvdict 84 222 223 224 def netCDFread(filename): 225 print(('Opening {} for reading '.format(filename))) 226 NCData=Dataset(filename, 'r') 227 class_dict={} 228 class_tree={} 229 230 for group in NCData.groups: 231 if len(NCData.groups[group].groups)>0: 232 for subgroup in NCData.groups[group].groups: 233 classe=str(group)+'.'+str(subgroup) 234 class_dict[classe]=[str(getattr(NCData.groups[group].groups[subgroup],'classtype')),] 235 if class_dict[classe][0] not in ['dict','list','cell']: 236 class_dict[classe].append(__import__(class_dict[classe][0])) 237 class_tree[classe]=[group,subgroup] 238 else: 239 classe=str(group) 240 try: 241 class_dict[classe]=[str(getattr(NCData.groups[group],'classtype')),] 242 if class_dict[classe][0] not in ['dict','list','cell']: 243 class_dict[classe].append(__import__(class_dict[classe][0])) 244 class_tree[classe]=[group,] 245 except AttributeError: 246 print(('group {} is empty'.format(group))) 247 NCData.close() 248 return class_dict,class_tree -
issm/trunk-jpl/src/py3/materials/TMeltingPoint.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 3 3 def TMeltingPoint(reftemp,pressure): -
issm/trunk-jpl/src/py3/materials/cuffey.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 3 3 def cuffey(temperature): … … 6 6 7 7 rigidity (in s^(1/3)Pa) is the flow law parameter in the flow law sigma=B*e(1/3) 8 (Cuffey and Paterson, p75). 8 (Cuffey and Paterson, p75). 9 9 temperature is in Kelvin degrees 10 10 … … 12 12 rigidity=cuffey(temperature) 13 13 """ 14 15 if n umpy.any(temperature<0.):14 15 if np.any(temperature<0.): 16 16 raise RuntimeError("input temperature should be in Kelvin (positive)") 17 18 T = temperature.reshape(-1,)-273.1519 17 20 rigidity=numpy.zeros_like(T) 21 pos=numpy.nonzero(T<=-45) 22 rigidity[pos]=10**8*(-0.000396645116301*(T[pos]+50)**3+ 0.013345579471334*(T[pos]+50)**2 -0.356868703259105*(T[pos]+50)+7.272363035371383) 23 pos=numpy.nonzero(numpy.logical_and(-45<=T,T<-40)) 24 rigidity[pos]=10**8*(-0.000396645116301*(T[pos]+45)**3+ 0.007395902726819*(T[pos]+45)**2 -0.253161292268336*(T[pos]+45)+5.772078366321591) 25 pos=numpy.nonzero(numpy.logical_and(-40<=T,T<-35)) 26 rigidity[pos]=10**8*(0.000408322072669*(T[pos]+40)**3+ 0.001446225982305*(T[pos]+40)**2 -0.208950648722716*(T[pos]+40)+4.641588833612773) 27 pos=numpy.nonzero(numpy.logical_and(-35<=T,T<-30)) 28 rigidity[pos]=10**8*(-0.000423888728124*(T[pos]+35)**3+ 0.007571057072334*(T[pos]+35)**2 -0.163864233449525*(T[pos]+35)+3.684031498640382) 29 pos=numpy.nonzero(numpy.logical_and(-30<=T,T<-25)) 30 rigidity[pos]=10**8*(0.000147154327025*(T[pos]+30)**3+ 0.001212726150476*(T[pos]+30)**2 -0.119945317335478*(T[pos]+30)+3.001000667185614) 31 pos=numpy.nonzero(numpy.logical_and(-25<=T,T<-20)) 32 rigidity[pos]=10**8*(-0.000193435838672*(T[pos]+25)**3+ 0.003420041055847*(T[pos]+25)**2 -0.096781481303861*(T[pos]+25)+2.449986525148220) 33 pos=numpy.nonzero(numpy.logical_and(-20<=T,T<-15)) 34 rigidity[pos]=10**8*(0.000219771255067*(T[pos]+20)**3+ 0.000518503475772*(T[pos]+20)**2 -0.077088758645767*(T[pos]+20)+2.027400665191131) 35 pos=numpy.nonzero(numpy.logical_and(-15<=T,T<-10)) 36 rigidity[pos]=10**8*(-0.000653438900191*(T[pos]+15)**3+ 0.003815072301777*(T[pos]+15)**2 -0.055420879758021*(T[pos]+15)+1.682390865739973) 37 pos=numpy.nonzero(numpy.logical_and(-10<=T,T<-5)) 38 rigidity[pos]=10**8*(0.000692439419762*(T[pos]+10)**3 -0.005986511201093 *(T[pos]+10)**2 -0.066278074254598*(T[pos]+10)+1.418983411970382) 39 pos=numpy.nonzero(numpy.logical_and(-5<=T,T<-2)) 40 rigidity[pos]=10**8*(-0.000132282004110*(T[pos]+5)**3 +0.004400080095332*(T[pos]+5)**2 -0.074210229783403*(T[pos]+5)+ 1.024485188140279) 41 pos=numpy.nonzero(-2<=T) 42 rigidity[pos]=10**8*(-0.000132282004110*(T[pos]+2)**3 +0.003209542058346*(T[pos]+2)**2 -0.051381363322371*(T[pos]+2)+ 0.837883605537096) 18 if np.ndim(temperature)==2: 19 #T = temperature.reshape(-1,)-273.15 20 T = temperature.flatten()-273.15 21 elif isinstance(temperature,float) or isinstance(temperature,int): 22 T = np.array([temperature])-273.15 23 else: 24 T = temperature-273.15 25 26 27 rigidity=np.zeros_like(T) 28 pos=np.nonzero(T<=-45) 29 if len(pos): 30 rigidity[pos]=10**8*(-0.000396645116301*(T[pos]+50)**3+ 0.013345579471334*(T[pos]+50)**2 -0.356868703259105*(T[pos]+50)+7.272363035371383) 31 pos=np.nonzero(np.logical_and(-45<=T,T<-40)) 32 if len(pos): 33 rigidity[pos]=10**8*(-0.000396645116301*(T[pos]+45)**3+ 0.007395902726819*(T[pos]+45)**2 -0.253161292268336*(T[pos]+45)+5.772078366321591) 34 pos=np.nonzero(np.logical_and(-40<=T,T<-35)) 35 if len(pos): 36 rigidity[pos]=10**8*(0.000408322072669*(T[pos]+40)**3+ 0.001446225982305*(T[pos]+40)**2 -0.208950648722716*(T[pos]+40)+4.641588833612773) 37 pos=np.nonzero(np.logical_and(-35<=T,T<-30)) 38 if len(pos): 39 rigidity[pos]=10**8*(-0.000423888728124*(T[pos]+35)**3+ 0.007571057072334*(T[pos]+35)**2 -0.163864233449525*(T[pos]+35)+3.684031498640382) 40 pos=np.nonzero(np.logical_and(-30<=T,T<-25)) 41 if len(pos): 42 rigidity[pos]=10**8*(0.000147154327025*(T[pos]+30)**3+ 0.001212726150476*(T[pos]+30)**2 -0.119945317335478*(T[pos]+30)+3.001000667185614) 43 pos=np.nonzero(np.logical_and(-25<=T,T<-20)) 44 if len(pos): 45 rigidity[pos]=10**8*(-0.000193435838672*(T[pos]+25)**3+ 0.003420041055847*(T[pos]+25)**2 -0.096781481303861*(T[pos]+25)+2.449986525148220) 46 pos=np.nonzero(np.logical_and(-20<=T,T<-15)) 47 if len(pos): 48 rigidity[pos]=10**8*(0.000219771255067*(T[pos]+20)**3+ 0.000518503475772*(T[pos]+20)**2 -0.077088758645767*(T[pos]+20)+2.027400665191131) 49 pos=np.nonzero(np.logical_and(-15<=T,T<-10)) 50 if len(pos): 51 rigidity[pos]=10**8*(-0.000653438900191*(T[pos]+15)**3+ 0.003815072301777*(T[pos]+15)**2 -0.055420879758021*(T[pos]+15)+1.682390865739973) 52 pos=np.nonzero(np.logical_and(-10<=T,T<-5)) 53 if len(pos): 54 rigidity[pos]=10**8*(0.000692439419762*(T[pos]+10)**3 -0.005986511201093 *(T[pos]+10)**2 -0.066278074254598*(T[pos]+10)+1.418983411970382) 55 pos=np.nonzero(np.logical_and(-5<=T,T<-2)) 56 if len(pos): 57 rigidity[pos]=10**8*(-0.000132282004110*(T[pos]+5)**3 +0.004400080095332*(T[pos]+5)**2 -0.074210229783403*(T[pos]+5)+ 1.024485188140279) 58 pos=np.nonzero(-2<=T) 59 if len(pos): 60 rigidity[pos]=10**8*(-0.000132282004110*(T[pos]+2)**3 +0.003209542058346*(T[pos]+2)**2 -0.051381363322371*(T[pos]+2)+ 0.837883605537096) 43 61 44 62 #Now make sure that rigidity is positive 45 pos=n umpy.nonzero(rigidity<0)46 rigidity[pos]=1**6 63 pos=np.nonzero(rigidity<0) 64 rigidity[pos]=1**6 47 65 48 66 return rigidity 49 -
issm/trunk-jpl/src/py3/materials/paterson.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 3 3 def paterson(temperature): … … 12 12 """ 13 13 14 if n umpy.any(temperature<0.):14 if np.any(temperature<0.): 15 15 raise RuntimeError("input temperature should be in Kelvin (positive)") 16 16 17 if n umpy.ndim(temperature)==2:17 if np.ndim(temperature)==2: 18 18 #T = temperature.reshape(-1,)-273.15 19 19 T = temperature.flatten()-273.15 20 20 elif isinstance(temperature,float) or isinstance(temperature,int): 21 T = n umpy.array([temperature])-273.1521 T = np.array([temperature])-273.15 22 22 else: 23 23 T = temperature-273.15 … … 36 36 # rigidity=fittedmodel(temperature); 37 37 38 rigidity=n umpy.zeros_like(T)39 pos1=n umpy.nonzero(T<=-45)[0]38 rigidity=np.zeros_like(T) 39 pos1=np.nonzero(T<=-45)[0] 40 40 if len(pos1): 41 41 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=n umpy.nonzero(numpy.logical_and(-45<=T,T<-40))[0]42 pos2=np.nonzero(np.logical_and(-45<=T,T<-40))[0] 43 43 if len(pos2): 44 44 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=n umpy.nonzero(numpy.logical_and(-40<=T,T<-35))[0]45 pos3=np.nonzero(np.logical_and(-40<=T,T<-35))[0] 46 46 if len(pos3): 47 47 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=n umpy.nonzero(numpy.logical_and(-35<=T,T<-30))[0]48 pos4=np.nonzero(np.logical_and(-35<=T,T<-30))[0] 49 49 if len(pos4): 50 50 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=n umpy.nonzero(numpy.logical_and(-30<=T,T<-25))[0]51 pos5=np.nonzero(np.logical_and(-30<=T,T<-25))[0] 52 52 if len(pos5): 53 53 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=n umpy.nonzero(numpy.logical_and(-25<=T,T<-20))[0]54 pos6=np.nonzero(np.logical_and(-25<=T,T<-20))[0] 55 55 if len(pos6): 56 56 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=n umpy.nonzero(numpy.logical_and(-20<=T,T<-15))[0]57 pos7=np.nonzero(np.logical_and(-20<=T,T<-15))[0] 58 58 if len(pos7): 59 59 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=n umpy.nonzero(numpy.logical_and(-15<=T,T<-10))[0]60 pos8=np.nonzero(np.logical_and(-15<=T,T<-10))[0] 61 61 if len(pos8): 62 62 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=n umpy.nonzero(numpy.logical_and(-10<=T,T<-5))[0]63 pos9=np.nonzero(np.logical_and(-10<=T,T<-5))[0] 64 64 if len(pos9): 65 65 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=n umpy.nonzero(numpy.logical_and(-5<=T,T<-2))[0]66 pos10=np.nonzero(np.logical_and(-5<=T,T<-2))[0] 67 67 if len(pos10): 68 68 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=n umpy.nonzero(-2<=T)[0]69 pos11=np.nonzero(-2<=T)[0] 70 70 if len(pos11): 71 71 rigidity[pos11]=10**8*(-0.003748937622488*(T[pos11]+2)**3-0.018449844983174*(T[pos11]+2)**2 -0.057638157095631*(T[pos11]+2)+ 0.746900791092860) 72 72 73 73 #Now make sure that rigidity is positive 74 pos=n umpy.nonzero(rigidity<0)[0]74 pos=np.nonzero(rigidity<0)[0] 75 75 if len(pos): 76 76 rigidity[pos]=1.e6 -
issm/trunk-jpl/src/py3/mech/analyticaldamage.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from averaging import averaging 3 3 #from plotmodel import plotmodel -
issm/trunk-jpl/src/py3/mech/backstressfrominversion.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from averaging import averaging 3 3 from thomasparams import thomasparams -
issm/trunk-jpl/src/py3/mech/calcbackstress.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from averaging import averaging 3 3 from thomasparams import thomasparams -
issm/trunk-jpl/src/py3/mech/damagefrominversion.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 3 3 def damagefrominversion(md): -
issm/trunk-jpl/src/py3/mech/mechanicalproperties.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from GetNodalFunctionsCoeff import GetNodalFunctionsCoeff 3 3 from results import results … … 109 109 #eigenvalues and vectors for stress 110 110 value,directions=np.linalg.eig(stress); 111 idx= abs(value).argsort()[::-1] # sort in descendingorder111 idx=value.argsort()[::-1] # sort in descending algebraic (not absolute) order 112 112 value=value[idx] 113 113 directions=directions[:,idx] … … 117 117 #eigenvalues and vectors for strain 118 118 value,directions=np.linalg.eig(strain); 119 idx= abs(value).argsort()[::-1] # sort in descending order119 idx=value.argsort()[::-1] # sort in descending order 120 120 value=value[idx] 121 121 directions=directions[:,idx] … … 125 125 ##plug onto the model 126 126 ##NB: Matlab sorts the eigen value in increasing order, we want the reverse 127 stress=results()128 stress.xx=tau_xx129 stress.yy=tau_yy130 stress.xy=tau_xy131 stress.principalvalue1=valuesstress[:,0]132 stress.principalaxis1=directionsstress[:,0:2]133 stress.principalvalue2=valuesstress[:,1]134 stress.principalaxis2=directionsstress[:,2:4]135 stress.effectivevalue=1./np.sqrt(2.)*np.sqrt(stress.xx**2+stress.yy**2+2.*stress.xy**2)136 md.results.stress=stress137 127 138 128 strainrate=results() -
issm/trunk-jpl/src/py3/mech/robintemperature.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from scipy.special import erf 3 3 -
issm/trunk-jpl/src/py3/mech/steadystateiceshelftemp.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 3 3 def steadystateiceshelftemp(md,surfacetemp,basaltemp): … … 18 18 temperature=steadystateiceshelftemp(md,surfacetemp,basaltemp) 19 19 """ 20 21 20 if len(md.geometry.thickness)!=md.mesh.numberofvertices: 22 21 raise ValueError('steadystateiceshelftemp error message: thickness should have a length of ' + md.mesh.numberofvertices) -
issm/trunk-jpl/src/py3/mech/thomasparams.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from averaging import averaging 3 3 -
issm/trunk-jpl/src/py3/mesh/ComputeHessian.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from GetNodalFunctionsCoeff import GetNodalFunctionsCoeff 3 3 from GetAreas import GetAreas … … 20 20 21 21 #some variables 22 numberofnodes=n umpy.size(x)23 numberofelements=n umpy.size(index,axis=0)22 numberofnodes=np.size(x) 23 numberofelements=np.size(index,axis=0) 24 24 25 25 #some checks 26 if n umpy.size(field)!=numberofnodes and numpy.size(field)!=numberofelements:26 if np.size(field)!=numberofnodes and np.size(field)!=numberofelements: 27 27 raise TypeError("ComputeHessian error message: the given field size not supported yet") 28 28 if not m.strcmpi(type,'node') and not m.strcmpi(type,'element'): … … 33 33 linesize=3*numberofelements 34 34 35 #get areas and nodal functions coefficients N(x,y)=alpha x + beta y + gamma 35 #get areas and nodal functions coefficients N(x,y)=alpha x + beta y + gamma 36 36 [alpha,beta,dum]=GetNodalFunctionsCoeff(index,x,y) 37 37 areas=GetAreas(index,x,y) 38 38 39 39 #compute weights that hold the volume of all the element holding the node i 40 weights=m.sparse(line,n umpy.ones((linesize,1)),numpy.tile(areas.reshape(-1,1),(3,1)),numberofnodes,1)40 weights=m.sparse(line,np.ones((linesize,1),dtype=int),np.tile(areas,(3,1)),numberofnodes,1) 41 41 42 42 #compute field on nodes if on elements 43 if n umpy.size(field,axis=0)==numberofelements:44 field=m.sparse(line,n umpy.ones((linesize,1)),numpy.tile(areas*field,(3,1)),numberofnodes,1)/weights43 if np.size(field,axis=0)==numberofelements: 44 field=m.sparse(line,np.ones((linesize,1),dtype=int),np.tile(areas*field,(3,1)),numberofnodes,1)/weights 45 45 46 46 #Compute gradient for each element 47 grad_elx=n umpy.sum(field[index-1,0]*alpha,axis=1)48 grad_ely=n umpy.sum(field[index-1,0]*beta,axis=1)47 grad_elx=np.sum(field[index-1]*alpha,axis=1) 48 grad_ely=np.sum(field[index-1]*beta,axis=1) 49 49 50 50 #Compute gradient for each node (average of the elements around) 51 gradx=m.sparse(line,n umpy.ones((linesize,1)),numpy.tile((areas*grad_elx).reshape(-1,1),(3,1)),numberofnodes,1)52 grady=m.sparse(line,n umpy.ones((linesize,1)),numpy.tile((areas*grad_ely).reshape(-1,1),(3,1)),numberofnodes,1)51 gradx=m.sparse(line,np.ones((linesize,1),dtype=int),np.tile((areas*grad_elx),(3,1)),numberofnodes,1) 52 grady=m.sparse(line,np.ones((linesize,1),dtype=int),np.tile((areas*grad_ely),(3,1)),numberofnodes,1) 53 53 gradx=gradx/weights 54 54 grady=grady/weights 55 55 56 56 #Compute hessian for each element 57 hessian=n umpy.hstack((numpy.sum(gradx[index-1,0]*alpha,axis=1).reshape(-1,1),numpy.sum(grady[index-1,0]*alpha,axis=1).reshape(-1,1),numpy.sum(grady[index-1,0]*beta,axis=1).reshape(-1,1)))57 hessian=np.vstack((np.sum(gradx[index-1,0]*alpha,axis=1),np.sum(grady[index-1,0]*alpha,axis=1),np.sum(grady[index-1,0]*beta,axis=1))).T 58 58 59 59 if m.strcmpi(type,'node'): 60 60 #Compute Hessian on the nodes (average of the elements around) 61 hessian=n umpy.hstack((m.sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*hessian[:,0]).reshape(-1,1),(3,1)),numberofnodes,1)/weights, \62 m.sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*hessian[:,1]).reshape(-1,1),(3,1)),numberofnodes,1)/weights, \63 m.sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*hessian[:,2]).reshape(-1,1),(3,1)),numberofnodes,1)/weights ))61 hessian=np.hstack((m.sparse(line,np.ones((linesize,1),dtype=int),np.tile((areas*hessian[:,0]),(3,1)),numberofnodes,1)/weights, 62 m.sparse(line,np.ones((linesize,1),dtype=int),np.tile((areas*hessian[:,1]),(3,1)),numberofnodes,1)/weights, 63 m.sparse(line,np.ones((linesize,1),dtype=int),np.tile((areas*hessian[:,2]),(3,1)),numberofnodes,1)/weights )) 64 64 65 65 return hessian 66 -
issm/trunk-jpl/src/py3/mesh/ComputeMetric.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 3 3 def ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos): … … 17 17 b=hessian[:,1] 18 18 d=hessian[:,2] 19 lambda1=0.5*((a+d)+n umpy.sqrt(4.*b**2+(a-d)**2))20 lambda2=0.5*((a+d)-n umpy.sqrt(4.*b**2+(a-d)**2))21 pos1=n umpy.nonzero(lambda1==0.)[0]22 pos2=n umpy.nonzero(lambda2==0.)[0]23 pos3=n umpy.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] 24 24 25 25 #Modify the eigen values to control the shape of the elements 26 lambda1=n umpy.minimum(numpy.maximum(numpy.abs(lambda1)*scale/epsilon,1./hmax**2),1./hmin**2)27 lambda2=n umpy.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) 28 28 29 29 #compute eigen vectors 30 norm1=n umpy.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)) 31 31 v1x=2.*b/norm1 32 v1y=((d-a)+n umpy.sqrt((a-d)**2+4.*b**2))/norm133 norm2=n umpy.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)) 34 34 v2x=2.*b/norm2 35 v2y=((d-a)-n umpy.sqrt((a-d)**2+4.*b**2))/norm235 v2y=((d-a)-np.sqrt((a-d)**2+4.*b**2))/norm2 36 36 37 37 v1x[pos3]=1. … … 41 41 42 42 #Compute new metric (for each node M=V*Lambda*V^-1) 43 metric=n umpy.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 46 46 47 47 #some corrections for 0 eigen values 48 metric[pos1,:]=n umpy.tile(numpy.array([[1./hmax**2,0.,1./hmax**2]]),(numpy.size(pos1),1))49 metric[pos2,:]=n umpy.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)) 50 50 51 51 #take care of water elements 52 metric[pos ,:]=n umpy.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)) 53 53 54 54 #take care of NaNs if any (use Numpy eig in a loop) 55 pos=n umpy.nonzero(numpy.isnan(metric))[0]56 if n umpy.size(pos):57 print((" %i NaN found in the metric. Use Numpy routine..." % n umpy.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))) 58 58 for posi in pos: 59 H=n umpy.array([[hessian[posi,0],hessian[posi,1]],[hessian[posi,1],hessian[posi,2]]])60 [v,u]=n umpy.linalg.eig(H)61 v=n umpy.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) 62 62 lambda1=v[0,0] 63 63 lambda2=v[1,1] 64 v[0,0]=n umpy.minimum(numpy.maximum(numpy.abs(lambda1)*scale/epsilon,1./hmax**2),1./hmin**2)65 v[1,1]=n umpy.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) 66 66 67 metricTria=n umpy.dot(numpy.dot(u,v),numpy.linalg.inv(u))68 metric[posi,:]=n umpy.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]]) 69 69 70 if n umpy.any(numpy.isnan(metric)):70 if np.any(np.isnan(metric)): 71 71 raise RunTimeError("ComputeMetric error message: NaN in the metric despite our efforts...") 72 72 -
issm/trunk-jpl/src/py3/mesh/ElementsFromEdge.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 import PythonFuncs as p 3 3 … … 12 12 """ 13 13 14 edgeelements=n umpy.nonzero(\15 p.logical_or_n(n umpy.logical_and(elements[:,0]==A,elements[:,1]==B), \16 n umpy.logical_and(elements[:,0]==A,elements[:,2]==B), \17 n umpy.logical_and(elements[:,1]==A,elements[:,2]==B), \18 n umpy.logical_and(elements[:,1]==A,elements[:,0]==B), \19 n umpy.logical_and(elements[:,2]==A,elements[:,0]==B), \20 n umpy.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), \ 21 21 ))[0]+1 22 22 -
issm/trunk-jpl/src/py3/mesh/GetNodalFunctionsCoeff.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 3 3 def GetNodalFunctionsCoeff(index,x,y): … … 23 23 24 24 #get nels and nods 25 nels=n umpy.size(index,axis=0)26 nods=n umpy.size(x)25 nels=np.size(index,axis=0) 26 nods=np.size(x) 27 27 28 28 #some checks 29 if n umpy.size(y)!=nods:29 if np.size(y)!=nods: 30 30 raise TypeError("GetNodalFunctionsCoeff error message: x and y do not have the same length.") 31 if n umpy.max(index)>nods:31 if np.max(index)>nods: 32 32 raise TypeError("GetNodalFunctionsCoeff error message: index should not have values above %d." % nods) 33 if n umpy.size(index,axis=1)!=3:33 if np.size(index,axis=1)!=3: 34 34 raise TypeError("GetNodalFunctionsCoeff error message: only 2d meshes supported. index should have 3 columns.") 35 35 36 36 #initialize output 37 alpha=n umpy.zeros((nels,3))38 beta=n umpy.zeros((nels,3))37 alpha=np.zeros((nels,3)) 38 beta=np.zeros((nels,3)) 39 39 40 40 #compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma … … 48 48 49 49 #get alpha and beta 50 alpha=n umpy.hstack(((invdet*(y2-y3)).reshape(-1,1),(invdet*(y3-y1)).reshape(-1,1),(invdet*(y1-y2)).reshape(-1,1)))51 beta =n umpy.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 52 52 53 53 #get gamma if requested 54 gamma=n umpy.zeros((nels,3))55 gamma=n umpy.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 56 56 57 57 return alpha,beta,gamma -
issm/trunk-jpl/src/py3/mesh/bamg.py
r19895 r23670 1 1 import os.path 2 import numpy 3 from mesh2d import mesh2d 2 import numpy as np 3 from mesh2d import * 4 from mesh2dvertical import * 5 from mesh3dsurface import * 4 6 from collections import OrderedDict 5 7 from pairoptions import pairoptions … … 13 15 from ContourToNodes import ContourToNodes 14 16 15 def bamg(md,* kwargs):17 def bamg(md,*args): 16 18 """ 17 19 BAMG - mesh generation … … 20 22 21 23 - domain : followed by an ARGUS file that prescribes the domain outline 24 - holes : followed by an ARGUS file that prescribes the holes 25 - subdomains : followed by an ARGUS file that prescribes the list of 26 subdomains (that need to be inside domain) 27 22 28 - hmin : minimum edge length (default is 10^-100) 23 29 - hmax : maximum edge length (default is 10^100) … … 37 43 1 -> use Green formula 38 44 - KeepVertices : try to keep initial vertices when adaptation is done on an existing mesh (default 1) 39 - MaxCornerAngle : maximum angle of corners in degree (default is 10)40 45 - maxnbv : maximum number of vertices used to allocate memory (default is 10^6) 41 46 - maxsubdiv : maximum subdivision of exisiting elements (default is 10) … … 49 54 - power : power applied to the metric (default is 1) 50 55 - splitcorners : split triangles whuch have 3 vertices on the outline (default is 1) 51 - geometricalmetric : take the geometry into account to generate the metric (default is 0)52 56 - verbose : level of verbosity (default is 1) 53 57 … … 66 70 67 71 #process options 68 options=pairoptions(* *kwargs)72 options=pairoptions(*args) 69 73 # options=deleteduplicates(options,1); 70 74 … … 74 78 bamg_mesh=bamgmesh() 75 79 80 subdomain_ref = 1 81 hole_ref = 1 82 76 83 # Bamg Geometry parameters {{{ 77 84 if options.exist('domain'): 78 79 85 #Check that file exists 80 86 domainfile=options.getfieldvalue('domain') 81 if not os.path.exists(domainfile): 82 raise IOError("bamg error message: file '%s' not found" % domainfile) 83 domain=expread(domainfile) 87 if type(domainfile) == str: 88 if not os.path.exists(domainfile): 89 raise IOError("bamg error message: file '%s' not found" % domainfile) 90 domain=expread(domainfile) 91 else: 92 domain=domainfile 84 93 85 94 #Build geometry 86 95 count=0 87 96 for i,domaini in enumerate(domain): 88 89 97 #Check that the domain is closed 90 98 if (domaini['x'][0]!=domaini['x'][-1] or domaini['y'][0]!=domaini['y'][-1]): 91 99 raise RuntimeError("bamg error message: all contours provided in ''domain'' should be closed") 92 100 93 #Checks that all holes are INSIDE the principle domain outline 101 #Checks that all holes are INSIDE the principle domain outline princial domain should be index 0 94 102 if i: 95 flags=ContourToNodes(domaini['x'],domaini['y'],domainfile,0) 96 if n umpy.any(numpy.logical_not(flags)):103 flags=ContourToNodes(domaini['x'],domaini['y'],domainfile,0)[0] 104 if np.any(np.logical_not(flags)): 97 105 raise RuntimeError("bamg error message: All holes should be strictly inside the principal domain") 106 107 #Check orientation 108 nods=domaini['nods']-1#the domain are closed 1=end; 109 110 test = np.sum((domaini['x'][1:nods+1] - domaini['x'][0:nods])*(domaini['y'][1:nods+1] + domaini['y'][0:nods])) 111 if (i==0 and test>0) or (i>0 and test<0): 112 print('At least one contour was not correctly oriented and has been re-oriented') 113 domaini['x'] = np.flipud(domaini['x']) 114 domaini['y'] = np.flipud(domaini['y']) 115 98 116 99 117 #Add all points to bamg_geometry 100 118 nods=domaini['nods']-1 #the domain are closed 0=end 101 bamg_geometry.Vertices=n umpy.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 =n umpy.vstack((bamg_geometry.Edges, numpy.hstack((numpy.arange(count+1,count+nods+1).reshape(-1,1),numpy.hstack((numpy.arange(count+2,count+nods+1),count+1)).reshape(-1,1),1.*numpy.ones((nods,1))))))119 bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.vstack((domaini['x'][0:nods],domaini['y'][0:nods],np.ones((nods)))).T)) 120 bamg_geometry.Edges =np.vstack((bamg_geometry.Edges,np.vstack((np.arange(count+1,count+nods+1),np.hstack((np.arange(count+2,count+nods+1),count+1)),1.*np.ones((nods)))).T)) 103 121 if i: 104 bamg_geometry.SubDomains=numpy.vstack((bamg_geometry.SubDomains,[2,count+1,1,1])) 105 122 bamg_geometry.SubDomains=np.vstack((bamg_geometry.SubDomains,[2,count+1,1,-subdomain_ref])) 123 subdomain_ref = subdomain_ref+1; 124 else: 125 bamg_geometry.SubDomains=np.vstack((bamg_geometry.SubDomains,[2,count+1,1,0])) 126 106 127 #update counter 107 128 count+=nods 129 130 #Deal with domain holes 131 if options.exist('holes'): 132 holesfile=options.getfieldvalue('holes') 133 if type(holesfile) == str: 134 if not os.path.exists(holesfile): 135 raise IOError("bamg error message: file '%s' not found" % holesfile) 136 holes=expread(holesfile) 137 else: 138 holes=holesfile 139 140 #Build geometry 141 for i,holei in enumerate(holes): 142 #Check that the hole is closed 143 if (holei['x'][0]!=holei['x'][-1] or holei['y'][0]!=holei['y'][-1]): 144 raise RuntimeError("bamg error message: all contours provided in ''hole'' should be closed") 145 146 #Checks that all holes are INSIDE the principle domain outline princial domain should be index 0 147 flags=ContourToNodes(holei['x'],holei['y'],domainfile,0)[0] 148 if np.any(np.logical_not(flags)): 149 raise RuntimeError("bamg error message: All holes should be strictly inside the principal domain") 150 151 #Check orientation 152 nods=holei['nods']-1#the hole are closed 1=end; 153 test = np.sum((holei['x'][1:nods+1] - holei['x'][0:nods])*(holei['y'][1:nods+1] + holei['y'][0:nods])) 154 if test<0: 155 print('At least one hole was not correctly oriented and has been re-oriented') 156 holei['x'] = np.flipud(holei['x']) 157 holei['y'] = np.flipud(holei['y']) 158 159 #Add all points to bamg_geometry 160 nods=holei['nods']-1 #the hole are closed 0=end 161 bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.vstack((holei['x'][0:nods],holei['y'][0:nods],np.ones((nods)))).T)) 162 bamg_geometry.Edges =np.vstack((bamg_geometry.Edges,np.vstack((np.arange(count+1,count+nods+1),np.hstack((np.arange(count+2,count+nods+1),count+1)),1.*np.ones((nods)))).T)) 163 #update counter 164 count+=nods 165 166 #And subdomains 167 if options.exist('subdomains'): 168 subdomainfile=options.getfieldvalue('subdomains') 169 if type(subdomainfile) == str: 170 if not os.path.exists(subdomainfile): 171 raise IOError("bamg error message: file '%s' not found" % subdomainfile) 172 subdomains=expread(subdomainfile) 173 else: 174 subdomains=subdomainfile 175 176 #Build geometry 177 for i,subdomaini in enumerate(subdomains): 178 #Check that the subdomain is closed 179 if (subdomaini['x'][0]!=subdomaini['x'][-1] or subdomaini['y'][0]!=subdomaini['y'][-1]): 180 raise RuntimeError("bamg error message: all contours provided in ''subdomain'' should be closed") 181 182 #Checks that all subdomains are INSIDE the principle subdomain outline princial domain should be index 0 183 if i: 184 flags=ContourToNodes(subdomaini['x'],subdomaini['y'],domainfile,0)[0] 185 if np.any(np.logical_not(flags)): 186 raise RuntimeError("bamg error message: All subdomains should be strictly inside the principal subdomain") 187 188 #Check orientation 189 nods=subdomaini['nods']-1#the subdomain are closed 1=end; 190 191 test = np.sum((subdomaini['x'][1:nods+1] - subdomaini['x'][0:nods])*(subdomaini['y'][1:nods+1] + subdomaini['y'][0:nods])) 192 if test>0: 193 print('At least one subcontour was not correctly oriented and has been re-oriented') 194 subdomaini['x'] = np.flipud(subdomaini['x']) 195 subdomaini['y'] = np.flipud(subdomaini['y']) 196 197 #Add all points to bamg_geometry 198 nods=subdomaini['nods']-1 #the subdomain are closed 0=end 199 bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.vstack((subdomaini['x'][0:nods],subdomaini['y'][0:nods],np.ones((nods)))).T)) 200 bamg_geometry.Edges =np.vstack((bamg_geometry.Edges,np.vstack((np.arange(count+1,count+nods+1),np.hstack((np.arange(count+2,count+nods+1),count+1)),1.*np.ones((nods)))).T)) 201 #update counter 202 count+=nods 203 204 if options.getfieldvalue('vertical',0): 205 if np.size(options.getfieldvalue('Markers',[]))!=np.size(bamg_geometry.Edges,0): 206 raise RuntimeError('for 2d vertical mesh, ''Markers'' option is required, and should be of size ' + str(np.size(bamg_geometry.Edges,0))) 207 if np.size(options.getfieldvalue('Markers',[]))==np.size(bamg_geometry.Edges,0): 208 bamg_geometry.Edges[:,2]=options.getfieldvalue('Markers') 108 209 109 210 #take care of rifts … … 119 220 120 221 #detect whether all points of the rift are inside the domain 121 flags=ContourToNodes(rifti['x'],rifti['y'],domain[0],0) 122 if n umpy.all(numpy.logical_not(flags)):222 flags=ContourToNodes(rifti['x'],rifti['y'],domain[0],0)[0] 223 if np.all(np.logical_not(flags)): 123 224 raise RuntimeError("one rift has all its points outside of the domain outline") 124 225 125 elif n umpy.any(numpy.logical_not(flags)):226 elif np.any(np.logical_not(flags)): 126 227 #We LOTS of work to do 127 228 print("Rift tip outside of or on the domain has been detected and is being processed...") 128 229 129 230 #check that only one point is outside (for now) 130 if n umpy.sum(numpy.logical_not(flags).astype(int))!=1:231 if np.sum(np.logical_not(flags).astype(int))!=1: 131 232 raise RuntimeError("bamg error message: only one point outside of the domain is supported yet") 132 233 … … 136 237 pass 137 238 elif not flags[-1]: 138 rifti['x']=n umpy.flipud(rifti['x'])139 rifti['y']=n umpy.flipud(rifti['y'])239 rifti['x']=np.flipud(rifti['x']) 240 rifti['y']=np.flipud(rifti['y']) 140 241 else: 141 242 raise RuntimeError("bamg error message: only a rift tip can be outside of the domain") … … 146 247 x2=rifti['x'][1] 147 248 y2=rifti['y'][1] 148 for j in range(0,n umpy.size(domain[0]['x'])-1):149 if SegIntersect(n umpy.array([[x1,y1],[x2,y2]]),numpy.array([[domain[0]['x'][j],domain[0]['y'][j]],[domain[0]['x'][j+1],domain[0]['y'][j+1]]])):249 for j in range(0,np.size(domain[0]['x'])-1): 250 if SegIntersect(np.array([[x1,y1],[x2,y2]]),np.array([[domain[0]['x'][j],domain[0]['y'][j]],[domain[0]['x'][j+1],domain[0]['y'][j+1]]])): 150 251 151 252 #Get position of the two nodes of the edge in domain … … 161 262 # 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]); 162 263 # 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=n umpy.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=n umpy.linalg.det(numpy.array([[numpy.linalg.det(numpy.array([[x1,y1],[x2,y2]])),y1-y2],[numpy.linalg.det(numpy.array([[x3,y3],[x4,y4]])),y3-y4]]))/numpy.linalg.det(numpy.array([[x1-x2,y1-y2],[x3-x4,y3-y4]]))264 x=np.linalg.det(np.array([[np.linalg.det(np.array([[x1,y1],[x2,y2]])),x1-x2],[np.linalg.det(np.array([[x3,y3],[x4,y4]])),x3-x4]]))/np.linalg.det(np.array([[x1-x2,y1-y2],[x3-x4,y3-y4]])) 265 y=np.linalg.det(np.array([[np.linalg.det(np.array([[x1,y1],[x2,y2]])),y1-y2],[np.linalg.det(np.array([[x3,y3],[x4,y4]])),y3-y4]]))/np.linalg.det(np.array([[x1-x2,y1-y2],[x3-x4,y3-y4]])) 165 266 166 267 segdis= sqrt((x4-x3)**2+(y4-y3)**2) 167 tipdis=n umpy.array([sqrt((x-x3)**2+(y-y3)**2),sqrt((x-x4)**2+(y-y4)**2)])168 169 if n umpy.min(tipdis)/segdis < options.getfieldvalue('toltip',0):268 tipdis=np.array([sqrt((x-x3)**2+(y-y3)**2),sqrt((x-x4)**2+(y-y4)**2)]) 269 270 if np.min(tipdis)/segdis < options.getfieldvalue('toltip',0): 170 271 print("moving tip-domain intersection point") 171 272 … … 179 280 #OK, now we can add our own rift 180 281 nods=rifti['nods']-1 181 bamg_geometry.Vertices=n umpy.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=n umpy.vstack((bamg_geometry.Edges,\183 n umpy.array([[pos,count+1,(1+i)]]),\184 n umpy.hstack((numpy.arange(count+1,count+nods).reshape(-1,1),numpy.arange(count+2,count+nods+1).reshape(-1,1),(1+i)*numpy.ones((nods-1,1))))))282 bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.hstack((rifti['x'][1:].reshape(-1,),rifti['y'][1:].reshape(-1,),np.ones((nods,1)))))) 283 bamg_geometry.Edges=np.vstack((bamg_geometry.Edges,\ 284 np.array([[pos,count+1,(1+i)]]),\ 285 np.hstack((np.arange(count+1,count+nods).reshape(-1,),np.arange(count+2,count+nods+1).reshape(-1,),(1+i)*np.ones((nods-1,1)))))) 185 286 count+=nods 186 287 … … 189 290 else: 190 291 #Add intersection point to Vertices 191 bamg_geometry.Vertices=n umpy.vstack((bamg_geometry.Vertices,numpy.array([[x,y,1]])))292 bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.array([[x,y,1]]))) 192 293 count+=1 193 294 194 295 #Decompose the crossing edge into 2 subedges 195 pos=n umpy.nonzero(numpy.logical_and(bamg_geometry.Edges[:,0]==i1,bamg_geometry.Edges[:,1]==i2))[0]296 pos=np.nonzero(np.logical_and(bamg_geometry.Edges[:,0]==i1,bamg_geometry.Edges[:,1]==i2))[0] 196 297 if not pos: 197 298 raise RuntimeError("bamg error message: a problem occurred...") 198 bamg_geometry.Edges=n umpy.vstack((bamg_geometry.Edges[0:pos-1,:],\199 n umpy.array([[bamg_geometry.Edges[pos,0],count ,bamg_geometry.Edges[pos,2]]]),\200 n umpy.array([[count ,bamg_geometry.Edges[pos,1],bamg_geometry.Edges[pos,2]]]),\299 bamg_geometry.Edges=np.vstack((bamg_geometry.Edges[0:pos-1,:],\ 300 np.array([[bamg_geometry.Edges[pos,0],count ,bamg_geometry.Edges[pos,2]]]),\ 301 np.array([[count ,bamg_geometry.Edges[pos,1],bamg_geometry.Edges[pos,2]]]),\ 201 302 bamg_geometry.Edges[pos+1:,:])) 202 303 203 304 #OK, now we can add our own rift 204 305 nods=rifti['nods']-1 205 bamg_geometry.Vertices=n umpy.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=n umpy.vstack((bamg_geometry.Edges,\207 n umpy.array([[count,count+1,2]]),\208 n umpy.hstack((numpy.arange(count+1,count+nods).reshape(-1,1),numpy.arange(count+2,count+nods+1).reshape(-1,1),(1+i)*numpy.ones((nods-1,1))))))306 bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.hstack((rifti['x'][1:].reshape(-1,),rifti['y'][1:].reshape(-1,),np.ones((nods,1)))))) 307 bamg_geometry.Edges=np.vstack((bamg_geometry.Edges,\ 308 np.array([[count,count+1,2]]),\ 309 np.hstack((np.arange(count+1,count+nods).reshape(-1,),np.arange(count+2,count+nods+1).reshape(-1,),(1+i)*np.ones((nods-1,1)))))) 209 310 count+=nods 210 311 … … 213 314 else: 214 315 nods=rifti['nods']-1 215 bamg_geometry.Vertices=n umpy.vstack(bamg_geometry.Vertices, numpy.hstack(rifti['x'][:],rifti['y'][:],numpy.ones((nods+1,1))))216 bamg_geometry.Edges =n umpy.vstack(bamg_geometry.Edges, numpy.hstack(numpy.arange(count+1,count+nods).reshape(-1,1),numpy.arange(count+2,count+nods+1).reshape(-1,1),i*numpy.ones((nods,1))))316 bamg_geometry.Vertices=np.vstack(bamg_geometry.Vertices, np.hstack(rifti['x'][:],rifti['y'][:],np.ones((nods+1,1)))) 317 bamg_geometry.Edges =np.vstack(bamg_geometry.Edges, np.hstack(np.arange(count+1,count+nods).reshape(-1,),np.arange(count+2,count+nods+1).reshape(-1,),i*np.ones((nods,1)))) 217 318 count=+nods+1 218 319 … … 224 325 if all(isinstance(track,str)): 225 326 A=expread(track) 226 track=n umpy.hstack((A.x.reshape(-1,1),A.y.reshape(-1,1)))327 track=np.hstack((A.x.reshape(-1,),A.y.reshape(-1,))) 227 328 else: 228 329 track=float(track) #for some reason, it is of class "single" 229 if n umpy.size(track,axis=1)==2:230 track=n umpy.hstack((track,3.*numpy.ones((size(track,axis=0),1))))330 if np.size(track,axis=1)==2: 331 track=np.hstack((track,3.*np.ones((size(track,axis=0),1)))) 231 332 232 333 #only keep those inside 233 flags=ContourToNodes(track[:,0],track[:,1],domainfile,0) 234 track=track[n umpy.nonzero(flags),:]334 flags=ContourToNodes(track[:,0],track[:,1],domainfile,0)[0] 335 track=track[np.nonzero(flags),:] 235 336 236 337 #Add all points to bamg_geometry 237 nods=n umpy.size(track,axis=0)238 bamg_geometry.Vertices=n umpy.vstack((bamg_geometry.Vertices,track))239 bamg_geometry.Edges =n umpy.vstack((bamg_geometry.Edges,numpy.hstack((numpy.arange(count+1,count+nods).reshape(-1,1),numpy.arange(count+2,count+nods+1).reshape(-1,1),3.*numpy.ones((nods-1,1))))))338 nods=np.size(track,axis=0) 339 bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,track)) 340 bamg_geometry.Edges =np.vstack((bamg_geometry.Edges,np.hstack((np.arange(count+1,count+nods).reshape(-1,),np.arange(count+2,count+nods+1).reshape(-1,),3.*np.ones((nods-1,1)))))) 240 341 241 342 #update counter … … 247 348 #recover RequiredVertices 248 349 requiredvertices=options.getfieldvalue('RequiredVertices') #for some reason, it is of class "single" 249 if numpy.size(requiredvertices,axis=1)==2: 250 requiredvertices=numpy.hstack((requiredvertices,4.*numpy.ones((numpy.size(requiredvertices,axis=0),1)))) 251 350 if np.size(requiredvertices,axis=1)==2: 351 requiredvertices=np.hstack((requiredvertices,4.*np.ones((np.size(requiredvertices,axis=0),1)))) 252 352 253 353 #only keep those inside 254 354 flags=ContourToNodes(requiredvertices[:,0],requiredvertices[:,1],domainfile,0)[0] 255 requiredvertices=requiredvertices[numpy.nonzero(flags)[0],:] 256 355 requiredvertices=requiredvertices[np.nonzero(flags)[0],:] 257 356 #Add all points to bamg_geometry 258 nods=n umpy.size(requiredvertices,axis=0)259 bamg_geometry.Vertices=n umpy.vstack((bamg_geometry.Vertices,requiredvertices))357 nods=np.size(requiredvertices,axis=0) 358 bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,requiredvertices)) 260 359 261 360 #update counter … … 277 376 bamg_mesh=bamgmesh(md.private.bamg['mesh'].__dict__) 278 377 else: 279 bamg_mesh.Vertices=numpy.hstack((md.mesh.x.reshape(-1,1),md.mesh.y.reshape(-1,1),numpy.ones((md.mesh.numberofvertices,1)))) 280 bamg_mesh.Triangles=numpy.hstack((md.mesh.elements,numpy.ones((md.mesh.numberofelements,1)))) 378 bamg_mesh.Vertices=np.vstack((md.mesh.x,md.mesh.y,np.ones((md.mesh.numberofvertices)))).T 379 #bamg_mesh.Vertices=np.hstack((md.mesh.x.reshape(-1,),md.mesh.y.reshape(-1,),np.ones((md.mesh.numberofvertices,1)))) 380 bamg_mesh.Triangles=np.hstack((md.mesh.elements,np.ones((md.mesh.numberofelements,1)))) 281 381 282 382 if isinstance(md.rifts.riftstruct,dict): … … 288 388 bamg_options['coeff']=options.getfieldvalue('coeff',1.) 289 389 bamg_options['cutoff']=options.getfieldvalue('cutoff',10.**-5) 290 bamg_options['err']=options.getfieldvalue('err',n umpy.array([[0.01]]))390 bamg_options['err']=options.getfieldvalue('err',np.array([[0.01]])) 291 391 bamg_options['errg']=options.getfieldvalue('errg',0.1) 292 bamg_options['field']=options.getfieldvalue('field',n umpy.empty((0,1)))392 bamg_options['field']=options.getfieldvalue('field',np.empty((0,1))) 293 393 bamg_options['gradation']=options.getfieldvalue('gradation',1.5) 294 394 bamg_options['Hessiantype']=options.getfieldvalue('Hessiantype',0) 295 395 bamg_options['hmin']=options.getfieldvalue('hmin',10.**-100) 296 396 bamg_options['hmax']=options.getfieldvalue('hmax',10.**100) 297 bamg_options['hminVertices']=options.getfieldvalue('hminVertices',n umpy.empty((0,1)))298 bamg_options['hmaxVertices']=options.getfieldvalue('hmaxVertices',n umpy.empty((0,1)))299 bamg_options['hVertices']=options.getfieldvalue('hVertices',n umpy.empty((0,1)))397 bamg_options['hminVertices']=options.getfieldvalue('hminVertices',np.empty((0,1))) 398 bamg_options['hmaxVertices']=options.getfieldvalue('hmaxVertices',np.empty((0,1))) 399 bamg_options['hVertices']=options.getfieldvalue('hVertices',np.empty((0,1))) 300 400 bamg_options['KeepVertices']=options.getfieldvalue('KeepVertices',1) 301 bamg_options['MaxCornerAngle']=options.getfieldvalue('MaxCornerAngle',10.)302 401 bamg_options['maxnbv']=options.getfieldvalue('maxnbv',10**6) 303 402 bamg_options['maxsubdiv']=options.getfieldvalue('maxsubdiv',10.) 304 bamg_options['metric']=options.getfieldvalue('metric',n umpy.empty((0,1)))403 bamg_options['metric']=options.getfieldvalue('metric',np.empty((0,1))) 305 404 bamg_options['Metrictype']=options.getfieldvalue('Metrictype',0) 306 405 bamg_options['nbjacobi']=options.getfieldvalue('nbjacobi',1) … … 309 408 bamg_options['power']=options.getfieldvalue('power',1.) 310 409 bamg_options['splitcorners']=options.getfieldvalue('splitcorners',1) 311 bamg_options['geometricalmetric']=options.getfieldvalue('geometricalmetric',0)312 bamg_options['random']=options.getfieldvalue('rand',True)313 410 bamg_options['verbose']=options.getfieldvalue('verbose',1) 314 411 #}}} 315 412 316 413 #call Bamg 317 [bamgmesh_out,bamggeom_out]=BamgMesher(bamg_mesh.__dict__,bamg_geometry.__dict__,bamg_options)414 bamgmesh_out,bamggeom_out=BamgMesher(bamg_mesh.__dict__,bamg_geometry.__dict__,bamg_options) 318 415 319 416 # plug results onto model 417 if options.getfieldvalue('vertical',0): 418 md.mesh=mesh2dvertical() 419 md.mesh.x=bamgmesh_out['Vertices'][:,0].copy() 420 md.mesh.y=bamgmesh_out['Vertices'][:,1].copy() 421 md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int) 422 md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int) 423 md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int) 424 md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int) 425 426 #Fill in rest of fields: 427 md.mesh.numberofelements=np.size(md.mesh.elements,axis=0) 428 md.mesh.numberofvertices=np.size(md.mesh.x) 429 md.mesh.numberofedges=np.size(md.mesh.edges,axis=0) 430 md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,bool) 431 md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True 432 433 #Now, build the connectivity tables for this mesh. Doubled in matlab for some reason 434 md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,) 435 md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=1 436 437 elif options.getfieldvalue('3dsurface',0): 438 md.mesh=mesh3dsurface() 439 md.mesh.x=bamgmesh_out['Vertices'][:,0].copy() 440 md.mesh.y=bamgmesh_out['Vertices'][:,1].copy() 441 md.mesh.z=md.mesh.x 442 md.mesh.z[:]=0 443 md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int) 444 md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int) 445 md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int) 446 md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int) 447 448 #Fill in rest of fields: 449 md.mesh.numberofelements=np.size(md.mesh.elements,axis=0) 450 md.mesh.numberofvertices=np.size(md.mesh.x) 451 md.mesh.numberofedges=np.size(md.mesh.edges,axis=0) 452 md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,bool) 453 md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True 454 455 else: 456 md.mesh=mesh2d() 457 md.mesh.x=bamgmesh_out['Vertices'][:,0].copy() 458 md.mesh.y=bamgmesh_out['Vertices'][:,1].copy() 459 md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int) 460 md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int) 461 md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int) 462 md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int) 463 464 #Fill in rest of fields: 465 md.mesh.numberofelements=np.size(md.mesh.elements,axis=0) 466 md.mesh.numberofvertices=np.size(md.mesh.x) 467 md.mesh.numberofedges=np.size(md.mesh.edges,axis=0) 468 md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,bool) 469 md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True 470 471 #Bamg private fields 320 472 md.private.bamg=OrderedDict() 321 473 md.private.bamg['mesh']=bamgmesh(bamgmesh_out) 322 474 md.private.bamg['geometry']=bamggeom(bamggeom_out) 323 md.mesh = mesh2d()324 md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()325 md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()326 md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int)327 md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int)328 md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int)329 md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int)330 331 #Fill in rest of fields:332 md.mesh.numberofelements=numpy.size(md.mesh.elements,axis=0)333 md.mesh.numberofvertices=numpy.size(md.mesh.x)334 md.mesh.numberofedges=numpy.size(md.mesh.edges,axis=0)335 md.mesh.vertexonboundary=numpy.zeros(md.mesh.numberofvertices,bool)336 md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True337 475 md.mesh.elementconnectivity=md.private.bamg['mesh'].ElementConnectivity 338 md.mesh.elementconnectivity[n umpy.nonzero(numpy.isnan(md.mesh.elementconnectivity))]=0476 md.mesh.elementconnectivity[np.nonzero(np.isnan(md.mesh.elementconnectivity))]=0 339 477 md.mesh.elementconnectivity=md.mesh.elementconnectivity.astype(int) 340 478 341 479 #Check for orphan 342 if n umpy.any(numpy.logical_not(numpy.in1d(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements.flat))):343 raise RuntimeError("Output mesh has orphans. Decrease MaxCornerAngle to prevent outside points (ex: 0.01)")480 if np.any(np.logical_not(np.in1d(np.arange(1,md.mesh.numberofvertices+1),md.mesh.elements.flat))): 481 raise RuntimeError("Output mesh has orphans. Check your Domain and/or RequiredVertices") 344 482 345 483 return md … … 351 489 print("Checking Edge crossing...") 352 490 i=0 353 while (i<n umpy.size(geom.Edges,axis=0)):491 while (i<np.size(geom.Edges,axis=0)): 354 492 355 493 #edge counter … … 364 502 365 503 j=i #test edges located AFTER i only 366 while (j<n umpy.size(geom.Edges,axis=0)):504 while (j<np.size(geom.Edges,axis=0)): 367 505 368 506 #edge counter … … 381 519 382 520 #Check if the two edges are crossing one another 383 if SegIntersect(n umpy.array([[x1,y1],[x2,y2]]),numpy.array([[x3,y3],[x4,y4]])):521 if SegIntersect(np.array([[x1,y1],[x2,y2]]),np.array([[x3,y3],[x4,y4]])): 384 522 385 523 #Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html) 386 x=n umpy.linalg.det(numpy.array([numpy.linalg.det(numpy.array([[x1,y1],[x2,y2]])),x1-x2],[numpy.linalg.det(numpy.array([[x3,y3],[x4,y4]])),x3-x4])/numpy.linalg.det(numpy.array([[x1-x2,y1-y2],[x3-x4,y3-y4]])))387 y=n umpy.linalg.det(numpy.array([numpy.linalg.det(numpy.array([[x1,y1],[x2,y2]])),y1-y2],[numpy.linalg.det(numpy.array([[x3,y3],[x4,y4]])),y3-y4])/numpy.linalg.det(numpy.array([[x1-x2,y1-y2],[x3-x4,y3-y4]])))524 x=np.linalg.det(np.array([np.linalg.det(np.array([[x1,y1],[x2,y2]])),x1-x2],[np.linalg.det(np.array([[x3,y3],[x4,y4]])),x3-x4])/np.linalg.det(np.array([[x1-x2,y1-y2],[x3-x4,y3-y4]]))) 525 y=np.linalg.det(np.array([np.linalg.det(np.array([[x1,y1],[x2,y2]])),y1-y2],[np.linalg.det(np.array([[x3,y3],[x4,y4]])),y3-y4])/np.linalg.det(np.array([[x1-x2,y1-y2],[x3-x4,y3-y4]]))) 388 526 389 527 #Add vertex to the list of vertices 390 geom.Vertices=n umpy.vstack((geom.Vertices,[x,y,min(color1,color2)]))391 id=n umpy.size(geom.Vertices,axis=0)528 geom.Vertices=np.vstack((geom.Vertices,[x,y,min(color1,color2)])) 529 id=np.size(geom.Vertices,axis=0) 392 530 393 531 #Update edges i and j … … 395 533 edgej=geom.Edges[j,:].copy() 396 534 geom.Edges[i,:] =[edgei(0),id ,edgei(2)] 397 geom.Edges=n umpy.vstack((geom.Edges,[id ,edgei(1),edgei(2)]))535 geom.Edges=np.vstack((geom.Edges,[id ,edgei(1),edgei(2)])) 398 536 geom.Edges[j,:] =[edgej(0),id ,edgej(2)] 399 geom.Edges=n umpy.vstack((geom.Edges,[id ,edgej(1),edgej(2)]))537 geom.Edges=np.vstack((geom.Edges,[id ,edgej(1),edgej(2)])) 400 538 401 539 #update current edge second tip … … 407 545 i=0 408 546 num=0 409 while (i<n umpy.size(geom.Vertices,axis=0)):547 while (i<np.size(geom.Vertices,axis=0)): 410 548 411 549 #vertex counter … … 425 563 426 564 #update edges 427 posedges=n umpy.nonzero(geom.Edges==i)565 posedges=np.nonzero(geom.Edges==i) 428 566 geom.Edges[posedges[0],:]=[] 429 posedges=n umpy.nonzero(geom.Edges>i)567 posedges=np.nonzero(geom.Edges>i) 430 568 geom.Edges[posedges]=geom.Edges[posedges]-1 431 569 -
issm/trunk-jpl/src/py3/mesh/meshconvert.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from collections import OrderedDict 3 3 from BamgConvertMesh import BamgConvertMesh … … 43 43 44 44 #Fill in rest of fields: 45 md.mesh.numberofelements = n umpy.size(md.mesh.elements,axis=0)46 md.mesh.numberofvertices = n umpy.size(md.mesh.x)47 md.mesh.numberofedges = n umpy.size(md.mesh.edges,axis=0)48 md.mesh.vertexonboundary = n umpy.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) 49 49 md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1] = True 50 50 -
issm/trunk-jpl/src/py3/mesh/rifts/meshprocessoutsiderifts.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from ElementsFromEdge import ElementsFromEdge 3 3 import MatlabFuncs as m … … 19 19 20 20 tips=rift.tips 21 outsidetips=tips[n umpy.nonzero(flags[rift.tips-1])[0]]21 outsidetips=tips[np.nonzero(flags[rift.tips-1])[0]] 22 22 23 23 #we have found outsidetips, tips that touch the domain outline. go through them … … 26 26 #find tip in the segments, take first segment (there should be 2) that holds tip, 27 27 #and node_connected_to_tip is the other node on this segment: 28 tipindex=n umpy.nonzero(rift.segments[:,0]==tip)[0]28 tipindex=np.nonzero(rift.segments[:,0]==tip)[0] 29 29 if tipindex: 30 30 tipindex=tipindex[0] 31 31 node_connected_to_tip=rift.segments[tipindex,1] 32 32 else: 33 tipindex=n umpy.nonzero(rift.segments[:,1]==tip)[0]33 tipindex=np.nonzero(rift.segments[:,1]==tip)[0] 34 34 tipindex=tipindex[0] 35 35 node_connected_to_tip=rift.segments[tipindex,1] … … 41 41 B=node_connected_to_tip 42 42 43 elements=n umpy.empty(0,int)43 elements=np.empty(0,int) 44 44 45 45 while flags(B): #as long as B does not belong to the domain outline, keep looking. … … 48 48 #rule out those we already detected 49 49 already_detected=m.ismember(edgeelements,elements) 50 nextelement=edgeelements(n umpy.nonzero(numpy.logical_not(already_detected))[0])50 nextelement=edgeelements(np.nonzero(np.logical_not(already_detected))[0]) 51 51 #add new detected element to the list of elements we are looking for. 52 elements=n umpy.concatenate((elements,nextelement))52 elements=np.concatenate((elements,nextelement)) 53 53 #new B: 54 B=md.mesh.elements[nextelement-1,n umpy.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]))))] 55 55 56 56 #take the list of elements on one side of the rift that connect to the tip, 57 57 #and duplicate the tip on them, so as to open the rift to the outside. 58 num=n umpy.size(md.mesh.x)+159 md.mesh.x=n umpy.concatenate((md.mesh.x,md.mesh.x[tip]))60 md.mesh.y=n umpy.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])) 61 61 md.mesh.numberofvertices=num 62 62 63 63 #replace tip in elements 64 64 newelements=md.mesh.elements[elements-1,:] 65 pos=n umpy.nonzero(newelements==tip)65 pos=np.nonzero(newelements==tip) 66 66 newelements[pos]=num 67 67 md.mesh.elements[elements-1,:]=newelements 68 rift.tips=n umpy.concatenate((rift.tips,num))68 rift.tips=np.concatenate((rift.tips,num)) 69 69 70 70 #deal with segments 71 tipsegments=n umpy.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] 72 72 for segment_index in tipsegments: 73 pos=n umpy.nonzero(md.mesh.segments[segment_index,0:2]!=tip)[0]73 pos=np.nonzero(md.mesh.segments[segment_index,0:2]!=tip)[0] 74 74 other_node=md.mesh.segments[segment_index,pos] 75 75 if not isconnected(md.mesh.elements,other_node,tip): 76 pos=n umpy.nonzero(md.mesh.segments[segment_index,0:2]==tip)[0]76 pos=np.nonzero(md.mesh.segments[segment_index,0:2]==tip)[0] 77 77 md.mesh.segments[segment_index,pos]=num 78 78 79 79 #Fill in rest of fields: 80 md.mesh.numberofelements=n umpy.size(md.mesh.elements,axis=0)81 md.mesh.numberofvertices=n umpy.size(md.mesh.x)82 md.mesh.vertexonboundary=n umpy.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) 83 83 md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True 84 84 md.rifts.numrifts=length(md.rifts.riftstruct) -
issm/trunk-jpl/src/py3/mesh/rifts/meshprocessrifts.py
r19895 r23670 1 import numpy 2 from TriMeshProcessRifts import TriMeshProcessRifts1 import numpy as np 2 from ProcessRifts import ProcessRifts 3 3 from ContourToMesh import ContourToMesh 4 4 from meshprocessoutsiderifts import meshprocessoutsiderifts … … 22 22 23 23 #Call MEX file 24 [md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,md.rifts.riftstruct]=TriMeshProcessRifts(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers)24 md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,md.rifts.riftstruct=ProcessRifts(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers) 25 25 md.mesh.elements=md.mesh.elements.astype(int) 26 26 md.mesh.x=md.mesh.x.reshape(-1) … … 29 29 md.mesh.segmentmarkers=md.mesh.segmentmarkers.astype(int) 30 30 if not isinstance(md.rifts.riftstruct,list) or not md.rifts.riftstruct: 31 raise RuntimeError(" TriMeshProcessRifts did not find any rift")31 raise RuntimeError("ProcessRifts did not find any rift") 32 32 33 33 #Fill in rest of fields: 34 34 numrifts=len(md.rifts.riftstruct) 35 md.mesh.numberofelements=n umpy.size(md.mesh.elements,axis=0)36 md.mesh.numberofvertices=n umpy.size(md.mesh.x)37 md.mesh.vertexonboundary=n umpy.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) 38 38 md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True 39 39 40 40 #get coordinates of rift tips 41 41 for rift in md.rifts.riftstruct: 42 rift['tip1coordinates']=n umpy.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']=n umpy.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,))) 44 44 45 45 #In case we have rifts that open up the domain outline, we need to open them: 46 [flags,dum]=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0)46 flags=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0) 47 47 found=0 48 48 for rift in md.rifts.riftstruct: … … 58 58 #get elements that are not correctly oriented in the correct direction: 59 59 aires=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y) 60 pos=n umpy.nonzero(aires<0)[0]61 md.mesh.elements[pos,:]=n umpy.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 62 62 63 63 return md -
issm/trunk-jpl/src/py3/mesh/roundmesh.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 import os 3 3 from collections import OrderedDict … … 20 20 21 21 #Get number of points on the circle 22 pointsonedge=n umpy.floor((2.*numpy.pi*radius) / resolution)22 pointsonedge=np.floor((2.*np.pi*radius) / resolution)+1 #+1 to close the outline 23 23 24 24 #Calculate the cartesians coordinates of the points 25 x_list=numpy.ones(pointsonedge) 26 y_list=numpy.ones(pointsonedge) 27 theta=numpy.linspace(0.,2.*numpy.pi,num=pointsonedge,endpoint=False) 28 x_list=roundsigfig(radius*x_list*numpy.cos(theta),12) 29 y_list=roundsigfig(radius*y_list*numpy.sin(theta),12) 25 theta=np.linspace(0.,2.*np.pi,pointsonedge) 26 x_list=roundsigfig(radius*np.cos(theta),12) 27 y_list=roundsigfig(radius*np.sin(theta),12) 30 28 A=OrderedDict() 31 29 A['x']=[x_list] … … 39 37 40 38 #move the closest node to the center 41 pos=n umpy.argmin(md.mesh.x**2+md.mesh.y**2)39 pos=np.argmin(md.mesh.x**2+md.mesh.y**2) 42 40 md.mesh.x[pos]=0. 43 41 md.mesh.y[pos]=0. … … 50 48 def roundsigfig(x,n): 51 49 52 digits=n umpy.ceil(numpy.log10(numpy.abs(x)))50 digits=np.ceil(np.log10(np.abs(x))) 53 51 x=x/10.**digits 54 x=n umpy.round(x,decimals=n)52 x=np.round(x,decimals=n) 55 53 x=x*10.**digits 56 54 57 pos=n umpy.nonzero(numpy.isnan(x))55 pos=np.nonzero(np.isnan(x)) 58 56 x[pos]=0. 59 57 -
issm/trunk-jpl/src/py3/mesh/squaremesh.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from NodeConnectivity import NodeConnectivity 3 3 from ElementConnectivity import ElementConnectivity … … 22 22 23 23 #initialization 24 index=n umpy.zeros((nel,3),int)25 x=n umpy.zeros((nx*ny))26 y=n umpy.zeros((nx*ny))24 index=np.zeros((nel,3),int) 25 x=np.zeros((nx*ny)) 26 y=np.zeros((nx*ny)) 27 27 28 28 #create coordinates … … 43 43 44 44 #Scale x and y 45 x=x/n umpy.max(x)*Lx46 y=y/n umpy.max(y)*Ly45 x=x/np.max(x)*Lx 46 y=y/np.max(y)*Ly 47 47 48 48 #create segments 49 segments=n umpy.zeros((2*(nx-1)+2*(ny-1),3),int)49 segments=np.zeros((2*(nx-1)+2*(ny-1),3),int) 50 50 #left edge: 51 segments[0:ny-1,:]=n umpy.hstack((numpy.arange(2,ny+1).reshape(-1,1),numpy.arange(1,ny).reshape(-1,1),(2*numpy.arange(1,ny)-1).reshape(-1,1)))51 segments[0:ny-1,:]=np.vstack((np.arange(2,ny+1),np.arange(1,ny),(2*np.arange(1,ny)-1))).T 52 52 #right edge: 53 segments[ny-1:2*(ny-1),:]=n umpy.hstack((numpy.arange(ny*(nx-1)+1,nx*ny).reshape(-1,1),numpy.arange(ny*(nx-1)+2,nx*ny+1).reshape(-1,1),2*numpy.arange((ny-1)*(nx-2)+1,(nx-1)*(ny-1)+1).reshape(-1,1)))53 segments[ny-1:2*(ny-1),:]=np.vstack((np.arange(ny*(nx-1)+1,nx*ny),np.arange(ny*(nx-1)+2,nx*ny+1),2*np.arange((ny-1)*(nx-2)+1,(nx-1)*(ny-1)+1))).T 54 54 #front edge: 55 segments[2*(ny-1):2*(ny-1)+(nx-1),:]=n umpy.hstack((numpy.arange(2*ny,ny*nx+1,ny).reshape(-1,1),numpy.arange(ny,ny*(nx-1)+1,ny).reshape(-1,1),numpy.arange(2*(ny-1),2*(nx-1)*(ny-1)+1,2*(ny-1)).reshape(-1,1)))55 segments[2*(ny-1):2*(ny-1)+(nx-1),:]=np.vstack((np.arange(2*ny,ny*nx+1,ny),np.arange(ny,ny*(nx-1)+1,ny),np.arange(2*(ny-1),2*(nx-1)*(ny-1)+1,2*(ny-1)))).T 56 56 #back edge 57 segments[2*(ny-1)+(nx-1):2*(nx-1)+2*(ny-1),:]=n umpy.hstack((numpy.arange(1,(nx-2)*ny+2,ny).reshape(-1,1),numpy.arange(ny+1,ny*(nx-1)+2,ny).reshape(-1,1),numpy.arange(1,2*(nx-2)*(ny-1)+2,2*(ny-1)).reshape(-1,1)))57 segments[2*(ny-1)+(nx-1):2*(nx-1)+2*(ny-1),:]=np.vstack((np.arange(1,(nx-2)*ny+2,ny),np.arange(ny+1,ny*(nx-1)+2,ny),np.arange(1,2*(nx-2)*(ny-1)+2,2*(ny-1)))).T 58 58 59 59 #plug coordinates and nodes … … 62 62 md.mesh.y=y 63 63 md.mesh.numberofvertices=nods 64 md.mesh.vertexonboundary=n umpy.zeros((nods),bool)64 md.mesh.vertexonboundary=np.zeros((nods),bool) 65 65 md.mesh.vertexonboundary[segments[:,0:2]-1]=True 66 66 … … 71 71 72 72 #Now, build the connectivity tables for this mesh. 73 [md.mesh.vertexconnectivity]=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)74 [md.mesh.elementconnectivity]=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)73 md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)[0] 74 md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)[0] 75 75 76 76 return md -
issm/trunk-jpl/src/py3/mesh/triangle.py
r19895 r23670 1 import numpy 1 import os.path 2 import numpy as np 2 3 from mesh2d import mesh2d 3 from TriMesh import TriMesh4 4 from NodeConnectivity import NodeConnectivity 5 5 from ElementConnectivity import ElementConnectivity 6 from Triangle_python import Triangle_python 6 7 import MatlabFuncs as m 7 8 … … 10 11 TRIANGLE - create model mesh using the triangle package 11 12 12 This routine creates a model mesh using Tri Meshand a domain outline, to within a certain resolution13 This routine creates a model mesh using Triangle and a domain outline, to within a certain resolution 13 14 where md is a @model object, domainname is the name of an Argus domain outline file, 14 15 and resolution is a characteristic length for the mesh (same unit as the domain outline … … 43 44 area = resolution**2 44 45 45 #Mesh using TriMesh 46 #Check that file exist (this is a very very common mistake) 47 if not os.path.exists(domainname): 48 raise IOError("file '%s' not found" % domainname) 49 50 #Mesh using Triangle 46 51 md.mesh=mesh2d() 47 [md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers]=TriMesh(domainname,riftname,area)52 md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers=Triangle_python(domainname,riftname,area) 48 53 md.mesh.elements=md.mesh.elements.astype(int) 49 54 md.mesh.segments=md.mesh.segments.astype(int) … … 51 56 52 57 #Fill in rest of fields: 53 md.mesh.numberofelements = n umpy.size(md.mesh.elements,axis=0)54 md.mesh.numberofvertices = n umpy.size(md.mesh.x)55 md.mesh.vertexonboundary = n umpy.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) 56 61 md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1] = True 57 62 58 63 #Now, build the connectivity tables for this mesh. 59 [md.mesh.vertexconnectivity] = NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices)60 [md.mesh.elementconnectivity] = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity)64 md.mesh.vertexconnectivity = NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices)[0] 65 md.mesh.elementconnectivity = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity)[0] 61 66 62 67 return md -
issm/trunk-jpl/src/py3/miscellaneous/MatlabFuncs.py
r19895 r23670 49 49 50 50 def ismember(a,s): 51 import numpy 51 import numpy as np 52 52 53 if not isinstance(s,(tuple,list,dict,n umpy.ndarray)):53 if not isinstance(s,(tuple,list,dict,np.ndarray)): 54 54 s=[s] 55 55 56 if not isinstance(a,(tuple,list,dict,n umpy.ndarray)):56 if not isinstance(a,(tuple,list,dict,np.ndarray)): 57 57 a=[a] 58 58 59 if not isinstance(a,n umpy.ndarray):59 if not isinstance(a,np.ndarray): 60 60 b=[item in s for item in a] 61 61 62 62 else: 63 if not isinstance(s,n umpy.ndarray):64 b=n umpy.empty_like(a)63 if not isinstance(s,np.ndarray): 64 b=np.empty_like(a) 65 65 for i,item in enumerate(a.flat): 66 66 b.flat[i]=item in s 67 67 else: 68 b=n umpy.in1d(a.flat,s.flat).reshape(a.shape)68 b=np.in1d(a.flat,s.flat).reshape(a.shape) 69 69 70 70 return b 71 71 72 72 def det(a): 73 import numpy 73 import numpy as np 74 74 75 75 if a.shape==(1,): … … 83 83 84 84 def sparse(ivec,jvec,svec,m=0,n=0,nzmax=0): 85 import numpy 85 import numpy as np 86 86 87 87 if not m: 88 m=n umpy.max(ivec)88 m=np.max(ivec) 89 89 if not n: 90 n=n umpy.max(jvec)90 n=np.max(jvec) 91 91 92 a=n umpy.zeros((m,n))92 a=np.zeros((m,n)) 93 93 94 94 for i,j,s in zip(ivec.reshape(-1,order='F'),jvec.reshape(-1,order='F'),svec.reshape(-1,order='F')): … … 98 98 99 99 def heaviside(x): 100 import numpy 100 import numpy as np 101 101 102 y=n umpy.zeros_like(x)103 y[n umpy.nonzero(x> 0.)]=1.104 y[n umpy.nonzero(x==0.)]=0.5102 y=np.zeros_like(x) 103 y[np.nonzero(x> 0.)]=1. 104 y[np.nonzero(x==0.)]=0.5 105 105 106 106 return y 107 -
issm/trunk-jpl/src/py3/miscellaneous/PythonFuncs.py
r19895 r23670 1 import numpy as np 2 1 3 def logical_and_n(*arg): 2 from numpy import logical_and 3 4 4 5 if len(arg): 5 6 result=arg[0] … … 12 13 13 14 def logical_or_n(*arg): 14 from numpy import logical_or 15 15 16 16 if len(arg): 17 17 result=arg[0] -
issm/trunk-jpl/src/py3/miscellaneous/fielddisplay.py
r19895 r23670 1 1 #Module import 2 import numpy 2 import numpy as np 3 3 from math import isnan 4 4 import MatlabFuncs as m … … 33 33 34 34 #matrix 35 elif isinstance(field,n umpy.ndarray):35 elif isinstance(field,np.ndarray): 36 36 string=displayunit(offset,name,str(field.shape),comment) 37 37 -
issm/trunk-jpl/src/py3/miscellaneous/isnans.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 3 3 def isnans(array): … … 13 13 returnvalue=0 14 14 else: 15 returnvalue=n umpy.isnan(array)15 returnvalue=np.isnan(array) 16 16 17 17 return returnvalue -
issm/trunk-jpl/src/py3/os/issmssh.py
r19895 r23670 1 1 from socket import gethostname 2 from sys import platform as _platform 2 3 import subprocess 3 4 import os … … 45 46 # (from http://code.google.com/p/robotframework/issues/detail?id=995) 46 47 47 # Make FreeBSD use blocking I/O like other platforms 48 import sys 49 import fcntl 50 from os import O_NONBLOCK 48 if _platform == "darwin": 49 # Make FreeBSD use blocking I/O like other platforms 50 import sys 51 import fcntl 52 from os import O_NONBLOCK 53 54 fd = sys.stdin.fileno() 55 flags = fcntl.fcntl(fd, fcntl.F_GETFL) 56 fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~O_NONBLOCK) 57 58 fd = sys.stdout.fileno() 59 flags = fcntl.fcntl(fd, fcntl.F_GETFL) 60 fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~O_NONBLOCK) 51 61 52 fd = sys.stdin.fileno()53 flags = fcntl.fcntl(fd, fcntl.F_GETFL)54 fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~O_NONBLOCK)55 56 fd = sys.stdout.fileno()57 flags = fcntl.fcntl(fd, fcntl.F_GETFL)58 fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~O_NONBLOCK)59 -
issm/trunk-jpl/src/py3/parameterization/contourenvelope.py
r19895 r23670 1 1 import os.path 2 import numpy 2 import numpy as np 3 3 import copy 4 4 from NodeConnectivity import NodeConnectivity … … 40 40 #Now, build the connectivity tables for this mesh. 41 41 #Computing connectivity 42 if n umpy.size(md.mesh.vertexconnectivity,axis=0)!=md.mesh.numberofvertices and numpy.size(md.mesh.vertexconnectivity,axis=0)!=md.mesh.numberofvertices2d:43 [md.mesh.vertexconnectivity]=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)44 if n umpy.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements and numpy.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements2d:45 [md.mesh.elementconnectivity]=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)42 if np.size(md.mesh.vertexconnectivity,axis=0)!=md.mesh.numberofvertices and np.size(md.mesh.vertexconnectivity,axis=0)!=md.mesh.numberofvertices2d: 43 md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)[0] 44 if np.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements and np.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements2d: 45 md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)[0] 46 46 47 47 #get nodes inside profile … … 65 65 #get flag list of elements and nodes inside the contour 66 66 nodein=ContourToMesh(elements,x,y,file,'node',1) 67 elemin=(n umpy.sum(nodein(elements),axis=1)==numpy.size(elements,axis=1))67 elemin=(np.sum(nodein(elements),axis=1)==np.size(elements,axis=1)) 68 68 #modify element connectivity 69 elemout=n umpy.nonzero(numpy.logical_not(elemin))[0]69 elemout=np.nonzero(np.logical_not(elemin))[0] 70 70 elementconnectivity[elemout,:]=0 71 elementconnectivity[n umpy.nonzero(m.ismember(elementconnectivity,elemout+1))]=071 elementconnectivity[np.nonzero(m.ismember(elementconnectivity,elemout+1))]=0 72 72 else: 73 73 #get flag list of elements and nodes inside the contour 74 nodein=n umpy.zeros(numberofvertices)75 elemin=n umpy.zeros(numberofelements)74 nodein=np.zeros(numberofvertices) 75 elemin=np.zeros(numberofelements) 76 76 77 pos=n umpy.nonzero(flags)77 pos=np.nonzero(flags) 78 78 elemin[pos]=1 79 79 nodein[elements[pos,:]-1]=1 80 80 81 81 #modify element connectivity 82 elemout=n umpy.nonzero(numpy.logical_not(elemin))[0]82 elemout=np.nonzero(np.logical_not(elemin))[0] 83 83 elementconnectivity[elemout,:]=0 84 elementconnectivity[n umpy.nonzero(m.ismember(elementconnectivity,elemout+1))]=084 elementconnectivity[np.nonzero(m.ismember(elementconnectivity,elemout+1))]=0 85 85 86 86 #Find element on boundary … … 88 88 flag=copy.deepcopy(elementconnectivity) 89 89 if len(args)==1: 90 flag[n umpy.nonzero(flag)]=elemin[flag[numpy.nonzero(flag)]]91 elementonboundary=n umpy.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) 92 92 93 93 #Find segments on boundary 94 pos=n umpy.nonzero(elementonboundary)[0]95 num_segments=n umpy.size(pos)96 segments=n umpy.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) 97 97 count=0 98 98 99 99 for el1 in pos: 100 els2=elementconnectivity[el1,n umpy.nonzero(elementconnectivity[el1,:])[0]]-1101 if n umpy.size(els2)>1:102 flag=n umpy.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,:]) 103 103 nods1=elements[el1,:] 104 nods1=n umpy.delete(nods1,numpy.nonzero(nods1==flag))104 nods1=np.delete(nods1,np.nonzero(nods1==flag)) 105 105 segments[count,:]=[nods1[0],nods1[1],el1+1] 106 106 107 ord1=n umpy.nonzero(nods1[0]==elements[el1,:])[0][0]108 ord2=n umpy.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] 109 109 110 110 #swap segment nodes if necessary … … 113 113 segments[count,0]=segments[count,1] 114 114 segments[count,1]=temp 115 segments[count,0:2]=n umpy.flipud(segments[count,0:2])115 segments[count,0:2]=np.flipud(segments[count,0:2]) 116 116 count+=1 117 117 else: 118 118 nods1=elements[el1,:] 119 flag=n umpy.setdiff1d(nods1,elements[els2,:])119 flag=np.setdiff1d(nods1,elements[els2,:]) 120 120 for j in range(0,3): 121 nods=n umpy.delete(nods1,j)122 if n umpy.any(m.ismember(flag,nods)):121 nods=np.delete(nods1,j) 122 if np.any(m.ismember(flag,nods)): 123 123 segments[count,:]=[nods[0],nods[1],el1+1] 124 ord1=n umpy.nonzero(nods[0]==elements[el1,:])[0][0]125 ord2=n umpy.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] 126 126 if ( (ord1==0 and ord2==1) or (ord1==1 and ord2==2) or (ord1==2 and ord2==0) ): 127 127 temp=segments[count,0] 128 128 segments[count,0]=segments[count,1] 129 129 segments[count,1]=temp 130 segments[count,0:2]=n umpy.flipud(segments[count,0:2])130 segments[count,0:2]=np.flipud(segments[count,0:2]) 131 131 count+=1 132 132 segments=segments[0:count,:] -
issm/trunk-jpl/src/py3/parameterization/setflowequation.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from model import model 3 3 from pairoptions import pairoptions 4 import MatlabFuncs as m5 import PythonFuncs as p6 4 from FlagElements import FlagElements 7 5 8 def setflowequation(md,* *kwargs):6 def setflowequation(md,*args): 9 7 """ 10 8 SETFLOWEQUATION - associate a solution type to each element … … 28 26 29 27 #some checks on list of arguments 30 if not isinstance(md,model) or not len( kwargs):28 if not isinstance(md,model) or not len(args): 31 29 raise TypeError("setflowequation error message") 32 30 33 31 #process options 34 options=pairoptions(**kwargs) 35 print(options) 36 # options=deleteduplicates(options,1); 32 options=pairoptions(*args) 33 # options=deleteduplicates(options,1); 37 34 38 35 #Find_out what kind of coupling to use 39 36 coupling_method=options.getfieldvalue('coupling','tiling') 40 if coupling_method is not 'tiling' or not 'penalties':37 if not coupling_method in ['tiling','penalties']: 41 38 raise TypeError("coupling type can only be: tiling or penalties") 42 39 … … 48 45 FSflag = FlagElements(md,options.getfieldvalue('FS','')) 49 46 filltype = options.getfieldvalue('fill','none') 50 51 47 #Flag the elements that have not been flagged as filltype 52 if filltype is 'SIA': 53 SIAflag[numpy.nonzero(numpy.logical_not(p.logical_or_n(SSAflag,HOflag)))]=True 54 elif filltype is 'SSA': 55 SSAflag[numpy.nonzero(numpy.logical_not(p.logical_or_n(SIAflag,HOflag,FSflag)))]=True 56 elif filltype is 'HO': 57 HOflag[numpy.nonzero(numpy.logical_not(p.logical_or_n(SIAflag,SSAflag,FSflag)))]=True 58 48 if 'SIA' in filltype: 49 SIAflag= ~SSAflag & ~HOflag 50 elif 'SSA' in filltype: 51 SSAflag=~SIAflag & ~HOflag & ~FSflag 52 elif 'HO' in filltype: 53 HOflag=~SIAflag & ~SSAflag & ~FSflag 59 54 #check that each element has at least one flag 60 55 if not any(SIAflag+SSAflag+L1L2flag+HOflag+FSflag): … … 64 59 if any(SIAflag+SSAflag+L1L2flag+HOflag+FSflag>1): 65 60 print("setflowequation warning message: some elements have several types, higher order type is used for them") 66 SIAflag[numpy.nonzero(numpy.logical_and(SIAflag,SSAflag))]=False 67 SIAflag[numpy.nonzero(numpy.logical_and(SIAflag,HOflag))]=False 68 SSAflag[numpy.nonzero(numpy.logical_and(SSAflag,HOflag))]=False 61 SIAflag[np.where(np.logical_and(SIAflag,SSAflag))]=False 62 SIAflag[np.where(np.logical_and(SIAflag,HOflag))]=False 63 SSAflag[np.where(np.logical_and(SSAflag,HOflag))]=False 64 65 #check that L1L2 is not coupled to any other model for now 66 if any(L1L2flag) and any(SIAflag+SSAflag+HOflag+FSflag): 67 raise TypeError('L1L2 cannot be coupled to any other model') 68 69 #Check that no HO or FS for 2d mesh 70 if domaintype(md.mesh)=='2Dhorizontal': 71 if any(FSflag+HOflag): 72 raise TypeError('FS and HO elements not allowed in 2d mesh, extrude it first') 69 73 70 74 #FS can only be used alone for now: … … 73 77 74 78 #Initialize node fields 75 nodeonSIA=n umpy.zeros(md.mesh.numberofvertices,bool)76 nodeonSIA[md.mesh.elements[n umpy.nonzero(SIAflag),:]-1]=True77 nodeonSSA=n umpy.zeros(md.mesh.numberofvertices,bool)78 nodeonSSA[md.mesh.elements[n umpy.nonzero(SSAflag),:]-1]=True79 nodeonL1L2=n umpy.zeros(md.mesh.numberofvertices,bool)80 nodeonL1L2[md.mesh.elements[n umpy.nonzero(L1L2flag),:]-1]=True81 nodeonHO=n umpy.zeros(md.mesh.numberofvertices,bool)82 nodeonHO[md.mesh.elements[n umpy.nonzero(HOflag),:]-1]=True83 nodeonFS=n umpy.zeros(md.mesh.numberofvertices,bool)84 noneflag=n umpy.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) 85 89 86 90 #First modify FSflag to get rid of elements contrained everywhere (spc + border with HO or SSA) 87 91 if any(FSflag): 88 # fullspcnodes=double((~isnan(md.stressbalance.spcvx)+~isnan(md.stressbalance.spcvy)+~isnan(md.stressbalance.spcvz))==3 | (nodeonHO & nodeonFS)); %find all the nodes on the boundary of the domain without icefront 89 fullspcnodes=numpy.logical_or(numpy.logical_not(numpy.isnan(md.stressbalance.spcvx)).astype(int)+ \ 90 numpy.logical_not(numpy.isnan(md.stressbalance.spcvy)).astype(int)+ \ 91 numpy.logical_not(numpy.isnan(md.stressbalance.spcvz)).astype(int)==3, \ 92 numpy.logical_and(nodeonHO,nodeonFS)).astype(int) #find all the nodes on the boundary of the domain without icefront 93 # fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6); %find all the nodes on the boundary of the domain without icefront 94 fullspcelems=(numpy.sum(fullspcnodes[md.mesh.elements-1],axis=1)==6).astype(int) #find all the nodes on the boundary of the domain without icefront 95 FSflag[numpy.nonzero(fullspcelems.reshape(-1))]=False 96 nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True 92 fullspcnodes=np.logical_or(~np.isnan(md.stressbalance.spcvx)+~np.isnan(md.stressbalance.spcvy)+~np.isnan(md.stressbalance.spcvz),np.logical_and(nodeonHO,nodeonFS)) #find all the nodes on the boundary of the domain without icefront 93 fullspcelems=np.sum(fullspcnodes[md.mesh.elements-1],axis=1)==6 #find all the nodes on the boundary of the domain without icefront 94 FSflag[np.where(fullspcelems.reshape(-1))]=False 95 nodeonFS[md.mesh.elements[np.where(FSflag),:]-1]=True 97 96 98 97 #Then complete with NoneApproximation or the other model used if there is no FS 99 98 if any(FSflag): 100 99 if any(HOflag): #fill with HO 101 HOflag[ numpy.logical_not(FSflag)]=True102 nodeonHO[md.mesh.elements[n umpy.nonzero(HOflag),:]-1]=True100 HOflag[~FSflag]=True 101 nodeonHO[md.mesh.elements[np.where(HOflag),:]-1]=True 103 102 elif any(SSAflag): #fill with SSA 104 SSAflag[ numpy.logical_not(FSflag)]=True105 nodeonSSA[md.mesh.elements[n umpy.nonzero(SSAflag),:]-1]=True103 SSAflag[~FSflag]=True 104 nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True 106 105 else: #fill with none 107 noneflag[n umpy.nonzero(numpy.logical_not(FSflag))]=True106 noneflag[np.where(~FSflag)]=True 108 107 109 108 #Now take care of the coupling between SSA and HO 110 md.stressbalance.vertex_pairing=n umpy.array([])111 nodeonSSAHO=n umpy.zeros(md.mesh.numberofvertices,bool)112 nodeonHOFS=n umpy.zeros(md.mesh.numberofvertices,bool)113 nodeonSSAFS=n umpy.zeros(md.mesh.numberofvertices,bool)114 SSAHOflag=n umpy.zeros(md.mesh.numberofelements,bool)115 SSAFSflag=n umpy.zeros(md.mesh.numberofelements,bool)116 HOFSflag=n umpy.zeros(md.mesh.numberofelements,bool)117 if coupling_method is'penalties':109 md.stressbalance.vertex_pairing=np.array([]) 110 nodeonSSAHO=np.zeros(md.mesh.numberofvertices,bool) 111 nodeonHOFS=np.zeros(md.mesh.numberofvertices,bool) 112 nodeonSSAFS=np.zeros(md.mesh.numberofvertices,bool) 113 SSAHOflag=np.zeros(md.mesh.numberofelements,bool) 114 SSAFSflag=np.zeros(md.mesh.numberofelements,bool) 115 HOFSflag=np.zeros(md.mesh.numberofelements,bool) 116 if coupling_method=='penalties': 118 117 #Create the border nodes between HO and SSA and extrude them 119 118 numnodes2d=md.mesh.numberofvertices2d 120 119 numlayers=md.mesh.numberoflayers 121 bordernodes2d=n umpy.nonzero(numpy.logical_and(nodeonHO[0:numnodes2d],nodeonSSA[0:numnodes2d]))[0]+1 #Nodes connected to two different types of elements120 bordernodes2d=np.where(np.logical_and(nodeonHO[0:numnodes2d],nodeonSSA[0:numnodes2d]))[0]+1 #Nodes connected to two different types of elements 122 121 123 122 #initialize and fill in penalties structure 124 if n umpy.all(numpy.logical_not(numpy.isnan(bordernodes2d))):125 penalties=n umpy.zeros((0,2))123 if np.all(np.logical_not(np.isnan(bordernodes2d))): 124 penalties=np.zeros((0,2)) 126 125 for i in range(1,numlayers): 127 penalties=n umpy.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)) 128 127 md.stressbalance.vertex_pairing=penalties 129 128 130 elif coupling_method is'tiling':131 if 129 elif coupling_method=='tiling': 130 if any(SSAflag) and any(HOflag): #coupling SSA HO 132 131 #Find node at the border 133 nodeonSSAHO[n umpy.nonzero(numpy.logical_and(nodeonSSA,nodeonHO))]=True132 nodeonSSAHO[np.where(np.logical_and(nodeonSSA,nodeonHO))]=True 134 133 #SSA elements in contact with this layer become SSAHO elements 135 matrixelements= m.ismember(md.mesh.elements-1,numpy.nonzero(nodeonSSAHO)[0])136 commonelements=n umpy.sum(matrixelements,axis=1)!=0137 commonelements[n umpy.nonzero(HOflag)]=False #only one layer: the elements previously in SSA138 SSAflag[n umpy.nonzero(commonelements)]=False #these elements are now SSAHOelements139 SSAHOflag[n umpy.nonzero(commonelements)]=True134 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 140 139 nodeonSSA[:]=False 141 nodeonSSA[md.mesh.elements[n umpy.nonzero(SSAflag),:]-1]=True140 nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True 142 141 143 142 #rule out elements that don't touch the 2 boundaries 144 pos=n umpy.nonzero(SSAHOflag)[0]145 elist=n umpy.zeros(numpy.size(pos),dtype=int)146 elist = elist + n umpy.sum(nodeonSSA[md.mesh.elements[pos,:]-1],axis=1).astype(bool)147 elist = elist - n umpy.sum(nodeonHO[md.mesh.elements[pos,:]-1] ,axis=1).astype(bool)148 pos1=n umpy.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] 149 148 SSAflag[pos[pos1]]=True 150 149 SSAHOflag[pos[pos1]]=False 151 pos2=n umpy.nonzero(elist==-1)[0]150 pos2=np.where(elist==-1)[0] 152 151 HOflag[pos[pos2]]=True 153 152 SSAHOflag[pos[pos2]]=False … … 155 154 #Recompute nodes associated to these elements 156 155 nodeonSSA[:]=False 157 nodeonSSA[md.mesh.elements[n umpy.nonzero(SSAflag),:]-1]=True156 nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True 158 157 nodeonHO[:]=False 159 nodeonHO[md.mesh.elements[n umpy.nonzero(HOflag),:]-1]=True158 nodeonHO[md.mesh.elements[np.where(HOflag),:]-1]=True 160 159 nodeonSSAHO[:]=False 161 nodeonSSAHO[md.mesh.elements[n umpy.nonzero(SSAHOflag),:]-1]=True160 nodeonSSAHO[md.mesh.elements[np.where(SSAHOflag),:]-1]=True 162 161 163 162 elif any(HOflag) and any(FSflag): #coupling HO FS 164 163 #Find node at the border 165 nodeonHOFS[n umpy.nonzero(numpy.logical_and(nodeonHO,nodeonFS))]=True164 nodeonHOFS[np.where(np.logical_and(nodeonHO,nodeonFS))]=True 166 165 #FS elements in contact with this layer become HOFS elements 167 matrixelements= m.ismember(md.mesh.elements-1,numpy.nonzero(nodeonHOFS)[0])168 commonelements=n umpy.sum(matrixelements,axis=1)!=0169 commonelements[n umpy.nonzero(HOflag)]=False #only one layer: the elements previously in SSA170 FSflag[n umpy.nonzero(commonelements)]=False #these elements are now SSAHOelements171 HOFSflag[n umpy.nonzero(commonelements)]=True172 nodeonFS=n umpy.zeros(md.mesh.numberofvertices,bool)173 nodeonFS[md.mesh.elements[n umpy.nonzero(FSflag),:]-1]=True166 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 174 173 175 174 #rule out elements that don't touch the 2 boundaries 176 pos=n umpy.nonzero(HOFSflag)[0]177 elist=n umpy.zeros(numpy.size(pos),dtype=int)178 elist = elist + n umpy.sum(nodeonFS[md.mesh.elements[pos,:]-1],axis=1).astype(bool)179 elist = elist - n umpy.sum(nodeonHO[md.mesh.elements[pos,:]-1],axis=1).astype(bool)180 pos1=n umpy.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] 181 180 FSflag[pos[pos1]]=True 182 181 HOFSflag[pos[pos1]]=False 183 pos2=n umpy.nonzero(elist==-1)[0]182 pos2=np.where(elist==-1)[0] 184 183 HOflag[pos[pos2]]=True 185 184 HOFSflag[pos[pos2]]=False … … 187 186 #Recompute nodes associated to these elements 188 187 nodeonFS[:]=False 189 nodeonFS[md.mesh.elements[n umpy.nonzero(FSflag),:]-1]=True188 nodeonFS[md.mesh.elements[np.where(FSflag),:]-1]=True 190 189 nodeonHO[:]=False 191 nodeonHO[md.mesh.elements[n umpy.nonzero(HOflag),:]-1]=True190 nodeonHO[md.mesh.elements[np.where(HOflag),:]-1]=True 192 191 nodeonHOFS[:]=False 193 nodeonHOFS[md.mesh.elements[numpy.nonzero(HOFSflag),:]-1]=True 194 192 nodeonHOFS[md.mesh.elements[np.where(HOFSflag),:]-1]=True 195 193 elif any(FSflag) and any(SSAflag): 196 194 #Find node at the border 197 nodeonSSAFS[n umpy.nonzero(numpy.logical_and(nodeonSSA,nodeonFS))]=True195 nodeonSSAFS[np.where(np.logical_and(nodeonSSA,nodeonFS))]=True 198 196 #FS elements in contact with this layer become SSAFS elements 199 matrixelements= m.ismember(md.mesh.elements-1,numpy.nonzero(nodeonSSAFS)[0])200 commonelements=n umpy.sum(matrixelements,axis=1)!=0201 commonelements[n umpy.nonzero(SSAflag)]=False #only one layer: the elements previously in SSA202 FSflag[n umpy.nonzero(commonelements)]=False #these elements are now SSASSAelements203 SSAFSflag[n umpy.nonzero(commonelements)]=True204 nodeonFS=n umpy.zeros(md.mesh.numberofvertices,bool)205 nodeonFS[md.mesh.elements[n umpy.nonzero(FSflag),:]-1]=True197 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 206 204 207 205 #rule out elements that don't touch the 2 boundaries 208 pos=n umpy.nonzero(SSAFSflag)[0]209 elist=n umpy.zeros(numpy.size(pos),dtype=int)210 elist = elist + n umpy.sum(nodeonSSA[md.mesh.elements[pos,:]-1],axis=1).astype(bool)211 elist = elist - n umpy.sum(nodeonFS[md.mesh.elements[pos,:]-1],axis=1).astype(bool)212 pos1=n umpy.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] 213 211 SSAflag[pos[pos1]]=True 214 212 SSAFSflag[pos[pos1]]=False 215 pos2=n umpy.nonzero(elist==-1)[0]213 pos2=np.where(elist==-1)[0] 216 214 FSflag[pos[pos2]]=True 217 215 SSAFSflag[pos[pos2]]=False … … 219 217 #Recompute nodes associated to these elements 220 218 nodeonSSA[:]=False 221 nodeonSSA[md.mesh.elements[n umpy.nonzero(SSAflag),:]-1]=True219 nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True 222 220 nodeonFS[:]=False 223 nodeonFS[md.mesh.elements[n umpy.nonzero(FSflag),:]-1]=True221 nodeonFS[md.mesh.elements[np.where(FSflag),:]-1]=True 224 222 nodeonSSAFS[:]=False 225 nodeonSSAFS[md.mesh.elements[n umpy.nonzero(SSAFSflag),:]-1]=True223 nodeonSSAFS[md.mesh.elements[np.where(SSAFSflag),:]-1]=True 226 224 227 225 elif any(FSflag) and any(SIAflag): … … 229 227 230 228 #Create SSAHOApproximation where needed 231 md.flowequation.element_equation=n umpy.zeros(md.mesh.numberofelements,int)232 md.flowequation.element_equation[n umpy.nonzero(noneflag)]=0233 md.flowequation.element_equation[n umpy.nonzero(SIAflag)]=1234 md.flowequation.element_equation[n umpy.nonzero(SSAflag)]=2235 md.flowequation.element_equation[n umpy.nonzero(L1L2flag)]=3236 md.flowequation.element_equation[n umpy.nonzero(HOflag)]=4237 md.flowequation.element_equation[n umpy.nonzero(FSflag)]=5238 md.flowequation.element_equation[n umpy.nonzero(SSAHOflag)]=6239 md.flowequation.element_equation[n umpy.nonzero(SSAFSflag)]=7240 md.flowequation.element_equation[n umpy.nonzero(HOFSflag)]=8229 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 241 239 242 240 #border … … 246 244 247 245 #Create vertices_type 248 md.flowequation.vertex_equation=n umpy.zeros(md.mesh.numberofvertices,int)249 pos=n umpy.nonzero(nodeonSSA)246 md.flowequation.vertex_equation=np.zeros(md.mesh.numberofvertices,int) 247 pos=np.where(nodeonSSA) 250 248 md.flowequation.vertex_equation[pos]=2 251 pos=n umpy.nonzero(nodeonL1L2)249 pos=np.where(nodeonL1L2) 252 250 md.flowequation.vertex_equation[pos]=3 253 pos=n umpy.nonzero(nodeonHO)251 pos=np.where(nodeonHO) 254 252 md.flowequation.vertex_equation[pos]=4 255 pos=n umpy.nonzero(nodeonFS)253 pos=np.where(nodeonFS) 256 254 md.flowequation.vertex_equation[pos]=5 257 255 #DO SIA LAST! Otherwise spcs might not be set up correctly (SIA should have priority) 258 pos=n umpy.nonzero(nodeonSIA)256 pos=np.where(nodeonSIA) 259 257 md.flowequation.vertex_equation[pos]=1 260 258 if any(FSflag): 261 pos=n umpy.nonzero(numpy.logical_not(nodeonFS))259 pos=np.where(np.logical_not(nodeonFS)) 262 260 if not (any(HOflag) or any(SSAflag)): 263 261 md.flowequation.vertex_equation[pos]=0 264 pos=n umpy.nonzero(nodeonSSAHO)262 pos=np.where(nodeonSSAHO) 265 263 md.flowequation.vertex_equation[pos]=6 266 pos=n umpy.nonzero(nodeonHOFS)264 pos=np.where(nodeonHOFS) 267 265 md.flowequation.vertex_equation[pos]=7 268 pos=n umpy.nonzero(nodeonSSAFS)266 pos=np.where(nodeonSSAFS) 269 267 md.flowequation.vertex_equation[pos]=8 270 268 -
issm/trunk-jpl/src/py3/parameterization/sethydrostaticmask.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 import os 3 3 from model import model 4 4 from FlagElements import FlagElements 5 import pairoptions 5 6 from ContourToMesh import ContourToMesh 6 7 … … 19 20 """ 20 21 21 if n umpy.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: 22 23 raise IOError("hydrostaticmask error message: fields in md.geometry do not have the right size.") 23 24 … … 26 27 27 28 #Check consistency of geometry 28 if any(md.geometry.base[n umpy.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.)]): 29 30 print "WARNING: md.geometry.bed and md.geometry.base not equal on grounded ice" 30 31 31 if any(md.geometry.base[n umpy.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.)]): 32 33 print "WARNING: md.geometry.base < md.geometry.bed on floating ice" 33 34 -
issm/trunk-jpl/src/py3/parameterization/setmask.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 import os 3 3 from model import model 4 4 from FlagElements import FlagElements 5 from pairoptionsimport pairoptions5 import pairoptions 6 6 from ContourToMesh import ContourToMesh 7 7 8 def setmask(md, floatingicename, groundedicename, * *kwargs):8 def setmask(md, floatingicename, groundedicename, *args): 9 9 """ 10 10 SETMASK - establish boundaries between grounded and floating ice. … … 26 26 raise TypeError("setmask error message") 27 27 28 if len(args)%2: 29 raise TypeError("odd number of arguments provided in setmask") 30 28 31 #process options 29 options=pairoptions (**kwargs)32 options=pairoptions.pairoptions(*args) 30 33 31 34 #Get assigned fields … … 41 44 #arrays come from domain outlines that can intersect one another: 42 45 43 elementonfloatingice = n umpy.logical_and(elementonfloatingice,numpy.logical_not(elementongroundedice))44 elementongroundedice = n umpy.logical_not(elementonfloatingice)46 elementonfloatingice = np.logical_and(elementonfloatingice,np.logical_not(elementongroundedice)) 47 elementongroundedice = np.logical_not(elementonfloatingice) 45 48 46 49 #the order here is important. we choose vertexongroundedice as default on the grounding line. 47 vertexonfloatingice = n umpy.zeros(md.mesh.numberofvertices,'bool')48 vertexongroundedice = n umpy.zeros(md.mesh.numberofvertices,'bool')49 vertexongroundedice[md.mesh.elements[n umpy.nonzero(elementongroundedice),:]-1]=True50 vertexonfloatingice[n umpy.nonzero(numpy.logical_not(vertexongroundedice))]=True50 vertexonfloatingice = np.zeros(md.mesh.numberofvertices,'bool') 51 vertexongroundedice = np.zeros(md.mesh.numberofvertices,'bool') 52 vertexongroundedice[md.mesh.elements[np.nonzero(elementongroundedice),:]-1]=True 53 vertexonfloatingice[np.nonzero(np.logical_not(vertexongroundedice))]=True 51 54 #}}} 52 55 53 56 #level sets 54 md.mask.groundedice_levelset = -1.*n umpy.ones(md.mesh.numberofvertices)55 md.mask.groundedice_levelset[md.mesh.elements[n umpy.nonzero(elementongroundedice),:]-1]=1.57 md.mask.groundedice_levelset = -1.*np.ones(md.mesh.numberofvertices) 58 md.mask.groundedice_levelset[md.mesh.elements[np.nonzero(elementongroundedice),:]-1]=1. 56 59 57 if(len( kwargs)):58 md.mask.ice_levelset = 1.*n umpy.ones(md.mesh.numberofvertices)60 if(len(args)): 61 md.mask.ice_levelset = 1.*np.ones(md.mesh.numberofvertices) 59 62 icedomainfile = options.getfieldvalue('icedomain','none') 60 63 if not os.path.exists(icedomainfile): 61 64 raise IOError("setmask error message: ice domain file '%s' not found." % icedomainfile) 62 65 #use contourtomesh to set ice values inside ice domain 63 [vertexinsideicedomain,elementinsideicedomain]=ContourToMesh(elements,x,y,icedomainfile,'node',1)64 md.mask.ice_levelset[n umpy.nonzero(vertexinsideicedomain)[0]] = -1.66 vertexinsideicedomain,elementinsideicedomain=ContourToMesh(elements,x,y,icedomainfile,'node',1) 67 md.mask.ice_levelset[np.nonzero(vertexinsideicedomain)[0]] = -1. 65 68 else: 66 md.mask.ice_levelset = -1.*n umpy.ones(md.mesh.numberofvertices)69 md.mask.ice_levelset = -1.*np.ones(md.mesh.numberofvertices) 67 70 68 71 return md -
issm/trunk-jpl/src/py3/plot/applyoptions.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from cmaptools import truncate_colormap 3 3 from plot_contour import plot_contour … … 10 10 from mpl_toolkits.mplot3d import Axes3D 11 11 import matplotlib as mpl 12 import pylab as p13 12 import matplotlib.pyplot as plt 14 13 except ImportError: 15 14 print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled") 16 15 17 def applyoptions(md,data,options,fig,ax ):16 def applyoptions(md,data,options,fig,axgrid,gridindex): 18 17 ''' 19 18 APPLYOPTIONS - apply options to current plot … … 30 29 # get handle to current figure and axes instance 31 30 #fig = p.gcf() 32 #ax=p.gca()33 34 # font {{{31 ax= axgrid[gridindex] 32 33 # {{{ font 35 34 fontsize=options.getfieldvalue('fontsize',8) 36 35 fontweight=options.getfieldvalue('fontweight','normal') … … 39 38 'fontweight' :fontweight, 40 39 'family' :fontfamily} 41 #}}} 42 43 #title {{{ 40 # }}} 41 # {{{ title 44 42 if options.exist('title'): 45 43 title=options.getfieldvalue('title') 46 44 if options.exist('titlefontsize'): 47 45 titlefontsize=options.getfieldvalue('titlefontsize') 48 else: 49 titlefontsize=fontsize 50 if options.exist('titlefontweight'): 51 titlefontweight=options.getfieldvalue('titlefontweight') 52 else: 53 titlefontweight=fontweight 54 #title font 55 titlefont=font.copy() 56 titlefont['size']=titlefontsize 57 titlefont['weight']=titlefontweight 58 ax.set_title(title,**titlefont) 59 #}}} 60 61 #xlabel, ylabel, zlabel {{{ 46 else: 47 titlefontsize=fontsize 48 if options.exist('titlefontweight'): 49 titlefontweight=options.getfieldvalue('titlefontweight') 50 else: 51 titlefontweight=fontweight 52 #title font 53 titlefont=font.copy() 54 titlefont['size']=titlefontsize 55 titlefont['weight']=titlefontweight 56 ax.set_title(title,**titlefont) 57 # }}} 58 # {{{ xlabel, ylabel, zlabel 62 59 if options.exist('labelfontsize'): 63 60 labelfontsize=options.getfieldvalue('labelfontsize') 64 else:65 labelfontsize=fontsize61 else: 62 labelfontsize=fontsize 66 63 if options.exist('labelfontweight'): 67 64 labelfontweight=options.getfieldvalue('labelfontweight') 68 else:69 labelfontweight=fontweight65 else: 66 labelfontweight=fontweight 70 67 71 68 #font dict for labels … … 76 73 if options.exist('xlabel'): 77 74 ax.set_xlabel(options.getfieldvalue('xlabel'),**labelfont) 78 if options.exist('ylabel'): 79 ax.set_ylabel(options.getfieldvalue('ylabel'),**labelfont) 80 if options.exist('zlabel'): 81 ax.set_zlabel(options.getfieldvalue('zlabel'),**labelfont) 82 #}}} 83 84 #xticks, yticks, zticks (tick locations) {{{ 75 if options.exist('ylabel'): 76 ax.set_ylabel(options.getfieldvalue('ylabel'),**labelfont) 77 if options.exist('zlabel'): 78 ax.set_zlabel(options.getfieldvalue('zlabel'),**labelfont) 79 # }}} 80 # {{{ xticks, yticks, zticks (tick locations) 85 81 if options.exist('xticks'): 86 82 if options.exist('xticklabels'): 87 83 xticklabels=options.getfieldvalue('xticklabels') 88 84 ax.set_xticks(options.getfieldvalue('xticks'),xticklabels) 89 else:90 ax.set_xticks(options.getfieldvalue('xticks'))85 else: 86 ax.set_xticks(options.getfieldvalue('xticks')) 91 87 if options.exist('yticks'): 92 88 if options.exist('yticklabels'): 93 89 yticklabels=options.getfieldvalue('yticklabels') 94 90 ax.set_yticks(options.getfieldvalue('yticks'),yticklabels) 95 else:96 ax.set_yticks(options.getfieldvalue('yticks'))91 else: 92 ax.set_yticks(options.getfieldvalue('yticks')) 97 93 if options.exist('zticks'): 98 94 if options.exist('zticklabels'): 99 95 zticklabels=options.getfieldvalue('zticklabels') 100 96 ax.set_zticks(options.getfieldvalue('zticks'),zticklabels) 101 else: 102 ax.set_zticks(options.getfieldvalue('zticks')) 103 #}}} 104 105 #xticklabels,yticklabels,zticklabels {{{ 97 else: 98 ax.set_zticks(options.getfieldvalue('zticks')) 99 # }}} 100 # {{{ xticklabels,yticklabels,zticklabels 106 101 if options.getfieldvalue('ticklabels','off')=='off' or options.getfieldvalue('ticklabels',0)==0: 107 102 options.addfielddefault('xticklabels',[]) 108 103 options.addfielddefault('yticklabels',[]) 109 104 # TODO check if ax has a z-axis (e.g. is 3D) 110 if options.exist('xticklabels'): 111 xticklabels=options.getfieldvalue('xticklabels') 112 ax.set_xticklabels(xticklabels) 113 if options.exist('yticklabels'): 114 yticklabels=options.getfieldvalue('yticklabels') 115 ax.set_yticklabels(yticklabels) 116 if options.exist('zticklabels'): 117 zticklabels=options.getfieldvalue('zticklabels') 118 ax.set_zticklabels(zticklabels) 119 #}}} 120 121 #ticklabel notation {{{ 105 if options.exist('xticklabels'): 106 xticklabels=options.getfieldvalue('xticklabels') 107 ax.set_xticklabels(xticklabels) 108 if options.exist('yticklabels'): 109 yticklabels=options.getfieldvalue('yticklabels') 110 ax.set_yticklabels(yticklabels) 111 if options.exist('zticklabels'): 112 zticklabels=options.getfieldvalue('zticklabels') 113 ax.set_zticklabels(zticklabels) 114 # }}} 115 # {{{ ticklabel notation 122 116 #ax.ticklabel_format(style='sci',scilimits=(0,0)) 123 #}}} 124 125 #ticklabelfontsize {{{ 117 # }}} 118 # {{{ ticklabelfontsize 126 119 if options.exist('ticklabelfontsize'): 127 120 for label in ax.get_xticklabels() + ax.get_yticklabels(): 128 121 label.set_fontsize(options.getfieldvalue('ticklabelfontsize')) 129 if int(md.mesh.dimension)==3: 130 for label in ax.get_zticklabels(): 131 label.set_fontsize(options.getfieldvalue('ticklabelfontsize')) 132 #}}} 133 134 #view 122 if int(md.mesh.dimension)==3: 123 for label in ax.get_zticklabels(): 124 label.set_fontsize(options.getfieldvalue('ticklabelfontsize')) 125 # }}} 126 # {{{ view TOFIX 135 127 #if int(md.mesh.dimension) == 3 and options.exist('layer'): 136 128 # #options.getfieldvalue('view') ? 137 129 # ax=fig.gca(projection='3d') 138 130 #plt.show() 139 140 # axis {{{131 # }}} 132 # {{{ axis 141 133 if options.exist('axis'): 142 134 if options.getfieldvalue('axis',True)=='off': … … 144 136 p.setp(ax.get_xticklabels(), visible=False) 145 137 p.setp(ax.get_yticklabels(), visible=False) 146 # }}} 147 148 #box 138 # }}} 139 # {{{ box 149 140 if options.exist('box'): 150 141 eval(options.getfieldvalue('box')) 151 152 # xlim, ylim, zlim {{{153 if options.exist('xlim'):142 # }}} 143 # {{{ xlim, ylim, zlim 144 if options.exist('xlim'): 154 145 ax.set_xlim(options.getfieldvalue('xlim')) 155 if options.exist('ylim'): 156 ax.set_ylim(options.getfieldvalue('ylim')) 157 if options.exist('zlim'): 158 ax.set_zlim(options.getfieldvalue('zlim')) 159 #}}} 160 161 #latlon 162 163 #Basinzoom 164 165 #ShowBasins 166 167 #clim {{{ 146 if options.exist('ylim'): 147 ax.set_ylim(options.getfieldvalue('ylim')) 148 if options.exist('zlim'): 149 ax.set_zlim(options.getfieldvalue('zlim')) 150 # }}} 151 # {{{ latlon TODO 152 # }}} 153 # {{{ Basinzoom TODO 154 # }}} 155 # {{{ ShowBasins TODO 156 # }}} 157 # {{{ clim 168 158 if options.exist('clim'): 169 159 lims=options.getfieldvalue('clim') 170 160 assert len(lims)==2, 'error, clim should be passed as a list of length 2' 171 elif options.exist('caxis'): 172 lims=options.getfieldvalue('caxis') 173 assert len(lims)==2, 'error, caxis should be passed as a list of length 2' 174 options.addfielddefault('clim',lims) 175 else: 176 if len(data)>0: lims=[data.min(),data.max()] 177 else: lims=[0,1] 178 #}}} 179 180 #shading 161 elif options.exist('caxis'): 162 lims=options.getfieldvalue('caxis') 163 assert len(lims)==2, 'error, caxis should be passed as a list of length 2' 164 options.addfielddefault('clim',lims) 165 else: 166 if len(data)>0: 167 lims=[data.min(),data.max()] 168 else: 169 lims=[0,1] 170 # }}} 171 # {{{ shading TODO 181 172 #if options.exist('shading'): 182 183 # grid {{{173 # }}} 174 # {{{ grid 184 175 if options.exist('grid'): 185 176 if 'on' in options.getfieldvalue('grid','on'): 186 177 ax.grid() 187 #}}} 188 189 #colormap {{{ 190 # default sequential colormap 191 defaultmap=truncate_colormap(mpl.cm.gnuplot2,0.1,0.9,128) 192 cmap=options.getfieldvalue('colormap',defaultmap) 193 norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1]) 194 options.addfield('colornorm',norm) 178 # }}} 179 # {{{ colormap 180 if options.exist('colornorm'): 181 norm=options.getfieldvalue('colornorm') 182 if options.exist('colormap'): 183 cmap=options.getfieldvalue('colormap') 195 184 cbar_extend=0 196 185 if options.exist('cmap_set_over'): 197 over=options.getfieldvalue('cmap_set_over','0.5')198 cmap.set_over(over)199 186 cbar_extend+=1 200 if options.exist('cmap_set_under'): 201 under=options.getfieldvalue('cmap_set_under','0.5') 202 cmap.set_under(under) 203 cbar_extend+=2 204 options.addfield('colormap',cmap) 205 #}}} 206 207 #contours {{{ 187 if options.exist('cmap_set_under'): 188 cbar_extend+=2 189 # }}} 190 # {{{ contours 208 191 if options.exist('contourlevels'): 209 192 plot_contour(md,data,options,ax) 210 #}}} 211 212 #wrapping 213 214 #colorbar {{{ 193 # }}} 194 # {{{ wrapping TODO 195 # }}} 196 # {{{ colorbar 215 197 if options.getfieldvalue('colorbar',1)==1: 216 198 if cbar_extend==0: 217 199 extend='neither' 218 elif cbar_extend==1:219 extend='max'220 elif cbar_extend==2:221 extend='min'222 elif cbar_extend==3:223 extend='both'224 cb = mpl.colorbar.ColorbarBase(ax.cax,cmap=cmap, norm=norm, extend=extend)225 if options.exist('alpha'):226 cb.set_alpha(options.getfieldvalue('alpha'))200 elif cbar_extend==1: 201 extend='max' 202 elif cbar_extend==2: 203 extend='min' 204 elif cbar_extend==3: 205 extend='both' 206 cb = mpl.colorbar.ColorbarBase(ax.cax,cmap=cmap, norm=norm, extend=extend) 207 if options.exist('alpha'): 208 cb.set_alpha(options.getfieldvalue('alpha')) 227 209 if options.exist('colorbarnumticks'): 228 210 cb.locator=MaxNLocator(nbins=options.getfieldvalue('colorbarnumticks',5)) 229 else:230 cb.locator=MaxNLocator(nbins=5) # default 5 ticks231 if options.exist('colorbartickspacing'):232 locs=np.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbartickspacing'))233 cb.set_ticks(locs)211 else: 212 cb.locator=MaxNLocator(nbins=5) # default 5 ticks 213 if options.exist('colorbartickspacing'): 214 locs=np.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbartickspacing')) 215 cb.set_ticks(locs) 234 216 if options.exist('colorbarlines'): 235 217 locs=np.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbarlines')) 236 218 cb.add_lines(locs,['k' for i in range(len(locs))],np.ones_like(locs)) 237 if options.exist('colorbarlineatvalue'): 238 locs=options.getfieldvalue('colorbarlineatvalue') 239 colors=options.getfieldvalue('colorbarlineatvaluecolor',['k' for i in range (len(locs))]) 240 widths=options.getfieldvalue('colorbarlineatvaluewidth',np.ones_like(locs)) 241 cb.add_lines(locs,colors,widths) 242 if options.exist('colorbartitle'): 243 if options.exist('colorbartitlepad'): 244 cb.set_label(options.getfieldvalue('colorbartitle'),labelpad=options.getfieldvalue('colorbartitlepad'),fontsize=fontsize) 245 else: 246 cb.set_label(options.getfieldvalue('colorbartitle'),fontsize=fontsize) 247 cb.ax.tick_params(labelsize=fontsize) 248 cb.solids.set_rasterized(True) 249 cb.update_ticks() 250 cb.set_alpha(1) 251 cb.draw_all() 252 plt.sca(ax) # return to original axes control 253 #}}} 254 255 #expdisp {{{ 256 if options.exist('expdisp'): 257 filename=options.getfieldvalue('expdisp') 258 style=options.getfieldvalue('expstyle','k') 259 linewidth=options.getfieldvalue('explinewidth',1) 260 for i in range(len(filename)): 261 filenamei=filename[i] 262 stylei=style[i] 263 if type(linewidth)==list: 264 linewidthi=linewidth[i] 265 else: 266 linewidthi=linewidth 267 expdisp(filenamei,ax,linestyle=stylei,linewidth=linewidthi,unitmultiplier=options.getfieldvalue('unit',1)) 268 #}}} 269 270 #area 271 272 #text {{{ 219 if options.exist('colorbarlineatvalue'): 220 locs=options.getfieldvalue('colorbarlineatvalue') 221 colors=options.getfieldvalue('colorbarlineatvaluecolor',['k' for i in range (len(locs))]) 222 widths=options.getfieldvalue('colorbarlineatvaluewidth',np.ones_like(locs)) 223 cb.add_lines(locs,colors,widths) 224 if options.exist('colorbartitle'): 225 if options.exist('colorbartitlepad'): 226 cb.set_label(options.getfieldvalue('colorbartitle'), 227 labelpad=options.getfieldvalue('colorbartitlepad'),fontsize=fontsize) 228 else: 229 cb.set_label(options.getfieldvalue('colorbartitle'),fontsize=fontsize) 230 cb.ax.tick_params(labelsize=fontsize) 231 cb.solids.set_rasterized(True) 232 cb.update_ticks() 233 cb.draw_all() 234 if options.exist('colorbarfontsize'): 235 colorbarfontsize=options.getfieldvalue('colorbarfontsize') 236 cb.ax.tick_params(labelsize=colorbarfontsize) 237 # cb.set_ticks([0,-10]) 238 # cb.set_ticklabels([-10,0,10]) 239 if options.exist('colorbarticks'): 240 colorbarticks=options.getfieldvalue('colorbarticks') 241 cb.set_ticks(colorbarticks) 242 plt.sca(ax) # return to original axes control 243 # }}} 244 # {{{ expdisp 245 if options.exist('expdisp'): 246 expdisp(ax,options) 247 # }}} 248 # {{{ area TODO 249 # }}} 250 # {{{ text 273 251 if options.exist('text'): 274 252 text=options.getfieldvalue('text') … … 281 259 for label,x,y,size,color,weight,rotation in zip(text,textx,texty,textfontsize,textcolor,textweight,textrotation): 282 260 ax.text(x,y,label,transform=ax.transAxes,fontsize=size,color=color,weight=weight,rotation=rotation) 283 #}}} 284 285 #north arrow 286 287 #scale ruler 288 289 #streamlines 261 # }}} 262 # {{{ north arrow TODO 263 # }}} 264 # {{{ scale ruler TODO 265 # }}} 266 # {{{ streamlines TOFIX 290 267 if options.exist('streamlines'): 291 268 plot_streamlines(md,options,ax) 292 293 294 #axis positions 295 296 #figure position 297 298 #axes position 299 300 #showregion 301 302 #flat edges of a partition 303 304 #scatter 305 306 #backgroundcolor 307 308 #figurebackgroundcolor 309 310 #lighting 311 312 #point cloud 313 314 #inset 315 269 # }}} 270 # {{{ axis positions TODO 271 # }}} 272 # {{{ figure position TODO 273 # }}} 274 # {{{ axes position TODO 275 # }}} 276 # {{{ showregion TODO 277 # }}} 278 # {{{ flat edges of a partition TODO 279 # }}} 280 # {{{ scatter TODO 281 # }}} 282 # {{{ backgroundcolor TODO 283 # }}} 284 # {{{ figurebackgroundcolor TODO 285 # }}} 286 # {{{ lighting TODO 287 # }}} 288 # {{{ point cloud TODO 289 # }}} 290 # {{{ inset TODO 291 # }}} -
issm/trunk-jpl/src/py3/plot/checkplotoptions.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 3 3 def checkplotoptions(md,options): … … 13 13 ''' 14 14 15 16 #units 15 # {{{ units 17 16 if options.exist('unit'): 18 17 if 'km' in options.getfieldvalue('unit','km'): … … 20 19 elif '100km' in options.getfieldvalue('unit','100km'): 21 20 options.changefieldvalue('unit',10**-5) 22 23 # density21 # }}} 22 # {{{ density 24 23 if options.exist('density'): 25 24 density=options.getfieldvalue('density') 26 25 options.changefieldvalue('density',abs(ceil(density))) 27 28 # show section26 # }}} 27 # {{{ show section 29 28 if options.exist('showsection'): 30 29 if 'on' in options.getfieldvalue('showsection','on'): 31 30 options.changefieldvalue('showsection',4) 32 33 # smooth values31 # }}} 32 # {{{ smooth values 34 33 if options.exist('smooth'): 35 34 if 'on' in options.getfieldvalue('smooth','on'): 36 35 options.changefieldvalue('smooth',0) 37 38 # contouronly values36 # }}} 37 # {{{ contouronly values 39 38 if options.exist('contouronly'): 40 39 if 'on' in options.getfieldvalue('contouronly','on'): 41 40 options.changefieldvalue('contouronly',1) 42 43 # colorbar41 # }}} 42 # {{{ colorbar 44 43 if options.exist('colorbar'): 45 44 if 'on' in options.getfieldvalue('colorbar','on'): … … 47 46 elif 'off' in options.getfieldvalue('colorbar','off'): 48 47 options.changefieldvalue('colorbar',0) 49 50 # text48 # }}} 49 # {{{ text 51 50 if options.exist('text'): 52 53 51 # text values (coerce to list for consistent functionality) 54 52 textlist=[] … … 56 54 textlist.extend([text] if isinstance(text,str) else text) 57 55 numtext=len(textlist) 58 59 56 # text position 60 57 textpos=options.getfieldvalue('textposition',[0.5,0.5]) 61 58 if not isinstance(textpos,list): 62 59 raise Exception('textposition should be passed as a list') 63 64 65 66 67 68 60 if any(isinstance(i,list) for i in textpos): 61 textx=[item[0] for item in textpos] 62 texty=[item[1] for item in textpos] 63 else: 64 textx=[textpos[0]] 65 texty=[textpos[1]] 69 66 if len(textx)!=numtext or len(texty)!=numtext: 70 67 raise Exception('textposition should contain one list of x,y vertices for every text instance') 71 68 72 69 # font size 73 if options.exist('textfontsize'):74 textfontsize=options.getfieldvalue('textfontsize',12)75 sizelist=[]76 sizelist.extend(textsize if isinstance(textfontsize,list) else [textfontsize])77 else:78 sizelist=[12]79 if len(sizelist)==1:80 sizelist=np.tile(sizelist,numtext)70 if options.exist('textfontsize'): 71 textfontsize=options.getfieldvalue('textfontsize',12) 72 sizelist=[] 73 sizelist.extend(textsize if isinstance(textfontsize,list) else [textfontsize]) 74 else: 75 sizelist=[12] 76 if len(sizelist)==1: 77 sizelist=np.tile(sizelist,numtext) 81 78 82 79 # font color … … 108 105 rotationlist=[0] 109 106 if len(rotationlist)==1: 110 rotationlist=np.tile(rotationlist,numtext)107 rotationlist=np.tile(rotationlist,numtext) 111 108 112 109 options.changefieldvalue('text',textlist) … … 117 114 options.changefieldvalue('textweight',weightlist) 118 115 options.changefieldvalue('textrotation',rotationlist) 119 120 # expdisp116 # }}} 117 # {{{ expdisp 121 118 expdispvaluesarray=[] 122 119 expstylevaluesarray=[] … … 136 133 else: 137 134 expstylevaluesarray.append('-k') 138 139 135 options.changefieldvalue('expstyle',expstylevaluesarray) 140 136 options.changefieldvalue('expdisp',expdispvaluesarray) 141 142 # latlonnumbering137 # }}} 138 # {{{ latlonnumbering 143 139 if options.exist('latlonclick'): 144 140 if 'on' in options.getfieldvalue('latlonclick','on'): 145 141 options.changefieldvalue('latlonclick',1) 146 147 # northarrow142 # }}} 143 # {{{ northarrow 148 144 if options.exist('northarrow'): 149 145 if 'on' in options.getfieldvalue('northarrow','on'): … … 152 148 Ly=max(md.mesh.y)-min(md.mesh.y) 153 149 options.changefieldvalue('northarrow',[min(md.mesh.x)+1./6.*Lx, min(md.mesh.y)+5./6.*Ly, 1./15.*Ly, 0.25, 1./250.*Ly]) 154 155 # scale ruler150 # }}} 151 # {{{ scale ruler 156 152 if options.exist('scaleruler'): 157 if 'on' in options. exist('scaleruler','on'):153 if 'on' in options.getfieldvalue('scaleruler','off'): 158 154 Lx=max(md.mesh.x)-min(md.mesh.x) 159 155 Ly=max(md.mesh.y)-min(md.mesh.y) 160 options.changefieldvalue('scaleruler',[min(md.mesh.x)+6./8.*Lx, min(md.mesh.y)+1./10.*Ly, 10**( ceil(log10(Lx)))/5,floor(Lx/100), 5])161 162 # log scale156 options.changefieldvalue('scaleruler',[min(md.mesh.x)+6./8.*Lx, min(md.mesh.y)+1./10.*Ly, 10**(np.ceil(np.log10(Lx)))/5, np.floor(Lx/100), 5]) 157 # }}} 158 # {{{ log scale 163 159 if options.exist('log'): 164 if options.exist('clim'): 165 options.changefieldvalue('clim',log(options.getfieldvalue('clim'))/log(options.getfieldvalue('log'))) 166 options.changefieldvalue('cutoff',log(options.getfieldvalue('cutoff',1.5))/log(options.getfieldvalue('log'))) 167 160 options.changefieldvalue('cutoff',np.log10(options.getfieldvalue('cutoff',1.5))/np.log10(options.getfieldvalue('log'))) 161 # }}} 168 162 return options -
issm/trunk-jpl/src/py3/plot/colormaps/cmaptools.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 3 3 try: -
issm/trunk-jpl/src/py3/plot/export_gl.py
r19895 r23670 2 2 from checkplotoptions import checkplotoptions 3 3 from model import model 4 import numpy as np4 import numpy as np 5 5 import math 6 6 from writejsfile import writejsfile -
issm/trunk-jpl/src/py3/plot/plot_contour.py
r21255 r23670 1 1 from averaging import averaging 2 import matplotlib.pyplot as plt3 2 from processmesh import processmesh 4 3 from processdata import processdata 4 try: 5 import matplotlib.pyplot as plt 6 except ImportError: 7 print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled") 5 8 6 9 def plot_contour(md,datain,options,ax): … … 31 34 # retrieve necessary options 32 35 levels=options.getfieldvalue('contourlevels') 33 colors=options.getfieldvalue('contourcolors')34 36 norm=options.getfieldvalue('colornorm') 35 linestyles=options.getfieldvalue('contourlinestyles') 36 linewidths=options.getfieldvalue('contourlinewidths') 37 colors=options.getfieldvalue('contourcolors','y') 38 linestyles=options.getfieldvalue('contourlinestyles','-') 39 linewidths=options.getfieldvalue('contourlinewidths',1) 37 40 38 41 ax.tricontour(x,y,elements,data,levels,colors=colors,norm=norm,linestyles=linestyles,linewidths=linewidths) -
issm/trunk-jpl/src/py3/plot/plot_manager.py
r19895 r23670 7 7 from checkplotoptions import checkplotoptions 8 8 from plot_mesh import plot_mesh 9 from plot_BC import plot_BC 10 from plot_elementnumbering import plot_elementnumbering 11 from plot_vertexnumbering import plot_vertexnumbering 9 12 from processmesh import processmesh 10 13 from processdata import processdata … … 22 25 from plot_overlay import plot_overlay 23 26 24 def plot_manager(md,options,fig,ax ):27 def plot_manager(md,options,fig,axgrid,gridindex): 25 28 ''' 26 29 PLOT_MANAGER - distribute the plots called by plotmodel … … 39 42 #parse options and get a structure of options 40 43 options=checkplotoptions(md,options) 44 #get data to be plotted 45 data=options.getfieldvalue('data') 46 #add ticklabel has a default option 47 options.addfielddefault('ticklabels','on') 41 48 42 #get data to be plotted 43 data=options.getfieldvalue('data'); 49 ax=axgrid[gridindex] 50 # {{{ basemap plot TOFIX 51 #if options.exist('basemap'): 52 # plot_basemap(md,data,options,nrows,ncols,i) 53 # }}} 54 # {{{ overlay plot 55 if options.exist('overlay') and overlaysupport: 56 plot_overlay(md,data,options,ax) 57 options.addfielddefault('alpha',0.5) 58 options.addfielddefault('xlim',[min(md.mesh.x),max(md.mesh.x)]) 59 options.addfielddefault('ylim',[min(md.mesh.y),max(md.mesh.y)]) 60 # }}} 61 # {{{ dealing with special plot 62 if isinstance(data,str): 63 if data=='mesh': 64 plot_mesh(md,options,fig,axgrid,gridindex) 44 65 66 #fig.delaxes(fig.axes[1]) # hack to remove colorbar after the fact 67 return 68 elif data=='BC': 69 plot_BC(md,options,fig,axgrid,gridindex) 70 return 71 elif data=='elementnumbering': 72 plot_elementnumbering(md,options,fig,axgrid,gridindex) 73 return 74 elif data=='vertexnumbering': 75 plot_vertexnumbering(md,options,fig,axgrid,gridindex) 76 return 77 elif data=='none': 78 print('no data provided to plot (TODO: write plot_none.py)') 79 applyoptions(md,[],options,fig,axgrid,gridindex) 80 return 81 else: 82 print("WARNING: '%s' is not implemented or is not a valid string for option 'data'" % data) 83 # }}} 84 # {{{ Gridded plot TODO 85 # }}} 86 # {{{ Section plot TODO 87 # }}} 88 # {{{ Profile plot TODO 89 # }}} 90 91 #process data and model 92 x,y,z,elements,is2d,isplanet=processmesh(md,data,options) 93 data2,datatype=processdata(md,data,options) 94 #plot unit 95 plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options,fig,axgrid,gridindex) 96 #apply all options 97 applyoptions(md,data2,options,fig,axgrid,gridindex) 98 99 #ground overlay on kml plot_unit 100 101 # Bits and pieces 45 102 #initialize plot handle variable 46 103 #handle=None … … 49 106 #p.subplot(nrows,ncols,i,aspect='equal') 50 107 51 ##basemap plot 52 #if options.exist('basemap'): 53 # plot_basemap(md,data,options,nrows,ncols,i) 54 55 #overlay plot 56 if options.exist('overlay') and overlaysupport: 57 plot_overlay(md,data,options,ax) 58 options.addfielddefault('alpha',0.5) 59 options.addfielddefault('xlim',[min(md.mesh.x),max(md.mesh.x)]) 60 options.addfielddefault('ylim',[min(md.mesh.y),max(md.mesh.y)]) 61 62 #figure out if this is a special plot 63 if isinstance(data,str): 64 65 # convert string to lower case for a case-insensitive comparison 66 if data.lower()=='mesh': 67 plot_mesh(md,options,ax) 68 applyoptions(md,[],options,fig,ax) 69 fig.delaxes(fig.axes[1]) # hack to remove colorbar after the fact 70 return 71 elif data.lower()=='none': 72 print('no data provided to plot (TODO: write plot_none.py)') 73 applyoptions(md,[],options,fig,ax) 74 return 75 else: 76 print(("WARNING: '%s' is not implemented or is not a valid string for option 'data'" % data)) 108 #standard plot 109 #if not handle: 110 # p.subplot(nrows,ncols,i,aspect='equal') 77 111 78 112 #elif data in vars(md): 79 113 #else: 80 114 #print "'data' not a string, plotting model properties yet to be implemented..." 81 82 #Gridded plot83 84 #Section plot85 86 #Profile plot87 88 #process data and model89 x,y,z,elements,is2d,isplanet=processmesh(md,data,options)90 data2,datatype=processdata(md,data,options)91 92 #standard plot93 #if not handle:94 # p.subplot(nrows,ncols,i,aspect='equal')95 96 #plot unit97 plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options,ax)98 99 #apply all options100 applyoptions(md,data2,options,fig,ax)101 102 #ground overlay on kml plot_unit -
issm/trunk-jpl/src/py3/plot/plot_mesh.py
r19895 r23670 4 4 print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled") 5 5 6 import numpy as np 6 7 from processmesh import processmesh 7 8 from applyoptions import applyoptions 8 9 def plot_mesh(md,options,ax): 9 from mpl_toolkits.mplot3d.art3d import Line3DCollection 10 from mpl_toolkits.axes_grid1 import inset_locator 11 from mpl_toolkits.mplot3d import Axes3D 12 def plot_mesh(md,options,fig,axgrid,gridindex): 10 13 ''' 11 14 PLOT_MESH - plot model mesh … … 16 19 See also: PLOTMODEL 17 20 ''' 21 x,y,z,elements,is2d,isplanet=processmesh(md,'mesh',options) 18 22 19 x,y,z,elements,is2d,isplanet=processmesh(md,[],options) 20 23 ax=axgrid[gridindex] 24 fig.delaxes(axgrid.cbar_axes[gridindex]) 25 21 26 if is2d: 22 27 ax.triplot(x,y,elements) 23 28 else: 24 print('WARNING: only 2D mesh plot is currently implemented') 25 29 ax=inset_locator.inset_axes(axgrid[gridindex],width='100%',height='100%',loc=3,borderpad=0,axes_class=Axes3D) 30 31 AB=elements[:,0:2] 32 BC=elements[:,1:3] 33 CA=np.vstack((elements[:,2],elements[:,0])).T 34 DE=elements[:,3:5] 35 EF=elements[:,4:] 36 FD=np.vstack((elements[:,5],elements[:,3])).T 37 AD=np.vstack((elements[:,0],elements[:,3])).T 38 BE=np.vstack((elements[:,1],elements[:,4])).T 39 CF=np.vstack((elements[:,2],elements[:,5])).T 40 41 tmpa=np.vstack((AB,BC,CA,DE,EF,FD,AD,BE,CF)) 42 #deleting segments that appear multiple times 43 tmpb = np.ascontiguousarray(tmpa).view(np.dtype((np.void, tmpa.dtype.itemsize * tmpa.shape[1]))) 44 _, idx = np.unique(tmpb, return_index=True) 45 triel= tmpa[idx] 46 47 for triangle in triel: 48 tri=list(zip(x[triangle],y[triangle],z[triangle])) 49 pl3=Line3DCollection([tri],edgecolor='r') 50 ax.add_collection3d(pl3) 51 52 ax.set_xlim([min(x),max(x)]) 53 ax.set_ylim([min(y),max(y)]) 54 ax.set_zlim([min(z),max(z)]) 26 55 #apply options 27 56 options.addfielddefault('title','Mesh') 28 57 options.addfielddefault('colorbar','off') 29 58 options.addfielddefault('ticklabels','on') 59 applyoptions(md,[],options,fig,axgrid,gridindex) -
issm/trunk-jpl/src/py3/plot/plot_overlay.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from processmesh import processmesh 3 3 from processdata import processdata … … 5 5 import matplotlib.pyplot as plt 6 6 import matplotlib as mpl 7 import os 7 8 try: 8 9 from mpl_toolkits.basemap import Basemap 9 10 except ImportError: 10 print('Basemap toolkit not installed') 11 12 import os 13 11 print('Basemap toolkit not installed') 14 12 try: 15 13 from osgeo import gdal 16 14 except ImportError: 17 15 print('osgeo/gdal for python not installed, plot_overlay is disabled') … … 25 23 26 24 x,y,z,elements,is2d,isplanet=processmesh(md,[],options) 27 28 if data=='none' or data==None: 25 try: 26 data,datatype=processdata(md,data,options) 27 imageonly=0 28 except (TypeError,ValueError):#that should catch None and 'none' but may also catch unwanted errors 29 29 imageonly=1 30 30 data=np.float('nan')*np.ones((md.mesh.numberofvertices,)) 31 31 datatype=1 32 else:33 imageonly=034 data,datatype=processdata(md,data,options)35 32 36 33 if not is2d: 37 34 raise Exception('overlay plot not supported for 3D meshes, project on a 2D layer first') 38 35 39 if not options.exist(' geotiff_name'):40 raise Exception('overlay error: provide geotiff_name with path to geotiff file')41 geotiff=options.getfieldvalue('geotiff_name')36 if not options.exist('overlay_image'): 37 raise Exception('overlay error: provide overlay_image with path to geotiff file') 38 image=options.getfieldvalue('overlay_image') 42 39 43 40 xlim=options.getfieldvalue('xlim',[min(md.mesh.x),max(md.mesh.x)]) 44 41 ylim=options.getfieldvalue('ylim',[min(md.mesh.y),max(md.mesh.y)]) 45 42 46 gtif=gdal.Open( geotiff)43 gtif=gdal.Open(image) 47 44 trans=gtif.GetGeoTransform() 48 45 xmin=trans[0] … … 50 47 ymin=trans[3]+gtif.RasterYSize*trans[5] 51 48 ymax=trans[3] 52 53 # allow supplied geotiff to have limits smaller than basemap or model limits 49 # allow supplied image to have limits smaller than basemap or model limits 54 50 x0=max(min(xlim),xmin) 55 51 x1=min(max(xlim),xmax) … … 57 53 y1=min(max(ylim),ymax) 58 54 inputname='temp.tif' 59 os.system('gdal_translate -quiet -projwin ' + str(x0) + ' ' + str(y1) + ' ' + str(x1) + ' ' + str(y0) + ' ' + geotiff+ ' ' + inputname)60 55 os.system('gdal_translate -quiet -projwin ' + str(x0) + ' ' + str(y1) + ' ' + str(x1) + ' ' + str(y0) + ' ' + image+ ' ' + inputname) 56 61 57 gtif=gdal.Open(inputname) 62 58 arr=gtif.ReadAsArray() 63 59 #os.system('rm -rf ./temp.tif') 64 60 65 61 if gtif.RasterCount>=3: # RGB array 66 62 r=gtif.GetRasterBand(1).ReadAsArray() … … 84 80 plt.hist(arr.flatten(),bins=256,range=(0.,1.)) 85 81 plt.title('histogram of overlay image, use for setting overlaylims') 86 82 plt.show() 87 83 plt.sca(ax) # return to original axes/figure 88 84 89 85 # get parameters from cropped geotiff 90 86 trans=gtif.GetGeoTransform() … … 94 90 ymax=trans[3] 95 91 dx=trans[1] 96 dy=trans[5] 97 92 dy=trans[5] 93 98 94 xarr=np.arange(xmin,xmax,dx) 99 95 yarr=np.arange(ymin,ymax,-dy) # -dy since origin='upper' (not sure how robust this is) … … 102 98 norm=mpl.colors.Normalize(vmin=overlaylims[0],vmax=overlaylims[1]) 103 99 100 pc=ax.pcolormesh(xg, yg, np.flipud(arr), cmap=mpl.cm.Greys, norm=norm) 101 104 102 if options.exist('basemap'): 105 103 # create coordinate grid in map projection units (for plotting) 106 lat,lon=xy2ll(xlim,ylim,-1,0,71) 107 #plt.sca(ax) 108 width=xmax-xmin 109 height=ymax-ymin 110 lat_0,lon_0=xy2ll(xmin+width/2.,ymin+height/2.,-1,0,71) 111 m=Basemap(projection='spstere', 112 llcrnrlon=lon[0],llcrnrlat=lat[0],urcrnrlon=lon[1],urcrnrlat=lat[1], 113 epsg=3031, 114 resolution='c') 115 #width=width,height=height,lon_0=lon_0,lat_0=lat_0, 116 #lat_0=-90,lon_0=0,lat_ts=-71, 117 #llcrnrx=x0,llcrnry=y0,urcrnrx=x1,urcrnry=y1) 118 #test 119 #m.ax=ax 120 meridians=np.arange(-180.,181.,1.) 121 parallels=np.arange(-80.,80.,1.) 122 m.drawparallels(parallels,labels=[0,0,1,1]) # labels=[left,right,top,bottom] 123 m.drawmeridians(meridians,labels=[1,1,0,0]) 124 m.drawcoastlines() 125 pc=m.pcolormesh(xg, yg, np.flipud(arr), cmap=mpl.cm.Greys, norm=norm, ax=ax) 104 if md.mesh.epsg==3413: 105 hemisphere=1 106 st_lat=70 107 lon_0=45 108 elif md.mesh.epsg==3031: 109 hemisphere=-1 110 st_lat=71 111 lon_0=0 112 else: 113 hemisphere=input('epsg code {} is not supported chose your hemisphere (1 for North, -1 for south)'.format(mesh.epsg)) 126 114 127 else: 128 pc=ax.pcolormesh(xg, yg, np.flipud(arr), cmap=mpl.cm.Greys, norm=norm) 129 130 #rasterization? 115 lat,lon=xy2ll(xlim,ylim,hemisphere,lon_0,st_lat) 116 extent=[np.diff(xlim)[0],np.diff(ylim)[0]] 117 center=[lon[0]+np.diff(lon)[0]*0.5,lat[0]+np.diff(lat)[0]*0.5] 118 m=Basemap(llcrnrlon=lon[0],llcrnrlat=lat[0],urcrnrlon=lon[1],urcrnrlat=lat[1], 119 lon_0=center[0],lat_0=center[1],#width=extent[0],height=extent[1],# 120 epsg=md.mesh.epsg,anchor='NW', 121 resolution='i',ax=ax) 122 123 meridians=np.arange(np.floor(lon[0]),np.ceil(lon[1]),1.) 124 parallels=np.arange(np.floor(lat[0]),np.ceil(lat[1]),1.) 125 m.drawparallels(parallels,labels=[1,0,0,0],ax=ax) # labels=[left,right,top,bottom] 126 m.drawmeridians(meridians,labels=[0,0,1,0],ax=ax) 127 m.drawcoastlines(ax=ax) 128 m.drawmapboundary(ax=ax) 129 130 #rasterization? 131 131 if options.getfieldvalue('rasterized',0): 132 132 pc.set_rasterized(True) -
issm/trunk-jpl/src/py3/plot/plot_streamlines.py
r21255 r23670 1 import numpy as np 2 import matplotlib.pyplot as plt 3 import matplotlib.tri as tri 1 import numpy as np 4 2 from processmesh import processmesh 5 3 from processdata import processdata 6 from scipy.interpolate import griddata7 4 from ContourToMesh import ContourToMesh 5 try: 6 import matplotlib.pyplot as plt 7 import matplotlib.tri as tri 8 from scipy.interpolate import griddata 9 except ImportError: 10 print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled") 8 11 9 12 def plot_streamlines(md,options,ax): 10 13 ''' 11 plot streamlines on a figure, using by default vx and vy components in md.initialization. 14 plot streamlines on a figure, using by default vx and vy components in md.initialization. 12 15 13 16 Usage: … … 22 25 streamlineswidthscale: scaling multiplier for linewidth scaled by velocity 23 26 streamlinesarrowsize: size of arrows on lines (default 1) 24 27 25 28 ''' 26 29 … … 33 36 arrowsize=options.getfieldvalue('streamlinesarrowsize',1) 34 37 35 #process mesh and data 38 #process mesh and data 36 39 x,y,z,elements,is2d,isplanet=processmesh(md,vx,options) 37 40 u,datatype=processdata(md,vx,options) -
issm/trunk-jpl/src/py3/plot/plot_unit.py
r21255 r23670 1 1 from cmaptools import truncate_colormap 2 from plot_quiver import plot_quiver 3 from scipy.interpolate import griddata 4 import numpy as np 2 5 try: 3 import pylab as p 4 import matplotlib as mpl 5 import matplotlib.pyplot as plt 6 import numpy as np 6 import matplotlib as mpl 7 import matplotlib.pyplot as plt 8 from mpl_toolkits.axes_grid1 import inset_locator 9 from mpl_toolkits.mplot3d import Axes3D 10 from mpl_toolkits.mplot3d.art3d import Poly3DCollection 7 11 except ImportError: 8 print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled") 9 10 def plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options,ax): 11 """ 12 PLOT_UNIT - unit plot, display data 13 14 Usage: 15 plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options) 16 17 See also: PLOTMODEL, PLOT_MANAGER 18 """ 19 20 #edgecolor 21 edgecolor=options.getfieldvalue('edgecolor','None') 22 23 #number of colorlevels for plots 24 colorlevels=options.getfieldvalue('colorlevels',128) 25 26 alpha=options.getfieldvalue('alpha',1) 27 28 #colormap 29 # default sequential colormap 30 defaultmap=truncate_colormap(mpl.cm.gnuplot2,0.1,0.9,128) 31 cmap=options.getfieldvalue('colormap',defaultmap) 32 if options.exist('cmap_set_over'): 33 over=options.getfieldvalue('cmap_set_over','0.5') 34 cmap.set_over(over) 35 if options.exist('cmap_set_under'): 36 under=options.getfieldvalue('cmap_set_under','0.5') 37 cmap.set_under(under) 38 39 #normalize colormap if clim/caxis specified 40 if options.exist('clim'): 41 lims=options.getfieldvalue('clim',[np.amin(data),np.amax(data)]) 42 elif options.exist('caxis'): 43 lims=options.getfieldvalue('caxis',[np.amin(data),np.amax(data)]) 44 else: 45 if np.amin(data)==np.amax(data): 46 lims=[np.amin(data)-0.5,np.amax(data)+0.5] 47 else: 48 lims=[np.amin(data),np.amax(data)] 49 norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1]) 50 if datatype==1: 51 #element plot 52 if is2d: 53 tri=ax.tripcolor(x,y,elements,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,edgecolors=edgecolor) 54 else: 55 raise ValueError('plot_unit error: 3D element plot not supported yet') 56 return 57 58 elif datatype==2: 59 #node plot 60 if is2d: 61 tri=ax.tricontourf(x,y,elements,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,extend='both') 62 if edgecolor != 'None': 63 ax.triplot(x,y,elements,color=edgecolor) 64 else: 65 raise ValueError('plot_unit error: 3D node plot not supported yet') 66 return 67 68 elif datatype==3: 69 vx=data[:,0] 70 vy=data[:,1] 71 #TODO write plot_quiver.py to handle this here 72 color=np.sqrt(vx**2+vy**2) 73 scale=options.getfieldvalue('scale',1000) 74 width=options.getfieldvalue('width',0.005*(np.amax(x)-np.amin(y))) 75 headwidth=options.getfieldvalue('headwidth',3) 76 headlength=options.getfieldvalue('headlength',5) 77 Q=ax.quiver(x,y,vx,vy,color,cmap=cmap,norm=norm,scale=scale, 78 width=width,headwidth=headwidth,headlength=headlength) 79 return 80 81 elif datatype==4: 82 #P1 patch plot 83 print('plot_unit message: P1 patch plot not implemented yet') 84 return 85 86 elif datatype==5: 87 print('plot_unit message: P0 patch plot not implemented yet') 88 return 89 90 else: 91 raise ValueError('datatype=%d not supported' % datatype) 92 12 print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled") 13 14 def plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options,fig,axgrid,gridindex): 15 """ 16 PLOT_UNIT - unit plot, display data 17 18 Usage: 19 plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options) 20 21 See also: PLOTMODEL, PLOT_MANAGER 22 """ 23 #if we are plotting 3d replace the current axis 24 if not is2d: 25 axgrid[gridindex].axis('off') 26 ax=inset_locator.inset_axes(axgrid[gridindex],width='100%',height='100%',loc=3,borderpad=0,axes_class=Axes3D) 27 ax.set_axis_bgcolor((0.7,0.7,0.7)) 28 else: 29 ax=axgrid[gridindex] 30 31 #edgecolor 32 edgecolor=options.getfieldvalue('edgecolor','None') 33 34 # colormap 35 # {{{ give number of colorlevels and transparency 36 colorlevels=options.getfieldvalue('colorlevels',128) 37 alpha=options.getfieldvalue('alpha',1) 38 if alpha<1: 39 antialiased=True 40 else: 41 antialiased=False 42 # }}} 43 # {{{ define wich colormap to use 44 try: 45 defaultmap=plt.cm.get_cmap('viridis',colorlevels) 46 except AttributeError: 47 print("Viridis can't be found (probably too old Matplotlib) reverting to gnuplot colormap") 48 defaultmap=truncate_colormap('gnuplot2',0.1,0.9,colorlevels) 49 cmap=options.getfieldvalue('colormap',defaultmap) 50 if options.exist('cmap_set_over'): 51 over=options.getfieldvalue('cmap_set_over','0.5') 52 cmap.set_over(over) 53 if options.exist('cmap_set_under'): 54 under=options.getfieldvalue('cmap_set_under','0.5') 55 cmap.set_under(under) 56 options.addfield('colormap',cmap) 57 # }}} 58 # {{{ if plotting only one of several layers reduce dataset, same for surface 59 if options.getfieldvalue('layer',0)>=1: 60 plotlayer=options.getfieldvalue('layer',0) 61 if datatype==1: 62 slicesize=np.shape(elements)[0] 63 elif datatype in [2,3]: 64 slicesize=len(x) 65 data=data[(plotlayer-1)*slicesize:plotlayer*slicesize] 66 # }}} 67 # {{{ Get the colormap limits 68 if options.exist('clim'): 69 lims=options.getfieldvalue('clim',[np.amin(data),np.amax(data)]) 70 elif options.exist('caxis'): 71 lims=options.getfieldvalue('caxis',[np.amin(data),np.amax(data)]) 72 else: 73 if np.amin(data)==np.amax(data): 74 lims=[np.amin(data)-0.5,np.amax(data)+0.5] 75 else: 76 lims=[np.amin(data),np.amax(data)] 77 # }}} 78 # {{{ Set the spread of the colormap (default is normal 79 if options.exist('log'): 80 norm = mpl.colors.LogNorm(vmin=lims[0], vmax=lims[1]) 81 else: 82 norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1]) 83 if options.exist('log'): 84 norm = mpl.colors.LogNorm(vmin=lims[0], vmax=lims[1]) 85 else: 86 norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1]) 87 options.addfield('colornorm',norm) 88 # }}} 89 90 # Plot depending on the datatype 91 # {{{ data are on elements 92 93 if datatype==1: 94 if is2d: 95 if options.exist('mask'): 96 triangles=mpl.tri.Triangulation(x,y,elements,data.mask) 97 else: 98 triangles=mpl.tri.Triangulation(x,y,elements) 99 tri=ax.tripcolor(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,edgecolors=edgecolor) 100 else: 101 #first deal with colormap 102 loccmap = plt.cm.ScalarMappable(cmap=cmap) 103 loccmap.set_array([min(data),max(data)]) 104 loccmap.set_clim(vmin=min(data),vmax=max(data)) 105 106 #dealing with prism sides 107 recface=np.vstack((elements[:,0],elements[:,1],elements[:,4],elements[:,3])).T 108 eltind=np.arange(0,np.shape(elements)[0]) 109 recface=np.vstack((recface,np.vstack((elements[:,1],elements[:,2],elements[:,5],elements[:,4])).T)) 110 eltind=np.hstack((eltind,np.arange(0,np.shape(elements)[0]))) 111 recface=np.vstack((recface,np.vstack((elements[:,2],elements[:,0],elements[:,3],elements[:,5])).T)) 112 eltind=np.hstack((eltind,np.arange(0,np.shape(elements)[0]))) 113 tmp = np.ascontiguousarray(np.sort(recface)).view(np.dtype((np.void, recface.dtype.itemsize * recface.shape[1]))) 114 _, idx, recur = np.unique(tmp, return_index=True, return_counts=True) 115 recel= recface[idx[np.where(recur==1)]] 116 recindex=eltind[idx[np.where(recur==1)]] 117 for i,rectangle in enumerate(recel): 118 rec=list(zip(x[rectangle],y[rectangle],z[rectangle])) 119 pl3=Poly3DCollection([rec]) 120 color=loccmap.to_rgba(data[recindex[i]]) 121 pl3.set_edgecolor(color) 122 pl3.set_color(color) 123 ax.add_collection3d(pl3) 124 125 #dealing with prism bases 126 triface=np.vstack((elements[:,0:3],elements[:,3:6])) 127 eltind=np.arange(0,np.shape(elements)[0]) 128 eltind=np.hstack((eltind,np.arange(0,np.shape(elements)[0]))) 129 tmp = np.ascontiguousarray(triface).view(np.dtype((np.void, triface.dtype.itemsize * triface.shape[1]))) 130 _, idx,recur = np.unique(tmp, return_index=True,return_counts=True) 131 #we keep only top and bottom elements 132 triel= triface[idx[np.where(recur==1)]] 133 triindex=eltind[idx[np.where(recur==1)]] 134 for i,triangle in enumerate(triel): 135 tri=list(zip(x[triangle],y[triangle],z[triangle])) 136 pl3=Poly3DCollection([tri]) 137 color=loccmap.to_rgba(data[triindex[i]]) 138 pl3.set_edgecolor(color) 139 pl3.set_color(color) 140 ax.add_collection3d(pl3) 141 142 ax.set_xlim([min(x),max(x)]) 143 ax.set_ylim([min(y),max(y)]) 144 ax.set_zlim([min(z),max(z)]) 145 146 #raise ValueError('plot_unit error: 3D element plot not supported yet') 147 return 148 149 # }}} 150 # {{{ data are on nodes 151 152 elif datatype==2: 153 if is2d: 154 if np.ma.is_masked(data): 155 EltMask=np.asarray([np.any(np.in1d(index,np.where(data.mask))) for index in elements]) 156 triangles=mpl.tri.Triangulation(x,y,elements,EltMask) 157 else: 158 triangles=mpl.tri.Triangulation(x,y,elements) 159 #tri=ax.tricontourf(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha) 160 if options.exist('log'): 161 if alpha<1:#help with antialiasing 162 tri=ax.tricontour(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=0.1,antialiased=antialiased) 163 tri=ax.tricontourf(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,antialiased=antialiased) 164 else: 165 if alpha<1:#help with antialiasing 166 tri=ax.tricontour(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=0.1,antialiased=antialiased) 167 tri=ax.tricontourf(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,extend='both',antialiased=antialiased) 168 if edgecolor != 'None': 169 ax.triplot(x,y,elements,color=edgecolor) 170 else: 171 #first deal with the colormap 172 loccmap = plt.cm.ScalarMappable(cmap=cmap) 173 loccmap.set_array([min(data),max(data)]) 174 loccmap.set_clim(vmin=min(data),vmax=max(data)) 175 176 #deal with prism sides 177 recface=np.vstack((elements[:,0],elements[:,1],elements[:,4],elements[:,3])).T 178 recface=np.vstack((recface,np.vstack((elements[:,1],elements[:,2],elements[:,5],elements[:,4])).T)) 179 recface=np.vstack((recface,np.vstack((elements[:,2],elements[:,0],elements[:,3],elements[:,5])).T)) 180 tmp = np.ascontiguousarray(np.sort(recface)).view(np.dtype((np.void, recface.dtype.itemsize * recface.shape[1]))) 181 _, idx, recur = np.unique(tmp, return_index=True, return_counts=True) 182 recel= recface[idx[np.where(recur==1)]] 183 for rectangle in recel: 184 rec=list(zip(x[rectangle],y[rectangle],z[rectangle])) 185 pl3=Poly3DCollection([rec]) 186 color=loccmap.to_rgba(np.mean(data[rectangle])) 187 pl3.set_edgecolor(color) 188 pl3.set_color(color) 189 ax.add_collection3d(pl3) 190 191 #deal with prism faces 192 triface=np.vstack((elements[:,0:3],elements[:,3:6])) 193 tmp = np.ascontiguousarray(triface).view(np.dtype((np.void, triface.dtype.itemsize * triface.shape[1]))) 194 _, idx,recur = np.unique(tmp, return_index=True,return_counts=True) 195 #we keep only top and bottom elements 196 triel= triface[idx[np.where(recur==1)]] 197 for triangle in triel: 198 tri=list(zip(x[triangle],y[triangle],z[triangle])) 199 pl3=Poly3DCollection([tri]) 200 color=loccmap.to_rgba(np.mean(data[triangle])) 201 pl3.set_edgecolor(color) 202 pl3.set_color(color) 203 ax.add_collection3d(pl3) 204 205 ax.set_xlim([min(x),max(x)]) 206 ax.set_ylim([min(y),max(y)]) 207 ax.set_zlim([min(z),max(z)]) 208 #raise ValueError('plot_unit error: 3D element plot not supported yet') 209 return 210 211 # }}} 212 # {{{ plotting quiver 213 elif datatype==3: 214 if is2d: 215 Q=plot_quiver(x,y,data,options,ax) 216 else: 217 raise ValueError('plot_unit error: 3D node plot not supported yet') 218 return 219 220 # }}} 221 # {{{ plotting P1 Patch (TODO) 222 223 elif datatype==4: 224 print('plot_unit message: P1 patch plot not implemented yet') 225 return 226 227 # }}} 228 # {{{ plotting P0 Patch (TODO) 229 230 elif datatype==5: 231 print('plot_unit message: P0 patch plot not implemented yet') 232 return 233 234 # }}} 235 else: 236 raise ValueError('datatype=%d not supported' % datatype) -
issm/trunk-jpl/src/py3/plot/plotmodel.py
r21255 r23670 1 import numpy as np1 import numpy as np 2 2 from plotoptions import plotoptions 3 from plotdoc import plotdoc 4 from plot_manager import plot_manager 5 from math import ceil, sqrt 3 6 4 7 try: … … 6 9 import matplotlib.pyplot as plt 7 10 from mpl_toolkits.axes_grid1 import ImageGrid, AxesGrid 11 from mpl_toolkits.mplot3d import Axes3D 8 12 except ImportError: 9 13 print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled") 10 14 11 from plot_manager import plot_manager12 from math import ceil, sqrt13 14 15 def plotmodel(md,*args): 15 ''' 16 at command prompt, type 'plotdoc' for additional documentation 16 ''' at command prompt, type 'plotdoc()' for additional documentation 17 17 ''' 18 18 19 #First process options 19 #First process options 20 20 options=plotoptions(*args) 21 21 22 22 #get number of subplots 23 23 subplotwidth=ceil(sqrt(options.numberofplots)) 24 25 24 #Get figure number and number of plots 26 25 figurenumber=options.figurenumber … … 37 36 nrows=np.ceil(numberofplots/subplotwidth) 38 37 nr=False 39 38 40 39 if options.list[0].exist('ncols'): 41 40 ncols=options.list[0].getfieldvalue('ncols') … … 46 45 ncols=int(ncols) 47 46 nrows=int(nrows) 48 47 49 48 #check that nrows and ncols were given at the same time! 50 49 if not nr==nc: 51 50 raise Exception('error: nrows and ncols need to be specified together, or not at all') 52 51 53 52 #Go through plots 54 53 if numberofplots: 55 56 54 #if plt.fignum_exists(figurenumber): 57 55 # plt.cla() … … 60 58 if options.list[0].exist('figsize'): 61 59 figsize=options.list[0].getfieldvalue('figsize') 62 fig=plt.figure(figurenumber,figsize=(figsize[0],figsize[1]) ,tight_layout=True)60 fig=plt.figure(figurenumber,figsize=(figsize[0],figsize[1]))#,tight_layout=True) 63 61 else: 64 fig=plt.figure(figurenumber ,tight_layout=True)62 fig=plt.figure(figurenumber)#,tight_layout=True) 65 63 fig.clf() 66 64 65 backgroundcolor=options.list[0].getfieldvalue('backgroundcolor',(0.7,0.7,0.7)) 66 fig.set_facecolor(backgroundcolor) 67 68 69 translator={'on':'each', 70 'off':'None', 71 'one':'single'} 67 72 # options needed to define plot grid 73 plotnum=options.numberofplots 68 74 direction=options.list[0].getfieldvalue('direction','row') # row,column 69 75 axes_pad=options.list[0].getfieldvalue('axes_pad',0.25) 70 76 add_all=options.list[0].getfieldvalue('add_all',True) # True,False 71 77 share_all=options.list[0].getfieldvalue('share_all',True) # True,False 72 label_mode=options.list[0].getfieldvalue('label_mode','1') # 1,L,all 73 cbar_mode=options.list[0].getfieldvalue('cbar_mode','each') # none,single,each 74 cbar_location=options.list[0].getfieldvalue('cbar_location','right') # right,top 75 cbar_size=options.list[0].getfieldvalue('cbar_size','5%') 76 cbar_pad=options.list[0].getfieldvalue('cbar_pad','2.5%') # None or % 77 78 axgrid=ImageGrid(fig, 111, 78 label_mode=options.list[0].getfieldvalue('label_mode','L') # 1,L,all 79 colorbar=options.list[0].getfieldvalue('colorbar','on') # on, off (single) 80 cbar_mode=translator[colorbar] 81 cbar_location=options.list[0].getfieldvalue('colorbarpos','right') # right,top 82 cbar_size=options.list[0].getfieldvalue('colorbarsize','5%') 83 cbar_pad=options.list[0].getfieldvalue('colorbarpad','2.5%') # None or % 84 85 axgrid=ImageGrid(fig,111, 79 86 nrows_ncols=(nrows,ncols), 87 ngrids=plotnum, 80 88 direction=direction, 81 89 axes_pad=axes_pad, … … 86 94 cbar_location=cbar_location, 87 95 cbar_size=cbar_size, 88 cbar_pad=cbar_pad 89 ) 96 cbar_pad=cbar_pad) 90 97 91 if cbar_mode=='none': 92 for ax in axgrid.cbar_axes: fig._axstack.remove(ax) 98 if cbar_mode=='None': 99 for ax in axgrid.cbar_axes: 100 fig._axstack.remove(ax) 93 101 94 for i in range(numberofplots): 95 plot_manager(options.list[i].getfieldvalue('model',md),options.list[i],fig,axgrid[i]) 96 102 for i,ax in enumerate(axgrid.axes_all): 103 plot_manager(options.list[i].getfieldvalue('model',md),options.list[i],fig,axgrid,i) 97 104 fig.show() 98 105 else: -
issm/trunk-jpl/src/py3/plot/processdata.py
r21255 r23670 1 from math import isnan 2 import numpy as np 1 import numpy as np 3 2 4 3 def processdata(md,data,options): 5 """ 6 PROCESSDATA - process data to be plotted 4 """ 5 PROCESSDATA - process data to be plotted 6 7 datatype = 1 -> elements 8 datatype = 2 -> nodes 9 datatype = 3 -> node quivers 10 datatype = 4 -> patch 11 12 Usage: 13 data,datatype=processdata(md,data,options); 14 15 See also: PLOTMODEL, PROCESSMESH 16 """ 17 # {{{ Initialisation and grabbing auxiliaries 18 # check format 19 if (len(data)==0 or (len(data)==1 and not isinstance(data,dict) and np.isnan(data).all())): 20 raise ValueError("processdata error message: 'data' provided is empty") 21 # get the shape 22 if 'numberofvertices2d' in dir(md.mesh): 23 numberofvertices2d=md.mesh.numberofvertices2d 24 numberofelements2d=md.mesh.numberofelements2d 25 else: 26 numberofvertices2d=np.nan 27 numberofelements2d=np.nan 28 procdata=np.copy(data) 29 #initialize datatype 30 datatype=0 31 # get datasize 32 if np.ndim(procdata)==1: 33 datasize=(np.shape(procdata)[0],1) 34 elif np.ndim(procdata)==2: 35 datasize=np.shape(procdata) 36 elif np.ndim(procdata)==3: 37 if np.shape(procdata)[0]==2: 38 #treating a dim two list that needs to be stacked 39 procdata=np.hstack((procdata[0,:,:],procdata[1,:,:])) 40 datasize=np.shape(procdata) 41 else: 42 raise ValueError('data list contains more than two vectore, we can not cope with that') 43 else: 44 raise ValueError('data passed to plotmodel has bad dimensions; check that column vectors are rank-1') 45 # }}} 46 # {{{ process NaN's if any 47 nanfill=options.getfieldvalue('nan',-9999) 48 if np.any(np.isnan(procdata)): 49 lb=np.nanmin(procdata) 50 ub=np.nanmax(procdata) 51 if lb==ub: 52 lb=lb-0.5 53 ub=ub+0.5 54 nanfill=lb-1 55 #procdata[np.isnan(procdata)]=nanfill 56 procdata=np.ma.array(procdata,mask=np.isnan(procdata)) 57 options.addfielddefault('clim',[lb,ub]) 58 options.addfielddefault('cmap_set_under','1') 59 print("WARNING: nan's treated as", nanfill, "by default. Change using pairoption 'nan',nan_fill_value in plotmodel call") 60 # }}} 61 # {{{ log 62 if options.exist('log'): 63 cutoff=options.getfieldvalue('log',1) 64 procdata[np.where(procdata<cutoff)]=cutoff 65 # }}} 66 # {{{ quiver plot 67 if datasize[1]>1 and datasize[0]!= md.mesh.numberofvertices+1: 68 if datasize[0]==md.mesh.numberofvertices and datasize[1]==2: 69 datatype=3 70 else: 71 raise ValueError('plotmodel error message: data should have two columns of length md.mesh.numberofvertices for a quiver plot') 72 # }}} 73 # {{{ element data 74 75 if datasize[0]==md.mesh.numberofelements and datasize[1]==1: 76 #initialize datatype if non patch 77 if datatype!=4 and datatype!=5: 78 datatype=1 79 # {{{mask 80 if options.exist('mask'): 81 flags=options.getfieldvalue('mask') 82 hide=np.invert(flags) 83 if np.size(flags)==md.mesh.numberofvertices: 84 EltMask=np.asarray([np.any(np.in1d(index,np.where(hide))) for index in md.mesh.elements-1]) 85 procdata=np.ma.array(procdata,mask=EltMask) 86 options.addfielddefault('cmap_set_bad','w') 87 elif np.size(flags)==md.mesh.numberofelements: 88 procdata=np.ma.array(procdata,mask=hide) 89 options.addfielddefault('cmap_set_bad','w') 90 else: 91 print('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements') 92 # }}} 93 94 # }}} 95 # {{{ node data 96 if datasize[0]==md.mesh.numberofvertices and datasize[1]==1: 97 datatype=2 98 # {{{ Mask 99 if options.exist('mask'): 100 flags=options.getfieldvalue('mask') 101 hide=np.invert(flags) 102 if np.size(flags)==md.mesh.numberofvertices: 103 procdata=np.ma.array(procdata,mask=hide) 104 options.addfielddefault('cmap_set_bad','w') 105 elif np.size(flags)==md.mesh.numberofelements: 106 NodeMask=np.zeros(np.shape(md.mesh.x),dtype=bool) 107 HideElt=md.mesh.elements[np.where(hide)[0]]-1 108 NodeMask[HideElt]=True 109 procdata=np.ma.array(procdata,mask=NodeMask) 110 options.addfielddefault('cmap_set_bad','w') 111 else: 112 print('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements') 113 # }}} 114 # }}} 115 # {{{ spc time series 116 if datasize[0]==md.mesh.numberofvertices+1: 117 datatype=2 118 spccol=options.getfieldvalue('spccol',0) 119 print('multiple-column spc field; specify column to plot using option "spccol"') 120 print('column ', spccol, ' plotted for time: ', procdata[-1,spccol]) 121 procdata=procdata[0:-1,spccol] 7 122 8 datatype = 1 -> elements 9 datatype = 2 -> nodes 10 datatype = 3 -> node quivers 11 datatype = 4 -> patch 12 13 Usage: 14 data,datatype=processdata(md,data,options); 15 16 See also: PLOTMODEL, PROCESSMESH 17 """ 18 19 #check format 20 if (len(data)==0 or (len(data)==1 and not isinstance(data,dict) and isnan(data).all())): 21 raise ValueError("processdata error message: 'data' provided is empty") 22 23 #needed later on 24 if 'numberofvertices2d' in dir(md.mesh): 25 numberofvertices2d=md.mesh.numberofvertices2d 26 numberofelements2d=md.mesh.numberofelements2d 27 else: 28 numberofvertices2d=np.nan 29 numberofelements2d=np.nan 30 31 procdata=np.copy(data) 32 33 #process patch 34 35 #initialize datatype 36 datatype=0 37 38 #get datasize 39 if np.ndim(procdata)==1: 40 datasize=np.array([len(procdata),1]) 41 else: 42 datasize=np.shape(procdata) 43 if len(datasize)>2: 44 raise ValueError('data passed to plotmodel has more than 2 dimensions; check that column vectors are rank-1') 45 46 #process NaN's if any 47 nanfill=options.getfieldvalue('nan',-9999) 48 if np.any(np.isnan(procdata)): 49 lb=np.min(data[~np.isnan(data)]) 50 ub=np.max(data[~np.isnan(data)]) 51 if lb==ub: 52 lb=lb-0.5 53 ub=ub+0.5 54 nanfill=lb-1 55 procdata[np.isnan(procdata)]=nanfill 56 options.addfielddefault('clim',[lb,ub]) 57 options.addfielddefault('cmap_set_under','1') 58 print(("WARNING: nan's treated as", nanfill, "by default. Change using pairoption 'nan',nan_fill_value in plotmodel call")) 59 60 #quiver plot 61 if datasize[1]>1 and datasize[0]!= md.mesh.numberofvertices+1: 62 if datasize[0]==md.mesh.numberofvertices and datasize[1]==2: 63 datatype=3 64 else: 65 raise ValueError('plotmodel error message: data should have two columns of length md.mesh.numberofvertices for a quiver plot') 66 67 #non-patch processing 68 69 #element data 70 if datasize[0]==md.mesh.numberofelements and datasize[1]==1: 71 72 #initialize datatype if non patch 73 if datatype!=4 and datatype!=5: 74 datatype=1 75 76 #mask? 77 78 #log? 79 80 #node data 81 if datasize[0]==md.mesh.numberofvertices and datasize[1]==1: 82 datatype=2 83 84 #spc time series? 85 if datasize[0]==md.mesh.numberofvertices+1: 86 datatype=2 87 spccol=options.getfieldvalue('spccol',0) 88 print('multiple-column spc field; specify column to plot using option "spccol"') 89 print(('column ', spccol, ' plotted for time: ', procdata[-1,spccol])) 90 procdata=procdata[0:-1,spccol] 91 92 #mask? 93 94 #log? 123 #mask? 95 124 96 125 #layer projection? 97 126 98 127 #control arrow density if quiver plot 99 100 #convert rank-2 array to rank-1 101 if np.ndim(procdata)==2 and np.shape(procdata)[1]==1: 102 procdata=procdata.reshape(-1,) 103 104 #if datatype is still zero, error out 105 if datatype==0: 106 raise ValueError("processdata error: data provided not recognized or not supported") 107 else: 108 return procdata, datatype 128 # }}} 129 # {{{ convert rank-2 array to rank-1 130 if np.ndim(procdata)==2 and np.shape(procdata)[1]==1: 131 procdata=procdata.reshape(-1,) 132 # }}} 133 # {{{ if datatype is still zero, error out 134 if datatype==0: 135 raise ValueError("processdata error: data provided not recognized or not supported") 136 else: 137 return procdata, datatype 138 # }}} -
issm/trunk-jpl/src/py3/plot/processmesh.py
r21255 r23670 1 1 from math import isnan 2 import MatlabFuncs as m 3 import numpy as np 2 import numpy as np 4 3 5 4 def processmesh(md,data,options): 6 5 """ 7 6 PROCESSMESH - process the mesh for plotting 8 7 9 8 Usage: 10 11 9 x,y,z,elements,is2d=processmech(md,data,options) 10 12 11 See also: PLOTMODEL, PROCESSDATA 13 12 """ 14 15 # some checks13 14 # {{{ check mesh size parameters 16 15 if md.mesh.numberofvertices==0: 17 16 raise ValueError('processmesh error: mesh is empty') 18 17 if md.mesh.numberofvertices==md.mesh.numberofelements: 19 18 raise ValueError('processmesh error: the number of elements is the same as the number of nodes') 19 # }}} 20 # {{{ treating coordinates 20 21 21 if len(data)==0 or not isinstance(data,dict): 22 try: 23 z=md.mesh.z 24 except AttributeError: 25 z=np.zeros(np.shape(md.mesh.x)) 26 elements=md.mesh.elements-1 27 28 if options.getfieldvalue('layer',0)>=1: 29 x=md.mesh.x2d 30 y=md.mesh.y2d 31 z=np.zeros(np.shape(x)) 32 elements=md.mesh.elements2d-1 33 elif 'latlon' in options.getfieldvalue('coord','xy'): 34 x=md.mesh.long 35 y=md.mesh.lat 36 else: 37 x=md.mesh.x 38 y=md.mesh.y 39 40 #is it a 2D plot? 41 if md.mesh.dimension()==2 or options.getfieldvalue('layer',0)>=1: 42 is2d=1 43 else: 44 is2d=0 22 45 23 if 'latlon' not in options.getfieldvalue('coord','xy').lower(): #convert to lower case for comparison24 x=md.mesh.x25 if 'x2d' in dir(md.mesh): x2d=md.mesh.x2d26 y=md.mesh.y27 if 'y2d' in dir(md.mesh): y2d=md.mesh.x2d28 else:29 x=md.mesh.long30 y=md.mesh.lat31 32 if 'z' in dir(md.mesh):33 z=md.mesh.z34 else:35 z=np.zeros_like(md.mesh.x)36 37 if 'elements2d' in dir(md.mesh):38 elements2d=md.mesh.elements2d39 elements2d=elements2d-1 # subtract one since python indexes from zero40 elements=md.mesh.elements41 elements=elements-142 43 #is it a 2D plot?44 if md.mesh.dimension()==2:45 is2d=146 else:47 if options.getfieldvalue('layer',0)>=1:48 is2d=149 else:50 is2d=051 52 #layer projection?53 if options.getfieldvalue('layer',0)>=1:54 if 'latlon' in options.getfieldvalue('coord','xy').lower():55 raise ValueError('processmesh error: cannot work with 3D mesh in lat-lon coords')56 #we modify the mesh temporarily to a 2D mesh from which the 3D mesh was extruded57 x=x2d58 y=y2d59 z=zeros(size(x2d))60 elements=elements2d61 62 else:63 #Process mesh for plotting64 if md.mesh.dimension()==2:65 is2d=166 else:67 # process polycollection here for 3D plot68 is2d=069 70 46 #units 71 47 if options.exist('unit'): -
issm/trunk-jpl/src/py3/plot/writejsfield.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 def writejsfield(fid,name,variable,nods): 3 3 #WRITEJSFIELD - write variable to javascript file … … 8 8 #write array: 9 9 #if not isinstance(variable, list): 10 if type(variable[0])==n umpy.float64:10 if type(variable[0])==np.float64: 11 11 fid.write('<!-- {0}{{{{{{-->\n'.format(name)) 12 12 fid.write('{0}=['.format(name)) -
issm/trunk-jpl/src/py3/plot/writejsfile.py
r19895 r23670 1 import numpy 1 import numpy as np 2 2 from writejsfield import writejsfield 3 3 def writejsfile(filename,model,keyname): … … 48 48 fid.write('result["shortlabel"]="{0}";\n'.format(results[i].shortlabel)) 49 49 fid.write('result["unit"]="{0}";\n'.format(results[i].unit)) 50 if type(results[i].data)==n umpy.float64:50 if type(results[i].data)==np.float64: 51 51 fid.write('result["time_range"]=[{0},{1}];\n'.format(results[i].time_range[0],results[i].time_range[1])) 52 52 fid.write('results["{0}"]=result;\n'.format(i)) -
issm/trunk-jpl/src/py3/shp/shp2exp.py
r21349 r23670 33 33 geom=shp.shapes()[i].shapeType 34 34 if geom==5: # polygon 35 35 expdict['closed']=1 36 36 tmpx=[p[0] for p in shp.shapes()[i].points] 37 37 tmpy=[q[1] for q in shp.shapes()[i].points] … … 39 39 y.append(tmpy) 40 40 elif geom==3: # line 41 41 expdict['closed']=0 42 42 tmpx=[p[0] for p in shp.shapes()[i].points] 43 43 tmpy=[q[1] for q in shp.shapes()[i].points] … … 45 45 y.append(tmpy) 46 46 elif geom==1: # point 47 47 expdict['closed']=0 48 48 x.append(shp.shapes()[i].points[0][0]) 49 49 y.append(shp.shapes()[i].points[0][1]) -
issm/trunk-jpl/src/py3/solve/WriteData.py
r19895 r23670 1 import numpy 2 import math 1 import numpy as np 3 2 import struct 4 3 import pairoptions 5 4 import MatlabFuncs as m 6 from EnumDefinitions import * 7 from EnumToString import EnumToString 8 9 def WriteData(fid,**kwargs): 5 6 def WriteData(fid,prefix,*args): 10 7 """ 11 8 WRITEDATA - write model field in binary file 12 9 13 10 Usage: 14 11 WriteData(fid,varargin) … … 16 13 17 14 #process options 18 options=pairoptions.pairoptions(* *kwargs)15 options=pairoptions.pairoptions(*args) 19 16 20 17 #Get data properties … … 24 21 fieldname = options.getfieldvalue('fieldname') 25 22 classname = options.getfieldvalue('class',str(type(obj)).rsplit('.')[-1].split("'")[0]) 26 if options.exist('enum'):27 enum = options.getfieldvalue('enum')28 else:29 enum = BuildEnum(classname+'_'+fieldname)30 data = getattr(obj,fieldname)23 name = options.getfieldvalue('name',prefix+'.'+fieldname); 24 if options.exist('data'): 25 data = options.getfieldvalue('data') 26 else: 27 data = getattr(obj,fieldname) 31 28 else: 32 29 #No processing required 33 30 data = options.getfieldvalue('data') 34 enum = options.getfieldvalue('enum') 31 name = options.getfieldvalue('name') 32 35 33 format = options.getfieldvalue('format') 36 34 mattype = options.getfieldvalue('mattype',0) #only required for matrices … … 44 42 #Scale data if necesarry 45 43 if options.exist('scale'): 44 data=np.array(data) 46 45 scale = options.getfieldvalue('scale') 47 if numpy.size(data) > 1 : 48 if numpy.size(data,0)==timeserieslength: 49 data=numpy.array(data) 50 data[0:-1,:] = scale*data[0:-1,:] 51 else: 52 data = scale*data 46 if np.size(data) > 1 and np.ndim(data) > 1 and np.size(data,0)==timeserieslength: 47 data[0:-1,:] = scale*data[0:-1,:] 53 48 else: 54 49 data = scale*data 55 if n umpy.size(data) > 1:56 if numpy.size(data,0)==timeserieslength:57 yts=365.0*24.0*3600.050 if np.size(data) > 1 and np.size(data,0)==timeserieslength: 51 yts = options.getfieldvalue('yts') 52 if np.ndim(data) > 1: 58 53 data[-1,:] = yts*data[-1,:] 54 else: 55 data[-1] = yts*data[-1] 59 56 60 57 #Step 1: write the enum to identify this record uniquely 61 fid.write(struct.pack('i',enum)) 58 fid.write(struct.pack('i',len(name))) 59 fid.write(struct.pack('%ds' % len(name),name)) 62 60 63 61 #Step 2: write the data itself. 64 62 if m.strcmpi(format,'Boolean'): # {{{ 65 63 # if len(data) !=1: 66 # raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum)[0])64 # raise ValueError('field %s cannot be marshalled as it has more than one element!' % name[0]) 67 65 68 66 #first write length of record 69 67 fid.write(struct.pack('i',4+4)) #1 bool (disguised as an int)+code 70 68 71 #write data code: 72 fid.write(struct.pack('i',FormatToCode(format))) 69 #write data code: 70 fid.write(struct.pack('i',FormatToCode(format))) 73 71 74 72 #now write integer … … 78 76 elif m.strcmpi(format,'Integer'): # {{{ 79 77 # if len(data) !=1: 80 # raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum)[0])78 # raise ValueError('field %s cannot be marshalled as it has more than one element!' % name[0]) 81 79 82 80 #first write length of record 83 81 fid.write(struct.pack('i',4+4)) #1 integer + code 84 82 85 #write data code: 86 fid.write(struct.pack('i',FormatToCode(format))) 83 #write data code: 84 fid.write(struct.pack('i',FormatToCode(format))) 87 85 88 86 #now write integer 89 fid.write(struct.pack('i',data)) 87 fid.write(struct.pack('i',data)) 90 88 # }}} 91 89 92 90 elif m.strcmpi(format,'Double'): # {{{ 93 91 # if len(data) !=1: 94 # raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum)[0])92 # raise ValueError('field %s cannot be marshalled as it has more than one element!' % name[0]) 95 93 96 94 #first write length of record 97 95 fid.write(struct.pack('i',8+4)) #1 double+code 98 96 99 #write data code: 100 fid.write(struct.pack('i',FormatToCode(format))) 97 #write data code: 98 fid.write(struct.pack('i',FormatToCode(format))) 101 99 102 100 #now write double 103 fid.write(struct.pack('d',data)) 101 fid.write(struct.pack('d',data)) 104 102 # }}} 105 103 … … 108 106 fid.write(struct.pack('i',len(data)+4+4)) #string + string size + code 109 107 110 #write data code: 111 fid.write(struct.pack('i',FormatToCode(format))) 108 #write data code: 109 fid.write(struct.pack('i',FormatToCode(format))) 112 110 113 111 #now write string 114 fid.write(struct.pack('i',len(data))) 115 fid.write(struct.pack('%ds' % len(data),data)) 112 fid.write(struct.pack('i',len(data))) 113 fid.write(struct.pack('%ds' % len(data),data)) 116 114 # }}} 117 115 … … 119 117 120 118 if isinstance(data,bool): 121 data=n umpy.array([data])119 data=np.array([data]) 122 120 elif isinstance(data,(list,tuple)): 123 data=n umpy.array(data).reshape(-1,1)124 if n umpy.ndim(data) == 1:125 if n umpy.size(data):126 data=data.reshape(n umpy.size(data),1)121 data=np.array(data).reshape(-1,) 122 if np.ndim(data) == 1: 123 if np.size(data): 124 data=data.reshape(np.size(data),) 127 125 else: 128 126 data=data.reshape(0,0) … … 131 129 s=data.shape 132 130 #if matrix = NaN, then do not write anything 133 if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):131 if np.ndim(data)==2 and np.product(s)==1 and np.all(np.isnan(data)): 134 132 s=(0,0) 135 133 136 134 #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 type138 139 #write data code and matrix type: 140 fid.write(struct.pack('i',FormatToCode(format))) 135 fid.write(struct.pack('i',4+4+8*np.product(s)+4+4)) #2 integers (32 bits) + the double matrix + code + matrix type 136 137 #write data code and matrix type: 138 fid.write(struct.pack('i',FormatToCode(format))) 141 139 fid.write(struct.pack('i',mattype)) 142 140 143 141 #now write matrix 144 fid.write(struct.pack('i',s[0])) 145 fid.write(struct.pack('i',s[1])) 146 for i in range(s[0]): 147 for j in range(s[1]): 148 fid.write(struct.pack('d',float(data[i][j]))) #get to the "c" convention, hence the transpose 142 if np.ndim(data)==1: 143 fid.write(struct.pack('i',s[0])) 144 fid.write(struct.pack('i',1)) 145 for i in range(s[0]): 146 fid.write(struct.pack('d',float(data[i]))) #get to the "c" convention, hence the transpose 147 else: 148 fid.write(struct.pack('i',s[0])) 149 fid.write(struct.pack('i',s[1])) 150 for i in range(s[0]): 151 for j in range(s[1]): 152 fid.write(struct.pack('d',float(data[i][j]))) #get to the "c" convention, hence the transpose 149 153 # }}} 150 154 … … 152 156 153 157 if isinstance(data,int): 154 data=n umpy.array([data])158 data=np.array([data]) 155 159 elif isinstance(data,(list,tuple)): 156 data=n umpy.array(data).reshape(-1,1)157 if n umpy.ndim(data) == 1:158 if n umpy.size(data):159 data=data.reshape(n umpy.size(data),1)160 data=np.array(data).reshape(-1,) 161 if np.ndim(data) == 1: 162 if np.size(data): 163 data=data.reshape(np.size(data),) 160 164 else: 161 165 data=data.reshape(0,0) … … 164 168 s=data.shape 165 169 #if matrix = NaN, then do not write anything 166 if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):170 if np.ndim(data)==2 and np.product(s)==1 and np.all(np.isnan(data)): 167 171 s=(0,0) 168 172 169 173 #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 type171 172 #write data code and matrix type: 173 fid.write(struct.pack('i',FormatToCode(format))) 174 fid.write(struct.pack('i',4+4+8*np.product(s)+4+4)) #2 integers (32 bits) + the double matrix + code + matrix type 175 176 #write data code and matrix type: 177 fid.write(struct.pack('i',FormatToCode(format))) 174 178 fid.write(struct.pack('i',mattype)) 175 179 176 180 #now write matrix 177 fid.write(struct.pack('i',s[0])) 178 fid.write(struct.pack('i',s[1])) 179 for i in range(s[0]): 180 for j in range(s[1]): 181 fid.write(struct.pack('d',float(data[i][j]))) #get to the "c" convention, hence the transpose 181 if np.ndim(data) == 1: 182 fid.write(struct.pack('i',s[0])) 183 fid.write(struct.pack('i',1)) 184 for i in range(s[0]): 185 fid.write(struct.pack('d',float(data[i]))) #get to the "c" convention, hence the transpose 186 else: 187 fid.write(struct.pack('i',s[0])) 188 fid.write(struct.pack('i',s[1])) 189 for i in range(s[0]): 190 for j in range(s[1]): 191 fid.write(struct.pack('d',float(data[i][j]))) #get to the "c" convention, hence the transpose 182 192 # }}} 183 193 … … 185 195 186 196 if isinstance(data,(bool,int,float)): 187 data=n umpy.array([data])197 data=np.array([data]) 188 198 elif isinstance(data,(list,tuple)): 189 data=n umpy.array(data).reshape(-1,1)190 if n umpy.ndim(data) == 1:191 if n umpy.size(data):192 data=data.reshape(n umpy.size(data),1)199 data=np.array(data).reshape(-1,) 200 if np.ndim(data) == 1: 201 if np.size(data): 202 data=data.reshape(np.size(data),) 193 203 else: 194 204 data=data.reshape(0,0) … … 197 207 s=data.shape 198 208 #if matrix = NaN, then do not write anything 199 if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):209 if np.ndim(data)==1 and np.product(s)==1 and np.all(np.isnan(data)): 200 210 s=(0,0) 201 211 202 212 #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 type204 if recordlength > 2**31 :205 raise ValueError('field %s cannot be marshalled because it is larger than 4^31 bytes!' % EnumToString(enum)[0])213 recordlength=4+4+8*np.product(s)+4+4; #2 integers (32 bits) + the double matrix + code + matrix type 214 if recordlength > 4**31 : 215 raise ValueError('field %s cannot be marshalled because it is larger than 4^31 bytes!' % enum) 206 216 207 217 fid.write(struct.pack('i',recordlength)) #2 integers (32 bits) + the double matrix + code + matrix type 208 218 209 #write data code and matrix type: 210 fid.write(struct.pack('i',FormatToCode(format))) 219 #write data code and matrix type: 220 fid.write(struct.pack('i',FormatToCode(format))) 211 221 fid.write(struct.pack('i',mattype)) 212 222 213 223 #now write matrix 214 fid.write(struct.pack('i',s[0])) 215 fid.write(struct.pack('i',s[1])) 216 for i in range(s[0]): 224 if np.ndim(data) == 1: 225 fid.write(struct.pack('i',s[0])) 226 fid.write(struct.pack('i',1)) 227 for i in range(s[0]): 228 fid.write(struct.pack('d',float(data[i]))) #get to the "c" convention, hence the transpose 229 else: 230 fid.write(struct.pack('i',s[0])) 231 fid.write(struct.pack('i',s[1])) 232 for i in range(s[0]): 233 for j in range(s[1]): 234 fid.write(struct.pack('d',float(data[i][j]))) #get to the "c" convention, hence the transpose 235 # }}} 236 237 elif m.strcmpi(format,'CompressedMat'): # {{{ 238 239 if isinstance(data,(bool,int,float)): 240 data=np.array([data]) 241 elif isinstance(data,(list,tuple)): 242 data=np.array(data).reshape(-1,) 243 if np.ndim(data) == 1: 244 if np.size(data): 245 data=data.reshape(np.size(data),) 246 else: 247 data=data.reshape(0,0) 248 249 #Get size 250 s=data.shape 251 if np.ndim(data) == 1: 252 n2=1 253 else: 254 n2=s[1] 255 256 #if matrix = NaN, then do not write anything 257 if np.ndim(data)==1 and np.product(s)==1 and np.all(np.isnan(data)): 258 s=(0,0) 259 n2=0 260 261 #first write length of record 262 recordlength=4+4+8+8+1*(s[0]-1)*n2+8*n2+4+4 #2 integers (32 bits) + the matrix + code + matrix type 263 if recordlength > 4**31 : 264 raise ValueError('field %s cannot be marshalled because it is larger than 4^31 bytes!' % enum) 265 266 fid.write(struct.pack('i',recordlength)) #2 integers (32 bits) + the matrix + code + matrix type 267 268 #write data code and matrix type: 269 fid.write(struct.pack('i',FormatToCode(format))) 270 fid.write(struct.pack('i',mattype)) 271 272 #Write offset and range 273 A = data[0:s[0]-1] 274 offsetA = A.min() 275 rangeA = A.max() - offsetA 276 277 if rangeA == 0: 278 A = A*0 279 else: 280 A = (A-offsetA)/rangeA*255. 281 282 #now write matrix 283 if np.ndim(data) == 1: 284 fid.write(struct.pack('i',s[0])) 285 fid.write(struct.pack('i',1)) 286 fid.write(struct.pack('d',float(offsetA))) 287 fid.write(struct.pack('d',float(rangeA))) 288 for i in range(s[0]-1): 289 fid.write(struct.pack('B',int(A[i]))) 290 291 fid.write(struct.pack('d',float(data[s[0]-1]))) #get to the "c" convention, hence the transpose 292 293 elif np.product(s) > 0: 294 fid.write(struct.pack('i',s[0])) 295 fid.write(struct.pack('i',s[1])) 296 fid.write(struct.pack('d',float(offsetA))) 297 fid.write(struct.pack('d',float(rangeA))) 298 for i in range(s[0]-1): 299 for j in range(s[1]): 300 fid.write(struct.pack('B',int(A[i][j]))) #get to the "c" convention, hence the transpose 301 217 302 for j in range(s[1]): 218 fid.write(struct.pack('d',float(data[i][j]))) #get to the "c" convention, hence the transpose 303 fid.write(struct.pack('d',float(data[s[0]-1][j]))) 304 219 305 # }}} 220 306 … … 225 311 for matrix in data: 226 312 if isinstance(matrix,(bool,int,float)): 227 matrix=n umpy.array([matrix])313 matrix=np.array([matrix]) 228 314 elif isinstance(matrix,(list,tuple)): 229 matrix=n umpy.array(matrix).reshape(-1,1)230 if n umpy.ndim(matrix) == 1:231 if n umpy.size(matrix):232 matrix=matrix.reshape(n umpy.size(matrix),1)315 matrix=np.array(matrix).reshape(-1,) 316 if np.ndim(matrix) == 1: 317 if np.size(matrix): 318 matrix=matrix.reshape(np.size(matrix),) 233 319 else: 234 320 matrix=matrix.reshape(0,0) 235 321 236 322 s=matrix.shape 237 recordlength+=4*2+ s[0]*s[1]*8 #row and col of matrix + matrix of doubles323 recordlength+=4*2+np.product(s)*8 #row and col of matrix + matrix of doubles 238 324 239 325 #write length of record 240 fid.write(struct.pack('i',recordlength)) 241 242 #write data code: 243 fid.write(struct.pack('i',FormatToCode(format))) 326 fid.write(struct.pack('i',recordlength)) 327 328 #write data code: 329 fid.write(struct.pack('i',FormatToCode(format))) 244 330 245 331 #write data, first number of records 246 fid.write(struct.pack('i',len(data))) 247 248 #write each matrix: 332 fid.write(struct.pack('i',len(data))) 333 249 334 for matrix in data: 250 335 if isinstance(matrix,(bool,int,float)): 251 matrix=n umpy.array([matrix])336 matrix=np.array([matrix]) 252 337 elif isinstance(matrix,(list,tuple)): 253 matrix=n umpy.array(matrix).reshape(-1,1)254 if n umpy.ndim(matrix) == 1:255 matrix=matrix.reshape(n umpy.size(matrix),1)338 matrix=np.array(matrix).reshape(-1,) 339 if np.ndim(matrix) == 1: 340 matrix=matrix.reshape(np.size(matrix),) 256 341 257 342 s=matrix.shape 258 fid.write(struct.pack('i',s[0])) 259 fid.write(struct.pack('i',s[1])) 260 for i in range(s[0]): 261 for j in range(s[1]): 262 fid.write(struct.pack('d',float(matrix[i][j]))) 343 344 if np.ndim(matrix) == 1: 345 fid.write(struct.pack('i',s[0])) 346 fid.write(struct.pack('i',1)) 347 for i in range(s[0]): 348 fid.write(struct.pack('d',float(matrix[i]))) #get to the "c" convention, hence the transpose 349 else: 350 fid.write(struct.pack('i',s[0])) 351 fid.write(struct.pack('i',s[1])) 352 for i in range(s[0]): 353 for j in range(s[1]): 354 fid.write(struct.pack('d',float(matrix[i][j]))) 263 355 # }}} 264 356 … … 271 363 272 364 #write length of record 273 fid.write(struct.pack('i',recordlength)) 274 275 #write data code: 276 fid.write(struct.pack('i',FormatToCode(format))) 365 fid.write(struct.pack('i',recordlength)) 366 367 #write data code: 368 fid.write(struct.pack('i',FormatToCode(format))) 277 369 278 370 #now write length of string array 279 fid.write(struct.pack('i',len(data))) 371 fid.write(struct.pack('i',len(data))) 280 372 281 373 #now write the strings 282 374 for string in data: 283 fid.write(struct.pack('i',len(string))) 284 fid.write(struct.pack('%ds' % len(string),string)) 375 fid.write(struct.pack('i',len(string))) 376 fid.write(struct.pack('%ds' % len(string),string)) 285 377 # }}} 286 378 287 379 else: # {{{ 288 raise TypeError('WriteData error message: data type: %d not supported yet! (%s)' % (format, EnumToString(enum)[0]))380 raise TypeError('WriteData error message: data type: %d not supported yet! (%s)' % (format,enum)) 289 381 # }}} 290 291 def BuildEnum(string): # {{{292 """293 BUILDENUM - build enum out of string294 295 Usage:296 enum=BuildEnum(string)297 """298 299 if '_' in string:300 substrs=string.split('_')301 string=''302 for substr in substrs:303 string+=substr[0].upper()+substr[1:]304 else:305 #take first letter of string and make it uppercase:306 string=string[0].upper()+string[1:]307 308 #Get Enum309 enum=StringToEnum(string)[0]310 311 return enum312 # }}}313 382 314 383 def FormatToCode(format): # {{{ 315 384 """ 316 This routine takes the format string, and hardcodes it into an integer, which 317 is passed along the record, in order to identify the nature of the dataset being 385 This routine takes the format string, and hardcodes it into an integer, which 386 is passed along the record, in order to identify the nature of the dataset being 318 387 sent. 319 388 """ … … 337 406 elif m.strcmpi(format,'StringArray'): 338 407 code=9 408 elif m.strcmpi(format,'CompressedMat'): 409 code=10 339 410 else: 340 411 raise InputError('FormatToCode error message: data type not supported yet!') … … 342 413 return code 343 414 # }}} 344 -
issm/trunk-jpl/src/py3/solve/loadresultsfromcluster.py
r19895 r23670 3 3 import platform 4 4 from loadresultsfromdisk import loadresultsfromdisk 5 6 from helpers import * 5 7 6 8 def loadresultsfromcluster(md,runtimename=False): … … 23 25 filelist.append(md.miscellaneous.name+'.qmu.err') 24 26 filelist.append(md.miscellaneous.name+'.qmu.out') 25 if 'tabular_graphics_data' in md.qmu.params:26 if md.qmu.params ['tabular_graphics_data']:27 if 'tabular_graphics_data' in fieldnames(md.qmu.params): 28 if md.qmu.params.tabular_graphics_data: 27 29 filelist.append('dakota_tabular.dat') 28 30 else: … … 31 33 32 34 #If we are here, no errors in the solution sequence, call loadresultsfromdisk. 33 md=loadresultsfromdisk(md,md.miscellaneous.name+'.outbin') 34 35 if os.path.exists(md.miscellaneous.name+'.outbin'): 36 if os.path.getsize(md.miscellaneous.name+'.outbin')>0: 37 md=loadresultsfromdisk(md,md.miscellaneous.name+'.outbin') 38 else: 39 print('WARNING, outbin file is empty for run '+md.miscellaneous.name) 40 elif not md.qmu.isdakota: 41 print('WARNING, outbin file does not exist '+md.miscellaneous.name) 42 35 43 #erase the log and output files 36 44 if md.qmu.isdakota: 37 filename=os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name) 45 #filename=os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name) 46 filename = md.miscellaneous.name 47 48 # this will not work like normal as dakota doesn't generate outbin files, 49 # instead calls postqmu to store results directly in the model 50 # at md.results.dakota via dakota_out_parse 51 md=loadresultsfromdisk(md,md.miscellaneous.name+'.outbin') 38 52 else: 39 53 filename=md.miscellaneous.name … … 49 63 if hostname==cluster.name: 50 64 if md.qmu.isdakota: 51 filename=os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name) 65 #filename=os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name) 66 filename = md.miscellaneous.name 52 67 TryRem('.queue',filename) 53 68 else: … … 59 74 TryRem('.bat',filename) 60 75 76 # remove this for bin file debugging 61 77 TryRem('.bin',filename) 78 79 #cwd = os.getcwd().split('/')[-1] 80 if md.qmu.isdakota: 81 os.chdir('..') 82 #TryRem('',cwd) 62 83 63 84 return md 64 85 65 86 def TryRem(extension,filename): 66 try: 87 try: 67 88 os.remove(filename+extension) 68 89 except OSError: -
issm/trunk-jpl/src/py3/solve/loadresultsfromdisk.py
r19895 r23670 2 2 from results import results 3 3 from parseresultsfromdisk import parseresultsfromdisk 4 from EnumToString import EnumToString5 4 import MatlabFuncs as m 5 from postqmu import postqmu 6 6 7 7 def loadresultsfromdisk(md,filename): … … 28 28 29 29 #load results onto model 30 structure=parseresultsfromdisk( filename,not md.settings.io_gather)30 structure=parseresultsfromdisk(md,filename,not md.settings.io_gather) 31 31 if not len(structure): 32 32 raise RuntimeError("No result found in binary file '%s'. Check for solution crash." % filename) … … 58 58 #post processes qmu results if necessary 59 59 else: 60 61 if not isinstance(md.private.solution,str): 62 [md.private.solution]=EnumToString(md.private.solution) 63 md=postqmu(md) 64 os.chdir('..') 60 md=postqmu(md,filename) 65 61 66 62 return md 67 -
issm/trunk-jpl/src/py3/solve/marshall.py
r19895 r23670 1 1 from WriteData import WriteData 2 from EnumDefinitions import *3 2 4 3 def marshall(md): … … 12 11 marshall(md) 13 12 """ 14 15 print("marshalling file '%s.bin'." % md.miscellaneous.name)13 if md.verbose.solution: 14 print("marshalling file '%s.bin'." % md.miscellaneous.name) 16 15 17 16 #open file for binary writing … … 21 20 raise IOError("marshall error message: could not open '%s.bin' file for binary writing." % md.miscellaneous.name) 22 21 23 #First, write MaximumNumberOfEnum to make sure that the Enums are synchronized24 WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum(),'data',True,'format','Boolean')25 26 #Go through all model fields: check that it is a class and call checkconsistency27 fields=vars(md)28 29 # for field in fields.iterkeys():30 22 for field in md.properties(): 31 23 32 24 #Some properties do not need to be marshalled 33 if field in ['results','radaroverlay','toolkits','cluster',' flaim','private']:25 if field in ['results','radaroverlay','toolkits','cluster','private']: 34 26 continue 35 27 … … 40 32 #Marshall current object 41 33 #print "marshalling %s ..." % field 42 exec("md. %s.marshall(md,fid)" % field)34 exec("md.{}.marshall('md.{}',md,fid)".format(field,field)) 43 35 44 #Last, write MaximumNumberOfEnum+1to make sure that the binary file is not corrupt45 WriteData(fid,' enum',MaximumNumberOfDefinitionsEnum()+1,'data',True,'format','Boolean');36 #Last, write "md.EOF" to make sure that the binary file is not corrupt 37 WriteData(fid,'XXX','name','md.EOF','data',True,'format','Boolean'); 46 38 47 39 #close file -
issm/trunk-jpl/src/py3/solve/parseresultsfromdisk.py
r19895 r23670 1 1 import struct 2 import numpy 2 import numpy as np 3 3 from collections import OrderedDict 4 4 import results as resultsclass 5 import MatlabFuncs as m 6 7 def parseresultsfromdisk(filename,iosplit): 8 """ 9 PARSERESULTSFROMDISK - ... 10 11 Usage: 12 results=parseresultsfromdisk(filename,iosplit) 13 """ 14 5 6 def parseresultsfromdisk(md,filename,iosplit): 15 7 if iosplit: 16 results=parseresultsfromdiskiosplit(filename)8 saveres=parseresultsfromdiskiosplit(md,filename) 17 9 else: 18 results=parseresultsfromdiskioserial(filename) 19 20 return results 21 22 def parseresultsfromdiskioserial(filename): # {{{ 23 """ 24 PARSERESULTSFROMDISK - ... 25 26 Usage: 27 results=parseresultsfromdiskioserial(filename) 28 """ 29 10 saveres=parseresultsfromdiskioserial(md,filename) 11 12 return saveres 13 14 def parseresultsfromdiskioserial(md,filename): # {{{ 30 15 #Open file 31 16 try: … … 35 20 36 21 #initialize results: 37 results=[] 38 results.append(None) 22 saveres=[] 39 23 40 24 #Read fields until the end of the file. 41 result=ReadData(fid)25 loadres=ReadData(fid,md) 42 26 43 27 counter=0 44 28 check_nomoresteps=0 45 step= result['step']46 47 while result:48 29 step=loadres['step'] 30 31 while loadres: 32 #check that the new result does not add a step, which would be an error: 49 33 if check_nomoresteps: 50 #check that the new result does not add a step, which would be an error: 51 if result['step']>=1: 34 if loadres['step']>=1: 52 35 raise TypeError("parsing results for a steady-state core, which incorporates transient results!") 53 36 54 37 #Check step, increase counter if this is a new step 55 if(step!= result['step'] and result['step']>1):38 if(step!=loadres['step'] and loadres['step']>1): 56 39 counter = counter + 1 57 step = result['step']58 59 #Add result 60 if result['step']==0:40 step = loadres['step'] 41 42 #Add result 43 if loadres['step']==0: 61 44 #if we have a step = 0, this is a steady state solution, don't expect more steps. 62 45 index = 0; 63 46 check_nomoresteps=1 64 65 elif result['step']==1: 47 elif loadres['step']==1: 66 48 index = 0 67 49 else: 68 50 index = counter; 69 70 if index > len(results)-1:71 for i in range(len(results)-1,index-1):72 results.append(None)73 results.append(resultsclass.results())74 51 75 elif results[index] is None: 76 results[index]=resultsclass.results() 77 52 if index > len(saveres)-1: 53 for i in range(len(saveres)-1,index-1): 54 saveres.append(None) 55 saveres.append(resultsclass.results()) 56 elif saveres[index] is None: 57 saveres[index]=resultsclass.results() 78 58 79 59 #Get time and step 80 if result['step'] != -9999.: 81 setattr(results[index],'step',result['step']) 82 if result['time'] != -9999.: 83 setattr(results[index],'time',result['time']) 84 85 #Add result 86 if hasattr(results[index],result['fieldname']) and not m.strcmp(result['fieldname'],'SolutionType'): 87 setattr(results[index],result['fieldname'],numpy.vstack((getattr(results[index],result['fieldname']),result['field']))) 88 else: 89 setattr(results[index],result['fieldname'],result['field']) 90 91 #read next result 92 result=ReadData(fid) 60 if loadres['step'] != -9999.: 61 saveres[index].__dict__['step']=loadres['step'] 62 if loadres['time'] != -9999.: 63 saveres[index].__dict__['time']=loadres['time'] 64 65 #Add result 66 saveres[index].__dict__[loadres['fieldname']]=loadres['field'] 67 68 #read next result 69 loadres=ReadData(fid,md) 93 70 94 71 fid.close() 95 72 96 return results 97 # }}} 98 def parseresultsfromdiskiosplit(filename): # {{{ 99 """ 100 PARSERESULTSFROMDISKIOSPLIT - ... 101 102 Usage: 103 results=parseresultsfromdiskiosplit(filename) 104 """ 73 return saveres 74 # }}} 75 def parseresultsfromdiskiosplit(md,filename): # {{{ 105 76 106 77 #Open file … … 110 81 raise IOError("loadresultsfromdisk error message: could not open '%s' for binary reading." % filename) 111 82 112 results=[]83 saveres=[] 113 84 114 85 #if we have done split I/O, ie, we have results that are fragmented across patches, 115 86 #do a first pass, and figure out the structure of results 116 result=ReadDataDimensions(fid)117 while result:87 loadres=ReadDataDimensions(fid) 88 while loadres: 118 89 119 90 #Get time and step 120 if result['step'] > len(results):121 for i in range(len( results),result['step']-1):122 results.append(None)123 results.append(resultsclass.results())124 setattr( results[result['step']-1],'step',result['step'])125 setattr( results[result['step']-1],'time',result['time'])126 127 #Add result 128 setattr( results[result['step']-1],result['fieldname'],float('NaN'))129 130 #read next result 131 result=ReadDataDimensions(fid)91 if loadres['step'] > len(saveres): 92 for i in range(len(saveres),loadres['step']-1): 93 saveres.append(None) 94 saveres.append(resultsclass.results()) 95 setattr(saveres[loadres['step']-1],'step',loadres['step']) 96 setattr(saveres[loadres['step']-1],'time',loadres['time']) 97 98 #Add result 99 setattr(saveres[loadres['step']-1],loadres['fieldname'],float('NaN')) 100 101 #read next result 102 loadres=ReadDataDimensions(fid) 132 103 133 104 #do a second pass, and figure out the size of the patches 134 105 fid.seek(0) #rewind 135 result=ReadDataDimensions(fid)136 while result:137 138 #read next result 139 result=ReadDataDimensions(fid)106 loadres=ReadDataDimensions(fid) 107 while loadres: 108 109 #read next result 110 loadres=ReadDataDimensions(fid) 140 111 141 112 #third pass, this time to read the real information 142 113 fid.seek(0) #rewind 143 result=ReadData(fid)144 while result:114 loadres=ReadData(fid,md) 115 while loadres: 145 116 146 117 #Get time and step 147 if result['step']> len(results):148 for i in range(len( results),result['step']-1):149 results.append(None)150 results.append(resultsclass.results())151 setattr( results[result['step']-1],'step',result['step'])152 setattr( results[result['step']-1],'time',result['time'])153 154 #Add result 155 setattr( results[result['step']-1],result['fieldname'],result['field'])156 157 #read next result 158 result=ReadData(fid)118 if loadres['step']> len(saveres): 119 for i in range(len(saveres),loadres['step']-1): 120 saveres.append(None) 121 saveres.append(saveresclass.saveres()) 122 setattr(saveres[loadres['step']-1],'step',loadres['step']) 123 setattr(saveres[loadres['step']-1],'time',loadres['time']) 124 125 #Add result 126 setattr(saveres[loadres['step']-1],loadres['fieldname'],loadres['field']) 127 128 #read next result 129 loadres=ReadData(fid,md) 159 130 160 131 #close file 161 132 fid.close() 162 133 163 return results164 # }}} 165 def ReadData(fid ): # {{{134 return saveres 135 # }}} 136 def ReadData(fid,md): # {{{ 166 137 """ 167 138 READDATA - ... 168 139 169 140 Usage: 170 field=ReadData(fid )141 field=ReadData(fid,md) 171 142 """ 172 143 … … 182 153 M=struct.unpack('i',fid.read(struct.calcsize('i')))[0] 183 154 if type==1: 184 field=n umpy.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) 185 156 elif type==2: 186 157 field=struct.unpack('%ds' % M,fid.read(M))[0][:-1] … … 188 159 N=struct.unpack('i',fid.read(struct.calcsize('i')))[0] 189 160 # field=transpose(fread(fid,[N M],'double')); 190 field=n umpy.zeros(shape=(M,N),dtype=float)161 field=np.zeros(shape=(M,N),dtype=float) 191 162 for i in range(M): 192 163 field[i,:]=struct.unpack('%dd' % N,fid.read(N*struct.calcsize('d'))) 164 elif type==4: 165 N=struct.unpack('i',fid.read(struct.calcsize('i')))[0] 166 # field=transpose(fread(fid,[N M],'int')); 167 field=np.zeros(shape=(M,N),dtype=int) 168 for i in range(M): 169 field[i,:]=struct.unpack('%ii' % N,fid.read(N*struct.calcsize('i'))) 193 170 else: 194 171 raise TypeError("cannot read data of type %d" % type) 195 172 196 173 #Process units here FIXME: this should not be done here! 197 yts=365.0*24.0*3600.0 198 if m.strcmp(fieldname,'BalancethicknessThickeningRate'): 199 field = field*yts 200 elif m.strcmp(fieldname,'Time'): 201 field = field/yts 202 elif m.strcmp(fieldname,'HydrologyWaterVx'): 203 field = field*yts 204 elif m.strcmp(fieldname,'HydrologyWaterVy'): 205 field = field*yts 206 elif m.strcmp(fieldname,'Vx'): 207 field = field*yts 208 elif m.strcmp(fieldname,'Vy'): 209 field = field*yts 210 elif m.strcmp(fieldname,'Vz'): 211 field = field*yts 212 elif m.strcmp(fieldname,'Vel'): 213 field = field*yts 214 elif m.strcmp(fieldname,'BasalforcingsGroundediceMeltingRate'): 215 field = field*yts 216 elif m.strcmp(fieldname,'TotalSmb'): 217 field = field/10.**12.*yts #(GigaTon/year) 218 elif m.strcmp(fieldname,'SmbMassBalance'): 219 field = field*yts 220 elif m.strcmp(fieldname,'CalvingCalvingrate'): 221 field = field*yts 222 223 224 result=OrderedDict() 225 result['fieldname']=fieldname 226 result['time']=time 227 result['step']=step 228 result['field']=field 174 yts=md.constants.yts 175 if fieldname=='BalancethicknessThickeningRate': 176 field = field*yts 177 elif fieldname=='HydrologyWaterVx': 178 field = field*yts 179 elif fieldname=='HydrologyWaterVy': 180 field = field*yts 181 elif fieldname=='Vx': 182 field = field*yts 183 elif fieldname=='Vy': 184 field = field*yts 185 elif fieldname=='Vz': 186 field = field*yts 187 elif fieldname=='Vel': 188 field = field*yts 189 elif fieldname=='BasalforcingsGroundediceMeltingRate': 190 field = field*yts 191 elif fieldname=='BasalforcingsFloatingiceMeltingRate': 192 field = field*yts 193 elif fieldname=='TotalFloatingBmb': 194 field = field/10.**12*yts #(GigaTon/year) 195 elif fieldname=='TotalFloatingBmbScaled': 196 field = field/10.**12*yts #(GigaTon/year) 197 elif fieldname=='TotalGroundedBmb': 198 field = field/10.**12*yts #(GigaTon/year) 199 elif fieldname=='TotalGroundedBmbScaled': 200 field = field/10.**12*yts #(GigaTon/year) 201 elif fieldname=='TotalSmb': 202 field = field/10.**12*yts #(GigaTon/year) 203 elif fieldname=='TotalSmbScaled': 204 field = field/10.**12*yts #(GigaTon/year) 205 elif fieldname=='SmbMassBalance': 206 field = field*yts 207 elif fieldname=='SmbPrecipitation': 208 field = field*yts 209 elif fieldname=='SmbRunoff': 210 field = field*yts 211 elif fieldname=='SmbEvaporation': 212 field = field*yts; 213 elif fieldname=='SmbRefreeze': 214 field = field*yts; 215 elif fieldname=='SmbEC': 216 field = field*yts 217 elif fieldname=='SmbAccumulation': 218 field = field*yts 219 elif fieldname=='SmbMelt': 220 field = field*yts 221 elif fieldname=='SmbMAdd': 222 field = field*yts 223 elif fieldname=='CalvingCalvingrate': 224 field = field*yts 225 elif fieldname=='LoveKernelsReal' or fieldname=='LoveKernelsImag': 226 nlayer = md.materials.numlayers 227 degmax = md.love.sh_nmax 228 nfreq = md.love.nfreq 229 #for numpy 1.8+ only 230 #temp_field = np.full((degmax+1,nfreq,nlayer+1,6),0.0) 231 temp_field = np.empty((degmax+1,nfreq,nlayer+1,6)) 232 temp_field.fill(0.0) 233 for ii in range(degmax+1): 234 for jj in range(nfreq): 235 for kk in range(nlayer+1): 236 ll = ii*(nlayer+1)*6 + (kk*6+1) 237 for mm in range(6): 238 temp_field[ii,jj,kk,mm] = field[ll+mm-1,jj] 239 field=temp_field 240 241 if time !=-9999: 242 time = time/yts 243 244 saveres=OrderedDict() 245 saveres['fieldname']=fieldname 246 saveres['time']=time 247 saveres['step']=step 248 saveres['field']=field 229 249 230 250 except struct.error as e: 231 result=None232 233 return result251 saveres=None 252 253 return saveres 234 254 # }}} 235 255 def ReadDataDimensions(fid): # {{{ … … 262 282 raise TypeError("cannot read data of type %d" % type) 263 283 264 result=OrderedDict()265 result['fieldname']=fieldname266 result['time']=time267 result['step']=step268 result['M']=M269 result['N']=N284 saveres=OrderedDict() 285 saveres['fieldname']=fieldname 286 saveres['time']=time 287 saveres['step']=step 288 saveres['M']=M 289 saveres['N']=N 270 290 271 291 except struct.error as e: 272 result=None273 274 return result275 # }}} 292 saveres=None 293 294 return saveres 295 # }}} -
issm/trunk-jpl/src/py3/solve/solve.py
r19895 r23670 3 3 import shutil 4 4 from pairoptions import pairoptions 5 from EnumDefinitions import *6 from EnumToString import EnumToString7 5 from ismodelselfconsistent import ismodelselfconsistent 8 6 from marshall import marshall 9 7 from waitonlock import waitonlock 10 8 from loadresultsfromcluster import loadresultsfromcluster 11 import MatlabFuncs as m 9 from preqmu import * 10 #from MatlabFuncs import * 12 11 13 def solve(md,solution enum,**kwargs):12 def solve(md,solutionstring,*args): 14 13 """ 15 14 SOLVE - apply solution sequence for this model 16 15 17 16 Usage: 18 md=solve(md,solution enum,varargin)17 md=solve(md,solutionstring,varargin) 19 18 where varargin is a list of paired arguments of string OR enums 20 19 21 solution types available comprise: 22 - StressbalanceSolutionEnum 23 - MasstransportSolutionEnum 24 - ThermalSolutionEnum 25 - SteadystateSolutionEnum 26 - TransientSolutionEnum 27 - BalancethicknessSolutionEnum 28 - BedSlopeSolutionEnum 29 - SurfaceSlopeSolutionEnum 30 - HydrologySolutionEnum 31 - FlaimSolutionEnum 32 20 solution types available comprise: 21 - 'Stressbalance' or 'sb' 22 - 'Masstransport' or 'mt' 23 - 'Thermal' or 'th' 24 - 'Steadystate' or 'ss' 25 - 'Transient' or 'tr' 26 - 'Balancethickness' or 'mc' 27 - 'Balancevelocity' or 'bv' 28 - 'BedSlope' or 'bsl' 29 - 'SurfaceSlope' or 'ssl' 30 - 'Hydrology' or 'hy' 31 - 'DamageEvolution' or 'da' 32 - 'Gia' or 'gia' 33 - 'Esa' or 'esa' 34 - 'Sealevelrise' or 'slr' 35 - 'Love' or 'lv' 36 33 37 extra options: 34 38 - loadonly : does not solve. only load results 35 39 - checkconsistency : 'yes' or 'no' (default is 'yes'), ensures checks on consistency of model 36 40 - restart: 'directory name (relative to the execution directory) where the restart file is located. 37 41 38 42 Examples: 39 md=solve(md,StressbalanceSolutionEnum); 43 md=solve(md,'Stressbalance'); 44 md=solve(md,'sb'); 40 45 """ 41 46 42 47 #recover and process solve options 43 if EnumToString(solutionenum)[0][-8:] != 'Solution': 44 raise ValueError("solutionenum '%s' not supported!" % EnumToString(solutionenum)[0]) 45 options=pairoptions(solutionenum=solutionenum,**kwargs) 48 if solutionstring.lower() == 'sb' or solutionstring.lower() == 'stressbalance': 49 solutionstring = 'StressbalanceSolution'; 50 elif solutionstring.lower() == 'mt' or solutionstring.lower() == 'masstransport': 51 solutionstring = 'MasstransportSolution'; 52 elif solutionstring.lower() == 'th' or solutionstring.lower() == 'thermal': 53 solutionstring = 'ThermalSolution'; 54 elif solutionstring.lower() == 'st' or solutionstring.lower() == 'steadystate': 55 solutionstring = 'SteadystateSolution'; 56 elif solutionstring.lower() == 'tr' or solutionstring.lower() == 'transient': 57 solutionstring = 'TransientSolution'; 58 elif solutionstring.lower() == 'mc' or solutionstring.lower() == 'balancethickness': 59 solutionstring = 'BalancethicknessSolution'; 60 elif solutionstring.lower() == 'bv' or solutionstring.lower() == 'balancevelocity': 61 solutionstring = 'BalancevelocitySolution'; 62 elif solutionstring.lower() == 'bsl' or solutionstring.lower() == 'bedslope': 63 solutionstring = 'BedSlopeSolution'; 64 elif solutionstring.lower() == 'ssl' or solutionstring.lower() == 'surfaceslope': 65 solutionstring = 'SurfaceSlopeSolution'; 66 elif solutionstring.lower() == 'hy' or solutionstring.lower() == 'hydrology': 67 solutionstring = 'HydrologySolution'; 68 elif solutionstring.lower() == 'da' or solutionstring.lower() == 'damageevolution': 69 solutionstring = 'DamageEvolutionSolution'; 70 elif solutionstring.lower() == 'gia' or solutionstring.lower() == 'gia': 71 solutionstring = 'GiaSolution'; 72 elif solutionstring.lower() == 'lv' or solutionstring.lower() == 'love': 73 solutionstring = 'LoveSolution'; 74 elif solutionstring.lower() == 'esa': 75 solutionstring = 'EsaSolution'; 76 elif solutionstring.lower() == 'slr' or solutionstring.lower() == 'sealevelrise': 77 solutionstring = 'SealevelriseSolution'; 78 else: 79 raise ValueError("solutionstring '%s' not supported!" % solutionstring) 80 options=pairoptions('solutionstring',solutionstring,*args) 46 81 47 82 #recover some fields 48 md.private.solution=solutionenum 49 cluster=md.cluster 83 md.private.solution=solutionstring 84 cluster=md.cluster 85 if options.getfieldvalue('batch','no')=='yes': 86 batch=1 87 else: 88 batch=0; 50 89 51 90 #check model consistency 52 if m.strcmpi(options.getfieldvalue('checkconsistency','yes'),'yes'): 53 print("checking model consistency") 54 if solutionenum == FlaimSolutionEnum(): 55 md.private.isconsistent=True 56 md.mesh.checkconsistency(md,solutionenum) 57 md.flaim.checkconsistency(md,solutionenum) 58 if not md.private.isconsistent: 59 raise RuntimeError("Model not consistent, see messages above.") 60 else: 61 ismodelselfconsistent(md) 91 if options.getfieldvalue('checkconsistency','yes')=='yes': 92 if md.verbose.solution: 93 print("checking model consistency") 94 ismodelselfconsistent(md) 62 95 63 96 #First, build a runtime name that is unique … … 80 113 md=preqmu(md,options) 81 114 82 #flaim analysis83 if solutionenum == FlaimSolutionEnum():84 md=flaim_sol(md,options)85 [md.private.solution]=EnumToString(solutionenum)86 return md87 88 115 #Do we load results only? 89 116 if options.getfieldvalue('loadonly',False): … … 95 122 marshall(md) # bin file 96 123 md.toolkits.ToolkitsFile(md.miscellaneous.name+'.toolkits') # toolkits file 97 cluster.BuildQueueScript(md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof,md.qmu.isdakota ) # queue file124 cluster.BuildQueueScript(md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof,md.qmu.isdakota,md.transient.isoceancoupling) # queue file 98 125 99 126 #Stop here if batch mode 100 if m.strcmpi(options.getfieldvalue('batch','no'),'yes'):127 if options.getfieldvalue('batch','no')=='yes': 101 128 print('batch mode requested: not launching job interactively') 102 129 print('launch solution sequence on remote cluster by hand') … … 113 140 114 141 #Launch job 115 cluster.LaunchQueueJob(md.miscellaneous.name,md.private.runtimename,filelist,restart )142 cluster.LaunchQueueJob(md.miscellaneous.name,md.private.runtimename,filelist,restart,batch) 116 143 117 144 #wait on lock … … 122 149 print('The results must be loaded manually with md=loadresultsfromcluster(md).') 123 150 else: #load results 124 print('loading results from cluster') 151 if md.verbose.solution: 152 print('loading results from cluster') 125 153 md=loadresultsfromcluster(md) 126 154 127 155 #post processes qmu results if necessary 128 156 if md.qmu.isdakota: 129 if not strncmpi(options ['keep'],'y',1):157 if not strncmpi(options.getfieldvalue('keep','y'),'y',1): 130 158 shutil.rmtree('qmu'+str(os.getpid())) 131 159 -
issm/trunk-jpl/src/py3/solve/waitonlock.py
r19895 r23670 48 48 #loop till file .lock exist or time is up 49 49 while ispresent==0 and etime<timelimit: 50 ispresent=os.path.exist (filename)50 ispresent=os.path.exists(filename) 51 51 time.sleep(1) 52 52 etime+=1/60 -
issm/trunk-jpl/src/py3/solvers/asmoptions.py
r19895 r23670 8 8 9 9 #retrieve options provided in varargin 10 arguments=pairoptions.pairoptions(* *kwargs)10 arguments=pairoptions.pairoptions(*args) 11 11 12 options=[['toolkit','petsc'],['mat_type',' aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','lu'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-30]];12 options=[['toolkit','petsc'],['mat_type','mpiaij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','lu'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-30]]; 13 13 14 14 #now, go through our arguments, and write over default options. -
issm/trunk-jpl/src/py3/solvers/iluasmoptions.py
r19895 r23670 11 11 12 12 #retrieve options provided in varargin 13 options=pairoptions.pairoptions(* *kwargs)13 options=pairoptions.pairoptions(*args) 14 14 iluasm=OrderedDict() 15 15 -
issm/trunk-jpl/src/py3/solvers/issmgslsolver.py
r19895 r23670 1 from collections import OrderedDict 1 2 import pairoptions 2 3 3 def issmgslsolver(* *kwargs):4 def issmgslsolver(*args): 4 5 #ISSMSOLVE - return issm solver options 5 6 # … … 8 9 9 10 #retrieve options provided in varargin 10 arguments=pairoptions.pairoptions(* *kwargs)11 arguments=pairoptions.pairoptions(*args) 11 12 12 options=[['toolkit','issm'],['mat_type','dense'],['vec_type','seq'],['solver_type','gsl']]; 13 options=OrderedDict() 14 options['toolkit'] = 'issm' 15 options['mat_type'] = 'dense' 16 options['vec_type'] = 'seq' 17 options['solver_type'] = 'gsl' 13 18 14 19 #now, go through our arguments, and write over default options. -
issm/trunk-jpl/src/py3/solvers/issmmumpssolver.py
r19895 r23670 1 from collections import OrderedDict 1 2 import pairoptions 2 3 3 def issmmumpssolver(* *kwargs):4 def issmmumpssolver(*args): 4 5 #ISSMSOLVE - return issm solver options 5 6 # … … 8 9 9 10 #retrieve options provided in varargin 10 arguments=pairoptions.pairoptions(* *kwargs)11 arguments=pairoptions.pairoptions(*args) 11 12 12 options=[['toolkit','issm'],['mat_type','mpidense'],['vec_type','mpi'],['solver_type','mumps']]; 13 options=OrderedDict() 14 options['toolkit'] = 'issm' 15 options['mat_type'] = 'mpidense' 16 options['vec_type'] = 'mpi' 17 options['solver_type'] = 'mumps' 13 18 14 19 #now, go through our arguments, and write over default options. -
issm/trunk-jpl/src/py3/solvers/jacobiasmoptions.py
r19895 r23670 1 1 import pairoptions 2 2 3 def jacobiasmoptions(* *kwargs):3 def jacobiasmoptions(*args): 4 4 #ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options 5 5 # … … 8 8 9 9 #retrieve options provided in varargin 10 arguments=pairoptions.pairoptions(* *kwargs)10 arguments=pairoptions.pairoptions(*args) 11 11 12 options=[['toolkit','petsc'],['mat_type',' aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','jacobi'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-15]];12 options=[['toolkit','petsc'],['mat_type','mpiaij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','jacobi'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-15]]; 13 13 14 14 #now, go through our arguments, and write over default options. -
issm/trunk-jpl/src/py3/solvers/jacobicgoptions.py
r19895 r23670 8 8 9 9 #retrieve options provided in varargin 10 arguments=pairoptions.pairoptions(* *kwargs)10 arguments=pairoptions.pairoptions(*args) 11 11 12 options=[['toolkit','petsc'],['mat_type',' aij'],['ksp_type','cg'],['ksp_max_it',100],['ksp_rtol',1e-15]];12 options=[['toolkit','petsc'],['mat_type','mpiaij'],['ksp_type','cg'],['ksp_max_it',100],['ksp_rtol',1e-15]]; 13 13 14 14 #now, go through our arguments, and write over default options. -
issm/trunk-jpl/src/py3/solvers/matlaboptions.py
r19895 r23670 1 1 import pairoptions 2 2 3 def matlaboptions(* *kwargs):3 def matlaboptions(*args): 4 4 #MATLABOPTIONS - return Matlab petsc options 5 5 # … … 8 8 9 9 #retrieve options provided in varargin 10 arguments=pairoptions.pairoptions(* *kwargs)10 arguments=pairoptions.pairoptions(*args) 11 11 12 12 options=[['toolkit','petsc'],['ksp_type','matlab']]; -
issm/trunk-jpl/src/py3/solvers/mumpsoptions.py
r19895 r23670 3 3 from IssmConfig import IssmConfig 4 4 5 def mumpsoptions(* *kwargs):5 def mumpsoptions(*args): 6 6 """ 7 7 MUMPSOPTIONS - return MUMPS direct solver petsc options … … 12 12 13 13 #retrieve options provided in varargin 14 options=pairoptions.pairoptions(* *kwargs)14 options=pairoptions.pairoptions(*args) 15 15 mumps=OrderedDict() 16 16 17 17 #default mumps options 18 PETSC_VERSION=IssmConfig('_PETSC_MAJOR_')[0] 19 if PETSC_VERSION==2.: 18 PETSC_MAJOR=IssmConfig('_PETSC_MAJOR_')[0] 19 PETSC_MINOR=IssmConfig('_PETSC_MINOR_')[0] 20 if PETSC_MAJOR==2.: 20 21 mumps['toolkit']='petsc' 21 22 mumps['mat_type']=options.getfieldvalue('mat_type','aijmumps') … … 23 24 mumps['pc_type']=options.getfieldvalue('pc_type','lu') 24 25 mumps['mat_mumps_icntl_14']=options.getfieldvalue('mat_mumps_icntl_14',120) 25 mumps['pc_factor_shift_positive_definite']=options.getfieldvalue('pc_factor_shift_positive_definite','true') 26 if PETSC_VERSION==3.: 26 if PETSC_MAJOR==3.: 27 27 mumps['toolkit']='petsc' 28 28 mumps['mat_type']=options.getfieldvalue('mat_type','mpiaij') 29 29 mumps['ksp_type']=options.getfieldvalue('ksp_type','preonly') 30 30 mumps['pc_type']=options.getfieldvalue('pc_type','lu') 31 mumps['pc_factor_mat_solver_package']=options.getfieldvalue('pc_factor_mat_solver_package','mumps') 31 if PETSC_MINOR>8.: 32 mumps['pc_factor_mat_solver_type']=options.getfieldvalue('pc_factor_mat_solver_type','mumps') 33 else: 34 mumps['pc_factor_mat_solver_package']=options.getfieldvalue('pc_factor_mat_solver_package','mumps') 32 35 mumps['mat_mumps_icntl_14']=options.getfieldvalue('mat_mumps_icntl_14',120) 33 mumps['pc_factor_shift_positive_definite']=options.getfieldvalue('pc_factor_shift_positive_definite','true')34 36 35 37 return mumps 36 -
issm/trunk-jpl/src/py3/solvers/soroptions.py
r19895 r23670 1 1 import pairoptions 2 2 3 def soroptions(* *kwargs):3 def soroptions(*args): 4 4 #SOROPTIONS - return Relaxation Solver petsc options 5 5 # … … 8 8 9 9 #retrieve options provided in varargin 10 arguments=pairoptions.pairoptions(* *kwargs)10 arguments=pairoptions.pairoptions(*args) 11 11 12 options=[['toolkit','petsc'],['mat_type',' aij'],['ksp_type','cg'],['pc_type','sor'],['pc_sor_omega',1.1],['pc_sor_its',2]];12 options=[['toolkit','petsc'],['mat_type','mpiaij'],['ksp_type','cg'],['pc_type','sor'],['pc_sor_omega',1.1],['pc_sor_its',2]]; 13 13 14 14 #now, go through our arguments, and write over default options. -
issm/trunk-jpl/src/py3/solvers/stokesoptions.py
r19895 r23670 2 2 from IssmConfig import IssmConfig 3 3 4 def stokesoptions(* *kwargs):4 def stokesoptions(*args): 5 5 #STOKESOPTIONS - return STOKES multi-physics solver petsc options 6 6 # … … 9 9 10 10 #retrieve options provided in varargin 11 arguments=pairoptions.pairoptions(* *kwargs)11 arguments=pairoptions.pairoptions(*args) 12 12 13 13
Note:
See TracChangeset
for help on using the changeset viewer.