source:
issm/oecreview/Archive/24684-25833/ISSM-25064-25065.diff
Last change on this file was 25834, checked in by , 4 years ago | |
---|---|
File size: 78.5 KB |
-
../trunk-jpl/src/m/shp/shpwrite.py
1 try: 2 import shapefile 3 except ImportError: 4 print("could not import shapefile, PyShp has not been installed, no shapefile reading capabilities enabled") 5 6 def shpwrite(shp, filename): #{{{ 7 ''' 8 SHPREAD - write a shape file from a contour structure 9 10 The current implementation of shpwrite depends on PyShp. 11 12 Usage: 13 shpwrite(shp, filename) 14 15 Example: 16 shpwrite(shp, 'domainoutline.shp') 17 18 See also SHPREAD 19 20 Sources: 21 - https://github.com/GeospatialPython/pyshp 22 23 TODO: 24 - Should we check if there is only one element (see how MATLAB's shaperead 25 and shapewrite handle single shapes versus multiple shapes)? 26 ''' 27 28 # Sanity checks 29 for shape in shp: 30 print(shape) 31 32 if shp[0].Geometry == 'Point': 33 shapeType = 1 34 elif shp[0].Geometry == 'Line': 35 shapeType = 3 36 elif shp[0].Geometry == 'Polygon': 37 shapeType = 5 38 else: 39 raise Exception('shpwrite error: geometry \'{}\' is not currently supported'.format(shp[0].Geometry)) 40 41 sf = shapefile.Writer(filename, shapeType=shapeType) 42 43 for i in range(len(shp)): 44 sf.field('name', 'C') # TODO: Allow shape ids/names to be passed through 45 if shapeType == 1: # POINT 46 sf.point(shp[i].x, shp[i].y) 47 elif shapeType == 3: # POLYLINE 48 points = [] 49 for j in range(len(shp[i].x)): 50 points.append([shp[i].x[j], shp[i].y[j]]) 51 sf.line(line) 52 elif shapeType == 5: # POLYGON 53 points = [] 54 for j in range(len(shp[i].x)): 55 points.append([shp[i].x[j], shp[i].y[j]]) 56 sf.poly(points) 57 sf.null() 58 sf.record(str(i)) 59 sf.close() 60 #}}} -
../trunk-jpl/src/m/shp/shpwrite.m
9 9 % 10 10 % See also SHPREAD 11 11 12 13 %initialize number of profile14 count=0;15 16 12 contours=struct([]); 17 13 for i=1:length(shp), 18 14 if strcmpi(shp(i).Geometry,'Point'), … … 21 17 contours(i).Geometry='Polygon'; 22 18 elseif strcmpi(shp(i).Geometry,'Line'), 23 19 contours(i).Geometry='Line'; 20 else, 21 error(['shpwrite error: geometry ' shp(i).Geometry ' not currently supported']); 24 22 end 25 23 contours(i).id=i; 26 24 contours(i).X=shp(i).x; 27 25 contours(i).Y=shp(i).y; 28 26 end 29 27 30 28 shapewrite(contours,filename); 31 29 end -
../trunk-jpl/src/m/mesh/meshintersect3d.py
6 6 7 7 from pairoptions import pairoptions 8 8 9 9 10 def meshintersect3d(x, y, z, xs, ys, zs, *args): #{{{ 10 11 ''' 11 MESHINTERSECT - returns indices (into x, y, and z) of common values between (x, y, z) and (xs, ys, zs) (i.e. x(index) = xs; y(index) = ys). 12 MESHINTERSECT - returns indices (into x, y, and z) of common values between 13 (x, y, z) and (xs, ys, zs) (i.e. x(index) = xs; y(index) = ys). 12 14 ''' 13 15 14 16 # Process options -
../trunk-jpl/src/m/coordsystems/laea.py
1 def laea(lat, long): #{{{ 2 ''' 3 LAEA - Lambert Azimuthal Equal Area projection at lat, long projection 4 center. 5 6 Usage: 7 string = laea(45, -90) 8 9 Example: 10 string = laea(45, -90) 11 return string = '+proj=laea +lat_0=45 +lon_0=-90 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs' 12 ''' 13 14 return '+proj=laea +lat_0={} +lon_0={} +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs'.format(lat, long) 15 #}}} -
../trunk-jpl/src/m/coordsystems/gdaltransform.m
19 19 % Bamber's Greeland projection 20 20 % +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 21 21 % 22 % 22 % To get proj.4 string from EPSG, use gdalsrsinfo. Example: 23 23 % 24 % 24 % gdalsrsinfo epsg:4326 | grep "PROJ.4" | sed "s/PROJ.4 : //" 25 25 26 26 %give ourselves unique file names 27 27 filename_in = tempname(); -
../trunk-jpl/src/m/geometry/AboveGround.py
1 import numpy as np 2 3 def function AboveGround(lat, long, r, height): #{{{ 4 r = r + height 5 x = r * np.cos(np.deg2rad(lat)) * np.cos(np.deg2rad(long)) 6 y = r * np.cos(np.deg2rad(lat)) * np.sin(np.deg2rad(long)) 7 z = r * np.sin(np.deg2rad(lat)) 8 #}}} -
../trunk-jpl/src/m/classes/plotoptions.py
1 1 from collections import OrderedDict 2 2 3 import pairoptions 3 4 4 5 … … 6 7 ''' 7 8 PLOTOPTIONS class definition 8 9 9 10 10 Usage: 11 plotoptions = plotoptions(*arg) 11 12 ''' 12 13 13 14 def __init__(self, *arg): # {{{ … … 35 36 def buildlist(self, *arg): #{{{ 36 37 #check length of input 37 38 if len(arg) % 2: 38 raise TypeError('Invalid parameter /value pair arguments')39 raise TypeError('Invalid parameter/value pair arguments') 39 40 40 41 #go through args and build list (like pairoptions) 41 42 rawoptions = pairoptions.pairoptions(*arg) … … 102 103 if len(nums) != 2: 103 104 continue 104 105 if False in [x.isdigit() for x in nums]: 105 raise ValueError('error: in option i -j both i and j must be integers')106 raise ValueError('error: in option i-j both i and j must be integers') 106 107 for j in range(int(nums[0]) - 1, int(nums[1])): 107 108 self.list[j].addfield(field, rawlist[i][1]) 108 109 -
../trunk-jpl/src/m/classes/basin.m
18 18 end 19 19 methods 20 20 function self = basin(varargin) % {{{ 21 switch nargin 22 case 0 23 self=setdefaultparameters(self); 24 otherwise 21 self=setdefaultparameters(self); 25 22 26 self=setdefaultparameters(self);27 28 29 30 31 32 23 if nargin>0, 24 options=pairoptions(varargin{:}); 25 26 %recover field values: 27 self.boundaries=getfieldvalue(options,'boundaries',{}); 28 self.name=getfieldvalue(options,'name',''); 29 self.continent=getfieldvalue(options,'continent',''); 33 30 34 %figure out projection string: 31 %figure out projection string: 32 if exist(options,'epsg'), 33 if exist(options,'proj'), 34 error(['Error in constructor for basin ' self.name '. Cannot supply epsg and proj at the same time!']); 35 end 36 epsg=getfieldvalue(options,'epsg'); 37 proj=epsg2proj(epsg); %convert to PROJ.4 format 38 elseif exist(options,'proj'), 35 39 if exist(options,'epsg'), 36 if exist(options,'proj'), 37 error(['Error in constructor for boundary ' self.shppath '.Cannot supply epsg and proj at the same time!']); 38 end 39 epsg=getfieldvalue(options,'epsg'); 40 %convert into proj4: 41 proj=epsg2proj(epsg); 42 elseif exist(options,'proj'), 43 if exist(options,'epsg'), 44 error(['Error in constructor for boundary ' self.shppath '.Cannot supply epsg and proj at the same time!']); 45 end 46 proj=getfieldvalue(options,'proj'); 47 else 48 proj= '+proj=longlat +datum=WGS84 +no_defs'; 40 error(['Error in constructor for basin ' self.name '. Cannot supply proj and epsg at the same time!']); 49 41 end 50 self.proj=proj; 42 proj=getfieldvalue(options,'proj'); 43 else 44 proj='+proj=longlat +datum=WGS84 +no_defs'; 45 end 46 47 self.proj=proj; 51 48 end 52 49 end % }}} 53 50 function self = setdefaultparameters(self) % {{{ 54 51 self.name=''; 55 52 self.continent=''; 56 self.proj='+proj=longlat +datum=WGS84 +no_defs 53 self.proj='+proj=longlat +datum=WGS84 +no_defs'; %EPSG 4326 57 54 self.boundaries={}; 58 55 59 56 end % }}} … … 92 89 options=pairoptions(varargin{:}); 93 90 extension=getfieldvalue(options,'extension',1); 94 91 95 [path,n me,ext]=fileparts(self.name);92 [path,name,ext]=fileparts(self.name); 96 93 if extension, 97 output=[n me ext];94 output=[name ext]; 98 95 else 99 output=n me;96 output=name; 100 97 end 101 98 end % }}} 102 99 function plot(self,varargin) % {{{ … … 173 170 inshapefile=getfieldvalue(options,'shapefile'); 174 171 outputshapefile=getfieldvalue(options,'outputshapefile',''); 175 172 176 if (exist(options,'epsgshapefile') & 173 if (exist(options,'epsgshapefile') & exist(options,'projshapefile')), 177 174 error('Basin shapefilecrop error message: cannot specify epsgshapefile and projshapefile at the same time'); 178 175 end 179 176 if exist(options,'epsgshapefile'), … … 185 182 end 186 183 187 184 188 %create list of contours that have critical length > threshold : (in lat,long)185 %create list of contours that have critical length > threshold (in lat,long): 189 186 contours=shpread(inshapefile); 190 187 llist=[]; 191 188 for i=1:length(contours), … … 211 208 flags=zeros(length(contours),1); 212 209 for i=1:length(contours), 213 210 h=contours(i); 214 i n=inpolygon(h.x,h.y,ba.x,ba.y);215 if ~isempty(find(i n==0)),211 isin=inpolygon(h.x,h.y,ba.x,ba.y); 212 if ~isempty(find(isin==0)), 216 213 flags(i)=1; 217 214 end 218 215 end -
../trunk-jpl/src/m/qmu/helpers.py
1 import numpy as np2 1 from collections import OrderedDict 3 2 from copy import deepcopy 4 3 4 import numpy as np 5 5 6 6 7 class struct(object): 7 8 '''An empty struct that can be assigned arbitrary attributes''' 8 9 pass … … 10 11 11 12 class Lstruct(list): 12 13 ''' 13 An empty struct that can be assigned arbitrary attributes 14 but can also beaccesed as a list. Eg. x.y = 'hello', x[:] = ['w', 'o', 'r', 'l', 'd']14 An empty struct that can be assigned arbitrary attributes but can also be 15 accesed as a list. Eg. x.y = 'hello', x[:] = ['w', 'o', 'r', 'l', 'd'] 15 16 16 Note that 'x' returns the array and x.__dict__ will only return 17 attributesother than the array17 Note that 'x' returns the array and x.__dict__ will only return attributes 18 other than the array 18 19 19 List-based and struct-based behaviors work normally, however they are referenced 20 as if the other does not exist; len(x) corresponds only to21 the list component of x, len(x.a) corresponds to x.a, x.__dict__22 correspondsonly to the non-x-list attributes20 List-based and struct-based behaviors work normally, however they are 21 referenced as if the other does not exist; len(x) corresponds only to the 22 list component of x, len(x.a) corresponds to x.a, x.__dict__ corresponds 23 only to the non-x-list attributes 23 24 24 Example uses:25 Examples: 25 26 26 x = Lstruct(1, 2, 3, 4) -> [1, 2, 3, 4]27 x.a = 'hello'28 len(x) -> 429 x.append(5)30 len(x) -> 531 x[2] -> 332 x.a -> 'hello'33 print x -> [1, 2, 3, 4, 5]34 x.__dict__ -> {'a':'hello'}35 x.b = [6, 7, 8, 9]36 x.b[-1] -> 937 len(x.b) -> 427 x = Lstruct(1, 2, 3, 4) -> [1, 2, 3, 4] 28 x.a = 'hello' 29 len(x) -> 4 30 x.append(5) 31 len(x) -> 5 32 x[2] -> 3 33 x.a -> 'hello' 34 print x -> [1, 2, 3, 4, 5] 35 x.__dict__ -> {'a':'hello'} 36 x.b = [6, 7, 8, 9] 37 x.b[-1] -> 9 38 len(x.b) -> 4 38 39 39 Other valid constructors:40 41 42 43 40 Other valid constructors: 41 x = Lstruct(1, 2, 3, a = 'hello') -> x.a -> 'hello', x -> [1, 2, 3] 42 x = Lstruct(1, 2, 3)(a = 'hello') 43 x = Lstruct([1, 2, 3], x = 'hello') 44 x = Lstruct((1, 2, 3), a = 'hello') 44 45 45 Credit: https://github.com/Vectorized/Python-Attribute-List 46 ''' 46 Sources: 47 -https://github.com/Vectorized/Python-Attribute-List 48 ''' 47 49 48 50 def __new__(self, *args, **kwargs): 49 51 return super(Lstruct, self).__new__(self, args, kwargs) … … 62 64 63 65 class OrderedStruct(object): 64 66 ''' 65 A form of dictionary-like structure that maintains the 66 ordering in which its fields/attributes and their 67 corresponding values were added. 67 A form of dictionary-like structure that maintains the ordering in which 68 its fields/attributes and their corresponding values were added. 68 69 69 OrderedDict is a similar device, however this class 70 can be used as an "ordered struct/class" giving 71 it much more flexibility in practice. It is 70 OrderedDict is a similar device, however this class can be used as an 71 "ordered struct/class" giving it much more flexibility in practice. It is 72 72 also easier to work with fixed valued keys in-code. 73 73 74 Eg:75 OrderedDict: # a bit clumsy to use and look at76 x['y'] = 574 Example: 75 OrderedDict: # a bit clumsy to use and look at 76 x['y'] = 5 77 77 78 OrderedStruct: # nicer to look at, and works the same way79 x.y = 580 OR81 x['y'] = 5 # supports OrderedDict-style usage78 OrderedStruct: # nicer to look at, and works the same way 79 x.y = 5 80 OR 81 x['y'] = 5 # supports OrderedDict-style usage 82 82 83 Supports: len(x), str(x), for-loop iteration.84 Has methods: x.keys(), x.values(), x.items(), x.iterkeys()83 Supports: len(x), str(x), for-loop iteration. 84 Has methods: x.keys(), x.values(), x.items(), x.iterkeys() 85 85 86 Usage:87 x = OrderedStruct()88 x.y = 589 x.z = 690 OR91 x = OrderedStruct('y', 5, 'z', 6)86 Usage: 87 x = OrderedStruct() 88 x.y = 5 89 x.z = 6 90 OR 91 x = OrderedStruct('y', 5, 'z', 6) 92 92 93 # note below that the output fields as iterables are always94 # in the sameorder as the inputs93 note below that the output fields as iterables are always in the same 94 order as the inputs 95 95 96 96 x.keys() -> ['y', 'z'] 97 97 x.values() -> [5, 6] … … 110 110 ('x', 5) 111 111 ('y', 6) 112 112 113 Note: to access internal fields use dir(x) 114 (input fields will be included, but 115 are not technically internals) 113 Note: to access internal fields use dir(x) (input fields will be included, 114 but are not technically internals) 116 115 ''' 117 116 118 117 def __init__(self, *args): 119 '''Provided either nothing or a series of strings, construct a structure that will, 120 when accessed as a list, return its fields in the same order in which they were provided''' 118 ''' 119 Provided either nothing or a series of strings, construct a structure 120 that will, when accessed as a list, return its fields in the same order 121 in which they were provided 122 ''' 121 123 122 # keys and values124 # keys and values 123 125 self._k = [] 124 126 self._v = [] 125 127 … … 184 186 yield(a, b) 185 187 186 188 def __copy__(self): 187 # shallow copy, hard copies of trivial attributes, 188 # references to structures like lists/OrderedDicts 189 # unless redefined as an entirely different structure 189 ''' 190 shallow copy, hard copies of trivial attributes, 191 references to structures like lists/OrderedDicts 192 unless redefined as an entirely different structure 193 ''' 190 194 newInstance = type(self)() 191 195 for k, v in list(self.items()): 192 196 exec(('newInstance.%s = v') % (k)) … … 193 197 return newInstance 194 198 195 199 def __deepcopy__(self, memo=None): 196 # hard copy of all attributes 197 # same thing but call deepcopy recursively 198 # technically not how it should be done, 199 # (see https://docs.python.org/2/library/copy.html #copy.deepcopy ) 200 # but will generally work in this case 200 ''' 201 hard copy of all attributes 202 same thing but call deepcopy recursively 203 technically not how it should be done, 204 (see https://docs.python.org/2/library/copy.html #copy.deepcopy ) 205 but will generally work in this case 206 ''' 201 207 newInstance = type(self)() 202 208 for k, v in list(self.items()): 203 209 exec(('newInstance.%s = deepcopy(v)') % (k)) … … 211 217 i = self._k.index(key) 212 218 k = self._k.pop(i) 213 219 v = self._v.pop(i) 214 #exec('del self.%s')%(key)220 #exec('del self.%s')%(key) 215 221 return (k, v) 216 222 217 223 def keys(self): … … 226 232 227 233 def isempty(x): 228 234 ''' 229 returns true if object is + -infinity, NaN, None, '', has length 0, or is an 230 array/matrix composed only of such components (includes mixtures of "empty" types)''' 235 returns true if object is +/-infinity, NaN, None, '', has length 0, or is 236 an array/matrix composed only of such components (includes mixtures of 237 "empty" types) 238 ''' 231 239 232 240 if type(x) in [list, np.ndarray, tuple]: 233 241 if np.size(x) == 0: … … 261 269 262 270 263 271 def fieldnames(x, ignore_internals=True): 264 '''returns a list of fields of x 265 ignore_internals ignores all fieldnames starting with '_' and is True by default''' 272 ''' 273 returns a list of fields of x 274 ignore_internals ignores all fieldnames starting with '_' and is True by 275 default 276 ''' 266 277 result = list(vars(x).keys()) 267 278 268 279 if ignore_internals: … … 272 283 273 284 274 285 def isfield(x, y, ignore_internals=True): 275 '''is y is a field of x? 276 ignore_internals ignores all fieldnames starting with '_' and is True by default''' 286 ''' 287 is y is a field of x? 288 ignore_internals ignores all fieldnames starting with '_' and is True by 289 default 290 ''' 277 291 return str(y) in fieldnames(x, ignore_internals) 278 292 279 293 … … 280 294 def fileparts(x): 281 295 ''' 282 296 given: "path/path/.../file_name.ext" 283 returns: [path, file_name, ext] (list of strings)''' 297 returns: [path, file_name, ext] (list of strings) 298 ''' 284 299 try: 285 300 a = x[:x.rindex('/')] #path 286 301 b = x[x.rindex('/') + 1:] #full filename … … 296 311 297 312 def fullfile(*args): 298 313 ''' 299 use: 314 usage: 315 fullfile(path, path, ... , file_name + ext) 300 316 301 fullfile(path, path, ... , file_name + ext)302 317 returns: "path/path/.../file_name.ext" 303 318 304 319 with all arguments as strings with no "/"s 305 320 306 321 regarding extensions and the '.': 307 as final arguments ('file.doc') or ('file' + '.doc') will work308 ('final', '.doc'), and the like, will not (you'd get 'final/.doc')309 '''322 as final arguments ('file.doc') or ('file' + '.doc') will work 323 ('final', '.doc'), and the like, will not (you'd get 'final/.doc') 324 ''' 310 325 result = str(args[0]) 311 326 for i in range(len(args[1:])): 312 327 # if last argument wasn't empty, add a '/' between it and the next argument … … 320 335 def findline(fidi, s): 321 336 ''' 322 337 returns full first line containing s (as a string), or None 338 323 339 Note: will include any newlines or tabs that occur in that line, 324 use str(findline(f, s)).strip() to remove these, str() in case result is None''' 340 use str(findline(f, s)).strip() to remove these, str() in case result is 341 None 342 ''' 325 343 for line in fidi: 326 344 if s in line: 327 345 return line … … 330 348 331 349 def empty_nd_list(shape, filler=0., as_numpy_ndarray=False): 332 350 ''' 333 returns a python list of the size/shape given (shape must be int or tuple)351 returns a python list of the size/shape given (shape must be int or tuple) 334 352 the list will be filled with the optional second argument 335 353 336 354 filler is 0.0 by default 337 355 338 as_numpy_ndarray will return the result as a numpy.ndarray and is False by default 356 as_numpy_ndarray will return the result as a numpy.ndarray and is False by 357 default 339 358 340 Note: the filler must be either None/np.nan/float('NaN'), float/double, or int341 359 Note: the filler must be either None/np.nan/float('NaN'), float/double, or 360 int. other numpy and float values such as +/- np.inf will also work 342 361 343 use:344 empty_nd_list((5, 5), 0.0) # returns a 5x5 matrix of 0.0's345 empty_nd_list(5, None) # returns a 5 long array of NaN346 '''362 Usage: 363 empty_nd_list((5, 5), 0.0) # returns a 5x5 matrix of 0.0's 364 empty_nd_list(5, None) # returns a 5 long array of NaN 365 ''' 347 366 result = np.empty(shape) 348 367 result.fill(filler) 349 368 if not as_numpy_ndarray: -
../trunk-jpl/src/m/mech/analyticaldamage.py
1 1 import numpy as np 2 2 3 from averaging import averaging 3 #from plotmodel import plotmodel4 4 from thomasparams import thomasparams 5 5 6 6 -
../trunk-jpl/src/m/plot/applyoptions.m
307 307 end 308 308 end 309 309 310 311 310 %text (default value is empty, not NaN...) 312 311 if exist(options,'text'); 313 312 textstring=getfieldvalue(options,'text'); … … 351 350 scaleruler(options); 352 351 end 353 352 354 %streamlines s353 %streamlines 355 354 if exist(options,'streamlines'), 356 355 plot_streamlines(md,options); 357 356 end -
../trunk-jpl/src/m/plot/plot_manager.py
1 2 from checkplotoptions import checkplotoptions3 from plot_mesh import plot_mesh4 from plot_BC import plot_BC5 from plot_elementnumbering import plot_elementnumbering6 from plot_vertexnumbering import plot_vertexnumbering7 from processmesh import processmesh8 from processdata import processdata9 from plot_unit import plot_unit10 from applyoptions import applyoptions11 12 1 try: 13 2 from osgeo import gdal 14 3 overlaysupport = True … … 16 5 print('osgeo/gdal for python not installed, overlay plots are not enabled') 17 6 overlaysupport = False 18 7 8 from applyoptions import applyoptions 9 from checkplotoptions import checkplotoptions 10 from plot_BC import plot_BC 11 from plot_mesh import plot_mesh 12 from plot_elementnumbering import plot_elementnumbering 19 13 if overlaysupport: 20 14 from plot_overlay import plot_overlay 15 from plot_unit import plot_unit 16 from plot_vertexnumbering import plot_vertexnumbering 17 from processdata import processdata 18 from processmesh import processmesh 21 19 22 20 23 21 def plot_manager(md, options, fig, axgrid, gridindex): … … 26 24 27 25 'fig' is a handle to the figure instance created by plotmodel. 28 26 29 'ax ' is a handle to the axes instance created by plotmodel.This is27 'axgrid' is a handle to the axes instance created by plotmodel. This is 30 28 currently generated using matplotlib's AxesGrid toolkit. 31 29 30 'gridindex' is passed through to specialized plot* functions and 31 applyoptions. 32 32 33 Usage: 33 34 plot_manager(md, options, fig, ax) 34 35 … … 36 37 ''' 37 38 #parse options and get a structure of options 38 39 options = checkplotoptions(md, options) 40 39 41 #get data to be plotted 40 42 data = options.getfieldvalue('data') 43 41 44 #add ticklabel has a default option 45 # 46 # TODO: Check why we are doing this and if it is absolutely necessary (see 47 # also src/m/plot/plot_mesh.py, src/m/plot/applyoptions.py) 42 48 options.addfielddefault('ticklabels', 'on') 43 49 44 50 ax = axgrid[gridindex] … … 57 63 if isinstance(data, str): 58 64 if data == 'mesh': 59 65 plot_mesh(md, options, fig, axgrid, gridindex) 60 61 #fig.delaxes(fig.axes[1]) # hack to remove colorbar after the fact 66 #fig.delaxes(fig.axes[1]) # hack to remove colorbar after the fact 62 67 return 63 68 elif data == 'BC': 64 69 plot_BC(md, options, fig, axgrid, gridindex) -
../trunk-jpl/src/m/plot/plot_overlay.py
1 import numpy as np 2 from processmesh import processmesh 3 from processdata import processdata 4 from xy2ll import xy2ll 1 import os 2 5 3 import matplotlib.pyplot as plt 6 4 import matplotlib as mpl 7 import os8 5 try: 9 6 from mpl_toolkits.basemap import Basemap 10 7 except ImportError: 11 8 print('Basemap toolkit not installed') 9 import numpy as np 12 10 try: 13 11 from osgeo import gdal 14 12 except ImportError: 15 13 print('osgeo/gdal for python not installed, plot_overlay is disabled') 16 14 15 from processdata import processdata 16 from processmesh import processmesh 17 from xy2ll import xy2ll 17 18 19 18 20 def plot_overlay(md, data, options, ax): 19 21 ''' 20 Function for plotting a georeferenced image. This function is called 21 from within the plotmodel code. 22 Function for plotting a georeferenced image. Called from plot_manager by 23 call to plotmodel. 24 25 Usage: 26 plot_overlay(md, data, options, ax) 27 28 See also: PLOTMODEL 22 29 ''' 23 30 24 31 x, y, z, elements, is2d, isplanet = processmesh(md, [], options) … … 80 87 plt.hist(arr.flatten(), bins=256, range=(0., 1.)) 81 88 plt.title('histogram of overlay image, use for setting overlaylims') 82 89 plt.show() 83 plt.sca(ax) # return to original axes /figure90 plt.sca(ax) # return to original axes/figure 84 91 85 92 # get parameters from cropped geotiff 86 93 trans = gtif.GetGeoTransform() -
../trunk-jpl/src/m/plot/plotmodel.m
9 9 numberofplots=options.numberofplots; 10 10 11 11 %get number of subplots 12 subplotwidth=ceil(sqrt( options.numberofplots));12 subplotwidth=ceil(sqrt(numberofplots)); 13 13 14 14 %if nlines and ncols specified, then bypass. 15 15 if ~exist(options.list{1},'nlines') & ~exist(options.list{1},'ncols') … … 103 103 end 104 104 end % }}} 105 105 106 %Use zbuffer renderer (s noother colors) and white background106 %Use zbuffer renderer (smoother colors) and white background 107 107 set(f,'Renderer','zbuffer','color',getfieldvalue(options.list{1},'figurebackgroundcolor','w')); 108 108 109 109 %Go through all data plottable and close window if an error occurs … … 124 124 rethrow(me); 125 125 end 126 126 else 127 error('plotmodel error message: no output data found. 127 error('plotmodel error message: no output data found.'); 128 128 end -
../trunk-jpl/src/m/plot/plot_manager.m
14 14 15 15 %figure out if this is a special plot 16 16 if ischar(data), 17 18 17 switch data, 19 20 18 case 'boundaries', 21 19 plot_boundaries(md,options,subplotwidth,i); 22 20 return; … … 32 30 case 'highlightelements', 33 31 plot_highlightelements(md,options,subplotwidth,i); 34 32 return; 35 36 33 case 'qmumean', 37 34 plot_qmumean(md,options,nlines,ncols,i); 38 35 return; 39 40 36 case 'qmustddev', 41 37 plot_qmustddev(md,options,nlines,ncols,i); 42 38 return; 43 44 39 case 'qmuhistnorm', 45 40 plot_qmuhistnorm(md,options,nlines,ncols,i); 46 41 return; 47 48 42 case 'qmu_mass_flux_segments', 49 43 plot_qmu_mass_flux_segments(md,options,nlines,ncols,i); 50 44 return; 51 52 45 case 'part_hist', 53 46 plot_parthist(md,options,nlines,ncols,i); 54 47 return; … … 120 113 case 'segments' 121 114 plot_segments(md,options,subplotwidth,i,data) 122 115 return 123 124 116 case 'quiver' 125 117 data=[md.initialization.vx md.initialization.vy]; %Go ahead and try plot_unit 126 127 118 case {'strainrate_tensor','strainrate','strainrate_principal','strainrate_principalaxis1','strainrate_principalaxis2','strainrate_principalaxis3',... 128 119 'stress_tensor','stress','stress_principal','stress_principalaxis1','stress_principalaxis2','stress_principalaxis3',... 129 120 'deviatoricstress_tensor','deviatoricstress','deviatoricstress_principal','deviatoricstress_principalaxis1','deviatoricstress_principalaxis2','deviatoricstress_principalaxis3'}, … … 137 128 return; 138 129 case 'transient_results', 139 130 plot_transient_results(md,options,subplotwidth,i); 140 141 131 case 'transient_field', 142 132 plot_transient_field(md,options,subplotwidth,i); 143 133 return; 144 145 134 otherwise, 146 147 135 if ismember(data,properties('model')), 148 136 data=eval(['md.' data ';']); 149 137 else … … 158 146 return; 159 147 end 160 148 161 %Figure out if this is a semi-transparentplot.149 %Figure out if this is a Google Maps plot. 162 150 if exist(options,'googlemaps'), 163 151 plot_googlemaps(md,data,options,nlines,ncols,i); 164 152 return; 165 153 end 166 154 167 %Figure out if this is a semi-transparent plot.155 %Figure out if this is a landsat plot. 168 156 if getfieldvalue(options,'landsat',0), 169 157 plot_landsat(md,data,options,nlines,ncols,i); 170 158 return; 171 159 end 172 160 173 %Figure out if this is a semi-transparentplot.161 %Figure out if this is a gridded plot. 174 162 if exist(options,'gridded'), 175 163 plot_gridded(md,data,options,nlines,ncols,i); 176 164 return; -
../trunk-jpl/src/m/shp/shpread.py
1 from os import path 2 try: 3 import shapefile 4 except ImportError: 5 print("could not import shapefile, PyShp has not been installed, no shapefile reading capabilities enabled") 6 7 from pairoptions import pairoptions 8 9 10 def shpread(filename, *args): #{{{ 11 ''' 12 SHPREAD - read a shape file and build a dict 13 14 This routine reads a shape file .shp and builds a dict array containing the 15 fields x and y corresponding to the coordinates, one for the filename 16 of the shp file, for the density, for the nodes, and a field closed to 17 indicate if the domain is closed. If this initial shapefile is point only, 18 the fields closed and points are ommited. 19 The first argument is the .shp file to be read and the second one 20 (optional) indicates if the last point shall be read (1 to read it, 0 not 21 to). 22 23 The current implementation of shpread depends on PyShp. 24 25 Usage: 26 dict = shpread(filename) 27 28 Example: 29 From underling PyShp implementation, "The shapefile format is actually 30 a collection of three files. You specify the base filename of the 31 shapefile or the complete filename of any of the shapefile component 32 files."" 33 34 dict = shpread('domainoutline.shp') 35 OR 36 dict = shpread('domainoutline.dbf') 37 OR 38 dict = shpread('domainoutline') 39 40 "OR any of the other 5+ formats which are potentially part of a 41 shapefile. The library does not care about file extensions". We do, 42 however, check that a file with the base filename or base filename with 43 .shp extension exists. 44 45 See also EXPDOC, EXPWRITEASVERTICES 46 47 Sources: 48 - https://github.com/GeospatialPython/pyshp 49 ''' 50 51 #recover options 52 options = pairoptions(*args) 53 54 #some checks 55 if not (path.isfile(filename) or path.isfile(filename + '.shp')): 56 raise RuntimeError('shpread error message: file {} or {}.shp not found!'.format(filename, filename)) 57 58 #read shapefile 59 sf = shapefile.Reader(filename) 60 61 Dicts = [] 62 63 #retrieve ID (if it exists) 64 fields = sf.fields 65 for i in range(1, len(fields)): # skip over first field, which is "DeletionFlag" 66 if fields[i][0] == 'id': 67 name = str(sf.record(i - 1)[0]) # record index is offset by one, again, because of "DeletionFlag" 68 break 69 70 shapes = sf.shapes() 71 for i in range(len(shapes)): 72 Dict = {} 73 shape = shapes[i] 74 if shape.shapeType == shapefile.POINT: 75 Dict['x'] = shape.points[0][0] 76 Dict['y'] = shape.points[0][1] 77 Dict['density'] = 1 78 Dict['Geometry'] = 'Point' 79 elif shape.shapeType == shapefile.POLYLINE: 80 num_points = len(shape.points) 81 x = [] 82 y = [] 83 for j in range(num_points): 84 point = shape.points[j] 85 x.append(point[0]) 86 y.append(point[1]) 87 Dict['x'] = x 88 Dict['y'] = y 89 Dict['nods'] = num_points 90 Dict['density'] = 1 91 Dict['closed'] = 1 92 Dict['BoundingBox'] = shape.bbox 93 Dict['Geometry'] = 'Line' 94 elif shape.shapeType == shapefile.POLYGON: 95 num_points = len(shape.points) 96 x = [] 97 y = [] 98 for j in range(num_points): 99 point = shape.points[j] 100 x.append(point[0]) 101 y.append(point[1]) 102 Dict['x'] = x 103 Dict['y'] = y 104 Dict['nods'] = num_points 105 Dict['density'] = 1 106 Dict['closed'] = 1 107 Dict['BoundingBox'] = shape.bbox 108 Dict['Geometry'] = 'Polygon' 109 else: 110 # NOTE: We could do this once before looping over shapes as all 111 # shapes in the file must be of the same type, but we would 112 # need to have a second check anyway in order to know how to 113 # parse the points. So, let's just assume the file is not 114 # malformed. 115 # 116 raise Exception('shpread error: geometry {} is not currently supported'.format(shape.shapeTypeName)) 117 name = '' 118 fields = sf.fields 119 for j in range(1, len(fields)): # skip over first field, which is "DeletionFlag" 120 fieldname = fields[j][0] 121 # 'id' field gets special treatment 122 if fieldname == 'id': 123 name = str(sf.record(j - 1)[0]) # record index is offset by one, again, because of "DeletionFlag" 124 else: 125 Dict[fieldname] = sf.record(j - 1)[0] 126 Dict['name'] = name 127 Dicts.append(Dict) 128 129 invert = options.getfieldvalue('invert', 0) 130 if invert: 131 for i in range(len(Dicts)): 132 Dicts[i].x = np.flipud(Dicts[i].x) 133 Dicts[i].y = np.flipud(Dicts[i].y) 134 135 return Dicts 136 #}}} -
../trunk-jpl/src/m/shp/shpread.m
1 1 function Struct=shpread(filename,varargin) 2 %SHPREAD - read a shape file and build a Structure2 %SHPREAD - read a shape file and build a struct 3 3 % 4 % This routine reads a shape file .shp and builds a Structure containing the5 % fields x and y corresponding to the coordinates, one for the filename of6 % the shp file, for the density, for the nodes, and a field closed to7 % indicate if the domain is closed.8 % If this initial shapefile is point only, the fields closed and9 % points are ommited10 % The first argument is the .shp file to be read and the second one (optional)11 % indicates if the last point shall be read (1 to read it, 0 notto).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). 12 12 % 13 % 14 % 13 % Usage: 14 % Struct=shpread(filename) 15 15 % 16 % 17 % 16 % Example: 17 % Struct=shpread('domainoutline.shp') 18 18 % 19 % 19 % See also EXPDOC, EXPWRITEASVERTICES 20 20 21 21 %recover options 22 22 options=pairoptions(varargin{:}); … … 26 26 error(['shpread error message: file ' filename ' not found!']); 27 27 end 28 28 29 %initialize number of profile30 count=0;31 32 29 %read shapefile 33 30 shp=shaperead(filename); 34 31 … … 35 32 Struct=struct([]); 36 33 fields=fieldnames(shp); 37 34 for i=1:length(shp), 38 if strcmpi(shp(i).Geometry,'Po lygon'),35 if strcmpi(shp(i).Geometry,'Point'), 39 36 x=shp(i).X'; y=shp(i).Y'; 40 37 ids=find(isnan(x)); 41 38 x(ids)=[]; y(ids)=[]; … … 42 39 43 40 Struct(end+1).x=x; 44 41 Struct(end).y=y; 45 Struct(end).nods=length(x);46 42 Struct(end).density=1; 47 Struct(end).closed=1;48 43 if isfield(shp,'id'), 49 44 Struct(end).name=num2str(shp(i).id); 50 45 else … … 56 51 Struct(end).(field)=shp(i).(field); 57 52 end 58 53 end 59 end 60 61 if strcmpi(shp(i).Geometry,'Line'), 54 elseif strcmpi(shp(i).Geometry,'Line'), 62 55 x=shp(i).X'; y=shp(i).Y'; 63 56 ids=find(isnan(x)); 64 57 x(ids)=[]; y(ids)=[]; … … 79 72 Struct(end).(field)=shp(i).(field); 80 73 end 81 74 end 82 end 83 84 85 if strcmpi(shp(i).Geometry,'Point'), 75 elseif strcmpi(shp(i).Geometry,'Polygon'), 86 76 x=shp(i).X'; y=shp(i).Y'; 87 77 ids=find(isnan(x)); 88 78 x(ids)=[]; y(ids)=[]; … … 89 79 90 80 Struct(end+1).x=x; 91 81 Struct(end).y=y; 82 Struct(end).nods=length(x); 92 83 Struct(end).density=1; 84 Struct(end).closed=1; 93 85 if isfield(shp,'id'), 94 86 Struct(end).name=num2str(shp(i).id); 95 87 else -
../trunk-jpl/src/m/mesh/planet/gmsh/gmshplanet.py
1 import os2 1 import subprocess 3 2 4 3 import numpy as np … … 9 8 from pairoptions import * 10 9 11 10 12 def gmshplanet(* varargin):11 def gmshplanet(*args): 13 12 ''' 14 13 GMSHPLANET - mesh generation for a sphere. Very specific code for gmsh from $ISSM_DIR/src/demos/simple_geo/sphere.geo 15 14 … … 33 32 raise RuntimeError('gmshplanet: Gmsh major version %s not supported!' % gmshmajorversion) 34 33 35 34 #process options 36 options = pairoptions(* varargin)35 options = pairoptions(*args) 37 36 #options = deleteduplicates(options, 1) 38 37 39 38 #recover parameters: -
../trunk-jpl/src/m/coordsystems/gdaltransform.py
5 5 6 6 from loadvars import * 7 7 8 8 9 def gdaltransform(x, y, proj_in, proj_out): #{{{ 9 10 ''' 10 11 GDALTRANSFORM - switch from one projection system to another 11 12 12 13 13 Usage: 14 [x, y] = gdaltransform(x1, y1, epsg_in, epsg_out) 14 15 15 16 16 Example: 17 [x, y] = gdaltranform(md.mesh.long, md.mesh.lat, 'EPSG:4326', 'EPSG:3031') 17 18 18 19 20 21 19 For reference: 20 EPSG: 4326 (lat, long) 21 EPSG: 3341 (Greenland, UPS 45W, 70N) 22 EPSG: 3031 (Antarctica, UPS 0E, 71S) 22 23 23 24 25 26 27 28 24 ll2xy default projection Antarctica: 25 +proj = stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.448564109 +units=m +no_defs 26 ll2xy default projection Greenland: 27 +proj = stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.448564109 +units=m +no_defs 28 Bamber's Greenland projection 29 +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 29 30 30 31 To get proj.4 string form EPSG, use gdalsrsinfo. Example: 31 32 32 gdalsrsinfo epsg:4326 | grep "PROJ.4" | sed "s/PROJ.4 : //" 33 gdalsrsinfo epsg:4326 | grep "PROJ.4" | sed "s/PROJ.4 : //" 34 35 TODO: 36 - Remove shlex and follow subprocess pattern implemented in src/m/coordsystems/epsg2proj.py 33 37 ''' 34 38 35 39 # Give ourselves unique file names … … 41 45 file_in.write(b'%8g %8g\n' % (x.flatten(1) y.flatten(1))) 42 46 file_in.close() 43 47 44 args = shlex.split('gdaltransform -s_srs %s -t_srs %s < %s > %s' %(proj_in, proj_out, filename_in, filename_out))48 args = shlex.split('gdaltransform -s_srs {} -t_srs {} < {} > {}'.format(proj_in, proj_out, filename_in, filename_out)) 45 49 subprocess.check_call(args) # Will raise CalledProcessError if return code is not 0 46 50 47 51 A = loadvars(filename_out) … … 52 56 53 57 os.remove(filename_in) 54 58 os.remove(filename_out) 59 60 return [xout, yout] 55 61 #}}} -
../trunk-jpl/src/m/geometry/polyarea.py
1 import math 2 3 import numpy as np 4 5 6 def polyarea: #{{{ 7 ''' 8 POLYAREA - returns the area of the 2-D polygon defined by the vertices in 9 lists x and y 10 11 Partial implementation of MATLAB's polyarea function. If x and y are 12 lists of the same length, then polyarea returns the scalar area of the 13 polygon defined by x and y. 14 15 Usage: 16 a = polyarea(x, y) 17 18 Sources: 19 - https://www.mathworks.com/help/matlab/ref/polyarea.html 20 - https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates 21 - https://en.wikipedia.org/wiki/Shoelace_formula 22 23 TODO: 24 - Test that output falls within some tolerance of MATLAB's polyarea 25 function. 26 ''' 27 return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) 28 #}}} -
../trunk-jpl/src/m/classes/boundary.py
1 import math 2 3 import numpy as np 4 5 from epsg2proj import epsg2proj 6 from pairoptions import pairoptions 7 from shpread import shpread 8 9 10 class boundary(object): #{{{ 11 ''' 12 BOUNDARY class definition 13 14 Usage: 15 boundary = boundary() 16 ''' 17 18 def __init__(self, *args): #{{{ 19 self.boundaries = [] 20 self.name = '' 21 self.continent = '' 22 self.proj = epsg2proj(4326) 23 24 self.setdefaultparameters() 25 26 if len(args): 27 options = pairoptions(*args) 28 29 #recover field values 30 self.shppath = options.getfieldvalue('shppath', '') 31 self.shpfilename = options.getfieldvalue('shpfilename', '') 32 self.orientation = options.getfieldvalue('orientation', 'normal') 33 34 #figure out projection string: 35 if options.exist('epsg'): 36 if options.exist('proj'): 37 raise RuntimeError('Error in constructor for boundary {}. Cannot supply epsg and proj at the same time!'.format(self.shppath)) 38 epsg = options.getfieldvalue('epsg') 39 proj = epsg2proj(epsg) # convert to PROJ.4 format 40 elif options.exist('proj'): 41 if options.exist('epsg'): 42 raise RuntimeError('Error in constructor for boundary {}. Cannot supply proj and epsg at the same time!'.format(self.shppath)) 43 proj = options.getfieldvalue('proj') 44 else: 45 proj = '+proj=longlat +datum=WGS84 +no_defs' 46 47 self.proj = proj 48 #}}} 49 50 def __repr__(self): #{{{ 51 s = ' boundary parameters:\n' 52 s += '{}\n'.format(fielddisplay(self, 'shppath', 'path to filename for this boundary')) 53 s += '{}\n'.format(fielddisplay(self, 'shpfilename', 'shape file name')) 54 s += '{}\n'.format(fielddisplay(self, 'orientation', 'orientation (default is \'normal\', can be \'reverse\')')) 55 s += '{}\n'.format(fielddisplay(self, 'proj', 'shape file projection string (follows PROJ.4 standard)')) 56 57 return s 58 #}}} 59 60 def setdefaultparameters(self): #{{{ 61 self.shppath = '' 62 self.shpfilename = '' 63 self.orientation = 'normal' 64 self.proj = '+proj=longlat +datum=WGS84 +no_defs' #EPSG 4326 65 66 return self 67 #}}} 68 69 def name(self): #{{{ 70 output = self.shpfilename 71 72 return output 73 #}}} 74 75 def edges(self): #{{{ 76 #read domain 77 path, name, ext = fileparts(shp.shpfilename) 78 if ext != 'shp': 79 ext = 'shp' 80 output = shpread('{}/{}.{}'.format(self.shppath, name, ext)) 81 82 #do we reverse? 83 if self.orientation == 'reverse': 84 output.x = np.flipud(output.x) 85 output.y = np.flipud(output.y) 86 #}}} 87 88 def plot(self, *args): #{{{ 89 #recover options 90 options = pairoptions(*args) 91 92 #parse input 93 # TODO: Sort out what options we should set (see 94 # src/m/classes/boundary.m) 95 96 if options.exist('epsg'): 97 if options.exist('proj'): 98 raise RuntimeError('Boundary plot error message: cannot specify epsg and proj at the same time for plot projection') 99 proj = epsg2proj(options.getfieldvalue('epsg')) 100 elif options.exist('proj'): 101 proj = options.getfieldvalue('proj') 102 else: 103 proj = epsg2proj(4326) 104 105 #read domain 106 path, name, ext = fileparts(shp.shpfilename) 107 if ext != 'shp': 108 ext = 'shp' 109 domain = shpread('{}/{}.{}'.format(self.shppath, name, ext)) 110 111 #convert boundary to another reference frame #{{{ 112 for i in range(len(domain)): 113 try: 114 x, y = gdaltransform(domain[i].x, domain[i].y, self.proj, proj) 115 except error as e: 116 print(e) 117 print(self) 118 119 # TODO: Figure out how to recover figure here: do we pass 'fig' and 120 # 'ax' in args? 121 #for i in range(len(domain)): 122 # x = domain[i].x * unitmultiplier 123 # y = domain[i].y * unitmultiplier 124 # if len(x) == 1: 125 #}}} 126 127 #TODO: Finish translating from MATLAB after test2004.py runs without plot 128 #}}} 129 130 def checkconsistency(self, *args): #{{{ 131 #recover options 132 options = pairoptions(*args) 133 tolerance = getfieldvalue(options, 'tolerance', 1e-5) 134 135 #recover edges 136 edges = self.edges() 137 138 if edges.Geometry == 'Point': 139 return 140 else: 141 #check that we don't have two identical vertices 142 x = edges.x 143 y = edges.y 144 distance = math.sqrt((x[:-2] - x[1:-1]) ** 2 + (y[:-2] - y[1:-1]) ** 2) 145 dmax = distance.max() 146 isidentical = np.where(np.asarray(distance) < dmax * tolerance) 147 for elem in isidentical: # distance should be a 1D array, but return from np.where is a tuple of arrays 148 if len(elem) != 0: 149 raise Exception('boundary {} has two vertices extermely close to one another'.format(shpfilename)) 150 151 def plot3d(self, *args): #{{{ 152 #recover options 153 options = pairoptions(*args) 154 155 #parse input 156 # TODO: Sort out what options we should set (see 157 # src/m/classes/boundary.m) 158 159 if options.exist('epsg'): 160 if options.exist('proj'): 161 raise RuntimeError('Boundary plot error message: cannot specify epsg and proj at the same time for plot projection') 162 proj = epsg2proj(options.getfieldvalue('epsg')) 163 elif options.exist('proj'): 164 proj = options.getfieldvalue('proj') 165 else: 166 proj = epsg2proj(4326) 167 168 #read domain 169 path, name, ext = fileparts(shp.shpfilename) 170 if ext != 'shp': 171 ext = 'shp' 172 domain = shpread('{}/{}.{}'.format(self.shppath, name, ext)) 173 174 #TODO: Finish translating from MATLAB after test2004.py runs without plot 175 #}}} 176 #}}} -
../trunk-jpl/src/m/classes/sealevelmodel.m
162 162 list=unique(list); 163 163 end % }}} 164 164 function addbasin(self,bas) % {{{ 165 if ~strcmpi(class(bas),'basin')166 error('addbasin method only takes a ''basin'' class object as input');167 end;168 self.basins{end+1}=bas;165 if ~strcmpi(class(bas),'basin') 166 error('addbasin method only takes a ''basin'' class object as input'); 167 end; 168 self.basins{end+1}=bas; 169 169 end % }}} 170 170 function intersections(self,varargin) % {{{ 171 171 -
../trunk-jpl/src/m/classes/sealevelmodel.py
10 10 from private import private 11 11 from TwoDToThreeD import TwoDToThreeD 12 12 13 13 14 class sealevelmodel(object): 14 15 ''' 15 16 SEALEVELMODEL class definition 16 17 17 18 18 Usage: 19 slm = sealevelmodel(*args) 19 20 20 21 where args is a variable list of options 21 22 22 23 24 25 26 27 23 Example: 24 slm = sealevelmodel( 25 'icecap', md_greenland, 26 'icecap', md_antarctica, 27 'earth', md_earth 28 ) 28 29 ''' 29 30 30 31 def __init__(self, *args): #{{{ … … 58 59 #}}} 59 60 60 61 def __repr__(self): # {{{ 61 s = ' %s\n' % fielddisplay(self, 'icecaps', 'ice caps')62 s += ' %s\n' % fielddisplay(self, 'earth', 'earth')63 s += ' %s\n' % fielddisplay(self, 'settings', 'settings properties')64 s += ' %s\n' % fielddisplay(self, 'cluster', 'cluster parameters (number of cpus...')65 s += ' %s\n' % fielddisplay(self, 'miscellaneous', 'miscellaneous fields')62 s = '{}\n'.format(fielddisplay(self, 'icecaps', 'ice caps')) 63 s += '{}\n'.format(fielddisplay(self, 'earth', 'earth')) 64 s += '{}\n'.format(fielddisplay(self, 'settings', 'settings properties')) 65 s += '{}\n'.format(fielddisplay(self, 'cluster', 'cluster parameters (number of cpus...')) 66 s += '{}\n'.format(fielddisplay(self, 'miscellaneous', 'miscellaneous fields')) 66 67 #}}} 67 68 68 69 def setdefaultparameters(self): # {{{ … … 84 85 # Is the coupler turned on? 85 86 for i in range(len(slm.icecaps)): 86 87 if slm.icecaps[i].transient.iscoupler == 0: 87 warnings.warn('sealevelmodel checkconsistency error: icecap model %s should have the transient coupler option turned on!' % slm.icecaps[i].miscellaneous.name)88 warnings.warn('sealevelmodel checkconsistency error: icecap model {} should have the transient coupler option turned on!'.format(slm.icecaps[i].miscellaneous.name)) 88 89 89 90 if slm.earth.transient.iscoupler == 0: 90 91 warnings.warn('sealevelmodel checkconsistency error: earth model should have the transient coupler option turned on!') … … 92 93 # Check that the transition vectors have the right size 93 94 for i in range(len(slm.icecaps)): 94 95 if slm.icecaps[i].mesh.numberofvertices != len(slm.earth.slr.transitions[i]): 95 raise RuntimeError('sealevelmodel checkconsistency issue with size of transition vector for ice cap: %i name: %s' %(i, slm.icecaps[i].miscellaneous.name))96 raise RuntimeError('sealevelmodel checkconsistency issue with size of transition vector for ice cap: {} name: {}'.format(i, slm.icecaps[i].miscellaneous.name)) 96 97 97 98 # Check that run frequency is the same everywhere 98 99 for i in range(len(slm.icecaps)): 99 100 if slm.icecaps[i].slr.geodetic_run_frequency != slm.earth.geodetic_run_frequency: 100 raise RuntimeError('sealevelmodel checkconsistency error: icecap model %s should have the same run frequency as earth!' % slm.icecaps[i].miscellaneous.name)101 raise RuntimeError('sealevelmodel checkconsistency error: icecap model {} should have the same run frequency as earth!'.format(slm.icecaps[i].miscellaneous.name)) 101 102 102 103 # Make sure steric_rate is the same everywhere 103 104 for i in range(len(slm.icecaps)): 104 105 md = slm.icecaps[i] 105 106 if np.nonzero(md.slr.steric_rate - slm.earth.slr.steric_rate[slm.earth.slr.transitions[i]]) != []: 106 raise RuntimeError('steric rate on ice cap %s is not the same as for the earth' % md.miscellaneous.name)107 raise RuntimeError('steric rate on ice cap {} is not the same as for the earth'.format(md.miscellaneous.name)) 107 108 #}}} 108 109 109 110 def mergeresults(self): # {{{ … … 137 138 138 139 def listcaps(self): # {{{ 139 140 for i in range(len(self.icecaps)): 140 print(' %i: %s' %(i, self.icecaps[i].miscellaneous.name))141 print('{}: {}'.format(i, self.icecaps[i].miscellaneous.name)) 141 142 #}}} 142 143 143 144 def continents(self): # {{{ … … 184 185 yei = mdi.mesh.y[mdi.mesh.elements] * onesmatrix / 3 185 186 zei = mdi.mesh.z[mdi.mesh.elements] * onesmatrix / 3 186 187 187 print('Computing vertex intersections for basin %s' % self.basins[i].name)188 print('Computing vertex intersections for basin {}'.format(self.basins[i].name)) 188 189 189 190 self.transitions.append(meshintersect3d(self.earth.mesh.x, self.earth.mesh.y, self.earth.mesh.z, mdi.mesh.x, mdi.mesh.y, mdi.mesh.z, 'force', force)) 190 191 self.eltransitions.append(meshintersect3d(xe, ye, ze, xei, yei, zei, 'force', force)) -
../trunk-jpl/src/m/classes/basin.py
1 import math 2 3 from boundary import boundary 4 from epsg2proj import epsg2proj 5 from helpers import fileparts 6 from laea import laea 7 from pairoptions import pairoptions 8 from polyarea import polyarea 9 from shpread import shpread 10 11 12 class basin(object): #{{{ 13 ''' 14 BASIN class definition 15 16 Usage: 17 basin = basin() 18 ''' 19 20 def __init__(self, *args): #{{{ 21 self.boundaries = [] 22 self.name = '' 23 self.continent = '' 24 self.proj = epsg2proj(4326) 25 26 self.setdefaultparameters() 27 28 if len(args): 29 options = pairoptions(*args) 30 31 #recover field values 32 self.boundaries = options.getfieldvalue('boundaries', []) 33 self.name = options.getfieldvalue('name', '') 34 self.continent = options.getfieldvalue('continent', '') 35 36 # figure out projection string 37 if options.exist('epsg'): 38 if options.exist('proj'): 39 raise RuntimeError('Error in constructor for basin %s. Cannot supply epsg and proj at the same time!'.format(self.name)) 40 epsg = options.getfieldvalue('epsg', '') 41 proj = epsg2proj(epsg)#convert to PROJ.4 format 42 elif options.exist('proj'): 43 if options.exist('epsg'): 44 raise RuntimeError('Error in constructor for basin {}. Cannot supply proj and epsg at the same time!'.format(self.name)) 45 proj = options.getfieldvalue('proj', '') 46 else: 47 proj = '+proj=longlat +datum=WGS84 +no_defs' 48 49 self.proj = proj 50 #}}} 51 52 def __repr__(self): # {{{ 53 s = ' basin parameters:\n' 54 s += '{}\n'.format(fielddisplay(self, 'continent', 'continent name')) 55 s += '{}\n'.format(fielddisplay(self, 'name', 'basin name')) 56 s += '{}\n'.format(fielddisplay(self, 'proj', 'basin projection string (follows PROJ.4 standard')) 57 s += '{}\n'.format(fielddisplay(self, 'boundaries','list of boundary objects')) 58 for i in range(len(self.boundaries)): 59 s += ' boundary #{}: {}\n'.format((i + 1), self.boundaries[i]) 60 61 return s 62 #}}} 63 64 def setdefaultparameters(self): # {{{ 65 self.name = '' 66 self.continent = '' 67 self.proj = '+proj=longlat +datum=WGS84 +no_defs' #EPSG 4326 68 self.boundaries = [] 69 70 return self 71 #}}} 72 73 def isnameany(self, *args): #{{{ 74 for arg in args: 75 if arg == self.name: 76 return 1 77 return 0 78 #}}} 79 80 def iscontinentany(self, *args): #{{{ 81 for arg in args: 82 if arg == self.continent: 83 return 1 84 return 0 85 #}}} 86 87 def outputname(self, *args): #{{{ 88 #recover options 89 options = pairoptions(*args) 90 extension = options.getfieldvalue('extension', 1) 91 92 path, name, ext = fileparts(*args) 93 if extension: 94 output = '{}{}'.format(name, ext) 95 else: 96 output = name 97 98 return output 99 #}}} 100 101 def plot(self, *args): #{{{ 102 #add option 103 for i in range(len(self.boundaries)): 104 self.boundaries[i].plot('proj', self.proj, *args) 105 #}}} 106 107 def plot3d(self, *args): #{{{ 108 #add option 109 for i in range(len(self.boundaries)): 110 self.boundaries[i].plot3d(*args) 111 #}}} 112 113 def contour(self, *args): #{{{ 114 #recover options 115 options = pairoptions(*args) 116 x = [] 117 y = [] 118 119 #go through boundaries, recover edges and project them in the basin epsg reference frame 120 for i in range(len(self.boundaries)): 121 boundary = self.boundaries[i] 122 contour = boundary.edges() 123 contour.x, contour.y = gdaltransform(contour.x, contour.y, boundary.proj, self.proj) 124 x = [[x], [contour.x]] 125 y = [[y], [contour.y]] 126 127 #close the contour 128 if x[-1] != x[0] or y[-1] != y[0]: 129 x.append(x[0]) 130 y.append(y[0]) 131 132 setattr(out, 'x', x) 133 setattr(out, 'y', y) 134 setattr(out, 'nods', len(x)) 135 136 return out 137 #}}} 138 139 def checkconsistency(self, *args): #{{{ 140 #recover options 141 options = pairoptions(*args) 142 143 #figure out if two boundaries are identical 144 for i in range(len(self.boundaries)): 145 namei = self.boundaries[i].shpfilename 146 for j in range(1, len(self.boundaries)): 147 namej = self.boundaries[j].shpfilename 148 if namei == namej: 149 raise RuntimeError('Basin {} has two identical boundaries named {}'.format(self.name, namei)) 150 151 #go through boundaries and check their consistency 152 for i in range(len(self.boundaries)): 153 boundary == self.boundaries[i] 154 boundary.checkconsistency() 155 #}}} 156 157 def contourplot(self, *args): #{{{ 158 contour = self.contour() 159 plot(contour.x, contour.y, 'r*-') 160 #}}} 161 162 def shapefilecrop(self, *args): #{{{ 163 #recover options 164 options = pairoptions(*args) 165 threshold = options.getfieldvalue('threshold', .65) #.65 degrees lat, long 166 inshapefile = options.getfieldvalue('shapefile') 167 outshapefile = options.getfieldvalue('outshapefile', '') 168 169 if options.exist('epsgshapefile') and options.exist('projshapefile'): 170 raise RuntimeError('Basin shapefilecrop error messgae: cannot specify epsgshapefile and projshapefile at the same time') 171 172 if options.exist('epsgshapefile'): 173 projshapefile = epsg2proj(options.getfieldvalue('epsgshapefile')) 174 elif options.exist('projshapefile'): 175 projshapefile = options.getfieldvalue('projshapefile') 176 else: 177 raise RuntimeError('Basin shapefilecrop error message: epsgshapefile or projshapefile should be specified') 178 179 #create list of contours that have critical length > threshold (in lat, long) 180 contours = shpread(inshapefile) 181 llist = [] 182 for i in range(len(contours)): 183 contour = contours[i] 184 carea = polyarea(contour.x, contour.y) 185 clength = math.sqrt(carea) 186 if clength < threshold: 187 llist = np.concatenate(llist, i) 188 setattr(contours, llist, []) 189 190 #project onto reference frame 191 for i in range(len(contours)): 192 h = contours[i] 193 h.x, h.y = gdaltransform(h.x, h.y, projshapefile, self.proj) 194 contours[i].x = h.x 195 contours[i].y = h.y 196 197 #only keep the contours that are inside the basin (take centroids) 198 ba = self.contour() 199 flags = np.zeros(len(contours)) 200 for i in range(len(contours)) 201 h = contours[i] 202 isin = inpolygon(h.x, h.y, ba.x, ba.y) 203 if len(np.where(isin == 0, isin, isin)): 204 flags[i] = 1 205 pos = flags.nonzero() 206 contours[pos] = [] 207 208 #Two options 209 if outputshapefile == '': 210 output = contours 211 else: 212 shpwrite(contours, outputshapefile) 213 #}}} 214 #}}} -
../trunk-jpl/src/m/classes/boundary.m
19 19 end 20 20 methods 21 21 function self = boundary(varargin) % {{{ 22 switch nargin 23 case 0 24 self=setdefaultparameters(self); 25 otherwise 26 self=setdefaultparameters(self); 27 options=pairoptions(varargin{:}); 28 29 %recover field values: 30 self.shppath=getfieldvalue(options,'shppath',''); 31 self.shpfilename=getfieldvalue(options,'shpfilename',''); 32 self.orientation=getfieldvalue(options,'orientation','normal'); 22 self=setdefaultparameters(self); 33 23 34 %figure out projection string: 24 if nargin > 0, 25 options=pairoptions(varargin{:}); 26 27 %recover field values: 28 self.shppath=getfieldvalue(options,'shppath',''); 29 self.shpfilename=getfieldvalue(options,'shpfilename',''); 30 self.orientation=getfieldvalue(options,'orientation','normal'); 31 32 %figure out projection string: 33 if exist(options,'epsg'), 34 if exist(options,'proj'), 35 error(['Error in constructor for boundary ' self.shppath '. Cannot supply epsg and proj at the same time!']); 36 end 37 epsg=getfieldvalue(options,'epsg'); 38 proj=epsg2proj(epsg); % convert to PROJ.4 format 39 elseif exist(options,'proj'), 35 40 if exist(options,'epsg'), 36 if exist(options,'proj'), 37 error(['Error in constructor for boundary ' self.shppath '.Cannot supply epsg and proj at the same time!']); 38 end 39 epsg=getfieldvalue(options,'epsg'); 40 %convert into proj4: 41 proj=epsg2proj(epsg); 42 elseif exist(options,'proj'), 43 if exist(options,'epsg'), 44 error(['Error in constructor for boundary ' self.shppath '.Cannot supply epsg and proj at the same time!']); 45 end 46 proj=getfieldvalue(options,'proj'); 47 else 48 proj= '+proj=longlat +datum=WGS84 +no_defs'; 41 error(['Error in constructor for boundary ' self.shppath '. Cannot supply proj and epsg at the same time!']); 49 42 end 50 self.proj=proj; 43 proj=getfieldvalue(options,'proj'); 44 else 45 proj= '+proj=longlat +datum=WGS84 +no_defs'; 46 end 47 self.proj=proj; 51 48 end 52 49 end % }}} 53 50 function self = setdefaultparameters(self) % {{{ … … 54 51 self.shppath=''; 55 52 self.shpfilename=''; 56 53 self.orientation='normal'; 57 self.proj='+proj=longlat +datum=WGS84 +no_defs 54 self.proj='+proj=longlat +datum=WGS84 +no_defs'; %EPSG 4326 58 55 end % }}} 59 56 function disp(self) % {{{ 60 57 disp(sprintf(' boundary parameters:')); … … 69 66 output=self.shpfilename; 70 67 end % }}} 71 68 function output=edges(self) % {{{ 72 73 %read domain:74 [path,name,ext]=fileparts(self.shpfilename);75 if ~strcmpi(ext,'shp'),76 ext='shp';77 end78 output=shpread([self.shppath '/' name '.' ext]);79 69 80 %do we reverse? 81 if strcmpi(self.orientation,'reverse'), 82 output.x=flipud(output.x); 83 output.y=flipud(output.y); 84 end 70 %read domain: 71 [path,name,ext]=fileparts(self.shpfilename); 72 if ~strcmpi(ext,'shp'), 73 ext='shp'; 74 end 75 output=shpread([self.shppath '/' name '.' ext]); 76 77 %do we reverse? 78 if strcmpi(self.orientation,'reverse'), 79 output.x=flipud(output.x); 80 output.y=flipud(output.y); 81 end 85 82 end % }}} 86 83 function plot(self,varargin) % {{{ 87 84 %recover options … … 100 97 fontsize=getfieldvalue(options,'fontsize',10); 101 98 label=getfieldvalue(options,'label','on'); 102 99 103 if (exist(options,'epsg') & exist(options,'proj')), 104 error('Boundary plot error message: cannot specify epsg and proj at the same time for plot projection'); 105 end 106 if exist(options,'epsg'), 100 if (exist(options,'epsg'), 101 if exist(options,'proj')), 102 error('Boundary plot error message: cannot specify epsg and proj at the same time for plot projection'); 107 103 proj=epsg2proj(getfieldvalue(options,'epsg')); 108 104 elseif exist(options,'proj'), 109 105 proj=getfieldvalue(options,'proj'); … … 118 114 end 119 115 domain=shpread([self.shppath '/' name '.' ext]); 120 116 121 %convert boundary to another reference frame: 117 %convert boundary to another reference frame: {{{ 122 118 for i=1:length(domain), 123 119 try, 124 120 [x,y] = gdaltransform(domain(i).x,domain(i).y,self.proj,proj); … … 168 164 dmax=max(distance); 169 165 isidentical=find(distance<dmax*tolerance); 170 166 if ~isempty(isidentical), 171 error(['boundary ' shpfilename ' has two 167 error(['boundary ' shpfilename ' has two vertices extremely close to one another']); 172 168 end 173 169 end 174 170 end % }}} … … 189 185 fontsize=getfieldvalue(options,'fontsize',10); 190 186 label=getfieldvalue(options,'label','on'); 191 187 188 if (exist(options,'epsg'), 189 if exist(options,'proj')), 190 error('Boundary plot error message: cannot specify epsg and proj at the same time for plot projection'); 191 proj=epsg2proj(getfieldvalue(options,'epsg')); 192 elseif exist(options,'proj'), 193 proj=getfieldvalue(options,'proj'); 194 else 195 proj=epsg2proj(4326); 196 end 197 192 198 %read domain: 193 199 [path,name,ext]=fileparts(self.shpfilename); 194 200 if ~strcmpi(ext,'shp'), -
../trunk-jpl/src/m/plot/plotmodel.py
1 import numpy as np2 from plotoptions import plotoptions3 from plot_manager import plot_manager4 1 from math import ceil, sqrt 5 2 6 3 try: … … 8 5 from mpl_toolkits.axes_grid1 import ImageGrid 9 6 except ImportError: 10 7 print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled") 8 import numpy as np 11 9 10 from plot_manager import plot_manager 11 from plotoptions import plotoptions 12 12 13 13 14 def plotmodel(md, *args): 14 ''' at command prompt, type 'plotdoc()' for additional documentation15 15 ''' 16 PLOTMODEL - At command prompt, type 'plotdoc()' for additional 17 documentation. 16 18 19 TODO: 20 - Fix 'plotdoc()', as it is not currently working. 21 ''' 22 17 23 #First process options 18 24 options = plotoptions(*args) 19 #get number of subplots 20 subplotwidth = ceil(sqrt(options.numberofplots)) 25 21 26 #Get figure number and number of plots 22 27 figurenumber = options.figurenumber 23 28 numberofplots = options.numberofplots 24 29 25 #get hold26 hold = options.list[0].getfieldvalue('hold', False)30 #get number of subplots 31 subplotwidth = ceil(sqrt(numberofplots)) 27 32 33 # TODO: Check that commenting this out is correct; we do not need a hold 34 # under matplotlib, right? 35 # 36 # #get hold 37 # hold = options.list[0].getfieldvalue('hold', False) 38 28 39 #if nrows and ncols specified, then bypass 29 40 if options.list[0].exist('nrows'): 30 41 nrows = options.list[0].getfieldvalue('nrows') … … 43 54 nrows = int(nrows) 44 55 45 56 #check that nrows and ncols were given at the same time! 46 if n ot nr == nc:47 raise Exception(' error: nrows and ncols need to be specified together, or not at all')57 if nr != nc: 58 raise Exception('plotmodel error message: nrows and ncols need to be specified together, or not at all') 48 59 49 #Go through plots 60 # Go through plots 61 # 62 # NOTE: The following is where Python + matplolib differs substantially in 63 # implementation and inteface from MATLAB. 64 # 65 # Sources: 66 # - https://matplotlib.org/api/_as_gen/mpl_toolkits.axes_grid1.axes_grid.ImageGrid.html 67 # 50 68 if numberofplots: 51 #if plt.fignum_exists(figurenumber):52 # plt.cla()53 54 69 #if figsize specified 55 70 if options.list[0].exist('figsize'): 56 71 figsize = options.list[0].getfieldvalue('figsize') … … 62 77 backgroundcolor = options.list[0].getfieldvalue('backgroundcolor', (0.7, 0.7, 0.7)) 63 78 fig.set_facecolor(backgroundcolor) 64 79 65 translator = {'on': 'each', 66 'off': 'None', 67 'one': 'single'} 68 # options needed to define plot grid 80 # options needed to define plot grid 69 81 plotnum = options.numberofplots 70 82 if plotnum == 1: 71 83 plotnum = None 72 direction = options.list[0].getfieldvalue('direction', 'row') # row, column 73 axes_pad = options.list[0].getfieldvalue('axes_pad', 0.25) 74 add_all = options.list[0].getfieldvalue('add_all', True) # True, False 75 share_all = options.list[0].getfieldvalue('share_all', True) # True, False 76 label_mode = options.list[0].getfieldvalue('label_mode', 'L') # 1, L, all 84 85 # NOTE: The inline comments for each of the following parameters are 86 # taken from https://matplotlib.org/api/_as_gen/mpl_toolkits.axes_grid1.axes_grid.ImageGrid.html 87 # 88 direction = options.list[0].getfieldvalue('direction', 'row') # {"row", "column"}, default: "row" 89 axes_pad = options.list[0].getfieldvalue('axes_pad', 0.25) # float or (float, float), default : 0.02; Padding or (horizonal padding, vertical padding) between axes, in inches 90 add_all = options.list[0].getfieldvalue('add_all', True) # bool, default: True 91 share_all = options.list[0].getfieldvalue('share_all', True) # bool, default: False 92 label_mode = options.list[0].getfieldvalue('label_mode', 'L') # {"L", "1", "all"}, default: "L"; Determines which axes will get tick labels: "L": All axes on the left column get vertical tick labels; all axes on the bottom row get horizontal tick labels;. "1": Only the bottom left axes is labelled. "all": all axes are labelled. 93 94 # Translate MATLAB colorbar mode to matplotlib 95 # 96 # TODO: 97 # - Add 'edge' option (research if there is a corresponding option in 98 # MATLAB)? 99 # 77 100 colorbar = options.list[0].getfieldvalue('colorbar', 'on') # on, off (single) 78 cbar_mode = translator[colorbar]79 cbar_location = options.list[0].getfieldvalue('colorbarpos', 'right') # right, top80 cbar_size = options.list[0].getfieldvalue('colorbarsize', '5%')81 cbar_pad = options.list[0].getfieldvalue('colorbarpad', 0.025) # None or %82 101 83 axgrid = ImageGrid(fig, 111, 84 nrows_ncols=(nrows, ncols), 85 direction=direction, 86 axes_pad=axes_pad, 87 add_all=add_all, 88 share_all=share_all, 89 label_mode=label_mode, 90 cbar_mode=cbar_mode, 91 cbar_location=cbar_location, 92 cbar_size=cbar_size, 93 cbar_pad=cbar_pad) 102 if colorbar == 'on': 103 colorbar = 'each' 104 elif colorbar == 'one': 105 colorbar = 'single' 106 elif colorbar == 'off': 107 colorbar = 'None' 108 else: 109 raise RuntimeError('plotmodel error: colorbar mode \'{}\' is not a valid option'.format(colorbar)) 94 110 111 cbar_mode = colorbar # {"each", "single", "edge", None }, default: None 112 cbar_location = options.list[0].getfieldvalue('colorbarpos', 'right') # {"left", "right", "bottom", "top"}, default: "right" 113 cbar_pad = options.list[0].getfieldvalue('colorbarpad', 0.025) # float, default: None 114 cbar_size = options.list[0].getfieldvalue('colorbarsize', '5%') # size specification (see Size.from_any), default: "5%" 115 116 # NOTE: Second parameter is: 117 # 118 # rect(float, float, float, float) or int 119 # 120 # The axes position, as a (left, bottom, width, height) tuple or as a 121 # three-digit subplot position code (e.g., "121"). 122 # 123 axgrid = ImageGrid( 124 fig, 125 111, 126 nrows_ncols=(nrows, ncols), 127 direction=direction, 128 axes_pad=axes_pad, 129 add_all=add_all, 130 share_all=share_all, 131 label_mode=label_mode, 132 cbar_mode=cbar_mode, 133 cbar_location=cbar_location, 134 cbar_size=cbar_size, 135 cbar_pad=cbar_pad 136 ) 137 95 138 if cbar_mode == 'None': 96 139 for ax in axgrid.cbar_axes: 97 140 fig._axstack.remove(ax) -
../trunk-jpl/src/m/plot/plot_unit.py
1 1 from cmaptools import getcolormap, truncate_colormap 2 from plot_quiver import plot_quiver3 import numpy as np4 2 try: 5 3 import matplotlib as mpl 6 4 import matplotlib.pyplot as plt … … 9 7 from mpl_toolkits.mplot3d.art3d import Poly3DCollection 10 8 except ImportError: 11 9 print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled") 10 import numpy as np 12 11 12 from plot_quiver import plot_quiver 13 13 14 14 15 def plot_unit(x, y, z, elements, data, is2d, isplanet, datatype, options, fig, axgrid, gridindex): 15 """16 ''' 16 17 PLOT_UNIT - unit plot, display data 17 18 18 19 Usage: 19 plot_unit(x, y, z, elements, data, is2d, isplanet, datatype, options)20 plot_unit(x, y, z, elements, data, is2d, isplanet, datatype, options) 20 21 21 22 See also: PLOTMODEL, PLOT_MANAGER 22 """23 ''' 23 24 #if we are plotting 3d replace the current axis 24 25 if not is2d: 25 26 axgrid[gridindex].axis('off') … … 227 228 else: 228 229 raise ValueError('plot_unit error: 3D node plot not supported yet') 229 230 return 230 231 231 # }}} 232 232 # {{{ plotting P1 Patch (TODO) 233 234 233 elif datatype == 4: 235 234 print('plot_unit message: P1 patch plot not implemented yet') 236 235 return 237 238 236 # }}} 239 237 # {{{ plotting P0 Patch (TODO) 240 241 238 elif datatype == 5: 242 239 print('plot_unit message: P0 patch plot not implemented yet') 243 240 return 244 245 241 # }}} 246 242 else: 247 243 raise ValueError('datatype = %d not supported' % datatype) -
../trunk-jpl/src/m/plot/applyoptions.py
1 import numpy as np2 1 from cmaptools import getcolormap 3 from plot_contour import plot_contour4 from plot_streamlines import plot_streamlines5 from expdisp import expdisp6 7 2 try: 8 from matplotlib.ticker import MaxNLocator9 3 import matplotlib as mpl 10 4 import matplotlib.pyplot as plt 5 from matplotlib.ticker import MaxNLocator 11 6 except ImportError: 12 7 print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled") 8 import numpy as np 13 9 10 from expdisp import expdisp 11 from plot_contour import plot_contour 12 from plot_streamlines import plot_streamlines 14 13 14 15 15 def applyoptions(md, data, options, fig, axgrid, gridindex): 16 16 ''' 17 17 APPLYOPTIONS - apply options to current plot … … 19 19 'plotobj' is the object returned by the specific plot call used to 20 20 render the data. This object is used for adding a colorbar. 21 21 22 23 22 Usage: 23 applyoptions(md, data, options) 24 24 25 25 See also: PLOTMODEL, PARSE_OPTIONS 26 26 ''' 27 27 28 28 # get handle to current figure and axes instance … … 33 33 fontsize = options.getfieldvalue('fontsize', 8) 34 34 fontweight = options.getfieldvalue('fontweight', 'normal') 35 35 fontfamily = options.getfieldvalue('fontfamily', 'sans - serif') 36 font = {'fontsize': fontsize, 37 'fontweight': fontweight, 38 'family': fontfamily} 36 font = { 37 'fontsize': fontsize, 38 'fontweight': fontweight, 39 'family': fontfamily 40 } 39 41 # }}} 40 42 # {{{ title 41 43 if options.exist('title'):
Note:
See TracBrowser
for help on using the repository browser.