diff --git a/MODULE.bazel b/MODULE.bazel
index b2d801bd9c..49787170d0 100644
--- a/MODULE.bazel
+++ b/MODULE.bazel
@@ -93,7 +93,7 @@ bazel_dep(name = "c3")
git_override(
module_name = "c3",
remote = "https://github.com/DAIRLab/c3.git",
- commit = "7e99d566b57deff9cfc02b016ae06930c6634da5"
+ commit = "194a8c9e3e361e24aa0568e5979f0a25b5364bbd"
)
diff --git a/bindings/pydairlib/analysis/tray_balance_study/BUILD.bazel b/bindings/pydairlib/analysis/tray_balance_study/BUILD.bazel
deleted file mode 100644
index 10aa865f41..0000000000
--- a/bindings/pydairlib/analysis/tray_balance_study/BUILD.bazel
+++ /dev/null
@@ -1,42 +0,0 @@
-# -*- python -*-
-load("@drake//tools/install:install.bzl", "install")
-
-package(default_visibility = ["//visibility:public"])
-
-load(
- "@drake//tools/skylark:pybind.bzl",
- "drake_pybind_library",
- "get_drake_py_installs",
- "get_pybind_package_info",
- "pybind_py_library",
-)
-
-py_binary(
- name = "run_tray_parameter_study",
- srcs = ["run_tray_parameter_study.py"],
- data = [
- "@drake_models//:franka_description",
- "@lcm//:lcm-python",
- ],
- deps = [
- "//bindings/pydairlib/common",
- "//lcmtypes:lcmtypes_robot_py",
- ],
-)
-
-py_binary(
- name = "parameter_study_analysis",
- srcs = ["parameter_study_analysis.py"],
- data = [
- ":parameter_study_config.yaml",
- "//examples/franka:parameters",
- "@drake_models//:franka_description",
- "@lcm//:lcm-python",
- ],
- deps = [
- "//bindings/pydairlib/analysis:mbp_plotting_utils",
- "//bindings/pydairlib/common",
- "//bindings/pydairlib/lcm:process_lcm_log",
- "//lcmtypes:lcmtypes_robot_py",
- ],
-)
diff --git a/bindings/pydairlib/analysis/tray_balance_study/generate_dataset.py b/bindings/pydairlib/analysis/tray_balance_study/generate_dataset.py
deleted file mode 100644
index 0ea6b5dd01..0000000000
--- a/bindings/pydairlib/analysis/tray_balance_study/generate_dataset.py
+++ /dev/null
@@ -1,41 +0,0 @@
-import numpy as np
-import os
-import datetime
-def gather_theta_batched_branin_data(n_datapoints,
- batch_size,
- gains_to_randomize,
- thetas_to_randomize,
- high_level_folder,
- params_t=BraninFnParamsTrain):
-
- assert n_datapoints == int(n_datapoints / batch_size) * batch_size
-
- num_batches = int(n_datapoints / (batch_size))
- # Each batch is associated with a single set of system intrinsic parameters
- intrinsics = np.zeros((num_batches, len(thetas_to_randomize)))
- # for each parameter vector, generate $batch_size random gains to evaluate
- gains_to_test = np.zeros((num_batches, batch_size, len(gains_to_randomize)))
-
- subfolder = "branin_data_" + datetime.now().strftime("%b_%d_%Y_%H%M") + "/"
- if not os.path.exists(os.path.join(high_level_folder, subfolder)):
- os.makedirs(os.path.join(high_level_folder, subfolder), exist_ok=True)
-
- with h5py.File(os.path.join(high_level_folder, subfolder, "dataset.hdf5"), 'w') as f:
- # intrinsic vectors don't actually get used anywhere, but good to save for bookkeeping
- f.create_dataset("intrinsics", shape=intrinsics.shape)
- f.create_dataset("gains", shape=gains_to_test.shape)
- # this system only has 1 performance metric, but in principle this could be any number
- f.create_dataset("metrics", shape=(num_batches, batch_size, 1))
- for batch in range(num_batches):
- # Generate a random intrinsic vector for this batch
- batch_intrinsic_obj = params_t.generate_random(thetas_to_randomize)
- f["intrinsics"][batch,...] = batch_intrinsic_obj.get_list()
- robot = Branin(batch_intrinsic_obj, gains_to_randomize)
- for point in range(batch_size):
- # generate a random gain vector
- gain = BraninInputs.generate_random(gains_to_randomize).get_list()[gains_to_randomize]
- # run the simulation and obtain the performance metrics
- metric = robot.evaluate_x(gain)
- f["metrics"][batch,point] = metric
- f["gains"][batch,point] = gain
- print(f"finished batch {batch}")
\ No newline at end of file
diff --git a/bindings/pydairlib/analysis/tray_balance_study/parameter_study_analysis.py b/bindings/pydairlib/analysis/tray_balance_study/parameter_study_analysis.py
deleted file mode 100644
index 0e5aab7237..0000000000
--- a/bindings/pydairlib/analysis/tray_balance_study/parameter_study_analysis.py
+++ /dev/null
@@ -1,141 +0,0 @@
-import subprocess
-import time
-from tqdm import *
-import lcm
-from bindings.pydairlib.common import plot_styler, plotting_utils
-import pydairlib.analysis.mbp_plotting_utils as mbp_plots
-from bindings.pydairlib.lcm.process_lcm_log import get_log_data
-import matplotlib.pyplot as plt
-import numpy as np
-import yaml
-import dairlib
-
-
-def process_c3_channel(data):
- t = []
- x = []
- for msg in data:
- t.append(msg.utime / 1e6)
- x.append(msg.state)
- t = np.array(t)
- x = np.array(x)
-
- return {'t': t,
- 'x': x}
-
-def load_c3_channels(data, c3_target_state_channel, c3_actual_state_channel, c3_debug_output_channel):
- c3_target = process_c3_channel(data[c3_target_state_channel])
- c3_actual = process_c3_channel(data[c3_actual_state_channel])
- c3_output = mbp_plots.process_c3_debug(data[c3_debug_output_channel])
- return c3_target, c3_actual, c3_output
-
-def load_lcm_logs():
- config_file = 'parameter_study_config.yaml'
- parameters_directory = 'examples/franka/parameters/'
- lcm_channels_sim = 'lcm_channels_simulation.yaml'
-
- with open(parameters_directory + lcm_channels_sim) as f:
- filedata = f.read()
- lcm_channels = yaml.load(filedata)
-
- with open('bindings/pydairlib/analysis/tray_balance_study/' + config_file) as f:
- filedata = f.read()
- param_study = yaml.load(filedata)
-
- start_time = 0
- duration = -1
-
- c3_channels = {lcm_channels['c3_target_state_channel']: dairlib.lcmt_c3_state,
- lcm_channels['c3_actual_state_channel']: dairlib.lcmt_c3_state,
- lcm_channels['c3_debug_output_channel']: dairlib.lcmt_c3_output}
- callback = load_c3_channels
- mass_range = np.arange(0.5, 2.0, 0.05)
- # mu_range = np.arange(0.3, 0.8, 0.01)
- effective_mu_range = np.arange(0.1, 0.71, 0.1)
-
- print(effective_mu_range.shape[0])
- all_successes = np.zeros((effective_mu_range.shape[0], 3))
- for i in range(effective_mu_range.shape[0]):
- print('%02d', effective_mu_range[i])
- # print(mass_range[i])
- # ps = plot_styler.PlotStyler(nrows=2)
-
- successes = np.zeros(3)
-
- for j in range(5):
- # ps = plot_styler.PlotStyler()
- log_filename = param_study['results_folder'] + param_study['parameter'][2] + '/simlog-' + '%02d_%1d' % (i, j)
- log = lcm.EventLog(log_filename, "r")
- c3_target, c3_actual, c3_output = \
- get_log_data(log, c3_channels, start_time, duration, callback, False,
- lcm_channels['c3_target_state_channel'], lcm_channels['c3_actual_state_channel'],
- lcm_channels['c3_debug_output_channel'])
- length = min(c3_target['t'].shape[0], c3_actual['t'].shape[0])
- # ps.plot(c3_actual['t'], c3_actual['x'][:, 8:9], subplot_index=0)
- # ps.plot(c3_actual['t'], c3_actual['x'][:, 9:10], subplot_index=0)
- # ps.plot(c3_actual['t'], c3_actual['x'][:, 1:2], subplot_index=0)
- # ps.plot(c3_actual['t'], c3_actual['x'][:, 2:3], subplot_index=0)
- first_target = np.array([0.45, 0, 0.485])
- second_target = np.array([0.45, 0, 0.6])
- third_target = np.array([0.7, 0.0, 0.485])
- reached_first_target = np.any(np.all(np.isclose(c3_target['x'][:, 7:10], second_target, atol=1e-3), axis=1))
- reached_second_target = np.any(np.all(np.isclose(c3_target['x'][:, 7:10], third_target, atol=1e-3), axis=1))
- reached_third_target = reached_second_target and np.linalg.norm(c3_target['x'][:length, 7:10] - c3_actual['x'][:length, 7:10], axis=1)[-1] < 0.1
- task_success = np.array([reached_first_target, reached_second_target, reached_third_target])
- # print('reached_targets: ', task_success)
- successes += task_success
- # print('reached_second_target: ', reached_second_target)
- # print('reached_third_target: ', reached_third_target)
- t_c3_slice = slice(c3_output['t'].size)
- # mbp_plots.plot_c3_inputs(c3_output, t_c3_slice, 1, ps)
- # plt.show()
- print(successes)
- all_successes[i] = successes
- # np.save('target_successes_23', all_successes )
- np.save('target_successes_03_26', all_successes )
-
-def plot_logs():
- all_successes = np.load('target_successes_03_25.npy')
- bar_width = 0.025
- bar_positions = np.arange(all_successes.shape[0])
- n = all_successes.shape[0]
- # mu_range = np.arange(0.3, 0.74, 0.05)
- effective_mu_range = np.arange(0.1, 0.71, 0.1)
-
- plt.rc('legend', fontsize=36)
- plt.rc('axes', labelsize=36, titlesize=36)
- plt.rc('xtick', labelsize=36)
- plt.rc('ytick', labelsize=36)
- # Plotting bars for each task
- for i in range(n):
- # for j in range(3):
- # plt.bar(bar_positions[i], all_successes[i, 2] / 30, width=bar_width)
- # plt.bar(effective_mu_range[i], all_successes[i, 2] / all_successes[i, 0], width=bar_width, color='grey')
- plt.bar(effective_mu_range[i], all_successes[i, 0] / 5, width=bar_width, color='grey')
- plt.ylabel('Target Success Rate')
- plt.xlabel('Tray/End Effector Friction Coefficient')
-
- # plt.savefig('/home/yangwill/Pictures/plot_styler/' + 'target_1_success')
- # plt.legend()
- # for i in range(3):
- # plt.bar(bar_positions + i * (n + 1), all_successes[:, i], label=f'Task {i + 1}')
-
- plt.show()
-
-def main():
- load_lcm_logs()
- # plot_logs()
-
-
-
-
-
-
-
-
-
-
-
-
-if __name__ == '__main__':
- main()
\ No newline at end of file
diff --git a/bindings/pydairlib/analysis/tray_balance_study/parameter_study_config.yaml b/bindings/pydairlib/analysis/tray_balance_study/parameter_study_config.yaml
deleted file mode 100644
index 32819883bb..0000000000
--- a/bindings/pydairlib/analysis/tray_balance_study/parameter_study_config.yaml
+++ /dev/null
@@ -1,21 +0,0 @@
-trajectory_path: /home/yangwill/workspace/dairlib/examples/Cassie/saved_trajectories/
-gains_path: examples/franka/parameters/
-model_path: examples/franka/urdf/
-results_folder: /media/yangwill/backups/home/yangwill/Documents/research/projects/franka/logs/2024/03_26_24/parameter_study/
-#results_folder: /media/yangwill/backups/home/yangwill/Documents/research/projects/franka/logs/2024/01_31_24/parameter_study/
-processed_results_folder: /media/yangwill/backups/home/yangwill/Documents/research/projects/franka/logs/2024/03_26_24/parameter_study/data/
-sim_cmd: bazel-bin/examples/franka/franka_sim
-osc_cmd: bazel-bin/examples/franka/franka_osc_controller
-c3_cmd: bazel-bin/examples/franka/franka_c3_controller
-fix_inertia_cmd: 'python3 -m pydrake.multibody.fix_inertia --in_place examples/franka/urdf/tray_parameter_sweep.sdf'
-
-nominal_c3_gain_filename: franka_c3_options_rotated_supports.yaml
-#nominal_model_filename: tray.sdf
-nominal_model_filename: plate_end_effector.urdf
-
-modified_c3_gain_filename: franka_c3_options_parameter_sweep.yaml
-#modified_model_filename: tray_parameter_sweep.sdf
-modified_model_filename: plate_end_effector_parameter_sweep.urdf
-
-parameter: ['mu_c3', 'mass_real', 'mu_real']
-
diff --git a/bindings/pydairlib/analysis/tray_balance_study/run_tray_parameter_study.py b/bindings/pydairlib/analysis/tray_balance_study/run_tray_parameter_study.py
deleted file mode 100644
index 141ba33efe..0000000000
--- a/bindings/pydairlib/analysis/tray_balance_study/run_tray_parameter_study.py
+++ /dev/null
@@ -1,111 +0,0 @@
-import subprocess
-import time
-from tqdm import *
-import lcm
-import dairlib.lcmt_radio_out
-
-import numpy as np
-import yaml
-
-
-def main():
- config_file = 'parameter_study_config.yaml'
- sim_time = 20.0
- cooldown_time = 10.0
- start_time = 0
- realtime_rate = 1.0
- num_trials = 10
- c3_start_up_time = 1.0
- sim_run_time = sim_time / realtime_rate
- controller_startup_time = 0.1
-
- with open('bindings/pydairlib/analysis/tray_balance_study/' + config_file) as f:
- filedata = f.read()
- config = yaml.load(filedata)
-
- # Add an extra second to the runtime of the simulator process to account for start up and stopping time
-
- lcm_logger_cmd = ''
- publisher = lcm.LCM()
-
- # parameter = 'mu_c3'
- # parameter = 'mass_real'
- parameter = config['parameter'][2]
-
- nominal_mu_value = 'mu: [0.6, 0.6, 0.6, 0.1, 0.1, 0.1, 0.1]'
- # nominal_real_mu_value = '0.4'
- nominal_real_mu_value = ''
- nominal_tray_mass = '1'
-
- # mu_range = np.arange(0.3, 0.8, 0.05)
- # mass_range = np.arange(0.5, 2.0, 0.05)
- effective_mu_range = np.arange(0.1, 0.71, 0.1)
- tray_mu = 0.4
-
- initial_radio_msg = dairlib.lcmt_radio_out()
- start_c3_radio_msg = dairlib.lcmt_radio_out()
- initial_radio_msg.channel[13] = 1
- initial_radio_msg.channel[11] = 0
- initial_radio_msg.channel[14] = 1
- start_c3_radio_msg.channel[13] = 1
- start_c3_radio_msg.channel[11] = 0
- start_c3_radio_msg.channel[14] = 0
-
- # for i in trange(mu_range.shape[0]):
- for i in trange(effective_mu_range.shape[0]):
- plate_mu = 0.5 * effective_mu_range[i] / (1 - effective_mu_range[i] / (2 * tray_mu))
- # modified_mu_value = 'mu: [%.2f, %.2f, %.2f, 0.1, 0.1, 0.1, 0.1]' % (mu_range[i], mu_range[i], mu_range[i])
- # modified_mass_value = ' %.1f ' % (mass_range[i])
- # modified_real_mu_value = '%.2f' % (mu_range[i])
- modified_real_mu_value = '' % (plate_mu)
-
- # f = open(gains_path + gain_filename, 'r')
- f = open(config['model_path'] + config['nominal_model_filename'], 'r')
-
- filedata = f.read()
- f.close()
- # newdata = filedata.replace(nominal_mu_value, modified_mu_value)
- newdata = filedata.replace(nominal_real_mu_value, modified_real_mu_value)
- # newdata = filedata.replace(nominal_tray_mass, modified_mass_value)
-
- # f = open(config['gains_path'] + config['modified_c3_gain_filename.yaml'], 'w')
- f = open(config['model_path'] + config['modified_model_filename'], 'w')
- f.write(newdata)
- f.close()
- if parameter == 'mass_real':
- fix_inertia_process = subprocess.Popen(config['fix_inertia_cmd'].split(' '))
- time.sleep(1.0)
-
- for j in trange(num_trials):
- log_path = config['results_folder'] + parameter + '/simlog-' + '%02d_%1d' % (i, j)
- lcm_logger_cmd = ['lcm-logger',
- '-f',
- '%s' % log_path,
- ]
-
- osc_process = subprocess.Popen(config['osc_cmd'], stdout=subprocess.DEVNULL,
- stderr=subprocess.STDOUT)
- c3_process = subprocess.Popen(config['c3_cmd'], stdout=subprocess.DEVNULL,
- stderr=subprocess.STDOUT)
- sim_process = subprocess.Popen(config['sim_cmd'], stdout=subprocess.DEVNULL,
- stderr=subprocess.STDOUT)
- time.sleep(controller_startup_time)
- publisher.publish("RADIO", initial_radio_msg.encode())
- logger_process = subprocess.Popen(lcm_logger_cmd, stdout=subprocess.DEVNULL,
- stderr=subprocess.STDOUT)
- time.sleep(c3_start_up_time)
- publisher.publish("RADIO", start_c3_radio_msg.encode())
- time.sleep(sim_run_time)
- osc_process.kill()
- c3_process.kill()
- sim_process.kill()
- logger_process.kill()
- time.sleep(cooldown_time)
-
-
-if __name__ == "__main__":
- main()
- # construct_success_plot()
- # convert_logs_to_costs()
- # plot_success()
- # plot_costs()
diff --git a/bindings/pydairlib/franka/BUILD.bazel b/bindings/pydairlib/franka/BUILD.bazel
deleted file mode 100644
index 503916512b..0000000000
--- a/bindings/pydairlib/franka/BUILD.bazel
+++ /dev/null
@@ -1,94 +0,0 @@
-# -*- python -*-
-load("@drake//tools/install:install.bzl", "install")
-load(
- "@drake//tools/skylark:pybind.bzl",
- "drake_pybind_library",
- "get_drake_py_installs",
- "get_pybind_package_info",
- "pybind_py_library",
-)
-
-package(default_visibility = ["//visibility:public"])
-
-pybind_py_library(
- name = "controllers_py",
- cc_deps = [
- "//examples/franka/diagrams:franka_c3_controller_diagram",
- "//examples/franka/diagrams:franka_osc_controller_diagram",
- "@drake//:drake_shared_library",
- ],
- cc_so_name = "controllers",
- cc_srcs = ["controllers_py.cc"],
- py_deps = [
- "@drake//bindings/pydrake",
- ":module_py",
- ],
- py_imports = ["."],
-)
-
-py_binary(
- name = "franka_env",
- srcs = ["franka_env.py"],
- data = [
- "//examples/franka:urdfs",
- "@drake_models//:franka_description",
- ],
- deps = [
- "//bindings/pydairlib/franka",
- "//bindings/pydairlib/lcm:lcm_trajectory_py",
- "//bindings/pydairlib/systems:framework_py",
- "//bindings/pydairlib/systems:primitives_py",
- "//bindings/pydairlib/systems:robot_lcm_systems_py",
- "//lcmtypes:lcmtypes_robot_py",
- "@drake//bindings/pydrake",
- ],
-)
-
-py_binary(
- name = "generate_dataset",
- srcs = ["generate_dataset.py"],
- data = [
- ":parameters/dataset_params.yaml",
- ],
- deps = [
- ":franka_env",
- "@drake//bindings/pydrake",
- ],
-)
-
-py_binary(
- name = "planar_box_example",
- srcs = ["planar_box_example.py"],
- data = [
- ],
- deps = [
- "//bindings/pydairlib/solvers:c3_py",
- "@drake//bindings/pydrake",
- ],
-)
-
-# This determines how `PYTHONPATH` is configured, and how to install the
-# bindings.
-PACKAGE_INFO = get_pybind_package_info("//bindings")
-
-py_library(
- name = "module_py",
- srcs = [
- "__init__.py",
- ],
- imports = PACKAGE_INFO.py_imports,
- deps = [
- "//bindings/pydairlib:module_py",
- ],
-)
-
-PY_LIBRARIES = [
- ":controllers_py",
-]
-
-# Package roll-up (for Bazel dependencies).
-py_library(
- name = "franka",
- imports = PACKAGE_INFO.py_imports,
- deps = PY_LIBRARIES,
-)
diff --git a/bindings/pydairlib/franka/__init__.py b/bindings/pydairlib/franka/__init__.py
deleted file mode 100644
index fa9c628350..0000000000
--- a/bindings/pydairlib/franka/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# Importing everything in this directory to this package
diff --git a/bindings/pydairlib/franka/controllers_py.cc b/bindings/pydairlib/franka/controllers_py.cc
deleted file mode 100644
index 074a2fd55f..0000000000
--- a/bindings/pydairlib/franka/controllers_py.cc
+++ /dev/null
@@ -1,113 +0,0 @@
-#include
-#include
-#include
-
-#include "examples/franka/diagrams/franka_c3_controller_diagram.h"
-#include "examples/franka/diagrams/franka_osc_controller_diagram.h"
-#include "solvers/c3_options.h"
-
-namespace py = pybind11;
-
-namespace dairlib {
-namespace pydairlib {
-
-using examples::controllers::FrankaC3ControllerDiagram;
-using examples::controllers::FrankaOSCControllerDiagram;
-
-PYBIND11_MODULE(controllers, m) {
- m.doc() = "Binding controller factories for plate balancing demo";
-
- using py_rvp = py::return_value_policy;
- py::module::import("pydrake.math");
-
- py::class_>(
- m, "FrankaOSCControllerDiagram")
- .def(py::init(),
- py::arg("controller_settings"), py::arg("lcm_channels"),
- py::arg("lcm"))
- .def("get_input_port_robot_state",
- &FrankaOSCControllerDiagram::get_input_port_robot_state,
- py_rvp::reference_internal)
- .def("get_input_port_end_effector_position",
- &FrankaOSCControllerDiagram::get_input_port_end_effector_position,
- py_rvp::reference_internal)
- .def("get_input_port_end_effector_orientation",
- &FrankaOSCControllerDiagram::get_input_port_end_effector_orientation,
- py_rvp::reference_internal)
- .def("get_input_port_end_effector_force",
- &FrankaOSCControllerDiagram::get_input_port_end_effector_force,
- py_rvp::reference_internal)
- .def("get_input_port_radio",
- &FrankaOSCControllerDiagram::get_input_port_radio,
- py_rvp::reference_internal)
- .def("get_output_port_robot_input",
- &FrankaOSCControllerDiagram::get_output_port_robot_input,
- py_rvp::reference_internal);
-
- py::class_>(
- m, "FrankaC3ControllerDiagram")
- .def(py::init(),
- py::arg("controller_settings"), py::arg("c3_options"),
- py::arg("lcm_channels"), py::arg("lcm"))
- .def("get_input_port_robot_state",
- &FrankaC3ControllerDiagram::get_input_port_robot_state,
- py_rvp::reference_internal)
- .def("get_input_port_object_state",
- &FrankaC3ControllerDiagram::get_input_port_object_state,
- py_rvp::reference_internal)
- .def("get_input_port_radio",
- &FrankaC3ControllerDiagram::get_input_port_radio,
- py_rvp::reference_internal)
- .def("get_output_port_mpc_plan",
- &FrankaC3ControllerDiagram::get_output_port_mpc_plan,
- py_rvp::reference_internal);
-
- py::class_(m, "C3Options")
- .def(py::init<>())
- .def_readwrite("admm_iter", &C3Options::admm_iter)
- .def_readwrite("rho", &C3Options::rho)
- .def_readwrite("rho_scale", &C3Options::rho_scale)
- .def_readwrite("num_threads", &C3Options::num_threads)
- .def_readwrite("delta_option", &C3Options::delta_option)
- .def_readwrite("projection_type", &C3Options::projection_type)
- .def_readwrite("contact_model", &C3Options::contact_model)
- .def_readwrite("warm_start", &C3Options::warm_start)
- .def_readwrite("use_predicted_x0", &C3Options::use_predicted_x0)
- .def_readwrite("solve_time_filter_alpha", &C3Options::solve_time_filter_alpha)
- .def_readwrite("publish_frequency", &C3Options::publish_frequency)
- .def_readwrite("world_x_limits", &C3Options::workspace_limits)
- .def_readwrite("u_horizontal_limits", &C3Options::u_horizontal_limits)
- .def_readwrite("u_vertical_limits", &C3Options::u_vertical_limits)
- .def_readwrite("workspace_margins", &C3Options::workspace_margins)
- .def_readwrite("N", &C3Options::N)
- .def_readwrite("gamma", &C3Options::gamma)
- .def_readwrite("q_vector", &C3Options::q_vector)
- .def_readwrite("r_vector", &C3Options::r_vector)
- .def_readwrite("g_vector", &C3Options::g_vector)
- .def_readwrite("g_x", &C3Options::g_x)
- .def_readwrite("g_gamma", &C3Options::g_gamma)
- .def_readwrite("g_lambda_n", &C3Options::g_lambda_n)
- .def_readwrite("g_lambda_t", &C3Options::g_lambda_t)
- .def_readwrite("g_lambda", &C3Options::g_lambda)
- .def_readwrite("g_u", &C3Options::g_u)
- .def_readwrite("u_vector", &C3Options::u_vector)
- .def_readwrite("u_x", &C3Options::u_x)
- .def_readwrite("u_gamma", &C3Options::u_gamma)
- .def_readwrite("u_lambda_n", &C3Options::u_lambda_n)
- .def_readwrite("u_lambda_t", &C3Options::u_lambda_t)
- .def_readwrite("u_lambda", &C3Options::u_lambda)
- .def_readwrite("u_u", &C3Options::u_u)
- .def_readwrite("mu", &C3Options::mu)
- .def_readwrite("dt", &C3Options::dt)
- .def_readwrite("solve_dt", &C3Options::solve_dt)
- .def_readwrite("num_friction_directions", &C3Options::num_friction_directions)
- .def_readwrite("num_contacts", &C3Options::num_contacts)
- .def_readwrite("Q", &C3Options::Q)
- .def_readwrite("R", &C3Options::R)
- .def_readwrite("G", &C3Options::G)
- .def_readwrite("U", &C3Options::U);
-}
-} // namespace pydairlib
-} // namespace dairlib
\ No newline at end of file
diff --git a/bindings/pydairlib/franka/franka_env.py b/bindings/pydairlib/franka/franka_env.py
deleted file mode 100644
index 4ba758f5e1..0000000000
--- a/bindings/pydairlib/franka/franka_env.py
+++ /dev/null
@@ -1,144 +0,0 @@
-from pydrake.all import *
-from pydairlib.franka.controllers import FrankaOSCControllerDiagram, FrankaC3ControllerDiagram, C3Options
-
-from pydrake.common.yaml import yaml_load
-from pydairlib.systems.primitives import *
-from pydairlib.systems.robot_lcm_systems import *
-from pydairlib.lcm.lcm_trajectory import *
-import pydrake.systems.lcm as mut
-from franka_env_helper_functions import *
-import dairlib
-
-
-def run_sim(intrinsics, gains):
- osc_params_file = "examples/franka/parameters/franka_osc_controller_params.yaml"
- c3_params_file = "examples/franka/parameters/franka_c3_controller_params.yaml"
- lcm_params_file = "examples/franka/parameters/lcm_channels_simulation.yaml"
- sim_params_file = "examples/franka/parameters/franka_sim_params.yaml"
-
- sim_params = yaml_load(filename=sim_params_file)
- lcm_params = yaml_load(filename=lcm_params_file)
- c3_options = load_c3_options(c3_params_file)
-
- lcm = DrakeLcm("udpm://239.255.76.67:7667?ttl=0")
- builder = DiagramBuilder()
- plant, scene_graph = AddMultibodyPlantSceneGraph(builder, sim_params['dt'])
-
- parser = Parser(plant)
- parser.SetAutoRenaming(True)
-
- franka_index, = parser.AddModels(FindResourceOrThrow(sim_params['franka_model']))
- end_effector_index, = parser.AddModels(sim_params['end_effector_model'])
- tray_index, = parser.AddModels(sim_params['tray_model'])
-
- T_X_W = RigidTransform(RotationMatrix(), np.zeros(3))
- T_EE_W = RigidTransform(RotationMatrix(), sim_params['tool_attachment_frame'])
-
- plant.WeldFrames(plant.world_frame(), plant.GetFrameByName('panda_link0'), T_X_W)
- frame = plant.GetFrameByName(name='plate', model_instance=end_effector_index)
- plant.WeldFrames(plant.GetFrameByName('panda_link7'),
- frame,
- T_EE_W)
- left_support_index, = parser.AddModels(sim_params['left_support_model'])
- right_support_index, = parser.AddModels(sim_params['right_support_model'])
- T_S1_W = RigidTransform(RollPitchYaw(sim_params['left_support_orientation']),
- sim_params['left_support_position'])
- T_S2_W = RigidTransform(RollPitchYaw(sim_params['right_support_orientation']),
- sim_params['right_support_position'])
- plant.WeldFrames(plant.world_frame(),
- plant.GetFrameByName("support", left_support_index),
- T_S1_W)
- plant.WeldFrames(plant.world_frame(),
- plant.GetFrameByName("support", right_support_index),
- T_S2_W)
- plant.Finalize()
-
- c3_options.publish_frequency = (gains[0] * 5) + 25
- c3_options.Q = (1 + 0.5 * gains[1]) * c3_options.Q
- c3_options.R = (1 + 0.5 * gains[2]) * c3_options.R
- c3_options.G = (1 + 0.5 * gains[3]) * c3_options.G
- c3_options.U = (1 + 0.5 * gains[4]) * c3_options.U
-
- osc_controller = builder.AddSystem(FrankaOSCControllerDiagram(
- "examples/franka/parameters/franka_osc_controller_params.yaml",
- "examples/franka/parameters/lcm_channels_simulation.yaml", lcm))
-
- c3_controller = builder.AddSystem(FrankaC3ControllerDiagram(
- "examples/franka/parameters/franka_c3_controller_params.yaml", c3_options,
- "examples/franka/parameters/lcm_channels_simulation.yaml", lcm))
-
- passthrough = builder.AddSystem(SubvectorPassThrough(8, 0, 7))
- tray_state_sender = builder.AddSystem(ObjectStateSender(plant, tray_index))
- franka_state_sender = builder.AddSystem(RobotOutputSender(plant, franka_index, False, False))
-
- # radio_sub = builder.AddSystem(LcmSubscriberSystem.Make(channel=lcm_params['radio_channel'], lcm_type=dairlib.lcmt_radio_out, lcm=lcm, use_cpp_serializer=True))
- sim_state_logger = builder.AddSystem(
- VectorLogSink(plant.num_positions() + plant.num_velocities(), 2 * sim_params['dt']))
-
- builder.Connect(c3_controller.get_output_port_mpc_plan(),
- osc_controller.get_input_port_end_effector_position())
- builder.Connect(c3_controller.get_output_port_mpc_plan(),
- osc_controller.get_input_port_end_effector_orientation())
- builder.Connect(c3_controller.get_output_port_mpc_plan(),
- osc_controller.get_input_port_end_effector_force())
-
- builder.Connect(osc_controller.get_output_port_robot_input(),
- passthrough.get_input_port())
-
- builder.Connect(franka_state_sender.get_output_port(),
- osc_controller.get_input_port_robot_state())
- builder.Connect(franka_state_sender.get_output_port(),
- c3_controller.get_input_port_robot_state())
- builder.Connect(tray_state_sender.get_output_port(),
- c3_controller.get_input_ports_object_state()[0])
-
- builder.Connect(plant.get_state_output_port(franka_index),
- franka_state_sender.get_input_port_state())
- builder.Connect(plant.get_state_output_port(tray_index),
- tray_state_sender.get_input_port_state())
- builder.Connect(plant.get_state_output_port(),
- sim_state_logger.get_input_port())
- builder.Connect(passthrough.get_output_port(),
- plant.get_actuation_input_port())
-
- if sim_params['visualize_drake_sim']:
- AddDefaultVisualization(builder)
-
- diagram = builder.Build()
- simulator = Simulator(diagram)
-
- simulator.set_publish_every_time_step(True)
- simulator.set_publish_at_initialization(True)
- simulator.set_target_realtime_rate(sim_params['realtime_rate'])
-
- plant_context = diagram.GetMutableSubsystemContext(plant, simulator.get_mutable_context())
- osc_controller_context = diagram.GetMutableSubsystemContext(osc_controller, simulator.get_mutable_context())
- c3_controller_context = diagram.GetMutableSubsystemContext(c3_controller, simulator.get_mutable_context())
- osc_controller.get_input_port_radio().FixValue(osc_controller_context, np.zeros(18))
- c3_controller.get_input_port_radio().FixValue(c3_controller_context, np.zeros(18))
- logger_context = diagram.GetSubsystemContext(sim_state_logger, simulator.get_context())
-
- q = np.hstack((sim_params['q_init_franka'], sim_params['q_init_tray'][sim_params['scene_index']]))
- v = np.zeros(plant.num_velocities())
- plant.SetPositions(plant_context, q)
-
- simulator.Initialize()
- simulator.AdvanceTo(5.0)
-
- sim_data = sim_state_logger.GetLog(logger_context)
- sim_states = sim_data.data()
- sim_times = sim_data.sample_times()
-
- # reward = compute_reward_sparse(sim_times, sim_states)
- reward = compute_reward_mpc(sim_times, sim_states)
- # print(reward)
- # print(sim_states.data().shape)
- # print(sim_states.sample_times().shape)
- return reward, sim_states
-
-
-if __name__ == '__main__':
- parameters = 2 * np.random.random(5) - 1 # center around 0. [-1, 1]
- # reward, sim_states = run_sim(np.zeros(5), np.ones(5))
- reward, sim_states = run_sim(np.zeros(5), parameters)
- print(reward)
diff --git a/bindings/pydairlib/franka/franka_env_helper_functions.py b/bindings/pydairlib/franka/franka_env_helper_functions.py
deleted file mode 100644
index ce01e8fff3..0000000000
--- a/bindings/pydairlib/franka/franka_env_helper_functions.py
+++ /dev/null
@@ -1,85 +0,0 @@
-from pydairlib.franka.controllers import C3Options
-import numpy as np
-from pydrake.common.yaml import yaml_load
-from pydrake.all import *
-
-def compute_reward_sparse(times, sim_states):
- first_target = np.array([0.45, 0, 0.485])
- second_target = np.array([0.45, 0, 0.6])
- third_target = np.array([0.7, 0.0, 0.485])
- length = min(times.shape[0], times.shape[0])
- reached_first_target = np.any(np.all(np.isclose(sim_states[:, 7:10], second_target, atol=1e-3), axis=1))
- reached_second_target = np.any(np.all(np.isclose(sim_states[:, 7:10], third_target, atol=1e-3), axis=1))
- reached_third_target = reached_second_target and np.linalg.norm(sim_states[:length, 7:10] - sim_states[:length, 7:10], axis=1)[-1] < 0.1
- # return reached_first_target + reached_second_target + reached_third_target
- return reached_first_target + reached_second_target + reached_third_target
-
-def compute_reward_mpc(times, sim_states):
- first_target = np.array([0.45, 0, 0.485])
- second_target = np.array([0.45, 0, 0.6])
- third_target = np.array([0.7, 0.0, 0.485])
- neutral_orientation = Quaternion()
- cumulative_cost = 0
- for i in range(times.shape[0]):
- tray_pos = sim_states[11:14, i]
- tray_orientation = sim_states[7:11, i]
- tray_quat = Quaternion(tray_orientation / np.linalg.norm(tray_orientation))
- cumulative_cost += np.linalg.norm(tray_pos - first_target)
- # tray_quat /= np.linalg.norm(tray_quat.wxyz())
- angle_difference = Quaternion.multiply(neutral_orientation.conjugate(), tray_quat)
- cumulative_cost += RotationMatrix(angle_difference).ToAngleAxis().angle()
- cumulative_cost /= times.shape[0]
- return cumulative_cost
-
-def load_c3_options(c3_params_file):
- c3_params = yaml_load(filename=c3_params_file)
- c3_options_file = c3_params['c3_options_file'][c3_params['scene_index']]
- c3_options_dict = yaml_load(filename=c3_options_file)
- c3_options = C3Options()
- c3_options.admm_iter = c3_options_dict['admm_iter']
- c3_options.rho = c3_options_dict['rho']
- c3_options.rho_scale = c3_options_dict['rho_scale']
- c3_options.num_threads = c3_options_dict['num_threads']
- c3_options.delta_option = c3_options_dict['delta_option']
- c3_options.projection_type = c3_options_dict['projection_type']
- c3_options.contact_model = c3_options_dict['contact_model']
- c3_options.warm_start = c3_options_dict['warm_start']
- c3_options.use_predicted_x0 = c3_options_dict['use_predicted_x0']
- c3_options.solve_time_filter_alpha = c3_options_dict['solve_time_filter_alpha']
- c3_options.publish_frequency = c3_options_dict['publish_frequency']
- c3_options.world_x_limits = c3_options_dict['world_x_limits']
- c3_options.world_y_limits = c3_options_dict['world_y_limits']
- c3_options.world_z_limits = c3_options_dict['world_z_limits']
- c3_options.u_horizontal_limits = c3_options_dict['u_horizontal_limits']
- c3_options.u_vertical_limits = c3_options_dict['u_vertical_limits']
- c3_options.workspace_margins = c3_options_dict['workspace_margins']
- c3_options.N = c3_options_dict['N']
- c3_options.gamma = c3_options_dict['gamma']
- c3_options.gamma = c3_options_dict['gamma']
- c3_options.q_vector = c3_options_dict['q_vector']
- c3_options.r_vector = c3_options_dict['r_vector']
- c3_options.g_x = c3_options_dict['g_x']
- c3_options.g_gamma = c3_options_dict['g_gamma']
- c3_options.g_lambda_n = c3_options_dict['g_lambda_n']
- c3_options.g_lambda_t = c3_options_dict['g_lambda_t']
- c3_options.g_lambda = c3_options_dict['g_lambda']
- c3_options.g_u = c3_options_dict['g_u']
- c3_options.u_x = c3_options_dict['u_x']
- c3_options.u_gamma = c3_options_dict['u_gamma']
- c3_options.u_lambda_n = c3_options_dict['u_lambda_n']
- c3_options.u_lambda_t = c3_options_dict['u_lambda_t']
- c3_options.u_lambda = c3_options_dict['u_lambda']
- c3_options.u_u = c3_options_dict['u_u']
- c3_options.gamma = c3_options_dict['gamma']
- c3_options.mu = c3_options_dict['mu']
- c3_options.dt = c3_options_dict['dt']
- c3_options.solve_dt = c3_options_dict['solve_dt']
- c3_options.num_friction_directions = c3_options_dict['num_friction_directions']
- c3_options.num_contacts = c3_options_dict['num_contacts']
- c3_options.Q = c3_options_dict['w_Q'] * np.diag(np.array(c3_options_dict['q_vector']))
- c3_options.R = c3_options_dict['w_R'] * np.diag(np.array(c3_options_dict['r_vector']))
- g_vec = np.hstack((c3_options_dict['g_x'], c3_options_dict['g_lambda'], c3_options_dict['g_u']))
- u_vec = np.hstack((c3_options_dict['u_x'], c3_options_dict['u_lambda'], c3_options_dict['u_u']))
- c3_options.G = c3_options_dict['w_G'] * np.diag(g_vec)
- c3_options.U = c3_options_dict['w_U'] * np.diag(u_vec)
- return c3_options
diff --git a/bindings/pydairlib/franka/generate_dataset.py b/bindings/pydairlib/franka/generate_dataset.py
deleted file mode 100644
index f892686be0..0000000000
--- a/bindings/pydairlib/franka/generate_dataset.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from franka_env import *
-from yaml import *
-from datetime import datetime
-import h5py
-
-# gains are controller params
-# thetas/intrinsics are environment params
-def generate_dataset(n_datapoints,
- batch_size,
- gains_to_randomize,
- thetas_to_randomize,
- high_level_folder):
- assert n_datapoints == int(n_datapoints / batch_size) * batch_size
-
- num_batches = int(n_datapoints / (batch_size))
- # Each batch is associated with a single set of system intrinsic parameters
- intrinsics = np.zeros((num_batches, len(thetas_to_randomize)))
- # for each parameter vector, generate $batch_size random gains to evaluate
- gains_to_test = np.zeros((num_batches, batch_size, len(gains_to_randomize)))
-
- subfolder = "occam_data" + datetime.now().strftime("%b_%d_%Y_%H%M") + "/"
- if not os.path.exists(os.path.join(high_level_folder, subfolder)):
- os.makedirs(os.path.join(high_level_folder, subfolder), exist_ok=True)
-
- with h5py.File(os.path.join(high_level_folder, subfolder, "dataset.hdf5"), 'w') as f:
- # intrinsic vectors don't actually get used anywhere, but good to save for bookkeeping
- f.create_dataset("intrinsics", shape=intrinsics.shape)
- f.create_dataset("gains", shape=gains_to_test.shape)
- # this system only has 1 performance metric, but in principle this could be any number
- f.create_dataset("metrics", shape=(num_batches, batch_size, 1))
- # f.create_dataset("states", shape=(num_batches, batch_size, 1))
- for batch in range(num_batches):
- # Generate a random intrinsic vector for this batch
- # batch_intrinsic_obj = params_t.generate_random(thetas_to_randomize)
- f["intrinsics"][batch, ...] = thetas_to_randomize
- # robot = Branin(batch_intrinsic_obj, gains_to_randomize)
- for point in range(batch_size):
- # generate a random gain vector
- # gain = BraninInputs.generate_random(gains_to_randomize).get_list()[gains_to_randomize]
- gain = 2 * np.random.random(gains_to_randomize.shape[0]) - 1 # center around 0. [-1, 1]
- # run the simulation and obtain the performance metrics
- # metric = robot.evaluate_x(gain)
- metric, states = run_sim(thetas_to_randomize, gain)
- f["metrics"][batch, point] = metric
- f["gains"][batch, point] = gain
- # f["states"][batch, point] = states
- print(f"finished batch {batch}")
-
-
-if __name__ == '__main__':
- hersh_dataset_params_file = 'bindings/pydairlib/franka/parameters/dataset_params.yaml'
- params = yaml_load(filename=hersh_dataset_params_file)
- generate_dataset(50 * 64, 64, np.ones(5), np.zeros(5), params['high_level_folder'])
diff --git a/bindings/pydairlib/franka/parameters/dataset_params.yaml b/bindings/pydairlib/franka/parameters/dataset_params.yaml
deleted file mode 100644
index 77293d3cb3..0000000000
--- a/bindings/pydairlib/franka/parameters/dataset_params.yaml
+++ /dev/null
@@ -1 +0,0 @@
-high_level_folder: /media/yangwill/backups/home/yangwill/Documents/research/projects/franka/occam/
diff --git a/bindings/pydairlib/franka/planar_box_example.py b/bindings/pydairlib/franka/planar_box_example.py
deleted file mode 100644
index e3036ee1ef..0000000000
--- a/bindings/pydairlib/franka/planar_box_example.py
+++ /dev/null
@@ -1,229 +0,0 @@
-import numpy as np
-from pydrake.all import (
- AddMultibodyPlantSceneGraph,
- ContactVisualizer,
- DiagramBuilder,
- ExternallyAppliedSpatialForce,
- LeafSystem,
- List,
- MeshcatVisualizer,
- ModelVisualizer,
- Parser,
- Simulator,
- SpatialForce,
- StartMeshcat,
- RigidTransform,
- Value,
- InitializeAutoDiff,
- ModelInstanceIndex,
- PiecewisePolynomial,
-)
-
-from c3 import *
-
-
-class Controller(LeafSystem):
- def __init__(self, plant, plant_context):
- LeafSystem.__init__(self)
- forces_cls = Value[List[ExternallyAppliedSpatialForce]]
- self.DeclareVectorOutputPort(
- "controller_output", 1, self.CalcOutput
- )
- self.DeclareVectorInputPort("system_state", plant.num_positions() + plant.num_velocities())
- self.plant = plant
- self.plant_context = plant_context
- self.c3_options = C3Options()
-
- lcs_builer = DiagramBuilder()
- self.plant_for_lcs, self.scene_graph_for_lcs = AddMultibodyPlantSceneGraph(
- lcs_builer, 0.0)
- lcs_parser = Parser(self.plant_for_lcs)
- self.passive_block_index = lcs_parser.AddModels(
- "bindings/pydairlib/franka/urdf/passive_block_lcs.sdf")[0]
- self.active_block_index = \
- lcs_parser.AddModels("bindings/pydairlib/franka/urdf/active_block.sdf")[
- 0]
- self.plant_for_lcs.WeldFrames(self.plant_for_lcs.world_frame(),
- self.plant_for_lcs.GetFrameByName("base",
- self.passive_block_index))
- self.plant_for_lcs.Finalize()
-
- lcs_diagram = lcs_builer.Build()
-
- diagram_context = lcs_diagram.CreateDefaultContext()
- self.context_for_lcs = lcs_diagram.GetMutableSubsystemContext(
- self.plant_for_lcs, diagram_context)
- self.plant_ad = self.plant_for_lcs.ToAutoDiffXd()
- self.context_ad = self.plant_ad.CreateDefaultContext()
-
- passive_block_contact_points = self.plant_for_lcs.GetCollisionGeometriesForBody(
- self.plant_for_lcs.GetBodyByName("passive_block",
- self.passive_block_index))
- active_block_contact_points = self.plant_for_lcs.GetCollisionGeometriesForBody(
- self.plant_for_lcs.GetBodyByName("active_block",
- self.active_block_index))
- self.contact_geoms = list()
- for geom_id in passive_block_contact_points:
- self.contact_geoms.append((active_block_contact_points[0], geom_id))
- self.num_friction_directions = 1
- self.mu = [0.4, 0.4]
- self.dt = 0.05
- self.N = 10
- self.contact_model = ContactModel.kAnitescu
- # self.contact_model = ContactModel.kStewartAndTrinkle
- self.Q = 50 * np.diag(np.array([1000, 5000, 10, 10, 5, 10, 5, 5]))
- self.R = 5 * np.eye(1)
- self.G = 0.1 * np.diag(np.hstack((np.ones(4), 1 * np.ones(4), 100 * np.ones(4), 5 * np.ones(1))))
- self.U = 0.1 * np.diag(np.hstack((np.ones(4), 1 * np.ones(4), 100 * np.ones(4), 5 * np.ones(1))))
- # self.G = 0.1 * np.diag(np.ones(13))
- # self.U = 0.1 * np.diag(np.ones(13))
-
- # self.U = 0.1 * np.diag(np.hstack((np.ones(4), 1 * np.ones(4), 0.01 * np.ones(8), 5 * np.ones(1))))
- # self.G = 0.1 * np.diag(np.hstack((np.ones(4), 1 * np.ones(4), 0.01 * np.ones(8), 5 * np.ones(1))))
- self.c3_options.admm_iter = 2
- self.c3_options.rho = 0
- self.c3_options.rho_scale = 2
- self.c3_options.num_threads = 4
- self.c3_options.delta_option = 1
- self.c3_options.contact_model = "anitescu"
- # self.c3_options.contact_model = "stewart_and_trinkle"
- self.c3_options.warm_start = 1
- self.c3_options.use_predicted_x0 = 0
- self.c3_options.end_on_qp_step = 0
- self.c3_options.use_robust_formulation = 0
- self.c3_options.solve_time_filter_alpha = 0.95
- self.c3_options.publish_frequency = 0
- self.c3_options.u_horizontal_limits = np.array([-5, 5])
- self.c3_options.u_vertical_limits = np.array([0, 0])
- self.c3_options.workspace_limits = [np.array([1, 0, 0, -0.5, 0.5])] # unused
- self.c3_options.workspace_margins = 0.05
- self.c3_options.N = self.N
- self.c3_options.gamma = 1.0
- self.c3_options.mu = self.mu
- self.c3_options.dt = self.dt
- self.c3_options.solve_dt = 0.0
- self.c3_options.num_friction_directions = self.num_friction_directions
- self.c3_options.num_contacts = len(self.mu)
- self.c3_options.Q = self.Q
- self.c3_options.R = self.R
- self.c3_options.G = self.G
- self.c3_options.U = self.U
- self.u = PiecewisePolynomial(np.array([0]))
- self.last_update_time = -1
- self.c3_solver = None
- self.x_des = np.array([0.0, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0])
- self.predicted_x1 = self.x_des
- self.lcs_pred = self.x_des
- Qs = []
- for i in range(self.N + 1):
- Qs.append(1.0 ** i * self.Q)
- # costs = CostMatrices((self.N + 1) * [self.Q], self.N * [self.R], self.N * [self.G], self.N * [self.U])
- self.costs = CostMatrices(Qs, self.N * [self.R], self.N * [self.G], self.N * [self.U])
-
- def CalcOutput(self, context, output):
-
-
- if context.get_time() > self.last_update_time + (0.1 * self.dt):
- x = self.EvalVectorInput(context, 0)
- x0 = x.value()
- # u0 = np.zeros(1)
- u0 = self.u.value(context.get_time())[0]
- x_u = np.hstack((x.value(), u0))
- x_u_ad = InitializeAutoDiff(x_u)
-
- if context.get_time() // 10 % 2 == 0:
- self.x_des = np.array([0.0, -0.3, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0])
- else:
- self.x_des = np.array([0.0, 0.3, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0])
- print("time: ", context.get_time())
- print("current cost: ", (x.value() - self.x_des).T @ (x.value() - self.x_des))
- print("desired x: ", self.x_des)
- print("planned x1: ", self.predicted_x1)
- print("lcs pred x1: ", self.lcs_pred)
- print("actual x1: ", x.value())
- # import pdb; pdb.set_trace()
- self.plant_for_lcs.SetPositionsAndVelocities(self.context_for_lcs, x0)
- self.plant_for_lcs.get_actuation_input_port().FixValue(self.context_for_lcs, u0)
- self.plant_ad.get_actuation_input_port().FixValue(self.context_ad, x_u_ad[-1])
- lcs = LinearizePlantToLCS(self.plant_for_lcs, self.context_for_lcs,
- self.plant_ad, self.context_ad, self.contact_geoms,
- self.num_friction_directions, self.mu, self.dt, self.N,
- self.contact_model)
-
- if self.c3_solver == None:
- self.c3_solver = C3MIQP(lcs, self.costs, (self.N + 1) * [self.x_des], self.c3_options)
- else:
- self.c3_solver.UpdateLCS(lcs)
- self.c3_solver.UpdateTarget((self.N + 1) * [self.x_des])
- self.c3_solver.Solve(x0)
- u_sol = self.c3_solver.GetInputSolution()
- x_sol = self.c3_solver.GetStateSolution()
- w_sol = self.c3_solver.GetDualWSolution()
- delta_sol = self.c3_solver.GetDualDeltaSolution()
- z_sol = self.c3_solver.GetFullSolution()
-
- u_sol = np.array(u_sol)
- x_sol = np.array(x_sol)
- w_sol = np.array(w_sol)
- delta_sol = np.array(delta_sol)
- z_sol = np.array(z_sol)
-
- self.predicted_x1 = x_sol[1, :]
- self.lcs_pred = lcs.Simulate(x0, u_sol[0])
- # print(next_pred)
- # next_pred = lcs.Simulate(next_pred, u_sol[0])
- # print(next_pred)
- # import pdb; pdb.set_trace()
- timestamps = context.get_time() + self.dt * np.arange(self.N)
- self.u = PiecewisePolynomial.ZeroOrderHold(timestamps, u_sol.T)
- # self.u = PiecewisePolynomial.FirstOrderHold(timestamps, np.array(u_sol).T)
- self.last_update_time = context.get_time()
- output.set_value(self.u.value(context.get_time()))
-
-
-def main():
- # np.set_printoptions(3, threshold=3, suppress=True)
- builder = DiagramBuilder()
-
- plant, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.001)
- parser = Parser(plant)
- passive_block_index = \
- parser.AddModels("bindings/pydairlib/franka/urdf/passive_block.sdf")[0]
- active_block_index = \
- parser.AddModels("bindings/pydairlib/franka/urdf/active_block.sdf")[0]
- offset = RigidTransform(np.array([0.0, 0.0, 0.0]))
- plant.WeldFrames(plant.world_frame(),
- plant.GetFrameByName("base", passive_block_index), offset)
- # plant.WeldFrames(plant.world_frame(),
- # plant.GetFrameByName("base", active_block_index))
- plant.Finalize()
- plant_context = plant.CreateDefaultContext()
- meshcat = StartMeshcat()
- visualizer = MeshcatVisualizer.AddToBuilder(builder, scene_graph, meshcat)
- ContactVisualizer.AddToBuilder(builder, plant, meshcat)
- controller = builder.AddSystem(Controller(plant, plant_context))
- builder.Connect(controller.get_output_port(),
- plant.get_actuation_input_port())
- builder.Connect(plant.get_state_output_port(),
- controller.get_input_port())
- diagram = builder.Build()
-
- meshcat.SetCameraPose(np.array([0, -3.0, 0.5]), np.array([0, 0.0, 0.0]))
- simulator = Simulator(diagram)
- context = simulator.get_context()
- plant.SetPositions(diagram.GetMutableSubsystemContext(plant,
- simulator.get_mutable_context()),
- np.array([0.0, 0.0, 0.1, 0])) # active x, passive: x, z, theta
- simulator.Initialize()
- simulator.set_target_realtime_rate(1.0)
- meshcat.StartRecording()
- simulator.AdvanceTo(40.0)
- meshcat.StopRecording()
- meshcat.PublishRecording()
- with open("planar_box_visualization.html", "r+") as f:
- f.write(meshcat.StaticHtml())
- print("done simulating")
-
-
-if __name__ == '__main__':
- main()
diff --git a/bindings/pydairlib/franka/urdf/active_block.sdf b/bindings/pydairlib/franka/urdf/active_block.sdf
deleted file mode 100644
index 0cf5c974ec..0000000000
--- a/bindings/pydairlib/franka/urdf/active_block.sdf
+++ /dev/null
@@ -1,64 +0,0 @@
-
-
-
-
-
-
- 0 0 0 0 0 0
- 1
-
- 0.014167
- 0
- 0
- 0.33417
- 0
- 0.34667
-
-
-
- 0 0 0 0 0 0
-
- 0.5 0.2 0.2 0.6
-
-
-
- 2.0 0.4 0.1
-
-
-
-
- 0 0 0 0 0 0
-
-
- 2.0 0.4 0.1
-
-
-
-
- 3.0e7
- 0.15
- 10
- 0.4
-
-
-
-
- world
- active_block
-
-
- 1 0 0
-
-
- -2.0
- 2.0
- 50.0
-
-
- 0.0
-
-
-
-
-
-
\ No newline at end of file
diff --git a/bindings/pydairlib/franka/urdf/passive_block.sdf b/bindings/pydairlib/franka/urdf/passive_block.sdf
deleted file mode 100644
index a9b43873f8..0000000000
--- a/bindings/pydairlib/franka/urdf/passive_block.sdf
+++ /dev/null
@@ -1,125 +0,0 @@
-
-
-
-
-
-
- 0 0 0 0 0 0
- 0
-
- 0
- 0
- 0
- 0
- 0
- 0
-
-
-
-
-
- 0 0 0 0 0 0
- 0
-
- 0
- 0
- 0
- 0
- 0
- 0
-
-
-
-
-
- 0 0 0 0 0 0
- 0
-
- 0
- 0
- 0
- 0
- 0
- 0
-
-
-
-
-
- 0 0 0 0 0 0
- 1
-
- 0.014167
- 0
- 0
- 0.014167
- 0
- 0.026667
-
-
-
- 0 0 0 0 0 0
-
- 0.1 0.1 0.1 0.6
-
-
-
- 0.4 0.4 0.1
-
-
-
-
- 0 0 0 0 0 0
-
-
- 0.4 0.4 0.1
-
-
-
-
- 3.0e7
- 0.15
- 10
- 0.4
-
-
-
-
- base
- base_x
-
-
- 1 0 0
-
-
- 0.0
-
-
-
-
- base_x
- base_xz
-
-
- 0 0 1
-
-
- 0.0
-
-
-
-
- base_xz
- passive_block
-
-
- 0 1 0
-
-
- 0.0
-
-
-
-
-
-
\ No newline at end of file
diff --git a/bindings/pydairlib/franka/urdf/passive_block_lcs.sdf b/bindings/pydairlib/franka/urdf/passive_block_lcs.sdf
deleted file mode 100644
index e218edb31e..0000000000
--- a/bindings/pydairlib/franka/urdf/passive_block_lcs.sdf
+++ /dev/null
@@ -1,126 +0,0 @@
-
-
-
-
-
-
- 0 0 0 0 0 0
- 0
-
- 0
- 0
- 0
- 0
- 0
- 0
-
-
-
-
-
- 0 0 0 0 0 0
- 0
-
- 0
- 0
- 0
- 0
- 0
- 0
-
-
-
-
-
- 0 0 0 0 0 0
- 0
-
- 0
- 0
- 0
- 0
- 0
- 0
-
-
-
-
-
- 0 0 0 0 0 0
- 1
-
- 0.014167
- 0
- 0
- 0.014167
- 0
- 0.026667
-
-
-
- 0 0 0 0 0 0
-
- 0.1 0.1 0.1 0.6
-
-
-
- 0.4 0.4 0.1
-
-
-
-
- -0.2 0.0 -0.048 0 0 0
-
-
- 0.001"
-
-
-
-
- 0.2 0.0 -0.048 0 0 0
-
-
- 0.001"
-
-
-
-
-
- base
- base_x
-
-
- 1 0 0
-
-
- 0.0
-
-
-
-
- base_x
- base_xz
-
-
- 0 0 1
-
-
- 0.0
-
-
-
-
- base_xz
- passive_block
-
-
- 0 1 0
-
-
- 0.0
-
-
-
-
-
-
\ No newline at end of file
diff --git a/bindings/pydairlib/solvers/BUILD.bazel b/bindings/pydairlib/solvers/BUILD.bazel
deleted file mode 100644
index 5fe19d4692..0000000000
--- a/bindings/pydairlib/solvers/BUILD.bazel
+++ /dev/null
@@ -1,54 +0,0 @@
-# -*- python -*-
-load("@drake//tools/install:install.bzl", "install")
-load(
- "@drake//tools/skylark:pybind.bzl",
- "drake_pybind_library",
- "get_drake_py_installs",
- "get_pybind_package_info",
- "pybind_py_library",
-)
-#load("@rules_python//python:packaging.bzl", "py_package", "py_wheel")
-
-package(default_visibility = ["//visibility:public"])
-
-pybind_py_library(
- name = "c3_py",
- cc_deps = [
- "//solvers:c3",
- "@drake//bindings/pydrake/common:default_scalars_pybind",
- "@drake//bindings/pydrake/common:deprecation_pybind",
- "@drake//bindings/pydrake/common:sorted_pair_pybind",
- ],
- cc_so_name = "c3",
- cc_srcs = ["c3_py.cc"],
- py_deps = [
- ":module_py",
- ],
- py_imports = ["."],
-)
-
-# This determines how `PYTHONPATH` is configured, and how to install the
-# bindings.
-PACKAGE_INFO = get_pybind_package_info("//bindings")
-
-py_library(
- name = "module_py",
- srcs = [
- "__init__.py",
- ],
- imports = PACKAGE_INFO.py_imports,
- deps = [
- ],
-)
-
-PY_LIBRARIES = [
- ":module_py",
- ":c3_py",
-]
-
-# Package roll-up (for Bazel dependencies).
-py_library(
- name = "pyc3",
- imports = PACKAGE_INFO.py_imports,
- deps = PY_LIBRARIES,
-)
diff --git a/bindings/pydairlib/solvers/__init__.py b/bindings/pydairlib/solvers/__init__.py
deleted file mode 100644
index 6faf2149f8..0000000000
--- a/bindings/pydairlib/solvers/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# Importing everything in this directory to this package
-from . import *
-from .c3 import *
diff --git a/bindings/pydairlib/solvers/c3_py.cc b/bindings/pydairlib/solvers/c3_py.cc
deleted file mode 100644
index 51dc308006..0000000000
--- a/bindings/pydairlib/solvers/c3_py.cc
+++ /dev/null
@@ -1,129 +0,0 @@
-#include
-#include
-#include
-#include
-
-#include "solvers/c3_miqp.h"
-#include "solvers/lcs.h"
-#include "solvers/lcs_factory.h"
-
-namespace py = pybind11;
-
-using Eigen::MatrixXd;
-using Eigen::VectorXd;
-using py::arg;
-using std::vector;
-
-using dairlib::solvers::C3MIQP;
-using dairlib::solvers::LCS;
-
-namespace c3 {
-namespace pyc3 {
-
-PYBIND11_MODULE(c3, m) {
- py::class_(m, "LCS")
- .def(py::init&, const vector&,
- const vector&, const vector&,
- const vector&, const vector&,
- const vector&, const vector&, double>(),
- arg("A"), arg("B"), arg("D"), arg("d"), arg("E"), arg("F"), arg("H"),
- arg("c"), arg("dt"))
- .def(py::init(),
- arg("A"), arg("B"), arg("D"), arg("d"), arg("E"), arg("F"), arg("H"),
- arg("c"), arg("N"), arg("dt"))
- .def_readwrite("A_", &LCS::A_)
- .def_readwrite("B_", &LCS::B_)
- .def_readwrite("D_", &LCS::D_)
- .def_readwrite("d_", &LCS::d_)
- .def_readwrite("E_", &LCS::E_)
- .def_readwrite("F_", &LCS::F_)
- .def_readwrite("H_", &LCS::H_)
- .def_readwrite("c_", &LCS::c_)
- .def("Simulate", &LCS::Simulate);
-
- m.def("LinearizePlantToLCS",
- &dairlib::solvers::LCSFactory::LinearizePlantToLCS,
- py::arg("plant"),
- py::arg("context"),
- py::arg("plant_ad"),
- py::arg("context_ad"),
- py::arg("contact_geoms"),
- py::arg("mu"),
- py::arg("dt"),
- py::arg("N"),
- py::arg("n_lambda_with_tangential"),
- py::arg("num_friction_directions_per_contact"),
- py::arg("starting_index_per_contact_in_lambda_t_vector"),
- py::arg("contact_model"));
-
- {
- using Enum = dairlib::solvers::ContactModel;
- py::enum_ enum_py(m, "ContactModel");
- enum_py // BR
- .value("kStewartAndTrinkle", Enum::kStewartAndTrinkle)
- .value("kAnitescu", Enum::kAnitescu);
- }
-
- py::class_(m, "CostMatrices")
- .def(py::init&, const std::vector&,
- const std::vector&, const std::vector&>(),
- arg("Q"), arg("R"), arg("G"), arg("U"));
-
- py::class_(m, "C3MIQP")
- .def(py::init&, const C3Options&>(),
- arg("LCS"), arg("costs"), arg("x_des"), arg("c3_options"))
- .def("Solve", &C3MIQP::Solve, arg("x0"), arg("verbose") = false)
- .def("UpdateTarget", &C3MIQP::UpdateTarget, arg("x0"))
- .def("UpdateLCS", &C3MIQP::UpdateLCS, arg("lcs"))
- .def("ADMMStep", &C3MIQP::ADMMStep, arg("x0"), arg("delta"), arg("w"),
- arg("G"), arg("admm_iteration"), arg("verbose") = false)
- .def("SolveQP", &C3MIQP::SolveQP, arg("x0"), arg("G"), arg("WD"), arg("delta"),
- arg("admm_iteration"), arg("is_final_solve"))
- .def("SolveProjection", &C3MIQP::SolveProjection, arg("U"), arg("WZ"), arg("admm_iteration"))
- .def("AddLinearConstraint", &C3MIQP::AddLinearConstraint, arg("A"),
- arg("lower_bound"), arg("upper_bound"), arg("constraint"))
- .def("RemoveConstraints", &C3MIQP::RemoveUserConstraints)
- .def("GetFullSolution", &C3MIQP::GetFullSolution)
- .def("GetStateSolution", &C3MIQP::GetStateSolution)
- .def("GetForceSolution", &C3MIQP::GetForceSolution)
- .def("GetInputSolution", &C3MIQP::GetInputSolution)
- .def("GetDualDeltaSolution", &C3MIQP::GetDualDeltaSolution)
- .def("GetDualWSolution", &C3MIQP::GetDualWSolution);
-
- py::class_ options(m, "C3Options");
- options.def(py::init<>())
- .def_readwrite("admm_iter", &C3Options::admm_iter)
- .def_readwrite("rho", &C3Options::rho)
- .def_readwrite("rho_scale", &C3Options::rho_scale)
- .def_readwrite("num_threads", &C3Options::num_threads)
- .def_readwrite("delta_option", &C3Options::delta_option)
- .def_readwrite("contact_model", &C3Options::contact_model)
- .def_readwrite("warm_start", &C3Options::warm_start)
- .def_readwrite("use_predicted_x0", &C3Options::use_predicted_x0)
- .def_readwrite("end_on_qp_step", &C3Options::end_on_qp_step)
- .def_readwrite("solve_time_filter_alpha",
- &C3Options::solve_time_filter_alpha)
- .def_readwrite("publish_frequency", &C3Options::publish_frequency)
- .def_readwrite("u_horizontal_limits", &C3Options::u_horizontal_limits)
- .def_readwrite("u_vertical_limits", &C3Options::u_vertical_limits)
- .def_readwrite("workspace_limits", &C3Options::workspace_limits)
- .def_readwrite("workspace_margins", &C3Options::workspace_margins)
- .def_readwrite("N", &C3Options::N)
- .def_readwrite("gamma", &C3Options::gamma)
- .def_readwrite("mu", &C3Options::mu)
- .def_readwrite("dt", &C3Options::dt)
- .def_readwrite("solve_dt", &C3Options::solve_dt)
- .def_readwrite("num_friction_directions",
- &C3Options::num_friction_directions)
- .def_readwrite("num_contacts", &C3Options::num_contacts)
- .def_readwrite("Q", &C3Options::Q)
- .def_readwrite("R", &C3Options::R)
- .def_readwrite("G", &C3Options::G)
- .def_readwrite("U", &C3Options::U);
-}
-
-} // namespace pyc3
-} // namespace c3
diff --git a/examples/franka/BUILD.bazel b/examples/franka/BUILD.bazel
deleted file mode 100644
index dd4655ae72..0000000000
--- a/examples/franka/BUILD.bazel
+++ /dev/null
@@ -1,286 +0,0 @@
-# -*- mode: python -*-
-# vi: set ft=python :
-
-package(default_visibility = ["//visibility:public"])
-
-cc_library(
- name = "urdfs",
- data = glob([
- "urdf/**",
- ]),
-)
-
-cc_binary(
- name = "full_diagram",
- srcs = ["full_diagram.cc"],
- data = [
- ":urdfs",
- "@drake_models//:franka_description",
- ],
- deps = [
- ":parameters",
- "//examples/franka/diagrams:franka_c3_controller_diagram",
- "//examples/franka/diagrams:franka_osc_controller_diagram",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "@drake//:drake_shared_library",
- ],
-)
-
-cc_binary(
- name = "franka_sim",
- srcs = ["franka_sim.cc"],
- data = [
- ":urdfs",
- "@drake_models//:franka_description",
- ],
- deps = [
- ":parameters",
- "//common",
- "//examples/franka/systems:franka_systems",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "//systems/controllers",
- "//systems/framework:lcm_driven_loop",
- "//systems/primitives:radio_parser",
- "@drake//:drake_shared_library",
- "@gflags",
- ],
-)
-
-cc_binary(
- name = "franka_osc_controller",
- srcs = ["franka_osc_controller.cc"],
- data = [
- ":urdfs",
- "@drake_models//:franka_description",
- ],
- deps = [
- ":parameters",
- "//common",
- "//examples/franka/systems:franka_systems",
- "//lcm:lcm_trajectory_saver",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "//systems/controllers",
- "//systems/controllers/osc:operational_space_control",
- "//systems/framework:lcm_driven_loop",
- "//systems/primitives:radio_parser",
- "//systems/trajectory_optimization:lcm_trajectory_systems",
- "@drake//:drake_shared_library",
- "@gflags",
- ],
-)
-
-cc_binary(
- name = "franka_c3_controller",
- srcs = ["franka_c3_controller.cc"],
- data = [
- ":urdfs",
- "@drake_models//:franka_description",
- ],
- deps = [
- ":parameters",
- "//common",
- "//examples/franka/systems:franka_systems",
- "//systems:franka_kinematics",
- "//systems/senders:c3_state_sender",
- "//lcm:lcm_trajectory_saver",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "//systems/controllers",
- "//systems/controllers:c3_controller",
- "//systems/controllers:lcs_factory_system",
- "//systems/controllers/osc:operational_space_control",
- "//systems/framework:lcm_driven_loop",
- "//systems/primitives:radio_parser",
- "//systems/trajectory_optimization:c3_output_systems",
- "@drake//:drake_shared_library",
- "@gflags",
- ],
-)
-
-cc_binary(
- name = "franka_c3_controller_two_objects",
- srcs = ["franka_c3_controller_two_objects.cc"],
- data = [
- ":urdfs",
- "@drake_models//:franka_description",
- ],
- deps = [
- ":parameters",
- "//common",
- "//examples/franka/systems:franka_systems",
- "//systems:franka_kinematics",
- "//systems/senders:c3_state_sender",
- "//lcm:lcm_trajectory_saver",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "//systems/controllers",
- "//systems/controllers:c3_controller",
- "//systems/controllers:lcs_factory_system",
- "//systems/controllers/osc:operational_space_control",
- "//systems/framework:lcm_driven_loop",
- "//systems/primitives:radio_parser",
- "//systems/trajectory_optimization:c3_output_systems",
- "@drake//:drake_shared_library",
- "@gflags",
- ],
-)
-
-cc_binary(
- name = "forward_kinematics_for_lcs",
- srcs = ["forward_kinematics_for_lcs.cc"],
- data = [
- ":urdfs",
- "@drake_models//:franka_description",
- ],
- deps = [
- ":parameters",
- "//common",
- "//examples/franka/systems:franka_systems",
- "//systems:franka_kinematics",
- "//systems/senders:c3_state_sender",
- "//lcm:lcm_trajectory_saver",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "//systems/controllers",
- "//systems/controllers:c3_controller",
- "//systems/controllers:lcs_factory_system",
- "//systems/controllers/osc:operational_space_control",
- "//systems/framework:lcm_driven_loop",
- "//systems/primitives:radio_parser",
- "//systems/trajectory_optimization:c3_output_systems",
- "@drake//:drake_shared_library",
- "@gflags",
- ],
-)
-
-cc_binary(
- name = "franka_visualizer",
- srcs = ["franka_visualizer.cc"],
- data = [
- ":urdfs",
- "@drake_models//:franka_description",
- ],
- deps = [
- ":parameters",
- "//common",
- "//multibody:utils",
- "//multibody:visualization_utils",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "//systems/primitives",
- "//systems/trajectory_optimization:lcm_trajectory_systems",
- "//systems/visualization:lcm_visualization_systems",
- "@drake//:drake_shared_library",
- "@gflags",
- ],
-)
-
-cc_binary(
- name = "franka_bridge_driver_out",
- srcs = ["franka_bridge_driver_out.cc"],
- data = [
- ":urdfs",
- "@drake_models//:franka_description",
- ],
- deps = [
- ":parameters",
- "//common",
- "//systems:franka_state_translator",
- "//multibody:utils",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "//systems/framework:lcm_driven_loop",
- "//systems/primitives",
- "@drake//:drake_shared_library",
- "@gflags",
- ],
-)
-
-cc_binary(
- name = "franka_bridge_driver_in",
- srcs = ["franka_bridge_driver_in.cc"],
- data = [
- ":urdfs",
- "@drake_models//:franka_description",
- ],
- deps = [
- ":parameters",
- "//common",
- "//systems:franka_state_translator",
- "//multibody:utils",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "//systems/framework:lcm_driven_loop",
- "//systems/primitives",
- "@drake//:drake_shared_library",
- "@gflags",
- ],
-)
-
-cc_binary(
- name = "franka_ros_lcm_bridge",
- srcs = ["franka_ros_lcm_bridge.cc"],
- data = [
- ":urdfs",
- "@drake_models//:franka_description",
- ],
- tags = ["ros"],
- deps = [
- ":parameters",
- "//common",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "//systems/primitives",
- "//systems/ros:franka_ros_channels",
- "//systems/ros:franka_ros_lcm_conversions",
- "//systems/ros:ros_pubsub_systems",
- "@drake//:drake_shared_library",
- "@gflags",
- "@ros",
- ],
-)
-
-cc_binary(
- name = "franka_lcm_ros_bridge",
- srcs = ["franka_lcm_ros_bridge.cc"],
- data = [
- ":urdfs",
- "@drake_models//:franka_description",
- ],
- tags = ["ros"],
- deps = [
- ":parameters",
- "//common",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "//systems/framework:lcm_driven_loop",
- "//systems/ros:franka_ros_channels",
- "//systems/ros:franka_ros_lcm_conversions",
- "//systems/ros:ros_pubsub_systems",
- "@drake//:drake_shared_library",
- "@gflags",
- "@ros",
- ],
-)
-
-cc_library(
- name = "parameters",
- hdrs = [
- "parameters/franka_c3_controller_params.h",
- "parameters/franka_c3_scene_params.h",
- "parameters/franka_lcm_channels.h",
- "parameters/franka_osc_controller_params.h",
- "parameters/franka_sim_params.h",
- "parameters/franka_sim_scene_params.h",
- ],
- data = glob([
- "parameters/*.yaml",
- ]),
- deps = [
- "@drake//:drake_shared_library",
- "//common/parameters:franka_drake_lcm_driver_channels",
- ],
-)
diff --git a/examples/franka/README.md b/examples/franka/README.md
deleted file mode 100644
index 989a8dc943..0000000000
--- a/examples/franka/README.md
+++ /dev/null
@@ -1,77 +0,0 @@
-## Experiment Instructions
-
-Central repo for C3 and its examples, including:
-- https://arxiv.org/abs/2405.08731
-
-This branch/repo is being constantly updated so examples may be unstable.
-
-## Simulated Robot
-
-1. Start the procman script containing a list of relevant processes
-```
-bot-procman-sheriff -l franka_sim.pmd
-```
-
-2. In the procman window, start the operator processes (meshcat visualizer) using the script `script:start_operator_commands`. Scripts are located in the top bar of the procman window.
-
-3. The meshcat visualizer can be viewed by opening a browser and navigating to `localhost:7000`
-
-4. The examples with the C3 controller can be run using the script `script:c3_mpc`. Note, the task can be changed by changing the `scene_index` in the parameters. More details in [changing the scene](#changing-the-scene). This script spawns three processes:
- - `bazel-bin/examples/franka/franka_sim`: Simulated environment which takes in torques commands from `franka_osc` and publishes the state of the system via LCM on various channels.
- - `bazel-bin/examples/franka/franka_osc_controller`: Low-level task-space controller that tracks task-space trajectories it receives from the MPC
- - `bazel-bin/examples/franka/franka_c3_controller`: Contact Implicit MPC controller that takes in the state of the system and publishes end effector trajectories to be tracked by the OSC.
-
-5. The simulator and controller can be stopped using the script `script:stop_controllers_and_simulators`.
-6. A comparison using the sampling based MPC controllers from the [MJMPC controllers](https://github.com/google-deepmind/mujoco_mpc) can be run using `script:mjmpc_with_drake_sim`. This extracts out just the controller portion of the MJMPC code base and runs in on the identical task (scene 1) in the Drake simulator. Instructions to build and configure the standalone MJMPC controllers are a WIP.
-
-## Physical Robot
-
-Hardware instructions updated for Ubuntu 22.04. We are no longer using ROS or ROS2 and instead relying on [drake-franka-driver](https://github.com/RobotLocomotion/drake-franka-driver), which works via LCM. Much thanks to the Drake developers who provided this!
-
-### Installing `drake-franka-driver`
-
-```
-git clone https://github.com/RobotLocomotion/drake-franka-driver
-cd drake-franka-driver
-bazel build ...
-```
-
-
-### Running Experiments
-
-1. Start the procman script containing a list of relevant processes. The primary differences from`franka_sim.pmd` script are the lcm_channels and the drake-franka-driver and corresponding translators to communicate with the Franka via LCM.
-
- - In the root of dairlib: ``` bot-procman-sheriff -l examples/franka/franka_hardware.pmd ```
- - In the root of drake-franka-driver: ```bot-procman-deputy franka_control```
-
-2. In the procman window, start the operator processes (meshcat visualizer and xbox controller) using the script `script:start_operator_commands`. Scripts are located in the top bar of the procman window.
-
-3. The meshcat visualizer can be viewed by opening a browser and navigating to `localhost:7000`
-
-4. The processes, except the C3 controller, can be run using the script `script:start_experiment`. This spawns the following processes:
- - `start_logging.py`: Starts a lcm-logger with an automatic naming convention for the log number.
- - `record_video.py`: Streams all available webcams to a .mp4 file corresponding to the log number.
- - `torque_driver`: `drake-franka-driver` in torque control mode.
- - `franka_driver_`(in/out): communicates with `drake-franka-driver` to receive/publish franka state information and torque commands. This is just a translator between Drake's Franka Panda specific lcm messages and the standardized robot commands that we use.
- - `bazel-bin/examples/franka/franka_osc_controller`: Low-level task-space controller that tracks task-space trajectories it receives from the MPC
-
-
-5. For safety, start the C3 controller separately after verifying the rest of the processes have started successfully, by manually starting the `franka_c3` process.
-6. Using the xbox controller, switch from tracking the teleop commands to the MPC plan by pressing "A".
-7. Stop the experiment using `script:stop_experiment`. This also stops logging and recording.
-
-
-## Changing the scene
-
-We currently have environment descriptions and gains for the following scenes:
-
-The scene can be changed by updating the `scene_index` parameter in BOTH `franka_sim_params.yaml` and `franka_c3_controller_params.yaml`.
-The visualizer process must be restarted if changing the scene.
-
-| Scene Index | Description |
-|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
-| 0 | No fixed environment features. For testing controlled sliding purely between the end effector and tray + optional objects. Gains still a WIP. |
-| 1 | Primary RSS paper example with supports |
-| 2 | Variation on RSS paper example with rotated supports |
-| 3 | Additional rotating with wall task for RSS paper |
-
diff --git a/examples/franka/diagrams/BUILD.bazel b/examples/franka/diagrams/BUILD.bazel
deleted file mode 100644
index bedf79b67d..0000000000
--- a/examples/franka/diagrams/BUILD.bazel
+++ /dev/null
@@ -1,59 +0,0 @@
-package(default_visibility = ["//visibility:public"])
-
-cc_library(
- name = "franka_c3_controller_diagram",
- srcs = ["franka_c3_controller_diagram.cc"],
- hdrs = ["franka_c3_controller_diagram.h"],
- deps = [
- "//common",
- "//examples/franka:parameters",
- "//examples/franka/systems:franka_systems",
- "//systems/senders:c3_state_sender",
- "//lcm:lcm_trajectory_saver",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "//systems/controllers",
- "//systems/controllers:c3_controller",
- "//systems/controllers:lcs_factory_system",
- "//systems/controllers/osc:operational_space_control",
- "//systems/framework:lcm_driven_loop",
- "//systems/primitives:radio_parser",
- "//systems/trajectory_optimization:c3_output_systems",
- "@drake//:drake_shared_library",
- "@gflags",
- ],
-)
-
-cc_library(
- name = "franka_osc_controller_diagram",
- srcs = ["franka_osc_controller_diagram.cc"],
- hdrs = ["franka_osc_controller_diagram.h"],
- deps = [
- "//common",
- "//examples/franka:parameters",
- "//examples/franka/systems:franka_systems",
- "//lcm:lcm_trajectory_saver",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "//systems/controllers",
- "//systems/controllers/osc:operational_space_control",
- "//systems/primitives:radio_parser",
- "//systems/trajectory_optimization:lcm_trajectory_systems",
- "@drake//:drake_shared_library",
- "@gflags",
- ],
-)
-
-cc_library(
- name = "franka_sim_diagram",
- srcs = ["franka_sim_diagram.cc"],
- hdrs = ["franka_sim_diagram.h"],
- deps = [
- "//common",
- "//examples/franka:parameters",
- "//systems:robot_lcm_systems",
- "//systems:system_utils",
- "@drake//:drake_shared_library",
- "@gflags",
- ],
-)
diff --git a/examples/franka/diagrams/franka_c3_controller_diagram.cc b/examples/franka/diagrams/franka_c3_controller_diagram.cc
deleted file mode 100644
index e49a5a91df..0000000000
--- a/examples/franka/diagrams/franka_c3_controller_diagram.cc
+++ /dev/null
@@ -1,339 +0,0 @@
-//
-// Created by yangwill on 2/19/24.
-//
-
-#include "examples/franka/diagrams/franka_c3_controller_diagram.h"
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "common/eigen_utils.h"
-#include "examples/franka/parameters/franka_c3_controller_params.h"
-#include "examples/franka/parameters/franka_c3_scene_params.h"
-#include "examples/franka/parameters/franka_lcm_channels.h"
-#include "systems/senders/c3_state_sender.h"
-#include "examples/franka/systems/c3_trajectory_generator.h"
-#include "systems/franka_kinematics.h"
-#include "examples/franka/systems/plate_balancing_target.h"
-#include "multibody/multibody_utils.h"
-#include "solvers/lcs_factory.h"
-#include "systems/controllers/c3/lcs_factory_system.h"
-#include "systems/controllers/c3/c3_controller.h"
-#include "systems/framework/lcm_driven_loop.h"
-#include "systems/primitives/radio_parser.h"
-#include "systems/robot_lcm_systems.h"
-#include "systems/system_utils.h"
-#include "systems/trajectory_optimization/c3_output_systems.h"
-
-namespace dairlib {
-
-namespace examples {
-namespace controllers {
-
-using dairlib::solvers::LCSFactory;
-using drake::SortedPair;
-using drake::geometry::GeometryId;
-using drake::math::RigidTransform;
-using drake::multibody::MultibodyPlant;
-using drake::multibody::Parser;
-using drake::systems::DiagramBuilder;
-using drake::systems::TriggerType;
-using drake::systems::TriggerTypeSet;
-using drake::systems::lcm::LcmPublisherSystem;
-using drake::systems::lcm::LcmSubscriberSystem;
-using Eigen::MatrixXd;
-
-using Eigen::Vector3d;
-using Eigen::VectorXd;
-using multibody::MakeNameToPositionsMap;
-using multibody::MakeNameToVelocitiesMap;
-using std::string;
-
-FrankaC3ControllerDiagram::FrankaC3ControllerDiagram(
- const string& controller_settings, const C3Options c3_options, const string& lcm_channels,
- drake::lcm::DrakeLcm* lcm, bool publish_c3_debug) {
- this->set_name("FrankaC3Controller");
- DiagramBuilder builder;
-
- FrankaC3ControllerParams controller_params =
- drake::yaml::LoadYamlFile(controller_settings);
- FrankaLcmChannels lcm_channel_params =
- drake::yaml::LoadYamlFile(lcm_channels);
- FrankaC3SceneParams scene_params =
- drake::yaml::LoadYamlFile(
- controller_params.c3_scene_file[controller_params.scene_index]);
-// C3Options c3_options = drake::yaml::LoadYamlFile(
-// controller_params.c3_options_file[controller_params.scene_index]);
- drake::solvers::SolverOptions solver_options =
- drake::yaml::LoadYamlFile(
- FindResourceOrThrow(controller_params.osqp_settings_file))
- .GetAsSolverOptions(drake::solvers::OsqpSolver::id());
-
- plant_franka_ = new drake::multibody::MultibodyPlant(0.0);
- Parser parser_franka(plant_franka_, nullptr);
- parser_franka.AddModelsFromUrl(scene_params.franka_model);
- drake::multibody::ModelInstanceIndex end_effector_index =
- parser_franka.AddModels(
- FindResourceOrThrow(scene_params.end_effector_model))[0];
-
- RigidTransform X_WI = RigidTransform::Identity();
- plant_franka_->WeldFrames(plant_franka_->world_frame(),
- plant_franka_->GetFrameByName("panda_link0"), X_WI);
-
- RigidTransform T_EE_W =
- RigidTransform(drake::math::RotationMatrix(),
- scene_params.tool_attachment_frame);
- plant_franka_->WeldFrames(
- plant_franka_->GetFrameByName("panda_link7"),
- plant_franka_->GetFrameByName("plate", end_effector_index), T_EE_W);
-
- plant_franka_->Finalize();
- plant_franka_context_ = plant_franka_->CreateDefaultContext();
-
- ///
- plant_tray_ = new drake::multibody::MultibodyPlant(0.0);
- Parser parser_tray(plant_tray_, nullptr);
- parser_tray.AddModels(scene_params.object_models[0]);
- plant_tray_->Finalize();
- plant_tray_context_ = plant_tray_->CreateDefaultContext();
-
- drake::planning::RobotDiagramBuilder lcs_diagram_builder;
- lcs_diagram_builder.parser().SetAutoRenaming(true);
- lcs_diagram_builder.parser().AddModels(scene_params.end_effector_lcs_model);
-
- std::vector environment_model_indices;
- environment_model_indices.resize(scene_params.environment_models.size());
- for (int i = 0; i < scene_params.environment_models.size(); ++i) {
- environment_model_indices[i] = lcs_diagram_builder.parser().AddModels(
- FindResourceOrThrow(scene_params.environment_models[i]))[0];
- RigidTransform T_E_W =
- RigidTransform(drake::math::RollPitchYaw(
- scene_params.environment_orientations[i]),
- scene_params.environment_positions[i]);
- lcs_diagram_builder.plant().WeldFrames(
- lcs_diagram_builder.plant().world_frame(),
- lcs_diagram_builder.plant().GetFrameByName("base", environment_model_indices[i]),
- T_E_W);
- }
- for (int i = 0; i < scene_params.object_models.size(); ++i) {
- lcs_diagram_builder.parser().AddModels(scene_params.object_models[i]);
- }
- lcs_diagram_builder.plant().WeldFrames(
- lcs_diagram_builder.plant().world_frame(),
- lcs_diagram_builder.plant().GetFrameByName("base_link"), X_WI);
- lcs_diagram_builder.plant().Finalize();
- robot_diagram_for_lcs_ = lcs_diagram_builder.Build();
- plant_for_lcs_autodiff_ = drake::systems::System::ToAutoDiffXd(
- robot_diagram_for_lcs_->plant());
-
- robot_diagram_root_context_ = robot_diagram_for_lcs_->CreateDefaultContext();
- plant_for_lcs_autodiff_context_ =
- plant_for_lcs_autodiff_->CreateDefaultContext();
-
- ///
- std::vector end_effector_contact_points =
- robot_diagram_for_lcs_->plant().GetCollisionGeometriesForBody(
- robot_diagram_for_lcs_->plant().GetBodyByName("plate"));
- for (int i = 0; i < environment_model_indices.size(); ++i) {
- std::vector
- environment_support_contact_points =
- robot_diagram_for_lcs_->plant().GetCollisionGeometriesForBody(
- robot_diagram_for_lcs_->plant().GetBodyByName("base",
- environment_model_indices[i]));
- end_effector_contact_points.insert(
- end_effector_contact_points.end(),
- environment_support_contact_points.begin(),
- environment_support_contact_points.end());
- }
- std::vector tray_geoms =
- robot_diagram_for_lcs_->plant().GetCollisionGeometriesForBody(
- robot_diagram_for_lcs_->plant().GetBodyByName("tray"));
- std::unordered_map>
- contact_geoms;
- contact_geoms["PLATE"] = end_effector_contact_points;
- contact_geoms["TRAY"] = tray_geoms;
-
- std::vector> contact_pairs;
- for (auto geom_id : contact_geoms["PLATE"]) {
- contact_pairs.emplace_back(geom_id, contact_geoms["TRAY"][0]);
- }
-
- auto franka_state_receiver =
- builder.AddSystem(*plant_franka_);
- auto tray_state_receiver =
- builder.AddSystem(*plant_tray_);
- auto reduced_order_model_receiver =
- builder.AddSystem(
- *plant_franka_, plant_franka_context_.get(), *plant_tray_,
- plant_tray_context_.get(), scene_params.end_effector_name,
- "tray", controller_params.include_end_effector_orientation);
-
- auto plate_balancing_target =
- builder.AddSystem(
- *plant_tray_, scene_params.end_effector_thickness,
- controller_params.near_target_threshold);
- plate_balancing_target->SetRemoteControlParameters(
- controller_params.first_target[controller_params.scene_index],
- controller_params.second_target[controller_params.scene_index],
- controller_params.third_target[controller_params.scene_index],
- controller_params.x_scale, controller_params.y_scale,
- controller_params.z_scale);
- std::vector input_sizes = {3, 7, 3, 6};
- auto target_state_mux =
- builder.AddSystem(input_sizes);
- auto end_effector_zero_velocity_source =
- builder.AddSystem(
- VectorXd::Zero(3));
- auto tray_zero_velocity_source =
- builder.AddSystem(
- VectorXd::Zero(6));
- builder.Connect(plate_balancing_target->get_output_port_end_effector_target(),
- target_state_mux->get_input_port(0));
- builder.Connect(plate_balancing_target->get_output_port_tray_target(),
- target_state_mux->get_input_port(1));
- builder.Connect(end_effector_zero_velocity_source->get_output_port(),
- target_state_mux->get_input_port(2));
- builder.Connect(tray_zero_velocity_source->get_output_port(),
- target_state_mux->get_input_port(3));
- auto lcs_factory = builder.AddSystem(
- robot_diagram_for_lcs_->plant(),
- robot_diagram_for_lcs_->mutable_plant_context(
- robot_diagram_root_context_.get()),
- *plant_for_lcs_autodiff_, *plant_for_lcs_autodiff_context_, contact_pairs,
- c3_options);
- auto controller = builder.AddSystem(
- robot_diagram_for_lcs_->plant(), c3_options);
- auto c3_trajectory_generator =
- builder.AddSystem(
- robot_diagram_for_lcs_->plant(), c3_options);
-// auto placeholder_trajectory = lcmt_timestamped_saved_traj();
- auto placeholder_solution = C3Output::C3Solution();
- placeholder_solution.x_sol_ = Eigen::MatrixXf::Zero(c3_options.g_x.size(), c3_options.N);
- placeholder_solution.lambda_sol_ = Eigen::MatrixXf::Zero(c3_options.g_lambda.size(), c3_options.N);
- placeholder_solution.u_sol_ = Eigen::MatrixXf::Zero(c3_options.g_u.size(), c3_options.N);
- placeholder_solution.time_vector_ = Eigen::VectorXf::LinSpaced(c3_options.N, 0, 1);
- auto discrete_time_delay = builder.AddSystem(1 / c3_options.publish_frequency,
- 2,
- drake::Value(placeholder_solution));
- std::vector state_names = {
- "end_effector_x", "end_effector_y", "end_effector_z", "tray_qw",
- "tray_qx", "tray_qy", "tray_qz", "tray_x",
- "tray_y", "tray_z", "end_effector_vx", "end_effector_vy",
- "end_effector_vz", "tray_wx", "tray_wy", "tray_wz",
- "tray_vz", "tray_vz", "tray_vz",
- };
- auto c3_state_sender =
- builder.AddSystem(3 + 7 + 3 + 6, state_names);
- c3_trajectory_generator->SetPublishEndEffectorOrientation(
- controller_params.include_end_effector_orientation);
- auto c3_output_sender = builder.AddSystem();
- auto passthrough = builder.AddSystem>(18);
-
- controller->SetOsqpSolverOptions(solver_options);
-
- // publisher connections
- DRAKE_DEMAND(c3_options.publish_frequency > 0);
- builder.Connect(controller->get_output_port_c3_solution(),
- discrete_time_delay->get_input_port());
-
-
- builder.Connect(franka_state_receiver->get_output_port(),
- reduced_order_model_receiver->get_input_port_franka_state());
- builder.Connect(target_state_mux->get_output_port(),
- controller->get_input_port_target());
- builder.Connect(lcs_factory->get_output_port_lcs(),
- controller->get_input_port_lcs());
- builder.Connect(tray_state_receiver->get_output_port(),
- *(reduced_order_model_receiver->get_input_ports_object_state()[0]));
- builder.Connect(tray_state_receiver->get_output_port(),
- plate_balancing_target->get_input_port_tray_state());
- builder.Connect(reduced_order_model_receiver->get_output_port(),
- controller->get_input_port_lcs_state());
- builder.Connect(reduced_order_model_receiver->get_output_port(),
- lcs_factory->get_input_port_lcs_state());
- builder.Connect(passthrough->get_output_port(),
- plate_balancing_target->get_input_port_radio());
- builder.Connect(discrete_time_delay->get_output_port(),
- c3_trajectory_generator->get_input_port_c3_solution());
- builder.Connect(lcs_factory->get_output_port_lcs_contact_jacobian(),
- c3_output_sender->get_input_port_lcs_contact_info());
-
- builder.Connect(target_state_mux->get_output_port(),
- c3_state_sender->get_input_port_target_state());
- builder.Connect(reduced_order_model_receiver->get_output_port_lcs_state(),
- c3_state_sender->get_input_port_actual_state());
-
- builder.Connect(discrete_time_delay->get_output_port(),
- c3_output_sender->get_input_port_c3_solution());
- builder.Connect(controller->get_output_port_c3_intermediates(),
- c3_output_sender->get_input_port_c3_intermediates());
-
-
- if (publish_c3_debug){
- auto actor_trajectory_sender = builder.AddSystem(
- LcmPublisherSystem::Make(
- lcm_channel_params.c3_actor_channel, lcm,
- TriggerTypeSet({TriggerType::kForced})));
- auto object_trajectory_sender = builder.AddSystem(
- LcmPublisherSystem::Make(
- lcm_channel_params.c3_object_channel, lcm,
- TriggerTypeSet({TriggerType::kForced})));
- auto c3_output_publisher =
- builder.AddSystem(LcmPublisherSystem::Make(
- lcm_channel_params.c3_debug_output_channel, lcm,
- TriggerTypeSet({TriggerType::kForced})));
- auto c3_target_state_publisher =
- builder.AddSystem(LcmPublisherSystem::Make(
- lcm_channel_params.c3_target_state_channel, lcm,
- TriggerTypeSet({TriggerType::kForced})));
- auto c3_actual_state_publisher =
- builder.AddSystem(LcmPublisherSystem::Make(
- lcm_channel_params.c3_actual_state_channel, lcm,
- TriggerTypeSet({TriggerType::kForced})));
- auto c3_forces_publisher =
- builder.AddSystem(LcmPublisherSystem::Make(
- lcm_channel_params.c3_force_channel, lcm,
- TriggerTypeSet({TriggerType::kForced})));
- builder.Connect(c3_trajectory_generator->get_output_port_actor_trajectory(),
- actor_trajectory_sender->get_input_port());
- builder.Connect(c3_trajectory_generator->get_output_port_object_trajectory(),
- object_trajectory_sender->get_input_port());
- builder.Connect(c3_state_sender->get_output_port_target_c3_state(),
- c3_target_state_publisher->get_input_port());
- builder.Connect(c3_state_sender->get_output_port_actual_c3_state(),
- c3_actual_state_publisher->get_input_port());
- builder.Connect(c3_output_sender->get_output_port_c3_debug(),
- c3_output_publisher->get_input_port());
- builder.Connect(c3_output_sender->get_output_port_c3_force(),
- c3_forces_publisher->get_input_port());
- }
-
-
-
- // Publisher connections
- franka_state_port_ = builder.ExportInput(franka_state_receiver->get_input_port(),
- "franka_state: lcmt_robot_output");
- tray_state_port_ = builder.ExportInput(tray_state_receiver->get_input_port(),
- "tray_state: lcmt_object_state");
- radio_port_ = builder.ExportInput(passthrough->get_input_port(), "raw_radio");
- mpc_plan_port_ = builder.ExportOutput(
- c3_trajectory_generator->get_output_port_actor_trajectory(),
- "actor_trajectory");
-
- builder.BuildInto(this);
- this->set_name("FrankaC3Controller");
-}
-
-} // namespace controllers
-} // namespace examples
-} // namespace dairlib
diff --git a/examples/franka/diagrams/franka_c3_controller_diagram.h b/examples/franka/diagrams/franka_c3_controller_diagram.h
deleted file mode 100644
index 4e0abb92c4..0000000000
--- a/examples/franka/diagrams/franka_c3_controller_diagram.h
+++ /dev/null
@@ -1,74 +0,0 @@
-#pragma once
-
-#include
-#include
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include "solvers/c3_options.h"
-
-namespace dairlib {
-namespace examples {
-namespace controllers {
-
-class FrankaC3ControllerDiagram : public drake::systems::Diagram {
- public:
- DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FrankaC3ControllerDiagram)
-
- /// @param[in] osc_gains_filename filepath containing the osc_running_gains.
- /// @param[in] osqp_settings filepath containing the osqp settings.
- FrankaC3ControllerDiagram(const std::string& controller_settings, const C3Options c3_options,
- const std::string& lcm_channels,
- drake::lcm::DrakeLcm* lcm, bool publish_c3_debug = false);
-
- /// @return the input port for the plant state.
- const drake::systems::InputPort& get_input_port_robot_state() const {
- return this->get_input_port(franka_state_port_);
- }
-
- /// @return the input port for the plant state.
- const drake::systems::InputPort& get_input_port_object_state() const {
- return this->get_input_port(tray_state_port_);
- }
-
- /// @return the input port for the cassie_out struct (containing radio
- /// commands).
- const drake::systems::InputPort& get_input_port_radio() const {
- return this->get_input_port(radio_port_);
- }
-
- /// @return the output port for the lcmt_robot_input message.
- const drake::systems::OutputPort& get_output_port_mpc_plan() const {
- return this->get_output_port(mpc_plan_port_);
- }
-
- private:
- drake::multibody::MultibodyPlant* plant_franka_;
- drake::multibody::MultibodyPlant* plant_tray_;
-
- // Storage for the diagram and its plant and scene graph.
- // After Build(), the `builder_` is set to nullptr.
- std::unique_ptr> robot_diagram_for_lcs_;
-
- std::unique_ptr> robot_diagram_root_context_;
- std::unique_ptr> plant_for_lcs_diagram_context_;
- std::unique_ptr> plant_for_lcs_autodiff_;
- std::unique_ptr> plant_franka_context_;
- std::unique_ptr> plant_tray_context_;
- std::unique_ptr> plant_for_lcs_autodiff_context_;
-
- drake::systems::InputPortIndex franka_state_port_;
- drake::systems::InputPortIndex tray_state_port_;
- drake::systems::InputPortIndex radio_port_;
- drake::systems::OutputPortIndex mpc_plan_port_;
-};
-
-} // namespace controllers
-} // namespace examples
-} // namespace dairlib
diff --git a/examples/franka/diagrams/franka_osc_controller_diagram.cc b/examples/franka/diagrams/franka_osc_controller_diagram.cc
deleted file mode 100644
index 21b8967d33..0000000000
--- a/examples/franka/diagrams/franka_osc_controller_diagram.cc
+++ /dev/null
@@ -1,267 +0,0 @@
-//
-// Created by yangwill on 2/19/24.
-//
-
-#include "examples/franka/diagrams/franka_osc_controller_diagram.h"
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "common/eigen_utils.h"
-#include "examples/franka/parameters/franka_lcm_channels.h"
-#include "examples/franka/parameters/franka_osc_controller_params.h"
-#include "systems/controllers/osc/end_effector_force.h"
-#include "systems/controllers/osc/end_effector_orientation.h"
-#include "systems/controllers/osc/end_effector_position.h"
-#include "lcm/lcm_trajectory.h"
-#include "multibody/multibody_utils.h"
-#include "systems/controllers/gravity_compensator.h"
-#include "systems/controllers/osc/operational_space_control.h"
-#include "systems/primitives/radio_parser.h"
-#include "systems/robot_lcm_systems.h"
-#include "systems/system_utils.h"
-#include "systems/trajectory_optimization/lcm_trajectory_systems.h"
-
-namespace dairlib {
-
-namespace examples {
-namespace controllers {
-
-using drake::SortedPair;
-using drake::geometry::GeometryId;
-using drake::math::RigidTransform;
-using drake::multibody::AddMultibodyPlantSceneGraph;
-using drake::multibody::MultibodyPlant;
-using drake::multibody::Parser;
-using drake::systems::DiagramBuilder;
-using drake::systems::TriggerType;
-using drake::systems::TriggerTypeSet;
-using drake::systems::lcm::LcmPublisherSystem;
-using drake::systems::lcm::LcmSubscriberSystem;
-using Eigen::MatrixXd;
-
-using Eigen::Vector3d;
-using Eigen::VectorXd;
-using multibody::MakeNameToPositionsMap;
-using multibody::MakeNameToVelocitiesMap;
-using std::string;
-
-FrankaOSCControllerDiagram::FrankaOSCControllerDiagram(
- const string& controller_settings, const string& lcm_channels,
- drake::lcm::DrakeLcm* lcm) {
- DiagramBuilder builder;
-
- // load parameters
- drake::yaml::LoadYamlOptions yaml_options;
- yaml_options.allow_yaml_with_no_cpp = true;
- FrankaControllerParams controller_params =
- drake::yaml::LoadYamlFile(controller_settings);
- FrankaLcmChannels lcm_channel_params =
- drake::yaml::LoadYamlFile(lcm_channels);
- OSCGains gains = drake::yaml::LoadYamlFile(
- FindResourceOrThrow(controller_settings), {}, {}, yaml_options);
- drake::solvers::SolverOptions solver_options =
- drake::yaml::LoadYamlFile(
- FindResourceOrThrow(
- "examples/franka/parameters/franka_osc_qp_settings.yaml"))
- .GetAsSolverOptions(drake::solvers::OsqpSolver::id());
-
- plant_ = new drake::multibody::MultibodyPlant(0.0);
- Parser parser(plant_, nullptr);
- parser.AddModelsFromUrl(controller_params.franka_model);
-
- RigidTransform X_WI = RigidTransform::Identity();
- plant_->WeldFrames(plant_->world_frame(),
- plant_->GetFrameByName("panda_link0"), X_WI);
-
- if (!controller_params.end_effector_name.empty()) {
- drake::multibody::ModelInstanceIndex end_effector_index = parser.AddModels(
- FindResourceOrThrow(controller_params.end_effector_model))[0];
- RigidTransform T_EE_W =
- RigidTransform(drake::math::RotationMatrix(),
- controller_params.tool_attachment_frame);
- plant_->WeldFrames(
- plant_->GetFrameByName("panda_link7"),
- plant_->GetFrameByName(controller_params.end_effector_name,
- end_effector_index),
- T_EE_W);
- } else {
- std::cout << "OSC plant has been constructed with no end effector."
- << std::endl;
- }
-
- plant_->Finalize();
- plant_context_ = plant_->CreateDefaultContext();
-
- auto state_receiver =
- builder.AddSystem(*plant_);
- auto end_effector_position_receiver =
- builder.AddSystem(
- "end_effector_position_target");
- auto end_effector_force_receiver =
- builder.AddSystem(
- "end_effector_force_target");
- auto end_effector_orientation_receiver =
- builder.AddSystem(
- "end_effector_orientation_target");
- auto franka_command_sender =
- builder.AddSystem(*plant_);
- auto osc_command_sender =
- builder.AddSystem(*plant_);
- auto end_effector_trajectory =
- builder.AddSystem(*plant_,
- plant_context_.get(), controller_params.neutral_position, false,
- controller_params.end_effector_name);
- auto passthrough = builder.AddSystem>(18);
- end_effector_trajectory->SetRemoteControlParameters(
- controller_params.neutral_position, controller_params.x_scale,
- controller_params.y_scale, controller_params.z_scale);
- auto end_effector_orientation_trajectory =
- builder.AddSystem();
- end_effector_orientation_trajectory->SetTrackOrientation(
- controller_params.track_end_effector_orientation);
- auto end_effector_force_trajectory =
- builder.AddSystem();
- auto osc = builder.AddSystem(
- *plant_, *plant_, plant_context_.get(), plant_context_.get(), false);
- if (controller_params.publish_debug_info) {
- auto franka_command_pub =
- builder.AddSystem(LcmPublisherSystem::Make(
- lcm_channel_params.franka_input_channel, lcm,
- TriggerTypeSet({TriggerType::kForced})));
- auto osc_command_pub =
- builder.AddSystem(LcmPublisherSystem::Make(
- lcm_channel_params.osc_channel, lcm,
- TriggerTypeSet({TriggerType::kForced})));
- auto osc_debug_pub =
- builder.AddSystem(LcmPublisherSystem::Make(
- lcm_channel_params.osc_debug_channel, lcm,
- TriggerTypeSet({TriggerType::kForced})));
- builder.Connect(osc->get_output_port_osc_debug(),
- osc_debug_pub->get_input_port());
- builder.Connect(franka_command_sender->get_output_port(),
- franka_command_pub->get_input_port());
- builder.Connect(osc_command_sender->get_output_port(),
- osc_command_pub->get_input_port());
- }
-
- auto end_effector_position_tracking_data =
- std::make_unique(
- "end_effector_target", controller_params.K_p_end_effector,
- controller_params.K_d_end_effector, controller_params.W_end_effector,
- *plant_, *plant_);
- end_effector_position_tracking_data->AddPointToTrack(
- controller_params.end_effector_name);
- const VectorXd& end_effector_acceleration_limits =
- controller_params.end_effector_acceleration * Vector3d::Ones();
- end_effector_position_tracking_data->SetCmdAccelerationBounds(
- -end_effector_acceleration_limits, end_effector_acceleration_limits);
- auto mid_link_position_tracking_data_for_rel =
- std::make_unique(
- "panda_joint2_target", controller_params.K_p_mid_link,
- controller_params.K_d_mid_link, controller_params.W_mid_link, *plant_,
- *plant_);
- mid_link_position_tracking_data_for_rel->AddJointToTrack("panda_joint2",
- "panda_joint2dot");
-
- auto end_effector_force_tracking_data =
- std::make_unique(
- "end_effector_force", controller_params.W_ee_lambda, *plant_, *plant_,
- controller_params.end_effector_name, Vector3d::Zero());
-
- auto end_effector_orientation_tracking_data =
- std::make_unique(
- "end_effector_orientation_target",
- controller_params.K_p_end_effector_rot,
- controller_params.K_d_end_effector_rot,
- controller_params.W_end_effector_rot, *plant_, *plant_);
- end_effector_orientation_tracking_data->AddFrameToTrack(
- controller_params.end_effector_name);
- Eigen::VectorXd orientation_target = Eigen::VectorXd::Zero(4);
- orientation_target(0) = 1;
- osc->AddTrackingData(std::move(end_effector_position_tracking_data));
- osc->AddConstTrackingData(std::move(mid_link_position_tracking_data_for_rel),
- 1.6 * VectorXd::Ones(1));
- osc->AddTrackingData(std::move(end_effector_orientation_tracking_data));
- osc->AddForceTrackingData(std::move(end_effector_force_tracking_data));
- osc->SetAccelerationCostWeights(gains.W_acceleration);
- osc->SetInputCostWeights(gains.W_input_regularization);
- osc->SetInputSmoothingCostWeights(gains.W_input_smoothing_regularization);
- osc->SetAccelerationConstraints(
- controller_params.enforce_acceleration_constraints);
-
- osc->SetContactFriction(controller_params.mu);
- osc->SetOsqpSolverOptions(solver_options);
-
- osc->Build();
-
- if (controller_params.cancel_gravity_compensation) {
- auto gravity_compensator =
- builder.AddSystem(*plant_,
- *plant_context_);
- builder.Connect(osc->get_output_port_osc_command(),
- gravity_compensator->get_input_port());
- builder.Connect(gravity_compensator->get_output_port(),
- franka_command_sender->get_input_port());
- } else {
- DRAKE_DEMAND(lcm_channels ==
- "examples/franka/parameters/lcm_channels_simulation.yaml");
- builder.Connect(osc->get_output_port_osc_command(),
- franka_command_sender->get_input_port(0));
- }
-
- builder.Connect(passthrough->get_output_port(),
- end_effector_trajectory->get_input_port_radio());
- builder.Connect(passthrough->get_output_port(),
- end_effector_orientation_trajectory->get_input_port_radio());
- builder.Connect(passthrough->get_output_port(),
- end_effector_force_trajectory->get_input_port_radio());
-
- builder.Connect(osc->get_output_port_osc_command(),
- osc_command_sender->get_input_port(0));
- builder.Connect(state_receiver->get_output_port(0),
- osc->get_input_port_robot_output());
- builder.Connect(end_effector_position_receiver->get_output_port(0),
- end_effector_trajectory->get_input_port_trajectory());
- builder.Connect(
- end_effector_orientation_receiver->get_output_port(0),
- end_effector_orientation_trajectory->get_input_port_trajectory());
- builder.Connect(end_effector_trajectory->get_output_port(0),
- osc->get_input_port_tracking_data("end_effector_target"));
- builder.Connect(
- end_effector_orientation_trajectory->get_output_port(0),
- osc->get_input_port_tracking_data("end_effector_orientation_target"));
- builder.Connect(end_effector_force_receiver->get_output_port(0),
- end_effector_force_trajectory->get_input_port_trajectory());
- builder.Connect(end_effector_force_trajectory->get_output_port(0),
- osc->get_input_port_tracking_data("end_effector_force"));
-
- // Publisher connections
- franka_state_port_ = builder.ExportInput(state_receiver->get_input_port(),
- "lcmt_robot_output");
- end_effector_position_port_ =
- builder.ExportInput(end_effector_position_receiver->get_input_port(),
- "end_effector_position: lcmt_timestamped_trajectory");
- end_effector_orientation_port_ = builder.ExportInput(
- end_effector_orientation_receiver->get_input_port(),
- "end_effector_orientation: lcmt_timestamped_trajectory");
- end_effector_force_port_ =
- builder.ExportInput(end_effector_force_receiver->get_input_port(),
- "end_effector_force: lcmt_timestamped_trajectory");
- radio_port_ = builder.ExportInput(passthrough->get_input_port(), "raw_radio");
- builder.ExportOutput(osc->get_output_port_osc_command(), "robot_input");
-
- builder.BuildInto(this);
- this->set_name("FrankaOSCController");
-}
-
-} // namespace controllers
-} // namespace examples
-} // namespace dairlib
diff --git a/examples/franka/diagrams/franka_osc_controller_diagram.h b/examples/franka/diagrams/franka_osc_controller_diagram.h
deleted file mode 100644
index 4c5a48e058..0000000000
--- a/examples/franka/diagrams/franka_osc_controller_diagram.h
+++ /dev/null
@@ -1,76 +0,0 @@
-#pragma once
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "systems/controllers/osc/joint_space_tracking_data.h"
-#include "systems/controllers/osc/relative_translation_tracking_data.h"
-#include "systems/controllers/osc/rot_space_tracking_data.h"
-#include "systems/controllers/osc/external_force_tracking_data.h"
-#include "systems/controllers/osc/trans_space_tracking_data.h"
-
-namespace dairlib {
-namespace examples {
-namespace controllers {
-
-using systems::controllers::JointSpaceTrackingData;
-using systems::controllers::RotTaskSpaceTrackingData;
-using systems::controllers::TransTaskSpaceTrackingData;
-using systems::controllers::ExternalForceTrackingData;
-
-class FrankaOSCControllerDiagram : public drake::systems::Diagram {
- public:
- DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FrankaOSCControllerDiagram)
-
- /// @param[in] osc_gains_filename filepath containing the osc_running_gains.
- /// @param[in] osqp_settings filepath containing the osqp settings.
- FrankaOSCControllerDiagram(const std::string& controller_settings,
- const std::string& lcm_channels,
- drake::lcm::DrakeLcm* lcm);
-
- /// @return the input port for the plant state.
- const drake::systems::InputPort& get_input_port_robot_state() const {
- return this->get_input_port(franka_state_port_);
- }
-
- const drake::systems::InputPort& get_input_port_end_effector_position() const {
- return this->get_input_port(end_effector_position_port_);
- }
-
- const drake::systems::InputPort& get_input_port_end_effector_orientation() const {
- return this->get_input_port(end_effector_orientation_port_);
- }
-
- const drake::systems::InputPort& get_input_port_end_effector_force() const {
- return this->get_input_port(end_effector_force_port_);
- }
-
- const drake::systems::InputPort& get_input_port_radio() const {
- return this->get_input_port(radio_port_);
- }
-
- /// @return the output port for the lcmt_robot_input message.
- const drake::systems::OutputPort& get_output_port_robot_input() const {
- return this->get_output_port(robot_input_port_);
- }
-
- private:
- drake::multibody::MultibodyPlant* plant_;
- std::unique_ptr> plant_context_;
-
- drake::systems::InputPortIndex franka_state_port_;
- drake::systems::InputPortIndex end_effector_position_port_;
- drake::systems::InputPortIndex end_effector_orientation_port_;
- drake::systems::InputPortIndex end_effector_force_port_;
- drake::systems::InputPortIndex radio_port_;
- const drake::systems::OutputPortIndex robot_input_port_ =
- drake::systems::OutputPortIndex(0);
-};
-
-} // namespace controllers
-} // namespace examples
-} // namespace dairlib
diff --git a/examples/franka/diagrams/franka_sim_diagram.cc b/examples/franka/diagrams/franka_sim_diagram.cc
deleted file mode 100644
index 584acef837..0000000000
--- a/examples/franka/diagrams/franka_sim_diagram.cc
+++ /dev/null
@@ -1,141 +0,0 @@
-
-#include "franka_sim_diagram.h"
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "common/find_resource.h"
-#include "examples/franka/parameters/franka_lcm_channels.h"
-#include "examples/franka/parameters/franka_sim_params.h"
-#include "examples/franka/parameters/franka_sim_scene_params.h"
-#include "systems/robot_lcm_systems.h"
-
-namespace dairlib {
-namespace examples {
-using drake::systems::lcm::LcmPublisherSystem;
-
-using drake::geometry::GeometrySet;
-using drake::math::RigidTransform;
-using drake::multibody::AddMultibodyPlantSceneGraph;
-using drake::systems::DiagramBuilder;
-
-FrankaSimDiagram::FrankaSimDiagram(std::unique_ptr> plant,
- drake::lcm::DrakeLcm* lcm) {
- // load parameters
- DiagramBuilder builder;
- scene_graph_ = builder.AddSystem();
- scene_graph_->set_name("scene_graph");
- FrankaSimParams sim_params = drake::yaml::LoadYamlFile(
- "examples/franka/parameters/franka_sim_params.yaml");
- FrankaLcmChannels lcm_channel_params =
- drake::yaml::LoadYamlFile("examples/franka/parameters/lcm_channels_simulation.yaml");
- FrankaSimSceneParams scene_params =
- drake::yaml::LoadYamlFile(
- sim_params.sim_scene_file[sim_params.scene_index]);
- /// Sim Start
- plant_ = builder.AddSystem(std::move(plant));
-
- auto parser = drake::multibody::Parser(plant_, scene_graph_);
-// lcs_diagram_builder.parser() lcs_diagram_builder.parser()(&plant);
- parser.SetAutoRenaming(true);
- drake::multibody::ModelInstanceIndex franka_index =
- parser.AddModelsFromUrl(sim_params.franka_model)[0];
- drake::multibody::ModelInstanceIndex c3_end_effector_index =
- parser.AddModels(FindResourceOrThrow(sim_params.end_effector_model))[0];
- drake::multibody::ModelInstanceIndex tray_index =
- parser.AddModels(FindResourceOrThrow(sim_params.tray_model))[0];
-
- RigidTransform T_X_W = RigidTransform(
- drake::math::RotationMatrix(), Eigen::VectorXd::Zero(3));
- RigidTransform T_EE_W = RigidTransform(
- drake::math::RotationMatrix(), sim_params.tool_attachment_frame);
- plant_->WeldFrames(plant_->world_frame(), plant_->GetFrameByName("panda_link0"),
- T_X_W);
- plant_->WeldFrames(plant_->GetFrameByName("panda_link7"),
- plant_->GetFrameByName("plate", c3_end_effector_index),
- T_EE_W);
-
- // we WANT to model collisions between link5 and the supports
- const drake::geometry::GeometrySet& franka_geom_set =
- plant->CollectRegisteredGeometries({&plant->GetBodyByName("panda_link0"),
- &plant->GetBodyByName("panda_link1"),
- &plant->GetBodyByName("panda_link2"),
- &plant->GetBodyByName("panda_link3"),
- &plant->GetBodyByName("panda_link4")});
- drake::geometry::GeometrySet support_geom_set;
- std::vector environment_model_indices;
- environment_model_indices.resize(scene_params.environment_models.size());
- for (int i = 0; i < scene_params.environment_models.size(); ++i) {
- environment_model_indices[i] = parser.AddModels(
- FindResourceOrThrow(scene_params.environment_models[i]))[0];
- RigidTransform T_E_W =
- RigidTransform(drake::math::RollPitchYaw(
- scene_params.environment_orientations[i]),
- scene_params.environment_positions[i]);
- plant->WeldFrames(
- plant->world_frame(),
- plant->GetFrameByName("base", environment_model_indices[i]),
- T_E_W);
- support_geom_set.Add(plant->GetCollisionGeometriesForBody(plant->GetBodyByName("base",
- environment_model_indices[i])));
- }
- plant->ExcludeCollisionGeometriesWithCollisionFilterGroupPair(
- {"supports", support_geom_set}, {"franka", franka_geom_set});
-
- const drake::geometry::GeometrySet& paddle_geom_set =
- plant_->CollectRegisteredGeometries({
- &plant_->GetBodyByName("panda_link2"),
- &plant_->GetBodyByName("panda_link3"),
- &plant_->GetBodyByName("panda_link4"),
- &plant_->GetBodyByName("panda_link5"),
- &plant_->GetBodyByName("panda_link6"),
- &plant_->GetBodyByName("panda_link8"),
- });
- auto tray_collision_set = GeometrySet(
- plant_->GetCollisionGeometriesForBody(plant_->GetBodyByName("tray")));
- plant_->ExcludeCollisionGeometriesWithCollisionFilterGroupPair(
- {"paddle", paddle_geom_set}, {"tray", tray_collision_set});
-
- plant_->Finalize();
- auto tray_state_sender =
- builder.AddSystem(*plant_, tray_index);
- auto franka_state_sender =
- builder.AddSystem(*plant_, franka_index, false);
-
- // for lcm debugging
- auto state_pub =
- builder.AddSystem(LcmPublisherSystem::Make(
- lcm_channel_params.franka_state_channel, lcm,
- drake::systems::TriggerTypeSet(
- {drake::systems::TriggerType::kForced})));
- auto tray_state_pub =
- builder.AddSystem(LcmPublisherSystem::Make(
- lcm_channel_params.tray_state_channel, lcm,
- drake::systems::TriggerTypeSet(
- {drake::systems::TriggerType::kForced})));
- builder.Connect(plant_->get_state_output_port(tray_index),
- tray_state_sender->get_input_port_state());
- builder.Connect(plant_->get_state_output_port(franka_index),
- franka_state_sender->get_input_port_state());
- builder.Connect(*franka_state_sender, *state_pub);
- builder.Connect(*tray_state_sender, *tray_state_pub);
- // end lcm debugging
-
- actuation_port_ = builder.ExportInput(plant_->get_actuation_input_port(),
- "franka_sim: robot_efforts");
- tray_state_port_ = builder.ExportOutput(tray_state_sender->get_output_port(),
- "franka_sim: tray_state");
- franka_state_port_ = builder.ExportOutput(franka_state_sender->get_output_port(),
- "franka_sim: franka_state");
-
- builder.BuildInto(this);
- this->set_name("FrankaSim");
-
-}
-} // namespace examples
-} // namespace dairlib
\ No newline at end of file
diff --git a/examples/franka/diagrams/franka_sim_diagram.h b/examples/franka/diagrams/franka_sim_diagram.h
deleted file mode 100644
index daf0d8f235..0000000000
--- a/examples/franka/diagrams/franka_sim_diagram.h
+++ /dev/null
@@ -1,55 +0,0 @@
-#pragma once
-
-#include
-#include
-
-#include
-#include
-#include
-
-#include "drake/common/drake_copyable.h"
-#include "drake/systems/framework/diagram.h"
-#include "drake/systems/framework/diagram_builder.h"
-#include "drake/systems/framework/system.h"
-
-namespace dairlib {
-namespace examples {
-
-class FrankaSimDiagram : public drake::systems::Diagram {
- public:
- DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FrankaSimDiagram)
-
- /// @param[in] urdf filepath containing the osc_running_gains.
- FrankaSimDiagram(
- std::unique_ptr> plant,
- drake::lcm::DrakeLcm* lcm);
-
- /// @return the input port for the actuation command.
- const drake::systems::InputPort& get_input_port_actuation() const {
- return this->get_input_port(actuation_port_);
- }
-
- /// @return the output port for the plant state as an OutputVector.
- const drake::systems::OutputPort& get_output_port_tray_state() const {
- return this->get_output_port(tray_state_port_);
- }
-
- /// @return the output port for the plant state as an OutputVector.
- const drake::systems::OutputPort& get_output_port_franka_state()
- const {
- return this->get_output_port(franka_state_port_);
- }
-
- const drake::multibody::MultibodyPlant& get_plant() { return *plant_; }
-
- private:
- drake::multibody::MultibodyPlant* plant_;
- drake::geometry::SceneGraph* scene_graph_;
-
- drake::systems::InputPortIndex actuation_port_;
- drake::systems::OutputPortIndex tray_state_port_;
- drake::systems::OutputPortIndex franka_state_port_;
-};
-
-} // namespace examples
-} // namespace dairlib
diff --git a/examples/franka/diagrams/full_diagram.cc b/examples/franka/diagrams/full_diagram.cc
deleted file mode 100644
index a7857cd503..0000000000
--- a/examples/franka/diagrams/full_diagram.cc
+++ /dev/null
@@ -1,146 +0,0 @@
-
-#include
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "common/eigen_utils.h"
-#include "common/find_resource.h"
-#include "examples/franka/diagrams/franka_c3_controller_diagram.h"
-#include "examples/franka/diagrams/franka_osc_controller_diagram.h"
-#include "examples/franka/diagrams/franka_sim_diagram.h"
-#include "examples/franka/parameters/franka_lcm_channels.h"
-#include "examples/franka/parameters/franka_sim_params.h"
-#include "multibody/multibody_utils.h"
-#include "systems/primitives/subvector_pass_through.h"
-#include "systems/robot_lcm_systems.h"
-#include "systems/system_utils.h"
-namespace dairlib {
-
-using drake::geometry::GeometrySet;
-using drake::math::RigidTransform;
-using drake::multibody::AddMultibodyPlantSceneGraph;
-using drake::multibody::Parser;
-using drake::systems::DiagramBuilder;
-using drake::systems::lcm::LcmPublisherSystem;
-using drake::systems::lcm::LcmSubscriberSystem;
-using Eigen::VectorXd;
-using examples::controllers::FrankaC3ControllerDiagram;
-using examples::controllers::FrankaOSCControllerDiagram;
-using systems::RobotInputReceiver;
-using systems::RobotOutputSender;
-using systems::SubvectorPassThrough;
-
-int DoMain(int argc, char* argv[]) {
- drake::lcm::DrakeLcm lcm("udpm://239.255.76.67:7667?ttl=0");
-
- drake::yaml::LoadYamlOptions yaml_options;
- yaml_options.allow_yaml_with_no_cpp = true;
- FrankaLcmChannels lcm_channel_params =
- drake::yaml::LoadYamlFile(
- "examples/franka/parameters/lcm_channels_simulation.yaml");
- FrankaSimParams sim_params = drake::yaml::LoadYamlFile(
- "examples/franka/parameters/franka_sim_params.yaml");
-
- DiagramBuilder builder;
- std::unique_ptr> sim_plant =
- std::make_unique>(sim_params.dt);
-
- auto franka_sim =
- builder.AddSystem(std::move(sim_plant), &lcm);
-
- /// OSC
- auto osc_controller = builder.AddSystem(
- "examples/franka/parameters/franka_osc_controller_params.yaml",
- "examples/franka/parameters/lcm_channels_simulation.yaml", &lcm);
-
- /// C3 plant
- auto c3_controller = builder.AddSystem(
- "examples/franka/parameters/franka_c3_controller_params.yaml",
- "examples/franka/parameters/lcm_channels_simulation.yaml", &lcm);
-
- /* -------------------------------------------------------------------------------------------*/
- auto passthrough = builder.AddSystem(
- osc_controller->get_output_port_robot_input().size(), 0,
- franka_sim->get_input_port_actuation().size());
- auto radio_sub =
- builder.AddSystem(LcmSubscriberSystem::Make(
- lcm_channel_params.radio_channel, &lcm));
-
- //// OSC connections
-
- // Diagram Connections
- builder.Connect(osc_controller->get_output_port_robot_input(),
- passthrough->get_input_port());
- builder.Connect(c3_controller->get_output_port_mpc_plan(),
- osc_controller->get_input_port_end_effector_position());
- builder.Connect(c3_controller->get_output_port_mpc_plan(),
- osc_controller->get_input_port_end_effector_orientation());
- builder.Connect(c3_controller->get_output_port_mpc_plan(),
- osc_controller->get_input_port_end_effector_force());
-
- builder.Connect(franka_sim->get_output_port_franka_state(),
- osc_controller->get_input_port_robot_state());
- builder.Connect(franka_sim->get_output_port_franka_state(),
- c3_controller->get_input_port_robot_state());
- builder.Connect(franka_sim->get_output_port_tray_state(),
- c3_controller->get_input_ports_object_state()[0]);
-
- builder.Connect(radio_sub->get_output_port(),
- c3_controller->get_input_port_radio());
- builder.Connect(radio_sub->get_output_port(),
- osc_controller->get_input_port_radio());
-
- builder.Connect(passthrough->get_output_port(),
- franka_sim->get_input_port_actuation());
-
- auto diagram = builder.Build();
- diagram->set_name("plate_balancing_full_diagram");
- DrawAndSaveDiagramGraph(*diagram);
-
- drake::systems::Simulator simulator(*diagram);
-
- simulator.set_publish_every_time_step(true);
- simulator.set_publish_at_initialization(true);
- simulator.set_target_realtime_rate(sim_params.realtime_rate);
-
-
- auto diagram_context = diagram->CreateDefaultContext();
- auto& plant = franka_sim->get_plant();
- auto& plant_context =
- diagram->GetMutableSubsystemContext(plant, diagram_context.get());
- int nq = plant.num_positions();
- int nv = plant.num_velocities();
- VectorXd q = VectorXd::Zero(nq);
- q.head(7) = sim_params.q_init_franka;
-
- q.tail(7) = sim_params.q_init_tray[sim_params.scene_index];
-
- plant.SetPositions(&plant_context, q);
-
- VectorXd v = VectorXd::Zero(nv);
- plant.SetVelocities(&plant_context, v);
-
- simulator.Initialize();
- simulator.AdvanceTo(std::numeric_limits::infinity());
-
- return 0;
-}
-
-} // namespace dairlib
-
-int main(int argc, char* argv[]) { dairlib::DoMain(argc, argv); }
diff --git a/examples/franka/forward_kinematics_for_lcs.cc b/examples/franka/forward_kinematics_for_lcs.cc
deleted file mode 100644
index c9fdca0831..0000000000
--- a/examples/franka/forward_kinematics_for_lcs.cc
+++ /dev/null
@@ -1,204 +0,0 @@
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "common/eigen_utils.h"
-#include "examples/franka/parameters/franka_c3_controller_params.h"
-#include "examples/franka/parameters/franka_c3_scene_params.h"
-#include "examples/franka/parameters/franka_lcm_channels.h"
-#include "systems/senders/c3_state_sender.h"
-#include "examples/franka/systems/c3_trajectory_generator.h"
-#include "systems/franka_kinematics.h"
-#include "examples/franka/systems/plate_balancing_target.h"
-#include "multibody/multibody_utils.h"
-#include "solvers/lcs_factory.h"
-#include "systems/controllers/c3/lcs_factory_system.h"
-#include "systems/framework/lcm_driven_loop.h"
-#include "systems/primitives/radio_parser.h"
-#include "systems/robot_lcm_systems.h"
-#include "systems/system_utils.h"
-
-namespace dairlib {
-
-using dairlib::solvers::LCSFactory;
-using drake::SortedPair;
-using drake::geometry::GeometryId;
-using drake::math::RigidTransform;
-using drake::multibody::AddMultibodyPlantSceneGraph;
-using drake::multibody::MultibodyPlant;
-using drake::multibody::Parser;
-using drake::systems::DiagramBuilder;
-using drake::systems::TriggerType;
-using drake::systems::TriggerTypeSet;
-using drake::systems::lcm::LcmPublisherSystem;
-using drake::systems::lcm::LcmSubscriberSystem;
-using Eigen::MatrixXd;
-
-using Eigen::Vector3d;
-using Eigen::VectorXd;
-using multibody::MakeNameToPositionsMap;
-using multibody::MakeNameToVelocitiesMap;
-
-DEFINE_string(controller_settings,
- "examples/franka/parameters/franka_c3_controller_params.yaml",
- "Controller settings such as channels. Attempting to minimize "
- "number of gflags");
-DEFINE_string(lcm_channels,
- "examples/franka/parameters/lcm_channels_simulation.yaml",
- "Filepath containing lcm channels");
-
-int DoMain(int argc, char* argv[]) {
- gflags::ParseCommandLineFlags(&argc, &argv, true);
- drake::lcm::DrakeLcm lcm("udpm://239.255.76.67:7667?ttl=0");
-
- // load parameters
- drake::yaml::LoadYamlOptions yaml_options;
- yaml_options.allow_yaml_with_no_cpp = true;
- FrankaC3ControllerParams controller_params =
- drake::yaml::LoadYamlFile(
- FLAGS_controller_settings);
- FrankaC3SceneParams scene_params =
- drake::yaml::LoadYamlFile(
- controller_params.c3_scene_file[controller_params.scene_index]);
- FrankaLcmChannels lcm_channel_params =
- drake::yaml::LoadYamlFile(FLAGS_lcm_channels);
-
- DiagramBuilder plant_builder;
-
- MultibodyPlant plant_franka(0.0);
- Parser parser_franka(&plant_franka, nullptr);
- parser_franka.AddModelsFromUrl(scene_params.franka_model);
- drake::multibody::ModelInstanceIndex end_effector_index =
- parser_franka.AddModels(
- FindResourceOrThrow(scene_params.end_effector_model))[0];
-
- RigidTransform X_WI = RigidTransform::Identity();
- plant_franka.WeldFrames(plant_franka.world_frame(),
- plant_franka.GetFrameByName("panda_link0"), X_WI);
-
- RigidTransform T_EE_W =
- RigidTransform