Exemplo n.º 1
0
//=======================================================
// AddToolByFileName
//=======================================================
bool mitk::OptitrackTrackingDevice::AddToolByDefinitionFile(std::string fileName)
{
  bool resultSetToolByFileName;
  if(m_initialized)
  {
    OptitrackTrackingTool::Pointer t = OptitrackTrackingTool::New();
    resultSetToolByFileName= t->SetToolByFileName(fileName);

    if(resultSetToolByFileName)
    {
      this->m_AllTools.push_back(t);
      MITK_INFO << "Added tool "<<t->GetToolName()<< ". Tool vector size is now: "<<m_AllTools.size();
      return true;
    }
    else
    {
      MITK_INFO << "Tool could not be added";
      mitkThrowException(mitk::IGTException) << "Tool could not be added";
      return false;
  }
  }
  else
  {
    MITK_INFO << "System is not Initialized -> Cannot Add tools";
    mitkThrowException(mitk::IGTException) << "System is not Initialized -> Cannot Add tools";
    return false;
  }
}
mitk::SemanticRelationsDataStorageAccess::DataNodeVector mitk::SemanticRelationsDataStorageAccess::GetAllSpecificImages(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::InformationType& informationType) const
{
  if (SemanticRelationsInference::InstanceExists(caseID, controlPoint))
  {
    if (SemanticRelationsInference::InstanceExists(caseID, informationType))
    {
      // control point exists, information type exists, retrieve all images from the storage
      DataNodeVector allImagesOfCase = GetAllImagesOfCase(caseID);
      // filter all images to remove the ones with a different control point and information type using a lambda function
      auto lambda = [&controlPoint, &informationType, this](DataNode::Pointer imageNode)
      {
        return (informationType != SemanticRelationsInference::GetInformationTypeOfImage(imageNode))
            || (controlPoint.date != SemanticRelationsInference::GetControlPointOfImage(imageNode).date);
      };

      allImagesOfCase.erase(std::remove_if(allImagesOfCase.begin(), allImagesOfCase.end(), lambda), allImagesOfCase.end());

      return allImagesOfCase;
    }
    else
    {
      mitkThrowException(SemanticRelationException) << "Could not find an existing information type for the given caseID " << caseID << " and information type " << informationType;
    }
  }
  else
  {
    mitkThrowException(SemanticRelationException) << "Could not find an existing control point for the given caseID " << caseID << " and control point " << controlPoint.UID;
  }
}
mitk::NavigationDataSet::Pointer mitk::NavigationDataReaderXML::Read(std::string fileName)
{
  //save old locale
  char * oldLocale;
  oldLocale = setlocale( LC_ALL, 0 );

  //define own locale
  std::locale C("C");
  setlocale( LC_ALL, "C" );

  m_FileName = fileName;

  TiXmlDocument document;
  if ( !document.LoadFile(fileName))
  {
    mitkThrowException(mitk::IGTIOException) << "File '"<<fileName<<"' could not be loaded.";
  }

  TiXmlElement* m_DataElem = document.FirstChildElement("Version");
  if(!m_DataElem)
  {
    // for backwards compatibility of version tag
    m_DataElem = document.FirstChildElement("Data");
    if(!m_DataElem)
    {
      mitkThrowException(mitk::IGTIOException) << "Data element not found.";
    }

  }

  if (m_DataElem->QueryIntAttribute("Ver", &m_FileVersion) != TIXML_SUCCESS)
  {
    if (m_DataElem->QueryIntAttribute("version", &m_FileVersion) != TIXML_SUCCESS)
    {
      mitkThrowException(mitk::IGTIOException) << "Version not specified in XML file.";
    }
  }

  if (m_FileVersion != 1)
  {
    mitkThrowException(mitk::IGTIOException) << "File format version "<<m_FileVersion<<" is not supported.";
  }

  m_parentElement = document.FirstChildElement("Data");
  if(!m_parentElement)
  {
    mitkThrowException(mitk::IGTIOException) << "Data element not found.";
  }

  m_parentElement->QueryIntAttribute("ToolCount", &m_NumberOfOutputs);

  mitk::NavigationDataSet::Pointer navigationDataSet = this->ReadNavigationDataSet();

  //switch back to old locale
  setlocale( LC_ALL, oldLocale );

  return navigationDataSet;
}
Exemplo n.º 4
0
//=======================================================
// TrackTools
//=======================================================
void mitk::OptitrackTrackingDevice::TrackTools()
{
  MITK_DEBUG << "TrackTools";

  Point3D position;
  ScalarType t = 0.0;

  try
  {
    bool localStopTracking;       // Because m_StopTracking is used by two threads, access has to be guarded by a mutex. To minimize thread locking, a local copy is used here
    this->m_StopTrackingMutex->Lock();  // update the local copy of m_StopTracking
    localStopTracking = this->m_StopTracking;

    /* lock the TrackingFinishedMutex to signal that the execution rights are now transfered to the tracking thread */
    if (!localStopTracking)
    {
    m_TrackingFinishedMutex->Lock();
    }

  this->m_StopTrackingMutex->Unlock();
    while ((this->GetState() == mitk::TrackingDevice::Tracking) && (localStopTracking == false))
    {
      // For each Tracked Tool update the position and orientation
      for (  int i = 0; i < GetToolCount(); ++i)  // use mutexed methods to access tool container
      {
        OptitrackTrackingTool* currentTool = this->GetOptitrackTool(i);
        if(currentTool != nullptr)
        {
          currentTool->updateTool();
          MITK_DEBUG << "Tool number " << i << " updated position";
        }
        else
        {
          MITK_DEBUG << "Get data from tool number " << i << " failed";
          mitkThrowException(mitk::IGTException) << "Get data from tool number " << i << " failed";
        }
      }

      /* Update the local copy of m_StopTracking */
      this->m_StopTrackingMutex->Lock();
      localStopTracking = m_StopTracking;
      this->m_StopTrackingMutex->Unlock();
      Sleep(OPTITRACK_FRAME_RATE);
    } // tracking ends if we pass this line

    m_TrackingFinishedMutex->Unlock(); // transfer control back to main thread
  }
  catch(...)
  {
    m_TrackingFinishedMutex->Unlock();
    this->StopTracking();
    mitkThrowException(mitk::IGTException) << "Error while trying to track tools. Thread stopped.";
  }
}
Exemplo n.º 5
0
bool mitk::ClaronTrackingDevice::OpenConnection()
{
  bool returnValue;
  //Create the temp directory
  itksys::SystemTools::MakeDirectory(m_ToolfilesDir.c_str());

  m_Device->Initialize(m_CalibrationDir,m_ToolfilesDir);
  returnValue = m_Device->StartTracking();

  if (returnValue)
  {
    this->SetState(Ready);
  }
  else
  {
    //reset everything
    if (m_Device.IsNull())
    {
      m_Device = mitk::ClaronInterface::New();
      m_Device->Initialize(m_CalibrationDir, m_ToolfilesDir);
    }
    m_Device->StopTracking();
    this->SetState(Setup);
    mitkThrowException(mitk::IGTHardwareException) << "Error while trying to open connection to the MicronTracker.";
  }
  return returnValue;
}
void mitk::NavigationDataRecorderDeprecated::StartRecording(std::ostream* stream)
{
    if (m_Recording)
    {
        MITK_WARN << "Already recording please stop before start new recording session";
        return;
    }

    m_Stream = stream;
    m_Stream->precision(10);

    //TODO store date and GMT time
    //cheking if the stream is good
    if (m_Stream->good())
    {
        if (m_OutputFormat == mitk::NavigationDataRecorderDeprecated::xml)
        {
            *m_Stream << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" << std::endl;
            /**m_Stream << "<Version Ver=\"1\" />" << std::endl;*/
            // should be a generic version, meaning a member variable, which has the actual version
            *m_Stream << "    " << "<Data ToolCount=\"" << (m_NumberOfInputs) << "\" version=\"1.0\">" << std::endl;
        }
        m_Recording = true;
    }
    else
    {
        m_Recording = false;
        mitkThrowException(mitk::IGTException)<<"The stream is not good";
    }
}
Exemplo n.º 7
0
//=======================================================
// ThreadStartTracking
//=======================================================
ITK_THREAD_RETURN_TYPE mitk::OptitrackTrackingDevice::ThreadStartTracking(void* pInfoStruct)
{
  MITK_DEBUG << "ThreadStartTracking";

  /* extract this pointer from Thread Info structure */
  struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct;

  if (pInfo == NULL)
  {
    return ITK_THREAD_RETURN_VALUE;
  }

  if (pInfo->UserData == NULL)
  {
    return ITK_THREAD_RETURN_VALUE;
  }

  OptitrackTrackingDevice *trackingDevice = static_cast<OptitrackTrackingDevice*>(pInfo->UserData);

  if (trackingDevice != NULL)
  {
    // Call the TrackTools function in this thread
    trackingDevice->TrackTools();
  }
  else
  {
    mitkThrowException(mitk::IGTException) << "In ThreadStartTracking(): trackingDevice is NULL";
  }

  trackingDevice->m_ThreadID = -1; // reset thread ID because we end the thread here
  return ITK_THREAD_RETURN_VALUE;
}
Exemplo n.º 8
0
//=======================================================
// OpenConnection
//=======================================================
bool mitk::OptitrackTrackingDevice::OpenConnection()
{
  // Not initialize the system twice.
  if(!m_initialized)
  {
    MITK_DEBUG << "Initialize Optitrack Tracking System";

  if( this->InitializeCameras() )
  {
    m_initialized = true; // Set the initialized variable to true
    this->SetState(mitk::TrackingDevice::Ready);
      if(this->m_calibrationPath.empty()){
      MITK_INFO << "Numer of connected cameras = " << TT_CameraCount();
      MITK_WARN << "Attention: No calibration File defined !!";
      return m_initialized;
    }
    else
    {
      this->LoadCalibration();
    }
  }
  else
  {
    m_initialized = false; // Set the initialized variable to false
    this->SetState(mitk::TrackingDevice::Setup); // Set the State to Setup
    MITK_INFO << "Device initialization failed. Device is still in setup state";
    mitkThrowException(mitk::IGTException) << "Device initialization failed. Device is still in setup state";
  }
  }
  //this->LoadCalibration();
  return m_initialized;
}
mitk::SemanticRelationsDataStorageAccess::DataNodeVector mitk::SemanticRelationsDataStorageAccess::GetAllImagesOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion) const
{
  if (m_DataStorage.IsExpired())
  {
    mitkThrowException(SemanticRelationException) << "Not a valid data storage.";
  }

  DataNodeVector allImagesOfLesion;
  // 1. get all segmentations that define the lesion
  // 2. retrieve the parent node (source) of the found segmentation node
  DataNodeVector allSegmentationsOfLesion = GetAllSegmentationsOfLesion(caseID, lesion);
  for (const auto& segmentationNode : allSegmentationsOfLesion)
  {
    // get parent node of the current segmentation node with the node predicate
    DataStorage::SetOfObjects::ConstPointer parentNodes = m_DataStorage.Lock()->GetSources(segmentationNode, NodePredicates::GetImagePredicate(), false);
    for (auto it = parentNodes->Begin(); it != parentNodes->End(); ++it)
    {
      DataNode::Pointer dataNode = it->Value();
      allImagesOfLesion.push_back(it->Value());
    }
  }

  std::sort(allImagesOfLesion.begin(), allImagesOfLesion.end());
  allImagesOfLesion.erase(std::unique(allImagesOfLesion.begin(), allImagesOfLesion.end()), allImagesOfLesion.end());
  return allImagesOfLesion;
}
Exemplo n.º 10
0
//=======================================================
// StopTracking
//=======================================================
bool mitk::OptitrackTrackingDevice::StopTracking()
{
  MITK_DEBUG << "StopTracking";

  if (this->GetState() == mitk::TrackingDevice::Tracking) // Only if the object is in the correct state
  {
    //Change the StopTracking value
    m_StopTrackingMutex->Lock();  // m_StopTracking is used by two threads, so we have to ensure correct thread handling
    m_StopTrackingMutex->Unlock();
    this->SetState(mitk::TrackingDevice::Ready);
  }
  else
  {
    MITK_INFO << "System is not in State Tracking -> Cannot StopTracking";
    mitkThrowException(mitk::IGTException) << "System is not in State Tracking -> Cannot StopTracking";
    return false;
  }

  /******************************************************************************
  ###############################################################################
  TODO: check the timestamp from the Optitrack API
  ###############################################################################
  ******************************************************************************/
  mitk::IGTTimeStamp::GetInstance()->Stop(this);

  m_TrackingFinishedMutex->Lock();
  return true;
}
mitk::NavigationToolStorage::Pointer mitk::NavigationToolStorageDeserializer::Deserialize(std::string filename)
  {
  bool success = false;
  
  //decomress zip file into temporary directory
  decomressFiles(filename,m_tempDirectory);
  
  //now read all files and convert them to navigation tools
  mitk::NavigationToolStorage::Pointer returnValue = mitk::NavigationToolStorage::New(m_DataStorage);
  bool cont = true;
  int i;
  for (i=0; cont==true; i++)
    {
    std::string fileName = m_tempDirectory + Poco::Path::separator() + "NavigationTool" + convertIntToString(i) + ".tool";
    mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New();
    mitk::NavigationTool::Pointer readTool = myReader->DoRead(fileName);
    if (readTool.IsNull()) cont = false;
    else returnValue->AddTool(readTool);
    //delete file
    std::remove(fileName.c_str());
    }
  if(i==1)
    {
    //throw an exception here in case of not finding any tool
    m_ErrorMessage = "Error: did not find any tool. \n Is this a tool storage file?";
    mitkThrowException(mitk::IGTException)<<"Error: did not find any tool. \n Is this a tool storage file?";
    }
  return returnValue;
  }
mitk::SemanticRelationsDataStorageAccess::DataNodeVector mitk::SemanticRelationsDataStorageAccess::GetAllSegmentationsOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion) const
{
  if (SemanticRelationsInference::InstanceExists(caseID, lesion))
  {
    // lesion exists, retrieve all case segmentations from the storage
    DataNodeVector allSegmentationsOfLesion = GetAllSegmentationsOfCase(caseID);

    // filter all segmentations: check for semantic relation with the given lesion using a lambda function
    auto lambda = [&lesion, this](DataNode::Pointer segmentation)
    {
      try
      {
        SemanticTypes::Lesion representedLesion = SemanticRelationsInference::GetLesionOfSegmentation(segmentation);
        return lesion.UID != representedLesion.UID;
      }
      catch (const SemanticRelationException&)
      {
        return true;
      }
    };
    allSegmentationsOfLesion.erase(std::remove_if(allSegmentationsOfLesion.begin(), allSegmentationsOfLesion.end(), lambda), allSegmentationsOfLesion.end());

    return allSegmentationsOfLesion;
  }
  else
  {
    mitkThrowException(SemanticRelationException) << "Could not find an existing lesion instance for the given caseID " << caseID << " and lesion " << lesion.UID << ".";
  }
}
Exemplo n.º 13
0
//=======================================================
// LoadCalibration
//=======================================================
bool mitk::OptitrackTrackingDevice::LoadCalibration()
{
  MITK_DEBUG << "Loading System Calibration";
  int resultLoadCalibration;

  // Check the file path
  if(this->m_calibrationPath.empty()){
    MITK_INFO << "Calibration Path is empty";
    mitkThrowException(mitk::IGTException) << "Calibration Path is empty";
    return false;
  }

  // Once the system is ready and Initialized , a calibration file is loaded.
  if(this->m_initialized)
  {

    for( int i=OPTITRACK_ATTEMPTS; i>0; i--)
    {
      resultLoadCalibration = TT_LoadCalibration(this->m_calibrationPath.c_str());

      if(resultLoadCalibration != NPRESULT_SUCCESS)
      {
        MITK_DEBUG << mitk::OptitrackErrorMessages::GetOptitrackErrorMessage(resultLoadCalibration);
        MITK_DEBUG << "Trying again...";
      }
      else
      {
        MITK_DEBUG << "Calibration file has been loaded successfully";
        return true;
      }

    }

    MITK_INFO << "System cannot load a calibration file";
    mitkThrowException(mitk::IGTException) << "System cannot load a calibration file";

  }
  else
  {
    MITK_INFO << "System is not ready for load a calibration file because it has not been initialized yet";
    mitkThrowException(mitk::IGTException) << "System is not ready for load a calibration file because it has not been initialized yet";
        return false;
  }

  // Never reach this point
  return false;
}
Exemplo n.º 14
0
//=======================================================
// CloseConnection
//=======================================================
bool mitk::OptitrackTrackingDevice::CloseConnection()
{
  MITK_DEBUG << "CloseConnection";
  int resultStop, resultShutdown;

  if(m_initialized) // Close connection if the System was initialized first
  {
    if(this->GetState() == mitk::TrackingDevice::Tracking)
  {
      MITK_DEBUG << "Device state: Tracking -> Stoping the Tracking";
      resultStop = this->StopTracking(); //Stop tracking on close
    }

    this->SetState(mitk::OptitrackTrackingDevice::Setup);

    for( int i=OPTITRACK_ATTEMPTS; i>0; i--)
    {

      TT_ClearTrackableList();
      resultShutdown = TT_Shutdown();

      if(resultShutdown == NPRESULT_SUCCESS)
      {
        MITK_DEBUG << "System has been Shutdown Correctly";
        Sleep(2000);
        return true;
      }
      else
      {
        MITK_DEBUG << "System cannot ShutDown now. Trying again...";
      }
    }

    MITK_INFO << "System cannot ShutDown now";
    mitkThrowException(mitk::IGTException) << mitk::OptitrackErrorMessages::GetOptitrackErrorMessage(resultShutdown);
    return false;
 }
 else
 {
   MITK_INFO << "System has not been initialized. Close connection cannot be done";
   mitkThrowException(mitk::IGTException) << "System has not been initialized. Close connection cannot be done";
   return false;
 }

 return false;
}
Exemplo n.º 15
0
//=======================================================
// Destructor
//=======================================================
mitk::OptitrackTrackingDevice::~OptitrackTrackingDevice()
{
  MITK_DEBUG << "Deleting OptitrackTrackingDevice";
  int result;

  // If device is in Tracking mode, stop the Tracking firts
  if (this->GetState() == mitk::TrackingDevice::Tracking)
  {
    MITK_DEBUG << "OptitrackTrackingDevice in Tracking State -> Stopping Tracking";
    result = this->StopTracking();

    if(result == NPRESULT_SUCCESS){
      MITK_INFO << "OptitrackTrackingDevice Stopped";
    }
    else
  {
      MITK_INFO << "Error during Stopping";
      mitkThrowException(mitk::IGTException) << mitk::OptitrackErrorMessages::GetOptitrackErrorMessage(result);
    }
  }

  // If device is Ready, Close the connection to device and release the memory
  if (this->GetState() == mitk::TrackingDevice::Ready)
  {
    MITK_DEBUG << "OptitrackTrackingDevice in Ready State ->  Closing the Connection";
    result = this->CloseConnection();

    if(result)
    {
      MITK_INFO << "OptitrackTrackingDevice Connection closed";
    }
    else
    {
      MITK_DEBUG << "Error during Closing Connection";
      mitkThrowException(mitk::IGTException) << mitk::OptitrackErrorMessages::GetOptitrackErrorMessage(result);
    }
  }

  // Set the device off
  m_initialized = false;
  // Change State to Setup
  this->SetState(mitk::TrackingDevice::Setup);
  MITK_DEBUG <<"OptitrackTrackingDevice deleted successfully";
}
Exemplo n.º 16
0
unsigned int mitk::NavigationDataPlayer::GetFileVersion(std::istream* stream)
{
  if (stream==NULL)
  {
    MITK_ERROR << "No input stream set!";
    mitkThrowException(mitk::IGTException)<<"No input stream set!";
  }
  if (!stream->good())
  {
    MITK_ERROR << "Stream is not good!";
    mitkThrowException(mitk::IGTException)<<"Stream is not good!";
  }
  int version = 1;

  TiXmlDeclaration* dec = new TiXmlDeclaration();
  *stream >> *dec;
  if(strcmp(dec->Version(),"") == 0)
  {
    MITK_ERROR << "The input stream seems to have XML incompatible format";
    mitkThrowException(mitk::IGTIOException) << "The input stream seems to have XML incompatible format";
  }

  m_parentElement = new TiXmlElement("");
  *stream >> *m_parentElement; //2nd line this is the file version

  std::string tempValue = m_parentElement->Value();
  if(tempValue != "Version")
  {
      if(tempValue == "Data"){
          m_parentElement->QueryIntAttribute("version",&version);
      }
  }
  else
  {
    m_parentElement->QueryIntAttribute("Ver",&version);
  }

  if (version > 0)
    return version;
  else
    return 0;

}
Exemplo n.º 17
0
void mitk::ImageReadAccessor::OrganizeReadAccess()
{
  m_Image->m_ReadWriteLock.Lock();

  // Check, if there is any Write-Access going on
  if (m_Image->m_Writers.size() > 0)
  {
    // Check for every WriteAccessors, if the Region of this ImageAccessors overlaps
    // make sure this iterator is not used, when m_ReadWriteLock is Unlocked!
    auto it = m_Image->m_Writers.begin();

    for (; it != m_Image->m_Writers.end(); ++it)
    {
      ImageAccessorBase *w = *it;
      if (Overlap(w))
      {
        // An Overlap was detected. There are two possibilities to deal with this situation:
        // Throw an exception or wait for the WriteAccessor w until it is released and start again with the request
        // afterwards.
        if (!(m_Options & ExceptionIfLocked))
        {
          PreventRecursiveMutexLock(w);

          // WAIT
          w->Increment();
          m_Image->m_ReadWriteLock.Unlock();
          ImageAccessorBase::WaitForReleaseOf(w->m_WaitLock);

          // after waiting for the WriteAccessor w, start this method again
          OrganizeReadAccess();
          return;
        }
        else
        {
          // THROW EXCEPTION
          m_Image->m_ReadWriteLock.Unlock();
          mitkThrowException(mitk::MemoryIsLockedException)
            << "The image part being ordered by the ImageAccessor is already in use and locked";
          return;
        }
      } // if
    }   // for
  }     // if

  // Now, we know, that there is no conflict with a Write-Access
  // Lock the Mutex in ImageAccessorBase, to make sure that every other ImageAccessor has to wait if it locks the mutex
  m_WaitLock->m_Mutex.Lock();

  // insert self into readers list in Image
  m_Image->m_Readers.push_back(this);

  // printf("ReadAccess %d %d\n",(int) m_Image->m_Readers.size(),(int) m_Image->m_Writers.size());
  // fflush(0);
  m_Image->m_ReadWriteLock.Unlock();
}
Exemplo n.º 18
0
void mitk::NavigationDataPlayer::GenerateData()
{
  if ( m_NavigationDataSet->Size() == 0 )
  {
    MITK_WARN << "Cannot do anything with empty set of navigation datas.";
    return;
  }

  //Only produce new output if the player is started
  if (m_CurPlayerState != PlayerRunning)
  {
    //The output is not valid anymore
    this->GraftEmptyOutput();
    return;
  }

  // get elapsed time since start of playing
  m_TimeStampSinceStart = mitk::IGTTimeStamp::GetInstance()->GetElapsed() - m_StartPlayingTimeStamp;

  // add offset of the first navigation data to the timestamp to start playing
  // imediatly with the first navigation data (not to wait till the first time
  // stamp is reached)
  TimeStampType timeStampSinceStartWithOffset = m_TimeStampSinceStart
      + m_NavigationDataSet->Begin()->at(0)->GetIGTTimeStamp();

  // iterate through all NavigationData objects of the given tool index
  // till the timestamp of the NavigationData is greater then the given timestamp
  for (; m_NavigationDataSetIterator != m_NavigationDataSet->End(); ++m_NavigationDataSetIterator)
  {
    // test if the timestamp of the successor is greater than the time stamp
    if ( m_NavigationDataSetIterator+1 == m_NavigationDataSet->End() ||
        (m_NavigationDataSetIterator+1)->at(0)->GetIGTTimeStamp() > timeStampSinceStartWithOffset )
    {
      break;
    }
  }

  for (unsigned int index = 0; index < GetNumberOfOutputs(); index++)
  {
    mitk::NavigationData* output = this->GetOutput(index);
    if( !output ) { mitkThrowException(mitk::IGTException) << "Output of index "<<index<<" is null."; }

    output->Graft(m_NavigationDataSetIterator->at(index));
  }

  // stop playing if the last NavigationData objects were grafted
  if (m_NavigationDataSetIterator+1 == m_NavigationDataSet->End())
  {
    this->StopPlaying();

    // start playing again if repeat is enabled
    if ( m_Repeat ) { this->StartPlaying(); }
  }
}
Exemplo n.º 19
0
bool mitk::IGTLClient::OpenConnection()
{
  if (this->GetState() != Setup)
  {
    mitkThrowException(mitk::Exception) <<
      "Can only try to open the connection if in setup mode";
    return false;
  }

  std::string hostname = this->GetHostname();
  int portNumber = this->GetPortNumber();

  if (portNumber == -1 || hostname.size() <= 0)
  {
    //port number or hostname was not correct
    return false;
  }

  //create a new client socket
  m_Socket = igtl::ClientSocket::New();

  //try to connect to the igtl server
  int response = dynamic_cast<igtl::ClientSocket*>(m_Socket.GetPointer())->
    ConnectToServer(hostname.c_str(), portNumber);

  //check the response
  if ( response != 0 )
  {
    mitkThrowException(mitk::Exception) <<
      "The client could not connect to " << hostname << " port: " << portNumber;
    return false;
  }

  // everything is initialized and connected so the communication can be started
  this->SetState(Ready);

  //inform observers about this new client
  this->InvokeEvent(NewClientConnectionEvent());

  return true;
}
void QmitkMITKIGTTrackingToolboxView::StartLogging()
  {

  if (m_ToolVisualizationFilter.IsNull())
  {
    MessageBox("Cannot activate logging without a connected device. Configure and connect a tracking device first.");
    return;
  }

  if (!m_logging)
    {
    //initialize logging filter
    m_loggingFilter = mitk::NavigationDataRecorder::New();
    m_loggingFilter->SetRecordingMode(mitk::NavigationDataRecorder::NormalFile);
    if (m_Controls->m_xmlFormat->isChecked()) m_loggingFilter->SetOutputFormat(mitk::NavigationDataRecorder::xml);
    else if (m_Controls->m_csvFormat->isChecked()) m_loggingFilter->SetOutputFormat(mitk::NavigationDataRecorder::csv);
    std::string filename = m_Controls->m_LoggingFileName->text().toStdString().c_str();
    // this part has been changed in order to prevent crash of the  program
    if(!filename.empty())
    m_loggingFilter->SetFileName(filename);
    else if(filename.empty()){
     std::string errormessage = "File name has not been set, please set the file name";
     mitkThrowException(mitk::IGTIOException)<<errormessage;
     QMessageBox::warning(NULL, "IGTPlayer: Error", errormessage.c_str());
     m_loggingFilter->SetFileName(filename);
    }

    if (m_Controls->m_LoggingLimit->isChecked()){m_loggingFilter->SetRecordCountLimit(m_Controls->m_LoggedFramesLimit->value());}

    //connect filter
    for(int i=0; i<m_ToolVisualizationFilter->GetNumberOfOutputs(); i++){m_loggingFilter->AddNavigationData(m_ToolVisualizationFilter->GetOutput(i));}

    //start filter with try-catch block for exceptions
    try
    {
    m_loggingFilter->StartRecording();
    }
    catch(mitk::IGTException)
    {
    std::string errormessage = "Error during start recording. Recorder already started recording?";
    QMessageBox::warning(NULL, "IGTPlayer: Error", errormessage.c_str());
    m_loggingFilter->StopRecording();
    return;
    }

    //update labels / logging variables
    this->m_Controls->m_LoggingLabel->setText("Logging ON");
    this->m_Controls->m_LoggedFramesLabel->setText("Logged Frames: 0");
    m_loggedFrames = 0;
    m_logging = true;
    DisableLoggingButtons();
  }
  }
Exemplo n.º 21
0
unsigned int mitk::NavigationDataPlayer::GetNumberOfNavigationDatas(std::istream* stream)
{
  if (stream == NULL)
  {
    MITK_ERROR << "No input stream set!";
    mitkThrowException(mitk::IGTException)<<"No input stream set!";
  }
  if (!stream->good())
  {
    MITK_ERROR << "Stream not good!";
    mitkThrowException(mitk::IGTException)<<"Stream not good!";
  }

  //If something has changed in a future version of the XML definition e.g. navigationcount or addional parameters
  //catch this here with a select case block (see GenerateData() method)

  int numberOfTools = 0;

  std::string tempValue = m_parentElement->Value();
  if(tempValue == "Version"){
    *stream >> *m_parentElement;
  }
Exemplo n.º 22
0
//=======================================================
// StartTracking
//=======================================================
bool mitk::OptitrackTrackingDevice::StartTracking()
{
  MITK_DEBUG << "StartTracking";
  bool resultIsTrackableTracked;

  if (this->GetState() != mitk::TrackingDevice::Ready)
  {
    MITK_INFO << "System is not in State Ready -> Cannot StartTracking";
    mitkThrowException(mitk::IGTException) << "System is not in State Ready -> Cannot StartTracking";
    return false;
  }

  this->SetState(mitk::TrackingDevice::Tracking);

  // Change the m_StopTracking Variable to false
  this->m_StopTrackingMutex->Lock();
  this->m_StopTracking = false;
  this->m_StopTrackingMutex->Unlock();

  m_TrackingFinishedMutex->Unlock(); // transfer the execution rights to tracking thread

  /******************************************************************************
  ###############################################################################
  TODO: check the timestamp from the Optitrack API
  ###############################################################################
  ******************************************************************************/
  mitk::IGTTimeStamp::GetInstance()->Start(this);

  // Launch multiThreader using the Function ThreadStartTracking that executes the TrackTools() method
  m_ThreadID = m_MultiThreader->SpawnThread(this->ThreadStartTracking, this);    // start a new thread that executes the TrackTools() method

  // Information for the user
  if(GetToolCount() == 0) MITK_INFO << "No tools are defined";

  for (  int i = 0; i < GetToolCount(); ++i)  // use mutexed methods to access tool container
  {
    resultIsTrackableTracked = TT_IsTrackableTracked(i);
    if(resultIsTrackableTracked)
    {
      MITK_DEBUG << "Trackable " << i << " is inside the Tracking Volume and it is Tracked";
    }
    else
    {
      MITK_DEBUG << "Trackable " << i << " is not been tracked. Check if it is inside the  Tracking volume";
    }

  }

  return true;
}
void mitk::NavigationToolStorageDeserializer::decompressFiles(std::string filename,std::string path)
{
  std::ifstream file( filename.c_str(), std::ios::binary );
  if (!file.good())
    {
    m_ErrorMessage = "Cannot open '" + filename + "' for reading";
    mitkThrowException(mitk::IGTException)<<"Cannot open"+filename+" for reading";
    }

  try
    {
    Poco::Zip::Decompress unzipper( file, Poco::Path( path ) );
    unzipper.decompressAllFiles();
    file.close();
    }

  catch(Poco::IllegalStateException e) //temporary solution: replace this by defined exception handling later!
    {
    m_ErrorMessage = "Error: wrong file format! \n (please only load tool storage files)";
    mitkThrowException(mitk::IGTException) << m_ErrorMessage;
    }

  }
bool mitk::NavigationToolStorageSerializer::Serialize(std::string filename, mitk::NavigationToolStorage::Pointer storage)
{
  //save every tool to temp directory
  mitk::NavigationToolWriter::Pointer myToolWriter = mitk::NavigationToolWriter::New();
  for(int i=0; i<storage->GetToolCount();i++)
  {
    std::string tempFileName = m_tempDirectory + Poco::Path::separator() + "NavigationTool" + convertIntToString(i) + ".tool";
    if (!myToolWriter->DoWrite(tempFileName,storage->GetTool(i)))
      {
        mitkThrowException(mitk::IGTIOException) << "Could not write tool to tempory directory: " << tempFileName;
      }
  }
  //add all files to zip archive
  std::ofstream file( filename.c_str(), std::ios::binary | std::ios::out);
  if (!file.good()) //test if the zip archive is ready for writing
  {
    //first: clean up
    for (int i=0; i<storage->GetToolCount();i++)
    {
      std::string tempFileName = m_tempDirectory + Poco::Path::separator() + "NavigationTool" + convertIntToString(i) + ".tool";
      std::remove(tempFileName.c_str());
    }
    //then: throw an exception
    mitkThrowException(mitk::IGTIOException) << "Could not open a file for writing: " << filename;
  }
  Poco::Zip::Compress zipper( file, true );
  for (int i=0; i<storage->GetToolCount();i++)
  {
    std::string fileName = m_tempDirectory + Poco::Path::separator() + "NavigationTool" + convertIntToString(i) + ".tool";
    zipper.addFile(fileName,myToolWriter->GetFileWithoutPath(fileName));
    std::remove(fileName.c_str()); //delete file
  }
 zipper.close();
 file.close();

 return true;
 }
Exemplo n.º 25
0
bool mitk::IGTLServer::OpenConnection()
{
  if (this->GetState() != Setup)
  {
    mitkThrowException(mitk::Exception) <<
      "Can only try to create a server if in setup mode";
    return false;
  }

  int portNumber = this->GetPortNumber();

  if (portNumber == -1)
  {
    //port number was not correct
    return false;
  }

  //create a new server socket
  m_Socket = igtl::ServerSocket::New();

  //try to create the igtl server
  int response = dynamic_cast<igtl::ServerSocket*>(m_Socket.GetPointer())->
    CreateServer(portNumber);

  //check the response
  if (response != 0)
  {
    mitkThrowException(mitk::Exception) <<
      "The server could not be created. Port: " << portNumber;
    return false;
  }

  // everything is initialized and connected so the communication can be started
  this->SetState(Ready);

  return true;
}
mitk::NavigationData::Pointer mitk::NavigationDataReaderXML::ReadVersion1()
{
  if ( !m_parentElement )
  {
    mitkThrowException(mitk::IGTIOException)
        << "Reading XML is not possible. Parent element is not set.";
  }

  TiXmlElement* elem;
  m_currentNode = m_parentElement->IterateChildren(m_currentNode);

  bool delElem;

  if(m_currentNode)
  {
    elem = m_currentNode->ToElement();
    if(elem==NULL)
    {
      mitkThrowException(mitk::IGTException) << "Cannot find element: Is this file damaged?";
    }
    delElem = false;
  }

  else
  {
    elem = new TiXmlElement("");
    delElem = true;
  }


  mitk::NavigationData::Pointer nd = this->ReadNavigationData(elem);

  if(delElem) { delete elem; }

  return nd;
}
Exemplo n.º 27
0
//=======================================================
// GetOptitrackTool
//=======================================================
mitk::OptitrackTrackingTool* mitk::OptitrackTrackingDevice::GetOptitrackTool( unsigned int toolNumber) const
{
  MITK_DEBUG << "ThreadStartTracking";
  OptitrackTrackingTool* t = nullptr;

  MutexLockHolder toolsMutexLockHolder(*m_ToolsMutex); // lock and unlock the mutex
  if(toolNumber < m_AllTools.size())
  {
    t = m_AllTools.at(toolNumber);
  }
  else
  {
  MITK_INFO << "The tool numbered " << toolNumber << " does not exist";
    mitkThrowException(mitk::IGTException) << "The tool numbered " << toolNumber << " does not exist";
  }
  return t;
}
mitk::SemanticRelationsDataStorageAccess::DataNodeVector mitk::SemanticRelationsDataStorageAccess::GetAllSegmentationsOfCase(const SemanticTypes::CaseID& caseID) const
{
  if (m_DataStorage.IsExpired())
  {
    mitkThrowException(SemanticRelationException) << "Not a valid data storage.";
  }

  std::vector<std::string> allSegmentationIDsOfCase = RelationStorage::GetAllSegmentationIDsOfCase(caseID);
  std::vector<DataNode::Pointer> allSegmentationsOfCase;
  // get all segmentation nodes of the current data storage
  // only those nodes are respected, that are currently held in the data storage
  DataStorage::SetOfObjects::ConstPointer segmentationNodes = m_DataStorage.Lock()->GetSubset(NodePredicates::GetSegmentationPredicate());
  for (auto it = segmentationNodes->Begin(); it != segmentationNodes->End(); ++it)
  {
    DataNode* segmentationNode = it->Value();

    std::string caseID;
    std::string segmentationID;
    try
    {
      // find the corresponding segmentation node for the given segmentation ID
      caseID = GetCaseIDFromDataNode(segmentationNode);
      segmentationID = GetIDFromDataNode(segmentationNode);
    }
    catch (SemanticRelationException&)
    {
      // found a segmentation node that is not stored in the semantic relations
      // this segmentation node does not have any DICOM information --> exception thrown
      // continue with the next segmentation to compare IDs
      continue;
    }

    if (caseID == caseID && (std::find(allSegmentationIDsOfCase.begin(), allSegmentationIDsOfCase.end(), segmentationID) != allSegmentationIDsOfCase.end()))
    {
      // found current image node in the storage, add it to the return vector
      allSegmentationsOfCase.push_back(segmentationNode);
    }
  }

  return allSegmentationsOfCase;
}
Exemplo n.º 29
0
//=======================================================
// InitializeCameras
//=======================================================
bool mitk::OptitrackTrackingDevice::InitializeCameras()
{
  MITK_DEBUG << "Initialize Optitrack";
  int result;

  result = TT_Initialize(); // Initialize the cameras

  if(result == NPRESULT_SUCCESS)
  {
    MITK_DEBUG << "Optitrack Initialization Succeed";
    return true;
  }
  else
  {
    MITK_DEBUG << mitk::OptitrackErrorMessages::GetOptitrackErrorMessage(result);
  // If not succeed after OPTITRACK_ATTEMPTS times launch exception
  MITK_INFO << "Optitrack Tracking System cannot be initialized \n" << mitk::OptitrackErrorMessages::GetOptitrackErrorMessage(result);
  mitkThrowException(mitk::IGTException) << "Optitrack Tracking System cannot be initialized \n" << mitk::OptitrackErrorMessages::GetOptitrackErrorMessage(result);
  return false;
  }
}
Exemplo n.º 30
0
bool mitk::ClaronTrackingDevice::StartTracking()
{

  //By Alfred: next line because no temp directory is set if MicronTracker is not installed
  if (!m_Device->IsMicronTrackerInstalled())
    return false;
  //##################################################################################

  //be sure that the temp-directory is empty at start: delete all files in the tool files directory
  itksys::SystemTools::RemoveADirectory(m_ToolfilesDir.c_str());
  itksys::SystemTools::MakeDirectory(m_ToolfilesDir.c_str());

  //copy all toolfiles into the temp directory
  for (unsigned int i=0; i<m_AllTools.size(); i++)
  {
    itksys::SystemTools::CopyAFile(m_AllTools[i]->GetFile().c_str(), m_ToolfilesDir.c_str());
  }
  this->SetState(Tracking);            // go to mode Tracking
  this->m_StopTrackingMutex->Lock();  // update the local copy of m_StopTracking
  this->m_StopTracking = false;
  this->m_StopTrackingMutex->Unlock();

  //restart the Microntracker, so it will load the new tool files
  m_Device->StopTracking();
  m_Device->Initialize(m_CalibrationDir,m_ToolfilesDir);

  m_TrackingFinishedMutex->Unlock(); // transfer the execution rights to tracking thread

  if (m_Device->StartTracking())
  {
    mitk::IGTTimeStamp::GetInstance()->Start(this);
    m_ThreadID = m_MultiThreader->SpawnThread(this->ThreadStartTracking, this);    // start a new thread that executes the TrackTools() method
    return true;
  }
  else
    {mitkThrowException(mitk::IGTHardwareException) << "Error while trying to start the device!";}
}