File: PivotCalibrationFLTKWidgetExample.cxx

package info (click to toggle)
igstk 4.2.0-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 36,940 kB
  • ctags: 6,895
  • sloc: cpp: 70,958; makefile: 99; xml: 70
file content (392 lines) | stat: -rw-r--r-- 13,978 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/*=========================================================================

  Program:   Image Guided Surgery Software Toolkit
  Module:    $RCSfile: PivotCalibrationFLTKWidgetExample.cxx,v $
  Language:  C++
  Date:      $Date: 2009-06-08 20:56:31 $
  Version:   $Revision: 1.1 $

  Copyright (c) ISC  Insight Software Consortium.  All rights reserved.
  See IGSTKCopyright.txt or http://www.igstk.org/copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "PivotCalibrationFLTKWidgetExample.h"
#include <FL/fl_ask.H>
#include <FL/Fl_File_Chooser.H>
#include "igstkPrecomputedTransformData.h"
#include "igstkTransformFileWriter.h"
#include "igstkRigidTransformXMLFileWriter.h"
#include "itksys/SystemTools.hxx"

#include "igstkSerialCommunication.h"

//
// settings for the serial communication
//
const igstk::SerialCommunication::ParityType
PivotCalibrationFLTKWidgetExample::PARITY =
  igstk::SerialCommunication::NoParity;

const igstk::SerialCommunication::BaudRateType
PivotCalibrationFLTKWidgetExample::BAUD_RATE =
  igstk::SerialCommunication::BaudRate115200;

const igstk::SerialCommunication::DataBitsType
PivotCalibrationFLTKWidgetExample::DATA_BITS =
  igstk::SerialCommunication::DataBits8;

const igstk::SerialCommunication::StopBitsType
PivotCalibrationFLTKWidgetExample::STOP_BITS =
  igstk::SerialCommunication::StopBits1;

const igstk::SerialCommunication::HandshakeType
PivotCalibrationFLTKWidgetExample::HAND_SHAKE =
  igstk::SerialCommunication::HandshakeOff;


PivotCalibrationFLTKWidgetExample::PivotCalibrationFLTKWidgetExample()
: PivotCalibrationFLTKWidgetExampleUI(), m_initialized(false)
{ 
               //create transform observer
  this->m_TransformToObserver = TransformToObserver::New();
               //create RMSE observer
  this->m_RMSEObserver = RMSEObserver::New();

               //create calibration success and failure observer
  this->m_CalibrationSuccessFailureObserver = CalibrationSuccessFailureObserverType::New();  
  this->m_CalibrationSuccessFailureObserver->SetCallbackFunction( 
    this, 
    &PivotCalibrationFLTKWidgetExample::OnCalibrationSuccessFailureEvent );

  this->m_pivotCalibrationFLTKWidget->AddObserver( 
    igstk::PivotCalibration::CalibrationSuccessEvent(),
    this->m_CalibrationSuccessFailureObserver );

  this->m_pivotCalibrationFLTKWidget->AddObserver( 
    igstk::PivotCalibration::CalibrationFailureEvent(),
    this->m_CalibrationSuccessFailureObserver );
    
  //create error observer
  this->m_errorObserver = TrackingErrorObserver::New();

  //create serial communication
  this->m_serialCommunication = igstk::SerialCommunication::New();

              //observe errors generated by the serial communication
  this->m_serialCommunication->AddObserver( igstk::OpenPortErrorEvent(),
                                            this->m_errorObserver );
  this->m_serialCommunication->AddObserver( igstk::ClosePortErrorEvent(),
                                            this->m_errorObserver );

              //create tracker
  this->m_tracker = igstk::PolarisTracker::New();

                 //observe errors generated by the tracker
  this->m_tracker->AddObserver( igstk::TrackerOpenErrorEvent(),
                                this->m_errorObserver );
  this->m_tracker->AddObserver( igstk::TrackerInitializeErrorEvent(),
                                this->m_errorObserver );
  this->m_tracker->AddObserver( igstk::TrackerStartTrackingErrorEvent(),
                                this->m_errorObserver );
  this->m_tracker->AddObserver( igstk::TrackerStopTrackingErrorEvent(),
                                this->m_errorObserver );
  this->m_tracker->AddObserver( igstk::TrackerUpdateStatusErrorEvent(),
                                this->m_errorObserver );
  this->m_tracker->AddObserver( igstk::TrackerCloseErrorEvent(),
                                this->m_errorObserver );
  this->m_tracker->AddObserver( igstk::TrackerUpdateStatusErrorEvent(),
                                this->m_errorObserver );

}

void
PivotCalibrationFLTKWidgetExample::InitializeTrackingAndCalibration()
{
              //gather the information from the UI
  typedef igstk::SerialCommunication::PortNumberType PortNumberType;
  PortNumberType comPort =
   static_cast<PortNumberType> ( this->m_comPortChoice->value() );
  unsigned int toolPort =
            static_cast<unsigned int>( this->m_toolPortChoice->value() );
  unsigned int delay =
            static_cast<unsigned int>( this->m_delaySlider->value() );
  unsigned int numberOfFrames =
            static_cast<unsigned int>( this->m_numberOfFramesSlider->value() );
  std::string sromFileName = this->m_SROMFileNameTextField->value();

      //check that the user entered valid data, wireless tool requires an
      //SROM file
  if( sromFileName.empty() && toolPort == 0 )
  {
    fl_alert( "Missing SROM file for wireless tool." );
    fl_beep( FL_BEEP_ERROR );
    return;
  }

              //if already initialized, shutdown everything and reinitialize
  if( this->m_initialized )
  {
    this->m_initialized = false;
    this->m_tracker->RequestStopTracking();
    if( this->m_errorObserver->Error() )
    {
      this->m_errorObserver->ClearError();
      return;
    }
    this->m_tracker->RequestClose();
    if( this->m_errorObserver->Error() )
    {
      this->m_errorObserver->ClearError();
      return;
    }
    this->m_serialCommunication->CloseCommunication();
    if( this->m_errorObserver->Error() )
    {
      this->m_errorObserver->ClearError();
      return;
    }
  }

  this->m_serialCommunication->SetPortNumber( comPort );
  this->m_serialCommunication->SetParity( PARITY );
  this->m_serialCommunication->SetBaudRate( BAUD_RATE );
  this->m_serialCommunication->SetDataBits( DATA_BITS );
  this->m_serialCommunication->SetStopBits( STOP_BITS );
  this->m_serialCommunication->SetHardwareHandshake( HAND_SHAKE );


                 // create tracked tool and configure it
  this->m_tool = igstk::PolarisTrackerTool::New();
         //different configuration for wired and wireless tools
         //toolPort == 0 is wireless all others are actual ports
  if( toolPort == 0) 
  {
    this->m_tool->RequestSelectWirelessTrackerTool();
    this->m_tool->RequestSetSROMFileName(sromFileName);
  }
  else  //we have a wired tool
  {
    this->m_tool->RequestSelectWiredTrackerTool();
                 //the physical ports start at 1, inside IGSTK we refer to 
                //them from 0
    this->m_tool->RequestSetPortNumber( toolPort - 1 );            
               //SROM file is optional 
    if ( !sromFileName.empty() )
    {
      this->m_tool->RequestSetSROMFileName(sromFileName);
    }
  }
  this->m_tool->RequestConfigure();

         //open serial communication
  this->m_serialCommunication->OpenCommunication();
  if( this->m_errorObserver->Error() )
  {
    this->m_errorObserver->ClearError();
    return;
  }
  this->m_tracker->SetCommunication( this->m_serialCommunication );
  this->m_tracker->RequestSetFrequency( 30 );

           //open tracker communication
  this->m_tracker->RequestOpen();
  if( this->m_errorObserver->Error() )
  {
    this->m_errorObserver->ClearError();
    return;
  }
                      //attach the tracker tool
  this->m_tool->RequestAttachToTracker( this->m_tracker );
  if( this->m_errorObserver->Error() )
  {
    this->m_errorObserver->ClearError();
    return;
  }
               //start tracking
  this->m_tracker->RequestStartTracking();
  if( this->m_errorObserver->Error() )
  {
    this->m_errorObserver->ClearError();
    return;
  }

  this->m_initialized = true;


  this->m_pivotCalibrationFLTKWidget->RequestSetDelay( delay );

  igstk::TrackerTool * genericTrackerTool = this->m_tool.GetPointer();

  this->m_pivotCalibrationFLTKWidget->RequestInitialize(numberOfFrames,
                                                        genericTrackerTool );
}

void
PivotCalibrationFLTKWidgetExample::SaveCalibration()
{
  char *fileName = fl_file_chooser("Save calibration file",
                                   "XML Files(*.xml,*.XML)", NULL,0);
  if(fileName != NULL)
    {
      igstk::PrecomputedTransformData::Pointer transformationData = 
        igstk::PrecomputedTransformData::New();

        //get the transformaion
    unsigned long observerID = this->m_pivotCalibrationFLTKWidget->AddObserver( igstk::CoordinateSystemTransformToEvent(),
                                                   this->m_TransformToObserver );
    this->m_pivotCalibrationFLTKWidget->RequestCalibrationTransform();
    igstk::Transform transform = this->m_TransformToObserver->GetTransformTo().GetTransform();
    this->m_pivotCalibrationFLTKWidget->RemoveObserver( observerID );
        //get the estimation error
    observerID = this->m_pivotCalibrationFLTKWidget->AddObserver( igstk::DoubleTypeEvent(),
      this->m_RMSEObserver );
    this->m_pivotCalibrationFLTKWidget->RequestCalibrationRMSE();
    this->m_pivotCalibrationFLTKWidget->RemoveObserver( observerID );
    igstk::EventHelperType::DoubleType rmse = this->m_RMSEObserver->GetRMSE();
              //get transformation description
    std::ostringstream descriptionStream;
    descriptionStream<<"Pivot calibration for tool ";
    descriptionStream<<this->m_tool->GetTrackerToolIdentifier();
             //get current date
    std::string estimationDate = 
      itksys::SystemTools::GetCurrentDateTime( "%Y %b %d %H:%M:%S" );
      
    transformationData->RequestInitialize( &transform, estimationDate,
                                           descriptionStream.str(), rmse );

          //setup the writer
    igstk::TransformFileWriter::Pointer transformFileWriter = 
      igstk::TransformFileWriter::New();

    igstk::TransformXMLFileWriterBase::Pointer xmlFileWriter;
      xmlFileWriter = igstk::RigidTransformXMLFileWriter::New();

    WriteFailureObserverType::Pointer writeFailureObserver = 
      WriteFailureObserverType::New();  
    writeFailureObserver->SetCallbackFunction( 
    this, 
    &PivotCalibrationFLTKWidgetExample::OnWriteFailureEvent );

    transformFileWriter->AddObserver( igstk::TransformFileWriter::WriteFailureEvent() , 
                                      writeFailureObserver );

    transformFileWriter->RequestSetWriter( xmlFileWriter );
    transformFileWriter->RequestSetData( transformationData,  
                                         fileName );
    transformFileWriter->RequestWrite();
    }
}


void 
PivotCalibrationFLTKWidgetExample::OnCalibrationSuccessFailureEvent( itk::Object *caller, 
                              const itk::EventObject & event )
{
  if( dynamic_cast< const igstk::PivotCalibration::CalibrationSuccessEvent * > 
     (&event) ) 
    { 
    this->m_saveButton->activate();
    }
  else if( dynamic_cast< const igstk::PivotCalibration::CalibrationFailureEvent * > 
           (&event) )
    {
    this->m_saveButton->deactivate();
    }
}


void 
PivotCalibrationFLTKWidgetExample::OnWriteFailureEvent( itk::Object *caller, 
                                                        const itk::EventObject & event )
{
  fl_alert( "Failed writing calibration data to file." );
  fl_beep( FL_BEEP_ERROR );
}


void
PivotCalibrationFLTKWidgetExample::TrackingErrorObserver::Execute(
  itk::Object *caller,
  const itk::EventObject & event )
{
  std::map<std::string,std::string>::iterator it;
  std::string className = event.GetEventName();
  it = this->m_ErrorEvent2ErrorMessage.find( className );
  if( it != this->m_ErrorEvent2ErrorMessage.end() )
    {
    this->m_ErrorOccured = true;
    fl_alert( "%s\n", (*it).second.c_str() );
    fl_beep( FL_BEEP_ERROR );
    }
}

void
PivotCalibrationFLTKWidgetExample::TrackingErrorObserver::Execute(
  const itk::Object *caller,
  const itk::EventObject & event )
{
  const itk::Object * constCaller = caller;
  this->Execute( constCaller, event );
}

void
PivotCalibrationFLTKWidgetExample::TrackingErrorObserver::ClearError()
{
  this->m_ErrorOccured = false;
}

bool
PivotCalibrationFLTKWidgetExample::TrackingErrorObserver::Error()
{
  return this->m_ErrorOccured;
}

PivotCalibrationFLTKWidgetExample
::TrackingErrorObserver::TrackingErrorObserver()
: m_ErrorOccured( false )
{
  //serial communication errors
  this->m_ErrorEvent2ErrorMessage.insert(
      std::pair<std::string,std::string>(
      igstk::OpenPortErrorEvent().GetEventName(), "Error opening com port." ) );

  this->m_ErrorEvent2ErrorMessage.insert(
      std::pair<std::string,std::string>(
      igstk::ClosePortErrorEvent().GetEventName(), "Error closing com port." ) );

  //tracker errors
  this->m_ErrorEvent2ErrorMessage.insert(
      std::pair<std::string,std::string>(
      igstk::TrackerOpenErrorEvent().GetEventName(),
      "Error opening tracker communication." ) );

  this->m_ErrorEvent2ErrorMessage.insert(
      std::pair<std::string,std::string>(
      igstk::TrackerInitializeErrorEvent().GetEventName(),
     "Error initializing tracker." ) );

  this->m_ErrorEvent2ErrorMessage.insert(
      std::pair<std::string,std::string>(
      igstk::TrackerStartTrackingErrorEvent().GetEventName(),
     "Error starting tracking." ) );

  this->m_ErrorEvent2ErrorMessage.insert(
      std::pair<std::string,std::string>(
      igstk::TrackerStopTrackingErrorEvent().GetEventName(),
     "Error stopping tracking." ) );

  this->m_ErrorEvent2ErrorMessage.insert(
      std::pair<std::string,std::string>(
      igstk::TrackerCloseErrorEvent().GetEventName(),
     "Error closing tracker communication." ) );

  this->m_ErrorEvent2ErrorMessage.insert(
      std::pair<std::string,std::string>(
      igstk::TrackerUpdateStatusErrorEvent().GetEventName(),
     "Error updating transformations from tracker." ) );
}