ctkDICOMQuery.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0.txt
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QSqlQuery>
  16. #include <QSqlRecord>
  17. #include <QVariant>
  18. #include <QDate>
  19. #include <QStringList>
  20. #include <QSet>
  21. #include <QFile>
  22. #include <QDirIterator>
  23. #include <QFileInfo>
  24. #include <QDebug>
  25. // ctkDICOMCore includes
  26. #include "ctkDICOMQuery.h"
  27. #include "ctkLogger.h"
  28. // DCMTK includes
  29. #include "dcmtk/dcmnet/dimse.h"
  30. #include "dcmtk/dcmnet/diutil.h"
  31. #include <dcmtk/dcmdata/dcfilefo.h>
  32. #include <dcmtk/dcmdata/dcfilefo.h>
  33. #include <dcmtk/dcmdata/dcdeftag.h>
  34. #include <dcmtk/dcmdata/dcdatset.h>
  35. #include <dcmtk/ofstd/ofcond.h>
  36. #include <dcmtk/ofstd/ofstring.h>
  37. #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */
  38. #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */
  39. // NOTE: using ctk stand-in class for now - switch back
  40. // to dcmtk's scu.h when cget support is in a release version
  41. //#include <dcmtk/dcmnet/scu.h>
  42. #include <ctkDcmSCU.h>
  43. static ctkLogger logger ( "org.commontk.dicom.DICOMQuery" );
  44. //------------------------------------------------------------------------------
  45. // A customized implemenation so that Qt signals can be emitted
  46. // when query results are obtained
  47. class ctkDICOMQuerySCUPrivate : public ctkDcmSCU
  48. {
  49. public:
  50. ctkDICOMQuery *query;
  51. ctkDICOMQuerySCUPrivate()
  52. {
  53. this->query = 0;
  54. };
  55. ~ctkDICOMQuerySCUPrivate() {};
  56. virtual OFCondition handleFINDResponse(const T_ASC_PresentationContextID presID,
  57. QRResponse *response,
  58. OFBool &waitForNextResponse)
  59. {
  60. if (this->query)
  61. {
  62. logger.debug ( "FIND RESPONSE" );
  63. emit this->query->debug("Got a find response!");
  64. return this->ctkDcmSCU::handleFINDResponse(presID, response, waitForNextResponse);
  65. }
  66. };
  67. };
  68. //------------------------------------------------------------------------------
  69. class ctkDICOMQueryPrivate
  70. {
  71. public:
  72. ctkDICOMQueryPrivate();
  73. ~ctkDICOMQueryPrivate();
  74. /// Add a StudyInstanceUID to be queried
  75. void addStudyInstanceUIDAndDataset(const QString& StudyInstanceUID, DcmDataset* dataset );
  76. QString CallingAETitle;
  77. QString CalledAETitle;
  78. QString Host;
  79. int Port;
  80. QMap<QString,QVariant> Filters;
  81. ctkDICOMQuerySCUPrivate SCU;
  82. DcmDataset* Query;
  83. QStringList StudyInstanceUIDList;
  84. QList<DcmDataset*> StudyDatasetList;
  85. bool Canceled;
  86. };
  87. //------------------------------------------------------------------------------
  88. // ctkDICOMQueryPrivate methods
  89. //------------------------------------------------------------------------------
  90. ctkDICOMQueryPrivate::ctkDICOMQueryPrivate()
  91. {
  92. this->Query = new DcmDataset();
  93. this->Port = 0;
  94. this->Canceled = false;
  95. }
  96. //------------------------------------------------------------------------------
  97. ctkDICOMQueryPrivate::~ctkDICOMQueryPrivate()
  98. {
  99. delete this->Query;
  100. }
  101. //------------------------------------------------------------------------------
  102. void ctkDICOMQueryPrivate::addStudyInstanceUIDAndDataset( const QString& s, DcmDataset* dataset )
  103. {
  104. this->StudyInstanceUIDList.append ( s );
  105. this->StudyDatasetList.append ( dataset );
  106. }
  107. //------------------------------------------------------------------------------
  108. // ctkDICOMQuery methods
  109. //------------------------------------------------------------------------------
  110. ctkDICOMQuery::ctkDICOMQuery(QObject* parentObject)
  111. : QObject(parentObject)
  112. , d_ptr(new ctkDICOMQueryPrivate)
  113. {
  114. Q_D(ctkDICOMQuery);
  115. d->SCU.query = this; // give the dcmtk level access to this for emitting signals
  116. }
  117. //------------------------------------------------------------------------------
  118. ctkDICOMQuery::~ctkDICOMQuery()
  119. {
  120. }
  121. /// Set methods for connectivity
  122. //------------------------------------------------------------------------------
  123. void ctkDICOMQuery::setCallingAETitle( const QString& callingAETitle )
  124. {
  125. Q_D(ctkDICOMQuery);
  126. d->CallingAETitle = callingAETitle;
  127. }
  128. //------------------------------------------------------------------------------
  129. QString ctkDICOMQuery::callingAETitle() const
  130. {
  131. Q_D(const ctkDICOMQuery);
  132. return d->CallingAETitle;
  133. }
  134. //------------------------------------------------------------------------------
  135. void ctkDICOMQuery::setCalledAETitle( const QString& calledAETitle )
  136. {
  137. Q_D(ctkDICOMQuery);
  138. d->CalledAETitle = calledAETitle;
  139. }
  140. //------------------------------------------------------------------------------
  141. QString ctkDICOMQuery::calledAETitle()const
  142. {
  143. Q_D(const ctkDICOMQuery);
  144. return d->CalledAETitle;
  145. }
  146. //------------------------------------------------------------------------------
  147. void ctkDICOMQuery::setHost( const QString& host )
  148. {
  149. Q_D(ctkDICOMQuery);
  150. d->Host = host;
  151. }
  152. //------------------------------------------------------------------------------
  153. QString ctkDICOMQuery::host() const
  154. {
  155. Q_D(const ctkDICOMQuery);
  156. return d->Host;
  157. }
  158. //------------------------------------------------------------------------------
  159. void ctkDICOMQuery::setPort ( int port )
  160. {
  161. Q_D(ctkDICOMQuery);
  162. d->Port = port;
  163. }
  164. //------------------------------------------------------------------------------
  165. int ctkDICOMQuery::port()const
  166. {
  167. Q_D(const ctkDICOMQuery);
  168. return d->Port;
  169. }
  170. //------------------------------------------------------------------------------
  171. void ctkDICOMQuery::setFilters( const QMap<QString,QVariant>& filters )
  172. {
  173. Q_D(ctkDICOMQuery);
  174. d->Filters = filters;
  175. }
  176. //------------------------------------------------------------------------------
  177. QMap<QString,QVariant> ctkDICOMQuery::filters()const
  178. {
  179. Q_D(const ctkDICOMQuery);
  180. return d->Filters;
  181. }
  182. //------------------------------------------------------------------------------
  183. QStringList ctkDICOMQuery::studyInstanceUIDQueried()const
  184. {
  185. Q_D(const ctkDICOMQuery);
  186. return d->StudyInstanceUIDList;
  187. }
  188. //------------------------------------------------------------------------------
  189. bool ctkDICOMQuery::query(ctkDICOMDatabase& database )
  190. {
  191. //// turn on logging if needed for debug:
  192. //dcmtk::log4cplus::Logger log = dcmtk::log4cplus::Logger::getRoot();
  193. //log.setLogLevel(OFLogger::DEBUG_LOG_LEVEL);
  194. // ctkDICOMDatabase::setDatabase ( database );
  195. Q_D(ctkDICOMQuery);
  196. // In the following, we emit progress(int) after progress(QString), this
  197. // is in case the connected object doesn't refresh its ui when the progress
  198. // message is updated but only if the progress value is (e.g. QProgressDialog)
  199. if ( database.database().isOpen() )
  200. {
  201. logger.debug ( "DB open in Query" );
  202. emit progress("DB open in Query");
  203. }
  204. else
  205. {
  206. logger.debug ( "DB not open in Query" );
  207. emit progress("DB not open in Query");
  208. }
  209. emit progress(0);
  210. if (d->Canceled) {return false;}
  211. d->StudyInstanceUIDList.clear();
  212. d->SCU.setAETitle ( OFString(this->callingAETitle().toStdString().c_str()) );
  213. d->SCU.setPeerAETitle ( OFString(this->calledAETitle().toStdString().c_str()) );
  214. d->SCU.setPeerHostName ( OFString(this->host().toStdString().c_str()) );
  215. d->SCU.setPeerPort ( this->port() );
  216. logger.error ( "Setting Transfer Syntaxes" );
  217. emit progress("Setting Transfer Syntaxes");
  218. emit progress(10);
  219. if (d->Canceled) {return false;}
  220. OFList<OFString> transferSyntaxes;
  221. transferSyntaxes.push_back ( UID_LittleEndianExplicitTransferSyntax );
  222. transferSyntaxes.push_back ( UID_BigEndianExplicitTransferSyntax );
  223. transferSyntaxes.push_back ( UID_LittleEndianImplicitTransferSyntax );
  224. d->SCU.addPresentationContext ( UID_FINDStudyRootQueryRetrieveInformationModel, transferSyntaxes );
  225. // d->SCU.addPresentationContext ( UID_VerificationSOPClass, transferSyntaxes );
  226. if ( !d->SCU.initNetwork().good() )
  227. {
  228. logger.error( "Error initializing the network" );
  229. emit progress("Error initializing the network");
  230. emit progress(100);
  231. return false;
  232. }
  233. logger.debug ( "Negotiating Association" );
  234. emit progress("Negatiating Association");
  235. emit progress(20);
  236. if (d->Canceled) {return false;}
  237. OFCondition result = d->SCU.negotiateAssociation();
  238. if (result.bad())
  239. {
  240. logger.error( "Error negotiating the association: " + QString(result.text()) );
  241. emit progress("Error negotiating the association");
  242. emit progress(100);
  243. return false;
  244. }
  245. // Clear the query
  246. d->Query->clear();
  247. // Insert all keys that we like to receive values for
  248. d->Query->insertEmptyElement ( DCM_PatientID );
  249. d->Query->insertEmptyElement ( DCM_PatientName );
  250. d->Query->insertEmptyElement ( DCM_PatientBirthDate );
  251. d->Query->insertEmptyElement ( DCM_StudyID );
  252. d->Query->insertEmptyElement ( DCM_StudyInstanceUID );
  253. d->Query->insertEmptyElement ( DCM_StudyDescription );
  254. d->Query->insertEmptyElement ( DCM_StudyDate );
  255. d->Query->insertEmptyElement ( DCM_StudyTime );
  256. d->Query->insertEmptyElement ( DCM_ModalitiesInStudy );
  257. d->Query->insertEmptyElement ( DCM_AccessionNumber );
  258. d->Query->insertEmptyElement ( DCM_NumberOfStudyRelatedInstances ); // Number of images in the series
  259. d->Query->insertEmptyElement ( DCM_NumberOfStudyRelatedSeries ); // Number of series in the study
  260. // Make clear we define our search values in ISO Latin 1 (default would be ASCII)
  261. d->Query->putAndInsertOFStringArray(DCM_SpecificCharacterSet, "ISO_IR 100");
  262. d->Query->putAndInsertString ( DCM_QueryRetrieveLevel, "STUDY" );
  263. /* Now, for all keys that the user provided for filtering on STUDY level,
  264. * overwrite empty keys with value. For now, only Patient's Name, Patient ID,
  265. * Study Description, Modalities in Study, and Study Date are used.
  266. */
  267. QString seriesDescription;
  268. foreach( QString key, d->Filters.keys() )
  269. {
  270. if ( key == QString("Name") && !d->Filters[key].toString().isEmpty())
  271. {
  272. // make the filter a wildcard in dicom style
  273. d->Query->putAndInsertString( DCM_PatientName,
  274. (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data());
  275. }
  276. else if ( key == QString("Study") && !d->Filters[key].toString().isEmpty())
  277. {
  278. // make the filter a wildcard in dicom style
  279. d->Query->putAndInsertString( DCM_StudyDescription,
  280. (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data());
  281. }
  282. else if ( key == QString("ID") && !d->Filters[key].toString().isEmpty())
  283. {
  284. // make the filter a wildcard in dicom style
  285. d->Query->putAndInsertString( DCM_PatientID,
  286. (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data());
  287. }
  288. else if ( key == QString("Modalities") && !d->Filters[key].toString().isEmpty())
  289. {
  290. // make the filter be an "OR" of modalities using backslash (dicom-style)
  291. QString modalitySearch("");
  292. foreach (const QString& modality, d->Filters[key].toStringList())
  293. {
  294. modalitySearch += modality + QString("\\");
  295. }
  296. modalitySearch.chop(1); // remove final backslash
  297. logger.debug("modalityInStudySearch " + modalitySearch);
  298. d->Query->putAndInsertString( DCM_ModalitiesInStudy, modalitySearch.toAscii().data() );
  299. }
  300. // Rememer Series Description for later series query if we go through the keys now
  301. else if ( key == QString("Series") && !d->Filters[key].toString().isEmpty())
  302. {
  303. // make the filter a wildcard in dicom style
  304. seriesDescription = "*" + d->Filters[key].toString() + "*";
  305. }
  306. else
  307. {
  308. logger.debug("Ignoring unknown search key: " + key);
  309. }
  310. }
  311. if ( d->Filters.keys().contains("StartDate") && d->Filters.keys().contains("EndDate") )
  312. {
  313. QString dateRange = d->Filters["StartDate"].toString() +
  314. QString("-") +
  315. d->Filters["EndDate"].toString();
  316. d->Query->putAndInsertString ( DCM_StudyDate, dateRange.toAscii().data() );
  317. logger.debug("Query on study date " + dateRange);
  318. }
  319. emit progress(30);
  320. if (d->Canceled) {return false;}
  321. OFList<QRResponse *> responses;
  322. Uint16 presentationContext = 0;
  323. // Check for any accepted presentation context for FIND in study root (dont care about transfer syntax)
  324. presentationContext = d->SCU.findPresentationContextID ( UID_FINDStudyRootQueryRetrieveInformationModel, "");
  325. if ( presentationContext == 0 )
  326. {
  327. logger.error ( "Failed to find acceptable presentation context" );
  328. emit progress("Failed to find acceptable presentation context");
  329. }
  330. else
  331. {
  332. logger.info ( "Found useful presentation context" );
  333. emit progress("Found useful presentation context");
  334. }
  335. emit progress(40);
  336. if (d->Canceled) {return false;}
  337. OFCondition status = d->SCU.sendFINDRequest ( presentationContext, d->Query, &responses );
  338. if ( !status.good() )
  339. {
  340. logger.error ( "Find failed" );
  341. emit progress("Find failed");
  342. d->SCU.closeAssociation ( DCMSCU_RELEASE_ASSOCIATION );
  343. emit progress(100);
  344. return false;
  345. }
  346. logger.debug ( "Find succeded");
  347. emit progress("Find succeded");
  348. emit progress(50);
  349. if (d->Canceled) {return false;}
  350. for ( OFIterator<QRResponse*> it = responses.begin(); it != responses.end(); it++ )
  351. {
  352. DcmDataset *dataset = (*it)->m_dataset;
  353. if ( dataset != NULL ) // the last response is always empty
  354. {
  355. database.insert ( dataset, false /* do not store to disk*/, false /* no thumbnail*/);
  356. OFString StudyInstanceUID;
  357. dataset->findAndGetOFString ( DCM_StudyInstanceUID, StudyInstanceUID );
  358. d->addStudyInstanceUIDAndDataset ( StudyInstanceUID.c_str(), dataset );
  359. emit progress(QString("Processing: ") + QString(StudyInstanceUID.c_str()));
  360. emit progress(50);
  361. if (d->Canceled) {return false;}
  362. }
  363. }
  364. /* Only ask for series attributes now. This requires kicking out the rest of former query. */
  365. d->Query->clear();
  366. d->Query->insertEmptyElement ( DCM_SeriesNumber );
  367. d->Query->insertEmptyElement ( DCM_SeriesDescription );
  368. d->Query->insertEmptyElement ( DCM_SeriesInstanceUID );
  369. d->Query->insertEmptyElement ( DCM_SeriesDate );
  370. d->Query->insertEmptyElement ( DCM_SeriesTime );
  371. d->Query->insertEmptyElement ( DCM_Modality );
  372. d->Query->insertEmptyElement ( DCM_NumberOfSeriesRelatedInstances ); // Number of images in the series
  373. /* Add user-defined filters */
  374. d->Query->putAndInsertOFStringArray(DCM_SeriesDescription, seriesDescription.toLatin1().data());
  375. // Now search each within each Study that was identified
  376. d->Query->putAndInsertString ( DCM_QueryRetrieveLevel, "SERIES" );
  377. float progressRatio = 25. / d->StudyInstanceUIDList.count();
  378. int i = 0;
  379. QListIterator<DcmDataset*> datasetIterator(d->StudyDatasetList);
  380. foreach ( QString StudyInstanceUID, d->StudyInstanceUIDList )
  381. {
  382. DcmDataset *studyDataset = datasetIterator.next();
  383. DcmElement *patientName, *patientID;
  384. studyDataset->findAndGetElement(DCM_PatientName, patientName);
  385. studyDataset->findAndGetElement(DCM_PatientID, patientID);
  386. logger.debug ( "Starting Series C-FIND for Study: " + StudyInstanceUID );
  387. emit progress(QString("Starting Series C-FIND for Study: ") + StudyInstanceUID);
  388. emit progress(50 + (progressRatio * i++));
  389. if (d->Canceled) {return false;}
  390. d->Query->putAndInsertString ( DCM_StudyInstanceUID, StudyInstanceUID.toStdString().c_str() );
  391. OFList<QRResponse *> responses;
  392. status = d->SCU.sendFINDRequest ( presentationContext, d->Query, &responses );
  393. if ( status.good() )
  394. {
  395. for ( OFIterator<QRResponse*> it = responses.begin(); it != responses.end(); it++ )
  396. {
  397. DcmDataset *dataset = (*it)->m_dataset;
  398. if ( dataset != NULL )
  399. {
  400. // add the patient elements not provided for the series level query
  401. dataset->insert( patientName, true );
  402. dataset->insert( patientID, true );
  403. // insert series dataset
  404. database.insert ( dataset, false /* do not store */, false /* no thumbnail */ );
  405. }
  406. }
  407. logger.debug ( "Find succeded on Series level for Study: " + StudyInstanceUID );
  408. emit progress(QString("Find succeded on Series level for Study: ") + StudyInstanceUID);
  409. emit progress(50 + (progressRatio * i++));
  410. if (d->Canceled) {return false;}
  411. }
  412. else
  413. {
  414. logger.error ( "Find on Series level failed for Study: " + StudyInstanceUID );
  415. emit progress(QString("Find on Series level failed for Study: ") + StudyInstanceUID);
  416. }
  417. emit progress(50 + (progressRatio * i++));
  418. if (d->Canceled) {return false;}
  419. }
  420. d->SCU.closeAssociation ( DCMSCU_RELEASE_ASSOCIATION );
  421. emit progress(100);
  422. return true;
  423. }
  424. //----------------------------------------------------------------------------
  425. void ctkDICOMQuery::cancel()
  426. {
  427. Q_D(ctkDICOMQuery);
  428. d->Canceled = true;
  429. }