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

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