DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>drawDC = wx.PaintDC(self)<EOL>if not self._isDrawn:<EOL><INDENT>self.draw(drawDC=drawDC)<EOL><DEDENT>else:<EOL><INDENT>self.gui_repaint(drawDC=drawDC)<EOL><DEDENT>evt.Skip()<EOL>


pass<EOL>

Called when window is redrawn; since we are blitting the entire
image, we can leave this blank to suppress flicker.


DEBUG_MSG("<STR_LIT>", <NUM_LIT:2>, self)<EOL>self._width, self._height = self.GetClientSize()<EOL>self.bitmap =wx.EmptyBitmap(self._width, self._height)<EOL>self._isDrawn = False<EOL>if self._width <= <NUM_LIT:1> or self._height <= <NUM_LIT:1>: return <EOL>dpival = self.figure.dpi<EOL>winch = self._width/dpival<EOL>hinch = self._height/dpival<EOL>self.figure.set_size_inches(winch, hinch)<EOL>self.Refresh(eraseBackground=False)<EOL>

Called when wxEventSize is generated.

In this application we attempt to resize to fit the window, so it
is better to take the performance hit and redraw the whole window.


evt.Skip()<EOL>FigureCanvasBase.idle_event(self, guiEvent=evt)<EOL>


key = self._get_key(evt)<EOL>evt.Skip()<EOL>FigureCanvasBase.key_press_event(self, key, guiEvent=evt)<EOL>


key = self._get_key(evt)<EOL>evt.Skip()<EOL>FigureCanvasBase.key_release_event(self, key, guiEvent=evt)<EOL>


x = evt.GetX()<EOL>y = self.figure.bbox.height - evt.GetY()<EOL>evt.Skip()<EOL>self.CaptureMouse()<EOL>FigureCanvasBase.button_press_event(self, x, y, <NUM_LIT:3>, guiEvent=evt)<EOL>


x = evt.GetX()<EOL>y = self.figure.bbox.height - evt.GetY()<EOL>evt.Skip()<EOL>if self.HasCapture(): self.ReleaseMouse()<EOL>FigureCanvasBase.button_release_event(self, x, y, <NUM_LIT:3>, guiEvent=evt)<EOL>


x = evt.GetX()<EOL>y = self.figure.bbox.height - evt.GetY()<EOL>evt.Skip()<EOL>self.CaptureMouse()<EOL>FigureCanvasBase.button_press_event(self, x, y, <NUM_LIT:1>, guiEvent=evt)<EOL>


x = evt.GetX()<EOL>y = self.figure.bbox.height - evt.GetY()<EOL>evt.Skip()<EOL>if self.HasCapture(): self.ReleaseMouse()<EOL>FigureCanvasBase.button_release_event(self, x, y, <NUM_LIT:1>, guiEvent=evt)<EOL>


<EOL>x = evt.GetX()<EOL>y = self.figure.bbox.height - evt.GetY()<EOL>delta = evt.GetWheelDelta()<EOL>rotation = evt.GetWheelRotation()<EOL>rate = evt.GetLinesPerAction()<EOL>step = rate*float(rotation)/delta<EOL>evt.Skip()<EOL>if wx.Platform == '<STR_LIT>':<EOL><INDENT>if not hasattr(self,'<STR_LIT>'):<EOL><INDENT>self._skipwheelevent = True<EOL><DEDENT>elif self._skipwheelevent:<EOL><INDENT>self._skipwheelevent = False<EOL>return  <EOL><DEDENT>else:<EOL><INDENT>self._skipwheelevent = True<EOL><DEDENT><DEDENT>FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=evt)<EOL>

Translate mouse wheel events into matplotlib events


x = evt.GetX()<EOL>y = self.figure.bbox.height - evt.GetY()<EOL>evt.Skip()<EOL>FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=evt)<EOL>


evt.Skip()<EOL>FigureCanvasBase.leave_notify_event(self, guiEvent = evt)<EOL>


FigureCanvasBase.enter_notify_event(self, guiEvent = evt)<EOL>


return self.toolbar<EOL>

Override wxFrame::GetToolBar as we don't have managed toolbar


self.canvas.SetInitialSize(wx.Size(width, height))<EOL>self.window.GetSizer().Fit(self.window)<EOL>


x, y = self.GetPositionTuple()<EOL>w, h = self.GetSizeTuple()<EOL>self.PopupMenuXY(self._menu, x, y+h-<NUM_LIT:4>)<EOL>evt.Skip()<EOL>


if len(self._axisId) == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>for i in range(len(self._axisId)):<EOL><INDENT>self._menu.Check(self._axisId[i], True)<EOL><DEDENT>self._toolbar.set_active(self.getActiveAxes())<EOL>evt.Skip()<EOL>

Called when the 'select all axes' menu item is selected.


if len(self._axisId) == <NUM_LIT:0>: return<EOL>for i in range(len(self._axisId)):<EOL><INDENT>if self._menu.IsChecked(self._axisId[i]):<EOL><INDENT>self._menu.Check(self._axisId[i], False)<EOL><DEDENT>else:<EOL><INDENT>self._menu.Check(self._axisId[i], True)<EOL><DEDENT><DEDENT>self._toolbar.set_active(self.getActiveAxes())<EOL>evt.Skip()<EOL>

Called when the invert all menu item is selected


current = self._menu.IsChecked(evt.GetId())<EOL>if current:<EOL><INDENT>new = False<EOL><DEDENT>else:<EOL><INDENT>new = True<EOL><DEDENT>self._menu.Check(evt.GetId(), new)<EOL>self._toolbar.set_active(self.getActiveAxes())<EOL>evt.Skip()<EOL>

Called whenever one of the specific axis menu items is selected


if maxAxis > len(self._axisId):<EOL><INDENT>for i in range(len(self._axisId) + <NUM_LIT:1>, maxAxis + <NUM_LIT:1>, <NUM_LIT:1>):<EOL><INDENT>menuId =wx.NewId()<EOL>self._axisId.append(menuId)<EOL>self._menu.Append(menuId, "<STR_LIT>" % i, "<STR_LIT>" % i, True)<EOL>self._menu.Check(menuId, True)<EOL>bind(self, wx.EVT_MENU, self._onMenuItemSelected, id=menuId)<EOL><DEDENT><DEDENT>self._toolbar.set_active(list(range(len(self._axisId))))<EOL>

Ensures that there are entries for max_axis axes in the menu
        (selected by default).


active = []<EOL>for i in range(len(self._axisId)):<EOL><INDENT>if self._menu.IsChecked(self._axisId[i]):<EOL><INDENT>active.append(i)<EOL><DEDENT><DEDENT>return active<EOL>


axis_txt = '<STR_LIT>'<EOL>for e in lst:<EOL><INDENT>axis_txt += '<STR_LIT>' % (e+<NUM_LIT:1>)<EOL><DEDENT>self.SetLabel("<STR_LIT>" % axis_txt[:-<NUM_LIT:1>])<EOL>

Update the list of selected axes in the menu button


def draw_rubberband(self, event, x0, y0, x1, y1):

canvas = self.canvas<EOL>dc =wx.ClientDC(canvas)<EOL>dc.SetLogicalFunction(wx.XOR)<EOL>wbrush =wx.Brush(wx.Colour(<NUM_LIT:255>,<NUM_LIT:255>,<NUM_LIT:255>), wx.TRANSPARENT)<EOL>wpen =wx.Pen(wx.Colour(<NUM_LIT:200>, <NUM_LIT:200>, <NUM_LIT:200>), <NUM_LIT:1>, wx.SOLID)<EOL>dc.SetBrush(wbrush)<EOL>dc.SetPen(wpen)<EOL>dc.ResetBoundingBox()<EOL>dc.BeginDrawing()<EOL>height = self.canvas.figure.bbox.height<EOL>y1 = height - y1<EOL>y0 = height - y0<EOL>if y1<y0: y0, y1 = y1, y0<EOL>if x1<y0: x0, x1 = x1, x0<EOL>w = x1 - x0<EOL>h = y1 - y0<EOL>rect = int(x0), int(y0), int(w), int(h)<EOL>try: lastrect = self.lastrect<EOL>except AttributeError: pass<EOL>else: dc.DrawRectangle(*lastrect)  <EOL>self.lastrect = rect<EOL>dc.DrawRectangle(*rect)<EOL>dc.EndDrawing()<EOL>


def __init__(self, canvas, can_kill=False):

wx.ToolBar.__init__(self, canvas.GetParent(), -<NUM_LIT:1>)<EOL>DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self.canvas = canvas<EOL>self._lastControl = None<EOL>self._mouseOnButton = None<EOL>self._parent = canvas.GetParent()<EOL>self._NTB_BUTTON_HANDLER = {<EOL>_NTB_X_PAN_LEFT  : self.panx,<EOL>_NTB_X_PAN_RIGHT : self.panx,<EOL>_NTB_X_ZOOMIN    : self.zoomx,<EOL>_NTB_X_ZOOMOUT   : self.zoomy,<EOL>_NTB_Y_PAN_UP    : self.pany,<EOL>_NTB_Y_PAN_DOWN  : self.pany,<EOL>_NTB_Y_ZOOMIN    : self.zoomy,<EOL>_NTB_Y_ZOOMOUT   : self.zoomy }<EOL>self._create_menu()<EOL>self._create_controls(can_kill)<EOL>self.Realize()<EOL>

figure is the Figure instance that the toolboar controls

win, if not None, is the wxWindow the Figure is embedded in


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self._menu = MenuButtonWx(self)<EOL>self.AddControl(self._menu)<EOL>self.AddSeparator()<EOL>

Creates the 'menu' - implemented as a button which opens a
pop-up menu since wxPython does not allow a menu as a control


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self.SetToolBitmapSize(wx.Size(<NUM_LIT:16>,<NUM_LIT:16>))<EOL>self.AddSimpleTool(_NTB_X_PAN_LEFT, _load_bitmap('<STR_LIT>'),<EOL>'<STR_LIT>', '<STR_LIT>')<EOL>self.AddSimpleTool(_NTB_X_PAN_RIGHT, _load_bitmap('<STR_LIT>'),<EOL>'<STR_LIT>', '<STR_LIT>')<EOL>self.AddSimpleTool(_NTB_X_ZOOMIN, _load_bitmap('<STR_LIT>'),<EOL>'<STR_LIT>', '<STR_LIT>')<EOL>self.AddSimpleTool(_NTB_X_ZOOMOUT, _load_bitmap('<STR_LIT>'),<EOL>'<STR_LIT>', '<STR_LIT>')<EOL>self.AddSeparator()<EOL>self.AddSimpleTool(_NTB_Y_PAN_UP,_load_bitmap('<STR_LIT>'),<EOL>'<STR_LIT>', '<STR_LIT>')<EOL>self.AddSimpleTool(_NTB_Y_PAN_DOWN, _load_bitmap('<STR_LIT>'),<EOL>'<STR_LIT>', '<STR_LIT>')<EOL>self.AddSimpleTool(_NTB_Y_ZOOMIN, _load_bitmap('<STR_LIT>'),<EOL>'<STR_LIT>', '<STR_LIT>')<EOL>self.AddSimpleTool(_NTB_Y_ZOOMOUT, _load_bitmap('<STR_LIT>'),<EOL>'<STR_LIT>', '<STR_LIT>')<EOL>self.AddSeparator()<EOL>self.AddSimpleTool(_NTB_SAVE, _load_bitmap('<STR_LIT>'),<EOL>'<STR_LIT>', '<STR_LIT>')<EOL>self.AddSeparator()<EOL>bind(self, wx.EVT_TOOL, self._onLeftScroll, id=_NTB_X_PAN_LEFT)<EOL>bind(self, wx.EVT_TOOL, self._onRightScroll, id=_NTB_X_PAN_RIGHT)<EOL>bind(self, wx.EVT_TOOL, self._onXZoomIn, id=_NTB_X_ZOOMIN)<EOL>bind(self, wx.EVT_TOOL, self._onXZoomOut, id=_NTB_X_ZOOMOUT)<EOL>bind(self, wx.EVT_TOOL, self._onUpScroll, id=_NTB_Y_PAN_UP)<EOL>bind(self, wx.EVT_TOOL, self._onDownScroll, id=_NTB_Y_PAN_DOWN)<EOL>bind(self, wx.EVT_TOOL, self._onYZoomIn, id=_NTB_Y_ZOOMIN)<EOL>bind(self, wx.EVT_TOOL, self._onYZoomOut, id=_NTB_Y_ZOOMOUT)<EOL>bind(self, wx.EVT_TOOL, self._onSave, id=_NTB_SAVE)<EOL>bind(self, wx.EVT_TOOL_ENTER, self._onEnterTool, id=self.GetId())<EOL>if can_kill:<EOL><INDENT>bind(self, wx.EVT_TOOL, self._onClose, id=_NTB_CLOSE)<EOL><DEDENT>bind(self, wx.EVT_MOUSEWHEEL, self._onMouseWheel)<EOL>

Creates the button controls, and links them to event handlers


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self._ind = ind<EOL>if ind != None:<EOL><INDENT>self._active = [ self._axes[i] for i in self._ind ]<EOL><DEDENT>else:<EOL><INDENT>self._active = []<EOL><DEDENT>self._menu.updateButtonText(ind)<EOL>

ind is a list of index numbers for the axes which are to be made active


return self._lastControl<EOL>

Returns the identity of the last toolbar button pressed.


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self._axes = self.canvas.figure.get_axes()<EOL>self._menu.updateAxes(len(self._axes))<EOL>

Update the toolbar menu - called when (e.g.) a new subplot or axes are added


pass<EOL>

A NULL event handler - does nothing whatsoever


if matplotlib.is_interactive():<EOL><INDENT>figManager =  Gcf.get_active()<EOL>if figManager != None:<EOL><INDENT>figManager.canvas.draw()<EOL><DEDENT><DEDENT>

Is called after every pylab drawing command


if QtGui.QApplication.startingUp():<EOL><INDENT>if DEBUG: print("<STR_LIT>")<EOL>global qApp<EOL>qApp = QtGui.QApplication( ["<STR_LIT:U+0020>"] )<EOL>QtCore.QObject.connect( qApp, QtCore.SIGNAL( "<STR_LIT>" ),<EOL>qApp, QtCore.SLOT( "<STR_LIT>" ) )<EOL>_create_qApp.qAppCreatedHere = True<EOL><DEDENT>

Only one qApp can exist at a time, so check before creating one.


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>manager.window.show()<EOL><DEDENT>if DEBUG: print('<STR_LIT>')<EOL>figManager =  Gcf.get_active()<EOL>if figManager != None:<EOL><INDENT>figManager.canvas.draw()<EOL><DEDENT>if _create_qApp.qAppCreatedHere:<EOL><INDENT>QtGui.qApp.exec_()<EOL><DEDENT>

Show all the figures and enter the qt main loop
This should be the last line of your script


def new_figure_manager( num, *args, **kwargs ):

thisFig = Figure( *args, **kwargs )<EOL>canvas = FigureCanvasQT( thisFig )<EOL>manager = FigureManagerQT( canvas, num )<EOL>return manager<EOL>


def exception_handler( type, value, tb ):

msg = '<STR_LIT>'<EOL>if hasattr(value, '<STR_LIT:filename>') and value.filename != None:<EOL><INDENT>msg = value.filename + '<STR_LIT>'<EOL><DEDENT>if hasattr(value, '<STR_LIT>') and value.strerror != None:<EOL><INDENT>msg += value.strerror<EOL><DEDENT>else:<EOL><INDENT>msg += str(value)<EOL><DEDENT>if len( msg ) : error_msg_qt( msg )<EOL>

Handle uncaught exceptions
    It does not catch SystemExit


self.window.resize(width, height)<EOL>


def __init__(self, canvas, parent, coordinates=True):

self.canvas = canvas<EOL>self.coordinates = coordinates<EOL>QtGui.QToolBar.__init__( self, parent )<EOL>NavigationToolbar2.__init__( self, canvas )<EOL>

coordinates: should we show the coordinates on the right?


pass<EOL>

For image backends - is not required
For GUI backends - this should be overriden if drawing should be done in
interactive python mode


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>pass<EOL><DEDENT>

For image backends - is not required
For GUI backends - show() is usually the last line of a pylab script and
tells the backend that it is time to draw.  In interactive mode, this may
be a do nothing func.  See the GTK backend for an example of how to handle
interactive versus batch mode


def new_figure_manager(num, *args, **kwargs):

<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas = FigureCanvasEMF(thisFig)<EOL>manager = FigureManagerEMF(canvas, num)<EOL>return manager<EOL>


def __init__(self, outfile, width, height, dpi):

self.outfile = outfile<EOL>self._cached = {}<EOL>self._fontHandle = {}<EOL>self.lastHandle = {'<STR_LIT>':-<NUM_LIT:1>, '<STR_LIT>':-<NUM_LIT:1>, '<STR_LIT>':-<NUM_LIT:1>}<EOL>self.emf=pyemf.EMF(width,height,dpi,'<STR_LIT>')<EOL>self.width=int(width*dpi)<EOL>self.height=int(height*dpi)<EOL>self.dpi = dpi<EOL>self.pointstodpi = dpi/<NUM_LIT><EOL>self.hackPointsForMathExponent = <NUM_LIT><EOL>self.emf.SetBkMode(pyemf.TRANSPARENT)<EOL>self.emf.SetTextAlign( pyemf.TA_BOTTOM|pyemf.TA_LEFT)<EOL>if debugPrint: print("<STR_LIT>" % (self.width,self.height,outfile,dpi))<EOL>

Initialize the renderer with a gd image instance


def draw_arc(self, gcEdge, rgbFace, x, y, width, height, angle1, angle2, rotation):

Draw an arc using GraphicsContext instance gcEdge, centered at x,y,
with width and height and angles from 0.0 to 360.0
0 degrees is at 3-o'clock
positive angles are anti-clockwise

If the color rgbFace is not None, fill the arc with it.


<EOL>pass<EOL>

Draw the Image instance into the current axes; x is the
distance in pixels from the left hand side of the canvas. y is
the distance from the origin.  That is, if origin is upper, y
is the distance from top.  If origin is lower, y is the
distance from bottom

bbox is a matplotlib.transforms.BBox instance for clipping, or
None


def draw_line(self, gc, x1, y1, x2, y2):

if debugPrint: print("<STR_LIT>" % (x1,y1,x2,y2))<EOL>if self.select_pen(gc):<EOL><INDENT>self.emf.Polyline([(int(x1),int(self.height-y1)),(int(x2),int(self.height-y2))])<EOL><DEDENT>else:<EOL><INDENT>if debugPrint: print("<STR_LIT>" % (x1,y1,x2,y2))<EOL><DEDENT>


if debugPrint: print("<STR_LIT>" % len(str(x)))<EOL>if self.select_pen(gc):<EOL><INDENT>points = [(int(x[i]), int(self.height-y[i])) for i in range(len(x))]<EOL>self.emf.Polyline(points)<EOL><DEDENT>

x and y are equal length arrays, draw lines connecting each
point in x, y


if debugPrint: print("<STR_LIT>" % (x,y))<EOL>pen=EMFPen(self.emf,gc)<EOL>self.emf.SetPixel(int(x),int(self.height-y),(pen.r,pen.g,pen.b))<EOL>

Draw a single point at x,y
Where 'point' is a device-unit point (or pixel), not a matplotlib point


def draw_polygon(self, gcEdge, rgbFace, points):

if debugPrint: print("<STR_LIT>" % len(points))<EOL>pen=self.select_pen(gcEdge)<EOL>brush=self.select_brush(rgbFace)<EOL>if pen or brush:<EOL><INDENT>points = [(int(x), int(self.height-y)) for x,y in points]<EOL>self.emf.Polygon(points)<EOL><DEDENT>else:<EOL><INDENT>points = [(int(x), int(self.height-y)) for x,y in points]<EOL>if debugPrint: print("<STR_LIT>" % (len(points),str(points)))<EOL><DEDENT>

Draw a polygon using the GraphicsContext instance gc.
points is a len vertices tuple, each element
giving the x,y coords a vertex

If the color rgbFace is not None, fill the polygon with it


def draw_rectangle(self, gcEdge, rgbFace, x, y, width, height):

if debugPrint: print("<STR_LIT>" % (x,y,width,height))<EOL>pen=self.select_pen(gcEdge)<EOL>brush=self.select_brush(rgbFace)<EOL>if pen or brush:<EOL><INDENT>self.emf.Rectangle(int(x),int(self.height-y),int(x)+int(width),int(self.height-y)-int(height))<EOL><DEDENT>else:<EOL><INDENT>if debugPrint: print("<STR_LIT>" % (x,y,width,height))<EOL><DEDENT>

Draw a non-filled rectangle using the GraphicsContext instance gcEdge,
with lower left at x,y with width and height.

If rgbFace is not None, fill the rectangle with it.


def draw_text(self, gc, x, y, s, prop, angle, ismath=False):

if debugText: print("<STR_LIT>" % (x,y,angle,s))<EOL>if ismath:<EOL><INDENT>self.draw_math_text(gc,x,y,s,prop,angle)<EOL><DEDENT>else:<EOL><INDENT>self.draw_plain_text(gc,x,y,s,prop,angle)<EOL><DEDENT>

Draw the text.Text instance s at x,y (display coords) with font
properties instance prop at angle in degrees, using GraphicsContext gc

**backend implementers note**

When you are trying to determine if you have gotten your bounding box
right (which is what enables the text layout/alignment to work
properly), it helps to change the line in text.py

          if 0: bbox_artist(self, renderer)

to if 1, and then the actual bounding box will be blotted along with
your text.


def draw_plain_text(self, gc, x, y, s, prop, angle):

Draw a text string verbatim; no conversion is done.


def draw_math_text(self, gc, x, y, s, prop, angle):

if debugText: print("<STR_LIT>" % (x,y,angle,s))<EOL>s = s[<NUM_LIT:1>:-<NUM_LIT:1>]  <EOL>match=re.match("<STR_LIT>",s)<EOL>if match:<EOL><INDENT>exp=match.group(<NUM_LIT:1>)<EOL>if debugText: print("<STR_LIT>" % exp)<EOL>font = self._get_font_ttf(prop)<EOL>font.set_text("<STR_LIT>", <NUM_LIT:0.0>)<EOL>w, h = font.get_width_height()<EOL>w /= <NUM_LIT>  <EOL>h /= <NUM_LIT><EOL>self.draw_plain_text(gc,x,y,"<STR_LIT>",prop,angle)<EOL>propexp=prop.copy()<EOL>propexp.set_size(prop.get_size_in_points()*<NUM_LIT>)<EOL>self.draw_plain_text(gc,x+w+self.points_to_pixels(self.hackPointsForMathExponent),y-(h/<NUM_LIT:2>),exp,propexp,angle)<EOL><DEDENT>else:<EOL><INDENT>self.draw_plain_text(gc,x,y,s,prop,angle)<EOL><DEDENT>

Draw a subset of TeX, currently handles exponents only.  Since
pyemf doesn't have any raster functionality yet, the
texmanager.get_rgba won't help.


def get_math_text_width_height(self, s, prop):

if debugText: print("<STR_LIT>")<EOL>s = s[<NUM_LIT:1>:-<NUM_LIT:1>]  <EOL>match=re.match("<STR_LIT>",s)<EOL>if match:<EOL><INDENT>exp=match.group(<NUM_LIT:1>)<EOL>if debugText: print("<STR_LIT>" % exp)<EOL>font = self._get_font_ttf(prop)<EOL>font.set_text("<STR_LIT>", <NUM_LIT:0.0>)<EOL>w1, h1 = font.get_width_height()<EOL>propexp=prop.copy()<EOL>propexp.set_size(prop.get_size_in_points()*<NUM_LIT>)<EOL>fontexp=self._get_font_ttf(propexp)<EOL>fontexp.set_text(exp, <NUM_LIT:0.0>)<EOL>w2, h2 = fontexp.get_width_height()<EOL>w=w1+w2<EOL>h=h1+(h2/<NUM_LIT:2>)<EOL>w /= <NUM_LIT>  <EOL>h /= <NUM_LIT><EOL>w+=self.points_to_pixels(self.hackPointsForMathExponent)<EOL>if debugText: print("<STR_LIT>" % (s, w, h))<EOL><DEDENT>else:<EOL><INDENT>w,h=self.get_text_width_height(s,prop,False)<EOL><DEDENT>return w, h<EOL>

get the width and height in display coords of the string s
with FontPropertry prop, ripped right out of backend_ps.  This
method must be kept in sync with draw_math_text.


return True<EOL>

return true if y small numbers are top for renderer
        Is used for drawing text (text.py) and images (image.py) only


return self.width,self.height<EOL>

return the canvas width and height in display coords


if self.lastHandle[type] != handle:<EOL><INDENT>self.emf.SelectObject(handle)<EOL>self.lastHandle[type]=handle<EOL><DEDENT>

Update the EMF file with the current handle, but only if it
isn't the same as the last one.  Don't want to flood the file
with duplicate info.


prop=EMFFontProperties(prop,angle)<EOL>size=int(prop.get_size_in_points()*self.pointstodpi)<EOL>face=prop.get_name()<EOL>key = hash(prop)<EOL>handle = self._fontHandle.get(key)<EOL>if handle is None:<EOL><INDENT>handle=self.emf.CreateFont(-size, <NUM_LIT:0>, int(angle)*<NUM_LIT:10>, int(angle)*<NUM_LIT:10>,<EOL>pyemf.FW_NORMAL, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>,<EOL>pyemf.ANSI_CHARSET, pyemf.OUT_DEFAULT_PRECIS,<EOL>pyemf.CLIP_DEFAULT_PRECIS, pyemf.DEFAULT_QUALITY,<EOL>pyemf.DEFAULT_PITCH | pyemf.FF_DONTCARE, face);<EOL>if debugHandle: print("<STR_LIT>" % (handle,face,size))<EOL>self._fontHandle[key]=handle<EOL><DEDENT>if debugHandle: print("<STR_LIT>" % (handle,face,size))<EOL>self.set_handle("<STR_LIT>",handle)<EOL>return handle<EOL>

Look up the handle for the font based on the dict of
properties *and* the rotation angle, since in EMF the font
rotation is a part of the font definition.


pen=EMFPen(self.emf,gc)<EOL>key=hash(pen)<EOL>handle=self._fontHandle.get(key)<EOL>if handle is None:<EOL><INDENT>handle=pen.get_handle()<EOL>self._fontHandle[key]=handle<EOL><DEDENT>if debugHandle: print("<STR_LIT>" % handle)<EOL>self.set_handle("<STR_LIT>",handle)<EOL>if pen.style != pyemf.PS_NULL:<EOL><INDENT>return pen<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Select a pen that includes the color, line width and line
style.  Return the pen if it will draw a line, or None if the
pen won't produce any output (i.e. the style is PS_NULL)


if rgb is not None:<EOL><INDENT>brush=EMFBrush(self.emf,rgb)<EOL>key=hash(brush)<EOL>handle=self._fontHandle.get(key)<EOL>if handle is None:<EOL><INDENT>handle=brush.get_handle()<EOL>self._fontHandle[key]=handle<EOL><DEDENT>if debugHandle: print("<STR_LIT>" % handle)<EOL>self.set_handle("<STR_LIT>",handle)<EOL>return brush<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Select a fill color, and return the brush if the color is
valid or None if this won't produce a fill operation.


key = hash(prop)<EOL>font = _fontd.get(key)<EOL>if font is None:<EOL><INDENT>fname = findfont(prop)<EOL>if debugText: print("<STR_LIT>" % fname)<EOL>font = FT2Font(str(fname))<EOL>_fontd[key] = font<EOL><DEDENT>font.clear()<EOL>size = prop.get_size_in_points()<EOL>font.set_size(size, self.dpi)<EOL>return font<EOL>

get the true type font properties, used because EMFs on
windows will use true type fonts.


def get_text_width_height(self, s, prop, ismath):

if debugText: print("<STR_LIT>" % (str(ismath),str(prop)))<EOL>if ismath:<EOL><INDENT>if debugText: print("<STR_LIT>" % str(ismath))<EOL>w,h = self.get_math_text_width_height(s, prop)<EOL>return w,h<EOL><DEDENT>font = self._get_font_ttf(prop)<EOL>font.set_text(s, <NUM_LIT:0.0>)<EOL>w, h = font.get_width_height()<EOL>w /= <NUM_LIT>  <EOL>h /= <NUM_LIT><EOL>if debugText: print("<STR_LIT>" % (s, w, h))<EOL>return w, h<EOL>

get the width and height in display coords of the string s
with FontPropertry prop, ripped right out of backend_ps


pass<EOL>


Show all the figures and enter the Cocoa mainloop.
    This function will not return until all windows are closed or
    the interpreter exits.


figManager =  Gcf.get_active()<EOL>if figManager is not None:<EOL><INDENT>figManager.canvas.invalidate()<EOL><DEDENT>

For performance reasons, we don't want to redraw the figure after
each draw command. Instead, we mark the figure as invalid, so that
it will be redrawn as soon as the event loop resumes via PyOS_InputHook.
This function should be called after each draw event, even if
matplotlib is not running interactively.


FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>figure = FigureClass(*args, **kwargs)<EOL>canvas = FigureCanvasMac(figure)<EOL>manager = FigureManagerMac(canvas, num)<EOL>return manager<EOL>


if rgbFace is None:<EOL><INDENT>fill = '<STR_LIT:none>'<EOL><DEDENT>else:<EOL><INDENT>fill = rgb2hex(rgbFace[:<NUM_LIT:3>])<EOL><DEDENT>offset, seq = gc.get_dashes()<EOL>if seq is None:<EOL><INDENT>dashes = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>dashes = '<STR_LIT>' % (<EOL>'<STR_LIT:U+002C>'.join(['<STR_LIT>'%val for val in seq]), offset)<EOL><DEDENT>linewidth = gc.get_linewidth()<EOL>if linewidth:<EOL><INDENT>return '<STR_LIT>''<STR_LIT>' % (<EOL>fill,<EOL>rgb2hex(gc.get_rgb()[:<NUM_LIT:3>]),<EOL>linewidth,<EOL>gc.get_joinstyle(),<EOL>_capstyle_d[gc.get_capstyle()],<EOL>dashes,<EOL>gc.get_alpha(),<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>' % (fill,<EOL>gc.get_alpha(),<EOL>)<EOL><DEDENT>

return the style string.
style is generated from the GraphicsContext, rgbFace and clippath


return rcParams['<STR_LIT>']<EOL>

if svg.image_noscale is True, compositing multiple images into one is prohibited


def _draw_mathtext(self, gc, x, y, s, prop, angle):

width, height, descent, svg_elements, used_characters =self.mathtext_parser.parse(s, <NUM_LIT>, prop)<EOL>svg_glyphs = svg_elements.svg_glyphs<EOL>svg_rects = svg_elements.svg_rects<EOL>color = rgb2hex(gc.get_rgb()[:<NUM_LIT:3>])<EOL>write = self._svgwriter.write<EOL>style = "<STR_LIT>" % color<EOL>if rcParams['<STR_LIT>']:<EOL><INDENT>new_chars = []<EOL>for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs:<EOL><INDENT>path = self._add_char_def(font, thetext)<EOL>if path is not None:<EOL><INDENT>new_chars.append(path)<EOL><DEDENT><DEDENT>if len(new_chars):<EOL><INDENT>write('<STR_LIT>')<EOL>for path in new_chars:<EOL><INDENT>write(path)<EOL><DEDENT>write('<STR_LIT>')<EOL><DEDENT>svg = ['<STR_LIT>' % style]<EOL>if angle != <NUM_LIT:0>:<EOL><INDENT>svg.append('<STR_LIT>'<EOL>% (x,y,-angle) )<EOL><DEDENT>else:<EOL><INDENT>svg.append('<STR_LIT>' % (x, y))<EOL><DEDENT>svg.append('<STR_LIT>')<EOL>for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs:<EOL><INDENT>charid = self._get_char_def_id(font, thetext)<EOL>svg.append('<STR_LIT>' %<EOL>(charid, new_x, -new_y_mtc, fontsize / self.FONT_SCALE))<EOL><DEDENT>svg.append('<STR_LIT>')<EOL><DEDENT>else: <EOL><INDENT>svg = ['<STR_LIT>' % (style, x, y)]<EOL>if angle != <NUM_LIT:0>:<EOL><INDENT>svg.append('<STR_LIT>'<EOL>% (x,y,-angle,-x,-y) ) <EOL><DEDENT>svg.append('<STR_LIT>')<EOL>curr_x,curr_y = <NUM_LIT:0.0>,<NUM_LIT:0.0><EOL>for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs:<EOL><INDENT>new_y = - new_y_mtc<EOL>style = "<STR_LIT>" % (fontsize, font.family_name)<EOL>svg.append('<STR_LIT>' % style)<EOL>xadvance = metrics.advance<EOL>svg.append('<STR_LIT>' % xadvance)<EOL>dx = new_x - curr_x<EOL>if dx != <NUM_LIT:0.0>:<EOL><INDENT>svg.append('<STR_LIT>' % dx)<EOL><DEDENT>dy = new_y - curr_y<EOL>if dy != <NUM_LIT:0.0>:<EOL><INDENT>svg.append('<STR_LIT>' % dy)<EOL><DEDENT>thetext = escape_xml_text(thetext)<EOL>svg.append('<STR_LIT>' % thetext)<EOL>curr_x = new_x + xadvance<EOL>curr_y = new_y<EOL><DEDENT>svg.append('<STR_LIT>')<EOL><DEDENT>if len(svg_rects):<EOL><INDENT>style = "<STR_LIT>" % color<EOL>svg.append('<STR_LIT>' % style)<EOL>if angle != <NUM_LIT:0>:<EOL><INDENT>svg.append('<STR_LIT>'<EOL>% (x,y,-angle) )<EOL><DEDENT>else:<EOL><INDENT>svg.append('<STR_LIT>' % (x, y))<EOL><DEDENT>svg.append('<STR_LIT>')<EOL>for x, y, width, height in svg_rects:<EOL><INDENT>svg.append('<STR_LIT>' % (x, -y + height, width, height))<EOL><DEDENT>svg.append("<STR_LIT>")<EOL><DEDENT>self.open_group("<STR_LIT>")<EOL>write ('<STR_LIT>'.join(svg))<EOL>self.close_group("<STR_LIT>")<EOL>

Draw math text using matplotlib.mathtext


s=s.replace("<STR_LIT:\\>", "<STR_LIT>")<EOL>s=s.replace("<STR_LIT:(>", "<STR_LIT>")<EOL>s=s.replace("<STR_LIT:)>", "<STR_LIT>")<EOL>s=s.replace("<STR_LIT:'>", "<STR_LIT>")<EOL>s=s.replace("<STR_LIT>", "<STR_LIT>")<EOL>s=re.sub(r"<STR_LIT>", lambda x: r"<STR_LIT>"%ord(x.group()), s)<EOL>return s<EOL>

Quote dangerous characters of S for use in a PostScript string constant.


if seq1 is None:<EOL><INDENT>return seq2 is None<EOL><DEDENT>if seq2 is None:<EOL><INDENT>return False<EOL><DEDENT>if len(seq1) != len(seq2): return False<EOL>return npy.alltrue(npy.equal(seq1, seq2))<EOL>

seq1 and seq2 are either None or sequences or numerix arrays
Return True if both are None or both are seqs with identical
elements


def convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble,<EOL>paperWidth, paperHeight, orientation):

tmpdir = os.path.split(tmpfile)[<NUM_LIT:0>]<EOL>epsfile = tmpfile+'<STR_LIT>'<EOL>shutil.move(tmpfile, epsfile)<EOL>latexfile = tmpfile+'<STR_LIT>'<EOL>outfile = tmpfile+'<STR_LIT>'<EOL>latexh = file(latexfile, '<STR_LIT:w>')<EOL>dvifile = tmpfile+'<STR_LIT>'<EOL>psfile = tmpfile+'<STR_LIT>'<EOL>if orientation=='<STR_LIT>': angle = <NUM_LIT><EOL>else: angle = <NUM_LIT:0><EOL>if rcParams['<STR_LIT>']:<EOL><INDENT>unicode_preamble = """<STR_LIT>"""<EOL><DEDENT>else:<EOL><INDENT>unicode_preamble = '<STR_LIT>'<EOL><DEDENT>s =

When we want to use the LaTeX backend with postscript, we write PSFrag tags
to a temporary postscript file, each one marking a position for LaTeX to
render some text. convert_psfrags generates a LaTeX document containing the
commands to convert those tags to text. LaTeX/dvips produces the postscript
file that includes the actual text.


def gs_distill(tmpfile, eps=False, ptype='<STR_LIT>', bbox=None):

paper = '<STR_LIT>'% ptype<EOL>psfile = tmpfile + '<STR_LIT>'<EOL>outfile = tmpfile + '<STR_LIT>'<EOL>dpi = rcParams['<STR_LIT>']<EOL>if sys.platform == '<STR_LIT:win32>': gs_exe = '<STR_LIT>'<EOL>else: gs_exe = '<STR_LIT>'<EOL>command = '<STR_LIT>'% (gs_exe, dpi, paper, psfile, tmpfile, outfile)<EOL>verbose.report(command, '<STR_LIT>')<EOL>exit_status = os.system(command)<EOL>fh = file(outfile)<EOL>if exit_status: raise RuntimeError('<STR_LIT>' + fh.read())<EOL>else: verbose.report(fh.read(), '<STR_LIT>')<EOL>fh.close()<EOL>os.remove(outfile)<EOL>os.remove(tmpfile)<EOL>shutil.move(psfile, tmpfile)<EOL>if eps:<EOL><INDENT>pstoeps(tmpfile, bbox)<EOL><DEDENT>

Use ghostscript's pswrite or epswrite device to distill a file.
This yields smaller files without illegal encapsulated postscript
operators. The output is low-level, converting text to outlines.


def xpdf_distill(tmpfile, eps=False, ptype='<STR_LIT>', bbox=None):

pdffile = tmpfile + '<STR_LIT>'<EOL>psfile = tmpfile + '<STR_LIT>'<EOL>outfile = tmpfile + '<STR_LIT>'<EOL>command = '<STR_LIT>'%pe, tmpfile, pdffile, outfile)<EOL>if sys.platform == '<STR_LIT:win32>': command = command.replace('<STR_LIT:=>', '<STR_LIT:#>')<EOL>verbose.report(command, '<STR_LIT>')<EOL>exit_status = os.system(command)<EOL>fh = file(outfile)<EOL>if exit_status: raise RuntimeError('<STR_LIT>' + fh.read())<EOL>else: verbose.report(fh.read(), '<STR_LIT>')<EOL>fh.close()<EOL>os.remove(outfile)<EOL>command = '<STR_LIT>'%(pdffile, psfile, outfile)<EOL>verbose.report(command, '<STR_LIT>')<EOL>exit_status = os.system(command)<EOL>fh = file(outfile)<EOL>if exit_status: raise RuntimeError('<STR_LIT>' + fh.read())<EOL>else: verbose.report(fh.read(), '<STR_LIT>')<EOL>fh.close()<EOL>os.remove(outfile)<EOL>os.remove(tmpfile)<EOL>shutil.move(psfile, tmpfile)<EOL>if eps:<EOL>pstoeps(tmpfile, bbox)<EOL>for fname in glob.glob(tmpfile+'<STR_LIT>'):<EOL>os.remove(fname)<EOL>

Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file.
This yields smaller files without illegal encapsulated postscript
operators. This distiller is preferred, generating high-level postscript
output that treats text as text.


outfile = tmpfile + '<STR_LIT>'<EOL>if sys.platform == '<STR_LIT:win32>': gs_exe = '<STR_LIT>'<EOL>else: gs_exe = '<STR_LIT>'<EOL>command = '<STR_LIT>' %(gs_exe, tmpfile)<EOL>verbose.report(command, '<STR_LIT>')<EOL>stdin, stdout, stderr = os.popen3(command)<EOL>verbose.report(stdout.read(), '<STR_LIT>')<EOL>bbox_info = stderr.read()<EOL>verbose.report(bbox_info, '<STR_LIT>')<EOL>bbox_found = re.search('<STR_LIT>', bbox_info)<EOL>if bbox_found:<EOL><INDENT>bbox_info = bbox_found.group()<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>'% bbox_info)<EOL><DEDENT>l, b, r, t = [float(i) for i in bbox_info.split()[-<NUM_LIT:4>:]]<EOL>if bbox is None:<EOL><INDENT>l, b, r, t = (l-<NUM_LIT:1>, b-<NUM_LIT:1>, r+<NUM_LIT:1>, t+<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>x = (l+r)/<NUM_LIT:2><EOL>y = (b+t)/<NUM_LIT:2><EOL>dx = (bbox[<NUM_LIT:2>]-bbox[<NUM_LIT:0>])/<NUM_LIT:2><EOL>dy = (bbox[<NUM_LIT:3>]-bbox[<NUM_LIT:1>])/<NUM_LIT:2><EOL>l,b,r,t = (x-dx, y-dy, x+dx, y+dy)<EOL><DEDENT>bbox_info = '<STR_LIT>' % (l, b, npy.ceil(r), npy.ceil(t))<EOL>hires_bbox_info = '<STR_LIT>' % (l, b, r, t)<EOL>return '<STR_LIT:\n>'.join([bbox_info, hires_bbox_info])<EOL>

Use ghostscript's bbox device to find the center of the bounding box. Return
an appropriately sized bbox centered around that point. A bit of a hack.


bbox_info = get_bbox(tmpfile, bbox)<EOL>epsfile = tmpfile + '<STR_LIT>'<EOL>epsh = file(epsfile, '<STR_LIT:w>')<EOL>tmph = file(tmpfile)<EOL>line = tmph.readline()<EOL>while line:<EOL><INDENT>if line.startswith('<STR_LIT>'):<EOL><INDENT>print("<STR_LIT>", file=epsh)<EOL>print(bbox_info, file=epsh)<EOL><DEDENT>elif line.startswith('<STR_LIT>'):<EOL><INDENT>epsh.write(line)<EOL>print('<STR_LIT>', file=epsh)<EOL>print('<STR_LIT>', file=epsh)<EOL>print('<STR_LIT>', file=epsh)<EOL>print('<STR_LIT>', file=epsh)<EOL>print('<STR_LIT>', file=epsh)<EOL>print('<STR_LIT>', file=epsh)<EOL>print('<STR_LIT>', file=epsh)<EOL>print('<STR_LIT>', file=epsh)<EOL>print('<STR_LIT>', file=epsh)<EOL>break<EOL><DEDENT>elif line.startswith('<STR_LIT>')or line.startswith('<STR_LIT>')or line.startswith('<STR_LIT>'):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>epsh.write(line)<EOL><DEDENT>line = tmph.readline()<EOL><DEDENT>line = tmph.readline()<EOL>while line:<EOL><INDENT>if line.startswith('<STR_LIT>'):<EOL><INDENT>print('<STR_LIT>', file=epsh)<EOL>print('<STR_LIT>', file=epsh)<EOL>print('<STR_LIT>', file=epsh)<EOL>print('<STR_LIT>', file=epsh)<EOL>print('<STR_LIT>', file=epsh)<EOL>if rcParams['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>line = tmph.readline()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>epsh.write(line)<EOL><DEDENT>line = tmph.readline()<EOL><DEDENT>tmph.close()<EOL>epsh.close()<EOL>os.remove(tmpfile)<EOL>shutil.move(epsfile, tmpfile)<EOL>

Convert the postscript to encapsulated postscript.


def __init__(self, width, height, pswriter, imagedpi=<NUM_LIT>):

RendererBase.__init__(self)<EOL>self.width = width<EOL>self.height = height<EOL>self._pswriter = pswriter<EOL>if rcParams['<STR_LIT>']:<EOL><INDENT>self.textcnt = <NUM_LIT:0><EOL>self.psfrag = []<EOL><DEDENT>self.imagedpi = imagedpi<EOL>if rcParams['<STR_LIT>']:<EOL><INDENT>self.simplify = (width * imagedpi, height * imagedpi)<EOL><DEDENT>else:<EOL><INDENT>self.simplify = None<EOL><DEDENT>self.color = None<EOL>self.linewidth = None<EOL>self.linejoin = None<EOL>self.linecap = None<EOL>self.linedash = None<EOL>self.fontname = None<EOL>self.fontsize = None<EOL>self.hatch = None<EOL>self.image_magnification = imagedpi/<NUM_LIT><EOL>self._clip_paths = {}<EOL>self._path_collection_id = <NUM_LIT:0><EOL>self.used_characters = {}<EOL>self.mathtext_parser = MathTextParser("<STR_LIT>")<EOL>

Although postscript itself is dpi independent, we need to
imform the image code about a requested dpi to generate high
res images and them scale them before embeddin them


realpath, stat_key = get_realpath_and_stat(font.fname)<EOL>used_characters = self.used_characters.setdefault(<EOL>stat_key, (realpath, set()))<EOL>used_characters[<NUM_LIT:1>].update([ord(x) for x in s])<EOL>

Keeps track of which characters are required from
        each font.


hatches = {'<STR_LIT>':<NUM_LIT:0>, '<STR_LIT>':<NUM_LIT:0>, '<STR_LIT>':<NUM_LIT:0>, '<STR_LIT>':<NUM_LIT:0>}<EOL>for letter in hatch:<EOL><INDENT>if   (letter == '<STR_LIT:/>'):    hatches['<STR_LIT>'] += <NUM_LIT:1><EOL>elif (letter == '<STR_LIT:\\>'):   hatches['<STR_LIT>'] += <NUM_LIT:1><EOL>elif (letter == '<STR_LIT:|>'):    hatches['<STR_LIT>']  += <NUM_LIT:1><EOL>elif (letter == '<STR_LIT:->'):    hatches['<STR_LIT>'] += <NUM_LIT:1><EOL>elif (letter == '<STR_LIT:+>'):<EOL><INDENT>hatches['<STR_LIT>'] += <NUM_LIT:1><EOL>hatches['<STR_LIT>'] += <NUM_LIT:1><EOL><DEDENT>elif (letter.lower() == '<STR_LIT:x>'):<EOL><INDENT>hatches['<STR_LIT>'] += <NUM_LIT:1><EOL>hatches['<STR_LIT>'] += <NUM_LIT:1><EOL><DEDENT><DEDENT>def do_hatch(angle, density):<EOL><INDENT>if (density == <NUM_LIT:0>): return "<STR_LIT>"<EOL>return

hatch can be one of:
    /   - diagonal hatching
    \   - back diagonal
    |   - vertical
    -   - horizontal
    +   - crossed
    X   - crossed diagonal

letters can be combined, in which case all the specified
hatchings are done

if same letter repeats, it increases the density of hatching
in that direction


return self.width, self.height<EOL>

return the canvas width and height in display coords


def get_text_width_height_descent(self, s, prop, ismath):

if rcParams['<STR_LIT>']:<EOL><INDENT>texmanager = self.get_texmanager()<EOL>fontsize = prop.get_size_in_points()<EOL>l,b,r,t = texmanager.get_ps_bbox(s, fontsize)<EOL>w = (r-l)<EOL>h = (t-b)<EOL>return w, h, <NUM_LIT:0><EOL><DEDENT>if ismath:<EOL><INDENT>width, height, descent, pswriter, used_characters =self.mathtext_parser.parse(s, <NUM_LIT>, prop)<EOL>return width, height, descent<EOL><DEDENT>if rcParams['<STR_LIT>']:<EOL><INDENT>if ismath: s = s[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>font = self._get_font_afm(prop)<EOL>l,b,w,h,d = font.get_str_bbox_and_descent(s)<EOL>fontsize = prop.get_size_in_points()<EOL>scale = <NUM_LIT>*fontsize<EOL>w *= scale<EOL>h *= scale<EOL>d *= scale<EOL>return w, h, d<EOL><DEDENT>font = self._get_font_ttf(prop)<EOL>font.set_text(s, <NUM_LIT:0.0>, flags=LOAD_NO_HINTING)<EOL>w, h = font.get_width_height()<EOL>w /= <NUM_LIT>  <EOL>h /= <NUM_LIT><EOL>d = font.get_descent()<EOL>d /= <NUM_LIT><EOL>return w, h, d<EOL>

get the width and height in display coords of the string s
with FontPropertry prop


return False<EOL>

return true if small y numbers are top for renderer


return self.image_magnification<EOL>

Get the factor by which to magnify images passed to draw_image.
Allows a backend to have images at a different resolution to other
artists.


def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None):

im.flipud_out()<EOL>if im.is_grayscale:<EOL><INDENT>h, w, bits = self._gray(im)<EOL>imagecmd = "<STR_LIT:image>"<EOL><DEDENT>else:<EOL><INDENT>h, w, bits = self._rgb(im)<EOL>imagecmd = "<STR_LIT>"<EOL><DEDENT>hexlines = '<STR_LIT:\n>'.join(self._hex_lines(bits))<EOL>xscale, yscale = (<EOL>w/self.image_magnification, h/self.image_magnification)<EOL>figh = self.height*<NUM_LIT><EOL>clip = []<EOL>if bbox is not None:<EOL><INDENT>clipx,clipy,clipw,cliph = bbox.bounds<EOL>clip.append('<STR_LIT>' % _nums_to_str(clipw, cliph, clipx, clipy))<EOL><DEDENT>if clippath is not None:<EOL><INDENT>id = self._get_clip_path(clippath, clippath_trans)<EOL>clip.append('<STR_LIT:%s>' % id)<EOL><DEDENT>clip = '<STR_LIT:\n>'.join(clip)<EOL>ps =

Draw the Image instance into the current axes; x is the
distance in pixels from the left hand side of the canvas and y
is the distance from bottom

bbox is a matplotlib.transforms.BBox instance for clipping, or
None


def draw_path(self, gc, path, transform, rgbFace=None):

ps = self._convert_path(path, transform, self.simplify)<EOL>self._draw_ps(ps, gc, rgbFace)<EOL>

Draws a Path instance using the given affine transform.


def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None):

if debugPS: self._pswriter.write('<STR_LIT>')<EOL>write = self._pswriter.write<EOL>if rgbFace:<EOL><INDENT>if rgbFace[<NUM_LIT:0>]==rgbFace[<NUM_LIT:1>] and rgbFace[<NUM_LIT:0>]==rgbFace[<NUM_LIT:2>]:<EOL><INDENT>ps_color = '<STR_LIT>' % rgbFace[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>ps_color = '<STR_LIT>' % rgbFace<EOL><DEDENT><DEDENT>ps_cmd = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'] <EOL>ps_cmd.append(self._convert_path(marker_path, marker_trans))<EOL>if rgbFace:<EOL><INDENT>ps_cmd.extend(['<STR_LIT>', ps_color, '<STR_LIT>', '<STR_LIT>'])<EOL><DEDENT>ps_cmd.extend(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>tpath = trans.transform_path(path)<EOL>for vertices, code in tpath.iter_segments():<EOL><INDENT>if len(vertices):<EOL><INDENT>x, y = vertices[-<NUM_LIT:2>:]<EOL>ps_cmd.append("<STR_LIT>" % (x, y))<EOL><DEDENT><DEDENT>ps = '<STR_LIT:\n>'.join(ps_cmd)<EOL>self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)<EOL>

Draw the markers defined by path at each of the positions in x
and y.  path coordinates are points, x and y coords will be
transformed by the transform


def draw_tex(self, gc, x, y, s, prop, angle, ismath='<STR_LIT>'):

w, h, bl = self.get_text_width_height_descent(s, prop, ismath)<EOL>fontsize = prop.get_size_in_points()<EOL>corr = <NUM_LIT:0><EOL>pos = _nums_to_str(x-corr, y)<EOL>thetext = '<STR_LIT>' % self.textcnt<EOL>color = '<STR_LIT>'% gc.get_rgb()[:<NUM_LIT:3>]<EOL>fontcmd = {'<STR_LIT>' : r'<STR_LIT>',<EOL>'<STR_LIT>'  : r'<STR_LIT>'}.get(<EOL>rcParams['<STR_LIT>'], r'<STR_LIT>')<EOL>s = fontcmd % s<EOL>tex = r'<STR_LIT>' % (color, s)<EOL>self.psfrag.append(r'<STR_LIT>'%(thetext, angle, fontsize, fontsize*<NUM_LIT>, tex))<EOL>ps =


def draw_text(self, gc, x, y, s, prop, angle, ismath):

<EOL>write = self._pswriter.write<EOL>if debugPS:<EOL><INDENT>write("<STR_LIT>")<EOL><DEDENT>if ismath=='<STR_LIT>':<EOL><INDENT>return self.tex(gc, x, y, s, prop, angle)<EOL><DEDENT>elif ismath:<EOL><INDENT>return self.draw_mathtext(gc, x, y, s, prop, angle)<EOL><DEDENT>elif isinstance(s, str):<EOL><INDENT>return self.draw_unicode(gc, x, y, s, prop, angle)<EOL><DEDENT>elif rcParams['<STR_LIT>']:<EOL><INDENT>font = self._get_font_afm(prop)<EOL>l,b,w,h = font.get_str_bbox(s)<EOL>fontsize = prop.get_size_in_points()<EOL>l *= <NUM_LIT>*fontsize<EOL>b *= <NUM_LIT>*fontsize<EOL>w *= <NUM_LIT>*fontsize<EOL>h *= <NUM_LIT>*fontsize<EOL>if angle==<NUM_LIT>: l,b = -b, l <EOL>pos = _nums_to_str(x-l, y-b)<EOL>thetext = '<STR_LIT>' % s<EOL>fontname = font.get_fontname()<EOL>fontsize = prop.get_size_in_points()<EOL>rotate = '<STR_LIT>' % angle<EOL>setcolor = '<STR_LIT>' % gc.get_rgb()[:<NUM_LIT:3>]<EOL>ps =


def draw_unicode(self, gc, x, y, s, prop, angle):

if rcParams['<STR_LIT>']:<EOL><INDENT>self.set_color(*gc.get_rgb())<EOL>font = self._get_font_afm(prop)<EOL>fontname = font.get_fontname()<EOL>fontsize = prop.get_size_in_points()<EOL>scale = <NUM_LIT>*fontsize<EOL>thisx = <NUM_LIT:0><EOL>thisy = font.get_str_bbox_and_descent(s)[<NUM_LIT:4>] * scale<EOL>last_name = None<EOL>lines = []<EOL>for c in s:<EOL><INDENT>name = uni2type1.get(ord(c), '<STR_LIT>')<EOL>try:<EOL><INDENT>width = font.get_width_from_char_name(name)<EOL><DEDENT>except KeyError:<EOL><INDENT>name = '<STR_LIT>'<EOL>width = font.get_width_char('<STR_LIT:?>')<EOL><DEDENT>if last_name is not None:<EOL><INDENT>kern = font.get_kern_dist_from_name(last_name, name)<EOL><DEDENT>else:<EOL><INDENT>kern = <NUM_LIT:0><EOL><DEDENT>last_name = name<EOL>thisx += kern * scale<EOL>lines.append('<STR_LIT>'%(thisx, thisy, name))<EOL>thisx += width * scale<EOL><DEDENT>thetext = "<STR_LIT:\n>".join(lines)<EOL>ps = """<STR_LIT>"""gsave<EOL><DEDENT>y)f translate<EOL>f rotate<EOL>t)s<EOL>cals()<EOL>self._pswriter.write(ps)<EOL>

draw a unicode string.  ps doesn't have unicode support, so
        we have to do this the hard way


def draw_mathtext(self, gc,<EOL>x, y, s, prop, angle):

if debugPS:<EOL><INDENT>self._pswriter.write("<STR_LIT>")<EOL><DEDENT>width, height, descent, pswriter, used_characters =self.mathtext_parser.parse(s, <NUM_LIT>, prop)<EOL>self.merge_used_characters(used_characters)<EOL>self.set_color(*gc.get_rgb())<EOL>thetext = pswriter.getvalue()<EOL>ps =

Draw the math text using matplotlib.mathtext


def _draw_ps(self, ps, gc, rgbFace, fill=True, stroke=True, command=None):

<EOL>write = self._pswriter.write<EOL>if debugPS and command:<EOL><INDENT>write("<STR_LIT>"+command+"<STR_LIT:\n>")<EOL><DEDENT>mightstroke = (gc.get_linewidth() > <NUM_LIT:0.0> and<EOL>(len(gc.get_rgb()) <= <NUM_LIT:3> or gc.get_rgb()[<NUM_LIT:3>] != <NUM_LIT:0.0>))<EOL>stroke = stroke and mightstroke<EOL>fill = (fill and rgbFace is not None and<EOL>(len(rgbFace) <= <NUM_LIT:3> or rgbFace[<NUM_LIT:3>] != <NUM_LIT:0.0>))<EOL>if mightstroke:<EOL><INDENT>self.set_linewidth(gc.get_linewidth())<EOL>jint = gc.get_joinstyle()<EOL>self.set_linejoin(jint)<EOL>cint = gc.get_capstyle()<EOL>self.set_linecap(cint)<EOL>self.set_linedash(*gc.get_dashes())<EOL>self.set_color(*gc.get_rgb()[:<NUM_LIT:3>])<EOL><DEDENT>write('<STR_LIT>')<EOL>cliprect = gc.get_clip_rectangle()<EOL>if cliprect:<EOL><INDENT>x,y,w,h=cliprect.bounds<EOL>write('<STR_LIT>' % (w,h,x,y))<EOL><DEDENT>clippath, clippath_trans = gc.get_clip_path()<EOL>if clippath:<EOL><INDENT>id = self._get_clip_path(clippath, clippath_trans)<EOL>write('<STR_LIT>' % id)<EOL><DEDENT>write(ps.strip())<EOL>write("<STR_LIT:\n>")<EOL>if fill:<EOL><INDENT>if stroke:<EOL><INDENT>write("<STR_LIT>")<EOL>self.set_color(store=<NUM_LIT:0>, *rgbFace[:<NUM_LIT:3>])<EOL>write("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self.set_color(store=<NUM_LIT:0>, *rgbFace[:<NUM_LIT:3>])<EOL>write("<STR_LIT>")<EOL><DEDENT><DEDENT>hatch = gc.get_hatch()<EOL>if hatch:<EOL><INDENT>self.set_hatch(hatch)<EOL><DEDENT>if stroke:<EOL><INDENT>write("<STR_LIT>")<EOL><DEDENT>write("<STR_LIT>")<EOL>

Emit the PostScript sniplet 'ps' with all the attributes from 'gc'
applied.  'ps' must consist of PostScript commands to construct a path.

The fill and/or stroke kwargs can be set to False if the
'ps' string already includes filling and/or stroking, in
which case _draw_ps is just supplying properties and
clipping.


def _print_figure(self, outfile, format, dpi=<NUM_LIT>, facecolor='<STR_LIT:w>', edgecolor='<STR_LIT:w>',<EOL>orientation='<STR_LIT>', isLandscape=False, papertype=None):

isEPSF = format == '<STR_LIT>'<EOL>passed_in_file_object = False<EOL>if is_string_like(outfile):<EOL><INDENT>title = outfile<EOL>tmpfile = os.path.join(gettempdir(), md5(outfile).hexdigest())<EOL><DEDENT>elif is_writable_file_like(outfile):<EOL><INDENT>title = None<EOL>tmpfile = os.path.join(gettempdir(), md5(str(hash(outfile))).hexdigest())<EOL>passed_in_file_object = True<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>fh = file(tmpfile, '<STR_LIT:w>')<EOL>width, height = self.figure.get_size_inches()<EOL>if papertype == '<STR_LIT>':<EOL><INDENT>if isLandscape: papertype = _get_papertype(height, width)<EOL>else: papertype = _get_papertype(width, height)<EOL><DEDENT>if isLandscape: paperHeight, paperWidth = papersize[papertype]<EOL>else: paperWidth, paperHeight = papersize[papertype]<EOL>if rcParams['<STR_LIT>'] and not papertype == '<STR_LIT>':<EOL><INDENT>if width>paperWidth or height>paperHeight:<EOL><INDENT>if isLandscape:<EOL><INDENT>papertype = _get_papertype(height, width)<EOL>paperHeight, paperWidth = papersize[papertype]<EOL><DEDENT>else:<EOL><INDENT>papertype = _get_papertype(width, height)<EOL>paperWidth, paperHeight = papersize[papertype]<EOL><DEDENT><DEDENT><DEDENT>xo = <NUM_LIT>*<NUM_LIT:0.5>*(paperWidth - width)<EOL>yo = <NUM_LIT>*<NUM_LIT:0.5>*(paperHeight - height)<EOL>l, b, w, h = self.figure.bbox.bounds<EOL>llx = xo<EOL>lly = yo<EOL>urx = llx + w<EOL>ury = lly + h<EOL>rotation = <NUM_LIT:0><EOL>if isLandscape:<EOL><INDENT>llx, lly, urx, ury = lly, llx, ury, urx<EOL>xo, yo = <NUM_LIT>*paperHeight - yo, xo<EOL>rotation = <NUM_LIT><EOL><DEDENT>bbox = (llx, lly, urx, ury)<EOL>origfacecolor = self.figure.get_facecolor()<EOL>origedgecolor = self.figure.get_edgecolor()<EOL>self.figure.set_facecolor(facecolor)<EOL>self.figure.set_edgecolor(edgecolor)<EOL>self._pswriter = StringIO()<EOL>renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)<EOL>self.figure.draw(renderer)<EOL>self.figure.set_facecolor(origfacecolor)<EOL>self.figure.set_edgecolor(origedgecolor)<EOL>if isEPSF: print("<STR_LIT>", file=fh)<EOL>else: print("<STR_LIT>", file=fh)<EOL>if title: print("<STR_LIT>"+title, file=fh)<EOL>print(("<STR_LIT>"<EOL>+__version__+"<STR_LIT>"), file=fh)<EOL>print("<STR_LIT>"+time.ctime(time.time()), file=fh)<EOL>print("<STR_LIT>" + orientation, file=fh)<EOL>if not isEPSF: print("<STR_LIT>"+papertype, file=fh)<EOL>print("<STR_LIT>" % bbox, file=fh)<EOL>if not isEPSF: print("<STR_LIT>", file=fh)<EOL>print("<STR_LIT>", file=fh)<EOL>Ndict = len(psDefs)<EOL>print("<STR_LIT>", file=fh)<EOL>if not rcParams['<STR_LIT>']:<EOL><INDENT>Ndict += len(renderer.used_characters)<EOL><DEDENT>print("<STR_LIT>"%Ndict, file=fh)<EOL>print("<STR_LIT>", file=fh)<EOL>for d in psDefs:<EOL><INDENT>d=d.strip()<EOL>for l in d.split('<STR_LIT:\n>'):<EOL><INDENT>print(l.strip(), file=fh)<EOL><DEDENT><DEDENT>if not rcParams['<STR_LIT>']:<EOL><INDENT>for font_filename, chars in list(renderer.used_characters.values()):<EOL><INDENT>if len(chars):<EOL><INDENT>font = FT2Font(font_filename)<EOL>cmap = font.get_charmap()<EOL>glyph_ids = []<EOL>for c in chars:<EOL><INDENT>gind = cmap.get(c) or <NUM_LIT:0><EOL>glyph_ids.append(gind)<EOL><DEDENT>if is_opentype_cff_font(font_filename):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>fonttype = rcParams['<STR_LIT>']<EOL>convert_ttf_to_ps(font_filename, fh, rcParams['<STR_LIT>'], glyph_ids)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>print("<STR_LIT:end>", file=fh)<EOL>print("<STR_LIT>", file=fh)<EOL>if not isEPSF: print("<STR_LIT>", file=fh)<EOL>print("<STR_LIT>", file=fh)<EOL>print("<STR_LIT>"%_nums_to_str(xo, yo), file=fh)<EOL>if rotation: print("<STR_LIT>"%rotation, file=fh)<EOL>print("<STR_LIT>"%_nums_to_str(width*<NUM_LIT>, height*<NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0>), file=fh)<EOL>print(self._pswriter.getvalue(), file=fh)<EOL>print("<STR_LIT:end>", file=fh)<EOL>print("<STR_LIT>", file=fh)<EOL>if not isEPSF: print("<STR_LIT>", file=fh)<EOL>fh.close()<EOL>if rcParams['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox)<EOL><DEDENT>elif rcParams['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox)<EOL><DEDENT>if passed_in_file_object:<EOL><INDENT>fh = file(tmpfile)<EOL>print(fh.read(), file=outfile)<EOL><DEDENT>else:<EOL><INDENT>shutil.move(tmpfile, outfile)<EOL><DEDENT>

Render the figure to hardcopy.  Set the figure patch face and
edge colors.  This is useful because some of the GUIs have a
gray figure face color background and you'll probably want to
override this on hardcopy

If outfile is a string, it is interpreted as a file name.
If the extension matches .ep* write encapsulated postscript,
otherwise write a stand-alone PostScript file.

If outfile is a file object, a stand-alone PostScript file is
written into this file object.


def _print_figure_tex(self, outfile, format, dpi, facecolor, edgecolor,<EOL>orientation, isLandscape, papertype):

isEPSF = format == '<STR_LIT>'<EOL>title = outfile<EOL>tmpfile = os.path.join(gettempdir(), md5(outfile).hexdigest())<EOL>fh = file(tmpfile, '<STR_LIT:w>')<EOL>self.figure.dpi = <NUM_LIT> <EOL>width, height = self.figure.get_size_inches()<EOL>xo = <NUM_LIT:0><EOL>yo = <NUM_LIT:0><EOL>l, b, w, h = self.figure.bbox.bounds<EOL>llx = xo<EOL>lly = yo<EOL>urx = llx + w<EOL>ury = lly + h<EOL>bbox = (llx, lly, urx, ury)<EOL>origfacecolor = self.figure.get_facecolor()<EOL>origedgecolor = self.figure.get_edgecolor()<EOL>self.figure.set_facecolor(facecolor)<EOL>self.figure.set_edgecolor(edgecolor)<EOL>self._pswriter = StringIO()<EOL>renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)<EOL>self.figure.draw(renderer)<EOL>self.figure.set_facecolor(origfacecolor)<EOL>self.figure.set_edgecolor(origedgecolor)<EOL>print("<STR_LIT>", file=fh)<EOL>if title: print("<STR_LIT>"+title, file=fh)<EOL>print(("<STR_LIT>"<EOL>+__version__+"<STR_LIT>"), file=fh)<EOL>print("<STR_LIT>"+time.ctime(time.time()), file=fh)<EOL>print("<STR_LIT>" % bbox, file=fh)<EOL>print("<STR_LIT>", file=fh)<EOL>Ndict = len(psDefs)<EOL>print("<STR_LIT>", file=fh)<EOL>print("<STR_LIT>"%Ndict, file=fh)<EOL>print("<STR_LIT>", file=fh)<EOL>for d in psDefs:<EOL><INDENT>d=d.strip()<EOL>for l in d.split('<STR_LIT:\n>'):<EOL><INDENT>print(l.strip(), file=fh)<EOL><DEDENT><DEDENT>print("<STR_LIT:end>", file=fh)<EOL>print("<STR_LIT>", file=fh)<EOL>print("<STR_LIT>", file=fh)<EOL>print("<STR_LIT>"%_nums_to_str(xo, yo), file=fh)<EOL>print("<STR_LIT>"%_nums_to_str(width*<NUM_LIT>, height*<NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0>), file=fh)<EOL>print(self._pswriter.getvalue(), file=fh)<EOL>print("<STR_LIT:end>", file=fh)<EOL>print("<STR_LIT>", file=fh)<EOL>fh.close()<EOL>if isLandscape: <EOL><INDENT>isLandscape = True<EOL>width, height = height, width<EOL>bbox = (lly, llx, ury, urx)<EOL><DEDENT>temp_papertype = _get_papertype(width, height)<EOL>if papertype=='<STR_LIT>':<EOL><INDENT>papertype = temp_papertype<EOL>paperWidth, paperHeight = papersize[temp_papertype]<EOL><DEDENT>else:<EOL><INDENT>paperWidth, paperHeight = papersize[papertype]<EOL>if (width>paperWidth or height>paperHeight) and isEPSF:<EOL><INDENT>paperWidth, paperHeight = papersize[temp_papertype]<EOL>verbose.report('<STR_LIT>'%(papertype, temp_papertype), '<STR_LIT>')<EOL><DEDENT><DEDENT>texmanager = renderer.get_texmanager()<EOL>font_preamble = texmanager.get_font_preamble()<EOL>custom_preamble = texmanager.get_custom_preamble()<EOL>convert_psfrags(tmpfile, renderer.psfrag, font_preamble,<EOL>custom_preamble, paperWidth, paperHeight,<EOL>orientation)<EOL>if rcParams['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox)<EOL><DEDENT>elif rcParams['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox)<EOL><DEDENT>elif rcParams['<STR_LIT>']:<EOL><INDENT>if False: pass <EOL>else: gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox)<EOL><DEDENT>if  isinstance(outfile, file):<EOL><INDENT>fh = file(tmpfile)<EOL>print(fh.read(), file=outfile)<EOL><DEDENT>else: shutil.move(tmpfile, outfile)<EOL>

If text.usetex is True in rc, a temporary pair of tex/eps files
are created to allow tex to manage the text layout via the PSFrags
package. These files are processed to yield the final ps or eps file.


if not self.available(o):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self._owner = o<EOL>


if not self.available(o):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self._owner = None<EOL>


return not self.locked() or self.isowner(o)<EOL>


return self._owner is o<EOL>


return self._owner is not None<EOL>


def __init__(self, ax, label, image=None,<EOL>color='<STR_LIT>', hovercolor='<STR_LIT>'):

if image is not None:<EOL><INDENT>ax.imshow(image)<EOL><DEDENT>self.label = ax.text(<NUM_LIT:0.5>, <NUM_LIT:0.5>, label,<EOL>verticalalignment='<STR_LIT>',<EOL>horizontalalignment='<STR_LIT>',<EOL>transform=ax.transAxes)<EOL>self.cnt = <NUM_LIT:0><EOL>self.observers = {}<EOL>self.ax = ax<EOL>ax.figure.canvas.mpl_connect('<STR_LIT>', self._click)<EOL>ax.figure.canvas.mpl_connect('<STR_LIT>', self._motion)<EOL>ax.set_navigate(False)<EOL>ax.set_axis_bgcolor(color)<EOL>ax.set_xticks([])<EOL>ax.set_yticks([])<EOL>self.color = color<EOL>self.hovercolor = hovercolor<EOL>self._lastcolor = color<EOL>

ax is the Axes instance the button will be placed into

label is a string which is the button text

image if not None, is an image to place in the button -- can
  be any legal arg to imshow (numpy array, matplotlib Image
  instance, or PIL image)

color is the color of the button when not activated

hovercolor is the color of the button when the mouse is over
  it


cid = self.cnt<EOL>self.observers[cid] = func<EOL>self.cnt += <NUM_LIT:1><EOL>return cid<EOL>

When the button is clicked, call this func with event

A connection id is returned which can be used to disconnect


try: del self.observers[cid]<EOL>except KeyError: pass<EOL>

remove the observer with connection id cid


def __init__(self, ax, label, valmin, valmax, valinit=<NUM_LIT:0.5>, valfmt='<STR_LIT>',<EOL>closedmin=True, closedmax=True, slidermin=None, slidermax=None,<EOL>dragging=True, **kwargs):

self.ax = ax<EOL>self.valmin = valmin<EOL>self.valmax = valmax<EOL>self.val = valinit<EOL>self.valinit = valinit<EOL>self.poly = ax.axvspan(valmin,valinit,<NUM_LIT:0>,<NUM_LIT:1>, **kwargs)<EOL>self.vline = ax.axvline(valinit,<NUM_LIT:0>,<NUM_LIT:1>, color='<STR_LIT:r>', lw=<NUM_LIT:1>)<EOL>self.valfmt=valfmt<EOL>ax.set_yticks([])<EOL>ax.set_xlim((valmin, valmax))<EOL>ax.set_xticks([])<EOL>ax.set_navigate(False)<EOL>ax.figure.canvas.mpl_connect('<STR_LIT>', self._update)<EOL>if dragging:<EOL><INDENT>ax.figure.canvas.mpl_connect('<STR_LIT>', self._update)<EOL><DEDENT>self.label = ax.text(-<NUM_LIT>, <NUM_LIT:0.5>, label, transform=ax.transAxes,<EOL>verticalalignment='<STR_LIT>',<EOL>horizontalalignment='<STR_LIT:right>')<EOL>self.valtext = ax.text(<NUM_LIT>, <NUM_LIT:0.5>, valfmt%valinit,<EOL>transform=ax.transAxes,<EOL>verticalalignment='<STR_LIT>',<EOL>horizontalalignment='<STR_LIT:left>')<EOL>self.cnt = <NUM_LIT:0><EOL>self.observers = {}<EOL>self.closedmin = closedmin<EOL>self.closedmax = closedmax<EOL>self.slidermin = slidermin<EOL>self.slidermax = slidermax<EOL>

Create a slider from valmin to valmax in axes ax;

valinit -  the slider initial position

label - the slider label

valfmt - used to format the slider value

closedmin and closedmax - indicate whether the slider interval is closed

slidermin and slidermax - be used to contrain the value of
  this slider to the values of other sliders.

additional kwargs are passed on to self.poly which is the
matplotlib.patches.Rectangle which draws the slider.  See the
matplotlib.patches.Rectangle documentation for legal property
names (eg facecolor, edgecolor, alpha, ...)


if event.button !=<NUM_LIT:1>: return<EOL>if event.inaxes != self.ax: return<EOL>val = event.xdata<EOL>if not self.closedmin and val<=self.valmin: return<EOL>if not self.closedmax and val>=self.valmax: return<EOL>if self.slidermin is not None:<EOL><INDENT>if val<=self.slidermin.val: return<EOL><DEDENT>if self.slidermax is not None:<EOL><INDENT>if val>=self.slidermax.val: return<EOL><DEDENT>self.set_val(val)<EOL>


When the slider valud is changed, call this func with the new
slider position

A connection id is returned which can be used to disconnect


if (self.val != self.valinit):<EOL><INDENT>self.set_val(self.valinit)<EOL><DEDENT>

reset the slider to the initial value if needed


def __init__(self, ax, labels, actives):

ax.set_xticks([])<EOL>ax.set_yticks([])<EOL>ax.set_navigate(False)<EOL>if len(labels)><NUM_LIT:1>:<EOL><INDENT>dy = <NUM_LIT:1.>/(len(labels)+<NUM_LIT:1>)<EOL>ys = np.linspace(<NUM_LIT:1>-dy, dy, len(labels))<EOL><DEDENT>else:<EOL><INDENT>dy = <NUM_LIT><EOL>ys = [<NUM_LIT:0.5>]<EOL><DEDENT>cnt = <NUM_LIT:0><EOL>axcolor = ax.get_axis_bgcolor()<EOL>self.labels = []<EOL>self.lines = []<EOL>self.rectangles = []<EOL>lineparams = {'<STR_LIT>':'<STR_LIT:k>', '<STR_LIT>':<NUM_LIT>, '<STR_LIT>':ax.transAxes,<EOL>'<STR_LIT>':'<STR_LIT>'}<EOL>for y, label in zip(ys, labels):<EOL><INDENT>t = ax.text(<NUM_LIT>, y, label, transform=ax.transAxes,<EOL>horizontalalignment='<STR_LIT:left>',<EOL>verticalalignment='<STR_LIT>')<EOL>w, h = dy/<NUM_LIT>, dy/<NUM_LIT><EOL>x, y = <NUM_LIT>, y-h/<NUM_LIT><EOL>p = Rectangle(xy=(x,y), width=w, height=h,<EOL>facecolor=axcolor,<EOL>transform=ax.transAxes)<EOL>l1 = Line2D([x, x+w], [y+h, y], **lineparams)<EOL>l2 = Line2D([x, x+w], [y, y+h], **lineparams)<EOL>l1.set_visible(actives[cnt])<EOL>l2.set_visible(actives[cnt])<EOL>self.labels.append(t)<EOL>self.rectangles.append(p)<EOL>self.lines.append((l1,l2))<EOL>ax.add_patch(p)<EOL>ax.add_line(l1)<EOL>ax.add_line(l2)<EOL>cnt += <NUM_LIT:1><EOL><DEDENT>ax.figure.canvas.mpl_connect('<STR_LIT>', self._clicked)<EOL>self.ax = ax<EOL>self.cnt = <NUM_LIT:0><EOL>self.observers = {}<EOL>

Add check buttons to axes.Axes instance ax

labels is a len(buttons) list of labels as strings

actives is a len(buttons) list of booleans indicating whether
 the button is active


When the button is clicked, call this func with button label

A connection id is returned which can be used to disconnect


def __init__(self, ax, labels, active=<NUM_LIT:0>, activecolor='<STR_LIT>'):

self.activecolor = activecolor<EOL>ax.set_xticks([])<EOL>ax.set_yticks([])<EOL>ax.set_navigate(False)<EOL>dy = <NUM_LIT:1.>/(len(labels)+<NUM_LIT:1>)<EOL>ys = np.linspace(<NUM_LIT:1>-dy, dy, len(labels))<EOL>cnt = <NUM_LIT:0><EOL>axcolor = ax.get_axis_bgcolor()<EOL>self.labels = []<EOL>self.circles = []<EOL>for y, label in zip(ys, labels):<EOL><INDENT>t = ax.text(<NUM_LIT>, y, label, transform=ax.transAxes,<EOL>horizontalalignment='<STR_LIT:left>',<EOL>verticalalignment='<STR_LIT>')<EOL>if cnt==active:<EOL><INDENT>facecolor = activecolor<EOL><DEDENT>else:<EOL><INDENT>facecolor = axcolor<EOL><DEDENT>p = Circle(xy=(<NUM_LIT>, y), radius=<NUM_LIT>, facecolor=facecolor,<EOL>transform=ax.transAxes)<EOL>self.labels.append(t)<EOL>self.circles.append(p)<EOL>ax.add_patch(p)<EOL>cnt += <NUM_LIT:1><EOL><DEDENT>ax.figure.canvas.mpl_connect('<STR_LIT>', self._clicked)<EOL>self.ax = ax<EOL>self.cnt = <NUM_LIT:0><EOL>self.observers = {}<EOL>

Add radio buttons to axes.Axes instance ax

labels is a len(buttons) list of labels as strings

active is the index into labels for the button that is active

activecolor is the color of the button when clicked


self.targetfig = targetfig<EOL>toolfig.subplots_adjust(left=<NUM_LIT>, right=<NUM_LIT>)<EOL>class toolbarfmt:<EOL><INDENT>def __init__(self, slider):<EOL><INDENT>self.slider = slider<EOL><DEDENT>def __call__(self, x, y):<EOL><INDENT>fmt = '<STR_LIT>'%(self.slider.label.get_text(), self.slider.valfmt)<EOL>return fmt%x<EOL><DEDENT><DEDENT>self.axleft = toolfig.add_subplot(<NUM_LIT>)<EOL>self.axleft.set_title('<STR_LIT>')<EOL>self.axleft.set_navigate(False)<EOL>self.sliderleft = Slider(self.axleft, '<STR_LIT:left>', <NUM_LIT:0>, <NUM_LIT:1>, targetfig.subplotpars.left, closedmax=False)<EOL>self.sliderleft.on_changed(self.funcleft)<EOL>self.axbottom = toolfig.add_subplot(<NUM_LIT>)<EOL>self.axbottom.set_navigate(False)<EOL>self.sliderbottom = Slider(self.axbottom, '<STR_LIT>', <NUM_LIT:0>, <NUM_LIT:1>, targetfig.subplotpars.bottom, closedmax=False)<EOL>self.sliderbottom.on_changed(self.funcbottom)<EOL>self.axright = toolfig.add_subplot(<NUM_LIT>)<EOL>self.axright.set_navigate(False)<EOL>self.sliderright = Slider(self.axright, '<STR_LIT:right>', <NUM_LIT:0>, <NUM_LIT:1>, targetfig.subplotpars.right, closedmin=False)<EOL>self.sliderright.on_changed(self.funcright)<EOL>self.axtop = toolfig.add_subplot(<NUM_LIT>)<EOL>self.axtop.set_navigate(False)<EOL>self.slidertop = Slider(self.axtop, '<STR_LIT>', <NUM_LIT:0>, <NUM_LIT:1>, targetfig.subplotpars.top, closedmin=False)<EOL>self.slidertop.on_changed(self.functop)<EOL>self.axwspace = toolfig.add_subplot(<NUM_LIT>)<EOL>self.axwspace.set_navigate(False)<EOL>self.sliderwspace = Slider(self.axwspace, '<STR_LIT>', <NUM_LIT:0>, <NUM_LIT:1>, targetfig.subplotpars.wspace, closedmax=False)<EOL>self.sliderwspace.on_changed(self.funcwspace)<EOL>self.axhspace = toolfig.add_subplot(<NUM_LIT>)<EOL>self.axhspace.set_navigate(False)<EOL>self.sliderhspace = Slider(self.axhspace, '<STR_LIT>', <NUM_LIT:0>, <NUM_LIT:1>, targetfig.subplotpars.hspace, closedmax=False)<EOL>self.sliderhspace.on_changed(self.funchspace)<EOL>self.sliderleft.slidermax = self.sliderright<EOL>self.sliderright.slidermin = self.sliderleft<EOL>self.sliderbottom.slidermax = self.slidertop<EOL>self.slidertop.slidermin = self.sliderbottom<EOL>bax = toolfig.add_axes([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>])<EOL>self.buttonreset = Button(bax, '<STR_LIT>')<EOL>sliders = (self.sliderleft, self.sliderbottom, self.sliderright,<EOL>self.slidertop, self.sliderwspace, self.sliderhspace, )<EOL>def func(event):<EOL><INDENT>thisdrawon = self.drawon<EOL>self.drawon = False<EOL>bs = []<EOL>for slider in sliders:<EOL><INDENT>bs.append(slider.drawon)<EOL>slider.drawon = False<EOL><DEDENT>for slider in sliders:<EOL><INDENT>slider.reset()<EOL><DEDENT>for slider, b in zip(sliders, bs):<EOL><INDENT>slider.drawon = b<EOL><DEDENT>self.drawon = thisdrawon<EOL>if self.drawon:<EOL><INDENT>toolfig.canvas.draw()<EOL>self.targetfig.canvas.draw()<EOL><DEDENT><DEDENT>validate = toolfig.subplotpars.validate<EOL>toolfig.subplotpars.validate = False<EOL>self.buttonreset.on_clicked(func)<EOL>toolfig.subplotpars.validate = validate<EOL>

targetfig is the figure to adjust

toolfig is the figure to embed the the subplot tool into.  If
None, a default pylab figure will be created.  If you are
using this from the GUI


def __init__(self, ax, useblit=False, **lineprops):

self.ax = ax<EOL>self.canvas = ax.figure.canvas<EOL>self.canvas.mpl_connect('<STR_LIT>', self.onmove)<EOL>self.canvas.mpl_connect('<STR_LIT>', self.clear)<EOL>self.visible = True<EOL>self.horizOn = True<EOL>self.vertOn = True<EOL>self.useblit = useblit<EOL>self.lineh = ax.axhline(ax.get_ybound()[<NUM_LIT:0>], visible=False, **lineprops)<EOL>self.linev = ax.axvline(ax.get_xbound()[<NUM_LIT:0>], visible=False, **lineprops)<EOL>self.background = None<EOL>self.needclear = False<EOL>

Add a cursor to ax.  If useblit=True, use the backend
dependent blitting features for faster updates (GTKAgg only
now).  lineprops is a dictionary of line properties.  See
examples/widgets/cursor.py.


if self.useblit:<EOL><INDENT>self.background = self.canvas.copy_from_bbox(self.ax.bbox)<EOL><DEDENT>self.linev.set_visible(False)<EOL>self.lineh.set_visible(False)<EOL>


if event.inaxes != self.ax:<EOL><INDENT>self.linev.set_visible(False)<EOL>self.lineh.set_visible(False)<EOL>if self.needclear:<EOL><INDENT>self.canvas.draw()<EOL>self.needclear = False<EOL><DEDENT>return<EOL><DEDENT>self.needclear = True<EOL>if not self.visible: return<EOL>self.linev.set_xdata((event.xdata, event.xdata))<EOL>self.lineh.set_ydata((event.ydata, event.ydata))<EOL>self.linev.set_visible(self.visible and self.vertOn)<EOL>self.lineh.set_visible(self.visible and self.horizOn)<EOL>self._update()<EOL>

on mouse motion draw the cursor if visible


if self.useblit:<EOL><INDENT>self.background = self.canvas.copy_from_bbox(self.canvas.figure.bbox)<EOL><DEDENT>for line in self.lines: line.set_visible(False)<EOL>


def __init__(self, ax, onselect, direction, minspan=None, useblit=False, rectprops=None, onmove_callback=None):

if rectprops is None:<EOL><INDENT>rectprops = dict(facecolor='<STR_LIT>', alpha=<NUM_LIT:0.5>)<EOL><DEDENT>assert direction in ['<STR_LIT>', '<STR_LIT>'], '<STR_LIT>'<EOL>self.direction = direction<EOL>self.ax = None<EOL>self.canvas = None<EOL>self.visible = True<EOL>self.cids=[]<EOL>self.rect = None<EOL>self.background = None<EOL>self.pressv = None<EOL>self.rectprops = rectprops<EOL>self.onselect = onselect<EOL>self.onmove_callback = onmove_callback<EOL>self.useblit = useblit<EOL>self.minspan = minspan<EOL>self.buttonDown = False<EOL>self.prev = (<NUM_LIT:0>, <NUM_LIT:0>)<EOL>self.new_axes(ax)<EOL>

Create a span selector in ax.  When a selection is made, clear
the span and call onselect with

  onselect(vmin, vmax)

and clear the span.

direction must be 'horizontal' or 'vertical'

If minspan is not None, ignore events smaller than minspan

The span rect is drawn with rectprops; default
  rectprops = dict(facecolor='red', alpha=0.5)

set the visible attribute to False if you want to turn off
the functionality of the span selector


if self.useblit:<EOL><INDENT>self.background = self.canvas.copy_from_bbox(self.ax.bbox)<EOL><DEDENT>


return  event.inaxes!=self.ax or not self.visible or event.button !=<NUM_LIT:1><EOL>


if self.ignore(event): return<EOL>self.buttonDown = True<EOL>self.rect.set_visible(self.visible)<EOL>if self.direction == '<STR_LIT>':<EOL><INDENT>self.pressv = event.xdata<EOL><DEDENT>else:<EOL><INDENT>self.pressv = event.ydata<EOL><DEDENT>return False<EOL>


if self.pressv is None or (self.ignore(event) and not self.buttonDown): return<EOL>self.buttonDown = False<EOL>self.rect.set_visible(False)<EOL>self.canvas.draw()<EOL>vmin = self.pressv<EOL>if self.direction == '<STR_LIT>':<EOL><INDENT>vmax = event.xdata or self.prev[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>vmax = event.ydata or self.prev[<NUM_LIT:1>]<EOL><DEDENT>if vmin>vmax: vmin, vmax = vmax, vmin<EOL>span = vmax - vmin<EOL>if self.minspan is not None and span<self.minspan: return<EOL>self.onselect(vmin, vmax)<EOL>self.pressv = None<EOL>return False<EOL>


if self.useblit:<EOL><INDENT>if self.background is not None:<EOL><INDENT>self.canvas.restore_region(self.background)<EOL><DEDENT>self.ax.draw_artist(self.rect)<EOL>self.canvas.blit(self.ax.bbox)<EOL><DEDENT>else:<EOL><INDENT>self.canvas.draw_idle()<EOL><DEDENT>return False<EOL>

draw using newfangled blit or oldfangled draw depending on useblit


if self.pressv is None or self.ignore(event): return<EOL>x, y = event.xdata, event.ydata<EOL>self.prev = x, y<EOL>if self.direction == '<STR_LIT>':<EOL><INDENT>v = x<EOL><DEDENT>else:<EOL><INDENT>v = y<EOL><DEDENT>minv, maxv = v, self.pressv<EOL>if minv>maxv: minv, maxv = maxv, minv<EOL>if self.direction == '<STR_LIT>':<EOL><INDENT>self.rect.set_x(minv)<EOL>self.rect.set_width(maxv-minv)<EOL><DEDENT>else:<EOL><INDENT>self.rect.set_y(minv)<EOL>self.rect.set_height(maxv-minv)<EOL><DEDENT>if self.onmove_callback is not None:<EOL><INDENT>vmin = self.pressv<EOL>if self.direction == '<STR_LIT>':<EOL><INDENT>vmax = event.xdata or self.prev[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>vmax = event.ydata or self.prev[<NUM_LIT:1>]<EOL><DEDENT>if vmin>vmax: vmin, vmax = vmax, vmin<EOL>self.onmove_callback(vmin, vmax)<EOL><DEDENT>self.update()<EOL>return False<EOL>


def __init__(self, ax, onselect, drawtype='<STR_LIT>',<EOL>minspanx=None, minspany=None, useblit=False,<EOL>lineprops=None, rectprops=None, spancoords='<STR_LIT:data>'):

self.ax = ax<EOL>self.visible = True<EOL>self.canvas = ax.figure.canvas<EOL>self.canvas.mpl_connect('<STR_LIT>', self.onmove)<EOL>self.canvas.mpl_connect('<STR_LIT>', self.press)<EOL>self.canvas.mpl_connect('<STR_LIT>', self.release)<EOL>self.canvas.mpl_connect('<STR_LIT>', self.update_background)<EOL>self.active = True                    <EOL>self.to_draw = None<EOL>self.background = None<EOL>if drawtype == '<STR_LIT:none>':<EOL><INDENT>drawtype = '<STR_LIT>'                        <EOL>self.visible = False                     <EOL><DEDENT>if drawtype == '<STR_LIT>':<EOL><INDENT>if rectprops is None:<EOL><INDENT>rectprops = dict(facecolor='<STR_LIT>', edgecolor = '<STR_LIT>',<EOL>alpha=<NUM_LIT:0.5>, fill=False)<EOL><DEDENT>self.rectprops = rectprops<EOL>self.to_draw = Rectangle((<NUM_LIT:0>,<NUM_LIT:0>), <NUM_LIT:0>, <NUM_LIT:1>,visible=False,**self.rectprops)<EOL>self.ax.add_patch(self.to_draw)<EOL><DEDENT>if drawtype == '<STR_LIT>':<EOL><INDENT>if lineprops is None:<EOL><INDENT>lineprops = dict(color='<STR_LIT>', linestyle='<STR_LIT:->',<EOL>linewidth = <NUM_LIT:2>, alpha=<NUM_LIT:0.5>)<EOL><DEDENT>self.lineprops = lineprops<EOL>self.to_draw = Line2D([<NUM_LIT:0>,<NUM_LIT:0>],[<NUM_LIT:0>,<NUM_LIT:0>],visible=False,**self.lineprops)<EOL>self.ax.add_line(self.to_draw)<EOL><DEDENT>self.onselect = onselect<EOL>self.useblit = useblit<EOL>self.minspanx = minspanx<EOL>self.minspany = minspany<EOL>assert(spancoords in ('<STR_LIT:data>', '<STR_LIT>'))<EOL>self.spancoords = spancoords<EOL>self.drawtype = drawtype<EOL>self.eventpress = None<EOL>self.eventrelease = None<EOL>

Create a selector in ax.  When a selection is made, clear
the span and call onselect with

  onselect(pos_1, pos_2)

and clear the drawn box/line. There pos_i are arrays of length 2
containing the x- and y-coordinate.

If minspanx is not None then events smaller than minspanx
in x direction are ignored(it's the same for y).

The rect is drawn with rectprops; default
  rectprops = dict(facecolor='red', edgecolor = 'black',
                   alpha=0.5, fill=False)

The line is drawn with lineprops; default
  lineprops = dict(color='black', linestyle='-',
                   linewidth = 2, alpha=0.5)

Use type if you want the mouse to draw a line, a box or nothing
between click and actual position ny setting

drawtype = 'line', drawtype='box' or drawtype = 'none'.

spancoords is one of 'data' or 'pixels'.  If 'data', minspanx
and minspanx will be interpreted in the same coordinates as
the x and ya axis, if 'pixels', they are in pixels


<EOL>if not self.active:<EOL><INDENT>return True<EOL><DEDENT>if not self.canvas.widgetlock.available(self):<EOL><INDENT>return True<EOL><DEDENT>if self.eventpress == None:<EOL><INDENT>return event.inaxes!= self.ax<EOL><DEDENT>return  (event.inaxes!=self.ax or<EOL>event.button != self.eventpress.button)<EOL>


<EOL>if self.ignore(event): return<EOL>self.to_draw.set_visible(self.visible)<EOL>self.eventpress = event<EOL>return False<EOL>


if self.eventpress is None or self.ignore(event): return<EOL>self.to_draw.set_visible(False)<EOL>self.canvas.draw()<EOL>self.eventrelease = event<EOL>if self.spancoords=='<STR_LIT:data>':<EOL><INDENT>xmin, ymin = self.eventpress.xdata, self.eventpress.ydata<EOL>xmax, ymax = self.eventrelease.xdata, self.eventrelease.ydata<EOL><DEDENT>elif self.spancoords=='<STR_LIT>':<EOL><INDENT>xmin, ymin = self.eventpress.x, self.eventpress.y<EOL>xmax, ymax = self.eventrelease.x, self.eventrelease.y<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if xmin>xmax: xmin, xmax = xmax, xmin<EOL>if ymin>ymax: ymin, ymax = ymax, ymin<EOL>spanx = xmax - xmin<EOL>spany = ymax - ymin<EOL>xproblems = self.minspanx is not None and spanx<self.minspanx<EOL>yproblems = self.minspany is not None and spany<self.minspany<EOL>if (self.drawtype=='<STR_LIT>')  and (xproblems or  yproblems):<EOL><INDENT>"""<STR_LIT>"""     <EOL>return                 <EOL><DEDENT>if (self.drawtype=='<STR_LIT>') and (xproblems and yproblems):<EOL><INDENT>"""<STR_LIT>"""    <EOL>return                 <EOL><DEDENT>self.onselect(self.eventpress, self.eventrelease)<EOL>self.eventpress = None                <EOL>self.eventrelease = None              <EOL>return False<EOL>


if self.useblit:<EOL><INDENT>if self.background is not None:<EOL><INDENT>self.canvas.restore_region(self.background)<EOL><DEDENT>self.ax.draw_artist(self.to_draw)<EOL>self.canvas.blit(self.ax.bbox)<EOL><DEDENT>else:<EOL><INDENT>self.canvas.draw_idle()<EOL><DEDENT>return False<EOL>


if self.eventpress is None or self.ignore(event): return<EOL>x,y = event.xdata, event.ydata            <EOL>if self.drawtype == '<STR_LIT>':<EOL><INDENT>minx, maxx = self.eventpress.xdata, x <EOL>miny, maxy = self.eventpress.ydata, y <EOL>if minx>maxx: minx, maxx = maxx, minx <EOL>if miny>maxy: miny, maxy = maxy, miny<EOL>self.to_draw.set_x(minx)             <EOL>self.to_draw.set_y(miny)<EOL>self.to_draw.set_width(maxx-minx)     <EOL>self.to_draw.set_height(maxy-miny)<EOL>self.update()<EOL>return False<EOL><DEDENT>if self.drawtype == '<STR_LIT>':<EOL><INDENT>self.to_draw.set_data([self.eventpress.xdata, x],<EOL>[self.eventpress.ydata, y])<EOL>self.update()<EOL>return False<EOL><DEDENT>

on motion notify event if box/line is wanted


self.active = active<EOL>

Use this to activate / deactivate the RectangleSelector

            from your program with an boolean variable 'active'.


return self.active<EOL>

to get status of active mode (boolean variable)


if os.path.exists(s): return s<EOL>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>'%s)<EOL><DEDENT>


if type(b) is str:<EOL><INDENT>b = b.lower()<EOL><DEDENT>if b in ('<STR_LIT:t>', '<STR_LIT:y>', '<STR_LIT:yes>', '<STR_LIT>', '<STR_LIT:true>', '<STR_LIT:1>', <NUM_LIT:1>, True): return True<EOL>elif b in ('<STR_LIT:f>', '<STR_LIT:n>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:false>', '<STR_LIT:0>', <NUM_LIT:0>, False): return False<EOL>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % b)<EOL><DEDENT>


if type(b) is str:<EOL><INDENT>b = b.lower()<EOL><DEDENT>if b=='<STR_LIT:none>': return None<EOL>if b in ('<STR_LIT:t>', '<STR_LIT:y>', '<STR_LIT:yes>', '<STR_LIT>', '<STR_LIT:true>', '<STR_LIT:1>', <NUM_LIT:1>, True): return True<EOL>elif b in ('<STR_LIT:f>', '<STR_LIT:n>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:false>', '<STR_LIT:0>', <NUM_LIT:0>, False): return False<EOL>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % b)<EOL><DEDENT>


try: return float(s)<EOL>except ValueError:<EOL><INDENT>raise ValueError('<STR_LIT>' % s)<EOL><DEDENT>


try: return int(s)<EOL>except ValueError:<EOL><INDENT>raise ValueError('<STR_LIT>' % s)<EOL><DEDENT>


fonttypes = { '<STR_LIT>':    <NUM_LIT:3>,<EOL>'<STR_LIT>': <NUM_LIT> }<EOL>try:<EOL><INDENT>fonttype = validate_int(s)<EOL><DEDENT>except ValueError:<EOL><INDENT>if s.lower() in list(fonttypes.keys()):<EOL><INDENT>return fonttypes[s.lower()]<EOL><DEDENT>raise ValueError('<STR_LIT>' % list(fonttypes.keys()))<EOL><DEDENT>else:<EOL><INDENT>if fonttype not in list(fonttypes.values()):<EOL><INDENT>raise ValueError('<STR_LIT>' % list(fonttypes.values()))<EOL><DEDENT>return fonttype<EOL><DEDENT>

confirm that this is a Postscript of PDF font type that we know how to convert to


if s.lower() == '<STR_LIT:none>':<EOL><INDENT>return '<STR_LIT:None>'<EOL><DEDENT>if is_color_like(s):<EOL><INDENT>return s<EOL><DEDENT>stmp = '<STR_LIT:#>' + s<EOL>if is_color_like(stmp):<EOL><INDENT>return stmp<EOL><DEDENT>colorarg = s<EOL>msg = '<STR_LIT>'<EOL>if s.find('<STR_LIT:U+002C>')>=<NUM_LIT:0>:<EOL><INDENT>stmp = '<STR_LIT>'.join([ c for c in s if c.isdigit() or c=='<STR_LIT:.>' or c=='<STR_LIT:U+002C>'])<EOL>vals = stmp.split('<STR_LIT:U+002C>')<EOL>if len(vals)!=<NUM_LIT:3>:<EOL><INDENT>msg = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>colorarg = [float(val) for val in vals]<EOL><DEDENT>except ValueError:<EOL><INDENT>msg = '<STR_LIT>'<EOL><DEDENT><DEDENT><DEDENT>if not msg and is_color_like(colorarg):<EOL><INDENT>return colorarg<EOL><DEDENT>raise ValueError('<STR_LIT>'%(s, msg))<EOL>


if type(s) is str:<EOL><INDENT>return [ v.strip() for v in s.split('<STR_LIT:U+002C>') ]<EOL><DEDENT>else:<EOL><INDENT>assert type(s) in [list,tuple]<EOL>return [ str(v) for v in s ]<EOL><DEDENT>


def __init__(self, key, valid, ignorecase=False):

self.key = key<EOL>self.ignorecase = ignorecase<EOL>def func(s):<EOL><INDENT>if ignorecase: return s.lower()<EOL>else: return s<EOL><DEDENT>self.valid = dict([(func(k),k) for k in valid])<EOL>


if type(s) is str:<EOL><INDENT>ss = s.split('<STR_LIT:U+002C>')<EOL>if len(ss) != self.n:<EOL><INDENT>raise ValueError('<STR_LIT>'%self.n)<EOL><DEDENT>try:<EOL><INDENT>return [float(val) for val in ss]<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>assert type(s) in (list,tuple)<EOL>if len(s) != self.n:<EOL><INDENT>raise ValueError('<STR_LIT>'%self.n)<EOL><DEDENT>return [float(val) for val in s]<EOL><DEDENT>


if type(s) is str:<EOL><INDENT>ss = s.split('<STR_LIT:U+002C>')<EOL>if len(ss) != self.n:<EOL><INDENT>raise ValueError('<STR_LIT>'%self.n)<EOL><DEDENT>try:<EOL><INDENT>return [int(val) for val in ss]<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>assert type(s) in (list,tuple)<EOL>if len(s) != self.n:<EOL><INDENT>raise ValueError('<STR_LIT>'%self.n)<EOL><DEDENT>return [int(val) for val in s]<EOL><DEDENT>


return np.sqrt(np.dot(x,x))<EOL>


return np.hanning(len(x))*x<EOL>

return x times the hanning window of len(x)


return x<EOL>


warnings.warn("<STR_LIT>", DeprecationWarning)<EOL>return np.convolve(x,y,mode)<EOL>


x = np.asarray(x)<EOL>if axis:<EOL><INDENT>ind = [slice(None)] * axis<EOL>ind.append(np.newaxis)<EOL>return x - x.mean(axis)[ind]<EOL><DEDENT>return x - x.mean(axis)<EOL>

Return x minus its mean along the specified axis


return x - x.mean()<EOL>


<EOL>x = np.arange(len(y), dtype=np.float_)<EOL>C = np.cov(x, y, bias=<NUM_LIT:1>)<EOL>b = C[<NUM_LIT:0>,<NUM_LIT:1>]/C[<NUM_LIT:0>,<NUM_LIT:0>]<EOL>a = y.mean() - b*x.mean()<EOL>return y - (b*x + a)<EOL>

Return y minus best fit line; 'linear' detrending


def psd(x, NFFT=<NUM_LIT>, Fs=<NUM_LIT:2>, detrend=detrend_none, window=window_hanning,<EOL>noverlap=<NUM_LIT:0>, pad_to=None, sides='<STR_LIT:default>', scale_by_freq=None):

Pxx,freqs = csd(x, x, NFFT, Fs, detrend, window, noverlap, pad_to, sides,<EOL>scale_by_freq)<EOL>return Pxx.real,freqs<EOL>

The power spectral density by Welch's average periodogram method.
The vector *x* is divided into *NFFT* length blocks.  Each block
is detrended by the function *detrend* and windowed by the function
*window*.  *noverlap* gives the length of the overlap between blocks.
The absolute(fft(block))**2 of each segment are averaged to compute
*Pxx*, with a scaling to correct for power loss due to windowing.

If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.

*x*
    Array or sequence containing the data
%(PSD)s
Returns the tuple (*Pxx*, *freqs*).

Refs:
    Bendat & Piersol -- Random Data: Analysis and Measurement
    Procedures, John Wiley & Sons (1986)


def csd(x, y, NFFT=<NUM_LIT>, Fs=<NUM_LIT:2>, detrend=detrend_none, window=window_hanning,<EOL>noverlap=<NUM_LIT:0>, pad_to=None, sides='<STR_LIT:default>', scale_by_freq=None):

Pxy, freqs, t = _spectral_helper(x, y, NFFT, Fs, detrend, window,<EOL>noverlap, pad_to, sides, scale_by_freq)<EOL>if len(Pxy.shape) == <NUM_LIT:2> and Pxy.shape[<NUM_LIT:1>]><NUM_LIT:1>:<EOL><INDENT>Pxy = Pxy.mean(axis=<NUM_LIT:1>)<EOL><DEDENT>return Pxy, freqs<EOL>

The cross power spectral density by Welch's average periodogram
method.  The vectors *x* and *y* are divided into *NFFT* length
blocks.  Each block is detrended by the function *detrend* and
windowed by the function *window*.  *noverlap* gives the length
of the overlap between blocks.  The product of the direct FFTs
of *x* and *y* are averaged over each segment to compute *Pxy*,
with a scaling to correct for power loss due to windowing.

If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero
padded to *NFFT*.

*x*, *y*
    Array or sequence containing the data
%(PSD)s
Returns the tuple (*Pxy*, *freqs*).

Refs:
    Bendat & Piersol -- Random Data: Analysis and Measurement
    Procedures, John Wiley & Sons (1986)


def specgram(x, NFFT=<NUM_LIT>, Fs=<NUM_LIT:2>, detrend=detrend_none, window=window_hanning,<EOL>noverlap=<NUM_LIT>, pad_to=None, sides='<STR_LIT:default>', scale_by_freq=None):

assert(NFFT > noverlap)<EOL>Pxx, freqs, t = _spectral_helper(x, x, NFFT, Fs, detrend, window,<EOL>noverlap, pad_to, sides, scale_by_freq)<EOL>Pxx = Pxx.real <EOL>if (np.iscomplexobj(x) and sides == '<STR_LIT:default>') or sides == '<STR_LIT>':<EOL><INDENT>freqs = np.concatenate((freqs[NFFT/<NUM_LIT:2>:]-Fs,freqs[:NFFT/<NUM_LIT:2>]))<EOL>Pxx   = np.concatenate((Pxx[NFFT/<NUM_LIT:2>:,:],Pxx[:NFFT/<NUM_LIT:2>,:]),<NUM_LIT:0>)<EOL><DEDENT>return Pxx, freqs, t<EOL>

Compute a spectrogram of data in *x*.  Data are split into *NFFT*
length segements and the PSD of each section is computed.  The
windowing function *window* is applied to each segment, and the
amount of overlap of each segment is specified with *noverlap*.

If *x* is real (i.e. non-complex) only the spectrum of the positive
frequencie is returned.  If *x* is complex then the complete
spectrum is returned.
%(PSD)s
Returns a tuple (*Pxx*, *freqs*, *t*):

     - *Pxx*: 2-D array, columns are the periodograms of
       successive segments

     - *freqs*: 1-D array of frequencies corresponding to the rows
       in Pxx

     - *t*: 1-D array of times corresponding to midpoints of
       segments.

.. seealso::
    :func:`psd`:
        :func:`psd` differs in the default overlap; in returning
        the mean of the segment periodograms; and in not returning
        times.


def cohere(x, y, NFFT=<NUM_LIT>, Fs=<NUM_LIT:2>, detrend=detrend_none, window=window_hanning,<EOL>noverlap=<NUM_LIT:0>, pad_to=None, sides='<STR_LIT:default>', scale_by_freq=None):

if len(x)<<NUM_LIT:2>*NFFT:<EOL><INDENT>raise ValueError(_coh_error)<EOL><DEDENT>Pxx, f = psd(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides,<EOL>scale_by_freq)<EOL>Pyy, f = psd(y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,<EOL>scale_by_freq)<EOL>Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,<EOL>scale_by_freq)<EOL>Cxy = np.divide(np.absolute(Pxy)**<NUM_LIT:2>, Pxx*Pyy)<EOL>Cxy.shape = (len(f),)<EOL>return Cxy, f<EOL>

The coherence between *x* and *y*.  Coherence is the normalized
cross spectral density:

.. math::

    C_{xy} = \\frac{|P_{xy}|^2}{P_{xx}P_{yy}}

*x*, *y*
    Array or sequence containing the data
%(PSD)s
The return value is the tuple (*Cxy*, *f*), where *f* are the
frequencies of the coherence vector. For cohere, scaling the
individual densities by the sampling frequency has no effect, since
the factors cancel out.

.. seealso::
    :func:`psd` and :func:`csd`:
        For information about the methods used to compute
        :math:`P_{xy}`, :math:`P_{xx}` and :math:`P_{yy}`.


warnings.warn("<STR_LIT>", DeprecationWarning)<EOL>kw = dict(rowvar=False)<EOL>return np.corrcoef(*args, **kw)<EOL>

corrcoef(*X*) where *X* is a matrix returns a matrix of correlation
coefficients for the columns of *X*

corrcoef(*x*, *y*) where *x* and *y* are vectors returns the matrix of
correlation coefficients for *x* and *y*.

Numpy arrays can be real or complex.

The correlation matrix is defined from the covariance matrix *C*
as

.. math::

  r_{ij} = \\frac{C_{ij}}{\\sqrt{C_{ii}C_{jj}}}


warnings.warn("<STR_LIT>", DeprecationWarning)<EOL>return np.polyfit(*args, **kwargs)<EOL>

polyfit(*x*, *y*, *N*)

Do a best fit polynomial of order *N* of *y* to *x*.  Return value
is a vector of polynomial coefficients [pk ... p1 p0].  Eg, for
*N*=2::

  p2*x0^2 +  p1*x0 + p0 = y1
  p2*x1^2 +  p1*x1 + p0 = y1
  p2*x2^2 +  p1*x2 + p0 = y2
  .....
  p2*xk^2 +  p1*xk + p0 = yk

Method: if *X* is a the Vandermonde Matrix computed from *x* (see
`vandermonds
<http://mathworld.wolfram.com/VandermondeMatrix.html>`_), then the
polynomial least squares solution is given by the '*p*' in

  X*p = y

where *X* is a (len(*x*) \N{MULTIPLICATION SIGN} *N* + 1) matrix,
*p* is a *N*+1 length vector, and *y* is a (len(*x*)
\N{MULTIPLICATION SIGN} 1) vector.

This equation can be solved as

.. math::

  p = (X_t X)^-1 X_t y

where :math:`X_t` is the transpose of *X* and -1 denotes the
inverse.  Numerically, however, this is not a good method, so we
use :func:`numpy.linalg.lstsq`.

For more info, see `least squares fitting
<http://mathworld.wolfram.com/LeastSquaresFittingPolynomial.html>`_,
but note that the *k*'s and *n*'s in the superscripts and
subscripts on that page.  The linear algebra is correct, however.

.. seealso::
    :func:`polyval`


warnings.warn("<STR_LIT>", DeprecationWarning)<EOL>return np.polyval(*args, **kwargs)<EOL>

*y* = polyval(*p*, *x*)

*p* is a vector of polynomial coeffients and *y* is the polynomial
evaluated at *x*.

Example code to remove a polynomial (quadratic) trend from y::

  p = polyfit(x, y, 2)
  trend = polyval(p, x)
  resid = y - trend

.. seealso::
    :func:`polyfit`


warnings.warn("<STR_LIT>", DeprecationWarning)<EOL>return np.vander(*args, **kwargs)<EOL>

*X* = vander(*x*, *N* = *None*)

The Vandermonde matrix of vector *x*.  The *i*-th column of *X* is the
the *i*-th power of *x*.  *N* is the maximum power to compute; if *N* is
*None* it defaults to len(*x*).


def cohere_pairs( X, ij, NFFT=<NUM_LIT>, Fs=<NUM_LIT:2>, detrend=detrend_none,<EOL>window=window_hanning, noverlap=<NUM_LIT:0>,<EOL>preferSpeedOverMemory=True,<EOL>progressCallback=donothing_callback,<EOL>returnPxx=False):

numRows, numCols = X.shape<EOL>if numRows < NFFT:<EOL><INDENT>tmp = X<EOL>X = np.zeros( (NFFT, numCols), X.dtype)<EOL>X[:numRows,:] = tmp<EOL>del tmp<EOL><DEDENT>numRows, numCols = X.shape<EOL>seen = {}<EOL>for i,j in ij:<EOL><INDENT>seen[i]=<NUM_LIT:1>; seen[j] = <NUM_LIT:1><EOL><DEDENT>allColumns = list(seen.keys())<EOL>Ncols = len(allColumns)<EOL>del seen<EOL>if np.iscomplexobj(X): numFreqs = NFFT<EOL>else: numFreqs = NFFT//<NUM_LIT:2>+<NUM_LIT:1><EOL>if cbook.iterable(window):<EOL><INDENT>assert(len(window) == NFFT)<EOL>windowVals = window<EOL><DEDENT>else:<EOL><INDENT>windowVals = window(np.ones((NFFT,), typecode(X)))<EOL><DEDENT>ind = list(range(<NUM_LIT:0>, numRows-NFFT+<NUM_LIT:1>, NFFT-noverlap))<EOL>numSlices = len(ind)<EOL>FFTSlices = {}<EOL>FFTConjSlices = {}<EOL>Pxx = {}<EOL>slices = list(range(numSlices))<EOL>normVal = norm(windowVals)**<NUM_LIT:2><EOL>for iCol in allColumns:<EOL><INDENT>progressCallback(i/Ncols, '<STR_LIT>')<EOL>Slices = np.zeros( (numSlices,numFreqs), dtype=np.complex_)<EOL>for iSlice in slices:<EOL><INDENT>thisSlice = X[ind[iSlice]:ind[iSlice]+NFFT, iCol]<EOL>thisSlice = windowVals*detrend(thisSlice)<EOL>Slices[iSlice,:] = fft(thisSlice)[:numFreqs]<EOL><DEDENT>FFTSlices[iCol] = Slices<EOL>if preferSpeedOverMemory:<EOL><INDENT>FFTConjSlices[iCol] = conjugate(Slices)<EOL><DEDENT>Pxx[iCol] = np.divide(np.mean(absolute(Slices)**<NUM_LIT:2>), normVal)<EOL><DEDENT>del Slices, ind, windowVals<EOL>Cxy = {}<EOL>Phase = {}<EOL>count = <NUM_LIT:0><EOL>N = len(ij)<EOL>for i,j in ij:<EOL><INDENT>count +=<NUM_LIT:1><EOL>if count%<NUM_LIT:10>==<NUM_LIT:0>:<EOL><INDENT>progressCallback(count/N, '<STR_LIT>')<EOL><DEDENT>if preferSpeedOverMemory:<EOL><INDENT>Pxy = FFTSlices[i] * FFTConjSlices[j]<EOL><DEDENT>else:<EOL><INDENT>Pxy = FFTSlices[i] * np.conjugate(FFTSlices[j])<EOL><DEDENT>if numSlices><NUM_LIT:1>: Pxy = np.mean(Pxy)<EOL>Pxy = np.divide(Pxy, normVal)<EOL>Cxy[(i,j)] = np.divide(np.absolute(Pxy)**<NUM_LIT:2>, Pxx[i]*Pxx[j])<EOL>Phase[(i,j)] =  np.arctan2(Pxy.imag, Pxy.real)<EOL><DEDENT>freqs = Fs/NFFT*np.arange(numFreqs)<EOL>if returnPxx:<EOL><INDENT>return Cxy, Phase, freqs, Pxx<EOL><DEDENT>else:<EOL><INDENT>return Cxy, Phase, freqs<EOL><DEDENT>

Cxy, Phase, freqs = cohere_pairs(X, ij, ...)

Compute the coherence for all pairs in *ij*.  *X* is a
(*numSamples*, *numCols*) numpy array.  *ij* is a list of tuples
(*i*, *j*).  Each tuple is a pair of indexes into the columns of *X*
for which you want to compute coherence.  For example, if *X* has 64
columns, and you want to compute all nonredundant pairs, define *ij*
as::

  ij = []
  for i in range(64):
      for j in range(i+1,64):
          ij.append( (i, j) )

The other function arguments, except for *preferSpeedOverMemory*
(see below), are explained in the help string of :func:`psd`.

Return value is a tuple (*Cxy*, *Phase*, *freqs*).

  - *Cxy*: a dictionary of (*i*, *j*) tuples -> coherence vector for that
    pair.  I.e., ``Cxy[(i,j)] = cohere(X[:,i], X[:,j])``.  Number of
    dictionary keys is ``len(ij)``.

  - *Phase*: a dictionary of phases of the cross spectral density at
    each frequency for each pair.  The keys are ``(i,j)``.

  - *freqs*: a vector of frequencies, equal in length to either
    the coherence or phase vectors for any (*i*, *j*) key..  Eg,
    to make a coherence Bode plot::

      subplot(211)
      plot( freqs, Cxy[(12,19)])
      subplot(212)
      plot( freqs, Phase[(12,19)])

For a large number of pairs, :func:`cohere_pairs` can be much more
efficient than just calling :func:`cohere` for each pair, because
it caches most of the intensive computations.  If *N* is the
number of pairs, this function is O(N) for most of the heavy
lifting, whereas calling cohere for each pair is
O(N\N{SUPERSCRIPT TWO}).  However, because of the caching, it is
also more memory intensive, making 2 additional complex arrays
with approximately the same number of elements as *X*.

The parameter *preferSpeedOverMemory*, if *False*, limits the
caching by only making one, rather than two, complex cache arrays.
This is useful if memory becomes critical.  Even when
*preferSpeedOverMemory* is *False*, :func:`cohere_pairs` will
still give significant performace gains over calling
:func:`cohere` for each pair, and will use subtantially less
memory than if *preferSpeedOverMemory* is *True*.  In my tests
with a (43000, 64) array over all non-redundant pairs,
*preferSpeedOverMemory* = *True* delivered a 33% performace boost
on a 1.7GHZ Athlon with 512MB RAM compared with
*preferSpeedOverMemory* = *False*.  But both solutions were more
than 10x faster than naievly crunching all possible pairs through
cohere.

.. seealso::
    :file:`test/cohere_pairs_test.py` in the src tree:
        For an example script that shows that this
        :func:`cohere_pairs` and :func:`cohere` give the same
        results for a given pair.


n,bins = np.histogram(y, bins)<EOL>n = n.astype(np.float_)<EOL>n = np.take(n, np.nonzero(n)[<NUM_LIT:0>])         <EOL>p = np.divide(n, len(y))<EOL>delta = bins[<NUM_LIT:1>]-bins[<NUM_LIT:0>]<EOL>S = -<NUM_LIT:1.0>*np.sum(p*log(p)) + log(delta)<EOL>return S<EOL>

r"""
    Return the entropy of the data in *y*.

    .. math::

      \sum p_i \log_2(p_i)

    where :math:`p_i` is the probability of observing *y* in the
    :math:`i^{th}` bin of *bins*.  *bins* can be a number of bins or a
    range of bins; see :func:`numpy.histogram`.

    Compare *S* with analytic calculation for a Gaussian::

      x = mu + sigma * randn(200000)
      Sanalytic = 0.5 * ( 1.0 + log(2*pi*sigma**2.0) )


def hist(y, bins=<NUM_LIT:10>, normed=<NUM_LIT:0>):

warnings.warn("<STR_LIT>", DeprecationWarning)<EOL>return np.histogram(y, bins=bins, range=None, normed=normed)<EOL>

Return the histogram of *y* with *bins* equally sized bins.  If
bins is an array, use those bins.  Return value is (*n*, *x*)
where *n* is the count for each bin in *x*.

If *normed* is *False*, return the counts in the first element of
the returned tuple.  If *normed* is *True*, return the probability
density :math:`\\frac{n}{(len(y)\mathrm{dbin}}`.

If *y* has rank > 1, it will be raveled.  If *y* is masked, only the
unmasked values will be used.

Credits: the Numeric 22 documentation


mu, sigma = args<EOL>return <NUM_LIT:1.>/(np.sqrt(<NUM_LIT:2>*np.pi)*sigma)*np.exp(-<NUM_LIT:0.5> * (<NUM_LIT:1.>/sigma*(x - mu))**<NUM_LIT:2>)<EOL>

Return the normal pdf evaluated at *x*; args provides *mu*, *sigma*


N = len(x)<EOL>if N%<NUM_LIT:2> != <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' +'<STR_LIT>')<EOL><DEDENT>dx = x[<NUM_LIT:1>]-x[<NUM_LIT:0>]<EOL>f = <NUM_LIT:1>/(N*dx)*np.arange(-N/<NUM_LIT:2>, N/<NUM_LIT:2>, np.float_)<EOL>ind = np.concatenate([np.arange(N/<NUM_LIT:2>, N, int),<EOL>np.arange(<NUM_LIT:0>, N/<NUM_LIT:2>, int)])<EOL>df = f[<NUM_LIT:1>]-f[<NUM_LIT:0>]<EOL>cfl = exp(-gamma*np.absolute(<NUM_LIT:2>*pi*f)**alpha)<EOL>px = np.fft.fft(np.take(cfl,ind)*df).astype(np.float_)<EOL>return np.take(px, ind)<EOL>

Returm the levy pdf evaluated at *x* for params *gamma*, *alpha*


res, = np.nonzero(np.ravel(condition))<EOL>return res<EOL>

Return the indices where ravel(condition) is true


warnings.warn("<STR_LIT>", DeprecationWarning)<EOL>return np.trapz(y, x)<EOL>


x = np.ravel(x)<EOL>if len(x)==<NUM_LIT:0>:<EOL><INDENT>return np.array([])<EOL><DEDENT>ind = (x==<NUM_LIT:0>).nonzero()[<NUM_LIT:0>]<EOL>if len(ind)==<NUM_LIT:0>:<EOL><INDENT>return np.arange(len(x))<EOL><DEDENT>if len(ind)==len(x):<EOL><INDENT>return np.array([])<EOL><DEDENT>y = np.zeros( (len(x)+<NUM_LIT:2>,), x.dtype)<EOL>y[<NUM_LIT:1>:-<NUM_LIT:1>] = x<EOL>dif = np.diff(y)<EOL>up = (dif ==  <NUM_LIT:1>).nonzero()[<NUM_LIT:0>];<EOL>dn = (dif == -<NUM_LIT:1>).nonzero()[<NUM_LIT:0>];<EOL>i = (dn-up == max(dn - up)).nonzero()[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>ind = np.arange(up[i], dn[i])<EOL>return ind<EOL>

Return the indices of the longest stretch of contiguous ones in *x*,
assuming *x* is a vector of zeros and ones.  If there are two
equally long stretches, pick the first.


return longest_contiguous_ones(x)<EOL>


U,s,v = np.linalg.svd(P)<EOL>varEach = s**<NUM_LIT:2>/P.shape[<NUM_LIT:1>]<EOL>totVar = varEach.sum()<EOL>fracVar = varEach/totVar<EOL>ind = slice((fracVar>=frac).sum())<EOL>Trans = U[:,ind].transpose()<EOL>Pcomponents = np.dot(Trans,P)<EOL>return Pcomponents, Trans, fracVar[ind]<EOL>

Compute the principal components of *P*.  *P* is a (*numVars*,
*numObs*) array.  *frac* is the minimum fraction of variance that a
component must contain to be included.

Return value is a tuple of the form (*Pcomponents*, *Trans*,
*fracVar*) where:

  - *Pcomponents* : a (numVars, numObs) array

  - *Trans* : the weights matrix, ie, *Pcomponents* = *Trans* *
     *P*

  - *fracVar* : the fraction of the variance accounted for by each
     component returned

A similar function of the same name was in the Matlab (TM)
R13 Neural Network Toolbox but is not found in later versions;
its successor seems to be called "processpcs".


def prctile(x, p = (<NUM_LIT:0.0>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>)):

x = np.array(x).ravel()  <EOL>x.sort()<EOL>Nx = len(x)<EOL>if not cbook.iterable(p):<EOL><INDENT>return x[int(p*Nx/<NUM_LIT>)]<EOL><DEDENT>p = np.asarray(p)* Nx/<NUM_LIT><EOL>ind = p.astype(int)<EOL>ind = np.where(ind>=Nx, Nx-<NUM_LIT:1>, ind)<EOL>return x.take(ind)<EOL>

Return the percentiles of *x*.  *p* can either be a sequence of
percentile values or a scalar.  If *p* is a sequence, the ith
element of the return sequence is the *p*(i)-th percentile of *x*.
If *p* is a scalar, the largest value of *x* less than or equal to
the *p* percentage point in the sequence is returned.


if not cbook.iterable(p):<EOL><INDENT>p = np.arange(<NUM_LIT>/p, <NUM_LIT>, <NUM_LIT>/p)<EOL><DEDENT>else:<EOL><INDENT>p = np.asarray(p)<EOL><DEDENT>if p.max()<=<NUM_LIT:1> or p.min()<<NUM_LIT:0> or p.max()><NUM_LIT:100>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>ptiles = prctile(x, p)<EOL>return np.searchsorted(ptiles, x)<EOL>

Return the rank for each element in *x*, return the rank
0..len(*p*).  Eg if *p* = (25, 50, 75), the return value will be a
len(*x*) array with values in [0,1,2,3] where 0 indicates the
value is less than the 25th percentile, 1 indicates the value is
>= the 25th and < 50th percentile, ... and 3 indicates the value
is above the 75th percentile cutoff.

*p* is either an array of percentiles in [0..100] or a scalar which
indicates how many quantiles of data you want ranked.


M = np.asarray(M, np.float_)<EOL>if dim:<EOL><INDENT>M = (M - M.mean(axis=<NUM_LIT:0>)) / M.std(axis=<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>M = (M - M.mean(axis=<NUM_LIT:1>)[:,np.newaxis])<EOL>M = M / M.std(axis=<NUM_LIT:1>)[:,np.newaxis]<EOL><DEDENT>return M<EOL>

Return the matrix *M* with each row having zero mean and unit std.

If *dim* = 1 operate on columns instead of rows.  (*dim* is
opposite to the numpy axis kwarg.)


try: Ny = len(y0)<EOL>except TypeError:<EOL><INDENT>yout = np.zeros( (len(t),), np.float_)<EOL><DEDENT>else:<EOL><INDENT>yout = np.zeros( (len(t), Ny), np.float_)<EOL><DEDENT>yout[<NUM_LIT:0>] = y0<EOL>i = <NUM_LIT:0><EOL>for i in np.arange(len(t)-<NUM_LIT:1>):<EOL><INDENT>thist = t[i]<EOL>dt = t[i+<NUM_LIT:1>] - thist<EOL>dt2 = dt/<NUM_LIT><EOL>y0 = yout[i]<EOL>k1 = np.asarray(derivs(y0, thist))<EOL>k2 = np.asarray(derivs(y0 + dt2*k1, thist+dt2))<EOL>k3 = np.asarray(derivs(y0 + dt2*k2, thist+dt2))<EOL>k4 = np.asarray(derivs(y0 + dt*k3, thist+dt))<EOL>yout[i+<NUM_LIT:1>] = y0 + dt/<NUM_LIT>*(k1 + <NUM_LIT:2>*k2 + <NUM_LIT:2>*k3 + k4)<EOL><DEDENT>return yout<EOL>

Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta.
This is a toy implementation which may be useful if you find
yourself stranded on a system w/o scipy.  Otherwise use
:func:`scipy.integrate`.

*y0*
    initial state vector

*t*
    sample times

*derivs*
    returns the derivative of the system and has the
    signature ``dy = derivs(yi, ti)``

Example 1 ::

    ## 2D system

    def derivs6(x,t):
        d1 =  x[0] + 2*x[1]
        d2 =  -3*x[0] + 4*x[1]
        return (d1, d2)
    dt = 0.0005
    t = arange(0.0, 2.0, dt)
    y0 = (1,2)
    yout = rk4(derivs6, y0, t)

Example 2::

    ## 1D system
    alpha = 2
    def derivs(x,t):
        return -alpha*x + exp(-t)

    y0 = 1
    yout = rk4(derivs, y0, t)

If you have access to scipy, you should probably be using the
scipy.integrate tools rather than this function.


def bivariate_normal(X, Y, sigmax=<NUM_LIT:1.0>, sigmay=<NUM_LIT:1.0>,<EOL>mux=<NUM_LIT:0.0>, muy=<NUM_LIT:0.0>, sigmaxy=<NUM_LIT:0.0>):

Xmu = X-mux<EOL>Ymu = Y-muy<EOL>rho = sigmaxy/(sigmax*sigmay)<EOL>z = Xmu**<NUM_LIT:2>/sigmax**<NUM_LIT:2> + Ymu**<NUM_LIT:2>/sigmay**<NUM_LIT:2> - <NUM_LIT:2>*rho*Xmu*Ymu/(sigmax*sigmay)<EOL>denom = <NUM_LIT:2>*np.pi*sigmax*sigmay*np.sqrt(<NUM_LIT:1>-rho**<NUM_LIT:2>)<EOL>return np.exp( -z/(<NUM_LIT:2>*(<NUM_LIT:1>-rho**<NUM_LIT:2>))) / denom<EOL>

Bivariate Gaussian distribution for equal shape *X*, *Y*.

See `bivariate normal
<http://mathworld.wolfram.com/BivariateNormalDistribution.html>`_
at mathworld.


X,Y = np.indices(Z.shape)<EOL>return X[Cond], Y[Cond], Z[Cond]<EOL>

*Z* and *Cond* are *M* x *N* matrices.  *Z* are data and *Cond* is
a boolean matrix where some condition is satisfied.  Return value
is (*x*, *y*, *z*) where *x* and *y* are the indices into *Z* and
*z* are the values of *Z* at those indices.  *x*, *y*, and *z* are
1D arrays.