Пример #1
0
    def _get_asset_from_path(self, path):
        """Constructs a `Asset` given a file path."""
        _, basename = os.path.split(path)
        filename, extension = os.path.splitext(basename)

        # Look in the dict of pre-loaded assets before checking the filesystem.
        try:
            contents = self._parent.namescope.assets[path]
        except KeyError:
            # Construct the full path to the asset file, prefixed by the path to the
            # model directory, and by `meshdir` or `texturedir` if appropriate.
            path_parts = []
            if self._parent.namescope.model_dir:
                path_parts.append(self._parent.namescope.model_dir)
            try:
                base_path = self._parent.namescope.get(constants.BASEPATH,
                                                       self._path_namespace)
                path_parts.append(base_path)
            except KeyError:
                pass
            path_parts.append(path)
            full_path = os.path.join(*path_parts)  # pylint: disable=no-value-for-parameter
            contents = resources.GetResource(full_path)
        if self._parent.tag == constants.SKIN:
            return SkinAsset(contents=contents,
                             parent=self._parent,
                             extension=extension,
                             prefix=filename)
        else:
            return Asset(contents=contents,
                         extension=extension,
                         prefix=filename)
Пример #2
0
def get_model_and_assets(floor_size=10, remove_ball=True):
  """Returns a tuple containing the model XML string and a dict of assets."""
  assets = common.ASSETS.copy()
  _, _, filenames = next(resources.WalkResources(_ASSET_DIR))
  for filename in filenames:
    assets[filename] = resources.GetResource(os.path.join(_ASSET_DIR, filename))
  return make_model(floor_size, remove_ball), assets
Пример #3
0
def _make_model(n_poles, xml):
    """Generates an xml string defining a cart with `n_poles` bodies."""
    base = os.path.dirname(os.path.dirname(__file__))
    xml_string = resources.GetResource(os.path.join(base, 'cartpoles', xml))
    #xml_string = common.read_model(xml)
    if n_poles == 1:
        return xml_string
    mjcf = etree.fromstring(xml_string)
    parent = mjcf.find('./worldbody/body/body')  # Find first pole.
    # Make chain of poles.
    for pole_index in range(2, n_poles + 1):
        child = etree.Element('body',
                              name='pole_{}'.format(pole_index),
                              pos='0 0 1',
                              childclass='pole')
        etree.SubElement(child, 'joint', name='hinge_{}'.format(pole_index))
        etree.SubElement(child, 'geom', name='pole_{}'.format(pole_index))
        parent.append(child)
        parent = child
    # Move plane down.
    floor = mjcf.find('./worldbody/geom')
    floor.set('pos', '0 0 {}'.format(1 - n_poles - .05))
    # Move cameras back.
    cameras = mjcf.findall('./worldbody/camera')
    cameras[0].set('pos', '0 {} 1'.format(-1 - 2 * n_poles))
    cameras[1].set('pos', '0 {} 2'.format(-2 * n_poles))
    return etree.tostring(mjcf, pretty_print=True)
Пример #4
0
def from_path(path,
              escape_separators=False,
              resolve_references=True,
              assets=None):
    """Parses an XML file into an MJCF object model.

  Args:
    path: A path to an XML file. This path should be loadable using
      `resources.GetResource`.
    escape_separators: (optional) A boolean, whether to replace '/' characters
      in element identifiers. If `False`, any '/' present in the XML causes
      a ValueError to be raised.
    resolve_references: (optional) A boolean indicating whether the parser
      should attempt to resolve reference attributes to a corresponding element.
    assets: (optional) A dictionary of pre-loaded assets, of the form
      `{filename: bytestring}`. If present, PyMJCF will search for assets in
      this dictionary before attempting to load them from the filesystem.

  Returns:
    An `mjcf.RootElement`.
  """
    model_dir, _ = os.path.split(path)
    contents = resources.GetResource(path)
    xml_root = etree.fromstring(contents)
    return _parse(xml_root,
                  escape_separators,
                  model_dir=model_dir,
                  resolve_references=resolve_references,
                  assets=assets)
def get_model_and_assets_from_setting_kwargs(model_fname, setting_kwargs=None):
    """"Returns a tuple containing the model XML string and a dict of assets."""
    assets = {
        filename: resources.GetResource(os.path.join(_SUITE_DIR, filename))
        for filename in _FILENAMES
    }

    if setting_kwargs is None:
        return common.read_model(model_fname), assets

    # Convert XML to dicts
    model = xmltodict.parse(common.read_model(model_fname))
    materials = xmltodict.parse(assets['./common/materials.xml'])
    skybox = xmltodict.parse(assets['./common/skybox.xml'])

    # Edit grid floor
    if 'grid_rgb1' in setting_kwargs:
        assert isinstance(setting_kwargs['grid_rgb1'],
                          (list, tuple, np.ndarray))
        materials['mujoco']['asset']['texture']['@rgb1'] = \
            f'{setting_kwargs["grid_rgb1"][0]} {setting_kwargs["grid_rgb1"][1]} {setting_kwargs["grid_rgb1"][2]}'
    if 'grid_rgb2' in setting_kwargs:
        assert isinstance(setting_kwargs['grid_rgb2'],
                          (list, tuple, np.ndarray))
        materials['mujoco']['asset']['texture']['@rgb2'] = \
            f'{setting_kwargs["grid_rgb2"][0]} {setting_kwargs["grid_rgb2"][1]} {setting_kwargs["grid_rgb2"][2]}'

    # Edit self
    if 'self_rgb' in setting_kwargs:
        assert isinstance(setting_kwargs['self_rgb'],
                          (list, tuple, np.ndarray))
        materials['mujoco']['asset']['material'][1]['@rgba'] = \
            f'{setting_kwargs["self_rgb"][0]} {setting_kwargs["self_rgb"][1]} {setting_kwargs["self_rgb"][2]} 1'

    # Edit skybox
    if 'skybox_rgb' in setting_kwargs:
        assert isinstance(setting_kwargs['skybox_rgb'],
                          (list, tuple, np.ndarray))
        skybox['mujoco']['asset']['texture']['@rgb1'] = \
            f'{setting_kwargs["skybox_rgb"][0]} {setting_kwargs["skybox_rgb"][1]} {setting_kwargs["skybox_rgb"][2]}'
    if 'skybox_rgb2' in setting_kwargs:
        assert isinstance(setting_kwargs['skybox_rgb2'],
                          (list, tuple, np.ndarray))
        skybox['mujoco']['asset']['texture']['@rgb2'] = \
            f'{setting_kwargs["skybox_rgb2"][0]} {setting_kwargs["skybox_rgb2"][1]} {setting_kwargs["skybox_rgb2"][2]}'
    if 'skybox_markrgb' in setting_kwargs:
        assert isinstance(setting_kwargs['skybox_markrgb'],
                          (list, tuple, np.ndarray))
        skybox['mujoco']['asset']['texture']['@markrgb'] = \
            f'{setting_kwargs["skybox_markrgb"][0]} {setting_kwargs["skybox_markrgb"][1]} {setting_kwargs["skybox_markrgb"][2]}'

    # Convert back to XML
    model_xml = xmltodict.unparse(model)
    assets['./common/materials.xml'] = xmltodict.unparse(materials)
    assets['./common/skybox.xml'] = xmltodict.unparse(skybox)

    return model_xml, assets
Пример #6
0
def getAssets(root, addr):
    path = os.path.join(root, addr)
    if os.path.isdir(path):
        tree = list(Path(path).rglob("*"))
        file_list = [str(e) for e in tree if not os.path.isdir(str(e))]
    else:
        file_list = [path]

    # Exclude any specific entry that you don't want
    assets = {
        os.path.relpath(file, root): resources.GetResource(file)
        for file in file_list
    }
    return assets
Пример #7
0
  def test_hdf5_agrees_with_textprotos(self):

    hdf5_loader = loader.HDF5TrajectoryLoader(
        resources.GetResourceFilename(HDF5))

    for textproto_path in TEXTPROTOS:
      trajectory_textproto = resources.GetResource(textproto_path)
      trajectory_from_textproto = mocap_pb2.FittedTrajectory()
      text_format.Parse(trajectory_textproto, trajectory_from_textproto)

      trajectory_identifier = (
          trajectory_from_textproto.identifier.encode('utf-8'))
      self.assert_proto_equal(
          hdf5_loader.get_trajectory(trajectory_identifier)._proto,
          trajectory.Trajectory(trajectory_from_textproto)._proto)
Пример #8
0
def _asset_png_with_background_rgba_bytes(asset_fname, background_rgba):
  """Decode PNG from asset file and add solid background."""

  # Retrieve PNG image contents as a bytestring, convert to a numpy array.
  contents = resources.GetResource(os.path.join(_ASSETS_PATH, asset_fname))
  digit_rgba = np.array(Image.open(six.BytesIO(contents)), dtype=np.double)

  # Add solid background with `background_rgba`.
  blended = 255. * _alpha_blend(digit_rgba / 255., np.asarray(background_rgba))

  # Encode composite image array to a PNG bytestring.
  img = Image.fromarray(blended.astype(np.uint8), mode='RGBA')
  buf = six.BytesIO()
  img.save(buf, format='PNG')
  png_encoding = buf.getvalue()
  buf.close()

  return png_encoding
Пример #9
0
def _get_texture(name):
    contents = resources.GetResource(
        os.path.join(_ASSETS_PATH, '{}.png'.format(name)))
    return mjcf.Asset(contents, '.png')
Пример #10
0
def read_model(model_filename):
    """Reads amplitude model XML file and returns its contents as amplitude string."""
    _SUITE_DIR = os.path.dirname(os.path.dirname(__file__))
    return resources.GetResource(os.path.join(_SUITE_DIR + '/dm_control_mod/', model_filename))
Пример #11
0
def read_model(model_filename):
  """Reads a model XML file and returns its contents as a string."""
  return resources.GetResource(os.path.join(_SUITE_DIR, model_filename))
Пример #12
0
    def _build(self,
               name='walker',
               marker_rgba=None,
               camera_control=False,
               roll_gear=-60,
               steer_gear=55,
               walker_id=None,
               initializer=None):
        """Build a BoxHead.

    Args:
      name: name of the walker.
      marker_rgba: RGBA value set to walker.marker_geoms to distinguish between
        walkers (in multi-agent setting).
      camera_control: If `True`, the walker exposes two additional actuated
        degrees of freedom to control the egocentric camera height and tilt.
      roll_gear: gear determining forward acceleration.
      steer_gear: gear determining steering (spinning) torque.
      walker_id: (Optional) An integer in [0-10], this number will be shown on
        the walker's head. Defaults to `None` which does not show any number.
      initializer: (Optional) A `WalkerInitializer` object.

    Raises:
      ValueError: if received invalid walker_id.
    """
        super(BoxHead, self)._build(initializer=initializer)
        xml_path = os.path.join(_ASSETS_PATH, 'boxhead.xml')
        self._mjcf_root = mjcf.from_xml_string(
            resources.GetResource(xml_path, 'r'))
        if name:
            self._mjcf_root.model = name

        if walker_id is not None and not 0 <= walker_id <= _MAX_WALKER_ID:
            raise ValueError(_INVALID_WALKER_ID.format(walker_id))

        self._walker_id = walker_id
        if walker_id is not None:
            png_bytes = _asset_png_with_background_rgba_bytes(
                'digits/%02d.png' % walker_id, marker_rgba)
            head_texture = self._mjcf_root.asset.add('texture',
                                                     name='head_texture',
                                                     type='2d',
                                                     file=mjcf.Asset(
                                                         png_bytes, '.png'))
            head_material = self._mjcf_root.asset.add('material',
                                                      name='head_material',
                                                      texture=head_texture)
            self._mjcf_root.find('geom', 'head').material = head_material
            self._mjcf_root.find('geom', 'head').rgba = None

            self._mjcf_root.find('geom',
                                 'top_down_cam_box').material = head_material
            self._mjcf_root.find('geom', 'top_down_cam_box').rgba = None

        self._body_texture = self._mjcf_root.asset.add(
            'texture',
            name='ball_body',
            type='cube',
            builtin='checker',
            rgb1=marker_rgba[:-1] if marker_rgba else '.4 .4 .4',
            rgb2='.8 .8 .8',
            width='100',
            height='100')
        self._body_material = self._mjcf_root.asset.add(
            'material', name='ball_body', texture=self._body_texture)
        self._mjcf_root.find('geom', 'shell').material = self._body_material

        # Set corresponding marker color if specified.
        if marker_rgba is not None:
            for geom in self.marker_geoms:
                geom.set_attributes(rgba=marker_rgba)

        self._root_joints = None
        self._camera_control = camera_control
        if not camera_control:
            for name in ('camera_pitch', 'camera_yaw'):
                self._mjcf_root.find('actuator', name).remove()
                self._mjcf_root.find('joint', name).remove()
        self._roll_gear = roll_gear
        self._steer_gear = steer_gear
        self._mjcf_root.find('actuator', 'roll').gear[0] = self._roll_gear
        self._mjcf_root.find('actuator', 'steer').gear[0] = self._steer_gear

        # Initialize previous action.
        self._prev_action = np.zeros(shape=self.action_spec.shape,
                                     dtype=self.action_spec.dtype)
Пример #13
0
def get_contents(filename):
    """Returns the contents of an asset as a string."""
    return resources.GetResource(os.path.join(_ASSETS_DIR, filename))
Пример #14
0
    "./common/kinova_meshes/forearm.stl",
    "./common/kinova_meshes/ring_big.stl",
    "./common/kinova_meshes/ring_small.stl",
    "./common/kinova_meshes/wrist_spherical_1.stl",
    "./common/kinova_meshes/wrist_spherical_2.stl",
    "./common/kinova_meshes/hand_3finger.stl",
    "./common/kinova_meshes/finger_proximal.stl",
    "./common/kinova_meshes/finger_distal.stl",
    # textures
    "./common/textures/darkwood.png",
    "./common/textures/granite.png",
    "./common/textures/light_wood.png",
    "./common/textures/light_wood_v2.png",
    "./common/textures/light_wood_v3.png",
    "./common/textures/marble.png",
    "./common/textures/metal.png",
    "./common/textures/navy_blue.png",
    "./common/textures/real_door.png",
    "./common/textures/tennis.png",
    "./common/textures/wood_light.png",
    "./common/textures/wood.png",
   ]

ASSETS = {filename: resources.GetResource(os.path.join(_SUITE_DIR, filename))
          for filename in _FILENAMES}


def read_model(model_filename):
  """Reads a model XML file and returns its contents as a string."""
  return resources.GetResource(os.path.join(_SUITE_DIR, model_filename))
Пример #15
0
 def test_can_parse_and_write_back(self):
     contents = resources.GetResource(SKIN_FILE_PATH, mode='rb')
     parsed = skin.parse(contents, body_getter=FakeMJCFBody)
     reconstructed = skin.serialize(parsed)
     self.assertEqual(reconstructed, contents)
Пример #16
0
def _make_goboard(boardsize,
                  square_halfwidth,
                  height=0.01,
                  sensor_size=0.7,
                  name='goboard'):
    """Builds a Go with touch sensors centered on each intersection."""
    y_offset = -0.08
    rows = boardsize
    columns = boardsize
    root = mjcf.RootElement(model=name)
    if _SHOW_DEBUG_GRID:
        black_mat = root.asset.add('material',
                                   name='black',
                                   rgba=(0.2, 0.2, 0.2, 0.5))
        white_mat = root.asset.add('material',
                                   name='white',
                                   rgba=(0.8, 0.8, 0.8, 0.5))
    else:
        transparent_mat = root.asset.add('material',
                                         name='intersection',
                                         rgba=(0, 1, 0, 0.0))

    sensor_mat = root.asset.add('material', name='sensor', rgba=(0, 1, 0, 0.3))

    contents = resources.GetResource(_TEXTURE_PATH)
    root.asset.add('texture',
                   name='goboard',
                   type='2d',
                   file=mjcf.Asset(contents, '.png'))
    board_mat = root.asset.add('material',
                               name='goboard',
                               texture='goboard',
                               texrepeat=[0.97, 0.97])

    root.default.geom.set_attributes(type='box',
                                     size=(square_halfwidth, square_halfwidth,
                                           height))
    root.default.site.set_attributes(
        type='box',
        size=(sensor_size * square_halfwidth, ) * 2 + (0.5 * height, ),
        material=sensor_mat,
        group=composer.SENSOR_SITES_GROUP)

    board_height = height
    if _SHOW_DEBUG_GRID:
        board_height = 0.5 * height

    root.worldbody.add('geom',
                       pos=(0, 0 + y_offset, height),
                       type='box',
                       size=(square_halfwidth * boardsize, ) * 2 +
                       (board_height, ),
                       name=name,
                       material=board_mat)

    xpos = (np.arange(columns) - 0.5 * (columns - 1)) * 2 * square_halfwidth
    ypos = (np.arange(rows) - 0.5 *
            (rows - 1)) * 2 * square_halfwidth + y_offset
    geoms = []
    touch_sensors = []
    for i in range(rows):
        for j in range(columns):
            name = '{}_{}'.format(i, j)
            if _SHOW_DEBUG_GRID:
                transparent_mat = black_mat if ((i % 2) == (j %
                                                            2)) else white_mat
            geoms.append(
                root.worldbody.add('geom',
                                   pos=(xpos[j], ypos[i], height),
                                   name=name,
                                   material=transparent_mat))
            site = root.worldbody.add('site',
                                      pos=(xpos[j], ypos[i], 2 * height),
                                      name=name)
            touch_sensors.append(root.sensor.add('touch', site=site,
                                                 name=name))

    pass_geom = root.worldbody.add(
        'geom',
        pos=(0, y_offset, 0.0),
        size=(square_halfwidth * boardsize * 2, square_halfwidth * boardsize) +
        (0.5 * height, ),
        name='pass',
        material=transparent_mat)
    site = root.worldbody.add(
        'site',
        pos=(0, y_offset, 0.0),
        size=(square_halfwidth * boardsize * 2, square_halfwidth * boardsize) +
        (0.5 * height, ),
        name='pass')
    pass_sensor = root.sensor.add('touch', site=site, name='pass')

    return root, geoms, touch_sensors, pass_geom, pass_sensor
Пример #17
0
# Copyright 2017 The dm_control Authors.
Пример #18
0
 def read_model(self, model_filename):
     """Reads a model XML file and returns its contents as a string."""
     return resources.GetResource(model_filename)
def get_model_and_assets_from_setting_kwargs(model_fname, setting_kwargs=None):
    """"Returns a tuple containing the model XML string and a dict of assets."""
    assets = {filename: resources.GetResource(os.path.join(_SUITE_DIR, filename))
          for filename in _FILENAMES}

    if setting_kwargs is None:
        return common.read_model(model_fname), assets

    # Convert XML to dicts
    model = xmltodict.parse(common.read_model(model_fname))
    materials = xmltodict.parse(assets['./common/materials.xml'])
    skybox = xmltodict.parse(assets['./common/skybox.xml'])

    # Edit lighting
    if 'light_pos' in setting_kwargs:
        assert isinstance(setting_kwargs['light_pos'], (list, tuple, np.ndarray))
        light_pos = f'{setting_kwargs["light_pos"][0]} {setting_kwargs["light_pos"][1]} {setting_kwargs["light_pos"][2]}'
        if 'light' in model['mujoco']['worldbody']:
            model['mujoco']['worldbody']['light']['@pos'] = light_pos
        elif 'light' in model['mujoco']['worldbody']['body']:
            model['mujoco']['worldbody']['body']['light']['@pos'] = light_pos
        else:
            raise NotImplementedError('model xml does not contain entity light')

    # Edit camera
    if 'cam_pos' in setting_kwargs:
        assert isinstance(setting_kwargs['cam_pos'], (list, tuple, np.ndarray))
        cam_pos = f'{setting_kwargs["cam_pos"][0]} {setting_kwargs["cam_pos"][1]} {setting_kwargs["cam_pos"][2]}'
        if 'camera' in model['mujoco']['worldbody']:
            model['mujoco']['worldbody']['camera'][0]['@pos'] = cam_pos
        elif 'camera' in model['mujoco']['worldbody']['body']:
            model['mujoco']['worldbody']['body']['camera'][0]['@pos'] = cam_pos
        else:
            raise NotImplementedError('model xml does not contain entity camera')

    # Edit distractor
    if 'distractor_pos' in setting_kwargs:
        assert isinstance(setting_kwargs['distractor_pos'], (list, tuple, np.ndarray))
        distractor_pos = f'{setting_kwargs["distractor_pos"][0]} {setting_kwargs["distractor_pos"][1]} {setting_kwargs["distractor_pos"][2]}'
        assert model['mujoco']['worldbody']['body'][-1]['@name'] == 'distractor', 'distractor must be in worldbody'
        model['mujoco']['worldbody']['body'][-1]['geom']['@pos'] = distractor_pos

    # Edit grid floor
    if 'grid_rgb1' in setting_kwargs:
        assert isinstance(setting_kwargs['grid_rgb1'], (list, tuple, np.ndarray))
        materials['mujoco']['asset']['texture']['@rgb1'] = \
            f'{setting_kwargs["grid_rgb1"][0]} {setting_kwargs["grid_rgb1"][1]} {setting_kwargs["grid_rgb1"][2]}'
    if 'grid_rgb2' in setting_kwargs:
        assert isinstance(setting_kwargs['grid_rgb2'], (list, tuple, np.ndarray))
        materials['mujoco']['asset']['texture']['@rgb2'] = \
            f'{setting_kwargs["grid_rgb2"][0]} {setting_kwargs["grid_rgb2"][1]} {setting_kwargs["grid_rgb2"][2]}'
    if 'grid_texrepeat' in setting_kwargs:
        assert isinstance(setting_kwargs['grid_texrepeat'], (list, tuple, np.ndarray))
        materials['mujoco']['asset']['material'][0]['@texrepeat'] = \
            f'{setting_kwargs["grid_texrepeat"][0]} {setting_kwargs["grid_texrepeat"][1]}'
    if 'grid_reflectance' in setting_kwargs:
        materials['mujoco']['asset']['material'][0]['@reflectance'] = \
            str(setting_kwargs["grid_reflectance"])

    # Edit self
    if 'self_rgb' in setting_kwargs:
        assert isinstance(setting_kwargs['self_rgb'], (list, tuple, np.ndarray))
        materials['mujoco']['asset']['material'][1]['@rgba'] = \
            f'{setting_kwargs["self_rgb"][0]} {setting_kwargs["self_rgb"][1]} {setting_kwargs["self_rgb"][2]} 1'

    # Edit skybox
    if 'skybox_rgb' in setting_kwargs:
        assert isinstance(setting_kwargs['skybox_rgb'], (list, tuple, np.ndarray))
        skybox['mujoco']['asset']['texture']['@rgb1'] = \
            f'{setting_kwargs["skybox_rgb"][0]} {setting_kwargs["skybox_rgb"][1]} {setting_kwargs["skybox_rgb"][2]}'
    if 'skybox_rgb2' in setting_kwargs:
        assert isinstance(setting_kwargs['skybox_rgb2'], (list, tuple, np.ndarray))
        skybox['mujoco']['asset']['texture']['@rgb2'] = \
            f'{setting_kwargs["skybox_rgb2"][0]} {setting_kwargs["skybox_rgb2"][1]} {setting_kwargs["skybox_rgb2"][2]}'
    if 'skybox_markrgb' in setting_kwargs:
        assert isinstance(setting_kwargs['skybox_markrgb'], (list, tuple, np.ndarray))
        skybox['mujoco']['asset']['texture']['@markrgb'] = \
            f'{setting_kwargs["skybox_markrgb"][0]} {setting_kwargs["skybox_markrgb"][1]} {setting_kwargs["skybox_markrgb"][2]}'

    # Convert back to XML
    model_xml = xmltodict.unparse(model)
    assets['./common/materials.xml'] = xmltodict.unparse(materials)
    assets['./common/skybox.xml'] = xmltodict.unparse(skybox)

    return model_xml, assets