source: issm/trunk/src/m/miscellaneous/MatlabFuncs.py@ 27035

Last change on this file since 27035 was 27035, checked in by Mathieu Morlighem, 3 years ago

merged trunk-jpl and trunk for revision 27033

File size: 7.0 KB
RevLine 
[26744]1"""A collection of functions that replicate the behavior of MATLAB built-in
2functions of the same, respective name.
[12889]3
[27035]4Where possible, users are encouraged to use native and/or the most efficient
5methods in Python, but we provide these functions as a way to make translations
[26744]6from the MATLAB to the Python ISSM API more seamless.
7"""
[12889]8
[26744]9def acosd(X): # {{{
10 """function acosd - Inverse cosine in degrees
[24313]11
[26744]12 Usage:
13 Y = acosd(X)
14 """
15 import numpy as np
[13170]16
[26744]17 return np.degrees(np.arccos(X))
18# }}}
[13170]19
[26744]20def asind(X): # {{{
21 """function asind - Inverse sine in degrees
[24313]22
[26744]23 Usage:
24 Y = asind(X)
25 """
26 import numpy as np
[14310]27
[26744]28 return np.degrees(np.arcsin(X))
29# }}}
[14310]30
[26744]31def atand(X): # {{{
32 """function atand - Inverse tangent in degrees
[12675]33
[26744]34 Usage:
35 Y = atand(X)
36 """
37 import numpy as np
[12675]38
[26744]39 return np.degrees(np.arctan(X))
40# }}}
41
42
43def atan2d(Y, X): # {{{
44 """function atan2d - Four-quadrant inverse tangent in degrees
45
46 Usage:
47 D = atan2d(Y, X)
48 """
49 import numpy as np
50
51 return np.degrees(np.arctan2(Y, X))
52# }}}
53
54def contains(str, pat): #{{{
55 """function contains - Determine if pattern is in strings
56
57 Usage:
58 TF = contains(str, pat)
59
60 TODO:
61 - Implement 'IgnoreCase' option
62 """
63
64# }}}
65
66def cosd(X): # {{{
67 """function cosd - Cosine of argument in degrees
68
69 Usage:
70 Y = cosd(X)
71 """
72 import numpy as np
73
74 if type(X) == np.ndarray:
75 Y = np.array([])
76 for x in X:
77 Y = np.append(Y, cosdsingle(x))
78 return Y
[24313]79 else:
[26744]80 return cosdsingle(X)
81# }}}
[12675]82
[26744]83def cosdsingle(x): # {{{
[27035]84 """function cosdsingle - Helper function for cosd to reduce repetition of
[26744]85 logic
[12675]86
[26744]87 Usage:
88 y = cosdsingle(x)
89 """
90 import numpy as np
[12675]91
[26744]92 while x >= 360:
93 x = x - 360
94
95 if x == 0:
96 return 1
97 elif x == 90 or x == 270:
98 return 0
99 elif x == 180:
100 return -1
[24313]101 else:
[26744]102 return np.cos(np.radians(x))
103# }}}
[12675]104
[26744]105def det(a): # {{{
106 if a.shape == (1, ):
107 return a[0]
108 elif a.shape == (1, 1):
109 return a[0, 0]
110 elif a.shape == (2, 2):
111 return a[0, 0] * a[1, 1] - a[0, 1] * a[1, 0]
112 else:
113 raise TypeError('MatlabFunc.det only implemented for shape (2, 2), not for shape {}.'.format(a.shape))
114# }}}
[12675]115
[26744]116def error(msg): # {{{
117 raise Exception(msg)
118# }}}
[12675]119
[26744]120def etime(t2, t1): # {{{
121 return t2 - t1
122# }}}
123
124def find(*args): # {{{
125 nargs = len(args)
126 if nargs >= 1 or nargs <= 2:
127 X = args[0]
128 n = len(args[0])
129 if nargs == 2:
130 n = args[1]
131 indices=[]
132 for i in range(n):
133 if X[i] != 0:
134 indices.push(i)
135 return indices
[24313]136 else:
[26744]137 raise Exception('find: must have 1 or 2 arguments')
138# }}}
[12842]139
[26744]140def floor(X): # {{{
141 import math
[12842]142
[26744]143 return int(math.floor(X))
144# }}}
[12842]145
[26744]146def heaviside(x): # {{{
147 import numpy as np
148
149 y = np.zeros_like(x)
150 y[np.nonzero(x > 0.)] = 1.
151 y[np.nonzero(x == 0.)] = 0.5
152
153 return y
154# }}}
155
156def intersect(A, B): # {{{
157 """function intersect - Set intersection of two arrays
158
159 Usage:
160 C = intersect(A, B)
161
162 NOTE:
163 - Only the following functionality is currently implemented:
[27035]164 - C = intersect(A,B) returns the data common to both A and B, with no
[26744]165 repetitions. C is in sorted order.
166
167 """
168 import numpy as np
169
170 return np.intersect1d(A, B)
171#}}}
172
173def isa(A, dataType): # {{{
174 """function isa
175
176 NOTE:
[27035]177 - Takes a type as its second argument (in contrast to the MATLAB function
[26744]178 that it replicates, which takes a string representing the name of a type)
179 """
180 return type(A) == dataType
181# }}}
182
183# NOTE: Conflicts with definition of isempty in $ISSM_DIR/src/m/qmu/helpers.py
184#
185# def isempty(A): # {{{
186# return len(A) > 0
187# # }}}
188
189def isfile(fileName): # {{{
190 import os
191
192 return os.path.exists(fileName)
193# }}}
194
195def ismac(): # {{{
196 import platform
197
198 if 'Darwin' in platform.system():
[24313]199 return True
200 else:
201 return False
[26744]202# }}}
[12842]203
[26744]204def ismember(a, s): # {{{
[24313]205 import numpy as np
206 if not isinstance(s, (tuple, list, dict, np.ndarray)):
207 s = [s]
208
209 if not isinstance(a, (tuple, list, dict, np.ndarray)):
210 a = [a]
211
212 if not isinstance(a, np.ndarray):
213 b = [item in s for item in a]
214 else:
215 if not isinstance(s, np.ndarray):
[27035]216 b = np.empty_like(a).flat
[24313]217 for i, item in enumerate(a.flat):
[27035]218 b[i] = item in s
[24313]219 else:
220 b = np.in1d(a.flat, s.flat).reshape(a.shape)
221 return b
[26744]222# }}}
[24313]223
[26744]224def isnan(A): # {{{
225 import numpy as np
[24313]226
[26744]227 return np.isnan(A)
228# }}}
[13975]229
[26744]230def ispc(): # {{{
231 import platform
232
233 if 'Windows' in platform.system():
234 return True
[24313]235 else:
[26744]236 return False
237# }}}
[13975]238
[26744]239def isprop(obj, PropertyName): # {{{
240 return hasattr(obj, PropertyName)
241# }}}
[13975]242
[26744]243def mod(a, m): # {{{
244 return a % m
245# }}}
246
247def numel(A): # {{{
248 """function numel - Number of array elements
249
250 Usage:
251 n = numel(A))
252 """
[24313]253 import numpy as np
[13975]254
[26744]255 return np.size(A)
256# }}}
257
258def pause(n): # {{{
259 import time
260
261 time.sleep(n)
262# }}}
263
264def pwd(): # {{{
265 import os
266
267 return os.getcwd()
268# }}}
269
270def oshostname(): # {{{
271 import socket
[27035]272 hostname = socket.gethostname()
[26744]273
[27035]274 return hostname.lower()
[26744]275# }}}
276
277def rem(a, b): # {{{
278 return a % b
279# }}}
280
281def sind(X): # {{{
282 """function sind - Sine of argument in degrees
283
284 Usage:
285 Y = sind(X)
286 """
287 import numpy as np
288
289 if type(X) == np.ndarray:
290 Y = np.array([])
291 for x in X:
292 Y = np.append(Y, sindsingle(x))
293 return Y
294 else:
295 return sindsingle(X)
296# }}}
297
298def sindsingle(x): # {{{
[27035]299 """function sindsingle - Helper function for sind to reduce repetition of
[26744]300 logic
301
302 Usage:
303 y = sindsingle(x)
304 """
305 import numpy as np
306
307 while x >= 360:
308 x = x - 360
309
310 if x == 0 or x == 180:
311 return 0
312 elif x == 90:
313 return 1
314 elif x == 270:
315 return -1
316 else:
317 return np.sin(np.radians(x))
318# }}}
319
320def sparse(ivec, jvec, svec, m=0, n=0, nzmax=0): # {{{
321 import numpy as np
322
[24313]323 if not m:
324 m = np.max(ivec)
325 if not n:
326 n = np.max(jvec)
[13975]327
[24313]328 a = np.zeros((m, n))
[13975]329
[24313]330 for i, j, s in zip(ivec.reshape(-1, order='F'), jvec.reshape(-1, order='F'), svec.reshape(-1, order='F')):
331 a[i - 1, j - 1] += s
[13975]332
[24313]333 return a
[26744]334# }}}
[24313]335
[26744]336def strcmp(s1, s2): # {{{
337 if s1 == s2:
338 return True
339 else:
340 return False
341# }}}
[24313]342
[26744]343def strcmpi(s1, s2): # {{{
344 if s1.lower() == s2.lower():
345 return True
346 else:
347 return False
348# }}}
[14310]349
[26744]350def strjoin(*args): # {{{
351 nargs = len(args)
352 if nargs >= 1 or nargs <= 2:
353 sep = ' '
354 if nargs == 2:
355 sep = args[1]
356 return sep.join(args[0])
357 else:
358 raise Exception('strjoin: must have 1 or 2 arguments')
359# }}}
[14310]360
[26744]361def strncmp(s1, s2, n): # {{{
362 if s1[0:n] == s2[0:n]:
363 return True
364 else:
365 return False
366# }}}
367
368def strncmpi(s1, s2, n): # {{{
369 if s1.lower()[0:n] == s2.lower()[0:n]:
370 return True
371 else:
372 return False
373# }}}
Note: See TracBrowser for help on using the repository browser.