Exemplo n.º 1
0
 def __call__(self,**params_to_override):
     p = ParamOverrides(self,params_to_override)
     p.generators=[Gaussian(aspect_ratio=p.aspect_ratio,size=p.gaussian_size),
                   UniformRandom(name=p.name,
                                 time_dependent=p.time_dependent,
                                 time_fn = p.time_fn)]
     return super(GaussianCloud,self).__call__(**p)
Exemplo n.º 2
0
    def __call__(self,output_fn,init_time=0,final_time=None,**params):
        p=ParamOverrides(self,params)

        if final_time is None:
            final_time=topo.sim.time()

        attrs = p.attrib_names if len(p.attrib_names)>0 else output_fn.attrib_names
        for a in attrs:
            pylab.figure(figsize=(6,4))
            isint=pylab.isinteractive()
            pylab.ioff()
            pylab.grid(True)
            ylabel=p.ylabel
            pylab.ylabel(a+" "+ylabel)
            pylab.xlabel('Iteration Number')

            coords = p.units if len(p.units)>0 else output_fn.units
            for coord in coords:
                y_data=[y for (x,y) in output_fn.values[a][coord]]
                x_data=[x for (x,y) in output_fn.values[a][coord]]
                if p.raw==True:
                    plot_data=zip(x_data,y_data)
                    pylab.save(normalize_path(p.filename+a+'(%.2f, %.2f)' %(coord[0], coord[1])),plot_data,fmt='%.6f', delimiter=',')


                pylab.plot(x_data,y_data, label='Unit (%.2f, %.2f)' %(coord[0], coord[1]))
                (ymin,ymax)=p.ybounds
                pylab.axis(xmin=init_time,xmax=final_time,ymin=ymin,ymax=ymax)

            if isint: pylab.ion()
            pylab.legend(loc=0)
            p.title=topo.sim.name+': '+a
            p.filename_suffix=a
            self._generate_figure(p)
Exemplo n.º 3
0
 def __call__(self, **params_to_override):
     p = ParamOverrides(self, params_to_override)
     p.generators = [
         Gaussian(aspect_ratio=p.aspect_ratio, size=p.gaussian_size),
         UniformRandom()
     ]
     return super(GaussianCloud, self).__call__(**p)
Exemplo n.º 4
0
    def __call__(self,**params):
        p=ParamOverrides(self,params)
        sheet = p.sheet
        for coordinate in p.coords:
            i_value,j_value=sheet.sheet2matrixidx(coordinate[0],coordinate[1])

            pylab.figure(figsize=(7,7))
            isint=pylab.isinteractive()
            pylab.ioff()

            pylab.ylabel('Response',fontsize='large')
            pylab.xlabel('%s (%s)' % (p.x_axis.capitalize(),p.unit),fontsize='large')
            pylab.title('Sheet %s, coordinate(x,y)=(%0.3f,%0.3f) at time %s' %
                        (sheet.name,coordinate[0],coordinate[1],topo.sim.timestr()))
            p.title='%s: %s Tuning Curve' % (topo.sim.name,p.x_axis.capitalize())

            self.first_curve=True
            for curve_label in sorted(sheet.curve_dict[p.x_axis].keys()):
                x_values,y_values,ticks=self._curve_values(i_value,j_value,sheet.curve_dict[p.x_axis][curve_label])

                x_tick_values,ticks = self._reduce_ticks(ticks)
                labels = [self._format_x_tick_label(x) for x in ticks]
                pylab.xticks(x_tick_values, labels,fontsize='large')
                pylab.yticks(fontsize='large')
                p.plot_type(x_values, y_values, label=curve_label,lw=3.0)
                self.first_curve=False

            if isint: pylab.ion()
            if p.legend: pylab.legend(loc=2)
            self._generate_figure(p)
Exemplo n.º 5
0
 def __call__(self,mat,aspect=None,colorbar=True,**params):
     p=ParamOverrides(self,params)
     
     p.plot_type()
     pylab.figure(figsize=(5,5))
     pylab.imshow(mat,interpolation='nearest',aspect=aspect)
     if colorbar and (mat.min()!= mat.max()): pylab.colorbar()
     self._generate_figure(p)
Exemplo n.º 6
0
    def __call__(self,data,colors=None,**params):
        p=ParamOverrides(self,params,allow_extra_keywords=True)

        pylab.figure(figsize=(4,2))
        n,bins,bars = pylab.hist(data,**(p.extra_keywords()))

        # if len(bars)!=len(colors), any extra bars won't have their
        # colors changed, or any extra colors will be ignored.
        if colors: [bar.set_fc(color) for bar,color in zip(bars,colors)]

        self._generate_figure(p)
Exemplo n.º 7
0
    def __call__(self, features, **params):
        p = ParamOverrides(self, params, allow_extra_keywords=True)
        self.features = features
        self._initialize_featureresponses(p)
        self._measure_responses(p)

        results = self._collate_results(p)

        if p.measurement_storage_hook:
            p.measurement_storage_hook(results)

        return results
Exemplo n.º 8
0
    def __call__(self, data, colors=None, **params):
        p = ParamOverrides(self, params, allow_extra_keywords=True)

        fig = plt.figure(figsize=(4, 2))
        n, bins, bars = plt.hist(data, **(p.extra_keywords()))

        # if len(bars)!=len(colors), any extra bars won't have their
        # colors changed, or any extra colors will be ignored.
        if colors: [bar.set_fc(color) for bar, color in zip(bars, colors)]

        self._generate_figure(p)
        return fig
Exemplo n.º 9
0
    def __call__(self, **params):

        p = ParamOverrides(self, params)
        name = p.plot_template.keys().pop(0)
        plot = make_template_plot(p.plot_template,
                                  p.sheet.views.Maps,
                                  p.sheet.xdensity,
                                  p.sheet.bounds,
                                  p.normalize,
                                  name=p.plot_template[name])
        fig = plt.figure(figsize=(5, 5))
        if plot:
            bitmap = plot.bitmap
            isint = plt.isinteractive(
            )  # Temporarily make non-interactive for plotting
            plt.ioff()  # Turn interactive mode off

            plt.imshow(bitmap.image, origin='lower', interpolation='nearest')
            plt.axis('off')

            for (t, pref, sel, c) in p.overlay:
                v = plt.flipud(p.sheet.views.Maps[pref].view()[0])
                if (t == 'contours'):
                    plt.contour(v, [sel, sel], colors=c, linewidths=2)

                if (t == 'arrows'):
                    s = plt.flipud(p.sheet.views.Maps[sel].view()[0])
                    scale = int(np.ceil(np.log10(len(v))))
                    X = np.array([x for x in xrange(len(v) / scale)])
                    v_sc = np.zeros((len(v) / scale, len(v) / scale))
                    s_sc = np.zeros((len(v) / scale, len(v) / scale))
                    for i in X:
                        for j in X:
                            v_sc[i][j] = v[scale * i][scale * j]
                            s_sc[i][j] = s[scale * i][scale * j]
                    plt.quiver(scale * X,
                               scale * X,
                               -np.cos(2 * np.pi * v_sc) * s_sc,
                               -np.sin(2 * np.pi * v_sc) * s_sc,
                               color=c,
                               edgecolors=c,
                               minshaft=3,
                               linewidths=1)

            p.title = '%s overlaid with %s at time %s' % (plot.name, pref,
                                                          topo.sim.timestr())
            if isint: plt.ion()
            p.filename_suffix = "_" + p.sheet.name
            self._generate_figure(p)
            return fig
Exemplo n.º 10
0
    def __call__(self, **params):
        p = ParamOverrides(self, params, allow_extra_keywords=True)

        x_axis = p.x_axis.capitalize()
        vmap = p.sheet.views.Curves[x_axis.capitalize() + "Tuning"]
        time = vmap.range('Time')[1]

        curves = []
        if vmap.dimensions(label=True) == 'X':
            for coord in p.coords:
                x, y = coord
                current_map = vmap[x, y, time, :, :, :]
                curve_map = current_map.sample(X=x, Y=y).collate(
                    p.x_axis.capitalize())
                curves.append(curve_map.overlay(p.group_by))
        else:
            current_map = vmap[time, :, :, :]
            curve_map = current_map.sample(p.coords).to.curve(
                p.x_axis.capitalize(), 'Response')
            overlaid_curves = curve_map.overlay(p.group_by)
            if not isinstance(curves, NdLayout): curves = [overlaid_curves]

        figs = []
        for coord, curve in zip(p.coords, curves):
            if isinstance(curve, HoloMap): curve = curve.last
            plot = OverlayPlot if isinstance(curve,
                                             CompositeOverlay) else CurvePlot
            fig = plot(curve,
                       center=p.center,
                       relative_labels=p.relative_labels,
                       show_legend=p.legend)()
            self._generate_figure(p, fig)
            figs.append((coord, fig))

        return figs
Exemplo n.º 11
0
    def __call__(self, **params_to_override):
        p = ParamOverrides(self, params_to_override)

        g_1 = Gaussian()
        g_2 = Gaussian()

        x_1 = g_1(
            orientation=p.orientation,
            bounds=p.bounds,
            xdensity=p.xdensity,
            ydensity=p.ydensity,
            offset=p.offset,
            size=p.size,
            aspect_ratio=p.aspect_ratio,
            x=p.x +
            0.7 * np.cos(p.orientation) * p.cross * p.size * p.aspect_ratio,
            y=p.y +
            0.7 * np.sin(p.orientation) * p.cross * p.size * p.aspect_ratio)
        x_2 = g_2(orientation=p.orientation + p.angle,
                  bounds=p.bounds,
                  xdensity=p.xdensity,
                  ydensity=p.ydensity,
                  offset=p.offset,
                  size=p.size,
                  aspect_ratio=p.aspect_ratio,
                  x=p.x + 0.7 * np.cos(p.orientation + p.angle) * p.cross *
                  p.size * p.aspect_ratio,
                  y=p.y + 0.7 * np.sin(p.orientation + p.angle) * p.cross *
                  p.size * p.aspect_ratio)

        return np.maximum(x_1, x_2)
Exemplo n.º 12
0
    def __call__(self,
                 x,
                 y,
                 z,
                 labels=["X", "Y", "Z"],
                 type="wireframe",
                 **params):
        p = ParamOverrides(self, params)

        from mpl_toolkits.mplot3d import axes3d

        fig = plt.figure()
        ax = axes3d.Axes3D(fig)

        if type == "wireframe":
            ax.plot_wireframe(x, y, z)
        elif type == "surface":
            ax.plot_surface(x, y, z)
        elif type == "contour":
            ax.contour3D(x, y, z)
        else:
            raise ValueError("Unknown plot type " + str(type))

        ax.set_xlabel(labels[0])
        ax.set_ylabel(labels[1])
        ax.set_zlabel(labels[2])

        self._generate_figure(p)
        return fig
Exemplo n.º 13
0
    def __call__(self,**params_to_override):
        """
        Call the subclass's 'function' method on a rotated and scaled coordinate system.

        Creates and fills an array with the requested pattern.  If
        called without any params, uses the values for the Parameters
        as currently set on the object. Otherwise, any params
        specified override those currently set on the object.
        """
        p=ParamOverrides(self,params_to_override)

        # CEBERRORALERT: position parameter is not currently
        # supported. We should delete the position parameter or fix
        # this.
        #
        # position=params_to_override.get('position',None) if position
        # is not None: x,y = position

        self._setup_xy(p.bounds,p.xdensity,p.ydensity,p.x,p.y,p.orientation)
        fn_result = self.function(p)
        self._apply_mask(p,fn_result)
        result = p.scale*fn_result+p.offset

        for of in p.output_fns:
            of(result)

        return result
Exemplo n.º 14
0
    def __call__(self, **params):
        p = ParamOverrides(self, params, allow_extra_keywords=True)

        x_axis = p.x_axis.capitalize()
        stack = p.sheet.views.Curves[x_axis.capitalize()+"Tuning"]
        time = stack.dim_range('Time')[1]

        curves = []
        if stack.dimension_labels[0] == 'X':
            for coord in p.coords:
                x, y = coord
                current_stack = stack[x, y, time, :, :, :]
                curve_stack = current_stack.sample(X=x, Y=y).collate(p.x_axis.capitalize())
                curves.append(curve_stack.overlay_dimensions(p.group_by))
        else:
            current_stack = stack[time, :, :, :]
            curve_stack = current_stack.sample(coords=p.coords).collate(p.x_axis.capitalize())
            overlaid_curves = curve_stack.overlay_dimensions(p.group_by)
            if not isinstance(curves, GridLayout): curves = [overlaid_curves]

        figs = []
        for coord, curve in zip(p.coords,curves):
            fig = plt.figure()
            ax = plt.subplot(111)
            plot = DataPlot if isinstance(curve.last, DataOverlay) else CurvePlot
            plot(curve, center=p.center, relative_labels=p.relative_labels,
                 show_legend=p.legend)(ax)
            self._generate_figure(p, fig)
            figs.append((coord, fig))

        return figs
Exemplo n.º 15
0
    def __call__(self,mat,aspect=None,colorbar=True,**params):
        p=ParamOverrides(self,params)

        pylab.figure(figsize=(5,5))
        p.plot_type()

        # Swap lbrt to lrbt to match pylab
        if p.extent is None:
            extent = None
        else:
            (l,b,r,t)=p.extent
            extent=(l,r,b,t)

        pylab.imshow(mat,interpolation='nearest',aspect=aspect,extent=extent)
        if colorbar and (mat.min()!= mat.max()): pylab.colorbar()
        self._generate_figure(p)
Exemplo n.º 16
0
    def __call__(self, mat, type="wireframe", **params):
        p = ParamOverrides(self, params)

        from mpl_toolkits.mplot3d import axes3d

        fig = plt.figure()
        ax = axes3d.Axes3D(fig)

        # Construct matrices for r and c values
        rn, cn = mat.shape
        c = np.outer(np.ones(rn), np.arange(cn * 1.0))
        r = np.outer(np.arange(rn * 1.0), np.ones(cn))

        if type == "wireframe":
            ax.plot_wireframe(r, c, mat)
        elif type == "surface":
            # Sometimes fails for no obvious reason
            ax.plot_surface(r, c, mat)
        elif type == "contour":
            # Works but not usually very useful
            ax.contour3D(r, c, mat)
        else:
            raise ValueError("Unknown plot type " + str(type))

        ax.set_xlabel('R')
        ax.set_ylabel('C')
        ax.set_zlabel('Value')

        self._generate_figure(p)
Exemplo n.º 17
0
   def __call__(self, **params):

       p = ParamOverrides(self, params)
       fig = plt.figure(figsize=(5, 5))

       # This one-liner works in Octave, but in matplotlib it
       # results in lines that are all connected across rows and columns,
       # so here we plot each line separately:
       #   plt.plot(x,y,"k-",transpose(x),transpose(y),"k-")
       # Here, the "k-" means plot in black using solid lines;
       # see matplotlib for more info.
       isint = plt.isinteractive() # Temporarily make non-interactive for
       # plotting
       plt.ioff()
       for r, c in zip(p.y[::p.skip], p.x[::p.skip]):
           plt.plot(c, r, "k-")
       for r, c in zip(np.transpose(p.y)[::p.skip],np.transpose(p.x)[::p.skip]):
           plt.plot(c, r, "k-")

       # Force last line avoid leaving cells open
       if p.skip != 1:
           plt.plot(p.x[-1], p.y[-1], "k-")
           plt.plot(np.transpose(p.x)[-1], np.transpose(p.y)[-1], "k-")

       plt.xlabel('x')
       plt.ylabel('y')
       # Currently sets the input range arbitrarily; should presumably figure out
       # what the actual possible range is for this simulation (which would presumably
       # be the maximum size of any GeneratorSheet?).
       plt.axis(p.axis)

       if isint: plt.ion()
       self._generate_figure(p)
       return fig
Exemplo n.º 18
0
    def __call__(self, mat, aspect=None, colorbar=True, **params):
        p = ParamOverrides(self, params)

        fig = plt.figure(figsize=(5, 5))
        p.plot_type()

        # Swap lbrt to lrbt to match pylab
        if p.extent is None:
            extent = None
        else:
            (l, b, r, t) = p.extent
            extent = (l, r, b, t)

        plt.imshow(mat, interpolation='nearest', aspect=aspect, extent=extent)
        if colorbar and (mat.min() != mat.max()): plt.colorbar()
        self._generate_figure(p)
        return fig
Exemplo n.º 19
0
    def __call__(self,**params):
        p=ParamOverrides(self,params)

        for template in p.plot_template:
            for sheet in topo.sim.objects(Sheet).values():
                if getattr(sheet, "measure_maps", False):
                    super(overlaid_plots, self).__call__(sheet=sheet, plot_template=template,
                                                         overlay=p.overlay, normalize=p.normalize)
Exemplo n.º 20
0
    def __call__(self, **params_to_override):
        p = ParamOverrides(self, params_to_override)

        xsize, ysize = SheetCoordinateSystem(p.bounds, p.xdensity,
                                             p.ydensity).shape
        xsize, ysize = int(round(xsize)), int(round(ysize))

        xdisparity = int(round(xsize * p.xdisparity))
        ydisparity = int(round(xsize * p.ydisparity))
        dotsize = int(round(xsize * p.dotsize))

        bigxsize = 2 * xsize
        bigysize = 2 * ysize
        ndots = int(
            round(p.dotdensity * (bigxsize + 2 * dotsize) *
                  (bigysize + 2 * dotsize) / min(dotsize, xsize) /
                  min(dotsize, ysize)))
        halfdot = floor(dotsize / 2)

        # Choose random colors and locations of square dots
        random_seed = p.random_seed

        numpy.random.seed(random_seed * 12 + random_seed * 99)
        col = numpy.where(numpy.random.random((ndots)) >= 0.5, 1.0, -1.0)

        numpy.random.seed(random_seed * 122 + random_seed * 799)
        xpos = numpy.floor(
            numpy.random.random((ndots)) * (bigxsize + 2 * dotsize)) - halfdot

        numpy.random.seed(random_seed * 1243 + random_seed * 9349)
        ypos = numpy.floor(
            numpy.random.random((ndots)) * (bigysize + 2 * dotsize)) - halfdot

        # Construct arrays of points specifying the boundaries of each
        # dot, cropping them by the big image size (0,0) to (bigxsize,bigysize)
        x1 = xpos.astype(numpy.int)
        x1 = choose(less(x1, 0), (x1, 0))
        y1 = ypos.astype(numpy.int)
        y1 = choose(less(y1, 0), (y1, 0))
        x2 = (xpos + (dotsize - 1)).astype(numpy.int)
        x2 = choose(greater(x2, bigxsize), (x2, bigxsize))
        y2 = (ypos + (dotsize - 1)).astype(numpy.int)
        y2 = choose(greater(y2, bigysize), (y2, bigysize))

        # Draw each dot in the big image, on a blank background
        bigimage = zeros((bigysize, bigxsize))
        for i in range(ndots):
            bigimage[y1[i]:y2[i] + 1, x1[i]:x2[i] + 1] = col[i]

        result = p.offset + p.scale * bigimage[
            (ysize / 2) + ydisparity:(3 * ysize / 2) + ydisparity,
            (xsize / 2) + xdisparity:(3 * xsize / 2) + xdisparity]

        for of in p.output_fns:
            of(result)

        return result
Exemplo n.º 21
0
 def __call__(self, pattern, pattern_label, pattern_number, master_seed,
              **params):
     p = ParamOverrides(self, params, allow_extra_keywords=True)
     new_pattern = copy.copy(pattern)
     new_pattern.y = pattern.get_value_generator('y')+\
         numbergen.UniformRandom(lbound=-p.position_bound_y,
                                 ubound=p.position_bound_y,
                                 seed=master_seed+35+pattern_number,
                                 name="YCoordinator"+str(pattern_number))
     return new_pattern
Exemplo n.º 22
0
    def __call__(self, pattern, pattern_label, pattern_number, master_seed, **params):
        p = ParamOverrides(self,params,allow_extra_keywords=True)
        new_pattern=copy.copy(pattern)
        new_pattern.size=pattern.get_value_generator('size')*\
                         numbergen.UniformRandom(lbound=1,
                                                 ubound=p.sf_spacing**(p.sf_max_channel-1),
                                                 seed=master_seed+77+pattern_number,
                                                 name="SpatialFrequencyCoordinator"+str(pattern_number))

        return new_pattern
Exemplo n.º 23
0
    def __call__(self,**params):
        p=ParamOverrides(self,params)

        for sheet in topo.sim.objects(Sheet).values():
            if ((p.xsheet_view_name in sheet.sheet_views) and
                (p.ysheet_view_name in sheet.sheet_views)):

                x = sheet.sheet_views[p.xsheet_view_name].view()[0]
                y = sheet.sheet_views[p.ysheet_view_name].view()[0]

                pylab.figure(figsize=(5,5))

                # This one-liner works in Octave, but in matplotlib it
                # results in lines that are all connected across rows and columns,
                # so here we plot each line separately:
                #   pylab.plot(x,y,"k-",transpose(x),transpose(y),"k-")
                # Here, the "k-" means plot in black using solid lines;
                # see matplotlib for more info.
                isint=pylab.isinteractive() # Temporarily make non-interactive for plotting
                pylab.ioff()
                for r,c in zip(y[::p.skip],x[::p.skip]):
                    pylab.plot(c,r,"k-")
                for r,c in zip(transpose(y)[::p.skip],transpose(x)[::p.skip]):
                    pylab.plot(c,r,"k-")

                # Force last line avoid leaving cells open
                if p.skip != 1:
                    pylab.plot(x[-1],y[-1],"k-")
                    pylab.plot(transpose(x)[-1],transpose(y)[-1],"k-")

                pylab.xlabel('x')
                pylab.ylabel('y')
                # Currently sets the input range arbitrarily; should presumably figure out
                # what the actual possible range is for this simulation (which would presumably
                # be the maximum size of any GeneratorSheet?).
                pylab.axis(p.axis)
                p.title='Topographic mapping to '+sheet.name+' at time '+topo.sim.timestr()

                if isint: pylab.ion()
                p.filename_suffix="_"+sheet.name
                self._generate_figure(p)
Exemplo n.º 24
0
    def __init__(self,inherent_features={},**params):

        """
        If a dataset already and inherently includes certain features, a dictionary
        with feature-name:code-to-access-the-feature pairs should be supplied
        specifying how to select (e.g. from a set of images) the appropriate
        feature value.

        Any extra parameter values supplied here will be passed down to the
        feature_coordinators requested in features_to_vary.
        """
        p=ParamOverrides(self,params,allow_extra_keywords=True)

        super(PatternCoordinator, self).__init__(**p.param_keywords())

        self._feature_params = p.extra_keywords()

        self._inherent_features = inherent_features

        # And also, this key must be in feature_coordinators because _inherent_features
        # can have additional features such as i to support multiple images

        # TFALERT: Once spatial frequency (sf) is added, this will
        # cause warnings, because all image datasets will have a
        # spatial frequency inherent feature, but mostly we just
        # ignore that by having only a single size of DoG, which
        # discards all but a narrow range of sf.  So the dataset will
        # have sf inherently, but that won't be an error or even
        # worthy of a warning.
        if(len((set(self._inherent_features.keys()) - set(self.features_to_vary)) & set(self.feature_coordinators.keys()))):
            self.warning('Inherent feature present which is not requested in features')

        self._feature_coordinators_to_apply = []
        for feature, feature_coordinator in self.feature_coordinators.iteritems():
            if feature in self.features_to_vary and feature not in self._inherent_features:
                # if it is a list, append each list item individually
                if isinstance(feature_coordinator,list):
                    for individual_feature_coordinator in feature_coordinator:
                        self._feature_coordinators_to_apply.append(individual_feature_coordinator)
                else:
                    self._feature_coordinators_to_apply.append(feature_coordinator)
Exemplo n.º 25
0
    def __call__(self, pattern, pattern_label, pattern_number, master_seed, **params):
        p = ParamOverrides(self,params,allow_extra_keywords=True)

        assert(param.Dynamic.time_dependent), "param.Dynamic.time_dependent!=True for motion"
        assert(numbergen.RandomDistribution.time_dependent), "numbergen.RandomDistribution.time_dependent!=True for motion" 

        moved_pattern = Sweeper(generator=copy.deepcopy(pattern),
                                speed=p.speed,
                                reset_period=p.reset_period,
                                time_fn=p.time_fn)

        return moved_pattern
Exemplo n.º 26
0
    def __call__(self, **params_to_override):
        p = ParamOverrides(self, params_to_override)

        shape = SheetCoordinateSystem(p.bounds, p.xdensity, p.ydensity).shape

        result = self._distrib(shape, p)
        self._apply_mask(p, result)

        for of in p.output_fns:
            of(result)

        return result
Exemplo n.º 27
0
    def __call__(self, vec, xvalues=None, style='-', label=None, **params):
        p = ParamOverrides(self, params)

        fig = plt.figure()
        if xvalues is not None:
            plt.plot(xvalues, vec, style, label=label)
        else:
            plt.plot(vec, style, label=label)

        plt.grid(True)
        self._generate_figure(p)
        return fig
Exemplo n.º 28
0
 def __call__(self, pattern, pattern_label, pattern_number, master_seed,
              **params):
     p = ParamOverrides(self, params, allow_extra_keywords=True)
     new_pattern = copy.copy(pattern)
     new_pattern.orientation = pattern.get_value_generator('orientation')+\
         numbergen.UniformRandom(lbound=-p.orientation_bound,
                                 ubound=p.orientation_bound,
                                 seed=master_seed+21+(0 if p.align_orientations else pattern_number),
                                 name=("OrientationCoordinator"
                                       + ('' if p.align_orientations else str(pattern_number)))
                             )
     return new_pattern
Exemplo n.º 29
0
    def __call__(self,**params_to_override):
        p = ParamOverrides(self,params_to_override)

        shape = SheetCoordinateSystem(p.bounds,p.xdensity,p.ydensity).shape

        result = p.scale*ones(shape, Float)+p.offset
        self._apply_mask(p,result)

        for of in p.output_fns:
            of(result)

        return result
Exemplo n.º 30
0
   def __call__(self, **params):

       p=ParamOverrides(self,params)
       name=p.plot_template.keys().pop(0)
       plot=make_template_plot(p.plot_template,
                               p.sheet.views.Maps, p.sheet.xdensity,p.sheet.bounds,
                               p.normalize,name=p.plot_template[name])
       fig = plt.figure(figsize=(5,5))
       if plot:
           bitmap=plot.bitmap
           isint=plt.isinteractive() # Temporarily make non-interactive for plotting
           plt.ioff()                                         # Turn interactive mode off

           plt.imshow(bitmap.image,origin='lower',interpolation='nearest')
           plt.axis('off')

           for (t,pref,sel,c) in p.overlay:
               v = plt.flipud(p.sheet.views.Maps[pref].view()[0])
               if (t=='contours'):
                   plt.contour(v,[sel,sel],colors=c,linewidths=2)

               if (t=='arrows'):
                   s = plt.flipud(p.sheet.views.Maps[sel].view()[0])
                   scale = int(np.ceil(np.log10(len(v))))
                   X = np.array([x for x in xrange(len(v)/scale)])
                   v_sc = np.zeros((len(v)/scale,len(v)/scale))
                   s_sc = np.zeros((len(v)/scale,len(v)/scale))
                   for i in X:
                       for j in X:
                           v_sc[i][j] = v[scale*i][scale*j]
                           s_sc[i][j] = s[scale*i][scale*j]
                   plt.quiver(scale*X, scale*X, -np.cos(2*np.pi*v_sc)*s_sc,
                              -np.sin(2*np.pi*v_sc)*s_sc, color=c,
                              edgecolors=c, minshaft=3, linewidths=1)

           p.title='%s overlaid with %s at time %s' %(plot.name,pref,topo.sim.timestr())
           if isint: plt.ion()
           p.filename_suffix="_"+p.sheet.name
           self._generate_figure(p)
           return fig
Exemplo n.º 31
0
    def __call__(self, **params_to_override):
        p = ParamOverrides(self, params_to_override)

        if self.time_fn() >= self.last_time + p.reset_period:
            ## Returns early if within episode interval
            if self.time_fn(
            ) < self.last_time + p.reset_period + p.episode_interval:
                return p.episode_separator(xdensity=p.xdensity,
                                           ydensity=p.ydensity,
                                           bounds=p.bounds)
            else:
                self._advance_params()

        # JABALERT: Does not allow x, y, or direction to be passed in
        # to the call; fixing this would require implementing
        # inspect_value and force_new_dynamic_value (for
        # use in _advance_params) for ParamOverrides.
        #
        # Access parameter values without giving them new values
        assert ('x' not in params_to_override and 'y' not in params_to_override
                and 'direction' not in params_to_override)
        x = self.inspect_value('x')
        y = self.inspect_value('y')
        direction = self.inspect_value('direction')

        # compute how much time elapsed from the last reset
        # float(t) required because time could be e.g. gmpy.mpq
        t = float(self.time_fn() - self.last_time)

        ## CEBALERT: mask gets applied twice, both for the underlying
        ## generator and for this one.  (leads to redundant
        ## calculations in current lissom_oo_or usage, but will lead
        ## to problems/limitations in the future).
        return p.generator(
            xdensity=p.xdensity,
            ydensity=p.ydensity,
            bounds=p.bounds,
            x=x + t * np.cos(direction) * p.speed + p.generator.x,
            y=y + t * np.sin(direction) * p.speed + p.generator.y,
            orientation=(direction - pi / 2) + p.generator.orientation)
Exemplo n.º 32
0
    def __call__(self, features, **params):
        """
        Present the given input patterns and collate the responses.

        Responses are statistics on the distributions of measure for
        every unit, extracted by functions that are subclasses of
        DistributionStatisticFn, and could be specified in each
        feature with the preference_fn parameter, otherwise the
        default in self.preference_fn is used.
        """
        p = ParamOverrides(self, params, allow_extra_keywords=True)
        self.features = features

        self._initialize_featureresponses(p)
        self._measure_responses(p)

        results = self._collate_results(p)

        if p.measurement_storage_hook:
            p.measurement_storage_hook(results)

        return results
Exemplo n.º 33
0
    def __init__(self, inherent_features=[], **params):
        """
        If a dataset already and inherently includes certain features,
        a list with the inherent feature names should be supplied.

        Any extra parameter values supplied here will be passed down
        to the feature_coordinators requested in features_to_vary.
        """
        p = ParamOverrides(self, params, allow_extra_keywords=True)

        super(PatternCoordinator, self).__init__(**p.param_keywords())

        self._feature_params = p.extra_keywords()

        self._inherent_features = inherent_features

        # TFALERT: Once spatial frequency (sf) is added, this will
        # cause warnings, because all image datasets will have a
        # spatial frequency inherent feature, but mostly we just
        # ignore that by having only a single size of DoG, which
        # discards all but a narrow range of sf.  So the dataset will
        # have sf inherently, but that won't be an error or even
        # worthy of a warning.
        if (len(set(self._inherent_features) - set(self.features_to_vary))):
            self.warning(
                'Inherent feature present which is not requested in features')

        self._feature_coordinators_to_apply = []
        for feature, feature_coordinator in self.feature_coordinators.items():
            if feature in self.features_to_vary and feature not in self._inherent_features:
                # if it is a list, append each list item individually
                if isinstance(feature_coordinator, list):
                    for individual_feature_coordinator in feature_coordinator:
                        self._feature_coordinators_to_apply.append(
                            individual_feature_coordinator)
                else:
                    self._feature_coordinators_to_apply.append(
                        feature_coordinator)
Exemplo n.º 34
0
    def __call__(self,**params_to_override):
        p=ParamOverrides(self,params_to_override)

        if self.time_fn() >= self.last_time + p.reset_period:
            ## Returns early if within episode interval
            if self.time_fn()<self.last_time+p.reset_period+p.episode_interval:
                return p.episode_separator(xdensity=p.xdensity,
                                           ydensity=p.ydensity,
                                           bounds=p.bounds)
            else:
                self._advance_params()

        # JABALERT: Does not allow x, y, or direction to be passed in
        # to the call; fixing this would require implementing
        # inspect_value and force_new_dynamic_value (for
        # use in _advance_params) for ParamOverrides.
        #
        # Access parameter values without giving them new values
        assert ('x' not in params_to_override and
                'y' not in params_to_override and
                'direction' not in params_to_override)
        x = self.inspect_value('x')
        y = self.inspect_value('y')
        direction = self.inspect_value('direction')

        # compute how much time elapsed from the last reset
        # float(t) required because time could be e.g. gmpy.mpq
        t = float(self.time_fn()-self.last_time)

        ## CEBALERT: mask gets applied twice, both for the underlying
        ## generator and for this one.  (leads to redundant
        ## calculations in current lissom_oo_or usage, but will lead
        ## to problems/limitations in the future).
        return p.generator(
            xdensity=p.xdensity,ydensity=p.ydensity,bounds=p.bounds,
            x=x+t*np.cos(direction)*p.speed+p.generator.x,
            y=y+t*np.sin(direction)*p.speed+p.generator.y,
            orientation=(direction-pi/2)+p.generator.orientation)
Exemplo n.º 35
0
 def test_missing_key(self):
     overrides = ParamOverrides(self.po, {'name': 'B'})
     try:
         overrides['doesnotexist']
     except AttributeError:
         pass
     except:
         raise AssertionError(
             "ParamOverrides should give AttributeError when key can't be found."
         )
     else:
         raise AssertionError(
             "Test supposed to lookup non-existent attribute and raise error."
         )
Exemplo n.º 36
0
    def __call__(self, **params):
        p = ParamOverrides(self, params)

        for sheet in topo.sim.objects(Sheet).values():
            if ((p.xsheet_view_name in sheet.views.Maps) and
                    (p.ysheet_view_name in sheet.views.Maps)):
                x = sheet.views.Maps[p.xsheet_view_name].last.data
                y = sheet.views.Maps[p.ysheet_view_name].last.data

                filename_suffix = "_" + sheet.name
                title = 'Topographic mapping to ' + sheet.name + ' at time ' \
                        + topo.sim.timestr()
                super(topographic_grid, self).__call__(x=x, y=y, title=title,
                                                       filename_suffix=filename_suffix)
Exemplo n.º 37
0
    def __init__(self,inherent_features=[],**params):

        """
        If a dataset already and inherently includes certain features,
        a list with the inherent feature names should be supplied.

        Any extra parameter values supplied here will be passed down
        to the feature_coordinators requested in features_to_vary.
        """
        p=ParamOverrides(self,params,allow_extra_keywords=True)

        super(PatternCoordinator, self).__init__(**p.param_keywords())

        self._feature_params = p.extra_keywords()

        self._inherent_features = inherent_features

        # TFALERT: Once spatial frequency (sf) is added, this will
        # cause warnings, because all image datasets will have a
        # spatial frequency inherent feature, but mostly we just
        # ignore that by having only a single size of DoG, which
        # discards all but a narrow range of sf.  So the dataset will
        # have sf inherently, but that won't be an error or even
        # worthy of a warning.
        if(len(set(self._inherent_features) - set(self.features_to_vary))):
            self.warning('Inherent feature present which is not requested in features')

        self._feature_coordinators_to_apply = []
        for feature, feature_coordinator in self.feature_coordinators.items():
            if feature in self.features_to_vary and feature not in self._inherent_features:
                # if it is a list, append each list item individually
                if isinstance(feature_coordinator,list):
                    for individual_feature_coordinator in feature_coordinator:
                        self._feature_coordinators_to_apply.append(individual_feature_coordinator)
                else:
                    self._feature_coordinators_to_apply.append(feature_coordinator)
Exemplo n.º 38
0
    def __call__(self,**params_to_override):
        p = ParamOverrides(self,params_to_override)
        if self.time_dependent:
            if 'name' in p:
                self._initialize_random_state(seed=self.seed, shared=True, name=p.name)
            self._hash_and_seed()

        shape = SheetCoordinateSystem(p.bounds,p.xdensity,p.ydensity).shape

        result = self._distrib(shape,p)
        self._apply_mask(p,result)

        for of in p.output_fns:
            of(result)

        return result
Exemplo n.º 39
0
 def __call__(self, viewcontainer, **params):
     p = ParamOverrides(self, params)
     objects = dict(topo.sim.objects(), **dict([(proj.name, proj) for proj in topo.sim.connections()]))
     for path, container in viewcontainer.path_items.items():
         label, src_name = path
         source = objects[src_name]
         if isinstance(source, Sheet):
             storage = source.views[p.sublabel] if p.sublabel else source.views
         else:
             proj_store = source.dest.views[source.name] = {}
             proj_store[p.sublabel] = {}
             storage = proj_store[p.sublabel]
         if label not in storage or p.only_latest:
             storage[label] = container
         else:
             storage[label].update(container)
Exemplo n.º 40
0
    def __call__(self, data, cyclic_range=1.0, **params):
        p = ParamOverrides(self, params)

        r, c = data.shape
        dx = np.diff(data, 1, axis=1)[0:r - 1, 0:c - 1]
        dy = np.diff(data, 1, axis=0)[0:r - 1, 0:c - 1]

        if cyclic_range is not None: # Wrap into the specified range
            # Convert negative differences to an equivalent positive value
            dx = wrap(0, cyclic_range, dx)
            dy = wrap(0, cyclic_range, dy)
            #
            # Make it increase as gradient reaches the halfway point,
            # and decrease from there
            dx = 0.5 * cyclic_range - np.abs(dx - 0.5 * cyclic_range)
            dy = 0.5 * cyclic_range - np.abs(dy - 0.5 * cyclic_range)

        return super(gradientplot, self).__call__(np.sqrt(dx*dx + dy*dy), **p)
Exemplo n.º 41
0
    def __call__(self, pattern, pattern_label, pattern_number, master_seed,
                 **params):
        p = ParamOverrides(self, params, allow_extra_keywords=True)

        err_msg = "%s must be enabled for motion"
        if not param.Dynamic.time_dependent:
            raise RuntimeError(err_msg % "param.Dynamic.time_dependent")

        if not numbergen.RandomDistribution.time_dependent:
            raise RuntimeError(err_msg %
                               "numbergen.RandomDistribution.time_dependent")

        moved_pattern = Sweeper(generator=copy.deepcopy(pattern),
                                speed=p.speed,
                                reset_period=p.reset_period,
                                time_fn=p.time_fn)

        return moved_pattern
Exemplo n.º 42
0
    def __call__(self, pattern, pattern_label, pattern_number, master_seed, **params):
        p = ParamOverrides(self,params,allow_extra_keywords=True)
        new_pattern=copy.copy(pattern)
        if(pattern_label.count('Left')):
            new_pattern.scale = (1-p.dim_fraction) + p.dim_fraction * \
                                (2.0-numbergen.UniformRandom(lbound=0,
                                                             ubound=2,
                                                             seed=master_seed+55+pattern_number,
                                                             name="OcularityCoordinator"+str(pattern_number)))
        elif(pattern_label.count('Right')):
            new_pattern.scale = (1-p.dim_fraction) + p.dim_fraction * \
                                 numbergen.UniformRandom(lbound=0,
                                                         ubound=2,
                                                         seed=master_seed+55+pattern_number,
                                                         name="OcularityCoordinator"+str(pattern_number))
        else:
            self.warning('Skipping region %s; Ocularity is defined only for Left and Right retinas.' % pattern)

        return new_pattern
Exemplo n.º 43
0
    def __call__(self, pattern, pattern_label, pattern_number, master_seed, **params):
        p = ParamOverrides(self,params,allow_extra_keywords=True)
        new_pattern=copy.copy(pattern)

        if(pattern_label.count('Left')):
            new_pattern.x = pattern.get_value_generator('x')-\
                numbergen.UniformRandom(lbound=-p.disparity_bound,
                                        ubound=p.disparity_bound,
                                        seed=master_seed+45+pattern_number,
                                        name="DisparityCoordinator"+str(pattern_number))
        elif(pattern_label.count('Right')):
            new_pattern.x = pattern.get_value_generator('x')+\
                numbergen.UniformRandom(lbound=-p.disparity_bound,
                                        ubound=p.disparity_bound,
                                        seed=master_seed+45+pattern_number,
                                        name="DisparityCoordinator"+str(pattern_number))
        else:
            self.warning('Skipping region %s; Disparity is defined only for Left and Right retinas.' % pattern)

        return new_pattern
Exemplo n.º 44
0
    def __call__(self,script_file,**params_to_override):
        p=ParamOverrides(self,params_to_override,allow_extra_keywords=True)

        import os
        import shutil

        # Construct simulation name, etc.
        scriptbase= re.sub('.ty$','',os.path.basename(script_file))
        prefix = ""
        if p.timestamp==(0,0): prefix += time.strftime(p.name_time_format)
        else:                  prefix += time.strftime(p.name_time_format, p.timestamp)

        prefix += "_" + scriptbase + "_" + p.tag
        simname = prefix

        # Construct parameter-value portion of filename; should do more filtering
        # CBENHANCEMENT: should provide chance for user to specify a
        # function (i.e. make this a function, and have a parameter to
        # allow the function to be overridden).
        # And sort by name by default? Skip ones that aren't different
        # from default, or at least put them at the end?
        prefix += p.dirname_params_filter(p.extra_keywords())

        # Set provided parameter values in main namespace
        from topo.misc.commandline import global_params
        global_params.set_in_context(**p.extra_keywords())

        # Create output directories
        if not os.path.isdir(normalize_path(p['output_directory'])):
            try: os.mkdir(normalize_path(p['output_directory']))
            except OSError: pass   # Catches potential race condition (simultaneous run_batch runs)

        dirname = self._truncate(p,p.dirname_prefix+prefix)
        normalize_path.prefix = normalize_path(os.path.join(p['output_directory'],dirname))

        if os.path.isdir(normalize_path.prefix):
            print "Batch run: Warning -- directory already exists!"
            print "Run aborted; wait one minute before trying again, or else rename existing directory: \n" + \
                  normalize_path.prefix

            sys.exit(-1)
        else:
            os.mkdir(normalize_path.prefix)
            print "Batch run output will be in " + normalize_path.prefix


        if p['vc_info']:
            _print_vc_info(simname+".diffs")

        hostinfo = "Host: " + " ".join(platform.uname())
        topographicalocation = "Topographica: " + os.path.abspath(sys.argv[0])
        topolocation = "topo package: " + os.path.abspath(topo.__file__)
        scriptlocation = "script: " + os.path.abspath(script_file)

        starttime=time.time()
        startnote = "Batch run started at %s." % time.strftime("%a %d %b %Y %H:%M:%S +0000",
                                                               time.gmtime())

        # store a re-runnable copy of the command used to start this batch run
        try:
            # pipes.quote is undocumented, so I'm not sure which
            # versions of python include it (I checked python 2.6 and
            # 2.7 on linux; they both have it).
            import pipes
            quotefn = pipes.quote
        except (ImportError,AttributeError):
            # command will need a human to insert quotes before it can be re-used
            quotefn = lambda x: x

        command_used_to_start = string.join([quotefn(arg) for arg in sys.argv])

        # CBENHANCEMENT: would be nice to separately write out a
        # runnable script that does everything necessary to
        # re-generate results (applies diffs etc).

        # Shadow stdout to a .out file in the output directory, so that
        # print statements will go to both the file and to stdout.
        batch_output = open(normalize_path(simname+".out"),'w')
        batch_output.write(command_used_to_start+"\n")
        sys.stdout = MultiFile(batch_output,sys.stdout)

        print
        print hostinfo
        print topographicalocation
        print topolocation
        print scriptlocation
        print
        print startnote

        from topo.misc.commandline import auto_import_commands
        auto_import_commands()

        # Ensure that saved state includes all parameter values
        from topo.command import save_script_repr
        param.parameterized.script_repr_suppress_defaults=False

        # Save a copy of the script file for reference
        shutil.copy2(script_file, normalize_path.prefix)
        shutil.move(normalize_path(scriptbase+".ty"),
                    normalize_path(simname+".ty"))


        # Default case: times is just a number that scales a standard list of times
        times=p['times']
        if not isinstance(times,list):
            times=[t*times for t in [0,50,100,500,1000,2000,3000,4000,5000,10000]]

        # Run script in main
        error_count = 0
        initial_warning_count = param.parameterized.warning_count
        try:
            execfile(script_file,__main__.__dict__) #global_params.context
            global_params.check_for_unused_names()
            if p.save_global_params:
                _save_parameters(p.extra_keywords(),simname+".global_params.pickle")
            print_sizes()
            topo.sim.name=simname

            # Run each segment, doing the analysis and saving the script state each time
            for run_to in times:
                topo.sim.run(run_to - topo.sim.time())
                p['analysis_fn']()
                save_script_repr()
                elapsedtime=time.time()-starttime
                param.Parameterized(name="run_batch").message(
                    "Elapsed real time %02d:%02d." % (int(elapsedtime/60),int(elapsedtime%60)))

            if p['snapshot']:
               save_snapshot()

        except:
            error_count+=1
            import traceback
            traceback.print_exc(file=sys.stdout)
            sys.stderr.write("Warning -- Error detected: execution halted.\n")


        print "\nBatch run completed at %s." % time.strftime("%a %d %b %Y %H:%M:%S +0000",
                                                             time.gmtime())
        print "There were %d error(s) and %d warning(s)%s." % \
              (error_count,(param.parameterized.warning_count-initial_warning_count),
               ((" (plus %d warning(s) prior to entering run_batch)"%initial_warning_count
                 if initial_warning_count>0 else "")))

        # restore stdout
        sys.stdout = sys.__stdout__
        batch_output.close()
Exemplo n.º 45
0
 def __call__(self, sheet, mat=None, **params):
     p = ParamOverrides(self, params)
     if p.extent is None: p.extent = sheet.bounds.aarect().lbrt()
     if mat is None: mat = sheet.activity
     return super(activityplot, self).__call__(mat, **p)