Example #1
0
def StartMeshcat():
    """
    Constructs a Meshcat instance, with support for Deepnote and Google Colab.

    On most platforms, this method is equivalent to calling `meshcat =
    Meshcat()`. On Deepnote or Google Colab, this provides extra functionality,
    setting Meshcat to use the appropriate ports and to use ngrok if necessary.

    Note that the free/unregistered version of ngrok only allows two
    connections. On Google Colab, this means one can only have two viable
    Meshcat instances running per provisioned machine. On Deepnote, we have one
    additional port available (port 8080) which does not require ngrok; you
    must "Allow incoming connections" in the environment settings to use it.

    If you run out of available ports, you can reset the notebook to free any
    ports that are currently used by the notebook.

    Warning:
     Drake's support for Colab is deprecated.
     New releases after 2022-04-01 will no longer be compatible with Colab.
     See `drake#13391 <https://github.com/RobotLocomotion/drake/issues/13391>`_
     or `colab#1880 <https://github.com/googlecolab/colabtools/issues/1880>`_
     for details.
    """
    prev_log_level = set_log_level("warn")
    use_ngrok = False
    if ("DEEPNOTE_PROJECT_ID" in os.environ):
        # Deepnote exposes port 8080 (only).  If we need multiple meshcats,
        # then we fall back to ngrok.
        # TODO(jwnimmer-tri) Use _start_meshcat_deepnote() instead of ngrok,
        # once we have a bit more experience with it.
        try:
            meshcat = Meshcat(8080)
        except RuntimeError:
            use_ngrok = True
        else:
            set_log_level(prev_log_level)
            web_url = f"https://{os.environ['DEEPNOTE_PROJECT_ID']}.deepnoteproject.com"  # noqa
            print(f'Meshcat is now available at {web_url}')
            return meshcat

    if 'google.colab' in sys.modules:
        use_ngrok = True

    meshcat = Meshcat()
    web_url = meshcat.web_url()
    if use_ngrok:
        from pyngrok import ngrok
        http_tunnel = ngrok.connect(meshcat.port(), bind_tls=False)
        web_url = http_tunnel.public_url

    set_log_level(prev_log_level)
    print(f'Meshcat is now available at {web_url}')

    return meshcat
Example #2
0
def _start_meshcat_ngrok():
    from IPython.display import display, HTML
    from pyngrok import ngrok
    from pydrake.common import set_log_level
    prev_log_level = set_log_level("warn")
    meshcat = Meshcat()
    set_log_level(prev_log_level)
    http_tunnel = ngrok.connect(meshcat.port(), bind_tls=False)
    url = http_tunnel.public_url
    display(HTML(f"Meshcat URL: <a href='{url}' target='_blank'>{url}</a>"))
    return meshcat
Example #3
0
def StartMeshcat():
    """
    Constructs a Meshcat instance, with support for Deepnote and Google Colab.

    On most platforms, this method is equivalent to calling `meshcat =
    Meshcat()`. On Deepnote or Google Colab, this provides extra functionality,
    setting Meshcat to use the appropriate ports and to use ngrok if necessary.

    Note that the free/unregistered version of ngrok only allows two
    connections. On Google Colab, this means one can only have two viable
    Meshcat instances running per provisioned machine. On Deepnote, we have one
    additional port available (port 8080) which does not require ngrok; you
    must "Allow incoming connections" in the environment settings to use it.

    If you run out of available ports, you can reset the notebook to free any
    ports that are currently used by the notebook.
    """
    prev_log_level = set_log_level("warn")
    use_ngrok = False
    if ("DEEPNOTE_PROJECT_ID" in os.environ):
        # Deepnote exposes port 8080 (only).  If we need multiple meshcats,
        # then we fall back to ngrok.
        try:
            meshcat = Meshcat(8080)
        except RuntimeError:
            use_ngrok = True
        else:
            set_log_level(prev_log_level)
            web_url = f"https://{os.environ['DEEPNOTE_PROJECT_ID']}.deepnoteproject.com"  # noqa
            print(f'Meshcat is now available at {web_url}')
            return meshcat

    if 'google.colab' in sys.modules:
        use_ngrok = True

    meshcat = Meshcat()
    web_url = meshcat.web_url()
    if use_ngrok:
        from pyngrok import ngrok
        http_tunnel = ngrok.connect(meshcat.port(), bind_tls=False)
        web_url = http_tunnel.public_url

    set_log_level(prev_log_level)
    print(f'Meshcat is now available at {web_url}')

    return meshcat
Example #4
0
def StartMeshcat(open_window=False):
    """
    A wrapper around the Meshcat constructor that supports Deepnote and Google
    Colab via ngrok when necessary.
    """
    prev_log_level = set_log_level("warn")
    use_ngrok = False
    if ("DEEPNOTE_PROJECT_ID" in os.environ):
        # Deepnote exposes port 8080 (only).  If we need multiple meshcats,
        # then we fall back to ngrok.
        try:
            meshcat = Meshcat(8080)
        except RuntimeError:
            use_ngrok = True
        else:
            set_log_level(prev_log_level)
            web_url = f"https://{os.environ['DEEPNOTE_PROJECT_ID']}.deepnoteproject.com"  # noqa
            print(f"Meshcat is now available at {web_url}")
            if open_window:
                display(Javascript(f'window.open("{web_url}");'))
            return meshcat

    if 'google.colab' in sys.modules:
        use_ngrok = True

    meshcat = Meshcat()
    web_url = meshcat.web_url()
    if use_ngrok:
        from pyngrok import ngrok
        http_tunnel = ngrok.connect(meshcat.port(), bind_tls=False)
        web_url = http_tunnel.public_url

    set_log_level(prev_log_level)
    display(
        HTML('Meshcat is now available at '
             f'<a href="{web_url}">{web_url}</a>'))

    if open_window:
        if 'google.colab' in sys.modules:
            from google.colab import output
            output.eval_js(f'window.open("{web_url}");', ignore_result=True)
        else:
            display(Javascript(f'window.open("{web_url}");'))

    return meshcat
Example #5
0
def main():
    # Parse our arguments.
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--python_level",
        metavar="INT",
        type=int,
        required=True,
        help="Set Python Drake logger to this level, or use 0 as a no-op.")
    parser.add_argument(
        "--spdlog_level_name",
        metavar="STR",
        type=str,
        required=True,
        help="Set C++ Drake to this log level, or use 'unchanged' as a no-op."
        " Refer to set_log_level in drake/common for valid level names.")
    parser.add_argument(
        "--use_nice_format",
        metavar="1|0",
        type=int,
        required=True,
        help="Switch on (or off) nicely formatted Python output.")
    args = parser.parse_args()

    # Configure Python logging (if requested).
    if args.python_level != logging.NOTSET:
        if args.use_nice_format:
            configure_logging()
            logging.getLogger().setLevel(args.python_level)
        else:
            logging.basicConfig(level=args.python_level)
            logging.getLogger("drake").setLevel(logging.NOTSET)
    else:
        # Trying to use the "nice format" makes no sense when we're not even
        # configuring Python logging in the first place.
        assert args.use_nice_format == 0

    # Configure C++ logging (if requested).
    if args.spdlog_level_name != "unchanged":
        set_log_level(args.spdlog_level_name)

    # Emit a bunch of log messages from C++. Depending on the level filtering,
    # not all of them will be printed.
    do_log_test()
Example #6
0
 def test_logging(self):
     self.assertTrue(mut._module_py._HAVE_SPDLOG)
     self.assertIsInstance(mut.set_log_level(level="unchanged"), str)
Example #7
0
def DepthCameraDemoSystem():
    builder = DiagramBuilder()

    # If you have trouble finding resources, you can enable trace logging
    # to see how `FindResource*` is searching.
    set_log_level("trace")

    # Create the physics engine + scene graph.
    plant, scene_graph = AddMultibodyPlantSceneGraph(builder, time_step=0.0)
    # Add a single object into it.
    Parser(plant, scene_graph).AddModelFromFile(
        FindResourceOrThrow(
            "drake/manipulation/models/ycb/sdf/006_mustard_bottle.sdf"))
    # Add a rendering engine
    renderer = "my_renderer"
    scene_graph.AddRenderer(renderer,
                            MakeRenderEngineVtk(RenderEngineVtkParams()))
    plant.Finalize()

    # Add a visualizer just to help us see the object.
    use_meshcat = False
    if use_meshcat:
        meshcat = builder.AddSystem(MeshcatVisualizer(scene_graph))
        builder.Connect(scene_graph.get_pose_bundle_output_port(),
                        meshcat.get_input_port(0))

    # Add a camera to the environment.
    pose = RigidTransform(RollPitchYaw(-0.2, 0.2, 0), [-.1, -0.1, -.5])
    properties = DepthCameraProperties(width=640,
                                       height=480,
                                       fov_y=np.pi / 4.0,
                                       renderer_name=renderer,
                                       z_near=0.1,
                                       z_far=10.0)
    camera = builder.AddSystem(
        RgbdSensor(parent_id=scene_graph.world_frame_id(),
                   X_PB=pose,
                   properties=properties,
                   show_window=False))
    camera.set_name("rgbd_sensor")
    builder.Connect(scene_graph.get_query_output_port(),
                    camera.query_object_input_port())

    # Export the camera outputs
    builder.ExportOutput(camera.color_image_output_port(), "color_image")
    builder.ExportOutput(camera.depth_image_32F_output_port(), "depth_image")

    # Add a system to convert the camera output into a point cloud
    to_point_cloud = builder.AddSystem(
        DepthImageToPointCloud(camera_info=camera.depth_camera_info(),
                               fields=BaseField.kXYZs | BaseField.kRGBs))
    builder.Connect(camera.depth_image_32F_output_port(),
                    to_point_cloud.depth_image_input_port())
    builder.Connect(camera.color_image_output_port(),
                    to_point_cloud.color_image_input_port())

    # Export the point cloud output.
    builder.ExportOutput(to_point_cloud.point_cloud_output_port(),
                         "point_cloud")

    diagram = builder.Build()
    diagram.set_name("depth_camera_demo_system")
    return diagram
Example #8
0
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its contributors
#   may be used to endorse or promote products derived from this software
#   without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Provides an example (and test) of finding resources with Python from a Bazel
project.
"""

from pydrake.common import FindResourceOrThrow, set_log_level

# If you have trouble finding resources, you can enable trace logging to see
# how `FindResource*` is searching.
set_log_level("trace")

FindResourceOrThrow("drake/examples/pendulum/Pendulum.urdf")
Example #9
0
 def test_logging(self):
     self.assertTrue(mut._module_py._HAVE_SPDLOG)
     with catch_drake_warnings(expected_count=1) as w:
         self.assertIsInstance(
             mut.set_log_level(level="unchanged"), str)
Example #10
0
def main():
    spdlog_level = sys.argv[1]
    set_log_level(spdlog_level)
    do_log_test()