source: trunk/Mars/mcore/zofits.h@ 17298

Last change on this file since 17298 was 17297, checked in by tbretz, 11 years ago
Added some more tweaks needed by CINT (default constructors, handling of __attribute((__packed__)))
File size: 38.7 KB
Line 
1#ifndef FACT_zofits
2#define FACT_zofits
3
4/*
5 * zofits.h
6 *
7 * FACT native compressed FITS writer
8 * Author: lyard
9 */
10
11#include "ofits.h"
12#include "huffman.h"
13#include "Queue.h"
14#include "MemoryManager.h"
15
16#ifdef HAVE_BOOST_THREAD
17#include <boost/thread.hpp>
18#endif
19
20class zofits : public ofits
21{
22#ifdef __MARS__ // Needed by CINT to access the structures
23public:
24#endif
25 /// Overriding of the begin() operator to get the smallest item in the list instead of the true begin
26 template<class S>
27 struct QueueMin : std::list<S>
28 {
29 typename std::list<S>::iterator begin()
30 {
31 return min_element(std::list<S>::begin(), std::list<S>::end());
32 }
33 };
34
35#ifdef __CINT__
36 struct CatalogEntry;
37#else
38 //catalog types
39 struct CatalogEntry
40 {
41 CatalogEntry(int64_t f=0, int64_t s=0) : first(f), second(s) { }
42 int64_t first; ///< Size of this column in the tile
43 int64_t second; ///< offset of this column in the tile, from the start of the heap area
44 } __attribute__((__packed__));
45#endif
46
47 typedef std::vector<CatalogEntry> CatalogRow;
48 typedef std::list<CatalogRow> CatalogType;
49
50 /// Parameters required to write a tile to disk
51 struct WriteTarget
52 {
53 bool operator < (const WriteTarget& other) const
54 {
55 return tile_num < other.tile_num;
56 }
57
58 WriteTarget() { }
59 WriteTarget(const WriteTarget &t, uint32_t sz) : tile_num(t.tile_num), size(sz), data(t.data) { }
60
61 uint32_t tile_num; ///< Tile index of the data (to make sure that they are written in the correct order)
62 uint32_t size; ///< Size to write
63 std::shared_ptr<char> data; ///< Memory block to write
64 };
65
66
67 /// Parameters required to compress a tile of data
68 struct CompressionTarget
69 {
70 CompressionTarget(CatalogRow& r) : catalog_entry(r)
71 {}
72
73 CatalogRow& catalog_entry; ///< Reference to the catalog entry to deal with
74 std::shared_ptr<char> src; ///< Original data
75 std::shared_ptr<char> transposed_src; ///< Transposed data
76 WriteTarget target; ///< Compressed data
77 uint32_t num_rows; ///< Number of rows to compress
78 };
79
80public:
81 /// static setter for the default number of threads to use. -1 means all available physical cores
82 static uint32_t DefaultNumThreads(const uint32_t &_n=-2) { static uint32_t n=0; if (int32_t(_n)<-1) n=_n; return n; }
83 static uint32_t DefaultMaxMemory(const uint32_t &_n=0) { static uint32_t n=1000000; if (_n>0) n=_n; return n; }
84 static uint32_t DefaultMaxNumTiles(const uint32_t &_n=0) { static uint32_t n=1000; if (_n>0) n=_n; return n; }
85 static uint32_t DefaultNumRowsPerTile(const uint32_t &_n=0) { static uint32_t n=100; if (_n>0) n=_n; return n; }
86
87 /// constructors
88 /// @param numTiles how many data groups should be pre-reserved ?
89 /// @param rowPerTile how many rows will be grouped together in a single tile
90 /// @param maxUsableMem how many bytes of memory can be used by the compression buffers
91 zofits(uint32_t numTiles = DefaultMaxNumTiles(),
92 uint32_t rowPerTile = DefaultNumRowsPerTile(),
93 uint32_t maxUsableMem= DefaultMaxMemory()) : ofits(),
94 fMemPool(0, maxUsableMem*1000),
95 fWriteToDiskQueue(std::bind(&zofits::WriteBufferToDisk, this, std::placeholders::_1), false)
96 {
97 InitMemberVariables(numTiles, rowPerTile, maxUsableMem*1000);
98 SetNumThreads(DefaultNumThreads());
99 }
100
101 /// @param fname the target filename
102 /// @param numTiles how many data groups should be pre-reserved ?
103 /// @param rowPerTile how many rows will be grouped together in a single tile
104 /// @param maxUsableMem how many bytes of memory can be used by the compression buffers
105 zofits(const char* fname,
106 uint32_t numTiles = DefaultMaxNumTiles(),
107 uint32_t rowPerTile = DefaultNumRowsPerTile(),
108 uint32_t maxUsableMem= DefaultMaxMemory()) : ofits(fname),
109 fMemPool(0, maxUsableMem*1000),
110 fWriteToDiskQueue(std::bind(&zofits::WriteBufferToDisk, this, std::placeholders::_1), false)
111 {
112 InitMemberVariables(numTiles, rowPerTile, maxUsableMem*1000);
113 SetNumThreads(DefaultNumThreads());
114 }
115
116 //initialization of member variables
117 /// @param nt number of tiles
118 /// @param rpt number of rows per tile
119 /// @param maxUsableMem max amount of RAM to be used by the compression buffers
120 void InitMemberVariables(const uint32_t nt=0, const uint32_t rpt=0, const uint64_t maxUsableMem=0)
121 {
122 fCheckOffset = 0;
123 fNumQueues = 0;
124
125 fNumTiles = nt==0 ? 1 : nt;
126 fNumRowsPerTile = rpt;
127
128 fRealRowWidth = 0;
129 fCatalogOffset = 0;
130 fCatalogSize = 0;
131
132 fMaxUsableMem = maxUsableMem;
133#ifdef __EXCEPTIONS
134 fThreadsException = std::exception_ptr();
135#endif
136 fErrno = 0;
137 }
138
139 /// write the header of the binary table
140 /// @param name the name of the table to be created
141 /// @return the state of the file
142 virtual bool WriteTableHeader(const char* name="DATA")
143 {
144 reallocateBuffers();
145
146 ofits::WriteTableHeader(name);
147
148 fCompressionQueues.front().setPromptExecution(fNumQueues==0);
149 fWriteToDiskQueue.setPromptExecution(fNumQueues==0);
150
151 if (fNumQueues != 0)
152 {
153 //start the compression queues
154 for (auto it=fCompressionQueues.begin(); it!= fCompressionQueues.end(); it++)
155 it->start();
156
157 //start the disk writer
158 fWriteToDiskQueue.start();
159 }
160
161 //mark that no tile has been written so far
162 fLatestWrittenTile = -1;
163
164 //no wiring error (in the writing of the data) has occured so far
165 fErrno = 0;
166
167 return good();
168 }
169
170 /// open a new file.
171 /// @param filename the name of the file
172 /// @param Whether or not the name of the extension should be added or not
173 void open(const char* filename, bool addEXTNAMEKey=true)
174 {
175 ofits::open(filename, addEXTNAMEKey);
176
177 //add compression-related header entries
178 SetBool( "ZTABLE", true, "Table is compressed");
179 SetInt( "ZNAXIS1", 0, "Width of uncompressed rows");
180 SetInt( "ZNAXIS2", 0, "Number of uncompressed rows");
181 SetInt( "ZPCOUNT", 0, "");
182 SetInt( "ZHEAPPTR", 0, "");
183 SetInt( "ZTILELEN", fNumRowsPerTile, "Number of rows per tile");
184 SetInt( "THEAP", 0, "");
185 SetStr( "RAWSUM", " 0", "Checksum of raw little endian data");
186 SetFloat("ZRATIO", 0, "Compression ratio");
187 SetInt( "ZSHRINK", 1, "Catalog shrink factor");
188
189 fCatalogSize = 0;
190 fRealRowWidth = 0;
191 fCatalogOffset = 0;
192 fCatalogSize = 0;
193 fCheckOffset = 0;
194
195 fRealColumns.clear();
196 fCatalog.clear();
197 fCatalogSum.reset();
198 fRawSum.reset();
199 }
200
201 /// Super method. does nothing as zofits does not know about DrsOffsets
202 /// @return the state of the file
203 virtual bool WriteDrsOffsetsTable()
204 {
205 return good();
206 }
207
208 /// Returns the number of bytes per uncompressed row
209 /// @return number of bytes per uncompressed row
210 uint32_t GetBytesPerRow() const
211 {
212 return fRealRowWidth;
213 }
214
215 /// Write the data catalog
216 /// @return the state of the file
217 bool WriteCatalog()
218 {
219 const uint32_t one_catalog_row_size = fTable.num_cols*2*sizeof(uint64_t);
220 const uint32_t total_catalog_size = fNumTiles*one_catalog_row_size;
221
222 // swap the catalog bytes before writing
223 std::vector<char> swapped_catalog(total_catalog_size);
224
225 uint32_t shift = 0;
226 for (auto it=fCatalog.cbegin(); it!=fCatalog.cend(); it++)
227 {
228 revcpy<sizeof(uint64_t)>(swapped_catalog.data() + shift, (char*)(it->data()), fTable.num_cols*2);
229 shift += one_catalog_row_size;
230 }
231
232 if (fCatalogSize < fNumTiles)
233 memset(swapped_catalog.data()+shift, 0, total_catalog_size-shift);
234
235 // first time writing ? remember where we are
236 if (fCatalogOffset == 0)
237 fCatalogOffset = tellp();
238
239 // remember where we came from
240 const off_t where_are_we = tellp();
241
242 // write to disk
243 seekp(fCatalogOffset);
244 write(swapped_catalog.data(), total_catalog_size);
245
246 if (where_are_we != fCatalogOffset)
247 seekp(where_are_we);
248
249 // udpate checksum
250 fCatalogSum.reset();
251 fCatalogSum.add(swapped_catalog.data(), total_catalog_size);
252
253 return good();
254 }
255
256 /// Applies the DrsOffsets calibration to the data. Does nothing as zofits knows nothing about drsoffsets.
257 virtual void DrsOffsetCalibrate(char* )
258 {
259
260 }
261
262 CatalogRow& AddOneCatalogRow()
263 {
264 // add one row to the catalog
265 fCatalog.emplace_back(CatalogRow());
266 fCatalog.back().resize(fTable.num_cols);
267 for (auto it=fCatalog.back().begin(); it != fCatalog.back().end(); it++)
268 *it = CatalogEntry(0,0);
269
270 fCatalogSize++;
271
272 return fCatalog.back();
273 }
274
275 /// write one row of data
276 /// Note, in a multi-threaded environment (NumThreads>0), the return code should be checked rather
277 /// than the badbit() of the stream (it might have been set by a thread before the errno has been set)
278 /// errno will then contain the correct error number of the last error which happened during writing.
279 /// @param ptr the source buffer
280 /// @param the number of bytes to write
281 /// @return the state of the file. WARNING: with multithreading, this will most likely be the state of the file before the data is actually written
282 bool WriteRow(const void* ptr, size_t cnt, bool = true)
283 {
284 if (cnt != fRealRowWidth)
285 {
286#ifdef __EXCEPTIONS
287 throw std::runtime_error("Wrong size of row given to WriteRow");
288#else
289 gLog << ___err___ << "ERROR - Wrong size of row given to WriteRow" << std::endl;
290 return false;
291#endif
292 }
293
294#ifdef __EXCEPTIONS
295 //check if something hapenned while the compression threads were working
296 //if so, re-throw the exception that was generated
297 if (fThreadsException != std::exception_ptr())
298 std::rethrow_exception(fThreadsException);
299#endif
300
301 //copy current row to pool or rows waiting for compression
302 char* target_location = fSmartBuffer.get() + fRealRowWidth*(fTable.num_rows%fNumRowsPerTile);
303 memcpy(target_location, ptr, fRealRowWidth);
304
305 //for now, make an extra copy of the data, for RAWSUM checksuming.
306 //Ideally this should be moved to the threads
307 //However, because the RAWSUM must be calculated before the tile is transposed, I am not sure whether
308 //one extra memcpy per row written is worse than 100 rows checksumed when the tile is full....
309 const uint32_t rawOffset = (fTable.num_rows*fRealRowWidth)%4;
310 char* buffer = fRawSumBuffer.data() + rawOffset;
311 auto ib = fRawSumBuffer.begin();
312 auto ie = fRawSumBuffer.rbegin();
313 *ib++ = 0;
314 *ib++ = 0;
315 *ib++ = 0;
316 *ib = 0;
317
318 *ie++ = 0;
319 *ie++ = 0;
320 *ie++ = 0;
321 *ie = 0;
322
323 memcpy(buffer, ptr, fRealRowWidth);
324
325 fRawSum.add(fRawSumBuffer, false);
326
327 fTable.num_rows++;
328
329 if (fTable.num_rows % fNumRowsPerTile != 0)
330 {
331 errno = fErrno;
332 return errno==0;
333 }
334
335 // use the least occupied queue
336 const auto imin = std::min_element(fCompressionQueues.begin(), fCompressionQueues.end());
337
338 if (!imin->emplace(InitNextCompression()))
339 {
340#ifdef __EXCEPTIONS
341 throw std::runtime_error("The compression queues are not started. Did you close the file before writing this row?");
342#else
343 gLog << ___err___ << "The compression queues are not started. Did you close the file before writing this row?" << std::endl;
344 errno = 0;
345 return false;
346#endif
347 }
348
349 errno = fErrno;
350 return errno==0;
351 }
352
353 /// update the real number of rows
354 void FlushNumRows()
355 {
356 SetInt("NAXIS2", (fTable.num_rows + fNumRowsPerTile-1)/fNumRowsPerTile);
357 SetInt("ZNAXIS2", fTable.num_rows);
358 FlushHeader();
359 }
360
361 /// Setup the environment to compress yet another tile of data
362 /// @param target the struct where to host the produced parameters
363 CompressionTarget InitNextCompression()
364 {
365 CompressionTarget target(AddOneCatalogRow());
366
367 //fill up compression target
368 target.src = fSmartBuffer;
369 target.transposed_src = fMemPool.malloc();
370 target.num_rows = fTable.num_rows;
371
372 //fill up write to disk target
373 WriteTarget &write_target = target.target;
374 write_target.tile_num = (fTable.num_rows-1)/fNumRowsPerTile;
375 write_target.size = 0;
376 write_target.data = fMemPool.malloc();
377
378 //get a new buffer to host the incoming data
379 fSmartBuffer = fMemPool.malloc();
380
381 return target;
382 }
383
384 /// Shrinks a catalog that is too long to fit into the reserved space at the beginning of the file.
385 const uint32_t ShrinkCatalog()
386 {
387 //add empty row to get either the target number of rows, or a multiple of the allowed size
388 for (uint32_t i=0;i<fCatalogSize%fNumTiles;i++)
389 AddOneCatalogRow();
390
391 //did we write more rows than what the catalog could host ?
392 if (fCatalogSize <= fNumTiles) // nothing to do
393 return 1;
394
395 //always exact as extra rows were added just above
396 const uint32_t shrink_factor = fCatalogSize / fNumTiles;
397
398 //shrink the catalog !
399 uint32_t entry_id = 1;
400 auto it = fCatalog.begin();
401 it++;
402 for (; it != fCatalog.end(); it++)
403 {
404 if (entry_id >= fNumTiles)
405 break;
406
407 const uint32_t target_id = entry_id*shrink_factor;
408
409 auto jt = it;
410 for (uint32_t i=0; i<target_id-entry_id; i++)
411 jt++;
412
413 *it = *jt;
414
415 entry_id++;
416 }
417
418 const uint32_t num_tiles_to_remove = fCatalogSize-fNumTiles;
419
420 //remove the too many entries
421 for (uint32_t i=0;i<num_tiles_to_remove;i++)
422 {
423 fCatalog.pop_back();
424 fCatalogSize--;
425 }
426
427 //update header keywords
428 fNumRowsPerTile *= shrink_factor;
429
430 SetInt("ZTILELEN", fNumRowsPerTile);
431 SetInt("ZSHRINK", shrink_factor);
432
433 return shrink_factor;
434 }
435
436 /// close an open file.
437 /// @return the state of the file
438 bool close()
439 {
440 // stop compression and write threads
441 for (auto it=fCompressionQueues.begin(); it != fCompressionQueues.end(); it++)
442 it->wait();
443
444 fWriteToDiskQueue.wait();
445
446 if (tellp() < 0)
447 return false;
448
449#ifdef __EXCEPTIONS
450 //check if something hapenned while the compression threads were working
451 //if so, re-throw the exception that was generated
452 if (fThreadsException != std::exception_ptr())
453 std::rethrow_exception(fThreadsException);
454#endif
455
456 //write the last tile of data (if any)
457 if (fErrno==0 && fTable.num_rows%fNumRowsPerTile!=0)
458 {
459 fWriteToDiskQueue.enablePromptExecution();
460 fCompressionQueues.front().enablePromptExecution();
461 fCompressionQueues.front().emplace(InitNextCompression());
462 }
463
464 AlignTo2880Bytes();
465
466 int64_t heap_size = 0;
467 int64_t compressed_offset = 0;
468 for (auto it=fCatalog.begin(); it!= fCatalog.end(); it++)
469 {
470 compressed_offset += sizeof(FITS::TileHeader);
471 heap_size += sizeof(FITS::TileHeader);
472 for (uint32_t j=0; j<it->size(); j++)
473 {
474 heap_size += (*it)[j].first;
475 (*it)[j].second = compressed_offset;
476 compressed_offset += (*it)[j].first;
477 if ((*it)[j].first == 0)
478 (*it)[j].second = 0;
479 }
480 }
481
482 const uint32_t shrink_factor = ShrinkCatalog();
483
484 //update header keywords
485 SetInt("ZNAXIS1", fRealRowWidth);
486 SetInt("ZNAXIS2", fTable.num_rows);
487
488 SetInt("ZHEAPPTR", fCatalogSize*fTable.num_cols*sizeof(uint64_t)*2);
489
490 const uint32_t total_num_tiles_written = (fTable.num_rows + fNumRowsPerTile-1)/fNumRowsPerTile;
491 const uint32_t total_catalog_width = 2*sizeof(int64_t)*fTable.num_cols;
492
493 SetInt("THEAP", total_num_tiles_written*total_catalog_width);
494 SetInt("NAXIS1", total_catalog_width);
495 SetInt("NAXIS2", total_num_tiles_written);
496 SetStr("RAWSUM", std::to_string((long long int)(fRawSum.val())));
497
498 const float compression_ratio = (float)(fRealRowWidth*fTable.num_rows)/(float)heap_size;
499 SetFloat("ZRATIO", compression_ratio);
500
501 //add to the heap size the size of the gap between the catalog and the actual heap
502 heap_size += (fCatalogSize - total_num_tiles_written)*fTable.num_cols*sizeof(uint64_t)*2;
503
504 SetInt("PCOUNT", heap_size, "size of special data area");
505
506 //Just for updating the fCatalogSum value
507 WriteCatalog();
508
509 fDataSum += fCatalogSum;
510
511 const Checksum checksm = UpdateHeaderChecksum();
512
513 std::ofstream::close();
514
515 fSmartBuffer = std::shared_ptr<char>();
516
517 //restore the number of rows per tile in case the catalog has been shrinked
518 if (shrink_factor != 1)
519 fNumRowsPerTile /= shrink_factor;
520
521 if ((checksm+fDataSum).valid())
522 return true;
523
524 std::ostringstream sout;
525 sout << "Checksum (" << std::hex << checksm.val() << ") invalid.";
526#ifdef __EXCEPTIONS
527 throw std::runtime_error(sout.str());
528#else
529 gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
530 return false;
531#endif
532 }
533
534 /// Overload of the ofits method. Just calls the zofits specific one with default, uncompressed options for this column
535 bool AddColumn(uint32_t cnt, char typechar, const std::string& name, const std::string& unit,
536 const std::string& comment="", bool addHeaderKeys=true)
537 {
538 return AddColumn(FITS::kFactRaw, cnt, typechar, name, unit, comment, addHeaderKeys);
539 }
540
541 /// Overload of the simplified compressed version
542 bool AddColumn(const FITS::Compression &comp, uint32_t cnt, char typechar, const std::string& name,
543 const std::string& unit, const std::string& comment="", bool addHeaderKeys=true)
544 {
545 if (!ofits::AddColumn(1, 'Q', name, unit, comment, addHeaderKeys))
546 return false;
547
548 const size_t size = SizeFromType(typechar);
549
550 Table::Column col;
551 col.name = name;
552 col.type = typechar;
553 col.num = cnt;
554 col.size = size;
555 col.offset = fRealRowWidth;
556
557 fRealRowWidth += size*cnt;
558
559 fRealColumns.emplace_back(col, comp);
560
561 SetStr("ZFORM"+std::to_string((long long int)(fRealColumns.size())), std::to_string((long long int)(cnt))+typechar, "format of "+name+" "+CommentFromType(typechar));
562 SetStr("ZCTYP"+std::to_string((long long int)(fRealColumns.size())), "FACT", "Compression type: FACT");
563
564 return true;
565 }
566
567 /// Get and set the actual number of threads for this object
568 int32_t GetNumThreads() const { return fNumQueues; }
569 bool SetNumThreads(uint32_t num)
570 {
571 if (tellp()>0)
572 {
573#ifdef __EXCEPTIONS
574 throw std::runtime_error("Number of threads cannot be changed in the middle of writing a file");
575#else
576 gLog << ___err___ << "ERROR - Number of threads cannot be changed in the middle of writing a file" << std::endl;
577#endif
578 return false;
579 }
580
581 //get number of physically available threads
582#ifdef HAVE_BOOST_THREAD
583 unsigned int num_available_cores = boost::thread::hardware_concurrency();
584#else
585 unsigned int num_available_cores = std::thread::hardware_concurrency();
586#endif
587 // could not detect number of available cores from system properties...
588 if (num_available_cores == 0)
589 num_available_cores = 1;
590
591 // leave one core for the main thread and one for the writing
592 if (num > num_available_cores)
593 num = num_available_cores>2 ? num_available_cores-2 : 1;
594
595 fCompressionQueues.resize(num<1?1:num, Queue<CompressionTarget>(std::bind(&zofits::CompressBuffer, this, std::placeholders::_1), false));
596 fNumQueues = num;
597
598 return true;
599 }
600
601 uint32_t GetNumTiles() const { return fNumTiles; }
602 void SetNumTiles(uint32_t num) { fNumTiles=num; }
603
604protected:
605
606 /// Allocates the required objects.
607 void reallocateBuffers()
608 {
609 const size_t chunk_size = fRealRowWidth*fNumRowsPerTile + fRealColumns.size()*sizeof(FITS::BlockHeader) + sizeof(FITS::TileHeader) + 8; //+8 for checksuming;
610 fMemPool.setChunkSize(chunk_size);
611
612 fSmartBuffer = fMemPool.malloc();
613 fRawSumBuffer.resize(fRealRowWidth + 4-fRealRowWidth%4); //for checksuming
614 }
615
616 /// Actually does the writing to disk (and checksuming)
617 /// @param src the buffer to write
618 /// @param sizeToWrite how many bytes should be written
619 /// @return the state of the file
620 bool writeCompressedDataToDisk(char* src, const uint32_t sizeToWrite)
621 {
622 char* checkSumPointer = src+4;
623 int32_t extraBytes = 0;
624 uint32_t sizeToChecksum = sizeToWrite;
625
626 //should we extend the array to the left ?
627 if (fCheckOffset != 0)
628 {
629 sizeToChecksum += fCheckOffset;
630 checkSumPointer -= fCheckOffset;
631 memset(checkSumPointer, 0, fCheckOffset);
632 }
633
634 //should we extend the array to the right ?
635 if (sizeToChecksum%4 != 0)
636 {
637 extraBytes = 4 - (sizeToChecksum%4);
638 memset(checkSumPointer+sizeToChecksum, 0, extraBytes);
639 sizeToChecksum += extraBytes;
640 }
641
642 //do the checksum
643 fDataSum.add(checkSumPointer, sizeToChecksum);
644
645 fCheckOffset = (4 - extraBytes)%4;
646
647 //write data to disk
648 write(src+4, sizeToWrite);
649
650 return good();
651 }
652
653 /// Compress a given buffer based on the target. This is the method executed by the threads
654 /// @param target the struct hosting the parameters of the compression
655 /// @return number of bytes of the compressed data, or always 1 when used by the Queues
656 bool CompressBuffer(const CompressionTarget& target)
657 {
658 //Can't get this to work in the thread. Printed the adresses, and they seem to be correct.
659 //Really do not understand what's wrong...
660 //calibrate data if required
661 const uint32_t thisRoundNumRows = (target.num_rows%fNumRowsPerTile) ? target.num_rows%fNumRowsPerTile : fNumRowsPerTile;
662 for (uint32_t i=0;i<thisRoundNumRows;i++)
663 {
664 char* target_location = target.src.get() + fRealRowWidth*i;
665 DrsOffsetCalibrate(target_location);
666 }
667#ifdef __EXCEPTIONS
668 try
669 {
670#endif
671 //transpose the original data
672 copyTransposeTile(target.src.get(), target.transposed_src.get(), target.num_rows);
673
674 //compress the buffer
675 const uint64_t compressed_size = compressBuffer(target.target.data.get(), target.transposed_src.get(), target.num_rows, target.catalog_entry);
676
677 //post the result to the writing queue
678 //get a copy so that it becomes non-const
679 fWriteToDiskQueue.emplace(target.target, compressed_size);
680
681#ifdef __EXCEPTIONS
682 }
683 catch (...)
684 {
685 fThreadsException = std::current_exception();
686 if (fNumQueues == 0)
687 std::rethrow_exception(fThreadsException);
688 }
689#endif
690
691 return true;
692 }
693
694 /// Write one compressed tile to disk. This is the method executed by the writing thread
695 /// @param target the struct hosting the write parameters
696 bool WriteBufferToDisk(const WriteTarget& target)
697 {
698 //is this the tile we're supposed to write ?
699 if (target.tile_num != (uint32_t)(fLatestWrittenTile+1))
700 return false;
701
702 fLatestWrittenTile++;
703
704#ifdef __EXCEPTIONS
705 try
706 {
707#endif
708 //could not write the data to disk
709 if (!writeCompressedDataToDisk(target.data.get(), target.size))
710 fErrno = errno;
711#ifdef __EXCEPTIONS
712 }
713 catch (...)
714 {
715 fThreadsException = std::current_exception();
716 if (fNumQueues == 0)
717 std::rethrow_exception(fThreadsException);
718 }
719#endif
720 return true;
721 }
722
723 /// Compress a given buffer based on its source and destination
724 //src cannot be const, as applySMOOTHING is done in place
725 /// @param dest the buffer hosting the compressed data
726 /// @param src the buffer hosting the transposed data
727 /// @param num_rows the number of uncompressed rows in the transposed buffer
728 /// @param the number of bytes of the compressed data
729 uint64_t compressBuffer(char* dest, char* src, uint32_t num_rows, CatalogRow& catalog_row)
730 {
731 const uint32_t thisRoundNumRows = (num_rows%fNumRowsPerTile) ? num_rows%fNumRowsPerTile : fNumRowsPerTile;
732 uint32_t offset = 0;
733
734 //skip the checksum reserved area
735 dest += 4;
736
737 //skip the 'TILE' marker and tile size entry
738 uint64_t compressedOffset = sizeof(FITS::TileHeader);
739
740 //now compress each column one by one by calling compression on arrays
741 for (uint32_t i=0;i<fRealColumns.size();i++)
742 {
743 catalog_row[i].second = compressedOffset;
744
745 if (fRealColumns[i].col.num == 0)
746 continue;
747
748 FITS::Compression& head = fRealColumns[i].block_head;
749
750 //set the default byte telling if uncompressed the compressed Flag
751 const uint64_t previousOffset = compressedOffset;
752
753 //skip header data
754 compressedOffset += head.getSizeOnDisk();
755
756 for (uint32_t j=0;j<head.getNumProcs();j++)//sequence.size(); j++)
757 {
758 switch (head.getProc(j))
759 {
760 case FITS::kFactRaw:
761 compressedOffset += compressUNCOMPRESSED(dest + compressedOffset, src + offset, thisRoundNumRows*fRealColumns[i].col.size*fRealColumns[i].col.num);
762 break;
763
764 case FITS::kFactSmoothing:
765 applySMOOTHING(src + offset, thisRoundNumRows*fRealColumns[i].col.num);
766 break;
767
768 case FITS::kFactHuffman16:
769 if (head.getOrdering() == FITS::kOrderByCol)
770 compressedOffset += compressHUFFMAN16(dest + compressedOffset, src + offset, thisRoundNumRows, fRealColumns[i].col.size, fRealColumns[i].col.num);
771 else
772 compressedOffset += compressHUFFMAN16(dest + compressedOffset, src + offset, fRealColumns[i].col.num, fRealColumns[i].col.size, thisRoundNumRows);
773 break;
774 }
775 }
776
777 //check if compressed size is larger than uncompressed
778 //if so set flag and redo it uncompressed
779 if ((head.getProc(0) != FITS::kFactRaw) && (compressedOffset - previousOffset > fRealColumns[i].col.size*fRealColumns[i].col.num*thisRoundNumRows+head.getSizeOnDisk()))// && two)
780 {
781 //de-smooth !
782 if (head.getProc(0) == FITS::kFactSmoothing)
783 UnApplySMOOTHING(src+offset, fRealColumns[i].col.num*thisRoundNumRows);
784
785 FITS::Compression he;
786
787 compressedOffset = previousOffset + he.getSizeOnDisk();
788 compressedOffset += compressUNCOMPRESSED(dest + compressedOffset, src + offset, thisRoundNumRows*fRealColumns[i].col.size*fRealColumns[i].col.num);
789
790 he.SetBlockSize(compressedOffset - previousOffset);
791 he.Memcpy(dest+previousOffset);
792
793 offset += thisRoundNumRows*fRealColumns[i].col.size*fRealColumns[i].col.num;
794
795 catalog_row[i].first = compressedOffset - catalog_row[i].second;
796 continue;
797 }
798
799 head.SetBlockSize(compressedOffset - previousOffset);
800 head.Memcpy(dest + previousOffset);
801
802 offset += thisRoundNumRows*fRealColumns[i].col.size*fRealColumns[i].col.num;
803 catalog_row[i].first = compressedOffset - catalog_row[i].second;
804 }
805
806 const FITS::TileHeader tile_head(thisRoundNumRows, compressedOffset);
807 memcpy(dest, &tile_head, sizeof(FITS::TileHeader));
808
809 return compressedOffset;
810 }
811
812 /// Transpose a tile to a new buffer
813 /// @param src buffer hosting the regular, row-ordered data
814 /// @param dest the target buffer that will receive the transposed data
815 void copyTransposeTile(const char* src, char* dest, uint32_t num_rows)
816 {
817 const uint32_t thisRoundNumRows = (num_rows%fNumRowsPerTile) ? num_rows%fNumRowsPerTile : fNumRowsPerTile;
818
819 //copy the tile and transpose it
820 for (uint32_t i=0;i<fRealColumns.size();i++)
821 {
822 switch (fRealColumns[i].block_head.getOrdering())
823 {
824 case FITS::kOrderByRow:
825 //regular, "semi-transposed" copy
826 for (uint32_t k=0;k<thisRoundNumRows;k++)
827 {
828 memcpy(dest, src+k*fRealRowWidth+fRealColumns[i].col.offset, fRealColumns[i].col.size*fRealColumns[i].col.num);
829 dest += fRealColumns[i].col.size*fRealColumns[i].col.num;
830 }
831 break;
832
833 case FITS::kOrderByCol:
834 //transposed copy
835 for (uint32_t j=0;j<fRealColumns[i].col.num;j++)
836 for (uint32_t k=0;k<thisRoundNumRows;k++)
837 {
838 memcpy(dest, src+k*fRealRowWidth+fRealColumns[i].col.offset+fRealColumns[i].col.size*j, fRealColumns[i].col.size);
839 dest += fRealColumns[i].col.size;
840 }
841 break;
842 };
843 }
844 }
845
846 /// Specific compression functions
847 /// @param dest the target buffer
848 /// @param src the source buffer
849 /// @param size number of bytes to copy
850 /// @return number of bytes written
851 uint32_t compressUNCOMPRESSED(char* dest, const char* src, uint32_t size)
852 {
853 memcpy(dest, src, size);
854 return size;
855 }
856
857 /// Do huffman encoding
858 /// @param dest the buffer that will receive the compressed data
859 /// @param src the buffer hosting the transposed data
860 /// @param numRows number of rows of data in the transposed buffer
861 /// @param sizeOfElems size in bytes of one data elements
862 /// @param numRowElems number of elements on each row
863 /// @return number of bytes written
864 uint32_t compressHUFFMAN16(char* dest, const char* src, uint32_t numRows, uint32_t sizeOfElems, uint32_t numRowElems)
865 {
866 std::string huffmanOutput;
867 uint32_t previousHuffmanSize = 0;
868
869 //if we have less than 2 elems to compress, Huffman encoder does not work (and has no point). Just return larger size than uncompressed to trigger the raw storage.
870 if (numRows < 2)
871 return numRows*sizeOfElems*numRowElems + 1000;
872
873 if (sizeOfElems < 2 )
874 {
875#ifdef __EXCEPTIONS
876 throw std::runtime_error("HUFMANN16 can only encode columns with 16-bit or longer types");
877#else
878 gLog << ___err___ << "ERROR - HUFMANN16 can only encode columns with 16-bit or longer types" << std::endl;
879 return 0;
880#endif
881 }
882
883 uint32_t huffmanOffset = 0;
884 for (uint32_t j=0;j<numRowElems;j++)
885 {
886 Huffman::Encode(huffmanOutput,
887 reinterpret_cast<const uint16_t*>(&src[j*sizeOfElems*numRows]),
888 numRows*(sizeOfElems/2));
889 reinterpret_cast<uint32_t*>(&dest[huffmanOffset])[0] = huffmanOutput.size() - previousHuffmanSize;
890 huffmanOffset += sizeof(uint32_t);
891 previousHuffmanSize = huffmanOutput.size();
892 }
893
894 const size_t totalSize = huffmanOutput.size() + huffmanOffset;
895
896 //only copy if not larger than not-compressed size
897 if (totalSize < numRows*sizeOfElems*numRowElems)
898 memcpy(&dest[huffmanOffset], huffmanOutput.data(), huffmanOutput.size());
899
900 return totalSize;
901 }
902
903 /// Applies Thomas' DRS4 smoothing
904 /// @param data where to apply it
905 /// @param numElems how many elements of type int16_t are stored in the buffer
906 /// @return number of bytes modified
907 uint32_t applySMOOTHING(char* data, uint32_t numElems)
908 {
909 int16_t* short_data = reinterpret_cast<int16_t*>(data);
910 for (int j=numElems-1;j>1;j--)
911 short_data[j] = short_data[j] - (short_data[j-1]+short_data[j-2])/2;
912
913 return numElems*sizeof(int16_t);
914 }
915
916 /// Apply the inverse transform of the integer smoothing
917 /// @param data where to apply it
918 /// @param numElems how many elements of type int16_t are stored in the buffer
919 /// @return number of bytes modified
920 uint32_t UnApplySMOOTHING(char* data, uint32_t numElems)
921 {
922 int16_t* short_data = reinterpret_cast<int16_t*>(data);
923 for (uint32_t j=2;j<numElems;j++)
924 short_data[j] = short_data[j] + (short_data[j-1]+short_data[j-2])/2;
925
926 return numElems*sizeof(uint16_t);
927 }
928
929
930
931 //thread related stuff
932 MemoryManager fMemPool; ///< Actual memory manager, providing memory for the compression buffers
933 int32_t fNumQueues; ///< Current number of threads that will be used by this object
934 uint64_t fMaxUsableMem; ///< Maximum number of bytes that can be allocated by the memory manager
935 int32_t fLatestWrittenTile; ///< Index of the last tile written to disk (for correct ordering while using several threads)
936
937 std::vector<Queue<CompressionTarget>> fCompressionQueues; ///< Processing queues (=threads)
938 Queue<WriteTarget, QueueMin<WriteTarget>> fWriteToDiskQueue; ///< Writing queue (=thread)
939
940 // catalog related stuff
941 CatalogType fCatalog; ///< Catalog for this file
942 uint32_t fCatalogSize; ///< Actual catalog size (.size() is slow on large lists)
943 uint32_t fNumTiles; ///< Number of pre-reserved tiles
944 uint32_t fNumRowsPerTile; ///< Number of rows per tile
945 off_t fCatalogOffset; ///< Offset of the catalog from the beginning of the file
946
947 // checksum related stuff
948 Checksum fCatalogSum; ///< Checksum of the catalog
949 Checksum fRawSum; ///< Raw sum (specific to FACT)
950 int32_t fCheckOffset; ///< offset to the data pointer to calculate the checksum
951
952 // data layout related stuff
953 /// Regular columns augmented with compression informations
954 struct CompressedColumn
955 {
956 CompressedColumn(const Table::Column& c, const FITS::Compression& h) : col(c),
957 block_head(h)
958 {}
959#ifdef __MARS__ // Needed for the compilation ofthe dictionary
960 CompressedColumn() { }
961#endif
962 Table::Column col; ///< the regular column entry
963 FITS::Compression block_head; ///< the compression data associated with that column
964 };
965 std::vector<CompressedColumn> fRealColumns; ///< Vector hosting the columns of the file
966 uint32_t fRealRowWidth; ///< Width in bytes of one uncompressed row
967 std::shared_ptr<char> fSmartBuffer; ///< Smart pointer to the buffer where the incoming rows are written
968 std::vector<char> fRawSumBuffer; ///< buffer used for checksuming the incoming data, before compression
969
970#ifdef __EXCEPTIONS
971 std::exception_ptr fThreadsException; ///< exception pointer to store exceptions coming from the threads
972#endif
973 int fErrno; ///< propagate errno to main thread
974};
975
976#endif
Note: See TracBrowser for help on using the repository browser.