-
Notifications
You must be signed in to change notification settings - Fork 20
/
util.py
1886 lines (1387 loc) · 58.8 KB
/
util.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# !/usr/bin/python # pylint: disable=I0011, C0302
r"""Classes and functions to help plot and interpret experimental data
**Classes:**
- :class:`ArrowLine` - A matplotlib_ subclass to draw an arrowhead on a line
- :class:`CallDict` - Dictionary that when called returns a dictionary of the
results from calling its entries
- :class:`CallList` - List that when called returns a list of the results from
calling its elements
- :class:`ParamDict` - Dictionary that prints its items as nested tuple-based
modifiers, formatted for Modelica_
**Functions:**
- :func:`accept_dict` - Decorator to also accept a dictionary as a single
positional argument
- :func:`add_arrows` - Overlay arrows with annotations on top of a pre-plotted
line.
- :func:`add_hlines` - Add horizontal lines to a set of axes with optional
labels.
- :func:`add_vlines` - Add vertical lines to a set of axes with optional
labels.
- :func:`basename` - Return the base filename from *fname*.
- :func:`call` - Run a system command, with the option to silence the output.
- :func:`cast_sametype` - Decorate a method to return an instance of the
containing class.
- :func:`color` - Plot 2D scalar data on a color axis in 2D Cartesian
coordinates.
- :func:`closeall` - Close all open figures (shortcut to :func:`destroy_all`
from :class:`matplotlib._pylab_helpers.Gcf`).
- :func:`cleanpath` - Clean up a file path by replacing '~' with the user
directory, making the path absolute, and replacing '/' with '\' on Windows.
- :func:`figure` - Create a figure and set its label.
- :func:`flatten_dict` - Flatten a nested dictionary.
- :func:`get_indices` - Return the pair of indices that bound a target value in
a monotonically increasing vector.
- :func:`get_pow1000` - Return the exponent of 1000 for which the
significand of a number is within the range [1, 1000).
- :func:`load_csv` - Load a CSV file into a dictionary.
- :func:`match` - Reduce a list of strings to those that match a pattern.
- :func:`modelica_str` - Express a Python_ value as a Modelica_ string.
- :func:`next_nonblank` - Advance to the next non-blank line of a file and
return that line minus any whitespace on the right.
- :func:`plot` - Plot 1D scalar data as points and/or line segments in 2D
Cartesian coordinates.
- :func:`quiver` - Plot 2D vector data as arrows in 2D Cartesian coordinates.
- :func:`read_values` - Read integers or floats from a formatted text file.
- :func:`save` - Save a figure in an image format or list of formats.
- :func:`saveall` - Save all open figures as images in a format or list of
formats.
- :func:`setup_subplots` - Create an array of subplots and return their axes.
- :func:`shift_scale_x` - Apply an offset and a factor as necessary to the x
axis.
- :func:`shift_scale_y` - Apply an offset and a factor as necessary to the y
axis.
- :func:`si_prefix` - Return the SI prefix for a power of 1000.
- :func:`tree` - Return a nested dictionary generated from keys and values.
- :func:`write_values` - Write integers or floats to a formatted text file.
.. _matplotlib: http://www.matplotlib.org/
.. _Python: http://www.python.org/
.. _Modelica: http://www.modelica.org/
"""
__author__ = "Kevin Davies"
__email__ = "kdavies4@gmail.com"
__credits__ = ["Arnout Aertgeerts", "Jason Grout", "Jason Heeris",
"Joerg Raedler"]
__copyright__ = ("Copyright 2012-2014, Kevin Davies, Hawaii Natural Energy "
"Institute, and Georgia Tech Research Corporation")
__license__ = "BSD-compatible (see LICENSE.txt)"
# Standard pylint settings for this project:
# pylint: disable=I0011, C0302, C0325, R0903, R0904, R0912, R0913, R0914, R0915
# pylint: disable=I0011, W0141, W0142
# Other:
# pylint: disable=I0011, C0103, C0301, E1101, F0401, R0921, W0102, W0621
import matplotlib.pyplot as plt
import numpy as np
import os
import re as regexp
import subprocess
import sys
import time
from collections import MutableMapping
from decimal import Decimal
from fnmatch import fnmatchcase
from functools import wraps
from glob import glob
from itertools import cycle
from math import floor
from matplotlib import rcParams
from matplotlib._pylab_helpers import Gcf
from matplotlib.cbook import iterable
from matplotlib.lines import Line2D
from natu.util import flatten_list
from six import string_types
# Load the getSaveFileName function from an available Qt installation.
try:
from PyQt4.QtGui import QFileDialog
getSaveFileName = (lambda *args, **kwargs:
str(QFileDialog.getSaveFileName(*args, **kwargs)))
except ImportError:
try:
from guidata.qt.QtGui import QFileDialog
getSaveFileName = (lambda *args, **kwargs:
str(QFileDialog.getSaveFileName(*args, **kwargs)))
except ImportError:
try:
from PySide.QtGui import QFileDialog
getSaveFileName = (lambda *args, **kwargs:
QFileDialog.getSaveFileName(*args, **kwargs)[0])
except ImportError:
getSaveFileName = lambda *args, **kwargs: None
# Function to close all open figures
closeall = Gcf.destroy_all
def accept_dict(func):
"""Decorator to also accept a dictionary as a single positional argument
If there is only one positional argument and it is a :class:`dict`, then its
contents are passed as keyword arguments into the original function.
"""
@wraps(func)
def wrapped(*space, **kwargs):
if len(space) == 1 and isinstance(space[0], dict):
return func(**space[0])
else:
return func(*space, **kwargs)
return wrapped
def add_arrows(plot, x_locs=[0], xstar_offset=0, ystar_offset=0,
lstar=0.05, label='', orientation='tangent', color='r'):
"""Overlay arrows with annotations on a pre-plotted line.
**Parameters:**
- *plot*: A plot instance (:class:`matplotlib.lines.Line2D` object)
- *x_locs*: x-axis locations of the arrows
- *xstar_offset*: Normalized x-axis offset from the middle of the arrow to
the text
- *ystar_offset*: Normalized y-axis offset from the middle of the arrow to
the text
- *lstar*: Length of each arrow in normalized xy axes
- *label*: Annotation text
- *orientation*: 'tangent', 'horizontal', or 'vertical'
- *color*: Color of the arrows (from :mod:`matplotlib.colors`)
**Example:**
.. plot:: examples/util-add_arrows.py
:alt: example of add_arrows()
"""
from math import atan, cos, sin
# Get data from the plot lines object.
x_dat = plt.getp(plot, 'xdata')
y_dat = plt.getp(plot, 'ydata')
ax = plot.get_axes()
Deltax = np.diff(ax.get_xlim())[0]
Deltay = np.diff(ax.get_ylim())[0]
for x_loc in x_locs:
# Get two unique indices.
i_a, i_b = get_indices(x_dat, x_loc)
if i_a == i_b:
if i_a > 0:
i_a -= 1
if i_b < len(x_dat):
i_b += 1
# Find the midpoint and x, y lengths of the arrow such that it has the
# given normalized length.
x_pts = x_dat.take([i_a, i_b])
y_pts = y_dat.take([i_a, i_b])
if orientation == 'vertical':
dx = lstar * Deltax
dy = 0
elif orientation == 'horizontal':
dx = 0
dy = lstar * Deltay
else: # tangent
theta = atan((y_pts[1] - y_pts[0]) * Deltax / ((x_pts[1] -
x_pts[0]) * Deltay))
dx = lstar * Deltax * cos(theta)
dy = lstar * Deltay * sin(theta)
x_mid = sum(x_pts) / 2
y_mid = sum(y_pts) / 2
# Add the arrow and text.
line = ArrowLine([x_mid - dx, x_mid + dx], [y_mid - dy, y_mid + dy],
color=color, arrowfacecolor=color,
arrowedgecolor=color, ls='-', lw=3, arrow='>',
arrowsize=10)
ax.add_line(line)
if label:
ax.text(x_mid + xstar_offset * Deltax, y_mid + ystar_offset * Deltax,
s=label, fontsize=12)
def add_hlines(ax=None, positions=[0], labels=[], **kwargs):
r"""Add horizontal lines to a set of axes with optional labels.
**Parameters:**
- *ax*: Axes (:class:`matplotlib.axes.Axes` object)
- *positions*: Positions (along the x axis)
- *labels*: List of labels for the lines
- *\*\*kwargs*: Line properties (propagated to
:func:`matplotlib.pyplot.axhline`)
E.g., ``color='k', linestyle='--', linewidth=0.5``
**Example:**
.. plot:: examples/util-add_hlines.py
:alt: example of add_hlines()
"""
# Process the inputs.
if not ax:
ax = plt.gca()
if not iterable(positions):
positions = (positions,)
if not iterable(labels):
labels = (labels,)
# Add and label lines.
for position in positions:
ax.axhline(y=position, **kwargs)
xpos = sum(ax.axis()[0:2]) / 2.0
for i, label in enumerate(labels):
ax.text(xpos, positions[i], label, backgroundcolor='w',
horizontalalignment='center', verticalalignment='center')
def add_vlines(ax=None, positions=[0], labels=[], **kwargs):
r"""Add vertical lines to a set of axes with optional labels.
**Parameters:**
- *ax*: Axes (:class:`matplotlib.axes.Axes` object)
- *positions*: Positions (along the x axis)
- *labels*: List of labels for the lines
- *\*\*kwargs*: Line properties (propagated to
:func:`matplotlib.pyplot.axvline`)
E.g., ``color='k', linestyle='--', linewidth=0.5``
**Example:**
.. plot:: examples/util-add_vlines.py
:alt: example of add_vlines()
"""
# Process the inputs.
if not ax:
ax = plt.gca()
if not iterable(positions):
positions = (positions,)
if not iterable(labels):
labels = (labels,)
# Add and label lines.
for position in positions:
ax.axvline(x=position, **kwargs)
ypos = sum(ax.axis()[2::]) / 2.0
for i, label in enumerate(labels):
ax.text(positions[i], ypos, label, backgroundcolor='w',
horizontalalignment='center', verticalalignment='center')
def basename(fname):
"""Return the base filename from *fname*.
Unlike :func:`os.path.basename`, this function strips the file extension."""
return os.path.splitext(os.path.basename(fname))[0]
def call(args, silent=False):
"""Run a system command, with the options to silence the output.
**Parameters:**
- *args*: List of program arguments or a single string
- *silent*: *False*, if the output should be printed
"""
subprocess.call(args, stdout=open(os.devnull, 'w') if silent else None)
def cast_sametype(meth):
"""Decorate a method to return an instance of the containing class.
"""
@wraps(meth)
def wrapped(self, *args, **kwargs):
"""Function that casts its output as self.__class__
"""
return self.__class__(meth(self, *args, **kwargs))
return wrapped
def color(ax, c, *args, **kwargs):
r"""Plot 2D scalar data on a color axis in 2D Cartesian coordinates.
This uses a uniform grid.
**Parameters:**
- *ax*: Axis onto which the data should be plotted
- *c*: color- or c-axis data (2D array)
- *\*args*, *\*\*kwargs*: Additional arguments for
:func:`matplotlib.pyplot.imshow`
**Example:**
.. code-block:: python
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x, y = np.meshgrid(np.arange(0, 2*np.pi, 0.2),
... np.arange(0, 2*np.pi, 0.2))
>>> c = np.cos(x) + np.sin(y)
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> color(ax, c) # doctest: +ELLIPSIS
<matplotlib.image.AxesImage object at 0x...>
"""
return ax.imshow(c, *args, **kwargs)
def dict_to_lists(dic):
keys = []
values = []
for key, value in dic.iteritems():
keys.append(key)
values.append(value)
return keys, values
def cleanpath(path):
r"""Clean up a file path by replacing '~' with the user directory, making
the path absolute, and replacing '/' with '\' on Windows.
**Example:**
>>> cleanpath('~/Documents') # doctest: +ELLIPSIS
'...Documents'
where ... is '/home/user/' on Linux or 'C:\Users\user\' on Windows (and
"user" is the user id).
"""
return os.path.abspath(os.path.expanduser(os.path.normpath(path)))
def figure(label='', *args, **kwargs):
r"""Create a figure and set its label.
**Parameters:**
- *label*: String to apply to the figure's *label* property
- *\*args*, *\*\*kwargs*: Additional arguments for
:func:`matplotlib.pyplot.figure`
**Example:**
.. code-block:: python
>>> import matplotlib.pyplot as plt
>>> fig = figure("velocity_vs_time") # doctest: +ELLIPSIS
>>> plt.getp(fig, 'label')
'velocity_vs_time'
.. testcleanup::
>>> plt.close()
.. Note:: The *label* property is used as the base filename in the
:func:`save` and :func:`saveall` functions.
"""
fig = plt.figure(*args, **kwargs)
plt.setp(fig, 'label', label)
# Note: As of matplotlib 1.2, matplotlib.pyplot.figure(label=label) isn't
# supported directly.
return fig
def flatten_dict(d, parent_key='', separator='.'):
"""Flatten a nested dictionary.
**Parameters:**
- *d*: Dictionary (may be nested to an arbitrary depth)
- *parent_key*: Key of the parent dictionary, if any
- *separator*: String or character that joins elements of the keys or path
names
**Example:**
>>> flatten_dict(dict(a=1, b=dict(c=2, d='hello'))) # doctest: +SKIP
{'a': 1, 'b.c': 2, 'b.d': 'hello'}
.. testcleanup::
>>> assert flatten_dict(dict(a=1, b=dict(c=2, d='hello'))) == {'a': 1, 'b.c': 2, 'b.d': 'hello'}
"""
# From
# http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys,
# 11/5/2012
items = []
for key, value in d.items():
new_key = parent_key + separator + key if parent_key else key
if isinstance(value, MutableMapping):
items.extend(flatten_dict(value, new_key).items())
else:
items.append((new_key, value))
return dict(items)
def _gen_offset_factor(label, tick_lo, tick_up, eagerness=0.325):
"""Apply an offset and a scaling factor to a label if necessary.
**Parameters:**
- *tick_lo*: Lower tick value
- *tick_up*: Upper tick value
- *eagerness*: Parameter to adjust how little of an offset is required
before the label will be recentered
- 0: Offset is never applied.
- 1: Offset is always applied if it will help.
**Returns:**
1. New label (label)
2. Offset (offset)
3. Exponent of 1000 which can be factored from the number (pow1000)
"""
# TODO: Use matplotlib's support for units?
def _label_offset_factor(label, offset_factor, offset_pow1000, pow1000):
"""Format an offset and factor into a LaTeX string and add to it an
existing string.
"""
DIVIDE = r'\,/\,' # LaTeX string for division
# Add the offset string.
if offset_factor:
if DIVIDE in label:
label = label.rstrip(r'$') + r'\,-\,%i$' % offset_factor
else:
label += r'$\,-\,%i$' % offset_factor
if offset_pow1000:
label = label.rstrip(r'$') + (r'\times10^{%i}$' %
(3 * offset_pow1000))
# Add the scaling notation.
if pow1000:
if offset_factor:
label = (r'$($' + label.rstrip(r'$') + r')' + DIVIDE +
r'10^{%i}$' % (3 * pow1000))
else:
if DIVIDE in label:
desc, unit = label.split(DIVIDE, 1)
if unit.endswith(r')$'):
label = (desc + DIVIDE + r'(10^{%i}' % (3 * pow1000) +
unit.lstrip(r'('))
else:
label = (desc + DIVIDE + r'(10^{%i}' % (3 * pow1000) +
unit.rstrip(r'$') + r')$')
else:
label += r'$' + DIVIDE + r'10^{%i}$' % (3 * pow1000)
return label
offset = 0
offset_factor = 0
offset_pow1000 = 1
outside = min(tick_lo, 0) + max(tick_up, 0)
if outside != 0:
inside = max(tick_lo, 0) + min(tick_up, 0)
if inside / outside > 1 - eagerness:
offset = inside - np.mod(inside, 1000 ** get_pow1000(inside))
offset_pow1000 = get_pow1000(offset)
offset_factor = offset / 1000 ** offset_pow1000
outside = min(tick_lo - offset, 0) + max(tick_up - offset, 0)
pow1000 = get_pow1000(outside)
label = _label_offset_factor(label, offset_factor, offset_pow1000, pow1000)
return label, offset, pow1000
def get_indices(x, target):
"""Return the pair of indices that bound a target value in a monotonically
increasing vector.
**Parameters:**
- *x*: Vector
- *target*: Target value
**Example:**
>>> get_indices([0, 1, 2], 1.6)
(1, 2)
"""
if target <= x[0]:
return 0, 0
if target >= x[-1]:
i = len(x) - 1
return i, i
else:
i_1 = 0
i_2 = len(x) - 1
while i_1 < i_2 - 1:
i_mid = int((i_1 + i_2) / 2)
if x[i_mid] == target:
return i_mid, i_mid
elif x[i_mid] > target:
i_2 = i_mid
else:
i_1 = i_mid
return i_1, i_2
def get_pow1000(num):
"""Return the exponent of 1000 for which the significand of a number is
within the range [1, 1000).
**Example:**
>>> get_pow1000(1e5)
1
"""
# Based on an algorithm by Jason Heeris 11/18/2009:
# http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg14433.html
dnum = Decimal(str(num))
if dnum == 0:
return 0
elif dnum < 0:
dnum = -dnum
return int(floor(dnum.log10() / 3))
def load_csv(fname, header_row=0, first_data_row=None, types=None, **kwargs):
r"""Load a CSV file into a dictionary.
The strings from the header row are used as dictionary keys.
**Parameters:**
- *fname*: Path and name of the file
- *header_row*: Row that contains the keys (uses zero-based indexing)
- *first_data_row*: First row of data (uses zero-based indexing)
If *first_data_row* is not provided, then it is assumed that the data
starts just after the header row.
- *types*: List of data types for each column
:class:`int` and :class:`float` data types will be cast into a
:class:`numpy.array`. If *types* is not provided, attempts will be
made to cast each column into :class:`int`, :class:`float`, and
:class:`str` (in that order).
- *\*\*kwargs*: Additional arguments for :func:`csv.reader`
**Example:**
>>> data = load_csv("examples/load-csv.csv", header_row=2)
>>> print("The keys are: %s" % list(data)) # doctest: +SKIP
The keys are: ['Description', 'Make', 'Model', 'Price', 'Year']
.. testcleanup::
>>> sorted(data)
['Description', 'Make', 'Model', 'Price', 'Year']
"""
import csv
try:
reader = csv.reader(open(fname), **kwargs)
except IOError:
raise IOError('Unable to load "%s". Check that it exists.' % fname)
# Read the header row and create the dictionary from it.
for i in range(header_row):
next(reader)
keys = next(reader)
data = dict.fromkeys(keys)
# print("The keys are: ")
# print(keys)
# Read the data.
if first_data_row:
# pylint: disable=I0011, W0612
for __ in range(first_data_row - header_row - 1):
next(reader)
if types:
for i, (key, column, t) in enumerate(zip(keys, zip(*reader), types)):
# zip(*reader) groups the data by columns.
try:
if isinstance(t, string_types):
data[key] = column
elif isinstance(t, (float, int)):
data[key] = np.array(map(t, column))
else:
data[key] = map(t, column)
except ValueError:
raise ValueError("Could not cast column %i into %i." % (i, t))
else:
for key, column in zip(keys, zip(*reader)):
try:
data[key] = np.array(map(int, column))
except ValueError:
try:
data[key] = np.array(map(float, column))
except ValueError:
data[key] = column
return data
def match(strings, pattern=None, re=False):
r"""Reduce a list of strings to those that match a pattern.
By default, all of the strings are returned.
**Parameters:**
- *strings*: List of strings
- *pattern*: Case-sensitive string used for matching
- If *re* is *False* (next argument), then the pattern follows the
Unix shell style:
============ ============================
Character(s) Role
============ ============================
\* Matches everything
? Matches any single character
[seq] Matches any character in seq
[!seq] Matches any char not in seq
============ ============================
Wildcard characters ('\*') are not automatically added at the
beginning or the end of the pattern. For example, '\*x\*' matches all
strings that contain "x", but 'x\*' matches only the strings that begin
with "x".
- If *re* is `True`, regular expressions are used a la `Python's re
module <http://docs.python.org/2/library/re.html>`_. See also
http://docs.python.org/2/howto/regex.html#regex-howto.
Since :func:`re.search` is used to produce the matches, it is as if
wildcards ('.*') are automatically added at the beginning and the
end. For example, 'x' matches all strings that contain "x". Use '^x$'
to match only the strings that begin with "x" and 'x$' to match only the
strings that end with "x".
Note that '.' is a subclass separator in Modelica_ but a wildcard in
regular expressions. Escape the subclass separator as '\\.'.
- *re*: `True` to use regular expressions (*False* to use shell style)
**Example:**
>>> match(['apple', 'orange', 'banana'], '*e')
['apple', 'orange']
.. _Modelica: http://www.modelica.org/
"""
if pattern is None or (pattern in ['.*', '.+', '.', '.?', ''] if re
else pattern == '*'):
return list(strings) # Shortcut
else:
if re:
matcher = regexp.compile(pattern).search
else:
matcher = lambda name: fnmatchcase(name, pattern)
return list(filter(matcher, strings))
def modelica_str(value):
"""Express a Python_ value as a Modelica_ string.
A Boolean variable (:class:`bool`) becomes 'true' or 'false' (lowercase).
For NumPy_ arrays, square brackets are curled.
**Examples:**
Booleans:
>>> # Booleans:
>>> modelica_str(True)
'true'
Arrays:
.. code-block:: python
>>> import numpy as np
>>> modelica_str(np.array([[1, 2], [3, 4]]))
'{{1, 2}, {3, 4}}'
>>> modelica_str(np.array([[True, True], [False, False]]))
'{{true, true}, {false, false}}'
"""
if isinstance(value, bool):
return 'true' if value else 'false'
elif isinstance(value, np.ndarray):
value = str(value)
for old, new in [(r'\[', '{'), (r'\]', '}'), (r'\n', ''),
(' ?True', 'true'), ('False', 'false'), (' +', ', ')]:
# Python 2.7 puts an extra space before True when representing an
# array.
value = regexp.sub(old, new, value)
return value
else:
return str(value)
def next_nonblank(f):
"""Advance to the next non-blank line of file *f* and return that line minus
any whitespace on the right.
This raises :class:`StopIteration` if all of the remaining lines are blank.
"""
line = f.next().rstrip()
while not line:
line = f.next().rstrip()
return line
def plot(y, x=None, ax=None, label=None,
color=['b', 'g', 'r', 'c', 'm', 'y', 'k'],
marker=None,
dashes=[(None, None), (3, 3), (1, 1), (3, 2, 1, 2)],
**kwargs):
r"""Plot 1D scalar data as points and/or line segments in 2D Cartesian
coordinates.
This is similar to :func:`matplotlib.pyplot.plot` (and actually calls that
function) but provides direct support for plotting an arbitrary number of
curves.
**Parameters:**
- *y*: List of y-axis series
- *x*: x-axis data
If *x* is not provided, the y-axis series will be plotted versus its
indices. If *x* is a single series, it will be used for all of the
y-axis series. If it is a list of series, each x-axis series will be
matched to a y-axis series.
- *ax*: Axis onto which the data should be plotted.
If *ax* is 'None' (default), axes are created.
- *label*: List of labels of each series (to be used later for the legend
if applied)
If *label* is 'None', no labels are applied.
- *color*: Single entry, list, or :func:`itertools.cycle` of colors that
will be used sequentially
Each entry may be a character, grayscale, or rgb value.
.. Seealso:: http://matplotlib.sourceforge.net/api/colors_api.html
- *marker*: Single entry, list, or :func:`itertools.cycle` of markers that
will be used sequentially
Use 'None' for no marker. A good assortment is ['o', 'v', '^', '<',
'>', 's', 'p', '*', 'h', 'H', 'D', 'd']. All of the possible entries
are listed at:
http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.lines.Line2D.set_marker.
- *dashes*: Single entry, list, or :func:`itertools.cycle` of dash styles
that will be used sequentially
Each style is a tuple of on/off lengths representing dashes. Use
(0, 1) for no line and ('None', 'None') for a solid line.
.. Seealso:: http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D.set_dashes
- *\*\*kwargs*: Additional arguments for :func:`matplotlib.pyplot.plot`
**Returns:** List of :class:`matplotlib.lines.Line2D` objects
**Example:**
>>> plot([range(11), range(10, -1, -1)]) # doctest: +ELLIPSIS
[[<matplotlib.lines.Line2D object at 0x...>], [<matplotlib.lines.Line2D object at 0x...>]]
"""
# Create axes if necessary.
if not ax:
fig = plt.figure()
ax = fig.add_subplot(111)
# Set up the color(s), marker(s), and dash style(s).
cyc = type(cycle([]))
if not isinstance(color, cyc):
if not iterable(color):
color = [color]
color = cycle(color)
if not isinstance(marker, cyc):
if not iterable(marker):
marker = [marker]
marker = cycle(marker)
if not isinstance(dashes, cyc):
if not iterable(dashes[0]):
dashes = [dashes]
dashes = cycle(dashes)
# 6/5/11: There is an ax.set_color_cycle() method that could be used, but
# there doesn't seem to be a corresponding set_line_cycle() or
# set_marker_cycle().
# 10/27/11: There may be a way to do this automatically. See:
# http://matplotlib.sourceforge.net/api/collections_api.html
# Plot the data.
if x is None:
# There is no x data; plot y vs its indices.
plots = [ax.plot(yi, label=None if label is None else label[i],
color=next(color), marker=next(marker),
dashes=next(dashes), **kwargs)
for i, yi in enumerate(y)]
elif not iterable(x[0]):
# There is only one x series; use it repeatedly.
plots = [ax.plot(x, yi, label=None if label is None else label[i],
color=next(color), marker=next(marker),
dashes=next(dashes), **kwargs)
for i, yi in enumerate(y)]
else:
# There is a x series for each y series.
plots = [ax.plot(xi, yi, label=None if label is None else label[i],
color=next(color), marker=next(marker),
dashes=next(dashes), **kwargs)
for i, (xi, yi) in enumerate(zip(x, y))]
return plots
def quiver(ax, u, v, x=None, y=None, pad=0.05, pivot='middle', **kwargs):
r"""Plot 2D vector data as arrows in 2D Cartesian coordinates using a
uniform grid.
**Parameters:**
- *ax*: Axis onto which the data should be plotted
- *u*: x-direction values (2D array)
- *v*: y-direction values (2D array)
- *pad*: Amount of white space around the data (relative to the span of the
field)
- *pivot*: 'tail' | 'middle' | 'tip' (see :func:`matplotlib.pyplot.quiver`)
- *\*\*kwargs*: Additional arguments for :func:`matplotlib.pyplot.quiver`
**Example:**
.. plot:: examples/util-quiver.py
:alt: plot of quiver()
"""
if x is None or y is None:
p = ax.quiver(u, v, pivot=pivot, **kwargs)
else:
p = ax.quiver(x, y, u, v, pivot=pivot, **kwargs)
plt.axis('tight')
l, r, b, t = plt.axis()
dx, dy = r - l, t - b
plt.axis([l - pad * dx, r + pad * dx, b - pad * dy, t + pad * dy])
return p
def read_values(names, fname, patterns):
"""Read integers or floats from a formatted text file.
**Parameters:**
- *names*: Variable name or list of names
- *fname*: Name of the file (may include the file path)
- *patterns*: List of possible multi-line regular expressions for a variable
specification
Each expression must contain '%s' for the variable name and parentheses
around the value. The expressions are tried in order until there is a
match.
"""
# Read the file.
with open(fname, 'r') as src:
text = src.read()
# Extract the values.
def _read_value(name):
"""Read a single value.
"""
namere = regexp.escape(name) # Escape the dots, square brackets, etc.
for pattern in patterns:
try:
match = regexp.search(pattern % namere, text,
regexp.MULTILINE).group(1)
except AttributeError:
continue # Try the next pattern.
try:
return int(match)
except ValueError:
try:
return float(match)
except ValueError:
raise ValueError(
'The value of %s ("%s") could not be represented as a '
'float or an int.' % (name, match))
else:
# pylint: disable=I0011, W0120
raise KeyError(
"Variable %s doesn't exist or isn't formatted as expected in "
"%s." % (name, fname))
if isinstance(names, string_types):
return _read_value(names)