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

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