def pie(self, x, explode=None, labels=None, colors=None,<EOL>autopct=None, pctdistance=<NUM_LIT>, shadow=False,<EOL>labeldistance=<NUM_LIT>):

self.set_frame_on(False)<EOL>x = np.asarray(x).astype(np.float32)<EOL>sx = float(x.sum())<EOL>if sx><NUM_LIT:1>: x = np.divide(x,sx)<EOL>if labels is None: labels = ['<STR_LIT>']*len(x)<EOL>if explode is None: explode = [<NUM_LIT:0>]*len(x)<EOL>assert(len(x)==len(labels))<EOL>assert(len(x)==len(explode))<EOL>if colors is None: colors = ('<STR_LIT:b>', '<STR_LIT:g>', '<STR_LIT:r>', '<STR_LIT:c>', '<STR_LIT:m>', '<STR_LIT:y>', '<STR_LIT:k>', '<STR_LIT:w>')<EOL>center = <NUM_LIT:0>,<NUM_LIT:0><EOL>radius = <NUM_LIT:1><EOL>theta1 = <NUM_LIT:0><EOL>i = <NUM_LIT:0><EOL>texts = []<EOL>slices = []<EOL>autotexts = []<EOL>for frac, label, expl in cbook.safezip(x,labels, explode):<EOL><INDENT>x, y = center<EOL>theta2 = theta1 + frac<EOL>thetam = <NUM_LIT:2>*math.pi*<NUM_LIT:0.5>*(theta1+theta2)<EOL>x += expl*math.cos(thetam)<EOL>y += expl*math.sin(thetam)<EOL>w = mpatches.Wedge((x,y), radius, <NUM_LIT>*theta1, <NUM_LIT>*theta2,<EOL>facecolor=colors[i%len(colors)])<EOL>slices.append(w)<EOL>self.add_patch(w)<EOL>w.set_label(label)<EOL>if shadow:<EOL><INDENT>shad = mpatches.Shadow(w, -<NUM_LIT>, -<NUM_LIT>,<EOL>)<EOL>shad.set_zorder(<NUM_LIT>*w.get_zorder())<EOL>self.add_patch(shad)<EOL><DEDENT>xt = x + labeldistance*radius*math.cos(thetam)<EOL>yt = y + labeldistance*radius*math.sin(thetam)<EOL>label_alignment = xt > <NUM_LIT:0> and '<STR_LIT:left>' or '<STR_LIT:right>'<EOL>t = self.text(xt, yt, label,<EOL>size=rcParams['<STR_LIT>'],<EOL>horizontalalignment=label_alignment,<EOL>verticalalignment='<STR_LIT>')<EOL>texts.append(t)<EOL>if autopct is not None:<EOL><INDENT>xt = x + pctdistance*radius*math.cos(thetam)<EOL>yt = y + pctdistance*radius*math.sin(thetam)<EOL>if is_string_like(autopct):<EOL><INDENT>s = autopct%(<NUM_LIT>*frac)<EOL><DEDENT>elif callable(autopct):<EOL><INDENT>s = autopct(<NUM_LIT>*frac)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>')<EOL><DEDENT>t = self.text(xt, yt, s,<EOL>horizontalalignment='<STR_LIT>',<EOL>verticalalignment='<STR_LIT>')<EOL>autotexts.append(t)<EOL><DEDENT>theta1 = theta2<EOL>i += <NUM_LIT:1><EOL><DEDENT>self.set_xlim((-<NUM_LIT>, <NUM_LIT>))<EOL>self.set_ylim((-<NUM_LIT>, <NUM_LIT>))<EOL>self.set_xticks([])<EOL>self.set_yticks([])<EOL>if autopct is None: return slices, texts<EOL>else: return slices, texts, autotexts<EOL>

r"""
        call signature::

          pie(x, explode=None, labels=None,
              colors=('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'),
              autopct=None, pctdistance=0.6, labeldistance=1.1, shadow=False)

        Make a pie chart of array *x*.  The fractional area of each
        wedge is given by x/sum(x).  If sum(x) <= 1, then the values
        of x give the fractional area directly and the array will not
        be normalized.

        Keyword arguments:

          *explode*: [ None | len(x) sequence ]
            If not *None*, is a len(*x*) array which specifies the
            fraction of the radius with which to offset each wedge.

          *colors*: [ None | color sequence ]
            A sequence of matplotlib color args through which the pie chart
            will cycle.

          *labels*: [ None | len(x) sequence of strings ]
            A sequence of strings providing the labels for each wedge

          *autopct*: [ None | format string | format function ]
            If not *None*, is a string or function used to label the
            wedges with their numeric value.  The label will be placed inside
            the wedge.  If it is a format string, the label will be ``fmt%pct``.
            If it is a function, it will be called.

          *pctdistance*: scalar
            The ratio between the center of each pie slice and the
            start of the text generated by *autopct*.  Ignored if
            *autopct* is *None*; default is 0.6.

          *labeldistance*: scalar
            The radial distance at which the pie labels are drawn

          *shadow*: [ False | True ]
            Draw a shadow beneath the pie.

        The pie chart will probably look best if the figure and axes are
        square.  Eg.::

          figure(figsize=(8,8))
          ax = axes([0.1, 0.1, 0.8, 0.8])

        Return value:
          If *autopct* is None, return the tuple (*patches*, *texts*):

            - *patches* is a sequence of
              :class:`matplotlib.patches.Wedge` instances

            - *texts* is a list of the label
              :class:`matplotlib.text.Text` instances.

          If *autopct* is not *None*, return the tuple (*patches*,
          *texts*, *autotexts*), where *patches* and *texts* are as
          above, and *autotexts* is a list of
          :class:`~matplotlib.text.Text` instances for the numeric
          labels.


return self._cursorProps<EOL>

return the cursor propertiess as a (*linewidth*, *color*)
tuple, where *linewidth* is a float and *color* is an RGBA
tuple


self.axison = True<EOL>


def __init__(self, fig, *args, **kwargs):

self.figure = fig<EOL>if len(args)==<NUM_LIT:1>:<EOL><INDENT>s = str(args[<NUM_LIT:0>])<EOL>if len(s) != <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>rows, cols, num = list(map(int, s))<EOL><DEDENT>elif len(args)==<NUM_LIT:3>:<EOL><INDENT>rows, cols, num = args<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(  '<STR_LIT>')<EOL><DEDENT>total = rows*cols<EOL>num -= <NUM_LIT:1>    <EOL>if num >= total:<EOL><INDENT>raise ValueError( '<STR_LIT>')<EOL><DEDENT>self._rows = rows<EOL>self._cols = cols<EOL>self._num = num<EOL>self.update_params()<EOL>self._axes_class.__init__(self, fig, self.figbox, **kwargs)<EOL>

*fig* is a :class:`matplotlib.figure.Figure` instance.

*args* is the tuple (*numRows*, *numCols*, *plotNum*), where
the array of subplots in the figure has dimensions *numRows*,
*numCols*, and where *plotNum* is the number of the subplot
being created.  *plotNum* starts at 1 in the upper left
corner and increases to the right.

If *numRows* <= *numCols* <= *plotNum* < 10, *args* can be the
decimal integer *numRows* * 100 + *numCols* * 10 + *plotNum*.


return self._shared_x_axes<EOL>

Return a copy of the shared axes Grouper object for x axes


self.xaxis = maxis.XAxis(self)<EOL>self.yaxis = maxis.YAxis(self)<EOL>self._update_transScale()<EOL>

move this out of __init__ because non-separable axes don't use it


if original:<EOL><INDENT>return self._originalPosition.frozen()<EOL><DEDENT>else:<EOL><INDENT>return self._position.frozen()<EOL><DEDENT>

Return the a copy of the axes rectangle as a Bbox


scalex = kwargs.pop( '<STR_LIT>', True)<EOL>scaley = kwargs.pop( '<STR_LIT>', True)<EOL>if not self._hold: self.cla()<EOL>lines = []<EOL>for line in self._get_lines(*args, **kwargs):<EOL><INDENT>self.add_line(line)<EOL>lines.append(line)<EOL><DEDENT>self.autoscale_view(scalex=scalex, scaley=scaley)<EOL>return lines<EOL>

Plot lines and/or markers to the
:class:`~matplotlib.axes.Axes`.  *args* is a variable length
argument, allowing for multiple *x*, *y* pairs with an
optional format string.  For example, each of the following is
legal::

    plot(x, y)         # plot x and y using default line style and color
    plot(x, y, 'bo')   # plot x and y using blue circle markers
    plot(y)            # plot y using x as index array 0..N-1
    plot(y, 'r+')      # ditto, but with red plusses

If *x* and/or *y* is 2-dimensional, then the corresponding columns
will be plotted.

An arbitrary number of *x*, *y*, *fmt* groups can be
specified, as in::

    a.plot(x1, y1, 'g^', x2, y2, 'g-')

Return value is a list of lines that were added.

The following format string characters are accepted to control
the line style or marker:

================    ===============================
character           description
================    ===============================
'-'                 solid line style
'--'                dashed line style
'-.'                dash-dot line style
':'                 dotted line style
'.'                 point marker
','                 pixel marker
'o'                 circle marker
'v'                 triangle_down marker
'^'                 triangle_up marker
'<'                 triangle_left marker
'>'                 triangle_right marker
'1'                 tri_down marker
'2'                 tri_up marker
'3'                 tri_left marker
'4'                 tri_right marker
's'                 square marker
'p'                 pentagon marker
'*'                 star marker
'h'                 hexagon1 marker
'H'                 hexagon2 marker
'+'                 plus marker
'x'                 x marker
'D'                 diamond marker
'd'                 thin_diamond marker
'|'                 vline marker
'_'                 hline marker
================    ===============================

The following color abbreviations are supported:

==========  ========
character   color
==========  ========
'b'         blue
'g'         green
'r'         red
'c'         cyan
'm'         magenta
'y'         yellow
'k'         black
'w'         white
==========  ========

In addition, you can specify colors in many weird and
wonderful ways, including full names (``'green'``), hex
strings (``'#008000'``), RGB or RGBA tuples (``(0,1,0,1)``) or
grayscale intensities as a string (``'0.8'``).  Of these, the
string specifications can be used in place of a ``fmt`` group,
but the tuple forms can be used only as ``kwargs``.

Line styles and colors are combined in a single format string, as in
``'bo'`` for blue circles.

The *kwargs* can be used to set line properties (any property that has
a ``set_*`` method).  You can use this to set a line label (for auto
legends), linewidth, anitialising, marker face color, etc.  Here is an
example::

    plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2)
    plot([1,2,3], [1,4,9], 'rs',  label='line 2')
    axis([0, 4, 0, 10])
    legend()

If you make multiple lines with one plot command, the kwargs
apply to all those lines, e.g.::

    plot(x1, y1, x2, y2, antialised=False)

Neither line will be antialiased.

You do not need to use format strings, which are just
abbreviations.  All of the line properties can be controlled
by keyword arguments.  For example, you can set the color,
marker, linestyle, and markercolor with::

    plot(x, y, color='green', linestyle='dashed', marker='o',
         markerfacecolor='blue', markersize=12).  See
         :class:`~matplotlib.lines.Line2D` for details.

The kwargs are :class:`~matplotlib.lines.Line2D` properties:

%(Line2D)s

kwargs *scalex* and *scaley*, if defined, are passed on to
:meth:`~matplotlib.axes.Axes.autoscale_view` to determine
whether the *x* and *y* axes are autoscaled; the default is
*True*.


self._base = base<EOL>self.offset = offset<EOL>

place ticks on the i-th data points where (i-offset)%base==0


self.seq = seq<EOL>self.offset_string = '<STR_LIT>'<EOL>

seq is a sequence of strings.  For positions `i<len(seq)` return
*seq[i]* regardless of *x*.  Otherwise return ''


lx = math.floor(math.log(x)/math.log(base))<EOL>return base**lx<EOL>


return self.fmt % x<EOL>

Return the format for tick val *x* at position *pos*


vmin, vmax = self.axis.get_view_interval()<EOL>if vmax<vmin:<EOL><INDENT>vmin, vmax = vmax, vmin<EOL><DEDENT>vmin = self._base.ge(vmin)<EOL>base = self._base.get_base()<EOL>n = (vmax - vmin + <NUM_LIT>*base)//base<EOL>locs = vmin + np.arange(n+<NUM_LIT:1>) * base<EOL>return locs<EOL>


dmin, dmax = self.axis.get_data_interval()<EOL>return np.arange(dmin + self.offset, dmax+<NUM_LIT:1>, self._base)<EOL>


return s<EOL>

some classes may want to replace a hyphen for minus with the
proper unicode symbol as described `here
<http://sourceforge.net/tracker/index.php?func=detail&aid=1962574&group_id=80706&atid=560720>`_.
The default is to do nothing

Note, if you use this method, eg in :meth`format_data` or
call, you probably don't want to use it for
:meth:`format_data_short` since the toolbar uses this for
interative coord reporting and I doubt we can expect GUIs
across platforms will handle the unicode correctly.  So for
now the classes that override :meth:`fix_minus` should have an
explicit :meth:`format_data_short` method


d,m = divmod(x, self._base)<EOL>if closeto(m,<NUM_LIT:0>) and not closeto(m/self._base,<NUM_LIT:1>):<EOL><INDENT>return (d-<NUM_LIT:1>)*self._base<EOL><DEDENT>return d*self._base<EOL>


return self.view_limits(*self.axis.get_view_interval())<EOL>


ticks = self()<EOL>numticks = len(ticks)<EOL>vmin, vmax = self.axis.get_view_interval()<EOL>vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander = <NUM_LIT>)<EOL>if numticks><NUM_LIT:2>:<EOL><INDENT>step = numsteps*abs(ticks[<NUM_LIT:0>]-ticks[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>d = abs(vmax-vmin)<EOL>step = numsteps*d/<NUM_LIT><EOL><DEDENT>vmin += step<EOL>vmax += step<EOL>self.axis.set_view_interval(vmin, vmax, ignore=True)<EOL>

Pan numticks (can be positive or negative)


self.labelOnlyBase=labelOnlyBase<EOL>


self.refresh()<EOL>return self._locator()<EOL>


lx = math.ceil(math.log(x)/math.log(base))<EOL>return base**lx<EOL>


def __init__(self, transform, subs=[<NUM_LIT:1.0>]):

self._transform = transform<EOL>self._subs = subs<EOL>self.numticks = <NUM_LIT:15><EOL>

place ticks on the location= base**i*subs[j]


raise NotImplementedError('<STR_LIT>')<EOL>

Return the format for tick val x at position pos; pos=None indicated unspecified


def __init__(self, numticks = None, presets=None):

self.numticks = numticks<EOL>if presets is None:<EOL><INDENT>self.presets = {}<EOL><DEDENT>else:<EOL><INDENT>self.presets = presets<EOL><DEDENT>

Use presets to set locs based on lom.  A dict mapping vmin, vmax->locs


if vmax<vmin:<EOL><INDENT>vmin, vmax = vmax, vmin<EOL><DEDENT>if vmin==vmax:<EOL><INDENT>vmin-=<NUM_LIT:1><EOL>vmax+=<NUM_LIT:1><EOL><DEDENT>exponent, remainder = divmod(math.log10(vmax - vmin), <NUM_LIT:1>)<EOL>if remainder < <NUM_LIT:0.5>:<EOL><INDENT>exponent -= <NUM_LIT:1><EOL><DEDENT>scale = <NUM_LIT:10>**(-exponent)<EOL>vmin = math.floor(scale*vmin)/scale<EOL>vmax = math.ceil(scale*vmax)/scale<EOL>return mtransforms.nonsingular(vmin, vmax)<EOL>

Try to choose the view limits intelligently


if len(self.locs)==<NUM_LIT:0>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>s = self.pprint_val(x)<EOL>return self.fix_minus(s)<EOL><DEDENT>


b = self._base<EOL>if x == <NUM_LIT:0>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>sign = np.sign(x)<EOL>fx = math.log(abs(x))/math.log(b)<EOL>isDecade = self.is_decade(fx)<EOL>usetex = rcParams['<STR_LIT>']<EOL>if sign == -<NUM_LIT:1>:<EOL><INDENT>sign_string = '<STR_LIT:->'<EOL><DEDENT>else:<EOL><INDENT>sign_string = '<STR_LIT>'<EOL><DEDENT>if not isDecade and self.labelOnlyBase: s = '<STR_LIT>'<EOL>elif not isDecade:<EOL><INDENT>if usetex:<EOL><INDENT>s = r'<STR_LIT>'% (sign_string, b, fx)<EOL><DEDENT>else:<EOL><INDENT>s = '<STR_LIT>'% (sign_string, b, fx)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if usetex:<EOL><INDENT>s = r'<STR_LIT>'% (sign_string, b, self.nearest_long(fx))<EOL><DEDENT>else:<EOL><INDENT>s = r'<STR_LIT>'% (sign_string, b, self.nearest_long(fx))<EOL><DEDENT><DEDENT>return s<EOL>


self.locs = locs<EOL>if len(self.locs) > <NUM_LIT:0>:<EOL><INDENT>vmin, vmax = self.axis.get_view_interval()<EOL>d = abs(vmax-vmin)<EOL>if self._useOffset: self._set_offset(d)<EOL>self._set_orderOfMagnitude(d)<EOL>self._set_format()<EOL><DEDENT>


if self.nbins is None:<EOL><INDENT>return self.locs<EOL><DEDENT>step = max(int(<NUM_LIT> + len(self.locs) / float(self.nbins)), <NUM_LIT:1>)<EOL>return self.locs[::step]<EOL>


vmin, vmax = self.axis.get_view_interval()<EOL>vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander = <NUM_LIT>)<EOL>if vmax<vmin:<EOL><INDENT>vmin, vmax = vmax, vmin<EOL><DEDENT>if (vmin, vmax) in self.presets:<EOL><INDENT>return self.presets[(vmin, vmax)]<EOL><DEDENT>if self.numticks is None:<EOL><INDENT>self._set_numticks()<EOL><DEDENT>if self.numticks==<NUM_LIT:0>: return []<EOL>ticklocs = np.linspace(vmin, vmax, self.numticks)<EOL>return ticklocs<EOL>


d = abs(d)<EOL>if d<=<NUM_LIT:0>:<EOL><INDENT>locator = MultipleLocator(<NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>try: ld = math.log10(d)<EOL>except OverflowError:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>fld = math.floor(ld)<EOL>base = <NUM_LIT:10>**fld<EOL>if   d >= <NUM_LIT:5>*base : ticksize = base<EOL>elif d >= <NUM_LIT:2>*base : ticksize = base/<NUM_LIT><EOL>else             : ticksize = base/<NUM_LIT><EOL>locator = MultipleLocator(ticksize)<EOL><DEDENT>return locator<EOL>

pick the best locator based on a distance


return self.format_data(value)<EOL>


xmin, xmax = self.axis.get_view_interval()<EOL>d = abs(xmax - xmin)<EOL>return self.pprint_val(x,d)<EOL>


b=self._base<EOL>vmin, vmax = self.axis.get_view_interval()<EOL>if vmin <= <NUM_LIT:0.0>:<EOL><INDENT>vmin = self.axis.get_minpos()<EOL>if vmin <= <NUM_LIT:0.0>:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>vmin = math.log(vmin)/math.log(b)<EOL>vmax = math.log(vmax)/math.log(b)<EOL>if vmax<vmin:<EOL><INDENT>vmin, vmax = vmax, vmin<EOL><DEDENT>numdec = math.floor(vmax)-math.ceil(vmin)<EOL>if self._subs is None: <EOL><INDENT>if numdec><NUM_LIT:10>: subs = np.array([<NUM_LIT:1.0>])<EOL>elif numdec><NUM_LIT:6>: subs = np.arange(<NUM_LIT>, b, <NUM_LIT>)<EOL>else: subs = np.arange(<NUM_LIT>, b)<EOL><DEDENT>else:<EOL><INDENT>subs = self._subs<EOL><DEDENT>stride = <NUM_LIT:1><EOL>while numdec/stride+<NUM_LIT:1> > self.numticks:<EOL><INDENT>stride += <NUM_LIT:1><EOL><DEDENT>decades = np.arange(math.floor(vmin),<EOL>math.ceil(vmax)+stride, stride)<EOL>if len(subs) > <NUM_LIT:1> or (len(subs == <NUM_LIT:1>) and subs[<NUM_LIT:0>] != <NUM_LIT:1.0>):<EOL><INDENT>ticklocs = []<EOL>for decadeStart in b**decades:<EOL><INDENT>ticklocs.extend( subs*decadeStart )<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ticklocs = b**decades<EOL><DEDENT>return np.array(ticklocs)<EOL>


d,m = divmod(x, self._base)<EOL>if closeto(m,<NUM_LIT:0>) and not closeto(m/self._base,<NUM_LIT:1>):<EOL><INDENT>return d*self._base<EOL><DEDENT>return (d+<NUM_LIT:1>)*self._base<EOL>

return the smallest multiple of base >= x


def get_intersection(cx1, cy1, cos_t1, sin_t1,<EOL>cx2, cy2, cos_t2, sin_t2):

<EOL>line1_rhs = sin_t1 * cx1 - cos_t1 * cy1<EOL>line2_rhs = sin_t2 * cx2 - cos_t2 * cy2<EOL>a, b = sin_t1, -cos_t1<EOL>c, d = sin_t2, -cos_t2<EOL>ad_bc = a*d-b*c<EOL>if ad_bc == <NUM_LIT:0.>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>a_, b_ = d, -b<EOL>c_, d_ = -c, a<EOL>a_, b_, c_, d_ = [k / ad_bc for k in [a_, b_, c_, d_]]<EOL>x = a_* line1_rhs + b_ * line2_rhs<EOL>y = c_* line1_rhs + d_ * line2_rhs<EOL>return x, y<EOL>

return a intersecting point between a line through (cx1, cy1)
    and having angle t1 and a line through (cx2, cy2) and angle t2.


def make_wedged_bezier2(bezier2, length, shrink_factor=<NUM_LIT:0.5>):

xx1, yy1 = bezier2[<NUM_LIT:2>]<EOL>xx2, yy2 = bezier2[<NUM_LIT:1>]<EOL>xx3, yy3 = bezier2[<NUM_LIT:0>]<EOL>cx, cy = xx3, yy3<EOL>x0, y0 = xx2, yy2<EOL>dist = sqrt((x0-cx)**<NUM_LIT:2> + (y0-cy)**<NUM_LIT:2>)<EOL>cos_t, sin_t = (x0-cx)/dist, (y0-cy)/dist,<EOL>x1, y1, x2, y2 = get_normal_points(cx, cy, cos_t, sin_t, length)<EOL>xx12, yy12 = (xx1+xx2)/<NUM_LIT>, (yy1+yy2)/<NUM_LIT>, <EOL>xx23, yy23 = (xx2+xx3)/<NUM_LIT>, (yy2+yy3)/<NUM_LIT>, <EOL>dist = sqrt((xx12-xx23)**<NUM_LIT:2> + (yy12-yy23)**<NUM_LIT:2>)<EOL>cos_t, sin_t = (xx12-xx23)/dist, (yy12-yy23)/dist,<EOL>xm1, ym1, xm2, ym2 = get_normal_points(xx2, yy2, cos_t, sin_t, length*shrink_factor)<EOL>l_plus = [(x1, y1), (xm1, ym1), (xx1, yy1)]<EOL>l_minus = [(x2, y2), (xm2, ym2), (xx1, yy1)]<EOL>return l_plus, l_minus<EOL>

Being similar to get_parallels, returns
control points of two quadrativ bezier lines having a width roughly parralel to given
one separated by *width*.


one_minus_t_powers = np.power(<NUM_LIT:1.>-t, self._orders)[::-<NUM_LIT:1>]<EOL>t_powers = np.power(t, self._orders)<EOL>tt = one_minus_t_powers * t_powers<EOL>_x = sum(tt * self._px)<EOL>_y = sum(tt * self._py)<EOL>return _x, _y<EOL>


<EOL>c1x, c1y = bezier2[<NUM_LIT:0>]<EOL>cmx, cmy = bezier2[<NUM_LIT:1>]<EOL>c2x, c2y = bezier2[<NUM_LIT:2>]<EOL>cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)<EOL>cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c2x, c2y)<EOL>c1x_left, c1y_left, c1x_right, c1y_right =get_normal_points(c1x, c1y, cos_t1, sin_t1, width)<EOL>c2x_left, c2y_left, c2x_right, c2y_right =get_normal_points(c2x, c2y, cos_t2, sin_t2, width)<EOL>cmx_left, cmy_left = get_intersection(c1x_left, c1y_left, cos_t1, sin_t1,<EOL>c2x_left, c2y_left, cos_t2, sin_t2)<EOL>cmx_right, cmy_right = get_intersection(c1x_right, c1y_right, cos_t1, sin_t1,<EOL>c2x_right, c2y_right, cos_t2, sin_t2)<EOL>path_left = [(c1x_left, c1y_left), (cmx_left, cmy_left), (c2x_left, c2y_left)]<EOL>path_right = [(c1x_right, c1y_right), (cmx_right, cmy_right), (c2x_right, c2y_right)]<EOL>return path_left, path_right<EOL>

Given the quadraitc bezier control points *bezier2*, returns
control points of quadrativ bezier lines roughly parralel to given
one separated by *width*.


def make_wedged_bezier2(bezier2, width, w1=<NUM_LIT:1.>, wm=<NUM_LIT:0.5>, w2=<NUM_LIT:0.>):

<EOL>c1x, c1y = bezier2[<NUM_LIT:0>]<EOL>cmx, cmy = bezier2[<NUM_LIT:1>]<EOL>c3x, c3y = bezier2[<NUM_LIT:2>]<EOL>cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)<EOL>cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c3x, c3y)<EOL>c1x_left, c1y_left, c1x_right, c1y_right =get_normal_points(c1x, c1y, cos_t1, sin_t1, width*w1)<EOL>c3x_left, c3y_left, c3x_right, c3y_right =get_normal_points(c3x, c3y, cos_t2, sin_t2, width*w2)<EOL>c12x, c12y = (c1x+cmx)*<NUM_LIT>, (c1y+cmy)*<NUM_LIT><EOL>c23x, c23y = (cmx+c3x)*<NUM_LIT>, (cmy+c3y)*<NUM_LIT> <EOL>c123x, c123y = (c12x+c23x)*<NUM_LIT>, (c12y+c23y)*<NUM_LIT><EOL>cos_t123, sin_t123 = get_cos_sin(c12x, c12y, c23x, c23y)<EOL>c123x_left, c123y_left, c123x_right, c123y_right =get_normal_points(c123x, c123y, cos_t123, sin_t123, width*wm)<EOL>path_left = find_control_points(c1x_left, c1y_left,<EOL>c123x_left, c123y_left,<EOL>c3x_left, c3y_left)<EOL>path_right = find_control_points(c1x_right, c1y_right,<EOL>c123x_right, c123y_right,<EOL>c3x_right, c3y_right)<EOL>return path_left, path_right<EOL>


bz = BezierSegment(bezier)<EOL>bezier_point_at_t = bz.point_at_t<EOL>t0, t1 = find_bezier_t_intersecting_with_closedpath(bezier_point_at_t,<EOL>inside_closedpath, <EOL>tolerence=tolerence)<EOL>_left, _right = split_de_casteljau(bezier, (t0+t1)/<NUM_LIT>)<EOL>return _left, _right<EOL>

bezier : control points of the bezier segment
inside_closedpath : a function which returns true if the point is inside the path


_o = len(control_points)<EOL>self._orders = np.arange(_o)<EOL>_coeff = BezierSegment._binom_coeff[_o - <NUM_LIT:1>]<EOL>_control_points = np.asarray(control_points)<EOL>xx = _control_points[:,<NUM_LIT:0>]<EOL>yy = _control_points[:,<NUM_LIT:1>]<EOL>self._px = xx * _coeff<EOL>self._py = yy * _coeff<EOL>

*control_points* : location of contol points. It needs have a
 shpae of n * 2, where n is the order of the bezier line. 1<=
 n <= 3 is supported.


def get_normal_points(cx, cy, cos_t, sin_t, length):

if length == <NUM_LIT:0.>:<EOL><INDENT>return cx, cy, cx, cy<EOL><DEDENT>cos_t1, sin_t1 = sin_t, -cos_t<EOL>cos_t2, sin_t2 = -sin_t, cos_t<EOL>x1, y1 = length*cos_t1 + cx, length*sin_t1 + cy<EOL>x2, y2 = length*cos_t2 + cx, length*sin_t2 + cy<EOL>return x1, y1, x2, y2<EOL>

For a line passing through (*cx*, *cy*) and having a angle *t*,
return locations of the two points located along its perpendicular line at the distance of *length*.


def set_over(self, color = '<STR_LIT:k>', alpha = <NUM_LIT:1.0>):

self._rgba_over = colorConverter.to_rgba(color, alpha)<EOL>if self._isinit: self._set_extremes()<EOL>

Set color to be used for high out-of-range values.
           Requires norm.clip = False


try:<EOL><INDENT>colorConverter.to_rgb(c)<EOL>return True<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT>

Return *True* if *c* can be converted to *RGB*


def __init__(self, colors, name = '<STR_LIT>', N = None):

self.colors = colors<EOL>self.monochrome = False  <EOL>if N is None:<EOL><INDENT>N = len(self.colors)<EOL><DEDENT>else:<EOL><INDENT>if cbook.is_string_like(self.colors):<EOL><INDENT>self.colors = [self.colors] * N<EOL>self.monochrome = True<EOL><DEDENT>elif cbook.iterable(self.colors):<EOL><INDENT>self.colors = list(self.colors) <EOL>if len(self.colors) == <NUM_LIT:1>:<EOL><INDENT>self.monochrome = True<EOL><DEDENT>if len(self.colors) < N:<EOL><INDENT>self.colors = list(self.colors) * N<EOL><DEDENT>del(self.colors[N:])<EOL><DEDENT>else:<EOL><INDENT>try: gray = float(self.colors)<EOL>except TypeError: pass<EOL>else:  self.colors = [gray] * N<EOL>self.monochrome = True<EOL><DEDENT><DEDENT>Colormap.__init__(self, name, N)<EOL>

Make a colormap from a list of colors.

*colors*
    a list of matplotlib color specifications,
    or an equivalent Nx3 floating point array (*N* rgb values)
*name*
    a string to identify the colormap
*N*
    the number of entries in the map.  The default is *None*,
    in which case there is one colormap entry for each
    element in the list of colors.  If::

        N < len(colors)

    the list will be truncated at *N*.  If::

        N > len(colors)

    the list will be extended by repetition.


try:<EOL><INDENT>if not cbook.is_string_like(arg) and cbook.iterable(arg):<EOL><INDENT>if len(arg) == <NUM_LIT:4>:<EOL><INDENT>if [x for x in arg if (float(x) < <NUM_LIT:0>) or  (x > <NUM_LIT:1>)]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if alpha is None:<EOL><INDENT>return tuple(arg)<EOL><DEDENT>if alpha < <NUM_LIT:0.0> or alpha > <NUM_LIT:1.0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return arg[<NUM_LIT:0>], arg[<NUM_LIT:1>], arg[<NUM_LIT:2>], arg[<NUM_LIT:3>] * alpha<EOL><DEDENT>r,g,b = arg[:<NUM_LIT:3>]<EOL>if [x for x in (r,g,b) if (float(x) < <NUM_LIT:0>) or  (x > <NUM_LIT:1>)]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>r,g,b = self.to_rgb(arg)<EOL><DEDENT>if alpha is None:<EOL><INDENT>alpha = <NUM_LIT:1.0><EOL><DEDENT>return r,g,b,alpha<EOL><DEDENT>except (TypeError, ValueError) as exc:<EOL><INDENT>raise ValueError('<STR_LIT>' % (str(arg), exc))<EOL><DEDENT>

Returns an *RGBA* tuple of four floats from 0-1.

For acceptable values of *arg*, see :meth:`to_rgb`.
If *arg* is an *RGBA* sequence and *alpha* is not *None*,
*alpha* will replace the original *A*.


self.name = name<EOL>self.N = N<EOL>self._rgba_bad = (<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>) <EOL>self._rgba_under = None<EOL>self._rgba_over = None<EOL>self._i_under = N<EOL>self._i_over = N+<NUM_LIT:1><EOL>self._i_bad = N+<NUM_LIT:2><EOL>self._isinit = False<EOL>

Public class attributes:
    :attr:`N` : number of rgb quantization levels
    :attr:`name` : name of colormap


try: return self.cache[arg]<EOL>except KeyError: pass<EOL>except TypeError: <EOL><INDENT>arg = tuple(arg)<EOL>try: return self.cache[arg]<EOL>except KeyError: pass<EOL>except TypeError:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>% (str(arg),))<EOL><DEDENT><DEDENT>try:<EOL><INDENT>if cbook.is_string_like(arg):<EOL><INDENT>color = self.colors.get(arg, None)<EOL>if color is None:<EOL><INDENT>str1 = cnames.get(arg, arg)<EOL>if str1.startswith('<STR_LIT:#>'):<EOL><INDENT>color = hex2color(str1)<EOL><DEDENT>else:<EOL><INDENT>fl = float(arg)<EOL>if fl < <NUM_LIT:0> or fl > <NUM_LIT:1>:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>color = tuple([fl]*<NUM_LIT:3>)<EOL><DEDENT><DEDENT><DEDENT>elif cbook.iterable(arg):<EOL><INDENT>if len(arg) > <NUM_LIT:4> or len(arg) < <NUM_LIT:3>:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'%len(arg))<EOL><DEDENT>color = tuple(arg[:<NUM_LIT:3>])<EOL>if [x for x in color if (float(x) < <NUM_LIT:0>) or  (x > <NUM_LIT:1>)]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self.cache[arg] = color<EOL><DEDENT>except (KeyError, ValueError, TypeError) as exc:<EOL><INDENT>raise ValueError('<STR_LIT>' % (str(arg), exc))<EOL><DEDENT>return color<EOL>

Returns an *RGB* tuple of three floats from 0-1.

*arg* can be an *RGB* or *RGBA* sequence or a string in any of
several forms:

    1) a letter from the set 'rgbcmykw'
    2) a hex color string, like '#00FFFF'
    3) a standard name, like 'aqua'
    4) a float, like '0.4', indicating gray on a 0-1 scale

if *arg* is *RGBA*, the *A* will simply be discarded.


try:<EOL><INDENT>adata = np.array(data)<EOL><DEDENT>except:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>shape = adata.shape<EOL>if len(shape) != <NUM_LIT:2> and shape[<NUM_LIT:1>] != <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>x  = adata[:,<NUM_LIT:0>]<EOL>y0 = adata[:,<NUM_LIT:1>]<EOL>y1 = adata[:,<NUM_LIT:2>]<EOL>if x[<NUM_LIT:0>] != <NUM_LIT:0.> or x[-<NUM_LIT:1>] != <NUM_LIT:1.0>:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>if np.sometrue(np.sort(x)-x):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>x = x * (N-<NUM_LIT:1>)<EOL>lut = np.zeros((N,), np.float)<EOL>xind = np.arange(float(N))<EOL>ind = np.searchsorted(x, xind)[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>lut[<NUM_LIT:1>:-<NUM_LIT:1>] = ( ((xind[<NUM_LIT:1>:-<NUM_LIT:1>] - x[ind-<NUM_LIT:1>]) / (x[ind] - x[ind-<NUM_LIT:1>]))<EOL>* (y0[ind] - y1[ind-<NUM_LIT:1>]) + y1[ind-<NUM_LIT:1>])<EOL>lut[<NUM_LIT:0>] = y1[<NUM_LIT:0>]<EOL>lut[-<NUM_LIT:1>] = y0[-<NUM_LIT:1>]<EOL>np.clip(lut, <NUM_LIT:0.0>, <NUM_LIT:1.0>)<EOL>return lut<EOL>

Create an *N* -element 1-d lookup table

    *data* represented by a list of x,y0,y1 mapping correspondences.
    Each element in this list represents how a value between 0 and 1
    (inclusive) represented by x is mapped to a corresponding value
    between 0 and 1 (inclusive). The two values of y are to allow
    for discontinuous mapping functions (say as might be found in a
    sawtooth) where y0 represents the value of y for values of x
    <= to that given, and y1 is the value to be used for x > than
    that given). The list must start with x=0, end with x=1, and
    all values of x must be in increasing order. Values between
    the given mapping points are determined by simple linear interpolation.

    The function returns an array "result" where ``result[x*(N-1)]``
    gives the closest value for values of x between 0 and 1.


return self.width, self.height, self.xdescent, self.ydescent<EOL>

Return with, height, xdescent, ydescent of box


self.width = width<EOL>


for c in self._children:<EOL><INDENT>c.draw(renderer)<EOL><DEDENT>bbox_artist(self, renderer, fill=False, props=dict(pad=<NUM_LIT:0.>))<EOL>


self._offset = xy<EOL>

Set the offset

accepts x, y, tuple, or a callable object.


return self._offset<EOL>


return self._minimumdescent<EOL>


def score_stretch(self, stretch1, stretch2):

try:<EOL><INDENT>stretchval1 = int(stretch1)<EOL><DEDENT>except ValueError:<EOL><INDENT>stretchval1 = stretch_dict.get(stretch1, <NUM_LIT>)<EOL><DEDENT>try:<EOL><INDENT>stretchval2 = int(stretch2)<EOL><DEDENT>except ValueError:<EOL><INDENT>stretchval2 = stretch_dict.get(stretch2, <NUM_LIT>)<EOL><DEDENT>return abs(stretchval1 - stretchval2) / <NUM_LIT><EOL>

Returns a match score between *stretch1* and *stretch2*.

The result is the absolute value of the difference between the
CSS numeric values of *stretch1* and *stretch2*, normalized
between 0.0 and 1.0.


if self._variant is None:<EOL><INDENT>return rcParams['<STR_LIT>']<EOL><DEDENT>return self._variant<EOL>

Return the font variant.  Values are: 'normal' or
'small-caps'.


return FontProperties(_init = self)<EOL>


fontfiles = {}<EOL>fontexts = get_fontext_synonyms(fontext)<EOL>if fontpaths is None:<EOL><INDENT>if sys.platform == '<STR_LIT:win32>':<EOL><INDENT>fontdir = win32FontDirectory()<EOL>fontpaths = [fontdir]<EOL>for f in win32InstalledFonts(fontdir):<EOL><INDENT>base, ext = os.path.splitext(f)<EOL>if len(ext)><NUM_LIT:1> and ext[<NUM_LIT:1>:].lower() in fontexts:<EOL><INDENT>fontfiles[f] = <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>fontpaths = x11FontDirectory()<EOL>if sys.platform == '<STR_LIT>':<EOL><INDENT>for f in OSXInstalledFonts(fontext=fontext):<EOL><INDENT>fontfiles[f] = <NUM_LIT:1><EOL><DEDENT><DEDENT>for f in get_fontconfig_fonts(fontext):<EOL><INDENT>fontfiles[f] = <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>elif isinstance(fontpaths, str):<EOL><INDENT>fontpaths = [fontpaths]<EOL><DEDENT>for path in fontpaths:<EOL><INDENT>files = []<EOL>for ext in fontexts:<EOL><INDENT>files.extend(glob.glob(os.path.join(path, '<STR_LIT>'+ext)))<EOL>files.extend(glob.glob(os.path.join(path, '<STR_LIT>'+ext.upper())))<EOL><DEDENT>for fname in files:<EOL><INDENT>fontfiles[os.path.abspath(fname)] = <NUM_LIT:1><EOL><DEDENT><DEDENT>return [fname for fname in list(fontfiles.keys()) if os.path.exists(fname)]<EOL>

Search for fonts in the specified font paths.  If no paths are
given, will use a standard set of system paths, as well as the
list of fonts tracked by fontconfig if fontconfig is installed and
available.  A list of TrueType fonts are returned by default with
AFM fonts as an option.


fontpaths = []<EOL>def add(arg,directory,files):<EOL><INDENT>fontpaths.append(directory)<EOL><DEDENT>for fontdir in OSXFontDirectories:<EOL><INDENT>try:<EOL><INDENT>if os.path.isdir(fontdir):<EOL><INDENT>os.path.walk(fontdir, add, None)<EOL><DEDENT><DEDENT>except (IOError, OSError, TypeError, ValueError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return fontpaths<EOL>

Return the system font directories for OS X.  This is done by
starting at the list of hardcoded paths in
:attr:`OSXFontDirectories` and returning all nested directories
within them.


fontpaths = []<EOL>def add(arg,directory,files):<EOL><INDENT>fontpaths.append(directory)<EOL><DEDENT>for fontdir in X11FontDirectories:<EOL><INDENT>try:<EOL><INDENT>if os.path.isdir(fontdir):<EOL><INDENT>os.path.walk(fontdir, add, None)<EOL><DEDENT><DEDENT>except (IOError, OSError, TypeError, ValueError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return fontpaths<EOL>

Return the system font directories for X11.  This is done by
starting at the list of hardcoded paths in
:attr:`X11FontDirectories` and returning all nested directories
within them.


if self._stretch is None:<EOL><INDENT>return rcParams['<STR_LIT>']<EOL><DEDENT>return self._stretch<EOL>

Return the font stretch or width.  Options are: 'ultra-condensed',
'extra-condensed', 'condensed', 'semi-condensed', 'normal',
'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'.


self.default_size = size<EOL>

Set the default font size in points.  The initial value is set
by ``font.size`` in rc.


if self._weight is None:<EOL><INDENT>return rcParams['<STR_LIT>']<EOL><DEDENT>return self._weight<EOL>

Set the font weight.  Options are: A numeric value in the
range 0-1000 or one of 'light', 'normal', 'regular', 'book',
'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold',
'heavy', 'extra bold', 'black'


if size2 == '<STR_LIT>':<EOL><INDENT>return <NUM_LIT:0.0><EOL><DEDENT>try:<EOL><INDENT>sizeval1 = float(size1)<EOL><DEDENT>except ValueError:<EOL><INDENT>sizeval1 = self.default_size * font_scalings(size1)<EOL><DEDENT>try:<EOL><INDENT>sizeval2 = float(size2)<EOL><DEDENT>except ValueError:<EOL><INDENT>return <NUM_LIT:1.0><EOL><DEDENT>return abs(sizeval1 - sizeval2) / <NUM_LIT><EOL>

Returns a match score between *size1* and *size2*.

If *size2* (the size specified in the font file) is 'scalable', this
function always returns 0.0, since any font size can be generated.

Otherwise, the result is the absolute distance between *size1* and
*size2*, normalized so that the usual range of font sizes (6pt -
72pt) will lie between 0.0 and 1.0.


if isinstance(weight, str):<EOL><INDENT>try:<EOL><INDENT>weight = weight_dict[weight.lower()]<EOL><DEDENT>except KeyError:<EOL><INDENT>weight = <NUM_LIT><EOL><DEDENT><DEDENT>elif weight in range(<NUM_LIT:100>, <NUM_LIT:1000>, <NUM_LIT:100>):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return weight<EOL>

Return the weight property as a numeric value.  String values
are converted to their corresponding numeric value.


def score_family(self, families, family2):

for i, family1 in enumerate(families):<EOL><INDENT>if family1.lower() in font_family_aliases:<EOL><INDENT>if family1 == '<STR_LIT>':<EOL><INDENT>family1 == '<STR_LIT>'<EOL><DEDENT>options = rcParams['<STR_LIT>' + family1]<EOL>if family2 in options:<EOL><INDENT>idx = options.index(family2)<EOL>return <NUM_LIT:0.1> * (float(idx) / len(options))<EOL><DEDENT><DEDENT>elif family1.lower() == family2.lower():<EOL><INDENT>return <NUM_LIT:0.0><EOL><DEDENT><DEDENT>return <NUM_LIT:1.0><EOL>

Returns a match score between the list of font families in
*families* and the font family name *family2*.

An exact match anywhere in the list returns 0.0.

A match by generic font name will return 0.1.

No match will return 1.0.


fh = open(filename, '<STR_LIT:w>')<EOL>try:<EOL><INDENT>pickle.dump(data, fh)<EOL><DEDENT>finally:<EOL><INDENT>fh.close()<EOL><DEDENT>

Equivalent to pickle.dump(data, open(filename, 'w'))
but closes the file to prevent filehandle leakage.


if variant not in ('<STR_LIT>', '<STR_LIT>', None):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._variant = variant<EOL>

Set the font variant.  Values are: 'normal' or 'small-caps'.


def score_variant(self, variant1, variant2):

if variant1 == variant2:<EOL><INDENT>return <NUM_LIT:0.0><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:1.0><EOL><DEDENT>

Returns a match score between *variant1* and *variant2*.

An exact match returns 0.0, otherwise 1.0.


fontlist = []<EOL>seen = {}<EOL>for fpath in fontfiles:<EOL><INDENT>verbose.report('<STR_LIT>' % (fpath), '<STR_LIT>')<EOL>fname = os.path.split(fpath)[<NUM_LIT:1>]<EOL>if fname in seen:  continue<EOL>else: seen[fname] = <NUM_LIT:1><EOL>if fontext == '<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>fh = open(fpath, '<STR_LIT:r>')<EOL><DEDENT>except:<EOL><INDENT>verbose.report("<STR_LIT>" % fpath)<EOL>continue<EOL><DEDENT>try:<EOL><INDENT>try:<EOL><INDENT>font = afm.AFM(fh)<EOL><DEDENT>finally:<EOL><INDENT>fh.close()<EOL><DEDENT><DEDENT>except RuntimeError:<EOL><INDENT>verbose.report("<STR_LIT>"%fpath)<EOL>continue<EOL><DEDENT>prop = afmFontProperty(fpath, font)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>font = ft2font.FT2Font(str(fpath))<EOL><DEDENT>except RuntimeError:<EOL><INDENT>verbose.report("<STR_LIT>"%fpath)<EOL>continue<EOL><DEDENT>except UnicodeError:<EOL><INDENT>verbose.report("<STR_LIT>")<EOL>continue<EOL><DEDENT>try: prop = ttfFontProperty(font)<EOL>except: continue<EOL><DEDENT>fontlist.append(prop)<EOL><DEDENT>return fontlist<EOL>

A function to create a font lookup list.  The default is to create
a list of TrueType fonts.  An AFM font list can optionally be
created.


try:<EOL><INDENT>import subprocess<EOL><DEDENT>except ImportError:<EOL><INDENT>return {}<EOL><DEDENT>fontext = get_fontext_synonyms(fontext)<EOL>fontfiles = {}<EOL>status, output = subprocess.getstatusoutput("<STR_LIT>")<EOL>if status == <NUM_LIT:0>:<EOL><INDENT>for line in output.split('<STR_LIT:\n>'):<EOL><INDENT>fname = line.split('<STR_LIT::>')[<NUM_LIT:0>]<EOL>if (os.path.splitext(fname)[<NUM_LIT:1>][<NUM_LIT:1>:] in fontext and<EOL>os.path.exists(fname)):<EOL><INDENT>fontfiles[fname] = <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return fontfiles<EOL>

Grab a list of all the fonts that are being tracked by fontconfig
by making a system call to ``fc-list``.  This is an easy way to
grab all of the fonts the user wants to be made available to
applications, without needing knowing where all of them reside.


if weight is not None:<EOL><INDENT>try:<EOL><INDENT>weight = int(weight)<EOL>if weight < <NUM_LIT:0> or weight > <NUM_LIT:1000>:<EOL><INDENT>raise ValueError()<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>if weight not in weight_dict:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>self._weight = weight<EOL>

Set the font weight.  May be either a numeric value in the
range 0-1000 or one of 'ultralight', 'light', 'normal',
'regular', 'book', 'medium', 'roman', 'semibold', 'demibold',
'demi', 'bold', 'heavy', 'extra bold', 'black'


return generate_fontconfig_pattern(self)<EOL>

Get a fontconfig pattern suitable for looking up the font as
specified with fontconfig's ``fc-match`` utility.

See the documentation on `fontconfig patterns
<http://www.fontconfig.org/fontconfig-user.html>`_.

This support does not require fontconfig to be installed or
support for it to be enabled.  We are merely borrowing its
pattern syntax for use here.


if os.path.splitext(filename)[<NUM_LIT:1>].lower() == '<STR_LIT>':<EOL><INDENT>result = _is_opentype_cff_font_cache.get(filename)<EOL>if result is None:<EOL><INDENT>fd = open(filename, '<STR_LIT:rb>')<EOL>tag = fd.read(<NUM_LIT:4>)<EOL>fd.close()<EOL>result = (tag == '<STR_LIT>')<EOL>_is_opentype_cff_font_cache[filename] = result<EOL><DEDENT>return result<EOL><DEDENT>return False<EOL>

Returns True if the given font is a Postscript Compact Font Format
Font embedded in an OpenType wrapper.  Used by the PostScript and
PDF backends that can not subset these fonts.


if axis is None:<EOL><INDENT>return alltrue(ravel(a))<EOL><DEDENT>else:<EOL><INDENT>return alltrue(a, axis)<EOL><DEDENT>


return reshape(array([_isnan(i) for i in ravel(a)],'<STR_LIT:b>'), shape(a))<EOL>

y = isnan(x) returns True where x is Not-A-Number


_dict = { "<STR_LIT>" : which[<NUM_LIT:0>],<EOL>"<STR_LIT>" : module,<EOL>"<STR_LIT>" : version + module<EOL>}<EOL>print("""<STR_LIT>""" % _dict)<EOL>

Prints a message when the array package specific version of an extension
    fails to import correctly.


def Matrix(data, typecode=None, copy=<NUM_LIT:1>, savespace=<NUM_LIT:0>):

if isinstance(data, type("<STR_LIT>")):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>a = fromlist(data, type=typecode)<EOL>if a.rank == <NUM_LIT:0>:<EOL><INDENT>a.shape = (<NUM_LIT:1>,<NUM_LIT:1>)<EOL><DEDENT>elif a.rank == <NUM_LIT:1>:<EOL><INDENT>a.shape = (<NUM_LIT:1>,) + a.shape<EOL><DEDENT>a.__class__ = _Matrix<EOL>return a<EOL>

Matrix constructs new matrices from 2D nested lists of numbers


if axis is None:<EOL><INDENT>return _all(a)<EOL><DEDENT>return alltrue(a, axis)<EOL>


self._visible = b<EOL>self.pchanged()<EOL>

Set the artist's visiblity.

ACCEPTS: [True | False]


return self._clippath<EOL>


insp = ArtistInspector(o)<EOL>if property is None:<EOL><INDENT>ret = insp.pprint_getters()<EOL>print('<STR_LIT:\n>'.join(ret))<EOL>return<EOL><DEDENT>func = getattr(o, '<STR_LIT>' + property)<EOL>return func()<EOL>

Return the value of handle property.  property is an optional string
for the property you want to return

Example usage::

    getp(o)  # get all the object properties
    getp(o, 'linestyle')  # get the linestyle property

*o* is a :class:`Artist` instance, eg
:class:`~matplotllib.lines.Line2D` or an instance of a
:class:`~matplotlib.axes.Axes` or :class:`matplotlib.text.Text`.
If the *property* is 'somename', this function returns

  o.get_somename()

:func:`getp` can be used to query all the gettable properties with
``getp(o)``. Many properties have aliases for shorter typing, e.g.
'lw' is an alias for 'linewidth'.  In the output, aliases and full
property names will be listed as:

  property or alias = value

e.g.:

  linewidth or lw = 2


insp = ArtistInspector(h)<EOL>if len(kwargs)==<NUM_LIT:0> and len(args)==<NUM_LIT:0>:<EOL><INDENT>print('<STR_LIT:\n>'.join(insp.pprint_setters()))<EOL>return<EOL><DEDENT>if len(kwargs)==<NUM_LIT:0> and len(args)==<NUM_LIT:1>:<EOL><INDENT>print(insp.pprint_setters(prop=args[<NUM_LIT:0>]))<EOL>return<EOL><DEDENT>if not cbook.iterable(h): h = [h]<EOL>else: h = cbook.flatten(h)<EOL>if len(args)%<NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>funcvals = []<EOL>for i in range(<NUM_LIT:0>, len(args)-<NUM_LIT:1>, <NUM_LIT:2>):<EOL><INDENT>funcvals.append((args[i], args[i+<NUM_LIT:1>]))<EOL><DEDENT>funcvals.extend(list(kwargs.items()))<EOL>ret = []<EOL>for o in h:<EOL><INDENT>for s, val in funcvals:<EOL><INDENT>s = s.lower()<EOL>funcName = "<STR_LIT>"%s<EOL>func = getattr(o,funcName)<EOL>ret.extend( [func(val)] )<EOL><DEDENT><DEDENT>return [x for x in cbook.flatten(ret)]<EOL>

matplotlib supports the use of :func:`setp` ("set property") and
:func:`getp` to set and get object properties, as well as to do
introspection on the object.  For example, to set the linestyle of a
line to be dashed, you can do::

  >>> line, = plot([1,2,3])
  >>> setp(line, linestyle='--')

If you want to know the valid types of arguments, you can provide the
name of the property you want to set without a value::

  >>> setp(line, 'linestyle')
      linestyle: [ '-' | '--' | '-.' | ':' | 'steps' | 'None' ]

If you want to see all the properties that can be set, and their
possible values, you can do::

  >>> setp(line)
      ... long output listing omitted

:func:`setp` operates on a single instance or a list of instances.
If you are in query mode introspecting the possible values, only
the first instance in the sequence is used.  When actually setting
values, all the instances will be set.  E.g., suppose you have a
list of two lines, the following will make both lines thicker and
red::

  >>> x = arange(0,1.0,0.01)
  >>> y1 = sin(2*pi*x)
  >>> y2 = sin(4*pi*x)
  >>> lines = plot(x, y1, x, y2)
  >>> setp(lines, linewidth=2, color='r')

:func:`setp` works with the matlab(TM) style string/value pairs or
with python kwargs.  For example, the following are equivalent::

  >>> setp(lines, 'linewidth', 2, 'color', r')  # matlab style

  >>> setp(lines, linewidth=2, color='r')       # python style


self.clipbox = clipbox<EOL>self.pchanged()<EOL>

Set the artist's clip :class:`~matplotlib.transforms.Bbox`.

ACCEPTS: a :class:`matplotlib.transforms.Bbox` instance


return self._picker<EOL>

Return the picker object used by this artist


self._snap = snap<EOL>

Sets the snap setting which may be:

  * True: snap vertices to the nearest pixel center

  * False: leave vertices as-is

  * None: (auto) If the path contains only rectilinear line
    segments, round to the nearest pixel center

Only supported by the Agg backends.


self.figure = fig<EOL>self.pchanged()<EOL>

Set the :class:`~matplotlib.figure.Figure` instance the artist
belongs to.

ACCEPTS: a :class:`matplotlib.figure.Figure` instance


self._clipon = b<EOL>self.pchanged()<EOL>

Set whether artist uses clipping.

ACCEPTS: [True | False]


return self.zorder<EOL>


return self._url<EOL>


for oid, func in list(self._propobservers.items()):<EOL><INDENT>func(self)<EOL><DEDENT>

Fire an event when property changed, calling all of the
registered callbacks.


self.axes = axes<EOL>

Set the :class:`~matplotlib.axes.Axes` instance in which the
artist resides, if any.

ACCEPTS: an :class:`~matplotlib.axes.Axes` instance


if cbook.iterable(o) and len(o): o = o[<NUM_LIT:0>]<EOL>self.oorig = o<EOL>if not isinstance(o, type):<EOL><INDENT>o = type(o)<EOL><DEDENT>self.o = o<EOL>self.aliasd = self.get_aliases()<EOL>

Initialize the artist inspector with an
:class:`~matplotlib.artist.Artist` or sequence of
:class:`Artists`.  If a sequence is used, we assume it is a
homogeneous sequence (all :class:`Artists` are of the same
type) and it is your responsibility to make sure this is so.


if self._transform is None:<EOL><INDENT>self._transform = IdentityTransform()<EOL><DEDENT>return self._transform<EOL>

Return the :class:`~matplotlib.transforms.Transform`
instance used by this artist.


self._animated = b<EOL>self.pchanged()<EOL>

Set the artist's animation state.

ACCEPTS: [True | False]


return self._visible<EOL>


try: del self._propobservers[oid]<EOL>except KeyError: pass<EOL>

Remove a callback based on its *id*.

.. seealso::
    :meth:`add_callback`


return self._snap<EOL>

Returns the snap setting which may be:

  * True: snap vertices to the nearest pixel center

  * False: leave vertices as-is

  * None: (auto) If the path contains only rectilinear line
    segments, round to the nearest pixel center

Only supported by the Agg backends.


if s in self.aliasd:<EOL><INDENT>return s + '<STR_LIT>'.join(['<STR_LIT>' % x for x in list(self.aliasd[s].keys())])<EOL><DEDENT>else:<EOL><INDENT>return s<EOL><DEDENT>

return 'PROPNAME or alias' if *s* has an alias, else return
PROPNAME.

E.g. for the line markerfacecolor property, which has an
alias, return 'markerfacecolor or mfc' and for the transform
property, which does not, return 'transform'


self._picker = picker<EOL>

Set the epsilon for picking used by this artist

*picker* can be one of the following:

  * *None*: picking is disabled for this artist (default)

  * A boolean: if *True* then picking will be enabled and the
    artist will fire a pick event if the mouse event is over
    the artist

  * A float: if picker is a number it is interpreted as an
    epsilon tolerance in points and the artist will fire
    off an event if it's data is within epsilon of the mouse
    event.  For some artists like lines and patch collections,
    the artist may provide additional data to the pick event
    that is generated, e.g. the indices of the data within
    epsilon of the pick event

  * A function: if picker is callable, it is a user supplied
    function which determines whether the artist is hit by the
    mouse event::

      hit, props = picker(artist, mouseevent)

    to determine the hit test.  if the mouse event is over the
    artist, return *hit=True* and props is a dictionary of
    properties you want added to the PickEvent attributes.

ACCEPTS: [None|float|boolean|callable]


ret = []<EOL>for k,v in list(kwargs.items()):<EOL><INDENT>k = k.lower()<EOL>funcName = "<STR_LIT>"%k<EOL>func = getattr(self,funcName)<EOL>ret.extend( [func(v)] )<EOL><DEDENT>return ret<EOL>

A tkstyle set command, pass *kwargs* to set properties


return [prop for prop, target in self._get_setters_and_targets()]<EOL>

Get the attribute strings with setters for object.  Eg., for a line,
return ``['markerfacecolor', 'linewidth', ....]``.


name = '<STR_LIT>'%attr<EOL>if not hasattr(self.o, name):<EOL><INDENT>raise AttributeError('<STR_LIT>'%(self.o,name))<EOL><DEDENT>func = getattr(self.o, name)<EOL>docstring = func.__doc__<EOL>if docstring is None: return '<STR_LIT>'<EOL>if docstring.startswith('<STR_LIT>'):<EOL><INDENT>return None<EOL><DEDENT>match = self._get_valid_values_regex.search(docstring)<EOL>if match is not None:<EOL><INDENT>return match.group(<NUM_LIT:1>).replace('<STR_LIT:\n>', '<STR_LIT:U+0020>')<EOL><DEDENT>return '<STR_LIT>'<EOL>

Get the legal arguments for the setter associated with *attr*.

This is done by querying the docstring of the function *set_attr*
for a line that begins with ACCEPTS:

Eg., for a line linestyle, return
[ '-' | '--' | '-.' | ':' | 'steps' | 'None' ]


return self._contains<EOL>

Return the _contains test used by the artist, or *None* for default.


return self._animated<EOL>


if match is None: <EOL><INDENT>def matchfunc(x): return True<EOL><DEDENT>elif cbook.issubclass_safe(match, Artist):<EOL><INDENT>def matchfunc(x):<EOL><INDENT>return isinstance(x, match)<EOL><DEDENT><DEDENT>elif callable(match):<EOL><INDENT>matchfunc = match<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>artists = []<EOL>for c in self.get_children():<EOL><INDENT>if matchfunc(c):<EOL><INDENT>artists.append(c)<EOL><DEDENT>artists.extend([thisc for thisc in c.findobj(matchfunc) if matchfunc(thisc)])<EOL><DEDENT>if matchfunc(self):<EOL><INDENT>artists.append(self)<EOL><DEDENT>return artists<EOL>

pyplot signature:
  findobj(o=gcf(), match=None)

Recursively find all :class:matplotlib.artist.Artist instances
contained in self.

*match* can be

  - None: return all objects contained in artist (including artist)

  - function with signature ``boolean = match(artist)`` used to filter matches

  - class instance: eg Line2D.  Only return artists of class type

.. plot:: mpl_examples/pylab_examples/findobj_demo.py


o = self.oorig<EOL>getters = [name for name in dir(o)<EOL>if name.startswith('<STR_LIT>')<EOL>and callable(getattr(o, name))]<EOL>getters.sort()<EOL>lines = []<EOL>for name in getters:<EOL><INDENT>func = getattr(o, name)<EOL>if self.is_alias(func): continue<EOL>try: val = func()<EOL>except: continue<EOL>if getattr(val, '<STR_LIT>', ()) != () and len(val)><NUM_LIT:6>:<EOL><INDENT>s = str(val[:<NUM_LIT:6>]) + '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>s = str(val)<EOL><DEDENT>s = s.replace('<STR_LIT:\n>', '<STR_LIT:U+0020>')<EOL>if len(s)><NUM_LIT:50>:<EOL><INDENT>s = s[:<NUM_LIT:50>] + '<STR_LIT>'<EOL><DEDENT>name = self.aliased_name(name[<NUM_LIT:4>:])<EOL>lines.append('<STR_LIT>' %(name, s))<EOL><DEDENT>return lines<EOL>

Return the getters and actual values as list of strings.


return self.figure<EOL>

Return the :class:`~matplotlib.figure.Figure` instance the
artist belongs to.


if isinstance(obj, dict):<EOL><INDENT>attrs = obj<EOL><DEDENT>elif hasattr(obj, "<STR_LIT>"):<EOL><INDENT>attrs = {attr: getattr(obj, attr) for attr in obj.__slots__}<EOL><DEDENT>elif hasattr(obj, "<STR_LIT>"):<EOL><INDENT>attrs = obj.__dict__<EOL><DEDENT>testParams = SERIALIZABLE_SUBCLASSES[obj.__class__.__name__]<EOL>if "<STR_LIT>" in testParams:<EOL><INDENT>for f in testParams["<STR_LIT>"]:<EOL><INDENT>if f in attrs:<EOL><INDENT>del attrs[f]<EOL><DEDENT><DEDENT><DEDENT>return attrs<EOL>


return cls.__subclasses__() + [<EOL>g for s in cls.__subclasses__() for g in _allSubclasses(s)<EOL>]<EOL>

Get all subclasses
:param cls: The class to get subclasses from
:return: list with all subclasses


def overlapsForUnrelatedAreas(n, w, radius, repetitions=<NUM_LIT:100>, verbose=False):

return overlapsForRelativeAreas(n, w, np.array([<NUM_LIT:0>, <NUM_LIT:0>]), radius,<EOL>dPosition=np.array([<NUM_LIT:0>, radius * <NUM_LIT:10>]),<EOL>num=repetitions, verbose=verbose)<EOL>

Return overlaps between an encoding and other, unrelated encodings


return (x & y).sum()<EOL>

Given two binary arrays, compute their overlap. The overlap is the number
of bits where x[i] and y[i] are both 1


numCols = numOnes * numPatterns<EOL>p = []<EOL>for i in range(numPatterns):<EOL><INDENT>x = np.zeros(numCols, dtype='<STR_LIT>')<EOL>x[i*numOnes:(i + <NUM_LIT:1>)*numOnes] = <NUM_LIT:1><EOL>p.append(x)<EOL><DEDENT>return p<EOL>

Very simple patterns. Each pattern has numOnes consecutive
    bits on. There are numPatterns*numOnes bits in the vector. These patterns
    are used as elements of sequences when building up a training set.


if origData is None:<EOL><INDENT>origData = []<EOL><DEDENT>if len(origData) > <NUM_LIT:0>:<EOL><INDENT>lastDate = origData[-<NUM_LIT:1>][<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>lastDate = datetime.datetime(<NUM_LIT>, <NUM_LIT:2>, <NUM_LIT:3>)<EOL><DEDENT>dateList = _getDateList(numSamples, lastDate)<EOL>data = copy.copy(origData)<EOL>for idx, date in enumerate(dateList):<EOL><INDENT>if (spikePeriod > <NUM_LIT:0>) and ( (idx + <NUM_LIT:1>) % spikePeriod == <NUM_LIT:0>):<EOL><INDENT>data.append([date, idx, spikeValue])<EOL><DEDENT>else:<EOL><INDENT>data.append([date, idx, <NUM_LIT:0.0>])<EOL><DEDENT><DEDENT>return data<EOL>

Add sample anomaly data to the existing data list and return it.
Note: this does not modify the original data list
Note 2: here we just add in increasing integers as the metric value


def frequency(self,<EOL>n=<NUM_LIT:15>,<EOL>w=<NUM_LIT:7>,<EOL>columnDimensions = <NUM_LIT>,<EOL>numActiveColumnsPerInhArea = <NUM_LIT>,<EOL>stimulusThreshold = <NUM_LIT:0>,<EOL>spSeed = <NUM_LIT:1>,<EOL>spVerbosity = <NUM_LIT:0>,<EOL>numColors = <NUM_LIT:2>,<EOL>seed=<NUM_LIT>,<EOL>minVal=<NUM_LIT:0>,<EOL>maxVal=<NUM_LIT:10>,<EOL>encoder = '<STR_LIT>',<EOL>forced=True):

print("<STR_LIT>")<EOL>print(encoder, '<STR_LIT>', '<STR_LIT>', seed, '<STR_LIT>', numColors, '<STR_LIT>')<EOL>spImpl = SpatialPooler(<EOL>columnDimensions=(columnDimensions, <NUM_LIT:1>),<EOL>inputDimensions=(<NUM_LIT:1>, n),<EOL>potentialRadius=n/<NUM_LIT:2>,<EOL>numActiveColumnsPerInhArea=numActiveColumnsPerInhArea,<EOL>spVerbosity=spVerbosity,<EOL>stimulusThreshold=stimulusThreshold,<EOL>potentialPct=<NUM_LIT:0.5>,<EOL>seed=spSeed,<EOL>globalInhibition=True,<EOL>)<EOL>rnd.seed(seed)<EOL>numpy.random.seed(seed)<EOL>colors = []<EOL>coincs = []<EOL>reUsedCoincs = []<EOL>spOutput = []<EOL>patterns = set([])<EOL>if encoder=='<STR_LIT>':<EOL><INDENT>enc = scalar.ScalarEncoder(name='<STR_LIT>', w=w, n=n, minval=minVal,<EOL>maxval=maxVal, periodic=False, forced=True) <EOL>for y in range(numColors):<EOL><INDENT>temp = enc.encode(rnd.random()*maxVal)<EOL>colors.append(numpy.array(temp, dtype=numpy.uint32))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for y in range(numColors):<EOL><INDENT>sdr = numpy.zeros(n, dtype=numpy.uint32)<EOL>sdr[rnd.sample(range(n), w)] = <NUM_LIT:1><EOL>colors.append(sdr)<EOL><DEDENT><DEDENT>print('<STR_LIT>', numColors, '<STR_LIT>')<EOL>startTime = time.time()<EOL>for i in range(numColors):<EOL><INDENT>spInput = colors[i]<EOL>onCells = numpy.zeros(columnDimensions, dtype=numpy.uint32)<EOL>spImpl.compute(spInput, True, onCells)<EOL>spOutput.append(onCells.tolist())<EOL>activeCoincIndices = set(onCells.nonzero()[<NUM_LIT:0>])<EOL>reUsed = activeCoincIndices.intersection(patterns)<EOL>if len(reUsed) == <NUM_LIT:0>:<EOL><INDENT>coincs.append((i, activeCoincIndices, colors[i]))<EOL><DEDENT>else:<EOL><INDENT>reUsedCoincs.append((i, activeCoincIndices, colors[i]))<EOL><DEDENT>patterns.update(activeCoincIndices)<EOL>if (i + <NUM_LIT:1>) % <NUM_LIT:100> == <NUM_LIT:0>:<EOL><INDENT>print('<STR_LIT>', i + <NUM_LIT:1>)<EOL>print("<STR_LIT>" % (time.time() - startTime))<EOL>print(len(reUsedCoincs), "<STR_LIT>")<EOL><DEDENT><DEDENT>summ = []<EOL>for z in coincs:<EOL><INDENT>summ.append(sum([len(z[<NUM_LIT:1>].intersection(y[<NUM_LIT:1>])) for y in reUsedCoincs]))<EOL><DEDENT>zeros = len([x for x in summ if x==<NUM_LIT:0>])<EOL>factor = max(summ)*len(summ)/sum(summ)<EOL>if len(reUsed) < <NUM_LIT:10>:<EOL><INDENT>self.assertLess(factor, <NUM_LIT>,<EOL>"<STR_LIT>" % (<EOL>factor, <NUM_LIT>))<EOL>self.assertLess(zeros, <NUM_LIT>*len(summ),<EOL>"<STR_LIT>" % (<EOL>zeros, <NUM_LIT>*len(summ)))<EOL><DEDENT>else:<EOL><INDENT>self.assertLess(factor, <NUM_LIT:8>,<EOL>"<STR_LIT>" % (<EOL>factor, <NUM_LIT:8>))<EOL>self.assertLess(zeros, <NUM_LIT:12>,<EOL>"<STR_LIT>" % (<EOL>zeros, <NUM_LIT:12>))<EOL><DEDENT>

Helper function that tests whether the SP predicts the most
        frequent record


return ((x + y) == <NUM_LIT:2>).sum()<EOL>


self.sp = CreateSP(imp, self.params)<EOL>self.spImplementation = imp<EOL>self.winningIteration.fill(<NUM_LIT:0>)<EOL>self.lastSDR = {}<EOL>self.boostTestPhase1()<EOL>self.boostTestPhase2()<EOL>self.boostTestPhase3()<EOL>self.boostTestPhase4()<EOL>


<EOL>self.assertTrue(_areAllSDRsUnique(self.lastSDR), "<STR_LIT>")<EOL>self.assertGreater(_computeOverlap(self.lastSDR[<NUM_LIT:0>], self.lastSDR[<NUM_LIT:1>]), <NUM_LIT:9>,<EOL>"<STR_LIT>")<EOL>for i in [<NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>]:<EOL><INDENT>for j in range(<NUM_LIT:5>):<EOL><INDENT>if (i!=j):<EOL><INDENT>self.assertLess(_computeOverlap(self.lastSDR[i], self.lastSDR[j]),<EOL><NUM_LIT>, "<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>

Verify that all SDRs have the properties desired for this test.

The bounds for checking overlap are set fairly loosely here since there is
some variance due to randomness and the artificial parameters used in this
test.


for c in range(tm.numberOfCols):<EOL><INDENT>assert tm.getNumSegmentsInCell(c, <NUM_LIT:0>) == <NUM_LIT:0><EOL><DEDENT>

Check that cell 0 has no incoming segments


tm.cells4.setVerbosity(verbosity)<EOL>tm.verbosity = verbosity<EOL>tmPy.verbosity = verbosity<EOL>


<EOL>tm = BacktrackingTMCPP(numberOfCols=<NUM_LIT:10>, cellsPerColumn=<NUM_LIT:3>,<EOL>initialPerm=<NUM_LIT>, connectedPerm= <NUM_LIT>,<EOL>minThreshold=<NUM_LIT:2>, newSynapseCount=<NUM_LIT:5>,<EOL>permanenceInc=<NUM_LIT>, permanenceDec= <NUM_LIT>,<EOL>permanenceMax=<NUM_LIT:1>, globalDecay=<NUM_LIT>,<EOL>activationThreshold=<NUM_LIT:4>, doPooling=False,<EOL>segUpdateValidDuration=<NUM_LIT:5>, seed=SEED,<EOL>verbosity=VERBOSITY)<EOL>tm.retrieveLearningStates = True<EOL>tm.makeCells4Ephemeral = False<EOL>pickle.dump(tm, open("<STR_LIT>", "<STR_LIT:wb>"))<EOL>tm2 = pickle.load(open("<STR_LIT>"))<EOL>self.assertTrue(fdrutils.tmDiff2(tm, tm2, VERBOSITY, checkStates=False))<EOL>for i in range(<NUM_LIT:5>):<EOL><INDENT>x = numpy.zeros(tm.numberOfCols, dtype='<STR_LIT>')<EOL>_RGEN.initializeUInt32Array(x, <NUM_LIT:2>)<EOL>tm.learn(x)<EOL><DEDENT>tm.reset()<EOL>tm.makeCells4Ephemeral = False<EOL>pickle.dump(tm, open("<STR_LIT>", "<STR_LIT:wb>"))<EOL>tm2 = pickle.load(open("<STR_LIT>"))<EOL>self.assertTrue(fdrutils.tmDiff2(tm, tm2, VERBOSITY))<EOL>patterns = numpy.zeros((<NUM_LIT:4>, tm.numberOfCols), dtype='<STR_LIT>')<EOL>for i in range(<NUM_LIT:4>):<EOL><INDENT>_RGEN.initializeUInt32Array(patterns[i], <NUM_LIT:2>)<EOL><DEDENT>for i in range(<NUM_LIT:10>):<EOL><INDENT>x = numpy.zeros(tm.numberOfCols, dtype='<STR_LIT>')<EOL>_RGEN.initializeUInt32Array(x, <NUM_LIT:2>)<EOL>tm.infer(x)<EOL>if i > <NUM_LIT:0>:<EOL><INDENT>tm._checkPrediction(patterns)<EOL><DEDENT><DEDENT>

Basic test (creation, pickling, basic run of learning and inference)


network = Network()<EOL>network.addRegion('<STR_LIT>', '<STR_LIT>', '<STR_LIT:{}>')<EOL>network.addRegion('<STR_LIT>', '<STR_LIT>', '<STR_LIT:{}>')<EOL>_createSensorToClassifierLinks(network, '<STR_LIT>', '<STR_LIT>')<EOL>sensorRegion = network.regions['<STR_LIT>'].getSelf()<EOL>encoderParams = {'<STR_LIT>': {'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT:1>,<EOL>'<STR_LIT:name>': '<STR_LIT>',<EOL>'<STR_LIT:type>': '<STR_LIT>'}}<EOL>encoder = MultiEncoder()<EOL>encoder.addMultipleEncoders(encoderParams)<EOL>sensorRegion.encoder = encoder<EOL>testDir = os.path.dirname(os.path.abspath(__file__))<EOL>inputFile = os.path.join(testDir, '<STR_LIT>', '<STR_LIT>')<EOL>dataSource = FileRecordStream(streamID=inputFile)<EOL>sensorRegion.dataSource = dataSource<EOL>network.regions['<STR_LIT>'].setParameter('<STR_LIT>', '<STR_LIT>')<EOL>return network<EOL>

Create a network with a RecordSensor region and a SDRClassifier region


network = Network()<EOL>network.addRegion('<STR_LIT>', '<STR_LIT>', '<STR_LIT:{}>')<EOL>sensorRegion = network.regions['<STR_LIT>'].getSelf()<EOL>encoderParams = {'<STR_LIT>': {'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT:1>,<EOL>'<STR_LIT:name>': '<STR_LIT>',<EOL>'<STR_LIT:type>': '<STR_LIT>'}}<EOL>encoder = MultiEncoder()<EOL>encoder.addMultipleEncoders(encoderParams)<EOL>sensorRegion.encoder = encoder<EOL>testDir = os.path.dirname(os.path.abspath(__file__))<EOL>inputFile = os.path.join(testDir, '<STR_LIT>', '<STR_LIT>')<EOL>dataSource = FileRecordStream(streamID=inputFile)<EOL>sensorRegion.dataSource = dataSource<EOL>network.regions['<STR_LIT>'].setParameter('<STR_LIT>', '<STR_LIT>')<EOL>return network<EOL>

Create network with one RecordSensor region.


self.files = {}<EOL>with tempfile.NamedTemporaryFile(<EOL>prefix='<STR_LIT>', delete=False) as outp:<EOL><INDENT>self.addCleanup(os.remove, outp.name)<EOL>with open(resource_filename(__name__, '<STR_LIT>')) as inp:<EOL><INDENT>outp.write(inp.read())<EOL><DEDENT>self.files['<STR_LIT>'] = outp.name<EOL><DEDENT>with tempfile.NamedTemporaryFile(<EOL>prefix='<STR_LIT>', delete=False) as outp:<EOL><INDENT>self.addCleanup(os.remove, outp.name)<EOL>with open(resource_filename(__name__, '<STR_LIT>')) as inp:<EOL><INDENT>outp.write(inp.read())<EOL><DEDENT>self.files['<STR_LIT>'] = outp.name<EOL><DEDENT>

configuration.Configuration relies on static methods
        which load files by name.  Since we need to be able to run tests and
        potentially change the content of those files between tests without
        interfering with one another and with the system configuration, this
        setUp() function will allocate temporary files used only during the using
        conf/nupic-default.xml and conf/nupic-site.xml (relative to the unit tests)
        as templates.


handle = tempfile.NamedTemporaryFile(prefix='<STR_LIT:test>', suffix='<STR_LIT>', dir='<STR_LIT:.>')<EOL>filename = handle.name<EOL>handle.close()<EOL>return filename<EOL>

Creates unique file name that starts with 'test' and ends with '.txt'.


for example in cls.examples:<EOL><INDENT>predictionGenerator = _getPredictionsGenerator(cls.examplesDir, example)<EOL>for prediction in predictionGenerator(MAX_PREDICTIONS):<EOL><INDENT>cls.oneStepPredictions[example].append(prediction[<NUM_LIT:0>])<EOL>cls.oneStepConfidences[example].append(prediction[<NUM_LIT:1>])<EOL>cls.fiveStepPredictions[example].append(prediction[<NUM_LIT:2>])<EOL>cls.fiveStepConfidences[example].append(prediction[<NUM_LIT:3>])<EOL><DEDENT><DEDENT>

Get the predictions and prediction confidences for all examples.


sys.path.insert(<NUM_LIT:0>, os.path.join(examplesDir, exampleName))<EOL>modName = "<STR_LIT>" % exampleName<EOL>mod = __import__(modName, fromlist=["<STR_LIT>"])<EOL>return getattr(mod, "<STR_LIT>")<EOL>

Get predictions generator for one of the quick-start example.

.. note::

  The examples are not part of the nupic package so we need to manually
  append the example module path to syspath.

:param examplesDir:
  (str) path to the example parent directory.
:param exampleName:
  (str) name of the example. E.g: "opf", "network", "algo".
:return predictionsGenerator:
  (function) predictions generator functions.


def TestH2a(sequenceLength, nTests, cellsPerColumn, numCols =<NUM_LIT:100>, nSequences =[<NUM_LIT:2>],<EOL>pctShared = <NUM_LIT>, seqGenMode = '<STR_LIT>',<EOL>shouldFail = False):

print("<STR_LIT>")<EOL>nFailed = <NUM_LIT:0><EOL>subsequenceStartPos = <NUM_LIT:10><EOL>assert subsequenceStartPos < sequenceLength<EOL>for numSequences in nSequences:<EOL><INDENT>print("<STR_LIT>",sequenceLength, end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>",cellsPerColumn,"<STR_LIT>",nTests,"<STR_LIT>", numCols)<EOL>print("<STR_LIT>",numSequences, "<STR_LIT>", pctShared, end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>", seqGenMode)<EOL>for k in range(nTests): <EOL><INDENT>trainingSet = buildTrainingSet(numSequences = numSequences,<EOL>sequenceLength = sequenceLength,<EOL>pctShared = pctShared, seqGenMode = seqGenMode,<EOL>subsequenceStartPos = subsequenceStartPos,<EOL>numCols = numCols,<EOL>minOnes = <NUM_LIT>, maxOnes = <NUM_LIT>)<EOL>print("<STR_LIT>")<EOL>numFailures3, numStrictErrors3, numPerfect3, tm3 =_testSequence(trainingSet,<EOL>nTrainingReps = <NUM_LIT:10>,<EOL>numberOfCols = numCols,<EOL>cellsPerColumn = cellsPerColumn,<EOL>initialPerm = <NUM_LIT>,<EOL>connectedPerm = <NUM_LIT>,<EOL>minThreshold = <NUM_LIT:12>,<EOL>permanenceInc = <NUM_LIT>,<EOL>permanenceDec = <NUM_LIT:0.1>,<EOL>permanenceMax = <NUM_LIT:1>,<EOL>globalDecay = <NUM_LIT>,<EOL>newSynapseCount = <NUM_LIT:15>,<EOL>activationThreshold = <NUM_LIT:12>,<EOL>doPooling = False,<EOL>shouldFail = shouldFail)<EOL>print("<STR_LIT>")<EOL>numFailures, numStrictErrors, numPerfect, tm2 =_testSequence(trainingSet,<EOL>nTrainingReps = <NUM_LIT:2>,<EOL>numberOfCols = numCols,<EOL>cellsPerColumn = cellsPerColumn,<EOL>initialPerm = <NUM_LIT>,<EOL>connectedPerm = <NUM_LIT>,<EOL>minThreshold = <NUM_LIT:12>,<EOL>permanenceInc = <NUM_LIT>,<EOL>permanenceDec = <NUM_LIT:0>,<EOL>permanenceMax = <NUM_LIT:1>,<EOL>globalDecay = <NUM_LIT>,<EOL>newSynapseCount = <NUM_LIT:15>,<EOL>activationThreshold = <NUM_LIT:12>,<EOL>doPooling = False,<EOL>shouldFail = shouldFail)<EOL>print("<STR_LIT>")<EOL>numFailures1, numStrictErrors1, numPerfect1, tm1 =_testSequence(trainingSet,<EOL>nTrainingReps = <NUM_LIT:1>,<EOL>numberOfCols = numCols,<EOL>cellsPerColumn = cellsPerColumn,<EOL>initialPerm = <NUM_LIT>,<EOL>connectedPerm = <NUM_LIT>,<EOL>minThreshold = <NUM_LIT:12>,<EOL>permanenceInc = <NUM_LIT>,<EOL>permanenceDec = <NUM_LIT:0>,<EOL>permanenceMax = <NUM_LIT:1>,<EOL>globalDecay = <NUM_LIT>,<EOL>newSynapseCount = <NUM_LIT:15>,<EOL>activationThreshold = <NUM_LIT:12>,<EOL>doPooling = False,<EOL>shouldFail = shouldFail)<EOL>segmentInfo1 = tm1.getSegmentInfo()<EOL>segmentInfo2 = tm2.getSegmentInfo()<EOL>if (abs(segmentInfo1[<NUM_LIT:0>] - segmentInfo2[<NUM_LIT:0>]) > <NUM_LIT:3>) or(abs(segmentInfo1[<NUM_LIT:1>] - segmentInfo2[<NUM_LIT:1>]) > <NUM_LIT:3>*<NUM_LIT:15>) :<EOL><INDENT>print("<STR_LIT>")<EOL>print(segmentInfo1)<EOL>print(segmentInfo2)<EOL>print(tm3.getSegmentInfo())<EOL>tm3.trimSegments()<EOL>print(tm3.getSegmentInfo())<EOL>print("<STR_LIT>")<EOL>print(numFailures1, numStrictErrors1, numPerfect1)<EOL>print(numFailures, numStrictErrors, numPerfect)<EOL>print(numFailures3, numStrictErrors3, numPerfect3)<EOL>numFailures += <NUM_LIT:1><EOL><DEDENT>if numFailures == <NUM_LIT:0> and not shouldFailor numFailures > <NUM_LIT:0> and shouldFail:<EOL><INDENT>print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>if shouldFail:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>print()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL>nFailed = nFailed + <NUM_LIT:1><EOL>print("<STR_LIT>", numFailures)<EOL>print("<STR_LIT>", numStrictErrors)<EOL>print("<STR_LIT>", numPerfect)<EOL><DEDENT><DEDENT><DEDENT>return nFailed<EOL>

Still need to test:
    Two overlapping sequences. OK to get new segments but check that we can
    get correct high order prediction after multiple reps.


numPatterns = <NUM_LIT><EOL>p = getSimplePatterns(numOnes, numPatterns)<EOL>s = []<EOL>s.append(p[rgen.randint(<NUM_LIT:5>,numPatterns)])<EOL>for i in range(<NUM_LIT:50>):<EOL><INDENT>r = rgen.randint(<NUM_LIT:5>,numPatterns)<EOL>print(r, end='<STR_LIT:U+0020>')<EOL>s.append(p[r])<EOL>if rgen.binomial(<NUM_LIT:1>, <NUM_LIT:0.5>) > <NUM_LIT:0>:<EOL><INDENT>print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>s.append(p[<NUM_LIT:0>])<EOL>s.append(p[<NUM_LIT:1>])<EOL>s.append(p[<NUM_LIT:2>])<EOL>s.append(p[<NUM_LIT:4>])<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>s.append(p[<NUM_LIT:1>])<EOL>s.append(p[<NUM_LIT:2>])<EOL>s.append(p[<NUM_LIT:3>])<EOL><DEDENT>r = rgen.randint(<NUM_LIT:5>,numPatterns)<EOL>s.append(p[r])<EOL>print(r, end='<STR_LIT:U+0020>')<EOL><DEDENT>print()<EOL>return ([s], [ [p[<NUM_LIT:0>], p[<NUM_LIT:1>], p[<NUM_LIT:2>], p[<NUM_LIT:4>]],  [p[<NUM_LIT:1>], p[<NUM_LIT:2>], p[<NUM_LIT:3>]] ])<EOL>

Simple sequences for HL0b. Each pattern in the sequence has a series of 1's
    in a specific set of columns.
      There are 23 patterns, p0 to p22.
      The sequences we want to learn are p1->p2->p3 and p0->p1->p2->p4.
      We create a very long sequence consisting of these two sub-sequences
      intermixed with noise, such as:
            N N p0 p1 p2 p4 N N p1 p2 p3 N N p1 p2 p3
      N is randomly chosen from p5 to p22


numCols = numOnes * numPatterns<EOL>p = []<EOL>for i in range(numPatterns):<EOL><INDENT>x = numpy.zeros(numCols, dtype='<STR_LIT>')<EOL>x[i*numOnes:(i+<NUM_LIT:1>)*numOnes] = <NUM_LIT:1><EOL>p.append(x)<EOL><DEDENT>return p<EOL>

Very simple patterns. Each pattern has numOnes consecutive
    bits on. There are numPatterns*numOnes bits in the vector.


def buildSequencePool(numSequences = <NUM_LIT:10>,<EOL>seqLen = [<NUM_LIT:2>,<NUM_LIT:3>,<NUM_LIT:4>],<EOL>numPatterns = <NUM_LIT:5>,<EOL>numOnBitsPerPattern = <NUM_LIT:3>,<EOL>patternOverlap = <NUM_LIT:0>,<EOL>**kwargs<EOL>):

<EOL>patterns = getSimplePatterns(numOnBitsPerPattern, numPatterns, patternOverlap)<EOL>numCols = len(patterns[<NUM_LIT:0>])<EOL>trainingSequences = []<EOL>for i in range(numSequences):<EOL><INDENT>sequence = []<EOL>length = random.choice(seqLen)<EOL>for j in range(length):<EOL><INDENT>patIdx = random.choice(range(numPatterns))<EOL>sequence.append(patterns[patIdx])<EOL><DEDENT>trainingSequences.append(sequence)<EOL><DEDENT>if VERBOSITY >= <NUM_LIT:3>:<EOL><INDENT>print("<STR_LIT>")<EOL>printAllTrainingSequences(trainingSequences)<EOL><DEDENT>return (numCols, trainingSequences)<EOL>

Create a bunch of sequences of various lengths, all built from
    a fixed set of patterns.

    Parameters:
    -----------------------------------------------------
    numSequences:         Number of training sequences to generate
    seqLen:               List of possible sequence lengths
    numPatterns:          How many possible patterns there are to use within
                            sequences
    numOnBitsPerPattern:  Number of ON bits in each TM input pattern
    patternOverlap:       Max number of bits of overlap between any 2 patterns
    retval:               (numCols, trainingSequences)
                            numCols - width of the patterns
                            trainingSequences - a list of training sequences


def createTMs(includeCPP = True,<EOL>includePy = True,<EOL>numCols = <NUM_LIT:100>,<EOL>cellsPerCol = <NUM_LIT:4>,<EOL>activationThreshold = <NUM_LIT:3>,<EOL>minThreshold = <NUM_LIT:3>,<EOL>newSynapseCount = <NUM_LIT:3>,<EOL>initialPerm = <NUM_LIT>,<EOL>permanenceInc = <NUM_LIT:0.1>,<EOL>permanenceDec = <NUM_LIT:0.0>,<EOL>globalDecay = <NUM_LIT:0.0>,<EOL>pamLength = <NUM_LIT:0>,<EOL>checkSynapseConsistency = True,<EOL>maxInfBacktrack = <NUM_LIT:0>,<EOL>maxLrnBacktrack = <NUM_LIT:0>,<EOL>**kwargs<EOL>):

<EOL>connectedPerm = <NUM_LIT:0.5><EOL>tms = dict()<EOL>if includeCPP:<EOL><INDENT>if VERBOSITY >= <NUM_LIT:2>:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>cpp_tm = BacktrackingTMCPP(numberOfCols = numCols, cellsPerColumn = cellsPerCol,<EOL>initialPerm = initialPerm, connectedPerm = connectedPerm,<EOL>minThreshold = minThreshold, newSynapseCount = newSynapseCount,<EOL>permanenceInc = permanenceInc, permanenceDec = permanenceDec,<EOL>activationThreshold = activationThreshold,<EOL>globalDecay = globalDecay, burnIn = <NUM_LIT:1>,<EOL>seed=SEED, verbosity=VERBOSITY,<EOL>checkSynapseConsistency = checkSynapseConsistency,<EOL>collectStats = True,<EOL>pamLength = pamLength,<EOL>maxInfBacktrack = maxInfBacktrack,<EOL>maxLrnBacktrack = maxLrnBacktrack,<EOL>)<EOL>cpp_tm.retrieveLearningStates = True<EOL>tms['<STR_LIT>'] = cpp_tm<EOL><DEDENT>if includePy:<EOL><INDENT>if VERBOSITY >= <NUM_LIT:2>:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>py_tm = BacktrackingTM(numberOfCols = numCols, cellsPerColumn = cellsPerCol,<EOL>initialPerm = initialPerm, connectedPerm = connectedPerm,<EOL>minThreshold = minThreshold, newSynapseCount = newSynapseCount,<EOL>permanenceInc = permanenceInc, permanenceDec = permanenceDec,<EOL>activationThreshold = activationThreshold,<EOL>globalDecay = globalDecay, burnIn = <NUM_LIT:1>,<EOL>seed=SEED, verbosity=VERBOSITY,<EOL>collectStats = True,<EOL>pamLength = pamLength,<EOL>maxInfBacktrack = maxInfBacktrack,<EOL>maxLrnBacktrack = maxLrnBacktrack,<EOL>)<EOL>tms['<STR_LIT>'] = py_tm<EOL><DEDENT>return tms<EOL>

Create one or more TM instances, placing each into a dict keyed by
    name.

    Parameters:
    ------------------------------------------------------------------
    retval:   tms - dict of TM instances


print('<STR_LIT>'.join('<STR_LIT:1>' if k != <NUM_LIT:0> else '<STR_LIT:.>' for k in x))<EOL>


def getSimplePatterns(numOnes, numPatterns, patternOverlap=<NUM_LIT:0>):

assert (patternOverlap < numOnes)<EOL>numNewBitsInEachPattern = numOnes - patternOverlap<EOL>numCols = numNewBitsInEachPattern * numPatterns + patternOverlap<EOL>p = []<EOL>for i in range(numPatterns):<EOL><INDENT>x = numpy.zeros(numCols, dtype='<STR_LIT>')<EOL>startBit = i*numNewBitsInEachPattern<EOL>nextStartBit = startBit + numOnes<EOL>x[startBit:nextStartBit] = <NUM_LIT:1><EOL>p.append(x)<EOL><DEDENT>return p<EOL>

Very simple patterns. Each pattern has numOnes consecutive
    bits on. The amount of overlap between consecutive patterns is
    configurable, via the patternOverlap parameter.

    Parameters:
    -----------------------------------------------------------------------
    numOnes:        Number of bits ON in each pattern
    numPatterns:    Number of unique patterns to generate
    patternOverlap: Number of bits of overlap between each successive pattern
    retval:         patterns


if len(tms) == <NUM_LIT:1>:<EOL><INDENT>return<EOL><DEDENT>if len(tms) > <NUM_LIT:2>:<EOL><INDENT>raise "<STR_LIT>"<EOL><DEDENT>same = fdrutils.tmDiff2(*list(tms.values()), verbosity=VERBOSITY)<EOL>assert(same)<EOL>return<EOL>

Check for diffs among the TM instances in the passed in tms dict and
raise an assert if any are detected

Parameters:
---------------------------------------------------------------------
tms:                  dict of TM instances


def _createTMs(numCols, cellsPerColumn=<NUM_LIT:4>, checkSynapseConsistency=True):

<EOL>minThreshold = <NUM_LIT:4><EOL>activationThreshold = <NUM_LIT:4><EOL>newSynapseCount = <NUM_LIT:5><EOL>initialPerm = <NUM_LIT><EOL>connectedPerm = <NUM_LIT:0.5><EOL>permanenceInc = <NUM_LIT:0.1><EOL>permanenceDec = <NUM_LIT><EOL>globalDecay = <NUM_LIT:0.0><EOL>if VERBOSITY > <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>cppTm = BacktrackingTMCPP(numberOfCols=numCols, cellsPerColumn=cellsPerColumn,<EOL>initialPerm=initialPerm, connectedPerm=connectedPerm,<EOL>minThreshold=minThreshold, newSynapseCount=newSynapseCount,<EOL>permanenceInc=permanenceInc, permanenceDec=permanenceDec,<EOL>activationThreshold=activationThreshold,<EOL>globalDecay=globalDecay, burnIn=<NUM_LIT:1>,<EOL>seed=SEED, verbosity=VERBOSITY,<EOL>checkSynapseConsistency=checkSynapseConsistency,<EOL>pamLength=<NUM_LIT:1000>)<EOL>if VERBOSITY > <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>pyTm = BacktrackingTM(numberOfCols=numCols, cellsPerColumn=cellsPerColumn,<EOL>initialPerm=initialPerm, connectedPerm=connectedPerm,<EOL>minThreshold=minThreshold, newSynapseCount=newSynapseCount,<EOL>permanenceInc=permanenceInc, permanenceDec=permanenceDec,<EOL>activationThreshold=activationThreshold,<EOL>globalDecay=globalDecay, burnIn=<NUM_LIT:1>,<EOL>seed=SEED, verbosity=VERBOSITY,<EOL>pamLength=<NUM_LIT:1000>)<EOL>return cppTm, pyTm<EOL>

Create TM and BacktrackingTMCPP instances with identical parameters.


def _computeTMMetric(tm=None, sequences=None, useResets=True, verbosity=<NUM_LIT:1>):

datasetScore = <NUM_LIT:0><EOL>numPredictions = <NUM_LIT:0><EOL>tm.resetStats()<EOL>for seqIdx, seq in enumerate(sequences):<EOL><INDENT>if useResets:<EOL><INDENT>tm.reset()<EOL><DEDENT>seq = numpy.array(seq, dtype='<STR_LIT>')<EOL>if verbosity > <NUM_LIT:2>:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>for i, inputPattern in enumerate(seq):<EOL><INDENT>if verbosity > <NUM_LIT:2>:<EOL><INDENT>print("<STR_LIT>" % (seqIdx, i), end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>", inputPattern)<EOL><DEDENT>y = tm.infer(inputPattern)<EOL>if verbosity > <NUM_LIT:2>:<EOL><INDENT>stats = tm.getStats()<EOL>if stats['<STR_LIT>'] > <NUM_LIT:0>:<EOL><INDENT>print("<STR_LIT>", stats['<STR_LIT>'])<EOL><DEDENT><DEDENT>if verbosity > <NUM_LIT:3>:<EOL><INDENT>print("<STR_LIT>")<EOL>predOut = numpy.sum(tm.predictedState['<STR_LIT:t>'], axis=<NUM_LIT:1>)<EOL>actOut  = numpy.sum(tm.activeState['<STR_LIT:t>'], axis=<NUM_LIT:1>)<EOL>outout  = numpy.sum(y.reshape(tm.activeState['<STR_LIT:t>'].shape), axis=<NUM_LIT:1>)<EOL>print("<STR_LIT>", predOut.nonzero())<EOL>print("<STR_LIT>", actOut.nonzero())<EOL>print("<STR_LIT>", inputPattern.nonzero())<EOL>print("<STR_LIT>", outout.nonzero())<EOL><DEDENT><DEDENT><DEDENT>stats = tm.getStats()<EOL>datasetScore = stats['<STR_LIT>']<EOL>numPredictions = stats['<STR_LIT>']<EOL>print("<STR_LIT>", datasetScore, end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>", numPredictions)<EOL>return datasetScore, numPredictions<EOL>

Given a trained TM and a list of sequences, compute the temporal memory
    performance metric on those sequences.

    Parameters:
    ===========
    tm:               A trained temporal memory.
    sequences:        A list of sequences. Each sequence is a list of numpy
                      vectors.
    useResets:        If True, the TM's reset method will be called before the
                      the start of each new sequence.
    verbosity:        An integer controlling the level of printouts. The higher
                      the number the more debug printouts.

    Return value:
    ============
    The following pair is returned:  (score, numPredictions)

    score:            The average prediction score per pattern.
    numPredictions:   The total number of predictions that were made.


def _getSimplePatterns(self, numOnes, numPatterns):

Very simple patterns. Each pattern has numOnes consecutive
        bits on. There are numPatterns*numOnes bits in the vector. These patterns
        are used as elements of sequences when building up a training set.


def _setVerbosity(self, verbosity, tm, tmPy):

tm.cells4.setVerbosity(verbosity)<EOL>tm.verbosity = verbosity<EOL>tmPy.verbosity = verbosity<EOL>


def _createTMs(self, numCols, fixedResources=False,<EOL>checkSynapseConsistency = True):

<EOL>minThreshold = <NUM_LIT:4><EOL>activationThreshold = <NUM_LIT:8><EOL>newSynapseCount = <NUM_LIT:15><EOL>initialPerm = <NUM_LIT><EOL>connectedPerm = <NUM_LIT:0.5><EOL>permanenceInc = <NUM_LIT:0.1><EOL>permanenceDec = <NUM_LIT><EOL>if fixedResources:<EOL><INDENT>permanenceDec = <NUM_LIT:0.1><EOL>maxSegmentsPerCell = <NUM_LIT:5><EOL>maxSynapsesPerSegment = <NUM_LIT:15><EOL>globalDecay = <NUM_LIT:0><EOL>maxAge = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>permanenceDec = <NUM_LIT><EOL>maxSegmentsPerCell = -<NUM_LIT:1><EOL>maxSynapsesPerSegment = -<NUM_LIT:1><EOL>globalDecay = <NUM_LIT><EOL>maxAge = <NUM_LIT:1><EOL><DEDENT>if g_testCPPTM:<EOL><INDENT>if g_options.verbosity > <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>cppTM = BacktrackingTMCPP(numberOfCols = numCols, cellsPerColumn = <NUM_LIT:4>,<EOL>initialPerm = initialPerm, connectedPerm = connectedPerm,<EOL>minThreshold = minThreshold,<EOL>newSynapseCount = newSynapseCount,<EOL>permanenceInc = permanenceInc,<EOL>permanenceDec = permanenceDec,<EOL>activationThreshold = activationThreshold,<EOL>globalDecay = globalDecay, maxAge=maxAge, burnIn = <NUM_LIT:1>,<EOL>seed=g_options.seed, verbosity=g_options.verbosity,<EOL>checkSynapseConsistency = checkSynapseConsistency,<EOL>pamLength = <NUM_LIT:1000>,<EOL>maxSegmentsPerCell = maxSegmentsPerCell,<EOL>maxSynapsesPerSegment = maxSynapsesPerSegment,<EOL>)<EOL>cppTM.retrieveLearningStates = True<EOL><DEDENT>else:<EOL><INDENT>cppTM = None<EOL><DEDENT>if g_options.verbosity > <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>pyTM = BacktrackingTM(numberOfCols = numCols, cellsPerColumn = <NUM_LIT:4>,<EOL>initialPerm = initialPerm,<EOL>connectedPerm = connectedPerm,<EOL>minThreshold = minThreshold,<EOL>newSynapseCount = newSynapseCount,<EOL>permanenceInc = permanenceInc,<EOL>permanenceDec = permanenceDec,<EOL>activationThreshold = activationThreshold,<EOL>globalDecay = globalDecay, maxAge=maxAge, burnIn = <NUM_LIT:1>,<EOL>seed=g_options.seed, verbosity=g_options.verbosity,<EOL>pamLength = <NUM_LIT:1000>,<EOL>maxSegmentsPerCell = maxSegmentsPerCell,<EOL>maxSynapsesPerSegment = maxSynapsesPerSegment,<EOL>)<EOL>return cppTM, pyTM<EOL>

Create an instance of the appropriate temporal memory. We isolate
        all parameters as constants specified here.


if short==<NUM_LIT:0>:<EOL><INDENT>LOGGER.info("<STR_LIT>")<EOL>numPatterns = numpy.random.randint(<NUM_LIT>, <NUM_LIT>)<EOL>numClasses = numpy.random.randint(<NUM_LIT:50>, <NUM_LIT>)<EOL><DEDENT>elif short==<NUM_LIT:1>:<EOL><INDENT>LOGGER.info("<STR_LIT>")<EOL>numPatterns = numpy.random.randint(<NUM_LIT>, <NUM_LIT>)<EOL>numClasses = numpy.random.randint(<NUM_LIT:50>, <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>LOGGER.info("<STR_LIT>")<EOL>numPatterns = numpy.random.randint(<NUM_LIT>, <NUM_LIT>)<EOL>numClasses = numpy.random.randint(<NUM_LIT:30>, <NUM_LIT:1000>)<EOL><DEDENT>LOGGER.info("<STR_LIT>", numPatterns)<EOL>LOGGER.info("<STR_LIT>", numClasses)<EOL>return numPatterns, numClasses<EOL>

Return the number of patterns and classes the test should use.


def runTestKNNClassifier(self, short = <NUM_LIT:0>):

failures = "<STR_LIT>"<EOL>if short != <NUM_LIT:2>:<EOL><INDENT>numpy.random.seed(<NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>seed_value = int(time.time())<EOL>numpy.random.seed(seed_value)<EOL>LOGGER.info('<STR_LIT>', seed_value)<EOL>f = open('<STR_LIT>', '<STR_LIT:a>')<EOL>f.write(str(seed_value))<EOL>f.write('<STR_LIT:\n>')<EOL>f.close()<EOL><DEDENT>failures += simulateKMoreThanOne()<EOL>LOGGER.info("<STR_LIT>")<EOL>numPatterns, numClasses = getNumTestPatterns(short)<EOL>patternSize = <NUM_LIT:100><EOL>patterns = numpy.random.rand(numPatterns, patternSize)<EOL>patternDict = dict()<EOL>testDict = dict()<EOL>for i in xrange(numPatterns):<EOL><INDENT>patternDict[i] = dict()<EOL>patternDict[i]['<STR_LIT>'] = patterns[i]<EOL>patternDict[i]['<STR_LIT>'] = numpy.random.randint(<NUM_LIT:0>, numClasses-<NUM_LIT:1>)<EOL>testDict[i] = copy.deepcopy(patternDict[i])<EOL>testDict[i]['<STR_LIT>'][:int(<NUM_LIT>*patternSize)] = numpy.random.rand()<EOL>testDict[i]['<STR_LIT>'] = None<EOL><DEDENT>LOGGER.info("<STR_LIT>")<EOL>knn = KNNClassifier(k=<NUM_LIT:1>)<EOL>failures += simulateClassifier(knn, patternDict,"<STR_LIT>")<EOL>LOGGER.info("<STR_LIT>")<EOL>knnL1 = KNNClassifier(k=<NUM_LIT:1>, distanceNorm=<NUM_LIT:1.0>)<EOL>failures += simulateClassifier(knnL1, patternDict,"<STR_LIT>")<EOL>LOGGER.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>knnExact = KNNClassifier(k=<NUM_LIT:1>, exact=True)<EOL>failures += simulateClassifier(knnExact,<EOL>patternDict,<EOL>"<STR_LIT>",<EOL>testDict=testDict)<EOL>numPatterns, numClasses = getNumTestPatterns(short)<EOL>patterns = (numpy.random.rand(numPatterns, <NUM_LIT>) > <NUM_LIT>).astype(RealNumpyDType)<EOL>patternDict = dict()<EOL>for i in patterns:<EOL><INDENT>iString = str(i.tolist())<EOL>if not patternDict.has_key(iString):<EOL><INDENT>randCategory = numpy.random.randint(<NUM_LIT:0>, numClasses-<NUM_LIT:1>)<EOL>patternDict[iString] = dict()<EOL>patternDict[iString]['<STR_LIT>'] = i<EOL>patternDict[iString]['<STR_LIT>'] = randCategory<EOL><DEDENT><DEDENT>LOGGER.info("<STR_LIT>")<EOL>knnDense = KNNClassifier(k=<NUM_LIT:1>)<EOL>failures += simulateClassifier(knnDense, patternDict,"<STR_LIT>")<EOL>self.assertEqual(len(failures), <NUM_LIT:0>,<EOL>"<STR_LIT>" + failures)<EOL>if short == <NUM_LIT:2>:<EOL><INDENT>f = open('<STR_LIT>', '<STR_LIT:a>')<EOL>f.write('<STR_LIT>')<EOL>f.close()<EOL><DEDENT>

Test the KNN classifier in this module. short can be:
            0 (short), 1 (medium), or 2 (long)


failures = "<STR_LIT>"<EOL>LOGGER.info("<STR_LIT>")<EOL>knn = KNNClassifier(k=<NUM_LIT:3>)<EOL>v = numpy.zeros((<NUM_LIT:6>, <NUM_LIT:2>))<EOL>v[<NUM_LIT:0>] = [<NUM_LIT:1.0>, <NUM_LIT:0.0>]<EOL>v[<NUM_LIT:1>] = [<NUM_LIT:1.0>, <NUM_LIT>]<EOL>v[<NUM_LIT:2>] = [<NUM_LIT:1.0>, <NUM_LIT>]<EOL>v[<NUM_LIT:3>] = [<NUM_LIT:1.0>, <NUM_LIT>]<EOL>v[<NUM_LIT:4>] = [<NUM_LIT:1.0>, <NUM_LIT>]<EOL>v[<NUM_LIT:5>] = [<NUM_LIT:1.0>, <NUM_LIT>]<EOL>knn.learn(v[<NUM_LIT:0>], <NUM_LIT:0>)<EOL>knn.learn(v[<NUM_LIT:1>], <NUM_LIT:0>)<EOL>knn.learn(v[<NUM_LIT:2>], <NUM_LIT:0>)<EOL>knn.learn(v[<NUM_LIT:3>], <NUM_LIT:1>)<EOL>knn.learn(v[<NUM_LIT:4>], <NUM_LIT:1>)<EOL>knn.learn(v[<NUM_LIT:5>], <NUM_LIT:1>)<EOL>winner, _inferenceResult, _dist, _categoryDist = knn.infer(v[<NUM_LIT:0>])<EOL>if winner != <NUM_LIT:0>:<EOL><INDENT>failures += "<STR_LIT>"<EOL><DEDENT>winner, _inferenceResult, _dist, _categoryDist = knn.infer(v[<NUM_LIT:2>])<EOL>if winner != <NUM_LIT:0>:<EOL><INDENT>failures += "<STR_LIT>"<EOL><DEDENT>winner, _inferenceResult, _dist, _categoryDist = knn.infer(v[<NUM_LIT:3>])<EOL>if winner != <NUM_LIT:0>:<EOL><INDENT>failures += "<STR_LIT>"<EOL><DEDENT>winner, _inferenceResult, _dist, _categoryDist = knn.infer(v[<NUM_LIT:5>])<EOL>if winner != <NUM_LIT:1>:<EOL><INDENT>failures += "<STR_LIT>"<EOL><DEDENT>if len(failures) == <NUM_LIT:0>:<EOL><INDENT>LOGGER.info("<STR_LIT>")<EOL><DEDENT>return failures<EOL>


tmpDir = tempfile.mkdtemp()<EOL>tmpFileName = os.path.join(tmpDir, os.path.basename(filename))<EOL>return tmpDir, tmpFileName<EOL>

Create a temp directory, and return path to filename in that directory


def runBaseDescriptionAndPermutations(self, expDesc, hsVersion, maxModels=<NUM_LIT:2>):

<EOL>self.getModules(expDesc, hsVersion=hsVersion)<EOL>permutationsPyPath = os.path.join(g_myEnv.testOutDir, "<STR_LIT>")<EOL>args = [g_myEnv.testOutDir]<EOL>from nupic.frameworks.opf.experiment_runner import runExperiment<EOL>LOGGER.info("<STR_LIT>")<EOL>LOGGER.info("<STR_LIT>")<EOL>LOGGER.info("<STR_LIT>")<EOL>LOGGER.info("<STR_LIT>")<EOL>runExperiment(args)<EOL>jobParams = {'<STR_LIT>' : generatePersistentJobGUID(),<EOL>'<STR_LIT>': permutationsPyPath,<EOL>'<STR_LIT>': hsVersion,<EOL>}<EOL>if maxModels is not None:<EOL><INDENT>jobParams['<STR_LIT>'] = maxModels<EOL><DEDENT>args = ['<STR_LIT>', '<STR_LIT>' % (json.dumps(jobParams))]<EOL>self.resetExtraLogItems()<EOL>self.addExtraLogItem({'<STR_LIT>':jobParams})<EOL>LOGGER.info("<STR_LIT>")<EOL>LOGGER.info("<STR_LIT>")<EOL>LOGGER.info("<STR_LIT>")<EOL>LOGGER.info("<STR_LIT>")<EOL>jobID = hypersearch_worker.main(args)<EOL>cjDAO = ClientJobsDAO.get()<EOL>models = cjDAO.modelsGetUpdateCounters(jobID)<EOL>modelIDs = [model.modelId for model in models]<EOL>results = cjDAO.modelsGetResultAndStatus(modelIDs)<EOL>if maxModels is not None:<EOL><INDENT>self.assertEqual(len(results), maxModels, "<STR_LIT>"<EOL>"<STR_LIT>" % (maxModels, len(results)))<EOL><DEDENT>for result in results:<EOL><INDENT>self.assertEqual(result.completionReason, cjDAO.CMPL_REASON_EOF,<EOL>"<STR_LIT>" % (result.completionMsg))<EOL><DEDENT>return results<EOL>

This does the following:

        1.) Calls ExpGenerator to generate a base description file and permutations
        file from expDescription.

        2.) Verifies that description.py and permutations.py are valid python
        modules that can be loaded

        3.) Runs the base description.py as an experiment using OPF RunExperiment.

        4.) Runs a Hypersearch using the generated permutations.py by passing it
        to HypersearchWorker.

        Parameters:
        -------------------------------------------------------------------
        expDesc:       JSON format experiment description
        hsVersion:     which version of hypersearch to use ('v2'; 'v1' was dropped)
        retval:        list of model results


def getModules(self, expDesc, hsVersion='<STR_LIT>'):

<EOL>shutil.rmtree(g_myEnv.testOutDir, ignore_errors=True)<EOL>args = [<EOL>"<STR_LIT>" % (json.dumps(expDesc)),<EOL>"<STR_LIT>" % (g_myEnv.testOutDir),<EOL>"<STR_LIT>" % (hsVersion)<EOL>]<EOL>self.addExtraLogItem({'<STR_LIT:args>':args})<EOL>experiment_generator.expGenerator(args)<EOL>descriptionPyPath = os.path.join(g_myEnv.testOutDir, "<STR_LIT>")<EOL>permutationsPyPath = os.path.join(g_myEnv.testOutDir, "<STR_LIT>")<EOL>return (self.checkPythonScript(descriptionPyPath),<EOL>self.checkPythonScript(permutationsPyPath))<EOL>

This does the following:

        1.) Calls ExpGenerator to generate a base description file and permutations
        file from expDescription.

        2.) Verifies that description.py and permutations.py are valid python
        modules that can be loaded

        3.) Returns the loaded base description module and permutations module

        Parameters:
        -------------------------------------------------------------------
        expDesc:       JSON format experiment description
        hsVersion:     which version of hypersearch to use ('v2'; 'v1' was dropped)
        retval:        (baseModule, permutationsModule)


global g_myEnv<EOL>if not g_myEnv:<EOL><INDENT>params = type('<STR_LIT>', (object,), {'<STR_LIT>' : resource_filename("<STR_LIT>", "<STR_LIT>")})<EOL>g_myEnv = MyTestEnvironment(params)<EOL><DEDENT>

Method called to prepare the test fixture. This is called by the
        unittest framework immediately before calling the test method; any exception
        raised by this method will be considered an error rather than a test
        failure. The default implementation does nothing.


suiteNames = ['<STR_LIT>']<EOL>testNames = []<EOL>for suite in suiteNames:<EOL><INDENT>for f in dir(eval(suite)):<EOL><INDENT>if f.startswith('<STR_LIT:test>'):<EOL><INDENT>testNames.append('<STR_LIT>' % (suite, f))<EOL><DEDENT><DEDENT><DEDENT>return testNames<EOL>

Get the list of tests that can be run from this module


<EOL>csvReader = self._openCsvFile(filepath)<EOL>names = next(csvReader)<EOL>_types = next(csvReader)<EOL>_specials = next(csvReader)<EOL>return (csvReader, names)<EOL>

Open an OPF prediction CSV file and advance it to the first data row

        Returns:      the tuple (csvReader, fieldNames), where 'csvReader' is the
                      csv reader object, and 'fieldNames' is a sequence of field
                      names.


return None<EOL>

Override to force unittest framework to use test method names instead
        of docstrings in the report.


<EOL>command = [<EOL>"<STR_LIT>",<EOL>runnerPath,<EOL>experimentDirPath,<EOL>]<EOL>command.extend(customOptions)<EOL>if short:<EOL><INDENT>command.append("<STR_LIT>")<EOL><DEDENT>self.addExtraLogItem({'<STR_LIT>':command})<EOL>r = _executeExternalCmdAndReapOutputs(command)<EOL>self.addExtraLogItem({'<STR_LIT:result>':r})<EOL>_debugOut(("<STR_LIT>") % (command, r))<EOL>self.assertEqual(r['<STR_LIT>'], <NUM_LIT:0>,<EOL>("<STR_LIT>") %(runnerPath, r['<STR_LIT>'],))<EOL>self.resetExtraLogItems()<EOL>return r<EOL>

Executes a positive RunExperiment.py test and performs
        basic validation

        runnerPath:         experiment running (LPF or OPF RunExperiment.py path)

        experimentDirPath:  directory containing the description.py file of interest

        short:              if True, attempt to run the experiment with --testMode
                            flag turned on, which causes all inference and training
                            iteration counts to be overridden with small counts.
                            NOTE: if the (possibly aggregated) dataset has fewer
                            rows than the count overrides, then an LPF experiment
                            will fail.

        Returns:            result from _executeExternalCmdAndReapOutputs


import inspect<EOL>frameObj = inspect.stack()[<NUM_LIT:2>][<NUM_LIT:0>]<EOL>return inspect.getframeinfo(frameObj)<EOL>

Returns: Traceback namedtuple for our caller's caller


excludedDirectories = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>excludedDirectories.extend(excludedExperiments)<EOL>return getAllDirectoriesWithFile(<EOL>path="<STR_LIT>",<EOL>filename="<STR_LIT>",<EOL>excludeDirs=excludedDirectories)<EOL>

Experiment directories are the directories with a description.py file


handle = tempfile.NamedTemporaryFile(prefix="<STR_LIT:test>", suffix="<STR_LIT>", dir="<STR_LIT:.>")<EOL>filename = handle.name<EOL>handle.close()<EOL>return filename<EOL>


def _aggregate(input, options, output, timeFieldName):

aggregator = Aggregator(aggregationInfo=options, <EOL>inputFields=input.getFields(),<EOL>timeFieldName=timeFieldName)<EOL>while True:<EOL><INDENT>inRecord = input.getNextRecord()<EOL>print("<STR_LIT>", inRecord)<EOL>(outRecord, aggBookmark) = aggregator.next(record = inRecord, <EOL>curInputBookmark = None)<EOL>print("<STR_LIT>", outRecord)<EOL>if outRecord is not None:<EOL><INDENT>output.appendRecord(outRecord, None)<EOL><DEDENT>if inRecord is None and outRecord is None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>

Aggregate the input stream and write aggregated records to the output
    stream


<EOL>return True<EOL>

This function can be used to selectively filter out specific permutation
    combinations. It is called by RunPermutations for every possible permutation
    of the variables in the permutations dict. It should return True for valid a
    combination of permutation values and False for an invalid one.

    Parameters:
    ---------------------------------------------------------
    perm: dict of one possible combination of name:value
          pairs chosen from permutations.


errScore = <NUM_LIT:50><EOL>errScore += abs(perm['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'] - <NUM_LIT>)<EOL>errScore += abs(perm['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT:n>'] - <NUM_LIT>)<EOL>if perm['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT:address>'] is not None:<EOL><INDENT>errScore -= <NUM_LIT:20><EOL><DEDENT>if perm['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'] is not None:<EOL><INDENT>errScore -= <NUM_LIT:10><EOL><DEDENT>waitTime = None<EOL>if eval(os.environ.get('<STR_LIT>', '<STR_LIT:False>')):<EOL><INDENT>if perm['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'] is not None:<EOL><INDENT>waitTime = <NUM_LIT><EOL><DEDENT><DEDENT>dummyModelParams = dict(<EOL>metricValue = errScore,<EOL>iterations = int(os.environ.get('<STR_LIT>', '<STR_LIT:1>')),<EOL>waitTime = waitTime,<EOL>sysExitModelRange = os.environ.get('<STR_LIT>',<EOL>None),<EOL>errModelRange = os.environ.get('<STR_LIT>',<EOL>None),<EOL>jobFailErr = bool(os.environ.get('<STR_LIT>', False))<EOL>)<EOL>return dummyModelParams<EOL>

This function can be used for Hypersearch algorithm development. When
    present, Hypersearch doesn't actually run the CLA model in the OPF, but
    instead runs a dummy model. This function returns the dummy model params that
    will be used. See the OPFDummyModelRunner class source code (in
    nupic.swarming.ModelRunner) for a description of the schema
    for the dummy model params.


<EOL>return True<EOL>


<EOL>if perm['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'] > <NUM_LIT>:<EOL><INDENT>return False;<EOL><DEDENT>return True<EOL>


<EOL>errScore = <NUM_LIT:50><EOL>if perm['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'] is not None:<EOL><INDENT>errScore += <NUM_LIT:10><EOL><DEDENT>if perm['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT:address>'] is not None:<EOL><INDENT>errScore -= <NUM_LIT:10><EOL><DEDENT>if perm['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'] is not None:<EOL><INDENT>errScore -= <NUM_LIT:20><EOL><DEDENT>if perm['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']is not None:<EOL><INDENT>errScore -= <NUM_LIT:30><EOL><DEDENT>if perm['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']is not None:<EOL><INDENT>errScore -= <NUM_LIT><EOL><DEDENT>dummyModelParams = dict(<EOL>metricValue = errScore,<EOL>iterations = int(os.environ.get('<STR_LIT>', '<STR_LIT:1>')),<EOL>waitTime = None,<EOL>sysExitModelRange = os.environ.get('<STR_LIT>',<EOL>None),<EOL>errModelRange = os.environ.get('<STR_LIT>',<EOL>None),<EOL>jobFailErr = bool(os.environ.get('<STR_LIT>', False))<EOL>)<EOL>return dummyModelParams<EOL>


<EOL>limit = int(os.environ.get('<STR_LIT>', <NUM_LIT>))<EOL>if perm['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'] > limit:<EOL><INDENT>return False;<EOL><DEDENT>return True<EOL>


errScore = <NUM_LIT:50><EOL>waitTime = <NUM_LIT><EOL>dummyModelParams = dict(<EOL>metricValue = errScore,<EOL>iterations = int(os.environ.get('<STR_LIT>', '<STR_LIT:5>')),<EOL>waitTime = waitTime,<EOL>sysExitModelRange = os.environ.get('<STR_LIT>',<EOL>None),<EOL>delayModelRange = os.environ.get('<STR_LIT>',<EOL>None),<EOL>errModelRange = os.environ.get('<STR_LIT>',<EOL>None),<EOL>jobFailErr = bool(os.environ.get('<STR_LIT>', False))<EOL>)<EOL>return dummyModelParams<EOL>

This function can be used for Hypersearch algorithm development. When
    present, Hypersearch doesn't actually run the CLA model in the OPF, but instead run
    a dummy model. This function returns the dummy model params that will be
    used. See the OPFDummyModelRunner class source code (in
    nupic.swarming.ModelRunner) for a description of the schema for
    the dummy model params.