File indexing completed on 2024-05-19 04:32:49

0001 #!/usr/bin/python2.7
0002 import pykst as kst
0003 import numpy as _np
0004 
0005 _current_plot = None
0006 _client = None
0007 _subplots = {}
0008 
0009 class _CurveInfo:
0010     def __init__(self):
0011         self.reset()
0012         self.line_width = 1
0013         self.line_style = ""
0014         self.color = "auto"
0015         self.marker_size=0
0016         self.label = None
0017 
0018 
0019     def reset(self):
0020         self.x = None
0021         self.y = None
0022         self.f = None
0023 
0024 def _add_curve_to_plot(P, C):
0025     global _client
0026 
0027     colors = {'b': "blue",   'r':"red",    'g':"green", 'c':"cyan",
0028               'm':"magenta", 'y':"yellow", 'k':"black", 'w':"white"}
0029     points = {'.':(3,3),  ',':(13,12), 'v':(9,10),  '^':(10,10), 's':(6,7),
0030               '*':(8,9), '+':(7,10),  'D':(12,10), 'x':(0,9), 'o':(3,10)}
0031 
0032     V1 = _client.new_editable_vector(C.x, name="X")
0033     V2 = _client.new_editable_vector(C.y, name="Y")
0034     c1 = _client.new_curve(V1, V2)
0035 
0036     if isinstance(C.f, basestring):
0037         if '--' in C.f:
0038             c1.set_line_style(1)
0039         elif '-.' in C.f:
0040             c1.set_line_style(3)
0041         elif ':' in C.f:
0042             c1.set_line_style(2)
0043 
0044         for color_key in colors.keys():
0045             if color_key in C.f:
0046                 c1.set_color(colors[color_key])
0047 
0048         for point_key in points.keys():
0049             if point_key in C.f:
0050                 c1.set_has_lines(False)
0051                 c1.set_has_points(True)
0052                 c1.set_point_type(points[point_key][0])
0053                 c1.set_point_size(points[point_key][1])
0054 
0055     c1.set_line_width(C.line_width)
0056     if C.color != "auto":
0057         c1.set_color(C.color)
0058 
0059     if (C.line_style == "-"):
0060         c1.set_line_style(0)
0061     elif (C.line_style == "--"):
0062         c1.set_line_style(1)
0063     elif (C.line_style == ":"):
0064         c1.set_line_style(2)
0065     elif (C.line_style == "-."):
0066         c1.set_line_style(3)
0067 
0068     if (C.marker_size > 0):
0069         c1.set_point_size(C.marker_size)
0070 
0071     if (C.label is not None):
0072         c1.set_name(C.label)
0073 
0074     P.add(c1)
0075 
0076 def semilogx(*args, **kwargs):
0077     """
0078     Add a curve to the current axis (or make a new one)
0079     with log scaling on the X axis.  All parameters are the same as :func:`plot()`.
0080     """
0081     plot(*args, **kwargs)
0082     _current_plot.set_log_x()
0083 
0084 def semilogy(*args, **kwargs):
0085     """
0086     Add a curve to the current axis (or make a new one)
0087     with log scaling on the Y axis.  All parameters are the same as :func:`plot()`.
0088     """
0089     plot(*args, **kwargs)
0090     _current_plot.set_log_y()
0091 
0092 def loglog(*args, **kwargs):
0093     """
0094     Add a curve to the current axis (or make a new one)
0095     with log-log scaling.  All parameters are the same as :func:`plot()`.
0096     """
0097     plot(*args, **kwargs)
0098     _current_plot.set_log_y()
0099     _current_plot.set_log_x()
0100 
0101 def xlabel(s):
0102     """
0103     Set the *x* axis label of the current axis.
0104     """
0105     _current_plot.set_bottom_label(s)
0106 
0107 def ylabel(s):
0108     """
0109     Set the *y* axis label of the current axis.
0110     """
0111     _current_plot.set_left_label(s)
0112 
0113 def title(s):
0114     """
0115     Set the *top* axis label of the current axis.
0116     """
0117     _current_plot.set_top_label(s)
0118 
0119 def show():
0120     """
0121     This method does nothing, but exists for compatibility
0122     with matplotlib scripts.
0123     """
0124     pass
0125 
0126 def savefig(fname, **kwargs):
0127     """
0128     Export the kst session as a series of graphics files.  If there is
0129     only 1 tab, then the file will be called *fname*.  If there are multiple
0130     tabs, the files will be called, for example, fname_1.png, fname_2.png, etc.
0131 
0132     The plot will be have the same aspect ratio as the kst session, and, for
0133     pixel based formats, will be 1280 pixels wide.
0134 
0135     The format is determined by the *format* kwarg, or by the *fname* extension
0136     if *format* is not defined.
0137 
0138     All formats supported by kst are supported, including, among many others, png,
0139     jpg, eps, svg, and pdf.
0140     """
0141     if "format" in kwargs:
0142         format = kwargs["format"]
0143     else:
0144         format = None
0145 
0146     _client.export_graphics_file(fname, format, 1280, 1024, 0)
0147 
0148 def figure():
0149     """
0150     Creates a new tab in kst.
0151     """
0152 
0153     global _client
0154     global _current_plot
0155     global _subplots
0156 
0157     if _client is None:
0158         _client=kst.Client()
0159 
0160     _client.new_tab()
0161     _current_plot = None
0162     _subplots = {}
0163 
0164 
0165 def plot(*args, **kwargs):
0166     """
0167     Plot lines and/or markers to a kst window.  *args* is a variable length
0168     argument, allowing for multiple *x*, *y* pairs with an
0169     optional format string.  For example, each of the following is
0170     legal::
0171 
0172         plot(x, y)        # plot x and y using default line style and color
0173         plot(x, y, 'bo')  # plot x and y using blue circle markers
0174         plot(y)           # plot y using x as index array 0..N-1
0175         plot(y, 'r+')     # ditto, but with red plusses
0176 
0177     An arbitrary number of *x*, *y*, *fmt* groups can be
0178     specified, as in::
0179 
0180         a.plot(x1, y1, 'g^', x2, y2, 'g-')
0181 
0182     By default, each line is assigned a different color in kst.
0183 
0184     The following format string characters are accepted to control
0185     the line style or marker:
0186 
0187         ================    ===============================
0188         character           description
0189         ================    ===============================
0190         ``'-'``             solid line style
0191         ``'--'``            dashed line style
0192         ``'-.'``            dash-dot line style
0193         ``':'``             dotted line style
0194         ``'.'``             point marker
0195         ``','``             pixel marker
0196         ``'o'``             circle marker
0197         ``'v'``             triangle_down marker
0198         ``'^'``             triangle_up marker
0199         ``'s'``             square marker
0200         ``'*'``             star marker
0201         ``'+'``             plus marker
0202         ``'x'``             x marker
0203         ``'D'``             diamond marker
0204         ================    ===============================
0205 
0206 
0207     The following color abbreviations are supported:
0208 
0209         ==========  ========
0210         character   color
0211         ==========  ========
0212         'b'         blue
0213         'g'         green
0214         'r'         red
0215         'c'         cyan
0216         'm'         magenta
0217         'y'         yellow
0218         'k'         black
0219         'w'         white
0220         ==========  ========
0221 
0222     Line styles and colors are combined in a single format string, as in
0223     ``'bo'`` for blue circles.
0224 
0225     The *kwargs* can be used to set the color, the line width, the line type,
0226     and the legend label.  You can specify colors using full names (``'green'``),
0227     or hex strings (``'#008000'``).
0228 
0229     Some examples::
0230 
0231         plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2)
0232         plot([1,2,3], [1,4,9], 'rs',  label='line 2')
0233         axis([0, 4, 0, 10])
0234         legend()
0235 
0236     If you make multiple lines with one plot command, the kwargs
0237     apply to all those lines, e.g.::
0238 
0239         plot(x1, y1, x2, y2, linewidth=2)
0240 
0241     Both lines will have a width of 2.
0242 
0243     You do not need to use format strings, which are just
0244     abbreviations.  All of the line properties can be controlled
0245     by keyword arguments.  For example, you can set the color,
0246     marker, linestyle, and markercolor with::
0247 
0248         plot(x, y, color='green', linestyle='dashed', marker='o',
0249         color='blue', markersize=12).
0250 
0251     Supported kwargs are::
0252 
0253         color
0254         label
0255         linestyle
0256         linewidth
0257         markersize
0258 
0259     """
0260     global _current_plot
0261     global _client
0262 
0263     if _client is None:
0264         _client=kst.Client()
0265 
0266     if _current_plot is None:
0267       _current_plot = _client.new_plot()
0268 
0269 
0270     C = _CurveInfo()
0271 
0272     if "linewidth" in kwargs:
0273         C.line_width = kwargs["linewidth"]
0274     if "color" in kwargs:
0275         C.color = kwargs["color"]
0276     if "linestyle" in kwargs:
0277         C.line_style = kwargs["linestyle"]
0278     if "markersize" in kwargs:
0279         C.marker_size = kwargs["markersize"]
0280     if "label" in kwargs:
0281         C.label = kwargs["label"]
0282 
0283     for arg in args:
0284         if isinstance(arg, basestring):
0285             C.f = arg
0286             if (C.y is None) & (isinstance(C.x, _np.ndarray)):
0287                 C.y = C.x
0288                 C.x = _np.linspace(0, C.y.size-1, C.y.size)
0289             if (isinstance(C.x, _np.ndarray)):
0290                 _add_curve_to_plot(_current_plot, C)
0291             C.reset()
0292         else:
0293             if (isinstance(C.y, _np.ndarray)):
0294                 _add_curve_to_plot(_current_plot, C)
0295                 C.reset()
0296             if isinstance(C.x, _np.ndarray):
0297                 C.y = _np.asanyarray(arg, dtype=_np.float64)
0298             else:
0299                 C.x = _np.asanyarray(arg, dtype=_np.float64)
0300 
0301     if (C.y is None) & (isinstance(C.x, _np.ndarray)):
0302         C.y = C.x
0303         C.x = _np.asanyarray([0.0, C.y.size-1.0], dtype=_np.float64)
0304     if (isinstance(C.x, _np.ndarray)):
0305         _add_curve_to_plot(_current_plot, C)
0306 
0307 def subplot(*args, **kwargs):
0308     """
0309     Return a subplot axes positioned by the given grid definition.
0310 
0311     Typical call signature::
0312 
0313       subplot(nrows, ncols, plot_number)
0314 
0315     Where *nrows* and *ncols* are used to notionally split the figure
0316     into ``nrows * ncols`` sub-axes, and *plot_number* is used to identify
0317     the particular subplot that this function is to create within the notional
0318     grid. *plot_number* starts at 1, increments across rows first and has a
0319     maximum of ``nrows * ncols``.
0320 
0321     In the case when *nrows*, *ncols* and *plot_number* are all less than 10,
0322     a convenience exists, such that the a 3 digit number can be given instead,
0323     where the hundreds represent *nrows*, the tens represent *ncols* and the
0324     units represent *plot_number*. For instance::
0325 
0326       subplot(211)
0327 
0328     produces a subaxes in a figure which represents the top plot (i.e. the
0329     first) in a 2 row by 1 column notional grid (no grid actually exists,
0330     but conceptually this is how the returned subplot has been positioned).
0331 
0332     .. note::
0333 
0334        unlike *matplotlib.pyplot.subplot()*, creating a new subplot with a position
0335        which is entirely inside a pre-existing axes will not delete the previous
0336        plot.
0337 
0338     Keyword arguments:
0339 
0340       *axisbg*:
0341         The background color of the subplot, which can be any valid
0342         color specifier.
0343 
0344 
0345     """
0346 
0347     global _current_plot
0348     global _client
0349     global _subplots
0350 
0351     w = 0
0352     h = 0
0353     x = 0
0354     y = 0
0355     n = 0
0356 
0357     if (len(args) == 1):
0358         h = args[0]/100
0359         w = (args[0]%100)/10
0360         n = args[0]%10
0361     elif (len(args) == 3):
0362         h = args[0]
0363         w = args[1]
0364         n = args[2]
0365     else:
0366         w = h = n = 1
0367 
0368     x = (n-1)%w
0369     y = (n-1)/w
0370 
0371     serial = y + x*100 + h*10000 + w*1000000
0372 
0373     #print args[0], w,h,x,y, serial
0374 
0375     size = (1.0/w, 1.0/h)
0376     pos = (x/float(w)+0.5/w,y/float(h)+0.5/h)
0377     #print pos, size
0378 
0379     if serial in _subplots:
0380         _current_plot = _subplots[serial]
0381     else:
0382         if _client is None:
0383             _client=kst.Client()
0384 
0385         _current_plot = _client.new_plot(pos, size)
0386         _subplots[serial] = _current_plot
0387 
0388     if "axisbg" in kwargs:
0389         _current_plot.set_fill_color(kwargs["axisbg"])
0390 
0391