Changeset 25455
- Timestamp:
- 08/25/20 00:32:13 (5 years ago)
- Location:
- issm/trunk-jpl
- Files:
-
- 9 added
- 68 edited
Legend:
- Unmodified
- Added
- Removed
-
issm/trunk-jpl/src/m/classes/bamgmesh.py
r24213 r25455 3 3 4 4 class bamgmesh(object): 5 """ 6 BAMGMESH class definition 5 """BAMGMESH class definition 7 6 8 9 7 Usage: 8 bamgmesh(varargin) 10 9 """ 11 10 -
issm/trunk-jpl/src/m/classes/basin.m
r25065 r25455 117 117 %recover options 118 118 options=pairoptions(varargin{:}); 119 x=[]; y=[]; 119 x=[]; 120 y=[]; 120 121 121 122 %go through boundaries, recover edges and project them in the basin epsg reference frame: … … 127 128 y=[y;contour.y]; 128 129 end 130 129 131 %close the contour: 130 132 if x(end)~=x(1) | y(end)~=y(1), … … 181 183 error('Basin shapefilecrop error message: epsgshapefile or projshapefile should be specified'); 182 184 end 183 184 185 185 186 %create list of contours that have critical length > threshold (in lat,long): … … 209 210 for i=1:length(contours), 210 211 h=contours(i); 211 isin=inpolygon(h.x,h.y,ba.x,ba.y); 212 isin=inpolygon(h.x,h.y,ba.x,ba.y); 212 213 if ~isempty(find(isin==0)), 213 214 flags(i)=1; 214 215 end 215 216 end 216 pos=find(flags); contours(pos)=[]; 217 218 pos=find(flags); 219 contours(pos)=[]; 217 220 218 221 %Two options: -
issm/trunk-jpl/src/m/classes/basin.py
r25125 r25455 1 from collections import OrderedDict 1 2 import math 3 4 from bamg import bamg 5 import matplotlib.path as path 2 6 import numpy as np 3 7 4 8 from boundary import boundary 5 9 from epsg2proj import epsg2proj 10 from fielddisplay import fielddisplay 6 11 from gdaltransform import gdaltransform 7 12 from helpers import fileparts 13 from inpolygon import inpolygon 8 14 from laea import laea 9 15 from pairoptions import pairoptions … … 13 19 14 20 class basin(object): #{{{ 15 ''' 16 BASIN class definition 21 """BASIN class definition 17 22 18 23 Usage: 19 24 basin = basin() 20 '''25 """ 21 26 22 27 def __init__(self, *args): #{{{ … … 136 141 for i in range(len(self.boundaries)): 137 142 boundary = self.boundaries[i] 138 contour = boundary.edges() 139 contour.x, contour.y = gdaltransform(contour.x, contour.y, boundary.proj, self.proj) 140 x = [[x], [contour.x]] 141 y = [[y], [contour.y]] 143 contours = boundary.edges() # NOTE: Differs from MATLAB in that shpread returns a list 144 for j in range(len(contours)): 145 contours[j]['x'], contours[j]['y'] = gdaltransform(contours[j]['x'], contours[j]['y'], boundary.proj, self.proj) 146 if x == []: 147 x = np.array(contours[j]['x']) 148 y = np.array(contours[j]['y']) 149 else: 150 x = np.concatenate((x, contours[j]['x']), axis=0) 151 y = np.concatenate((y, contours[j]['y']), axis=0) 142 152 143 153 #close the contour 144 154 if x[-1] != x[0] or y[-1] != y[0]: 145 x .append(x[0])146 y .append(y[0])147 148 out = {}155 x = np.append(x, x[0]) 156 y = np.append(y, y[0]) 157 158 out = OrderedDict() 149 159 out['x'] = x 150 160 out['y'] = y … … 182 192 threshold = options.getfieldvalue('threshold', .65) #.65 degrees lat, long 183 193 inshapefile = options.getfieldvalue('shapefile') 184 out shapefile = options.getfieldvalue('outshapefile', '')194 outputshapefile = options.getfieldvalue('outputshapefile', '') 185 195 186 196 if options.exist('epsgshapefile') and options.exist('projshapefile'): … … 199 209 for i in range(len(contours)): 200 210 contour = contours[i] 201 carea = polyarea(contour .x, contour.y)211 carea = polyarea(contour['x'], contour['y']) 202 212 clength = math.sqrt(carea) 203 213 if clength < threshold: 204 llist = np.concatenate(llist, i) 205 setattr(contours, llist, []) 214 llist.append(i) 215 216 contours_above_threshold = [] 217 for i in range(len(contours)): 218 if i not in llist: 219 contours_above_threshold.append(contours[i]) 220 contours = contours_above_threshold 206 221 207 222 #project onto reference frame 208 223 for i in range(len(contours)): 209 224 h = contours[i] 210 h .x, h.y = gdaltransform(h.x, h.y, projshapefile, self.proj)211 contours[i] .x = h.x212 contours[i] .y = h.y225 h['x'], h['y'] = gdaltransform(h['x'], h['y'], projshapefile, self.proj) 226 contours[i]['x'] = h['x'] 227 contours[i]['y'] = h['y'] 213 228 214 229 #only keep the contours that are inside the basin (take centroids) … … 217 232 for i in range(len(contours)): 218 233 h = contours[i] 219 isin = inpolygon(h .x, h.y, ba.x, ba.y)220 if len(np.where(isin == 0 , isin, isin)):234 isin = inpolygon(h['x'], h['y'], ba['x'], ba['y']) 235 if len(np.where(isin == 0)[0]): 221 236 flags[i] = 1 222 pos = flags.nonzero() 223 contours[pos] = [] 237 238 pos = flags.nonzero()[0] 239 240 contours_in_basin = [] 241 for i in range(len(contours)): 242 if i not in pos: 243 contours_in_basin.append(contours[i]) 244 contours = contours_in_basin 224 245 225 246 #Two options 247 output = None 226 248 if outputshapefile == '': 227 249 output = contours 228 250 else: 229 251 shpwrite(contours, outputshapefile) 252 253 return output 230 254 #}}} 231 255 #}}} -
issm/trunk-jpl/src/m/classes/boundary.py
r25125 r25455 4 4 5 5 from epsg2proj import epsg2proj 6 from fielddisplay import fielddisplay 6 7 from helpers import * 7 8 from pairoptions import pairoptions … … 10 11 11 12 class boundary(object): #{{{ 12 ''' 13 BOUNDARY class definition 13 """BOUNDARY class definition 14 14 15 15 Usage: 16 16 boundary = boundary() 17 '''17 """ 18 18 19 19 def __init__(self, *args): #{{{ … … 32 32 self.shpfilename = options.getfieldvalue('shpfilename', '') 33 33 self.orientation = options.getfieldvalue('orientation', 'normal') 34 35 # If shppath is missing trailing slash, add it 36 if self.shppath[-1] != '/': 37 self.shppath += '/' 34 38 35 39 #figure out projection string: … … 77 81 #read domain 78 82 path, name, ext = fileparts(self.shpfilename) 79 if ext != ' shp':80 ext = ' shp'81 output = shpread('{} /{}.{}'.format(self.shppath, name, ext))83 if ext != '.shp': 84 ext = '.shp' 85 output = shpread('{}{}{}'.format(self.shppath, name, ext)) 82 86 83 87 #do we reverse? 84 88 if self.orientation == 'reverse': 85 89 for i in range(len(output)): 86 output[i].x = np.flipud(output[i].x) 87 output[i].y = np.flipud(output[i].y) 90 output[i]['x'] = np.flipud(output[i]['x']) 91 output[i]['y'] = np.flipud(output[i]['y']) 92 93 return output 88 94 #}}} 89 95 … … 107 113 #read domain 108 114 path, name, ext = fileparts(self.shpfilename) 109 if ext != ' shp':110 ext = ' shp'111 domain = shpread('{} /{}.{}'.format(self.shppath, name, ext))115 if ext != '.shp': 116 ext = '.shp' 117 domain = shpread('{}{}{}'.format(self.shppath, name, ext)) 112 118 113 119 #convert boundary to another reference frame #{{{ 114 120 for i in range(len(domain)): 115 121 try: 116 x, y = gdaltransform(domain[i] .x, domain[i].y, self.proj, proj)122 x, y = gdaltransform(domain[i]['x'], domain[i]['y'], self.proj, proj) 117 123 except error as e: 118 124 print(e) … … 170 176 #read domain 171 177 path, name, ext = fileparts(self.shpfilename) 172 if ext != ' shp':173 ext = ' shp'174 domain = shpread('{} /{}.{}'.format(self.shppath, name, ext))178 if ext != '.shp': 179 ext = '.shp' 180 domain = shpread('{}{}{}'.format(self.shppath, name, ext)) 175 181 176 182 #TODO: Finish translating from MATLAB after test2004.py runs without plot -
issm/trunk-jpl/src/m/classes/mesh3dsurface.py
r25158 r25455 9 9 10 10 class mesh3dsurface(object): 11 ''' 12 MESH3DSURFACE class definition 13 14 Usage: 15 mesh3dsurface = mesh3dsurface() 16 ''' 17 18 def __init__(self, *args): # {{{ 11 """MESH3DSURFACE class definition 12 13 Usage: 14 mesh3dsurface = mesh3dsurface() 15 """ 16 17 def __init__(self, *args): #{{{ 19 18 self.x = np.nan 20 19 self.y = np.nan … … 40 39 self.extractedelements = np.nan 41 40 42 if not len(args): 41 nargs = len(args) 42 if not nargs: 43 43 self.setdefaultparameters() 44 elif len(args)== 1:44 elif nargs == 1: 45 45 self = mesh3dsurface() 46 46 arg = args[1] … … 52 52 else: 53 53 raise RuntimeError('constructor not supported') 54 55 # }}} 56 57 def __repr__(self): # {{{ 58 string = ' 2D tria Mesh (horizontal):' 59 60 string += '\n Elements and vertices:' 61 string = "%s\n%s" % (string, fielddisplay(self, 'numberofelements', 'number of elements')) 62 string = "%s\n%s" % (string, fielddisplay(self, 'numberofvertices', 'number of vertices')) 63 string = "%s\n%s" % (string, fielddisplay(self, 'elements', 'vertex indices of the mesh elements')) 64 string = "%s\n%s" % (string, fielddisplay(self, 'x', 'vertices x coordinate [m]')) 65 string = "%s\n%s" % (string, fielddisplay(self, 'y', 'vertices y coordinate [m]')) 66 string = "%s\n%s" % (string, fielddisplay(self, 'z', 'vertices z coordinate [m]')) 67 string = "%s\n%s" % (string, fielddisplay(self, 'lat', 'vertices latitude [degrees]')) 68 string = "%s\n%s" % (string, fielddisplay(self, 'long', 'vertices longitude [degrees]')) 69 string = "%s\n%s" % (string, fielddisplay(self, 'r', 'vertices radius [m]')) 70 71 string = "%s\n%s" % (string, fielddisplay(self, 'edges', 'edges of the 2d mesh (vertex1 vertex2 element1 element2)')) 72 string = "%s\n%s" % (string, fielddisplay(self, 'numberofedges', 'number of edges of the 2d mesh')) 73 74 string += '\n Properties:' 75 string = "%s\n%s" % (string, fielddisplay(self, 'vertexonboundary', 'vertices on the boundary of the domain flag list')) 76 string = "%s\n%s" % (string, fielddisplay(self, 'segments', 'edges on domain boundary (vertex1 vertex2 element)')) 77 string = "%s\n%s" % (string, fielddisplay(self, 'segmentmarkers', 'number associated to each segment')) 78 string = "%s\n%s" % (string, fielddisplay(self, 'vertexconnectivity', 'list of elements connected to vertex_i')) 79 string = "%s\n%s" % (string, fielddisplay(self, 'elementconnectivity', 'list of elements adjacent to element_i')) 80 string = "%s\n%s" % (string, fielddisplay(self, 'average_vertex_connectivity', 'average number of vertices connected to one vertex')) 81 82 string += '\n Extracted model():' 83 string = "%s\n%s" % (string, fielddisplay(self, 'extractedvertices', 'vertices extracted from the model()')) 84 string = "%s\n%s" % (string, fielddisplay(self, 'extractedelements', 'elements extracted from the model()')) 85 86 return string 87 # }}} 88 89 def setdefaultparameters(self): # {{{ 54 #}}} 55 56 def __repr__(self): #{{{ 57 s = ' 2D tria Mesh (surface):' 58 59 s += '\n Elements and vertices:' 60 s = "%s\n%s" % (s, fielddisplay(self, 'numberofelements', 'number of elements')) 61 s = "%s\n%s" % (s, fielddisplay(self, 'numberofvertices', 'number of vertices')) 62 s = "%s\n%s" % (s, fielddisplay(self, 'elements', 'vertex indices of the mesh elements')) 63 s = "%s\n%s" % (s, fielddisplay(self, 'x', 'vertices x coordinate [m]')) 64 s = "%s\n%s" % (s, fielddisplay(self, 'y', 'vertices y coordinate [m]')) 65 s = "%s\n%s" % (s, fielddisplay(self, 'z', 'vertices z coordinate [m]')) 66 s = "%s\n%s" % (s, fielddisplay(self, 'lat', 'vertices latitude [degrees]')) 67 s = "%s\n%s" % (s, fielddisplay(self, 'long', 'vertices longitude [degrees]')) 68 s = "%s\n%s" % (s, fielddisplay(self, 'r', 'vertices radius [m]')) 69 70 s = "%s\n%s" % (s, fielddisplay(self, 'edges', 'edges of the 2d mesh (vertex1 vertex2 element1 element2)')) 71 s = "%s\n%s" % (s, fielddisplay(self, 'numberofedges', 'number of edges of the 2d mesh')) 72 73 s += '\n Properties:' 74 s = "%s\n%s" % (s, fielddisplay(self, 'vertexonboundary', 'vertices on the boundary of the domain flag list')) 75 s = "%s\n%s" % (s, fielddisplay(self, 'segments', 'edges on domain boundary (vertex1 vertex2 element)')) 76 s = "%s\n%s" % (s, fielddisplay(self, 'segmentmarkers', 'number associated to each segment')) 77 s = "%s\n%s" % (s, fielddisplay(self, 'vertexconnectivity', 'list of elements connected to vertex_i')) 78 s = "%s\n%s" % (s, fielddisplay(self, 'elementconnectivity', 'list of elements adjacent to element_i')) 79 s = "%s\n%s" % (s, fielddisplay(self, 'average_vertex_connectivity', 'average number of vertices connected to one vertex')) 80 81 s += '\n Extracted model():' 82 s = "%s\n%s" % (s, fielddisplay(self, 'extractedvertices', 'vertices extracted from the model()')) 83 s = "%s\n%s" % (s, fielddisplay(self, 'extractedelements', 'elements extracted from the model()')) 84 85 return s 86 #}}} 87 88 def setdefaultparameters(self): #{{{ 90 89 #The connectivity is the average number of nodes linked to a given node 91 90 #through an edge. This connectivity is used to initially allocate … … 94 93 #test/NightlyRun/runme.py. 95 94 self.average_vertex_connectivity = 25 96 # 97 98 def checkconsistency(self, md, solution, analyses): # 95 #}}} 96 97 def checkconsistency(self, md, solution, analyses): #{{{ 99 98 md = checkfield(md, 'fieldname', 'mesh.x', 'NaN', 1, 'Inf', 1, 'size', [md.mesh.numberofvertices]) 100 99 md = checkfield(md, 'fieldname', 'mesh.y', 'NaN', 1, 'Inf', 1, 'size', [md.mesh.numberofvertices]) … … 116 115 117 116 return md 118 # 119 120 def marshall(self, prefix, md, fid): # 117 #}}} 118 119 def marshall(self, prefix, md, fid): #{{{ 121 120 WriteData(fid, prefix, 'name', 'md.mesh.domain_type', 'data', 'Domain' + self.domaintype(), 'format', 'String') 122 121 WriteData(fid, prefix, 'name', 'md.mesh.domain_dimension', 'data', self.dimension(), 'format', 'Integer') … … 134 133 WriteData(fid, prefix, 'object', self, 'fieldname', 'average_vertex_connectivity', 'format', 'Integer') 135 134 WriteData(fid, prefix, 'object', self, 'fieldname', 'vertexonboundary', 'format', 'DoubleMat', 'mattype', 1) 136 # 137 138 def domaintype(self): # 135 #}}} 136 137 def domaintype(self): #{{{ 139 138 return '3Dsurface' 140 # 141 142 def dimension(self): # 139 #}}} 140 141 def dimension(self): #{{{ 143 142 return 2 144 # 145 146 def elementtype(self): # 143 #}}} 144 145 def elementtype(self): #{{{ 147 146 return 'Tria' 148 # 149 150 def processmesh(self, options): # 147 #}}} 148 149 def processmesh(self, options): #{{{ 151 150 isplanet = 1 152 151 is2d = 0 … … 156 155 y = self.y 157 156 z = self.z 158 return [x, y, z, elements, is2d, isplanet] 159 # }}} 160 161 def savemodeljs(self, fid, modelname): # {{{ 157 158 return x, y, z, elements, is2d, isplanet 159 #}}} 160 161 def savemodeljs(self, fid, modelname): #{{{ 162 162 fid.write(' #s.mesh = new mesh3dsurface()\n' % modelname) 163 163 writejs1Darray(fid, [modelname, '.mesh.x'], self.x) … … 180 180 writejs1Darray(fid, [modelname, '.mesh.extractedvertices'], self.extractedvertices) 181 181 writejs1Darray(fid, [modelname, '.mesh.extractedelements'], self.extractedelements) 182 # 183 184 def export(self, *args): # 182 #}}} 183 184 def export(self, *args): #{{{ 185 185 options = pairoptions(*args) 186 186 … … 269 269 #write style file: 270 270 applyqgisstyle(filename, 'mesh') 271 # 271 #}}} -
issm/trunk-jpl/src/m/classes/model.py
r25172 r25455 79 79 class model(object): 80 80 #properties 81 def __init__(self): #{{{ 82 ''' classtype = model.properties 83 for classe in dict.keys(classtype): 84 print classe 85 self.__dict__[classe] = classtype[str(classe)] 86 ''' 81 def __init__(self): #{{{ 87 82 self.mesh = mesh2d() 88 83 self.mask = mask() … … 232 227 233 228 def extract(self, area): # {{{ 229 """EXTRACT - extract a model according to an Argus contour or flag list 230 231 This routine extracts a submodel from a bigger model with respect to a given contour 232 md must be followed by the corresponding exp file or flags list 233 It can either be a domain file (argus type, .exp extension), or an array of element flags. 234 If user wants every element outside the domain to be 235 extract2d, add '~' to the name of the domain file (ex: '~HO.exp') 236 an empty string '' will be considered as an empty domain 237 a string 'all' will be considered as the entire domain 238 239 Usage: 240 md2 = extract(md, area) 241 242 Examples: 243 md2 = extract(md, 'Domain.exp') 244 245 See also: EXTRUDE, COLLAPSE 234 246 """ 235 extract - extract a model according to an Argus contour or flag list 236 237 This routine extracts a submodel from a bigger model with respect to a given contour 238 md must be followed by the corresponding exp file or flags list 239 It can either be a domain file (argus type, .exp extension), or an array of element flags. 240 If user wants every element outside the domain to be 241 extract2d, add '~' to the name of the domain file (ex: '~HO.exp') 242 an empty string '' will be considered as an empty domain 243 a string 'all' will be considered as the entire domain 244 245 Usage: 246 md2 = extract(md, area) 247 248 Examples: 249 md2 = extract(md, 'Domain.exp') 250 251 See also: EXTRUDE, COLLAPSE 252 """ 253 254 #copy model 247 248 #copy model 255 249 md1 = copy.deepcopy(self) 256 250 257 #get elements that are inside area251 #get elements that are inside area 258 252 flag_elem = FlagElements(md1, area) 259 253 if not np.any(flag_elem): 260 254 raise RuntimeError("extracted model is empty") 261 255 262 #kick out all elements with 3 dirichlets256 #kick out all elements with 3 dirichlets 263 257 spc_elem = np.nonzero(np.logical_not(flag_elem))[0] 264 258 spc_node = np.unique(md1.mesh.elements[spc_elem, :]) - 1 … … 268 262 flag_elem[pos] = 0 269 263 270 #extracted elements and nodes lists264 #extracted elements and nodes lists 271 265 pos_elem = np.nonzero(flag_elem)[0] 272 266 pos_node = np.unique(md1.mesh.elements[pos_elem, :]) - 1 273 267 274 #keep track of some fields268 #keep track of some fields 275 269 numberofvertices1 = md1.mesh.numberofvertices 276 270 numberofelements1 = md1.mesh.numberofelements … … 280 274 flag_node[pos_node] = 1 281 275 282 #Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)276 #Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements) 283 277 Pelem = np.zeros(numberofelements1, int) 284 278 Pelem[pos_elem] = np.arange(1, numberofelements2 + 1) … … 286 280 Pnode[pos_node] = np.arange(1, numberofvertices2 + 1) 287 281 288 #renumber the elements (some node won't exist anymore)282 #renumber the elements (some node won't exist anymore) 289 283 elements_1 = copy.deepcopy(md1.mesh.elements) 290 284 elements_2 = elements_1[pos_elem, :] … … 297 291 elements_2[:, 5] = Pnode[elements_2[:, 5] - 1] 298 292 299 #OK, now create the new model!300 301 #take every field from model293 #OK, now create the new model! 294 295 #take every field from model 302 296 md2 = copy.deepcopy(md1) 303 297 304 #automatically modify fields305 306 #loop over model fields298 #automatically modify fields 299 300 #loop over model fields 307 301 model_fields = vars(md1) 308 302 for fieldi in model_fields: … … 310 304 field = getattr(md1, fieldi) 311 305 fieldsize = np.shape(field) 312 if hasattr(field, '__dict__') and fieldi not in ['results']: 306 if hasattr(field, '__dict__') and fieldi not in ['results']: #recursive call 313 307 object_fields = vars(field) 314 308 for fieldj in object_fields: … … 416 410 #recreate segments 417 411 if md1.mesh.__class__.__name__ == 'mesh2d': 418 md2.mesh.vertexconnectivity = NodeConnectivity(md2.mesh.elements, md2.mesh.numberofvertices) [0]419 md2.mesh.elementconnectivity = ElementConnectivity(md2.mesh.elements, md2.mesh.vertexconnectivity) [0]412 md2.mesh.vertexconnectivity = NodeConnectivity(md2.mesh.elements, md2.mesh.numberofvertices) 413 md2.mesh.elementconnectivity = ElementConnectivity(md2.mesh.elements, md2.mesh.vertexconnectivity) 420 414 md2.mesh.segments = contourenvelope(md2) 421 415 md2.mesh.vertexonboundary = np.zeros(numberofvertices2, bool) … … 423 417 else: 424 418 #First do the connectivity for the contourenvelope in 2d 425 md2.mesh.vertexconnectivity = NodeConnectivity(md2.mesh.elements2d, md2.mesh.numberofvertices2d) [0]426 md2.mesh.elementconnectivity = ElementConnectivity(md2.mesh.elements2d, md2.mesh.vertexconnectivity) [0]419 md2.mesh.vertexconnectivity = NodeConnectivity(md2.mesh.elements2d, md2.mesh.numberofvertices2d) 420 md2.mesh.elementconnectivity = ElementConnectivity(md2.mesh.elements2d, md2.mesh.vertexconnectivity) 427 421 segments = contourenvelope(md2) 428 422 md2.mesh.vertexonboundary = np.zeros(int(numberofvertices2 / md2.mesh.numberoflayers), bool) … … 430 424 md2.mesh.vertexonboundary = np.tile(md2.mesh.vertexonboundary, md2.mesh.numberoflayers) 431 425 #Then do it for 3d as usual 432 md2.mesh.vertexconnectivity = NodeConnectivity(md2.mesh.elements, md2.mesh.numberofvertices) [0]433 md2.mesh.elementconnectivity = ElementConnectivity(md2.mesh.elements, md2.mesh.vertexconnectivity) [0]426 md2.mesh.vertexconnectivity = NodeConnectivity(md2.mesh.elements, md2.mesh.numberofvertices) 427 md2.mesh.elementconnectivity = ElementConnectivity(md2.mesh.elements, md2.mesh.vertexconnectivity) 434 428 435 429 #Boundary conditions: Dirichlets on new boundary … … 504 498 setattr(fieldr, solutionsubfield, subfield) 505 499 506 #Keep track of pos_node and pos_elem500 #Keep track of pos_node and pos_elem 507 501 md2.mesh.extractedvertices = pos_node + 1 508 502 md2.mesh.extractedelements = pos_elem + 1 … … 512 506 513 507 def extrude(md, *args): # {{{ 514 """ 515 EXTRUDE - vertically extrude a 2d mesh 516 517 vertically extrude a 2d mesh and create corresponding 3d mesh. 518 The vertical distribution can: 508 """EXTRUDE - vertically extrude a 2d mesh 509 510 vertically extrude a 2d mesh and create corresponding 3d mesh. 511 The vertical distribution can: 519 512 - follow a polynomial law 520 513 - follow two polynomial laws, one for the lower part and one for the upper part of the mesh … … 522 515 523 516 524 525 526 527 528 529 530 531 532 533 534 517 Usage: 518 md = extrude(md, numlayers, extrusionexponent) 519 md = extrude(md, numlayers, lowerexponent, upperexponent) 520 md = extrude(md, listofcoefficients) 521 522 Example: 523 md = extrude(md, 15, 1.3) 524 md = extrude(md, 15, 1.3, 1.2) 525 md = extrude(md, [0 0.2 0.5 0.7 0.9 0.95 1]) 526 527 See also: MODELEXTRACT, COLLAPSE 535 528 """ 529 536 530 #some checks on list of arguments 537 531 if len(args) > 3 or len(args) < 1: … … 698 692 # }}} 699 693 700 def collapse(md): #{{{ 701 ''' 702 collapses a 3d mesh into a 2d mesh 694 def collapse(md): #{{{ 695 """COLLAPSE - collapses a 3d mesh into a 2d mesh 703 696 704 697 This routine collapses a 3d model into a 2d model and collapses all … … 706 699 707 700 Usage: 708 709 '''701 md = collapse(md) 702 """ 710 703 711 704 #Check that the model is really a 3d model … … 881 874 md.mesh.scale_factor = project2d(md, md.mesh.scale_factor, 1) 882 875 md.mesh = mesh 883 md.mesh.vertexconnectivity = NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices) [0]884 md.mesh.elementconnectivity = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity) [0]876 md.mesh.vertexconnectivity = NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices) 877 md.mesh.elementconnectivity = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity) 885 878 md.mesh.segments = contourenvelope(md) 886 879 887 880 return md 888 889 881 #}}} -
issm/trunk-jpl/src/m/classes/pairoptions.py
r25125 r25455 1 1 from collections import OrderedDict 2 2 3 3 4 class pairoptions(object): 4 """ 5 PAIROPTIONS class definition 5 """PAIROPTIONS class definition 6 6 7 8 9 7 Usage: 8 pairoptions = pairoptions() 9 pairoptions = pairoptions('module', true, 'solver', false) 10 10 """ 11 11 … … 39 39 40 40 def buildlist(self, *arg): # {{{ 41 """BUILDLIST - build list of objects from input""" 41 """BUILDLIST - build list of objects from input 42 """ 42 43 43 44 #check length of input -
issm/trunk-jpl/src/m/classes/sealevelmodel.m
r25136 r25455 21 21 mergedcaps = 0; 22 22 transitions = {}; 23 eltransitions 23 eltransitions = {}; 24 24 planet = ''; 25 25 %}}} … … 170 170 function intersections(self,varargin) % {{{ 171 171 172 options=pairoptions(varargin{:}); 173 force=getfieldvalue(options,'force',0); 172 options=pairoptions(varargin{:}); 173 force=getfieldvalue(options,'force',0); 174 175 %initialize, to avoid issues of having more transitions than meshes. 176 self.transitions={}; self.eltransitions={}; 177 178 %for elements: 179 xe=self.earth.mesh.x(self.earth.mesh.elements)*[1;1;1]/3; 180 ye=self.earth.mesh.y(self.earth.mesh.elements)*[1;1;1]/3; 181 ze=self.earth.mesh.z(self.earth.mesh.elements)*[1;1;1]/3; 182 183 for i=1:length(self.icecaps), 184 mdi=self.icecaps{i}; 185 mdi=TwoDToThreeD(mdi,self.planet); 174 186 175 %initialize, to avoid issues of having more transitions than meshes. 176 self.transitions={}; self.eltransitions={}; 177 178 %for elements: 179 xe=self.earth.mesh.x(self.earth.mesh.elements)*[1;1;1]/3; 180 ye=self.earth.mesh.y(self.earth.mesh.elements)*[1;1;1]/3; 181 ze=self.earth.mesh.z(self.earth.mesh.elements)*[1;1;1]/3; 182 183 for i=1:length(self.icecaps), 184 mdi=self.icecaps{i}; 185 mdi=TwoDToThreeD(mdi,self.planet); 186 187 %for elements: 188 xei=mdi.mesh.x(mdi.mesh.elements)*[1;1;1]/3; 189 yei=mdi.mesh.y(mdi.mesh.elements)*[1;1;1]/3; 190 zei=mdi.mesh.z(mdi.mesh.elements)*[1;1;1]/3; 191 192 disp(sprintf('Computing vertex intersections for basin %s',self.basins{i}.name)); 187 %for elements: 188 xei=mdi.mesh.x(mdi.mesh.elements)*[1;1;1]/3; 189 yei=mdi.mesh.y(mdi.mesh.elements)*[1;1;1]/3; 190 zei=mdi.mesh.z(mdi.mesh.elements)*[1;1;1]/3; 193 191 194 self.transitions{end+1}=meshintersect3d(self.earth.mesh.x,self.earth.mesh.y,self.earth.mesh.z,mdi.mesh.x,mdi.mesh.y,mdi.mesh.z,'force',force); 195 196 self.eltransitions{end+1}=meshintersect3d(xe,ye,ze,xei,yei,zei,'force',force); 197 end 192 disp(sprintf('Computing vertex intersections for basin %s',self.basins{i}.name)); 193 194 self.transitions{end+1}=meshintersect3d(self.earth.mesh.x,self.earth.mesh.y,self.earth.mesh.z,mdi.mesh.x,mdi.mesh.y,mdi.mesh.z,'force',force); 195 196 self.eltransitions{end+1}=meshintersect3d(xe,ye,ze,xei,yei,zei,'force',force); 197 end 198 198 199 199 end % }}} 200 200 function checkintersections(self) % {{{ 201 flags=zeros(self.earth.mesh.numberofvertices,1);202 for i=1:length(self.basins),203 flags(self.transitions{i})=i;204 end205 plotmodel(self.earth,'data',flags,'coastline','on');201 flags=zeros(self.earth.mesh.numberofvertices,1); 202 for i=1:length(self.basins), 203 flags(self.transitions{i})=i; 204 end 205 plotmodel(self.earth,'data',flags,'coastline','on'); 206 206 207 207 end % }}} … … 227 227 end 228 228 continent=unique(continent); 229 else 230 %nothing to do: assume we have a list of continents 229 231 end 230 232 else 231 %nothing to do ,we have a list of continents233 %nothing to do: assume we have a list of continents 232 234 end 233 235 else … … 416 418 eval(['self.earth.' string '=field;']); %do not forget to plug the field variable into its final location 417 419 %}}} 418 elseif n==self.icecaps{1} 420 elseif n==self.icecaps{1}.mesh.numberofelements, 419 421 eval(['self.earth.' string '=zeros(self.earth.mesh.numberofelements,1);']); 420 422 for i=1:length(self.icecaps), -
issm/trunk-jpl/src/m/classes/sealevelmodel.py
r25158 r25455 7 7 from meshintersect3d import meshintersect3d 8 8 from miscellaneous import miscellaneous 9 from model import model 10 from modelmerge3d import modelmerge3d 9 11 from pairoptions import pairoptions 10 12 from private import private … … 13 15 14 16 class sealevelmodel(object): 15 ''' 16 SEALEVELMODEL class definition 17 """SEALEVELMODEL class definition 17 18 18 19 Usage: … … 27 28 'earth', md_earth 28 29 ) 29 '''30 """ 30 31 31 32 def __init__(self, *args): #{{{ … … 207 208 bas = options.getfieldvalue('basin', 'all') 208 209 209 # expand continent list #{{{210 # Expand continent list #{{{ 210 211 if type(continent) == np.ndarray: 211 212 if continent.shape[1] == 1: 212 213 if continent[0] == 'all': 213 # need to transform this into a list of continents214 # Need to transform this into a list of continents 214 215 continent = [] 215 216 for i in range(len(self.basins)): 216 217 continent.append(self.basins[i].continent) 217 218 continent = np.unique(continent) 219 else: 220 pass # Nothing to do: assume we have a list of continents 218 221 else: 219 pass # nothing to do,we have a list of continents222 pass # Nothing to do: assume we have a list of continents 220 223 else: 221 224 if continent == 'all': 222 # need to transform this into a list of continents225 # Need to transform this into a list of continents 223 226 continent = [] 224 227 for i in range(len(self.basins)): … … 226 229 continent = np.unique(continent) 227 230 else: 228 continent = [continent]231 pass # Nothing to do: assume we have a list of continents 229 232 #}}} 230 #expand basins list using the continent list above and the extra bas discriminator #{{{ 233 234 # Expand basins list using the continent list above and the extra bas discriminator #{{{ 231 235 if type(bas) == np.ndarray: 232 236 if bas.shape[1] == 1: 233 237 if bas[0] == 'all': 234 # need to transform this into a list of basins238 # Need to transform this into a list of basins 235 239 baslist = [] 236 240 for i in range(len(self.basins)): … … 246 250 baslist.append(i) 247 251 else: 248 # we have a list of basin names252 # We have a list of basin names 249 253 baslist = [] 250 254 for i in range(len(bas)): … … 273 277 #}}} 274 278 #}}} 279 280 def addicecap(self, md): #{{{ 281 if not type(md) == model: 282 raise Exception("addicecap method only takes a 'model' class object as input") 283 284 self.icecaps.append(md) 285 #}}} 286 287 def basinsplot3d(self, *args): #{{{ 288 for i in range(len(self.basins)): 289 self.basins[i].plot3d(*args) 290 #}}} 291 292 def caticecaps(self, *args): #{{{ 293 # Recover options 294 options = pairoptions(*args) 295 tolerance = options.getfieldvalue('tolerance', .65) 296 loneedgesdetect = options.getfieldvalue('loneedgesdetect', 0) 297 298 # Make 3D model 299 models = self.icecaps 300 for i in range(len(models)): 301 models[i] = TwoDToThreeD(models[i], self.planet) 302 303 # Plug all models together 304 md = models[0] 305 for i in range(1, len(models)): 306 md = modelmerge3d(md, models[i], 'tolerance', tolerance) 307 md.private.bamg.landmask = np.vstack((md.private.bamg.landmask, models[i].private.bamg.landmask)) 308 309 # Look for lone edges if asked for it 310 if loneedgesdetect: 311 edges = loneedges(md) 312 plotmodel(md, 'data', md.mask.land_levelset) 313 for i in range(len(edges)): 314 ind1 = edges(i, 1) 315 ind1 = edges(i, 2) 316 plot3([md.mesh.x[ind1], md.mesh.x[ind2]], [md.mesh.y[ind1], md.mesh.y[ind2]], [md.mesh.z[ind1], md.mesh.z[ind2]], 'g*-') 317 318 # Plug into earth 319 self.earth = md 320 321 # Create mesh radius 322 self.earth.mesh.r = planetradius('earth') 323 #}}} 324 325 def viscousiterations(self): #{{{ 326 for i in range(len(self.icecaps)): 327 ic = self.icecaps[i] 328 mvi = ic.resutls.TransientSolution[0].StressbalanceConvergenceNumSteps 329 for j in range(1, len(ic.results.TransientSolution) - 1): 330 mvi = np.max(mvi, ic.results.TransientSolution[j].StressbalanceConvergenceNumSteps) 331 print("{}, {}: {}".format(i, self.icecaps[i].miscellaneous.name, mvi)) 332 #}}} 333 334 def maxtimestep(self): #{{{ 335 for i in range(len(self.icecaps)): 336 ic = self.icecaps[i] 337 mvi = len(ic.results.TransientSolution) 338 timei = ic.results.TransientSolution[-1].time 339 print("{}, {}: {}/{}".format(i, self.icecaps[i].miscellaneous.name, mvi, timei)) 340 341 mvi = len(self.earth.results.TransientSolution) 342 timei = self.earth.results.TransientSolution[-1].time 343 print("Earth: {}/{}", mvi, timei) 344 #}}} 345 346 def transfer(self, string): #{{{ 347 # Recover field size in one icecap 348 n = np.size(getattr(self.icecaps[i], string), 0) 349 350 if n == self.icecaps[0].mesh.numberofvertices: 351 setattr(self.earth, string, np.zeros((self.earth.mesh.numberofvertices, ))) 352 for i in range(len(self.icecaps)): 353 getattr(self.earth, string)[self.transitions[i]] = getattr(self.icecaps[i], string) 354 elif n == (self.self.icecaps[0].mesh.numberofvertices + 1): 355 # Dealing with transient dataset 356 # Check that all timetags are similar between all icecaps #{{{ 357 for i in range(len(self.icecaps)): 358 capfieldi = getattr(self.icecaps[i], string) 359 for j in range(1, len(self.icecaps)): 360 capfieldj = getattr(self.icecaps[j], string) 361 if capfieldi[-1, :] != capfieldj[-1, :]: 362 raise Exception("Time stamps for {} field is different between icecaps {} and {}".format(string, i, j)) 363 capfield1 = getattr(self.icecaps[0], string) 364 times = capfield1[-1, :] 365 nsteps = len(times) 366 #}}} 367 # Initialize #{{{ 368 field = np.zeros((self.earth.mesh.numberofvertices + 1, nsteps)) 369 field[-1, :] = times # Transfer the times only, not the values 370 #}}} 371 # Transfer all the time fields #{{{ 372 for i in range(len(self.icecaps)): 373 capfieldi = getattr(self.icecaps[i], string) 374 for j in range(nsteps): 375 field[self.transitions[i], j] = capfieldi[0:-2, j] # Transfer only the values, not the time 376 setattr(self.earth, string, field) # Do not forget to plug the field variable into its final location 377 #}}} 378 elif n == (self.icecaps[0].mesh.numberofelements): 379 setattr(self.earth, string, np.zeros((self.earth.mesh.numberofvertices, ))) 380 for i in range(len(self.icecaps)): 381 getattr(self.earth, string)[self.eltransitions[i]] = getattr(self.icecaps[i], string) 382 else: 383 raise Exception('not supported yet') 384 #}}} 385 386 def homogenize(self, noearth=0): #{{{ 387 mintimestep = np.inf 388 389 for i in range(len(self.icecaps)): 390 ic = self.icecaps[i] 391 mintimestep = np.min(mintimestep, len (ic.results.TransientSolution)) 392 393 if not noearth: 394 mintimestep = np.min(mintimestep, len(self.earth.results.TransientSolution)) 395 396 for i in range(len(self.icecaps)): 397 ic = self.icecaps[i] 398 ic.resuts.TransientSolution = ic.results.TransientSolution[:mintimestep] 399 self.icecaps[i] = ic 400 401 ic = self.earth 402 403 if not noearth: 404 ic.results.TransientSolution = ic.resutls.TransientSolution[:mintimestep] 405 406 self.earth = ic 407 408 return self 409 #}}} 410 411 def initializemodels(self): #{{{ 412 for i in range(len(self.basins)): 413 md = model() 414 md.miscellaneous.name = self.basins[i].name 415 self.addicecap(md) 416 #}}} -
issm/trunk-jpl/src/m/coordsystems/epsg2proj.m
r25189 r25455 1 1 function string = epsg2proj(epsg) 2 % FUNCTIONEPSG2PROJ - uses gdalsrsinfo to provide PROJ.4 compatible string from2 %EPSG2PROJ - uses gdalsrsinfo to provide PROJ.4 compatible string from 3 3 %EPSG code 4 4 % -
issm/trunk-jpl/src/m/coordsystems/epsg2proj.py
r25346 r25455 1 import shlex2 1 import subprocess 3 2 4 3 5 4 def epsg2proj(epsg): #{{{ 6 """ 7 FUNCTION EPSG2PROJ - uses gdalsrsinfo to provide PROJ.4 compatible string 5 """EPSG2PROJ - uses gdalsrsinfo to provide PROJ.4 compatible string 8 6 from EPSG code 9 7 … … 22 20 23 21 #First, get GDAL version 24 subproc_args = shlex.split("gdalsrsinfo --version | awk '{print $2}' | cut -d '.' -f1")22 subproc_args = "gdalsrsinfo --version | awk '{print $2}' | cut -d '.' -f1" 25 23 subproc = subprocess.Popen(subproc_args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 26 24 outs, errs = subproc.communicate() … … 30 28 version_major=int(outs) 31 29 32 subproc_args = shlex.split("gdalsrsinfo epsg:{} | command grep PROJ.4 | tr -d '\n' | sed 's/PROJ.4 : //'".format(epsg))30 subproc_args = "gdalsrsinfo epsg:{} | command grep PROJ.4 | tr -d '\n' | sed 's/PROJ.4 : //'".format(epsg) 33 31 subproc = subprocess.Popen(subproc_args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 34 32 outs, errs = subproc.communicate() -
issm/trunk-jpl/src/m/coordsystems/gdaltransform.m
r25065 r25455 21 21 % 22 22 % To get proj.4 string from EPSG, use gdalsrsinfo. Example: 23 %24 23 % gdalsrsinfo epsg:4326 | grep "PROJ.4" | sed "s/PROJ.4 : //" 25 24 … … 32 31 fclose(fid); 33 32 34 [s,r]=system(['gdaltransform -s_srs "',proj_in,'" -t_srs "',proj_out,'" 33 [s,r]=system(['gdaltransform -s_srs "',proj_in,'" -t_srs "',proj_out,'" < ' filename_in ' > ' filename_out]); 35 34 if s~=0 | ~isempty(deblank(r)), 36 35 error(r); 37 36 end 37 38 38 A=load(filename_out); 39 xout=A(:,1); xout=reshape(xout,size(x));40 yout=A(:,2); yout=reshape(yout,size(y));41 39 42 40 %clean up 43 41 delete(filename_in); 44 42 delete(filename_out); 43 44 xout=A(:,1); 45 xout=reshape(xout,size(x)); 46 yout=A(:,2); 47 yout=reshape(yout,size(y)); -
issm/trunk-jpl/src/m/coordsystems/gdaltransform.py
r25163 r25455 4 4 import tempfile 5 5 6 import numpy as np 7 6 8 from loadvars import * 7 9 8 10 9 11 def gdaltransform(x, y, proj_in, proj_out): #{{{ 10 ''' 11 GDALTRANSFORM - switch from one projection system to another 12 """GDALTRANSFORM - switch from one projection system to another 12 13 13 14 Usage: … … 29 30 +proj = stere +lat_0=90 +lat_ts=71 +lon_0=-39 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.448564109 +units=m +no_defs 30 31 31 To get proj.4 string form EPSG, use gdalsrsinfo. Example: 32 32 To get proj.4 string from EPSG, use gdalsrsinfo. Example: 33 33 gdalsrsinfo epsg:4326 | grep "PROJ.4" | sed "s/PROJ.4 : //" 34 35 TODO: 36 - Follow subprocess pattern implemented in src/m/coordsystems/epsg2proj.py 37 ''' 34 """ 38 35 39 36 # Give ourselves unique file names 40 file_in = tempfile.NamedTemporaryFile(' r+b')37 file_in = tempfile.NamedTemporaryFile('w', delete=False) 41 38 filename_in = file_in.name 42 file_out = tempfile.NamedTemporaryFile('w +b')39 file_out = tempfile.NamedTemporaryFile('w', delete=False) 43 40 filename_out = file_out.name 44 41 45 file_in.write(b'%8g %8g\n' % (x.flatten(1), y.flatten(1))) 42 points = np.vstack((x, y)).T 43 np.savetxt(file_in, points, fmt='%8g %8g') 44 file_in.close() # NOTE: Opening file in 'r+' or 'w+' mode does not allow subsequent reading by subprocess. We therefore need to close it and reopen it. 45 file_in = open(filename_in) # Open for reading by subprocess 46 47 subproc_args = shlex.split("gdaltransform -s_srs '{}' -t_srs '{}'".format(proj_in, proj_out)) 48 subproc = subprocess.Popen(subproc_args, bufsize=-1, stdin=file_in, stdout=file_out, stderr=subprocess.PIPE, close_fds=True) 49 outs, errs = subproc.communicate() 50 if errs != '': 51 raise RuntimeError("gdaltransform: call to gdaltransform failed: {}".format(errs)) 52 53 A = np.loadtxt(filename_out) 54 55 # Clean up 46 56 file_in.close() 57 file_out.close() 58 remove(filename_in) 59 remove(filename_out) 47 60 48 subproc_args = shlex.split('gdaltransform -s_srs {} -t_srs {} < {} > {}'.format(proj_in, proj_out, filename_in, filename_out)) 49 subprocess.check_call(subproc_args) # Will raise CalledProcessError if return code is not 0 50 51 A = loadvars(filename_out) 52 xout = A[0] 53 xout = xout.reshape(x.shape) 54 yout = A[1] 55 yout = yout.reshape(y.shape) 56 57 os.remove(filename_in) 58 os.remove(filename_out) 61 if np.ndim(A) > 1: 62 xout = np.array(A[:,0]) 63 yout = np.array(A[:,1]) 64 # if type(x) == "np.ndarray": 65 # xout = xout.reshape(x.shape) # TODO: Do we need to do this? 66 # yout = yout.reshape(y.shape) # TODO: Do we need to do this? 67 else: 68 xout = [A[0]] 69 yout = [A[1]] 59 70 60 71 return [xout, yout] -
issm/trunk-jpl/src/m/coordsystems/laea.m
r24777 r25455 9 9 % return string='+proj=laea +lat_0=45 +lon_0=-90 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs' 10 10 11 string=sprintf('+proj=laea +lat_0=%i +lon_0=%i +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs 11 string=sprintf('+proj=laea +lat_0=%i +lon_0=%i +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs',lat,long); -
issm/trunk-jpl/src/m/exp/expread.py
r24254 r25455 1 from collections import OrderedDict 1 2 import os.path 3 2 4 import numpy as np 3 from collections import OrderedDict 5 4 6 import MatlabFuncs as m 5 7 6 8 7 9 def expread(filename): 10 """EXPREAD - read a exp file and build a list of OrderedDicts 11 12 This routine reads a file .exp and builds a list of OrderedDicts containing 13 the fields x and y corresponding to the coordinates, one for the filename 14 of the exp file, for the density, for the nodes, and a field closed to 15 indicate if the domain is closed. The first argument is the .exp file to be 16 read and the second one (optional) indicate if the last point shall be read 17 (1 to read it, 0 not to). 18 19 Usage: 20 contours = expread(filename) 21 22 Example: 23 contours = expread('domainoutline.exp') 24 contours = expread('domainoutline.exp') 25 26 See Also: 27 - EXPDOC 28 - EXPWRITEASVERTICES 29 30 TODO: 31 - Convert returned data structure from list of OrderedDict objects to list 32 of OrderedStruct objects (see also src/m/shp/shpread.py). Also, modify 33 handling of returned data structure in, 34 - src/m/exp/expcoarsen.py 35 - src/m/exp/expdisp.py 36 - src/m/interp/SectionValues.py 37 - src/m/mesh/bamg.py 38 May also need to modify addressing in corresponding FetchData function, or 39 create new one, in src/wrappers/ContoursToNodes/ContoursToNodes.cpp. 8 40 """ 9 41 10 EXPREAD - read a file exp and build a Structure11 12 This routine reads a file .exp and builds a list of dicts containing the13 fields x and y corresponding to the coordinates, one for the filename of14 the exp file, for the density, for the nodes, and a field closed to15 indicate if the domain is closed.16 The first argument is the .exp file to be read and the second one (optional)17 indicate if the last point shall be read (1 to read it, 0 not to).18 19 Usage:20 contours = expread(filename)21 22 Example:23 contours = expread('domainoutline.exp')24 contours = expread('domainoutline.exp')25 26 See also EXPDOC, EXPWRITEASVERTICES27 28 """29 42 #some checks 30 43 if not os.path.exists(filename): -
issm/trunk-jpl/src/m/geometry/find_point.m
r21067 r25455 2 2 %FIND_POINT - find closest point 3 3 % 4 % find which point of the list (tabx,taby) is 5 % the closest to (poinx,pointy) 4 % find which point of the list (tabx,taby) is the closest to (pointx,pointy) 6 5 % 7 6 % Usage: -
issm/trunk-jpl/src/m/geometry/polyarea.py
r25125 r25455 5 5 6 6 def polyarea(x, y): #{{{ 7 '''7 """ 8 8 POLYAREA - returns the area of the 2-D polygon defined by the vertices in 9 9 lists x and y … … 24 24 - Test that output falls within some tolerance of MATLAB's polyarea 25 25 function. 26 ''' 26 """ 27 27 28 return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) 28 29 #}}} -
issm/trunk-jpl/src/m/interp/SectionValues.py
r24256 r25455 1 1 import os 2 3 import numpy as np 4 2 5 from expread import expread 3 import numpy as np4 from project2d import project2d5 6 #from InterpFromMesh2d import InterpFromMesh2d 6 7 from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d 7 8 from InterpFromMeshToMesh3d import InterpFromMeshToMesh3d 9 from project2d import project2d 8 10 9 11 10 12 def SectionValues(md, data, infile, resolution): 11 ''' 12 compute the value of a field on a section 13 """SECTIONVALUES - compute the value of a field on a section 13 14 14 15 This routine gets the value of a given field of the model on points … … 17 18 18 19 Usage: 19 [elements, x, y, z, s, data] = SectionValues(md, data, filename, resolution)20 [elements, x, y, z, s, data] = SectionValues(md, data, profile_structure, resolution)21 '''20 [elements, x, y, z, s, data] = SectionValues(md, data, filename, resolution) 21 [elements, x, y, z, s, data] = SectionValues(md, data, profile_structure, resolution) 22 """ 22 23 23 24 if os.path.isfile(infile): … … 84 85 85 86 #Interpolation of data on specified points 86 #data_interp = InterpFromMesh2d(md.mesh.elements, md.mesh.x, md.mesh.y, data, X, Y) [0]87 data_interp = InterpFromMeshToMesh2d(md.mesh.elements, md.mesh.x, md.mesh.y, data, X, Y) [0]87 #data_interp = InterpFromMesh2d(md.mesh.elements, md.mesh.x, md.mesh.y, data, X, Y) 88 data_interp = InterpFromMeshToMesh2d(md.mesh.elements, md.mesh.x, md.mesh.y, data, X, Y) 88 89 #data_interp = griddata(md.mesh.x, md.mesh.y, data, X, Y) 89 90 … … 95 96 #Get base and surface for each 2d point, offset to make sure that it is inside the glacier system 96 97 offset = 1.e-3 97 base = InterpFromMeshToMesh2d(md.mesh.elements2d, md.mesh.x2d, md.mesh.y2d, project2d(md, md.geometry.base, 1), X, Y) [0]+ offset98 base = InterpFromMeshToMesh2d(md.mesh.elements2d, md.mesh.x2d, md.mesh.y2d, project2d(md, md.geometry.base, 1), X, Y) + offset 98 99 base = base.reshape(-1, ) 99 surface = InterpFromMeshToMesh2d(md.mesh.elements2d, md.mesh.x2d, md.mesh.y2d, project2d(md, md.geometry.surface, 1), X, Y) [0]- offset100 surface = InterpFromMeshToMesh2d(md.mesh.elements2d, md.mesh.x2d, md.mesh.y2d, project2d(md, md.geometry.surface, 1), X, Y) - offset 100 101 surface = surface.reshape(-1, ) 101 102 … … 126 127 127 128 #Interpolation of data on specified points 128 data_interp = InterpFromMeshToMesh3d(md.mesh.elements, md.mesh.x, md.mesh.y, md.mesh.z, data, X3, Y3, Z3, np.nan) [0]129 data_interp = InterpFromMeshToMesh3d(md.mesh.elements, md.mesh.x, md.mesh.y, md.mesh.z, data, X3, Y3, Z3, np.nan) 129 130 130 131 #build outputs -
issm/trunk-jpl/src/m/io/loadmodel.m
r13007 r25455 1 1 function varargout=loadmodel(path) 2 %LOADMODEL - load a model using built-in load module 2 %LOADMODEL - load a model using built-in load module 3 3 % 4 4 % check that model prototype has not changed. if so, adapt to new model prototype. -
issm/trunk-jpl/src/m/io/loadmodel.py
r25346 r25455 1 1 from loadvars import loadvars 2 # hack to keep python 2 compatipility2 # Hack to keep python 2 compatibility 3 3 try: 4 #py3 import 5 from dbm import whichdb 4 from dbm import whichdb # Python 3 6 5 except ImportError: 7 #py2 import8 from whichdb import whichdb 6 from whichdb import whichdb # Python 2 7 9 8 from netCDF4 import Dataset 10 9 11 10 12 11 def loadmodel(path, onlylast=False): 13 """ 14 LOADMODEL - load a model using built - in load module 12 """LOADMODEL - load a model 15 13 16 check that model prototype has not changed. if so, adapt to new model prototype.14 Check that model prototype has not changed: if if has, adapt to new model prototype. 17 15 18 19 16 Usage: 17 md = loadmodel(path) 20 18 """ 21 19 -
issm/trunk-jpl/src/m/io/loadvars.py
r25346 r25455 1 1 from collections import OrderedDict 2 # Hack to keep python 2 compatibility 3 try: 4 from dbm import whichdb # Python 3 5 except ImportError: 6 from whichdb import whichdb # Python 2 7 from re import findall 8 import shelve 9 2 10 from netCDF4 import Dataset 3 11 import numpy as np 4 from re import findall5 import shelve6 12 7 13 from model import * 8 #hack to keep python 2 compatibility9 try:10 #py3 import11 from dbm import whichdb12 except ImportError:13 #py2 import14 from whichdb import whichdb15 14 16 15 17 16 def loadvars(*args, **kwargs): 18 """ 19 LOADVARS - function to load variables from a file. 17 """LOADVARS - function to load variables from a file 20 18 21 19 This function loads one or more variables from a file. The names of the -
issm/trunk-jpl/src/m/mech/newforcing.m
r20186 r25455 1 1 function forcing=newforcing(t0,t1,deltaT,f0,f1,nodes) 2 % FUNCTION NEWFORCING Build forcing that extends temporally from t0 to t1, and in magnitude from f0 to f1. Equal time3 % 2 %NEWFORCING - Build forcing that extends temporally from t0 to t1, and in 3 %magnitude from f0 to f1. Equal time and magnitude spacing. 4 4 % 5 % Usage: forcing=newforcing(t0,t1,deltaT,f0,f1,nodes); 6 % Where: 7 % t0:t1: time interval. 8 % deltaT: time step 9 % f0:f1: magnitude interval. 10 % nodes: number of vertices where we have a temporal forcing 5 % Usage: forcing=newforcing(t0,t1,deltaT,f0,f1,nodes); 6 % 7 % Where: 8 % t0:t1: time interval. 9 % deltaT: time step 10 % f0:f1: magnitude interval. 11 % nodes: number of vertices where we have a temporal forcing 11 12 % 12 % Example: 13 % md.smb.mass_balance=newforcing(md.timestepping.start_time,md.timestepping.final_time,... 14 % md.timestepping.time_step,-1,+2,md.mesh.numberofvertices); 13 % Example: 14 % md.smb.mass_balance=newforcing(md.timestepping.start_time,md.timestepping.final_time,md.timestepping.time_step,-1,+2,md.mesh.numberofvertices); 15 15 % 16 16 -
issm/trunk-jpl/src/m/mech/newforcing.py
r24256 r25455 4 4 def newforcing(t0, t1, deltaT, f0, f1, nodes): 5 5 ''' 6 FUNCTION NEWFORCINGBuild forcing that extends temporally from t0 to t1, and in magnitude from f0 to f1. Equal time6 NEWFORCING - Build forcing that extends temporally from t0 to t1, and in magnitude from f0 to f1. Equal time 7 7 and magnitude spacing. 8 8 9 Usage: forcing = newforcing(t0, t1, deltaT, f0, f1, nodes); 10 Where: 11 t0:t1: time interval. 12 deltaT: time step 13 f0:f1: magnitude interval. 14 nodes: number of vertices where we have a temporal forcing 9 Usage: forcing = newforcing(t0, t1, deltaT, f0, f1, nodes); 10 11 Where: 12 t0:t1: time interval. 13 deltaT: time step 14 f0:f1: magnitude interval. 15 nodes: number of vertices where we have a temporal forcing 15 16 16 Example: 17 md.smb.mass_balance = newforcing(md.timestepping.start_time, md.timestepping.final_time, 18 md.timestepping.time_step, -1, +2, md.mesh.numberofvertices) 17 Example: 18 md.smb.mass_balance = newforcing( 19 md.timestepping.start_time, 20 md.timestepping.final_time, 21 md.timestepping.time_step, 22 -1, 23 +2, 24 md.mesh.numberofvertices 25 ) 19 26 ''' 27 20 28 #Number of time steps: 21 29 nsteps = (t1 - t0) / deltaT + 1 -
issm/trunk-jpl/src/m/mesh/TwoDToThreeD.m
r24999 r25455 21 21 vc=md.mesh.vertexconnectivity; 22 22 vb=md.mesh.vertexonboundary; 23 md.mesh=mesh3dsurface(); 23 md.mesh=mesh3dsurface(); 24 24 md.mesh.lat=lat; 25 25 md.mesh.long=long; -
issm/trunk-jpl/src/m/mesh/TwoDToThreeD.py
r25035 r25455 1 1 import numpy as np 2 2 3 from epsg2proj import epsg2proj 4 from gdaltransform import gdaltransform 3 5 from mesh3dsurface import mesh3dsurface 4 6 from planetradius import planetradius 5 7 6 def TwoDToThreeD(md, planet): #{{{ 8 9 def TwoDToThreeD(md, planet): 7 10 # Reproject model into lat, long if necessary 8 11 if md.mesh.proj != epsg2proj(4326): … … 13 16 14 17 # We assume x and y hold the long, lat values 15 long = md.mesh.x16 lat = md.mesh.y18 longe = md.mesh.x 19 late = md.mesh.y 17 20 18 21 # Assume spherical body 19 x = R * np.cos(np.deg2rad(lat )) * np.cos(np.deg2rad(long))20 y = R * np.cos(np.deg2rad(lat )) * np.sin(np.deg2rad(long))21 z = R * np.sin(np.deg2rad(lat ))22 x = R * np.cos(np.deg2rad(late)) * np.cos(np.deg2rad(longe)) 23 y = R * np.cos(np.deg2rad(late)) * np.sin(np.deg2rad(longe)) 24 z = R * np.sin(np.deg2rad(late)) 22 25 23 26 elements = md.mesh.elements 24 27 vc = md.mesh.vertexconnectivity 25 28 vb = md.mesh.vertexonboundary 26 md.mesh .mesh3dsurface()27 md.mesh.lat = lat 28 md.mesh.long = long 29 md.mesh = mesh3dsurface() 30 md.mesh.lat = late 31 md.mesh.long = longe 29 32 md.mesh.x = x 30 33 md.mesh.y = y … … 32 35 md.mesh.elements = elements 33 36 md.mesh.numberofelements = len(elements) 34 md.mesh.numberofvertices = len(lat )35 md.mesh.r = R * np.ones( md.mesh.numberofvertices)37 md.mesh.numberofvertices = len(late) 38 md.mesh.r = R * np.ones((md.mesh.numberofvertices, )) 36 39 md.mesh.vertexconnectivity = vc 37 40 md.mesh.vertexonboundary = vb 38 #}}} 41 42 return md -
issm/trunk-jpl/src/m/mesh/bamg.m
r24865 r25455 80 80 domain=shpread(domainfile); 81 81 else 82 error(['bamg error message: file ' domainfile ' format not supported (. shp or .exp)']);82 error(['bamg error message: file ' domainfile ' format not supported (.exp or .shp)']); 83 83 end 84 84 elseif isstruct(domainfile), … … 140 140 end 141 141 142 %Check sthat all holes are INSIDE the principle domain outline142 %Check that all holes are INSIDE the principle domain outline 143 143 if i>1, 144 144 flags=ContourToNodes(domain(i).x,domain(i).y,domain(1),0); … … 149 149 150 150 %Check orientation 151 nods=domain(i).nods-1; %the domain are closed 1=end;151 nods=domain(i).nods-1; %the domain is closed (domain[1] = domain[end]) 152 152 test = sum([(domain(i).x(2:nods+1) - domain(i).x(1:nods)).*(domain(i).y(2:nods+1) + domain(i).y(1:nods))]); 153 153 if (i==1 && test>0) || (i>1 && test<0), … … 163 163 bamg_geometry.Edges =[bamg_geometry.Edges; [transpose(count+1:count+nods) transpose([count+2:count+nods count+1]) 1*ones(nods,1)]]; 164 164 165 %Flag how many edges we have now, that way we know which edges belong to the domain, will 166 %be used later for required edges when NoBoundaryRefinement is one: 165 % Flag how many edges we have now, that way we know which edges belong 166 % to the domain. Will be used later for required edges if 167 % NoBoundaryRefinement equals 1. 167 168 new_edge_length=length(bamg_geometry.Edges); 168 169 edges_required=(edge_length+1):new_edge_length; 169 170 170 171 if i>1, 171 bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 -subdomain_ref]; subdomain_ref = subdomain_ref+1; 172 bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 -subdomain_ref]; 173 subdomain_ref = subdomain_ref+1; 172 174 else 173 175 bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 0]; … … 179 181 for i=1:length(holes), 180 182 181 %Check that the subdomainsis closed183 %Check that the hole is closed 182 184 if (holes(i).x(1)~=holes(i).x(end) | holes(i).y(1)~=holes(i).y(end)), 183 185 error('bamg error message: all contours provided in ''holes'' should be closed'); 184 186 end 185 187 186 %Check s that all holes are INSIDE the principle domain outline188 %Check that all holes are INSIDE the principal domain (principal domain should be index 0) 187 189 flags=ContourToNodes(holes(i).x,holes(i).y,domain(1),0); 188 190 if any(~flags), error('bamg error message: All holes should be strictly inside the principal domain'); end 189 191 190 192 %Check that hole is correctly oriented 191 nods=holes(i).nods-1; %the hole s are closed 1=end;193 nods=holes(i).nods-1; %the hole is closed (hole[1] = hole[end]) 192 194 if(sum([(holes(i).x(2:nods+1) - holes(i).x(1:nods)).*(holes(i).y(2:nods+1) + holes(i).y(1:nods))]))<0 193 195 disp('At least one hole was not correctly oriented and has been re-oriented'); … … 205 207 for i=1:length(subdomains), 206 208 207 %Check that the subdomain sis closed209 %Check that the subdomain is closed 208 210 if (subdomains(i).x(1)~=subdomains(i).x(end) | subdomains(i).y(1)~=subdomains(i).y(end)), 209 211 error('bamg error message: all contours provided in ''subdomains'' should be closed'); 210 212 end 211 213 212 %Checks that all holes are INSIDE the principle domain outline214 %Checks that all subdomains are INSIDE the principal domain (principal domain should be index 0) 213 215 flags=ContourToNodes(subdomains(i).x,subdomains(i).y,domain(1),0); 214 216 if any(~flags), 215 error('bamg error message: All holes should be strictly inside the principal domain');216 end 217 218 %Check that holeis correctly oriented219 nods=subdomains(i).nods-1; % the subdomains are closed 1=end;217 error('bamg error message: All subdomains should be strictly inside the principal domain'); 218 end 219 220 %Check that subdomain is correctly oriented 221 nods=subdomains(i).nods-1; % the subdomains are closed (subdomains[1] = subdomains[end]) 220 222 if(sum([(subdomains(i).x(2:nods+1) - subdomains(i).x(1:nods)).*(subdomains(i).y(2:nods+1) + subdomains(i).y(1:nods))]))>0 221 223 disp('At least one subdomain was not correctly oriented and has been re-oriented'); 222 subdomains(i).x = flipud(subdomains(i).x); subdomains(i).y = flipud(subdomains(i).y); 224 subdomains(i).x = flipud(subdomains(i).x); 225 subdomains(i).y = flipud(subdomains(i).y); 223 226 end 224 227 … … 227 230 bamg_geometry.Edges =[bamg_geometry.Edges; [transpose(count+1:count+nods) transpose([count+2:count+nods count+1]) 1.*ones(nods,1)]]; 228 231 229 bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 subdomain_ref]; subdomain_ref = subdomain_ref+1; 232 bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 subdomain_ref]; 233 subdomain_ref = subdomain_ref+1; 230 234 231 235 %update counter 232 236 count=count+nods; 233 237 end 238 234 239 if getfieldvalue(options,'vertical',0), 235 240 if numel(getfieldvalue(options,'Markers',[]))~=size(bamg_geometry.Edges,1), … … 243 248 %take care of rifts 244 249 if exist(options,'rifts'), 245 246 %Check that file exists 250 %read rift file according to its extension: 247 251 riftfile=getfieldvalue(options,'rifts'); 248 [pathr,namer,extr]=fileparts(riftfile);249 if ~exist(riftfile,'file')250 error(['bamg error message: file ' riftfile ' not found ']);251 elseif strcmp(extr,'.exp'),252 rift=expread(riftfile);253 elseif strcmp(extr,'.shp'),254 rift=shpread(riftfile);255 end256 %read rift file according to its extension:257 252 [path,name,ext]=fileparts(riftfile); 258 253 if strcmp(ext,'.exp'), … … 261 256 rift=shpread(riftfile); 262 257 else 263 error(['bamg error message: file ' riftfile ' format not supported (. shp or .exp)']);258 error(['bamg error message: file ' riftfile ' format not supported (.exp or .shp)']); 264 259 end 265 260 … … 272 267 273 268 elseif any(~flags), 274 %We LOTS of work to do269 %We have LOTS of work to do 275 270 disp('Rift tip outside of or on the domain has been detected and is being processed...'); 276 271 277 272 %check that only one point is outside (for now) 278 273 if sum(~flags)~=1, 279 error('bamg error message: only one point outside of the domain is supported yet');274 error('bamg error message: only one point outside of the domain is supported at this time'); 280 275 end 281 276 … … 290 285 end 291 286 292 %Get cordinate of intersection point 293 x1=rift(i).x(1); y1=rift(i).y(1); 294 x2=rift(i).x(2); y2=rift(i).y(2); 287 %Get coordinate of intersection point 288 x1=rift(i).x(1); 289 y1=rift(i).y(1); 290 x2=rift(i).x(2); 291 y2=rift(i).y(2); 295 292 for j=1:length(domain(1).x)-1; 296 293 if SegIntersect([x1 y1; x2 y2],[domain(1).x(j) domain(1).y(j); domain(1).x(j+1) domain(1).y(j+1)]), … … 489 486 md.mesh.numberofvertices=length(md.mesh.x); 490 487 md.mesh.numberofedges=size(md.mesh.edges,1); 491 md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1; 492 493 %Now, build the connectivity tables for this mesh. 494 md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1; 488 md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); 489 md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1; 495 490 496 491 elseif getfieldvalue(options,'3dsurface',0), … … 509 504 md.mesh.numberofvertices=length(md.mesh.x); 510 505 md.mesh.numberofedges=size(md.mesh.edges,1); 511 md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1; 506 md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); 507 md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1; 512 508 513 509 else … … 524 520 md.mesh.numberofvertices=length(md.mesh.x); 525 521 md.mesh.numberofedges=size(md.mesh.edges,1); 526 md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1; 522 md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); 523 md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1; 527 524 end 528 525 -
issm/trunk-jpl/src/m/mesh/bamg.py
r24262 r25455 1 from collections import namedtuple, OrderedDict 1 2 import os.path 3 2 4 import numpy as np 5 6 from bamggeom import bamggeom 7 from BamgMesher import BamgMesher 8 from bamgmesh import bamgmesh 9 from ContourToNodes import ContourToNodes 10 from expread import expread 11 from helpers import fileparts, OrderedStruct 3 12 from mesh2d import * 4 13 from mesh2dvertical import * 5 14 from mesh3dsurface import * 6 from collections import OrderedDict7 15 from pairoptions import pairoptions 8 from bamggeom import bamggeom9 from bamgmesh import bamgmesh10 from expread import expread11 16 from SegIntersect import SegIntersect 12 import MatlabFuncs as m 13 from BamgMesher import BamgMesher 14 from ContourToNodes import ContourToNodes 17 from shpread import shpread 15 18 16 19 17 20 def bamg(md, *args): 18 """ 19 BAMG - mesh generation 21 """BAMG - mesh generation 20 22 21 23 Available options (for more details see ISSM website http://issm.jpl.nasa.gov/): … … 43 45 1 -> use Green formula 44 46 - KeepVertices : try to keep initial vertices when adaptation is done on an existing mesh (default 1) 47 - NoBoundaryRefinement: do not refine boundary, only follow contour provided (default 0). Allow subdomain boundary refinement though 48 - NoBoundaryRefinementAllBoundaries: do not refine boundary, only follow contour provided (default 0) 45 49 - maxnbv : maximum number of vertices used to allocate memory (default is 1.0e6) 46 50 - maxsubdiv : maximum subdivision of exisiting elements (default is 10) … … 63 67 will be merged 64 68 65 Examples: 66 md = bamg(md, 'domain', 'DomainOutline.exp', 'hmax', 3000) 67 md = bamg(md, 'field', [md.inversion.vel_obs md.geometry.thickness], 'hmax', 20000, 'hmin', 1000) 68 md = bamg(md, 'metric', A, 'hmin', 1000, 'hmax', 20000, 'gradation', 3, 'anisomax', 1) 69 Examples: 70 md = bamg(md, 'domain', 'DomainOutline.exp', 'hmax', 3000) 71 md = bamg(md, 'field', [md.inversion.vel_obs md.geometry.thickness], 'hmax', 20000, 'hmin', 1000) 72 md = bamg(md, 'metric', A, 'hmin', 1000, 'hmax', 20000, 'gradation', 3, 'anisomax', 1) 73 74 TODO: 75 - Verify that values of third column of bamg_geometry.Vertices and bamg_geometry.Edges are valid (compare to src/m/mesh/bamg.m) 69 76 """ 70 77 … … 79 86 80 87 subdomain_ref = 1 88 hole_ref = 1 81 89 82 90 # Bamg Geometry parameters {{{ … … 86 94 if type(domainfile) == str: 87 95 if not os.path.exists(domainfile): 88 raise IOError("bamg error message: file '%s' not found" % domainfile) 96 raise IOError("bamg error message: file {} not found".format( domainfile)) 97 98 # Read domain according to its extension 99 path, name, ext = fileparts(domainfile) 100 if ext == '.exp': 101 domain = expread(domainfile) 102 elif ext == '.shp': 103 domain = shpread(domainfile) 104 else: 105 raise Exception('bamg error message: file {} format not supported (.exp or .shp)'.format(domainfile)) 89 106 domain = expread(domainfile) 107 elif type(domainfile) == list: 108 if len(domainfile): 109 if type(domainfile[0]) in [dict, OrderedDict]: 110 domain = domainfile 111 else: 112 raise Exception("bamg error message: if 'domain' is a list, its elements must be of type dict or OrderedDict") 113 else: 114 domain = domainfile 115 elif type(domainfile) in [dict, OrderedDict]: 116 domain = [domainfile] 90 117 else: 91 domain = domainfile 92 93 #Build geometry 118 raise Exception("bamg error message: 'domain' type {} not supported yet".format(type(domainfile))) 119 120 holes = [] 121 if options.exist('holes'): 122 holesfile = options.getfieldvalue('holes') 123 if type(holesfile) == str: 124 if not os.path.exists(holesfile): 125 raise IOError("bamg error message: file {} not found".format(holesfile)) 126 127 # Read holes accoridng to its extension 128 path, name, ext = fileparts(holesfile) 129 if ext == '.exp': 130 holes = expread(holesfile) 131 elif ext == '.shp': 132 holes = shpread(holesfile) 133 else: 134 raise Exception('bamg error message: file {} format not supported (.exp or .shp)'.format(holesfile)) 135 elif type(holesfile) == list: 136 if len(holesfile): 137 if type(holesfile[0]) in [dict, OrderedDict]: 138 holes = holesfile 139 else: 140 raise Exception("bamg error message: if 'holes' is a list, its elements must be of type dict or OrderedDict") 141 else: 142 holes = holesfile 143 elif type(holesfile) in [dict, OrderedDict]: 144 holes = [holesfile] 145 else: 146 raise Exception("'holes' type {} not supported yet".format(type(holesfile))) 147 148 subdomains = [] 149 if options.exist('subdomains'): 150 subdomainsfile = options.getfieldvalue('subdomains') 151 if type(subdomainsfile) == str: 152 if not os.path.exists(subdomainsfile): 153 raise IOError("bamg error message: file {} not found".format(subdomainsfile)) 154 155 # Read subdomains accoridng to its extension 156 path, name, ext = fileparts(subdomainsfile) 157 if ext == '.exp': 158 subdomains = expread(subdomainsfile) 159 elif ext == '.shp': 160 subdomains = shpread(subdomainsfile) 161 else: 162 raise Exception('bamg error message: file {} format not supported (.exp or .shp)'.format(subdomainsfile)) 163 elif type(subdomainsfile) == list: 164 if len(subdomainsfile): 165 if type(subdomainsfile[0]) in [dict, OrderedDict]: 166 subdomains = subdomainsfile 167 else: 168 raise Exception("bamg error message: if 'subdomains' is a list, its elements must be of type dict or OrderedDict") 169 else: 170 subdomains = subdomainsfile 171 elif type(subdomainsfile) in [dict, OrderedDict]: 172 subdomains = [subdomainsfile] 173 else: 174 raise Exception("'subdomains' type {} not supported yet".format(type(subdomainsfile))) 175 176 # Build geometry 94 177 count = 0 95 for i , domaini in enumerate(domain):96 # Check that the domain is closed97 if (domain i['x'][0] != domaini['x'][-1] or domaini['y'][0] != domaini['y'][-1]):178 for i in range(len(domain)): 179 # Check that the domain is closed 180 if (domain[i]['x'][0] != domain[i]['x'][-1] or domain[i]['y'][0] != domain[i]['y'][-1]): 98 181 raise RuntimeError("bamg error message: all contours provided in ''domain'' should be closed") 99 182 100 # Checks that all holes are INSIDE the principle domain outline princial domain should be index 0183 # Check that all holes are INSIDE the principle domain outline 101 184 if i: 102 flags = ContourToNodes(domain i['x'], domaini['y'], domainfile, 0)[0]185 flags = ContourToNodes(domain[i]['x'], domain[i]['y'], [domain[0]], 0)[0] # NOTE: Down stack call to FetchPythonData requires contour to be a list of struct if we are not passing in a path to a file, hence the odd addressing: '[domain[0]]' 103 186 if np.any(np.logical_not(flags)): 104 187 raise RuntimeError("bamg error message: All holes should be strictly inside the principal domain") 105 188 106 # Check orientation107 nods = domain i['nods'] - 1 #the domain are closed 1 = end108 test = np.sum((domain i['x'][1:nods + 1] - domaini['x'][0:nods]) * (domaini['y'][1:nods + 1] + domaini['y'][0:nods]))189 # Check orientation 190 nods = domain[i]['nods'] - 1 # the domain is closed (domain[0] = domain[-1]) 191 test = np.sum((domain[i]['x'][1:nods + 1] - domain[i]['x'][0:nods]) * (domain[i]['y'][1:nods + 1] + domain[i]['y'][0:nods])) 109 192 if (i == 0 and test > 0) or (i > 0 and test < 0): 110 193 print('At least one contour was not correctly oriented and has been re-oriented') 111 domaini['x'] = np.flipud(domaini['x']) 112 domaini['y'] = np.flipud(domaini['y']) 113 114 #Add all points to bamg_geometry 115 nods = domaini['nods'] - 1 #the domain are closed 0 = end 116 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, np.vstack((domaini['x'][0:nods], domaini['y'][0:nods], np.ones((nods)))).T)) 194 domain[i]['x'] = np.flipud(domain[i]['x']) 195 domain[i]['y'] = np.flipud(domain[i]['y']) 196 197 # Flag how many edges we have so far 198 edge_length = len(bamg_geometry.Edges) 199 200 # Add all points to bamg_geometry 201 #nods = domain[i]['nods'] - 1 #the domain are closed 0 = end 202 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, np.vstack((domain[i]['x'][0:nods], domain[i]['y'][0:nods], np.ones((nods)))).T)) 117 203 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)) 118 if i: 204 205 # Flag how many edges we have now, that way we know which edges 206 # belong to the subdomain. Will be used later fo required edges 207 # if NoBoundaryRefinement equals 1. 208 new_edge_length = len(bamg_geometry.Edges) 209 edges_required = range((edge_length + 1), (new_edge_length + 1)) # NOTE: Upper bound of range is non-inclusive (compare to src/m/mesh/bamg.m) 210 211 if i: # NOTE: same as `if i > 0` (MATLAB is `if i > 1`) 119 212 bamg_geometry.SubDomains = np.vstack((bamg_geometry.SubDomains, [2, count + 1, 1, -subdomain_ref])) 120 213 subdomain_ref = subdomain_ref + 1 … … 122 215 bamg_geometry.SubDomains = np.vstack((bamg_geometry.SubDomains, [2, count + 1, 1, 0])) 123 216 124 # update counter217 # Update counter 125 218 count += nods 126 219 127 #Deal with domain holes 128 if options.exist('holes'): 129 holesfile = options.getfieldvalue('holes') 130 if type(holesfile) == str: 131 if not os.path.exists(holesfile): 132 raise IOError("bamg error message: file '%s' not found" % holesfile) 133 holes = expread(holesfile) 134 else: 135 holes = holesfile 136 137 #Build geometry 138 for i, holei in enumerate(holes): 139 #Check that the hole is closed 140 if (holei['x'][0] != holei['x'][-1] or holei['y'][0] != holei['y'][-1]): 141 raise RuntimeError("bamg error message: all contours provided in ''hole'' should be closed") 142 143 #Checks that all holes are INSIDE the principle domain outline princial domain should be index 0 144 flags = ContourToNodes(holei['x'], holei['y'], domainfile, 0)[0] 145 if np.any(np.logical_not(flags)): 146 raise RuntimeError("bamg error message: All holes should be strictly inside the principal domain") 147 148 #Check orientation 149 nods = holei['nods'] - 1 #the hole are closed 1 = end 150 test = np.sum((holei['x'][1:nods + 1] - holei['x'][0:nods]) * (holei['y'][1:nods + 1] + holei['y'][0:nods])) 151 if test < 0: 152 print('At least one hole was not correctly oriented and has been re-oriented') 153 holei['x'] = np.flipud(holei['x']) 154 holei['y'] = np.flipud(holei['y']) 155 156 #Add all points to bamg_geometry 157 nods = holei['nods'] - 1 #the hole are closed 0 = end 158 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, np.vstack((holei['x'][0:nods], holei['y'][0:nods], np.ones((nods)))).T)) 159 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)) 160 #update counter 161 count += nods 162 163 #And subdomains 164 if options.exist('subdomains'): 165 subdomainfile = options.getfieldvalue('subdomains') 166 if type(subdomainfile) == str: 167 if not os.path.exists(subdomainfile): 168 raise IOError("bamg error message: file '{}' not found".format(subdomainfile)) 169 subdomains = expread(subdomainfile) 170 else: 171 subdomains = subdomainfile 172 173 #Build geometry 174 for i, subdomaini in enumerate(subdomains): 175 #Check that the subdomain is closed 176 if (subdomaini['x'][0] != subdomaini['x'][-1] or subdomaini['y'][0] != subdomaini['y'][-1]): 177 raise RuntimeError("bamg error message: all contours provided in ''subdomain'' should be closed") 178 179 #Checks that all subdomains are INSIDE the principle subdomain outline princial domain should be index 0 180 if i: 181 flags = ContourToNodes(subdomaini['x'], subdomaini['y'], domainfile, 0)[0] 182 if np.any(np.logical_not(flags)): 183 raise RuntimeError("bamg error message: All subdomains should be strictly inside the principal subdomain") 184 185 #Check orientation 186 nods = subdomaini['nods'] - 1 #the subdomain are closed 1 = end 187 188 test = np.sum((subdomaini['x'][1:nods + 1] - subdomaini['x'][0:nods]) * (subdomaini['y'][1:nods + 1] + subdomaini['y'][0:nods])) 189 if test > 0: 190 print('At least one subcontour was not correctly oriented and has been re-oriented') 191 subdomaini['x'] = np.flipud(subdomaini['x']) 192 subdomaini['y'] = np.flipud(subdomaini['y']) 193 194 #Add all points to bamg_geometry 195 nods = subdomaini['nods'] - 1 #the subdomain are closed 0 = end 196 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, np.vstack((subdomaini['x'][0:nods], subdomaini['y'][0:nods], np.ones((nods)))).T)) 197 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)) 198 #update counter 199 count += nods 220 for i in range(len(holes)): 221 # heck that the hole is closed 222 if (holes[i]['x'][0] != holes[i]['x'][-1] or holes[i]['y'][0] != holes[i]['y'][-1]): 223 raise RuntimeError("bamg error message: all contours provided in ''hole'' should be closed") 224 225 # Check that all holes are INSIDE the principal domain (principal domain should be index 0) 226 flags = ContourToNodes(holes[i]['x'], holes[i]['y'], [domain[0]], 0)[0] # NOTE: Down stack call to FetchPythonData requires contour to be a list of struct if we are not passing in a path to a file, hence the odd addressing: '[domain[0]]' 227 if np.any(np.logical_not(flags)): 228 raise RuntimeError("bamg error message: All holes should be strictly inside the principal domain") 229 230 # Check that hole is correctly oriented 231 nods = holes[i]['nods'] - 1 # the holes are closed (holes[0] = holes[-1]) 232 test = np.sum((holes[i]['x'][1:nods + 1] - holes[i]['x'][0:nods]) * (holes[i]['y'][1:nods + 1] + holes[i]['y'][0:nods])) 233 if test < 0: 234 print('At least one hole was not correctly oriented and has been re-oriented') 235 holes[i]['x'] = np.flipud(holes[i]['x']) 236 holes[i]['y'] = np.flipud(holes[i]['y']) 237 238 # Add all points to bamg_geometry 239 #nods = holes[i]['nods'] - 1 # the hole is closed (hole[0] = hole[-1]) 240 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, np.vstack((holes[i]['x'][0:nods], holes[i]['y'][0:nods], np.ones((nods)))).T)) 241 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)) 242 bamg.geometry.SubDomains = np.vstack((bamg_geometry.SubDomains, [2, count + 1, 1, -hole_ref])) 243 hole_ref = hole_ref + 1 244 245 # Update counter 246 count += nods 247 248 for i in range(len(subdomains)): 249 # Check that the subdomain is closed 250 if (subdomains[i]['x'][0] != subdomains[i]['x'][-1] or subdomains[i]['y'][0] != subdomains[i]['y'][-1]): 251 raise RuntimeError("bamg error message: all contours provided in ''subdomains'' should be closed") 252 253 # Check that all subdomains are INSIDE the principal domain (principal domain should be index 0) 254 flags = ContourToNodes(subdomains[i]['x'], subdomains[i]['y'], [domain[0]], 0)[0] # NOTE: Down stack call to FetchPythonData requires contour to be a list of struct if we are not passing in a path to a file, hence the odd addressing: '[domain[0]]' 255 if np.any(np.logical_not(flags)): 256 raise RuntimeError("bamg error message: All subdomains should be strictly inside the principal domain") 257 258 # Check that subdomain is correctly oriented 259 nods = subdomains[i]['nods'] - 1 # the subdomains are closed (subdomains[0] = subdomains[-1]) 260 261 test = np.sum((subdomains[i]['x'][1:nods + 1] - subdomains[i]['x'][0:nods]) * (subdomains[i]['y'][1:nods + 1] + subdomains[i]['y'][0:nods])) 262 if test: 263 print('At least one subcontour was not correctly oriented and has been re-oriented') 264 subdomains[i]['x'] = np.flipud(subdomains[i]['x']) 265 subdomains[i]['y'] = np.flipud(subdomains[i]['y']) 266 267 #Add all points to bamg_geometry 268 #nods = subdomains[i]['nods'] - 1 # the subdomains are closed (subdomains[0] = subdomains[-1]) 269 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, np.vstack((subdomains[i]['x'][0:nods], subdomains[i]['y'][0:nods], np.ones((nods)))).T)) 270 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)) 271 bamg_geometry.SubDomains = np.vstack((bamg_geometry.SubDomains, [2, count + 1, 1, subdomain_ref])) 272 subdomain_ref = subdomain_ref + 1 273 274 # Update counter 275 count += nods 200 276 201 277 if options.getfieldvalue('vertical', 0): 202 278 if np.size(options.getfieldvalue('Markers', [])) != np.size(bamg_geometry.Edges, 0): 203 279 raise RuntimeError('for 2d vertical mesh, ''Markers'' option is required, and should be of size ' + str(np.size(bamg_geometry.Edges, 0))) 204 205 206 207 # take care of rifts280 if np.size(options.getfieldvalue('Markers', [])) == np.size(bamg_geometry.Edges, 0): 281 bamg_geometry.Edges[:, 2] = options.getfieldvalue('Markers') 282 283 # Take care of rifts 208 284 if options.exist('rifts'): 209 210 #Check that file exists 285 # Read rift file according to its extension 211 286 riftfile = options.getfieldvalue('rifts') 212 if not os.path.exists(riftfile): 213 raise IOError("bamg error message: file '%s' not found" % riftfile) 214 rift = expread(riftfile) 215 216 for i, rifti in enumerate(rift): 217 #detect whether all points of the rift are inside the domain 218 flags = ContourToNodes(rifti['x'], rifti['y'], domain[0], 0)[0] 287 path, name, ext = fileparts(riftfile) 288 if ext == '.exp': 289 rift = expread(riftfile) 290 elif ext == '.shp': 291 rift = shpread(riftfile) 292 else: 293 raise IOError("bamg error message: file '{}' format not supported (.exp or .shp)".format(riftfile)) 294 295 for i in range(len(rift)): 296 # Detect whether all points of the rift are inside the domain 297 flags = ContourToNodes(rift[i]['x'], rift[i]['y'], [domain[0]], 0)[0] # NOTE: Down stack call to FetchPythonData requires contour to be a list of struct if we are not passing in a path to a file, hence the odd addressing: '[domain[0]]' 219 298 if np.all(np.logical_not(flags)): 220 299 raise RuntimeError("one rift has all its points outside of the domain outline") 221 222 300 elif np.any(np.logical_not(flags)): 223 # We LOTS of work to do301 # We have LOTS of work to do 224 302 print("Rift tip outside of or on the domain has been detected and is being processed...") 225 #check that only one point is outside (for now) 303 304 # Check that only one point is outside (for now) 226 305 if np.sum(np.logical_not(flags).astype(int)) != 1: 227 raise RuntimeError("bamg error message: only one point outside of the domain is supported yet")228 229 # Move tip outside to the first position306 raise RuntimeError("bamg error message: only one point outside of the domain is supported at this time") 307 308 # Move tip outside to the first position 230 309 if not flags[0]: 231 # OK, first point is outside (do nothing),310 # OK, first point is outside (do nothing), 232 311 pass 233 312 elif not flags[-1]: 234 rift i['x'] = np.flipud(rifti['x'])235 rift i['y'] = np.flipud(rifti['y'])313 rift[i]['x'] = np.flipud(rift[i]['x']) 314 rift[i]['y'] = np.flipud(rift[i]['y']) 236 315 else: 237 316 raise RuntimeError("bamg error message: only a rift tip can be outside of the domain") 238 317 239 # Get cordinate of intersection point240 x1 = rift i['x'][0]241 y1 = rift i['y'][0]242 x2 = rift i['x'][1]243 y2 = rift i['y'][1]318 # Get coordinate of intersection point 319 x1 = rift[i]['x'][0] 320 y1 = rift[i]['y'][0] 321 x2 = rift[i]['x'][1] 322 y2 = rift[i]['y'][1] 244 323 for j in range(0, np.size(domain[0]['x']) - 1): 245 324 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]]])): 246 325 247 # Get position of the two nodes of the edge in domain326 # Get position of the two nodes of the edge in domain 248 327 i1 = j 249 328 i2 = j + 1 250 329 251 # rift is crossing edge [i1i2] of the domain252 # Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html)330 # Rift is crossing edge [i1, i2] of the domain 331 # Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html) 253 332 x3 = domain[0]['x'][i1] 254 333 y3 = domain[0]['y'][i1] 255 334 x4 = domain[0]['x'][i2] 256 335 y4 = domain[0]['y'][i2] 257 #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])258 #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])259 336 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]])) 260 337 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]])) … … 264 341 265 342 if np.min(tipdis) / segdis < options.getfieldvalue('toltip', 0): 266 print("moving tip -domain intersection point")267 268 # Get position of the closer point343 print("moving tip-domain intersection point") 344 345 # Get position of the closer point 269 346 if tipdis[0] > tipdis[1]: 270 347 pos = i2 … … 272 349 pos = i1 273 350 274 #This point is only in Vertices (number pos). 275 #OK, now we can add our own rift 276 nods = rifti['nods'] - 1 277 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, np.hstack((rifti['x'][1:].reshape(-1, ), rifti['y'][1:].reshape(-1, ), np.ones((nods, 1)))))) 278 bamg_geometry.Edges = np.vstack((bamg_geometry.Edges, 279 np.array([[pos, count + 1, (1 + i)]]), 280 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)))))) 351 # This point is only in Vertices (number pos). 352 # OK, now we can add our own rift 353 nods = rift[i]['nods'] - 1 354 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, np.hstack((rift[i]['x'][1:].reshape(-1, ), rift[i]['y'][1:].reshape(-1, ), np.ones((nods, 1)))))) 355 bamg_geometry.Edges = np.vstack(( 356 bamg_geometry.Edges, 357 np.array([[pos, count + 1, (1 + i)]]), 358 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)))) 359 )) 281 360 count += nods 282 361 break 283 284 362 else: 285 #Add intersection point to Vertices 286 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, np.array([[x, y, 1]]))) 363 # Add intersection point to Vertices 364 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, 365 np.array([[x, y, 1]]) 366 )) 287 367 count += 1 288 368 289 # Decompose the crossing edge into 2 subedges369 # Decompose the crossing edge into 2 subedges 290 370 pos = np.nonzero(np.logical_and(bamg_geometry.Edges[:, 0] == i1, bamg_geometry.Edges[:, 1] == i2))[0] 291 371 if not pos: 292 372 raise RuntimeError("bamg error message: a problem occurred...") 293 bamg_geometry.Edges = np.vstack((bamg_geometry.Edges[0:pos - 1, :], 294 np.array([[bamg_geometry.Edges[pos, 0], count, bamg_geometry.Edges[pos, 2]]]), 295 np.array([[count, bamg_geometry.Edges[pos, 1], bamg_geometry.Edges[pos, 2]]]), 296 bamg_geometry.Edges[pos + 1:, :])) 297 298 #OK, now we can add our own rift 299 nods = rifti['nods'] - 1 300 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, np.hstack((rifti['x'][1:].reshape(-1, ), rifti['y'][1:].reshape(-1, ), np.ones((nods, 1)))))) 301 bamg_geometry.Edges = np.vstack((bamg_geometry.Edges, 302 np.array([[count, count + 1, 2]]), 303 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)))))) 373 bamg_geometry.Edges = np.vstack(( 374 bamg_geometry.Edges[0:pos - 1, :], 375 np.array([[ 376 bamg_geometry.Edges[pos, 0], 377 count, 378 bamg_geometry.Edges[pos, 2] 379 ]]), 380 np.array([[ 381 count, 382 bamg_geometry.Edges[pos, 1], 383 bamg_geometry.Edges[pos, 2] 384 ]]), 385 bamg_geometry.Edges[pos + 1:, :] 386 )) 387 388 # OK, now we can add our own rift 389 nods = rift[i]['nods'] - 1 390 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, 391 np.hstack(( 392 rift[i]['x'][1:].reshape(-1, ), 393 rift[i]['y'][1:].reshape(-1, ), 394 np.ones((nods, 1)) 395 )) 396 )) 397 bamg_geometry.Edges = np.vstack(( 398 bamg_geometry.Edges, 399 np.array([[count, count + 1, 2]]), 400 np.hstack(( 401 np.arange(count + 1, count + nods).reshape(-1, ), 402 np.arange(count + 2, count + nods + 1).reshape(-1, ), 403 (1 + i) * np.ones((nods - 1, 1)) 404 )) 405 )) 304 406 count += nods 305 407 break 306 307 408 else: 308 nods = rifti['nods'] - 1 309 bamg_geometry.Vertices = np.vstack(bamg_geometry.Vertices, np.hstack(rifti['x'][:], rifti['y'][:], np.ones((nods + 1, 1)))) 310 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)))) 311 count += nods + 1 312 313 #Deal with tracks 409 nods = rift[i]['nods'] - 1 410 bamg_geometry.Vertices = np.vstack(( 411 bamg_geometry.Vertices, 412 np.hstack(( 413 rift[i]['x'][:], 414 rift[i]['y'][:], 415 np.ones((nods + 1, 1)) 416 )) 417 )) 418 bamg_geometry.Edges = np.vstack(( 419 bamg_geometry.Edges, 420 np.hstack(( 421 np.arange(count + 1, count + nods).reshape(-1, ), 422 np.arange(count + 2, count + nods + 1).reshape(-1, ), 423 i * np.ones((nods, 1)) 424 )) 425 )) 426 count += (nods + 1) 427 428 # Deal with tracks 314 429 if options.exist('tracks'): 315 316 #read tracks 430 # Read tracks 317 431 track = options.getfieldvalue('tracks') 318 432 if all(isinstance(track, str)): … … 320 434 track = np.hstack((A.x.reshape(-1, ), A.y.reshape(-1, ))) 321 435 else: 322 track = float(track) #for some reason, it is of class "single" 436 track = float(track) 437 323 438 if np.size(track, axis=1) == 2: 324 439 track = np.hstack((track, 3. * np.ones((size(track, axis=0), 1)))) 325 440 326 # only keep those inside327 flags = ContourToNodes(track[:, 0], track[:, 1], domainfile, 0)[0]441 # Only keep those inside 442 flags = ContourToNodes(track[:, 0], track[:, 1], [domain[0]], 0)[0] # NOTE: Down stack call to FetchPythonData requires contour to be a list of struct if we are not passing in a path to a file, hence the odd addressing: '[domain[0]]' 328 443 track = track[np.nonzero(flags), :] 329 444 330 # Add all points to bamg_geometry445 # Add all points to bamg_geometry 331 446 nods = np.size(track, axis=0) 332 447 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, track)) 333 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)))))) 334 335 #update counter 448 bamg_geometry.Edges = np.vstack(( 449 bamg_geometry.Edges, 450 np.hstack(( 451 np.arange(count + 1, count + nods).reshape(-1, ), 452 np.arange(count + 2, count + nods + 1).reshape(-1, ), 453 3. * np.ones((nods - 1, 1)) 454 )) 455 )) 456 457 # Update counter 336 458 count += nods 337 459 338 # Deal with vertices that need to be kept by mesher460 # Deal with vertices that need to be kept by mesher 339 461 if options.exist('RequiredVertices'): 340 341 #recover RequiredVertices 342 requiredvertices = options.getfieldvalue('RequiredVertices') #for some reason, it is of class "single" 462 # Recover RequiredVertices 463 requiredvertices = options.getfieldvalue('RequiredVertices') 343 464 if np.size(requiredvertices, axis=1) == 2: 344 465 requiredvertices = np.hstack((requiredvertices, 4. * np.ones((np.size(requiredvertices, axis=0), 1)))) 345 466 346 # only keep those inside347 flags = ContourToNodes(requiredvertices[:, 0], requiredvertices[:, 1], domainfile, 0)[0]467 # Only keep those inside 468 flags = ContourToNodes(requiredvertices[:, 0], requiredvertices[:, 1], [domain[0]], 0)[0] # NOTE: Down stack call to FetchPythonData requires contour to be a list of struct if we are not passing in a path to a file, hence the odd addressing: '[domain[0]]' 348 469 requiredvertices = requiredvertices[np.nonzero(flags)[0], :] 349 #Add all points to bamg_geometry 470 471 # Add all points to bamg_geometry 350 472 nods = np.size(requiredvertices, axis=0) 351 473 bamg_geometry.Vertices = np.vstack((bamg_geometry.Vertices, requiredvertices)) 352 474 353 # update counter475 # Update counter 354 476 count += nods 355 477 356 #process geom 357 #bamg_geometry = processgeometry(bamg_geometry, options.getfieldvalue('tol', float(nan)), domain[0]) 478 # Deal with RequiredEdges 479 if options.getfieldvalue('NoBoundaryRefinement', 0): 480 bamg_geometry.RequiredEdges = edges_required 481 elif options.getfieldvalue('NoBoundaryRefinementAllBoundaries', 0): 482 bamg_geometry.RequiredEdges = np.arange(1, bamg_geometry.Edges.shape[0]).T 483 484 # Process geom 485 #bamg_geometry = processgeometry(bamg_geometry, options.getfieldvalue('tol', np.nan), domain[0]) 358 486 elif isinstance(md.private.bamg, dict) and 'geometry' in md.private.bamg: 359 487 bamg_geometry = bamggeom(md.private.bamg['geometry'].__dict__) … … 362 490 pass 363 491 #}}} 364 # Bamg Mesh parameters {{{365 if not options.exist('domain') and md.mesh.numberofvertices and m .strcmp(md.mesh.elementtype(), 'Tria'):492 # Bamg mesh parameters {{{ 493 if not options.exist('domain') and md.mesh.numberofvertices and md.mesh.elementtype() == 'Tria': 366 494 if isinstance(md.private.bamg, dict) and 'mesh' in md.private.bamg: 367 495 bamg_mesh = bamgmesh(md.private.bamg['mesh'].__dict__) 368 496 else: 369 bamg_mesh.Vertices = np.vstack((md.mesh.x, md.mesh.y, np.ones((md.mesh.numberofvertices)))).T 370 #bamg_mesh.Vertices = np.hstack((md.mesh.x.reshape(-1, ), md.mesh.y.reshape(-1, ), np.ones((md.mesh.numberofvertices, 1)))) 497 bamg_mesh.Vertices = np.vstack(( 498 md.mesh.x, 499 md.mesh.y, 500 np.ones((md.mesh.numberofvertices)) 501 )).T 371 502 bamg_mesh.Triangles = np.hstack((md.mesh.elements, np.ones((md.mesh.numberofelements, 1)))) 372 503 … … 374 505 raise TypeError("bamg error message: rifts not supported yet. Do meshprocessrift AFTER bamg") 375 506 #}}} 376 # Bamg Options {{{507 # Bamg options {{{ 377 508 bamg_options['Crack'] = options.getfieldvalue('Crack', 0) 378 509 bamg_options['anisomax'] = options.getfieldvalue('anisomax', 10.**18) … … 402 533 #}}} 403 534 404 # call Bamg535 # Call Bamg 405 536 bamgmesh_out, bamggeom_out = BamgMesher(bamg_mesh.__dict__, bamg_geometry.__dict__, bamg_options) 406 537 407 # plug results onto model538 # Plug results onto model 408 539 if options.getfieldvalue('vertical', 0): 409 540 md.mesh = mesh2dvertical() … … 415 546 md.mesh.segmentmarkers = bamgmesh_out['IssmSegments'][:, 3].astype(int) 416 547 417 # Fill in rest of fields:548 # Fill in rest of fields 418 549 md.mesh.numberofelements = np.size(md.mesh.elements, axis=0) 419 550 md.mesh.numberofvertices = np.size(md.mesh.x) 420 551 md.mesh.numberofedges = np.size(md.mesh.edges, axis=0) 421 md.mesh.vertexonboundary = np.zeros(md.mesh.numberofvertices, bool) 422 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = True 423 424 #Now, build the connectivity tables for this mesh. Doubled in matlab for some reason 425 md.mesh.vertexonboundary = np.zeros(md.mesh.numberofvertices, ) 552 md.mesh.vertexonboundary = np.zeros(md.mesh.numberofvertices, int) 426 553 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = 1 427 554 … … 437 564 md.mesh.segmentmarkers = bamgmesh_out['IssmSegments'][:, 3].astype(int) 438 565 439 # Fill in rest of fields:566 # Fill in rest of fields 440 567 md.mesh.numberofelements = np.size(md.mesh.elements, axis=0) 441 568 md.mesh.numberofvertices = np.size(md.mesh.x) 442 569 md.mesh.numberofedges = np.size(md.mesh.edges, axis=0) 443 md.mesh.vertexonboundary = np.zeros(md.mesh.numberofvertices, bool)444 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = True570 md.mesh.vertexonboundary = np.zeros(md.mesh.numberofvertices, int) 571 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = 1 445 572 446 573 else: … … 453 580 md.mesh.segmentmarkers = bamgmesh_out['IssmSegments'][:, 3].astype(int) 454 581 455 # Fill in rest of fields:582 # Fill in rest of fields 456 583 md.mesh.numberofelements = np.size(md.mesh.elements, axis=0) 457 584 md.mesh.numberofvertices = np.size(md.mesh.x) 458 585 md.mesh.numberofedges = np.size(md.mesh.edges, axis=0) 459 md.mesh.vertexonboundary = np.zeros(md.mesh.numberofvertices, bool)460 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = True461 462 # Bamg private fields586 md.mesh.vertexonboundary = np.zeros(md.mesh.numberofvertices, int) 587 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = 1 588 589 # Bamg private fields 463 590 md.private.bamg = OrderedDict() 464 591 md.private.bamg['mesh'] = bamgmesh(bamgmesh_out) … … 476 603 477 604 def processgeometry(geom, tol, outline): # {{{ 478 raise RuntimeError("bamg.py / processgeometry is not complete.") 479 #Deal with edges 605 raise RuntimeError("bamg.py::processgeometry is not complete.") 606 607 # Deal with edges 480 608 print("Checking Edge crossing...") 481 609 i = 0 482 610 while (i < np.size(geom.Edges, axis=0)): 483 # edge counter611 # Edge counter 484 612 i += 1 485 613 486 # Get coordinates614 # Get coordinates 487 615 x1 = geom.Vertices[geom.Edges[i, 0], 0] 488 616 y1 = geom.Vertices[geom.Edges[i, 0], 1] … … 491 619 color1 = geom.Edges[i, 2] 492 620 493 j = i #test edges located AFTER i only621 j = i # Test edges located AFTER i only 494 622 while (j < np.size(geom.Edges, axis=0)): 495 # edge counter623 # Edge counter 496 624 j += 1 497 625 498 # Skip if the two edges already have a vertex in common626 # Skip if the two edges already have a vertex in common 499 627 if any(m.ismember(geom.Edges[i, 0:2], geom.Edges[j, 0:2])): 500 628 continue 501 629 502 # Get coordinates630 # Get coordinates 503 631 x3 = geom.Vertices[geom.Edges[j, 0], 0] 504 632 y3 = geom.Vertices[geom.Edges[j, 0], 1] … … 507 635 color2 = geom.Edges[j, 2] 508 636 509 # Check if the two edges are crossing one another637 # Check if the two edges are crossing one another 510 638 if SegIntersect(np.array([[x1, y1], [x2, y2]]), np.array([[x3, y3], [x4, y4]])): 511 639 512 # Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html)640 # Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html) 513 641 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]]))) 514 642 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]]))) 515 643 516 # Add vertex to the list of vertices644 # Add vertex to the list of vertices 517 645 geom.Vertices = np.vstack((geom.Vertices, [x, y, min(color1, color2)])) 518 646 id = np.size(geom.Vertices, axis=0) 519 647 520 # Update edges i and j648 # Update edges i and j 521 649 edgei = geom.Edges[i, :].copy() 522 650 edgej = geom.Edges[j, :].copy() … … 526 654 geom.Edges = np.vstack((geom.Edges, [id, edgej(1), edgej(2)])) 527 655 528 # update current edge second tip656 # Update current edge second tip 529 657 x2 = x 530 658 y2 = y 531 659 532 # Check point outside660 # Check point outside 533 661 print("Checking for points outside the domain...") 534 662 i = 0 535 663 num = 0 536 664 while (i < np.size(geom.Vertices, axis=0)): 537 # vertex counter665 # Vertex counter 538 666 i += 1 539 667 540 # Get coordinates668 # Get coordinates 541 669 x = geom.Vertices[i, 0] 542 670 y = geom.Vertices[i, 1] 543 671 color = geom.Vertices[i, 2] 544 672 545 # Check that the point is inside the domain673 # Check that the point is inside the domain 546 674 if color != 1 and not ContourToNodes(x, y, outline[0], 1): 547 # Remove points from list of Vertices675 # Remove points from list of Vertices 548 676 num += 1 549 677 geom.Vertices[i, :] = [] 550 678 551 # update edges679 # Update edges 552 680 posedges = np.nonzero(geom.Edges == i) 553 681 geom.Edges[posedges[0], :] = [] … … 555 683 geom.Edges[posedges] = geom.Edges[posedges] - 1 556 684 557 # update counter685 # Update counter 558 686 i -= 1 559 687 … … 564 692 %Check point spacing 565 693 if ~isnan(tol), 566 disp('Checking point spacing...')694 print('Checking point spacing...') 567 695 i = 0 568 696 while (i < size(geom.Vertices, 1)), … … 608 736 """ 609 737 return geom 610 # 738 #}}} -
issm/trunk-jpl/src/m/mesh/bamgflowband.py
r24260 r25455 7 7 8 8 def bamgflowband(md, x, surf, base, *args): 9 """ 10 BAMGFLOWBAND - create flowband mesh with bamg 9 """BAMGFLOWBAND - create flowband mesh with bamg 11 10 12 11 Usage: -
issm/trunk-jpl/src/m/mesh/findsegments.m
r13009 r25455 2 2 %FINDSEGMENTS - build segments model field 3 3 % 4 % Usage: 5 % segments=findsegments(md,varargin); 6 % 4 7 % Optional inputs: 5 8 % 'mesh.elementconnectivity' 6 %7 % Usage:8 % segments=findsegments(md,varargin);9 9 10 10 %get options … … 14 14 mesh.elementconnectivity=getfieldvalue(options,'mesh.elementconnectivity',md.mesh.elementconnectivity); 15 15 16 %Now, build the connectivity tables for this mesh if not correc lty done16 %Now, build the connectivity tables for this mesh if not correctly done 17 17 if size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements, 18 18 if exist(options,'mesh.elementconnectivity'), 19 error(' 19 error('''mesh.elementconnectivity'' option does not have thge right size.'); 20 20 else 21 21 mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity); … … 39 39 els2=mesh.elementconnectivity(el1,find(mesh.elementconnectivity(el1,:))); 40 40 41 %el1 is connected to 2 other elements 41 %get nodes of 'el1' 42 nods1=md.mesh.elements(el1,:); 43 44 %'el1' is connected to 2 other elements 42 45 if length(els2)>1, 43 44 %get nodes of el145 nods1=md.mesh.elements(el1,:);46 46 47 47 %find the common vertices to the two elements connected to el1 (1 or 2) … … 55 55 ord1=find(nods1(1)==md.mesh.elements(el1,:)); 56 56 ord2=find(nods1(2)==md.mesh.elements(el1,:)); 57 57 58 if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ), 58 59 temp=segments(count,1); … … 60 61 segments(count,2)=temp; 61 62 end 63 disp(segments(count,1:2)) 62 64 segments(count,1:2)=fliplr(segments(count,1:2)); 65 disp(segments) 63 66 count=count+1; 64 67 65 % el1is connected to only one element68 %'el1' is connected to only one element 66 69 else 67 %get nodes of el168 nods1=md.mesh.elements(el1,:);69 70 70 %find the vertex the el1 to not share with els271 %find the vertex the 'el1' does not share with 'els2' 71 72 flag=setdiff(nods1,md.mesh.elements(els2,:)); 72 73 -
issm/trunk-jpl/src/m/mesh/meshconvert.py
r24213 r25455 1 1 import numpy as np 2 3 from BamgConvertMesh import BamgConvertMesh 4 from bamggeom import bamggeom 5 from bamgmesh import bamgmesh 2 6 from collections import OrderedDict 3 from BamgConvertMesh import BamgConvertMesh4 7 from mesh2d import mesh2d 5 from bamgmesh import bamgmesh6 from bamggeom import bamggeom7 8 8 9 9 10 def meshconvert(md, *args): 10 """ 11 CONVERTMESH - convert mesh to bamg mesh 11 """CONVERTMESH - convert mesh to bamg mesh 12 12 13 14 15 13 Usage: 14 md = meshconvert(md) 15 md = meshconvert(md, index, x, y) 16 16 """ 17 17 18 if not len(args) == 0 and not len(args) == 3: 18 nargs = len(args) 19 20 if not nargs == 0 and not nargs == 3: 19 21 raise TypeError("meshconvert error message: bad usage") 20 22 21 if not len(args):23 if not nargs: 22 24 index = md.mesh.elements 23 25 x = md.mesh.x … … 47 49 md.mesh.numberofvertices = np.size(md.mesh.x) 48 50 md.mesh.numberofedges = np.size(md.mesh.edges, axis=0) 49 md.mesh.vertexonboundary = np.zeros(md.mesh.numberofvertices, bool)50 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = True51 md.mesh.vertexonboundary = np.zeros(md.mesh.numberofvertices, int) 52 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = 1 51 53 52 54 return md -
issm/trunk-jpl/src/m/mesh/modelmerge3d.m
r25000 r25455 8 8 options=pairoptions(varargin{:}); 9 9 10 tolerance=getfieldvalue(options,'tolerance',1 0^-5);10 tolerance=getfieldvalue(options,'tolerance',1e-4); 11 11 12 12 md=model(); … … 16 16 md.private=md1.private; 17 17 18 %some initializat oin:18 %some initialization: 19 19 elements1=md1.mesh.elements; 20 20 x1=md1.mesh.x; … … 34 34 elements2=elements2+nods1; 35 35 36 %go into the vertices on boundary of mesh 1, and figure out which ones are common to mesh2: 37 verticesonboundary=find(md1.mesh.vertexonboundary); 36 %go into the vertices on boundary of mesh 1 and figure out which ones are common with mesh2: 37 verticesonboundary=find(md1.mesh.vertexonboundary); 38 38 39 for i=1:length(verticesonboundary), 39 node1=verticesonboundary(i); xnode1=x1(node1); ynode1=y1(node1); znode1=z1(node1); 40 %is there another node with these coordinates in mesh2? 41 ind=find(sqrt(((x2-xnode1).^2+(y2-ynode1).^2)+(z2-znode1).^2)<tolerance); 40 node1=verticesonboundary(i); 41 xnode1=x1(node1); 42 ynode1=y1(node1); 43 znode1=z1(node1); 44 45 %is there another node with these coordinates in mesh 2? 46 ind=find(sqrt((x2-xnode1).^2+(y2-ynode1).^2+(z2-znode1).^2)<tolerance); 42 47 if length(ind)>1, 43 48 disp('should reduce the tolerance, several vertices picked up!'); … … 47 52 y2(ind)=NaN; 48 53 z2(ind)=NaN; 49 pos=find(elements2==(ind+nods1)); elements2(pos)=node1; 54 pos=find(elements2==(ind+nods1)); 55 elements2(pos)=node1; 50 56 end 51 57 end 58 %go through elements2 and drop counter on each vertex that is above the x2 and y2 vertices being dropped: 59 indices_nan=isnan(x2); 60 while(~isempty(indices_nan)), 61 % Use the index of the first instance of 'nan' value to remove that element from 'x2', 'y2', and 'z2' 62 index_nan=indices_nan(1); 63 pos=find(elements2>(index_nan+nods1)); 64 elements2(pos)=elements2(pos)-1; 65 x2(index_nan)=[]; 66 y2(index_nan)=[]; 67 z2(index_nan)=[]; 52 68 53 %go through elements2 and drop counter on each vertex that is above the x2 and y2 vertices being dropped: 54 while( ~isempty(find(isnan(x2)))), 55 for i=1:length(x2), 56 if isnan(x2(i)), 57 pos=find(elements2>(i+nods1)); 58 elements2(pos)=elements2(pos)-1; 59 x2(i)=[]; 60 y2(i)=[]; 61 z2(i)=[]; 62 break; 63 end 64 end 69 % Check again in 'x2' for instances of 'nan' 70 indices_nan=find(isnan(x2)); 65 71 end 66 72 … … 83 89 %connectivities: 84 90 md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices); 91 % disp(md.mesh.vertexconnectivity) 85 92 md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity); 93 % disp(md.mesh.elementconnectivity) 86 94 87 95 %find segments: … … 91 99 md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); 92 100 md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1; 101 disp(md.mesh.vertexonboundary) 102 pause 93 103 94 104 %some checks: -
issm/trunk-jpl/src/m/mesh/rifts/meshprocessoutsiderifts.py
r24213 r25455 1 1 import numpy as np 2 3 from ContourToMesh import ContourToMesh 2 4 from ElementsFromEdge import ElementsFromEdge 3 5 import MatlabFuncs as m 4 from ContourToMesh import ContourToMesh5 6 6 7 7 8 def meshprocessoutsiderifts(md, domainoutline): 8 """ 9 MESHPROCESSOUTSIDERIFTS - process rifts when they touch the domain outline 9 """MESHPROCESSOUTSIDERIFTS - process rifts when they touch the domain outline 10 10 11 Usage: 12 md = meshprocessoutsiderifts(md, domain) 13 11 Usage: 12 md = meshprocessoutsiderifts(md, domain) 14 13 """ 15 14 … … 53 52 elements = np.concatenate((elements, nextelement)) 54 53 #new B: 55 B = md.mesh.elements[nextelement - 1, np.nonzero(np.logical_not(m.ismember(md.mesh.elements[nextelement - 1, :], np.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]))))[0]] 56 55 57 56 #take the list of elements on one side of the rift that connect to the tip, … … 64 63 #replace tip in elements 65 64 newelements = md.mesh.elements[elements - 1, :] 66 pos = np.nonzero(newelements == tip) 65 pos = np.nonzero(newelements == tip)[0] 67 66 newelements[pos] = num 68 67 md.mesh.elements[elements - 1, :] = newelements … … 81 80 md.mesh.numberofelements = np.size(md.mesh.elements, axis=0) 82 81 md.mesh.numberofvertices = np.size(md.mesh.x) 83 md.mesh.vertexonboundary = np.zeros(np.size(md.mesh.x), bool)84 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = True82 md.mesh.vertexonboundary = np.zeros(np.size(md.mesh.x), int) 83 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = 1 85 84 md.rifts.numrifts = np.length(md.rifts.riftstruct) 86 85 … … 88 87 89 88 90 def isconnected(elements, A, B): # {{{ 91 """ 92 ISCONNECTED: are two nodes connected by a triangulation? 89 def isconnected(elements, A, B): #{{{ 90 """ISCONNECTED: are two nodes connected by a triangulation? 93 91 94 Usage: flag = isconnected(elements, A, B)95 92 Usage: 93 flag = isconnected(elements, A, B) 96 94 """ 97 95 … … 103 101 104 102 return flag 105 # 103 #}}} -
issm/trunk-jpl/src/m/mesh/rifts/meshprocessrifts.py
r24256 r25455 1 1 import numpy as np 2 3 from ContourToMesh import ContourToMesh 4 from GetAreas import GetAreas 5 from meshprocessoutsiderifts import meshprocessoutsiderifts 2 6 from ProcessRifts import ProcessRifts 3 from ContourToMesh import ContourToMesh4 from meshprocessoutsiderifts import meshprocessoutsiderifts5 from GetAreas import GetAreas6 7 7 8 8 9 def meshprocessrifts(md, domainoutline): 9 """ 10 MESHPROCESSRIFTS - process mesh when rifts are present 10 """MESHPROCESSRIFTS - process mesh when rifts are present 11 11 12 13 14 12 split rifts inside mesh (rifts are defined by presence of 13 segments inside the domain outline) 14 if domain outline is provided, check for rifts that could touch it, and open them up. 15 15 16 17 16 Usage: 17 md = meshprocessrifts(md, domainoutline) 18 18 19 Ex: 20 md = meshprocessrifts(md, 'DomainOutline.exp') 21 19 Example: 20 md = meshprocessrifts(md, 'DomainOutline.exp') 22 21 """ 23 22 24 # Call MEX file23 # Call Python module 25 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) 26 25 md.mesh.elements = md.mesh.elements.astype(int) … … 35 34 md.mesh.numberofelements = np.size(md.mesh.elements, axis=0) 36 35 md.mesh.numberofvertices = np.size(md.mesh.x) 37 md.mesh.vertexonboundary = np.zeros(np.size(md.mesh.x), bool)38 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = True36 md.mesh.vertexonboundary = np.zeros(np.size(md.mesh.x), int) 37 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = 1 39 38 40 39 #get coordinates of rift tips -
issm/trunk-jpl/src/m/mesh/squaremesh.py
r24213 r25455 1 1 import numpy as np 2 from NodeConnectivity import NodeConnectivity 2 3 3 from ElementConnectivity import ElementConnectivity 4 4 from mesh2d import mesh2d 5 from NodeConnectivity import NodeConnectivity 5 6 6 7 7 8 def squaremesh(md, Lx, Ly, nx, ny): 8 """ 9 SQUAREMESH - create a structured square mesh 9 """SQUAREMESH - create a structured square mesh 10 10 11 12 13 14 11 This script will generate a structured square mesh 12 Lx and Ly are the dimension of the domain (in meters) 13 nx anx ny are the number of nodes in the x and y direction 14 The coordinates x and y returned are in meters. 15 15 16 17 16 Usage: 17 [md] = squaremesh(md, Lx, Ly, nx, ny) 18 18 """ 19 19 … … 24 24 #initialization 25 25 index = np.zeros((nel, 3), int) 26 x = np.zeros((nx * ny ))27 y = np.zeros((nx * ny ))26 x = np.zeros((nx * ny, )) 27 y = np.zeros((nx * ny, )) 28 28 29 29 #create coordinates … … 63 63 md.mesh.y = y 64 64 md.mesh.numberofvertices = nods 65 md.mesh.vertexonboundary = np.zeros( (nods), bool)66 md.mesh.vertexonboundary[segments[:, 0:2] - 1] = True65 md.mesh.vertexonboundary = np.zeros(nods, int) 66 md.mesh.vertexonboundary[segments[:, 0:2] - 1] = 1 67 67 68 68 #plug elements … … 72 72 73 73 #Now, build the connectivity tables for this mesh. 74 md.mesh.vertexconnectivity = NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices) [0]75 md.mesh.elementconnectivity = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity) [0]74 md.mesh.vertexconnectivity = NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices) 75 md.mesh.elementconnectivity = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity) 76 76 77 77 return md -
issm/trunk-jpl/src/m/mesh/triangle.py
r24213 r25455 1 1 import os.path 2 2 3 import numpy as np 4 5 from ElementConnectivity import ElementConnectivity 3 6 from mesh2d import mesh2d 4 7 from NodeConnectivity import NodeConnectivity 5 from ElementConnectivity import ElementConnectivity6 8 from Triangle_python import Triangle_python 7 9 8 10 9 11 def triangle(md, domainname, *args): 10 """ 11 TRIANGLE - create model mesh using the triangle package 12 """TRIANGLE - create model mesh using the triangle package 12 13 13 14 15 16 14 This routine creates a model mesh using Triangle and a domain outline, to within a certain resolution 15 where md is a @model object, domainname is the name of an Argus domain outline file, 16 and resolution is a characteristic length for the mesh (same unit as the domain outline 17 unit). Riftname is an optional argument (Argus domain outline) describing rifts. 17 18 18 Usage: 19 md = triangle(md, domainname, resolution) 20 or md = triangle(md, domainname, resolution, riftname) 19 Usage: 20 md = triangle(md, domainname, resolution) 21 OR 22 md = triangle(md, domainname, resolution, riftname) 21 23 22 23 24 24 Examples: 25 md = triangle(md, 'DomainOutline.exp', 1000) 26 md = triangle(md, 'DomainOutline.exp', 1000, 'Rifts.exp') 25 27 """ 26 28 … … 45 47 return None 46 48 47 area = resolution **249 area = resolution ** 2 48 50 49 51 #Check that file exist (this is a very very common mistake) … … 61 63 md.mesh.numberofelements = np.size(md.mesh.elements, axis=0) 62 64 md.mesh.numberofvertices = np.size(md.mesh.x) 63 md.mesh.vertexonboundary = np.zeros(md.mesh.numberofvertices, bool)64 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = True65 md.mesh.vertexonboundary = np.zeros(md.mesh.numberofvertices, int) 66 md.mesh.vertexonboundary[md.mesh.segments[:, 0:2] - 1] = 1 65 67 66 68 #Now, build the connectivity tables for this mesh. 67 md.mesh.vertexconnectivity = NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices) [0]68 md.mesh.elementconnectivity = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity) [0]69 md.mesh.vertexconnectivity = NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices) 70 md.mesh.elementconnectivity = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity) 69 71 70 72 return md -
issm/trunk-jpl/src/m/modules/BamgMesher.py
r24213 r25455 3 3 4 4 def BamgMesher(bamgmesh, bamggeom, bamgoptions): 5 """ 6 BAMGMESHER 7 8 Usage: 9 bamgmesh, bamggeom = BamgMesher(bamgmesh, bamggeom, bamgoptions) 5 """BAMGMESHER 10 6 11 7 bamgmesh: input bamg mesh 12 8 bamggeom: input bamg geometry for the mesh 13 9 bamgoptions: options for the bamg mesh 10 11 Usage: 12 bamgmesh, bamggeom = BamgMesher(bamgmesh, bamggeom, bamgoptions) 14 13 """ 15 14 16 # Call mexmodule15 # Call module 17 16 bamgmesh, bamggeom = BamgMesher_python(bamgmesh, bamggeom, bamgoptions) 18 17 19 #return20 18 return bamgmesh, bamggeom -
issm/trunk-jpl/src/m/modules/ContourToNodes.py
r24213 r25455 3 3 4 4 def ContourToNodes(x, y, contourname, edgevalue): 5 """ 6 CONTOURTONODES - flags vertices inside contour 5 """CONTOURTONODES - flags vertices inside contour 7 6 8 Usage: 9 flags = ContourToNodes(x, y, contourname, edgevalue) 7 x, y: list of nodes 8 contourname: name of .exp/.shp file containing the contours, or resulting structure from call to expread/shpread 9 edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons 10 flags: vector of flags (0 or 1), of size nodes 10 11 11 x, y: list of nodes 12 contourname: name of .exp file containing the contours, or resulting structure from call to expread 13 edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons 14 flags: vector of flags (0 or 1), of size nodes 12 Usage: 13 flags = ContourToNodes(x, y, contourname, edgevalue) 15 14 """ 16 15 17 # Call mexmodule16 # Call Python module 18 17 flags = ContourToNodes_python(x, y, contourname, edgevalue) 19 18 20 #return21 19 return flags -
issm/trunk-jpl/src/m/modules/ElementConnectivity.py
r24213 r25455 3 3 4 4 def ElementConnectivity(elements, nodeconnectivity): 5 """ELEMENTCONNECTIVITY - Build element connectivity using node connectivity and elements 6 7 Usage: 8 elementconnectivity = ElementConnectivity(elements, nodeconnectivity) 5 9 """ 6 ELEMENTCONNECTIVITY - Build element connectivity using node connectivity and elements 7 8 Usage: 9 elementconnectivity = ElementConnectivity(elements, nodeconnectivity) 10 """ 11 #Call mex module 10 11 # Call Python module 12 12 elementconnectivity = ElementConnectivity_python(elements, nodeconnectivity) 13 13 14 #Return 15 return elementconnectivity 14 return elementconnectivity[0] # NOTE: Value returned from wrapper function is a tuple, the first element of which being the result we actually want -
issm/trunk-jpl/src/m/modules/ExpToLevelSet.py
r25163 r25455 2 2 from shpread import shpread 3 3 4 4 5 def ExpToLevelSet(x, y, contourname): #{{{ 5 ''' 6 EXPTOLEVELSET - Determine levelset distance between a contour and a cloud 7 of points 6 """EXPTOLEVELSET - Determine levelset distance between a contour and a 7 cloud of points 8 8 9 10 9 Usage: 10 distance = ExpToLevelSet(x, y, contourname) 11 11 12 13 14 15 12 x, y: cloud point 13 contourname: name of .exp file containing the contours 14 distance: distance vector representing a levelset where the 0 15 level is one of the contour segments 16 16 17 18 17 Example: 18 distance = ExpToLevelSet(md.mesh.x, md.mesh.y, 'Contour.exp') 19 19 20 21 22 23 '''20 TODO: 21 - Need to compile Python version of ExpToLevelSet_matlab for this 22 to work as intended (see src/m/modules/ExpToLevelSet.m) 23 """ 24 24 25 25 if isinstance(contourname, basestring): -
issm/trunk-jpl/src/m/modules/InterpFromMesh2d.m
r20875 r25455 4 4 % Usage: 5 5 % data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime); 6 % or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value); 7 % or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value,contourname); 6 % OR 7 % data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value); 8 % OR 9 % data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value,contourname); 8 10 % 11 % index: index of the mesh where data is defined 9 12 % x,y: coordinates of the nodes where data is defined 10 % index: index of the mesh where data is defined11 13 % data: vector holding the data to be interpolated onto the points 12 14 % x_prime,y_prime: coordinates of the mesh vertices onto which we interpolate … … 32 34 data_prime=InterpFromMesh2d_matlab(varargin{1},varargin{2},varargin{3},varargin{4},varargin{5},varargin{6},varargin{7},varargin{8}); 33 35 otherwise 36 % NOTE: Should never get here because of previous check 34 37 error('InterpFromMesh2d not supported'); 35 38 end -
issm/trunk-jpl/src/m/modules/InterpFromMeshToMesh2d.py
r24213 r25455 3 3 4 4 def InterpFromMeshToMesh2d(*args): 5 """ 6 INTERPFROMMESHTOMESH2D - Interpolation from a 2d triangular mesh onto a list of points 5 """INTERPFROMMESHTOMESH2D - Interpolation from a 2d triangular mesh onto a list of points 7 6 8 Usage: 9 data_interp = InterpFromMeshToMesh2d(index, x, y, data, x_interp, y_interp) 10 or data_interp = InterpFromMeshToMesh2d(index, x, y, data, x_interp, y_interp, OPTIONS) 7 Usage: 8 data_interp = InterpFromMeshToMesh2d(index, x, y, data, x_interp, y_interp) 9 OR 10 data_interp = InterpFromMeshToMesh2d(index, x, y, data, x_interp, y_interp, OPTIONS) 11 11 12 index:index of the mesh where data is defined (e.g. md.mesh.elements)13 x, y:coordinates of the nodes where data is defined14 data:matrix holding the data to be interpolated onto the mesh (one column per field)15 x_interp, y_interp:coordinates of the points onto which we interpolate16 data_interp:vector of mesh interpolated data17 18 default:default value if point is outsite of triangulation (instead of linear interpolation)12 index: index of the mesh where data is defined (e.g. md.mesh.elements) 13 x, y: coordinates of the nodes where data is defined 14 data: matrix holding the data to be interpolated onto the mesh (one column per field) 15 x_interp, y_interp: coordinates of the points onto which we interpolate 16 data_interp: vector of mesh interpolated data 17 Available options: 18 default: default value if point is outsite of triangulation (instead of linear interpolation) 19 19 20 20 Example: 21 22 23 21 load('temperature.mat') 22 md.initialization.temperature = InterpFromMeshToMesh2d(index, x, y, temperature, md.mesh.x, md.mesh.y) 23 md.initialization.temperature = InterpFromMeshToMesh2d(index, x, y, temperature, md.mesh.x, md.mesh.y, 'default', 253) 24 24 """ 25 # Call mex module 25 26 # Check usage 27 nargs = len(args) 28 if nargs != 6 and nargs != 8: 29 print(InterpFromMeshToMesh2d.__doc__) 30 raise Exception('Wrong usage (see above)') 31 32 # Call Python module 26 33 data_interp = InterpFromMeshToMesh2d_python(*args) 27 # Return 28 return data_interp 34 35 return data_interp[0] # NOTE: Value returned from wrapper function is a tuple, the first element of which being the result we actually want -
issm/trunk-jpl/src/m/modules/InterpFromMeshToMesh3d.py
r24213 r25455 3 3 4 4 def InterpFromMeshToMesh3d(index, x, y, z, data, x_prime, y_prime, z_prime, default_value): 5 """INTERPFROMMESHTOMESH3D - Interpolation from a 3d hexahedron mesh onto a list of points 6 7 Usage: 8 index: index of the mesh where data is defined 9 x, y, z: coordinates of the nodes where data is defined 10 data: matrix holding the data to be interpolated onto the mesh 11 x_prime, y_prime, z_prime: coordinates of the points onto which we interpolate 12 default_value: default value if no data is found (holes) 13 data_prime: vector of mesh interpolated data 14 15 Example: 16 load('temperature.mat') 17 md.initialization.temperature = InterpFromMeshToMesh3d(index, x, y, z, temperature, md.mesh.x, md.mesh.y, md.mesh.z, 253) 5 18 """ 6 INTERPFROMMESHTOMESH3D - Interpolation from a 3d hexahedron mesh onto a list of points7 19 8 Usage: 9 index: index of the mesh where data is defined 10 x, y, z: coordinates of the nodes where data is defined 11 data: matrix holding the data to be interpolated onto the mesh 12 x_prime, y_prime, z_prime: coordinates of the points onto which we interpolate 13 default_value: default value if no data is found (holes) 14 data_prime: vector of mesh interpolated data 20 # Check usage 21 nargs = len(args) 22 if nargs != 9: 23 print(InterpFromMeshToMesh3d.__doc__) 24 raise Exception('Wrong usage (see above)') 15 25 16 Example: 17 load('temperature.mat') 18 md.initialization.temperature = InterpFromMeshToMesh3d(index, x, y, z, temperature, md.mesh.x, md.mesh.y, md.mesh.z, 253) 19 """ 20 # Call mex module 26 # Call Python module 21 27 data_prime = InterpFromMeshToMesh3d_python(index, x, y, z, data, x_prime, y_prime, z_prime, default_value) 22 28 23 # Return24 29 return data_prime -
issm/trunk-jpl/src/m/modules/NodeConnectivity.py
r24213 r25455 3 3 4 4 def NodeConnectivity(elements, numnodes): 5 """NODECONNECTIVITY - Build node connectivity from elements 6 7 Usage: 8 connectivity = NodeConnectivity(elements, numnodes) 5 9 """ 6 NODECONNECTIVITY - Build node connectivity from elements7 10 8 Usage: 9 connectivity = NodeConnectivity(elements, numnodes) 10 """ 11 # Call mex module 11 # Call Python module 12 12 connectivity = NodeConnectivity_python(elements, numnodes) 13 13 14 # Return 15 return connectivity 14 return connectivity[0] # NOTE: Value returned from wrapper function is a tuple, the first element of which being the result we actually want -
issm/trunk-jpl/src/m/parameterization/contourenvelope.py
r24213 r25455 9 9 10 10 def contourenvelope(md, *args): 11 """ 12 CONTOURENVELOPE - build a set of segments enveloping a contour .exp 11 """CONTOURENVELOPE - build a set of segments enveloping a contour .exp 13 12 14 15 13 Usage: 14 segments = contourenvelope(md, varargin) 16 15 17 18 19 16 Example: 17 segments = contourenvelope(md, 'Stream.exp') 18 segments = contourenvelope(md) 20 19 """ 21 20 … … 41 40 #Computing connectivity 42 41 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]42 md.mesh.vertexconnectivity = NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices) 44 43 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]44 md.mesh.elementconnectivity = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity) 46 45 47 46 #get nodes inside profile -
issm/trunk-jpl/src/m/partition/adjacency.py
r24254 r25455 1 1 import numpy as np 2 3 from GetAreas import * 2 4 import MatlabFuncs as m 3 5 from NodeConnectivity import * 4 from GetAreas import *5 6 6 7 7 8 def adjacency(md): 8 #ADJACENCY - compute adjacency matrix, list of vertices and list of weights. 9 # 10 # function to create the adjacency matrix from the connectivity table. 11 # 12 # the required output is: 13 # md.adj_mat (double [sparse nv x nv], vertex adjacency matrix) 14 # md.qmu.vertex_weight (double [nv], vertex weights) 9 """ADJACENCY - compute adjacency matrix, list of vertices and list of weights. 10 11 function to create the adjacency matrix from the connectivity table. 12 13 the required output is: 14 md.adj_mat (double [sparse nv x nv], vertex adjacency matrix) 15 md.qmu.vertex_weight (double [nv], vertex weights) 16 """ 15 17 16 18 indi = np.array([md.mesh.elements[:, 0], md.mesh.elements[:, 1], md.mesh.elements[:, 2]]) -
issm/trunk-jpl/src/m/plot/processmesh.py
r25163 r25455 4 4 5 5 def processmesh(md, data, options): 6 ''' 7 PROCESSMESH - process mesh to be plotted 6 """PROCESSMESH - process mesh to be plotted 8 7 9 8 Usage: … … 16 15 - Test that output of delaunay matches output of delaunay in MATLAB (see 17 16 src/m/plot/processmesh.m) 18 '''17 """ 19 18 20 19 #some checks -
issm/trunk-jpl/src/m/qmu/dakota_in_data.py
r25163 r25455 57 57 58 58 if strcmpi(params.analysis_driver, 'matlab') and params.analysis_components == '': 59 [pathstr, name, ext]= fileparts(filei)59 pathstr, name, ext = fileparts(filei) 60 60 params.analysis_components = fullfile(pathstr, name + '.py') 61 61 -
issm/trunk-jpl/src/m/qmu/dakota_in_write.py
r24870 r25455 56 56 filei = str(eval(input('Dakota input file to write? '))) 57 57 58 [pathstr, name, ext]= fileparts(filei)58 pathstr, name, ext = fileparts(filei) 59 59 if len(ext) == 0: 60 60 # fileparts only considers '.in' to be the extension, not '.qmu.in' … … 266 266 param_write(fidi, '\t ', 'processors_per_evaluation', '=', '\n', params) 267 267 if len(params.analysis_components) != 0: 268 [pathstr, name, ext]= fileparts(params.analysis_components)268 pathstr, name, ext = fileparts(params.analysis_components) 269 269 if ext != '': 270 270 ext = '.py' -
issm/trunk-jpl/src/m/qmu/helpers.py
r25065 r25455 6 6 7 7 class struct(object): 8 '''An empty struct that can be assigned arbitrary attributes'''8 """An empty struct that can be assigned arbitrary attributes""" 9 9 pass 10 10 11 11 12 12 class Lstruct(list): 13 '''13 """ 14 14 An empty struct that can be assigned arbitrary attributes but can also be 15 15 accesed as a list. Eg. x.y = 'hello', x[:] = ['w', 'o', 'r', 'l', 'd'] … … 46 46 Sources: 47 47 -https://github.com/Vectorized/Python-Attribute-List 48 '''48 """ 49 49 50 50 def __new__(self, *args, **kwargs): … … 64 64 65 65 class OrderedStruct(object): 66 '''66 """ 67 67 A form of dictionary-like structure that maintains the ordering in which 68 68 its fields/attributes and their corresponding values were added. … … 113 113 Note: to access internal fields use dir(x) (input fields will be included, 114 114 but are not technically internals) 115 '''115 """ 116 116 117 117 def __init__(self, *args): 118 '''118 """ 119 119 Provided either nothing or a series of strings, construct a structure 120 120 that will, when accessed as a list, return its fields in the same order 121 121 in which they were provided 122 '''122 """ 123 123 124 124 # keys and values … … 187 187 188 188 def __copy__(self): 189 '''189 """ 190 190 shallow copy, hard copies of trivial attributes, 191 191 references to structures like lists/OrderedDicts 192 192 unless redefined as an entirely different structure 193 '''193 """ 194 194 newInstance = type(self)() 195 195 for k, v in list(self.items()): … … 198 198 199 199 def __deepcopy__(self, memo=None): 200 '''200 """ 201 201 hard copy of all attributes 202 202 same thing but call deepcopy recursively … … 204 204 (see https://docs.python.org/2/library/copy.html #copy.deepcopy ) 205 205 but will generally work in this case 206 '''206 """ 207 207 newInstance = type(self)() 208 208 for k, v in list(self.items()): … … 232 232 233 233 def isempty(x): 234 '''234 """ 235 235 returns true if object is +/-infinity, NaN, None, '', has length 0, or is 236 236 an array/matrix composed only of such components (includes mixtures of 237 237 "empty" types) 238 '''238 """ 239 239 240 240 if type(x) in [list, np.ndarray, tuple]: … … 270 270 271 271 def fieldnames(x, ignore_internals=True): 272 '''272 """ 273 273 returns a list of fields of x 274 274 ignore_internals ignores all fieldnames starting with '_' and is True by 275 275 default 276 '''276 """ 277 277 result = list(vars(x).keys()) 278 278 … … 284 284 285 285 def isfield(x, y, ignore_internals=True): 286 '''286 """ 287 287 is y is a field of x? 288 288 ignore_internals ignores all fieldnames starting with '_' and is True by 289 289 default 290 '''290 """ 291 291 return str(y) in fieldnames(x, ignore_internals) 292 292 293 293 294 294 def fileparts(x): 295 '''295 """ 296 296 given: "path/path/.../file_name.ext" 297 297 returns: [path, file_name, ext] (list of strings) 298 '''298 """ 299 299 try: 300 300 a = x[:x.rindex('/')] #path … … 311 311 312 312 def fullfile(*args): 313 '''313 """ 314 314 usage: 315 315 fullfile(path, path, ... , file_name + ext) … … 322 322 as final arguments ('file.doc') or ('file' + '.doc') will work 323 323 ('final', '.doc'), and the like, will not (you'd get 'final/.doc') 324 '''324 """ 325 325 result = str(args[0]) 326 326 for i in range(len(args[1:])): … … 334 334 335 335 def findline(fidi, s): 336 '''336 """ 337 337 returns full first line containing s (as a string), or None 338 338 … … 340 340 use str(findline(f, s)).strip() to remove these, str() in case result is 341 341 None 342 '''342 """ 343 343 for line in fidi: 344 344 if s in line: … … 348 348 349 349 def empty_nd_list(shape, filler=0., as_numpy_ndarray=False): 350 '''350 """ 351 351 returns a python list of the size/shape given (shape must be int or tuple) 352 352 the list will be filled with the optional second argument … … 363 363 empty_nd_list((5, 5), 0.0) # returns a 5x5 matrix of 0.0's 364 364 empty_nd_list(5, None) # returns a 5 long array of NaN 365 '''365 """ 366 366 result = np.empty(shape) 367 367 result.fill(filler) -
issm/trunk-jpl/src/m/qmu/postqmu.py
r25163 r25455 1 1 from os import getpid, stat 2 2 from os.path import isfile 3 import shlex4 3 from subprocess import call 5 4 … … 62 61 # move all the individual function evalutations into zip files 63 62 if not md.qmu.isdakota: 64 subproc_args = shlex.split('zip -mq params.in.zip params.in.[1-9]*')63 subproc_args = 'zip -mq params.in.zip params.in.[1-9]*' 65 64 call(subproc_args, shell=True) 66 subproc_args = shlex.split('zip -mq results.out.zip results.out.[1-9]*')65 subproc_args = 'zip -mq results.out.zip results.out.[1-9]*' 67 66 call(subproc_args, shell=True) 68 subproc_args = shlex.split('zip -mq matlab.out.zip matlab*.out.[1-9]*')67 subproc_args = 'zip -mq matlab.out.zip matlab*.out.[1-9]*' 69 68 call(subproc_args, shell=True) 70 69 -
issm/trunk-jpl/src/m/shp/shpread.m
r25125 r25455 2 2 %SHPREAD - read a shape file and build a struct 3 3 % 4 % This routine reads a shape file .shp and builds a structure array 5 % containing the fields x and y corresponding to the coordinates, one for the 6 % filename of the shp file, for the density, for the nodes, and a field 7 % closed to indicate if the domain is closed. If this initial shapefile is 8 % point only, the fields closed and points are omitted. 9 % The first argument is the .shp file to be read and the second one 10 % (optional) indicates if the last point shall be read (1 to read it, 0 not 11 % to). 4 % This routine reads a shape file .shp and builds a structure array 5 % containing the fields x and y corresponding to the coordinates, one for the 6 % filename of the shp file, for the density, for the nodes, and a field 7 % closed to indicate if the domain is closed. If this initial shapefile is 8 % point only, the fields closed and points are omitted. 12 9 % 13 % Usage: 14 % Struct=shpread(filename) 10 % The first argument is the .shp file to be read and the second one 11 % (optional) indicates if the last point shall be read (1 to read it, 0 not 12 % to). 15 13 % 16 % Example:17 % Struct=shpread('domainoutline.shp')14 % Usage: 15 % Struct=shpread(filename) 18 16 % 19 % See also EXPDOC, EXPWRITEASVERTICES 17 % Example: 18 % Struct=shpread('domainoutline.shp') 20 19 21 20 %recover options -
issm/trunk-jpl/src/m/shp/shpread.py
r25125 r25455 1 from collections import OrderedDict 1 2 from os import path 2 3 try: … … 5 6 print("could not import shapefile, PyShp has not been installed, no shapefile reading capabilities enabled") 6 7 7 from helpers import OrderedStruct8 8 from pairoptions import pairoptions 9 9 10 10 11 11 def shpread(filename, *args): #{{{ 12 ''' 13 SHPREAD - read a shape file and build a dict 12 """SHPREAD - read a shapefile and build a list of shapes 14 13 15 This routine reads a shape file .shp and builds a dict array containing the 16 fields x and y corresponding to the coordinates, one for the filename 17 of the shp file, for the density, for the nodes, and a field closed to 18 indicate if the domain is closed. If this initial shapefile is point only, 19 the fields closed and points are ommited. 20 The first argument is the .shp file to be read and the second one 21 (optional) indicates if the last point shall be read (1 to read it, 0 not 22 to). 14 This routine reads a shapefile and builds a list of OrderedDict objects 15 containing the fields x and y corresponding to the coordinates, one for the 16 filename of the shp file, for the density, for the nodes, and a field 17 closed to indicate if the domain is closed. If this initial shapefile is 18 point only, the fields closed and points are ommitted. The first argument 19 is the shapefile to be read and the second argument (optional) indicates if 20 the last point shall be read (1 to read it, 0 not to). 23 21 24 22 The current implementation of shpread depends on PyShp. 25 23 26 24 Usage: 27 dict = shpread(filename)25 list = shpread(filename) 28 26 29 27 Example: … … 31 29 a collection of three files. You specify the base filename of the 32 30 shapefile or the complete filename of any of the shapefile component 33 files." "31 files." 34 32 35 dict = shpread('domainoutline.shp')33 list = shpread('domainoutline.shp') 36 34 OR 37 dict = shpread('domainoutline.dbf')35 list = shpread('domainoutline.dbf') 38 36 OR 39 dict = shpread('domainoutline')37 list = shpread('domainoutline') 40 38 41 39 "OR any of the other 5+ formats which are potentially part of a … … 44 42 .shp extension exists. 45 43 46 See also EXPDOC, EXPWRITEASVERTICES47 48 44 Sources: 49 45 - https://github.com/GeospatialPython/pyshp 50 46 47 NOTE: 48 - OrderedDict objects are used instead of OrderedStruct objects (although 49 addressing in the latter case is closer to the MATLAB struct type) in order 50 to remain consistent with the pattern established by src/m/exp/expread.py. 51 51 52 TODO: 52 53 - Create class that can be used to store and pretty print shape structs 53 (ala OrderedStruct from src/m/qmu/helpers.py). 54 ''' 54 (ala OrderedStruct from src/m/qmu/helpers.py). 55 - Convert returned data structure from list of OrderedDict objects to list 56 of OrderedStruct objects and remove corresponding note (see also 57 src/m/exp/expread.py). Also, modify handling of returned data structure in, 58 - src/m/classes/basin.py 59 - src/m/classes/boundary.py 60 - src/m/modules/ExpToLevelSet.py 61 - src/m/mesh/bamg.py 62 May also need to modify addressing in corresponding FetchData function, or 63 create new one, in src/wrappers/ContoursToNodes/ContoursToNodes.cpp. 64 """ 55 65 56 66 #recover options … … 67 77 shapes = sf.shapes() 68 78 for i in range(len(shapes)): 69 Struct = Ordered Struct()79 Struct = OrderedDict() 70 80 shape = shapes[i] 71 81 if shape.shapeType == shapefile.POINT: 72 Struct .x= shape.points[0][0]73 Struct .y= shape.points[0][1]74 Struct .density= 175 Struct .Geometry= 'Point'82 Struct['x'] = shape.points[0][0] 83 Struct['y'] = shape.points[0][1] 84 Struct['density'] = 1 85 Struct['Geometry'] = 'Point' 76 86 elif shape.shapeType == shapefile.POLYLINE: 77 87 num_points = len(shape.points) … … 82 92 x.append(point[0]) 83 93 y.append(point[1]) 84 Struct .x= x85 Struct .y= y86 Struct .nods= num_points87 Struct .density= 188 Struct .closed= 189 Struct .BoundingBox= shape.bbox90 Struct .Geometry= 'Line'94 Struct['x'] = x 95 Struct['y'] = y 96 Struct['nods'] = num_points 97 Struct['density'] = 1 98 Struct['closed'] = 1 99 Struct['BoundingBox'] = shape.bbox 100 Struct['Geometry'] = 'Line' 91 101 elif shape.shapeType == shapefile.POLYGON: 92 102 num_points = len(shape.points) … … 97 107 x.append(point[0]) 98 108 y.append(point[1]) 99 Struct .x= x100 Struct .y= y101 Struct .nods= num_points102 Struct .density= 1103 Struct .closed= 1104 Struct .BoundingBox= shape.bbox105 Struct .Geometry= 'Polygon'109 Struct['x'] = x 110 Struct['y'] = y 111 Struct['nods'] = num_points 112 Struct['density'] = 1 113 Struct['closed'] = 1 114 Struct['BoundingBox'] = shape.bbox 115 Struct['Geometry'] = 'Polygon' 106 116 else: 107 117 # NOTE: We could do this once before looping over shapes as all … … 122 132 else: 123 133 setattr(Struct, str(fieldname), sf.record(i)[j - 1]) # cast to string removes "u" from "u'fieldname'" 124 Struct .name= name134 Struct['name'] = name 125 135 Structs.append(Struct) 126 136 … … 128 138 if invert: 129 139 for i in range(len(Structs)): 130 Structs[i] .x = np.flipud(Structs[i].x)131 Structs[i] .y = np.flipud(Structs[i].y)140 Structs[i]['x'] = np.flipud(Structs[i]['x']) 141 Structs[i]['y'] = np.flipud(Structs[i]['y']) 132 142 133 143 return Structs -
issm/trunk-jpl/src/wrappers/ContourToMesh/ContourToMesh.cpp
r20855 r25455 67 67 68 68 /*Run interpolation routine: */ 69 ContourToMeshx( 69 ContourToMeshx(&in_nod,&in_elem,index,x,y,contours,interptype,nel,nods,edgevalue); 70 70 71 71 /* output: */ -
issm/trunk-jpl/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp
r22731 r25455 42 42 /*contours*/ 43 43 int i; 44 #ifdef _HAVE_MATLAB_MODULES_ 44 45 mxArray *matlabstructure = NULL; 46 #endif 45 47 Contour<double> **contours=NULL; 46 48 int numcontours; … … 59 61 60 62 /*checks on arguments on the matlab side: */ 63 #ifdef _HAVE_MATLAB_MODULES_ 61 64 if(nlhs!=NLHS){ 62 65 InterpFromMesh2dUsage(); 63 66 _error_("InterpFromMeshToMesh2dUsage usage error"); 64 67 } 68 #endif 65 69 if((nrhs!=6) && (nrhs!=7) && (nrhs!=8)){ 66 70 InterpFromMesh2dUsage(); … … 85 89 } 86 90 87 if(nrhs >=8){91 if(nrhs==8){ 88 92 89 93 #ifdef _HAVE_MATLAB_MODULES_ -
issm/trunk-jpl/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp
r23168 r25455 31 31 32 32 /*Intermediaties*/ 33 int *index = NULL;34 double *x_data = NULL;35 double *y_data = NULL;36 double *data = NULL;33 int* index = NULL; 34 double* x_data = NULL; 35 double* y_data = NULL; 36 double* data = NULL; 37 37 int nods_data,nels_data; 38 38 int M_data,N_data; 39 double *x_interp = NULL;40 double *y_interp = NULL;39 double* x_interp = NULL; 40 double* y_interp = NULL; 41 41 int N_interp; 42 Options *options = NULL;43 double *data_interp = NULL;42 Options* options = NULL; 43 double* data_interp = NULL; 44 44 int test1,test2,test; 45 45 -
issm/trunk-jpl/src/wrappers/python/Makefile.am
r24919 r25455 36 36 ElementConnectivity_python.la \ 37 37 ExpToLevelSet_python.la \ 38 InterpFromMesh2d_python.la \ 38 39 InterpFromMeshToMesh2d_python.la \ 39 40 InterpFromMeshToMesh3d_python.la \ … … 144 145 ExpToLevelSet_python_la_LIBADD = ${deps} $(PETSCLIB) $(HDF5LIB) $(BLASLAPACKLIB) $(MPILIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB) $(NEOPZLIB) 145 146 147 InterpFromMesh2d_python_la_SOURCES = ../InterpFromMesh2d/InterpFromMesh2d.cpp 148 InterpFromMesh2d_python_la_CXXFLAGS = ${AM_CXXFLAGS} 149 InterpFromMesh2d_python_la_LIBADD = ${deps} $(PETSCLIB) $(HDF5LIB) $(BLASLAPACKLIB) $(MPILIB) $(MULTITHREADINGLIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB) 150 146 151 InterpFromGridToMesh_python_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp 147 152 InterpFromGridToMesh_python_la_CXXFLAGS = ${AM_CXXFLAGS} -
issm/trunk-jpl/test/NightlyRun/test2004.m
r25147 r25455 77 77 alreadyloaded=0; 78 78 %}}} 79 for i =sl.basinindx('basin','all'),80 81 bas=sl.basins{i };79 for ind=sl.basinindx('basin','all'), 80 81 bas=sl.basins{ind}; 82 82 disp(sprintf('Meshing basin %s\n',bas.name)); 83 83 … … 85 85 domain=bas.contour(); 86 86 87 %recover coastline inside basin, using GSHHS_c_L1. It's a lat ,long file, hence epsg 432688 coastline=bas.shapefilecrop('shapefile',gshhsshapefile,'epsgshapefile',4326,'threshold',threshold); 89 90 %mesh: 87 %recover coastline inside basin, using GSHHS_c_L1. It's a lat/long file, hence epsg 4326 88 coastline=bas.shapefilecrop('shapefile',gshhsshapefile,'epsgshapefile',4326,'threshold',threshold); 89 90 %mesh: 91 91 md=bamg(model,'domain',domain,'subdomains',coastline,'hmin',hmin,'hmax',hmax,defaultoptions{:}); 92 92 %plotmodel(md,'data','mesh');pause(1); … … 108 108 %Parameterization: 109 109 %Parameterize ice sheets : {{{ 110 111 110 for ind=sl.basinindx('continent',{'antarctica'}), 112 111 disp(sprintf('Parameterizing basin %s\n', sl.icecaps{ind}.miscellaneous.name)); 113 112 114 md=sl.icecaps{ind}; bas=sl.basins{ind}; 113 md=sl.icecaps{ind}; 114 bas=sl.basins{ind}; 115 115 %masks : %{{{ 116 116 %ice levelset from domain outlines: … … 125 125 %}}} 126 126 %latlong: % {{{ 127 [md.mesh.long,md.mesh.lat]=gdaltransform(md.mesh.x,md.mesh.y,md.mesh.proj,'EPSG:4326'); 127 [md.mesh.long,md.mesh.lat]=gdaltransform(md.mesh.x,md.mesh.y,md.mesh.proj,'EPSG:4326'); 128 128 %}}} 129 129 %geometry: {{{ … … 137 137 if bas.iscontinentany('antarctica'), 138 138 if testagainst2002, 139 % TODO: Check if the following works as expected: 'pos' is empty, so nothing is assigned to 'md.solidearth.surfaceload.icethicknesschange(pos)' 139 140 md.solidearth.surfaceload.icethicknesschange=zeros(md.mesh.numberofelements,1); 140 141 %antarctica … … 146 147 md.solidearth.surfaceload.icethicknesschange(pos)=-100*ratio; 147 148 else 148 delH=textread('../Data/AIS_delH_trend.txt'); 149 longAIS=delH(:,1); latAIS=delH(:,2); delHAIS=delH(:,3); index=delaunay(longAIS,latAIS); 150 lat=md.mesh.lat; long=md.mesh.long+360; pos=find(long>360);long(pos)=long(pos)-360; 149 in_fileID=fopen('../Data/AIS_delH_trend.txt', 'r'); 150 delH=textscan(in_fileID, '%f %f %f'); 151 fclose(in_fileID); 152 longAIS=delH{:,1}; 153 latAIS=delH{:,2}; 154 delHAIS=delH{:,3}; 155 index=delaunay(longAIS,latAIS); 156 lat=md.mesh.lat; 157 long=md.mesh.long+360; 158 pos=find(long>360); 159 long(pos)=long(pos)-360; 151 160 delHAIS=InterpFromMesh2d(index,longAIS,latAIS,delHAIS,long,lat); 152 northpole=find_point(md.mesh.long,md.mesh.lat,0,90); delHAIS(northpole)=0;153 154 md.solidearth.surfaceload.icethicknesschange= delHAIS(md.mesh.elements)*[1;1;1]/3/100;161 northpole=find_point(md.mesh.long,md.mesh.lat,0,90); 162 delHAIS(northpole)=0; 163 md.solidearth.surfaceload.icethicknesschange=mean(delHAIS(md.mesh.elements),2)/100; 155 164 end 156 165 … … 172 181 end 173 182 %}}} 183 174 184 % ParameterizeContinents {{{ 175 176 sl.basinindx('continent',{'hemisphereeast','hemispherewest'})177 178 185 for ind=sl.basinindx('continent',{'hemisphereeast','hemispherewest'}), 179 186 disp(sprintf('Masks for basin %s\n', sl.icecaps{ind}.miscellaneous.name)); 180 md=sl.icecaps{ind}; bas=sl.basins{ind}; 187 md=sl.icecaps{ind}; 188 bas=sl.basins{ind}; 181 189 182 190 %recover lat,long: … … 184 192 185 193 %mask: %{{{ 186 %Figure out mask from initial mesh: deal with land and ocean masks (land include grounded ice). %{{{ 187 %first, transform land element mask into vertex driven one. 194 %Figure out mask from initial mesh: deal with land and ocean masks (land 195 %includes grounded ice). %{{{ 196 %first, transform land element mask into vertex-driven one 188 197 land=md.private.bamg.landmask; 189 198 land_mask=-ones(md.mesh.numberofvertices,1); … … 192 201 land_mask(md.mesh.elements(landels,:))=1; 193 202 194 % gothrough edges of each land element203 % Gothrough edges of each land element 195 204 connectedels=md.mesh.elementconnectivity(landels,:); 196 205 connectedisonocean=~land(connectedels); … … 200 209 landelsconocean=landels(find(sumconnectedisonocean)); 201 210 202 ind1=[md.mesh.elements(landelsconocean,1); md.mesh.elements(landelsconocean,2); md.mesh.elements(landelsconocean,3)]; 203 ind2=[md.mesh.elements(landelsconocean,2); md.mesh.elements(landelsconocean,3); md.mesh.elements(landelsconocean,1)]; 204 211 ind1=[md.mesh.elements(landelsconocean,1); 212 md.mesh.elements(landelsconocean,2); 213 md.mesh.elements(landelsconocean,3)]; 214 ind2=[md.mesh.elements(landelsconocean,2); 215 md.mesh.elements(landelsconocean,3); 216 md.mesh.elements(landelsconocean,1)]; 205 217 206 218 %edge ind1 and ind2: … … 223 235 % {{{ 224 236 %greenland 225 pos=find(md.mesh.lat > 70 & 237 pos=find(md.mesh.lat > 70 & md.mesh.lat < 80 & md.mesh.long>-60 & md.mesh.long<-30); 226 238 md.mask.ice_levelset(pos)=-1; 227 239 % }}} 228 240 end 229 230 241 % }}} 231 242 %}}} 232 243 %slr loading/calibration: {{{ 244 md.solidearth.surfaceload.icethicknesschange=zeros(md.mesh.numberofelements,1); 233 245 234 246 if testagainst2002, 235 247 % {{{ 236 md.solidearth.surfaceload.icethicknesschange=zeros(md.mesh.numberofelements,1);237 248 %greenland 238 249 late=sum(md.mesh.lat(md.mesh.elements),2)/3; … … 243 254 244 255 %correct mask: 245 md.mask.ice_levelset(md.mesh.elements(pos,:))=-1; 256 md.mask.ice_levelset(md.mesh.elements(pos,:))=-1; 246 257 % }}} 247 258 else 248 249 md.solidearth.surfaceload.icethicknesschange=zeros(md.mesh.numberofelements,1);250 251 259 delH=textread('../Data/GIS_delH_trend.txt'); 252 longGIS=delH(:,1); latGIS=delH(:,2); delHGIS=delH(:,3); index=delaunay(longGIS,latGIS); 253 lat=md.mesh.lat; long=md.mesh.long+360; pos=find(long>360);long(pos)=long(pos)-360; 260 longGIS=delH(:,1); 261 latGIS=delH(:,2); 262 delHGIS=delH(:,3); 263 index=delaunay(longGIS,latGIS); 264 lat=md.mesh.lat; 265 long=md.mesh.long+360; 266 pos=find(long>360); 267 long(pos)=long(pos)-360; 254 268 delHGIS=InterpFromMeshToMesh2d(index,longGIS,latGIS,delHGIS,long,lat); 255 269 delHGISe=delHGIS(md.mesh.elements)*[1;1;1]/3; 256 270 257 271 delH=textread('../Data/GLA_delH_trend_15regions.txt'); 258 longGLA=delH(:,1); latGLA=delH(:,2); delHGLA=sum(delH(:,3:end),2); index=delaunay(longGLA,latGLA); 259 lat=md.mesh.lat; long=md.mesh.long+360; pos=find(long>360);long(pos)=long(pos)-360; 272 longGLA=delH(:,1); 273 latGLA=delH(:,2); 274 delHGLA=sum(delH(:,3:end),2); 275 index=delaunay(longGLA,latGLA); 276 lat=md.mesh.lat; 277 long=md.mesh.long+360; 278 pos=find(long>360); 279 long(pos)=long(pos)-360; 260 280 delHGLA=InterpFromMeshToMesh2d(index,longGLA,latGLA,delHGLA,long,lat); 261 281 delHGLAe=delHGLA(md.mesh.elements)*[1;1;1]/3; … … 293 313 end 294 314 % }}} 315 295 316 %%Assemble Earth in 3D {{{ 296 317 … … 300 321 loneedgesdetect=0; 301 322 302 %create earth model by concatenating all the icecaps in 3d:323 %create Earth model by concatenating all the icecaps in 3D: 303 324 sl.caticecaps('tolerance',tolerance,'loneedgesdetect',loneedgesdetect); 304 325 -
issm/trunk-jpl/test/NightlyRun/test423.m
r24862 r25455 8 8 pos=find(rad==min(rad)); 9 9 md.mesh.x(pos)=0.; md.mesh.y(pos)=0.; %the closest node to the center is changed to be exactly at the center 10 xelem=m d.mesh.x(md.mesh.elements)*[1;1;1]/3.;11 yelem=m d.mesh.y(md.mesh.elements)*[1;1;1]/3.;10 xelem=mean(md.mesh.x(md.mesh.elements),2); 11 yelem=mean(md.mesh.y(md.mesh.elements),2); 12 12 rad=sqrt(xelem.^2+yelem.^2); 13 13 flags=zeros(md.mesh.numberofelements,1); -
issm/trunk-jpl/test/NightlyRun/test423.py
r24862 r25455 19 19 md.mesh.x[pos] = 0. 20 20 md.mesh.y[pos] = 0. #the closest node to the center is changed to be exactly at the center 21 xelem = np.mean(md.mesh.x[md.mesh.elements .astype(int)- 1], axis=1)22 yelem = np.mean(md.mesh.y[md.mesh.elements .astype(int)- 1], axis=1)21 xelem = np.mean(md.mesh.x[md.mesh.elements - 1], axis=1) 22 yelem = np.mean(md.mesh.y[md.mesh.elements - 1], axis=1) 23 23 rad = np.sqrt(xelem**2 + yelem**2) 24 24 flags = np.zeros(md.mesh.numberofelements) -
issm/trunk-jpl/test/NightlyRun/test433.m
r24862 r25455 8 8 pos=find(rad==min(rad)); 9 9 md.mesh.x(pos)=0.; md.mesh.y(pos)=0.; %the closest node to the center is changed to be exactly at the center 10 xelem=m d.mesh.x(md.mesh.elements)*[1;1;1]/3.;11 yelem=m d.mesh.y(md.mesh.elements)*[1;1;1]/3.;10 xelem=mean(md.mesh.x(md.mesh.elements), 2); 11 yelem=mean(md.mesh.y(md.mesh.elements), 2); 12 12 rad=sqrt(xelem.^2+yelem.^2); 13 13 flags=zeros(md.mesh.numberofelements,1); -
issm/trunk-jpl/test/NightlyRun/test433.py
r24862 r25455 19 19 md.mesh.x[pos] = 0. 20 20 md.mesh.y[pos] = 0. #the closest node to the center is changed to be exactly at the center 21 xelem = np.mean(md.mesh.x[md.mesh.elements .astype(int)- 1], axis=1)22 yelem = np.mean(md.mesh.y[md.mesh.elements .astype(int)- 1], axis=1)21 xelem = np.mean(md.mesh.x[md.mesh.elements - 1], axis=1) 22 yelem = np.mean(md.mesh.y[md.mesh.elements - 1], axis=1) 23 23 rad = np.sqrt(xelem**2 + yelem**2) 24 24 flags = np.zeros(md.mesh.numberofelements) -
issm/trunk-jpl/test/Par/79North.py
r24862 r25455 19 19 thickness = numpy.array(archread('../Data/79North.arch', 'thickness')) 20 20 21 md.initialization.vx = InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y)[ 0][:, 0]22 md.initialization.vy = InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y)[ 0][:, 0]23 md.geometry.surface = InterpFromMeshToMesh2d(index, x, y, surface, md.mesh.x, md.mesh.y)[ 0][:, 0]24 md.geometry.thickness = InterpFromMeshToMesh2d(index, x, y, thickness, md.mesh.x, md.mesh.y)[ 0][:, 0]21 md.initialization.vx = InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y)[:, 0] 22 md.initialization.vy = InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y)[:, 0] 23 md.geometry.surface = InterpFromMeshToMesh2d(index, x, y, surface, md.mesh.x, md.mesh.y)[:, 0] 24 md.geometry.thickness = InterpFromMeshToMesh2d(index, x, y, thickness, md.mesh.x, md.mesh.y)[:, 0] 25 25 md.geometry.base = md.geometry.surface - md.geometry.thickness 26 26 -
issm/trunk-jpl/test/Par/Pig.py
r24862 r25455 20 20 bed = np.array(archread('../Data/Pig.arch', 'bed')) 21 21 22 md.inversion.vx_obs = InterpFromMeshToMesh2d(index, x, y, vx_obs, md.mesh.x, md.mesh.y)[ 0][:, 0]23 md.inversion.vy_obs = InterpFromMeshToMesh2d(index, x, y, vy_obs, md.mesh.x, md.mesh.y)[ 0][:, 0]24 md.geometry.surface = InterpFromMeshToMesh2d(index, x, y, surface, md.mesh.x, md.mesh.y)[ 0][:, 0]25 md.geometry.thickness = InterpFromMeshToMesh2d(index, x, y, thickness, md.mesh.x, md.mesh.y)[ 0][:, 0]22 md.inversion.vx_obs = InterpFromMeshToMesh2d(index, x, y, vx_obs, md.mesh.x, md.mesh.y)[:, 0] 23 md.inversion.vy_obs = InterpFromMeshToMesh2d(index, x, y, vy_obs, md.mesh.x, md.mesh.y)[:, 0] 24 md.geometry.surface = InterpFromMeshToMesh2d(index, x, y, surface, md.mesh.x, md.mesh.y)[:, 0] 25 md.geometry.thickness = InterpFromMeshToMesh2d(index, x, y, thickness, md.mesh.x, md.mesh.y)[:, 0] 26 26 md.geometry.base = md.geometry.surface - md.geometry.thickness 27 27 md.geometry.bed = np.array(md.geometry.base) 28 28 pos = np.where(md.mask.ocean_levelset < 0.) 29 md.geometry.bed[pos] = InterpFromMeshToMesh2d(index, x, y, bed, md.mesh.x[pos], md.mesh.y[pos])[ 0][:, 0]29 md.geometry.bed[pos] = InterpFromMeshToMesh2d(index, x, y, bed, md.mesh.x[pos], md.mesh.y[pos])[:, 0] 30 30 md.initialization.vx = md.inversion.vx_obs 31 31 md.initialization.vy = md.inversion.vy_obs -
issm/trunk-jpl/test/Par/SquareSheetConstrained.py
r25129 r25455 28 28 index = archread('../Data/SquareSheetConstrained.arch', 'index').astype(int) 29 29 30 md.initialization.vx = InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y) [0]31 md.initialization.vy = InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y) [0]30 md.initialization.vx = InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y) 31 md.initialization.vy = InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y) 32 32 md.initialization.vz = np.zeros((md.mesh.numberofvertices)) 33 33 md.initialization.pressure = np.zeros((md.mesh.numberofvertices)) -
issm/trunk-jpl/test/Par/SquareSheetConstrainedCO2.py
r24862 r25455 44 44 index = archread('../Data/SquareSheetConstrained.arch', 'index').astype(int) 45 45 46 [md.initialization.vx]= InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y)47 [md.initialization.vy]= InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y)46 md.initialization.vx = InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y) 47 md.initialization.vy = InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y) 48 48 md.initialization.vz = np.zeros((md.mesh.numberofvertices)) 49 49 md.initialization.pressure = np.zeros((md.mesh.numberofvertices)) -
issm/trunk-jpl/test/Par/SquareSheetShelf.py
r24862 r25455 31 31 index = np.array(archread('../Data/SquareSheetShelf.arch', 'index')).astype(int) 32 32 33 [md.initialization.vx]= InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y)34 [md.initialization.vy]= InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y)33 md.initialization.vx = InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y) 34 md.initialization.vy = InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y) 35 35 md.initialization.vz = np.zeros((md.mesh.numberofvertices)) 36 36 md.initialization.pressure = np.zeros((md.mesh.numberofvertices)) -
issm/trunk-jpl/test/Par/SquareShelf2.py
r24862 r25455 32 32 #dbg - end 33 33 34 [md.initialization.vx]= InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y)35 [md.initialization.vy]= InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y)34 md.initialization.vx = InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y) 35 md.initialization.vy = InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y) 36 36 md.initialization.vz = np.zeros((md.mesh.numberofvertices)) 37 37 md.initialization.pressure = np.zeros((md.mesh.numberofvertices)) -
issm/trunk-jpl/test/Par/SquareShelfConstrained.py
r24862 r25455 28 28 index = np.array(archread('../Data/SquareShelfConstrained.arch', 'index').astype(int)) 29 29 30 [md.initialization.vx]= InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y)31 [md.initialization.vy]= InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y)30 md.initialization.vx = InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y) 31 md.initialization.vy = InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y) 32 32 md.initialization.vz = np.zeros((md.mesh.numberofvertices)) 33 33 md.initialization.pressure = np.zeros((md.mesh.numberofvertices))
Note:
See TracChangeset
for help on using the changeset viewer.