forked from 3dem/relion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage.h
1626 lines (1460 loc) · 41.1 KB
/
image.h
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
/***************************************************************************
*
* Author: "Sjors H.W. Scheres", "Takanori Nakane"
* MRC Laboratory of Molecular Biology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This complete copyright notice must be included in any revised version of the
* source code. Additional authorship citations may be added, but existing
* author citations must be preserved.
***************************************************************************/
/***************************************************************************
*
* Authors: Sjors H.W. Scheres ([email protected])
*
* Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC
*
* Part of this module has been developed by Lorenzo Zampighi and Nelson Tang
* Dept. Physiology of the David Geffen School of Medicine
* Univ. of California, Los Angeles.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*
* All comments concerning this program package may be sent to the
* e-mail address '[email protected]'
***************************************************************************/
#ifndef IMAGE_H
#define IMAGE_H
#include <typeinfo>
#include <fcntl.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <tiffio.h>
#include "src/funcs.h"
#include "src/memory.h"
#include "src/filename.h"
#include "src/multidim_array.h"
#include "src/transformations.h"
#include "src/metadata_table.h"
#include "src/fftw.h"
/// @defgroup Images Images
//@{
/** Data type.
* This class defines the datatype of the data inside this image.
*/
typedef enum
{
Unknown_Type = 0, // Undefined data type
UChar = 1, // Unsigned character or byte type
SChar = 2, // Signed character (for CCP4)
UShort = 3, // Unsigned integer (2-byte)
Short = 4, // Signed integer (2-byte)
UInt = 5, // Unsigned integer (4-byte)
Int = 6, // Signed integer (4-byte)
Long = 7, // Signed integer (4 or 8 byte, depending on system)
Float = 8, // Floating point (4-byte)
Double = 9, // Double precision floating point (8-byte)
Boolean = 10, // Boolean (1-byte?)
UHalf = 11, // Signed 4-bit integer (SerialEM extension)
LastEntry = 15 // This must be the last entry
} DataType;
/** Write mode
* This class defines the writing behavior.
*/
typedef enum
{
WRITE_OVERWRITE, //forget about the old file and overwrite it
WRITE_APPEND, //append and object at the end of a stack, so far can not append stacks
WRITE_REPLACE, //replace a particular object by another
WRITE_READONLY //only can read the file
} WriteMode;
extern "C" {
typedef struct TiffInMemory
{
unsigned char *buf;
tsize_t size;
toff_t pos;
} TiffInMemory;
static tsize_t TiffInMemoryReadProc(thandle_t handle, tdata_t buf, tsize_t read_size)
{
TiffInMemory *tiff_handle = (TiffInMemory*)handle;
#ifdef TIFF_DEBUG
std::cout << "TiffInMemoryReadProc: read_size = " << read_size << " cur_pos = " << tiff_handle->pos << " buf_size = " << tiff_handle->size << std::endl;
#endif
if (tiff_handle->pos + read_size >= tiff_handle->size)
REPORT_ERROR("TiffInMemoryReadProc: seeking beyond the end of the buffer.");
memcpy(buf, tiff_handle->buf + tiff_handle->pos, read_size);
tiff_handle->pos += read_size;
return read_size;
}
static tsize_t TiffInMemoryWriteProc(thandle_t handle, tdata_t buf, tsize_t write_size)
{
#ifdef TIFF_DEBUG
REPORT_ERROR("TiffInMemoryWriteProc: Not implemented.");
#endif
return -1;
}
static toff_t TiffInMemorySeekProc(thandle_t handle, toff_t offset, int whence)
{
TiffInMemory *tiff_handle = (TiffInMemory*)handle;
#ifdef TIFF_DEBUG
std::cout << "TiffInMemorySeekProc: offset = " << offset << " cur_pos = " << tiff_handle->pos << " buf_size = " << tiff_handle->size << std::endl;
#endif
switch (whence)
{
case SEEK_SET:
tiff_handle->pos = 0;
break;
case SEEK_CUR:
tiff_handle->pos += offset;
break;
case SEEK_END:
REPORT_ERROR("TIFFInMemorySeekProc: SEEK_END is not supported.");
// break; // intentional to suppress compiler warnings.
}
if (tiff_handle->pos >= tiff_handle->size)
REPORT_ERROR("TIFFInMemorySeekProc: seeking beyond the end of the buffer.");
return 0;
}
static int TiffInMemoryCloseProc(thandle_t handle)
{
#ifdef TIFF_DEBUG
std::cout << "TiffInMemoryCloseProc" << std::endl;
#endif
return 0;
}
static toff_t TiffInMemorySizeProc(thandle_t handle)
{
#ifdef TIFF_DEBUG
std::cout << "TiffInMemorySizeProc" << std::endl;
#endif
return ((TiffInMemory*)handle)->size;
}
static int TiffInMemoryMapFileProc(thandle_t handle, tdata_t *base, toff_t *size)
{
TiffInMemory *tiff_handle = (TiffInMemory*)handle;
#ifdef TIFF_DEBUG
std::cout << "TiffInMemoryMapFileProc" << std::endl;
#endif
*base = tiff_handle->buf;
*size = tiff_handle->size;
return 1;
}
static void TiffInMemoryUnmapFileProc(thandle_t handle, tdata_t base, toff_t size)
{
#ifdef TIFF_DEBUG
std::cout << "TiffInMemoryUnmapFileProc" << std::endl;
#endif
return;
}
}
/** File handler class
* This struct is used to share the File handlers with Image Collection class
*/
class fImageHandler
{
public:
FILE* fimg; // Image File handler
FILE* fhed; // Image File header handler
TIFF* ftiff;
FileName ext_name; // Filename extension
bool exist; // Shows if the file exists
bool isTiff; // Shows if this is a TIFF file
/** Empty constructor
*/
fImageHandler()
{
fimg=NULL;
fhed=NULL;
ftiff=NULL;
ext_name="";
exist=false;
isTiff=false;
}
/** Destructor: closes file (if it still open)
*/
~fImageHandler()
{
closeFile();
}
void openFile(const FileName &name, int mode = WRITE_READONLY)
{
// Close any file that was left open in this handler
if (!(fimg ==NULL && fhed == NULL))
closeFile();
FileName fileName, headName = "";
// get the format, checking for possible format specifier before suffix
// getFileFormat("file.spi") will return "spi"
// getFileFormat("file.spi:mrc") will return "mrc"
// getFileFormat("file") will return ""
ext_name = name.getFileFormat();
long int dump;
name.decompose(dump, fileName);
// Subtract 1 to have numbering 0...N-1 instead of 1...N
if (dump > 0)
dump--;
// create the filename from a possible input format specifier (file.spi:mrc means "it's called .spi, but it's really a .mrc")
// file.spi:mrc -> file.spi
fileName = fileName.removeFileFormat();
size_t found = fileName.find_first_of("%");
if (found!=std::string::npos)
fileName = fileName.substr(0, found) ;
exist = exists(fileName);
std::string wmChar;
switch (mode)
{
case WRITE_READONLY:
if (!exist)
REPORT_ERROR((std::string) "Cannot read file " + fileName + " It does not exist" );
wmChar = "r";
break;
case WRITE_OVERWRITE:
wmChar = "w";
break;
case WRITE_APPEND:
if (exist)
wmChar = "r+";
else
wmChar = "w+";
break;
case WRITE_REPLACE:
wmChar = "r+";
break;
}
if (ext_name.contains("img") || ext_name.contains("hed"))
{
fileName = fileName.withoutExtension();
headName = fileName.addExtension("hed");
fileName = fileName.addExtension("img");
}
else if(ext_name=="")
{
ext_name="spi"; // SPIDER is default format if none is specified
fileName = fileName.addExtension(ext_name);
}
isTiff = ext_name.contains("tif");
if (isTiff && mode != WRITE_READONLY)
REPORT_ERROR((std::string)"TIFF is supported only for reading");
// Open image file
if ((!isTiff && ((fimg = fopen(fileName.c_str(), wmChar.c_str())) == NULL))
|| (isTiff && ((ftiff = TIFFOpen(fileName.c_str(), "r")) == NULL))
)
REPORT_ERROR((std::string)"Image::openFile cannot open: " + name);
if (headName != "")
{
if ((fhed = fopen(headName.c_str(), wmChar.c_str())) == NULL)
REPORT_ERROR((std::string)"Image::openFile cannot open: " + headName);
}
else
fhed = NULL;
}
void closeFile()
{
ext_name="";
exist=false;
// Check whether the file was closed already
if (fimg == NULL && fhed == NULL && ftiff == NULL)
return;
if (isTiff && ftiff != NULL) {
TIFFClose(ftiff);
ftiff = NULL;
}
if (!isTiff && fclose(fimg) != 0)
REPORT_ERROR((std::string)"Can not close image file ");
else
fimg = NULL;
if (fhed != NULL && fclose(fhed) != 0)
REPORT_ERROR((std::string)"Can not close header file ");
else
fhed = NULL;
}
};
/** Returns memory size of datatype
*/
unsigned long gettypesize(DataType type);
/** Convert datatype string to datatypr enun */
int datatypeString2Int(std::string s);
/** Swapping trigger.
* Threshold file z size above which bytes are swapped.
*/
#define SWAPTRIG 65535
/** Template class for images.
* The image class is the general image handling class.
*/
template<typename T>
class Image
{
public:
MultidimArray<T> data; // The image data array
MetaDataTable MDMainHeader; // metadata for the file
private:
FileName filename; // File name
FILE* fimg; // Image File handler
FILE* fhed; // Image File header handler
bool stayOpen; // To maintain the image file open after read/write
int dataflag; // Flag to force reading of the data
unsigned long i; // Current image number (may be > NSIZE)
unsigned long offset; // Data offset
int swap; // Perform byte swapping upon reading
long int replaceNsize; // Stack size in the replace case
bool _exists; // does target file exists?
// equal 0 is not exists or not a stack
bool mmapOn; // Mapping when loading from file
int mFd; // Handle the file in reading method and mmap
size_t mappedSize; // Size of the mapped file
public:
/** Empty constructor
*
* An empty image is created.
*
* @code
* Image<RFLOAT> I;
* @endcode
*/
Image()
{
mmapOn = false;
clear();
MDMainHeader.addObject();
}
/** Constructor with size
*
* A blank image (0.0 filled) is created with the given size. Pay attention
* to the dimension order: Y and then X.
*
* @code
* Image I(64,64);
* @endcode
*/
Image(long int Xdim, long int Ydim, long int Zdim=1, long int Ndim=1)
{
mmapOn = false;
clear();
data.resize(Ndim, Zdim, Ydim, Xdim);
MDMainHeader.addObject();
}
/** Clear.
* Initialize everything to 0
*/
void clear()
{
if (mmapOn)
{
munmap(data.data-offset,mappedSize);
close(mFd);
data.data = NULL;
}
else
data.clear();
dataflag = -1;
i = 0;
filename = "";
offset = 0;
swap = 0;
clearHeader();
replaceNsize=0;
mmapOn = false;
}
/** Clear the header of the image
*/
void clearHeader()
{
MDMainHeader.clear();
}
/** Destructor.
*/
~Image()
{
clear();
}
/** Specific read functions for different file formats
*/
#include "src/rwSPIDER.h"
#include "src/rwMRC.h"
#include "src/rwIMAGIC.h"
#include "src/rwTIFF.h"
/** Is this file an image
*
* Check whether a real-space image can be read
*
*/
bool isImage(const FileName &name)
{
return !read(name, false);
}
/** Rename the image
*/
void rename (const FileName &name)
{
filename = name;
}
/** General read function
* you can read a single image from a single image file
* or a single image file from an stack, in the second case
* the select slide may come in the image name or in the select_img parameter
* file name takes precedence over select_img
* If -1 is given the whole object is read
* The number before @ in the filename is 1-indexed, while select_img is 0-indexed.
*/
int read(const FileName &name, bool readdata=true, long int select_img=-1, bool mapData = false, bool is_2D = false)
{
if (name == "")
REPORT_ERROR("ERROR: trying to read image with empty file name!");
int err = 0;
fImageHandler hFile;
hFile.openFile(name);
err = _read(name, hFile, readdata, select_img, mapData, is_2D);
// the destructor of fImageHandler will close the file
// Negative errors are bad
return err;
}
/** Read function from a file that has already been opened
*
*/
int readFromOpenFile(const FileName &name, fImageHandler &hFile, long int select_img, bool is_2D = false)
{
int err = 0;
err = _read(name, hFile, true, select_img, false, is_2D);
// Reposition file pointer for a next read
rewind(fimg);
return err;
}
/** General write function
* select_img= which slice should I replace
* overwrite = 0, append slice
* overwrite = 1 overwrite slice
*
* NOTE:
* select_img has higher priority than the number before "@" in the name.
* select_img counts from 0, while the number before "@" in the name from 1!
*/
void write(FileName name="",
long int select_img=-1,
bool isStack=false,
int mode=WRITE_OVERWRITE)
{
const FileName &fname = (name == "") ? filename : name;
fImageHandler hFile;
hFile.openFile(name, mode);
_write(fname, hFile, select_img, isStack, mode);
// the destructor of fImageHandler will close the file
}
/** Cast a page of data from type dataType to type Tdest
* input pointer char *
*/
void castPage2T(char *page, T *ptrDest, DataType datatype, size_t pageSize )
{
switch (datatype)
{
case Unknown_Type:
REPORT_ERROR("ERROR: datatype is Unknown_Type");
case UChar:
{
if (typeid(T) == typeid(unsigned char))
memcpy(ptrDest, page, pageSize * sizeof(T));
else
{
unsigned char *ptr = (unsigned char *)page;
for (size_t i = 0; i < pageSize; i++)
ptrDest[i] = (T)ptr[i];
}
break;
}
case SChar:
{
if (typeid(T) == typeid(signed char))
{
memcpy(ptrDest, page, pageSize * sizeof(T));
}
else
{
signed char *ptr = (signed char *)page;
for (size_t i = 0; i < pageSize; i++)
ptrDest[i] = (T)ptr[i];
}
break;
}
case UShort:
{
if (typeid(T) == typeid(unsigned short))
{
memcpy(ptrDest, page, pageSize * sizeof(T));
}
else
{
unsigned short *ptr = (unsigned short *)page;
for(size_t i = 0; i < pageSize; i++)
ptrDest[i] = (T)ptr[i];
}
break;
}
case Short:
{
if (typeid(T) == typeid(short))
{
memcpy(ptrDest, page, pageSize * sizeof(T));
}
else
{
short *ptr = (short *)page;
for(size_t i = 0; i < pageSize; i++)
ptrDest[i] = (T)ptr[i];
}
break;
}
case UInt:
{
if (typeid(T) == typeid(unsigned int))
{
memcpy(ptrDest, page, pageSize * sizeof(T));
}
else
{
unsigned int *ptr = (unsigned int *)page;
for(size_t i = 0; i < pageSize; i++)
ptrDest[i] = (T)ptr[i];
}
break;
}
case Int:
{
if (typeid(T) == typeid(int))
{
memcpy(ptrDest, page, pageSize * sizeof(T));
}
else
{
int *ptr = (int *)page;
for(size_t i = 0; i < pageSize; i++)
ptrDest[i] = (T)ptr[i];
}
break;
}
case Long:
{
if (typeid(T) == typeid(long))
{
memcpy(ptrDest, page, pageSize * sizeof(T));
}
else
{
long *ptr = (long *)page;
for(size_t i = 0; i < pageSize; i++)
ptrDest[i] = (T)ptr[i];
}
break;
}
case Float:
{
if (typeid(T) == typeid(float))
{
memcpy(ptrDest, page, pageSize * sizeof(T));
}
else
{
float *ptr = (float *)page;
for(size_t i = 0; i < pageSize; i++)
ptrDest[i] = (T)ptr[i];
}
break;
}
case Double:
{
if (typeid(T) == typeid(RFLOAT))
{
memcpy(ptrDest, page, pageSize * sizeof(T));
}
else
{
RFLOAT *ptr = (RFLOAT *)page;
for(size_t i = 0; i < pageSize; i++)
ptrDest[i] = (T)ptr[i];
}
break;
}
case UHalf:
{
if (pageSize % 2 != 0) REPORT_ERROR("Logic error in castPage2T; for UHalf, pageSize must be even.");
for(size_t i = 0, ilim = pageSize / 2; i < ilim; i++)
{
// Here we are assuming the fill-order is LSB2MSB according to IMOD's
// iiProcessReadLine() in libiimod/mrcsec.c.
// The default fill-order in the TIFF specification is MSB2LSB
// but IMOD assumes LSB2MSB even for TIFF.
// See IMOD's iiTIFFCheck() in libiimod/iitif.c.
ptrDest[i * 2 ] = (T)(page[i] & 15); // 1111 = 1+2+4+8 = 15
ptrDest[i * 2 + 1] = (T)((page[i] >> 4) & 15);
}
break;
}
default:
{
std::cerr<<"Datatype= "<<datatype<<std::endl;
REPORT_ERROR(" ERROR: cannot cast datatype to T");
}
}
}
/** Cast page from T to datatype
* input pointer char *
*/
void castPage2Datatype(T *srcPtr, char *page, DataType datatype, size_t pageSize)
{
switch (datatype)
{
case Float:
{
if (typeid(T) == typeid(float))
{
memcpy(page, srcPtr, pageSize*sizeof(T));
}
else
{
float *ptr = (float *)page;
for (size_t i = 0; i < pageSize; i++)
ptr[i] = (float)srcPtr[i];
}
break;
}
case Double:
{
if (typeid(T) == typeid(RFLOAT))
{
memcpy(page, srcPtr, pageSize*sizeof(T));
}
else
{
RFLOAT *ptr = (RFLOAT *)page;
for (size_t i = 0; i < pageSize; i++)
ptr[i] = (RFLOAT)srcPtr[i];
}
break;
}
case Short:
{
if (typeid(T) == typeid(short))
{
memcpy(page, srcPtr, pageSize*sizeof(T));
}
else
{
short *ptr = (short *)page;
for (size_t i = 0; i < pageSize; i++)
ptr[i] = (short)srcPtr[i];
}
break;
}
case UShort:
{
if (typeid(T) == typeid(unsigned short))
{
memcpy(page, srcPtr, pageSize*sizeof(T));
}
else
{
unsigned short *ptr = (unsigned short *)page;
for (size_t i = 0; i < pageSize; i++)
ptr[i] = (unsigned short)srcPtr[i];
}
break;
}
case UChar:
{
if (typeid(T) == typeid(unsigned char))
{
memcpy(page, srcPtr, pageSize*sizeof(T));
}
else
{
unsigned char *ptr = (unsigned char *)page;
for (size_t i = 0; i < pageSize; i++)
ptr[i] = (unsigned char)srcPtr[i];
}
break;
}
default:
{
std::cerr << "outputDatatype= " << datatype << std::endl;
REPORT_ERROR(" ERROR: cannot cast T to outputDatatype");
}
}
}
/** Check file Datatype is same as T type to use mmap.
*/
bool checkMmapT(DataType datatype)
{
switch (datatype)
{
case Unknown_Type:
REPORT_ERROR("ERROR: datatype is Unknown_Type");
case UChar:
{
if (typeid(T) == typeid(unsigned char))
return 1;
else
return 0;
}
case SChar:
{
if (typeid(T) == typeid(signed char))
return 1;
else
return 0;
}
case UShort:
{
if (typeid(T) == typeid(unsigned short))
return 1;
else
return 0;
}
case Short:
{
if (typeid(T) == typeid(short))
return 1;
else
return 0;
}
case UInt:
{
if (typeid(T) == typeid(unsigned int))
return 1;
else
return 0;
}
case Int:
{
if (typeid(T) == typeid(int))
return 1;
else
return 0;
}
case Long:
{
if (typeid(T) == typeid(long))
return 1;
else
return 0;
}
case Float:
{
if (typeid(T) == typeid(float))
return 1;
else
return 0;
}
case Double:
{
if (typeid(T) == typeid(RFLOAT))
return 1;
else
return 0;
}
default:
{
std::cerr << "Datatype= " << datatype << std::endl;
REPORT_ERROR(" ERROR: cannot cast datatype to T");
}
}
// int * iTemp = (int*) map;
// ptrDest = reinterpret_cast<T*> (iTemp);
}
/** Write an entire page as datatype
*
* A page of datasize_n elements T is cast to datatype and written to fimg
* The memory for the casted page is allocated and freed internally.
*/
void writePageAsDatatype(FILE * fimg, DataType datatype, size_t datasize_n )
{
size_t datasize = datasize_n * gettypesize(datatype);
char * fdata = (char *) askMemory(datasize);
castPage2Datatype(MULTIDIM_ARRAY(data), fdata, datatype, datasize_n);
fwrite( fdata, datasize, 1, fimg );
freeMemory(fdata, datasize);
}
/** Swap an entire page
* input pointer char *
*/
void swapPage(char * page, size_t pageNrElements, DataType datatype)
{
unsigned long datatypesize = gettypesize(datatype);
#ifdef DEBUG
std::cerr<<"DEBUG swapPage: Swapping image data with swap= "
<< swap<<" datatypesize= "<<datatypesize
<< " pageNrElements " << pageNrElements
<< " datatype " << datatype
<<std::endl;
;
#endif
// Swap bytes if required
if ( swap == 1 )
{
for (unsigned long i=0; i<pageNrElements; i+=datatypesize)
swapbytes(page+i, datatypesize);
}
else if ( swap > 1 )
{
for (unsigned long i=0; i<pageNrElements; i+=swap)
swapbytes(page+i, swap);
}
}
/** Read the raw data
*/
int readData(FILE* fimg, long int select_img, DataType datatype, unsigned long pad)
{
//#define DEBUG
#ifdef DEBUG
std::cerr<<"entering readdata"<<std::endl;
std::cerr<<" readData flag= "<<dataflag<<std::endl;
#endif
if ( dataflag < 1 )
return 0;
size_t myoffset, readsize, readsize_n, pagemax = 1073741824; // 1 GB
size_t datatypesize; // bytes
size_t pagesize; // bytes
if (datatype == UHalf)
{
if (YXSIZE(data) % 2 != 0) REPORT_ERROR("For UHalf, YXSIZE(data) must be even.");
pagesize = ZYXSIZE(data) / 2;
}
else
{
datatypesize = gettypesize(datatype);
pagesize = ZYXSIZE(data)*datatypesize;
}
size_t haveread_n=0; // number of pixels (not necessarily bytes!) processed so far
//Multidimarray mmapOn is priority over image mmapOn
if(data.mmapOn)
mmapOn = false;
if (datatype == UHalf) mmapOn = false;
// Flag to know that data is not going to be mapped although mmapOn is true
if (mmapOn && !checkMmapT(datatype))
{
std::cout << "WARNING: Image Class. File datatype and image declaration not compatible with mmap. Loading into memory." <<std::endl;
mmapOn = false;
mFd = -1;
}
if (mmapOn)
{
if ( NSIZE(data) > 1 )
{
REPORT_ERROR("Image Class::ReadData: mmap with multiple \
images file not compatible. Try selecting a unique image.");
}
fclose(fimg);
//if ( ( mFd = open(filename.c_str(), O_RDWR, S_IREAD | S_IWRITE) ) == -1 )
if ( ( mFd = open(filename.c_str(), O_RDWR, S_IRUSR | S_IWUSR) ) == -1 )
REPORT_ERROR("Image Class::ReadData: Error opening the image file.");
char * map;
mappedSize = pagesize+offset;
if ( (map = (char*) mmap(0,mappedSize, PROT_READ | PROT_WRITE, MAP_SHARED, mFd, 0)) == (void*) -1 )
REPORT_ERROR("Image Class::ReadData: mmap of image file failed.");
data.data = reinterpret_cast<T*> (map+offset);
}
else
{
// Reset select to get the correct offset
if ( select_img < 0 )
select_img = 0;
char* page = NULL;
// Allocate memory for image data (Assume xdim, ydim, zdim and ndim are already set
// if memory already allocated use it (no resize allowed)
data.coreAllocateReuse();
myoffset = offset + select_img*(pagesize + pad);
//#define DEBUG
#ifdef DEBUG
data.printShape();
printf("DEBUG: Page size: %ld offset= %d \n", pagesize, offset);
printf("DEBUG: Swap = %d Pad = %ld Offset = %ld\n", swap, pad, offset);
printf("DEBUG: myoffset = %d select_img= %d \n", myoffset, select_img);
#endif
if (pagesize > pagemax)
page = (char *) askMemory(pagemax*sizeof(char));
else
page = (char *) askMemory(pagesize*sizeof(char));
// Because we requested XYSIZE to be even for UHalf, this is always safe.
int error_fseek = fseek(fimg, myoffset, SEEK_SET);
if (error_fseek != 0)
return -1;
for (size_t myn=0; myn<NSIZE(data); myn++)
{
for (size_t myj=0; myj<pagesize; myj+=pagemax) //pagesize size of object
{
// Read next page. Divide pages larger than pagemax
readsize = pagesize - myj;