]> Creatis software - creaContours.git/blob - lib/kernel_ManagerContour_NDimensions/ParserOsirix/OsirixParser.cxx
export contours data
[creaContours.git] / lib / kernel_ManagerContour_NDimensions / ParserOsirix / OsirixParser.cxx
1
2 //----------------------------------------------------------------------------------------------------------------
3 // Class definition include
4 //----------------------------------------------------------------------------------------------------------------
5 #include "OsirixParser.h"
6 #include <stdio.h>
7
8
9 OsirixParser::OsirixParser(std::string xsdfile, double* spacing, int* extent)
10 {
11         schema=xsdfile;
12
13         OSIRIX_DICT = "dict";
14         OSIRIX_KEY = "key";
15         OSIRIX_IMAGES = "Images";
16         OSIRIX_ARRAY = "array";
17         OSIRIX_IMAGEINDEX = "ImageIndex";
18         OSIRIX_INTEGER = "integer";
19         OSIRIX_NUMBEROFROIS = "NumberOfROIs";
20         OSIRIX_ROIS = "ROIs";
21         OSIRIX_POINT_MM = "Point_mm";
22         OSIRIX_POINT_PX = "Point_px";
23         OSIRIX_STRING = "string";
24         OSIRIX_NAME = "Name";
25
26         if(spacing != NULL){
27                 _spacing[0] = spacing[0];
28                 _spacing[1] = spacing[1];
29                 _spacing[2] = spacing[2];
30         }else{
31                 _spacing[0] = 1;
32                 _spacing[1] = 1;
33                 _spacing[2] = 1;
34         }
35
36         if(extent != NULL){
37                 _extent[0] = extent[0];
38                 _extent[1] = extent[1];
39                 _extent[2] = extent[2];
40                 _extent[3] = extent[3];
41                 _extent[4] = extent[4];
42                 _extent[5] = extent[5];
43                 
44         }else{
45                 _extent[0] = 1;
46                 _extent[1] = 1;
47                 _extent[2] = 1;         
48                 _extent[3] = 1;
49                 _extent[4] = 1;
50                 _extent[5] = 1;
51         }
52
53
54         /*HEADER*/
55         CREACONTOUR = "--CreaContour--";
56         CREACONTOUR_VERSION = "Version 1.0.2";
57         CREACONTOUR_IMAGEDIMENSIONS = "ImageDimensions";
58         CREACONTOUR_IMAGESPACING = "ImageSpacing";
59         CREACONTOUR_NUMBEROFCONTOURS = "NumberOfContours";
60         /*FOR EACH CONTOUR*/
61         CREACONTOUR_INSTANT = "Instant";
62         CREACONTOUR_TYPEMODEL = "TypeModel";
63         CREACONTOUR_NUMBEROFCONTROLPOINTS = "NumberOfControlPoints";
64         CREACONTOUR_TYPEVIEW = "TypeView";      
65         /*STATICCONTOURS*/
66         CREACONTOUR_NUMBEROFCONTOURSSTATIC = "NumberOfContoursStatic";
67
68         TEMPIMPORTOSIRIXFILE = "";
69
70 #ifdef WIN32
71
72         char currentPath[_MAX_PATH];    
73         GetModuleFileName(NULL, currentPath, _MAX_PATH);
74         TEMPIMPORTOSIRIXFILE = currentPath;
75
76         TEMPIMPORTOSIRIXFILE = TEMPIMPORTOSIRIXFILE.substr(0,TEMPIMPORTOSIRIXFILE.find_last_of("\\"));
77
78         TEMPIMPORTOSIRIXFILE.append("\\data\\TEMPIMPORTOSIRIXFILE.roi");
79         
80 #else
81         char * pPath;
82         pPath = getenv ("HOME");
83
84         if(pPath){
85             TEMPIMPORTOSIRIXFILE.append(pPath);
86         }else{
87             TEMPIMPORTOSIRIXFILE.append(".");
88         }
89         TEMPIMPORTOSIRIXFILE.append("/.creaContourDataTemp/TEMPIMPORTOSIRIXFILE.roi");
90 #endif
91         
92 }
93 OsirixParser::~OsirixParser(){
94
95 }
96
97 int OsirixParser::ParseFile(const char* xmlfile){
98
99         xercesc::DOMDocument *doc;
100
101
102         try {
103             XMLPlatformUtils::Initialize();
104         }
105         catch (const XMLException& toCatch) {
106             char* message = XMLString::transcode(toCatch.getMessage());
107             cout << "Error during initialization! :\n"
108                  << message << "\n";
109             XMLString::release(&message);
110             return 1;
111         }
112
113         XercesDOMParser* OsirixParser = new XercesDOMParser();
114
115
116                 OsirixParser->setDoNamespaces(true);
117                 OsirixParser->setDoSchema(true);
118                 OsirixParser->setValidationScheme(XercesDOMParser::Val_Always );
119                 OsirixParser->setExternalNoNamespaceSchemaLocation(XMLString::transcode(schema.c_str()));
120                 OsirixParser->setValidationSchemaFullChecking(true);
121                 OsirixParser->setValidationConstraintFatal(true);
122                 OsirixParser->setExitOnFirstFatalError(true);
123
124
125         ErrorHandler* errHandler = (ErrorHandler*) new OsirixParserErrorHandler();
126
127         OsirixParser->setErrorHandler(errHandler);
128
129
130         try {
131             OsirixParser->parse(xmlfile);
132
133
134                         if(OsirixParser->getErrorCount() > 0){
135
136                                 errorline = ((OsirixParserErrorHandler*)OsirixParser->getErrorHandler())->getErrorMsg();
137
138
139                                 delete OsirixParser;
140                                 delete errHandler;
141                                 return -2;
142                         }
143
144
145
146         }
147         catch (const XMLException& toCatch) {
148             char* message = XMLString::transcode(toCatch.getMessage());
149             cout << "Exception message is: \n"
150                  << message << "\n";
151             XMLString::release(&message);
152                         delete OsirixParser;
153                     delete errHandler;
154             return -1;
155         }
156         catch (const DOMException& toCatch) {
157             char* message = XMLString::transcode(toCatch.msg);
158             cout << "Exception message is: \n"
159                  << message << "\n";
160             XMLString::release(&message);
161                         delete OsirixParser;
162                         delete errHandler;
163             return -1;
164         }
165         catch (...) {
166             cout << "Unexpected Exception \n" ;
167                         delete OsirixParser;
168                         delete errHandler;
169             return -1;
170         }
171
172                 std::cout<<"parsing document..."<<std::endl;
173
174
175         doc = OsirixParser->getDocument();
176 //              DOMNodeList* list = doc->getChildNodes();               
177                 getUserData(doc->getDocumentElement());
178
179
180                 saveCreaContoursFormat();
181
182         delete OsirixParser;
183         delete errHandler;
184
185
186
187                 return 0;
188
189 }
190
191 void OsirixParser::setErrorLine(DOMNodeList* list){
192
193         DOMNode* node = list->item(0);
194         this->errorline =       XMLString::transcode(node->getTextContent());
195
196 }
197 DOMNode* OsirixParser::getLastNode(DOMNodeList* list){
198
199
200         DOMNode* node;
201         /*for(int i = list->getLength()-1; i >= 0 ;i--){
202
203                 node = list->item(i);
204
205                 if(node->getNodeType() == DOMNode::ELEMENT_NODE){
206                         i = -1;
207                 }
208
209         }*/
210         node = list->item(list->getLength()-1);
211
212
213
214         if(node->getChildNodes()->getLength()>0){
215                 return getLastNode(node->getChildNodes());
216         }
217         return node;
218
219 }
220
221 void OsirixParser::getUserData(DOMElement* element){
222         parseOSIRIX_DICT(element->getElementsByTagName(XMLString::transcode(OSIRIX_DICT)));
223 }
224
225 void OsirixParser::parseOSIRIX_DICT(DOMNodeList* list){
226         int i, j;
227         DOMNode* node, *childnode, *childnode1, *childarray;
228         std::string point_mm, point_px, osirixinteger, imageindex, temp;
229         DOMNodeList* childlist;
230         point_mm = OSIRIX_POINT_MM;
231         point_px = OSIRIX_POINT_PX;
232         imageindex = OSIRIX_IMAGEINDEX;
233         osirixinteger = OSIRIX_INTEGER;
234         
235         std::string osirixstring = OSIRIX_STRING;
236         std::string osirixname = OSIRIX_NAME;
237         
238
239         for(i = 0; i < (int)(list->getLength()); i++){
240                 node = list->item(i);           
241                 childlist = node->getChildNodes();
242                 for(j = 0; j < (int)(childlist->getLength());j++){
243                         childnode = childlist->item(j);                 
244                         temp = XMLString::transcode(childnode->getTextContent());       
245
246
247                         if(point_mm.compare(temp)==0){                          
248                                 childarray = childlist->item(j+2);
249                                 //temp = XMLString::transcode(childarray->getNodeName());                                       
250                                 if(childarray != 0){                                    
251                                         parseOSIRIX_POINT_MM(childarray->getChildNodes());                                      
252                                 }                               
253                         }else if(point_px.compare(temp)==0){                            
254                                 childarray = childlist->item(j+2);
255                                 //temp = XMLString::transcode(childarray->getNodeName());                                       
256                                 if(childarray != 0){                                    
257                                         parseOSIRIX_POINT_PX(childarray->getChildNodes());                                      
258                                 }                               
259                         }else if(imageindex.compare(temp) == 0){
260                                 childnode1 = childlist->item(j+2);
261                                 if(childnode1 != NULL && osirixinteger.compare(XMLString::transcode(childnode1->getNodeName())) == 0){
262                                         _imageindex = atoi(XMLString::transcode(childnode1->getTextContent()));                                         
263                                 }                               
264                         } else if(osirixname.compare(temp) == 0) {
265                           // keep information about the name of the ROI
266                                 childnode1 = childlist->item(j+2);
267                                 if(childnode1 != NULL && osirixstring.compare(XMLString::transcode(childnode1->getNodeName())) == 0){
268                                   char* roiname = XMLString::transcode(childnode1->getTextContent());
269                                   _roiname = string(roiname);
270                                 }
271                         }
272                 }               
273         }
274 }
275
276 void OsirixParser::parseOSIRIX_POINT_MM(DOMNodeList* list){
277         int i, stringfound0, stringfound1;
278         DOMNode* node;
279         string temp, osirix_string, numx, numy, numz;
280         vector<double>* vectorx;
281         vector<double>* vectory;
282         vector<double>* vectorz;
283         vectorXYZ vectorxyz;
284         double x, y, z; 
285
286         vectorx = new vector<double>;
287         vectory = new vector<double>;
288         vectorz = new vector<double>;
289
290         osirix_string = OSIRIX_STRING;
291
292         for(i = 0; i < (int)(list->getLength()); i++){
293                 node = list->item(i);
294                 if(osirix_string.compare(XMLString::transcode(node->getNodeName()))==0){
295                         temp = XMLString::transcode(node->getTextContent());                    
296
297                         stringfound0 = temp.find(",",0);
298                         numx = temp.substr(1, stringfound0-1);
299
300                         stringfound1 = temp.find(",",stringfound0+1);
301                         numy = temp.substr(stringfound0+1, stringfound1-stringfound0-1);
302
303                         stringfound0 = temp.find(")",stringfound1+1);
304                         numz = temp.substr(stringfound1+1, stringfound0-stringfound1-1);
305
306                         x = atof(numx.c_str());         
307                         y = atof(numy.c_str());         
308                         z = atof(numz.c_str());         
309
310                         vectorx->push_back(x);
311                         vectory->push_back(y);
312                         vectorz->push_back(z);
313                 }               
314         }
315         if(vectorx->size() > 0){
316                 vectorxyz.push_back(*vectorx);
317                 vectorxyz.push_back(*vectory);
318                 vectorxyz.push_back(*vectorz);
319                 contoursmapMM.insert(pair<int, vectorXYZ>(contoursmapMM.size(), vectorxyz));
320                 contoursnameMM.insert(pair<int, string>(contoursnameMM.size(), _roiname));
321         }
322 }
323
324 void OsirixParser::parseOSIRIX_POINT_PX(DOMNodeList* list){
325         int i, stringfound0, stringfound1;
326         DOMNode* node;
327         string temp, osirix_string, numx, numy;
328         vector<double>* vectorx;
329         vector<double>* vectory;        
330         vector<double>* vectorz;        
331         vectorXYZ vectorxyz;
332         double x, y, z; 
333
334         vectorx = new vector<double>;
335         vectory = new vector<double>;   
336         vectorz = new vector<double>;   
337
338         osirix_string = OSIRIX_STRING;
339
340         for(i = 0; i < (int)(list->getLength()); i++){
341                 node = list->item(i);
342                 if(osirix_string.compare(XMLString::transcode(node->getNodeName()))==0){
343                         temp = XMLString::transcode(node->getTextContent());                    
344
345                         stringfound0 = temp.find(",",0);
346                         numx = temp.substr(1, stringfound0-1);                                  
347
348                         stringfound1 = temp.find(")",stringfound0+1);
349                         numy = temp.substr(stringfound0+1, stringfound1-stringfound0-1);
350
351                         x = atof(numx.c_str());         
352                         y = atof(numy.c_str());                                 
353
354                         vectorx->push_back(x);
355                         vectory->push_back(y);  
356                         vectorz->push_back(_imageindex);
357                 }               
358         }
359         if(vectorx->size() > 0){
360                 vectorxyz.push_back(*vectorx);
361                 vectorxyz.push_back(*vectory);  
362                 vectorxyz.push_back(*vectorz);  
363                 contoursmapPX.insert(pair<int, vectorXYZ>(contoursmapPX.size(), vectorxyz));
364                 contoursnamePX.insert(pair<int, string>(contoursnamePX.size(), _roiname));
365         }       
366 }
367                 
368
369
370 void OsirixParser::getData(DOMNodeList* list, std::vector<std::string>& vect, std::string tagname){
371
372         for(int i = 0; i < (int)(list->getLength()); i++){
373                 DOMNode* node = list->item(i);
374                 if(tagname.compare(XMLString::transcode(node->getNodeName()))==0){
375                         std::cout<<"NODENAME "<<XMLString::transcode(node->getTextContent())<<std::endl;
376                         vect.push_back(XMLString::transcode(node->getTextContent()));
377                 }
378
379         }
380 }
381
382 void OsirixParser::saveCreaContoursFormat(){
383         FILE *pFile=fopen(TEMPIMPORTOSIRIXFILE.c_str(),"w+");
384
385         if(pFile){
386                 writeHeader(pFile);
387                 writeContours(pFile);
388                 writeContoursStatic(pFile);
389                 fclose(pFile);
390         }
391 }
392
393 void OsirixParser::writeContoursStatic(FILE* pFile){
394         fprintf(pFile, CREACONTOUR_IMAGEDIMENSIONS);
395         fprintf(pFile, " %d %d %d\n", _extent[1] - _extent[0],_extent[3] - _extent[2], _extent[5] - _extent[4]);
396         fprintf(pFile, CREACONTOUR_IMAGESPACING);
397         fprintf(pFile, " %f %f %f\n", _spacing[0], _spacing[1], _spacing[2]);
398         fprintf(pFile, CREACONTOUR_NUMBEROFCONTOURSSTATIC);
399         fprintf(pFile, " 0\n");
400 }
401
402 void OsirixParser::writeContours(FILE* pFile){
403         
404         map<int, vectorXYZ>::iterator itPX;
405         vector<double> vectx, vecty, vectz;
406         int i, valuez;
407         int dimz = 0, dimy = 0;
408
409         if(_extent != 0){
410                 dimz = _extent[5] - _extent[4] + 1;
411                 dimy = _extent[3] - _extent[2] + 1;
412         }
413
414         /*for (itMM = contoursmapMM.begin(),  itPX = contoursmapPX.begin(); 
415                         itMM != contoursmapMM.end(), itPX != contoursmapPX.end(); 
416                         itMM++, itPX++ ){*/
417         for (itPX = contoursmapPX.begin(); itPX != contoursmapPX.end(); itPX++ ){
418
419                 vectx = ((*itPX).second)[0];
420                 vecty = ((*itPX).second)[1];
421                 vectz = ((*itPX).second)[2];
422
423                 if(!vectz.empty()){
424
425                         valuez = (int) vectz[0] / _spacing[2];
426
427                         fprintf(pFile, CREACONTOUR_INSTANT);
428                         fprintf(pFile, " 1 %d 1 1 1 1\n",dimz - valuez);
429                         fprintf(pFile, CREACONTOUR_TYPEMODEL);
430                         fprintf(pFile, " 1\n");
431                         fprintf(pFile, CREACONTOUR_NUMBEROFCONTROLPOINTS);
432                         fprintf(pFile, " %d\n", vectz.size());
433                         for(i = 0; i < vectx.size(); i++){
434                           fprintf(pFile, "%f %f 900.00\n", vectx[i]/ _spacing[0], dimy - vecty[i]/ _spacing[1]);
435                           // fprintf(pFile, "%f %f %f\n", vectx[i] , vecty[i], vectz[i]);
436                         }               
437                         fprintf(pFile, CREACONTOUR_TYPEVIEW);
438                         fprintf(pFile, " 1\n");
439                         
440                 }
441         }
442 }
443
444 void OsirixParser::writeHeader(FILE* pFile){ 
445          
446
447         fprintf(pFile, CREACONTOUR);
448         fprintf(pFile, "\n");
449         fprintf(pFile, CREACONTOUR_VERSION);
450         fprintf(pFile, "\n");
451         fprintf(pFile, CREACONTOUR_IMAGEDIMENSIONS);
452         fprintf(pFile, " %d %d %d\n", _extent[1] - _extent[0],_extent[3] - _extent[2], _extent[5] - _extent[4]);
453         fprintf(pFile, CREACONTOUR_IMAGESPACING);
454         fprintf(pFile, " %f %f %f\n", _spacing[0], _spacing[1], _spacing[2]);
455         fprintf(pFile, CREACONTOUR_NUMBEROFCONTOURS);
456         fprintf(pFile, " %d\n", contoursmapPX.size());
457
458
459
460 }
461
462
463 std::string OsirixParser::getContoursFileName(){
464         return TEMPIMPORTOSIRIXFILE;
465 }
466
467 /**
468 **      The Error Handler's interface implementation
469 **/
470
471 /**
472         ** Default Constructor
473         **/
474 OsirixParserErrorHandler::OsirixParserErrorHandler()
475 : ErrorHandler(){
476
477
478
479
480 }
481         /**
482         ** Desctructor by defect
483         **/
484 OsirixParserErrorHandler::~OsirixParserErrorHandler(){
485 }
486
487 void    OsirixParserErrorHandler::warning (const SAXParseException &exc){
488 }
489
490 void    OsirixParserErrorHandler::error (const SAXParseException &exc){
491         char c[1000];
492         errormsg = "Column ";
493 //      errormsg +=     itoa(exc.getColumnNumber(),c,10);
494 #ifdef WIN32
495         sprintf_s(c,"%d",(int)(exc.getColumnNumber()));
496 #else
497         sprintf(c,"%d",(int)(exc.getColumnNumber()));
498 #endif
499         errormsg +=     std::string(c);
500
501         errormsg += " Line ";
502 //      errormsg +=     itoa(exc.getLineNumber(),c,10);
503 #ifdef WIN32
504         sprintf_s(c,"%d",(int)(exc.getLineNumber()));
505 #else
506         sprintf(c,"%d",(int)(exc.getLineNumber()));
507 #endif
508         errormsg +=     std::string(c);
509
510         errormsg += " ";
511         errormsg += XMLString::transcode(exc.getMessage());
512
513 }
514
515 void    OsirixParserErrorHandler::fatalError (const SAXParseException &exc){
516         char c[1000];
517         errormsg = "Column ";
518 //      errormsg +=     itoa(exc.getColumnNumber(),c,10);
519 #ifdef WIN32
520         sprintf_s(c,"%d",(int)(exc.getColumnNumber()));
521 #else
522         sprintf(c,"%d",(int)(exc.getColumnNumber()));
523 #endif
524         errormsg +=     std::string(c);
525
526         errormsg += " Line ";
527 //      errormsg +=     itoa(exc.getLineNumber(),c,10);
528 #ifdef WIN32
529         sprintf_s(c,"%d",(int)(exc.getLineNumber()));
530 #else
531         sprintf(c,"%d",(int)(exc.getLineNumber()));
532 #endif
533         errormsg +=     std::string(c);
534
535         errormsg += " ";
536         errormsg += XMLString::transcode(exc.getMessage());
537 }
538
539 void    OsirixParserErrorHandler::resetErrors (){
540 }
541
542 std::string OsirixParserErrorHandler::getErrorMsg(){
543         return this->errormsg;
544 }