ctkDICOMQuery.cpp 16 KB

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