Exemplo n.º 1
0
    def __init__(self, knowledge_base):
        # this knowledge base reference is used for updating the robot state
        self.knowledge_base = knowledge_base

        # create the viewer
        self.viewer = Viewer()

        BaseJob.__init__(self, None, None)
Exemplo n.º 2
0
class ControlJob(BaseJob):
    def __init__(self, knowledge_base):
        # this knowledge base reference is used for updating the robot state
        self.knowledge_base = knowledge_base

        # create the viewer
        self.viewer = Viewer()

        BaseJob.__init__(self, None, None)

    def _get_interface(self):
        return ControlInterface

    def _handler(self):
        logger.debug('child {} start'.format(self.child.pid))

        # hold a reference to the world so that it is not garbage collected
        self.world = WorldModel()
        # create the robot model for the controller
        self.robot = self.world.loadRobot(os.path.join('klampt_models', baxter.klampt_model_name))
        logger.debug('robot model loaded from {}'.format(baxter.klampt_model_name))
        self.controller = LowLevelController(self.robot, baxter.klampt_model_name)
        logger.debug('controller low-level controller initialized')

        # send the initial controller state
        self.child_pipe.send((None, RobotState(self.controller)))

        while True:
            # get the call information
            try:
                # update the viewer while waiting for a command
                while not self.child_pipe.poll():
                    self._update_viewer()
                    sleep(interval)

                # receive the command
                (self.knowledge_base, self.method, self.args, self.kwargs) = self.child_pipe.recv()
            except EOFError:
                logger.info('child {} shutdown requested'.format(self.child.pid))
                # signal to shut down
                break

            # distinguish between pure knowledge base updates and method calls
            if not self.method:
                self._update_viewer()
                self._send_result(None)
                continue

            # route remote calls
            self.init_args = (self.controller, self.knowledge_base)
            # hook the sleep method to update the viewer during execution
            self.kwargs['sleep'] = lambda n: self._sleep(n)
            BaseJob._handler(self)

        # clean up
        # need to call the superclass since this class overrides with empty method
        BaseJob._close()
        # TODO: shutdown the controller
        #controller.motion.shutdown()

        self.viewer.close()

    def _sleep(self, n):
        while n > 0:
            self._update_viewer()
            n -= interval
            sleep(interval)

    def _update_viewer(self):
        try:
            # check to see if the viewer is alive
            if self.viewer.heartbeat:
                # update the viewer
                logger.info('updating viewer')
                self.viewer.update(self.knowledge_base, RobotState(self.controller))
                logger.info('done updating viewer')
            else:
                logger.info('viewer missed heartbeat')
                pass
        except Exception as e:
            logger.error('failed to update the viewer: {}'.format(e))

    def _send_result(self, result):
        # attach the robot state to the job result
        BaseJob._send_result(self, (result, RobotState(self.controller)))

    def _check(self):
        # run even if child is still alive
        # check for a result before attempting a blocking call
        if self.pipe.poll():
            self._process_result()
            self._done = True

            # extract the robot state and update the knowledge base
            if not self.error:
                (self._result, self.knowledge_base.robot_state) = self.result

        # check that the child is alive
        # this is done after the poll since the child could have sent a result and then executed
        if not self.alive:
            logger.error('child {} died unexpectedly: {}'.format(self.child.pid, self.child.exitcode))
            # set this exception as the error result
            self._error = Exception('child died unexpectedly: {}'.format(self.child.exitcode))
            self._done = True

    def _close(self):
        # keep the pipes open by default
        pass
                  clip_max=clip_max)
    images_adv, = batch_eval(model._sess, [model.nodes.input], [n_fgsm],
                             [adv_image_lists[0]],
                             args={'batch_size': batch_size},
                             feed={model._is_training: False})
    adv_image_lists.append(images_adv)


def generate_visualization(i0):
    def get_row(i):
        ims = adv_image_lists[i][i0:i0 + image_count]
        s, m = Cifar10Loader.std, Cifar10Loader.mean
        scale = lambda x: np.clip(x * s + m, 0, 255).astype(np.ubyte)
        return list(map(scale, ims))

    cols = [get_row(i) for i in range(i0, i0 + len(epss))]
    return visualization.compose(cols, format=None)

    images = [im for i in range(i0, i0 + 3) for im in get_row(i)]
    comp_format = "".join([
        str(i) + "," if i % image_count == image_count - 1 else ";"
        for i in range(len(images))
    ])[:-1]
    return visualization.compose(images, format=comp_format)


scaled_eps = eps * np.max(Cifar10Loader.std)
viewer = Viewer("Adversarial examples, scaled eps=" + str(scaled_eps) +
                ", eps=" + str(eps))
viewer.display(np.arange(batch_size), generate_visualization)