ctkDICOMQuery.cpp 17 KB

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