Matrix.h
Go to the documentation of this file.
1 /* Copyright (C) 2008 National Institute For Space Research (INPE) - Brazil.
2 
3  This file is part of the TerraLib - a Framework for building GIS enabled applications.
4 
5  TerraLib is free software: you can redistribute it and/or modify
6  it under the terms of the GNU Lesser General Public License as published by
7  the Free Software Foundation, either version 3 of the License,
8  or (at your option) any later version.
9 
10  TerraLib is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU Lesser General Public License for more details.
14 
15  You should have received a copy of the GNU Lesser General Public License
16  along with TerraLib. See COPYING. If not, write to
17  TerraLib Team at <terralib-team@terralib.org>.
18  */
19 
20 /*!
21  \file terralib/rp/Matrix.h
22  \brief Generic template matrix.
23  */
24 
25 #ifndef __TERRALIB_RP_INTERNAL_MATRIX_H
26 #define __TERRALIB_RP_INTERNAL_MATRIX_H
27 
28  #include "Macros.h"
29 
30  #include "../common/PlatformUtils.h"
31  #include "../core/filesystem/FileSystem.h"
32  #include "../core/encoding/CharEncoding.h"
33  #include "../core/utils/Platform.h"
34 
35  #include <cstring>
36  #include <cmath>
37  #include <cstdio>
38  #include <string>
39  #include <vector>
40  #include <memory>
41 
42  #include <boost/scoped_array.hpp>
43  #include <boost/filesystem.hpp>
44 
45  namespace te
46  {
47  namespace rp
48  {
49  /*!
50  \class Matrix
51  \brief A generic template matrix
52  */
53  template< typename TemplateElementType >
54  class Matrix {
55  public :
56 
57  /*!
58  \brief Public matrix element type definition.
59  */
60  typedef TemplateElementType ElementTypeT;
61 
62  /*!
63  \brief Memory polycy.
64  */
66  {
67  /*!
68  \details Automatic memory policy ( Try to use RAM or DISK, if there is no
69  avaliable RAM ) DO NOT USE AutoMemPol FOR COMPLEX DATA TYPES.
70  */
72  /*!
73  \details RAM memory policy.
74  */
76  /*!
77  \details Disk memory policy ( virtual mapped memory ) -
78  DO NOT USE DiskMemPol FOR COMPLEX DATA TYPES.
79  */
81  };
82 
83  Matrix();
84 
85  Matrix( const Matrix< TemplateElementType >& external );
86 
87  virtual ~Matrix();
88 
89  /*!
90  \brief Reset (clear) the active instance data.
91  \note Other parameters will not be changed.
92 
93  \param memoryPolicy Memory policy.
94  */
95  void reset();
96 
97  /*!
98  \brief Reset (clear) the active instance data and update its
99  internal parameters folowing the the new supplied parameters.
100  \note Other parameters will not be changed.
101 
102  \param memoryPolicy Memory policy.
103  */
104  void reset( MemoryPolicy memoryPolicy );
105 
106  /*!
107  \brief Reset (clear) the active instance data and update its
108  internal parameters folowing the the new supplied parameters.
109  \note Other parameters will not be changed.
110  \param lines Number of lines.
111  \param columns Number of columns.
112  \return true if OK, false on error.
113  */
114  bool reset( unsigned int lines, unsigned int columns );
115 
116  /*!
117  \brief Reset (clear) the active instance data and update its
118  internal parameters folowing the the new supplied parameters.
119  \note Other parameters will not be changed.
120 
121  \param lines Number of lines.
122  \param columns Number of columns.
123  \param memoryPolicy Memory policy.
124  \return true if OK, false on error.
125  */
126  bool reset( unsigned int lines, unsigned int columns,
127  MemoryPolicy memoryPolicy );
128 
129  /*!
130  \brief Reset (clear) the active instance data and update its
131  internal parameters folowing the the new supplied parameters.
132  \note Other parameters will not be changed.
133 
134  \param lines Number of lines.
135  \param columns Number of columns.
136  \param memoryPolicy Memory policy.
137  \param maxMemPercentUsage The max amount of free memory to use
138  when necessary (suggested default:40).
139  \return true if OK, false on error.
140  */
141  bool reset( unsigned int lines, unsigned int columns,
142  MemoryPolicy memoryPolicy, unsigned char maxMemPercentUsage );
143 
144  /*!
145  \brief Reset (clear) the active instance data and update its
146  internal parameters folowing the the new supplied parameters.
147  \note Other parameters will not be changed.
148 
149  \param lines Number of lines.
150  \param columns Number of columns.
151  \param memoryPolicy Memory policy.
152  \param maxTmpFileSize Max temp file size.
153  \param maxMemPercentUsage The max amount of free memory to use
154  when necessary (suggested default:40).
155  \return true if OK, false on error.
156  */
157  bool reset( unsigned int lines, unsigned int columns,
158  MemoryPolicy memoryPolicy, unsigned long int maxTmpFileSize,
159  unsigned char maxMemPercentUsage );
160 
161  /*!
162  \brief Clear all allocated resources and go back to the initial
163  default parameters.
164  */
165  void clear();
166 
167  /*!
168  \brief The number of current matrix lines.
169 
170  \return The number of current matrix lines.
171  */
172  unsigned int getLinesNumber() const;
173 
174  /*!
175  \brief The number of current matrix columns.
176 
177  \return The number of current matrix columns
178  */
179  unsigned int getColumnsNumber() const;
180 
181  /*!
182  \brief Empty Matrix verification.
183 
184  \return true if the matrix is empty.
185  */
186  bool isEmpty() const;
187 
188  /*!
189  \brief Operator = overload.
190 
191  \note The external memory policy will be used as reference.
192 
193  \param external External instance reference.
194  \return A reference to the current matrix.
195  */
197  const Matrix< TemplateElementType >& external );
198 
199  /*!
200  \brief Operator () overload.
201 
202  \param line Line number.
203  \param column Column number.
204  \return A reference to the required element.
205  */
206  inline TemplateElementType& operator()(
207  const unsigned int& line,
208  const unsigned int& column )
209  {
211  "Invalid columns" )
212 
213  return getScanLine( line )[ column ];
214  };
215 
216  /*!
217  \brief Operator () overload.
218 
219  \param line Line number.
220  \param column Column number.
221  \return A const reference to the required element.
222  */
223  inline const TemplateElementType& operator()(
224  const unsigned int& line,
225  const unsigned int& column ) const
226  {
228  "Invalid columns" )
229 
230  return getScanLine( line )[ column ] ;
231  };
232 
233  /*!
234  \brief Operator [] overload.
235 
236  \param line Line number.
237  \param column Column number.
238  \return A pointer to the required line.
239  \note The returned pointer is garanteed to
240  be valid until an acess to another line occurs.
241  \note Concurrent thread access to this method is guaranteed
242  if RAMMemPol policy method is used.
243  */
244  inline TemplateElementType* operator[](
245  const unsigned int& line )
246  {
247  return getScanLine( line );
248  };
249 
250  /*!
251  \brief Operator [] overload.
252 
253  \param line Line number.
254  \param column Column number.
255  \return A pointer to the required line.
256  \note The returned pointer is garanteed to
257  be valid until an acess to another line occurs.
258  \note Concurrent thread access to this method is guaranteed
259  if RAMMemPol policy method is used.
260  */
261  inline TemplateElementType const* operator[](
262  const unsigned int& line ) const
263  {
264  return getScanLine( line );
265  };
266 
267  /*!
268  \brief Returns the current memory policy.
269  \return The current memory policy.
270  */
271  MemoryPolicy getMemPolicy() const;
272 
273  /*!
274  \brief Returns the current maximum temporary disk file size.
275  \return Returns the current maximum temporary disk file size.
276  */
277  unsigned long int getMaxTmpFileSize() const;
278 
279  /*!
280  \brief Returns the max amount of free memory to use when necessary.
281  \return Returns the max amount of free memory to use when necessary.
282  */
283  unsigned char getMaxMemPercentUsage() const;
284 
285  protected :
286 
287  /*!
288  \brief Disk lines info.
289  */
291  {
292  public :
293 
294  FILE* m_filePtr; //!< The file pointer.
295 
296  unsigned int m_fileOff; //!< The offset within the file.
297 
298  DiskLineInfo();
299 
300  ~DiskLineInfo();
301  };
302 
303  /*!
304  \brief Openend disk files info node.
305  */
307  {
308  public :
309 
310  FILE* m_filePtr; //!< The file pointer.
311 
312  std::string m_fullFileName; //!< The full created file name.
313 
315 
317  };
318 
319  /*!
320  \brief Max bytes per temp file (for swapped tiles only, default: 2GB).
321  */
322  unsigned long int m_maxTmpFileSize;
323 
324  /*!
325  \brief the max amount of free memory to use when necessary.
326  */
327  unsigned char m_maxMemPercentUsage;
328 
329  /*!
330  \brief The total lines number (default:0).
331  */
332  unsigned int m_totalLines;
333 
334  /*!
335  \brief The total columns number (default:0).
336  */
337  unsigned int m_totalColumns;
338 
339  /*!
340  \brief The used memory policy (default:RAMMemPol).
341  */
343 
344  /*!
345  \brief The index inside ramLinesIndexesVec_ of the next RAM
346  line index that will be swapped to disk when a disk line
347  is required.
348  */
350 
351  /*!
352  \brief A pointer to the current swap tile.
353  */
354  mutable TemplateElementType* m_currentSwapTilePtr;
355 
356  std::vector< TemplateElementType* > m_memoryblocksHandler;
357 
358  /*!
359  \brief A vector with pointers to all lines.
360  */
361  mutable std::vector< TemplateElementType* > m_allLinesPtrsVec;
362 
363  /*!
364  \brief A vector with open disk files handler.
365  */
366  std::vector< OpenDiskFileHandler > m_openDiskFilesHandler;
367 
368  /*!
369  \brief Info of all lines, used when a line is on disk.
370  */
371  mutable std::vector< DiskLineInfo > m_diskLinesInfoVec;
372 
373  /*!
374  \brief The indexes of all lines loaded into RAM.
375  */
376  mutable std::vector< unsigned int > m_ramLinesIndexesVec;
377 
378  /*!
379  \brief An auxiliar line used when swapping
380  data to/from disk.
381  */
382  mutable boost::scoped_array< TemplateElementType > m_swapMemoryBlockHandler;
383 
384  /*!
385  \brief Reset the internal variables to the initial state.
386  */
387  void init();
388 
389  /*!
390  \brief Allocate disk lines.
391  \param startingLineIdx Starting line index.
392  \return true if OK, false on errors.
393  */
394  bool allocateDiskLines( unsigned int startingLineIdx );
395 
396  /*!
397  \brief Returns a pointer to the required line.
398 
399  \param line Line number.
400  \param column Column number.
401  \return A pointer to the required line.
402  \note The returned pointer is garanteed to
403  be valid until an acess to another line occurs.
404  \note Concurrent thread access to this method is guaranteed
405  if RAMMemPol policy method is used.
406  */
407  TemplateElementType* getScanLine(
408  const unsigned int& line ) const;
409 
410  /*!
411  \brief Create a new disk file.
412  \param size The file size.
413  \param fileptr The file pointer.
414  \param fullFileName The created full file name.
415  \return true if OK. false on errors.
416  */
417  bool createNewDiskFile( unsigned long int size, FILE** fileptr,
418  std::string& fullFileName ) const;
419  };
420 
421  template< typename TemplateElementType >
423  {
424  m_filePtr = 0;
425  m_fileOff = 0;
426  }
427 
428  template< typename TemplateElementType >
430  {
431  }
432 
433  template< typename TemplateElementType >
435  {
436  m_filePtr = 0;
437  }
438 
439  template< typename TemplateElementType >
441  {
442  if( m_filePtr )
443  {
444  remove( m_fullFileName.c_str() );
445  fclose( m_filePtr );
446  }
447  }
448 
449  template< typename TemplateElementType >
451  {
452  m_maxTmpFileSize = 2ul * 1024ul * 1024ul * 1024ul;;
454  m_totalLines = 0;
455  m_totalColumns = 0;
459  }
460 
461  template< typename TemplateElementType >
463  {
464  init();
465  }
466 
467  template< typename TemplateElementType >
469  const Matrix< TemplateElementType >& external )
470  {
471  init();
472 
473  operator=( external );
474  }
475 
476  template< typename TemplateElementType >
478  {
479  clear();
480  }
481 
482  template< typename TemplateElementType >
484  {
485  clear();
486  }
487 
488  template< typename TemplateElementType >
490  {
491  reset( 0, 0, memoryPolicy, m_maxTmpFileSize, m_maxMemPercentUsage );
492  }
493 
494  template< typename TemplateElementType >
495  bool Matrix< TemplateElementType >::reset( unsigned int lines,
496  unsigned int columns )
497  {
498  return reset( lines, columns, m_memoryPolicy, m_maxTmpFileSize,
500  }
501 
502  template< typename TemplateElementType >
503  bool Matrix< TemplateElementType >::reset( unsigned int lines,
504  unsigned int columns, MemoryPolicy memoryPolicy )
505  {
506  return reset( lines, columns, memoryPolicy, m_maxTmpFileSize,
508  }
509 
510  template< typename TemplateElementType >
511  bool Matrix< TemplateElementType >::reset( unsigned int lines,
512  unsigned int columns, MemoryPolicy memoryPolicy,
513  unsigned char maxMemPercentUsage )
514  {
515  return reset( lines, columns, memoryPolicy, m_maxTmpFileSize,
516  maxMemPercentUsage );
517  }
518 
519  template< typename TemplateElementType >
520  bool Matrix< TemplateElementType >::reset( unsigned int lines,
521  unsigned int columns, MemoryPolicy memoryPolicy,
522  unsigned long int maxTmpFileSize,
523  unsigned char maxMemPercentUsage )
524  {
525  clear();
526 
527  // Updating the global vars
528 
529  m_maxTmpFileSize = maxTmpFileSize;
530  m_maxMemPercentUsage = maxMemPercentUsage;
531  m_memoryPolicy = memoryPolicy;
532 
533  /* Update the old buffer if necessary */
534 
535  if( ( lines > 0 ) && ( columns > 0 ) )
536  {
537  try
538  {
539  // Updating the global vars
540 
541  m_totalLines = lines;
542  m_totalColumns = columns;
543 
544  const unsigned int lineSizeBytes = (unsigned int)(
545  sizeof( TemplateElementType ) * m_totalColumns );
546 
547  // Allocating the lines pointers vectpr
548 
549  m_allLinesPtrsVec.resize( m_totalLines, 0 );
550 
551  if( m_memoryPolicy == RAMMemPol )
552  {
553  m_ramLinesIndexesVec.resize( m_totalLines, 0 );
555 
556  TemplateElementType* newLinePtr = 0;
557 
558  for( unsigned int allLinesPtrsVecIdx = 0 ; allLinesPtrsVecIdx <
559  m_totalLines ; ++allLinesPtrsVecIdx )
560  {
561  newLinePtr = new TemplateElementType[ m_totalColumns ];
562 
563  m_memoryblocksHandler[ allLinesPtrsVecIdx ] = newLinePtr;
564 
565  m_allLinesPtrsVec[ allLinesPtrsVecIdx ] = newLinePtr;
566 
567  m_ramLinesIndexesVec[ allLinesPtrsVecIdx ] = allLinesPtrsVecIdx;
568  }
569  }
570  else
571  { // AutoMemPol, DiskMemPol
572 
573  // Allocating the swap line pointer
574 
575  m_swapMemoryBlockHandler.reset( new TemplateElementType[ m_totalColumns ] );
577 
578  // Defining the number of max RAM lines
579 
580  unsigned int maxRAMLines = 1;
581 
582  if( m_memoryPolicy == AutoMemPol )
583  {
584  // Defining the max number of RAM tiles
585 
586  const double totalPhysMem = (double)te::common::GetTotalPhysicalMemory();
587 
588  const double usedVMem = (double)te::common::GetUsedVirtualMemory();
589 
590  const double totalVMem = (double)te::common::GetTotalVirtualMemory();
591 
592  const double freeVMem = MIN( totalPhysMem,
593  ( totalVMem - usedVMem ) );
594 
595  const double linesMem = ( ((double)m_maxMemPercentUsage) / 100.0 ) *
596  freeVMem;
597 
598  maxRAMLines = (unsigned int)MAX( 1.0, linesMem /
599  ((double)lineSizeBytes) );
600  }
601 
602  // Allocating RAM lines
603 
604  const unsigned int ramLinesIndexesVecSize = MIN( maxRAMLines,
605  m_totalLines );
606 
607  m_ramLinesIndexesVec.resize( ramLinesIndexesVecSize, 0 );
608  m_memoryblocksHandler.resize( ramLinesIndexesVecSize );
609 
610  TemplateElementType* newLinePtr = 0;
611 
612  for( unsigned int allLinesPtrsVecIdx = 0 ; allLinesPtrsVecIdx <
613  ramLinesIndexesVecSize ; ++allLinesPtrsVecIdx )
614  {
615  newLinePtr = new TemplateElementType[ m_totalColumns ];
616 
617  m_memoryblocksHandler[ allLinesPtrsVecIdx ] = newLinePtr;
618 
619  m_allLinesPtrsVec[ allLinesPtrsVecIdx ] = newLinePtr;
620 
621  m_ramLinesIndexesVec[ allLinesPtrsVecIdx ] = allLinesPtrsVecIdx;
622  }
623 
624  // Allocating Disk lines
625 
626  if( ! allocateDiskLines( ramLinesIndexesVecSize ) )
627  {
628  clear();
629  TERP_LOG_AND_RETURN_FALSE( "Tiles allocation error" )
630  }
631  }
632  }
633  catch(...)
634  {
635  clear();
636 
637  TERP_LOG_AND_RETURN_FALSE( "Tiles allocation error" )
638  }
639  }
640 
641  return true;
642  }
643 
644  template< typename TemplateElementType >
646  {
647  TemplateElementType* linePtr = 0;
648  for( unsigned int memoryblocksHandlerIdx = 0 ; memoryblocksHandlerIdx <
649  m_memoryblocksHandler.size() ; ++memoryblocksHandlerIdx )
650  {
651  linePtr = m_memoryblocksHandler[ memoryblocksHandlerIdx ];
652 
653  if( linePtr )
654  {
655  delete[] ( linePtr );
656  }
657  }
658  m_memoryblocksHandler.clear();
659 
660  m_allLinesPtrsVec.clear();
661 
662  m_openDiskFilesHandler.clear();
663 
664  m_diskLinesInfoVec.clear();
665 
666  m_ramLinesIndexesVec.clear();
667 
668  m_swapMemoryBlockHandler.reset();
669 
670  init();
671  }
672 
673  template< typename TemplateElementType >
675  {
676  return m_totalLines;
677  }
678 
679 
680  template< typename TemplateElementType >
682  {
683  return m_totalColumns;
684  }
685 
686 
687  template< typename TemplateElementType >
689  {
690  return ( m_totalLines == 0 ) ? true : false;
691  }
692 
693  template< typename TemplateElementType >
695  const Matrix< TemplateElementType >& external )
696  {
698  reset( external.m_totalLines, external.m_totalColumns,
700  "Unable to initiate the matrix object" );
701 
702  unsigned int column = 0;;
703  TemplateElementType const* inLinePtr = 0;
704  TemplateElementType* outLinePtr = 0;
705 
706  for( unsigned int line = 0 ; line < m_totalLines ; ++line )
707  {
708  inLinePtr = external.getScanLine( line );
709  outLinePtr = getScanLine( line );
710 
711  for( column = 0 ; column < m_totalColumns ; ++column ) {
712  outLinePtr[ column ] = inLinePtr[ column ];
713  }
714  }
715 
716  return *this;
717  }
718 
719  template< typename TemplateElementType >
721  {
722  return m_memoryPolicy;
723  }
724 
725  template< typename TemplateElementType >
727  {
728  return m_maxTmpFileSize;
729  }
730 
731  template< typename TemplateElementType >
733  {
734  return m_maxMemPercentUsage;
735  }
736 
737  template< typename TemplateElementType >
738  bool Matrix< TemplateElementType >::allocateDiskLines( unsigned int startingLineIdx )
739  {
740  const unsigned long int diskLinesNmb = m_totalLines - startingLineIdx;
741 
742  if( diskLinesNmb )
743  {
744  const unsigned long int lineSizeBytes = (unsigned long int)(
745  sizeof( TemplateElementType ) * m_totalColumns );
746 
747  const unsigned long int maxLinesPerFile = ( unsigned long int )
748  floor( ( (double)m_maxTmpFileSize ) / ( (double) lineSizeBytes ) );
749 
750  const unsigned long int maxFileSize = (unsigned long int)
751  ( maxLinesPerFile * lineSizeBytes );
752 
753  const unsigned int openDiskFilesNumber = (unsigned int)ceil( ((double)diskLinesNmb)
754  / ((double)maxLinesPerFile) );
755 
756  // Allocating each file
757 
759 
760  unsigned int remainingLinesNmb = diskLinesNmb;
761  unsigned int fileSize = 0;
762  unsigned int fileLinesNumber = 0;
763  unsigned int diskLinesVecIdx = startingLineIdx;
764 
765  for( unsigned int fileIdx = 0 ; fileIdx < openDiskFilesNumber ;
766  ++fileIdx )
767  {
768  // Defining the current file size
769 
770  fileSize = maxFileSize;
771  fileLinesNumber = maxLinesPerFile;
772 
773  if( remainingLinesNmb < maxLinesPerFile )
774  {
775  fileSize = (unsigned long int)( lineSizeBytes * remainingLinesNmb );
776  fileLinesNumber = remainingLinesNmb;
777  }
778 
779  remainingLinesNmb -= fileLinesNumber;
780 
781  // allocating the temporary file
782 
783  FILE* newFilePtr = 0;
784  std::string newFullFileName;
785 
786  if( ! createNewDiskFile( fileSize, &( newFilePtr ), newFullFileName ) )
787  {
788  TERP_LOGERR( "Unable to create temporary disk file" );
789  return false;
790  }
791  else
792  {
794  m_openDiskFilesHandler.back().m_filePtr = newFilePtr;
795  m_openDiskFilesHandler.back().m_fullFileName = newFullFileName;
796 
797  for( unsigned int lineIdx = 0; lineIdx < fileLinesNumber ; ++lineIdx )
798  {
799  m_diskLinesInfoVec[ diskLinesVecIdx ].m_filePtr = newFilePtr;
800  m_diskLinesInfoVec[ diskLinesVecIdx ].m_fileOff = lineIdx *
801  lineSizeBytes;
802 
803  ++diskLinesVecIdx;
804  }
805  }
806  }
807  }
808 
809  return true;
810  }
811 
812  template< typename TemplateElementType >
813  TemplateElementType*
814  Matrix< TemplateElementType >::getScanLine( const unsigned int& line ) const
815  {
816  TERP_DEBUG_TRUE_OR_THROW( line < m_totalLines, "Invalid tile index" );
817 
818  if( m_allLinesPtrsVec[ line ] )
819  {
820  return m_allLinesPtrsVec[ line ];
821  }
822  else
823  {
824  // Finding the swap line index
825 
827  m_ramLinesIndexesVec.size(), "Internal error" );
828  const unsigned int swapLineIdx = m_ramLinesIndexesVec[
830 
831  TERP_DEBUG_TRUE_OR_THROW( line < m_diskLinesInfoVec.size(), "Internal error" );
832  DiskLineInfo& inLineData = m_diskLinesInfoVec[ line ];
833 
834  TERP_DEBUG_TRUE_OR_THROW( swapLineIdx < m_diskLinesInfoVec.size(),
835  "Internal error" )
836  DiskLineInfo& outLineData = m_diskLinesInfoVec[
837  swapLineIdx ];
838 
839  /* Reading the required tile into RAM */
840 
841  TERP_DEBUG_TRUE_OR_THROW( inLineData.m_filePtr, "Internal error" );
842  TERP_TRUE_OR_THROW( 0 == fseek( inLineData.m_filePtr,
843  (long)( inLineData.m_fileOff ), SEEK_SET ),
844  "File seek error" )
845 
846  TERP_DEBUG_TRUE_OR_THROW( m_currentSwapTilePtr, "Internal error" );
847  TERP_TRUE_OR_THROW( 1 == fread( (void*)m_currentSwapTilePtr,
848  (size_t)( sizeof( TemplateElementType ) * m_totalColumns ), 1, inLineData.m_filePtr ),
849  "File read error" )
850 
851  /* Flushing the choosed tile to disk */
852 
853  TERP_TRUE_OR_THROW( 0 == fseek( inLineData.m_filePtr,
854  (long)( inLineData.m_fileOff ), SEEK_SET ),
855  "File seek error" );
856 
857  TERP_DEBUG_TRUE_OR_THROW( swapLineIdx < m_allLinesPtrsVec.size(),
858  "Internal error" );
859  TERP_TRUE_OR_THROW( 1 == fwrite( (void*)m_allLinesPtrsVec[
860  swapLineIdx ],
861  (size_t)( sizeof( TemplateElementType ) * m_totalColumns ), 1,
862  inLineData.m_filePtr ), "File write error" )
863 
864  // Updating the tile pointers
865 
866  TemplateElementType* linePtr = m_allLinesPtrsVec[ swapLineIdx ];
867 
868  m_allLinesPtrsVec[ swapLineIdx ] = 0;
869 
871 
872  m_currentSwapTilePtr = linePtr;
873 
874  /* Updating the info vectors */
875 
876  outLineData.m_filePtr = inLineData.m_filePtr;
877  outLineData.m_fileOff = inLineData.m_fileOff;
878 
879  inLineData.m_filePtr = 0;
880  inLineData.m_fileOff = 0;
881 
885  m_ramLinesIndexesVec.size() );
887  m_ramLinesIndexesVec.size(), "Internal error" );
888 
889  return m_allLinesPtrsVec[ line ];
890  }
891  }
892 
893  template< typename TemplateElementType >
895  FILE** fileptr, std::string& fullFileName ) const
896  {
897  // trying to use the system temp path
898 
899  bool returnValue = true;
900  long seekoff = (long)size;
901  const boost::filesystem::path randShortFileNamePath(
902  "TerralibRPMatrix_%%%%-%%%%-%%%%-%%%%" );
903  const unsigned char c = '\0';
904 
905  fullFileName = te::core::FileSystem::uniquePath(
906  (boost::filesystem::path(te::core::GetUserDirectory()) /=
907  randShortFileNamePath).string());
908 
909  if( fullFileName.empty() )
910  {
911  returnValue = false;
912  }
913  else
914  {
915  try
916  {
917  (*fileptr) = std::fopen( te::core::CharEncoding::fromUTF8(fullFileName).c_str(), "wb+" );
918  if( (*fileptr) == 0 )
919  {
920  returnValue = false;
921  }
922  else
923  {
924  if( std::fseek( (*fileptr), seekoff, SEEK_SET ) != 0 )
925  {
926  std::fclose( (*fileptr) );
927  std::remove( fullFileName.c_str() );
928  returnValue = false;
929  }
930  else
931  {
932  if( 1 != std::fwrite( &c, 1, 1, (*fileptr) ) )
933  {
934  std::fclose( (*fileptr) );
935  std::remove( fullFileName.c_str() );
936  returnValue = false;
937  }
938  }
939  }
940  }
941  catch(...)
942  {
943  if( (*fileptr) )
944  {
945  std::fclose( (*fileptr) );
946  }
947 
948  std::remove( fullFileName.c_str() );
949  returnValue = false;
950  }
951  }
952 
953  // trying to use the user home path
954 
955  if( ! returnValue )
956  {
957  fullFileName = te::core::FileSystem::uniquePath(
958  (boost::filesystem::path(te::core::GetUserDirectory()) /=
959  randShortFileNamePath).string());
960 
961  if( fullFileName.empty() )
962  {
963  returnValue = false;
964  }
965  else
966  {
967  try
968  {
969  (*fileptr) = std::fopen( te::core::CharEncoding::fromUTF8(fullFileName).c_str(), "wb+" );
970  if( (*fileptr) == 0 )
971  {
972  returnValue = false;
973  }
974  else
975  {
976  if( std::fseek( (*fileptr), seekoff, SEEK_SET ) != 0 )
977  {
978  std::fclose( (*fileptr) );
979  std::remove( fullFileName.c_str() );
980  returnValue = false;
981  }
982  else
983  {
984  if( 1 != std::fwrite( &c, 1, 1, (*fileptr) ) )
985  {
986  std::fclose( (*fileptr) );
987  std::remove( fullFileName.c_str() );
988  returnValue = false;
989  }
990  }
991  }
992  }
993  catch(...)
994  {
995  if( (*fileptr) )
996  {
997  std::fclose( (*fileptr) );
998  }
999 
1000  std::remove( fullFileName.c_str() );
1001  returnValue = false;
1002  }
1003  }
1004  }
1005 
1006  return returnValue;
1007  }
1008  } //namespace rp
1009  } // namespace te
1010 #endif //__TERRALIB_RP_INTERNAL_MATRIX_H
1011 
TECOMMONEXPORT unsigned long long int GetTotalVirtualMemory()
Returns the amount of total virtual memory (bytes) that can be claimed by the current process (physic...
void clear()
Clear all allocated resources and go back to the initial default parameters.
Definition: Matrix.h:645
unsigned int m_fileOff
The offset within the file.
Definition: Matrix.h:296
static std::string uniquePath(const std::string &format="%%%%-%%%%-%%%%-%%%%")
Retrives an unique path generated by a given format.
FILE * m_filePtr
The file pointer.
Definition: Matrix.h:294
unsigned char m_maxMemPercentUsage
the max amount of free memory to use when necessary.
Definition: Matrix.h:327
unsigned char getMaxMemPercentUsage() const
Returns the max amount of free memory to use when necessary.
Definition: Matrix.h:732
std::vector< DiskLineInfo > m_diskLinesInfoVec
Info of all lines, used when a line is on disk.
Definition: Matrix.h:371
#define MIN(a, b)
Macro that returns min between two values.
#define TERP_LOGERR(message)
Logs an error message.
Definition: Macros.h:117
const TemplateElementType & operator()(const unsigned int &line, const unsigned int &column) const
Operator () overload.
Definition: Matrix.h:223
TemplateElementType & operator()(const unsigned int &line, const unsigned int &column)
Operator () overload.
Definition: Matrix.h:206
bool allocateDiskLines(unsigned int startingLineIdx)
Allocate disk lines.
Definition: Matrix.h:738
Disk lines info.
Definition: Matrix.h:290
#define MAX(a, b)
Macro that returns max between two values.
void init()
Reset the internal variables to the initial state.
Definition: Matrix.h:450
TECOMMONEXPORT unsigned long long int GetTotalPhysicalMemory()
Returns the amount of total physical memory (bytes).
MemoryPolicy m_memoryPolicy
The used memory policy (default:RAMMemPol).
Definition: Matrix.h:342
MemoryPolicy getMemPolicy() const
Returns the current memory policy.
Definition: Matrix.h:720
unsigned long int m_maxTmpFileSize
Max bytes per temp file (for swapped tiles only, default: 2GB).
Definition: Matrix.h:322
TECOREEXPORT std::string GetUserDirectory()
Returns the system user home dir path.
std::vector< unsigned int > m_ramLinesIndexesVec
The indexes of all lines loaded into RAM.
Definition: Matrix.h:376
MemoryPolicy
Memory polycy.
Definition: Matrix.h:65
std::vector< TemplateElementType * > m_allLinesPtrsVec
A vector with pointers to all lines.
Definition: Matrix.h:361
unsigned int getColumnsNumber() const
The number of current matrix columns.
Definition: Matrix.h:681
Openend disk files info node.
Definition: Matrix.h:306
unsigned int m_totalColumns
The total columns number (default:0).
Definition: Matrix.h:337
const Matrix< TemplateElementType > & operator=(const Matrix< TemplateElementType > &external)
Operator = overload.
Definition: Matrix.h:694
URI C++ Library.
TECOMMONEXPORT unsigned long long int GetUsedVirtualMemory()
Returns the amount of used virtual memory (bytes) for the current process (physical + swapped)...
unsigned long int getMaxTmpFileSize() const
Returns the current maximum temporary disk file size.
Definition: Matrix.h:726
static std::string fromUTF8(const std::string &src)
Convert a string in UTF-8 to the current locale encoding.
std::vector< OpenDiskFileHandler > m_openDiskFilesHandler
A vector with open disk files handler.
Definition: Matrix.h:366
void reset()
Reset (clear) the active instance data.
Definition: Matrix.h:483
TemplateElementType * getScanLine(const unsigned int &line) const
Returns a pointer to the required line.
Definition: Matrix.h:814
#define TERP_LOG_AND_RETURN_FALSE(message)
Logs a warning message will and return false.
Definition: Macros.h:237
TemplateElementType const * operator[](const unsigned int &line) const
Operator [] overload.
Definition: Matrix.h:261
std::vector< TemplateElementType * > m_memoryblocksHandler
Definition: Matrix.h:356
A generic template matrix.
Definition: Matrix.h:54
TemplateElementType ElementTypeT
Public matrix element type definition.
Definition: Matrix.h:60
FILE * m_filePtr
The file pointer.
Definition: Matrix.h:310
TemplateElementType * m_currentSwapTilePtr
A pointer to the current swap tile.
Definition: Matrix.h:354
unsigned int m_nextSwapLineRamLinesIndexesVecIdx
The index inside ramLinesIndexesVec_ of the next RAM line index that will be swapped to disk when a d...
Definition: Matrix.h:349
bool createNewDiskFile(unsigned long int size, FILE **fileptr, std::string &fullFileName) const
Create a new disk file.
Definition: Matrix.h:894
#define TERP_DEBUG_TRUE_OR_THROW(value, message)
Checks if value is true and throws an exception if not.
Definition: Macros.h:357
std::string m_fullFileName
The full created file name.
Definition: Matrix.h:312
bool isEmpty() const
Empty Matrix verification.
Definition: Matrix.h:688
unsigned int m_totalLines
The total lines number (default:0).
Definition: Matrix.h:332
virtual ~Matrix()
Definition: Matrix.h:477
unsigned int getLinesNumber() const
The number of current matrix lines.
Definition: Matrix.h:674
TemplateElementType * operator[](const unsigned int &line)
Operator [] overload.
Definition: Matrix.h:244
#define TERP_TRUE_OR_THROW(value, message)
Checks if value is true and throws an exception if not.
Definition: Macros.h:150
boost::scoped_array< TemplateElementType > m_swapMemoryBlockHandler
An auxiliar line used when swapping data to/from disk.
Definition: Matrix.h:382