-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.py
1721 lines (1290 loc) · 53.1 KB
/
base.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
# -*- coding: utf-8 -*-
"""Basic methods to help plot and interpret experimental data
This module contains the following classes:
- :class:`ArrowLine` - A matplotlib subclass to draw an arrowhead on a line
- :class:`Quantity` - Named tuple class for a constant physical quantity
and the following functions:
- :meth:`add_arrows` - Overlays arrows with annotations on top of a pre-plotted
line
- :meth:`add_hlines` - Adds horizontal lines to a set of axes with optional
labels
- :meth:`add_vlines` - Adds vertical lines to a set of axes with optional
labels
- :meth:`animate` - Encodes a series of PNG images as a MPG movie
- :meth:`color` - Plots 2D scalar data on a color axis in 2D Cartesian
coordinates
- :meth:`closeall` - Closes all open figures
- :meth:`convert` - Converts the expression of a physical quantity between units
- :meth:`expand_path` - Expands a file path by replacing '~' with the user
directory and makes the path absolute
- :meth:`flatten_dict` - Flattens a nested dictionary
- :meth:`flatten_list` - Flattens a nested list
- :meth:`figure` - Creates a figure and set its label
- :meth:`get_indices` - Returns the pair of indices that bound a target value in
a monotonically increasing vector
- :meth:`get_pow10` - Returns the exponent of 10 for which the significand
of a number is within the range [1, 10)
- :meth:`get_pow1000` - Returns the exponent of 1000 for which the
significand of a number is within the range [1, 1000)
- :meth:`load_csv` - Loads a CSV file into a dictionary
- :meth:`plot` - Plots 1D scalar data as points and/or line segments in 2D
Cartesian coordinates
- :meth:`quiver` - Plots 2D vector data as arrows in 2D Cartesian coordinates
- :meth:`save` - Saves the current figures as images in a format or list of
formats
- :meth:`saveall` - Saves all open figures as images in a format or list of
formats
- :meth:`setup_subplots` - Creates an array of subplots and return their axes
- :meth:`shift_scale_x` - Applies an offset and a factor as necessary to the x
axis
- :meth:`shift_scale_y` - Applies an offset and a factor as necessary to the y
axis
"""
__author__ = "Kevin Davies"
__email__ = "[email protected]"
__credits__ = ["Jason Grout", "Jason Heeris"]
__copyright__ = "Copyright 2012-2013, Georgia Tech Research Corporation"
__license__ = "BSD-compatible (see LICENSE.txt)"
import os
import wx
import numpy as np
import matplotlib.pyplot as plt
from collections import MutableMapping, namedtuple
from itertools import cycle
from decimal import Decimal
from math import floor
from matplotlib import rcParams
from matplotlib.lines import Line2D
from matplotlib.cbook import iterable
Quantity = namedtuple('Quantity', ['number', 'factor', 'offset', 'unit'])
"""Named tuple class for a constant physical quantity
The factor and then the offset are applied to the number to arrive at the
quantity expressed in terms of the unit.
"""
# Create a class to contain information about a unit conversion.
#Conversion = namedtuple('Conversion', ['unit', 'factor', 'offset', 'new_unit'])
def add_arrows(p, x_locs=[0], xstar_offset=0, ystar_offset=0,
lstar=0.05, label='',
orientation='tangent', color='r'):
r"""Overlay arrows with annotations on top of a pre-plotted line.
**Arguments:**
- *p*: 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:**
.. code-block:: python
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from modelicares import *
>>> # Create a plot.
>>> figure('examples/add_arrows') # doctest: +ELLIPSIS
<matplotlib.figure.Figure object at 0x...>
>>> x = np.arange(100)
>>> p = plt.plot(x, np.sin(x/4.0))
>>> # Add arrows and annotations.
>>> add_arrows(p[0], x_locs=x.take(np.arange(20,100,20)),
... label="Incr. time", xstar_offset=-0.15)
>>> save()
Saved examples/add_arrows.pdf
Saved examples/add_arrows.png
>>> plt.show()
.. only:: html
.. image:: ../examples/add_arrows.png
:scale: 70 %
:alt: example of add_arrows()
.. only:: latex
.. figure:: ../examples/add_arrows.pdf
:scale: 70 %
Example of add_arrows()
"""
from math import atan, cos, sin
# Get data from the plot lines object.
x_dat = plt.getp(p, 'xdata')
y_dat = plt.getp(p, 'ydata')
ax = p.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.
**Arguments:**
- *ax*: Axes (:class:`matplotlib.axes` object)
- *positions*: Positions (along the x axis)
- *labels*: List of labels for the lines
- *\*\*kwargs*: Line properties (propagated to
:meth:`matplotlib.pyplot.axhline`)
E.g., ``color='k', linestyle='--', linewidth=0.5``
**Example:**
.. code-block:: python
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from modelicares import *
>>> # Create a plot.
>>> figure('examples/add_hlines') # doctest: +ELLIPSIS
<matplotlib.figure.Figure object at 0x...>
>>> x = np.arange(100)
>>> y = np.sin(x/4.0)
>>> plt.plot(x, y) # doctest: +ELLIPSIS
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-1.2, 1.2])
(-1.2, 1.2)
>>> # Add horizontal lines and labels.
>>> add_hlines(positions=[min(y), max(y)], labels=["min", "max"],
... color='r', ls='--')
>>> save()
Saved examples/add_hlines.pdf
Saved examples/add_hlines.png
>>> plt.show()
.. only:: html
.. image:: ../examples/add_hlines.png
:scale: 70 %
:alt: example of add_hlines()
.. only:: latex
.. figure:: ../examples/add_hlines.pdf
:scale: 70 %
Example of add_hlines()
"""
# Process the inputs.
if not ax:
ax = plt.gca()
if not iterable(positions):
xpositions = (xpositions,)
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):
"""Add vertical lines to a set of axes with optional labels.
**Arguments:**
- *ax*: Axes (matplotlib.axes object)
- *positions*: Positions (along the x axis)
- *labels*: List of labels for the lines
- *\*\*kwargs*: Line properties (propagated to
:meth:`matplotlib.pyplot.axvline`)
E.g., ``color='k', linestyle='--', linewidth=0.5``
**Example:**
.. code-block:: python
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from modelicares import *
>>> # Create a plot.
>>> figure('examples/add_vlines') # doctest: +ELLIPSIS
<matplotlib.figure.Figure object at 0x...>
>>> x = np.arange(100)
>>> y = np.sin(x/4.0)
>>> plt.plot(x, y) # doctest: +ELLIPSIS
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-1.2, 1.2])
(-1.2, 1.2)
>>> # Add horizontal lines and labels.
>>> add_vlines(positions=[25, 50, 75], labels=["A", "B", "C"],
... color='k', ls='--')
>>> save()
Saved examples/add_vlines.pdf
Saved examples/add_vlines.png
>>> plt.show()
.. only:: html
.. image:: ../examples/add_vlines.png
:scale: 70 %
:alt: example of add_vlines()
.. only:: latex
.. figure:: ../examples/add_vlines.pdf
:scale: 70 %
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 animate(imagebase='_tmp', fname="animation", fps=10, clean=False):
"""Encode a series of PNG images as a MPG movie.
**Arguments:**
- *imagebase*: Base filename for the PNG images
The images should be located in the current directory as an
"*imagebase**xx*.png" sequence, where *xx* is a frame index.
- *fname*: Filename for the movie
".mpg" will be appended if necessary.
- *fps*: Number of frames per second
- *clean*: *True*, if the PNG images should be deleted afterward
.. Note:: This function requires mencoder_. On Linux, install it with the
following command: ``sudo apt-get install mencoder``. Currently, this
function is not supported on Windows.
.. _mencoder: http://en.wikipedia.org/wiki/MEncoder
**Example:**
.. code-block:: python
import matplotlib.pyplot as plt
from numpy.random import rand
from modelicares import *
# Create the frames.
fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(111)
for i in range(50): # 50 frames
ax.cla()
ax.imshow(rand(5,5), interpolation='nearest')
fname = '_tmp%02d.png' % i
print("Saving frame %i (file %s)" % (i, fname))
fig.savefig(fname) # doctest: +ELLIPSIS
# Assemble the frames into a movie.
animate(clean=True)
"""
# Note: The output of the code above is too large for inline doctest.
# TODO: Consider using the animation module from matplotlib. Should it
# supercede this function?
# TODO: Add support for Windows.
# Based on
# http://matplotlib.sourceforge.net/faq/howto_faq.html#make-a-movie,
# accessed 11/2/10
if not fname.lower().endswith('.mpg'):
fname += '.mpg'
print('Making movie "%s". This may take a while.' % fname)
os.system("mencoder 'mf://%s*.png' -mf type=png:fps=%i -ovc lavc "
"-lavcopts vcodec=wmv2 -oac copy -o %s"%(imagebase, fps, fname))
if clean:
from glob import glob
for image in glob(imagebase + '*.png'):
os.remove(image)
def color(ax, c, *args, **kwargs):
"""Plot 2D scalar data on a color axis in 2D Cartesian coordinates.
This uses a uniform grid.
**Arguments:**
- *ax*: Axis onto which the data should be plotted
- *c*: color- or c-axis data (2D array)
- *\*args*, *\*\*kwargs*: Additional arguments for
:meth:`matplotlib.pyplot.imshow`
**Example:**
.. code-block:: python
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from modelicares import *
>>> figure('examples/color') # doctest: +ELLIPSIS
<matplotlib.figure.Figure object at 0x...>
>>> 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)
>>> ax = plt.subplot(111)
>>> color(ax, c) # doctest: +ELLIPSIS
<matplotlib.image.AxesImage object at 0x...>
>>> save()
Saved examples/color.pdf
Saved examples/color.png
>>> plt.show()
.. only:: html
.. image:: ../examples/color.png
:scale: 70 %
:alt: example of color()
.. only:: latex
.. figure:: ../examples/color.pdf
:scale: 70 %
Example of color()
"""
return ax.imshow(c, *args, **kwargs)
def closeall():
"""Close all open figures.
This is a shortcut for the following:
>>> from matplotlib._pylab_helpers import Gcf
>>> Gcf.destroy_all()
"""
from matplotlib._pylab_helpers import Gcf
Gcf.destroy_all()
#for manager in Gcf.get_all_fig_managers():
# manager.canvas.figure.close()
#plt.close("all")
def convert(quantity):
"""Convert the expression of a physical quantity between units.
**Arguments:**
- *quantity*: Instance of :class:`Quantity`
**Example:**
.. code-block:: python
>>> from modelicares import *
>>> T = 293.15 # Temperature in K
>>> T_degC = convert(Quantity(T, factor=1, offset=-273.15, unit='C'))
>>> print(str(T) + " K is " + str(T_degC) + " degC.")
293.15 K is 20.0 degC.
"""
return quantity.number*quantity.factor + quantity.offset
def expand_path(path):
r"""Expand a file path by replacing '~' with the user directory and making
the path absolute.
**Example:**
.. code-block:: python
>>> from modelicares import *
>>> expand_path('~/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(path))
def flatten_dict(d, parent_key='', separator='.'):
"""Flatten a nested dictionary.
**Arguments:**
- *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:**
>>> from modelicares import *
>>> 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 flatten_list(l, ltypes=(list, tuple)):
"""Flatten a nested list.
**Arguments:**
- *l*: List (may be nested to an arbitrary depth)
If the type of *l* is not in ltypes, then it is placed in a list.
- *ltypes*: Tuple (not list) of accepted indexable types
**Example:**
>>> from modelicares import *
>>> flatten_list([1, [2, 3, [4]]])
[1, 2, 3, 4]
"""
# Based on
# http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html,
# 10/28/2011
ltype = type(l)
if ltype not in ltypes: # So that strings aren't split into characters
return [l]
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
if l[i]:
l[i:i + 1] = l[i]
else:
l.pop(i)
i -= 1
break
i += 1
return ltype(l)
def figure(label='', *args, **kwargs):
"""Create a figure and set its label.
**Arguments:**
- *label*: String to apply to the figure's *label* property
- *\*args*, *\*\*kwargs*: Additional arguments for
:meth:`matplotlib.pyplot.figure`
**Example:**
.. code-block:: python
>>> fig = figure("velocity_vs_time") # doctest: +ELLIPSIS
>>> plt.getp(fig, 'label')
'velocity_vs_time'
.. Note:: The *label* property is used as the base filename in the
:meth:`saveall` method.
"""
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 _gen_offset_factor(label, tick_lo, tick_up, eagerness=0.325):
"""Apply an offset and a scaling factor to a label if necessary.
**Arguments:**
- *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: Utilize 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.
**Arguments:**
- *x*: Vector
- *target*: Target value
**Example:**
>>> from modelicares import *
>>> 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(np.floor((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_pow10(num):
"""Return the exponent of 10 for which the significand of a number is
within the range [1, 10).
**Example:**
>>> get_pow10(50)
1
"""
# Based on an algorithm by Jason Heeris 11/18/2009:
#
dnum = Decimal(str(num))
if dnum == 0:
return 0
elif dnum < 0:
dnum = -dnum
return int(floor(dnum.log10()))
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/[email protected]/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):
"""Load a CSV file into a dictionary.
The strings from the header row are used as dictionary keys.
**Arguments:**
- *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 :meth:`csv.reader`
**Example:**
>>> from modelicares import *
>>> data = load_csv("examples/load-csv.csv", header_row=2)
>>> print("The keys are: %s" % data.keys())
The keys are: ['Price', 'Description', 'Make', 'Model', 'Year']
"""
import csv
try:
reader = csv.reader(open(fname), **kwargs)
except IOError:
print('Unable to load "%s". Check that it exists.' % fname)
return
# Read the header row and create the dictionary from it.
for i in range(header_row):
reader.next()
keys = reader.next()
data = dict.fromkeys(keys)
#print("The keys are: ")
#print(keys)
# Read the data.
if first_data_row:
for row in range(first_data_row - header_row - 1):
reader.next()
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, basestring):
data[key] = column
elif isinstance(t, (float, int)):
data[key] = np.array(map(t, column))
else:
data[key] = map(t, column)
except ValueError:
print("Could not cast column %i into %i." % (i, t))
return
else:
for key, column in zip(keys, zip(*reader)):
try:
data[key] = np.array(map(int, column))
except:
try:
data[key] = np.array(map(float, column))
except:
data[key] = map(str, column)
return data
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):
"""Plot 1D scalar data as points and/or line segments in 2D Cartesian
coordinates.
This is similar to :meth:`matplotlib.pyplot.plot` (and actually calls that
method), but provides direct support for plotting an arbitrary number of
curves.
**Arguments:**
- *y*: y-axis data
This may contain multiple series.
- *x*: x-axis data
If *x* is not provided, the y-axis data 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)
- *color*: Single entry, list, or :class:`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 :class:`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 :class:`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.sourceforge.net/api/collections_api.html
- *\*\*kwargs*: Additional arguments for :meth:`matplotlib.pyplot.plot`
**Returns:** List of :class:`matplotlib.lines.Line2D` objects
**Example:**
.. testsetup::
>>> closeall()
.. code-block:: python
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from modelicares import *
>>> figure('examples/plot') # doctest: +ELLIPSIS
<matplotlib.figure.Figure object at 0x...>
>>> ax = plt.subplot(111)
>>> plot([range(11), range(10, -1, -1)], ax=ax) # doctest: +ELLIPSIS
[[<matplotlib.lines.Line2D object at 0x...>], [<matplotlib.lines.Line2D object at 0x...>]]
>>> save()
Saved examples/plot.pdf
Saved examples/plot.png
>>> plt.show()
.. only:: html
.. image:: ../examples/plot.png
:scale: 70 %
:alt: example of plot()
.. only:: latex
.. figure:: ../examples/plot.pdf
:scale: 70 %
Example of plot()
"""
# 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=color.next(), marker=marker.next(),
dashes=dashes.next(), **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=color.next(), marker=marker.next(),
dashes=dashes.next(), **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=color.next(), marker=marker.next(),
dashes=dashes.next(), **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):
"""Plot 2D vector data as arrows in 2D Cartesian coordinates.
Uses a uniform grid.
**Arguments:**
- *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 :meth:`matplotlib.pyplot.quiver`)