ctkDICOMQuery.cpp 17 KB

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