def set_world_primitives(self, primitives):
     # XXX: inefficient
     for x in primitives:
         surface = x.id_object
         if isinstance(x, PolyLine):
             self.surface2texture[surface] = instantiate_spec(x.texture)
         if isinstance(x, Circle):
             self.surface2texture[surface] = instantiate_spec(x.texture)
     MyRaytracer.set_world_primitives(self, primitives)
Example #2
0
def cairo_show_world_geometry(cr,
                              world_state,
                              plot_sources=False,
                              plot_textures=False,
                              extra_pad=0):
    bounds = world_state['bounds']
    primitives = world_state['primitives']

    with cairo_save(cr):
        xb = bounds[0]
        yb = bounds[1]
        xb = [xb[0] - extra_pad, xb[1] + extra_pad]
        yb = [yb[0] - extra_pad, yb[1] + extra_pad]

        cr.rectangle(xb[0], yb[0], xb[1] - xb[0], yb[1] - yb[0])
        cr.clip()

        # Draw it twice for special effects
        for i in range(2):
            for p in primitives:
                ptype = p['type']
                if ptype == VehiclesConstants.PRIMITIVE_POLYLINE:
                    points = np.array(p['points']).T
                    texture = instantiate_spec(p['texture'])
                    if not plot_textures:
                        texture = None
                    cairo_plot_polyline_primitive(cr,
                                                  points=points,
                                                  texture=texture)

                elif ptype == VehiclesConstants.PRIMITIVE_CIRCLE:
                    texture = instantiate_spec(p['texture'])
                    if not plot_textures:
                        texture = None
                    cairo_plot_circle_primitive(cr,
                                                center=p['center'],
                                                texture=texture,
                                                radius=p['radius'],
                                                solid=p['solid'],
                                                numpass=i)

                elif ptype == VehiclesConstants.PRIMITIVE_SOURCE:
                    if plot_sources:
                        cairo_plot_circle(cr,
                                          center=p['center'],
                                          radius=0.05,
                                          edgecolor=[0, 0, 0],
                                          facecolor=[1, 0, 0],
                                          width=0.01)
                    # TODO: parametrize
                else:
                    pass  # XXX
Example #3
0
    def __init__(self,
                 directions,
                 invalid=10,
                 min_range=0.2,
                 max_range=10,
                 noise=None):
        ''' 
            :param directions: array of orientations
            :param invalid: value for invalid data (i.e., out of range) 
        '''
        self.invalid = invalid
        self.min_range = min_range
        self.max_range = max_range

        self.noise_spec = noise
        self.noise = (None if self.noise_spec is None else instantiate_spec(
            self.noise_spec))

        spec = {
            'desc': 'Range-finder',
            'shape': [len(directions)],
            'format': 'C',
            'range': [0, +1],
            'extra': {
                'directions': np.array(directions).tolist(),
                'noise': noise,
                'invalid': float(invalid),
                'max_range': float(max_range),
                'min_range': float(min_range)
            }
        }
        VehicleSensor.__init__(self, spec)
        MyRaytracer.__init__(self, directions)
Example #4
0
    def __init__(self, sigma, texture, resolution=None):
        sigma = float(sigma)
        if resolution is None:
            resolution = sigma / 10.0

        max_length = 100
        texture = instantiate_spec(texture)

        num_cells = max_length / resolution

        cell_coord = np.linspace(0, max_length, num_cells)
        unsmoothed = texture(cell_coord)

        kernel_size = int(2 * (sigma * 3) / resolution)

        #print('resol: %s' % resolution)
        #print('sigma: %s' % sigma)
        #print('kernel_size: %s' % kernel_size)
        #print kernel

        kernel = gaussian(kernel_size, sigma / resolution)
        kernel = kernel / kernel.sum()

        assert kernel.size == kernel_size
        assert_allclose(kernel.sum(), 1)

        smoothed = convolve(unsmoothed, kernel, 'same')

        assert smoothed.size == cell_coord.size

        SampledTexture.__init__(self, smoothed, resolution)
 def __init__(self, importance, explorer):
     """ importance: spec to instantiate """
     self.importance = instantiate_spec(importance)
     self.explorer = explorer  
     self.y_deriv = DerivativeBox()
     self.rd = RemoveDoubles(0.5)  # XXX
     self.count = 0
Example #6
0
    def __init__(self, directions, invalid=10, min_range=0.2, max_range=10,
                 noise=None):
        ''' 
            :param directions: array of orientations
            :param invalid: value for invalid data (i.e., out of range) 
        '''
        self.invalid = invalid
        self.min_range = min_range
        self.max_range = max_range

        self.noise_spec = noise
        self.noise = (None if self.noise_spec is None else
                          instantiate_spec(self.noise_spec))

        spec = {
            'desc': 'Range-finder',
            'shape': [len(directions)],
            'format': 'C',
            'range': [0, +1],
            'extra': {'directions': np.array(directions).tolist(),
                      'noise': noise,
                      'invalid': float(invalid),
                      'max_range': float(max_range),
                      'min_range': float(min_range)}
        }
        VehicleSensor.__init__(self, spec)
        MyRaytracer.__init__(self, directions)
Example #7
0
 def get_servo(self):
     servo_agent = instantiate_spec(self.servo)
     servo_agent.init(self.boot_spec)
     assert isinstance(servo_agent, BDSEServoInterface)
     model = self.bdse_estimator.get_model()
     servo_agent.set_model(model)
     return servo_agent
 def get_servo(self):
     # XXX :repeated code with BDSEAgent
     print('Servo: %r' % self.servo)
     servo_agent = instantiate_spec(self.servo)
     assert isinstance(servo_agent, BDSEServoInterface)
     servo_agent.init(self.boot_spec)
     model = self.estimator.get_model()
     servo_agent.set_model(model)
     return servo_agent
Example #9
0
 def __init__(self, id_object, tags, center, kernel_spec):
     '''
         Initializes the structure.
         
         :param center: 2D position of the source
         :param kernel: Scalar function from distance to intensity.
                        Described as a code spec.
     '''
     Primitive.__init__(self, id_object, tags)
     self.kernel_spec = kernel_spec
     self.kernel = instantiate_spec(self.kernel_spec)
     self.set_center(center)
Example #10
0
def cairo_show_world_geometry(cr, world_state, plot_sources=False, plot_textures=False, extra_pad=0):
    bounds = world_state["bounds"]
    primitives = world_state["primitives"]

    with cairo_save(cr):
        xb = bounds[0]
        yb = bounds[1]
        xb = [xb[0] - extra_pad, xb[1] + extra_pad]
        yb = [yb[0] - extra_pad, yb[1] + extra_pad]

        cr.rectangle(xb[0], yb[0], xb[1] - xb[0], yb[1] - yb[0])
        cr.clip()

        # Draw it twice for special effects
        for i in range(2):
            for p in primitives:
                ptype = p["type"]
                if ptype == VehiclesConstants.PRIMITIVE_POLYLINE:
                    points = np.array(p["points"]).T
                    texture = instantiate_spec(p["texture"])
                    if not plot_textures:
                        texture = None
                    cairo_plot_polyline_primitive(cr, points=points, texture=texture)

                elif ptype == VehiclesConstants.PRIMITIVE_CIRCLE:
                    texture = instantiate_spec(p["texture"])
                    if not plot_textures:
                        texture = None
                    cairo_plot_circle_primitive(
                        cr, center=p["center"], texture=texture, radius=p["radius"], solid=p["solid"], numpass=i
                    )

                elif ptype == VehiclesConstants.PRIMITIVE_SOURCE:
                    if plot_sources:
                        cairo_plot_circle(
                            cr, center=p["center"], radius=0.05, edgecolor=[0, 0, 0], facecolor=[1, 0, 0], width=0.01
                        )
                    # TODO: parametrize
                else:
                    pass  # XXX
    def init(self, boot_spec):
        DerivAgentRobust.init(self, boot_spec)
        shape = boot_spec.get_observations().shape()
        if len(shape) != 1:
            msg = 'This agent only works with 1D signals'
            raise UnsupportedSpec(msg)

        self.estimator = instantiate_spec(self.estimator_spec)
        if not isinstance(self.estimator, BDSEEstimatorInterface):
            msg = ('Expected a BDSEEstimatorInterface, got %s' 
                   % describe_type(self.estimator))
            raise ValueError(msg)

        self.commands_spec = boot_spec.get_commands()
Example #12
0
    def __init__(self, directions, noise=None, invalid=0.5):
        self.invalid = invalid

        self.noise_spec = noise
        self.noise = (None if self.noise_spec is None else
                          instantiate_spec(self.noise_spec))

        spec = {
            'desc': 'Photoreceptors',
            'shape': [len(directions)],
            'format': 'C',
            'range': [0, +1],
            'extra': {'directions': directions.tolist(),
                      'invalid': invalid,
                      'sono': 'qui',
                      'noise': self.noise_spec}
        }
        VehicleSensor.__init__(self, spec)

        TexturedRaytracer.__init__(self, directions)
Example #13
0
    def __init__(self, directions, noise=None, invalid=0.5):
        self.invalid = invalid

        self.noise_spec = noise
        self.noise = (None if self.noise_spec is None else instantiate_spec(
            self.noise_spec))

        spec = {
            'desc': 'Photoreceptors',
            'shape': [len(directions)],
            'format': 'C',
            'range': [0, +1],
            'extra': {
                'directions': directions.tolist(),
                'invalid': invalid,
                'sono': 'qui',
                'noise': self.noise_spec
            }
        }
        VehicleSensor.__init__(self, spec)

        TexturedRaytracer.__init__(self, directions)
    def __init__(self, directions, spatial_sigma_deg, upsample=10,
                 noise=None, invalid=0.5):
        self.invalid = invalid

        self.noise_spec = noise
        self.noise = (None if self.noise_spec is None else
                          instantiate_spec(self.noise_spec))

        spatial_sigma_rad = np.deg2rad(spatial_sigma_deg)
        self.delta = np.linspace(-3, 3, upsample) * spatial_sigma_rad

        directions2 = []
        for d in directions:
            for s in self.delta:
                directions2.append(d + s)

        self.directions_o = np.array(directions)

        def kernel(x):
            return np.exp(-(x ** 2))

        self.coeff = kernel(self.delta)
        self.coeff = self.coeff / np.sum(self.coeff)

        spec = {
            'desc': 'Photoreceptors',
            'shape': [len(directions)],
            'format': 'C',
            'range': [0, +1],
            'extra': {'directions': self.directions_o.tolist(),
                      'noise': self.noise_spec,
                      'delta': self.delta.tolist(),
                      'coeff': self.coeff.tolist(),
                      'spatial_sigma_deg': spatial_sigma_deg},
        }

        VehicleSensor.__init__(self, spec)
        TexturedRaytracer.__init__(self, np.array(directions2))
Example #15
0
    def __init__(self, positions,
                 min_value=0, max_value=1, normalize=False, noise=None,
                 shape=None):
        '''
            :param positions: 2D positions of the sensels 
        '''

        if normalize:
            logger.warning('normalize=True is deprecated')
            
        if shape is None:
            shape = [len(positions)]

        self.num_sensels = len(positions)
        self.positions = np.array(positions)
        self.min_value = min_value
        self.max_value = max_value
        self.normalize = normalize

        self.noise_spec = noise
        self.noise = (None if self.noise_spec is None else
                          instantiate_spec(self.noise_spec))

        boot_spec = {
            'desc': 'Field sampler',
            'shape': shape,
            'format': 'C',
            'range': [float(self.min_value), float(self.max_value)],
            'extra': {'positions': self.positions.tolist(),
                      'normalize': bool(normalize),
                      'max_value': float(max_value),
                      'min_value': float(min_value),
                      'noise': self.noise_spec}
        }

        VehicleSensor.__init__(self, boot_spec)

        self.primitives = None
Example #16
0
    def init(self, boot_spec):
        self.boot_spec = boot_spec
        
        if len(boot_spec.get_observations().shape()) != 1:
            raise UnsupportedSpec('This agent can only work with 1D signals.')

        self.count = 0
        self.rd = RemoveDoubles(self.change_fraction)
        self.y_deriv = DerivativeBox()

        self.bdse_estimator = instantiate_spec(self.estimator_spec)
        if not isinstance(self.bdse_estimator, BDSEEstimatorInterface):
            msg = ('Expected a BDSEEstimatorInterface, got %s' 
                   % describe_type(self.estimator))
            raise ValueError(msg)

    
        self.y_stats = MeanCovariance()

        self.explorer.init(boot_spec)
        self.commands_spec = boot_spec.get_commands()

        # All the rest are only statistics
        self.stats = MiscStatistics()
Example #17
0
def inspect_textures():
    parser = OptionParser(usage=usage)
    parser.disable_interspersed_args()

    parser.add_option("-w", "--world", default='stochastic_box_10',
                       help="ID world [%default].")

    parser.add_option("-n", default=1, type='int',
                    help="number of simulations [%default].")
    parser.add_option("--outdir", "-o", default='out-inspect_textures',
                    help="output directory [%default]")
    parser.add_option("--figsize", default=1, type='float',
                    help="figsize (inches) [%default]")
    parser.add_option("-z", "--zoom", default=0, type='float',
                    help="zoom in meters; 0 for full view [%default]")

    (options, args) = parser.parse_args()
    if args:
        raise Exception()  # XXX

    id_world = options.world

    logger.info('  id_world: %s' % id_world)

    world = VehiclesConfig.worlds.instance(id_world)  # @UndefinedVariable

    from reprep import Report
    basename = 'inspect_textures-%s' % (id_world)
    r = Report(basename)

    for i in range(options.n):
        sec = r.node('simulation%d' % i)
        world.new_episode()
        primitives = world.get_primitives()
        for p in primitives:
            psec = sec.node('%s_%d' % (p.__class__.__name__, p.id_object))
            psec.text('object', pformat(p.to_yaml()))

            f = psec.figure(cols=2)
            if not isinstance(p, GeometricShape):
                continue

            perimeter = p.get_perimeter()
            texture = instantiate_spec(p.texture)

            chunk_size = 10
            nchunks = np.ceil(perimeter * 1.0 / chunk_size)

            for c in range(int(nchunks)):
                xfrom = c * chunk_size
                xto = np.minimum(perimeter, xfrom + chunk_size)
                N = 1000
                x = np.linspace(xfrom, xto, N)

                lum = texture(x)

                with f.plot('chunk%s' % c,
                              figsize=(options.figsize * 10,
                                      options.figsize)) as pylab:
                    pylab.plot(x, lum)
                    pylab.axis((xfrom, xfrom + chunk_size, -0.1, 1.1))

#
#        if False:
#            with f.data_pylab('pdf', mime=MIME_PDF,
#                              figsize=(options.figsize,
#                                      options.figsize)) as pylab:
#                    display_all(pylab, sim_state, grid=1, zoom=0, 
# show_sensor_data = True)
#            f.last().add_to(f)

    filename = os.path.join(options.outdir, 'index.html')
    logger.info('Writing to %r.' % filename)
    r.to_html(filename)
 def __init__(self, fraction, estimator):
     self.estimator = instantiate_spec(estimator)
     self.fraction = fraction
Example #19
0
 def get_servo(self):
     servo_agent = instantiate_spec(self.servo)
     servo_agent.init(self.boot_spec)
     assert isinstance(servo_agent, DiffeoServoAgentInterface)
     servo_agent.set_discdds(self.discdds)
     return servo_agent
Example #20
0
def inspect_textures():
    parser = OptionParser(usage=usage)
    parser.disable_interspersed_args()

    parser.add_option("-w",
                      "--world",
                      default='stochastic_box_10',
                      help="ID world [%default].")

    parser.add_option("-n",
                      default=1,
                      type='int',
                      help="number of simulations [%default].")
    parser.add_option("--outdir",
                      "-o",
                      default='out-inspect_textures',
                      help="output directory [%default]")
    parser.add_option("--figsize",
                      default=1,
                      type='float',
                      help="figsize (inches) [%default]")
    parser.add_option("-z",
                      "--zoom",
                      default=0,
                      type='float',
                      help="zoom in meters; 0 for full view [%default]")

    (options, args) = parser.parse_args()
    if args:
        raise Exception()  # XXX

    id_world = options.world

    logger.info('  id_world: %s' % id_world)

    world = VehiclesConfig.worlds.instance(id_world)  # @UndefinedVariable

    from reprep import Report
    basename = 'inspect_textures-%s' % (id_world)
    r = Report(basename)

    for i in range(options.n):
        sec = r.node('simulation%d' % i)
        world.new_episode()
        primitives = world.get_primitives()
        for p in primitives:
            psec = sec.node('%s_%d' % (p.__class__.__name__, p.id_object))
            psec.text('object', pformat(p.to_yaml()))

            f = psec.figure(cols=2)
            if not isinstance(p, GeometricShape):
                continue

            perimeter = p.get_perimeter()
            texture = instantiate_spec(p.texture)

            chunk_size = 10
            nchunks = np.ceil(perimeter * 1.0 / chunk_size)

            for c in range(int(nchunks)):
                xfrom = c * chunk_size
                xto = np.minimum(perimeter, xfrom + chunk_size)
                N = 1000
                x = np.linspace(xfrom, xto, N)

                lum = texture(x)

                with f.plot('chunk%s' % c,
                            figsize=(options.figsize * 10,
                                     options.figsize)) as pylab:
                    pylab.plot(x, lum)
                    pylab.axis((xfrom, xfrom + chunk_size, -0.1, 1.1))


#
#        if False:
#            with f.data_pylab('pdf', mime=MIME_PDF,
#                              figsize=(options.figsize,
#                                      options.figsize)) as pylab:
#                    display_all(pylab, sim_state, grid=1, zoom=0,
# show_sensor_data = True)
#            f.last().add_to(f)

    filename = os.path.join(options.outdir, 'index.html')
    logger.info('Writing to %r.' % filename)
    r.to_html(filename)
Example #21
0
 def get_servo(self):
     servo_agent = instantiate_spec(self.servo)
     servo_agent.init(self.boot_spec)
     assert isinstance(servo_agent, DiffeoServoAgentInterface)
     servo_agent.set_discdds(self.discdds)
     return servo_agent