This repository has been archived by the owner on May 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparsematlab.py
81 lines (78 loc) · 2.78 KB
/
parsematlab.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/python
import numpy as np
def parse(value):
"""
Parses certain types of matlab types from strings. Specifically:
* 2D arrays consisting of space/comma-separated integers or floats
* ranges of values composed of start:stop or start:step:stop
* integers or floats
In the event of an error, a string is returned containing an error message.
"""
original = value
if isinstance(value, int) or isinstance(value, float):
return value
value = value.strip()
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
value = value.replace(',', ' ')
if ':' in value:
value = value.split(':')
if len(value) == 2:
try:
start = int(value[0].strip())
stop = int(value[1].strip())
step = 1
return np.arange(start, stop + step, step, dtype = int)
except ValueError:
pass
try:
start = float(value[0].strip())
stop = float(value[1].strip())
step = 1.
return np.arange(start, stop, step)
except ValueError:
return 'Range parameters must be numbers.\n' + \
'Instead, found:\n "%s"' % original
elif len(value) == 3:
try:
start = int(value[0].strip())
stop = int(value[2].strip())
step = int(value[1].strip())
return np.arange(start, stop + step, step, dtype = int)
except ValueError:
pass
try:
start = float(value[0].strip())
stop = float(value[2].strip())
step = float(value[1].strip())
return np.arange(start, stop, step)
except ValueError:
return 'Range parameters must be numbers.\n' + \
'Instead, found:\n "%s"' % original
else:
return 'Ranges must be composed of start:stop or' + \
' start:step:stop.\nInstead, found:\n "%s"' % original
if ' ' in value:
value = value.split()
newvalue = []
for subvalue in value:
try:
newvalue.append(int(subvalue))
continue
except ValueError:
pass
try:
newvalue.append(float(subvalue))
continue
except ValueError:
pass
return 'Lists must be composed of numbers separated' + \
' by spaces.\nInstead, found:\n %s' % original
return np.asarray(newvalue)
return 'Cannot recognize\n "%s"\nas a valid value.' % original