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