AutoBalancer.cpp
Go to the documentation of this file.
00001 // -*- C++ -*-
00010 #include <rtm/CorbaNaming.h>
00011 #include <hrpModel/Link.h>
00012 #include <hrpModel/Sensor.h>
00013 #include <hrpModel/ModelLoaderUtil.h>
00014 #include "AutoBalancer.h"
00015 #include <hrpModel/JointPath.h>
00016 #include <hrpUtil/MatrixSolvers.h>
00017 #include "hrpsys/util/Hrpsys.h"
00018 
00019 
00020 typedef coil::Guard<coil::Mutex> Guard;
00021 using namespace rats;
00022 
00023 // Module specification
00024 // <rtc-template block="module_spec">
00025 static const char* autobalancer_spec[] =
00026     {
00027         "implementation_id", "AutoBalancer",
00028         "type_name",         "AutoBalancer",
00029         "description",       "autobalancer component",
00030         "version",           HRPSYS_PACKAGE_VERSION,
00031         "vendor",            "AIST",
00032         "category",          "example",
00033         "activity_type",     "DataFlowComponent",
00034         "max_instance",      "10",
00035         "language",          "C++",
00036         "lang_type",         "compile",
00037         // Configuration variables
00038         "conf.default.debugLevel", "0",
00039         ""
00040     };
00041 // </rtc-template>
00042 
00043 static std::ostream& operator<<(std::ostream& os, const struct RTC::Time &tm)
00044 {
00045     int pre = os.precision();
00046     os.setf(std::ios::fixed);
00047     os << std::setprecision(6)
00048        << (tm.sec + tm.nsec/1e9)
00049        << std::setprecision(pre);
00050     os.unsetf(std::ios::fixed);
00051     return os;
00052 }
00053 
00054 AutoBalancer::AutoBalancer(RTC::Manager* manager)
00055     : RTC::DataFlowComponentBase(manager),
00056       // <rtc-template block="initializer">
00057       m_qRefIn("qRef", m_qRef),
00058       m_basePosIn("basePosIn", m_basePos),
00059       m_baseRpyIn("baseRpyIn", m_baseRpy),
00060       m_zmpIn("zmpIn", m_zmp),
00061       m_optionalDataIn("optionalData", m_optionalData),
00062       m_emergencySignalIn("emergencySignal", m_emergencySignal),
00063       m_diffCPIn("diffCapturePoint", m_diffCP),
00064       m_refFootOriginExtMomentIn("refFootOriginExtMoment", m_refFootOriginExtMoment),
00065       m_refFootOriginExtMomentIsHoldValueIn("refFootOriginExtMomentIsHoldValue", m_refFootOriginExtMomentIsHoldValue),
00066       m_actContactStatesIn("actContactStates", m_actContactStates),
00067       m_qOut("q", m_qRef),
00068       m_zmpOut("zmpOut", m_zmp),
00069       m_basePosOut("basePosOut", m_basePos),
00070       m_baseRpyOut("baseRpyOut", m_baseRpy),
00071       m_baseTformOut("baseTformOut", m_baseTform),
00072       m_basePoseOut("basePoseOut", m_basePose),
00073       m_accRefOut("accRef", m_accRef),
00074       m_contactStatesOut("contactStates", m_contactStates),
00075       m_toeheelRatioOut("toeheelRatio", m_toeheelRatio),
00076       m_controlSwingSupportTimeOut("controlSwingSupportTime", m_controlSwingSupportTime),
00077       m_walkingStatesOut("walkingStates", m_walkingStates),
00078       m_sbpCogOffsetOut("sbpCogOffset", m_sbpCogOffset),
00079       m_cogOut("cogOut", m_cog),
00080       m_AutoBalancerServicePort("AutoBalancerService"),
00081       // </rtc-template>
00082       gait_type(BIPED),
00083       m_robot(hrp::BodyPtr()),
00084       m_debugLevel(0)
00085 {
00086     m_service0.autobalancer(this);
00087 }
00088 
00089 AutoBalancer::~AutoBalancer()
00090 {
00091 }
00092 
00093 
00094 RTC::ReturnCode_t AutoBalancer::onInitialize()
00095 {
00096     std::cerr << "[" << m_profile.instance_name << "] onInitialize()" << std::endl;
00097     bindParameter("debugLevel", m_debugLevel, "0");
00098 
00099     // Registration: InPort/OutPort/Service
00100     // <rtc-template block="registration">
00101     // Set InPort buffers
00102     addInPort("qRef", m_qRefIn);
00103     addInPort("basePosIn", m_basePosIn);
00104     addInPort("baseRpyIn", m_baseRpyIn);
00105     addInPort("zmpIn", m_zmpIn);
00106     addInPort("optionalData", m_optionalDataIn);
00107     addInPort("emergencySignal", m_emergencySignalIn);
00108     addInPort("diffCapturePoint", m_diffCPIn);
00109     addInPort("actContactStates", m_actContactStatesIn);
00110     addInPort("refFootOriginExtMoment", m_refFootOriginExtMomentIn);
00111     addInPort("refFootOriginExtMomentIsHoldValue", m_refFootOriginExtMomentIsHoldValueIn);
00112 
00113     // Set OutPort buffer
00114     addOutPort("q", m_qOut);
00115     addOutPort("zmpOut", m_zmpOut);
00116     addOutPort("basePosOut", m_basePosOut);
00117     addOutPort("baseRpyOut", m_baseRpyOut);
00118     addOutPort("baseTformOut", m_baseTformOut);
00119     addOutPort("basePoseOut", m_basePoseOut);
00120     addOutPort("accRef", m_accRefOut);
00121     addOutPort("contactStates", m_contactStatesOut);
00122     addOutPort("toeheelRatio", m_toeheelRatioOut);
00123     addOutPort("controlSwingSupportTime", m_controlSwingSupportTimeOut);
00124     addOutPort("cogOut", m_cogOut);
00125     addOutPort("walkingStates", m_walkingStatesOut);
00126     addOutPort("sbpCogOffset", m_sbpCogOffsetOut);
00127   
00128     // Set service provider to Ports
00129     m_AutoBalancerServicePort.registerProvider("service0", "AutoBalancerService", m_service0);
00130   
00131     // Set service consumers to Ports
00132   
00133     // Set CORBA Service Ports
00134     addPort(m_AutoBalancerServicePort);
00135   
00136     // </rtc-template>
00137     // <rtc-template block="bind_config">
00138     // Bind variables and configuration variable
00139   
00140     // </rtc-template>
00141 
00142     RTC::Properties& prop =  getProperties();
00143     coil::stringTo(m_dt, prop["dt"].c_str());
00144 
00145     m_robot = hrp::BodyPtr(new hrp::Body());
00146     RTC::Manager& rtcManager = RTC::Manager::instance();
00147     std::string nameServer = rtcManager.getConfig()["corba.nameservers"];
00148     int comPos = nameServer.find(",");
00149     if (comPos < 0){
00150         comPos = nameServer.length();
00151     }
00152     nameServer = nameServer.substr(0, comPos);
00153     RTC::CorbaNaming naming(rtcManager.getORB(), nameServer.c_str());
00154     if (!loadBodyFromModelLoader(m_robot, prop["model"].c_str(), 
00155                                  CosNaming::NamingContext::_duplicate(naming.getRootContext())
00156                                  )){
00157       std::cerr << "[" << m_profile.instance_name << "] failed to load model[" << prop["model"] << "]" << std::endl;
00158       return RTC::RTC_ERROR;
00159     }
00160 
00161     // allocate memory for outPorts
00162     m_qRef.data.length(m_robot->numJoints());
00163     m_baseTform.data.length(12);
00164 
00165     control_mode = MODE_IDLE;
00166     loop = 0;
00167 
00168     // setting from conf file
00169     // GaitGenerator requires abc_leg_offset and abc_stride_parameter in robot conf file
00170     // setting leg_pos from conf file
00171     coil::vstring leg_offset_str = coil::split(prop["abc_leg_offset"], ",");
00172     leg_names.push_back("rleg");
00173     leg_names.push_back("lleg");
00174 
00175     // Generate FIK
00176     fik = fikPtr(new SimpleFullbodyInverseKinematicsSolver(m_robot, std::string(m_profile.instance_name), m_dt));
00177 
00178     // setting from conf file
00179     // rleg,TARGET_LINK,BASE_LINK
00180     coil::vstring end_effectors_str = coil::split(prop["end_effectors"], ",");
00181     size_t prop_num = 10;
00182     if (end_effectors_str.size() > 0) {
00183       size_t num = end_effectors_str.size()/prop_num;
00184       for (size_t i = 0; i < num; i++) {
00185         std::string ee_name, ee_target, ee_base;
00186         coil::stringTo(ee_name, end_effectors_str[i*prop_num].c_str());
00187         coil::stringTo(ee_target, end_effectors_str[i*prop_num+1].c_str());
00188         coil::stringTo(ee_base, end_effectors_str[i*prop_num+2].c_str());
00189         ABCIKparam tp;
00190         hrp::Link* root = m_robot->link(ee_target);
00191         for (size_t j = 0; j < 3; j++) {
00192           coil::stringTo(tp.localPos(j), end_effectors_str[i*prop_num+3+j].c_str());
00193         }
00194         double tmpv[4];
00195         for (int j = 0; j < 4; j++ ) {
00196           coil::stringTo(tmpv[j], end_effectors_str[i*prop_num+6+j].c_str());
00197         }
00198         tp.localR = Eigen::AngleAxis<double>(tmpv[3], hrp::Vector3(tmpv[0], tmpv[1], tmpv[2])).toRotationMatrix(); // rotation in VRML is represented by axis + angle
00199         // FIK param
00200         SimpleFullbodyInverseKinematicsSolver::IKparam tmp_fikp;
00201         tmp_fikp.manip = hrp::JointPathExPtr(new hrp::JointPathEx(m_robot, m_robot->link(ee_base), m_robot->link(ee_target), m_dt, false, std::string(m_profile.instance_name)));
00202         tmp_fikp.target_link = m_robot->link(ee_target);
00203         tmp_fikp.localPos = tp.localPos;
00204         tmp_fikp.localR = tp.localR;
00205         tmp_fikp.max_limb_length = 0.0;
00206         while (!root->isRoot()) {
00207           tmp_fikp.max_limb_length += root->b.norm();
00208           tmp_fikp.parent_name = root->name;
00209           root = root->parent;
00210         }
00211         fik->ikp.insert(std::pair<std::string, SimpleFullbodyInverseKinematicsSolver::IKparam>(ee_name, tmp_fikp));
00212         // Fix for toe joint
00213         //   Toe joint is defined as end-link joint in the case that end-effector link != force-sensor link
00214         //   Without toe joints, "end-effector link == force-sensor link" is assumed.
00215         //   With toe joints, "end-effector link != force-sensor link" is assumed.
00216         if (m_robot->link(ee_target)->sensors.size() == 0) { // If end-effector link has no force sensor
00217             std::vector<double> optw(fik->ikp[ee_name].manip->numJoints(), 1.0);
00218             optw.back() = 0.0; // Set weight = 0 for toe joint by default
00219             fik->ikp[ee_name].manip->setOptionalWeightVector(optw);
00220             tp.has_toe_joint = true;
00221         } else {
00222             tp.has_toe_joint = false;
00223         }
00224         tp.target_link = m_robot->link(ee_target);
00225         ikp.insert(std::pair<std::string, ABCIKparam>(ee_name , tp));
00226         ee_vec.push_back(ee_name);
00227         std::cerr << "[" << m_profile.instance_name << "] End Effector [" << ee_name << "]" << std::endl;
00228         std::cerr << "[" << m_profile.instance_name << "]   target = " << ikp[ee_name].target_link->name << ", base = " << ee_base << std::endl;
00229         std::cerr << "[" << m_profile.instance_name << "]   offset_pos = " << tp.localPos.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "    [", "]")) << "[m]" << std::endl;
00230         std::cerr << "[" << m_profile.instance_name << "]   has_toe_joint = " << (tp.has_toe_joint?"true":"false") << std::endl;
00231         contact_states_index_map.insert(std::pair<std::string, size_t>(ee_name, i));
00232       }
00233       m_contactStates.data.length(num);
00234       m_toeheelRatio.data.length(num);
00235       if (ikp.find("rleg") != ikp.end() && ikp.find("lleg") != ikp.end()) {
00236         m_contactStates.data[contact_states_index_map["rleg"]] = true;
00237         m_contactStates.data[contact_states_index_map["lleg"]] = true;
00238       }
00239       if (ikp.find("rarm") != ikp.end() && ikp.find("larm") != ikp.end()) {
00240         m_contactStates.data[contact_states_index_map["rarm"]] = false;
00241         m_contactStates.data[contact_states_index_map["larm"]] = false;
00242       }
00243       m_controlSwingSupportTime.data.length(num);
00244       for (size_t i = 0; i < num; i++) m_controlSwingSupportTime.data[i] = 1.0;
00245       for (size_t i = 0; i < num; i++) m_toeheelRatio.data[i] = rats::no_using_toe_heel_ratio;
00246     }
00247     std::vector<hrp::Vector3> leg_pos;
00248     if (leg_offset_str.size() > 0) {
00249       hrp::Vector3 leg_offset;
00250       for (size_t i = 0; i < 3; i++) coil::stringTo(leg_offset(i), leg_offset_str[i].c_str());
00251       std::cerr << "[" << m_profile.instance_name << "] abc_leg_offset = " << leg_offset.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "    [", "]")) << "[m]" << std::endl;
00252       leg_pos.push_back(hrp::Vector3(-1*leg_offset));
00253       leg_pos.push_back(hrp::Vector3(leg_offset));
00254     }
00255     if (leg_pos.size() < ikp.size()) {
00256         size_t tmp_leg_pos_size = leg_pos.size();
00257         for (size_t i = 0; i < ikp.size() - tmp_leg_pos_size; i++) {
00258             leg_pos.push_back(hrp::Vector3::Zero());
00259         }
00260     }
00261 
00262     std::vector<std::pair<hrp::Link*, hrp::Link*> > interlocking_joints;
00263     readInterlockingJointsParamFromProperties(interlocking_joints, m_robot, prop["interlocking_joints"], std::string(m_profile.instance_name));
00264     if (interlocking_joints.size() > 0) {
00265         fik->initializeInterlockingJoints(interlocking_joints);
00266     }
00267 
00268     zmp_offset_interpolator = new interpolator(ikp.size()*3, m_dt);
00269     zmp_offset_interpolator->setName(std::string(m_profile.instance_name)+" zmp_offset_interpolator");
00270     zmp_transition_time = 1.0;
00271     transition_interpolator = new interpolator(1, m_dt, interpolator::HOFFARBIB, 1);
00272     transition_interpolator->setName(std::string(m_profile.instance_name)+" transition_interpolator");
00273     transition_interpolator_ratio = 0.0;
00274     adjust_footstep_interpolator = new interpolator(1, m_dt, interpolator::HOFFARBIB, 1);
00275     adjust_footstep_interpolator->setName(std::string(m_profile.instance_name)+" adjust_footstep_interpolator");
00276     transition_time = 2.0;
00277     adjust_footstep_transition_time = 2.0;
00278     leg_names_interpolator = new interpolator(1, m_dt, interpolator::HOFFARBIB, 1);
00279     leg_names_interpolator->setName(std::string(m_profile.instance_name)+" leg_names_interpolator");
00280     leg_names_interpolator_ratio = 1.0;
00281 
00282     // setting stride limitations from conf file
00283     double stride_fwd_x_limit = 0.15;
00284     double stride_outside_y_limit = 0.05;
00285     double stride_outside_th_limit = 10;
00286     double stride_bwd_x_limit = 0.05;
00287     double stride_inside_y_limit = stride_outside_y_limit*0.5;
00288     double stride_inside_th_limit = stride_outside_th_limit*0.5;
00289     std::cerr << "[" << m_profile.instance_name << "] abc_stride_parameter : " << stride_fwd_x_limit << "[m], " << stride_outside_y_limit << "[m], " << stride_outside_th_limit << "[deg], " << stride_bwd_x_limit << "[m]" << std::endl;
00290     if (default_zmp_offsets.size() == 0) {
00291       for (size_t i = 0; i < ikp.size(); i++) default_zmp_offsets.push_back(hrp::Vector3::Zero());
00292     }
00293     if (leg_offset_str.size() > 0) {
00294       gg = ggPtr(new rats::gait_generator(m_dt, leg_pos, leg_names, stride_fwd_x_limit/*[m]*/, stride_outside_y_limit/*[m]*/, stride_outside_th_limit/*[deg]*/,
00295                                           stride_bwd_x_limit/*[m]*/, stride_inside_y_limit/*[m]*/, stride_inside_th_limit/*[m]*/));
00296       gg->set_default_zmp_offsets(default_zmp_offsets);
00297     }
00298     gg_is_walking = gg_solved = false;
00299     m_walkingStates.data = false;
00300     fix_leg_coords = coordinates();
00301 
00302     // load virtual force sensors
00303     readVirtualForceSensorParamFromProperties(m_vfs, m_robot, prop["virtual_force_sensor"], std::string(m_profile.instance_name));
00304     // ref force port
00305     unsigned int npforce = m_robot->numSensors(hrp::Sensor::FORCE);
00306     unsigned int nvforce = m_vfs.size();
00307     unsigned int nforce  = npforce + nvforce;
00308     // check number of force sensors
00309     if (nforce < m_contactStates.data.length()) {
00310         std::cerr << "[" << m_profile.instance_name << "] WARNING! This robot model has less force sensors(" << nforce;
00311         std::cerr << ") than end-effector settings(" << m_contactStates.data.length() << ") !" << std::endl;
00312     }
00313 
00314     m_ref_force.resize(nforce);
00315     m_ref_forceIn.resize(nforce);
00316     m_force.resize(nforce);
00317     m_ref_forceOut.resize(nforce);
00318     m_limbCOPOffset.resize(nforce);
00319     m_limbCOPOffsetOut.resize(nforce);
00320     for (unsigned int i=0; i<npforce; i++){
00321         sensor_names.push_back(m_robot->sensor(hrp::Sensor::FORCE, i)->name);
00322     }
00323     for (unsigned int i=0; i<nvforce; i++){
00324         for ( std::map<std::string, hrp::VirtualForceSensorParam>::iterator it = m_vfs.begin(); it != m_vfs.end(); it++ ) {
00325             if (it->second.id == (int)i) sensor_names.push_back(it->first);
00326         }
00327     }
00328     // set ref force port
00329     std::cerr << "[" << m_profile.instance_name << "] force sensor ports (" << nforce << ")" << std::endl;
00330     for (unsigned int i=0; i<nforce; i++){
00331         m_ref_forceIn[i] = new InPort<TimedDoubleSeq>(std::string("ref_"+sensor_names[i]).c_str(), m_ref_force[i]);
00332         m_ref_force[i].data.length(6);
00333         registerInPort(std::string("ref_"+sensor_names[i]).c_str(), *m_ref_forceIn[i]);
00334         std::cerr << "[" << m_profile.instance_name << "]   name = " << std::string("ref_"+sensor_names[i]) << std::endl;
00335         ref_forces.push_back(hrp::Vector3(0,0,0));
00336     }
00337     // set force port
00338     for (unsigned int i=0; i<nforce; i++){
00339         m_ref_forceOut[i] = new OutPort<TimedDoubleSeq>(std::string(sensor_names[i]).c_str(), m_force[i]);
00340         m_force[i].data.length(6);
00341         m_force[i].data[0] = m_force[i].data[1] = m_force[i].data[2] = 0.0;
00342         m_force[i].data[3] = m_force[i].data[4] = m_force[i].data[5] = 0.0;
00343         registerOutPort(std::string(sensor_names[i]).c_str(), *m_ref_forceOut[i]);
00344         std::cerr << "[" << m_profile.instance_name << "]   name = " << std::string(sensor_names[i]) << std::endl;
00345     }
00346     // set limb cop offset port
00347     std::cerr << "[" << m_profile.instance_name << "] limbCOPOffset ports (" << nforce << ")" << std::endl;
00348     for (unsigned int i=0; i<nforce; i++){
00349         std::string nm("limbCOPOffset_"+sensor_names[i]);
00350         m_limbCOPOffsetOut[i] = new OutPort<TimedPoint3D>(nm.c_str(), m_limbCOPOffset[i]);
00351         registerOutPort(nm.c_str(), *m_limbCOPOffsetOut[i]);
00352         m_limbCOPOffset[i].data.x = m_limbCOPOffset[i].data.y = m_limbCOPOffset[i].data.z = 0.0;
00353         std::cerr << "[" << m_profile.instance_name << "]   name = " << nm << std::endl;
00354     }
00355     sbp_offset = hrp::Vector3(0,0,0);
00356     sbp_cog_offset = hrp::Vector3(0,0,0);
00357     //use_force = MODE_NO_FORCE;
00358     use_force = MODE_REF_FORCE;
00359 
00360     if (ikp.find("rleg") != ikp.end() && ikp.find("lleg") != ikp.end()) {
00361       is_legged_robot = true;
00362     } else {
00363       is_legged_robot = false;
00364     }
00365 
00366     m_accRef.data.ax = m_accRef.data.ay = m_accRef.data.az = 0.0;
00367     prev_imu_sensor_vel = hrp::Vector3::Zero();
00368 
00369     graspless_manip_mode = false;
00370     graspless_manip_arm = "arms";
00371     graspless_manip_p_gain = hrp::Vector3::Zero();
00372 
00373     is_stop_mode = false;
00374     is_hand_fix_mode = false;
00375 
00376     hrp::Sensor* sen = m_robot->sensor<hrp::RateGyroSensor>("gyrometer");
00377     if (sen == NULL) {
00378         std::cerr << "[" << m_profile.instance_name << "] WARNING! This robot model has no GyroSensor named 'gyrometer'! " << std::endl;
00379     }
00380 
00381     additional_force_applied_link = m_robot->rootLink();
00382     additional_force_applied_point_offset = hrp::Vector3::Zero();
00383     return RTC::RTC_OK;
00384 }
00385 
00386 
00387 
00388 RTC::ReturnCode_t AutoBalancer::onFinalize()
00389 {
00390   delete zmp_offset_interpolator;
00391   delete transition_interpolator;
00392   delete adjust_footstep_interpolator;
00393   delete leg_names_interpolator;
00394   return RTC::RTC_OK;
00395 }
00396 
00397 /*
00398   RTC::ReturnCode_t AutoBalancer::onStartup(RTC::UniqueId ec_id)
00399   {
00400   return RTC::RTC_OK;
00401   }
00402 */
00403 
00404 /*
00405   RTC::ReturnCode_t AutoBalancer::onShutdown(RTC::UniqueId ec_id)
00406   {
00407   return RTC::RTC_OK;
00408   }
00409 */
00410 
00411 RTC::ReturnCode_t AutoBalancer::onActivated(RTC::UniqueId ec_id)
00412 {
00413     std::cerr << "[" << m_profile.instance_name<< "] onActivated(" << ec_id << ")" << std::endl;
00414     
00415     return RTC::RTC_OK;
00416 }
00417 
00418 RTC::ReturnCode_t AutoBalancer::onDeactivated(RTC::UniqueId ec_id)
00419 {
00420   std::cerr << "[" << m_profile.instance_name<< "] onDeactivated(" << ec_id << ")" << std::endl;
00421   Guard guard(m_mutex);
00422   if (control_mode == MODE_ABC) {
00423     control_mode = MODE_SYNC_TO_IDLE;
00424     double tmp_ratio = 0.0;
00425     transition_interpolator->setGoal(&tmp_ratio, m_dt, true); // sync in one controller loop
00426   }
00427   return RTC::RTC_OK;
00428 }
00429 
00430 #define DEBUGP ((m_debugLevel==1 && loop%200==0) || m_debugLevel > 1 )
00431 //#define DEBUGP2 ((loop%200==0))
00432 #define DEBUGP2 (false)
00433 RTC::ReturnCode_t AutoBalancer::onExecute(RTC::UniqueId ec_id)
00434 {
00435   // std::cerr << "AutoBalancer::onExecute(" << ec_id << ")" << std::endl;
00436     loop ++;
00437 
00438     // Read Inport
00439     if (m_qRefIn.isNew()) {
00440         m_qRefIn.read();
00441     }
00442     if (m_basePosIn.isNew()) {
00443       m_basePosIn.read();
00444       input_basePos(0) = m_basePos.data.x;
00445       input_basePos(1) = m_basePos.data.y;
00446       input_basePos(2) = m_basePos.data.z;
00447     }
00448     if (m_baseRpyIn.isNew()) {
00449       m_baseRpyIn.read();
00450       input_baseRot = hrp::rotFromRpy(m_baseRpy.data.r, m_baseRpy.data.p, m_baseRpy.data.y);
00451     }
00452     if (m_zmpIn.isNew()) {
00453       m_zmpIn.read();
00454       input_zmp(0) = m_zmp.data.x;
00455       input_zmp(1) = m_zmp.data.y;
00456       input_zmp(2) = m_zmp.data.z;
00457     }
00458     for (unsigned int i=0; i<m_ref_forceIn.size(); i++){
00459         if ( m_ref_forceIn[i]->isNew() ) {
00460             m_ref_forceIn[i]->read();
00461         }
00462     }
00463     if (m_optionalDataIn.isNew()) {
00464         m_optionalDataIn.read();
00465     }
00466     if (m_emergencySignalIn.isNew()){
00467         m_emergencySignalIn.read();
00468         // if (!is_stop_mode) {
00469         //     std::cerr << "[" << m_profile.instance_name << "] emergencySignal is set!" << std::endl;
00470         //     is_stop_mode = true;
00471         //     gg->emergency_stop();
00472         // }
00473     }
00474     if (m_diffCPIn.isNew()) {
00475       m_diffCPIn.read();
00476       gg->set_diff_cp(hrp::Vector3(m_diffCP.data.x, m_diffCP.data.y, m_diffCP.data.z));
00477     }
00478     if (m_refFootOriginExtMomentIn.isNew()) {
00479       m_refFootOriginExtMomentIn.read();
00480     }
00481     if (m_refFootOriginExtMomentIsHoldValueIn.isNew()) {
00482       m_refFootOriginExtMomentIsHoldValueIn.read();
00483     }
00484     if (m_actContactStatesIn.isNew()) {
00485       m_actContactStatesIn.read();
00486       std::vector<bool> tmp_contacts(m_actContactStates.data.length());
00487       for (size_t i = 0; i < m_actContactStates.data.length(); i++) {
00488         tmp_contacts[i] = m_actContactStates.data[i];
00489       }
00490       gg->set_act_contact_states(tmp_contacts);
00491     }
00492 
00493     // Calculation
00494     Guard guard(m_mutex);
00495     hrp::Vector3 ref_basePos;
00496     hrp::Matrix33 ref_baseRot;
00497     hrp::Vector3 rel_ref_zmp; // ref zmp in base frame
00498     if ( is_legged_robot ) {
00499       // For parameters
00500       fik->storeCurrentParameters();
00501       getTargetParameters();
00502       // Get transition ratio
00503       bool is_transition_interpolator_empty = transition_interpolator->isEmpty();
00504       if (!is_transition_interpolator_empty) {
00505         transition_interpolator->get(&transition_interpolator_ratio, true);
00506       } else {
00507         transition_interpolator_ratio = (control_mode == MODE_IDLE) ? 0.0 : 1.0;
00508       }
00509       if (control_mode != MODE_IDLE ) {
00510         solveFullbodyIK();
00511 //        /////// Inverse Dynamics /////////
00512 //        if(!idsb.is_initialized){
00513 //          idsb.setInitState(m_robot, m_dt);
00514 //          invdyn_zmp_filters.resize(3);
00515 //          for(int i=0;i<3;i++){
00516 //            invdyn_zmp_filters[i].setParameterAsBiquad(25, 1/std::sqrt(2), 1.0/m_dt);
00517 //            invdyn_zmp_filters[i].reset(ref_zmp(i));
00518 //          }
00519 //        }
00520 //        calcAccelerationsForInverseDynamics(m_robot, idsb);
00521 //        if(gg_is_walking){
00522 //          calcWorldZMPFromInverseDynamics(m_robot, idsb, ref_zmp);
00523 //          for(int i=0;i<3;i++) ref_zmp(i) = invdyn_zmp_filters[i].passFilter(ref_zmp(i));
00524 //        }
00525 //        updateInvDynStateBuffer(idsb);
00526 
00527         rel_ref_zmp = m_robot->rootLink()->R.transpose() * (ref_zmp - m_robot->rootLink()->p);
00528       } else {
00529         rel_ref_zmp = input_zmp;
00530         fik->d_root_height = 0.0;
00531       }
00532       // Transition
00533       if (!is_transition_interpolator_empty) {
00534         // transition_interpolator_ratio 0=>1 : IDLE => ABC
00535         // transition_interpolator_ratio 1=>0 : ABC => IDLE
00536         ref_basePos = (1-transition_interpolator_ratio) * input_basePos + transition_interpolator_ratio * m_robot->rootLink()->p;
00537         rel_ref_zmp = (1-transition_interpolator_ratio) * input_zmp + transition_interpolator_ratio * rel_ref_zmp;
00538         rats::mid_rot(ref_baseRot, transition_interpolator_ratio, input_baseRot, m_robot->rootLink()->R);
00539         for ( unsigned int i = 0; i < m_robot->numJoints(); i++ ) {
00540           m_robot->joint(i)->q = (1-transition_interpolator_ratio) * m_qRef.data[i] + transition_interpolator_ratio * m_robot->joint(i)->q;
00541         }
00542         for (unsigned int i=0; i< m_force.size(); i++) {
00543             for (unsigned int j=0; j<6; j++) {
00544                 m_force[i].data[j] = transition_interpolator_ratio * m_force[i].data[j] + (1-transition_interpolator_ratio) * m_ref_force[i].data[j];
00545             }
00546         }
00547         for (unsigned int i=0; i< m_limbCOPOffset.size(); i++) {
00548             // transition (TODO:set stopABCmode value instead of 0)
00549             m_limbCOPOffset[i].data.x = transition_interpolator_ratio * m_limbCOPOffset[i].data.x;// + (1-transition_interpolator_ratio) * 0;
00550             m_limbCOPOffset[i].data.y = transition_interpolator_ratio * m_limbCOPOffset[i].data.y;// + (1-transition_interpolator_ratio) * 0;
00551             m_limbCOPOffset[i].data.z = transition_interpolator_ratio * m_limbCOPOffset[i].data.z;// + (1-transition_interpolator_ratio) * 0;
00552         }
00553       } else {
00554         ref_basePos = m_robot->rootLink()->p;
00555         ref_baseRot = m_robot->rootLink()->R;
00556       }
00557       // mode change for sync
00558       if (control_mode == MODE_SYNC_TO_ABC) {
00559         control_mode = MODE_ABC;
00560       } else if (control_mode == MODE_SYNC_TO_IDLE && transition_interpolator->isEmpty() ) {
00561         std::cerr << "[" << m_profile.instance_name << "] [" << m_qRef.tm
00562                   << "] Finished cleanup" << std::endl;
00563         control_mode = MODE_IDLE;
00564       }
00565     }
00566 
00567     // Write Outport
00568     if ( m_qRef.data.length() != 0 ) { // initialized
00569       if (is_legged_robot) {
00570         for ( unsigned int i = 0; i < m_robot->numJoints(); i++ ){
00571           m_qRef.data[i] = m_robot->joint(i)->q;
00572         }
00573       }
00574       m_qOut.write();
00575     }
00576     if (is_legged_robot) {
00577       // basePos
00578       m_basePos.data.x = ref_basePos(0);
00579       m_basePos.data.y = ref_basePos(1);
00580       m_basePos.data.z = ref_basePos(2);
00581       m_basePos.tm = m_qRef.tm;
00582       // baseRpy
00583       hrp::Vector3 baseRpy = hrp::rpyFromRot(ref_baseRot);
00584       m_baseRpy.data.r = baseRpy(0);
00585       m_baseRpy.data.p = baseRpy(1);
00586       m_baseRpy.data.y = baseRpy(2);
00587       m_baseRpy.tm = m_qRef.tm;
00588       // baseTform
00589       double *tform_arr = m_baseTform.data.get_buffer();
00590       tform_arr[0] = m_basePos.data.x;
00591       tform_arr[1] = m_basePos.data.y;
00592       tform_arr[2] = m_basePos.data.z;
00593       hrp::setMatrix33ToRowMajorArray(ref_baseRot, tform_arr, 3);
00594       m_baseTform.tm = m_qRef.tm;
00595       // basePose
00596       m_basePose.data.position.x = m_basePos.data.x;
00597       m_basePose.data.position.y = m_basePos.data.y;
00598       m_basePose.data.position.z = m_basePos.data.z;
00599       m_basePose.data.orientation.r = m_baseRpy.data.r;
00600       m_basePose.data.orientation.p = m_baseRpy.data.p;
00601       m_basePose.data.orientation.y = m_baseRpy.data.y;
00602       m_basePose.tm = m_qRef.tm;
00603       // zmp
00604       m_zmp.data.x = rel_ref_zmp(0);
00605       m_zmp.data.y = rel_ref_zmp(1);
00606       m_zmp.data.z = rel_ref_zmp(2);
00607       m_zmp.tm = m_qRef.tm;
00608       // cog
00609       m_cog.data.x = ref_cog(0);
00610       m_cog.data.y = ref_cog(1);
00611       m_cog.data.z = ref_cog(2);
00612       m_cog.tm = m_qRef.tm;
00613       // sbpCogOffset
00614       m_sbpCogOffset.data.x = sbp_cog_offset(0);
00615       m_sbpCogOffset.data.y = sbp_cog_offset(1);
00616       m_sbpCogOffset.data.z = sbp_cog_offset(2);
00617       m_sbpCogOffset.tm = m_qRef.tm;
00618       // write
00619       m_basePosOut.write();
00620       m_baseRpyOut.write();
00621       m_baseTformOut.write();
00622       m_basePoseOut.write();
00623       m_zmpOut.write();
00624       m_cogOut.write();
00625       m_sbpCogOffsetOut.write();
00626 
00627       // reference acceleration
00628       hrp::Sensor* sen = m_robot->sensor<hrp::RateGyroSensor>("gyrometer");
00629       if (sen != NULL) {
00630           hrp::Vector3 imu_sensor_pos = sen->link->p + sen->link->R * sen->localPos;
00631           hrp::Vector3 imu_sensor_vel = (imu_sensor_pos - prev_imu_sensor_pos)/m_dt;
00632           // convert to imu sensor local acceleration
00633           hrp::Vector3 acc = (sen->link->R * sen->localR).transpose() * (imu_sensor_vel - prev_imu_sensor_vel)/m_dt;
00634           m_accRef.data.ax = acc(0); m_accRef.data.ay = acc(1); m_accRef.data.az = acc(2);
00635           m_accRefOut.write();
00636           prev_imu_sensor_pos = imu_sensor_pos;
00637           prev_imu_sensor_vel = imu_sensor_vel;
00638       }
00639 
00640       // control parameters
00641       m_contactStates.tm = m_qRef.tm;
00642       m_contactStatesOut.write();
00643       m_controlSwingSupportTime.tm = m_qRef.tm;
00644       m_controlSwingSupportTimeOut.write();
00645       m_toeheelRatio.tm = m_qRef.tm;
00646       m_toeheelRatioOut.write();
00647       m_walkingStates.data = gg_is_walking;
00648       m_walkingStates.tm = m_qRef.tm;
00649       m_walkingStatesOut.write();
00650 
00651       for (unsigned int i=0; i<m_ref_forceOut.size(); i++){
00652           m_force[i].tm = m_qRef.tm;
00653           m_ref_forceOut[i]->write();
00654       }
00655 
00656       for (unsigned int i=0; i<m_limbCOPOffsetOut.size(); i++){
00657           m_limbCOPOffset[i].tm = m_qRef.tm;
00658           m_limbCOPOffsetOut[i]->write();
00659       }
00660     }
00661 
00662     return RTC::RTC_OK;
00663 }
00664 
00665 void AutoBalancer::getTargetParameters()
00666 {
00667   // joint angles
00668   for ( unsigned int i = 0; i < m_robot->numJoints(); i++ ){
00669     m_robot->joint(i)->q = m_qRef.data[i];
00670   }
00671   fik->setReferenceJointAngles();
00672   // basepos, rot, zmp
00673   m_robot->rootLink()->p = input_basePos;
00674   m_robot->rootLink()->R = input_baseRot;
00675   m_robot->calcForwardKinematics();
00676   gg->proc_zmp_weight_map_interpolation();
00677   if (control_mode != MODE_IDLE) {
00678     interpolateLegNamesAndZMPOffsets();
00679     // Calculate tmp_fix_coords and something
00680     coordinates tmp_fix_coords;
00681     if ( gg_is_walking ) {
00682       gg->set_default_zmp_offsets(default_zmp_offsets);
00683       gg_solved = gg->proc_one_tick();
00684       gg->get_swing_support_mid_coords(tmp_fix_coords);
00685     } else {
00686       tmp_fix_coords = fix_leg_coords;
00687     }
00688     if (!adjust_footstep_interpolator->isEmpty()) {
00689         calcFixCoordsForAdjustFootstep(tmp_fix_coords);
00690         fix_leg_coords = tmp_fix_coords;
00691     }
00692     // TODO : see explanation in this function
00693     fixLegToCoords2(tmp_fix_coords);
00694     fix_leg_coords2 = tmp_fix_coords;
00695 
00696     // Get output parameters and target EE coords
00697     target_root_p = m_robot->rootLink()->p;
00698     target_root_R = m_robot->rootLink()->R;
00699     if ( gg_is_walking ) {
00700       getOutputParametersForWalking();
00701     } else {
00702       getOutputParametersForABC();
00703     }
00704     //   Just for ik initial value
00705     if (control_mode == MODE_SYNC_TO_ABC) {
00706         fik->current_root_p = target_root_p;
00707         fik->current_root_R = target_root_R;
00708         for ( std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++ ) {
00709             if ( std::find(leg_names.begin(), leg_names.end(), it->first) != leg_names.end() ) {
00710                 it->second.target_p0 = it->second.target_link->p + it->second.target_link->R * it->second.localPos;
00711                 it->second.target_r0 = it->second.target_link->R * it->second.localR;
00712             }
00713         }
00714     }
00715 
00716     // Calculate other parameters
00717     updateTargetCoordsForHandFixMode (tmp_fix_coords);
00718     rotateRefForcesForFixCoords (tmp_fix_coords);
00719     // TODO : see explanation in this function
00720     calculateOutputRefForces ();
00721     // TODO : see explanation in this function
00722     updateWalkingVelocityFromHandError(tmp_fix_coords);
00723     calcReferenceJointAnglesForIK();
00724 
00725     // Calculate ZMP, COG, and sbp targets
00726     hrp::Vector3 tmp_ref_cog(m_robot->calcCM());
00727     hrp::Vector3 tmp_foot_mid_pos = calcFootMidPosUsingZMPWeightMap ();
00728     if (gg_is_walking) {
00729       ref_cog = gg->get_cog();
00730     } else {
00731       ref_cog = tmp_foot_mid_pos;
00732     }
00733     ref_cog(2) = tmp_ref_cog(2);
00734     if (gg_is_walking) {
00735       ref_zmp = gg->get_refzmp();
00736     } else {
00737       ref_zmp(0) = ref_cog(0);
00738       ref_zmp(1) = ref_cog(1);
00739       ref_zmp(2) = tmp_foot_mid_pos(2);
00740     }
00741   } else { // MODE_IDLE
00742       // Update fix_leg_coords based on input basePos and rot if MODE_IDLE
00743       std::vector<coordinates> tmp_end_coords_list;
00744       for ( std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++ ) {
00745           if ( std::find(leg_names.begin(), leg_names.end(), it->first) != leg_names.end() ) {
00746               tmp_end_coords_list.push_back(coordinates(it->second.target_link->p+it->second.target_link->R*it->second.localPos, it->second.target_link->R*it->second.localR));
00747           }
00748       }
00749       multi_mid_coords(fix_leg_coords, tmp_end_coords_list);
00750       getOutputParametersForIDLE();
00751       // Set force
00752       for (unsigned int i=0; i< m_force.size(); i++) {
00753           for (unsigned int j=0; j<6; j++) {
00754               m_force[i].data[j] = m_ref_force[i].data[j];
00755           }
00756       }
00757   }
00758   // Just for stop walking
00759   if (gg_is_walking && !gg_solved) stopWalking ();
00760 };
00761 
00762 void AutoBalancer::getOutputParametersForWalking ()
00763 {
00764     for (std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++) {
00765         size_t idx = contact_states_index_map[it->first];
00766         // Check whether "it->first" ee_name is included in leg_names. leg_names is equivalent to "swing" + "support" in gg.
00767         if (std::find(leg_names.begin(), leg_names.end(), it->first) != leg_names.end()) {
00768             // Set EE coords
00769             gg->get_swing_support_ee_coords_from_ee_name(it->second.target_p0, it->second.target_r0, it->first);
00770             // Set contactStates
00771             m_contactStates.data[idx] = gg->get_current_support_state_from_ee_name(it->first);
00772             // Set controlSwingSupportTime
00773             m_controlSwingSupportTime.data[idx] = gg->get_current_swing_time_from_ee_name(it->first);
00774             // Set limbCOPOffset
00775             hrp::Vector3 tmpzmpoff(m_limbCOPOffset[idx].data.x, m_limbCOPOffset[idx].data.y, m_limbCOPOffset[idx].data.z);
00776             gg->get_swing_support_foot_zmp_offsets_from_ee_name(tmpzmpoff, it->first);
00777             m_limbCOPOffset[idx].data.x = tmpzmpoff(0);
00778             m_limbCOPOffset[idx].data.y = tmpzmpoff(1);
00779             m_limbCOPOffset[idx].data.z = tmpzmpoff(2);
00780             // Set toe heel ratio which can be used force moment distribution
00781             double tmp = m_toeheelRatio.data[idx];
00782             gg->get_current_toe_heel_ratio_from_ee_name(tmp, it->first);
00783             m_toeheelRatio.data[idx] = tmp;
00784         } else { // Not included in leg_names
00785             // Set EE coords
00786             it->second.target_p0 = it->second.target_link->p + it->second.target_link->R * it->second.localPos;
00787             it->second.target_r0 = it->second.target_link->R * it->second.localR;
00788             // contactStates is OFF other than leg_names
00789             m_contactStates.data[idx] = false;
00790             // controlSwingSupportTime is not used while double support period, 1.0 is neglected
00791             m_controlSwingSupportTime.data[idx] = 1.0;
00792             // Set limbCOPOffset
00793             m_limbCOPOffset[idx].data.x = default_zmp_offsets[idx](0);
00794             m_limbCOPOffset[idx].data.y = default_zmp_offsets[idx](1);
00795             m_limbCOPOffset[idx].data.z = default_zmp_offsets[idx](2);
00796             // Set toe heel ratio which can be used force moment distribution
00797             m_toeheelRatio.data[idx] = rats::no_using_toe_heel_ratio;
00798         }
00799     }
00800 };
00801 
00802 void AutoBalancer::getOutputParametersForABC ()
00803 {
00804     // double support by default
00805     for (std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++) {
00806         size_t idx = contact_states_index_map[it->first];
00807         // Set EE coords.
00808         //   If not included in leg_names, calculate EE coords because of not being used in GaitGenerator.
00809         //   Otherwise, keep previous EE coords derived from GaitGenerator or initial value.
00810         if ( std::find(leg_names.begin(), leg_names.end(), it->first) == leg_names.end() ) {
00811             it->second.target_p0 = it->second.target_link->p + it->second.target_link->R * it->second.localPos;
00812             it->second.target_r0 = it->second.target_link->R * it->second.localR;
00813         }
00814         // Set contactStates
00815         std::vector<std::string>::const_iterator dst = std::find_if(leg_names.begin(), leg_names.end(), (boost::lambda::_1 == it->first));
00816         if (dst != leg_names.end()) {
00817             m_contactStates.data[idx] = true;
00818         } else {
00819             m_contactStates.data[idx] = false;
00820         }
00821         // controlSwingSupportTime is not used while double support period, 1.0 is neglected
00822         m_controlSwingSupportTime.data[idx] = 1.0;
00823         // Set limbCOPOffset
00824         m_limbCOPOffset[idx].data.x = default_zmp_offsets[idx](0);
00825         m_limbCOPOffset[idx].data.y = default_zmp_offsets[idx](1);
00826         m_limbCOPOffset[idx].data.z = default_zmp_offsets[idx](2);
00827         // Set toe heel ratio is not used while double support
00828         m_toeheelRatio.data[idx] = rats::no_using_toe_heel_ratio;
00829     }
00830 };
00831 
00832 void AutoBalancer::getOutputParametersForIDLE ()
00833 {
00834     // Set contactStates and controlSwingSupportTime
00835     if (m_optionalData.data.length() >= contact_states_index_map.size()*2) {
00836         // current optionalData is contactstates x limb and controlSwingSupportTime x limb
00837         //   If contactStates in optionalData is 1.0, m_contactStates is true. Otherwise, false.
00838         for ( std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++ ) {
00839             m_contactStates.data[contact_states_index_map[it->first]] = isOptionalDataContact(it->first);
00840             m_controlSwingSupportTime.data[contact_states_index_map[it->first]] = m_optionalData.data[contact_states_index_map[it->first]+contact_states_index_map.size()];
00841         }
00842         // If two feet have no contact, force set double support contact
00843         if ( !m_contactStates.data[contact_states_index_map["rleg"]] && !m_contactStates.data[contact_states_index_map["lleg"]] ) {
00844             m_contactStates.data[contact_states_index_map["rleg"]] = true;
00845             m_contactStates.data[contact_states_index_map["lleg"]] = true;
00846         }
00847     }
00848     for ( std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++ ) {
00849         size_t idx = contact_states_index_map[it->first];
00850         // Set limbCOPOffset
00851         m_limbCOPOffset[idx].data.x = 0;
00852         m_limbCOPOffset[idx].data.y = 0;
00853         m_limbCOPOffset[idx].data.z = 0;
00854         // Set toe heel ratio is not used while double support
00855         m_toeheelRatio.data[idx] = rats::no_using_toe_heel_ratio;
00856     }
00857 };
00858 
00859 void AutoBalancer::interpolateLegNamesAndZMPOffsets()
00860 {
00861     if (!zmp_offset_interpolator->isEmpty()) {
00862       double *default_zmp_offsets_output = new double[ikp.size()*3];
00863       zmp_offset_interpolator->get(default_zmp_offsets_output, true);
00864       for (size_t i = 0; i < ikp.size(); i++)
00865         for (size_t j = 0; j < 3; j++)
00866           default_zmp_offsets[i](j) = default_zmp_offsets_output[i*3+j];
00867       delete[] default_zmp_offsets_output;
00868       if (DEBUGP) {
00869         std::cerr << "[" << m_profile.instance_name << "] default_zmp_offsets (interpolated)" << std::endl;
00870         for ( std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++ ) {
00871             std::cerr << "[" << m_profile.instance_name << "]   " << it->first << " = " << default_zmp_offsets[contact_states_index_map[it->first]].format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "    [", "]")) << "[m]" << std::endl;
00872         }
00873       }
00874     }
00875     if (!leg_names_interpolator->isEmpty()) {
00876         leg_names_interpolator->get(&leg_names_interpolator_ratio, true);
00877     }else {
00878         leg_names_interpolator_ratio = 1.0;
00879     }
00880 };
00881 
00882 void AutoBalancer::calcFixCoordsForAdjustFootstep (coordinates& tmp_fix_coords)
00883 {
00884     double tmp = 0.0;
00885     adjust_footstep_interpolator->get(&tmp, true);
00886     //std::cerr << "[" << m_profile.instance_name << "] adjust ratio " << tmp << std::endl;
00887     ikp["rleg"].target_p0 = (1-tmp) * ikp["rleg"].adjust_interpolation_org_p0 + tmp*ikp["rleg"].adjust_interpolation_target_p0;
00888     ikp["lleg"].target_p0 = (1-tmp) * ikp["lleg"].adjust_interpolation_org_p0 + tmp*ikp["lleg"].adjust_interpolation_target_p0;
00889     rats::mid_rot(ikp["rleg"].target_r0, tmp, ikp["rleg"].adjust_interpolation_org_r0, ikp["rleg"].adjust_interpolation_target_r0);
00890     rats::mid_rot(ikp["lleg"].target_r0, tmp, ikp["lleg"].adjust_interpolation_org_r0, ikp["lleg"].adjust_interpolation_target_r0);
00891     coordinates tmprc, tmplc;
00892     tmprc.pos = ikp["rleg"].target_p0;
00893     tmprc.rot = ikp["rleg"].target_r0;
00894     tmplc.pos = ikp["lleg"].target_p0;
00895     tmplc.rot = ikp["lleg"].target_r0;
00896     rats::mid_coords(tmp_fix_coords, 0.5, tmprc, tmplc);
00897     //fix_leg_coords = tmp_fix_coords;
00898 };
00899 
00900 void AutoBalancer::rotateRefForcesForFixCoords (coordinates& tmp_fix_coords)
00901 {
00902     /* update ref_forces ;; StateHolder's absolute -> AutoBalancer's absolute */
00903     for (size_t i = 0; i < m_ref_forceIn.size(); i++) {
00904       // hrp::Matrix33 eeR;
00905       // hrp::Link* parentlink;
00906       // hrp::ForceSensor* sensor = m_robot->sensor<hrp::ForceSensor>(sensor_names[i]);
00907       // if (sensor) parentlink = sensor->link;
00908       // else parentlink = m_vfs[sensor_names[i]].link;
00909       // for ( std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++ ) {
00910       //     if (it->second.target_link->name == parentlink->name) eeR = parentlink->R * it->second.localR;
00911       // }
00912       // End effector frame
00913       //ref_forces[i] = eeR * hrp::Vector3(m_ref_force[i].data[0], m_ref_force[i].data[1], m_ref_force[i].data[2]);
00914       // world frame
00915       ref_forces[i] = tmp_fix_coords.rot * hrp::Vector3(m_ref_force[i].data[0], m_ref_force[i].data[1], m_ref_force[i].data[2]);
00916     }
00917     sbp_offset = tmp_fix_coords.rot * hrp::Vector3(sbp_offset);
00918 };
00919 
00920 void AutoBalancer::updateTargetCoordsForHandFixMode (coordinates& tmp_fix_coords)
00921 {
00922     // Move hand for hand fix mode
00923     //   If arms' ABCIKparam.is_active is true, move hands according to cog velocity.
00924     //   If is_hand_fix_mode is false, no hand fix mode and move hands according to cog velocity.
00925     //   If is_hand_fix_mode is true, hand fix mode and do not move hands in Y axis in tmp_fix_coords.rot.    
00926     if (gg_is_walking) {
00927         // hand control while walking = solve hand ik with is_hand_fix_mode and solve hand ik without is_hand_fix_mode
00928         bool is_hand_control_while_walking = false;
00929         for ( std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++ ) {
00930             if ( it->second.is_active && std::find(leg_names.begin(), leg_names.end(), it->first) == leg_names.end()
00931                  && it->first.find("arm") != std::string::npos ) {
00932                 is_hand_control_while_walking = true;
00933             }
00934         }
00935         if (is_hand_control_while_walking) {
00936         //if (false) { // Disabled temporarily
00937             // Store hand_fix_initial_offset in the initialization of walking
00938             if (is_hand_fix_initial) hand_fix_initial_offset = tmp_fix_coords.rot.transpose() * (hrp::Vector3(gg->get_cog()(0), gg->get_cog()(1), tmp_fix_coords.pos(2)) - tmp_fix_coords.pos);
00939             is_hand_fix_initial = false;
00940             hrp::Vector3 dif_p = hrp::Vector3(gg->get_cog()(0), gg->get_cog()(1), tmp_fix_coords.pos(2)) - tmp_fix_coords.pos - tmp_fix_coords.rot * hand_fix_initial_offset;
00941             if (is_hand_fix_mode) {
00942                 dif_p = tmp_fix_coords.rot.transpose() * dif_p;
00943                 dif_p(1) = 0;
00944                 dif_p = tmp_fix_coords.rot * dif_p;
00945             }
00946             for ( std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++ ) {
00947                 if ( it->second.is_active && std::find(leg_names.begin(), leg_names.end(), it->first) == leg_names.end()
00948                      && it->first.find("arm") != std::string::npos ) {
00949                     it->second.target_p0 = it->second.target_p0 + dif_p;
00950                 }
00951             }
00952         }
00953     }
00954 };
00955 
00956 void AutoBalancer::calculateOutputRefForces ()
00957 {
00958     // TODO : need to be updated for multicontact and other walking
00959     if (leg_names.size() == 2) {
00960         std::vector<hrp::Vector3> ee_pos;
00961         for (size_t i = 0 ; i < leg_names.size(); i++) {
00962             ABCIKparam& tmpikp = ikp[leg_names[i]];
00963             ee_pos.push_back(tmpikp.target_p0 + tmpikp.target_r0 * default_zmp_offsets[i]);
00964         }
00965         double alpha = (ref_zmp - ee_pos[1]).norm() / ((ee_pos[0] - ref_zmp).norm() + (ee_pos[1] - ref_zmp).norm());
00966         if (alpha>1.0) alpha = 1.0;
00967         if (alpha<0.0) alpha = 0.0;
00968         if (DEBUGP) {
00969             std::cerr << "[" << m_profile.instance_name << "] alpha:" << alpha << std::endl;
00970         }
00971         double mg = m_robot->totalMass() * gg->get_gravitational_acceleration();
00972         m_force[0].data[2] = alpha * mg;
00973         m_force[1].data[2] = (1-alpha) * mg;
00974     }
00975     if ( use_force == MODE_REF_FORCE_WITH_FOOT || use_force == MODE_REF_FORCE_RFU_EXT_MOMENT ) { // TODO : use other use_force mode. This should be depends on Stabilizer distribution mode.
00976         distributeReferenceZMPToWrenches (ref_zmp);
00977     }
00978     prev_ref_zmp = ref_zmp;
00979 };
00980 
00981 hrp::Vector3 AutoBalancer::calcFootMidPosUsingZMPWeightMap ()
00982 {
00983     hrp::Vector3 tmp_foot_mid_pos(hrp::Vector3::Zero());
00984     std::map<leg_type, std::string> leg_type_map = gg->get_leg_type_map();
00985     std::map<leg_type, double> zmp_weight_map = gg->get_zmp_weight_map();
00986     double sum_of_weight = 0.0;
00987     for (size_t i = 0; i < leg_names.size(); i++) {
00988         ABCIKparam& tmpikp = ikp[leg_names[i]];
00989         // for foot_mid_pos
00990         std::map<leg_type, std::string>::const_iterator dst = std::find_if(leg_type_map.begin(), leg_type_map.end(), (&boost::lambda::_1->* &std::map<leg_type, std::string>::value_type::second == leg_names[i]));
00991         tmp_foot_mid_pos += (tmpikp.target_p0 + tmpikp.target_r0 * default_zmp_offsets[i]) * zmp_weight_map[dst->first];
00992         sum_of_weight += zmp_weight_map[dst->first];
00993     }
00994     tmp_foot_mid_pos *= (1.0 / sum_of_weight);
00995     return tmp_foot_mid_pos;
00996 };
00997 
00998 void AutoBalancer::updateWalkingVelocityFromHandError (coordinates& tmp_fix_coords)
00999 {
01000     // TODO : check frame and robot state for this calculation
01001     if ( gg_is_walking && gg->get_lcg_count() == gg->get_overwrite_check_timing()+2 ) {
01002         hrp::Vector3 vel_htc(calc_vel_from_hand_error(tmp_fix_coords));
01003         gg->set_offset_velocity_param(vel_htc(0), vel_htc(1) ,vel_htc(2));
01004     }//  else {
01005     //     if ( gg_is_walking && gg->get_lcg_count() == static_cast<size_t>(gg->get_default_step_time()/(2*m_dt))-1) {
01006     //         gg->set_offset_velocity_param(0,0,0);
01007     //     }
01008     // }
01009 };
01010 
01011 void AutoBalancer::calcReferenceJointAnglesForIK ()
01012 {
01013     fik->overwrite_ref_ja_index_vec.clear();
01014     // Fix for toe joint
01015     for ( std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++ ) {
01016         if (it->second.is_active && it->second.has_toe_joint && gg->get_use_toe_joint()) {
01017             int i = it->second.target_link->jointId;
01018             if (gg->get_swing_leg_names().front() == it->first) {
01019                 fik->qrefv[i] = fik->qrefv[i] + -1 * gg->get_foot_dif_rot_angle();
01020             }
01021             fik->overwrite_ref_ja_index_vec.push_back(i);
01022         }
01023     }
01024 };
01025 
01026 hrp::Matrix33 AutoBalancer::OrientRotationMatrix (const hrp::Matrix33& rot, const hrp::Vector3& axis1, const hrp::Vector3& axis2)
01027 {
01028   hrp::Vector3 vv = axis1.cross(axis2);
01029   if (fabs(vv.norm()-0.0) < 1e-5) {
01030     return rot;
01031   } else {
01032     Eigen::AngleAxis<double> tmpr(std::asin(vv.norm()), vv.normalized());
01033     return tmpr.toRotationMatrix() * rot;
01034   }
01035 }
01036 
01037 void AutoBalancer::fixLegToCoords (const hrp::Vector3& fix_pos, const hrp::Matrix33& fix_rot)
01038 {
01039   // get current foot mid pos + rot
01040   std::vector<coordinates> foot_coords;
01041   for (size_t i = 0; i < leg_names.size(); i++) {
01042       ABCIKparam& tmpikp = ikp[leg_names[i]];
01043       if (leg_names[i].find("leg") != std::string::npos) foot_coords.push_back(coordinates((tmpikp.target_link->p + tmpikp.target_link->R * tmpikp.localPos),
01044                                                                                            (tmpikp.target_link->R * tmpikp.localR)));
01045   }
01046   coordinates current_foot_mid_coords;
01047   multi_mid_coords(current_foot_mid_coords, foot_coords);
01048   hrp::Vector3 current_foot_mid_pos = current_foot_mid_coords.pos;
01049   hrp::Matrix33 current_foot_mid_rot = current_foot_mid_coords.rot;
01050   // fix root pos + rot to fix "coords" = "current_foot_mid_xx"
01051   hrp::Matrix33 tmpR (fix_rot * current_foot_mid_rot.transpose());
01052   m_robot->rootLink()->p = fix_pos + tmpR * (m_robot->rootLink()->p - current_foot_mid_pos);
01053   rats::rotm3times(m_robot->rootLink()->R, tmpR, m_robot->rootLink()->R);
01054   m_robot->calcForwardKinematics();
01055 }
01056 
01057 void AutoBalancer::fixLegToCoords2 (coordinates& tmp_fix_coords)
01058 {
01059     // Tempolarily modify tmp_fix_coords
01060     // This will be removed after seq outputs adequate waistRPY discussed in https://github.com/fkanehiro/hrpsys-base/issues/272
01061     // Snap input tmp_fix_coords to XY plan projection.
01062     {
01063       hrp::Vector3 ex = hrp::Vector3::UnitX();
01064       hrp::Vector3 ez = hrp::Vector3::UnitZ();
01065       hrp::Vector3 xv1 (tmp_fix_coords.rot * ex);
01066       xv1(2) = 0.0;
01067       xv1.normalize();
01068       hrp::Vector3 yv1(ez.cross(xv1));
01069       tmp_fix_coords.rot(0,0) = xv1(0); tmp_fix_coords.rot(1,0) = xv1(1); tmp_fix_coords.rot(2,0) = xv1(2);
01070       tmp_fix_coords.rot(0,1) = yv1(0); tmp_fix_coords.rot(1,1) = yv1(1); tmp_fix_coords.rot(2,1) = yv1(2);
01071       tmp_fix_coords.rot(0,2) = ez(0); tmp_fix_coords.rot(1,2) = ez(1); tmp_fix_coords.rot(2,2) = ez(2);
01072     }
01073     fixLegToCoords(tmp_fix_coords.pos, tmp_fix_coords.rot);
01074 }
01075 
01076 void AutoBalancer::solveFullbodyIK ()
01077 {
01078   // Set ik target params
01079   fik->target_root_p = target_root_p;
01080   fik->target_root_R = target_root_R;
01081   for ( std::map<std::string, SimpleFullbodyInverseKinematicsSolver::IKparam>::iterator it = fik->ikp.begin(); it != fik->ikp.end(); it++ ) {
01082       it->second.target_p0 = ikp[it->first].target_p0;
01083       it->second.target_r0 = ikp[it->first].target_r0;
01084   }
01085   fik->ratio_for_vel = transition_interpolator_ratio * leg_names_interpolator_ratio;
01086 //  fik->current_tm = m_qRef.tm;
01087   for ( std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++ ) {
01088       fik->ikp[it->first].is_ik_enable = it->second.is_active;
01089   }
01090   // Revert
01091   fik->revertRobotStateToCurrent();
01092   // TODO : SBP calculation is outside of solve ik?
01093   hrp::Vector3 tmp_input_sbp = hrp::Vector3(0,0,0);
01094   static_balance_point_proc_one(tmp_input_sbp, ref_zmp(2));
01095   hrp::Vector3 dif_cog = tmp_input_sbp - ref_cog;
01096   // Solve IK
01097   fik->solveFullbodyIK (dif_cog, transition_interpolator->isEmpty());
01098 }
01099 
01100 
01101 /*
01102   RTC::ReturnCode_t AutoBalancer::onAborting(RTC::UniqueId ec_id)
01103   {
01104   return RTC::RTC_OK;
01105   }
01106 */
01107 
01108 /*
01109   RTC::ReturnCode_t AutoBalancer::onError(RTC::UniqueId ec_id)
01110   {
01111   return RTC::RTC_OK;
01112   }
01113 */
01114 
01115 /*
01116   RTC::ReturnCode_t AutoBalancer::onReset(RTC::UniqueId ec_id)
01117   {
01118   return RTC::RTC_OK;
01119   }
01120 */
01121 
01122 /*
01123   RTC::ReturnCode_t AutoBalancer::onStateUpdate(RTC::UniqueId ec_id)
01124   {
01125   return RTC::RTC_OK;
01126   }
01127 */
01128 
01129 /*
01130   RTC::ReturnCode_t AutoBalancer::onRateChanged(RTC::UniqueId ec_id)
01131   {
01132   return RTC::RTC_OK;
01133   }
01134 */
01135 
01136 void AutoBalancer::startABCparam(const OpenHRP::AutoBalancerService::StrSequence& limbs)
01137 {
01138   std::cerr << "[" << m_profile.instance_name << "] start auto balancer mode" << std::endl;
01139   Guard guard(m_mutex);
01140   double tmp_ratio = 0.0;
01141   transition_interpolator->clear();
01142   transition_interpolator->set(&tmp_ratio);
01143   tmp_ratio = 1.0;
01144   transition_interpolator->setGoal(&tmp_ratio, transition_time, true);
01145   prev_ref_zmp = ref_zmp;
01146   for ( std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++ ) {
01147     it->second.is_active = false;
01148   }
01149 
01150   for (size_t i = 0; i < limbs.length(); i++) {
01151     ABCIKparam& tmp = ikp[std::string(limbs[i])];
01152     tmp.is_active = true;
01153     std::cerr << "[" << m_profile.instance_name << "]   limb [" << std::string(limbs[i]) << "]" << std::endl;
01154   }
01155 
01156   control_mode = MODE_SYNC_TO_ABC;
01157 }
01158 
01159 void AutoBalancer::stopABCparam()
01160 {
01161   std::cerr << "[" << m_profile.instance_name << "] stop auto balancer mode" << std::endl;
01162   //Guard guard(m_mutex);
01163   double tmp_ratio = 1.0;
01164   transition_interpolator->clear();
01165   transition_interpolator->set(&tmp_ratio);
01166   tmp_ratio = 0.0;
01167   transition_interpolator->setGoal(&tmp_ratio, transition_time, true);
01168   control_mode = MODE_SYNC_TO_IDLE;
01169 }
01170 
01171 bool AutoBalancer::startWalking ()
01172 {
01173   if ( control_mode != MODE_ABC ) {
01174     std::cerr << "[" << m_profile.instance_name << "] Cannot start walking without MODE_ABC. Please startAutoBalancer." << std::endl;
01175     return false;
01176   }
01177   {
01178     Guard guard(m_mutex);
01179     fik->resetIKFailParam();
01180     std::vector<std::string> init_swing_leg_names(gg->get_footstep_front_leg_names());
01181     std::vector<std::string> tmp_all_limbs(leg_names);
01182     std::vector<std::string> init_support_leg_names;
01183     std::sort(tmp_all_limbs.begin(), tmp_all_limbs.end());
01184     std::sort(init_swing_leg_names.begin(), init_swing_leg_names.end());
01185     std::set_difference(tmp_all_limbs.begin(), tmp_all_limbs.end(),
01186                         init_swing_leg_names.begin(), init_swing_leg_names.end(),
01187                         std::back_inserter(init_support_leg_names));
01188     std::vector<step_node> init_support_leg_steps, init_swing_leg_dst_steps;
01189     for (std::vector<std::string>::iterator it = init_support_leg_names.begin(); it != init_support_leg_names.end(); it++)
01190         init_support_leg_steps.push_back(step_node(*it, coordinates(ikp[*it].target_p0, ikp[*it].target_r0), 0, 0, 0, 0));
01191     for (std::vector<std::string>::iterator it = init_swing_leg_names.begin(); it != init_swing_leg_names.end(); it++)
01192         init_swing_leg_dst_steps.push_back(step_node(*it, coordinates(ikp[*it].target_p0, ikp[*it].target_r0), 0, 0, 0, 0));
01193     gg->set_default_zmp_offsets(default_zmp_offsets);
01194     gg->initialize_gait_parameter(ref_cog, init_support_leg_steps, init_swing_leg_dst_steps);
01195   }
01196   is_hand_fix_initial = true;
01197   while ( !gg->proc_one_tick() );
01198   {
01199     Guard guard(m_mutex);
01200     gg_is_walking = gg_solved = true;
01201   }
01202   return true;
01203 }
01204 
01205 void AutoBalancer::stopWalking ()
01206 {
01207   std::vector<coordinates> tmp_end_coords_list;
01208   for (std::vector<string>::iterator it = leg_names.begin(); it != leg_names.end(); it++) {
01209       if ((*it).find("leg") != std::string::npos) tmp_end_coords_list.push_back(coordinates(ikp[*it].target_p0, ikp[*it].target_r0));
01210   }
01211   multi_mid_coords(fix_leg_coords, tmp_end_coords_list);
01212   fixLegToCoords(fix_leg_coords.pos, fix_leg_coords.rot);
01213   gg->clear_footstep_nodes_list();
01214   gg_is_walking = false;
01215 }
01216 
01217 bool AutoBalancer::startAutoBalancer (const OpenHRP::AutoBalancerService::StrSequence& limbs)
01218 {
01219   if (control_mode == MODE_IDLE) {
01220     fik->resetIKFailParam();
01221     startABCparam(limbs);
01222     waitABCTransition();
01223     return true;
01224   } else {
01225     return false;
01226   }
01227 }
01228 
01229 bool AutoBalancer::stopAutoBalancer ()
01230 {
01231   if (control_mode == MODE_ABC) {
01232     stopABCparam();
01233     waitABCTransition();
01234     return true;
01235   } else {
01236     return false;
01237   }
01238 }
01239 
01240 void AutoBalancer::waitABCTransition()
01241 {
01242   while (!transition_interpolator->isEmpty()) usleep(1000);
01243   usleep(1000);
01244 }
01245 bool AutoBalancer::goPos(const double& x, const double& y, const double& th)
01246 {
01247     //  if ( !gg_is_walking && !is_stop_mode) {
01248   if ( !is_stop_mode) {
01249     gg->set_all_limbs(leg_names);
01250     coordinates start_ref_coords;
01251     std::vector<coordinates> initial_support_legs_coords;
01252     std::vector<leg_type> initial_support_legs;
01253     bool is_valid_gait_type = calc_inital_support_legs(y, initial_support_legs_coords, initial_support_legs, start_ref_coords);
01254     if (is_valid_gait_type == false) return false;
01255     bool ret = gg->go_pos_param_2_footstep_nodes_list(x, y, th,
01256                                                       initial_support_legs_coords, // Dummy if gg_is_walking
01257                                                       start_ref_coords,            // Dummy if gg_is_walking
01258                                                       initial_support_legs,        // Dummy if gg_is_walking
01259                                                       (!gg_is_walking)); // If gg_is_walking, initialize. Otherwise, not initialize and overwrite footsteps.
01260     if (!ret) {
01261         std::cerr << "[" << m_profile.instance_name << "] Cannot goPos because of invalid timing." << std::endl;
01262     }
01263     if ( !gg_is_walking ) { // Initializing
01264         ret = startWalking();
01265     }
01266     return ret;
01267   } else {
01268     std::cerr << "[" << m_profile.instance_name << "] Cannot goPos while stopping mode." << std::endl;
01269     return false;
01270   }
01271 }
01272 
01273 bool AutoBalancer::goVelocity(const double& vx, const double& vy, const double& vth)
01274 {
01275   gg->set_all_limbs(leg_names);
01276   bool ret = true;
01277   if (gg_is_walking && gg_solved) {
01278     gg->set_velocity_param(vx, vy, vth);
01279   } else {
01280     coordinates ref_coords;
01281     ref_coords.pos = (ikp["rleg"].target_p0+ikp["lleg"].target_p0)*0.5;
01282     mid_rot(ref_coords.rot, 0.5, ikp["rleg"].target_r0, ikp["lleg"].target_r0);
01283     std::vector<leg_type> current_legs;
01284     switch(gait_type) {
01285     case BIPED:
01286         current_legs = (vy > 0 ? boost::assign::list_of(RLEG) : boost::assign::list_of(LLEG));
01287         break;
01288     case TROT:
01289         current_legs = (vy > 0 ? boost::assign::list_of(RLEG)(LARM) : boost::assign::list_of(LLEG)(RARM));
01290         break;
01291     case PACE:
01292         current_legs = (vy > 0 ? boost::assign::list_of(RLEG)(RARM) : boost::assign::list_of(LLEG)(LARM));
01293         break;
01294     case CRAWL:
01295         std::cerr << "[" << m_profile.instance_name << "] crawl walk[" << gait_type << "] is not implemented yet." << std::endl;
01296         return false;
01297     case GALLOP:
01298         /* at least one leg shoud be in contact */
01299         std::cerr << "[" << m_profile.instance_name << "] gallop walk[" << gait_type << "] is not implemented yet." << std::endl;
01300         return false;
01301     default: break;
01302     }
01303     gg->initialize_velocity_mode(ref_coords, vx, vy, vth, current_legs);
01304     ret = startWalking();
01305   }
01306   return ret;
01307 }
01308 
01309 bool AutoBalancer::goStop ()
01310 {
01311   gg->finalize_velocity_mode();
01312   waitFootSteps();
01313   return true;
01314 }
01315 
01316 bool AutoBalancer::emergencyStop ()
01317 {
01318   std::cerr << "[" << m_profile.instance_name << "] emergencyStop" << std::endl;
01319   // is_stop_mode = true;
01320   gg->emergency_stop();
01321   waitFootSteps();
01322   return true;
01323 }
01324 
01325 bool AutoBalancer::releaseEmergencyStop ()
01326 {
01327   if (is_stop_mode) {
01328       std::cerr << "[" << m_profile.instance_name << "] releaseEmergencyStop" << std::endl;
01329       is_stop_mode = false;
01330   }
01331   return true;
01332 }
01333 
01334 bool AutoBalancer::setFootSteps(const OpenHRP::AutoBalancerService::FootstepsSequence& fss, CORBA::Long overwrite_fs_idx)
01335 {
01336   OpenHRP::AutoBalancerService::StepParamsSequence spss;
01337   spss.length(fss.length());
01338   // If gg_is_walking is false, initial footstep will be double support. So, set 0 for step_height and toe heel angles.
01339   // If gg_is_walking is true, do not set to 0.
01340   for (size_t i = 0; i < spss.length(); i++) {
01341       spss[i].sps.length(fss[i].fs.length());
01342       for (size_t j = 0; j < spss[i].sps.length(); j++) {
01343           spss[i].sps[j].step_height = ((!gg_is_walking && i==0) ? 0.0 : gg->get_default_step_height());
01344           spss[i].sps[j].step_time = gg->get_default_step_time();
01345           spss[i].sps[j].toe_angle = ((!gg_is_walking && i==0) ? 0.0 : gg->get_toe_angle());
01346           spss[i].sps[j].heel_angle = ((!gg_is_walking && i==0) ? 0.0 : gg->get_heel_angle());
01347       }
01348   }
01349   setFootStepsWithParam(fss, spss, overwrite_fs_idx);
01350 }
01351 
01352 bool AutoBalancer::setFootStepsWithParam(const OpenHRP::AutoBalancerService::FootstepsSequence& fss, const OpenHRP::AutoBalancerService::StepParamsSequence& spss, CORBA::Long overwrite_fs_idx)
01353 {
01354     if (!is_stop_mode) {
01355         std::cerr << "[" << m_profile.instance_name << "] setFootStepsList" << std::endl;
01356 
01357         // Initial footstep Snapping
01358         coordinates tmpfs, fstrans;
01359         step_node initial_support_step, initial_input_step;
01360         {
01361             std::vector<step_node> initial_support_steps;
01362             if (gg_is_walking) {
01363                 if (overwrite_fs_idx <= 0) {
01364                     std::cerr << "[" << m_profile.instance_name << "]   Invalid overwrite index = " << overwrite_fs_idx << std::endl;
01365                     return false;
01366                 }
01367                 if (!gg->get_footstep_nodes_by_index(initial_support_steps, overwrite_fs_idx-1)) {
01368                     std::cerr << "[" << m_profile.instance_name << "]   Invalid overwrite index = " << overwrite_fs_idx << std::endl;
01369                     return false;
01370                 }
01371             } else {
01372                 // If walking, snap initial leg to current ABC foot coords.
01373                 for (size_t i = 0; i < fss[0].fs.length(); i++) {
01374                     ABCIKparam& tmpikp = ikp[std::string(fss[0].fs[i].leg)];
01375                     initial_support_steps.push_back(step_node(std::string(fss[0].fs[i].leg), coordinates(tmpikp.target_p0, tmpikp.target_r0), 0, 0, 0, 0));
01376                 }
01377             }
01378             initial_support_step = initial_support_steps.front(); /* use only one leg for representation */
01379         }
01380         {
01381             std::map<leg_type, std::string> leg_type_map = gg->get_leg_type_map();
01382             for (size_t i = 0; i < fss[0].fs.length(); i++) {
01383                 if (std::string(fss[0].fs[i].leg) == leg_type_map[initial_support_step.l_r]) {
01384                     coordinates tmp;
01385                     memcpy(tmp.pos.data(), fss[0].fs[i].pos, sizeof(double)*3);
01386                     tmp.rot = (Eigen::Quaternion<double>(fss[0].fs[i].rot[0], fss[0].fs[i].rot[1], fss[0].fs[i].rot[2], fss[0].fs[i].rot[3])).normalized().toRotationMatrix(); // rtc: (x, y, z, w) but eigen: (w, x, y, z)
01387                     initial_input_step = step_node(std::string(fss[0].fs[i].leg), tmp, 0, 0, 0, 0);
01388                 }
01389             }
01390         }
01391 
01392         // Get footsteps
01393         std::vector< std::vector<coordinates> > fs_vec_list;
01394         std::vector< std::vector<std::string> > leg_name_vec_list;
01395         for (size_t i = 0; i < fss.length(); i++) {
01396             std::vector<coordinates> fs_vec;
01397             std::vector<std::string> leg_name_vec;
01398             for (size_t j = 0; j < fss[i].fs.length(); j++) {
01399                 std::string leg(fss[i].fs[j].leg);
01400                 if (std::find(leg_names.begin(), leg_names.end(), leg) != leg_names.end()) {
01401                     memcpy(tmpfs.pos.data(), fss[i].fs[j].pos, sizeof(double)*3);
01402                     tmpfs.rot = (Eigen::Quaternion<double>(fss[i].fs[j].rot[0], fss[i].fs[j].rot[1], fss[i].fs[j].rot[2], fss[i].fs[j].rot[3])).normalized().toRotationMatrix(); // rtc: (x, y, z, w) but eigen: (w, x, y, z)
01403                     initial_input_step.worldcoords.transformation(fstrans, tmpfs);
01404                     tmpfs = initial_support_step.worldcoords;
01405                     tmpfs.transform(fstrans);
01406                 } else {
01407                     std::cerr << "[" << m_profile.instance_name << "]   No such target : " << leg << std::endl;
01408                     return false;
01409                 }
01410                 leg_name_vec.push_back(leg);
01411                 fs_vec.push_back(tmpfs);
01412             }
01413             leg_name_vec_list.push_back(leg_name_vec);
01414             fs_vec_list.push_back(fs_vec);
01415         }
01416         if (spss.length() != fs_vec_list.size()) {
01417             std::cerr << "[" << m_profile.instance_name << "]   StepParam length " << spss.length () << " != Footstep length " << fs_vec_list.size() << std::endl;
01418             return false;
01419         }
01420         std::cerr << "[" << m_profile.instance_name << "] print footsteps " << std::endl;
01421         std::vector< std::vector<step_node> > fnsl;
01422         for (size_t i = 0; i < fs_vec_list.size(); i++) {
01423             if (!(gg_is_walking && i == 0)) { // If initial footstep, e.g., not walking, pass user-defined footstep list. If walking, pass cdr footsteps in order to neglect initial double support leg.
01424                 std::vector<step_node> tmp_fns;
01425                 for (size_t j = 0; j < fs_vec_list.at(i).size(); j++) {
01426                     tmp_fns.push_back(step_node(leg_name_vec_list[i][j], fs_vec_list[i][j], spss[i].sps[j].step_height, spss[i].sps[j].step_time, spss[i].sps[j].toe_angle, spss[i].sps[j].heel_angle));
01427                 }
01428                 fnsl.push_back(tmp_fns);
01429             }
01430         }
01431         bool ret = true;
01432         if (gg_is_walking) {
01433             std::cerr << "[" << m_profile.instance_name << "]  Set overwrite footsteps" << std::endl;
01434             gg->set_overwrite_foot_steps_list(fnsl);
01435             gg->set_overwrite_foot_step_index(overwrite_fs_idx);
01436         } else {
01437             std::cerr << "[" << m_profile.instance_name << "]  Set normal footsteps" << std::endl;
01438             gg->set_foot_steps_list(fnsl);
01439             ret = startWalking();
01440         }
01441         return ret;
01442     } else {
01443         std::cerr << "[" << m_profile.instance_name << "] Cannot setFootSteps while walking." << std::endl;
01444         return false;
01445     }
01446 }
01447 
01448 void AutoBalancer::waitFootSteps()
01449 {
01450   //while (gg_is_walking) usleep(10);
01451   while (gg_is_walking || !transition_interpolator->isEmpty() )
01452     usleep(1000);
01453   usleep(1000);
01454   gg->set_offset_velocity_param(0,0,0);
01455 }
01456 
01457 void AutoBalancer::waitFootStepsEarly(const double tm)
01458 {
01459   if (!gg_is_walking) { return;}
01460   while ( !gg->is_finalizing(tm)|| !transition_interpolator->isEmpty() )
01461     usleep(1000);
01462   usleep(1000);
01463   gg->set_offset_velocity_param(0,0,0);
01464 }
01465 
01466 bool AutoBalancer::setGaitGeneratorParam(const OpenHRP::AutoBalancerService::GaitGeneratorParam& i_param)
01467 {
01468   std::cerr << "[" << m_profile.instance_name << "] setGaitGeneratorParam" << std::endl;
01469   if (i_param.stride_parameter.length() == 4) { // Support old stride_parameter definitions
01470       gg->set_stride_parameters(i_param.stride_parameter[0], i_param.stride_parameter[1], i_param.stride_parameter[2], i_param.stride_parameter[3],
01471                                 i_param.stride_parameter[1]*0.5, i_param.stride_parameter[2]*0.5);
01472   } else {
01473       gg->set_stride_parameters(i_param.stride_parameter[0], i_param.stride_parameter[1], i_param.stride_parameter[2], i_param.stride_parameter[3],
01474                                 i_param.stride_parameter[4], i_param.stride_parameter[5]);
01475   }
01476   std::vector<hrp::Vector3> off;
01477   for (size_t i = 0; i < i_param.leg_default_translate_pos.length(); i++) {
01478       off.push_back(hrp::Vector3(i_param.leg_default_translate_pos[i][0], i_param.leg_default_translate_pos[i][1], i_param.leg_default_translate_pos[i][2]));
01479   }
01480   gg->set_leg_default_translate_pos(off);
01481   gg->set_default_step_time(i_param.default_step_time);
01482   gg->set_default_step_height(i_param.default_step_height);
01483   gg->set_default_double_support_ratio_before(i_param.default_double_support_ratio/2.0);
01484   gg->set_default_double_support_ratio_after(i_param.default_double_support_ratio/2.0);
01485   gg->set_default_double_support_static_ratio_before(i_param.default_double_support_static_ratio/2.0);
01486   gg->set_default_double_support_static_ratio_after(i_param.default_double_support_static_ratio/2.0);
01487   gg->set_default_double_support_ratio_swing_before(i_param.default_double_support_ratio/2.0);
01488   gg->set_default_double_support_ratio_swing_after(i_param.default_double_support_ratio/2.0);
01489   // gg->set_default_double_support_ratio_before(i_param.default_double_support_ratio_before);
01490   // gg->set_default_double_support_ratio_after(i_param.default_double_support_ratio_after);
01491   // gg->set_default_double_support_static_ratio_before(i_param.default_double_support_static_ratio_before);
01492   // gg->set_default_double_support_static_ratio_after(i_param.default_double_support_static_ratio_after);
01493   // gg->set_default_double_support_ratio_swing_before(i_param.default_double_support_ratio_before);
01494   // gg->set_default_double_support_ratio_swing_after(i_param.default_double_support_ratio_after);
01495   // gg->set_default_double_support_ratio_swing_before(i_param.default_double_support_ratio_swing_before);
01496   // gg->set_default_double_support_ratio_swing_after(i_param.default_double_support_ratio_swing_after);
01497   if (i_param.default_orbit_type == OpenHRP::AutoBalancerService::SHUFFLING) {
01498     gg->set_default_orbit_type(SHUFFLING);
01499   } else if (i_param.default_orbit_type == OpenHRP::AutoBalancerService::CYCLOID) {
01500     gg->set_default_orbit_type(CYCLOID);
01501   } else if (i_param.default_orbit_type == OpenHRP::AutoBalancerService::RECTANGLE) {
01502     gg->set_default_orbit_type(RECTANGLE);
01503   } else if (i_param.default_orbit_type == OpenHRP::AutoBalancerService::STAIR) {
01504     gg->set_default_orbit_type(STAIR);
01505   } else if (i_param.default_orbit_type == OpenHRP::AutoBalancerService::CYCLOIDDELAY) {
01506     gg->set_default_orbit_type(CYCLOIDDELAY);
01507   } else if (i_param.default_orbit_type == OpenHRP::AutoBalancerService::CYCLOIDDELAYKICK) {
01508     gg->set_default_orbit_type(CYCLOIDDELAYKICK);
01509   } else if (i_param.default_orbit_type == OpenHRP::AutoBalancerService::CROSS) {
01510     gg->set_default_orbit_type(CROSS);
01511   }
01512   gg->set_swing_trajectory_delay_time_offset(i_param.swing_trajectory_delay_time_offset);
01513   gg->set_swing_trajectory_final_distance_weight(i_param.swing_trajectory_final_distance_weight);
01514   gg->set_swing_trajectory_time_offset_xy2z(i_param.swing_trajectory_time_offset_xy2z);
01515   gg->set_stair_trajectory_way_point_offset(hrp::Vector3(i_param.stair_trajectory_way_point_offset[0], i_param.stair_trajectory_way_point_offset[1], i_param.stair_trajectory_way_point_offset[2]));
01516   gg->set_cycloid_delay_kick_point_offset(hrp::Vector3(i_param.cycloid_delay_kick_point_offset[0], i_param.cycloid_delay_kick_point_offset[1], i_param.cycloid_delay_kick_point_offset[2]));  
01517   gg->set_gravitational_acceleration(i_param.gravitational_acceleration);
01518   gg->set_toe_angle(i_param.toe_angle);
01519   gg->set_heel_angle(i_param.heel_angle);
01520   gg->set_toe_pos_offset_x(i_param.toe_pos_offset_x);
01521   gg->set_heel_pos_offset_x(i_param.heel_pos_offset_x);
01522   gg->set_toe_zmp_offset_x(i_param.toe_zmp_offset_x);
01523   gg->set_heel_zmp_offset_x(i_param.heel_zmp_offset_x);
01524   gg->set_toe_check_thre(i_param.toe_check_thre);
01525   gg->set_heel_check_thre(i_param.heel_check_thre);
01526   std::vector<double> tmp_ratio(i_param.toe_heel_phase_ratio.get_buffer(), i_param.toe_heel_phase_ratio.get_buffer()+i_param.toe_heel_phase_ratio.length());
01527   std::cerr << "[" << m_profile.instance_name << "]   "; // for set_toe_heel_phase_ratio
01528   gg->set_toe_heel_phase_ratio(tmp_ratio);
01529   gg->set_use_toe_joint(i_param.use_toe_joint);
01530   gg->set_use_toe_heel_transition(i_param.use_toe_heel_transition);
01531   gg->set_use_toe_heel_auto_set(i_param.use_toe_heel_auto_set);
01532   gg->set_zmp_weight_map(boost::assign::map_list_of<leg_type, double>(RLEG, i_param.zmp_weight_map[0])(LLEG, i_param.zmp_weight_map[1])(RARM, i_param.zmp_weight_map[2])(LARM, i_param.zmp_weight_map[3]));
01533   gg->set_optional_go_pos_finalize_footstep_num(i_param.optional_go_pos_finalize_footstep_num);
01534   gg->set_overwritable_footstep_index_offset(i_param.overwritable_footstep_index_offset);
01535   gg->set_leg_margin(i_param.leg_margin);
01536   gg->set_stride_limitation_for_circle_type(i_param.stride_limitation_for_circle_type);
01537   gg->set_overwritable_stride_limitation(i_param.overwritable_stride_limitation);
01538   gg->set_use_stride_limitation(i_param.use_stride_limitation);
01539   gg->set_footstep_modification_gain(i_param.footstep_modification_gain);
01540   gg->set_modify_footsteps(i_param.modify_footsteps);
01541   gg->set_cp_check_margin(i_param.cp_check_margin);
01542   gg->set_margin_time_ratio(i_param.margin_time_ratio);
01543   if (i_param.stride_limitation_type == OpenHRP::AutoBalancerService::SQUARE) {
01544     gg->set_stride_limitation_type(SQUARE);
01545   } else if (i_param.stride_limitation_type == OpenHRP::AutoBalancerService::CIRCLE) {
01546     gg->set_stride_limitation_type(CIRCLE);
01547   }
01548 
01549   // print
01550   gg->print_param(std::string(m_profile.instance_name));
01551   return true;
01552 };
01553 
01554 bool AutoBalancer::getGaitGeneratorParam(OpenHRP::AutoBalancerService::GaitGeneratorParam& i_param)
01555 {
01556   gg->get_stride_parameters(i_param.stride_parameter[0], i_param.stride_parameter[1], i_param.stride_parameter[2], i_param.stride_parameter[3], i_param.stride_parameter[4], i_param.stride_parameter[5]);
01557   std::vector<hrp::Vector3> off;
01558   gg->get_leg_default_translate_pos(off);
01559   i_param.leg_default_translate_pos.length(off.size());
01560   for (size_t i = 0; i < i_param.leg_default_translate_pos.length(); i++) {
01561       i_param.leg_default_translate_pos[i].length(3);
01562       i_param.leg_default_translate_pos[i][0] = off[i](0);
01563       i_param.leg_default_translate_pos[i][1] = off[i](1);
01564       i_param.leg_default_translate_pos[i][2] = off[i](2);
01565   }
01566   i_param.default_step_time = gg->get_default_step_time();
01567   i_param.default_step_height = gg->get_default_step_height();
01568   i_param.default_double_support_ratio_before = gg->get_default_double_support_ratio_before();
01569   i_param.default_double_support_ratio_after = gg->get_default_double_support_ratio_after();
01570   i_param.default_double_support_static_ratio_before = gg->get_default_double_support_static_ratio_before();
01571   i_param.default_double_support_static_ratio_after = gg->get_default_double_support_static_ratio_after();
01572   i_param.default_double_support_ratio_swing_before = gg->get_default_double_support_ratio_swing_before();
01573   i_param.default_double_support_ratio_swing_after = gg->get_default_double_support_ratio_swing_after();
01574   i_param.default_double_support_ratio = i_param.default_double_support_ratio_before + i_param.default_double_support_ratio_after;
01575   i_param.default_double_support_static_ratio = i_param.default_double_support_static_ratio_before + i_param.default_double_support_static_ratio_after;
01576   if (gg->get_default_orbit_type() == SHUFFLING) {
01577     i_param.default_orbit_type = OpenHRP::AutoBalancerService::SHUFFLING;
01578   } else if (gg->get_default_orbit_type() == CYCLOID) {
01579     i_param.default_orbit_type = OpenHRP::AutoBalancerService::CYCLOID;
01580   } else if (gg->get_default_orbit_type() == RECTANGLE) {
01581     i_param.default_orbit_type = OpenHRP::AutoBalancerService::RECTANGLE;
01582   } else if (gg->get_default_orbit_type() == STAIR) {
01583     i_param.default_orbit_type = OpenHRP::AutoBalancerService::STAIR;
01584   } else if (gg->get_default_orbit_type() == CYCLOIDDELAY) {
01585     i_param.default_orbit_type = OpenHRP::AutoBalancerService::CYCLOIDDELAY;
01586   } else if (gg->get_default_orbit_type() == CYCLOIDDELAYKICK) {
01587     i_param.default_orbit_type = OpenHRP::AutoBalancerService::CYCLOIDDELAYKICK;
01588   } else if (gg->get_default_orbit_type() == CROSS) {
01589     i_param.default_orbit_type = OpenHRP::AutoBalancerService::CROSS;
01590   }
01591 
01592   hrp::Vector3 tmpv = gg->get_stair_trajectory_way_point_offset();
01593   for (size_t i = 0; i < 3; i++) i_param.stair_trajectory_way_point_offset[i] = tmpv(i);
01594   tmpv = gg->get_cycloid_delay_kick_point_offset();
01595   for (size_t i = 0; i < 3; i++) i_param.cycloid_delay_kick_point_offset[i] = tmpv(i);
01596   i_param.swing_trajectory_delay_time_offset = gg->get_swing_trajectory_delay_time_offset();
01597   i_param.swing_trajectory_final_distance_weight = gg->get_swing_trajectory_final_distance_weight();
01598   i_param.swing_trajectory_time_offset_xy2z = gg->get_swing_trajectory_time_offset_xy2z();
01599   i_param.gravitational_acceleration = gg->get_gravitational_acceleration();
01600   i_param.toe_angle = gg->get_toe_angle();
01601   i_param.heel_angle = gg->get_heel_angle();
01602   i_param.toe_pos_offset_x = gg->get_toe_pos_offset_x();
01603   i_param.heel_pos_offset_x = gg->get_heel_pos_offset_x();
01604   i_param.toe_zmp_offset_x = gg->get_toe_zmp_offset_x();
01605   i_param.heel_zmp_offset_x = gg->get_heel_zmp_offset_x();
01606   i_param.toe_check_thre = gg->get_toe_check_thre();
01607   i_param.heel_check_thre = gg->get_heel_check_thre();
01608   std::vector<double> ratio(gg->get_NUM_TH_PHASES(),0.0);
01609   gg->get_toe_heel_phase_ratio(ratio);
01610   for (int i = 0; i < gg->get_NUM_TH_PHASES(); i++) i_param.toe_heel_phase_ratio[i] = ratio[i];
01611   i_param.use_toe_joint = gg->get_use_toe_joint();
01612   i_param.use_toe_heel_transition = gg->get_use_toe_heel_transition();
01613   i_param.use_toe_heel_auto_set = gg->get_use_toe_heel_auto_set();
01614   std::map<leg_type, double> tmp_zmp_weight_map = gg->get_zmp_weight_map();
01615   i_param.zmp_weight_map[0] = tmp_zmp_weight_map[RLEG];
01616   i_param.zmp_weight_map[1] = tmp_zmp_weight_map[LLEG];
01617   i_param.zmp_weight_map[2] = tmp_zmp_weight_map[RARM];
01618   i_param.zmp_weight_map[3] = tmp_zmp_weight_map[LARM];
01619   i_param.optional_go_pos_finalize_footstep_num = gg->get_optional_go_pos_finalize_footstep_num();
01620   i_param.overwritable_footstep_index_offset = gg->get_overwritable_footstep_index_offset();
01621   for (size_t i=0; i<4; i++) {
01622     i_param.leg_margin[i] = gg->get_leg_margin(i);
01623   }
01624   for (size_t i=0; i<5; i++) {
01625     i_param.stride_limitation_for_circle_type[i] = gg->get_stride_limitation_for_circle_type(i);
01626   }
01627   for (size_t i=0; i<5; i++) {
01628     i_param.overwritable_stride_limitation[i] = gg->get_overwritable_stride_limitation(i);
01629   }
01630   i_param.use_stride_limitation = gg->get_use_stride_limitation();
01631   i_param.footstep_modification_gain = gg->get_footstep_modification_gain();
01632   i_param.modify_footsteps = gg->get_modify_footsteps();
01633   for (size_t i=0; i<2; i++) {
01634     i_param.cp_check_margin[i] = gg->get_cp_check_margin(i);
01635   }
01636   i_param.margin_time_ratio = gg->get_margin_time_ratio();
01637   if (gg->get_stride_limitation_type() == SQUARE) {
01638     i_param.stride_limitation_type = OpenHRP::AutoBalancerService::SQUARE;
01639   } else if (gg->get_stride_limitation_type() == CIRCLE) {
01640     i_param.stride_limitation_type = OpenHRP::AutoBalancerService::CIRCLE;
01641   }
01642   return true;
01643 };
01644 
01645 bool AutoBalancer::setAutoBalancerParam(const OpenHRP::AutoBalancerService::AutoBalancerParam& i_param)
01646 {
01647   Guard guard(m_mutex);
01648   std::cerr << "[" << m_profile.instance_name << "] setAutoBalancerParam" << std::endl;
01649   double *default_zmp_offsets_array = new double[ikp.size()*3];
01650   for (size_t i = 0; i < ikp.size(); i++)
01651     for (size_t j = 0; j < 3; j++)
01652       default_zmp_offsets_array[i*3+j] = i_param.default_zmp_offsets[i][j];
01653   zmp_transition_time = i_param.zmp_transition_time;
01654   adjust_footstep_transition_time = i_param.adjust_footstep_transition_time;
01655   if (zmp_offset_interpolator->isEmpty()) {
01656       zmp_offset_interpolator->clear();
01657       zmp_offset_interpolator->setGoal(default_zmp_offsets_array, zmp_transition_time, true);
01658   } else {
01659       std::cerr << "[" << m_profile.instance_name << "]   default_zmp_offsets cannot be set because interpolating." << std::endl;
01660   }
01661   if (control_mode == MODE_IDLE) {
01662     switch (i_param.use_force_mode) {
01663     case OpenHRP::AutoBalancerService::MODE_NO_FORCE:
01664         use_force = MODE_NO_FORCE;
01665         break;
01666     case OpenHRP::AutoBalancerService::MODE_REF_FORCE:
01667         use_force = MODE_REF_FORCE;
01668         break;
01669     case OpenHRP::AutoBalancerService::MODE_REF_FORCE_WITH_FOOT:
01670         use_force = MODE_REF_FORCE_WITH_FOOT;
01671         break;
01672     case OpenHRP::AutoBalancerService::MODE_REF_FORCE_RFU_EXT_MOMENT:
01673         use_force = MODE_REF_FORCE_RFU_EXT_MOMENT;
01674         break;
01675     default:
01676         break;
01677     }
01678   } else {
01679       std::cerr << "[" << m_profile.instance_name << "]   use_force_mode cannot be changed to [" << i_param.use_force_mode << "] during MODE_ABC, MODE_SYNC_TO_IDLE or MODE_SYNC_TO_ABC." << std::endl;
01680   }
01681   graspless_manip_mode = i_param.graspless_manip_mode;
01682   graspless_manip_arm = std::string(i_param.graspless_manip_arm);
01683   for (size_t j = 0; j < 3; j++)
01684       graspless_manip_p_gain[j] = i_param.graspless_manip_p_gain[j];
01685   for (size_t j = 0; j < 3; j++)
01686       graspless_manip_reference_trans_coords.pos[j] = i_param.graspless_manip_reference_trans_pos[j];
01687   graspless_manip_reference_trans_coords.rot = (Eigen::Quaternion<double>(i_param.graspless_manip_reference_trans_rot[0],
01688                                                                           i_param.graspless_manip_reference_trans_rot[1],
01689                                                                           i_param.graspless_manip_reference_trans_rot[2],
01690                                                                           i_param.graspless_manip_reference_trans_rot[3]).normalized().toRotationMatrix()); // rtc: (x, y, z, w) but eigen: (w, x, y, z)
01691   transition_time = i_param.transition_time;
01692   std::vector<std::string> cur_leg_names, dst_leg_names;
01693   cur_leg_names = leg_names;
01694   for (size_t i = 0; i < i_param.leg_names.length(); i++) {
01695       dst_leg_names.push_back(std::string(i_param.leg_names[i]));
01696   }
01697   std::sort(cur_leg_names.begin(), cur_leg_names.end());
01698   std::sort(dst_leg_names.begin(), dst_leg_names.end());
01699   if (cur_leg_names != dst_leg_names) {
01700       if (leg_names_interpolator->isEmpty()) {
01701           leg_names.clear();
01702           leg_names = dst_leg_names;
01703           if (control_mode == MODE_ABC) {
01704               double tmp_ratio = 0.0;
01705               leg_names_interpolator->set(&tmp_ratio);
01706               tmp_ratio = 1.0;
01707               leg_names_interpolator->setGoal(&tmp_ratio, 5.0, true);
01708               control_mode = MODE_SYNC_TO_ABC;
01709           }
01710       }
01711   } else {
01712       std::cerr << "[" << m_profile.instance_name << "]   leg_names cannot be set because interpolating." << std::endl;
01713   }
01714   if (!gg_is_walking) {
01715       is_hand_fix_mode = i_param.is_hand_fix_mode;
01716       std::cerr << "[" << m_profile.instance_name << "]   is_hand_fix_mode = " << is_hand_fix_mode << std::endl;
01717   } else {
01718       std::cerr << "[" << m_profile.instance_name << "]   is_hand_fix_mode cannot be set in (gg_is_walking = true). Current is_hand_fix_mode is " << (is_hand_fix_mode?"true":"false") << std::endl;
01719   }
01720   if (control_mode == MODE_IDLE) {
01721       for (size_t i = 0; i < i_param.end_effector_list.length(); i++) {
01722           std::map<std::string, ABCIKparam>::iterator it = ikp.find(std::string(i_param.end_effector_list[i].leg));
01723           memcpy(it->second.localPos.data(), i_param.end_effector_list[i].pos, sizeof(double)*3);
01724           it->second.localR = (Eigen::Quaternion<double>(i_param.end_effector_list[i].rot[0], i_param.end_effector_list[i].rot[1], i_param.end_effector_list[i].rot[2], i_param.end_effector_list[i].rot[3])).normalized().toRotationMatrix();
01725       }
01726   } else {
01727       std::cerr << "[" << m_profile.instance_name << "] cannot change end-effectors except during MODE_IDLE" << std::endl;
01728   }
01729   if (i_param.default_gait_type == OpenHRP::AutoBalancerService::BIPED) {
01730       gait_type = BIPED;
01731   } else if (i_param.default_gait_type == OpenHRP::AutoBalancerService::TROT) {
01732       gait_type = TROT;
01733   } else if (i_param.default_gait_type == OpenHRP::AutoBalancerService::PACE) {
01734       gait_type = PACE;
01735   } else if (i_param.default_gait_type == OpenHRP::AutoBalancerService::CRAWL) {
01736       gait_type = CRAWL;
01737   } else if (i_param.default_gait_type == OpenHRP::AutoBalancerService::GALLOP) {
01738       gait_type = GALLOP;
01739   }
01740   // Ref force balancing
01741   std::cerr << "[" << m_profile.instance_name << "] Ref force balancing" << std::endl;
01742   if ( use_force == MODE_REF_FORCE_WITH_FOOT && control_mode != MODE_IDLE ) {
01743       std::cerr << "[" << m_profile.instance_name << "]   additional_force_applied_point_offset and additional_force_applied_link_name cannot be updated during MODE_REF_FORCE_WITH_FOOT and non-MODE_IDLE"<< std::endl;
01744   } else if ( !m_robot->link(std::string(i_param.additional_force_applied_link_name)) ) {
01745       std::cerr << "[" << m_profile.instance_name << "]   Invalid link name for additional_force_applied_link_name = " << i_param.additional_force_applied_link_name << std::endl;
01746   } else {
01747       additional_force_applied_link = m_robot->link(std::string(i_param.additional_force_applied_link_name));
01748       for (size_t i = 0; i < 3; i++) {
01749           additional_force_applied_point_offset(i) = i_param.additional_force_applied_point_offset[i];
01750       }
01751       std::cerr << "[" << m_profile.instance_name << "]   Link name for additional_force_applied_link_name = " << additional_force_applied_link->name << ", additional_force_applied_point_offset = " << additional_force_applied_point_offset.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "    [", "]")) << "[m]" << std::endl;
01752   }
01753 
01754   for (std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++) {
01755       std::cerr << "[" << m_profile.instance_name << "] End Effector [" << it->first << "]" << std::endl;
01756       std::cerr << "[" << m_profile.instance_name << "]   localpos = " << it->second.localPos.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "    [", "]")) << "[m]" << std::endl;
01757       std::cerr << "[" << m_profile.instance_name << "]   localR = " << it->second.localR.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", "\n", "    [", "]")) << std::endl;
01758   }
01759 
01760   std::cerr << "[" << m_profile.instance_name << "]   default_zmp_offsets = ";
01761   for (size_t i = 0; i < ikp.size() * 3; i++) {
01762       std::cerr << default_zmp_offsets_array[i] << " ";
01763   }
01764   std::cerr << std::endl;
01765   delete[] default_zmp_offsets_array;
01766   std::cerr << "[" << m_profile.instance_name << "]   use_force_mode = " << getUseForceModeString() << std::endl;
01767   std::cerr << "[" << m_profile.instance_name << "]   graspless_manip_mode = " << graspless_manip_mode << std::endl;
01768   std::cerr << "[" << m_profile.instance_name << "]   graspless_manip_arm = " << graspless_manip_arm << std::endl;
01769   std::cerr << "[" << m_profile.instance_name << "]   graspless_manip_p_gain = " << graspless_manip_p_gain.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "    [", "]")) << std::endl;
01770   std::cerr << "[" << m_profile.instance_name << "]   graspless_manip_reference_trans_pos = " << graspless_manip_reference_trans_coords.pos.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "    [", "]")) << std::endl;
01771   std::cerr << "[" << m_profile.instance_name << "]   graspless_manip_reference_trans_rot = " << graspless_manip_reference_trans_coords.rot.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", "\n", "    [", "]")) << std::endl;
01772   std::cerr << "[" << m_profile.instance_name << "]   transition_time = " << transition_time << "[s], zmp_transition_time = " << zmp_transition_time << "[s], adjust_footstep_transition_time = " << adjust_footstep_transition_time << "[s]" << std::endl;
01773   for (std::vector<std::string>::iterator it = leg_names.begin(); it != leg_names.end(); it++) std::cerr << "[" << m_profile.instance_name << "]   leg_names [" << *it << "]" << std::endl;
01774   std::cerr << "[" << m_profile.instance_name << "]   default_gait_type = " << gait_type << std::endl;
01775   // FIK
01776   fik->move_base_gain = i_param.move_base_gain;
01777   fik->pos_ik_thre = i_param.pos_ik_thre;
01778   fik->rot_ik_thre = i_param.rot_ik_thre;
01779   fik->printParam();
01780   // IK limb parameters
01781   fik->setIKParam(ee_vec, i_param.ik_limb_parameters);
01782   // Limb stretch avoidance
01783   fik->use_limb_stretch_avoidance = i_param.use_limb_stretch_avoidance;
01784   fik->limb_stretch_avoidance_time_const = i_param.limb_stretch_avoidance_time_const;
01785   for (size_t i = 0; i < 2; i++) {
01786     fik->limb_stretch_avoidance_vlimit[i] = i_param.limb_stretch_avoidance_vlimit[i];
01787   }
01788   for (size_t i = 0; i < fik->ikp.size(); i++) {
01789     fik->ikp[ee_vec[i]].limb_length_margin = i_param.limb_length_margin[i];
01790   }
01791   return true;
01792 };
01793 
01794 bool AutoBalancer::getAutoBalancerParam(OpenHRP::AutoBalancerService::AutoBalancerParam& i_param)
01795 {
01796   i_param.default_zmp_offsets.length(ikp.size());
01797   for (size_t i = 0; i < ikp.size(); i++) {
01798       i_param.default_zmp_offsets[i].length(3);
01799       for (size_t j = 0; j < 3; j++) {
01800           i_param.default_zmp_offsets[i][j] = default_zmp_offsets[i](j);
01801       }
01802   }
01803   switch(control_mode) {
01804   case MODE_IDLE: i_param.controller_mode = OpenHRP::AutoBalancerService::MODE_IDLE; break;
01805   case MODE_ABC: i_param.controller_mode = OpenHRP::AutoBalancerService::MODE_ABC; break;
01806   case MODE_SYNC_TO_IDLE: i_param.controller_mode = OpenHRP::AutoBalancerService::MODE_SYNC_TO_IDLE; break;
01807   case MODE_SYNC_TO_ABC: i_param.controller_mode = OpenHRP::AutoBalancerService::MODE_SYNC_TO_ABC; break;
01808   default: break;
01809   }
01810   switch(use_force) {
01811   case MODE_NO_FORCE: i_param.use_force_mode = OpenHRP::AutoBalancerService::MODE_NO_FORCE; break;
01812   case MODE_REF_FORCE: i_param.use_force_mode = OpenHRP::AutoBalancerService::MODE_REF_FORCE; break;
01813   case MODE_REF_FORCE_WITH_FOOT: i_param.use_force_mode = OpenHRP::AutoBalancerService::MODE_REF_FORCE_WITH_FOOT; break;
01814   case MODE_REF_FORCE_RFU_EXT_MOMENT: i_param.use_force_mode = OpenHRP::AutoBalancerService::MODE_REF_FORCE_RFU_EXT_MOMENT; break;
01815   default: break;
01816   }
01817   i_param.graspless_manip_mode = graspless_manip_mode;
01818   i_param.graspless_manip_arm = graspless_manip_arm.c_str();
01819   for (size_t j = 0; j < 3; j++)
01820       i_param.graspless_manip_p_gain[j] = graspless_manip_p_gain[j];
01821   for (size_t j = 0; j < 3; j++)
01822       i_param.graspless_manip_reference_trans_pos[j] = graspless_manip_reference_trans_coords.pos[j];
01823   Eigen::Quaternion<double> qt(graspless_manip_reference_trans_coords.rot);
01824   i_param.graspless_manip_reference_trans_rot[0] = qt.w();
01825   i_param.graspless_manip_reference_trans_rot[1] = qt.x();
01826   i_param.graspless_manip_reference_trans_rot[2] = qt.y();
01827   i_param.graspless_manip_reference_trans_rot[3] = qt.z();
01828   i_param.transition_time = transition_time;
01829   i_param.zmp_transition_time = zmp_transition_time;
01830   i_param.adjust_footstep_transition_time = adjust_footstep_transition_time;
01831   i_param.leg_names.length(leg_names.size());
01832   for (size_t i = 0; i < leg_names.size(); i++) i_param.leg_names[i] = leg_names.at(i).c_str();
01833   i_param.is_hand_fix_mode = is_hand_fix_mode;
01834   i_param.end_effector_list.length(ikp.size());
01835   {
01836       size_t i = 0;
01837       for (std::map<std::string, ABCIKparam>::const_iterator it = ikp.begin(); it != ikp.end(); it++) {
01838           copyRatscoords2Footstep(i_param.end_effector_list[i],
01839                                   coordinates(it->second.localPos, it->second.localR));
01840           i_param.end_effector_list[i].leg = it->first.c_str();
01841           i++;
01842       }
01843   }
01844   switch(gait_type) {
01845   case BIPED:  i_param.default_gait_type = OpenHRP::AutoBalancerService::BIPED;  break;
01846   case TROT:   i_param.default_gait_type = OpenHRP::AutoBalancerService::TROT;   break;
01847   case PACE:   i_param.default_gait_type = OpenHRP::AutoBalancerService::PACE;   break;
01848   case CRAWL:  i_param.default_gait_type = OpenHRP::AutoBalancerService::CRAWL;  break;
01849   case GALLOP: i_param.default_gait_type = OpenHRP::AutoBalancerService::GALLOP; break;
01850   default: break;
01851   }
01852   // FIK
01853   i_param.move_base_gain = fik->move_base_gain;
01854   i_param.pos_ik_thre = fik->pos_ik_thre;
01855   i_param.rot_ik_thre = fik->rot_ik_thre;
01856   // IK limb parameters
01857   fik->getIKParam(ee_vec, i_param.ik_limb_parameters);
01858   // Limb stretch avoidance
01859   i_param.use_limb_stretch_avoidance = fik->use_limb_stretch_avoidance;
01860   i_param.limb_stretch_avoidance_time_const = fik->limb_stretch_avoidance_time_const;
01861   i_param.limb_length_margin.length(fik->ikp.size());
01862   for (size_t i = 0; i < 2; i++) {
01863     i_param.limb_stretch_avoidance_vlimit[i] = fik->limb_stretch_avoidance_vlimit[i];
01864   }
01865   for (size_t i = 0; i < ikp.size(); i++) {
01866     i_param.limb_length_margin[i] = fik->ikp[ee_vec[i]].limb_length_margin;
01867   }
01868   i_param.additional_force_applied_link_name = additional_force_applied_link->name.c_str();
01869   for (size_t i = 0; i < 3; i++) {
01870       i_param.additional_force_applied_point_offset[i] = additional_force_applied_point_offset(i);
01871   }
01872   return true;
01873 };
01874 
01875 void AutoBalancer::copyRatscoords2Footstep(OpenHRP::AutoBalancerService::Footstep& out_fs, const rats::coordinates& in_fs)
01876 {
01877   memcpy(out_fs.pos, in_fs.pos.data(), sizeof(double)*3);
01878   Eigen::Quaternion<double> qt(in_fs.rot);
01879   out_fs.rot[0] = qt.w();
01880   out_fs.rot[1] = qt.x();
01881   out_fs.rot[2] = qt.y();
01882   out_fs.rot[3] = qt.z();
01883 };
01884 
01885 bool AutoBalancer::getFootstepParam(OpenHRP::AutoBalancerService::FootstepParam& i_param)
01886 {
01887   copyRatscoords2Footstep(i_param.support_leg_coords, gg->get_support_leg_steps().front().worldcoords);
01888   copyRatscoords2Footstep(i_param.swing_leg_coords, gg->get_swing_leg_steps().front().worldcoords);
01889   copyRatscoords2Footstep(i_param.swing_leg_src_coords, gg->get_swing_leg_src_steps().front().worldcoords);
01890   copyRatscoords2Footstep(i_param.swing_leg_dst_coords, gg->get_swing_leg_dst_steps().front().worldcoords);
01891   copyRatscoords2Footstep(i_param.dst_foot_midcoords, gg->get_dst_foot_midcoords());
01892   if (gg->get_support_leg_names().front() == "rleg") {
01893     i_param.support_leg = OpenHRP::AutoBalancerService::RLEG;
01894   } else {
01895     i_param.support_leg = OpenHRP::AutoBalancerService::LLEG;
01896   }
01897   switch ( gg->get_current_support_states().front() ) {
01898   case BOTH: i_param.support_leg_with_both = OpenHRP::AutoBalancerService::BOTH; break;
01899   case RLEG: i_param.support_leg_with_both = OpenHRP::AutoBalancerService::RLEG; break;
01900   case LLEG: i_param.support_leg_with_both = OpenHRP::AutoBalancerService::LLEG; break;
01901   default: break;
01902   }
01903   return true;
01904 };
01905 
01906 bool AutoBalancer::adjustFootSteps(const OpenHRP::AutoBalancerService::Footstep& rfootstep, const OpenHRP::AutoBalancerService::Footstep& lfootstep)
01907 {
01908   std::cerr << "[" << m_profile.instance_name << "] [" << m_qRef.tm
01909             << "] adjustFootSteps" << std::endl;
01910   if (control_mode == MODE_ABC && !gg_is_walking && adjust_footstep_interpolator->isEmpty()) {
01911       Guard guard(m_mutex);
01912       //
01913       hrp::Vector3 eepos, org_mid_rpy, target_mid_rpy;
01914       hrp::Matrix33 eerot, tmprot;
01915       coordinates org_mid_coords, target_mid_coords;
01916       // Get org coords
01917       ikp["rleg"].adjust_interpolation_org_p0 = ikp["rleg"].target_p0;
01918       ikp["lleg"].adjust_interpolation_org_p0 = ikp["lleg"].target_p0;
01919       ikp["rleg"].adjust_interpolation_org_r0 = ikp["rleg"].target_r0;
01920       ikp["lleg"].adjust_interpolation_org_r0 = ikp["lleg"].target_r0;
01921       mid_coords(org_mid_coords, 0.5,
01922                  coordinates(ikp["rleg"].adjust_interpolation_org_p0, ikp["rleg"].adjust_interpolation_org_r0),
01923                  coordinates(ikp["lleg"].adjust_interpolation_org_p0, ikp["lleg"].adjust_interpolation_org_r0));
01924       org_mid_rpy = hrp::rpyFromRot(org_mid_coords.rot);
01925       // Get target coords
01926       //   Input : ee coords
01927       //   Output : link coords
01928       memcpy(eepos.data(), rfootstep.pos, sizeof(double)*3);
01929       eerot = (Eigen::Quaternion<double>(rfootstep.rot[0], rfootstep.rot[1], rfootstep.rot[2], rfootstep.rot[3])).normalized().toRotationMatrix(); // rtc: 
01930       ikp["rleg"].adjust_interpolation_target_r0 = eerot;
01931       ikp["rleg"].adjust_interpolation_target_p0 = eepos;
01932       memcpy(eepos.data(), lfootstep.pos, sizeof(double)*3);
01933       eerot = (Eigen::Quaternion<double>(lfootstep.rot[0], lfootstep.rot[1], lfootstep.rot[2], lfootstep.rot[3])).normalized().toRotationMatrix(); // rtc: 
01934       ikp["lleg"].adjust_interpolation_target_r0 = eerot;
01935       ikp["lleg"].adjust_interpolation_target_p0 = eepos;
01936       mid_coords(target_mid_coords, 0.5,
01937                  coordinates(ikp["rleg"].adjust_interpolation_target_p0, ikp["rleg"].adjust_interpolation_target_r0),
01938                  coordinates(ikp["lleg"].adjust_interpolation_target_p0, ikp["lleg"].adjust_interpolation_target_r0));
01939       coordinates rtrans, ltrans;
01940       target_mid_coords.transformation(rtrans, coordinates(ikp["rleg"].adjust_interpolation_target_p0, ikp["rleg"].adjust_interpolation_target_r0));
01941       target_mid_coords.transformation(ltrans, coordinates(ikp["lleg"].adjust_interpolation_target_p0, ikp["lleg"].adjust_interpolation_target_r0));
01942       target_mid_rpy = hrp::rpyFromRot(target_mid_coords.rot);
01943       // Fix target pos => org pos, target yaw => org yaw
01944       target_mid_rpy(2) = org_mid_rpy(2);
01945       target_mid_coords.rot = hrp::rotFromRpy(target_mid_rpy);
01946       target_mid_coords.pos = org_mid_coords.pos;
01947       // Calculate rleg and lleg coords
01948       coordinates tmpc;
01949       tmpc = target_mid_coords;
01950       tmpc.transform(rtrans);
01951       ikp["rleg"].adjust_interpolation_target_p0 = tmpc.pos;
01952       ikp["rleg"].adjust_interpolation_target_r0 = tmpc.rot;
01953       tmpc = target_mid_coords;
01954       tmpc.transform(ltrans);
01955       ikp["lleg"].adjust_interpolation_target_p0 = tmpc.pos;
01956       ikp["lleg"].adjust_interpolation_target_r0 = tmpc.rot;
01957       // Set interpolator
01958       adjust_footstep_interpolator->clear();
01959       double tmp = 0.0;
01960       adjust_footstep_interpolator->set(&tmp);
01961       tmp = 1.0;
01962       adjust_footstep_interpolator->setGoal(&tmp, adjust_footstep_transition_time, true);
01963   }
01964   while (!adjust_footstep_interpolator->isEmpty() )
01965     usleep(1000);
01966   usleep(1000);
01967   return true;
01968 };
01969 
01970 bool AutoBalancer::getRemainingFootstepSequence(OpenHRP::AutoBalancerService::FootstepSequence_out o_footstep, CORBA::Long& o_current_fs_idx)
01971 {
01972     std::cerr << "[" << m_profile.instance_name << "] getRemainingFootstepSequence" << std::endl;
01973     o_footstep = new OpenHRP::AutoBalancerService::FootstepSequence;
01974     if (gg_is_walking) {
01975         std::vector< std::vector<step_node> > fsnl = gg->get_remaining_footstep_nodes_list();
01976         o_current_fs_idx = gg->get_footstep_index();
01977         o_footstep->length(fsnl.size());
01978         for (size_t i = 0; i < fsnl.size(); i++) {
01979             o_footstep[i].leg = (fsnl[i].front().l_r==RLEG?"rleg":"lleg");
01980             copyRatscoords2Footstep(o_footstep[i], fsnl[i].front().worldcoords);
01981         }
01982     }
01983 };
01984 
01985 bool AutoBalancer::getGoPosFootstepsSequence(const double& x, const double& y, const double& th, OpenHRP::AutoBalancerService::FootstepsSequence_out o_footstep)
01986 {
01987     std::cerr << "[" << m_profile.instance_name << "] getGoPosFootstepsSequence" << std::endl;
01988     o_footstep = new OpenHRP::AutoBalancerService::FootstepsSequence;
01989     if (gg_is_walking) {
01990         std::cerr << "[" << m_profile.instance_name << "] Cannot call getGoPosFootstepsSequence in walking" << std::endl;
01991         return false;
01992     } else {
01993         gg->set_all_limbs(leg_names);
01994         std::vector< std::vector<step_node> > new_footstep_nodes_list;
01995         coordinates start_ref_coords;
01996         std::vector<coordinates> initial_support_legs_coords;
01997         std::vector<leg_type> initial_support_legs;
01998         bool is_valid_gait_type = calc_inital_support_legs(y, initial_support_legs_coords, initial_support_legs, start_ref_coords);
01999         if (is_valid_gait_type == false) return false;
02000         /* go_pos_param_2_footstep_nodes_list_core is const member function  */
02001         gg->go_pos_param_2_footstep_nodes_list_core (x, y, th,
02002                                                      initial_support_legs_coords, start_ref_coords, initial_support_legs,
02003                                                      new_footstep_nodes_list, true, 0);
02004         o_footstep->length(new_footstep_nodes_list.size());
02005         for (size_t i = 0; i < new_footstep_nodes_list.size(); i++) {
02006             o_footstep[i].fs.length(new_footstep_nodes_list.at(i).size());
02007             for (size_t j = 0; j < new_footstep_nodes_list.at(i).size(); j++) {
02008                 leg_type tmp_leg_type = new_footstep_nodes_list.at(i).at(j).l_r;
02009                 o_footstep[i].fs[j].leg = ((tmp_leg_type == RLEG) ? "rleg":
02010                                            (tmp_leg_type == LLEG) ? "lleg":
02011                                            (tmp_leg_type == RARM) ? "rarm":
02012                                            "larm");
02013                 copyRatscoords2Footstep(o_footstep[i].fs[j], new_footstep_nodes_list.at(i).at(j).worldcoords);
02014             }
02015         }
02016         return true;
02017     }
02018 };
02019 
02020 void AutoBalancer::static_balance_point_proc_one(hrp::Vector3& tmp_input_sbp, const double ref_com_height)
02021 {
02022   hrp::Vector3 target_sbp = hrp::Vector3(0, 0, 0);
02023   hrp::Vector3 tmpcog = m_robot->calcCM();
02024   if ( use_force == MODE_NO_FORCE ) {
02025     tmp_input_sbp = tmpcog + sbp_cog_offset;
02026   } else {
02027     calc_static_balance_point_from_forces(target_sbp, tmpcog, ref_com_height, ref_forces);
02028     tmp_input_sbp = target_sbp - sbp_offset;
02029     sbp_cog_offset = tmp_input_sbp - tmpcog;
02030   }
02031 };
02032 
02033 void AutoBalancer::calc_static_balance_point_from_forces(hrp::Vector3& sb_point, const hrp::Vector3& tmpcog, const double ref_com_height, std::vector<hrp::Vector3>& tmp_forces)
02034 {
02035   hrp::Vector3 denom, nume;
02036   /* sb_point[m] = nume[kg * m/s^2 * m] / denom[kg * m/s^2] */
02037   double mass = m_robot->totalMass();
02038   double mg = mass * gg->get_gravitational_acceleration();
02039   hrp::Vector3 total_sensor_ref_force = hrp::Vector3::Zero();
02040   for (size_t i = 0; i < tmp_forces.size(); i++) {
02041       total_sensor_ref_force += tmp_forces[i];
02042   }
02043   hrp::Vector3 total_nosensor_ref_force = mg * hrp::Vector3::UnitZ() - total_sensor_ref_force; // total ref force at the point without sensors, such as torso
02044   hrp::Vector3 tmp_ext_moment = fix_leg_coords2.pos.cross(total_nosensor_ref_force) + fix_leg_coords2.rot * hrp::Vector3(m_refFootOriginExtMoment.data.x, m_refFootOriginExtMoment.data.y, m_refFootOriginExtMoment.data.z);
02045   // For MODE_REF_FORCE_RFU_EXT_MOMENT, store previous root position to calculate influence from tmp_ext_moment while walking (basically, root link moves while walking).
02046   //   Calculate values via fix_leg_coords2 relative/world values.
02047   static hrp::Vector3 prev_additional_force_applied_pos = fix_leg_coords2.rot.transpose() * (additional_force_applied_link->p-fix_leg_coords2.pos);
02048   //   If not is_hold_value (not hold value), update prev_additional_force_applied_pos
02049   if ( !m_refFootOriginExtMomentIsHoldValue.data ) {
02050       prev_additional_force_applied_pos = fix_leg_coords2.rot.transpose() * (additional_force_applied_link->p-fix_leg_coords2.pos);
02051   }
02052   hrp::Vector3 tmp_prev_additional_force_applied_pos = fix_leg_coords2.rot * prev_additional_force_applied_pos + fix_leg_coords2.pos;
02053   // Calculate SBP
02054   for (size_t j = 0; j < 2; j++) {
02055     nume(j) = mg * tmpcog(j);
02056     denom(j) = mg;
02057     if ( use_force == MODE_REF_FORCE_RFU_EXT_MOMENT ) {
02058         //nume(j) += (j==0 ? tmp_ext_moment(1):-tmp_ext_moment(0));
02059         nume(j) += (tmp_prev_additional_force_applied_pos(j)-additional_force_applied_link->p(j))*total_nosensor_ref_force(2) + (j==0 ? tmp_ext_moment(1):-tmp_ext_moment(0));
02060         denom(j) -= total_nosensor_ref_force(2);
02061     } else {
02062         for ( std::map<std::string, ABCIKparam>::iterator it = ikp.begin(); it != ikp.end(); it++ ) {
02063             // Check leg_names. leg_names is assumed to be support limb for locomotion, cannot be used for manipulation. If it->first is not included in leg_names, use it for manipulation and static balance point calculation.
02064             if (std::find(leg_names.begin(), leg_names.end(), it->first) == leg_names.end()) {
02065                 size_t idx = contact_states_index_map[it->first];
02066                 // Force applied point is assumed as end effector
02067                 hrp::Vector3 fpos = it->second.target_link->p + it->second.target_link->R * it->second.localPos;
02068                 nume(j) += ( (fpos(2) - ref_com_height) * tmp_forces[idx](j) - fpos(j) * tmp_forces[idx](2) );
02069                 denom(j) -= tmp_forces[idx](2);
02070             }
02071         }
02072         if ( use_force == MODE_REF_FORCE_WITH_FOOT ) {
02073             hrp::Vector3 fpos(additional_force_applied_link->p+additional_force_applied_point_offset);
02074             nume(j) += ( (fpos(2) - ref_com_height) * total_nosensor_ref_force(j) - fpos(j) * total_nosensor_ref_force(2) );
02075             denom(j) -= total_nosensor_ref_force(2);
02076         }
02077     }
02078     sb_point(j) = nume(j) / denom(j);
02079   }
02080   sb_point(2) = ref_com_height;
02081 };
02082 
02083 #ifndef rad2deg
02084 #define rad2deg(rad) (rad * 180 / M_PI)
02085 #endif
02086 #ifndef deg2rad
02087 #define deg2rad(deg) (deg * M_PI / 180)
02088 #endif
02089 
02090 hrp::Vector3 AutoBalancer::calc_vel_from_hand_error (const coordinates& tmp_fix_coords)
02091 {
02092   if (graspless_manip_mode) {
02093     hrp::Vector3 dp,dr;
02094     coordinates ref_hand_coords(gg->get_dst_foot_midcoords()), act_hand_coords;
02095     ref_hand_coords.transform(graspless_manip_reference_trans_coords); // desired arm coords
02096     hrp::Vector3 foot_pos(gg->get_dst_foot_midcoords().pos);
02097     if ( graspless_manip_arm == "arms" ) {
02098         hrp::Vector3 rarm_pos = ikp["rarm"].target_p0;
02099         hrp::Vector3 larm_pos = ikp["larm"].target_p0;
02100         act_hand_coords.pos = (rarm_pos+larm_pos)/2.0;
02101         hrp::Vector3 act_y = larm_pos-rarm_pos;
02102         act_y(2) = 0;
02103         act_y.normalize();
02104         hrp::Vector3 ref_y(ref_hand_coords.rot * hrp::Vector3::UnitY());
02105         ref_y(2) = 0;
02106         ref_y.normalize();
02107         dr = hrp::Vector3(0,0,(hrp::Vector3(ref_y.cross(act_y))(2) > 0 ? 1.0 : -1.0) * std::acos(ref_y.dot(act_y))); // fix for rotation
02108     } else {
02109       ABCIKparam& tmpikp = ikp[graspless_manip_arm];
02110       act_hand_coords = rats::coordinates(tmpikp.target_p0,
02111                                           tmpikp.target_r0);
02112       rats::difference_rotation(dr, ref_hand_coords.rot, act_hand_coords.rot);
02113       dr(0) = 0; dr(1) = 0;
02114     }
02115     dp = act_hand_coords.pos - ref_hand_coords.pos
02116         + dr.cross(hrp::Vector3(foot_pos - act_hand_coords.pos));
02117     dp(2) = 0;
02118     hrp::Matrix33 foot_mt(gg->get_dst_foot_midcoords().rot.transpose());
02119     //alias(dp) = foot_mt * dp;
02120     hrp::Vector3 dp2 = foot_mt * dp;
02121     //alias(dr) = foot_mt * dr;
02122     return hrp::Vector3(graspless_manip_p_gain[0] * dp2(0)/gg->get_default_step_time(),
02123                         graspless_manip_p_gain[1] * dp2(1)/gg->get_default_step_time(),
02124                         graspless_manip_p_gain[2] * rad2deg(dr(2))/gg->get_default_step_time());
02125   } else {
02126     return hrp::Vector3::Zero();
02127   }
02128 };
02129 
02130 bool AutoBalancer::calc_inital_support_legs(const double& y, std::vector<coordinates>& initial_support_legs_coords, std::vector<leg_type>& initial_support_legs, coordinates& start_ref_coords) {
02131     switch(gait_type) {
02132     case BIPED:
02133         initial_support_legs_coords = (y > 0 ?
02134                                        boost::assign::list_of(coordinates(ikp["rleg"].target_p0, ikp["rleg"].target_r0))
02135                                        : boost::assign::list_of(coordinates(ikp["lleg"].target_p0, ikp["lleg"].target_r0)));
02136         initial_support_legs = (y > 0 ? boost::assign::list_of(RLEG) : boost::assign::list_of(LLEG));
02137         break;
02138     case TROT:
02139         initial_support_legs_coords = (y > 0 ?
02140                                        boost::assign::list_of(coordinates(ikp["rleg"].target_p0, ikp["rleg"].target_r0))(coordinates(ikp["larm"].target_p0, ikp["larm"].target_r0))
02141                                        : boost::assign::list_of(coordinates(ikp["lleg"].target_p0, ikp["lleg"].target_r0))(coordinates(ikp["rarm"].target_p0, ikp["rarm"].target_r0)));
02142         initial_support_legs = (y > 0 ? boost::assign::list_of(RLEG)(LARM) : boost::assign::list_of(LLEG)(RARM));
02143         break;
02144     case PACE:
02145         initial_support_legs_coords = (y > 0 ?
02146                                        boost::assign::list_of(coordinates(ikp["rleg"].target_p0, ikp["rleg"].target_r0))(coordinates(ikp["rarm"].target_p0, ikp["rarm"].target_r0))
02147                                        : boost::assign::list_of(coordinates(ikp["lleg"].target_p0, ikp["lleg"].target_r0))(coordinates(ikp["larm"].target_p0, ikp["larm"].target_r0)));
02148         initial_support_legs = (y > 0 ? boost::assign::list_of(RLEG)(RARM) : boost::assign::list_of(LLEG)(LARM));
02149         break;
02150     case CRAWL:
02151         std::cerr << "[" << m_profile.instance_name << "] crawl walk[" << gait_type << "] is not implemented yet." << std::endl;
02152         return false;
02153     case GALLOP:
02154         /* at least one leg shoud be in contact */
02155         std::cerr << "[" << m_profile.instance_name << "] gallop walk[" << gait_type << "] is not implemented yet." << std::endl;
02156         return false;
02157     default: break;
02158     }
02159     start_ref_coords.pos = (ikp["rleg"].target_p0+ikp["lleg"].target_p0)*0.5;
02160     mid_rot(start_ref_coords.rot, 0.5, ikp["rleg"].target_r0, ikp["lleg"].target_r0);
02161     return true;
02162 };
02163 
02164 // TODO : Use same code as ZMPDistributor.h
02165 // Solve A * x = b => x = W A^T (A W A^T)-1 b
02166 // => x = W^{1/2} Pinv(A W^{1/2}) b
02167 // Copied from ZMPDistributor.h
02168 void calcWeightedLinearEquation(hrp::dvector& ret, const hrp::dmatrix& A, const hrp::dmatrix& W, const hrp::dvector& b)
02169 {
02170     hrp::dmatrix W2 = hrp::dmatrix::Zero(W.rows(), W.cols());
02171     for (size_t i = 0; i < W.rows(); i++) W2(i,i) = std::sqrt(W(i,i));
02172     hrp::dmatrix Aw = A*W2;
02173     hrp::dmatrix Aw_inv = hrp::dmatrix::Zero(A.cols(), A.rows());
02174     hrp::calcPseudoInverse(Aw, Aw_inv);
02175     ret = W2 * Aw_inv * b;
02176     //ret = W2 * Aw.colPivHouseholderQr().solve(b);
02177 };
02178 
02179 void AutoBalancer::distributeReferenceZMPToWrenches (const hrp::Vector3& _ref_zmp)
02180 {
02181     // apply inverse system
02182     // TODO : fix 0.055 (zmp delay)
02183     hrp::Vector3 tmp_ref_zmp = _ref_zmp + 0.055 * (_ref_zmp - prev_ref_zmp) / m_dt;
02184 
02185     std::vector<hrp::Vector3> cop_pos;
02186     std::vector<double> limb_gains;
02187     for (size_t i = 0 ; i < leg_names.size(); i++) {
02188         ABCIKparam& tmpikp = ikp[leg_names[i]];
02189         cop_pos.push_back(tmpikp.target_p0 + tmpikp.target_r0 * tmpikp.localR * default_zmp_offsets[i]);
02190         limb_gains.push_back(m_contactStates.data[contact_states_index_map[leg_names[i]]] ? 1.0 : 0.0);
02191     }
02192     size_t ee_num = leg_names.size();
02193     size_t state_dim = 6*ee_num;
02194     size_t total_wrench_dim = 5;
02195     // size_t total_fz = m_robot->totalMass() * gg->get_gravitational_acceleration();
02196     size_t total_fz = m_ref_force[0].data[2]+m_ref_force[1].data[2];
02197     //size_t total_wrench_dim = 3;
02198     hrp::dmatrix Wmat = hrp::dmatrix::Identity(state_dim/2, state_dim/2);
02199     hrp::dmatrix Gmat = hrp::dmatrix::Zero(total_wrench_dim, state_dim/2);
02200     // Set Gmat
02201     //   Fill Fz
02202     for (size_t j = 0; j < ee_num; j++) {
02203         if (total_wrench_dim == 3) {
02204             Gmat(0,3*j+2) = 1.0;
02205         } else {
02206             for (size_t k = 0; k < 3; k++) Gmat(k,3*j+k) = 1.0;
02207         }
02208     }
02209     //   Fill Nx and Ny
02210     for (size_t i = 0; i < total_wrench_dim; i++) {
02211         for (size_t j = 0; j < ee_num; j++) {
02212             if ( i == total_wrench_dim-2 ) { // Nx
02213                 Gmat(i,3*j+1) = -(cop_pos[j](2) - tmp_ref_zmp(2));
02214                 Gmat(i,3*j+2) = (cop_pos[j](1) - tmp_ref_zmp(1));
02215             } else if ( i == total_wrench_dim-1 ) { // Ny
02216                 Gmat(i,3*j) = (cop_pos[j](2) - tmp_ref_zmp(2));
02217                 Gmat(i,3*j+2) = -(cop_pos[j](0) - tmp_ref_zmp(0));
02218             }
02219         }
02220     }
02221     // Set Wmat
02222     for (size_t j = 0; j < ee_num; j++) {
02223         for (size_t i = 0; i < 3; i++) {
02224             if (ee_num == 2)
02225                 Wmat(i+j*3, i+j*3) = Wmat(i+j*3, i+j*3) * limb_gains[j] * (i==2? 1.0 : 0.01);
02226             else
02227                 Wmat(i+j*3, i+j*3) = Wmat(i+j*3, i+j*3) * limb_gains[j];
02228         }
02229     }
02230     // Ret is wrench around cop_pos
02231     //   f_cop = f_ee
02232     //   n_ee = (cop_pos - ee_pos) x f_cop + n_cop
02233     hrp::dvector ret(state_dim/2);
02234     hrp::dvector total_wrench = hrp::dvector::Zero(total_wrench_dim);
02235     total_wrench(total_wrench_dim-5) = m_ref_force[0].data[0]+m_ref_force[1].data[0];
02236     total_wrench(total_wrench_dim-4) = m_ref_force[0].data[1]+m_ref_force[1].data[1];
02237     total_wrench(total_wrench_dim-3) = total_fz;
02238     calcWeightedLinearEquation(ret, Gmat, Wmat, total_wrench);
02239     if (DEBUGP) {
02240         std::cerr << "[" << m_profile.instance_name << "] distributeReferenceZMPToWrenches" << std::endl;
02241     }
02242     for (size_t i = 0 ; i < leg_names.size(); i++) {
02243         size_t fidx = contact_states_index_map[leg_names[i]];
02244         ABCIKparam& tmpikp = ikp[leg_names[i]];
02245         hrp::Vector3 f_ee(ret(3*i), ret(3*i+1), ret(3*i+2));
02246         //hrp::Vector3 tmp_ee_pos = tmpikp.target_p0 + tmpikp.target_r0 * tmpikp.localPos;
02247         hrp::Vector3 tmp_ee_pos = tmpikp.target_p0;
02248         hrp::Vector3 n_ee = (cop_pos[i]-tmp_ee_pos).cross(f_ee); // n_cop = 0
02249         m_force[fidx].data[0] = f_ee(0);
02250         m_force[fidx].data[1] = f_ee(1);
02251         m_force[fidx].data[2] = f_ee(2);
02252         m_force[fidx].data[3] = n_ee(0);
02253         m_force[fidx].data[4] = n_ee(1);
02254         m_force[fidx].data[5] = n_ee(2);
02255         if (DEBUGP) {
02256             std::cerr << "[" << m_profile.instance_name << "]   "
02257                       << "ref_force  [" << leg_names[i] << "] " << f_ee.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "[", "]")) << "[N], "
02258                       << "ref_moment [" << leg_names[i] << "] " << n_ee.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "[", "]")) << "[Nm]" << std::endl;
02259         }
02260     }
02261     if (DEBUGP) {
02262         std::cerr << "[" << m_profile.instance_name << "]   Gmat = " << Gmat.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "[", "]")) << "[N,Nm]" << std::endl;
02263         std::cerr << "[" << m_profile.instance_name << "]   total_wrench = " << total_wrench.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "[", "]")) << "[N,Nm]" << std::endl;
02264         hrp::dvector tmp(total_wrench.size());
02265         tmp = Gmat*ret;
02266         std::cerr << "[" << m_profile.instance_name << "]   Gmat*ret = " << tmp.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "[", "]")) << "[N,Nm]" << std::endl;
02267         std::cerr << "[" << m_profile.instance_name << "]   (Gmat*ret-total_wrench) = " << (tmp-total_wrench).format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "[", "]")) << "[N,Nm]" << std::endl;
02268         std::cerr << "[" << m_profile.instance_name << "]   ret = " << ret.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", "[", "]")) << "[N,Nm]" << std::endl;
02269         std::cerr << "[" << m_profile.instance_name << "]   Wmat(diag) = [";
02270         for (size_t j = 0; j < ee_num; j++) {
02271             for (size_t i = 0; i < 3; i++) {
02272                 std::cerr << Wmat(i+j*3, i+j*3) << " ";
02273             }
02274         }
02275         std::cerr << "]" << std::endl;
02276     }
02277 };
02278 
02279 std::string AutoBalancer::getUseForceModeString ()
02280 {
02281     switch (use_force) {
02282     case OpenHRP::AutoBalancerService::MODE_NO_FORCE:
02283         return "MODE_NO_FORCE";
02284     case OpenHRP::AutoBalancerService::MODE_REF_FORCE:
02285         return "MODE_REF_FORCE";
02286     case OpenHRP::AutoBalancerService::MODE_REF_FORCE_WITH_FOOT:
02287         return "MODE_REF_FORCE_WITH_FOOT";
02288     case OpenHRP::AutoBalancerService::MODE_REF_FORCE_RFU_EXT_MOMENT:
02289         return "MODE_REF_FORCE_RFU_EXT_MOMENT";
02290     default:
02291         return "";
02292     }
02293 };
02294 
02295 //
02296 extern "C"
02297 {
02298 
02299     void AutoBalancerInit(RTC::Manager* manager)
02300     {
02301         RTC::Properties profile(autobalancer_spec);
02302         manager->registerFactory(profile,
02303                                  RTC::Create<AutoBalancer>,
02304                                  RTC::Delete<AutoBalancer>);
02305     }
02306 
02307 };
02308 
02309 


hrpsys
Author(s): AIST, Fumio Kanehiro
autogenerated on Wed Sep 6 2017 02:35:54