void QmitkIGTLDeviceSetupConnectionWidget::OnConnect()
{
  if (m_IGTLDevice->GetState() == mitk::IGTLDevice::Setup)
  {
    QString port = m_Controls->editPort->text();
    m_IGTLDevice->SetPortNumber(port.toInt());
    std::string hostname = m_Controls->editIP->text().toStdString();
    m_IGTLDevice->SetHostname(hostname);
    //connect with the other OpenIGTLink device => changes the state from Setup
    //to Ready
    if (m_IGTLDevice->OpenConnection())
    {
      //starts the communication thread => changes the state from Ready to
      //Running
      if (m_IGTLDevice->StartCommunication())
      {
        if (this->m_IsClient)
        {
          MITK_INFO("IGTLDeviceSourceManagementWidget")
            << "Successfully connected to " << hostname
            << " on port " << port.toStdString();
        }
      }
      else
      {
        MITK_ERROR("QmitkIGTLDeviceSetupConnectionWidget") <<
          "Could not start a communication with the"
          "server because the client is in the wrong state";
      }
    }
    else
    {
      MITK_ERROR("QmitkIGTLDeviceSetupConnectionWidget") <<
        "Could not connect to the server. "
        "Please check the hostname and port.";
    }
  }
  else if (m_IGTLDevice->GetState() == mitk::IGTLDevice::Ready || m_IGTLDevice->GetState() == mitk::IGTLDevice::Running)
  {
    m_IGTLDevice->CloseConnection();
    MITK_INFO("QmitkIGTLDeviceSetupConnectionWidget") << "Closed connection";
  }
  else
  {
    mitkThrow() << "Invalid state of IGTLDevice";
  }
  this->AdaptGUIToState();
}
Example #2
0
bool mitk::USDevice::Connect()
{
  MITK_DEBUG << "mitk::USDevice::Connect() called";

  if (this->GetIsConnected())
  {
    MITK_INFO("mitkUSDevice") << "Tried to connect an ultrasound device that "
      "was already connected. Ignoring call...";
    return true;
  }

  if (!this->GetIsInitialized())
  {
    MITK_ERROR("mitkUSDevice")
      << "Cannot connect device if it is not in initialized state.";
    return false;
  }

  // Prepare connection, fail if this fails.
  if (!this->OnConnection())
  {
    return false;
  }

  // Update state
  m_DeviceState = State_Connected;

  this->UpdateServiceProperty(
    mitk::USDevice::GetPropertyKeys().US_PROPKEY_ISCONNECTED, true);
  return true;
}
Example #3
0
unsigned int mitk::IGTLDevice::SendMessagePrivate(igtl::MessageBase::Pointer msg,
                                          igtl::Socket::Pointer socket)
{
  //check the input message
  if ( msg.IsNull() )
  {
    MITK_ERROR("IGTLDevice") << "Could not send message because message is not "
                                "valid. Please check.";
    return false;
  }

  // add the name of this device to the message
  msg->SetDeviceName(this->GetName().c_str());

  // Pack (serialize) and send
  msg->Pack();

  // measure the time
  AddTrackingMeasurements(5, msg, 0);

  int sendSuccess = socket->Send(msg->GetPackPointer(), msg->GetPackSize());

  if (sendSuccess)
  {
     this->InvokeEvent(MessageSentEvent());
     return IGTL_STATUS_OK;
  }
  else
  {
     return IGTL_STATUS_UNKNOWN_ERROR;
  }
}
bool mitk::USCombinedModality::OnActivation()
{
  if ( m_UltrasoundDevice.IsNull() )
  {
    MITK_ERROR("USCombinedModality")("USDevice") << "UltrasoundDevice must not be null.";
    mitkThrow() << "UltrasoundDevice must not be null.";
  }

  mitk::TrackingDeviceSource::Pointer trackingDeviceSource = dynamic_cast<mitk::TrackingDeviceSource*>(m_TrackingDevice.GetPointer());
  if ( trackingDeviceSource.IsNull() )
  {
    MITK_WARN("USCombinedModality")("USDevice") << "Cannot start tracking as TrackingDeviceSource is null.";
  }
  trackingDeviceSource->StartTracking();

  // activate ultrasound device only if it is not already activated
  if ( m_UltrasoundDevice->GetDeviceState() >= mitk::USDevice::State_Activated )
  {
    return true;
  }
  else
  {
    return m_UltrasoundDevice->Activate();
  }
}
void QmitkUSNavigationStepPlacementPlanning::OnUpdate()
{
  this->UpdateTargetColors();

    // get navigation data source and make sure that it is not null
  mitk::NavigationDataSource::Pointer navigationDataSource = this->GetCombinedModality()->GetNavigationDataSource();
  if ( navigationDataSource.IsNull() )
  {
    MITK_ERROR("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepPunctuationIntervention")
    << "Navigation Data Source of Combined Modality must not be null.";
    mitkThrow() << "Navigation Data Source of Combined Modality must not be null.";
  }

  navigationDataSource->Update();
  this->UpdateBodyMarkerStatus(navigationDataSource->GetOutput(m_ReferenceSensorIndex));

  ui->freezeImageButton->setEnabled(m_BodyMarkerValid);

  mitk::PointSet::Pointer needleProjectionPointSet = m_NeedleProjectionFilter->GetProjection();
  if ( needleProjectionPointSet->GetSize() == 2 )
  {
    m_TargetIntersectionFilter->SetTargetSurface(dynamic_cast<mitk::Surface*>(m_TargetNode->GetData()));
    m_TargetIntersectionFilter->SetLine(needleProjectionPointSet);
    m_TargetIntersectionFilter->CalculateIntersection();
    if ( m_TargetIntersectionFilter->GetIsIntersecting() )
    {
      // only enable button if body marker is in the tracking volume, too
      ui->placeTargetButton->setEnabled(m_BodyMarkerValid);
      ui->placeTargetButton->setToolTip("");

      if ( m_PlannedTargetNodes.size() == m_NumberOfTargets - 1 )
      {
        mitk::PointSet::Pointer targetPointSet = mitk::PointSet::New();

        mitk::PointSet::PointIdentifier n = 0;
        for ( QVector<itk::SmartPointer<mitk::DataNode> >::iterator it = m_PlannedTargetNodes.begin();
          it != m_PlannedTargetNodes.end(); ++it )
        {
          targetPointSet->InsertPoint(n++, (*it)->GetData()->GetGeometry()->GetOrigin());
        }
        targetPointSet->InsertPoint(n, m_TargetIntersectionFilter->GetIntersectionPoint());

        this->CalculatePlanningQuality(dynamic_cast<mitk::Surface*>(m_TargetNode->GetData()), targetPointSet);
      }
    }
    else
    {
      ui->placeTargetButton->setEnabled(false);
      ui->placeTargetButton->setToolTip("Target cannot be placed as the needle path is not intersecting the target surface.");

      // no not show planning quality if not all nodes are planned for now
      // and there is no needle path intersection
      if ( m_PlannedTargetNodes.size() < m_NumberOfTargets )
      {
        ui->angleDifferenceValue->setText("");
        ui->centersOfMassValue->setText("");
      }
    }
  }
}
void QmitkUSNavigationZoneDistancesWidget::UpdateDistancesToNeedlePosition(mitk::NavigationData::Pointer needle)
{
  if ( needle.IsNull() )
  {
    MITK_ERROR("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepMarkerIntervention")
      << "Current Navigation Data for needle must not be null.";
    mitkThrow() << "Current Navigation Data for needle must not be null.";
  }

  // get needle position
  if (needle->IsDataValid())
  {
    mitk::Point3D needlePosition = needle->GetPosition();

    for (int n = 0; n < m_ZoneNodes.size(); ++n)
    {
      mitk::Point3D zoneOrigin = m_ZoneNodes.at(n)->GetData()->GetGeometry()->GetOrigin();

      // calculate absolute distance
      mitk::ScalarType distance = sqrt( pow(zoneOrigin[0] - needlePosition[0], 2) + pow(zoneOrigin[1] - needlePosition[1], 2) + pow(zoneOrigin[2] - needlePosition[2], 2) );

      // subtract zone size
      float zoneSize;
      m_ZoneNodes.at(n)->GetFloatProperty(m_SizePropertyKey.c_str(), zoneSize);
      distance = distance - zoneSize;

      m_ZoneProgressBars.at(n)->setValue(distance);

      if ( distance < 0 ) { SignalZoneViolated(m_ZoneNodes.at(n), needlePosition); }
    }
  }
}
void QmitkUSNavigationStepPunctuationIntervention::UpdateBodyMarkerStatus(mitk::NavigationData::Pointer bodyMarker)
{
  if ( bodyMarker.IsNull() )
  {
    MITK_ERROR("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepPunctuationIntervention")
      << "Current Navigation Data for body marker of Combined Modality must not be null.";
    mitkThrow() << "Current Navigation Data for body marker of Combined Modality must not be null.";
  }

  bool valid = bodyMarker->IsDataValid();

  // update body marker status label
  if (valid)
  {
    ui->bodyMarkerTrackingStatusLabel->setStyleSheet(
      "background-color: #8bff8b; margin-right: 1em; margin-left: 1em; border: 1px solid grey");
    ui->bodyMarkerTrackingStatusLabel->setText("Body marker is inside the tracking volume.");
  }
  else
  {
    ui->bodyMarkerTrackingStatusLabel->setStyleSheet(
          "background-color: #ff7878; margin-right: 1em; margin-left: 1em; border: 1px solid grey");
    ui->bodyMarkerTrackingStatusLabel->setText("Body marker is not inside the tracking volume.");
  }

  ui->riskStructuresRangeGroupBox->setEnabled(valid);
}
Example #8
0
void* mitk::OclDataSet::TransferDataToCPU(cl_command_queue gpuComQueue)
{
  cl_int clErr = 0;

  // if image created on GPU, needs to create mitk::Image
  if( m_gpuBuffer == nullptr ){
    MITK_ERROR("ocl.DataSet") << "(mitk) No buffer present!\n";
    return nullptr;
  }

  // check buffersize
  char* data = new char[m_bufferSize * (size_t)m_BpE];

  // debug info
  #ifdef SHOW_MEM_INFO
  oclPrintMemObjectInfo( m_gpuBuffer );
  #endif

  clErr = clEnqueueReadBuffer( gpuComQueue, m_gpuBuffer, CL_TRUE, 0, m_bufferSize * (size_t)m_BpE, data ,0, nullptr, nullptr);
  CHECK_OCL_ERR(clErr);

  if(clErr != CL_SUCCESS)
    mitkThrow() << "openCL Error when reading Output Buffer";

  clFlush( gpuComQueue );
  // the cpu data is same as gpu
  this->m_gpuModified = false;

  return (void*) data;
}
  bool mitk::NodeDisplacementFilter::AddNode( mitk::DataNode::Pointer node )
  {
    // Consistency Checks
    if (node.IsNull())
    {
      MITK_WARN("NodeDisplacementFilter")
        << "Null Node passed to NodeDisplacementFilter. Ignoring Node....";
      return false;
    }
    if (node->GetData() == 0)
    {
      MITK_WARN("NodeDisplacementFilter")
        << "Empty Node passed to NodeDisplacementFilter. Ignoring Node....";
      return false;
    }
    if(m_SelectedInput == -1)
    {
      MITK_ERROR("NodeDisplacementFilter")
        << "Cannot add nodes before input Stream was selected";
      mitkThrow() << "Cannot add nodes before input Stream was selected";
    }

    this->Update(); // make sure we are working on current data
    mitk::NavigationData::Pointer reference = this->GetOutput(m_SelectedInput);

    if (! reference->IsDataValid())
    {
      MITK_WARN("NodeDisplacementFilter")
        << "Cannot add node while selected tool is not tracked. Ignoring Node....";
      return false;
    }

    // find transformation and add node
    mitk::AffineTransform3D::Pointer inverseAffineTransform = mitk::AffineTransform3D::New();
    if ( ! reference->GetAffineTransform3D()->GetInverse(inverseAffineTransform) )
    {
      MITK_ERROR("NodeDisplacementFilter")
        << "Could not get the inverse transformation of the navigation data transformation.";
      mitkThrow() << "Could not get the inverse transformation of the navigation data transformation.";
    }

    inverseAffineTransform->Compose(node->GetData()->GetGeometry()->GetIndexToWorldTransform(), true);
    m_Transforms.push_back(inverseAffineTransform);
    m_Nodes.push_back(node);

    return true;
  }
bool mitk::USCombinedModality::OnDisconnection()
{
  if (m_UltrasoundDevice.IsNull())
  {
    MITK_ERROR("USCombinedModality")("USDevice") << "UltrasoundDevice must not be null.";
    mitkThrow() << "UltrasoundDevice must not be null.";
  }

  return m_UltrasoundDevice->Disconnect();
}
mitk::USImageSource::Pointer mitk::USCombinedModality::GetUSImageSource()
{
  if (m_UltrasoundDevice.IsNull())
  {
    MITK_ERROR("USCombinedModality")("USDevice") << "UltrasoundDevice must not be null.";
    mitkThrow() << "UltrasoundDevice must not be null.";
  }

  return m_UltrasoundDevice->GetUSImageSource();
}
mitk::USControlInterfaceProbes::Pointer mitk::USCombinedModality::GetControlInterfaceProbes()
{
  if (m_UltrasoundDevice.IsNull())
  {
    MITK_ERROR("USCombinedModality")("USDevice") << "UltrasoundDevice must not be null.";
    mitkThrow() << "UltrasoundDevice must not be null.";
  }

  return m_UltrasoundDevice->GetControlInterfaceProbes();
}
void mitk::USNavigationLoggingBackend::WriteCSVFileWithNavigationMessages(std::string filename)
{
  std::ofstream csvStream;
  csvStream.open(filename.c_str());
  if ( ! csvStream.is_open() ) {MITK_ERROR("USNavigationLoggingBackend") << "File '" << filename << "' cannot be opened for logging."; return;}
  for (int i = 0; i < m_allNavigationMessages.size(); i++)
    {
    csvStream << m_allNavigationMessages.at(i) << "\n";
    }
  csvStream.close();
}
 void mitk::NodeDisplacementFilter::SelectInput(int i)
 {
   if (i < 0) { mitkThrow() << "Negative Input selected in NodeDisplacementFilter"; }
   if (! (static_cast<unsigned int>(i) < this->GetInputs().size()))
   {
     MITK_ERROR("NodeDisplacementFilter")
       << "Selected input index is larger than actual number of inputs.";
     mitkThrow() << "Selected input index is larger than actual number of inputs in NodeDisplacementFilter";
   }
   m_SelectedInput = i;
 }
void mitk::GrabCutOpenCVImageFilter::SetModelPointsDilationSize(int modelPointsDilationSize)
{
  if ( modelPointsDilationSize < 0 )
  {
    MITK_ERROR("AbstractOpenCVImageFilter")("GrabCutOpenCVImageFilter")
            << "Model points dilation size must not be smaller then zero.";
    mitkThrow() << "Model points dilation size must not be smaller then zero.";
  }

  m_ModelPointsDilationSize = modelPointsDilationSize;
}
void mitk::USNavigationLoggingBackend::SetOutputFileName(std::string filename)
{
  if ( m_OutputStream.is_open() ) { m_OutputStream.close(); }

  m_OutputStream.open(filename.c_str());
  if ( ! m_OutputStream.is_open() )
  {
    MITK_ERROR("USNavigationLoggingBackend")
      << "File '" << filename << "' cannot be opened for logging.";
    mitkThrow() << "File '" << filename << "' cannot be opened for logging.";
  }
}
void NonBlockingAlgorithm::UnDefineTriggerParameter(const char* parameter)
{
  MapTypeStringUInt::iterator iter = m_TriggerPropertyConnections.find( parameter );

  if ( iter != m_TriggerPropertyConnections.end() )
  {
    BaseProperty* value = m_Parameters->GetProperty( parameter );

    MITK_ERROR(!value) << "NonBlockingAlgorithm::UnDefineTriggerProperty() in bad state." << std::endl; ;

    value->RemoveObserver( m_TriggerPropertyConnections[parameter] );
    m_TriggerPropertyConnections.erase(iter);
  }
}
bool mitk::USCombinedModality::OnInitialization()
{
  if (m_UltrasoundDevice.IsNull())
  {
    MITK_ERROR("USCombinedModality")("USDevice") << "UltrasoundDevice must not be null.";
    mitkThrow() << "UltrasoundDevice must not be null.";
  }

  if ( m_UltrasoundDevice->GetDeviceState() < mitk::USDevice::State_Initialized )
  {
    return m_UltrasoundDevice->Initialize();
  }
  else
  {
    return true;
  }
}
Example #19
0
void mitk::IGTLDevice::RunCommunication(void (IGTLDevice::*ComFunction)(void), itk::FastMutexLock* mutex)
{
  if (this->GetState() != Running)
    return;

  try
  {
     // keep lock until end of scope
     MutexLockHolder communicationFinishedLockHolder(*mutex);

     // Because m_StopCommunication is used by two threads, access has to be guarded
     // by a mutex. To minimize thread locking, a local copy is used here
     bool localStopCommunication;

     // update the local copy of m_StopCommunication
     this->m_StopCommunicationMutex->Lock();
     localStopCommunication = this->m_StopCommunication;
     this->m_StopCommunicationMutex->Unlock();
     while ((this->GetState() == Running) && (localStopCommunication == false))
     {
        (this->*ComFunction)();

        /* Update the local copy of m_StopCommunication */
        this->m_StopCommunicationMutex->Lock();
        localStopCommunication = m_StopCommunication;
        this->m_StopCommunicationMutex->Unlock();

        // time to relax
        itksys::SystemTools::Delay(1);
     }
  }
  catch (...)
  {
     mutex->Unlock();
     this->StopCommunication();
     MITK_ERROR("IGTLDevice::RunCommunication") << "Error while communicating. Thread stopped.";
     //mitkThrowException(mitk::IGTException) << "Error while communicating. Thread stopped.";
  }
  // StopCommunication was called, thus the mode should be changed back to Ready now
  // that the tracking loop has ended.
  //this->SetState(Ready); //this is done elsewhere
  MITK_DEBUG("IGTLDevice::RunCommunication") << "Reached end of communication.";
  // returning from this function (and ThreadStartCommunication())
  // this will end the thread
  return;
}
bool mitk::USCombinedModality::OnConnection()
{
  if (m_UltrasoundDevice.IsNull())
  {
    MITK_ERROR("USCombinedModality")("USDevice") << "UltrasoundDevice must not be null.";
    mitkThrow() << "UltrasoundDevice must not be null.";
  }

  // connect ultrasound device only if it is not already connected
  if ( m_UltrasoundDevice->GetDeviceState() >= mitk::USDevice::State_Connected )
  {
    return true;
  }
  else
  {
    return m_UltrasoundDevice->Connect();
  }
}
bool mitk::USCombinedModality::OnDeactivation()
{
  if ( m_UltrasoundDevice.IsNull() )
  {
    MITK_ERROR("USCombinedModality")("USDevice") << "UltrasoundDevice must not be null.";
    mitkThrow() << "UltrasoundDevice must not be null.";
  }

  mitk::TrackingDeviceSource::Pointer trackingDeviceSource = dynamic_cast<mitk::TrackingDeviceSource*>(m_TrackingDevice.GetPointer());
  if ( trackingDeviceSource.IsNull() )
  {
    MITK_WARN("USCombinedModality")("USDevice") << "Cannot stop tracking as TrackingDeviceSource is null.";
  }
  trackingDeviceSource->StopTracking();

  m_UltrasoundDevice->Deactivate();

  return m_UltrasoundDevice->GetIsConnected();
}
void QmitkUSNavigationStepMarkerIntervention::OnUpdate()
{
  // get navigation data source and make sure that it is not null
  mitk::NavigationDataSource::Pointer navigationDataSource = this->GetCombinedModality()->GetNavigationDataSource();
  if (navigationDataSource.IsNull())
  {
    MITK_ERROR("QmitkUSAbstractNavigationStep")
      ("QmitkUSNavigationStepMarkerIntervention") << "Navigation Data Source of Combined Modality must not be null.";
    mitkThrow() << "Navigation Data Source of Combined Modality must not be null.";
  }

  ui->riskStructuresRangeWidget->UpdateDistancesToNeedlePosition(navigationDataSource->GetOutput(m_NeedleSensorIndex));
  this->UpdateBodyMarkerStatus(navigationDataSource->GetOutput(m_ReferenceSensorIndex));

  this->UpdateTargetColors();
  this->UpdateTargetScore();

  this->UpdateTargetViolationStatus();
}
void mitk::USCombinedModality::OnFreeze(bool freeze)
{
  if (m_UltrasoundDevice.IsNull())
  {
    MITK_ERROR("USCombinedModality")("USDevice") << "UltrasoundDevice must not be null.";
    mitkThrow() << "UltrasoundDevice must not be null.";
  }
  m_UltrasoundDevice->SetIsFreezed(freeze);

  mitk::TrackingDeviceSource::Pointer trackingDeviceSource = dynamic_cast<mitk::TrackingDeviceSource*>(m_TrackingDevice.GetPointer());
  if ( trackingDeviceSource.IsNull() )
  {
    MITK_WARN("USCombinedModality")("USDevice") << "Cannot freeze tracking.";
  }
  else
  {
    if ( freeze ) { trackingDeviceSource->StopTracking(); }
    else { trackingDeviceSource->StartTracking(); }
  }
}
bool mitk::USTelemedImageSource::CreateAndConnectConverterPlugin(Usgfw2Lib::IUsgDataView* usgDataView, Usgfw2Lib::tagScanMode scanMode)
{
  IUnknown* tmp_obj = nullptr;

  // create control object from Telemed API
  mitk::telemed::CreateUsgControl( usgDataView, Usgfw2Lib::IID_IUsgScanConverterPlugin, scanMode, 0, (void**)&tmp_obj );
  if ( ! tmp_obj )
  {
    MITK_ERROR("USImageSource")("USTelemedImageSource") << "Could not create scan converter plugin.";
    return false;
  }

  // create the callback object for the scan conversion
  if ( ! m_PluginCallback )
  {
    m_PluginCallback = new USTelemedScanConverterPlugin();

    // current image buffer should be copied to m_Image at every callback
    m_PluginCallback->SetOutputImage(m_Image.GetPointer(), m_ImageMutex);
  }
  else
  {
    // make sure that the scan converter plugin is not set
    // to the plugin callback any longer
    m_PluginCallback->SetScanConverterPlugin(0);
  }

  // now the ScanConverterPlugin can be created and set as plugin
  SAFE_RELEASE(m_Plugin);
  m_Plugin = (Usgfw2Lib::IUsgScanConverterPlugin*)tmp_obj;
  m_PluginCallback->SetScanConverterPlugin(m_Plugin);

  //last: create some connections which are needed inside this class for communication with the telemed device
  m_UsgDataView = usgDataView;

  // create telemed controls
  if (!m_DepthProperties) {CREATE_TelemedControl(m_DepthProperties, m_UsgDataView, Usgfw2Lib::IID_IUsgDepth, Usgfw2Lib::IUsgDepth, Usgfw2Lib::SCAN_MODE_B);}
  if (!m_ImageProperties) {CREATE_TelemedControl(m_ImageProperties, m_UsgDataView, Usgfw2Lib::IID_IUsgImageProperties, Usgfw2Lib::IUsgImageProperties, Usgfw2Lib::SCAN_MODE_B);}

  return true;
}
void QmitkUSNavigationStepPunctuationIntervention::OnUpdate()
{
  // get navigation data source and make sure that it is not null
  mitk::NavigationDataSource::Pointer navigationDataSource =
      this->GetCombinedModality()->GetNavigationDataSource();
  if ( navigationDataSource.IsNull() )
  {
    MITK_ERROR("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepPunctuationIntervention")
    << "Navigation Data Source of Combined Modality must not be null.";
    mitkThrow() << "Navigation Data Source of Combined Modality must not be null.";
  }
  // update body marker
  this->UpdateBodyMarkerStatus(navigationDataSource->GetOutput(1));
  // update critical structures
  this->UpdateCriticalStructures(navigationDataSource->GetOutput(0),m_NeedleProjectionFilter->GetProjection());

  //Update Distance to US image
  mitk::Point3D point1 = m_NeedleProjectionFilter->GetProjection()->GetPoint(0);
  mitk::Point3D point2 = m_NeedleProjectionFilter->GetProjection()->GetPoint(1);
  double distance = point1.EuclideanDistanceTo(point2);
  ui->m_DistanceToUSPlane->setText(QString::number(distance) + " mm");
}
Example #26
0
int mitk::OclDataSet::TransferDataToGPU(cl_command_queue gpuComQueue)
{
  cl_int clErr = 0;

  // check whether an image present
  if (m_Data == nullptr){
    MITK_ERROR("ocl.DataSet") << "(mitk) No data present!\n";
    return -1;
  }

  // there is a need for copy only if RAM-Data newer then GMEM data
  if (m_cpuModified)
  {
    //check the buffer
    if(m_gpuBuffer == nullptr)
    {
      CreateGPUBuffer();
    }

    if (m_gpuBuffer != nullptr)
    {
      clErr = clEnqueueWriteBuffer(gpuComQueue, m_gpuBuffer, CL_TRUE, 0, m_bufferSize * (size_t)m_BpE, m_Data, 0, NULL, NULL);
      MITK_DEBUG << "Wrote Data to GPU Buffer Object.";

      CHECK_OCL_ERR(clErr);
      m_gpuModified = true;

      if (clErr != CL_SUCCESS)
        mitkThrow() << "openCL Error when writing Buffer";
    }
    else
    {
      MITK_ERROR << "No GPU buffer present!";
    }
  }

  return clErr;
}
void QmitkRigidRegistrationSelectorView::DoLoadRigidRegistrationPreset(std::string presetName)
{
  itk::Array<double> transformValues;
  transformValues = m_Preset->getTransformValues(presetName);

  if( transformValues.size() == 0 )
  {
    MITK_ERROR("RigidRegistration.Selector.View") << "Failed to load preset : " << presetName;
    return;
  }

  m_Controls.m_TransformGroup->setChecked(true);
  m_Controls.m_TransformFrame->setVisible(true);
  m_Controls.m_TransformBox->setCurrentIndex((int)transformValues[0]);
  m_Controls.m_TransformWidgetStack->setCurrentIndex((int)transformValues[0]);
  this->TransformSelected((int)transformValues[0]);
  itk::Array<double> transformValuesForGUI;
  transformValuesForGUI.SetSize(transformValues.Size());
  transformValuesForGUI.fill(0);
  for (unsigned int i = 1; i < transformValues.Size(); i++)
  {
    transformValuesForGUI[i-1] = transformValues[i];
  }
  dynamic_cast<QmitkRigidRegistrationTransformsGUIBase*>(m_Controls.m_TransformWidgetStack->currentWidget())->SetTransformParameters(transformValuesForGUI);

  itk::Array<double> metricValues;
  metricValues = m_Preset->getMetricValues(presetName);

  m_Controls.m_MetricGroup->setChecked(true);
  m_Controls.m_MetricFrame->setVisible(true);
  m_Controls.m_MetricBox->setCurrentIndex((int)metricValues[0]);
  m_Controls.m_MetricWidgetStack->setCurrentIndex((int)metricValues[0]);
  this->MetricSelected((int)metricValues[0]);
  itk::Array<double> metricValuesForGUI;
  metricValuesForGUI.SetSize(metricValues.Size());
  metricValuesForGUI.fill(0);
  for (unsigned int i = 1; i < metricValues.Size(); i++)
  {
    metricValuesForGUI[i-1] = metricValues[i];
  }
  dynamic_cast<QmitkRigidRegistrationMetricsGUIBase*>(m_Controls.m_MetricWidgetStack->currentWidget())->SetMetricParameters(metricValuesForGUI);

  itk::Array<double> optimizerValues;
  optimizerValues = m_Preset->getOptimizerValues(presetName);

  m_Controls.m_OptimizerGroup->setChecked(true);
  m_Controls.m_OptimizerFrame->setVisible(true);
  m_Controls.m_OptimizerBox->setCurrentIndex((int)optimizerValues[0]);
  m_Controls.m_OptimizerWidgetStack->setCurrentIndex((int)optimizerValues[0]);
  this->OptimizerSelected((int)optimizerValues[0]);
  itk::Array<double> optimizerValuesForGUI;
  optimizerValuesForGUI.SetSize(optimizerValues.Size());
  optimizerValuesForGUI.fill(0);
  for (unsigned int i = 1; i < optimizerValues.Size(); i++)
  {
    optimizerValuesForGUI[i-1] = optimizerValues[i];
  }
  dynamic_cast<QmitkRigidRegistrationOptimizerGUIBase*>(m_Controls.m_OptimizerWidgetStack->currentWidget())->SetOptimizerParameters(optimizerValuesForGUI);

  itk::Array<double> interpolatorValues;
  interpolatorValues = m_Preset->getInterpolatorValues(presetName);

  m_Controls.m_InterpolatorGroup->setChecked(true);
  m_Controls.m_InterpolatorFrame->setVisible(true);
  m_Controls.m_InterpolatorBox->setCurrentIndex((int)interpolatorValues[0]);
}
int main( int argc, char* argv[] )
{

  mitkCommandLineParser parser;

  parser.setTitle("Diffusion Kurtosis Fit");
  parser.setCategory("Diffusion Related Measures");
  parser.setContributor("MIC");
  parser.setDescription("Fitting Kurtosis");
  parser.setArgumentPrefix("--","-");

  // mandatory arguments
  parser.addArgument("input", "i", mitkCommandLineParser::InputFile, "Input: ", "input image (DWI)", us::Any(), false);
  parser.addArgument("output", "o", mitkCommandLineParser::String, "Output Preifx: ", "Prefix for the output images, will append _f, _K, _D accordingly ", us::Any(), false);
  parser.addArgument("output_type", "ot", mitkCommandLineParser::String, "Output Type: ", "choose data type of output image, e.g. '.nii' or '.nrrd' ", us::Any(), false);

  // optional arguments
  parser.addArgument("mask", "m", mitkCommandLineParser::InputFile, "Masking Image: ", "ROI (segmentation)", us::Any());
  parser.addArgument("help", "h", mitkCommandLineParser::Bool, "Help", "Show this help text");
  parser.addArgument("omitbzero", "om", mitkCommandLineParser::Bool, "Omit b0:", "Omit b0 value during fit (default = false)", us::Any());
  parser.addArgument("lowerkbound", "kl", mitkCommandLineParser::Float, "lower Kbound:", "Set (unsigned) lower boundary for Kurtosis parameter (default = -1000)", us::Any());
  parser.addArgument("upperkbound", "ku", mitkCommandLineParser::Float, "upper Kbound:", "Set upper boundary for Kurtosis parameter (default = 1000)", us::Any());


  std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);

  if (parsedArgs.size()==0 || parsedArgs.count("help") || parsedArgs.count("h")){
    std::cout << parser.helpText();
    return EXIT_SUCCESS;
  }

  // mandatory arguments
  std::string inFileName = us::any_cast<std::string>(parsedArgs["input"]);
  std::string out_prefix = us::any_cast<std::string>(parsedArgs["output"]);
  std::string maskPath = "";

  mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor({"Diffusion Weighted Images"}, {});
  mitk::Image::Pointer inputImage = mitk::IOUtil::LoadImage(inFileName, &functor);

  bool omitBZero = false;
  double lower = -1000;
  double upper = 1000;
  std::string  out_type = "nrrd";

  if (parsedArgs.count("mask") || parsedArgs.count("m"))
  {
    maskPath = us::any_cast<std::string>(parsedArgs["mask"]);
  }

  if (parsedArgs.count("output_type") || parsedArgs.count("ot"))
  {
    out_type = us::any_cast<std::string>(parsedArgs["output_type"]);
  }

  if (parsedArgs.count("omitbzero") || parsedArgs.count("om"))
  {
    omitBZero = us::any_cast<bool>(parsedArgs["omitbzero"]);
  }

  if (parsedArgs.count("lowerkbound") || parsedArgs.count("kl"))
  {
    lower = us::any_cast<float>(parsedArgs["lowerkbound"]);
  }

  if (parsedArgs.count("upperkbound") || parsedArgs.count("ku"))
  {
    upper = us::any_cast<float>(parsedArgs["upperkbound"]);
  }

  if( !DPH::IsDiffusionWeightedImage( inputImage ) )
  {
    MITK_ERROR("DiffusionIVIMFit.Input") << "No valid diffusion-weighted image provided, failed to load " << inFileName << " as DW Image. Aborting...";
    return EXIT_FAILURE;
  }



KurtosisMapComputation( inputImage,
                        out_prefix ,
                        out_type,
                        maskPath,
                        omitBZero,
                        lower,
                        upper);

}
bool mitk::PersistenceService::Save(const std::string &fileName, bool appendChanges)
{
  this->Initialize();
  bool save = false;
  std::string theFile = fileName;
  if (theFile.empty())
    theFile = PersistenceService::GetDefaultPersistenceFile();

  std::string thePath = itksys::SystemTools::GetFilenamePath(theFile.c_str());
  if (!thePath.empty() && !itksys::SystemTools::FileExists(thePath.c_str()))
  {
    if (!itksys::SystemTools::MakeDirectory(thePath.c_str()))
    {
      MITK_ERROR("PersistenceService") << "Could not create " << thePath;
      return false;
    }
  }

  bool createFile = !itksys::SystemTools::FileExists(theFile.c_str());
  if (!itksys::SystemTools::Touch(theFile.c_str(), createFile))
  {
    MITK_ERROR("PersistenceService") << "Could not create or write to " << theFile;
    return false;
  }

  bool xmlFile = false;
  if (itksys::SystemTools::GetFilenameLastExtension(theFile.c_str()) == ".xml")
    xmlFile = true;

  mitk::DataStorage::Pointer tempDs;
  if (appendChanges)
  {
    if (xmlFile == false)
    {
      if (itksys::SystemTools::FileExists(theFile.c_str()))
      {
        bool load = false;
        DataStorage::Pointer ds = m_SceneIO->LoadScene(theFile);
        load = (m_SceneIO->GetFailedNodes() == 0 || m_SceneIO->GetFailedNodes()->size() == 0) &&
               (m_SceneIO->GetFailedNodes() == 0 || m_SceneIO->GetFailedProperties()->IsEmpty());
        if (!load)
          return false;

        tempDs = ds;
      }
    }
    else
    {
      tempDs = mitk::StandaloneDataStorage::New();
      if (xmlFile && appendChanges && itksys::SystemTools::FileExists(theFile.c_str()))
      {
        if (!m_PropertyListsXmlFileReaderAndWriter->ReadLists(theFile, m_PropertyLists))
          return false;
      }
    }

    this->RestorePropertyListsFromPersistentDataNodes(tempDs);
  }
  else if (xmlFile == false)
  {
    tempDs = mitk::StandaloneDataStorage::New();
  }

  if (xmlFile)
  {
    save = m_PropertyListsXmlFileReaderAndWriter->WriteLists(theFile, m_PropertyLists);
  }

  else
  {
    DataStorage::SetOfObjects::Pointer sceneNodes = this->GetDataNodes(tempDs);
    if (m_SceneIO.IsNull())
    {
      m_SceneIO = mitk::SceneIO::New();
    }
    save = m_SceneIO->SaveScene(sceneNodes.GetPointer(), tempDs, theFile);
  }
  if (save)
  {
    long int currentModifiedTime = itksys::SystemTools::ModifiedTime(theFile.c_str());
    m_FileNamesToModifiedTimes[theFile] = currentModifiedTime;
  }

  return save;
}
Example #30
0
unsigned int mitk::IGTLDevice::ReceivePrivate(igtl::Socket* socket)
{
  // Create a message buffer to receive header
  igtl::MessageHeader::Pointer headerMsg;
  headerMsg = igtl::MessageHeader::New();

  // Initialize receive buffer
  headerMsg->InitPack();

  // Receive generic header from the socket
  int r =
     socket->Receive(headerMsg->GetPackPointer(), headerMsg->GetPackSize(), 0);

  //MITK_INFO << "Server received r = " << r;

  if (r == 0) //connection error
  {
    // an error was received, therefor the communication with this socket
    // must be stoppedy
    return IGTL_STATUS_NOT_PRESENT;
  }
  else if (r == -1 ) //timeout
  {
    // a timeout was received, this is no error state, thus, do nothing
    return IGTL_STATUS_TIME_OUT;
  }
  else if (r == headerMsg->GetPackSize())
  {
    // Deserialize the header and check the CRC
    // ERROR HERE: This probably means the header data is corrupted...
    int crcCheck = headerMsg->Unpack(1);

    if (crcCheck & igtl::MessageHeader::UNPACK_HEADER)
    {
      // Allocate a time stamp
      igtl::TimeStamp::Pointer ts;
      ts = igtl::TimeStamp::New();

      // Get time stamp
      igtlUint32 sec;
      igtlUint32 nanosec;

      headerMsg->GetTimeStamp(ts);
      ts->GetTimeStamp(&sec, &nanosec);

//      std::cerr << "Time stamp: "
//                << sec << "."
//                << nanosec << std::endl;

//      std::cerr << "Dev type and name: " << headerMsg->GetDeviceType() << " "
//                << headerMsg->GetDeviceName() << std::endl;

//      headerMsg->Print(std::cout);

      //check the type of the received message
      //if it is a GET_, STP_ or RTS_ command push it into the command queue
      //otherwise continue reading the whole message from the socket
      const char* curDevType = headerMsg->GetDeviceType();
      if ( std::strstr( curDevType, "GET_" ) != nullptr ||
           std::strstr( curDevType, "STP_" ) != nullptr ||
           std::strstr( curDevType, "RTS_" ) != nullptr)
      {
        this->m_CommandQueue->PushMessage(headerMsg);
        this->InvokeEvent(CommandReceivedEvent());
        return IGTL_STATUS_OK;
      }

      //Create a message according to the header message
      igtl::MessageBase::Pointer curMessage;
      curMessage = m_MessageFactory->CreateInstance(headerMsg);

      //check if the curMessage is created properly, if not the message type is
      //not supported and the message has to be skipped
      if ( curMessage.IsNull() )
      {
        socket->Skip(headerMsg->GetBodySizeToRead(), 0);
      //  MITK_ERROR("IGTLDevice") << "The received type is not supported. Please "
      //                              "add it to the message factory.";
        return IGTL_STATUS_NOT_FOUND;
      }

      //insert the header to the message and allocate the pack
      curMessage->SetMessageHeader(headerMsg);
      curMessage->AllocatePack();

      // Receive transform data from the socket
      int receiveCheck = 0;
      receiveCheck = socket->Receive(curMessage->GetPackBodyPointer(),
         curMessage->GetPackBodySize(), m_ReadFully);


      // measure the time
      const long long timeStamp6 = std::chrono::high_resolution_clock::now().time_since_epoch().count();

      if ( receiveCheck > 0 )
      {
        int c = curMessage->Unpack(1);
        if ( !(c & igtl::MessageHeader::UNPACK_BODY) )
        {
          return IGTL_STATUS_CHECKSUM_ERROR;
        }

        //save timestamp 6 now because we know the index
        AddTrackingMeasurements(6, curMessage, timeStamp6);
        //check the type of the received message
        //if it is a command push it into the command queue
        //otherwise into the normal receive queue
        //STP_ commands are handled here because they implemented additional
        //member variables that are not stored in the header message
        if ( std::strstr( curDevType, "STT_" ) != nullptr )
        {
          this->m_CommandQueue->PushMessage(curMessage);
          this->InvokeEvent(CommandReceivedEvent());
        }
        else
        {
          AddTrackingMeasurements(7, curMessage, timeStamp6);
          this->m_ReceiveQueue->PushMessage(curMessage);
          this->InvokeEvent(MessageReceivedEvent());
        }
        return IGTL_STATUS_OK;
      }
      else
      {
        MITK_ERROR("IGTLDevice") << "Received a valid header but could not "
                                 << "read the whole message.";
        return IGTL_STATUS_UNKNOWN_ERROR;
      }
    }
    else
    {
      //CRC check failed
      MITK_ERROR << "CRC Check failed";
      return IGTL_STATUS_CHECKSUM_ERROR;
    }
  }
  else
  {
    //Message size information and actual data size don't match.
    //this state is not suppossed to be reached, return unknown error
    MITK_ERROR << "IGTL status unknown";
    return IGTL_STATUS_UNKNOWN_ERROR;
  }
}