ctkDICOMQuery.cpp 18 KB

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