ctkDICOMDatabase.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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.commontk.org/LICENSE
  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. #include <stdexcept>
  15. // Qt includes
  16. #include <QSqlQuery>
  17. #include <QSqlRecord>
  18. #include <QSqlError>
  19. #include <QVariant>
  20. #include <QDate>
  21. #include <QStringList>
  22. #include <QSet>
  23. #include <QFile>
  24. #include <QDirIterator>
  25. #include <QFileInfo>
  26. #include <QDebug>
  27. #include <QFileSystemWatcher>
  28. // ctkDICOM includes
  29. #include "ctkDICOMDatabase.h"
  30. #include "ctkDICOMImage.h"
  31. #include "ctkLogger.h"
  32. // DCMTK includes
  33. #ifndef WIN32
  34. #define HAVE_CONFIG_H
  35. #endif
  36. #include <dcmtk/dcmdata/dcfilefo.h>
  37. #include <dcmtk/dcmdata/dcfilefo.h>
  38. #include <dcmtk/dcmdata/dcdeftag.h>
  39. #include <dcmtk/dcmdata/dcdatset.h>
  40. #include <dcmtk/ofstd/ofcond.h>
  41. #include <dcmtk/ofstd/ofstring.h>
  42. #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */
  43. #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */
  44. #include <dcmimage.h>
  45. //------------------------------------------------------------------------------
  46. static ctkLogger logger("org.commontk.dicom.DICOMDatabase" );
  47. //------------------------------------------------------------------------------
  48. //------------------------------------------------------------------------------
  49. class ctkDICOMDatabasePrivate
  50. {
  51. Q_DECLARE_PUBLIC(ctkDICOMDatabase);
  52. protected:
  53. ctkDICOMDatabase* const q_ptr;
  54. public:
  55. ctkDICOMDatabasePrivate(ctkDICOMDatabase&);
  56. ~ctkDICOMDatabasePrivate();
  57. void init(QString databaseFile);
  58. bool executeScript(const QString script);
  59. QString DatabaseFileName;
  60. QString LastError;
  61. QSqlDatabase Database;
  62. };
  63. //------------------------------------------------------------------------------
  64. // ctkDICOMDatabasePrivate methods
  65. //------------------------------------------------------------------------------
  66. ctkDICOMDatabasePrivate::ctkDICOMDatabasePrivate(ctkDICOMDatabase& o): q_ptr(&o)
  67. {
  68. }
  69. //------------------------------------------------------------------------------
  70. void ctkDICOMDatabasePrivate::init(QString databaseFilename)
  71. {
  72. Q_Q(ctkDICOMDatabase);
  73. q->openDatabase(databaseFilename);
  74. }
  75. //------------------------------------------------------------------------------
  76. ctkDICOMDatabasePrivate::~ctkDICOMDatabasePrivate()
  77. {
  78. }
  79. //------------------------------------------------------------------------------
  80. void ctkDICOMDatabase::openDatabase(const QString databaseFile, const QString& connectionName )
  81. {
  82. Q_D(ctkDICOMDatabase);
  83. d->DatabaseFileName = databaseFile;
  84. d->Database = QSqlDatabase::addDatabase("QSQLITE",connectionName);
  85. d->Database.setDatabaseName(databaseFile);
  86. if ( ! (d->Database.open()) )
  87. {
  88. d->LastError = d->Database.lastError().text();
  89. throw std::runtime_error(qPrintable(d->LastError));
  90. }
  91. if ( d->Database.tables().empty() )
  92. {
  93. initializeDatabase();
  94. }
  95. if (databaseFile != ":memory")
  96. {
  97. QFileSystemWatcher* watcher = new QFileSystemWatcher(QStringList(databaseFile),this);
  98. connect(watcher, SIGNAL( fileChanged(const QString&)),this, SIGNAL ( databaseChanged() ) );
  99. }
  100. }
  101. //------------------------------------------------------------------------------
  102. // ctkDICOMDatabase methods
  103. //------------------------------------------------------------------------------
  104. ctkDICOMDatabase::ctkDICOMDatabase(QString databaseFile)
  105. : d_ptr(new ctkDICOMDatabasePrivate(*this))
  106. {
  107. Q_D(ctkDICOMDatabase);
  108. d->init(databaseFile);
  109. }
  110. ctkDICOMDatabase::ctkDICOMDatabase()
  111. : d_ptr(new ctkDICOMDatabasePrivate(*this))
  112. {
  113. }
  114. //------------------------------------------------------------------------------
  115. ctkDICOMDatabase::~ctkDICOMDatabase()
  116. {
  117. }
  118. //----------------------------------------------------------------------------
  119. //------------------------------------------------------------------------------
  120. const QString ctkDICOMDatabase::lastError() const {
  121. Q_D(const ctkDICOMDatabase);
  122. return d->LastError;
  123. }
  124. //------------------------------------------------------------------------------
  125. const QString ctkDICOMDatabase::databaseFilename() const {
  126. Q_D(const ctkDICOMDatabase);
  127. return d->DatabaseFileName;
  128. }
  129. //------------------------------------------------------------------------------
  130. const QString ctkDICOMDatabase::databaseDirectory() const {
  131. QString databaseFile = databaseFilename();
  132. if (!QFileInfo(databaseFile).isAbsolute())
  133. {
  134. databaseFile.prepend(QDir::currentPath() + "/");
  135. }
  136. return QFileInfo ( databaseFile ).absoluteDir().path();
  137. }
  138. //------------------------------------------------------------------------------
  139. const QSqlDatabase& ctkDICOMDatabase::database() const {
  140. Q_D(const ctkDICOMDatabase);
  141. return d->Database;
  142. }
  143. //------------------------------------------------------------------------------
  144. bool ctkDICOMDatabasePrivate::executeScript(const QString script) {
  145. QFile scriptFile(script);
  146. scriptFile.open(QIODevice::ReadOnly);
  147. if ( !scriptFile.isOpen() )
  148. {
  149. qDebug() << "Script file " << script << " could not be opened!\n";
  150. return false;
  151. }
  152. QString sqlCommands( QTextStream(&scriptFile).readAll() );
  153. sqlCommands.replace( '\n', ' ' );
  154. sqlCommands.replace("; ", ";\n");
  155. QStringList sqlCommandsLines = sqlCommands.split('\n');
  156. QSqlQuery query(Database);
  157. for (QStringList::iterator it = sqlCommandsLines.begin(); it != sqlCommandsLines.end()-1; ++it)
  158. {
  159. if (! (*it).startsWith("--") )
  160. {
  161. qDebug() << *it << "\n";
  162. query.exec(*it);
  163. if (query.lastError().type())
  164. {
  165. qDebug() << "There was an error during execution of the statement: " << (*it);
  166. qDebug() << "Error message: " << query.lastError().text();
  167. return false;
  168. }
  169. }
  170. }
  171. return true;
  172. }
  173. //------------------------------------------------------------------------------
  174. bool ctkDICOMDatabase::initializeDatabase(const char* sqlFileName)
  175. {
  176. Q_D(ctkDICOMDatabase);
  177. return d->executeScript(sqlFileName);
  178. }
  179. //------------------------------------------------------------------------------
  180. void ctkDICOMDatabase::closeDatabase()
  181. {
  182. Q_D(ctkDICOMDatabase);
  183. d->Database.close();
  184. }
  185. //------------------------------------------------------------------------------
  186. /*
  187. void ctkDICOMDatabase::insert ( DcmDataset *dataset ) {
  188. this->insert ( dataset, QString() );
  189. }
  190. */
  191. //------------------------------------------------------------------------------
  192. void ctkDICOMDatabase::insert ( DcmDataset *dataset, bool storeFile, bool createThumbnail )
  193. {
  194. Q_D(ctkDICOMDatabase);
  195. if (!dataset)
  196. {
  197. return;
  198. }
  199. // Check to see if the file has already been loaded
  200. OFString sopInstanceUID ;
  201. dataset->findAndGetOFString(DCM_SOPInstanceUID, sopInstanceUID);
  202. QSqlQuery fileExists ( d->Database );
  203. fileExists.prepare("SELECT InsertTimestamp,Filename FROM Images WHERE SOPInstanceUID == ?");
  204. fileExists.bindValue(0,QString(sopInstanceUID.c_str()));
  205. fileExists.exec();
  206. if ( fileExists.next() && QFileInfo(fileExists.value(1).toString()).lastModified() < QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate) )
  207. {
  208. logger.debug ( "File " + fileExists.value(1).toString() + " already added" );
  209. return;
  210. }
  211. OFString patientsName, patientID, patientsBirthDate, patientsBirthTime, patientsSex,
  212. patientComments, patientsAge;
  213. OFString studyInstanceUID, studyID, studyDate, studyTime,
  214. accessionNumber, modalitiesInStudy, institutionName, performingPhysiciansName, referringPhysician, studyDescription;
  215. OFString seriesInstanceUID, seriesDate, seriesTime,
  216. seriesDescription, bodyPartExamined, frameOfReferenceUID,
  217. contrastAgent, scanningSequence;
  218. OFString instanceNumber;
  219. Sint32 seriesNumber = 0, acquisitionNumber = 0, echoNumber = 0, temporalPosition = 0;
  220. //If the following fields can not be evaluated, cancel evaluation of the DICOM file
  221. dataset->findAndGetOFString(DCM_PatientsName, patientsName);
  222. dataset->findAndGetOFString(DCM_StudyInstanceUID, studyInstanceUID);
  223. dataset->findAndGetOFString(DCM_SeriesInstanceUID, seriesInstanceUID);
  224. dataset->findAndGetOFString(DCM_PatientID, patientID);
  225. dataset->findAndGetOFString(DCM_PatientsBirthDate, patientsBirthDate);
  226. dataset->findAndGetOFString(DCM_PatientsBirthTime, patientsBirthTime);
  227. dataset->findAndGetOFString(DCM_PatientsSex, patientsSex);
  228. dataset->findAndGetOFString(DCM_PatientsAge, patientsAge);
  229. dataset->findAndGetOFString(DCM_PatientComments, patientComments);
  230. dataset->findAndGetOFString(DCM_StudyID, studyID);
  231. dataset->findAndGetOFString(DCM_StudyDate, studyDate);
  232. dataset->findAndGetOFString(DCM_StudyTime, studyTime);
  233. dataset->findAndGetOFString(DCM_AccessionNumber, accessionNumber);
  234. dataset->findAndGetOFString(DCM_ModalitiesInStudy, modalitiesInStudy);
  235. dataset->findAndGetOFString(DCM_InstitutionName, institutionName);
  236. dataset->findAndGetOFString(DCM_PerformingPhysiciansName, performingPhysiciansName);
  237. dataset->findAndGetOFString(DCM_ReferringPhysiciansName, referringPhysician);
  238. dataset->findAndGetOFString(DCM_StudyDescription, studyDescription);
  239. dataset->findAndGetOFString(DCM_SeriesDate, seriesDate);
  240. dataset->findAndGetOFString(DCM_SeriesTime, seriesTime);
  241. dataset->findAndGetOFString(DCM_SeriesDescription, seriesDescription);
  242. dataset->findAndGetOFString(DCM_BodyPartExamined, bodyPartExamined);
  243. dataset->findAndGetOFString(DCM_FrameOfReferenceUID, frameOfReferenceUID);
  244. dataset->findAndGetOFString(DCM_ContrastBolusAgent, contrastAgent);
  245. dataset->findAndGetOFString(DCM_ScanningSequence, scanningSequence);
  246. dataset->findAndGetSint32(DCM_SeriesNumber, seriesNumber);
  247. dataset->findAndGetSint32(DCM_AcquisitionNumber, acquisitionNumber);
  248. dataset->findAndGetSint32(DCM_EchoNumbers, echoNumber);
  249. dataset->findAndGetSint32(DCM_TemporalPositionIdentifier, temporalPosition);
  250. // store the file if the database is not in memomry
  251. QString filename;
  252. if ( storeFile && !this->isInMemory() )
  253. {
  254. DcmFileFormat* fileformat = new DcmFileFormat ( dataset );
  255. QString destinationDirectoryName = databaseDirectory() + "/dicom/";
  256. QDir destinationDir(destinationDirectoryName);
  257. QString studySeriesDirectory = QString(studyInstanceUID.c_str()) + "/" + seriesInstanceUID.c_str();
  258. destinationDir.mkpath(studySeriesDirectory);
  259. filename = databaseDirectory() + "/dicom/" + pathForDataset(dataset);
  260. logger.debug ( "Saving file: " + filename );
  261. OFCondition status = fileformat->saveFile ( filename.toAscii() );
  262. if ( !status.good() )
  263. {
  264. logger.error ( "Error saving file: " + filename + "\nError is " + status.text() );
  265. delete fileformat;
  266. return;
  267. }
  268. delete fileformat;
  269. }
  270. QSqlQuery check_exists_query(d->Database);
  271. //The patient UID is a unique number within the database, generated by the sqlite autoincrement
  272. int patientUID = -1;
  273. if ( patientID != "" && patientsName != "" )
  274. {
  275. //Check if patient is already present in the db
  276. check_exists_query.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" );
  277. check_exists_query.bindValue ( 0, QString ( patientID.c_str() ) );
  278. check_exists_query.bindValue ( 1, QString ( patientsName.c_str() ) );
  279. check_exists_query.exec();
  280. if (check_exists_query.next())
  281. {
  282. patientUID = check_exists_query.value(check_exists_query.record().indexOf("UID")).toInt();
  283. }
  284. else
  285. {
  286. // Insert it
  287. QSqlQuery statement ( d->Database );
  288. statement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" );
  289. statement.bindValue ( 0, QString ( patientsName.c_str() ) );
  290. statement.bindValue ( 1, QString ( patientID.c_str() ) );
  291. statement.bindValue ( 2, QString ( patientsBirthDate.c_str() ) );
  292. statement.bindValue ( 3, QString ( patientsBirthTime.c_str() ) );
  293. statement.bindValue ( 4, QString ( patientsSex.c_str() ) );
  294. statement.bindValue ( 5, QString ( patientsAge.c_str() ) );
  295. statement.bindValue ( 6, QString ( patientComments.c_str() ) );
  296. statement.exec ();
  297. patientUID = statement.lastInsertId().toInt();
  298. logger.debug ( "New patient inserted: " + QString().setNum ( patientUID ) );
  299. }
  300. }
  301. if ( studyInstanceUID != "" )
  302. {
  303. check_exists_query.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" );
  304. check_exists_query.bindValue ( 0, QString ( studyInstanceUID.c_str() ) );
  305. check_exists_query.exec();
  306. if(!check_exists_query.next())
  307. {
  308. QSqlQuery statement ( d->Database );
  309. statement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
  310. statement.bindValue ( 0, QString ( studyInstanceUID.c_str() ) );
  311. statement.bindValue ( 1, patientUID );
  312. statement.bindValue ( 2, QString ( studyID.c_str() ) );
  313. statement.bindValue ( 3, QDate::fromString ( studyDate.c_str(), "yyyyMMdd" ) );
  314. statement.bindValue ( 4, QString ( studyTime.c_str() ) );
  315. statement.bindValue ( 5, QString ( accessionNumber.c_str() ) );
  316. statement.bindValue ( 6, QString ( modalitiesInStudy.c_str() ) );
  317. statement.bindValue ( 7, QString ( institutionName.c_str() ) );
  318. statement.bindValue ( 8, QString ( referringPhysician.c_str() ) );
  319. statement.bindValue ( 9, QString ( performingPhysiciansName.c_str() ) );
  320. statement.bindValue ( 10, QString ( studyDescription.c_str() ) );
  321. if ( !statement.exec() )
  322. {
  323. logger.error ( "Error executing statament: " + statement.lastQuery() + " Error: " + statement.lastError().text() );
  324. }
  325. }
  326. }
  327. if ( seriesInstanceUID != "" )
  328. {
  329. check_exists_query.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" );
  330. check_exists_query.bindValue ( 0, QString ( seriesInstanceUID.c_str() ) );
  331. logger.warn ( "Statement: " + check_exists_query.lastQuery() );
  332. check_exists_query.exec();
  333. if(!check_exists_query.next())
  334. {
  335. QSqlQuery statement ( d->Database );
  336. statement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
  337. statement.bindValue ( 0, QString ( seriesInstanceUID.c_str() ) );
  338. statement.bindValue ( 1, QString ( studyInstanceUID.c_str() ) );
  339. statement.bindValue ( 2, static_cast<int>(seriesNumber) );
  340. statement.bindValue ( 3, QString ( seriesDate.c_str() ) );
  341. statement.bindValue ( 4, QDate::fromString ( seriesTime.c_str(), "yyyyMMdd" ) );
  342. statement.bindValue ( 5, QString ( seriesDescription.c_str() ) );
  343. statement.bindValue ( 6, QString ( bodyPartExamined.c_str() ) );
  344. statement.bindValue ( 7, QString ( frameOfReferenceUID.c_str() ) );
  345. statement.bindValue ( 8, static_cast<int>(acquisitionNumber) );
  346. statement.bindValue ( 9, QString ( contrastAgent.c_str() ) );
  347. statement.bindValue ( 10, QString ( scanningSequence.c_str() ) );
  348. statement.bindValue ( 11, static_cast<int>(echoNumber) );
  349. statement.bindValue ( 12, static_cast<int>(temporalPosition) );
  350. if ( !statement.exec() )
  351. {
  352. logger.error ( "Error executing statament: " + statement.lastQuery() + " Error: " + statement.lastError().text() );
  353. }
  354. }
  355. }
  356. if ( !filename.isEmpty() )
  357. {
  358. check_exists_query.prepare ( "SELECT * FROM Images WHERE Filename = ?" );
  359. check_exists_query.bindValue ( 0, filename );
  360. check_exists_query.exec();
  361. if(!check_exists_query.next())
  362. {
  363. QSqlQuery statement ( d->Database );
  364. statement.prepare ( "INSERT INTO Images ( 'SOPInstanceUID', 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ?, ? )" );
  365. statement.bindValue ( 0, QString ( sopInstanceUID.c_str() ) );
  366. statement.bindValue ( 1, filename );
  367. statement.bindValue ( 2, QString ( seriesInstanceUID.c_str() ) );
  368. statement.bindValue ( 3, QDateTime::currentDateTime() );
  369. statement.exec();
  370. }
  371. }
  372. if (createThumbnail)
  373. {
  374. QString thumbnailBaseDir = databaseDirectory() + "/thumbs/";
  375. QString thumbnailFilename = thumbnailBaseDir + "/" + pathForDataset(dataset) + ".png";
  376. QFileInfo thumbnailInfo(thumbnailFilename);
  377. if ( ! ( thumbnailInfo.exists() && thumbnailInfo.lastModified() < QFileInfo(filename).lastModified() ) )
  378. {
  379. QString studySeriesDirectory = QString(studyInstanceUID.c_str()) + "/" + seriesInstanceUID.c_str();
  380. QDir(thumbnailBaseDir).mkpath(studySeriesDirectory);
  381. // TODO: reuse dataset
  382. DicomImage dcmtkImage(filename.toAscii());
  383. ctkDICOMImage ctkImage(&dcmtkImage);
  384. QImage image( ctkImage.frame(0) );
  385. image.scaled(128,128,Qt::KeepAspectRatio).save(thumbnailFilename,"PNG");
  386. }
  387. }
  388. if (d->DatabaseFileName == ":memory:")
  389. {
  390. emit databaseChanged();
  391. }
  392. }
  393. bool ctkDICOMDatabase::isInMemory() const
  394. {
  395. Q_D(const ctkDICOMDatabase);
  396. return d->DatabaseFileName == ":memory:";
  397. }
  398. QString ctkDICOMDatabase::pathForDataset( DcmDataset *dataset)
  399. {
  400. if (!dataset)
  401. {
  402. return QString();
  403. }
  404. OFString studyInstanceUID, seriesInstanceUID, sopInstanceUID;
  405. dataset->findAndGetOFString(DCM_StudyInstanceUID, studyInstanceUID);
  406. dataset->findAndGetOFString(DCM_SeriesInstanceUID, seriesInstanceUID);
  407. dataset->findAndGetOFString(DCM_SOPInstanceUID, sopInstanceUID);
  408. return QString(studyInstanceUID.c_str()) + "/" + seriesInstanceUID.c_str() + "/" + sopInstanceUID.c_str();
  409. }