ctkDICOMQuery.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 "ctkDcmSCU.h"
  32. #include <dcmtk/dcmdata/dcfilefo.h>
  33. #include <dcmtk/dcmdata/dcfilefo.h>
  34. #include <dcmtk/dcmdata/dcdeftag.h>
  35. #include <dcmtk/dcmdata/dcdatset.h>
  36. #include <dcmtk/ofstd/ofcond.h>
  37. #include <dcmtk/ofstd/ofstring.h>
  38. #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */
  39. #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */
  40. static ctkLogger logger ( "org.commontk.dicom.DICOMQuery" );
  41. //------------------------------------------------------------------------------
  42. // A customized implemenation so that Qt signals can be emitted
  43. // when query results are obtained
  44. class ctkDICOMQuerySCUPrivate : public DcmSCU
  45. {
  46. public:
  47. ctkDICOMQuery *query;
  48. ctkDICOMQuerySCUPrivate()
  49. {
  50. this->query = 0;
  51. };
  52. ~ctkDICOMQuerySCUPrivate() {};
  53. virtual OFCondition handleFINDResponse(const T_ASC_PresentationContextID presID,
  54. QRResponse *response,
  55. OFBool &waitForNextResponse)
  56. {
  57. if (this->query)
  58. {
  59. logger.debug ( "FIND RESPONSE" );
  60. emit this->query->debug("Got a find response!");
  61. return this->DcmSCU::handleFINDResponse(presID, response, waitForNextResponse);
  62. }
  63. return DIMSE_NULLKEY;
  64. };
  65. };
  66. //------------------------------------------------------------------------------
  67. class ctkDICOMQueryPrivate
  68. {
  69. public:
  70. ctkDICOMQueryPrivate();
  71. ~ctkDICOMQueryPrivate();
  72. /// Add a StudyInstanceUID to be queried
  73. void addStudyInstanceUIDAndDataset(const QString& StudyInstanceUID, DcmDataset* dataset );
  74. QString CallingAETitle;
  75. QString CalledAETitle;
  76. QString Host;
  77. int Port;
  78. bool PreferCGET;
  79. QMap<QString,QVariant> Filters;
  80. ctkDICOMQuerySCUPrivate SCU;
  81. DcmDataset* Query;
  82. QStringList StudyInstanceUIDList;
  83. QList<DcmDataset*> StudyDatasetList;
  84. bool Canceled;
  85. };
  86. //------------------------------------------------------------------------------
  87. // ctkDICOMQueryPrivate methods
  88. //------------------------------------------------------------------------------
  89. ctkDICOMQueryPrivate::ctkDICOMQueryPrivate()
  90. {
  91. this->Query = new DcmDataset();
  92. this->Port = 0;
  93. this->Canceled = false;
  94. this->PreferCGET = 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::setPreferCGET ( bool preferCGET )
  172. {
  173. Q_D(ctkDICOMQuery);
  174. d->PreferCGET = preferCGET;
  175. }
  176. //------------------------------------------------------------------------------
  177. bool ctkDICOMQuery::preferCGET()const
  178. {
  179. Q_D(const ctkDICOMQuery);
  180. return d->PreferCGET;
  181. }
  182. //------------------------------------------------------------------------------
  183. void ctkDICOMQuery::setFilters( const QMap<QString,QVariant>& filters )
  184. {
  185. Q_D(ctkDICOMQuery);
  186. d->Filters = filters;
  187. }
  188. //------------------------------------------------------------------------------
  189. QMap<QString,QVariant> ctkDICOMQuery::filters()const
  190. {
  191. Q_D(const ctkDICOMQuery);
  192. return d->Filters;
  193. }
  194. //------------------------------------------------------------------------------
  195. QStringList ctkDICOMQuery::studyInstanceUIDQueried()const
  196. {
  197. Q_D(const ctkDICOMQuery);
  198. return d->StudyInstanceUIDList;
  199. }
  200. //------------------------------------------------------------------------------
  201. bool ctkDICOMQuery::query(ctkDICOMDatabase& database )
  202. {
  203. //// turn on logging if needed for debug:
  204. //dcmtk::log4cplus::Logger log = dcmtk::log4cplus::Logger::getRoot();
  205. //log.setLogLevel(OFLogger::DEBUG_LOG_LEVEL);
  206. // ctkDICOMDatabase::setDatabase ( database );
  207. Q_D(ctkDICOMQuery);
  208. // In the following, we emit progress(int) after progress(QString), this
  209. // is in case the connected object doesn't refresh its ui when the progress
  210. // message is updated but only if the progress value is (e.g. QProgressDialog)
  211. if ( database.database().isOpen() )
  212. {
  213. logger.debug ( "DB open in Query" );
  214. emit progress("DB open in Query");
  215. }
  216. else
  217. {
  218. logger.debug ( "DB not open in Query" );
  219. emit progress("DB not open in Query");
  220. }
  221. emit progress(0);
  222. if (d->Canceled) {return false;}
  223. d->StudyInstanceUIDList.clear();
  224. d->SCU.setAETitle ( OFString(this->callingAETitle().toStdString().c_str()) );
  225. d->SCU.setPeerAETitle ( OFString(this->calledAETitle().toStdString().c_str()) );
  226. d->SCU.setPeerHostName ( OFString(this->host().toStdString().c_str()) );
  227. d->SCU.setPeerPort ( this->port() );
  228. logger.error ( "Setting Transfer Syntaxes" );
  229. emit progress("Setting Transfer Syntaxes");
  230. emit progress(10);
  231. if (d->Canceled) {return false;}
  232. OFList<OFString> transferSyntaxes;
  233. transferSyntaxes.push_back ( UID_LittleEndianExplicitTransferSyntax );
  234. transferSyntaxes.push_back ( UID_BigEndianExplicitTransferSyntax );
  235. transferSyntaxes.push_back ( UID_LittleEndianImplicitTransferSyntax );
  236. d->SCU.addPresentationContext ( UID_FINDStudyRootQueryRetrieveInformationModel, transferSyntaxes );
  237. // d->SCU.addPresentationContext ( UID_VerificationSOPClass, transferSyntaxes );
  238. if ( !d->SCU.initNetwork().good() )
  239. {
  240. logger.error( "Error initializing the network" );
  241. emit progress("Error initializing the network");
  242. emit progress(100);
  243. return false;
  244. }
  245. logger.debug ( "Negotiating Association" );
  246. emit progress("Negotiating Association");
  247. emit progress(20);
  248. if (d->Canceled) {return false;}
  249. OFCondition result = d->SCU.negotiateAssociation();
  250. if (result.bad())
  251. {
  252. logger.error( "Error negotiating the association: " + QString(result.text()) );
  253. emit progress("Error negotiating the association");
  254. emit progress(100);
  255. return false;
  256. }
  257. // Clear the query
  258. d->Query->clear();
  259. // Insert all keys that we like to receive values for
  260. d->Query->insertEmptyElement ( DCM_PatientID );
  261. d->Query->insertEmptyElement ( DCM_PatientName );
  262. d->Query->insertEmptyElement ( DCM_PatientBirthDate );
  263. d->Query->insertEmptyElement ( DCM_StudyID );
  264. d->Query->insertEmptyElement ( DCM_StudyInstanceUID );
  265. d->Query->insertEmptyElement ( DCM_StudyDescription );
  266. d->Query->insertEmptyElement ( DCM_StudyDate );
  267. d->Query->insertEmptyElement ( DCM_StudyTime );
  268. d->Query->insertEmptyElement ( DCM_ModalitiesInStudy );
  269. d->Query->insertEmptyElement ( DCM_AccessionNumber );
  270. d->Query->insertEmptyElement ( DCM_NumberOfStudyRelatedInstances ); // Number of images in the series
  271. d->Query->insertEmptyElement ( DCM_NumberOfStudyRelatedSeries ); // Number of series in the study
  272. // Make clear we define our search values in ISO Latin 1 (default would be ASCII)
  273. d->Query->putAndInsertOFStringArray(DCM_SpecificCharacterSet, "ISO_IR 100");
  274. d->Query->putAndInsertString ( DCM_QueryRetrieveLevel, "STUDY" );
  275. /* Now, for all keys that the user provided for filtering on STUDY level,
  276. * overwrite empty keys with value. For now, only Patient's Name, Patient ID,
  277. * Study Description, Modalities in Study, and Study Date are used.
  278. */
  279. QString seriesDescription;
  280. foreach( QString key, d->Filters.keys() )
  281. {
  282. if ( key == QString("Name") && !d->Filters[key].toString().isEmpty())
  283. {
  284. // make the filter a wildcard in dicom style
  285. d->Query->putAndInsertString( DCM_PatientName,
  286. (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data());
  287. }
  288. else if ( key == QString("Study") && !d->Filters[key].toString().isEmpty())
  289. {
  290. // make the filter a wildcard in dicom style
  291. d->Query->putAndInsertString( DCM_StudyDescription,
  292. (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data());
  293. }
  294. else if ( key == QString("ID") && !d->Filters[key].toString().isEmpty())
  295. {
  296. // make the filter a wildcard in dicom style
  297. d->Query->putAndInsertString( DCM_PatientID,
  298. (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data());
  299. }
  300. else if ( key == QString("Modalities") && !d->Filters[key].toString().isEmpty())
  301. {
  302. // make the filter be an "OR" of modalities using backslash (dicom-style)
  303. QString modalitySearch("");
  304. foreach (const QString& modality, d->Filters[key].toStringList())
  305. {
  306. modalitySearch += modality + QString("\\");
  307. }
  308. modalitySearch.chop(1); // remove final backslash
  309. logger.debug("modalityInStudySearch " + modalitySearch);
  310. d->Query->putAndInsertString( DCM_ModalitiesInStudy, modalitySearch.toAscii().data() );
  311. }
  312. // Rememer Series Description for later series query if we go through the keys now
  313. else if ( key == QString("Series") && !d->Filters[key].toString().isEmpty())
  314. {
  315. // make the filter a wildcard in dicom style
  316. seriesDescription = "*" + d->Filters[key].toString() + "*";
  317. }
  318. else
  319. {
  320. logger.debug("Ignoring unknown search key: " + key);
  321. }
  322. }
  323. if ( d->Filters.keys().contains("StartDate") && d->Filters.keys().contains("EndDate") )
  324. {
  325. QString dateRange = d->Filters["StartDate"].toString() +
  326. QString("-") +
  327. d->Filters["EndDate"].toString();
  328. d->Query->putAndInsertString ( DCM_StudyDate, dateRange.toAscii().data() );
  329. logger.debug("Query on study date " + dateRange);
  330. }
  331. emit progress(30);
  332. if (d->Canceled) {return false;}
  333. OFList<QRResponse *> responses;
  334. Uint16 presentationContext = 0;
  335. // Check for any accepted presentation context for FIND in study root (dont care about transfer syntax)
  336. presentationContext = d->SCU.findPresentationContextID ( UID_FINDStudyRootQueryRetrieveInformationModel, "");
  337. if ( presentationContext == 0 )
  338. {
  339. logger.error ( "Failed to find acceptable presentation context" );
  340. emit progress("Failed to find acceptable presentation context");
  341. }
  342. else
  343. {
  344. logger.info ( "Found useful presentation context" );
  345. emit progress("Found useful presentation context");
  346. }
  347. emit progress(40);
  348. if (d->Canceled) {return false;}
  349. OFCondition status = d->SCU.sendFINDRequest ( presentationContext, d->Query, &responses );
  350. if ( !status.good() )
  351. {
  352. logger.error ( "Find failed" );
  353. emit progress("Find failed");
  354. d->SCU.closeAssociation ( DCMSCU_RELEASE_ASSOCIATION );
  355. emit progress(100);
  356. return false;
  357. }
  358. logger.debug ( "Find succeded");
  359. emit progress("Find succeded");
  360. emit progress(50);
  361. if (d->Canceled) {return false;}
  362. for ( OFIterator<QRResponse*> it = responses.begin(); it != responses.end(); it++ )
  363. {
  364. DcmDataset *dataset = (*it)->m_dataset;
  365. if ( dataset != NULL ) // the last response is always empty
  366. {
  367. database.insert ( dataset, false /* do not store to disk*/, false /* no thumbnail*/);
  368. OFString StudyInstanceUID;
  369. dataset->findAndGetOFString ( DCM_StudyInstanceUID, StudyInstanceUID );
  370. d->addStudyInstanceUIDAndDataset ( StudyInstanceUID.c_str(), dataset );
  371. emit progress(QString("Processing: ") + QString(StudyInstanceUID.c_str()));
  372. emit progress(50);
  373. if (d->Canceled) {return false;}
  374. }
  375. }
  376. /* Only ask for series attributes now. This requires kicking out the rest of former query. */
  377. d->Query->clear();
  378. d->Query->insertEmptyElement ( DCM_SeriesNumber );
  379. d->Query->insertEmptyElement ( DCM_SeriesDescription );
  380. d->Query->insertEmptyElement ( DCM_SeriesInstanceUID );
  381. d->Query->insertEmptyElement ( DCM_SeriesDate );
  382. d->Query->insertEmptyElement ( DCM_SeriesTime );
  383. d->Query->insertEmptyElement ( DCM_Modality );
  384. d->Query->insertEmptyElement ( DCM_NumberOfSeriesRelatedInstances ); // Number of images in the series
  385. /* Add user-defined filters */
  386. d->Query->putAndInsertOFStringArray(DCM_SeriesDescription, seriesDescription.toLatin1().data());
  387. // Now search each within each Study that was identified
  388. d->Query->putAndInsertString ( DCM_QueryRetrieveLevel, "SERIES" );
  389. float progressRatio = 25. / d->StudyInstanceUIDList.count();
  390. int i = 0;
  391. QListIterator<DcmDataset*> datasetIterator(d->StudyDatasetList);
  392. foreach ( QString StudyInstanceUID, d->StudyInstanceUIDList )
  393. {
  394. DcmDataset *studyDataset = datasetIterator.next();
  395. DcmElement *patientName, *patientID;
  396. studyDataset->findAndGetElement(DCM_PatientName, patientName);
  397. studyDataset->findAndGetElement(DCM_PatientID, patientID);
  398. logger.debug ( "Starting Series C-FIND for Study: " + StudyInstanceUID );
  399. emit progress(QString("Starting Series C-FIND for Study: ") + StudyInstanceUID);
  400. emit progress(50 + (progressRatio * i++));
  401. if (d->Canceled) {return false;}
  402. d->Query->putAndInsertString ( DCM_StudyInstanceUID, StudyInstanceUID.toStdString().c_str() );
  403. OFList<QRResponse *> responses;
  404. status = d->SCU.sendFINDRequest ( presentationContext, d->Query, &responses );
  405. if ( status.good() )
  406. {
  407. for ( OFIterator<QRResponse*> it = responses.begin(); it != responses.end(); it++ )
  408. {
  409. DcmDataset *dataset = (*it)->m_dataset;
  410. if ( dataset != NULL )
  411. {
  412. // add the patient elements not provided for the series level query
  413. dataset->insert( patientName, true );
  414. dataset->insert( patientID, true );
  415. // insert series dataset
  416. database.insert ( dataset, false /* do not store */, false /* no thumbnail */ );
  417. }
  418. }
  419. logger.debug ( "Find succeded on Series level for Study: " + StudyInstanceUID );
  420. emit progress(QString("Find succeded on Series level for Study: ") + StudyInstanceUID);
  421. emit progress(50 + (progressRatio * i++));
  422. if (d->Canceled) {return false;}
  423. }
  424. else
  425. {
  426. logger.error ( "Find on Series level failed for Study: " + StudyInstanceUID );
  427. emit progress(QString("Find on Series level failed for Study: ") + StudyInstanceUID);
  428. }
  429. emit progress(50 + (progressRatio * i++));
  430. if (d->Canceled) {return false;}
  431. }
  432. d->SCU.closeAssociation ( DCMSCU_RELEASE_ASSOCIATION );
  433. emit progress(100);
  434. return true;
  435. }
  436. //----------------------------------------------------------------------------
  437. void ctkDICOMQuery::cancel()
  438. {
  439. Q_D(ctkDICOMQuery);
  440. d->Canceled = true;
  441. }