This file is indexed.

/usr/bin/plotit is in python-wxmpl 2.0.0-2.1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
#! /usr/bin/python

# Name: plotit
# Purpose: Experiment data visualization
# Author: Ken McIvor <mcivor@iit.edu>
#
# Copyright 2004-2009 Illinois Institute of Technology
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL ILLINOIS INSTITUTE OF TECHNOLOGY BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Except as contained in this notice, the name of Illinois Institute
# of Technology shall not be used in advertising or otherwise to promote
# the sale, use or other dealings in this Software without prior written
# authorization from Illinois Institute of Technology.

# ChangeLog
#
# 10-17-2011  Carlo Segre <segre@iit.edu>
#  * Release 3.0
#  * Replace all references to Numerix with Numpy
# 02-21-2009  Ken McIvor <mcivor@iit.edu>
#  * Release 2.3.4
#  * Fixed a bug that was breaking the quickplot ('-q') mode
# 02-20-2009  Ken McIvor <mcivor@iit.edu>
#  * Release 2.3.3
#  * Stopped using the deprecated 'sre' module
#  * Updated legend formatting for matplotlib 0.98.x
#  * Dollar signs in axes labels are now properly escaped
# 04-06-2006  Ken McIvor <mcivor@iit.edu>
#  * Release 2.3.2
#  * Had another go at shutting down cleanly after the "exit" command while in
#    stripchart mode.
#  * Fixed a bug in cmd_START_PLOT()'s error handling.
# 04-04-2006  Ken McIvor <mcivor@iit.edu>
#  * Release 2.3.1
#  * Attemped to fix a subtle race condition that caused the plot window to
#    survive the "exit" command, hanging around at the end of MX quick scans.
#  * Switched to using LinearLocator(5) for X and Y axis tick locations to
#    yield nicer looking plots for the occasional corner cases (e.g. when
#    AutoLocator gives you 9 ticks with overlapping labels).
# 11-14-2005  Ken McIvor <mcivor@iit.edu>
#  * Release: 2.3
#  * Column names may be used in expressions if they are present in the files
#  * Empty data files no longer cause the entire plot to fail
#  * Column expressions are now masked arrays, clamping +/- INF
# 11-11-2005  Ken McIvor <mcivor@iit.edu>
#  * Merged the ScalarFormatter fix from August back into the main trunk.  This
#    fix undoes some of the confusing axis labeling caused by changes
#    introduced in matplotlib 0.81.
# 10-21-2005  Ken McIvor <mcivor@iit.edu>
#  * Release: 2.2
#  * Added full support for plotgngu.pl's start_plot command.  The two integer
#    arguments that were previously ignored are now required and specify the
#    number of columns of independently varying data and the column index that
#    contains the abscissa (starting from zero).
# 08-08-2005  Ken McIvor <mcivor@iit.edu>
#  * Release: 2.1.1
#  * Worked around a problem in matplotlib so that PlotIt no longer chokes on
#    expressions that evaluate to inf or NaN.
# 07-10-2005  Ken McIvor <mcivor@iit.edu>
#  * Release: 2.1
#  * Quickplot mode now correctly handles single-column data files.
#  * You can now plot only the Y expressions of files from the command line.
#  * PlotIt now tries to remeber its last window position, which should improve
#    the user experience when it's being used by MX to display scan data.
# 05-26-2005  Ken McIvor <mcivor@iit.edu>
#  * Release: 2.0
# 05-23-2005  Ken McIvor <mcivor@iit.edu>
#  * Fixed a bug in the `set linestyles' command.
#  * Made the linestyles, ticksize, and ticks `set' commands more robust
#    against invalid arguments.
#  * The PlotItApp no longer redirects stderr.
# 05-19-2005  Ken McIvor <mcivor@iit.edu>
#  * Release: 2.0rc4
#  * The command-line invocation has been changed so `$ plotit' won't appear to
#    hang as it reads commands from standard input.
#  * Added a quick-plotting mode that graphs the first two columns of files.
#  * Expression evaluation only does one row at a time if an error occurs.
#  * Error handling in expression evaluation is much more robust.
# 05-15-2005  Ken McIvor <mcivor@iit.edu>
#   * Release: 2.0rc3 (`plot' is now `plotit')
#   * Refactored the static vs. stripcharting logic out of PlotApp
#   * Cleaned up the MX kludges, especially the workaround for wx.PostEvent()
#     hanging after MainLoop() has exited (a queue is now used in place of the
#     CommandEvent).
#   * The plot window is now unclosable while stripcharting stdin.
#   * Fixed up bug where cmd_START_PLOT() relied entirely on parse_command() to
#     split up the equations.
#   * Added several new `set' commands: ticks, ticksize, linestyles.
#   * Added the `marker' command to draw vertical lines.
#   * Plot expressions now recognize `@N' for column names in addition to `$N'.
#   * Added the ability to do quick plots of multiple data files from the
#     command line.
# 05-12-2005  Ken McIvor <mcivor@iit.edu>
#   * Added some missing calls to sys.exit() to the ImportError handlers.
#   * Added the `start_plot' command and special case handling for MX's
#     inconsistent syntax (e.g. "start_plot;0;1;$f[0]/$f[1]").
#   * The `plot' command is now a no-op, since MX sends it after every `data'
#     command.
#   * Fixed a bug where `convert_plotgnu_expression()' was omitting the rest of
#     the expression after the last channel number (e.g. "log($0/$1)" was
#     becoming "log($2/$3")
#   * Added an `exit' command.
#   * Fixed the way the PlotApp and FileReaderThread interact because
#     `wx.PostEvent()' blocks after the PlotApp has exited.
# 05-10-2005  Ken McIvor <mcivor@iit.edu>
#   * release: 2.0rc2
#   * Default behavior is now to watch stdin, but not watch files.  The `-w'
#     argument has been changed to reflect this.
#   * Plot window now has a correct title, rather than just "WxMpl".
# 05-05-2005  Ken McIvor <mcivor@iit.edu>
#   * release: 2.0rc1
#   * WxMpl is now used for the plotting, rather than including wxPyPlot
#   * The `plot' command has been changed to be compatible with `plotgnu'
#   * A new command, `line', has been added to support the new equation syntax
#   * Replotting is now driven by a timer, rather than the arrival of new data
#   * The Python 2.1 compatability fixes have been removed, since matplotlib
#     requires Python 2.3 or later.
# 10-04-2004  Ken McIvor <mcivken@iit.edu>
#   * release: 1.1
#   * Debian Stable fixes:
#     - removed `typecode' keyword from Numerix.zeros()
#     - forcibly placed wxPython.wx.wxNewId() into wx as NewId()
# 10-03-2004  Ken McIvor <mcivken@iit.edu>
#   * release: 1.0

__version__ = '2.3.2'


import ConfigParser
import os.path
import re
import sys
import threading

try:
    import wx
except ImportError:
    if __name__ == '__main__':
        sys.stderr.write('''\
This program requires wxPython, the Python bindings for the wxWidgets GUI
framework.

    wxPython can be downloaded from http://www.wxpython.org
''')
        sys.exit(1)

try:
    import matplotlib
except ImportError:
    if __name__ == '__main__':
        sys.stderr.write('''\
This program requires matplotlib, Python's 2D plotting library.

    matplotlib can be downloaded from http://matplotlib.sourceforge.net
''')
        sys.exit(1)

try:
    import wxmpl
except ImportError:
    if __name__ == '__main__':
        sys.stderr.write('''\
This program requires WxMpl, a library for embedding matplotlib in wxPython
applications.

    WxMpl can be downloaded from http://agni.phys.iit.edu/~kmcivor/wxmp/
''')
        sys.exit(1)

try:
    import xdp.io # if it's available, use XDP to load data
except ImportError:
    xdp = None


import numpy as NumPy
from matplotlib.font_manager import FontProperties


class Queue:
    def __init__(self):
        self.mutex = threading.Lock()
        self.queue = []

    def put(self, item):
        self.mutex.acquire()
        self.queue.append(item)
        self.mutex.release()

    def getAll(self):
        self.mutex.acquire()
        items = self.queue[:]
        del self.queue[:]
        self.mutex.release()
        return items


#
# Functions to load and store the plot window's position.
#

# FIXME: this is rather POSIX-specific
PLOTIT_POSITION_FILE = '~/.plotitrc'


def load_window_position():
    fnam = os.path.expanduser(PLOTIT_POSITION_FILE)
    cp = ConfigParser.ConfigParser()

    try:
        cp.read([fnam])
        x = cp.getint('position', 'x')
        y = cp.getint('position', 'y')
    except Exception:
        return wx.DefaultPosition

    return wx.Point(x, y)


def store_window_position(pos):
    fnam = os.path.expanduser(PLOTIT_POSITION_FILE)
    cp = ConfigParser.ConfigParser()
    cp.add_section('position')
    cp.set('position', 'x', str(pos.x))
    cp.set('position', 'y', str(pos.y))
 
    try:
        output = file(fnam, 'w')
        cp.write(output)
        output.close()
    except Exception:
        pass


#
# wxPython Application class
#

class PlotItApp(wx.App):
    def __init__(self, options, arguments, **kwds):
        self.options = options
        self.director = None
        self.arguments = arguments
        wx.App.__init__(self, **kwds)

    def OnInit(self):
        self.frame = PlotFrame(pos=load_window_position())

        if len(self.arguments) < 2 and not options.quick:
            self.init_plotgnu()
        else:
            self.init_quickplot()

        self.frame.Show(True)
        return True

    def init_plotgnu(self):
        args = self.arguments

        if args[0] == '-':
            inputFile = sys.stdin
            options.watch = not options.watch
        else:
            try:
                inputFile = file(args[0], 'r')
            except IOError, e:
                fatalIOError(e)

        if self.options.watch:
            self.director = StripChartDirector(self.frame, inputFile)
        else:
            self.director = PlotCommandDirector(self.frame, inputFile)

    def init_quickplot(self):
        args = self.arguments
        style = 'lp'

        if options.lines and options.points:
            pass # let people type `-lp' like in GNUPLOT
        elif options.lines:
            style = 'l'
        elif options.points:
            style = 'p'

        if options.quick:
            self.director = QuickPlotDirector(self.frame, args, style)
        else:
            if len(args) == 2 or not is_plot_expression(args[1]):
                xExpr = None
                yExpr, fileNames = args[0], args[1:]
            else:
                xExpr, yExpr, fileNames = args[0], args[1], args[2:]

            self.director = ExpressionPlotDirector(self.frame, xExpr, yExpr,
                fileNames, style)

    def cleanup(self):
        self.director.cleanup()


class PlotFrame(wxmpl.PlotFrame):
    ABOUT_TITLE = 'About plotit'

    ABOUT_MESSAGE = ('plotit %s\n' %  __version__
        + 'Written by Ken McIvor <mcivor@iit.edu>\n'
        + 'Copyright 2004-2005 Illinois Institute of Technology')

    def __init__(self, **kwds):
        wxmpl.PlotFrame.__init__(self, None, -1, 'plotit', **kwds)


#
# Classes to perform the various kinds of plotting
#

class PlotDirector:
    def __init__(self, frame):
        self.frame = frame
        wx.EVT_CLOSE(self.frame, self.OnClose)

    def OnClose(self, evt):
        store_window_position(self.frame.GetPosition())
        evt.Skip()

    def setup_axes(self, axes):
        if matplotlib.__version__ >= '0.81':
            axes.yaxis.set_major_formatter(
                matplotlib.ticker.OldScalarFormatter())
            axes.yaxis.set_major_locator(
                matplotlib.ticker.LinearLocator(5))

            axes.xaxis.set_major_formatter(
                matplotlib.ticker.OldScalarFormatter())
            axes.xaxis.set_major_locator(
                matplotlib.ticker.LinearLocator(5))

    def cleanup(self):
        pass


class PlotCommandDirector(PlotDirector):
    def __init__(self, frame, inputFile):
        PlotDirector.__init__(self, frame)

        frame.SetTitle(get_frame_title(inputFile))
        interpreter = CommandInterpreter(frame.get_figure().gca(),
           inputFile, ignoreExit=True)

        line = inputFile.readline()
        while line:
            line = line.strip()
            interpreter.doCommand(line)
            line = inputFile.readline()
        interpreter.replot()


class StripChartDirector(PlotDirector):
    def __init__(self, frame, inputFile):
        PlotDirector.__init__(self, frame)

        axes = frame.get_figure().gca()
        self.setup_axes(axes)

        frame.SetTitle(get_frame_title(inputFile))
        self.inputFile = inputFile
        self.canClose = inputFile is not sys.stdin

        self.interpreter = CommandInterpreter(axes, inputFile)
        self.queue = Queue()
        self.fileReader = FileReaderThread(inputFile, self.queue)
        self.timer = wx.PyTimer(self.OnTimer)

        self.timer.Start(250)
        self.fileReader.start()

    def OnClose(self, evt):
        if not self.canClose and evt.CanVeto() and self.fileReader.isAlive():
            wx.Bell()
            evt.Veto()
        else:
            self.timer.Stop()
            PlotDirector.OnClose(self, evt)

    def OnTimer(self):
        interpreter = self.interpreter

        for cmd in self.queue.getAll():
            interpreter.doCommand(cmd)
            if interpreter.hasExited:
                self.timer.Stop()
                try:
                    self.inputFile.close()
                except:
                    pass

        if self.fileReader.isAlive():
            interpreter.replot()
        else:
            self.timer.Stop()
            interpreter.replot()

    def cleanup(self):
        if self.fileReader.isAlive():
            self.fileReader.join()


class QuickPlotDirector(PlotDirector):
    def __init__(self, frame, inputFiles, style):
        PlotDirector.__init__(self, frame)
        frame.SetTitle('PlotIt')

        axes = frame.get_figure().gca()
        self.setup_axes(axes)

        # FIXME: refactor this chunk into a function shared by
        # QuickPlotDirector and ExpressionPlotDirector
        lines = []
        for inputFile in inputFiles[:]:
            x, y = quickplot_evaluate_file(inputFile)
            if x is None or y is None:
                inputFiles.remove(inputFile)
            else:
                lines.append((x, y))

        inputs = [split_path(x) for x in inputFiles]
        if len(inputs) == 1:
            idx = 0
        else:
            idx = len(os.path.commonprefix([x[0] for x in inputs]))

        matplotlib.rc('lines', markersize=2)
        for i, (x, y) in enumerate(lines):
            if x is None or y is None:
                continue

            path, name = inputs[i]
            fullName = os.path.join(path[idx:], name)
            line = axes.plot(x, y, label=fullName)[0]

            if style == 'l':
                pass
            elif style == 'p':
                line.set_linestyle('None')
                line.set_marker('o')
            else:
                line.set_marker('o')
            line.set_markeredgecolor(line.get_color())
            line.set_markerfacecolor(line.get_color())

        if not axes.get_lines():
            sys.stderr.write('%s: no data to plot\n'
                % os.path.basename(sys.argv[0]))
            sys.exit(1)

        axes.legend(numpoints=2, prop=FontProperties(size='x-small'))


class ExpressionPlotDirector(PlotDirector):
    def __init__(self, frame, xExpr, yExpr, inputFiles, style):
        PlotDirector.__init__(self, frame)
        frame.SetTitle('PlotIt')

        axes = frame.get_figure().gca()
        self.setup_axes(axes)
        axes.set_ylabel(yExpr.replace('@', '$').replace('$', '\$'))

        if xExpr is None:
            axes.set_xlabel('0...N')
        else:
            axes.set_xlabel(xExpr.replace('@', '$').replace('$', '\$'))

        lines = []
        for inputFile in inputFiles[:]:
            x, y = evaluate_file(inputFile, xExpr, yExpr)
            if x is None or y is None:
                inputFiles.remove(inputFile)
            else:
                lines.append((x, y))

        inputs = [split_path(x) for x in inputFiles]
        if len(inputs) == 1:
            idx = 0
        else:
            idx = len(os.path.commonprefix([x[0] for x in inputs]))

        matplotlib.rc('lines', markersize=2)
        for i, (x, y) in enumerate(lines):
            if x is None or y is None:
                continue

            path, name = inputs[i]
            fullName = os.path.join(path[idx:], name)
            line = axes.plot(x, y, label=fullName)[0]

            if style == 'l':
                pass
            elif style == 'p':
                line.set_linestyle('None')
                line.set_marker('o')
            else:
                line.set_marker('o')
            line.set_markeredgecolor(line.get_color())
            line.set_markerfacecolor(line.get_color())

        if not axes.get_lines():
            sys.stderr.write('%s: no data to plot\n'
                % os.path.basename(sys.argv[0]))
            sys.exit(1)

        axes.legend(numpoints=2, prop=FontProperties(size='x-small'))

    def cleanup(self):
        pass



#
# Thread that pushes lines from a file into a Queue
#

class FileReaderThread(threading.Thread):
    def __init__(self, inputFile, queue):
        threading.Thread.__init__(self, name='FileReader')
        self.queue = queue
        self.inputFile = inputFile

    def run(self):
        queue = self.queue
        inputFile = self.inputFile

        line = inputFile.readline()
        while line:
            line = line.strip()
            queue.put(line)
            line = inputFile.readline()


#
# Class that executes plotting commands
#

class CommandInterpreter:
    def __init__(self, axes, inputFile, ignoreExit=False):
        self.axes = axes
        self.ignoreExit = ignoreExit

        if inputFile is sys.stdin:
            self.fileDesc = 'standard input'
        else:
            self.fileDesc = 'file `%s\'' % inputFile.name

        self.buffer = wxmpl.MatrixBuffer()
        self.charter = wxmpl.StripCharter(axes)
        self.channels = []
        self.hasExited = False
        self.need_replot = False

        matplotlib.rc('lines', markersize=2)

    def replot(self):
        if self.need_replot and not self.hasExited:
            self.need_replot = False
            self.charter.update()

    def doCommand(self, command):
        tokens = self.parse_command(command)
        if not len(tokens):
            return

        cmd, args = tokens[0].upper(), tokens[1:]
        method = getattr(self, 'cmd_%s'%cmd, None)
        if callable(method) and method(args):
            self.need_replot = True

    def parse_command(self, command):
        if command.startswith('start_plot;'):
            return ['start_plot'] + command.split(';')[1:]

        try:
            return tokenize(command)
        except Exception:
            return []

    def cmd_START_PLOT(self, args):
        if len(args) < 3:
            return False

        try:
            independent_variable_count = int(args[0])
            innermost_loop_motor_index = int(args[1])
        except (ValueError, OverflowError), e:
            print >> sys.stderr, (
                'Error in "start_plot" statement for file %s: %s'
                % (self.fileDesc, e))
            return False

        if independent_variable_count < 1:
            independent_variable_count = 0

        if innermost_loop_motor_index < 0:
            innermost_loop_motor_index = 0

        xExpr = '$%d' % (innermost_loop_motor_index + 1)

        for eqn in args[2:]:
            yExpr = convert_plotgnu_expression(eqn, independent_variable_count)
            channel = ExpressionChannel(self.buffer, xExpr, yExpr,
                self.fileDesc)
            channel.marker = 'o'
            self.channels.append(channel)
        self.charter.setChannels(self.channels)
        return True

    def cmd_PLOT(self, args):
        return False

    def cmd_REPLOT(self, args):
        self.replot()
        return False

    def cmd_SET(self, args):
        if len(args):
            var, args = args[0].upper(), args[1:]

            if len(args) and args[0] == '=':
                args = args[1:]

            method = getattr(self, 'set_%s'%var, None)
            if callable(method):
                return method(args)
        return False

    def cmd_DATA(self, args):
        if not len(args):
            return False

        data = [0.0] * len(args)
        for i, point in enumerate(args):
            try:
                data[i] = float(point)
            except Exception, e:
                pass

        self.buffer.append(data)
        for channel in self.channels:
            channel.recalculate()
        return True

    def cmd_MARKER(self, args):
        if len(args) != 1:
            return False

        try:
            x = float(args[0])
        except:
            return False

        self.axes.axvline(x, color='k', linestyle='--')
        return True

    def set_TITLE(self, args):
        if len(args) == 1:
            self.axes.set_title(args[0])
            return True
        else:
            return False

    def set_XLABEL(self, args):
        if len(args) == 1:
            self.axes.set_xlabel(args[0])
            return True
        else:
            return False

    def set_YLABEL(self, args):
        if len(args) == 1:
            self.axes.set_ylabel(args[0])
            return True
        else:
            return False

    def set_TIC(self, args):
        return self.set_TICKS(args)

    def set_TICS(self, args):
        return self.set_TICKS(args)

    def set_TICSIZE(self, args):
        return self.set_TICKSIZE(args)

    def set_TICKS(self, args):
        if len(args):
            ticks = []
            for tick in args:
                if matplotlib.lines.Line2D._markers.has_key(tick):
                    ticks.append(tick)
                else:
                    ticks.append(None)
            for i, marker in enumerate(ticks[:len(self.channels)]):
                self.channels[i].marker = marker
        else:
            for channel in self.channels:
                channel.marker = None
        self.charter.setChannels(self.channels)
        return True

    def set_TICKSIZE(self, args):
        if len(args) == 0:
            matplotlib.rc('lines', markersize=2)
            return
        elif len(args) != 1:
            return True

        try:
            size = float(args[0])
        except:
            return False

        if markersize <= 0:
            return False

        matplotlib.rc('lines', markersize=size)
        return True

    def set_LINESTYLES(self, args):
        if len(args):
            styles = []
            for style in args:
                if matplotlib.lines.Line2D._lineStyles.has_key(style):
                    styles.append(style)
                else:
                    styles.append(None)
            for i, style in enumerate(styles[:len(self.channels)]):
                self.channels[i].style = style
        else:
            for channel in self.channels:
                channel.style = None
        self.charter.setChannels(self.channels)
        return True

    def set_LEGEND(self, args):
        if len(args):
            for i, label in enumerate(args[:len(self.channels)]):
                self.channels[i].name = label
            self.charter.setChannels(self.channels)
        else:
            self.axes.legend_ = None
        return True

    def cmd_EXIT(self, args):
        if self.ignoreExit:
            return False

        app = wx.GetApp()
        if app is not None:
            app.ExitMainLoop()
            self.hasExited = True
        return False


#
# Channels that calculate their X and Y data from expressions
#

class ExpressionChannel(wxmpl.Channel):
    def __init__(self, buffer, xExpr, yExpr, fileDesc):
        if xExpr is None:
            label = yExpr
        else:
            label = xExpr + ', ' + yExpr

        wxmpl.Channel.__init__(self, label)
        self.buffer = buffer
        self.x = None
        self.y = None
        self.xExpr = xExpr
        self.yExpr = yExpr
        self.fileDesc = fileDesc

    def getX(self):
        def failure(msg, *args):
            print >> sys.stderr, (msg % args) ; self.x = None ; return None

        if self.x is not None:
            return self.x

        if self.xExpr is None:
            data = self.buffer.getData()
            if data is not None:
                self.x = data[:, 0]
                return self.x

        try:
            self.x = evaluate_expression(self.xExpr, self.buffer.getData())
        except Exception, e:
            return failure('Error evaluating X expression `%s\' for %s: %s',
                self.xExpr, self.fileDesc, e)

        if (self.x is not None
        and not isinstance(self.x,
         (NumPy.ArrayType, NumPy.ma.MaskedArray))):
            return failure('Error evaluating X expression `%s\' for %s: '
                'result is not a vector', self.xExpr, self.fileDesc)

        return self.x

    def getY(self):
        def failure(msg, *args):
            print >> sys.stderr, (msg % args) ; self.y = None ; return None

        if self.y is not None:
            return self.y

        try:
            self.y = evaluate_expression(self.yExpr, self.buffer.getData())
        except Exception, e:
            return failure('Error evaluating Y expression `%s\' for %s: %s',
                self.yExpr, self.fileDesc, e)

        if (self.y is not None
        and not isinstance(self.y,
         (NumPy.ArrayType, NumPy.ma.MaskedArray))):
            return failure('Error evaluating Y expression `%s\' for %s: '
                'result is not a vector', self.yExpr, self.fileDesc)

        return self.y

    def recalculate(self):
        self.x = self.y = None
        self.setChanged(True)


#
# Evaluate X and Y expressions using a file of data
#

def quickplot_evaluate_file(fileName):
    def failure(msg, *args):
        print >> sys.stderr, (msg % args)
        return None, None

    data, columnNames = load_data(fileName)
    if data is None:
        return None, None

    if data.shape[1] == 1:
        return NumPy.arange(0, data.shape[0], 1, dtype=float), data[:, 0]
    else:
        return data[:, 0], data[:, 1]


def evaluate_file(fileName, xExpr, yExpr):
    def failure(msg, *args):
        print >> sys.stderr, (msg % args)
        return None, None

    data, columnNames = load_data(fileName)
    if data is None:
        return None, None

    try:
        x = evaluate_expression(xExpr, data, columnNames)
    except Exception, e:
        return failure('Error evaluating X for file `%s\': %s', fileName, e)

    try:
        y = evaluate_expression(yExpr, data, columnNames)
    except Exception, e:
        return failure('Error evaluating Y for file `%s\': %s', fileName, e)

    if not isinstance(x, (NumPy.ArrayType, NumPy.ma.MaskedArray)):
        return failure('Error evaluating X for file `%s\': result is not a '
            'vector', fileName)
    elif not isinstance(y, (NumPy.ArrayType, NumPy.ma.MaskedArray)):
        return failure('Error evaluating Y for file `%s\': result is not a '
            'vector', fileName)

    if x.shape != y.shape:
        return failure('BUG? x.shape != y.shape for file `%s\'', fileName)

    return x, y


def load_data(fileName):
    if xdp is not None:
        try:
            header, dataset = xdp.io.readFile(fileName)
        except IOError:
            pass
        else:
            return dataset.getMatrix(), dataset.getColumnNames()

    try:
        input = file(fileName, 'r')
    except IOError, e:
        fatalIOError(e)

    buffer = wxmpl.MatrixBuffer()

    line = input.readline()
    while line:
        line = line.strip()
        if line:
            _parse_data(buffer, line)
        line = input.readline()

    input.close()
    return buffer.getData(), ()


def _parse_data(buffer, line):
    failures = 0
    values = line.split()
    data = [0.0] * len(values)
    for i, point in enumerate(values):
        try:
            data[i] = float(point)
        except Exception, e:
            if i == 0 and point == 'data':
                failures += 1
            else:
                return

    if failures:
        buffer.append(data[failures:])
    else:
        buffer.append(data)


#
# Evaluating equations against a matrix
#

def is_plot_expression(string):
    return (COLNUMS.search(string) is not None
        or COLNAMES.search(string) is not None
        or PG_COLNUMS.search(string) is not None)


def convert_plotgnu_expression(pgExpr, offset):
    i = 0
    expr = ''
    while 1:
        m = PG_COLNUMS.search(pgExpr[i:])
        if m is None:
            break
        expr += pgExpr[i:i+m.start()]
        expr += '$' + str(int(m.group('number'))+offset+1)
        i += m.end()
    expr += pgExpr[i:]
    return expr


def evaluate_expression(expr, data, columnNames=()):
    if data is None:
        return None
    elif expr is None:
        return NumPy.arange(0, data.shape[0], 1, dtype=float)

    columnCount = data.shape[1]
    namespace = EVAL_NAMESPACE.copy()

    for column, _, number in COLNUMS.findall(expr):
        number = int(number)
        if number < 1 or number > columnCount:
            raise ValueError('invalid column "%s"' % number)

    for column, _, name in COLNAMES.findall(expr):
        if not columnNames:
            raise ValueError('column names are unavailable')
        elif name not in columnNames:
            raise ValueError('invalid column "%s"' % name)

    expr = COLNUMS.sub('__C_\g<number>', expr)
    expr = COLNAMES.sub('__C_\g<name>', expr)

    try:
        code = compile(expr, '<expr>', 'eval')
    except SyntaxError, e:
        raise ValueError('incorrect syntax: %s' % e)

    for i in range(0, columnCount):
        namespace['__C_%d' % (i+1)] = None
    for i in range(0, min(columnCount, len(columnNames))):
        namespace['__C_%s' % columnNames[i]] = None

    for var in code.co_names:
        if not namespace.has_key(var):
            raise ValueError('invalid variable "%s"' % var)

    # try to evaluate things the fast way
    # XXX: causes problems with Matplotlib, which chokes on `inf' and `NaN'.
    for i in range(0, columnCount):
        namespace['__C_%d' % (i+1)] = data[:, i]
    for i in range(0, min(columnCount, len(columnNames))):
        namespace['__C_%s' % columnNames[i]] = data[:, i]

    try:
        result = eval(code, namespace)
        return NumPy.ma.masked_outside(result, -1e308, 1e308)
    except Exception, e:
        pass

    # evaluate one point at a time if necessary
    res = NumPy.zeros((data.shape[0],), dtype=float)
    for i in range(0, data.shape[0]):
        for j in range(0, columnCount):
            namespace['__C_%d' % (j+1)] = data[i, j]
        for j in range(0, min(columnCount, len(columnNames))):
            namespace['__C_%s' % columnNames[j]] =data[i, j]

        try:
            res[i] = eval(code, namespace)
        except Exception, e:
            pass
    return res

COLNUMS    = re.compile(r'(?P<column>(\$|\@)(?P<number>\d+))')
COLNAMES   = re.compile(r'(?P<column>(\$|\@)(?P<name>[a-zA-Z_][a-zA-Z0-9_]*))')
PG_COLNUMS = re.compile(r'(?P<column>\$f\[(?P<number>\d+)\])')

EVAL_NAMESPACE = {
    'int': int,
    'float': float,
    'complex': complex,
    'pi': NumPy.pi,
    'e': NumPy.e,
    'abs': NumPy.absolute,
    'arccos': NumPy.arccos,
    'arccosh': NumPy.arccosh,
    'arcsin': NumPy.arcsin,
    'arcsinh': NumPy.arcsinh,
    'arctan': NumPy.arctan,
    'arctanh': NumPy.arctanh,
    'cos': NumPy.cos,
    'cosh': NumPy.cosh,
    'exp': NumPy.exp,
    'log': NumPy.log,
    'log10': NumPy.log10,
    'power': NumPy.power,
    'sin': NumPy.sin,
    'sinh': NumPy.sinh,
    'sqrt': NumPy.sqrt,
    'tan': NumPy.tan,
    'tanh': NumPy.tanh
}


#
# Potpourri utility functions
#

WORD   = r'(\\.)|[^"\'\s]'
DWORD  = r'(\\.)|[^"\s]'
SWORD  = r'(\\.)|[^\'\s]'
DQUOTE = r'%s| |\t' % SWORD
SQUOTE = r'%s| |\t' % SWORD
RE_SKIP  = re.compile(r'\s+')
RE_TOKEN = re.compile(r'(%s)+|("(%s|(\\.))*")|(\'(%s|(\\.))*\')' % (WORD,
    DQUOTE, SQUOTE))

def tokenize(string, limit=None):
    tokens = []

    while string:
        m = RE_SKIP.match(string)
        if m is not None:
            string = string[m.end():]

        if not string:
            break

        if limit is not None and len(tokens) == limit:
            tokens.append(string)
            break

        m = RE_TOKEN.match(string)

        if m is None:
            return None

        tok = string[:m.end()]
        if tok.startswith('"') or tok.startswith('\''):
            tok = tok[1:-1]
        tokens.append(tok)
        string = string[m.end():]

    return tokens


def enumerate(seq):
    return [(i,seq[i]) for i in range(0, len(seq))]


def split_path(fileName):
    name = os.path.basename(fileName)
    path = os.path.dirname(os.path.abspath(fileName))
    user = os.path.expanduser('~')
    if user != '~':
        path = path.replace(user, '~')
    return path, name


def cleanup_path(fileName):
    return os.path.join(*split_path(fileName))


def get_frame_title(inputFile):
    if inputFile is sys.stdin:
        return 'stdin - PlotIt'
    else:
        path, name = split_path(inputFile.name)
        return (name + ' (' + path + ') - PlotIt')


#
# Command-Line Interface
#

def fatalError(msg):
    sys.stderr.write('Error: ')
    sys.stderr.write(str(msg))
    sys.stderr.write('\n')
    sys.exit(1)


def fatalIOError(err):
    if isinstance(err, IOError) and err.strerror and err.filename:
        err = '%s: %s' % (err.strerror, err.filename)
    fatalError(err)


def ParseArguments(args):
    from optparse import OptionParser

    USAGE = '''\
%prog [-w] FILE: execute the commands read from FILE (use `-' for stdin)
       %prog [-lp] -q FILE [FILE...]:  plot the 1st and 2nd columns of files
       %prog [-lp] Y FILE [FILE...]:   plot the Y expressions for files
       %prog [-lp] X Y FILE [FILE...]: plot the X and Y expressions for files

`%prog' is a simple plotting program which can draw line plots and stripcharts
using a subset of GNUPLOT's command language.  You can also do quick plots of
multiple data files from the command-line.'''
    VERSION = '%prog ' + __version__ + ', by Ken McIvor <mcivor@iit.edu>'
    parser = OptionParser(usage=USAGE, version=VERSION)

    #
    # Command-line options
    #
    parser.add_option('-w',
        action='store_const',
        dest='watch',
        const=True,
        default=False,
        help=('watch the input file for commands to stripchart, or wait to '
            + ' read all of of stdin before plotting'))

    parser.add_option('-q',
        action='store_const',
        dest='quick',
        const=True,
        default=False,
        help='plot the first and second columns of multiple files')

    parser.add_option('-l',
        action='store_const',
        dest='lines',
        const=True,
        default=False,
        help='plot X and Y with lines')

    parser.add_option('-p',
        action='store_const',
        dest='points',
        const=True,
        default=False,
        help='plot X and Y with points')

    opts, args = parser.parse_args(args)

    if (not len(args)
    or (len(args) == 2
    and is_plot_expression(args[0])
    and is_plot_expression(args[1]))):
        parser.print_usage()
        sys.exit(1)

    return opts, args


#
# Application entry-point
#

def main(options, arguments):
    app = PlotItApp(options, arguments, redirect=0)
    app.MainLoop()
    app.cleanup()


#
# Magic incantation to call main() when run as a script
#

if __name__ == '__main__':
    try:
        options, arguments = ParseArguments(sys.argv[1:])
        main(options, arguments)
    except KeyboardInterrupt:
        pass