EigenGraspPlanner.cpp
Go to the documentation of this file.
00001 
00021 #include <grasp_planning_graspit/EigenGraspPlanner.h>
00022 #include <grasp_planning_graspit/LogBinding.h>
00023 #include <grasp_planning_graspit/PrintHelpers.h>
00024 #include <grasp_planning_graspit/EigenGraspResult.h>
00025 #include <grasp_planning_graspit/GraspItHelpers.h>
00026 
00027 #include <string>
00028 #include <vector>
00029 #include <algorithm>
00030 
00031 #include <graspit/matvec3D.h>
00032 #include <graspit/world.h>
00033 #include <graspit/robot.h>
00034 #include <graspit/body.h>
00035 #include <graspit/grasp.h>
00036 #include <graspit/eigenGrasp.h>
00037 
00038 #include <graspit/EGPlanner/search.h>
00039 #include <graspit/EGPlanner/searchState.h>
00040 #include <graspit/EGPlanner/energy/searchEnergy.h>
00041 #include <graspit/EGPlanner/egPlanner.h>
00042 #include <graspit/EGPlanner/simAnn.h>
00043 #include <graspit/EGPlanner/simAnnPlanner.h>
00044 
00045 #include <QWidget>
00046 #include <Inventor/Qt/SoQt.h>
00047 #include <Inventor/actions/SoWriteAction.h>
00048 #include <Inventor/actions/SoGetBoundingBoxAction.h>
00049 #include <Inventor/sensors/SoIdleSensor.h>
00050 
00051 #include <boost/filesystem.hpp>
00052 
00053 #define AUTOGRASP_VELOCITY 0.05
00054 #define QUICKOPEN_FACTOR 0.01
00055 
00056 using GraspIt::EigenGraspPlanner;
00057 using GraspIt::Log;
00058 
00059 EigenGraspPlanner::EigenGraspPlanner(const std::string& name, const SHARED_PTR<GraspItSceneManager>& intr):
00060     GraspItAccessor(name, intr),
00061     // mEnergyCalculator(NULL),
00062     graspitEgPlanner(NULL),
00063     graspitStateType(AxisAngle),
00064     graspitSearchEnergyType(EnergyContact),
00065     useContacts(true),
00066 #ifdef USE_SEPARATE_SOSENSOR
00067     mIdleSensor(NULL),
00068 #endif
00069     planCommand(NONE)
00070 {
00071     // mEnergyCalculator=new SearchEnergy();
00072     // mEnergyCalculator->setStatStream(&std::cout);
00073 
00074     if (!eventThreadRunsQt())
00075     {
00076         PRINTERROR("EigenGraspPlanner supports only GraspItSceneManager instances which run Qt.");
00077         throw std::string("EigenGraspPlanner supports only GraspItSceneManager instances which run Qt.");
00078     }
00079 
00080     addAsIdleListener();
00081 }
00082 
00083 EigenGraspPlanner::~EigenGraspPlanner()
00084 {
00085     PRINTMSG("EigenGrasp planner destructor");
00086 
00087     removeFromIdleListeners();
00088 
00089 #ifdef USE_SEPARATE_SOSENSOR
00090     // quit the idle sensor to avoid conflicts when Inventor
00091     // is shut down
00092     if (mIdleSensor)
00093     {
00094         if (mIdleSensor->isScheduled())
00095         {
00096             mIdleSensor->unschedule();
00097         }
00098         delete mIdleSensor;
00099         mIdleSensor = NULL;
00100     }
00101 #endif
00102 
00103     graspitEgPlannerMtx.lock();
00104     if (graspitEgPlanner)
00105     {
00106         delete graspitEgPlanner;
00107         graspitEgPlanner = NULL;
00108     }
00109     graspitEgPlannerMtx.unlock();
00110 
00111     deleteResults();
00112 
00113     // if (mEnergyCalculator) delete mEnergyCalculator;
00114     PRINTMSG("Exit EigenGrasp planner destructor");
00115 }
00116 
00117 
00118 void EigenGraspPlanner::onSceneManagerShutdown()
00119 {
00120 #ifdef USE_SEPARATE_SOSENSOR
00121     // quit the idle sensor to avoid conflicts when Inventor
00122     // is shut down
00123     if (mIdleSensor)
00124     {
00125         if (mIdleSensor->isScheduled())
00126         {
00127             mIdleSensor->unschedule();
00128         }
00129         delete mIdleSensor;
00130         mIdleSensor = NULL;
00131     }
00132 #endif
00133 
00134     graspitEgPlannerMtx.lock();
00135     if (graspitEgPlanner)
00136     {
00137         delete graspitEgPlanner;
00138         graspitEgPlanner = NULL;
00139     }
00140     graspitEgPlannerMtx.unlock();
00141 }
00142 
00143 void EigenGraspPlanner::idleEventFromSceneManager()
00144 {
00145 #ifdef USE_SEPARATE_SOSENSOR
00146     if (mIdleSensor)
00147     {
00148         if (mIdleSensor->isScheduled()) mIdleSensor->unschedule();
00149         delete mIdleSensor;
00150     }
00151 
00152     // start the idle sensor which is triggered regularly from within the inventor thread
00153     mIdleSensor = new SoIdleSensor(sensorCB, this);
00154     mIdleSensor->schedule();
00155 #else
00156     scheduleForIdleEventUpdate();
00157     ivIdleCallback();
00158 #endif
00159 }
00160 
00161 
00162 
00163 
00164 void EigenGraspPlanner::plannerUpdateSlot()
00165 {
00166     plannerUpdate();
00167 }
00168 
00169 void EigenGraspPlanner::plannerCompleteSlot()
00170 {
00171     PRINTMSG("Planning complete!!");
00172     setPlannerCommand(STOP);
00173 }
00174 
00175 
00176 EigenGraspPlanner::PlannerCommand EigenGraspPlanner::getPlannerCommand()
00177 {
00178     UNIQUE_LOCK lck(planCommandMtx);
00179     return planCommand;
00180 }
00181 
00182 void EigenGraspPlanner::setPlannerCommand(const PlannerCommand c)
00183 {
00184     UNIQUE_LOCK lck(planCommandMtx);
00185     planCommand = c;
00186 }
00187 
00188 
00189 #ifdef USE_SEPARATE_SOSENSOR
00190 void EigenGraspPlanner::sensorCB(void *data, SoSensor *)
00191 {
00192     // PRINTMSG(" ### sensorCB ###");
00193     EigenGraspPlanner* _this = dynamic_cast<EigenGraspPlanner*>(static_cast<EigenGraspPlanner*>(data));
00194     if (!_this)
00195     {
00196         PRINTERROR("Could not cast EigenGraspPlanner");
00197         return;
00198     }
00199 
00200     _this->ivIdleCallback();
00201 
00202     // trigger another call of this method in the next event loop iteration
00203     _this->mIdleSensor->schedule();
00204 }
00205 #endif
00206 
00207 void EigenGraspPlanner::ivIdleCallback()
00208 {
00209     if (!getGraspItSceneManager()->isInitialized())
00210     {
00211         PRINTWARN("Graspit scene manager not initialized.");
00212         return;
00213     }
00214 
00215     UNIQUE_RECURSIVE_LOCK(graspitEgPlannerMtx);
00216     if (getPlannerCommand() == START)
00217     {
00218         PRINTMSG("### Start planner! ###");
00219         assert(graspitEgPlanner);
00220         if (!graspitEgPlanner)
00221         {
00222             PRINTERROR("EigenGraspPlanner not initialized");
00223         }
00224         else
00225         {
00226             if (!QObject::connect(graspitEgPlanner, SIGNAL(update()),
00227                                   this, SLOT(plannerUpdateSlot()), Qt::DirectConnection) ||
00228                     !QObject::connect(graspitEgPlanner, SIGNAL(complete()),
00229                                       this, SLOT(plannerCompleteSlot()), Qt::DirectConnection))
00230             {
00231                 PRINTERROR("Could not connect signals and slots");
00232             }
00233             else
00234             {
00235                 PRINTMSG("Entering planner loop...");
00236                 // start the planner. This method is non-blocking:
00237                 // it kicks off the planner in a separate thread.
00238                 graspitEgPlanner->startPlanner();
00239             }
00240             // remove the starting flag, because the planner has either started
00241             // or a fatal error occurred.
00242             setPlannerCommand(NONE);
00243         }
00244     }
00245     else if (getPlannerCommand() == STOP)
00246     {
00247         if (!QObject::connect(graspitEgPlanner, SIGNAL(update()),
00248                               this, SLOT(plannerUpdateSlot()), Qt::DirectConnection) ||
00249                 !QObject::connect(graspitEgPlanner, SIGNAL(complete()),
00250                                   this, SLOT(plannerCompleteSlot()), Qt::DirectConnection))
00251         {
00252             PRINTERROR("Could not disconnect signals and slots");
00253         }
00254     }
00255 }
00256 
00257 
00258 bool EigenGraspPlanner::plan(const std::string& handName, const std::string& objectName,
00259                              const EigenTransform * objectPose,
00260                              const int maxPlanningSteps,
00261                              const int repeatPlanning,
00262                              const int maxResultsPerRepeat,
00263                              const bool finishWithAutograsp,
00264                              const PlannerType& planType)
00265 {
00266     if (!getGraspItSceneManager()->isInitialized())
00267     {
00268         PRINTERROR("Graspit scene manager not initialized. Cannot do planning.");
00269         return false;
00270     }
00271 
00272     // lock the world so that it won't change while we set the hand/object and do the planning
00273     UNIQUE_RECURSIVE_LOCK lock = getUniqueWorldLock();
00274     if (getGraspItSceneManager()->setCurrentHand(handName) != 0)
00275     {
00276         PRINTERROR("Could not set current hand " << handName);
00277         return false;
00278     }
00279     if (getGraspItSceneManager()->setCurrentGraspableObject(objectName) != 0)
00280     {
00281         PRINTERROR("Could not set current object " << objectName);
00282         return false;
00283     }
00284     if (objectPose && (getGraspItSceneManager()->moveObject(objectName, *objectPose) != 0))
00285     {
00286         PRINTERROR("Could not set the object pose");
00287         return false;
00288     }
00289 
00290     // for testing we can save the start world to see how it looks before we start planning
00291     // getGraspItSceneManager()->saveGraspItWorld("/home/jenny/test/worlds/startWorld.xml",true);
00292     // getGraspItSceneManager()->saveInventorWorld("/home/jenny/test/worlds/startWorld.iv",true);
00293 
00294     return plan(maxPlanningSteps, repeatPlanning, maxResultsPerRepeat, finishWithAutograsp, planType);
00295 }
00296 
00297 bool compareGraspPlanningStates(const GraspPlanningState* g1, const GraspPlanningState* g2)
00298 {
00299     return g1->getEnergy() < g2->getEnergy();
00300 }
00301 
00302 void EigenGraspPlanner::deleteResults()
00303 {
00304     for (std::vector<const GraspPlanningState*>::iterator it=results.begin(); it!=results.end(); ++it)
00305     {
00306         delete *it;
00307     }
00308     results.clear();
00309 }
00310 
00311 bool EigenGraspPlanner::plan(const int maxPlanningSteps,
00312                              const int repeatPlanning,
00313                              const int maxResultsPerRepeat,
00314                              const bool finishWithAutograsp,
00315                              const PlannerType& planType)
00316 {
00317     if (!getGraspItSceneManager()->isInitialized())
00318     {
00319         PRINTERROR("Graspit scene manager not initialized. Cannot do planning.");
00320         return false;
00321     }
00322 
00323     deleteResults();
00324 
00325     // lock the world so that it won't change while we do the planning
00326     UNIQUE_RECURSIVE_LOCK lock = getUniqueWorldLock();
00327 
00328     for (int i = 0; i < repeatPlanning; ++i)
00329     {
00330         //PRINTMSG("Initializing planning...");
00331         if (!initPlanner(maxPlanningSteps, planType))
00332         {
00333             PRINTERROR("Could not initialize planner.");
00334             return false;
00335         }
00336         {
00337             UNIQUE_RECURSIVE_LOCK(graspitEgPlannerMtx);
00338             if (!graspitEgPlanner)
00339             {
00340                 PRINTERROR("EigenGraspPlanner not initialized");
00341                 return false;
00342             }
00343 
00344             if (graspitEgPlanner->isActive())
00345             {
00346                 PRINTERROR("EigenGraspPlanner is already active, you cannot call plan()");
00347                 return false;
00348             }
00349 
00350             if (!graspitEgPlanner->isReady())
00351             {
00352                 PRINTERROR("EigenGraspPlanner is not ready.");
00353                 return false;
00354             }
00355         }
00356 
00357         PRINTMSG("Initiating planning, trial #"<<i);
00358 
00359         scheduleForIdleEventUpdate();
00360         setPlannerCommand(START);
00361 
00362         PRINTMSG("Waiting for planning algorithm to finish...");
00363         // this is the wait loop, ONLY needed for option a)
00364         while (getPlannerCommand() != STOP)
00365         {
00366             // PRINTMSG("EigenGraspPlanner is running");
00367             SLEEP(0.1);
00368         }
00369         // re-set planner command to none because now the stopping has been registered in this thread.
00370         setPlannerCommand(NONE);
00371 
00372         plannerComplete();
00373         PRINTMSG("Planning done.");
00374 
00375         // store results
00376         graspitEgPlannerMtx.lock();
00377 
00378         int numGrasps = std::min(graspitEgPlanner->getListSize(), maxResultsPerRepeat);
00379         for (int i = 0; i < numGrasps; ++i)
00380         {
00381             const GraspPlanningState *sOrig = graspitEgPlanner->getGrasp(i);
00382             GraspPlanningState * sCopy = new GraspPlanningState(sOrig);
00383             if (finishWithAutograsp)
00384             {
00385                 if (!sCopy->execute())
00386                 {
00387                     PRINTERROR("Could not execute grasp state for grasp "<<i<<", skipping auto-grasp");
00388                     continue;
00389                 }
00390                 else
00391                 {
00392                     if (!sCopy->getHand()->autoGrasp(false,AUTOGRASP_VELOCITY,false))
00393                     {
00394                         PRINTWARN("Could not perform autograsp for grasp "<<i);
00395                     }
00396                     else
00397                     {
00398                          sCopy->saveCurrentHandState();
00399                     }
00400                 }
00401             }
00402             results.push_back(sCopy);
00403         }
00404         graspitEgPlannerMtx.unlock();
00405     }
00406     std::sort(results.begin(), results.end(), compareGraspPlanningStates);
00407     return true;
00408 }
00409 
00410 /*void EigenGraspPlanner::stopPlanner()
00411 {
00412     graspitEgPlannerMtx.lock();
00413     graspitEgPlanner->pausePlanner();
00414     graspitEgPlannerMtx.unlock();
00415 }*/
00416 
00417 GraspIt::EigenTransform EigenGraspPlanner::getHandTransform(const GraspPlanningState * s) const
00418 {
00419     EigenTransform handTransform = getEigenTransform(s->getTotalTran());
00420     return handTransform;
00421 }
00422 
00423 GraspIt::EigenTransform EigenGraspPlanner::getObjectTransform(const GraspPlanningState * s) const
00424 {
00425     GraspableBody * object = s->getObject();
00426     if (!object)
00427     {
00428         PRINTERROR("Object not initialized");
00429         return EigenTransform::Identity();
00430     }
00431 
00432     transf pose = object->getTran();
00433     Quaternion q = pose.rotation();
00434     vec3 t = pose.translation();
00435 
00436     // PRINTMSG("Object position: "<<t.x()<<"/"<<t.y()<<"/"<<t.z());
00437     // PRINTMSG("Object quaternion: "<<q.x<<"/"<<q.y<<"/"<<q.z<<"/"<<q.w);
00438 
00439     EigenTransform objectTransform;
00440     objectTransform.setIdentity();
00441     Eigen::Vector3d eObjectTranslation(t.x(), t.y(), t.z());
00442     Eigen::Quaterniond eObjectQuaternion(q.w(), q.x(), q.y(), q.z());
00443 
00444     objectTransform = objectTransform.translate(eObjectTranslation);
00445     objectTransform = objectTransform.rotate(eObjectQuaternion);
00446 
00447     return objectTransform;
00448 }
00449 
00450 void EigenGraspPlanner::getGraspJointDOFs(const GraspPlanningState * s, std::vector<double>& dofs) const
00451 {
00452     if (!s->getHand())
00453     {
00454         PRINTERROR("Hand is NULL!");
00455         return;
00456     }
00457     const PostureState* handPosture = s->readPosture();
00458     if (!handPosture)
00459     {
00460         PRINTERROR("Posture is NULL!");
00461         return;
00462     }
00463 
00464     // this gets the DOF values for the 3 fingers. If the hand has only one EigenGrasp which is symmetric,
00465     // the 3 values will be the same.
00466     const int numDOF = s->getHand()->getNumDOF();
00467     double * _dofs = new double[numDOF];
00468     handPosture->getHandDOF(_dofs);
00469     // PRINTMSG("Grasp DOFs: ");
00470     for (int k = 0; k < numDOF; ++k)
00471     {
00472         // PRINTMSG(_dofs[k]);
00473         dofs.push_back(_dofs[k]);
00474     }
00475 }
00476 
00477 
00478 void EigenGraspPlanner::getPregraspJointDOFs(const GraspPlanningState * s, std::vector<double>& dofs) const
00479 {
00480     GraspPlanningState sCopy(s);
00481     if (!sCopy.getHand())
00482     {
00483         PRINTERROR("Hand is NULL!");
00484         return;
00485     }
00486     const int numDOF = sCopy.getHand()->getNumDOF();
00487     const PostureState* handPosture = sCopy.readPosture();
00488     if (!handPosture)
00489     {
00490         PRINTERROR("Posture is NULL!");
00491         return;
00492     }
00493     
00494     // execute the auto-grasp in "opening" direction
00495     if (!sCopy.execute())
00496     {
00497         PRINTWARN("Could not execute grasp state, the pre-grasp state may not be ideal.");
00498     }
00499     // opens hand until no collision is detected
00500     if (!sCopy.getHand()->quickOpen(QUICKOPEN_FACTOR))
00501     {
00502         PRINTMSG("INFO - EigenGraspPlanner: quickOpen() returned false. The hand may have been completely opened (quickOpen() is a Graspit! hack with no alternative so far, as auto-grasp requires collision-free state)");
00503     }
00504 
00505     // XXX test print:
00506     /*double * __dofs = new double[numDOF];
00507     sCopy.getHand()->getDOFVals(__dofs);
00508     PRINTMSG("After quickopen DOFs: ");
00509     for (int k = 0; k < numDOF; ++k)
00510     {
00511         PRINTMSG(__dofs[k]);
00512     }*/
00513     // XXX end test print
00514 
00515     // re-close grip until first contact, this should also retreat a tiny bit,
00516     // so that there are no more contacts
00517     /*if (!sCopy.getHand()->autoGrasp(false,AUTOGRASP_VELOCITY,true))
00518     {
00519         PRINTWARN("Could not correctly re-close hand with auto-grasp. The resulting pre-grasp state may not be ideal.");
00520     }*/
00521 
00522     // opens hand until a collision is detected. This will open the hand either all the way,
00523     // or not all the way if collision detected.
00524     // Prerequisite: Hand may not be in collision, otherwise this gets interpolation errors and 
00525     // returns false
00526     if (!sCopy.getHand()->autoGrasp(false,-AUTOGRASP_VELOCITY,true))
00527     {
00528         PRINTWARN("Could not correctly open hand with auto-grasp, the pre-grasp state may not be ideal.");
00529     }
00530     // in case a collision stopped the opening of hand, close the grip again
00531     // until no collision is detected. 
00532     /*if (!sCopy.getHand()->quickOpen(-QUICKOPEN_FACTOR))
00533     {
00534         PRINTWARN("Could not correctly open hand with auto-grasp, the pre-grasp state may not be ideal.");
00535     }*/
00536     sCopy.saveCurrentHandState();
00537 
00538     // this gets the DOF values for the 3 fingers. If the hand has only one EigenGrasp which is symmetric,
00539     // the 3 values will be the same.
00540     double * _dofs = new double[numDOF];
00541     handPosture->getHandDOF(_dofs);
00542     //PRINTMSG("Pre-grasp DOFs: ");
00543     for (int k = 0; k < numDOF; ++k)
00544     {
00545         //PRINTMSG(_dofs[k]);
00546         dofs.push_back(_dofs[k]);
00547     }
00548 }
00549 
00550 
00551 
00552 void EigenGraspPlanner::getEigenGraspValues(const GraspPlanningState * s, std::vector<double>& egVals) const
00553 {
00554     if (!s->readPosture())
00555     {
00556         PRINTERROR("Posture is NULL!");
00557         return;
00558     }
00559 
00560     const PostureState* handPosture = s->readPosture();
00561 
00562     // print the EigenGrasp value
00563     for (int k = 0; k < handPosture->getNumVariables(); ++k)
00564     {
00565         // PRINTMSG("EigenGrasp val " << k << ": " << handPosture->getVariable(k)->getValue());
00566         egVals.push_back(handPosture->getVariable(k)->getValue());
00567     }
00568 }
00569 
00570 bool EigenGraspPlanner::checkStateValidity(const GraspPlanningState * s) const
00571 {
00572     if (!s->readPosture() || !s->readPosition())
00573     {
00574         PRINTERROR("Posture or Position is NULL!");
00575         return false;
00576     }
00577 
00578     const PostureState* handPosture = s->readPosture();
00579     const PositionState* handPosition = s->readPosition();
00580 
00581     StateType postureType = handPosture->getType();
00582     if (postureType != POSE_EIGEN)
00583     {
00584         // TODO: testing neeed with other state types before we allow this
00585         PRINTERROR("Check if implementation for other pose types than Eigen work!");
00586         return false;
00587     }
00588     StateType positionType = handPosition->getType();
00589     if (positionType != SPACE_AXIS_ANGLE)
00590     {
00591         // TODO: testing neeed with other state types before we allow this
00592         PRINTERROR("Check if implementation for other position types than Axis-Angle work!");
00593         return false;
00594     }
00595 
00596     // we assume that the hand has not changed since we started the plannning
00597     const Hand * mHand = readCurrentHand();
00598     if (!mHand)
00599     {
00600         PRINTERROR("Hand is NULL!");
00601         return false;
00602     }
00603     if (mHand != s->getHand())
00604     {
00605         PRINTERROR("We have changed hand pointer!!!");
00606         return false;
00607     }
00608 
00609     return true;
00610 }
00611 
00612 
00613 bool EigenGraspPlanner::saveResultsAsWorldFiles(const std::string& inDirectory,
00614         const std::string& fileNamePrefix, bool asGraspIt,
00615         bool asInventor, bool createDir,
00616         bool saveSeparatePoseIV)
00617 {
00618     if (!asGraspIt && !asInventor)
00619     {
00620         PRINTERROR("Have to specify either to save results as GraspIt or as Inventor files");
00621         return false;
00622     }
00623 
00624     if (!getGraspItSceneManager()->isInitialized())
00625     {
00626         PRINTERROR("Graspit scene manager not initialized.");
00627         return false;
00628     }
00629 
00630     // retrieve robot name if separate pose file should be saved
00631     std::string robotName;
00632     if (saveSeparatePoseIV)
00633     {
00634         std::vector<std::string> robs = getGraspItSceneManager()->getRobotNames();       
00635         if (robs.empty())
00636         {
00637             PRINTERROR("No robots loaded");
00638             return false;
00639         }
00640         if (robs.size()!=1)
00641         {
00642             PRINTERROR("Exactly 1 robot should have been loaded");
00643             return false;
00644         }
00645         robotName=robs.front();
00646     }
00647 
00648     int numGrasps = results.size();
00649     for (int i = 0; i < numGrasps; ++i)
00650     {
00651         const GraspPlanningState * s = results[i];
00652         if (!s)
00653         {
00654             PRINTERROR("GraspPlanningState is NULL!");
00655             return false;
00656         }
00657 
00658         if (!checkStateValidity(s))
00659         {
00660             PRINTERROR("Cannot work with the state of grasp " << i);
00661             return false;
00662         }
00663 
00664         // Execute grasp so that the correct world is saved
00665         if (!s->execute())
00666         {
00667             PRINTERROR("Could not execute grasp state for grasp "<<i<<", won't save the result");
00668             continue;
00669         }
00670 
00671         std::stringstream _wFilename;
00672         _wFilename << inDirectory << "/" << fileNamePrefix << "_" << (i + 1);
00673         std::string wFilename = _wFilename.str();
00674         if (asGraspIt && !getGraspItSceneManager()->saveGraspItWorld(wFilename + ".xml", createDir))
00675         {
00676             PRINTERROR("GraspIt could not save world file " << i);
00677             return false;
00678         }
00679         if (asInventor && !getGraspItSceneManager()->saveInventorWorld(wFilename + ".iv", createDir))
00680         {
00681             PRINTERROR("GraspIt could not save world file " << i);
00682             return false;
00683         }
00684         bool forceWrite = createDir;  // only enforce if creating dir is also allowed
00685         if (saveSeparatePoseIV && !getGraspItSceneManager()->saveRobotAsInventor(wFilename + "_pose.iv", robotName, createDir, forceWrite))
00686         {
00687             PRINTERROR("GraspIt could not save robot pose file " << i);
00688         }
00689     }
00690     return true;
00691 }
00692 
00693 
00694 
00695 bool EigenGraspPlanner::copyResult(const GraspPlanningState * s, EigenGraspResult& result) const
00696 {
00697     if (!checkStateValidity(s))
00698     {
00699         PRINTERROR("Cannot work with this state");
00700         return false;
00701     }
00702 
00703     EigenTransform handTransform = getHandTransform(s);
00704     //PRINTMSG("RESULT "<<i<<" Hand transform: " << handTransform);
00705 
00706     EigenTransform objectTransform = getObjectTransform(s);
00707     //PRINTMSG("RESULT "<<i<<" Object transform: " << objectTransform);
00708 
00709     // Compute hand transform relative to object
00710     // objectTransform * relTransform = handTransform
00711     // relTransform = objectTransform.inverse() * handTransform;
00712     EigenTransform relTransform = objectTransform.inverse() * handTransform;
00713     
00714     //PRINTMSG("RESULT "<<i<<" rel transform: " << relTransform);
00715 
00716     // PRINTMSG("Relative transform: " << relTransform);
00717 
00718     // PRINTMSG("-- getting (pre)grasp DOFs --");
00719     std::vector<double> graspDOFs;
00720     getGraspJointDOFs(s, graspDOFs);
00721     /*     int k=0;
00722          for (std::vector<double>::const_iterator it=graspDOFs.begin(); it!=graspDOFs.end(); ++it){
00723              PRINTMSG("Grasp hand DOF "<<k<<": "<<*it);
00724              ++k;
00725          }
00726     */
00727     std::vector<double> pregraspDOFs;
00728     getPregraspJointDOFs(s, pregraspDOFs);
00729     /*     int k=0;
00730          for (std::vector<double>::const_iterator it=pregraspDOFs.begin(); it!=pregraspDOFs.end(); ++it){
00731              PRINTMSG("Grasp hand DOF "<<k<<": "<<*it);
00732              ++k;
00733          }
00734     */
00735     std::vector<double> egVals;
00736     getEigenGraspValues(s, egVals);
00737     /*      for (std::vector<double>::const_iterator it=egVals.begin(); it!=egVals.end(); ++it){
00738               PRINTMSG("EigenGrasp value "<<k<<": "<<*it);
00739               ++k;
00740           }*/
00741     result = EigenGraspResult(relTransform, graspDOFs, pregraspDOFs, egVals,
00742                 s->isLegal(), s->getEpsilonQuality(), s->getVolume(), s->getEnergy());
00743     return true;
00744 }
00745 
00746 
00747 
00748 
00749 void EigenGraspPlanner::getResults(std::vector<EigenGraspResult>& allGrasps) const
00750 {
00751     int numGrasps = results.size();
00752     for (int i = 0; i < numGrasps; ++i)
00753     {
00754         const GraspPlanningState * s = results[i];
00755         EigenGraspResult res;
00756         if (!copyResult(s,res))
00757         {
00758             PRINTERROR("Cannot work with this state");
00759             continue;
00760         }
00761         allGrasps.push_back(res);
00762     }
00763 }
00764 
00765 
00766 std::string getSearchEnergyType(const EigenGraspPlanner::GraspItSearchEnergyType& st)
00767 {
00768   std::string ret;
00769     switch (st)
00770     {
00771     case EigenGraspPlanner::EnergyContact:
00772     {
00773         ret = "CONTACT_ENERGY";
00774         break;
00775     }
00776     // CONTACT_ENERGY, POTENTIAL_QUALITY_ENERGY, CONTACT_QUALITY_ENERGY,
00777     // AUTOGRASP_QUALITY_ENERGY, GUIDED_AUTOGRASP_ENERGY, STRICT_AUTOGRASP_ENERGY,
00778     // COMPLIANT_ENERGY, DYNAMIC_ENERGY
00779     default:
00780     {
00781         PRINTERROR("Unsupported search type");
00782     }
00783     }
00784     return ret;
00785 }
00786 
00787 
00788 
00789 
00790 StateType getStateType(const EigenGraspPlanner::GraspItStateType& st)
00791 {
00792     StateType ret;
00793     switch (st)
00794     {
00795     case EigenGraspPlanner::AxisAngle:
00796     {
00797         ret = SPACE_AXIS_ANGLE;
00798         break;
00799     }
00800     /*    case SPACE_AXIS_ANGLE:
00801         case SPACE_COMPLETE:
00802         case SPACE_ELLIPSOID:
00803         case SPACE_APPROACH:
00804     */
00805     default:
00806     {
00807         PRINTERROR("Unsupported search type");
00808     }
00809     }
00810     return ret;
00811 }
00812 
00813 
00814 
00815 
00816 
00817 bool EigenGraspPlanner::initPlanner(const int maxPlanningSteps, const PlannerType& plannerType)
00818 {
00819     Hand * mHand = getCurrentHand();
00820     GraspableBody * mObject = getCurrentGraspableBody();
00821     if (!mHand || !mObject)
00822     {
00823         PRINTERROR("Cannot initialize planner if no current hand and/or object is loaded");
00824         return false;
00825     }
00826 
00827     if (!mHand->getEigenGrasps())
00828     {
00829         PRINTERROR("Current hand has no EigenGrasp information!");
00830         return false;
00831     }
00832 
00833     if (!mHand->getGrasp())
00834     {
00835         PRINTERROR("Grasp is NULL!");
00836         return false;
00837     }
00838 
00839     if (mHand->getGrasp()->getObject() != mObject)
00840     {
00841         // this should already be set, but if it wasn't we could do it with this:
00842         // mHand->getGrasp()->setObjectNoUpdate(mObject);
00843         PRINTERROR("Consistency: Currently loaded object to grasp should be the same!");
00844         return false;
00845     }
00846 
00847     // mHand->getGrasp()->setGravity(true);
00848     mHand->getGrasp()->setGravity(false);
00849     GraspPlanningState graspPlanningState(mHand);
00850     graspPlanningState.setObject(mObject);
00851     StateType _stateType = getStateType(graspitStateType);
00852     graspPlanningState.setPositionType(_stateType);
00853     graspPlanningState.setRefTran(mObject->getTran());
00854     graspPlanningState.reset();
00855 
00856     /*
00857     // initialize variable types for this search:
00858     for (int i=0; i<graspPlanningState.getNumVariables(); i++) {
00859         // if checkbox in interface is checked:
00860         graspPlanningState.getVariable(i)->setFixed(false);
00861         graspPlanningState.getVariable(i)->setConfidence(0.0);
00862     }*/
00863 
00864     graspitEgPlannerMtx.lock();
00865 
00866     graspitEgPlanner = NULL;
00867 
00868     initSearchType(graspPlanningState, graspitStateType);
00869 
00870     initPlannerType(graspPlanningState, plannerType);
00871 
00872     setPlanningParameters();
00873     // steps
00874     graspitEgPlanner->setMaxSteps(maxPlanningSteps);
00875 
00876     graspitEgPlannerMtx.unlock();
00877 
00878     // print stats of the current grasp planning state
00879     /*    for (int i=0; i<graspPlanningState.getNumVariables(); i++) {
00880             std::string varName=graspPlanningState.getVariable(i)->getName().toStdString();
00881             float varValue=graspPlanningState.getVariable(i)->getValue();
00882             bool varFixed=graspPlanningState.getVariable(i)->isFixed();
00883             float varConf=graspPlanningState.getVariable(i)->getConfidence();
00884             PRINTMSG("Variable: "<<varName<<", value="<<varValue<<", fixed="<<varFixed<<", conf="<<varConf);
00885         }
00886     */
00887     return true;
00888 }
00889 
00890 
00891 
00892 void EigenGraspPlanner::initSearchType(GraspPlanningState& graspPlanningState, const GraspItStateType& st)
00893 {
00894     StateType _stateType = getStateType(st);
00895     graspPlanningState.setPositionType(_stateType);
00896 
00897     GraspableBody * mObject = getCurrentGraspableBody();
00898     if (!mObject)
00899     {
00900         PRINTERROR("Object is NULL!");
00901         return;
00902     }
00903 
00904     switch (st)
00905     {
00906         /*    case SPACE_AXIS_ANGLE:
00907             case SPACE_COMPLETE:
00908             case SPACE_ELLIPSOID:*/
00909     case AxisAngle:
00910     {
00911         graspPlanningState.setRefTran(mObject->getTran());
00912         break;
00913     }
00914     /*    case SPACE_APPROACH:
00915         {
00916             Hand * mHand = getCurrentHand();
00917             if (!mHand)
00918             {
00919                 PRINTERROR("Hand is NULL!");
00920                 return;
00921             }
00922             graspPlanningState.setRefTran(mHand->getTran());
00923             break;
00924         }*/
00925     default:
00926     {
00927         PRINTERROR("Unsupported search type");
00928     }
00929     }
00930 
00931     graspPlanningState.reset();
00932 
00933     // force a reset of the planner
00934     graspitEgPlannerMtx.lock();
00935     if (graspitEgPlanner)
00936     {
00937         graspitEgPlanner->invalidateReset();
00938     }  // if graspitEgPlanner is NULL, it will have to be created again in initPlannerType()
00939     graspitEgPlannerMtx.unlock();
00940 }
00941 
00942 
00943 
00944 void EigenGraspPlanner::initPlannerType(const GraspPlanningState& graspPlanningState, const PlannerType &pt)
00945 {
00946     PRINTMSG("Initializing planner type");
00947 
00948 
00949     Hand * mHand = getCurrentHand();
00950     if (!mHand)
00951     {
00952         PRINTERROR("Hand is NULL!");
00953         return;
00954     }
00955 
00956     UNIQUE_RECURSIVE_LOCK(graspitEgPlannerMtx);
00957 
00958     // tell the planner which GraspPlanningState parameters to use by the graspPlanningState object.
00959     // the graspPlanningState object is only used as template in the functions called below (the object
00960     // is copied by the graspitEgPlanner object)
00961     switch (pt)
00962     {
00963     case SimAnn:
00964     {
00965         if (graspitEgPlanner) delete graspitEgPlanner;
00966         SimAnnPlanner * planner = new SimAnnPlanner(mHand);
00967         planner->setModelState(&graspPlanningState);
00968         graspitEgPlanner = planner;
00969         break;
00970     }
00971     /*case Loop: {
00972         if (graspitEgPlanner) delete graspitEgPlanner;
00973         graspitEgPlanner = new LoopEigenGraspPlanner(mHand);
00974         ((LoopEigenGraspPlanner*)graspitEgPlanner)->setModelState(&graspPlanningState);
00975     }
00976     case MultiThreaded: {
00977         if (graspitEgPlanner) delete graspitEgPlanner;
00978         graspitEgPlanner = new GuidedEigenGraspPlanner(mHand);
00979         ((GuidedEigenGraspPlanner*)graspitEgPlanner)->setModelState(&graspPlanningState);
00980     } */
00981     default:
00982     {
00983         PRINTERROR("Unknown planner type requested");
00984         return;
00985     }
00986     }
00987 
00988     plannerReset();
00989 }
00990 
00991 
00992 
00993 void EigenGraspPlanner::setPlanningParameters()
00994 {
00995     UNIQUE_RECURSIVE_LOCK(graspitEgPlannerMtx);
00996     if (!graspitEgPlanner)
00997     {
00998         PRINTERROR("Planner is NULL!");
00999         return;
01000     }
01001 
01002     std::string _searchEnergyType = getSearchEnergyType(graspitSearchEnergyType);
01003     graspitEgPlanner->setEnergyType(_searchEnergyType);
01004 
01005     // contact type
01006     if (useContacts)
01007     {
01008         graspitEgPlanner->setContactType(CONTACT_PRESET);
01009         // if (mEnergyCalculator) mEnergyCalculator->setContactType(CONTACT_PRESET);
01010     }
01011     else
01012     {
01013         graspitEgPlanner->setContactType(CONTACT_LIVE);
01014         // if (mEnergyCalculator) mEnergyCalculator->setContactType(CONTACT_LIVE);
01015     }
01016 
01017 
01018     // if (mEnergyCalculator) mEnergyCalculator->setType(_searchEnergyType);
01019 }
01020 
01021 
01022 
01023 
01024 void EigenGraspPlanner::plannerReset()
01025 {
01026     UNIQUE_RECURSIVE_LOCK(graspitEgPlannerMtx);
01027     if (!graspitEgPlanner)
01028     {
01029         PRINTERROR("Planner is NULL!");
01030         return;
01031     }
01032 
01033     assert(graspitEgPlanner);
01034     setPlanningParameters();
01035 
01036     graspitEgPlanner->resetPlanner();
01037 }
01038 
01039 
01040 void EigenGraspPlanner::plannerUpdate()
01041 {
01042     PRINTMSG("=== EigenGraspPlanner update ===");
01043     updateResults();
01044 }
01045 
01046 
01047 void EigenGraspPlanner::plannerComplete()
01048 {
01049     //printPlanningResults();
01050     PRINTMSG("=== EigenGraspPlanner complete ===");
01051 }
01052 
01053 void EigenGraspPlanner::updateResults()
01054 {
01055     UNIQUE_RECURSIVE_LOCK(graspitEgPlannerMtx);
01056     if (!graspitEgPlanner)
01057     {
01058         PRINTERROR("Planner is NULL!");
01059         return;
01060     }
01061 
01062     int nStep = graspitEgPlanner->getCurrentStep();
01063     float runTime = graspitEgPlanner->getRunningTime();
01064     PRINTMSG("Current Step: " << nStep);
01065     // PRINTMSG("Current time: " << runTime);
01066 
01067     printResult(0, false);
01068 }
01069 
01070 
01071 /* double EigenGraspPlanner::getEnergy(const GraspPlanningState * s)
01072 {
01073     s->execute();
01074     bool l; double e;
01075     if (mEnergyCalculator) mEnergyCalculator->analyzeCurrentPosture(s->getHand(), s->getObject(), l, e, false);
01076     return e;
01077 }*/
01078 
01079 
01080 
01081 
01082 /*void EigenGraspPlanner::printEnergy(int i)
01083 {
01084     assert (i>=0 && i < graspitEgPlanner->getListSize());
01085     const GraspPlanningState *s = graspitEgPlanner->getGrasp(i);
01086     s->execute();
01087     bool l; double e;
01088     if (mEnergyCalculator) mEnergyCalculator->analyzeCurrentPosture(s->getHand(), s->getObject(), l, e, false);
01089     PRINTMSG("Re-computed energy: " << e);
01090 }
01091 */
01092 
01093 void EigenGraspPlanner::printResult(int i, bool detailed)
01094 {
01095     UNIQUE_RECURSIVE_LOCK(graspitEgPlannerMtx);
01096     if (!graspitEgPlanner)
01097     {
01098         PRINTERROR("Planner is NULL!");
01099         return;
01100     }
01101 
01102     int d = graspitEgPlanner->getListSize();
01103     int rank, size, iteration;
01104     double energy;
01105 
01106     int displayState = i;
01107 
01108     if (d == 0)
01109     {
01110         displayState = rank = size = energy = iteration = 0;
01111     }
01112     else if (displayState < 0)
01113     {
01114         displayState = 0;
01115     }
01116     else if (displayState >= d)
01117     {
01118         displayState = d - 1;
01119     }
01120 
01121     const GraspPlanningState *s = NULL;
01122 
01123     if (d != 0)
01124     {
01125         s = graspitEgPlanner->getGrasp(displayState);
01126         if (!s)
01127         {
01128             PRINTERROR("GraspPlanningState is NULL!");
01129             return;
01130         }
01131         rank = displayState + 1;
01132         size = d;
01133         iteration = s->getItNumber();
01134         energy = s->getEnergy();
01135     }
01136 
01137     /*
01138     FILE *f = fopen("foo.txt","w");
01139     for (int i=0; i<graspitEgPlanner->getListSize(); i++) {
01140         for(int j=i+1; j<graspitEgPlanner->getListSize(); j++) {
01141             float d = graspitEgPlanner->getGrasp(i)->distance( graspitEgPlanner->getGrasp(j) );
01142             fprintf(stderr,"%d -- %d: %f\n",i+1,j+1,d);
01143         }
01144         fprintf(stderr,"\n");
01145         graspitEgPlanner->getGrasp(i)->writeToFile(f);
01146     }
01147     fclose(f);
01148     */
01149 
01150     // PRINTMSG("Rank: " << rank << "/" << size);
01151     // PRINTMSG("Iteration: " << iteration);
01152     PRINTMSG("Energy: " << energy);
01153 
01154     if (s && detailed)
01155     {
01156         PRINTMSG("Detailed state:");
01157         s->printState();
01158     }
01159 }
01160 
01161 
01162 void EigenGraspPlanner::printPlanningResults()
01163 {
01164     PRINTMSG("########## Final results ############");
01165     UNIQUE_RECURSIVE_LOCK(graspitEgPlannerMtx);
01166     if (!graspitEgPlanner)
01167     {
01168         PRINTERROR("Planner is NULL!");
01169         return;
01170     }
01171     int numResults = graspitEgPlanner->getListSize();
01172     for (int i = 0; i < numResults; ++i)
01173     {
01174         PRINTMSG("---------------------");
01175         PRINTMSG("--- Result #" << (i + 1) << "  ---");
01176         PRINTMSG("---------------------");
01177         printResult(i, true);
01178         // printEnergy(i);
01179     }
01180 }
01181 
01182 
01183 /*
01184 void EigenGraspPlanner::inputLoad(const std::string& inputGraspFile)
01185 {
01186     if (inputGraspFile.empty())
01187     {
01188         PRINTERROR("No input grasp file specified");
01189         return;
01190     }
01191 
01192     UNIQUE_RECURSIVE_LOCK(graspitEgPlannerMtx);
01193     if (!graspitEgPlanner)
01194     {
01195         PRINTERROR("Planner is NULL!");
01196         return;
01197     }
01198 
01199     FILE *fp = fopen(inputGraspFile.c_str(), "r");
01200     bool success = true;
01201     if (!fp)
01202     {
01203         PRINTMSG("Failed to open input file!");
01204         success = false;
01205     }
01206     else if (!graspitEgPlanner->getTargetState()->readFromFile(fp))
01207     {
01208         PRINTMSG("Failed to read target from input file!");
01209         success = false;
01210     }
01211     else
01212     {
01213         PRINTMSG("Target values loaded successfully");
01214     }
01215     fclose(fp);
01216     graspitEgPlanner->setInput(INPUT_FILE, success);
01217 }
01218 */


grasp_planning_graspit
Author(s): Jennifer Buehler
autogenerated on Wed May 8 2019 02:53:36