-
Notifications
You must be signed in to change notification settings - Fork 50
/
main.cpp
2142 lines (1776 loc) · 85.7 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <libxml/parser.h>
#include <libxml/xmlschemas.h>
#include <libxml/xmlmemory.h>
#include <libxml/debugXML.h>
#include <libxml/HTMLtree.h>
#include <libxml/xmlIO.h>
#include <libxml/xinclude.h>
#include <libxml/catalog.h>
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include <boost/make_shared.hpp>
#include "siemensraw.h"
#include "base64.h"
#include "XNode.h"
#include "ConverterXml.h"
#include "ismrmrd/ismrmrd.h"
#include "ismrmrd/dataset.h"
#include "ismrmrd/version.h"
#include "ismrmrd/xml.h"
#include "converter_version.h"
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <boost/filesystem.hpp>
#include <boost/locale/encoding_utf.hpp>
using boost::locale::conv::utf_to_utf;
#include <iomanip>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <streambuf>
#include <utility>
#include <typeinfo>
const size_t MYSTERY_BYTES_EXPECTED = 160;
// defined in generated defaults.cpp
extern void initializeEmbeddedFiles(void);
extern std::map<std::string, std::string> global_embedded_files;
struct ChannelHeaderAndData
{
sChannelHeader header;
std::vector<complex_float_t> data;
};
struct MeasurementHeaderBuffer
{
std::string name;
std::string buf;
};
void calc_vds(double slewmax,double gradmax,double Tgsample,double Tdsample,int Ninterleaves,
double* fov, int numfov,double krmax,
int ngmax, double** xgrad,double** ygrad,int* numgrad);
void calc_traj(double* xgrad, double* ygrad, int ngrad, int Nints, double Tgsamp, double krmax,
double** x_trajectory, double** y_trajectory,
double** weights);
std::vector<ISMRMRD::Waveform> readSyncdata(std::ifstream &siemens_dat, bool VBFILE, unsigned long acquisitions,
uint32_t dma_length, sScanHeader scanheader, ISMRMRD::IsmrmrdHeader &header,
long scan_counter, bool skip_syncdata);
std::string select_file(const std::string &, const std::string &, bool, unsigned int);
std::string get_file_content(const std::string &file);
std::vector<MrParcRaidFileEntry>
readParcFileEntries(std::ifstream &siemens_dat, const MrParcRaidFileHeader &ParcRaidHead, bool VBFILE);
std::vector<MeasurementHeaderBuffer> readMeasurementHeaderBuffers(std::ifstream &siemens_dat, uint32_t num_buffers);
std::string readXmlConfig(bool debug_xml, const std::string ¶mmap_file_content, uint32_t num_buffers,
std::vector<MeasurementHeaderBuffer> &buffers, std::vector<std::string> &wip_double,
Trajectory &trajectory, long &dwell_time_0, long &max_channels, long &radial_views, long* global_table_pos,
std::string &baseLine_string, std::string &protocol_name, std::string& software_version);
std::string parseXML(bool debug_xml, const std::string ¶mmap_xsl_content, std::string &schema_file_name_content,
const std::string xml_config);
ISMRMRD::NDArray<float>
getTrajectory(const std::vector<std::string> &wip_double, const Trajectory &trajectory, long dwell_time_0,
long radial_views);
ISMRMRD::Acquisition
getAcquisition(bool flash_pat_ref_scan, const Trajectory &trajectory, long dwell_time_0, long* global_table_pos, long max_channels,
bool isAdjustCoilSens, bool isAdjQuietCoilSens, bool isVB, bool isNX, bool attachTrajectory, ISMRMRD::NDArray<float> &traj,
const sScanHeader &scanhead, const std::vector<ChannelHeaderAndData> &channels);
void readScanHeader(std::ifstream &siemens_dat, bool VBFILE, sMDH &mdh, sScanHeader &scanhead);
std::vector<ChannelHeaderAndData>
readChannelHeaders(std::ifstream &siemens_dat, bool VBFILE, const sScanHeader &scanhead);
int xml_file_is_valid(std::string &xml, std::string &schema_file) {
xmlDocPtr doc;
//parse an XML in-memory block and build a tree.
doc = xmlParseMemory(xml.c_str(), xml.size());
xmlDocPtr schema_doc;
//parse an XML in-memory block and build a tree.
schema_doc = xmlParseMemory(schema_file.c_str(), schema_file.size());
//Create an XML Schemas parse context for that document. NB. The document may be modified during the parsing process.
xmlSchemaParserCtxtPtr parser_ctxt = xmlSchemaNewDocParserCtxt(schema_doc);
if (parser_ctxt == NULL) {
/* unable to create a parser context for the schema */
xmlFreeDoc(schema_doc);
return -2;
}
//parse a schema definition resource and build an internal XML Shema structure which can be used to validate instances.
xmlSchemaPtr schema = xmlSchemaParse(parser_ctxt);
if (schema == NULL) {
/* the schema itself is not valid */
xmlSchemaFreeParserCtxt(parser_ctxt);
xmlFreeDoc(schema_doc);
return -3;
}
//Create an XML Schemas validation context based on the given schema.
xmlSchemaValidCtxtPtr valid_ctxt = xmlSchemaNewValidCtxt(schema);
if (valid_ctxt == NULL) {
/* unable to create a validation context for the schema */
xmlSchemaFree(schema);
xmlSchemaFreeParserCtxt(parser_ctxt);
xmlFreeDoc(schema_doc);
xmlFreeDoc(doc);
return -4;
}
//Validate a document tree in memory. Takes a schema validation context and a parsed document tree
int is_valid = (xmlSchemaValidateDoc(valid_ctxt, doc) == 0);
xmlSchemaFreeValidCtxt(valid_ctxt);
xmlSchemaFree(schema);
xmlSchemaFreeParserCtxt(parser_ctxt);
xmlFreeDoc(schema_doc);
xmlFreeDoc(doc);
/* force the return value to be non-negative on success */
return is_valid ? 1 : 0;
}
std::string get_date_time_string() {
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
std::stringstream str;
str << timeinfo->tm_year + 1900 << "-"
<< std::setw(2) << std::setfill('0') << timeinfo->tm_mon + 1
<< "-"
<< std::setw(2) << std::setfill('0') << timeinfo->tm_mday
<< " "
<< std::setw(2) << std::setfill('0') << timeinfo->tm_hour
<< ":"
<< std::setw(2) << std::setfill('0') << timeinfo->tm_min
<< ":"
<< std::setw(2) << std::setfill('0') << timeinfo->tm_sec;
std::string ret = str.str();
return ret;
}
bool is_number(const std::string &s) {
bool ret = true;
for (unsigned int i = 0; i < s.size(); i++) {
if (!std::isdigit(s.c_str()[i])) {
ret = false;
break;
}
}
return ret;
}
std::string get_time_string(size_t hours, size_t mins, size_t secs) {
std::stringstream str;
str << std::setw(2) << std::setfill('0') << hours << ":"
<< std::setw(2) << std::setfill('0') << mins << ":"
<< std::setw(2) << std::setfill('0') << secs;
std::string ret = str.str();
return ret;
}
bool fill_ismrmrd_header(ISMRMRD::IsmrmrdHeader &h, const std::string &study_date, const std::string &study_time) {
try {
// ---------------------------------
// fill more info into the ismrmrd header
// ---------------------------------
// study
bool study_date_needed = false;
bool study_time_needed = false;
if (h.studyInformation) {
if (!h.studyInformation->studyDate) {
study_date_needed = true;
}
if (!h.studyInformation->studyTime) {
study_time_needed = true;
}
} else {
study_date_needed = true;
study_time_needed = true;
}
if (study_date_needed || study_time_needed) {
ISMRMRD::StudyInformation study;
if(h.studyInformation)
study = *h.studyInformation;
if(study_date_needed && !study_date.empty())
{
study.studyDate.set(study_date);
std::cout << "Study date: " << study_date << std::endl;
}
if (study_time_needed && !study_time.empty()) {
study.studyTime.set(study_time);
std::cout << "Study time: " << study_time << std::endl;
}
h.studyInformation.set(study);
}
// ---------------------------------
// go back to string
// ---------------------------------
}
catch (...) {
return false;
}
return true;
}
void append_buffers_to_xml_header(std::vector<MeasurementHeaderBuffer> &buffers, size_t num_buffers,
ISMRMRD::IsmrmrdHeader &header) {
for (unsigned int b = 0; b < num_buffers; b++) {
ISMRMRD::UserParameterString p;
p.value = base64_encode(reinterpret_cast<const unsigned char *>(buffers[b].buf.c_str()), buffers[b].buf.size());
p.name = std::string("SiemensBuffer_") + buffers[b].name;
if (!header.userParameters.is_present()) {
ISMRMRD::UserParameters up;
header.userParameters = up;
}
header.userParameters().userParameterBase64.push_back(p);
}
}
std::string ProcessParameterMap(const XProtocol::XNode &node, const char *mapfile) {
TiXmlDocument out_doc;
TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "", "");
out_doc.LinkEndChild(decl);
ConverterXMLNode out_n(&out_doc);
//Input document
TiXmlDocument doc;
doc.Parse(mapfile);
TiXmlHandle docHandle(&doc);
TiXmlElement *parameters = docHandle.FirstChildElement("siemens").FirstChildElement("parameters").ToElement();
if (parameters) {
TiXmlNode *p = 0;
while ((p = parameters->IterateChildren("p", p))) {
TiXmlHandle ph(p);
TiXmlText *s = ph.FirstChildElement("s").FirstChild().ToText();
TiXmlText *d = ph.FirstChildElement("d").FirstChild().ToText();
if (s && d) {
std::string source = s->Value();
std::string destination = d->Value();
std::vector<std::string> split_path;
boost::split(split_path, source, boost::is_any_of("."), boost::token_compress_on);
if (is_number(split_path[0])) {
std::cout << "First element of path (" << source << ") cannot be numeric" << std::endl;
continue;
}
std::string search_path = split_path[0];
for (unsigned int i = 1; i < split_path.size() - 1; i++) {
/*
if (is_number(split_path[i]) && (i != split_path.size())) {
std::cout << "Numeric index not supported inside path for source = " << source << std::endl;
continue;
}*/
search_path += std::string(".") + split_path[i];
}
int index = -1;
if (is_number(split_path[split_path.size() - 1])) {
index = atoi(split_path[split_path.size() - 1].c_str());
} else {
search_path += std::string(".") + split_path[split_path.size() - 1];
}
const XProtocol::XNode *n = boost::apply_visitor(XProtocol::getChildNodeByName(search_path), node);
std::vector<std::string> parameters;
if (n) {
parameters = boost::apply_visitor(XProtocol::getStringValueArray(), *n);
} else {
std::cout << "Search path: " << search_path << " not found." << std::endl;
}
if (index >= 0) {
if (parameters.size() > index) {
out_n.add(destination, parameters[index]);
} else {
std::cout << "Parameter index (" << index << ") not valid for search path " << search_path
<< std::endl;
continue;
}
} else {
out_n.add(destination, parameters);
}
} else {
std::cout << "Malformed parameter map" << std::endl;
}
}
} else {
std::cout << "Malformed parameter map (parameters section not found)" << std::endl;
return std::string("");
}
return XmlToString(out_doc);
}
/// compute noise dwell time in us for dependency and built-in noise in VD/VB lines
double compute_noise_sample_in_us(size_t num_of_noise_samples_this_acq, bool isAdjustCoilSens, bool isAdjQuietCoilSens,
bool isVB, bool isNX)
{
if(isNX)
{
return 5.0;
}
else if (isAdjustCoilSens)
{
return 5.0;
}
else if (isAdjQuietCoilSens)
{
return 4.0;
}
else if (isVB)
{
return (1e6 / num_of_noise_samples_this_acq / 130.0);
}
else
{
return (((long) (76800.0 / num_of_noise_samples_this_acq)) / 10.0);
}
return 5.0;
}
std::string load_embedded(std::string name) {
std::string contents;
std::map<std::string, std::string>::iterator it = global_embedded_files.find(name);
if (it != global_embedded_files.end()) {
std::string encoded = it->second;
contents = base64_decode(encoded);
} else {
std::stringstream sstream;
sstream << "ERROR: File " << name << " is not embedded!";
throw std::runtime_error(sstream.str());
}
return contents;
}
std::string load_file(std::string file_name) {
// Read in file contents
std::string contents;
std::ifstream f(file_name.c_str());
if (!f) {
std::stringstream sstream;
sstream << "file: " << file_name << " does not exist.";
throw std::runtime_error(sstream.str());
}
std::string str_f((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
contents = str_f;
return contents;
}
std::string ws2s(const std::wstring &wstr) {
std::string ret(wstr.size(), '0');
for (size_t i = 0; i < wstr.size(); i++) {
wchar_t c = wstr[i];
if (((uint32_t) c) > 127) {
ret[i] = 'X';
} else {
ret[i] = static_cast<char>(c);
}
}
return ret;
}
int main(int argc, char* argv[]) {
std::string siemens_dat_filename;
int measurement_number;
std::string parammap_file;
std::string parammap_xsl;
std::string usermap_file;
std::string usermap_xsl;
std::string schema_file_name;
std::string ismrmrd_group;
std::string date_time = get_date_time_string();
std::string study_date_user_supplied;
bool debug_xml = false;
bool flash_pat_ref_scan = false;
bool header_only = false;
bool append_buffers = false;
bool all_measurements = false;
bool multi_meas_file = false;
bool skip_syncdata = false;
bool attachTrajectory = false;
bool list = false;
std::string to_extract;
std::string xslt_home;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Produce HELP message")
("version,v", "Prints converter version and ISMRMRD version")
("file,f", po::value<std::string>(&siemens_dat_filename), "<SIEMENS dat file>")
("measNum,z", po::value<int>(&measurement_number)->default_value(1), "<Measurement number (with negative indexing)>")
("allMeas,Z", po::value<bool>(&all_measurements)->implicit_value(true), "<All measurements flag>")
("multiMeasFile,M", po::value<bool>(&multi_meas_file)->implicit_value(true), "<Multiple measurements in single output file flag>")
("skipSyncData", po::value<bool>(&skip_syncdata)->implicit_value(true), "<Skip syncdata (PMU) conversion>")
("attachTrajectory", po::value<bool>(&attachTrajectory)->implicit_value(true), "<Attach trajectories using vds design>")
("pMap,m", po::value<std::string>(¶mmap_file), "<Parameter map XML file>")
("pMapStyle,x", po::value<std::string>(¶mmap_xsl), "<Parameter stylesheet XSL file>")
("user-map", po::value<std::string>(&usermap_file), "<Provide a parameter map XML file>")
("user-stylesheet", po::value<std::string>(&usermap_xsl), "<Provide a parameter stylesheet XSL file>")
("output,o", po::value<std::string>(), "<ISMRMRD output file (defaults to the input file name, with .mrd extension)>")
("outputGroup,g", po::value<std::string>(&ismrmrd_group)->default_value("dataset"),
"<ISMRMRD output group>")
("list,l", po::value<bool>(&list)->implicit_value(true), "<List embedded files>")
("extract,e", po::value<std::string>(&to_extract), "<Extract embedded file>")
("debug,X", po::value<bool>(&debug_xml)->implicit_value(true), "<Debug XML flag>")
("flashPatRef,F", po::value<bool>(&flash_pat_ref_scan)->implicit_value(true), "<FLASH PAT REF flag>")
("headerOnly,H", po::value<bool>(&header_only)->implicit_value(true),
"<HEADER ONLY flag (create xml header only)>")
("bufferAppend,B", po::value<bool>(&append_buffers)->implicit_value(true),
"<Append Siemens protocol buffers (bas64) to user parameters>")
("studyDate", po::value<std::string>(&study_date_user_supplied),
"<User can supply study date, in the format of yyyy-mm-dd>");
po::options_description display_options("Allowed options");
display_options.add_options()
("help,h", "Produce HELP message")
("version,v", "Prints converter version and ISMRMRD version")
("file,f", "<SIEMENS dat file>")
("measNum,z", "<Measurement number>")
("allMeas,Z", "<All measurements flag>")
("multiMeasFile,M", "<Multiple measurements in single file flag>")
("skipSyncData", "<Skip syncdata (PMU) conversion>")
("attachTrajectory", "<Attach trajectories using vds design>")
("pMap,m", "<Parameter map XML>")
("pMapStyle,x", "<Parameter stylesheet XSL>")
("output,o", "<ISMRMRD output file>")
("outputGroup,g", "<ISMRMRD output group>")
("list,l", "<List embedded files>")
("extract,e", "<Extract embedded file>")
("debug,X", "<Debug XML flag>")
("flashPatRef,F", "<FLASH PAT REF flag>")
("headerOnly,H", "<HEADER ONLY flag (create xml header only)>")
("bufferAppend,B", "<Append protocol buffers>")
("studyDate", "<User can supply study date, in the format of yyyy-mm-dd>");
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << display_options << "\n";
return 0;
}
if (vm.count("version")) {
std::cout << "Converter version is: " << SIEMENS_TO_ISMRMRD_VERSION_MAJOR << "."
<< SIEMENS_TO_ISMRMRD_VERSION_MINOR << "." << SIEMENS_TO_ISMRMRD_VERSION_PATCH << "\n";
std::cout << "Built against ISMRMRD version: " << ISMRMRD_VERSION_MAJOR << "." << ISMRMRD_VERSION_MINOR
<< "." << ISMRMRD_VERSION_PATCH << "\n";
return 0;
}
}
catch (po::error& e) {
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << display_options << std::endl;
return -1;
}
if (!usermap_file.empty()) {
if (!parammap_file.empty()) throw std::runtime_error("Specifying both --user-map and -m is not allowed.");
std::cout << "WARNING: Specifying --user-map is deprecated; use -m instead." << std::endl;
parammap_file = usermap_file;
}
if (!usermap_xsl.empty()) {
if (!parammap_xsl.empty()) throw std::runtime_error("Specifying both --user-stylesheet and -x is not allowed.");
std::cout << "WARNING: Specifying --user-stylesheet is deprecated; use -x instead." << std::endl;
parammap_xsl = usermap_xsl;
}
// Add all embedded files to the global_embedded_files map
initializeEmbeddedFiles();
// List embedded parameter maps if requested
if (list) {
std::map<std::string, std::string>::iterator iter;
std::cout << "Embedded Files: " << std::endl;
for (iter = global_embedded_files.begin(); iter != global_embedded_files.end(); ++iter) {
if (iter->first != "ismrmrd.xsd") {
std::cout << " " << iter->first << std::endl;
}
}
return 0;
}
// Extract specified parameter map if requested
if (to_extract.length() > 0) {
std::string contents = load_embedded(to_extract);
std::ofstream outfile(to_extract.c_str());
outfile.write(contents.c_str(), contents.size());
std::cout << to_extract << " successfully extracted. " << std::endl;
return 0;
}
if (measurement_number == 0) {
std::cerr << "The measurement number must not be zero (count starts at 1)" << std::endl;
std::cerr << display_options << "\n";
return -1;
}
// Siemens file must be specified
if (siemens_dat_filename.length() == 0) {
std::cerr << "Missing Siemens DAT filename" << std::endl;
std::cerr << display_options << "\n";
return -1;
}
// Check if Siemens file is valid
std::ifstream infile(siemens_dat_filename.c_str());
if (!infile) {
std::cerr << "Provided Siemens file can not be open or does not exist." << std::endl;
std::cerr << display_options << "\n";
return -1;
}
std::cout << "Siemens file is: " << siemens_dat_filename << std::endl;
std::string ismrmrd_file;
if (!vm.count("output"))
{
boost::filesystem::path siemens_dat_path(siemens_dat_filename);
ismrmrd_file = siemens_dat_path.replace_extension(".mrd").string();
std::cout << "Output file not specified -- using " << ismrmrd_file << std::endl;
} else {
ismrmrd_file = vm["output"].as<std::string>();
}
std::string schema_file_name_content = load_embedded("ismrmrd.xsd");
std::ifstream siemens_dat(siemens_dat_filename.c_str(), std::ios::binary);
MrParcRaidFileHeader ParcRaidHead;
siemens_dat.read((char*)(&ParcRaidHead), sizeof(MrParcRaidFileHeader));
bool VBFILE = false;
if (ParcRaidHead.hdSize_ > 32) {
VBFILE = true;
//Rewind, we have no raid file header.
siemens_dat.seekg(0, std::ios::beg);
ParcRaidHead.hdSize_ = ParcRaidHead.count_;
ParcRaidHead.count_ = 1;
}
else if (ParcRaidHead.hdSize_ != 0) {
//This is a VB line data file
std::cerr << "Only VD line files with MrParcRaidFileHeader.hdSize_ == 0 (MR_PARC_RAID_ALLDATA) supported."
<< std::endl;
return -1;
}
if (measurement_number < 0) {
// negative indexing support ('-1' returns the last measurement)
if (-measurement_number > ParcRaidHead.count_)
{
std::cout << "The file you are trying to convert has only " << ParcRaidHead.count_ << " measurements."
<< std::endl;
std::cout << "Using negative indexing, you are trying to convert measurement number: " << measurement_number
<< std::endl;
return -1;
}
measurement_number = ParcRaidHead.count_ + measurement_number + 1;
}
// Loop through all measurements in multi-raid
std::string ismrmrd_file_orig = ismrmrd_file;
std::string ismrmrd_group_orig = ismrmrd_group;
unsigned int firstMeas, lastMeas;
if (all_measurements)
{
firstMeas = 1;
lastMeas = ParcRaidHead.count_;
}
else
{
firstMeas = measurement_number;
lastMeas = measurement_number;
}
for (unsigned int currentMeas = firstMeas; currentMeas <= lastMeas; currentMeas++) {
measurement_number = currentMeas;
if (all_measurements)
{
if (multi_meas_file)
{
// Add the measurement number as a suffix to the group name
ismrmrd_group = ismrmrd_group_orig;
ismrmrd_group.append("_");
ismrmrd_group.append(std::to_string(currentMeas));
}
else
{
// Add the measurement number as a suffix to the filename, excluding the file extension
std::vector<std::string> v;
boost::algorithm::split(v, ismrmrd_file_orig, boost::is_any_of("."));
if (v.size() > 1)
{
std::stringstream ss;
ss << v.at(v.size()-2) << "_" << currentMeas;
v.at(v.size()-2) = ss.str();
ismrmrd_file = boost::algorithm::join(v, ".");
}
else
{
// No file extension found
std::stringstream ss;
ss << ismrmrd_file_orig << "_" << currentMeas;
ismrmrd_file = ss.str();
}
}
// Reset file position
if (!VBFILE)
{
siemens_dat.seekg(sizeof(MrParcRaidFileHeader), std::ios::beg);
}
else
{
siemens_dat.seekg(0, std::ios::beg);
}
}
std::cout << "-----------------------------------------------------------------" << std::endl;
if (all_measurements)
{
std::cout << "Converting measurement " << currentMeas << "/" << lastMeas << " into file " << ismrmrd_file << " in group " << ismrmrd_group << std::endl;
}
else
{
std::cout << "Converting measurement " << currentMeas << " into file " << ismrmrd_file << " in group " << ismrmrd_group << std::endl;
}
std::cout << "-----------------------------------------------------------------" << std::endl;
if (!VBFILE && measurement_number > ParcRaidHead.count_) {
std::cout << "The file you are trying to convert has only " << ParcRaidHead.count_ << " measurements."
<< std::endl;
std::cout << "You are trying to convert measurement number: " << measurement_number << std::endl;
return -1;
}
//if it is a VB scan
if (VBFILE && measurement_number != 1) {
std::cout << "The file you are trying to convert is a VB file and it has only one measurement." << std::endl;
std::cout << "You tried to convert measurement number: " << measurement_number << std::endl;
return -1;
}
// Parameter map
std::string default_parammap;
if (VBFILE) {
default_parammap = "IsmrmrdParameterMap_Siemens_VB17.xml";
} else {
default_parammap = "IsmrmrdParameterMap_Siemens.xml";
}
std::string parammap_actual_file = select_file(parammap_file, default_parammap, all_measurements, currentMeas);
std::string parammap_file_content = get_file_content(parammap_actual_file);
std::cout << "Using parameter map: " << parammap_actual_file << std::endl;
std::cout << "This file contains " << ParcRaidHead.count_ << " measurement(s)." << std::endl;
std::vector<MrParcRaidFileEntry> ParcFileEntries = readParcFileEntries(siemens_dat, ParcRaidHead, VBFILE);
// find the beginning of the desired measurement
siemens_dat.seekg(ParcFileEntries[measurement_number - 1].off_, std::ios::beg);
uint32_t dma_length = 0, num_buffers = 0;
siemens_dat.read((char*)(&dma_length), sizeof(uint32_t));
siemens_dat.read((char*)(&num_buffers), sizeof(uint32_t));
//std::cout << "Measurement header DMA length: " << mhead.dma_length << std::endl;
auto buffers = readMeasurementHeaderBuffers(siemens_dat, num_buffers);
//We need to be on a 32 byte boundary after reading the buffers
long long int position_in_meas =
(long long int) (siemens_dat.tellg()) - ParcFileEntries[measurement_number - 1].off_;
if (position_in_meas % 32 != 0) {
siemens_dat.seekg(32 - (position_in_meas % 32), std::ios::cur);
}
// Measurement header done!
//Now we should have the measurement headers, so let's use the Meas header to create the XML parametersstd::string xml_config;
std::vector<std::string> wip_double;
Trajectory trajectory;
long dwell_time_0;
long max_channels;
long radial_views;
long* global_table_pos = new long[3];
std::string baseLineString;
std::string protocol_name;
std::string software_version;
std::string xml_config = readXmlConfig(debug_xml, parammap_file_content, num_buffers, buffers, wip_double,
trajectory, dwell_time_0,
max_channels, radial_views, global_table_pos, baseLineString, protocol_name, software_version);
// whether this scan is a adjustment scan
bool isAdjustCoilSens = false;
if (protocol_name == "AdjCoilSens") {
isAdjustCoilSens = true;
}
bool isAdjQuietCoilSens = false;
if (protocol_name == "AdjQuietCoilSens") {
isAdjQuietCoilSens = true;
}
// whether this scan is from VB line
bool isVB = false;
if ((baseLineString.find("VB17") != std::string::npos)
|| (baseLineString.find("VB15") != std::string::npos)
|| (baseLineString.find("VB13") != std::string::npos)
|| (baseLineString.find("VB11") != std::string::npos)) {
isVB = true;
}
std::cout << "Baseline: " << baseLineString << std::endl;
std::cout << "Software version: " << software_version << std::endl;
std::cout << "Protocol name: " << protocol_name << std::endl;
bool isNX = false;
if ((baseLineString.find("NXVA") != std::string::npos) || (software_version.find("syngo MR XA") != std::string::npos) )
{
isNX = true;
}
if (isNX)
{
int nxVersion = atoi(software_version.substr(11).c_str());
std::cout << "Detected Numaris/X version: " << nxVersion << std::endl;
if (nxVersion > 30)
{
skip_syncdata = true;
std::cout << "Disabling parsing of syncdata due to incompatibility!" << std::endl;
}
}
std::cout << "Dwell time: " << dwell_time_0 << std::endl;
if (debug_xml) {
std::ofstream o("xml_raw.xml");
o.write(xml_config.c_str(), xml_config.size());
}
// Parameter style-sheet
std::string default_parammap_xsl;
if (isNX) {
default_parammap_xsl = "IsmrmrdParameterMap_Siemens_NX.xsl";
} else {
default_parammap_xsl = "IsmrmrdParameterMap_Siemens.xsl";
}
std::string parammap_xsl_actual_file = select_file(parammap_xsl, default_parammap_xsl, all_measurements, currentMeas);
std::string parammap_xsl_content = get_file_content(parammap_xsl_actual_file);
std::cout << "Using parameter XSL: " << parammap_xsl_actual_file << std::endl;
ISMRMRD::IsmrmrdHeader header;
{
std::string config = parseXML(debug_xml, parammap_xsl_content, schema_file_name_content, xml_config);
ISMRMRD::deserialize(config.c_str(), header);
}
//Append buffers to xml_config if requested
if (append_buffers) {
append_buffers_to_xml_header(buffers, num_buffers, header);
}
// Free memory used for MeasurementHeaderBuffers
auto ismrmrd_dataset = boost::make_shared<ISMRMRD::Dataset>(ismrmrd_file.c_str(), ismrmrd_group.c_str(), true);
//If this is a spiral acquisition, we will calculate the trajectory and add it to the individual profilesISMRMRD::NDArray<float> traj;
// auto traj = getTrajectory(wip_double, trajectory, dwell_time_0, radial_views);
ISMRMRD::NDArray<float> traj;
uint32_t last_mask = 0;
unsigned long int acquisitions = 1;
unsigned long int sync_data_packets = 0;
sMDH mdh;//For VB line
bool first_call = true;
while (!(last_mask & 1) && //Last scan not encountered
(((ParcFileEntries[measurement_number - 1].off_ + ParcFileEntries[measurement_number - 1].len_) -
siemens_dat.tellg()) > sizeof(sScanHeader))) //not reached end of measurement without acqend
{
size_t position_in_meas = siemens_dat.tellg();
sScanHeader scanhead;
readScanHeader(siemens_dat, VBFILE, mdh, scanhead);
if (!siemens_dat) {
std::cerr << "Error reading header at acquisition " << acquisitions << "." << std::endl;
break;
}
uint32_t dma_length = scanhead.ulFlagsAndDMALength & MDH_DMA_LENGTH_MASK;
uint32_t mdh_enable_flags = scanhead.ulFlagsAndDMALength & MDH_ENABLE_FLAGS_MASK;
//Check if this is synch data, if so, it must be handled differently.
if (scanhead.aulEvalInfoMask[0] & (1 << 5)) {
uint32_t last_scan_counter = acquisitions - 1;
auto waveforms = readSyncdata(siemens_dat, VBFILE, acquisitions, dma_length, scanhead, header,
last_scan_counter, skip_syncdata);
for (auto &w : waveforms)
ismrmrd_dataset->appendWaveform(w);
sync_data_packets++;
continue;
}
if (first_call) {
uint32_t time_stamp = scanhead.ulTimeStamp;
// convert to acqusition date and time
double timeInSeconds = time_stamp * 2.5 / 1e3;
size_t hours = (size_t) (timeInSeconds / 3600);
size_t mins = (size_t) ((timeInSeconds - hours * 3600) / 60);
size_t secs = (size_t) (timeInSeconds - hours * 3600 - mins * 60);
hours = hours % 24;
mins = mins % 60;
std::string study_time = get_time_string(hours, mins, secs);
// if some of the ismrmrd header fields are not filled, here is a place to take some further actions
if (!fill_ismrmrd_header(header, study_date_user_supplied, study_time)) {
std::cerr << "Failed to further fill XML header" << std::endl;
}
std::stringstream sstream;
ISMRMRD::serialize(header, sstream);
xml_config = sstream.str();
if (xml_file_is_valid(xml_config, schema_file_name_content) <= 0) {
std::cerr << "Generated XML is not valid according to the ISMRMRD schema" << std::endl;
return -1;
}
if (debug_xml) {
std::ofstream o("processed.xml");
o.write(xml_config.c_str(), xml_config.size());
}
//This means we should only create XML header and exit
if (header_only) {
std::ofstream header_out_file(ismrmrd_file.c_str());
header_out_file << xml_config;
return -1;
}
// Create an ISMRMRD dataset
}
//This check only makes sense in VD line files.
if (!VBFILE && (scanhead.lMeasUID != ParcFileEntries[measurement_number - 1].measId_)) {
//Something must have gone terribly wrong. Bail out.
if (first_call) {
std::cerr << "Corrupted or retro-recon dataset detected (scanhead.lMeasUID != ParcFileEntries["
<< measurement_number - 1 << "].measId_)" << std::endl;
std::cerr << "Fix the scanhead.lMeasUID ... " << std::endl;
}
scanhead.lMeasUID = ParcFileEntries[measurement_number - 1].measId_;
}
if (first_call) first_call = false;
//Allocate data for channels
std::vector<ChannelHeaderAndData> channels = readChannelHeaders(siemens_dat, VBFILE, scanhead);
if (!siemens_dat) {
std::cerr << "Error reading data at acquisition " << acquisitions << "." << std::endl;
break;
}
acquisitions++;
last_mask = scanhead.aulEvalInfoMask[0];
if (scanhead.aulEvalInfoMask[0] & 1) {
std::cout << "Last scan reached..." << std::endl;
break;
}
ismrmrd_dataset->appendAcquisition(
getAcquisition(flash_pat_ref_scan, trajectory, dwell_time_0, global_table_pos, max_channels, isAdjustCoilSens,
isAdjQuietCoilSens, isVB, isNX, attachTrajectory, traj, scanhead, channels));
}//End of the while loop
delete [] global_table_pos;
if (!siemens_dat) {
std::cerr << "WARNING: Unexpected error. Please check the result." << std::endl;
return -1;
}
ismrmrd_dataset->writeHeader(xml_config);
//Mystery bytes. There seems to be 160 mystery bytes at the end of the data.
std::streamoff mystery_bytes = (std::streamoff) (ParcFileEntries[measurement_number - 1].off_ +
ParcFileEntries[measurement_number - 1].len_) -
siemens_dat.tellg();
if (mystery_bytes > 0) {
if (mystery_bytes != MYSTERY_BYTES_EXPECTED) {
// Something in not quite right
std::cerr << "WARNING: Unexpected number of mystery bytes detected: " << mystery_bytes << std::endl;
std::cerr << "ParcFileEntries[" << measurement_number - 1 << "].off_ = "
<< ParcFileEntries[measurement_number - 1].off_ << std::endl;
std::cerr << "ParcFileEntries[" << measurement_number - 1 << "].len_ = "
<< ParcFileEntries[measurement_number - 1].len_ << std::endl;
std::cerr << "siemens_dat.tellg() = " << siemens_dat.tellg() << std::endl;
std::cerr << "Please check the result." << std::endl;
} else {
// Read the mystery bytes
char mystery_data[MYSTERY_BYTES_EXPECTED];
siemens_dat.read(reinterpret_cast<char *>(&mystery_data), mystery_bytes);