id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,540,964
|
PtPPTBFLoader.hpp
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtPPTBFLoader.hpp
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
/******************************************************************************
***************************** METHOD DEFINITION ******************************
******************************************************************************/
namespace Pt
{
} // namespace Pt
| 719
|
C++
|
.h
| 21
| 32.333333
| 84
| 0.269452
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,965
|
PtFeature.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtFeature.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_FEATURE_H_
#define _PT_FEATURE_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtConfig.h"
// STL
#include <vector>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
namespace Pt
{
class PtWindow;
class PtFeature;
}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace Pt
{
/**
* @class PtFeature
*
* @brief The PtFeature class provides interface to the "best matching tile selection" stage.
*
* The best matching tile selection occurs during the final texture synthesis stage:
* - for each tile of a given composition map, a list of candidate tiles matching some features/characteristics is determined,
* - the selector job is to select the best one among all acandidates.
*/
class PTMODEL_EXPORT PtFeature
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
/**
* Constructor
*/
PtFeature();
/**
* Destructor
*/
virtual ~PtFeature();
/**
* Initialize
*/
void initialize();
/**
* Finalize
*/
void finalize();
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/**
* Window function
*/
PtWindow* mWindow;
/**
* Feature function
*/
PtFeature* mFeature;
/******************************** METHODS *********************************/
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
}; // end of class PtFeature
} // end of namespace Pt
/******************************************************************************
******************************* INLINE SECTION ******************************
******************************************************************************/
#include "PtFeature.hpp"
#endif // _PT_FEATURE_H_
| 4,124
|
C++
|
.h
| 103
| 37.61165
| 127
| 0.263515
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,966
|
PtImageHelper.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtImageHelper.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_IMAGE_HELPER_H_
#define _PT_IMAGE_HELPER_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtConfig.h"
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace Pt
{
/**
* @class PtImageHelper
*
* @brief The PtImageHelper class provides interface to the "best matching tile selection" stage.
*
* The best matching tile selection occurs during the final texture synthesis stage:
* - for each tile of a given composition map, a list of candidate tiles matching some features/characteristics is determined,
* - the selector job is to select the best one among all acandidates.
*/
class PTMODEL_EXPORT PtImageHelper
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
// Load/Save image
static void loadImage( const char* pFilename, int& pWidth, int& pHeight, int& pNrChannels, unsigned char*& pData, int desired_channels = 0 );
static int saveImage( const char* pFilename, const int pWidth, const int pHeight, const int pNrChannels, const void* pData );
static void freeImage( unsigned char* pData );
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
}; // end of class PtImageHelper
} // end of namespace Pt
/******************************************************************************
******************************* INLINE SECTION ******************************
******************************************************************************/
#endif // _PT_IMAGE_HELPER_H_
| 4,106
|
C++
|
.h
| 75
| 52.346667
| 142
| 0.276596
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,967
|
PtWindow.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtWindow.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_WINDOW_H_
#define _PT_WINDOW_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtConfig.h"
// STL
#include <vector>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
namespace Pt
{
class PtWindow;
class PtFeature;
}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace Pt
{
/**
* @class PtWindow
*
* @brief The PtWindow class provides interface to the "best matching tile selection" stage.
*
* The best matching tile selection occurs during the final texture synthesis stage:
* - for each tile of a given composition map, a list of candidate tiles matching some features/characteristics is determined,
* - the selector job is to select the best one among all acandidates.
*/
class PTMODEL_EXPORT PtWindow
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
/**
* Constructor
*/
PtWindow();
/**
* Destructor
*/
virtual ~PtWindow();
/**
* Initialize
*/
void initialize();
/**
* Finalize
*/
void finalize();
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/**
* Window function
*/
PtWindow* mWindow;
/**
* Feature function
*/
PtFeature* mFeature;
/******************************** METHODS *********************************/
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
}; // end of class PtWindow
} // end of namespace Pt
/******************************************************************************
******************************* INLINE SECTION ******************************
******************************************************************************/
#include "PtWindow.hpp"
#endif // _PT_WINDOW_H_
| 4,114
|
C++
|
.h
| 103
| 37.514563
| 127
| 0.261659
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,968
|
PtPPTBFLoader.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtPPTBFLoader.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_PPTBF_LOADER_H_
#define _PT_PPTBF_LOADER_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtConfig.h"
// Project
#include "PtPPTBF.h"
// STL
#include <vector>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
//namespace Pt
//{
// class PtPPTBF;
//}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace Pt
{
/**
* @class PtPPTBFLoader
*
* @brief The PtPPTBFLoader class provides interface to the "best matching tile selection" stage.
*
* The best matching tile selection occurs during the final texture synthesis stage:
* - for each tile of a given composition map, a list of candidate tiles matching some features/characteristics is determined,
* - the selector job is to select the best one among all acandidates.
*/
class PTMODEL_EXPORT PtPPTBFLoader
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
// Point process
PtPPTBF::tilingtype pTilingType;
float pJittering;
float pCellSubdivisionProbability;
int pNbRelaxationIterations;
// Window function
float pCellularToGaussianWindowBlend;
float pCellularWindowNorm;
float pRectangularToVoronoiShapeBlend;
float pCellularWindowDecay;
float pGaussianWindowDecay;
float pGaussianWindowDecayJittering;
// Feature function
int pMinNbGaborKernels;
int pMaxNbGaborKernels;
float pFeatureNorm;
int pGaborStripesFrequency;
float pGaborStripesCurvature;
float pGaborStripesOrientation;
float pGaborStripesThickness;
float pGaborDecay;
float pGaborDecayJittering;
float pFeaturePhaseShift;
bool pBombingFlag;
// Deformation
float turbulenceA0;
float turbulenceA1;
float turbulenceA2;
// Others
float pRecursiveWindowSubdivisionProbability;
float pRecursiveWindowSubdivisionScale;
// Debug
bool pShowWindow;
bool pShowFeature;
/******************************** METHODS *********************************/
/**
* Constructor
*/
PtPPTBFLoader();
/**
* Destructor
*/
virtual ~PtPPTBFLoader();
/**
* Initialize
*/
void initialize();
/**
* Finalize
*/
void finalize();
/**
* Read file
*/
PtPPTBF* import( const char* pFilename );
/**
* Write file
*/
void write( const PtPPTBF* pDataModel, const char* pFilename );
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
}; // end of class PtPPTBFLoader
} // end of namespace Pt
/******************************************************************************
******************************* INLINE SECTION ******************************
******************************************************************************/
#include "PtPPTBFLoader.hpp"
#endif // _PT_PPTBF_LOADER_H_
| 5,142
|
C++
|
.h
| 138
| 34.956522
| 127
| 0.379714
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,969
|
PtPPTBF.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtPPTBF.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_PPTBF_H_
#define _PT_PPTBF_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtConfig.h"
// STL
#include <vector>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
namespace Pt
{
class PtWindow;
class PtFeature;
class PtNoise;
}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace Pt
{
/**
* @class PtPPTBF
*
* @brief The PtPPTBF class provides interface to the "best matching tile selection" stage.
*
* The best matching tile selection occurs during the final texture synthesis stage:
* - for each tile of a given composition map, a list of candidate tiles matching some features/characteristics is determined,
* - the selector job is to select the best one among all acandidates.
*/
class PTMODEL_EXPORT PtPPTBF
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* INNER TYPES *******************************/
/**
* Tiling type
*/
typedef enum
{
REGULAR, IRREGULAR, CROSS, BISQUARE, IRREGULARX, IRREGULARY
}
tilingtype;
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
/**
* Constructor
*/
PtPPTBF();
/**
* Destructor
*/
virtual ~PtPPTBF();
/**
* Initialize
*/
void initialize();
/**
* Finalize
*/
void finalize();
inline const PtWindow* const getWindow() const;
inline const PtFeature* const getFeature() const;
inline const PtNoise* const getNoise() const;
/**
* Evaluate PPTBF
*/
float eval( const float x, const float y,
// Point process
const PtPPTBF::tilingtype pTilingType, const float pJittering, const float pCellSubdivisionProbability, const int pNbRelaxationIterations,
// Window function
const float pCellularToGaussianWindowBlend, /*const*/ float pCellularWindowNorm, const float pRectangularToVoronoiShapeBlend, const float pCellularWindowDecay, const float pGaussianWindowDecay, const float pGaussianWindowDecayJittering,
// Feature function
const int pMinNbGaborKernels, const int pMaxNbGaborKernels, /*const*/ float pFeatureNorm, const int pGaborStripesFrequency, const float pGaborStripesCurvature, const float pGaborStripesOrientation, const float pGaborStripesThickness, const float pGaborDecay, const float pGaborDecayJittering, const float pFeaturePhaseShift, const bool pBombingFlag,
// Others
const float pRecursiveWindowSubdivisionProbability, const float pRecursiveWindowSubdivisionScale,
// Debug
const bool pShowWindow = true, const bool pShowFeature = true );
/**
* ...
*/
/*inline*/ static float getNorm( float inorm );
/**
* PPTBF size
*/
inline int getWidth() const;
inline void setWidth( const int pValue );
inline int getHeight() const;
inline void setHeight( const int pValue );
// Model Transform
inline int getResolution() const;
inline void setResolution( const int pValue );
inline float getShiftX() const;
inline void setShiftX( const float pValue );
inline float getShiftY() const;
inline void setShiftY( const float pValue );
inline float getAlpha() const;
inline void setAlpha( const float pValue );
inline float getRescalex() const;
inline void setRescalex( const float pValue );
// Deformation
inline float getTurbulenceAmplitude0() const;
inline void setTurbulenceAmplitude0( const float pValue );
inline float getTurbulenceAmplitude1() const;
inline void setTurbulenceAmplitude1( const float pValue );
inline float getTurbulenceAmplitude2() const;
inline void setTurbulenceAmplitude2( const float pValue );
// Point process
inline int getTilingType() const;
inline float getJittering() const;
inline float getCellSubdivisionProbability() const;
inline int getNbRelaxationIterations() const;
inline void setTilingType( const int pValue );
inline void setJittering( const float pValue );
inline void setCellSubdivisionProbability( const float pValue );
inline void setNbRelaxationIterations( const int pValue );
// Window function
inline void setCellularToGaussianWindowBlend( const float pValue );
// - cellular window
inline float getRectangularToVoronoiShapeBlend() const;
inline void setRectangularToVoronoiShapeBlend( const float pValue );
inline float getCellularWindowDecay() const;
inline void setCellularWindowDecay( const float pValue );
inline float getCellularWindowNorm() const;
inline void setCellularWindowNorm( const float pValue );
// - Gaussian window
inline int getWindowShape() const;
inline void setWindowShape( const int pValue );
inline float getWindowArity() const;
inline void setWindowArity( const float pValue );
inline float getWindowLarp() const;
inline void setWindowLarp( const float pValue );
inline float getWindowNorm() const;
inline void setWindowNorm( const float pValue );
inline float getWindowSmooth() const;
inline void setWindowSmooth( const float pValue );
inline float getWindowBlend() const;
inline void setWindowBlend( const float pValue );
inline float getWindowSigwcell() const;
inline void setWindowSigwcell( const float pValue );
inline void setGaussianWindowDecay( const float pValue );
inline void setGaussianWindowDecayJittering( const float pValue );
// Feature function
inline int getBombingFlag() const;
inline void setBombingFlag( const int pValue );
inline float getFeatureNorm() const;
inline void setFeatureNorm( const float pValue );
inline float getFeatureWinfeatcorrel() const;
inline void setFeatureWinfeatcorrel( const float pValue );
inline float getFeatureAnisotropy() const;
inline void setFeatureAnisotropy( const float pValue );
inline int getMinNbGaborKernels() const;
inline void setMinNbGaborKernels( const int pValue );
inline int getMaxNbGaborKernels() const;
inline void setMaxNbGaborKernels( const int pValue );
inline float getGaborDecay() const;
inline void setGaborDecay( const float pValue );
inline float getGaborDecayJittering() const;
inline void setGaborDecayJittering( const float pValue );
inline int getGaborStripesFrequency() const;
inline void setGaborStripesFrequency( const int pValue );
inline float getFeaturePhaseShift() const;
inline void setFeaturePhaseShift( const float pValue );
inline float getGaborStripesThickness() const;
inline void setGaborStripesThickness( const float pValue );
inline float getGaborStripesCurvature() const;
inline void setGaborStripesCurvature( const float pValue );
inline float getGaborStripesOrientation() const;
inline void setGaborStripesOrientation( const float pValue );
// Recursivity
inline void setRecursiveWindowSubdivisionProbability( const float pValue );
inline void setRecursiveWindowSubdivisionScale( const float pValue );
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/**
* Window function
*/
PtWindow* mWindow;
/**
* Feature function
*/
PtFeature* mFeature;
/**
* Noise
*/
PtNoise* mNoise;
/**
* PPTBF size
*/
int mWidth;
int mHeight;
// Model Transform
int mResolution;
float mShiftX;
float mShiftY;
float mAlpha;
float mRescalex;
// Deformation
float mTurbulenceAmplitude0;
float mTurbulenceAmplitude1;
float mTurbulenceAmplitude2;
// Point process
PtPPTBF::tilingtype mTilingType;
float mJittering;
float mCellSubdivisionProbability;
int mNbRelaxationIterations;
// Window function
float mCellularToGaussianWindowBlend;
float mCellularWindowNorm;
float mRectangularToVoronoiShapeBlend;
float mCellularWindowDecay;
int mWindowShape; // new: type of window function [0,3] (blended tapered cos, Gauss, triang, tapered cos)
float mWindowArity; // >=2.0 && <=5.0, arity of polygonal cell window
float mWindowLarp; // anisotropy of cell for cellular window
float mWindowNorm; // norm 1=L1, 2=L2, 3=Linf of cellular window
float mWindowSmooth; // smoothness of cellular 0=linear, 1 or 2=Bezier
float mWindowBlend; // blend between cellular=1 and classical window=0
float mWindowSigwcell; // power of cellular window
float mGaussianWindowDecay;
float mGaussianWindowDecayJittering;
// Feature function
int mBombingFlag;
float mFeatureNorm;
float mFeatureWinfeatcorrel;
float mFeatureAnisotropy;
int mMinNbGaborKernels;
int mMaxNbGaborKernels;
float mGaborDecay; // uFeatureSigcos
float mGaborDecayJittering; // uFeatureSigcosvar
int mGaborStripesFrequency;
float mFeaturePhaseShift;
float mGaborStripesThickness;
float mGaborStripesCurvature;
float mGaborStripesOrientation;
// Recursivity
float mRecursiveWindowSubdivisionProbability;
float mRecursiveWindowSubdivisionScale;
/******************************** METHODS *********************************/
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
}; // end of class PtPPTBF
} // end of namespace Pt
/******************************************************************************
******************************* INLINE SECTION ******************************
******************************************************************************/
#include "PtPPTBF.hpp"
#endif // _PT_PPTBF_H_
| 11,255
|
C++
|
.h
| 278
| 38.169065
| 351
| 0.61272
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,970
|
PtConfig.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtConfig.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_CONFIG_H_
#define _PT_CONFIG_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtModelConfig.h"
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
// It seams to be used by "hview" library
// - TODO: modify this...
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif
// GLM
#define GLM_ENABLE_EXPERIMENTAL
#define GLM_FORCE_MESSAGES
#define GLM_FORCE_SWIZZLE
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
#endif // !_PT_CONFIG_H_
| 1,754
|
C++
|
.h
| 41
| 40.902439
| 84
| 0.266745
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,971
|
PtNoise.hpp
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtNoise.hpp
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
/******************************************************************************
***************************** METHOD DEFINITION ******************************
******************************************************************************/
namespace Pt
{
inline const std::vector< int >& PtNoise::getP()
{
return mP;
}
inline const std::vector< float >& PtNoise::getRndTab()
{
return mRndTab;
}
inline const std::vector< float >& PtNoise::getG()
{
return mG;
}
} // namespace Pt
| 932
|
C++
|
.h
| 33
| 26.454545
| 84
| 0.367003
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,972
|
PtEnvironment.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtEnvironment.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_ENVIRONMENT_H_
#define _PT_ENVIRONMENT_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtConfig.h"
// STL
#include <string>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
#define _OS_USE_VIEWER_REFRESH_
//#define _OS_USE_DEBUG_GL_
//#define _OS_USE_HOME_PATH_
#define _OS_USE_SHADER_DEBUG_
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
namespace Pt
{
class PTMODEL_EXPORT PtEnvironment
{
public:
static std::string mProgramPath;
static std::string mWorkingDirectory;
static std::string mSettingDirectory;
static std::string mDataPath;
static std::string mShaderPath;
static std::string mImagePath;
};
}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
#endif // !_PT_ENVIRONMENT_H_
| 1,954
|
C++
|
.h
| 51
| 36.490196
| 84
| 0.320975
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,973
|
PtNoise.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtModel/PtNoise.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_NOISE_H_
#define _PT_NOISE_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtConfig.h"
// STL
#include <vector>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace Pt
{
/**
* @class PtNoise
*
* @brief The PtNoise class provides interface to the "best matching tile selection" stage.
*
* The best matching tile selection occurs during the final texture synthesis stage:
* - for each tile of a given composition map, a list of candidate tiles matching some features/characteristics is determined,
* - the selector job is to select the best one among all acandidates.
*/
class PTMODEL_EXPORT PtNoise
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
/**
* Constructor
*/
PtNoise();
/**
* Destructor
*/
virtual ~PtNoise();
/**
* Initialize
*/
void initialize();
/**
* Finalize
*/
void finalize();
/**
* Evaluate PPTBF
*/
float eval();
inline static const std::vector< int >& getP();
inline static const std::vector< float >& getRndTab();
inline static const std::vector< float >& getG();
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/**
* Permutation table
*/
static const std::vector< int > mP;
/**
* rnd_tab
*/
static const std::vector< float > mRndTab;
/**
* G
*/
static const std::vector< float > mG;
/******************************** METHODS *********************************/
}; // end of class PtNoise
} // end of namespace Pt
/******************************************************************************
******************************* INLINE SECTION ******************************
******************************************************************************/
#include "PtNoise.hpp"
#endif // _PT_NOISE_H_
| 4,340
|
C++
|
.h
| 109
| 37.33945
| 127
| 0.278548
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,974
|
PtViewer.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtBDDParameterSpaceSampler/PtViewer.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Computer Graphics Forum (EGSR 2020 special issue)
* Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin
*
* Code author: Pascal Guehl
*/
/**
* @version 1.0
*/
#ifndef _OS_TEXTURE_SYNTHESIZER_VIEWER_H_
#define _OS_TEXTURE_SYNTHESIZER_VIEWER_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// GLFW
#include <glad/glad.h>
#include <GLFW/glfw3.h>
// Project
#include "PtViewerConfig.h"
#include "PtCamera.h"
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
// Project
namespace PtGraphics
{
class PtGraphicsPPTBF;
class PtGraphicsHistogram;
class PtGraphicsLBP;
}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace PtGUI
{
/**
* @class PtViewer
*
* @brief The PtViewer class provides ...
*
* ...
*/
class PtViewer
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* ATTRIBUTES *******************************/
/**
* Request: texture synthesis
*/
bool mLaunchRequest;
/**
* Request: texture synthesis
*/
bool mRequestLabelMapViewer;
/**
* ...
*/
void synthesize();
// Main variables
// Exemplar
std::string uiModelFilename;
bool uiTextureSynthesis_launch = false;
/**
* Flag to tell whether or not to display the user interface
*/
bool mShowUI;
/******************************** METHODS *********************************/
/**
* Constructor
*
* @param pTextureSynthesizer texture synthesizer manager
*/
PtViewer();
/**
* Destructor
*/
virtual ~PtViewer();
/**
* Finalize
*/
void finalize();
/**
* Graphics window
*/
GLFWwindow* getWindow();
/**
* Initialize Window
*/
void initializeWindow();
/**
* Initialize GL
*/
void initializeGL();
/**
* Handle requests
*/
void handleRequests();
/**
* Refresh
*/
void refresh();
/**
* Get PPTBF
*/
PtGraphics::PtGraphicsPPTBF* getPPTBF();
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* ATTRIBUTES *******************************/
/**
* Graphics window
*/
GLFWwindow* mWindow;
/**
* Camera
*/
PtGraphics::PtCamera* mCamera;
/**
* OpenGL and GLSL versions
*/
const GLubyte* mVendor;
const GLubyte* mRenderer;
const GLubyte* mVersion;
const GLubyte* mShadingLanguageVersion;
GLint mMajorVersion;
GLint mMinorVersion;
/**
* User interface parameters
*/
// - Point process parameters
int uiPointProcess_tilingType;
float uiPointProcess_cellSubdivisionProbability;
int uiPointProcess_nbRelaxationIterations;
float uiPointProcess_jittering;
// - Window function parameters
float uiWindowFunction_cellularVSGaussianWindowBlend;
float uiWindowFunction_rectangularToVoronoiShapeBlend;
float uiWindowFunction_cellularWindowDecay;
float uiWindowFunction_cellularWindowDecayVariation;
float uiWindowFunction_cellularWindowNorm;
int uiWindowFunction_windowShape;
float uiWindowFunction_windowArity;
float uiWindowFunction_windowLarp;
float uiWindowFunction_windowNorm;
float uiWindowFunction_windowSmooth;
float uiWindowFunction_windowBlend;
float uiWindowFunction_windowSigwcell;
float uiWindowFunction_gaussianWindowDecay;
float uiWindowFunction_gaussianWindowDecayVariation;
float uiWindowFunction_gaussianWindowNorm;
// - Feature function parameters
float uiFeatureFunction_featureNorm;
float uiFeatureFunction_winfeatcorrel; // new
float uiFeatureFunction_anisotropy; // new
int uiFeatureFunction_gaborMinNbKernels;
int uiFeatureFunction_gaborMaxNbKernels;
float uiFeatureFunction_gaborDecay;
float uiFeatureFunction_gaborDecayVariation;
float uiFeatureFunction_gaborStripesCurvature;
float uiFeatureFunction_gaborStripesOrientation;
float uiFeatureFunction_gaborStripesFrequency;
float uiFeatureFunction_gaborStripesThickness;
float uiFeatureFunction_featurePhaseShift;
// - Deformations, Non-Stationarity and_Mixtures parameters
glm::vec3 uiDefNonStaAndMix_spatialDeformation;
float uiDefNonStaAndMix_recursiveWindowSplittingProbability;
float uiDefNonStaAndMix_recursiveWindowSplittingScaleRatio;
// Global settings
int uiGlobalSettings_RESOL;
float uiGlobalSettings_alpha;
float uiGlobalSettings_rescalex;
// PPTBF
int uiPPTBF_bombingFlag;
bool uiPPTBF_animation;
bool uiPPTBF_megaKernel;
bool uiPPTBF_timer;
// Debug
bool uiGlobalSettings_useWindowFunction;
bool uiGlobalSettings_useFeatureFunction;
// Histograms
int uiBinaryStructureMap_nbBins;
int uiBinaryStructureMap_threshold;
/**
* Graphics objects
*/
PtGraphics::PtGraphicsPPTBF* mGraphicsPPTBF;
/**
* Histogram
*/
PtGraphics::PtGraphicsHistogram* mGraphicsHistogram;
/**
* UI edition flag
*/
bool mPPTBFUpdateRequested;
/**
* UI edition flag
*/
bool mHistogramUpdateRequested;
/**
* UI edition flag
*/
bool mUIShowHistogram;
float mBinaryStructureMapThreshold;
bool mUseRealTime;
// GPU timer
GLuint mQueryTimeElapsed;
GLuint64 mPPTBFGenerationTime;
/**
* LBP graphics manager
*/
PtGraphics::PtGraphicsLBP* mGraphicsLBP;
/**
* GL Core profile parameters
*/
bool mUseGLCoreProfile;
GLuint mGLCoreProfileVAO;
/******************************** METHODS *********************************/
/**
* ...
*/
static void window_close_callback( GLFWwindow* window );
/**
* ...
*/
static void window_size_callback( GLFWwindow* window, int width, int height );
/**
* ...
*/
static void framebuffer_size_callback( GLFWwindow* window, int width, int height );
/**
* Slot called when the data model has been modified
*/
virtual void onDataModelModified();
/**
* Callback called when PPTBF size has been modified
*/
void onSizeModified( const int pWidth, const int pHeight );
/**
* Initialize timer(s)
*/
void graphicsInitialization_Timer();
/**
* Finalize timer(s)
*/
void graphicsFinalization_Timer();
/**
* Initialize PPTBF
*/
void initializePPTBF( const int pWidth, const int pHeight );
/**
* Finalize PPTBF
*/
void finalizePPTBF();
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
};
}
#endif
| 7,932
|
C++
|
.h
| 273
| 26.593407
| 84
| 0.556713
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,975
|
PtViewerConfig.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtBDDParameterSpaceSampler/PtViewerConfig.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Computer Graphics Forum (EGSR 2020 special issue)
* Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin
*
* Code author: Pascal Guehl
*/
/**
* @version 1.0
*/
#ifndef _OS_VIEWER_CONFIG_H_
#define _OS_VIEWER_CONFIG_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// STL
#include <string>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
#define _OS_USE_VIEWER_REFRESH_
//#define _OS_USE_DEBUG_GL_
//#define _OS_USE_HOME_PATH_
#define _OS_USE_SHADER_DEBUG_
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
namespace Pt
{
//class PtEnvironment
//{
// static std::string mShaderPath;
// static std::string mImagePath;
// static std::string mProgramPath;
//};
}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
#endif // !_OS_VIEWER_CONFIG_H_
| 1,897
|
C++
|
.h
| 43
| 42.348837
| 84
| 0.28913
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,976
|
PtApplication.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtBDDParameterSpaceSampler/PtApplication.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Computer Graphics Forum (EGSR 2020 special issue)
* Authors: P. Guehl , R. AllEgre , J.-M. Dischler, B. Benes , and E. Galin
*
* Code author: Pascal Guehl
*/
/**
* @version 1.0
*/
#ifndef _PT_APPLICATION_H_
#define _PT_APPLICATION_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtViewerConfig.h"
//#include "PtPipelineManager.h"
// STL
#include <string>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
// Project
namespace PtGraphics
{
class PtGraphicsPPTBF;
}
namespace PtGUI
{
class PtViewer;
}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace PtGUI
{
/**
* @class PtApplication
*
* @brief The PtApplication class provides ...
*
* ...
*/
class PtApplication
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* INNER TYPES *******************************/
/**
* Type of pipeline request
*/
enum PtPipelineRequest
{
eLoadDataModel,
eSynthesizeTexture,
eUpdateTexture,
eRequestNbTypes
};
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
/**
* Get the unique instance.
*
* @return the unique instance
*/
static PtApplication& get();
/**
* Destructor.
*/
virtual ~PtApplication();
/**
* Initialize
*/
virtual bool initialize( const char* const pWorkingDirectory );
/**
* Finalize
*/
virtual void finalize();
/**
* Execute
* - main event loop
*/
virtual void execute();
/**
* Post a request
*/
void postRequest( PtPipelineRequest pRequest );
/**
* Get PPTBF
*/
PtGraphics::PtGraphicsPPTBF* getPPTBF();
/**
* BDD image parameters
*/
void setBDDImageWidth( const int pValue );
void setBDDImageHeight( const int pValue );
void setBDDImageDirectory( const char* pPath );
void setBDDSerieID( const int pValue );
void setPPTBFParameterFilename( const char* pPath );
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* ATTRIBUTES *******************************/
/**
* Main window
*/
PtViewer* mMainWindow;
/**
* Requests
*/
bool mOmniScaleModelUpdateRequested;
bool mTextureSynthesisRequested;
/**
* BDD image parameters
*/
int mBDDImageWidth;
int mBDDImageHeight;
std::string mBDDImageDirectory;
int mBDDserieID;
std::string mPPTBFParameterFilename;
/******************************** METHODS *********************************/
/**
* Initialize GLFW
*/
virtual void initializeGLFW();
/**
* Finalize GLFW
*/
virtual void finalizeGLFW();
/**
* Initialize windows
*/
virtual void initializeWindows();
/**
* Initialize GL library
*/
virtual void initializeGL();
/**
* Initialize ImGui user interface
*/
virtual void initializeImGuiUserInterface();
///**
// * Process Events
// */
//virtual void processEvents();
/**
* Handle requests
*/
virtual void handleRequests();
/**
* GLFW error callback
*/
static void error_callback( int error, const char* description );
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* ATTRIBUTES *******************************/
/**
* The unique instance
*/
static PtApplication* msInstance;
/******************************** METHODS *********************************/
/**
* Constructor
*/
PtApplication();
};
}
#endif
| 5,143
|
C++
|
.h
| 180
| 26.116667
| 84
| 0.397065
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,977
|
PtViewer.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtViewer/PtViewer.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _OS_TEXTURE_SYNTHESIZER_VIEWER_H_
#define _OS_TEXTURE_SYNTHESIZER_VIEWER_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// GLFW
#include <glad/glad.h>
#include <GLFW/glfw3.h>
// Project
#include "PtViewerConfig.h"
#include "PtCamera.h"
// STL
#include <vector>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
// Project
namespace PtGraphics
{
class PtGraphicsPPTBF;
class PtGraphicsHistogram;
class PtGraphicsMeshManager;
class PtShaderProgram;
}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace PtGUI
{
/**
* @class PtViewer
*
* @brief The PtViewer class provides ...
*
* ...
*/
class PtViewer
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* ATTRIBUTES *******************************/
/**
* Request: texture synthesis
*/
bool mLaunchRequest;
/**
* Request: texture synthesis
*/
bool mRequestLabelMapViewer;
/**
* ...
*/
void synthesize();
// Main variables
// Exemplar
std::string uiModelFilename;
bool uiTextureSynthesis_launch = false;
/**
* Flag to tell whether or not to display the user interface
*/
bool mShowUI;
/******************************** METHODS *********************************/
/**
* Constructor
*
* @param pTextureSynthesizer texture synthesizer manager
*/
PtViewer();
/**
* Destructor
*/
virtual ~PtViewer();
/**
* Finalize
*/
void finalize();
/**
* Render
*/
void render();
/**
* Graphics window
*/
GLFWwindow* getWindow();
/**
* ...
*/
static void mouse_button_callback( GLFWwindow* window, int button, int action, int mods );
/**
* ...
*/
static void cursor_position_callback( GLFWwindow* window, double xpos, double ypos );
/**
* Initialize Window
*/
void initializeWindow();
/**
* Initialize GL
*/
void initializeGL();
/**
* Handle requests
*/
void handleRequests();
/**
* Refresh
*/
void refresh();
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* ATTRIBUTES *******************************/
/**
* Graphics window
*/
GLFWwindow* mWindow;
/**
* Camera
*/
PtGraphics::PtCamera* mCamera;
/**
* OpenGL and GLSL versions
*/
const GLubyte* mVendor;
const GLubyte* mRenderer;
const GLubyte* mVersion;
const GLubyte* mShadingLanguageVersion;
GLint mMajorVersion;
GLint mMinorVersion;
/**
* User interface parameters
*/
// - Point process parameters
int uiPointProcess_tilingType;
float uiPointProcess_cellSubdivisionProbability;
int uiPointProcess_nbRelaxationIterations;
float uiPointProcess_jittering;
// - Window function parameters
float uiWindowFunction_cellularVSGaussianWindowBlend;
float uiWindowFunction_rectangularToVoronoiShapeBlend;
float uiWindowFunction_cellularWindowDecay;
float uiWindowFunction_cellularWindowDecayVariation;
float uiWindowFunction_cellularWindowNorm;
int uiWindowFunction_windowShape;
float uiWindowFunction_windowArity;
float uiWindowFunction_windowLarp;
float uiWindowFunction_windowNorm;
float uiWindowFunction_windowSmooth;
float uiWindowFunction_windowBlend;
float uiWindowFunction_windowSigwcell;
float uiWindowFunction_gaussianWindowDecay;
float uiWindowFunction_gaussianWindowDecayVariation;
float uiWindowFunction_gaussianWindowNorm;
// - Feature function parameters
float uiFeatureFunction_featureNorm;
float uiFeatureFunction_winfeatcorrel; // new
float uiFeatureFunction_anisotropy; // new
int uiFeatureFunction_gaborMinNbKernels;
int uiFeatureFunction_gaborMaxNbKernels;
float uiFeatureFunction_gaborDecay;
float uiFeatureFunction_gaborDecayVariation;
float uiFeatureFunction_gaborStripesCurvature;
float uiFeatureFunction_gaborStripesOrientation;
float uiFeatureFunction_gaborStripesFrequency;
float uiFeatureFunction_gaborStripesThickness;
float uiFeatureFunction_featurePhaseShift;
// - Deformations, Non-Stationarity and_Mixtures parameters
glm::vec3 uiDefNonStaAndMix_spatialDeformation;
float uiDefNonStaAndMix_recursiveWindowSplittingProbability;
float uiDefNonStaAndMix_recursiveWindowSplittingScaleRatio;
// Global settings
int uiGlobalSettings_RESOL;
float uiGlobalSettings_alpha;
float uiGlobalSettings_rescalex;
// PPTBF
int uiPPTBF_bombingFlag;
bool uiPPTBF_animation;
bool uiPPTBF_megaKernel;
bool uiPPTBF_timer;
// Debug
bool uiGlobalSettings_useWindowFunction;
bool uiGlobalSettings_useFeatureFunction;
// Histograms
int uiBinaryStructureMap_nbBins;
int uiBinaryStructureMap_threshold;
/**
* Graphics objects
*/
PtGraphics::PtGraphicsPPTBF* mGraphicsPPTBF;
/**
* Histogram
*/
PtGraphics::PtGraphicsHistogram* mGraphicsHistogram;
/**
* UI edition flag
*/
bool mPPTBFUpdateRequested;
/**
* UI edition flag
*/
bool mHistogramUpdateRequested;
/**
* UI edition flag
*/
bool mUIShowHistogram;
float mBinaryStructureMapThreshold;
bool mUseRealTime;
// GPU timer
GLuint mQueryTimeElapsed;
GLuint64 mPPTBFGenerationTime;
/**
* GL Core profile parameters
*/
bool mUseGLCoreProfile;
GLuint mGLCoreProfileVAO;
/**
* Mesh manager
*/
PtGraphics::PtGraphicsMeshManager* mGraphicsMeshManager;
/**
* Transfer fucntion
*/
GLuint mTransferFunctionTex;
std::vector< float > histogram; // todo: modify this...
std::vector< float > CDF; // todo: modify this...
/******************************** METHODS *********************************/
/**
* ...
*/
static void key_callback( GLFWwindow* window, int key, int scancode, int action, int mods );
/**
* ...
*/
static void window_close_callback( GLFWwindow* window );
/**
* ...
*/
static void window_size_callback( GLFWwindow* window, int width, int height );
/**
* ...
*/
static void framebuffer_size_callback( GLFWwindow* window, int width, int height );
/**
* ...
*/
static void window_pos_callback( GLFWwindow* window, int xpos, int ypos );
///**
// * ...
// */
//static void cursor_position_callback( GLFWwindow* window, double xpos, double ypos );
///**
// * ...
// */
//static void mouse_button_callback( GLFWwindow* window, int button, int action, int mods );
/**
* ...
*/
static void character_callback( GLFWwindow* window, unsigned int codepoint );
/**
* ...
*/
void processCharacterEvent( unsigned int codepoint );
/**
* ...
*/
void processMouseMoveEvent( double xpos, double ypos );
/**
* ...
*/
void processMouseButtonEvent( int button, int action, int mods );
/**
* ...
*/
void processScrollEvent( double xoffset, double yoffset );
/**
* ...
*/
static void scroll_callback( GLFWwindow* window, double xoffset, double yoffset );
/**
* Slot called when the data model has been modified
*/
virtual void onDataModelModified();
/**
* Callback called when PPTBF size has been modified
*/
void onSizeModified( const int pWidth, const int pHeight );
/**
* Render HUD
*/
void renderHUD();
/**
* Render GUI
*/
void renderGUI();
/**
* Initialize timer(s)
*/
void graphicsInitialization_Timer();
/**
* Finalize timer(s)
*/
void graphicsFinalization_Timer();
/**
* Initialize PPTBF
*/
void initializePPTBF( const int pWidth, const int pHeight );
/**
* Finalize PPTBF
*/
void finalizePPTBF();
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
void showExampleAppFixedOverlay( bool* p_open );
};
}
#endif
| 9,367
|
C++
|
.h
| 341
| 24.970674
| 93
| 0.57234
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,978
|
PtApplication.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/Tools/PtViewer/PtApplication.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_APPLICATION_H_
#define _PT_APPLICATION_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtViewerConfig.h"
//#include "PtPipelineManager.h"
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
// Project
namespace PtGUI
{
class PtViewer;
}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace PtGUI
{
/**
* @class PtApplication
*
* @brief The PtApplication class provides ...
*
* ...
*/
class PtApplication
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* INNER TYPES *******************************/
/**
* Type of pipeline request
*/
enum PtPipelineRequest
{
eLoadDataModel,
eSynthesizeTexture,
eUpdateTexture,
eRequestNbTypes
};
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
/**
* Get the unique instance.
*
* @return the unique instance
*/
static PtApplication& get();
/**
* Destructor.
*/
virtual ~PtApplication();
/**
* Initialize
*/
virtual bool initialize( const char* const pWorkingDirectory );
/**
* Finalize
*/
virtual void finalize();
/**
* Execute
* - main event loop
*/
virtual void execute();
/**
* Post a request
*/
void postRequest( PtPipelineRequest pRequest );
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* ATTRIBUTES *******************************/
/**
* Main window
*/
PtViewer* mMainWindow;
/**
* Requests
*/
bool mOmniScaleModelUpdateRequested;
bool mTextureSynthesisRequested;
/******************************** METHODS *********************************/
/**
* Initialize GLFW
*/
virtual void initializeGLFW();
/**
* Finalize GLFW
*/
virtual void finalizeGLFW();
/**
* Initialize windows
*/
virtual void initializeWindows();
/**
* Initialize GL library
*/
virtual void initializeGL();
/**
* Initialize ImGui user interface
*/
virtual void initializeImGuiUserInterface();
///**
// * Process Events
// */
//virtual void processEvents();
/**
* Handle requests
*/
virtual void handleRequests();
/**
* GLFW error callback
*/
static void error_callback( int error, const char* description );
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* ATTRIBUTES *******************************/
/**
* The unique instance
*/
static PtApplication* msInstance;
/******************************** METHODS *********************************/
/**
* Constructor
*/
PtApplication();
};
}
#endif
| 4,469
|
C++
|
.h
| 156
| 26.179487
| 84
| 0.345685
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,979
|
PtGraphicsHistogram.hpp
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtGraphicsHistogram.hpp
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtShaderProgram.h"
/******************************************************************************
***************************** METHOD DEFINITION ******************************
******************************************************************************/
namespace PtGraphics
{
} // namespace PtGraphics
| 776
|
C++
|
.h
| 23
| 31.869565
| 84
| 0.311497
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,980
|
PtGraphicsPPTBF.hpp
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtGraphicsPPTBF.hpp
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymousmShaderProgram
* anonymous
*/
/**
* @version 1.0
*/
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtShaderProgram.h"
// STL
#include <algorithm>
//#include <cmath>
#include <math.h>
/******************************************************************************
***************************** METHOD DEFINITION ******************************
******************************************************************************/
namespace PtGraphics
{
/******************************************************************************
* Get the shader program
*
* @return the shader program
******************************************************************************/
inline PtShaderProgram* PtGraphicsPPTBF::editPPTBFGeneratorShaderProgram()
{
//return mShaderProgram;
//return nullptr;
/*if ( mRenderingMode == ERenderingMode::eBinaryMap )
{
return mMegakernelThresholdShaderProgram;
}*/
return mMegakernelShaderProgram;
}
/******************************************************************************
* Get the shader program
*
* @return the shader program
******************************************************************************/
inline PtShaderProgram* PtGraphicsPPTBF::editPPTBFViewerShaderProgram()
{
return mPPTBFViewerShaderProgram;
}
/******************************************************************************
* Get the shader program
*
* @return the shader program
******************************************************************************/
inline PtShaderProgram* PtGraphicsPPTBF::editBinaryStructureMapShaderProgram()
{
return mBinaryStructureMapShaderProgram;
}
/******************************************************************************
* General parameters
******************************************************************************/
inline void PtGraphicsPPTBF::setResolution( const int pValue )
{
//mShaderProgram->set( pValue, "uResolution" );
mResolution = pValue;
mUpdateDeformation = true;
mUpdatePointProcess = true;
mUpdateWindowCellular = true;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setAlpha( const float pValue )
{
//mShaderProgram->set( pValue, "alpha" );
mAlpha = pValue;
mUpdateDeformation = true;
mUpdatePointProcess = true;
mUpdateWindowCellular = true;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setRescalex( const float pValue )
{
//mShaderProgram->set( pValue, "rescalex" );
mRescalex = pValue;
mUpdateDeformation = true;
mUpdatePointProcess = true;
mUpdateWindowCellular = true;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setImageWidth( const int pValue )
{
//mShaderProgram->set( pValue, "imageWidth" );
mWidth = pValue;
mUpdateDeformation = true;
mUpdatePointProcess = true;
mUpdateWindowCellular = true;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setImageHeight( const int pValue )
{
//mShaderProgram->set( pValue, "imageHeight" );
mHeight = pValue;
mUpdateDeformation = true;
mUpdatePointProcess = true;
mUpdateWindowCellular = true;
mUpdateFeature = true;
}
/******************************************************************************
* Point process
******************************************************************************/
inline void PtGraphicsPPTBF::setTilingType( const int pValue )
{
//mShaderProgram->set( pValue, "uTilingType" );
mTilingType = static_cast< tilingtype >( pValue );
mUpdatePointProcess = true;
mUpdateWindowCellular = true;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setJittering( const float pValue )
{
//mShaderProgram->set( pValue, "uJittering" );
mJittering = pValue;
mUpdatePointProcess = true;
mUpdateWindowCellular = true;
mUpdateFeature = true; // correlated to point process ?
}
inline void PtGraphicsPPTBF::setCellSubdivisionProbability( const float pValue )
{
//mShaderProgram->set( pValue, "uCellSubdivisionProbability" );
mCellSubdivisionProbability = pValue;
mUpdatePointProcess = true;
mUpdateWindowCellular = true;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setNbRelaxationIterations( const int pValue )
{
//mShaderProgram->set( pValue, "uNbRelaxationIterations" );
mNbRelaxationIterations = pValue;
mUpdatePointProcess = true;
mUpdateWindowCellular = true;
mUpdateFeature = true;
}
/******************************************************************************
* Window function
******************************************************************************/
inline void PtGraphicsPPTBF::setCellularToGaussianWindowBlend( const float pValue )
{
//mShaderProgram->set( pValue, "uCellularToGaussianWindowBlend" );
mCellularToGaussianWindowBlend = pValue;
}
// - cellular window
inline void PtGraphicsPPTBF::setRectangularToVoronoiShapeBlend( const float pValue )
{
//mShaderProgram->set( pValue, "uRectangularToVoronoiShapeBlend" );
mRectangularToVoronoiShapeBlend = pValue;
mUpdatePointProcess = true; // modify this...
mUpdateWindowCellular = true;
}
inline void PtGraphicsPPTBF::setCellularWindowDecay( const float pValue )
{
//mShaderProgram->set( pValue, "uCellularWindowDecay" );
mCellularWindowDecay = pValue;
mUpdateWindowCellular = true;
}
inline void PtGraphicsPPTBF::setCellularWindowNorm( const float pValue )
{
//mShaderProgram->set( pValue, "uCellularWindowNorm" );
mCellularWindowNorm = pValue;
mUpdatePointProcess = true; // modify this...
mUpdateWindowCellular = true;
}
// - Gaussian window
//inline int PtGraphicsPPTBF::getWindowShape() const
//{
// return mWindowShape;
//}
//inline void PtGraphicsPPTBF::setWindowShape( const int pValue )
//{
// mWindowShape = pValue;
//}
inline void PtGraphicsPPTBF::setGaussianWindowDecay( const float pValue )
{
//mShaderProgram->set( pValue, "uGaussianWindowDecay" );
mGaussianWindowDecay = pValue;
}
inline void PtGraphicsPPTBF::setGaussianWindowDecayJittering( const float pValue )
{
//mShaderProgram->set( pValue, "uGaussianWindowDecayJittering" );
mGaussianWindowDecayJittering = pValue;
}
/******************************************************************************
* Feature function
******************************************************************************/
inline void PtGraphicsPPTBF::setMinNbGaborKernels( const int pValue )
{
//mShaderProgram->set( pValue, "uMinNbGaborKernels" );
mMinNbGaborKernels = pValue;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setMaxNbGaborKernels( const int pValue )
{
//mShaderProgram->set( pValue, "uMaxNbGaborKernels" );
mMaxNbGaborKernels = pValue;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setFeatureNorm( const float pValue )
{
//mShaderProgram->set( pValue, "uFeatureNorm" );
mFeatureNorm = pValue;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setGaborStripesFrequency( const int pValue )
{
//mShaderProgram->set( pValue, "uGaborStripesFrequency" );
mGaborStripesFrequency = pValue;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setGaborStripesCurvature( const float pValue )
{
//mShaderProgram->set( pValue, "uGaborStripesCurvature" );
mGaborStripesCurvature = pValue;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setGaborStripesOrientation( const float pValue )
{
//mShaderProgram->set( pValue, "uGaborStripesOrientation" );
mGaborStripesOrientation = pValue;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setGaborStripesThickness( const float pValue )
{
//mShaderProgram->set( pValue, "uGaborStripesThickness" );
mGaborStripesThickness = pValue;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setGaborDecay( const float pValue )
{
//mShaderProgram->set( pValue, "uGaborDecay" );
mGaborDecay = pValue;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setGaborDecayJittering( const float pValue )
{
//mShaderProgram->set( pValue, "uGaborDecayJittering" );
mGaborDecayJittering = pValue;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setFeaturePhaseShift( const float pValue )
{
//mShaderProgram->set( pValue, "uFeaturePhaseShift" );
mFeaturePhaseShift = pValue;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setBombingFlag( const int pValue )
{
//mShaderProgram->set( pValue, "uBombingFlag" );
mBombingFlag = pValue;
mUpdateFeature = true; // feature or window ?
}
inline void PtGraphicsPPTBF::setUseAnimation( const bool pFlag )
{
//mShaderProgram->set(static_cast< unsigned int >( pFlag ), "uUseAnimation");
}
/******************************************************************************
* Deformation
******************************************************************************/
inline void PtGraphicsPPTBF::setTurbulenceAmplitude0( const float pValue )
{
//mShaderProgram->set( pValue, "uTurbulenceAmplitude_0" );
mTurbulenceAmplitude0 = pValue;
mUpdateDeformation = true;
mUpdatePointProcess = true;
mUpdateWindowCellular = true;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setTurbulenceAmplitude1( const float pValue )
{
//mShaderProgram->set( pValue, "uTurbulenceAmplitude_1" );
mTurbulenceAmplitude1 = pValue;
mUpdateDeformation = true;
mUpdatePointProcess = true;
mUpdateWindowCellular = true;
mUpdateFeature = true;
}
inline void PtGraphicsPPTBF::setTurbulenceAmplitude2( const float pValue )
{
//mShaderProgram->set( pValue, "uTurbulenceAmplitude_2" );
mTurbulenceAmplitude2 = pValue;
mUpdateDeformation = true;
mUpdatePointProcess = true;
mUpdateWindowCellular = true;
mUpdateFeature = true;
}
/******************************************************************************
* Recursivity
******************************************************************************/
inline void PtGraphicsPPTBF::setRecursiveWindowSubdivisionProbability( const float pValue )
{
//mShaderProgram->set( pValue, "uRecursiveWindowSubdivisionProbability" );
}
inline void PtGraphicsPPTBF::setRecursiveWindowSubdivisionScale( const float pValue )
{
//mShaderProgram->set( pValue, "uRecursiveWindowSubdivisionScale" );
}
/******************************************************************************
* Labeling
******************************************************************************/
inline int PtGraphicsPPTBF::getNbLabels() const
{
return mNbLabels;
}
inline void PtGraphicsPPTBF::setNbLabels( const int pValue )
{
mNbLabels = pValue;
}
inline GLuint PtGraphicsPPTBF::getPPTBFLabelMapGLHandle() const
{
return mPPTBFLabelMap;
}
inline GLuint PtGraphicsPPTBF::getPPTBFRandomValueMapGLHandle() const
{
return mPPTBFRandomValueMap;
}
/******************************************************************************
* Animation
******************************************************************************/
inline void PtGraphicsPPTBF::setTime( const float pValue )
{
mTime = pValue;
//mShaderProgram->set( pValue, "uTime" );
}
/******************************************************************************
* ...
******************************************************************************/
inline float PtGraphicsPPTBF::getSynthesisTime() const
{
return mSynthesisTime;
}
/******************************************************************************
* ...
******************************************************************************/
inline const std::stringstream& PtGraphicsPPTBF::getSynthesisInfo() const
{
return mSynthesisInfo;
}
/******************************************************************************
* Get threshold used to binarize PPTBF
******************************************************************************/
inline float PtGraphicsPPTBF::getThreshold() const
{
return mThreshold;
}
/******************************************************************************
* Set threshold used to binarize PPTBF
******************************************************************************/
inline void PtGraphicsPPTBF::setThreshold( const float pValue )
{
mThreshold = pValue;
}
/******************************************************************************
* Get the rendering mode
******************************************************************************/
inline PtGraphicsPPTBF::ERenderingMode PtGraphicsPPTBF::getRenderingMode() const
{
return mRenderingMode;
}
/******************************************************************************
* Set the rendering mode
******************************************************************************/
inline void PtGraphicsPPTBF::setRenderingMode( const PtGraphicsPPTBF::ERenderingMode pValue )
{
mRenderingMode = pValue;
}
/******************************************************************************
* Compute the number of mipmap levels corresponding to given width and height of an image
*
* @param pImageWidth width of an image
* @param pImageHeight height of an image
*
* @return the number of mipmap levels
******************************************************************************/
inline int PtGraphicsPPTBF::getNbMipmapLevels( const int pImageWidth, const int pImageHeight )
{
return static_cast< int >( std::floor( std::log2( static_cast< float >( std::max( pImageWidth, pImageHeight ) ) ) ) ) + 1;
}
} // namespace PtGraphics
| 13,439
|
C++
|
.h
| 386
| 33.121762
| 123
| 0.596028
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,981
|
PtGraphicsLibrary.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtGraphicsLibrary.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_GRAPHICS_LIBRARY_H_
#define _PT_GRAPHICS_LIBRARY_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtGraphicsConfig.h"
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace PtGraphics
{
class PTGRAPHICS_EXPORT PtGraphicsLibrary
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
/**
* Main GsGraphics module initialization method
*/
static bool initialize( const char* const pWorkingDirectory );
/**
* Main GsGraphics module finalization method
*/
static void finalize();
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/**
* Flag telling whether or not the library is initialized
*/
static bool mIsInitialized;
/******************************** METHODS *********************************/
};
}
#endif // !_PT_GRAPHICS_LIBRARY_H_
| 3,427
|
C++
|
.h
| 71
| 45.28169
| 84
| 0.220517
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,982
|
PtGraphicsMeshManager.hpp
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtGraphicsMeshManager.hpp
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
/******************************************************************************
***************************** METHOD DEFINITION ******************************
******************************************************************************/
namespace PtGraphics
{
inline bool PtGraphicsMeshManager::useMaterial() const
{
return mUseMaterial;
}
inline void PtGraphicsMeshManager::setUseMaterial( const bool pFlag )
{
mUseMaterial = pFlag;
}
inline PtGraphicsMeshManager::MeshType PtGraphicsMeshManager::getMeshType() const
{
return mMeshType;
}
/******************************************************************************
* Color map
******************************************************************************/
inline int PtGraphicsMeshManager::getColormapIndex() const
{
return mColormapIndex;
}
inline void PtGraphicsMeshManager::setColormapIndex( const int pValue )
{
mColormapIndex = pValue;
}
} // namespace PtGraphics
| 1,386
|
C++
|
.h
| 44
| 29.795455
| 84
| 0.443361
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,983
|
PtGraphicsHistogram.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtGraphicsHistogram.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_GRAPHICS_HISTOGRAM_H_
#define _PT_GRAPHICS_HISTOGRAM_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtGraphicsConfig.h"
// GL
#include <glad/glad.h>
// STL
#include <vector>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
namespace Pt
{
class PtPPTBF;
}
namespace PtGraphics
{
class PtShaderProgram;
}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace PtGraphics
{
/**
* @class PtPPTBF
*
* @brief The PtPPTBF class provides interface to the "best matching tile selection" stage.
*
* The best matching tile selection occurs during the final texture synthesis stage:
* - for each tile of a given composition map, a list of candidate tiles matching some features/characteristics is determined,
* - the selector job is to select the best one among all acandidates.
*/
class PTGRAPHICS_EXPORT PtGraphicsHistogram
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/**
* Textures
** TODO: move this to "protected"
*/
GLuint mPPTBFFrameBuffer;
GLuint mPPTBFTexture;
/******************************** METHODS *********************************/
/**
* Constructor
*/
PtGraphicsHistogram();
/**
* Destructor
*/
virtual ~PtGraphicsHistogram();
/**
* Initialize
*/
void initialize( const int pNbBins );
/**
* Finalize
*/
void finalize();
/**
* Compute
*/
void compute( const GLuint pTexture, const int pTextureWidth, const int pTextureHeight );
/**
* Get histogram
*/
void getHistogram( std::vector< float >& pHistogram, std::vector< float >& pCDF, const int pTextureWidth, const int pTextureHeight );
/**
* Render
*/
void render();
/**
* Number of bins
*/
int getNbBins() const;
void setNbBins( const int pValue );
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/**
* PPTBF generator shader program
*/
PtShaderProgram* mShaderProgram;
/**
* Number of bins
*/
int mNbBins;
/******************************** METHODS *********************************/
/**
* Initialize
*/
void initializeFramebuffer();
bool initializeShaderProgram();
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
}; // end of class PtGraphicsHistogram
} // end of namespace PtGraphics
/******************************************************************************
******************************* INLINE SECTION ******************************
******************************************************************************/
#include "PtGraphicsHistogram.hpp"
#endif // _PT_GRAPHICS_PPTBF_H_
| 4,935
|
C++
|
.h
| 136
| 33.823529
| 134
| 0.341695
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,984
|
PtGraphicsConfig.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtGraphicsConfig.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_GRAPHICS_CONFIG_H_
#define _PT_GRAPHICS_CONFIG_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
//*** GsGraphics Library
// Static or dynamic link configuration
#ifdef WIN32
# ifdef PTGRAPHICS_MAKELIB // Create a static library.
# define PTGRAPHICS_EXPORT
# define PTGRAPHICS_TEMPLATE_EXPORT
# elif defined PTGRAPHICS_USELIB // Use a static library.
# define PTGRAPHICS_EXPORT
# define PTGRAPHICS_TEMPLATE_EXPORT
# elif defined PTGRAPHICS_MAKEDLL // Create a DLL library.
# define PTGRAPHICS_EXPORT __declspec(dllexport)
# define PTGRAPHICS_TEMPLATE_EXPORT
# else // Use DLL library
# define PTGRAPHICS_EXPORT __declspec(dllimport)
# define PTGRAPHICS_TEMPLATE_EXPORT extern
# endif
#else
# if defined(PTGRAPHICS_MAKEDLL) || defined(PTGRAPHICS_MAKELIB)
# define PTGRAPHICS_EXPORT
# define PTGRAPHICS_TEMPLATE_EXPORT
# else
# define PTGRAPHICS_EXPORT
# define PTGRAPHICS_TEMPLATE_EXPORT extern
# endif
#endif
// ---------------- GLM library Management ----------------
///**
// * To remove warnings at compilation with GLM deprecated functions
// */
#define GLM_ENABLE_EXPERIMENTAL
#define GLM_FORCE_RADIANS
//#define _OS_USE_HOME_PATH_
#endif // !_PT_GRAPHICS_CONFIG_H_
| 1,827
|
C++
|
.h
| 53
| 33.264151
| 83
| 0.578798
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,985
|
PtGraphicsMeshManager.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtGraphicsMeshManager.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_GRAPHICS_MESH_MANAGER_H_
#define _PT_GRAPHICS_MESH_MANAGER_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtGraphicsConfig.h"
// GL
#include <glad/glad.h>
// glm
#include <glm/glm.hpp>
// STL
#include <vector>
#include <sstream>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
namespace PtGraphics
{
class PtShaderProgram;
class PtCamera;
}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace PtGraphics
{
/**
* @class PtPPTBF
*
* @brief The PtPPTBF class provides interface to the "best matching tile selection" stage.
*
* The best matching tile selection occurs during the final texture synthesis stage:
* - for each tile of a given composition map, a list of candidate tiles matching some features/characteristics is determined,
* - the selector job is to select the best one among all acandidates.
*/
class PTGRAPHICS_EXPORT PtGraphicsMeshManager
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* INNER TYPES *******************************/
/**
* Shader type enumeration
*/
enum class MeshType
{
eGridMesh = 0,
eWaveMesh,
eCylinderMesh,
eTorusMesh,
eSphereMesh,
eNbMeshTypes
};
/******************************* ATTRIBUTES *******************************/
/**
* Model matrix
*/
glm::mat4 mModelMatrix; // TODO: for test...
float mBump;
/******************************** METHODS *********************************/
/**
* Constructor
*/
PtGraphicsMeshManager();
/**
* Destructor
*/
virtual ~PtGraphicsMeshManager();
/**
* Initialize
*/
void initialize();
/**
* Finalize
*/
void finalize();
/**
* Render
*/
void render( const PtCamera* const pCamera );
/**
* Render
*/
void renderBasic();
/**
*
*/
void setPPTBFTexture( const GLuint pTexture );
/**
* Set the mesh type
*/
void setMeshType( const MeshType pMeshType );
inline MeshType getMeshType() const;
// Material
inline bool useMaterial() const;
inline void setUseMaterial( const bool pFlag );
// Color map
inline int getColormapIndex() const;
inline void setColormapIndex( const int pValue );
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/**
* Mesh graphics resources
*/
GLuint mVAO;
GLuint mPositionVBO;
GLuint mTextureCoordinateVBO;
GLuint mNormalVBO;
GLuint mElementArrayBuffer;
unsigned int mNbMeshIndices;
bool mUseMaterial;
MeshType mMeshType;
/**
* PPTBF generator shader program
*/
PtShaderProgram* mShaderProgram;
PtShaderProgram* mShaderProgram2;
/**
* PPTBF texture
*/
GLuint mPPTBFTexture;
// Appearance
int mColormapIndex;
/******************************** METHODS *********************************/
/**
* Initialize shader programs
*
* @return a flag telling whether or not it succeeds
*/
bool initializeGraphicsResources();
/**
* Initialize shader programs
*
* @return a flag telling whether or not it succeeds
*/
bool finalizeGraphicsResources();
/**
* Initialize shader programs
*
* @return a flag telling whether or not it succeeds
*/
bool initializeShaderPrograms();
/**
* Release graphics resources
*/
void setGraphicsResources( const std::vector< glm::vec3 >& pPositions,
const std::vector< glm::vec2 >& pTextureCoordinates,
const std::vector< glm::vec3 >& pNormals,
const std::vector< unsigned int >& pIndices );
/**
* Generate a grid mesh
*/
void generateGrid( const unsigned int pResolution );
/**
* Generate a wave mesh
*/
void generateWave( const unsigned int pResolution );
/**
* Generate a cylinder mesh
*/
void generateCylinder( const unsigned int pResolution );
/**
* Generate a torus mesh
*/
void generateTorus( const unsigned int pResolution );
/**
* Generate a sphere mesh
*/
void generateSphere( const unsigned int pResolution );
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
}; // end of class PtGraphicsMeshManager
} // end of namespace PtGraphics
/******************************************************************************
******************************* INLINE SECTION ******************************
******************************************************************************/
#include "PtGraphicsMeshManager.hpp"
#endif // _PT_GRAPHICS_MESH_MANAGER_H_
| 6,555
|
C++
|
.h
| 207
| 29.077295
| 127
| 0.437689
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,986
|
PtGraphicsPPTBF.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtGraphicsPPTBF.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_GRAPHICS_PPTBF_H_
#define _PT_GRAPHICS_PPTBF_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// Project
#include "PtGraphicsConfig.h"
#include "PtPPTBF.h"
// GL
#include <glad/glad.h>
// STL
#include <vector>
#include <sstream>
// glm
#include <glm/glm.hpp>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
namespace PtGraphics
{
class PtShaderProgram;
class PtGraphicsDeformation;
class PtGraphicsPointProcess;
class PtGraphicsWindowCellular;
class PtGraphicsFeature;
}
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace PtGraphics
{
/**
* @class PtPPTBF
*
* @brief The PtPPTBF class provides interface to the "best matching tile selection" stage.
*
* The best matching tile selection occurs during the final texture synthesis stage:
* - for each tile of a given composition map, a list of candidate tiles matching some features/characteristics is determined,
* - the selector job is to select the best one among all acandidates.
*/
class PTGRAPHICS_EXPORT PtGraphicsPPTBF : public Pt::PtPPTBF
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* INNER TYPES *******************************/
/**
* PPTBF rendering mode
*/
enum class ERenderingMode
{
ePPTBF = 0,
eBinaryMap,
ePalette,
eNbRenderingModes
};
/******************************* ATTRIBUTES *******************************/
/**
* Textures
** TODO: move this to "protected"
*/
GLuint mTexture_P;
GLuint mTexture_rnd_tab;
GLuint mTexture_G;
GLuint mSampler_PRNG_Noise;
GLuint mPPTBFFrameBuffer;
GLuint mPPTBFTexture;
GLuint mThresholdTexture;
/**
* Palette exemplar
*/
PtShaderProgram* mShaderProgram;
// Multiple outputs
std::vector< GLuint > mPPTBFTextureLists;
/******************************** METHODS *********************************/
/**
* Constructor
*/
PtGraphicsPPTBF();
/**
* Destructor
*/
virtual ~PtGraphicsPPTBF();
/**
* Initialize
*/
void initialize( const int pWidth, const int pHeight );
/**
* Initialize
*/
void initialize( const int pWidth, const int pHeight, const int pNbOutputs );
/**
* Finalize
*/
void finalize();
/**
* Get the shader program
*
* @return the shader program
*/
inline PtShaderProgram* editPPTBFGeneratorShaderProgram();
/**
* Get the shader program
*
* @return the shader program
*/
inline PtShaderProgram* editPPTBFViewerShaderProgram();
inline PtShaderProgram* editBinaryStructureMapShaderProgram();
/**
* Compute PPTBF
*/
void compute();
void compute( const int pOutputID );
/**
* Render
*/
void render();
// General parameters
inline void setResolution( const int pValue );
inline void setAlpha( const float pValue );
inline void setRescalex( const float pValue );
inline void setImageWidth( const int pValue );
inline void setImageHeight( const int pValue );
// Point process
inline void setTilingType( const int pValue );
inline void setJittering( const float pValue );
inline void setCellSubdivisionProbability( const float pValue );
inline void setNbRelaxationIterations( const int pValue );
// Window function
inline void setCellularToGaussianWindowBlend( const float pValue );
// - cellular window
inline void setRectangularToVoronoiShapeBlend( const float pValue );
inline void setCellularWindowDecay( const float pValue );
inline void setCellularWindowNorm( const float pValue );
// - Gaussian window
/*inline int getWindowShape() const;
inline void setWindowShape( const int pValue );*/
/*inline float getWindowArity() const;
inline void setWindowArity( const float pValue );
inline float getWindowLarp() const;
inline void setWindowLarp( const float pValue );
inline float getWindowNorm() const;
inline void setWindowNorm( const float pValue );
inline float getWindowSmooth() const;
inline void setWindowSmooth( const float pValue );
inline float getWindowBlend() const;
inline void setWindowBlend( const float pValue );
inline float getWindowSigwcell() const;
inline void setWindowSigwcell( const float pValue );*/
inline void setGaussianWindowDecay( const float pValue );
inline void setGaussianWindowDecayJittering( const float pValue );
// Feature function
inline void setMinNbGaborKernels( const int pValue );
inline void setMaxNbGaborKernels( const int pValue );
inline void setFeatureNorm( const float pValue );
inline void setGaborStripesFrequency( const int pValue );
inline void setGaborStripesCurvature( const float pValue );
inline void setGaborStripesOrientation( const float pValue );
inline void setGaborStripesThickness( const float pValue );
inline void setGaborDecay( const float pValue );
inline void setGaborDecayJittering( const float pValue );
inline void setFeaturePhaseShift( const float pValue );
inline void setBombingFlag( const int pValue );
inline void setUseAnimation( const bool pValue );
inline void setUseMegaKernel( const bool pValue );
// Deformation
inline void setTurbulenceAmplitude0( const float pValue );
inline void setTurbulenceAmplitude1( const float pValue );
inline void setTurbulenceAmplitude2( const float pValue );
// Recursivity
inline void setRecursiveWindowSubdivisionProbability( const float pValue );
inline void setRecursiveWindowSubdivisionScale( const float pValue );
// Animation
inline void setTime( const float pValue );
/**
* Labeling
*/
inline int getNbLabels() const;
inline void setNbLabels( const int pValue );
inline GLuint getPPTBFLabelMapGLHandle() const;
inline GLuint getPPTBFRandomValueMapGLHandle() const;
/**
* Callback called when PPTBF size has been modified
*/
void onSizeModified( const int pWidth, const int pHeight );
/**
* Flag to tell whether or not to use full FBO resolution (slow "screen size" or faster "640x480" for editing)
*/
bool useLowResolutionPPTBF() const;
void setUseLowResolutionPPTBF( const bool pFlag );
/**
* Generate database
*/
// test : uniform sampling
void generateDatabase_test( const unsigned int pWidth, const unsigned int pHeight, const char* pPath );
// advanced sampling
void generateDatabase( const unsigned int pWidth, const unsigned int pHeight, const char* pPath, const unsigned int pSerieID );
/**
* Generate a PPTBF given a parameter file
*/
void generatePPTBF( const unsigned int pWidth, const unsigned int pHeight, const char* pParameterFilename );
/**
* Timer info
*/
inline float getSynthesisTime() const;
inline const std::stringstream& getSynthesisInfo() const;
/**
* Get threshold used to binarize PPTBF
*/
inline float getThreshold() const;
/**
* Set threshold used to binarize PPTBF
*/
inline void setThreshold( const float pValue );
/**
* Set the rendering mode
*/
inline ERenderingMode getRenderingMode() const;
/**
* Set the rendering mode
*/
inline void setRenderingMode( const ERenderingMode pValue );
/**
* Compute binary structure map
*/
void computeBinaryStructureMap();
/**
* Helper function to load a texture
*/
static bool loadTexture( const char* pFilename,
const int pNbRequestedChannels, const GLenum pInternalFormat, const GLenum pFormat, const GLenum pType,
const bool pGenerateMipmap,
GLuint& pTexture,
int& pWidth, int& pHeight );
/**
* Compute the number of mipmap levels corresponding to given width and height of an image
*
* @param pImageWidth width of an image
* @param pImageHeight height of an image
*
* @return the number of mipmap levels
*/
static inline int getNbMipmapLevels( const int pImageWidth, const int pImageHeight );
/**
* sampleParameterSpace
*/
void sampleParameterSpace( const unsigned int pWidth, const unsigned int pHeight, const char* pPath, const char* pImageName,
// method parameters
const int pDescriptor, const int pKEEPNBEST, const int pNR, const float pDeltaAlpha, const float pFactResol, const float pFactRescaleX, const float pEcart, const float pPercent,
// external data
std::vector< float >& mPptbfCandidateThresholds,
std::vector< float >& mPptbfCandidateMinValues,
std::vector< float >& mPptbfCandidateMaxValues,
std::vector< float >& mPptbfCandidateMeanValues,
std::vector< bool >& mSelectedNNCandidates,
// PPTBF
// - Point Process
std::vector< int >& tilingType,
std::vector< float >& jittering,
// - Transform
std::vector< int >& resolution,
std::vector< float >& rotation,
std::vector< float >& rescalex,
// - Turbulence
std::vector< float >& turbAmplitude0,
std::vector< float >& turbAmplitude1,
std::vector< float >& turbAmplitude2,
std::vector< std::vector< float > >& turbAmp,
// - Window
std::vector< int >& windowShape,
std::vector< float >& windowArity,
std::vector< float >& windowLarp,
std::vector< float >& windowNorm,
std::vector< float >& windowSmoothness,
std::vector< float >& windowBlend,
std::vector< float >& windowSigwcell,
// - Feature
std::vector< int >& featureBombing,
std::vector< float >& featureNorm,
std::vector< float >& featureWinfeatcorrel,
std::vector< float >& featureAniso,
std::vector< int >& featureMinNbKernels,
std::vector< int >& featureMaxNbKernels,
std::vector< float >& featureSigcos,
std::vector< float >& featureSigcosvar,
std::vector< int >& featureFrequency,
std::vector< float >& featurePhaseShift,
std::vector< float >& featureThickness,
std::vector< float >& featureCurvature,
std::vector< float >& featureOrientation,
// save bank ID
std::vector< int >& featureBankIDs );
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/**
* PPTBF viewer shader program
*/
PtShaderProgram* mPPTBFViewerShaderProgram;
PtShaderProgram* mBinaryStructureMapShaderProgram;
/**
* Flag to tell whether or not to use full FBO resolution (slow "screen size" or faster "640x480" for editing)
*/
bool mUseLowResolutionPPTBF;
int mWidthLowQuality;
int mHeightLowQuality;
/**
* Animation
*/
float mTime;
/**
* PPTBF componenets status flag
*/
bool mUpdateDeformation;
bool mUpdatePointProcess;
bool mUpdateWindowCellular;
bool mUpdateFeature;
// GPU timer
GLuint mQueryTimeElapsed;
GLuint64 mPPTBFGenerationTime;
float mSynthesisTime;
std::stringstream mSynthesisInfo;
/**
* PPTBF megakernel shader program
*/
PtShaderProgram* mMegakernelShaderProgram;
/**
* PPTBF megakernel shader program with threshold
*/
PtShaderProgram* mMegakernelThresholdShaderProgram;
/**
* Colormap shader program
*/
PtShaderProgram* mColormapShaderProgram;
int mColormapIndex;
/**
* Threshold to binarize PPTBF
*/
float mThreshold;
/**
* Rendering mode
*/
ERenderingMode mRenderingMode;
// Labeling: on-the-fly generation
// - labeling
int mNbLabels;
// - texture of labels
GLuint mPPTBFLabelMap;
GLuint mPPTBFRandomValueMap;
/******************************** METHODS *********************************/
/**
* Initialize shader programs
*
* @return a flag telling whether or not it succeeds
*/
bool initializeShaderPrograms();
void graphicsInitialization_BinaryStructureMap();
/**
* Initialize PRNG
*/
void graphicsInitialization_PRNG();
/**
* Initialize noise
*/
void graphicsInitialization_Noise();
void graphicsInitialization_Noise_rnd_tab();
void graphicsInitialization_Noise_G();
/**
* Initialize timer(s)
*/
void graphicsInitialization_Timer();
/**
* Finalize timer(s)
*/
void graphicsFinalization_Timer();
/**
* Execute the mega-kernel approach
*/
void executeMegakernelApproach();
void executeMegakernelApproach( const int pOutputID );
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
}; // end of class PtGraphicsPPTBF
} // end of namespace PtGraphics
/******************************************************************************
******************************* INLINE SECTION ******************************
******************************************************************************/
#include "PtGraphicsPPTBF.hpp"
#endif // _PT_GRAPHICS_PPTBF_H_
| 14,241
|
C++
|
.h
| 416
| 31.682692
| 179
| 0.621566
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,987
|
PtShaderProgram.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtShaderProgram.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_SHADER_PROGRAM_H_
#define _PT_SHADER_PROGRAM_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
#include "PtGraphicsConfig.h"
// OpenGL
#include <glad/glad.h>
// STL
#include <string>
#include <vector>
#include <map>
#include <utility>
// glm
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace PtGraphics
{
/**
* @class PtShaderProgram
*
* @brief The PtShaderProgram class provides interface to handle a ray map.
*
* Ray map is a container of ray initialized for the rendering phase.
*/
class PTGRAPHICS_EXPORT PtShaderProgram
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/****************************** INNER TYPES *******************************/
/**
* Shader type enumeration
*/
enum class ShaderType
{
eVertexShader = 0,
eTesselationControlShader,
eTesselationEvaluationShader,
eGeometryShader,
eFragmentShader,
eComputeShader,
eNbShaderTypes
};
/**
* Shader type names
*/
static const char* ShaderTypeName[ static_cast< int >( ShaderType::eNbShaderTypes ) ];
/**
* Type definition to manipulate shaders as (shadertype, filename)
*/
typedef std::vector< std::pair< ShaderType, std::string > > TShaderList;
/******************************* ATTRIBUTES *******************************/
/**
* Main shader program
*/
GLuint _program;
/******************************** METHODS *********************************/
/**
* Constructor
*/
PtShaderProgram();
/**
* Destructor
*/
virtual ~PtShaderProgram();
/**
* Initialize
*
* @return a flag to tell whether or not it succeeds.
*/
bool initialize();
/**
* Finalize
*
* @return a flag to tell whether or not it succeeds.
*/
bool finalize();
/**
* Compile shader
*/
bool addShader( ShaderType pShaderType, const std::string& pShaderFileName );
/**
* Link program
*/
bool link();
/**
* Initialize program with shaders as (shadertype, filename)
*/
bool initializeProgram( const TShaderList& pShaders );
/**
* Use program
*/
inline void use() const;
/**
* Unuse program
*/
static inline void unuse();
/**
* Tell whether or not pipeline has a given type of shader
*
* @param pShaderType the type of shader to test
*
* @return a flag telling whether or not pipeline has a given type of shader
*/
bool hasShaderType( ShaderType pShaderType ) const;
/**
* Get the source code associated to a given type of shader
*
* @param pShaderType the type of shader
*
* @return the associated shader source code
*/
std::string getShaderSourceCode( ShaderType pShaderType ) const;
/**
* Get the filename associated to a given type of shader
*
* @param pShaderType the type of shader
*
* @return the associated shader filename
*/
std::string getShaderFilename( ShaderType pShaderType ) const;
/**
* ...
*
* @param pShaderType the type of shader
*
* @return ...
*/
bool reloadShader( ShaderType pShaderType );
/**
* Register uniform names
*/
void registerUniforms( const std::vector< std::string >& pUniformNames );
/**
* Set uniform
*/
template< typename TType >
void set( const TType& pValue, const char* pName );
/**
* Shader name (short, no space)
*/
inline const char* getName() const;
/**
* Shader name (short, no space)
*/
inline void setName( const char* pText );
/**
* Shader info (name, etc...)
*/
inline const char* getInfo() const;
/**
* Shader info (name, etc...)
*/
inline void setInfo( const char* pText );
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/****************************** INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/**
* Vertex shader file name
*/
#if defined _MSC_VER
#pragma warning( push )
#pragma warning( disable:4251 )
#endif
std::string _vertexShaderFilename;
#if defined _MSC_VER
#pragma warning( pop )
#endif
/**
* Tesselation Control shader file name
*/
#if defined _MSC_VER
#pragma warning( push )
#pragma warning( disable:4251 )
#endif
std::string _tesselationControlShaderFilename;
#if defined _MSC_VER
#pragma warning( pop )
#endif
/**
* Tesselation Evaluation shader file name
*/
#if defined _MSC_VER
#pragma warning( push )
#pragma warning( disable:4251 )
#endif
std::string _tesselationEvaluationShaderFilename;
#if defined _MSC_VER
#pragma warning( pop )
#endif
/**
* Geometry shader file name
*/
#if defined _MSC_VER
#pragma warning( push )
#pragma warning( disable:4251 )
#endif
std::string _geometryShaderFilename;
#if defined _MSC_VER
#pragma warning( pop )
#endif
/**
* Fragment shader file name
*/
#if defined _MSC_VER
#pragma warning( push )
#pragma warning( disable:4251 )
#endif
std::string _fragmentShaderFilename;
#if defined _MSC_VER
#pragma warning( pop )
#endif
/**
* Compute shader file name
*/
#if defined _MSC_VER
#pragma warning( push )
#pragma warning( disable:4251 )
#endif
std::string _computeShaderFilename;
#if defined _MSC_VER
#pragma warning( pop )
#endif
/**
* Vertex shader source code
*/
#if defined _MSC_VER
#pragma warning( push )
#pragma warning( disable:4251 )
#endif
std::string _vertexShaderSourceCode;
#if defined _MSC_VER
#pragma warning( pop )
#endif
/**
* Tesselation Control shader source code
*/
#if defined _MSC_VER
#pragma warning( push )
#pragma warning( disable:4251 )
#endif
std::string _tesselationControlShaderSourceCode;
#if defined _MSC_VER
#pragma warning( pop )
#endif
/**
* Tesselation Evaluation shader source code
*/
#if defined _MSC_VER
#pragma warning( push )
#pragma warning( disable:4251 )
#endif
std::string _tesselationEvaluationShaderSourceCode;
#if defined _MSC_VER
#pragma warning( pop )
#endif
/**
* Geometry shader source code
*/
#if defined _MSC_VER
#pragma warning( push )
#pragma warning( disable:4251 )
#endif
std::string _geometryShaderSourceCode;
#if defined _MSC_VER
#pragma warning( pop )
#endif
/**
* Fragment shader source code
*/
#if defined _MSC_VER
#pragma warning( push )
#pragma warning( disable:4251 )
#endif
std::string _fragmentShaderSourceCode;
#if defined _MSC_VER
#pragma warning( pop )
#endif
/**
* Compute shader source code
*/
#if defined _MSC_VER
#pragma warning( push )
#pragma warning( disable:4251 )
#endif
std::string _computeShaderSourceCode;
#if defined _MSC_VER
#pragma warning( pop )
#endif
///**
// * Main shader program
// */
//GLuint _program;
/**
* Vertex shader
*/
GLuint _vertexShader;
/**
* Tesselation Control shader
*/
GLuint _tesselationControlShader;
/**
* Tesselation Evaluation shader
*/
GLuint _tesselationEvaluationShader;
/**
* Geometry shader
*/
GLuint _geometryShader;
/**
* Fragment shader
*/
GLuint _fragmentShader;
/**
* Compute shader
*/
GLuint _computeShader;
/**
* ...
*/
bool _linked;
/**
* List of uniform locations
*/
std::map< std::string, GLint > mUniformLocations;
/**
* Shader info (name, etc...)
*/
std::string mName;
/**
* Shader info (name, etc...)
*/
std::string mInfo;
/******************************** METHODS *********************************/
/**
* ...
*
* @param pFilename ...
* @param pFileContent ...
*
* @return ...
*/
static bool getFileContent( const std::string& pFilename, std::string& pFileContent );
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/****************************** INNER TYPES *******************************/
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
/**
* Copy constructor forbidden.
*/
PtShaderProgram( const PtShaderProgram& );
/**
* Copy operator forbidden.
*/
PtShaderProgram& operator=( const PtShaderProgram& );
};
} // namespace PtGraphics
/**************************************************************************
***************************** INLINE SECTION *****************************
**************************************************************************/
#include "PtShaderProgram.hpp"
#endif
| 10,063
|
C++
|
.h
| 394
| 23.279188
| 87
| 0.528221
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,988
|
PtShaderProgram.hpp
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtShaderProgram.hpp
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
// System
#include <cassert>
/******************************************************************************
****************************** INLINE DEFINITION *****************************
******************************************************************************/
namespace PtGraphics
{
/******************************************************************************
* Use program
******************************************************************************/
inline void PtShaderProgram::use() const
{
assert( _linked );
if ( _linked )
{
glUseProgram( _program );
}
}
/******************************************************************************
* Unuse program
******************************************************************************/
inline void PtShaderProgram::unuse()
{
glUseProgram( 0 );
}
///******************************************************************************
// * ...
// ******************************************************************************/
//template< typename TType >
//inline void PtShaderProgram::set< TType >( const TType& pValue, const char* pName )
//{
//}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< glm::mat4 >( const glm::mat4& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniformMatrix4fv( mUniformLocations[ pName ], 1, GL_FALSE, glm::value_ptr( pValue ) );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< glm::mat3 >( const glm::mat3& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniformMatrix3fv( mUniformLocations[ pName ], 1, GL_FALSE, glm::value_ptr( pValue ) );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< glm::mat2 >( const glm::mat2& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniformMatrix2fv( mUniformLocations[ pName ], 1, GL_FALSE, glm::value_ptr( pValue ) );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< glm::vec4 >( const glm::vec4& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform4fv( mUniformLocations[ pName ], 1, glm::value_ptr( pValue ) );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< glm::ivec4 >( const glm::ivec4& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform4iv( mUniformLocations[ pName ], 1, glm::value_ptr( pValue ) );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< glm::uvec4 >( const glm::uvec4& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform4uiv( mUniformLocations[ pName ], 1, glm::value_ptr( pValue ) );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< glm::vec3 >( const glm::vec3& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform3fv( mUniformLocations[ pName ], 1, glm::value_ptr( pValue ) );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< glm::ivec3 >( const glm::ivec3& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform3iv( mUniformLocations[ pName ], 1, glm::value_ptr( pValue ) );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< glm::uvec3 >( const glm::uvec3& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform3uiv( mUniformLocations[ pName ], 1, glm::value_ptr( pValue ) );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< glm::vec2 >( const glm::vec2& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform2fv( mUniformLocations[ pName ], 1, glm::value_ptr( pValue ) );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< glm::ivec2 >( const glm::ivec2& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform2iv( mUniformLocations[ pName ], 1, glm::value_ptr( pValue ) );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< glm::uvec2 >( const glm::uvec2& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform2uiv( mUniformLocations[ pName ], 1, glm::value_ptr( pValue ) );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< float >( const float& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform1f( mUniformLocations[ pName ], pValue );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< int >( const int& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform1i( mUniformLocations[ pName ], pValue );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< unsigned int >( const unsigned int& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform1ui( mUniformLocations[ pName ], pValue );
}
}
/******************************************************************************
* ...
******************************************************************************/
template<>
inline void PtShaderProgram::set< bool >( const bool& pValue, const char* pName )
{
if ( mUniformLocations[ pName ] >= 0 )
{
glUniform1i( mUniformLocations[ pName ], pValue );
}
}
/******************************************************************************
* Shader (name, etc...)
******************************************************************************/
inline const char* PtShaderProgram::getName() const
{
return mName.c_str();
}
/******************************************************************************
* Shader info (name, etc...)
******************************************************************************/
inline void PtShaderProgram::setName( const char* pText )
{
mName = pText;
}
/******************************************************************************
* Shader info (name, etc...)
******************************************************************************/
inline const char* PtShaderProgram::getInfo() const
{
return mInfo.c_str();
}
/******************************************************************************
* Shader info (name, etc...)
******************************************************************************/
inline void PtShaderProgram::setInfo( const char* pText )
{
mInfo = pText;
}
} // namespace PtGraphics
| 8,981
|
C++
|
.h
| 252
| 33.916667
| 97
| 0.363229
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,989
|
PtCamera.h
|
ASTex-ICube_semiproctex/PPTBF_Structures_Src/PtGraphics/PtCamera.h
|
/*
* Publication: Semi-Procedural Textures Using Point Process Texture Basis Functions
* Authors: anonymous
*
* Code author: Pascal Guehl
*
* anonymous
* anonymous
*/
/**
* @version 1.0
*/
#ifndef _PT_CAMERA_H_
#define _PT_CAMERA_H_
/******************************************************************************
******************************* INCLUDE SECTION ******************************
******************************************************************************/
#include "PtGraphicsConfig.h"
// glm
#include <glm/glm.hpp>
/******************************************************************************
************************* DEFINE AND CONSTANT SECTION ************************
******************************************************************************/
/******************************************************************************
***************************** TYPE DEFINITION ********************************
******************************************************************************/
/******************************************************************************
******************************** CLASS USED **********************************
******************************************************************************/
/******************************************************************************
****************************** CLASS DEFINITION ******************************
******************************************************************************/
namespace PtGraphics
{
/**
* @class PtCamera
*
* @brief The PtCamera class provides ...
*
* ...
*/
class PTGRAPHICS_EXPORT PtCamera
{
/**************************************************************************
***************************** PUBLIC SECTION *****************************
**************************************************************************/
public:
/******************************* ATTRIBUTES *******************************/
/**
* Camera type
*/
enum ECameraType
{
ePerspective,
eOrthographic
};
/******************************** METHODS *********************************/
/**
* Default constructor.
*/
PtCamera();
/**
* Destructor.
*/
virtual ~PtCamera();
void tilt( float pValue );
void pan( float pValue );
void dolly( float pValue );
void truck( float pValue );
void pedestal( float pValue );
void zoom( float pValue );
void setEye( const glm::vec3& pPosition );
void setFront( const glm::vec3& pPosition );
void setUp( const glm::vec3& pDirection );
float getFovY() const;
void setFovY( float pValue );
float getAspect() const;
void setAspect( float pValue );
float getLeft() const;
void setLeft( float pValue );
float getRight() const;
void setRight( float pValue );
float getBottom() const;
void setBottom( float pValue );
float getTop() const;
void setTop( float pValue );
float getZNear() const;
void setZNear( float pValue );
float getZFar() const;
void setZFar( float pValue );
float getSensitivity() const;
void setSensitivity( float pValue );
glm::mat4 getViewMatrix() const;
glm::mat4 getProjectionMatrix() const;
void setCameraType( ECameraType pType );
/**************************************************************************
**************************** PROTECTED SECTION ***************************
**************************************************************************/
protected:
/******************************* ATTRIBUTES *******************************/
glm::vec3 mEye;
glm::vec3 mFront;
glm::vec3 mUp;
/**
* Perspective
*/
float mFovY;
float mAspect;
/**
* Orthographic
*/
float mLeft;
float mRight;
float mBottom;
float mTop;
float mZNear;
float mZFar;
float mSensitivity;
/**
* Camera type
*/
ECameraType mCameraType;
/******************************** METHODS *********************************/
/**************************************************************************
***************************** PRIVATE SECTION ****************************
**************************************************************************/
private:
/******************************* ATTRIBUTES *******************************/
/******************************** METHODS *********************************/
};
}
#endif
| 4,325
|
C++
|
.h
| 132
| 30.356061
| 84
| 0.354036
|
ASTex-ICube/semiproctex
| 39
| 8
| 2
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,990
|
mideaAC.cpp
|
Links2004_arduinoMideaAC/src/mideaAC.cpp
|
#include "mideaAC.h"
void acSerial::onStatusEvent(acSerialEvent cbEvent) {
_cbEvent = cbEvent;
}
void acSerial::begin(Stream * s, const char * name) {
if(!s) return;
_s = s;
_name = name;
_s->setTimeout(1000);
_needBytes = 0;
_cbEvent = nullptr;
loop();
uint8_t reset[] = { 0x00, 0x07, 0x00 };
write(0xFF, &reset[0], sizeof(reset));
write(0xFF, &reset[0], sizeof(reset));
write(0xFF, &reset[0], sizeof(reset));
}
void acSerial::send_getSN() {
uint8_t data[] = { 0x01, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x5e };
write(0xFF, &data[0], sizeof(data));
}
void acSerial::send_status(bool wifi, bool app) {
uint8_t data[] = { 0xAC, 0xB2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x01, 0x01, 0x02, 0x0A, 0x32, 0x0B, 0x0A, 0x00, (wifi ? 0x00 : 0x02), 0x00, (app ? 0x01 : 0x00), (app ? 0x01 : 0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
write_raw(&data[0], sizeof(data));
}
void acSerial::request_status() {
uint8_t data[] = { 0x00, 0x03, 0x41, 0x81, 0x00, 0xFF, 0x03, 0xFF, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xCD };
write(0xAC, &data[0], sizeof(data));
}
void acSerial::print_conf(ac_conf_t * conf) {
#ifdef AC_DEBUG_PORT
AC_DEBUG_PORT.printf("on: %d\n", conf->on);
AC_DEBUG_PORT.printf("soll: %d\n", conf->soll);
AC_DEBUG_PORT.printf("fan: %d\n", conf->fan);
AC_DEBUG_PORT.printf("mode: %d\n", conf->mode);
AC_DEBUG_PORT.printf("lamelle: %d\n", conf->lamelle);
AC_DEBUG_PORT.printf("turbo: %d\n", conf->turbo);
AC_DEBUG_PORT.printf("eco: %d\n", conf->eco);
#endif
}
void acSerial::print_status(ac_status_t * status) {
#ifdef AC_DEBUG_PORT
print_conf(&(status->conf));
AC_DEBUG_PORT.print("ist: ");
AC_DEBUG_PORT.println(status->ist);
AC_DEBUG_PORT.print("aussen: ");
AC_DEBUG_PORT.println(status->aussen);
#endif
}
void acSerial::send_conf_h(bool on, uint8_t soll, uint8_t fan, ac_mode_t mode, bool lamelle, bool turbo, bool eco) {
#ifdef AC_DEBUG_PORT
AC_DEBUG_PORT.printf("on: %d\n", on);
if(on) {
AC_DEBUG_PORT.printf("soll: %d\n", soll);
AC_DEBUG_PORT.printf("fan: %d\n", fan);
AC_DEBUG_PORT.printf("mode: %d\n", mode);
AC_DEBUG_PORT.printf("lamelle: %d\n", lamelle);
AC_DEBUG_PORT.printf("turbo: %d\n", turbo);
AC_DEBUG_PORT.printf("eco: %d\n", eco);
}
#endif
ac_conf_t conf;
switch(fan) {
case 1:
conf.fan = acFAN1;
break;
case 2:
conf.fan = acFAN2;
break;
case 3:
conf.fan = acFAN3;
break;
default:
case 0:
conf.fan = acFANA;
break;
}
conf.soll = soll;
conf.mode = mode;
conf.lamelle = (lamelle ? acLamelleHV : acLamelleOff);
conf.on = on;
conf.turbo = turbo;
conf.eco = eco;
send_conf(&conf);
}
void acSerial::send_conf(ac_conf_t * conf) {
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
uint8_t data[] = { 0x03, 0x02, 0x40, 0x42, 0x00, 0x00, 0x7F, 0x7F, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x04, 0xC0 };
data[3] = 0x42 | (conf->on & 0b1);
data[4] = (conf->soll & 0x0F) | ((conf->mode & 0x7) << 5);
data[5] = (conf->fan);
data[9] = 0x30 | (conf->lamelle & 0x0F);
if(conf->turbo) {
data[10] = 0x20;
data[12] = 0x02;
}
if(conf->eco) {
data[11] = 80;
}
write(0xAC, &data[0], sizeof(data));
}
void acSerial::handleMessage() {
ac_message_t * msg = (ac_message_t *)&_buf[0];
if(msg->header != 0xAA) {
return;
}
if(msg->len == 0x22 && msg->targed == 0xAC) {
if(msg->data[5] == 0x03 && msg->data[6] == 0x03 && msg->data[7] == 0xC0) {
// request_status answer
uint8_t * payload = &(msg->data[8]);
ac_status_t status;
status.conf.on = payload[0] & 0x01;
status.conf.soll = (payload[1] & 0x0F) + 16;
status.conf.mode = (ac_mode_t)((payload[1] >> 5) & 0x07);
status.conf.fan = (ac_fan_speed_t)payload[2];
status.conf.lamelle = (ac_lamelle_t)(payload[6] & 0x0F);
status.conf.turbo = (ac_lamelle_t)(payload[9] == 0x02);
status.conf.eco = (ac_lamelle_t)(payload[8] == 0x10);
status.ist = ((double)payload[10] * 0.5) - 25;
status.aussen = ((double)payload[11] * 0.5) - 25;
if(_cbEvent) {
_cbEvent(&status);
} else {
print_status(&status);
}
}
return;
}
}
bool acSerial::write(uint8_t target, uint8_t * data, uint8_t len) {
if(!_s) return false;
if(len <= 0 || len > 254) return false;
uint8_t raw_len = 6;
uint8_t raw[0xFF] = { 0x00 };
raw[0] = target;
raw_len += len;
memcpy(&raw[6], data, len);
return write_raw(raw, raw_len);
}
bool acSerial::write_raw(uint8_t * data, uint8_t len) {
if(!_s) return false;
if(!data) return false;
if(len <= 0 || len > 254) return false;
// Handle old data
loop();
// send data
_s->write(0xAA);
_s->write(len + 2);
_s->write(&data[0], len);
bool ok = _s->write(calcCheckSum(&data[0], len));
_s->flush();
delay(100);
if(data[0] == 0xAC) {
unsigned long start = millis();
while(_s->available() < 3) {
if(millis() - start >= 1000) {
#ifdef AC_DEBUG_PORT
AC_DEBUG_PORT.println("no Answer to write\n");
#endif
return false;
}
}
}
// Handle new data
loop();
return ok;
}
uint8_t acSerial::calcCheckSum(uint8_t * data, uint8_t len) {
uint8_t checkSum = len + 2;
for(uint8_t i = 0; i < len; i++) {
checkSum += data[i];
}
checkSum = (uint8_t)(checkSum ^ 0xFF) + 1;
return checkSum;
}
void acSerial::loop() {
if(!_s) return;
if(_needBytes == 0 && _s->available() >= 2) {
// AC_DEBUG_PORT.print(_name);
// AC_DEBUG_PORT.print(": ");
uint8_t header = _s->read();
if(header == 0xAA) {
_needBytes = _s->read() - 1;
_buf = (uint8_t *)malloc(_needBytes + 2);
_buf[0] = header;
_buf[1] = _needBytes + 1;
if(!_buf) {
#ifdef AC_DEBUG_PORT
AC_DEBUG_PORT.println("mallocFail");
#endif
_needBytes = 0;
return;
}
// AC_DEBUG_PORT.println("found start");
} else {
#ifdef AC_DEBUG_RAW
AC_DEBUG_PORT.print("wrong Header ");
AC_DEBUG_PORT.println(header, 16);
#endif
}
} else if(_needBytes > 0 && _needBytes >= _s->available()) {
if(_buf) {
#ifdef AC_DEBUG_RAW
AC_DEBUG_PORT.print(_name);
AC_DEBUG_PORT.print(": ");
#endif
size_t read = _s->readBytes(&_buf[2], _needBytes);
#ifdef AC_DEBUG_RAW
if(read != _needBytes) {
AC_DEBUG_PORT.print("short read ");
AC_DEBUG_PORT.print(read);
AC_DEBUG_PORT.print(" != ");
AC_DEBUG_PORT.print(_needBytes);
AC_DEBUG_PORT.print(" ");
}
#endif
uint8_t checkSum = calcCheckSum(&_buf[2], read - 1);
#ifdef AC_DEBUG_RAW
if(_buf[read + 1] != checkSum) {
AC_DEBUG_PORT.print("check Sum wrong ");
AC_DEBUG_PORT.print(_buf[read + 1], 16);
AC_DEBUG_PORT.print(" != ");
AC_DEBUG_PORT.print(checkSum, 16);
AC_DEBUG_PORT.print(" ");
}
for(uint8_t i = 0; i < (read + 2); i++) {
if(_buf[i] < 0x10) {
AC_DEBUG_PORT.write('0');
}
AC_DEBUG_PORT.print(_buf[i], 16);
AC_DEBUG_PORT.print(" ");
}
AC_DEBUG_PORT.println();
#endif
if(_buf[read + 1] == checkSum) {
handleMessage();
}
free(_buf);
_buf = NULL;
} else {
#ifdef AC_DEBUG_RAW
AC_DEBUG_PORT.println("missing buf");
#endif
}
_needBytes = 0;
#ifdef AC_DEBUG_RAW
AC_DEBUG_PORT.println();
#endif
}
}
| 8,658
|
C++
|
.cpp
| 250
| 27.084
| 238
| 0.518439
|
Links2004/arduinoMideaAC
| 37
| 8
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,991
|
mideaAC.h
|
Links2004_arduinoMideaAC/src/mideaAC.h
|
#ifndef _AC_control_H_
#define _AC_control_H_
#include <Arduino.h>
#ifndef __AVR__
#include <functional>
#endif
//#define AC_DEBUG_PORT DEBUG_ESP_PORT
//#define AC_DEBUG_RAW
#ifndef AC_DEBUG_PORT
#ifdef DEBUG_ESP_PORT
#define AC_DEBUG_PORT DEBUG_ESP_PORT
#endif
#endif
typedef enum {
acFAN1 = 0x28,
acFAN2 = 0x3C,
acFAN3 = 0x50,
acFANA = 0x66,
// 65 ??
} ac_fan_speed_t;
typedef enum {
acModeAuto = 0b001, // 1
acModeCool = 0b010, // 2
acModeDry = 0b011, // 3
acModeHeat = 0b100, // 4
acModeFan = 0b101, // 5
} ac_mode_t;
typedef enum {
acLamelleOff = 0b0000,
acLamelleH = 0b0011,
acLamelleV = 0b1100,
acLamelleHV = 0b1111,
} ac_lamelle_t;
typedef struct {
bool on;
bool turbo;
bool eco;
ac_mode_t mode;
ac_lamelle_t lamelle;
ac_fan_speed_t fan;
uint8_t soll;
} ac_conf_t;
typedef struct {
ac_conf_t conf;
double ist;
double aussen;
} ac_status_t;
class acSerial {
public:
#ifdef __AVR__
typedef void (*acSerialEvent)(ac_status_t * status);
#else
typedef std::function<void(ac_status_t * status)> acSerialEvent;
#endif
void onStatusEvent(acSerialEvent cbEvent);
void begin(Stream * s, const char * name);
void loop();
bool write(uint8_t target, uint8_t * data, uint8_t len);
void send_getSN();
void send_status(bool wifi, bool app);
void request_status();
void send_conf(ac_conf_t * conf);
void send_conf_h(bool on, uint8_t soll, uint8_t fan, ac_mode_t mode, bool lamelle = false, bool turbo = false, bool eco = false);
void print_conf(ac_conf_t * conf);
void print_status(ac_status_t * status);
protected:
Stream * _s = NULL;
const char * _name = NULL;
uint8_t * _buf = NULL;
uint8_t _needBytes = 0;
acSerialEvent _cbEvent;
void handleMessage();
uint8_t calcCheckSum(uint8_t * data, uint8_t len);
bool write_raw(uint8_t * data, uint8_t len);
};
typedef struct {
uint8_t header;
uint8_t len;
uint8_t targed;
uint8_t data[0];
} __attribute__((packed)) ac_message_t;
#endif /* _AC_control_H_ */
| 2,143
|
C++
|
.h
| 82
| 22.487805
| 133
| 0.648728
|
Links2004/arduinoMideaAC
| 37
| 8
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,996
|
options.cpp
|
jwr-git_pwcoco/src/options.cpp
|
/*
*
* PWCOCO
*
*
* With major thanks to the GCTA-COJO and COLOC R package teams!
*/
#include "options.h"
int main(int argc, char* argv[])
{
spdlog::info(" ****************************************");
spdlog::info(" *______ _ _ _____ _____ *");
spdlog::info(" *| ___ \\ | | / __ \\ / __ \\ *");
spdlog::info(" *| |_/ / | | | / \\/ ___ | / \\/ ___ *");
spdlog::info(" *| __/| |/\\| | | / _ \\| | / _ \\ *");
spdlog::info(" *| | \\ /\\ / \\__/\\ (_) | \\__/\\ (_) |*");
spdlog::info(" *\\_| \\/ \\/ \\____/\\___/ \\____/\\___/ *");
spdlog::info(" * *");
spdlog::info(" ****************************************");
spdlog::info("Version: 1.1.1");
spdlog::info("!! Remember to periodically 'git pull' in your PWCoCo directory to obtain the latest updates and bug fixes !!");
/*
* Option reading
*/
unsigned short chr = 0;
int i = 0, threads = 8;
double p_cutoff1 = 5e-8, p_cutoff2 = 5e-8,
collinear = 0.9, maf = 0.1, ld_window = 1.0e7,
freq_threshold = 0.2, init_h4 = 80, top_snp = 1e10,
p1 = 1e-4, p2 = 1e-4, p3 = 1e-5,
n1 = 0.0, n2 = 0.0, n1_case = 0.0, n2_case = 0.0,
pve1 = -1.0, pve2 = -1.0;
string bfile = "", bim_file = "", fam_file = "", bed_file = "",
phen1_file = "", phen2_file = "",
out = "pwcoco_out", log = "pwcoco_log", snplist = "",
pve_file1 = "", pve_file2 = "",
opt;
bool out_cond = false, cond_ssize = false,
verbose = false,
data_folder = false, // Whether the data is in folders or files
pairwise = false; // Whether to run PWCoCo on the pairwise combination of folders or not (if folders are given)
for (i = 1; i < argc; i++) {
opt = argv[i];
if (opt == "--version") {
spdlog::info("Version: 1.1.1");
}
if (opt == "--help") {
spdlog::info("Usage: pwcoco [options]");
spdlog::info("");
spdlog::info("Please remember to periodically check for new updates using git pull!");
spdlog::info("More information about these flags and how to use PWCoCo can be found on GitHub:");
spdlog::info("https://github.com/jwr-git/pwcoco");
spdlog::info("");
spdlog::info("Required flags:");
spdlog::info(" --bfile Location to the reference data in Plink (bed/bim/fam) format.");
spdlog::info(" Do not include the file ending name.");
spdlog::info(" Each file requires the same name and be in the same directory.");
spdlog::info("");
spdlog::info(" --sum_stats1, sum_stats2 Location to the first file or folder containing summary statistics.");
spdlog::info("");
spdlog::info("Optional flags:");
spdlog::info(" --pve_file1, pve_file2 Files from which to calculate the phenotypic variance for the summary statistics.");
spdlog::info("");
spdlog::info(" --pve1, pve2 If the phenotypic variance has already been calculated, you can specify it directly here.");
spdlog::info("");
spdlog::info(" --log Specify log name; default is 'pwcoco_log.txt' and will save in the current directory.");
spdlog::info("");
spdlog::info(" --out Prefix for all output files for this analysis.");
spdlog::info("");
spdlog::info(" --p_cutoff P value cutoff for SNPs to be selected by the stepwise selection process; default is 5e-8.");
spdlog::info(" Alternatively, --p_cutoff1 and --p_cutoff2 can specify dataset-specific P value cutoffs.");
spdlog::info("");
spdlog::info(" --chr Limit the reference data to reading only this chromosome.");
spdlog::info("");
spdlog::info(" --top_snp Maximum number of SNPs that can be selected by the stepwise selection process; default 1e10.");
spdlog::info("");
spdlog::info(" --ld_window Distance in kb that is assumed for SNPs to be in total linkage equilibrium; default is 1e7.");
spdlog::info("");
spdlog::info(" --collinear Threshold that determines if SNPs are collinear; default is 0.9.");
spdlog::info("");
spdlog::info(" --maf Filters SNPs from the reference dataset according to this threshold; default is 0.1.");
spdlog::info("");
spdlog::info(" --freq_threshold Exclude SNPs with an allele frequency difference between the sum stats and the reference data");
spdlog::info(" greater than this threshold; default is 0.2.");
spdlog::info("");
spdlog::info(" --init_h4 Treshold to termine the program early if the initial colocalisation H4 is higher than this; default 80.");
spdlog::info("");
spdlog::info(" --out_cond Flag to turn on extra files to be output corresponding to the conditioned data.");
spdlog::info("");
spdlog::info(" --coloc_pp Specify the three prior probabilities; default 1e-4, 1e-4 and 1e-5.");
spdlog::info("");
spdlog::info(" --n1, n2 Specify the sample size for summary statistics.");
spdlog::info("");
spdlog::info(" --n1_case, n2_case Specific the number of cases for summary statistics.");
spdlog::info("");
spdlog::info(" --threads Number of threads available for OpenMP multi-threaded functions; default is 8.");
spdlog::info("");
spdlog::info(" --verbose Output extra files and messages for debugging purposes.");
spdlog::info("");
spdlog::info(" --pairwise If using folders as input, will run PWCoCo on the pairwise combination of files.");
spdlog::info(" Without this flag, the files must match based on name.");
}
if (opt == "--bfile") {
bfile = argv[++i];
if (bfile.substr(bfile.length() - 5) == ".bfile")
bfile = bfile.substr(0, bfile.length() - 5);
bim_file = bfile + ".bim";
fam_file = bfile + ".fam";
bed_file = bfile + ".bed";
spdlog::info("Using {} as reference files.", bfile);
}
else if (opt == "--phen1_file" || opt == "--sum_stats1") {
phen1_file = argv[++i];
spdlog::info("Using {} summary statistic 1 files or folders.", phen1_file);
}
else if (opt == "--phen2_file" || opt == "--sum_stats2") {
phen2_file = argv[++i];
spdlog::info("Using {} summary statistic 2 files or folders.", phen2_file);
}
else if (opt == "--pve_file1") {
pve_file1 = argv[++i];
spdlog::info("Calculating phenotypic variance from {}.", pve_file1);
}
else if (opt == "--pve_file2") {
pve_file2 = argv[++i];
spdlog::info("Calculating phenotypic variance from {}.", pve_file2);
}
else if (opt == "--n1") {
n1 = stod(argv[++i]);
if (n1 <= 0) {
n1 = 0;
}
spdlog::info("--n1 {}.", n1);
}
else if (opt == "--n2") {
n2 = stod(argv[++i]);
if (n2 <= 0) {
n2 = 0;
}
spdlog::info("--n2 {}.", n2);
}
else if (opt == "--n1_case") {
n1_case = stod(argv[++i]);
if (n1_case <= 0) {
n1_case = 0;
}
spdlog::info("--n1_case {}.", n1_case);
}
else if (opt == "--n2_case") {
n2_case = stod(argv[++i]);
if (n2_case <= 0) {
n2_case = 0;
}
spdlog::info("--n2_case {}.", n2_case);
}
else if (opt == "--log") {
log = argv[++i];
spdlog::info("--log {}.", log);
}
else if (opt == "--p_cutoff") {
p_cutoff1 = p_cutoff2 = stod(argv[++i]);
spdlog::info("--p_cutoff {}.", p_cutoff1);
}
else if (opt == "--p_cutoff1") {
p_cutoff1 = stod(argv[++i]);
spdlog::info("--p_cutoff1 {}.", p_cutoff1);
}
else if (opt == "--p_cutoff2") {
p_cutoff2 = stod(argv[++i]);
spdlog::info("--p_cutoff2 {}.", p_cutoff2);
}
else if (opt == "--out") {
out = argv[++i];
spdlog::info("--out {}.", out);
}
else if (opt == "--chr") {
chr = (unsigned short)stoi(argv[++i]);
if (chr < 1 || chr > 23) {
chr = (chr < 1 ? 1 : chr > 23 ? 23 : chr);
}
spdlog::info("--chr {}.", chr);
}
else if (opt == "--top_snp") {
top_snp = stod(argv[++i]);
if (top_snp < 1 || top_snp > 10000) {
top_snp = (top_snp <= 1 ? 1 : top_snp >= 10000 ? 10000 : top_snp);
}
spdlog::info("--top_snp {}.", top_snp);
}
else if (opt == "--ld_window") {
ld_window = stoi(argv[++i]);
if (ld_window > 10000) {
ld_window = 10000;
}
ld_window *= 1000;
spdlog::info("--ld_window {}.", ld_window);
}
else if (opt == "--collinear") {
collinear = stod(argv[++i]);
if (collinear < 0.01 || collinear > 0.99) {
collinear = (collinear <= 0.01 ? 0.01 : collinear >= 0.99 ? 0.99 : collinear);
}
spdlog::info("--collinear {}.", collinear);
}
else if (opt == "--maf") {
maf = stod(argv[++i]);
if (maf < 0.0 || maf > 0.5) {
maf = (maf < 0.0 ? 0.0 : maf > 0.5 ? 0.5 : maf);
}
spdlog::info("--maf {}.", maf);
}
else if (opt == "--freq_threshold") {
freq_threshold = stod(argv[++i]);
if (freq_threshold < 0.0 || freq_threshold > 1.0) {
freq_threshold = (freq_threshold < 0.0 ? 0.0 : freq_threshold > 1.0 ? 1.0 : freq_threshold);
}
spdlog::info("--freq_threshold {}.", freq_threshold);
}
else if (opt == "--init_h4") {
init_h4 = stod(argv[++i]);
if (init_h4 < 0.0 || init_h4 > 100.0) {
init_h4 = (init_h4 < 0.0 ? 0.0 : init_h4 > 100.0 ? 100.0 : init_h4);
}
spdlog::info("--init_h4 {}.", init_h4);
}
else if (opt == "--out_cond") {
out_cond = true;
spdlog::info("--out_cond.");
}
else if (opt == "--coloc_pp") {
p1 = stod(argv[++i]);
p2 = stod(argv[++i]);
p3 = stod(argv[++i]);
p1 = (p1 > 1.0 ? 1.0 : p1 < 1e-50 ? 1e-50 : p1);
p2 = (p2 > 1.0 ? 1.0 : p2 < 1e-50 ? 1e-50 : p2);
p3 = (p3 > 1.0 ? 1.0 : p3 < 1e-50 ? 1e-50 : p3);
spdlog::info("--coloc_pp p1 {} p2 {} p3 {}.", p1, p2, p3);
}
else if (opt == "--cond_ssize") {
cond_ssize = true;
spdlog::info("--cond_ssize.");
}
else if (opt == "--threads") {
threads = stoi(argv[++i]);
spdlog::info("--threads {}.", threads);
}
else if (opt == "--verbose") {
verbose = true;
out_cond = true;
spdlog::info("--verbose.");
}
else if (opt == "--pve1") {
pve1 = stod(argv[++i]);
spdlog::info("--pve1 {}.", pve1);
}
else if (opt == "--pve2") {
pve2 = stod(argv[++i]);
spdlog::info("--pve2 {}.", pve2);
}
else if (opt == "--pairwise") {
pairwise = true;
spdlog::info("--pairwise.");
}
}
// First set up the logger
vector<spdlog::sink_ptr> sinks;
#ifdef _WIN32
sinks.push_back(make_shared<spdlog::sinks::wincolor_stdout_sink_mt>());
#else
sinks.push_back(make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>());
#endif
try {
sinks.push_back(make_shared<spdlog::sinks::basic_file_sink_mt>(log + ".txt"));
auto logger = make_shared<spdlog::logger>("pwcoco_log", begin(sinks), end(sinks));
spdlog::set_default_logger(logger);
}
catch (const spdlog::spdlog_ex &ex) {
cout << "Log setup failed: " << ex.what() << " - attempting to create default log \"pwcoco_log.txt\"." << endl;
sinks.push_back(make_shared<spdlog::sinks::basic_file_sink_mt>("pwcoco_log.txt"));
auto logger = make_shared<spdlog::logger>("pwcoco_log", begin(sinks), end(sinks));
spdlog::set_default_logger(logger);
}
spdlog::flush_on(spdlog::level::info);
// Some analytics why not?
chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
// .bim file MUST be supplied
if (bim_file.compare("") == 0) {
spdlog::critical("No .bim file found; a .bim file MUST be supplied!");
return 0;
}
//else if (!file_exists(bim_file)) {
// spdlog::critical(".bim file {} cannot be opened.", bim_file);
// return;
//}
// .fam file MUST be supplied
if (fam_file.compare("") == 0) {
spdlog::critical("No .fam file found; a .fam file MUST be supplied!");
return 0;
}
//else if (!file_exists(fam_file)) {
// spdlog::critical(".fam file {} cannot be opened.", fam_file);
// return 0;
//}
// Check if summary stats 1 is file or directory
const fs::path path(phen1_file);
error_code ec;
if (fs::is_directory(path, ec)) {
data_folder = true;
spdlog::info("Summary stats 1 is treated as a folder.");
spdlog::warn("Passing folders as the summary statistics arguments is a beta feature and may be buggy. Please do not use this feature to inform on active analyses!");
}
else if (fs::is_regular_file(path, ec)) {
data_folder = false;
spdlog::info("Summary stats 1 is treated as a file.");
}
// Check to see if summary stats 2 matches 1
const fs::path path2(phen2_file);
error_code ec2;
if (data_folder && fs::is_directory(path2, ec2)) {
spdlog::info("Summary stats 2 is treated as a folder.");
}
else if (data_folder && !fs::is_directory(path2, ec2)) {
spdlog::info("Summary stats 2 expected to be a folder but is not. Please fix this before continuing.");
return 0;
}
else if (!data_folder && fs::is_regular_file(path2, ec2)) {
spdlog::info("Summary stats 2 is treated as a file.");
}
else if (!data_folder && !fs::is_regular_file(path2, ec2)) {
spdlog::info("Summary stats 2 expected to be a file but is not. Please fix this before continuing.");
return 0;
}
#if defined(_OPENMP)
omp_set_dynamic(0);
omp_set_num_threads(threads);
spdlog::info("OpenMP will attempt to use up to {} threads.", threads);
#endif
// Set up for some common variables
reference *ref = new reference(out, chr); // Reference dataset
init_h4 /= 100; // coloc returns h4 as a decimal
// Depending on whether the summary statistics are given as a folder
// or as separate files, we either:
// 1. Load the reference panel into memory and preserve it across analyses (folders)
// 2. Load the necessary SNPs from the reference panel (files)
// These steps should increase efficiency and speed for the two different cases
if (data_folder)
{
// Case 1
// Folders were given
// therefore we expect the same file name in two different folders
using recursive_directory_iterator = fs::recursive_directory_iterator;
for (const auto &dir_entry : recursive_directory_iterator(phen1_file))
{
string filename{ dir_entry.path().filename().u8string() },
path_to_file1{ dir_entry.path().u8string() };
for (const auto &dir_entry2 : recursive_directory_iterator(phen2_file))
{
string filename2{ dir_entry2.path().filename().u8string() },
path_to_file2{ dir_entry2.path().u8string() };
if (!pairwise && !path_to_file1.compare(path_to_file2)) {
continue;
}
phenotype *exposure = init_pheno(path_to_file1, filename + (pairwise ? "" : ".exp"), n1, n1_case, pve1, pve_file1);
phenotype *outcome = init_pheno(path_to_file2, filename2 + (pairwise ? "" : ".out"), n2, n2_case, pve2, pve_file2);
if (exposure->has_failed() || outcome->has_failed()) {
spdlog::error("Reading of either summary statistic files has failed; have these been moved or altered?");
spdlog::error("File 1: {}", path_to_file1);
spdlog::error("File 2: {}", path_to_file2);
continue;
}
if (initial_coloc(exposure, outcome, out, p1, p2, p3, init_h4)) {
continue;
}
if (!ref->is_ready()) {
// Bim-related first
if (ref->read_bimfile(bim_file) == 0) {
return 0;
}
// In case 1, we load all of the SNPs in the reference data as they may be required
ref->whole_bim();
ref->sanitise_list();
// Fam-related
if (ref->read_famfile(fam_file) == 0) {
return 0;
}
// Finally bed-related
if (ref->read_bedfile(bed_file) == 0) {
return 0;
}
}
else {
// Need to clear previous matching
ref->reset_vectors();
}
// Match SNPs to bim
ref->match_bim(exposure->get_snp_names(), outcome->get_snp_names(), true);
ref->sanitise_list();
if (maf > 0.0) {
if (ref->filter_snp_maf(maf) == 0)
return 0;
}
// Do the related conditional and colocalisation analyses
if (pwcoco_sub(exposure, outcome, ref, p_cutoff1, p_cutoff2, collinear, ld_window, out, top_snp, freq_threshold, cond_ssize, out_cond, p1, p2, p3, verbose)) {
continue;
}
}
}
}
else {
// Case 2
// Files were given
phenotype *exposure = init_pheno(phen1_file, fs::path(phen1_file).filename().string(), n1, n1_case, pve1, pve_file1);
phenotype *outcome = init_pheno(phen2_file, fs::path(phen2_file).filename().string(), n2, n2_case, pve2, pve_file2);
if (exposure->has_failed() || outcome->has_failed()) {
spdlog::critical("Reading of either summary statistic files has failed; have these been moved or altered?");
return 1;
}
if (initial_coloc(exposure, outcome, out, p1, p2, p3, init_h4)) {
return 0;
}
// Bim-related first
if (ref->read_bimfile(bim_file) == 0) {
return 0;
}
// In case 2, we only need those SNPs which have already been matched between the exposure and the outcome
ref->match_bim(exposure->get_snp_names(), outcome->get_snp_names(), false);
ref->sanitise_list();
// Fam-related
if (ref->read_famfile(fam_file) == 0) {
return 0;
}
// Finally bed-related
if (ref->read_bedfile(bed_file) == 0) {
return 0;
}
//ref->calculate_allele_freq();
if (maf > 0.0) {
if (ref->filter_snp_maf(maf) == 0)
return 0;
}
// Do the related conditional and colocalisation analyses
if (pwcoco_sub(exposure, outcome, ref, p_cutoff1, p_cutoff2, collinear, ld_window, out, top_snp, freq_threshold, cond_ssize, out_cond, p1, p2, p3, verbose)) {
return 0;
}
}
#ifdef PYTHON_INC
Py_Finalize();
#endif
chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
spdlog::info("Analysis finished. Computational time: {} secs", (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000000.0);
return 0;
}
/*
* Common function to do the initial pass of colocalisation
* @param phenotype exposure read exposure data
* @param phenotype outcome read outcome data
* @param double p1 value for coloc p1
* @param double p2 value for coloc p2
* @param double p3 value for coloc p3
* @param double init_h4 H4 threshold
* @ret int
*/
int initial_coloc(phenotype *exposure, phenotype *outcome, string out, double p1, double p2, double p3, double init_h4)
{
// First pass through - match data and perform coloc
mdata *matched = new mdata(exposure, outcome);
coloc_analysis *initial_coloc = new coloc_analysis(matched, out, p1, p2, p3);
if (initial_coloc->num_snps() == 0) {
spdlog::info("Stopping algorthim as no SNPs included in initial colocalisation analysis.");
return 1;
}
initial_coloc->init_coloc(exposure->get_phenoname(), outcome->get_phenoname());
if (initial_coloc->pp_abf[H4] > init_h4) {
spdlog::info("Stopping algorthim as H4 for initial colocalisation analysis is already at or above threshold ({}%).", init_h4 * 100);
return 1;
}
delete(initial_coloc);
return 0;
}
/*
* Common function to run the subsequent conditional and colocalisation analyses
*/
int pwcoco_sub(phenotype *exposure, phenotype *outcome, reference *ref, double p_cutoff1, double p_cutoff2, double collinear, double ld_window, string out, double top_snp,
double freq_threshold, double cond_ssize, bool out_cond, double p1, double p2, double p3, bool verbose)
{
// Holder for the conditional matrices
conditional_dat *exp_cdat = new conditional_dat();
conditional_dat *out_cdat = new conditional_dat();
// Find each independent SNPs for both exposure and outcome data
cond_analysis *exp_analysis = new cond_analysis(p_cutoff1, collinear, ld_window, out, top_snp, freq_threshold, exposure->get_phenoname(), cond_ssize, verbose);
exp_analysis->init_conditional(exposure, ref);
exp_analysis->find_independent_snps(exp_cdat, ref);
cond_analysis *out_analysis = new cond_analysis(p_cutoff2, collinear, ld_window, out, top_snp, freq_threshold, outcome->get_phenoname(), cond_ssize, verbose);
out_analysis->init_conditional(outcome, ref);
out_analysis->find_independent_snps(out_cdat, ref);
// If both of the conditionals failed - don't continue
if (exp_analysis->get_num_ind() == 0 && out_analysis->get_num_ind() == 0)
{
spdlog::warn("Both conditional analyses failed to run or find any conditionally independednt signals, and so no colocalisation will be run.");
return 1;
}
spdlog::info("There are {} selected SNPs in the exposure dataset and {} in the outcome dataset.", exp_analysis->get_num_ind(), out_analysis->get_num_ind());
spdlog::info("Performing {} conditional and colocalisation analyses.", (exp_analysis->get_num_ind() == 0 ? 1 : exp_analysis->get_num_ind()) * (out_analysis->get_num_ind() == 0 ? 1 : out_analysis->get_num_ind()));
#ifdef PYTHON_INC
Py_Initialize();
PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
#endif
// Perform PWCoCo!
//#pragma omp parallel for
for (int i = 0; i < exp_analysis->get_num_ind() + 1; i++)
{
string exp_snp_name = "", out_snp_name = "";
if (i < exp_analysis->get_num_ind())
{
// New conditional data struct for parallelisation
conditional_dat *par_exp_cdat = new conditional_dat(*exp_cdat);
exp_analysis->pw_conditional(exp_analysis->get_num_ind() > 1 ? i : -1, out_cond, par_exp_cdat, ref); // Be careful not to remove the only independent SNP
exp_snp_name = exp_analysis->get_ind_snp_name(i);
delete(par_exp_cdat);
}
else if (i >= exp_analysis->get_num_ind())
{
exp_snp_name = "unconditioned";
}
for (int j = 0; j < out_analysis->get_num_ind() + 1; j++)
{
if (j < out_analysis->get_num_ind())
{
conditional_dat *par_out_cdat = new conditional_dat(*out_cdat);
out_analysis->pw_conditional(out_analysis->get_num_ind() > 1 ? j : -1, out_cond, par_out_cdat, ref);
out_snp_name = out_analysis->get_ind_snp_name(j);
delete(par_out_cdat);
}
else if (j >= out_analysis->get_num_ind())
{
out_snp_name = "unconditioned";
}
if (exp_snp_name == "unconditioned" && out_snp_name == "unconditioned")
continue;
mdata *matched_conditional;
if (exp_snp_name == "unconditioned")
matched_conditional = new mdata(out_analysis, exposure);
else if (out_snp_name == "unconditioned")
matched_conditional = new mdata(exp_analysis, outcome);
else
matched_conditional = new mdata(exp_analysis, out_analysis);
coloc_analysis *conditional_coloc = new coloc_analysis(matched_conditional, out, p1, p2, p3);
conditional_coloc->init_coloc(exp_snp_name, out_snp_name, exp_analysis->get_cond_name(), out_analysis->get_cond_name());
delete(matched_conditional);
delete(conditional_coloc);
}
}
return 0;
}
| 22,552
|
C++
|
.cpp
| 555
| 37.136937
| 213
| 0.621455
|
jwr-git/pwcoco
| 36
| 4
| 10
|
GPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,051
|
demo.cpp
|
kikkimo_WgsToGcj/test/demo.cpp
|
#include "WGS2GCJ.h"
#include <iostream>
#include <vector>
#include <omp.h>
#include <assert.h>
#include <time.h>
#include <conio.h>
/**
* \brief Check if the point in china roughly
*
* \param [in] lon: longitude of geodetic point, unit degree
* \param [in] lat: latitude of geodetic point,unit degree
* \return Returns true if point in china
* \time 15:22:01 2020/06/12
*/
bool OutOfChina(const double& lon, const double& lat) {
return !(72.004 <= lon && lon <= 137.8347 &&
0.8293 <= lat && lat <= 55.8271);
}
void TestCase1()
{
double lonWgs = 116.39123343289631;
double latWgs = 39.9072885060602;
std::cout.precision(16);
std::cout << "WGS84 Point: (" << lonWgs << ", " << latWgs << ")\n";
auto [lonGcj, latGcj] = Wgs2Gcj(lonWgs, latWgs);
std::cout << "GCJ-02 Point [Wgs2Gcj]: (" << lonGcj << ", " << latGcj << ")\n";
//simple linear iteration
auto [lonWgsNS, latWgsNS] = Gcj2Wgs_SimpleIteration(lonGcj, latGcj);
std::cout << "WGS84 Point [simple linear iteration]: (" << lonWgsNS << ", " << latWgsNS << ")\n";
//numerically differentiated cost function
auto [lonWgsND, latWgsND] = Gcj2Wgs_NumbericDiff(lonGcj, latGcj);
std::cout << "WGS84 Point [numerically derivation]: (" << lonWgsND << ", " << latWgsND << ")\n";
//analytical differentiated cost function
auto [lonWgsNAn, latWgsNAn] = Gcj2Wgs_AnalyticDiff(lonGcj, latGcj);
std::cout << "WGS84 Point [analytical derivation]: (" << lonWgsNAn << ", " << latWgsNAn << ")\n";
#ifdef _USE_CERES
//auto differentiable, use ceres
auto [lonWgsNA, latWgsNA] = Gcj2Wgs_AutoDiff(lonGcj, latGcj);
std::cout << "WGS84 Point [auto differentiable]: (" << lonWgsNA << ", " << latWgsNA << ")\n";
#endif
}
void TestCase2()
{
//range of china
std::vector<double> wgslonRange, wgslatRange;
for (double wgslon = 72.004; wgslon <= 137.8347; wgslon += 0.01)
{
for (double wgslat = 0.8293; wgslat <= 55.8271; wgslat += 0.01)
{
if (OutOfChina(wgslon, wgslat))
continue;
wgslonRange.push_back(wgslon);
wgslatRange.push_back(wgslat);
}
}
size_t size = wgslonRange.size();
assert(size == wgslatRange.size());
double lfXMin = DBL_MAX;
double lfXMax = 0.0l;
double lfXAverage = 0.0l;
double lfYMin = DBL_MAX;
double lfYMax = 0.0l;
double lfYAverage = 0.0l;
int counts = 0;
long t_begin = clock();
#pragma omp parallel for
for (long i = 0; i < size; ++i)
{
auto [gcj02lon, gcj02lat] = Wgs2Gcj(wgslonRange[i], wgslatRange[i]);
auto [wgslonN, wgslatN] = Gcj2Wgs_SimpleIteration(gcj02lon, gcj02lat);
double lfXError = wgslonN - wgslonRange[i];
double lfYError = wgslatN - wgslatRange[i];
double lfXE = fabs(lfXError);
double lfYE = fabs(lfYError);
#pragma omp critical
{
lfXMin = fabs(lfXMin) < lfXE ? lfXMin : lfXError;
lfXMax = fabs(lfXMax) > lfXE ? lfXMax : lfXError;
lfYMin = fabs(lfYMin) < lfYE ? lfYMin : lfYError;
lfYMax = fabs(lfYMax) > lfYE ? lfYMax : lfYError;
lfXAverage += lfXE * lfXE;
lfYAverage += lfYE * lfYE;
counts++;
}
}
lfXAverage /= counts;
lfYAverage /= counts;
lfXAverage = sqrt(lfXAverage);
lfYAverage = sqrt(lfYAverage);
long t_end = clock();
std::cout << "| SimpleIteration: " << counts << " case finished!" << std::endl;
std::cout << "| minimum X error: " << lfXMin << std::endl;
std::cout << "| maximum X error: " << lfXMax << std::endl;
std::cout << "| average X error: " << lfXAverage << std::endl;
std::cout << "| minimum Y error: " << lfYMin << std::endl;
std::cout << "| maximum Y error: " << lfYMax << std::endl;
std::cout << "| average Y error: " << lfYAverage << std::endl;
std::cout << "| time use: " << t_end - t_begin << " ms" << std::endl;
lfXMin = DBL_MAX;
lfXMax = 0.0l;
lfXAverage = 0.0l;
lfYMin = DBL_MAX;
lfYMax = 0.0l;
lfYAverage = 0.0l;
counts = 0;
t_begin = clock();
#pragma omp parallel for
for (long i = 0; i < size; ++i)
{
auto [gcj02lon, gcj02lat] = Wgs2Gcj(wgslonRange[i], wgslatRange[i]);
auto [wgslonN, wgslatN] = Gcj2Wgs_AnalyticDiff(gcj02lon, gcj02lat);
double lfXError = wgslonN - wgslonRange[i];
double lfYError = wgslatN - wgslatRange[i];
double lfXE = fabs(lfXError);
double lfYE = fabs(lfYError);
#pragma omp critical
{
lfXMin = fabs(lfXMin) < lfXE ? lfXMin : lfXError;
lfXMax = fabs(lfXMax) > lfXE ? lfXMax : lfXError;
lfYMin = fabs(lfYMin) < lfYE ? lfYMin : lfYError;
lfYMax = fabs(lfYMax) > lfYE ? lfYMax : lfYError;
lfXAverage += lfXE * lfXE;
lfYAverage += lfYE * lfYE;
counts++;
}
}
lfXAverage /= counts;
lfYAverage /= counts;
lfXAverage = sqrt(lfXAverage);
lfYAverage = sqrt(lfYAverage);
t_end = clock();
std::cout << "| analytical derivation: " << counts << " case finished!" << std::endl;
std::cout << "| minimum X error: " << lfXMin << std::endl;
std::cout << "| maximum X error: " << lfXMax << std::endl;
std::cout << "| average X error: " << lfXAverage << std::endl;
std::cout << "| minimum Y error: " << lfYMin << std::endl;
std::cout << "| maximum Y error: " << lfYMax << std::endl;
std::cout << "| average Y error: " << lfYAverage << std::endl;
std::cout << "| time use: " << t_end - t_begin << " ms" << std::endl;
lfXMin = DBL_MAX;
lfXMax = 0.0l;
lfXAverage = 0.0l;
lfYMin = DBL_MAX;
lfYMax = 0.0l;
lfYAverage = 0.0l;
counts = 0;
t_begin = clock();
#pragma omp parallel for
for (long i = 0; i < size; ++i)
{
auto [gcj02lon, gcj02lat] = Wgs2Gcj(wgslonRange[i], wgslatRange[i]);
auto [wgslonN, wgslatN] = Gcj2Wgs_NumbericDiff(gcj02lon, gcj02lat);
double lfXError = wgslonN - wgslonRange[i];
double lfYError = wgslatN - wgslatRange[i];
double lfXE = fabs(lfXError);
double lfYE = fabs(lfYError);
#pragma omp critical
{
lfXMin = fabs(lfXMin) < lfXE ? lfXMin : lfXError;
lfXMax = fabs(lfXMax) > lfXE ? lfXMax : lfXError;
lfYMin = fabs(lfYMin) < lfYE ? lfYMin : lfYError;
lfYMax = fabs(lfYMax) > lfYE ? lfYMax : lfYError;
lfXAverage += lfXE * lfXE;
lfYAverage += lfYE * lfYE;
counts++;
}
}
lfXAverage /= counts;
lfYAverage /= counts;
lfXAverage = sqrt(lfXAverage);
lfYAverage = sqrt(lfYAverage);
t_end = clock();
std::cout << "| numerically differentiated: " << counts << " case finished!" << std::endl;
std::cout << "| minimum X error: " << lfXMin << std::endl;
std::cout << "| maximum X error: " << lfXMax << std::endl;
std::cout << "| average X error: " << lfXAverage << std::endl;
std::cout << "| minimum Y error: " << lfYMin << std::endl;
std::cout << "| maximum Y error: " << lfYMax << std::endl;
std::cout << "| average Y error: " << lfYAverage << std::endl;
std::cout << "| time use: " << t_end - t_begin << " ms" << std::endl;
}
int main()
{
TestCase1();
TestCase2();
getch();
return 0;
}
| 6,657
|
C++
|
.cpp
| 189
| 32.84127
| 98
| 0.648552
|
kikkimo/WgsToGcj
| 36
| 9
| 0
|
GPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,052
|
WGS2GCJ.cpp
|
kikkimo_WgsToGcj/src/WGS2GCJ.cpp
|
#include <iostream>
#include <cmath>
#include "WGS2GCJ.h"
#ifdef _USE_CERES
#include <ceres/ceres.h>
#endif
//Beijing54 Geodetic coordinate system (Krasovsky reference ellipsoid)
constexpr double kKRASOVSKY_A = 6378245.0; // equatorial radius [unit: meter]
constexpr double kKRASOVSKY_B = 6356863.0187730473; // polar radius
constexpr double kKRASOVSKY_ECCSQ = 6.6934216229659332e-3; // first eccentricity squared
constexpr double kKRASOVSKY_ECC2SQ = 6.7385254146834811e-3; // second eccentricity squared
constexpr double PI = 3.14159265358979323846; //π
constexpr double kDEG2RAD = PI / 180.0;
constexpr double kRAD2DEG = 180.0 / PI;
/**
* \brief Angle unit transform, degree to radian
*
* \param [in] deg: angle in degrees
* \return Returns angle in radians
* \time 15:21:22 2020/06/12
*/
constexpr inline double Deg2Rad(const double deg) {
return deg * kDEG2RAD;
}
/**
* \brief Angle unit transform, radian to degree
*
* \param [in] rad: angle in radians
* \return Returns angle in degrees
* \time 15:21:01 2020/06/12
*/
constexpr inline double Rad2Deg(const double rad) {
return rad * kRAD2DEG;
}
/**
* \brief Get geodetic offset used by GCJ-02
*
* \param [in] wgs84lon: longitude in WGS84 coordinate system [unit:degree]
* \param [in] wgs84lat: latitude in WGS84 coordinate system [unit:degree]
* \return Returns a pair of geodetic offset used by GCJ-02
* \time 15:28:33 2020/06/12
*/
std::pair<double,double> GetGeodeticOffset(const double& wgs84lon,const double& wgs84lat)
{
//get geodetic offset relative to 'center china'
double lon0 = wgs84lon - 105.0;
double lat0 = wgs84lat - 35.0;
//generate an pair offset roughly in meters
double lon1 = 300.0 + lon0 + 2.0 * lat0 + 0.1 * lon0 * lon0 + 0.1 * lon0 * lat0 + 0.1 * sqrt(fabs(lon0));
lon1 = lon1 + (20.0 * sin(6.0 * lon0 * PI) + 20.0 * sin(2.0 * lon0 * PI)) * 2.0 / 3.0;
lon1 = lon1 + (20.0 * sin(lon0 * PI) + 40.0 * sin(lon0 / 3.0 * PI)) * 2.0 / 3.0;
lon1 = lon1 + (150.0 * sin(lon0 / 12.0 * PI) + 300.0 * sin(lon0 * PI / 30.0)) * 2.0 / 3.0;
double lat1 = -100.0 + 2.0 * lon0 + 3.0 * lat0 + 0.2 * lat0 * lat0 + 0.1 * lon0 * lat0 + 0.2 * sqrt(fabs(lon0));
lat1 = lat1 + (20.0 * sin(6.0 * lon0 * PI) + 20.0 * sin(2.0 * lon0 * PI)) * 2.0 / 3.0;
lat1 = lat1 + (20.0 * sin(lat0 * PI) + 40.0 * sin(lat0 / 3.0 * PI)) * 2.0 / 3.0;
lat1 = lat1 + (160.0 * sin(lat0 / 12.0 * PI) + 320.0 * sin(lat0 * PI / 30.0)) * 2.0 / 3.0;
//latitude in radian
double B = Deg2Rad(wgs84lat);
double sinB = sin(B), cosB = cos(B);
double W = sqrt(1 - kKRASOVSKY_ECCSQ * sinB * sinB);
double N = kKRASOVSKY_A / W;
//geodetic offset used by GCJ-02
double lon2 = Rad2Deg(lon1 / (N * cosB));
double lat2 = Rad2Deg(lat1 * W * W / (N * (1 - kKRASOVSKY_ECCSQ)));
return {lon2, lat2};
}
/**
* \brief Covert geodetic coordinate in WGS84 coordinate system to geodetic coordinate
* in GCJ-02 coordinate system
*
* \param [in] wgs84lon: longitude in WGS84 coordinate system [unit:degree]
* \param [in] wgs84lat: latitude in WGS84 coordinate system [unit:degree]
* \return Returns geodetic coordinate in GCJ-02 coordinate system
* \time 15:47:38 2020/06/12
*/
std::pair<double, double> Wgs2Gcj(const double& wgs84lon, const double& wgs84lat)
{
auto [dlon, dlat] = GetGeodeticOffset(wgs84lon, wgs84lat);
double gcj02lon = wgs84lon + dlon;
double gcj02lat = wgs84lat + dlat;
return { gcj02lon, gcj02lat };
}
/**
* \brief Covert geodetic coordinate in GCJ-02 coordinate system to geodetic coordinate
* in WGS84 coordinate system
*
* \param [in] gcj02lon: longitude in GCJ-02 coordinate system [unit:degree]
* \param [in] gcj02lat: latitude in GCJ-02 coordinate system [unit:degree]
* \return Returns geodetic coordinate in WGS84 coordinate system
* \remark simple linear iteration
* \detail
* \time 15:51:13 2020/06/12
*/
std::pair<double, double> Gcj2Wgs_SimpleIteration(const double& gcj02lon,
const double& gcj02lat)
{
auto [lon0, lat0] = Wgs2Gcj(gcj02lon, gcj02lat);
int iterCounts = 0;
while (++iterCounts < 1000)
{
auto[lon1, lat1] = Wgs2Gcj(lon0, lat0);
double dlon = lon1 - gcj02lon;
double dlat = lat1 - gcj02lat;
lon1 = lon0 - dlon;
lat1 = lat0 - dlat;
//1.0e-9 degree corresponding to 0.1mm
if (fabs(dlon) < 1.0e-9 && fabs(dlat) < 1.0e-9)
break;
lon0 = lon1;
lat0 = lat1;
}
return {lon0 , lat0};
}
#ifdef _USE_CERES //_USE_CERES
class AutoDiffCostFunc
{
public:
AutoDiffCostFunc(const double lon, const double lat) :
mlonGcj(lon), mlatGcj(lat) {}
template <typename T>
bool operator() (const T* const lonWgs, const T* const latWgs, T* residuals) const
{
//get geodetic offset relative to 'center china'
T lon0 = lonWgs[0] - T(105.0);
T lat0 = latWgs[0] - T(35.0);
//generate an pair offset roughly in meters
T lon1 = T(300.0) + lon0 + T(2.0) * lat0 + T(0.1) * lon0 * lon0 + T(0.1) * lon0 * lat0
+ T(0.1) * ceres::sqrt(ceres::abs(lon0));
lon1 = lon1 + (T(20.0) * ceres::sin(T(6.0) * lon0 * T(PI)) + T(20.0) * ceres::sin(T(2.0) * lon0 * T(PI))) * T(2.0) / T(3.0);
lon1 = lon1 + (T(20.0) * ceres::sin(lon0 * T(PI)) + T(40.0) * ceres::sin(lon0 / T(3.0) * T(PI))) * T(2.0) / T(3.0);
lon1 = lon1 + (T(150.0) * ceres::sin(lon0 / T(12.0) * T(PI)) + T(300.0) * ceres::sin(lon0 * T(PI) / T(30.0))) * T(2.0) / T(3.0);
T lat1 = T(-100.0) + T(2.0) * lon0 + T(3.0) * lat0 + T(0.2) * lat0 * lat0 + T(0.1) * lon0 * lat0
+ T(0.2) * ceres::sqrt(ceres::abs(lon0));
lat1 = lat1 + (T(20.0) * ceres::sin(T(6.0) * lon0 * T(PI)) + T(20.0) * ceres::sin(T(2.0) * lon0 * T(PI))) * T(2.0) / T(3.0);
lat1 = lat1 + (T(20.0) * ceres::sin(lat0 * T(PI)) + T(40.0) * ceres::sin(lat0 / T(3.0) * T(PI))) * T(2.0) / T(3.0);
lat1 = lat1 + (T(160.0) * ceres::sin(lat0 / T(12.0) * T(PI)) + T(320.0) * ceres::sin(lat0 * T(PI) / T(30.0))) * T(2.0) / T(3.0);
//latitude in radian
T B = latWgs[0] * T(kDEG2RAD);
T sinB = ceres::sin(B), cosB = ceres::cos(B);
T W = ceres::sqrt(T(1) - T(kKRASOVSKY_ECCSQ) * sinB * sinB);
T N = T(kKRASOVSKY_A) / W;
//geodetic offset used by GCJ-02
T lon2 = T(kRAD2DEG) * lon1 / (N * cosB);
T lat2 = T(kRAD2DEG) * (lat1 * W * W / (N * (1 - kKRASOVSKY_ECCSQ)));
//residuals
residuals[0] = lonWgs[0] + lon2 - mlonGcj;
residuals[1] = latWgs[0] + lat2 - mlatGcj;
return true;
}
private:
double mlonGcj;
double mlatGcj;
};
/**
* \brief Covert geodetic coordinate in GCJ-02 coordinate system to geodetic coordinate
* in WGS84 coordinate system
*
* \param [in] gcj02lon: longitude in GCJ-02 coordinate system [unit:degree]
* \param [in] gcj02lat: latitude in GCJ-02 coordinate system [unit:degree]
* \return Returns geodetic coordinate in WGS84 coordinate system
* \remark the encryption formula is known and use an auto-differentiable cost function
* \time 15:51:13 2020/06/12
*/
std::pair<double, double> Gcj2Wgs_AutoDiff(const double& gcj02lon,
const double& gcj02lat)
{
ceres::Problem * poProblem = new ceres::Problem;
AutoDiffCostFunc* pCostFunc = new AutoDiffCostFunc(gcj02lon,gcj02lat);
double wgslon = gcj02lon , wgslat = gcj02lat;
poProblem->AddResidualBlock(new ceres::AutoDiffCostFunction<AutoDiffCostFunc, 2, 1, 1>(pCostFunc),
nullptr,
&wgslon,
&wgslat);
ceres::Solver::Options options;
options.max_num_iterations = 30;
options.linear_solver_type = ceres::DENSE_QR;
options.minimizer_progress_to_stdout = false;
options.gradient_tolerance = 1e-16;
options.function_tolerance = 1e-12;
options.parameter_tolerance = 1e-14;
ceres::Solver::Summary summary;
ceres::Solve(options, poProblem, &summary);
delete poProblem; //auto free memory of cost function "pCostFunc"
return { wgslon, wgslat };
}
#endif // _USE_CERES
/**
* \brief Calculate the partial derivatives with respect to estimated longitude in WGS84
*
* \param [in] wgs84lon: estimated longitude in WGS84 coordinate system [unit:degree]
* \param [in] wgs84lat: estimated latitude in WGS84 coordinate system [unit:degree]
* \param [in] dlon: delta longitude (close to zero) in WGS84 coordinate system [unit:degree],
* \return Returns partial derivatives with respect to estimated longitude in WGS84
* \time 20:26:16 2020/06/13
*/
std::pair<double, double> GetPartialDerivative_Lon(const double& wgs84lon, const double& wgs84lat, const double& dlon)
{
double lonBk = wgs84lon + dlon;
double lonFw = wgs84lon - dlon;
auto [gcjlonBk, gcjlatBk] = Wgs2Gcj(lonBk, wgs84lat);
auto [gcjlonFw, gcjlatFw] = Wgs2Gcj(lonFw, wgs84lat);
double dlongcj_dlonwgs = (gcjlonBk - gcjlonFw) / (dlon * 2.0);
double dlatgcj_dlonwgs = (gcjlatBk - gcjlatFw) / (dlon * 2.0);
return { dlongcj_dlonwgs , dlatgcj_dlonwgs };
}
/**
* \brief Calculate the partial derivatives with respect to estimated latitude in WGS84
*
* \param [in] wgs84lon: estimated longitude in WGS84 coordinate system [unit:degree]
* \param [in] wgs84lat: estimated latitude in WGS84 coordinate system [unit:degree]
* \param [in] dlat: delta latitude (close to zero) in WGS84 coordinate system [unit:degree],
* \return Returns partial derivatives with respect to estimated latitude in WGS84
* \time 20:26:25 2020/06/13
*/
std::pair<double, double> GetPartialDerivative_Lat(const double& wgs84lon, const double& wgs84lat, const double& dlat)
{
double latBk = wgs84lat + dlat;
double latFw = wgs84lat - dlat;
auto [gcjlonBk, gcjlatBk] = Wgs2Gcj(wgs84lon, latBk);
auto [gcjlonFw, gcjlatFw] = Wgs2Gcj(wgs84lon, latFw);
double dlongcj_dlatwgs = (gcjlonBk - gcjlonFw) / (dlat * 2.0);
double dlatgcj_dlatwgs = (gcjlatBk - gcjlatFw) / (dlat * 2.0);
return { dlongcj_dlatwgs , dlatgcj_dlatwgs };
}
/**
* \brief Covert geodetic coordinate in GCJ-02 coordinate system to geodetic coordinate
* in WGS84 coordinate system
*
* \param [in] gcj02lon: longitude in GCJ-02 coordinate system [unit:degree]
* \param [in] gcj02lat: latitude in GCJ-02 coordinate system [unit:degree]
* \return Returns geodetic coordinate in WGS84 coordinate system
* \remark the encryption formula is unknown but we can covert point in WGS84 to point
* in GCJ-02 with an API,then use the numerical derivation method to solve the
* problem
* \detail Assuming the encryption formula is
*
* gcj02lon = Wgs2Gcj(wgs84lon, wgs84lat)
* gcj02lat = Wgs2Gcj(wgs84lon, wgs84lat)
*
* In the rectification process, (wgs84lon, wgs84lat) are unknown items. Obviously,
* this is a system of nonlinear equations.
*
* The linear formed error functions of forward intersection come from
* consideration of a Taylor series expansion.
* V = AX - b
* here:
* V: The residuals of the observed values
* A: The jacobian matrix
* X: The modification of the unknown items
* b: The constant terms of the error functions
*
* Then the error functions written in vector form are:
* | V_lon | = | dlongcj_dlonwgs dlongcj_dlatwgs | | d_lonwgs | - | l_lon |
* | V_lat | = | 0 dlatgcj_dlatwgs | | d_latwgs | - | l_lat |
* here:
* l_lon = longcj - longcj' // the modification of longcj
* l_lat = latgcj - latgcj' // the modification of latgcj
* longcj : the observed longitude in GCJ-02
* latgcj : the observed latitude in GCJ-02
* longcj' = Wgs2Gcj(wgs84lon',wgs84lat') // estimated longitude in GCJ-02
* latgcj' = Wgs2Gcj(wgs84lon',wgs84lat') // estimated latitude in GCJ-02
* wgs84lon' : estimated longitude in WGS84
* wgs84lat' : estimated latitude in WGS84
* d_lonwgs : unknown items
* d_latwgs : unknown items
* wgs84lon = wgs84lon' + d_lonwgs // update
* wgs84lat = wgs84lat' + d_latwgs
*
* let V = [V_lon V_lat]T = 0, then
* d_latwgs = (l_lon * dlatgcj_dlonwgs - l_lat * dlongcj_dlonwgs) /
* (dlongcj_dlatwgs * dlatgcj_dlonwgs - dlatgcj_dlatwgs * dlongcj_dlonwgs)
* d_lonwgs = (l_lon - dlongcj_dlatwgs * d_latwgs) / dlongcj_dlonwgs
*
* This iterative procedure is repeated until X= [d_lonwgs d_latwgs]T are
* sufficiently small.
* \time 17:42:01 2020/06/12
*/
std::pair<double, double> Gcj2Wgs_NumbericDiff(const double& gcj02lon,
const double& gcj02lat)
{
double wgs84lon = gcj02lon, wgs84lat = gcj02lat;
int nIterCount = 0;
double tol = 1e-9;
while (++nIterCount < 1000)
{
auto [dlongcj_dlonwgs, dlatgcj_dlonwgs] = GetPartialDerivative_Lon(wgs84lon, wgs84lat, tol);
auto [dlongcj_dlatwgs, dlatgcj_dlatwgs] = GetPartialDerivative_Lat(wgs84lon, wgs84lat, tol);
auto [gcj02lonEst, gcj02latEst] = Wgs2Gcj(wgs84lon, wgs84lat);
double l_lon = gcj02lon - gcj02lonEst;
double l_lat = gcj02lat - gcj02latEst;
double d_latwgs = (l_lon * dlatgcj_dlonwgs - l_lat * dlongcj_dlonwgs) /
(dlongcj_dlatwgs * dlatgcj_dlonwgs - dlatgcj_dlatwgs * dlongcj_dlonwgs);
double d_lonwgs = (l_lon - dlongcj_dlatwgs * d_latwgs) / dlongcj_dlonwgs;
if (fabs(d_latwgs) < tol && fabs(d_lonwgs) < tol)
break;
wgs84lon = wgs84lon + d_lonwgs;
wgs84lat = wgs84lat + d_latwgs;
}
return { wgs84lon, wgs84lat };
}
/**
* \brief Covert geodetic coordinate in GCJ-02 coordinate system to geodetic coordinate
* in WGS84 coordinate system
*
* \param [in] gcj02lon: longitude in GCJ-02 coordinate system [unit:degree]
* \param [in] gcj02lat: latitude in GCJ-02 coordinate system [unit:degree]
* \return Returns geodetic coordinate in WGS84 coordinate system
* \remark The encryption formula is known,and use the analytical derivation method to
* solve the problem with high precision.
* \detail Assuming the encryption formula is
*
* gcj02lon = Wgs2Gcj(wgs84lon, wgs84lat)
* gcj02lat = Wgs2Gcj(wgs84lon, wgs84lat)
*
* In the rectification process, (wgs84lon, wgs84lat) are unknown items. Obviously,
* this is a system of nonlinear equations.
*
* The linear formed error functions of forward intersection come from
* consideration of a Taylor series expansion.
* V = AX - b
* here:
* V: The residuals of the observed values
* A: The jacobian matrix
* X: The modification of the unknown items
* b: The constant terms of the error functions
*
* Then the error functions written in vector form are:
* | V_lon | = | dlongcj_dlonwgs dlongcj_dlatwgs | | d_lonwgs | - | l_lon |
* | V_lat | = | dlatgcj_dlonwgs dlatgcj_dlatwgs | | d_latwgs | - | l_lat |
* here:
* l_lon = longcj - longcj' // the modification of longcj
* l_lat = latgcj - latgcj' // the modification of latgcj
* longcj : the observed longitude in GCJ-02
* latgcj : the observed latitude in GCJ-02
* longcj' = Wgs2Gcj(wgs84lon',wgs84lat') // estimated longitude in GCJ-02
* latgcj' = Wgs2Gcj(wgs84lon',wgs84lat') // estimated latitude in GCJ-02
* wgs84lon' : estimated longitude in WGS84
* wgs84lat' : estimated latitude in WGS84
* d_lonwgs : unknown items
* d_latwgs : unknown items
* wgs84lon = wgs84lon' + d_lonwgs // update
* wgs84lat = wgs84lat' + d_latwgs
*
* let V = [V_lon V_lat]T = 0, then
* d_latwgs = (l_lon * dlatgcj_dlonwgs - l_lat * dlongcj_dlonwgs) /
* (dlongcj_dlatwgs * dlatgcj_dlonwgs - dlatgcj_dlatwgs * dlongcj_dlonwgs)
* d_lonwgs = (l_lon - dlongcj_dlatwgs * d_latwgs) / dlongcj_dlonwgs
*
* This iterative procedure is repeated until X= [d_lonwgs d_latwgs]T are
* sufficiently small.
* \time 01:54:46 2020/06/13
*/
std::pair<double, double> Gcj2Wgs_AnalyticDiff(const double& gcj02lon,
const double& gcj02lat)
{
double wgs84lon = gcj02lon, wgs84lat = gcj02lat;
int nIterCount = 0;
while (++nIterCount < 1000)
{
//get geodetic offset relative to 'center china'
double lon0 = wgs84lon - 105.0;
double lat0 = wgs84lat - 35.0;
//generate an pair offset roughly in meters
double lon1 = 300.0 + lon0 + 2.0 * lat0 + 0.1 * lon0 * lon0 + 0.1 * lon0 * lat0 + 0.1 * sqrt(fabs(lon0));
lon1 = lon1 + (20.0 * sin(6.0 * lon0 * PI) + 20.0 * sin(2.0 * lon0 * PI)) * 2.0 / 3.0;
lon1 = lon1 + (20.0 * sin(lon0 * PI) + 40.0 * sin(lon0 / 3.0 * PI)) * 2.0 / 3.0;
lon1 = lon1 + (150.0 * sin(lon0 / 12.0 * PI) + 300.0 * sin(lon0 * PI / 30.0)) * 2.0 / 3.0;
double lat1 = -100.0 + 2.0 * lon0 + 3.0 * lat0 + 0.2 * lat0 * lat0 + 0.1 * lon0 * lat0 + 0.2 * sqrt(fabs(lon0));
lat1 = lat1 + (20.0 * sin(6.0 * lon0 * PI) + 20.0 * sin(2.0 * lon0 * PI)) * 2.0 / 3.0;
lat1 = lat1 + (20.0 * sin(lat0 * PI) + 40.0 * sin(lat0 / 3.0 * PI)) * 2.0 / 3.0;
lat1 = lat1 + (160.0 * sin(lat0 / 12.0 * PI) + 320.0 * sin(lat0 * PI / 30.0)) * 2.0 / 3.0;
double g_lon0 = 0;
if (lon0 > 0)
g_lon0 = 0.05 / sqrt(lon0);
else
if (lon0 < 0)
g_lon0 = -0.05 / sqrt(-lon0);
else
g_lon0 = 0;
double PIlon0 = PI * lon0, PIlat0 = PI * lat0;
double dlon1_dlonwgs = 1 + 0.2 * lon0 + 0.1 * lat0 + g_lon0
+ ((120 * PI * cos(6 * PIlon0) + 40 * PI * cos(2 * PIlon0))
+ (20 * PI * cos(PIlon0) + 40 * PI / 3.0 * cos(PIlon0 / 3.0))
+ (12.5 * PI * cos(PIlon0 / 12.0) + 10 * PI * cos(PIlon0 / 30.0))) * 2.0 / 3.0;
double dlon1_dlatwgs = 2 + 0.1 * lon0;
double dlat1_dlonwgs = 2 + 0.1 * lat0 + 2 * g_lon0
+ (120 * PI * cos(6 * PIlon0) + 40 * PI * cos(2 * PIlon0)) * 2.0 / 3.0;
double dlat1_dlatwgs = 3 + 0.4 * lat0 + 0.1 * lon0
+ ((20 * PI * cos(PIlat0) + 40.0 * PI / 3.0 * cos(PIlat0 / 3.0))
+ (40 * PI / 3.0 * cos(PIlat0 / 12.0) + 32.0 * PI / 3.0 * cos(PIlat0 / 30.0))) * 2.0 / 3.0;
//latitude in radian
double B = Deg2Rad(wgs84lat);
double sinB = sin(B), cosB = cos(B);
double WSQ = 1 - kKRASOVSKY_ECCSQ * sinB * sinB;
double W = sqrt(WSQ);
double N = kKRASOVSKY_A / W;
double dW_dlatwgs = -PI * kKRASOVSKY_ECCSQ * sinB * cosB / (180.0 * W);
double dN_dlatwgs = -kKRASOVSKY_A * dW_dlatwgs / WSQ;
double PIxNxCosB = PI * N * cosB;
double dlongcj_dlonwgs = 1.0 + 180.0 * dlon1_dlonwgs / PIxNxCosB;
double dlongcj_dlatwgs = 180 * dlon1_dlatwgs / PIxNxCosB -
180 * lon1 * PI * (dN_dlatwgs * cosB - PI * N * sinB / 180.0) / (PIxNxCosB * PIxNxCosB);
double PIxNxSubECCSQ = PI * N * (1 - kKRASOVSKY_ECCSQ);
double dlatgcj_dlonwgs = 180 * WSQ * dlat1_dlonwgs / PIxNxSubECCSQ;
double dlatgcj_dlatwgs = 1.0 + 180 * (N * (dlat1_dlatwgs * WSQ + 2.0 * lat1 * W * dW_dlatwgs) - lat1 * WSQ * dN_dlatwgs) /
(N * PIxNxSubECCSQ);
auto [gcj02lonEst, gcj02latEst] = Wgs2Gcj(wgs84lon, wgs84lat);
double l_lon = gcj02lon - gcj02lonEst;
double l_lat = gcj02lat - gcj02latEst;
double d_latwgs = (l_lon * dlatgcj_dlonwgs - l_lat * dlongcj_dlonwgs) /
(dlongcj_dlatwgs * dlatgcj_dlonwgs - dlatgcj_dlatwgs * dlongcj_dlonwgs);
double d_lonwgs = (l_lon - dlongcj_dlatwgs * d_latwgs) / dlongcj_dlonwgs;
if (fabs(d_latwgs) < 1.0e-9 && fabs(d_lonwgs) < 1.0e-9)
break;
wgs84lon = wgs84lon + d_lonwgs;
wgs84lat = wgs84lat + d_latwgs;
}
return { wgs84lon, wgs84lat };
}
| 19,110
|
C++
|
.cpp
| 419
| 42.708831
| 130
| 0.655061
|
kikkimo/WgsToGcj
| 36
| 9
| 0
|
GPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,053
|
WGS2GCJ.h
|
kikkimo_WgsToGcj/include/WGS2GCJ.h
|
/***************************************************************************
*
* This class WGStoGCJ implements geodetic coordinate transform between geodetic
* coordinate in WGS84 coordinate system and geodetic coordinate in GCJ-02
* coordinate system.
*
* details: https://blog.csdn.net/gudufuyun/article/details/106738942
*
* Copyright (c) 2020. All rights reserved.
*
* kikkimo
* School of Remote Sensing and Information Engineering,
* WuHan University,
* Wuhan, Hubei, P.R. China. 430079
* fywhu@outlook.com
*
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#pragma once
#include <utility>
#ifdef _WGSTOGCJ_API
#if (defined _WIN32 || defined WINCE || defined __CYGWIN__)
#define WGSTOGCJ_API_EXPORTS __declspec(dllexport)
#elif defined __GNUC__ && __GNUC__ >= 4
#define WGSTOGCJ_API_EXPORTS __attribute__((visibility("default")))
#endif
#endif
#ifndef WGSTOGCJ_API_EXPORTS
#define WGSTOGCJ_API_EXPORTS
#endif
/**
* \brief Covert geodetic coordinate in WGS84 coordinate system to geodetic coordinate
* in GCJ-02 coordinate system
*
* \param [in] wgs84lon: longitude in WGS84 coordinate system [unit:degree]
* \param [in] wgs84lat: latitude in WGS84 coordinate system [unit:degree]
* \return Returns geodetic coordinate in GCJ-02 coordinate system
* \time 15:47:38 2020/06/12
*/
WGSTOGCJ_API_EXPORTS std::pair<double, double>
Wgs2Gcj(const double& wgs84lon, const double& wgs84lat);
/**
* \brief Covert geodetic coordinate in GCJ-02 coordinate system to geodetic coordinate
* in WGS84 coordinate system
*
* \param [in] gcj02lon: longitude in GCJ-02 coordinate system [unit:degree]
* \param [in] gcj02lat: latitude in GCJ-02 coordinate system [unit:degree]
* \return Returns geodetic coordinate in WGS84 coordinate system
* \remark simple linear iteration
* \detail
* \time 15:51:13 2020/06/12
*/
std::pair<double, double> __declspec(dllexport)
Gcj2Wgs_SimpleIteration(const double& gcj02lon, const double& gcj02lat);
#ifdef _USE_CERES
/**
* \brief Covert geodetic coordinate in GCJ-02 coordinate system to geodetic coordinate
* in WGS84 coordinate system
*
* \param [in] gcj02lon: longitude in GCJ-02 coordinate system [unit:degree]
* \param [in] gcj02lat: latitude in GCJ-02 coordinate system [unit:degree]
* \return Returns geodetic coordinate in WGS84 coordinate system
* \remark the encryption formula is known and use an auto-differentiable cost function
* \time 15:51:13 2020/06/12
*/
WGSTOGCJ_API_EXPORTS std::pair<double, double>
Gcj2Wgs_AutoDiff(const double& gcj02lon, const double& gcj02lat);
#endif
/**
* \brief Covert geodetic coordinate in GCJ-02 coordinate system to geodetic coordinate
* in WGS84 coordinate system
*
* \param [in] gcj02lon: longitude in GCJ-02 coordinate system [unit:degree]
* \param [in] gcj02lat: latitude in GCJ-02 coordinate system [unit:degree]
* \return Returns geodetic coordinate in WGS84 coordinate system
* \remark the encryption formula is unknown but we can covert point in WGS84 to point
* in GCJ-02 with an API,then use the numerical derivation method to solve the
* problem
* \detail Assuming the encryption formula is
*
* gcj02lon = Wgs2Gcj(wgs84lon, wgs84lat)
* gcj02lat = Wgs2Gcj(wgs84lon, wgs84lat)
*
* In the rectification process, (wgs84lon, wgs84lat) are unknown items. Obviously,
* this is a system of nonlinear equations.
*
* The linear formed error functions of forward intersection come from
* consideration of a Taylor series expansion.
* V = AX - b
* here:
* V: The residuals of the observed values
* A: The jacobian matrix
* X: The modification of the unknown items
* b: The constant terms of the error functions
*
* Then the error functions written in vector form are:
* | V_lon | = | dlongcj_dlonwgs dlongcj_dlatwgs | | d_lonwgs | - | l_lon |
* | V_lat | = | 0 dlatgcj_dlatwgs | | d_latwgs | - | l_lat |
* here:
* l_lon = longcj - longcj' // the modification of longcj
* l_lat = latgcj - latgcj' // the modification of latgcj
* longcj : the observed longitude in GCJ-02
* latgcj : the observed latitude in GCJ-02
* longcj' = Wgs2Gcj(wgs84lon',wgs84lat') // estimated longitude in GCJ-02
* latgcj' = Wgs2Gcj(wgs84lon',wgs84lat') // estimated latitude in GCJ-02
* wgs84lon' : estimated longitude in WGS84
* wgs84lat' : estimated latitude in WGS84
* d_lonwgs : unknown items
* d_latwgs : unknown items
* wgs84lon = wgs84lon' + d_lonwgs // update
* wgs84lat = wgs84lat' + d_latwgs
*
* let V = [V_lon V_lat]T = 0, then
* d_latwgs = (l_lon * dlatgcj_dlonwgs - l_lat * dlongcj_dlonwgs) /
* (dlongcj_dlatwgs * dlatgcj_dlonwgs - dlatgcj_dlatwgs * dlongcj_dlonwgs)
* d_lonwgs = (l_lon - dlongcj_dlatwgs * d_latwgs) / dlongcj_dlonwgs
*
* This iterative procedure is repeated until X= [d_lonwgs d_latwgs]T are
* sufficiently small.
* \time 17:42:01 2020/06/12
*/
WGSTOGCJ_API_EXPORTS std::pair<double, double>
Gcj2Wgs_NumbericDiff(const double& gcj02lon, const double& gcj02lat);
/**
* \brief Covert geodetic coordinate in GCJ-02 coordinate system to geodetic coordinate
* in WGS84 coordinate system
*
* \param [in] gcj02lon: longitude in GCJ-02 coordinate system [unit:degree]
* \param [in] gcj02lat: latitude in GCJ-02 coordinate system [unit:degree]
* \return Returns geodetic coordinate in WGS84 coordinate system
* \remark The encryption formula is known,and use the analytical derivation method to
* solve the problem with high precision.
* \detail Assuming the encryption formula is
*
* gcj02lon = Wgs2Gcj(wgs84lon, wgs84lat)
* gcj02lat = Wgs2Gcj(wgs84lon, wgs84lat)
*
* In the rectification process, (wgs84lon, wgs84lat) are unknown items. Obviously,
* this is a system of nonlinear equations.
*
* The linear formed error functions of forward intersection come from
* consideration of a Taylor series expansion.
* V = AX - b
* here:
* V: The residuals of the observed values
* A: The jacobian matrix
* X: The modification of the unknown items
* b: The constant terms of the error functions
*
* Then the error functions written in vector form are:
* | V_lon | = | dlongcj_dlonwgs dlongcj_dlatwgs | | d_lonwgs | - | l_lon |
* | V_lat | = | dlatgcj_dlonwgs dlatgcj_dlatwgs | | d_latwgs | - | l_lat |
* here:
* l_lon = longcj - longcj' // the modification of longcj
* l_lat = latgcj - latgcj' // the modification of latgcj
* longcj : the observed longitude in GCJ-02
* latgcj : the observed latitude in GCJ-02
* longcj' = Wgs2Gcj(wgs84lon',wgs84lat') // estimated longitude in GCJ-02
* latgcj' = Wgs2Gcj(wgs84lon',wgs84lat') // estimated latitude in GCJ-02
* wgs84lon' : estimated longitude in WGS84
* wgs84lat' : estimated latitude in WGS84
* d_lonwgs : unknown items
* d_latwgs : unknown items
* wgs84lon = wgs84lon' + d_lonwgs // update
* wgs84lat = wgs84lat' + d_latwgs
*
* let V = [V_lon V_lat]T = 0, then
* d_latwgs = (l_lon * dlatgcj_dlonwgs - l_lat * dlongcj_dlonwgs) /
* (dlongcj_dlatwgs * dlatgcj_dlonwgs - dlatgcj_dlatwgs * dlongcj_dlonwgs)
* d_lonwgs = (l_lon - dlongcj_dlatwgs * d_latwgs) / dlongcj_dlonwgs
*
* This iterative procedure is repeated until X= [d_lonwgs d_latwgs]T are
* sufficiently small.
* \time 01:54:46 2020/06/13
*/
WGSTOGCJ_API_EXPORTS std::pair<double, double>
Gcj2Wgs_AnalyticDiff(const double& gcj02lon, const double& gcj02lat);
| 8,287
|
C++
|
.h
| 183
| 43.120219
| 88
| 0.663372
|
kikkimo/WgsToGcj
| 36
| 9
| 0
|
GPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,054
|
main_modelling.cpp
|
brightskiesinc_Reverse_Time_Migration/main_modelling.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
///
/// @brief This should contain the main function that drives the
/// Seismic Engine Modelling execution.
///
#include <bs/base/logger/concrete/LoggerSystem.hpp>
#include <bs/base/logger/concrete/FileLogger.hpp>
#include <bs/base/logger/concrete/ConsoleLogger.hpp>
#include <stbx/parsers/Parser.hpp>
#include <stbx/parsers/ArgumentsParser.hpp>
#include <stbx/generators/Generator.hpp>
using namespace std;
using namespace stbx::parsers;
using namespace stbx::generators;
using namespace stbx::writers;
using namespace operations::dataunits;
using namespace operations::engines;
using namespace bs::base::logger;
using namespace bs::timer::configurations;
int main(int argc, char *argv[]) {
string parameter_file = WORKLOAD_PATH "/computation_parameters.json";
string configuration_file = WORKLOAD_PATH "/modelling_configuration.json";
string callback_file = WORKLOAD_PATH "/callback_configuration.json";
string system_file = WORKLOAD_PATH "/system_configuration.json";
string write_path = WRITE_PATH;
auto logger = LoggerSystem::GetInstance();
/* Registering the needed loggers. */
logger->RegisterLogger(new FileLogger(write_path + "/log.txt"));
logger->RegisterLogger(new ConsoleLogger());
/* Configuring the logger. */
logger->ConfigureLoggers("Main logger", FILE_CONSOLE, DATE_TIME);
logger->Info() << "Starting Seismic Engine..." << '\n';
ArgumentsParser::Parse(parameter_file,
configuration_file,
callback_file,
system_file,
write_path,
argc, argv);
auto parser = Parser::GetInstance();
parser->RegisterFile(parameter_file);
parser->RegisterFile(configuration_file);
parser->RegisterFile(callback_file);
parser->RegisterFile(system_file);
parser->BuildMap();
auto generator = new Generator(parser->GetMap());
auto cp = generator->GenerateParameters();
auto engine_configuration = generator->GenerateModellingEngineConfiguration(write_path);
auto cbs = generator->GenerateCallbacks(write_path);
auto engine = new ModellingEngine(engine_configuration, cp, cbs);
TimerManager::GetInstance()->Configure(generator->GenerateTimerConfiguration());
auto agent = generator->GenerateAgent();
agent->AssignEngine(engine);
agent->AssignArgs(argc, argv);
agent->Execute();
delete engine_configuration;
delete cbs;
delete cp;
delete engine;
auto writer = generator->GenerateWriter();
writer->WriteTimeResults(write_path);
TimerManager::GetInstance()->Terminate(true);
TimerManager::Kill();
delete parser;
delete generator;
return EXIT_SUCCESS;
}
| 3,513
|
C++
|
.cpp
| 83
| 37.337349
| 92
| 0.723541
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,055
|
main_migration.cpp
|
brightskiesinc_Reverse_Time_Migration/main_migration.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
///
/// @brief This should contain the main function that drives the
/// Seismic Engine execution.
///
#include <bs/base/logger/concrete/LoggerSystem.hpp>
#include <bs/base/logger/concrete/FileLogger.hpp>
#include <bs/base/logger/concrete/ConsoleLogger.hpp>
#include <stbx/parsers/Parser.hpp>
#include <stbx/parsers/ArgumentsParser.hpp>
#include <stbx/generators/Generator.hpp>
using namespace std;
using namespace stbx::parsers;
using namespace stbx::generators;
using namespace stbx::writers;
using namespace operations::dataunits;
using namespace operations::engines;
using namespace bs::base::logger;
using namespace bs::timer::configurations;
int main(int argc, char *argv[]) {
string parameter_file = WORKLOAD_PATH "/computation_parameters.json";
string configuration_file = WORKLOAD_PATH "/engine_configuration.json";
string callback_file = WORKLOAD_PATH "/callback_configuration.json";
string system_file = WORKLOAD_PATH "/system_configuration.json";
string write_path = WRITE_PATH;
auto logger = LoggerSystem::GetInstance();
/* Registering the needed loggers. */
logger->RegisterLogger(new FileLogger(write_path + "/log.txt"));
logger->RegisterLogger(new ConsoleLogger());
/* Configuring the logger. */
logger->ConfigureLoggers("Main logger", FILE_CONSOLE, DATE_TIME);
logger->Info() << "Starting Seismic Engine..." << '\n';
ArgumentsParser::Parse(parameter_file,
configuration_file,
callback_file,
system_file,
write_path,
argc, argv);
auto parser = Parser::GetInstance();
parser->RegisterFile(parameter_file);
parser->RegisterFile(configuration_file);
parser->RegisterFile(callback_file);
parser->RegisterFile(system_file);
parser->BuildMap();
auto generator = new Generator(parser->GetMap());
auto engine = generator->GenerateEngine(write_path);
TimerManager::GetInstance()->Configure(generator->GenerateTimerConfiguration());
auto agent = generator->GenerateAgent();
agent->AssignEngine(engine);
agent->AssignArgs(argc, argv);
auto md = agent->Execute();
delete engine;
auto writer = generator->GenerateWriter();
writer->AssignMigrationData(md);
writer->Write(write_path);
TimerManager::GetInstance()->Terminate(true);
TimerManager::Kill();
delete parser;
delete generator;
return EXIT_SUCCESS;
}
| 3,262
|
C++
|
.cpp
| 78
| 36.833333
| 84
| 0.718483
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,056
|
Comparator.cpp
|
brightskiesinc_Reverse_Time_Migration/tools/cmp/Comparator.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#define STEP 1
#define MAX_NT 2
#define SRC 3
#define DST 4
#define PRFX 5
using namespace std;
void compare_files(const string &name, const string &cpu, const string &gpu);
void read_csv_header(uint *nz, uint *nx, const string &file_name);
void read_csv(float *mat, uint nz, uint nx, const string &file_name);
double within_epsilon(float *output, float *reference,
size_t dim_x, size_t dim_z, unsigned int radius,
int z_adjust, float delta, const string &time_step);
void print_help();
int main(int argc, char *argv[]) {
if (argc == 3) {
string file1(argv[STEP]);
string file2(argv[MAX_NT]);
compare_files("File comparison", file1, file2);
} else if (argc == 5) {
int step = stoi(argv[STEP]);
int nt = stoi(argv[MAX_NT]);
string path1(argv[SRC]);
string path2(argv[DST]);
string prefix(argv[PRFX]);
for (int i = step; i <= nt; i += step) {
string time_step = to_string(i);
string file_1 = path1 + prefix + "_" + time_step + ".csv";
string file_2 = path2 + prefix + "_" + time_step + ".csv";
compare_files(time_step, file_1, file_2);
}
} else {
print_help();
}
return 0;
}
/**
* @brief Host-Code. Utility function to calculate L2-norm between resulting
* buffer and reference buffer.
*/
double within_epsilon(float *output, float *reference,
const size_t dim_x, const size_t dim_z, const unsigned int radius,
const int z_adjust, const float delta, const string &time_step) {
bool error = false;
double norm2 = 0;
for (size_t iz = 0; iz < dim_z; iz++) {
for (size_t ix = 0; ix < dim_x; ix++) {
if (ix >= radius && ix < (dim_x - radius) && iz >= radius &&
iz < (dim_z - radius + z_adjust)) {
float difference = fabsf(*reference - *output);
norm2 += difference * difference;
if (difference > delta) {
error = true;
cout << time_step << "\t"
<< "ERROR (" << ix << "," << iz << ") = " << *output << " "
<< *reference << " " << difference << endl;
}
}
++output;
++reference;
}
}
norm2 = sqrt(norm2);
return norm2;
}
void read_csv(float *mat, uint nz, uint nx, const string &file_name) {
std::ifstream in(file_name);
if (!in.is_open()) {
cout << "Couldn't open file : " << file_name << endl;
}
string line, word;
getline(in, line);
for (uint row = 0; row < nz; row++) {
getline(in, line, '\n');
stringstream s(line);
for (uint col = 0; col < nx; col++) {
getline(s, word, ',');
mat[row * nx + col] = stod(word);
}
}
}
void read_csv_header(uint *nz, uint *nx, const string &file_name) {
std::ifstream in(file_name);
if (!in.is_open()) {
cout << "Couldn't open file : " << file_name << endl;
}
char v;
int n;
in >> n;
*nx = n;
in >> v;
in >> n;
*nz = n;
in >> v;
}
void compare_files(const string &name, const string &cpu, const string &gpu) {
uint nz, nx;
read_csv_header(&nz, &nx, cpu);
auto *cpu_array = (float *) malloc(sizeof(float) * nz * nx);
auto *gpu_array = (float *) malloc(sizeof(float) * nz * nx);
read_csv(cpu_array, nz, nx, cpu);
read_csv(gpu_array, nz, nx, gpu);
float abs_error = 0;
float cpu_rel_error = 0;
float gpu_rel_error = 0;
for (int i = 0; i < nz; i++) {
for (int j = 0; j < nx; j++) {
abs_error += abs(cpu_array[i * nx + j] - gpu_array[i * nx + j]);
}
}
double l2_error =
within_epsilon(gpu_array, cpu_array, nz, nx, 4, 0, 0.1f, name);
cout << name << "\t" << abs_error << "\t" << l2_error << endl;
free(cpu_array);
free(gpu_array);
}
void print_help() {
cout << "Usage:" << endl
<< "\t ./Comparator <step> <max-nt> <src> <dst> <csv-prefix>" << endl
<< "\t ./Comparator <src> <dst>" << endl;
}
| 5,048
|
C++
|
.cpp
| 142
| 28.880282
| 88
| 0.561874
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,057
|
SyntheticModelGenerator.cpp
|
brightskiesinc_Reverse_Time_Migration/tools/gen/SyntheticModelGenerator.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <random>
#include <cstring>
#include <fstream>
#include <stdexcept>
#include <unistd.h>
#include <prerequisites/libraries/nlohmann/json.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <operations/utils/io/write_utils.h>
#define GREEN "\033[1;32m"
using namespace std;
using json = nlohmann::json;
#define META_DATA json
META_DATA read_file(const string &file_name);
void print_help();
void generate_model(META_DATA &meta_data, float *data);
void generate_layers(META_DATA &meta_data, float *data);
void inject_salt_bodies(META_DATA &meta_data, float *data);
void inject_cracks(META_DATA &meta_data, float *data);
void write_csv(float *data, uint nx, uint ny, uint nz, const string &file_name);
int main(int argc, char *argv[]) {
string meta_data_file;
string data_file;
int opt;
while ((opt = getopt(argc, argv, ":m:d")) != -1) {
switch (opt) {
case 'm':
meta_data_file = string(optarg);
break;
default:
print_help();
exit(EXIT_FAILURE);
}
}
META_DATA meta_data = read_file(meta_data_file);
uint nx = 0, ny = 0, nz = 0;
nx = meta_data["grid-size"]["nx"].get<int>();
ny = meta_data["grid-size"]["ny"].get<int>();
nz = meta_data["grid-size"]["nz"].get<int>();
uint bytes = nx * ny * nz * sizeof(float);
auto data = (float *) malloc(bytes);
memset(data, 0.0f, bytes);
string model_name = "synthetic_" + meta_data["model-name"].get<string>();
generate_model(meta_data, data);
float dx = 0.0f, dy = 0.0f, dz = 0.0f;
dx = meta_data["cell-dimension"]["dx"].get<float>();
dy = meta_data["cell-dimension"]["dy"].get<float>();
dz = meta_data["cell-dimension"]["dz"].get<float>();
if (dx <= 0.0f) {
dx = 1.0f;
}
if (dy <= 0.0f) {
dy = 1.0f;
}
if (dz <= 0.0f) {
dz = 1.0f;
}
nlohmann::json configuration_map;
bs::base::configurations::JSONConfigurationMap io_map(configuration_map);
bs::io::streams::SeismicWriter writer(bs::io::streams::SeismicWriter::ToWriterType("segy"),
&io_map);
writer.AcquireConfiguration();
writer.Initialize(model_name);
auto gathers = operations::utils::io::TransformToGather(data, nx, ny, nz, dx, dy, dz,
0, 0, 0, 0,
1, 1e3, 1e3);
writer.Write(gathers);
writer.Finalize();
for (auto g : gathers) {
delete g;
}
auto percentile = meta_data["percentile"].get<float>();
if (percentile < 0 || percentile > 100) {
percentile = 98.5;
}
write_csv(data, nx, ny, nz, model_name + ".csv");
free(data);
cout << GREEN "Synthetic model generated successfully...";
return 0;
}
void print_help() {
cout << "Usage:" << endl
<< "\t ./Generator -m <meta_data.json>";
}
META_DATA read_file(const string &file_name) {
std::ifstream in(file_name.c_str());
json j;
in >> j;
return j;
}
void generate_model(META_DATA &meta_data, float *data) {
generate_layers(meta_data, data);
inject_salt_bodies(meta_data, data);
inject_cracks(meta_data, data);
}
void generate_layers(META_DATA &meta_data, float *data) {
uint nx = meta_data["grid-size"]["nx"].get<uint>();
uint ny = meta_data["grid-size"]["ny"].get<uint>();
uint nz = meta_data["grid-size"]["nz"].get<uint>();
META_DATA properties = meta_data["properties"];
float min = 0.0f, max = 0.0f;
if (!properties["value-range"].empty()) {
min = properties["value-range"]["min"].get<float>();
max = properties["value-range"]["max"].get<float>();
}
uint num_cracks = 1;
if (properties["cracks"]["enable"].get<bool>()) {
num_cracks = properties["cracks"]["count"].get<uint>();
if (num_cracks < 1) {
num_cracks = 1;
}
}
uint num_layers = 1;
string type_layers;
float sample_step_layer = 0.0f;
if (properties["layers"]["enable"].get<bool>()) {
num_layers = properties["layers"]["count"].get<uint>();
if (num_layers < 1) {
num_layers = 1;
}
type_layers = properties["layers"]["type"].get<string>();
if (type_layers == "smooth") {
sample_step_layer = 1.0 * (max - min) / num_layers;
} else if (type_layers == "sharp") {
sample_step_layer = -1;
}
}
uint layer = 1;
float val = 1.0f;
for (int iy = 0; iy < ny; ++iy) {
for (int iz = 0; iz < nz; ++iz) {
if (sample_step_layer == -1) {
if (iz > (layer * (nz / num_layers))) {
layer++;
val *= 2;
}
} else {
val += sample_step_layer;
}
for (int ix = 0; ix < nx; ++ix) {
data[iz * nx + ix + (iy * nx * nz)] = val;
}
}
}
}
void inject_salt_bodies(META_DATA &meta_data, float *data) {
META_DATA salt_bodies = meta_data["properties"]["salt-bodies"];
if (!salt_bodies["enable"].get<bool>()) {
return;
}
uint nx = meta_data["grid-size"]["nx"].get<uint>();
uint ny = meta_data["grid-size"]["ny"].get<uint>();
uint nz = meta_data["grid-size"]["nz"].get<uint>();
uint salt_bodies_count = 0;
uint salt_bodies_width = 0;
salt_bodies_count = salt_bodies["count"].get<uint>();
if (salt_bodies_count < 1) {
salt_bodies_count = 1;
}
string s_width = salt_bodies["width"].get<string>();
if (s_width == "narrow") {
salt_bodies_width = 50;
} else if (s_width == "wide") {
salt_bodies_width = 100;
}
string salt_bodies_type = salt_bodies["type"].get<string>();
random_device random;
mt19937 generate(random());
uniform_int_distribution<> distribution_nx(salt_bodies_width, nx - salt_bodies_width);
uniform_int_distribution<> distribution_nz(salt_bodies_width, nz - salt_bodies_width);
for (int is = 0; is < salt_bodies_count; ++is) {
uint nx_start = distribution_nz(generate);
uint nz_start = distribution_nz(generate);
uint nx_end = nx_start + salt_bodies_width;
uint nz_end = nz_start + salt_bodies_width;
float val;
if (salt_bodies_type == "random") {
val *= -10.0f;
} else if (salt_bodies_type == "identical") {
val = -10.0f;
}
for (int iy = 0; iy < ny; ++iy) {
for (int iz = nz_start; iz < nz_end; ++iz) {
for (int ix = nx_start; ix < nx_end; ++ix) {
data[iz * nx + ix + (iy * nx * nz)] = val;
}
}
}
}
}
void inject_cracks(META_DATA &meta_data, float *data) {
/// @todo To be implemented.
}
void write_csv(float *data, uint nx, uint ny, uint nz, const string &file_name) {
ofstream out(file_name);
out << nx << "," << nz << "\n";
for (uint iz = 0; iz < nz; iz++) {
for (uint ix = 0; ix < nx; ix++)
out << data[iz * nx + ix] << ',';
out << '\n';
}
}
| 8,038
|
C++
|
.cpp
| 220
| 29.504545
| 95
| 0.571042
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,058
|
main.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/examples/logger/main.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bs/base/api/cpp/BSBase.hpp>
using namespace bs::base::logger;
int main() {
/* Creating the logger System. */
LoggerSystem *ls = LoggerSystem::GetInstance();;
/* Registering the needed loggers. */
ls->RegisterLogger(new FileLogger("./Output1.txt"));
ls->RegisterLogger(new ConsoleLogger());
/* Configuring the logger. */
ls->ConfigureLoggers("Logger1", FILE_CONSOLE);
/* Testing different functionalities. */
ls->Info()
<< "Hello I'm the First info string , it appears in file & console with the default format " << '\n';
ls->Error()
<< "Hello I'm the First Error statement ,it appears in file & console with the default format " << '\n';
ls->Critical()
<< "Hello I'm the First critical statement , it appears in file & console with the default format " << '\n';
ls->Debug()
<< "Hello I'm the First Debug statement , it appears in file & console with the default format " << '\n';
/* Registering a new output file. */
ls->RegisterLogger(new FileLogger("./Output2.txt"));
/* Configuring the new logger. */
ls->ConfigureLoggers("Ostream", FILE_MODE);
/* Testing different functionalities. */
ls->Info() << "Hello I'm the Ostream info string , it appears in file format only " << '\n';
ls->Error() << "Hello I'm the Ostream Error statement ,it appears in file format only" << '\n';
ls->Critical() << "Hello I'm the Ostream critical statement , it appears in file format only"
<< '\n';
ls->Debug() << "Hello I'm the Ostream Debug statement , it appears in file format only" << '\n';
/* Configuring the new logger. */
ls->ConfigureLoggers("Console", CONSOLE_MODE);
/* Testing different functionalities. */
ls->Info() << "Hello I'm the Console info string , it appears in Console format only " << '\n';
ls->Error() << "Hello I'm the Console Error statement ,it appears in Console format only" << '\n';
ls->Critical() << "Hello I'm the Console critical statement , it appears in Console format only"
<< '\n';
ls->Debug() << "Hello I'm the Console Debug statement , it appears in Console format only" << '\n';
return EXIT_SUCCESS;
}
| 3,032
|
C++
|
.cpp
| 58
| 47.258621
| 120
| 0.67027
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,059
|
main.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/examples/exceptions/main.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bs/base/api/cpp/BSBase.hpp>
using namespace bs::base::exceptions;
class ExceptionTest {
public:
ExceptionTest() = default;
void
Foo() { throw NOT_IMPLEMENTED_EXCEPTION_WITH_MESSAGE("test message"); }
void
Bar() { throw UNSUPPORTED_FEATURE_EXCEPTION(); }
};
int main() {
ExceptionTest test;
/* Right catching. No termination. */
try {
test.Foo();
} catch (NotImplementedException &e) {
std::cout << e.what() << std::endl;
}
/* Right catching. No termination. */
try {
test.Bar();
} catch (UnsupportedFeatureException &e) {
std::cout << e.what() << std::endl;
}
/* Wrong catching. Termination encountered. */
try {
test.Bar();
} catch (UndefinedException &e) {
std::cout << e.what() << std::endl;
}
return EXIT_SUCCESS;
}
| 1,646
|
C++
|
.cpp
| 51
| 28.294118
| 77
| 0.679293
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,060
|
test_main.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/tests/test_main.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#define CATCH_CONFIG_MAIN
#include <prerequisites/libraries/catch/catch.hpp>
| 840
|
C++
|
.cpp
| 20
| 40.05
| 77
| 0.764059
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,061
|
TestJSONConfigurationMap.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/tests/configurations/concrete/TestJSONConfigurationMap.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <prerequisites/libraries/catch/catch.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
using namespace bs::base::configurations;
using json = nlohmann::json;
TEST_CASE() {
/// @todo
}
| 985
|
C++
|
.cpp
| 25
| 37.4
| 77
| 0.762552
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,062
|
TestOneAPIBackend.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/tests/backend/oneapi/TestOneAPIBackend.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vector>
#include <prerequisites/libraries/catch/catch.hpp>
#include <bs/base/backend/Backend.hpp>
using namespace std;
using namespace bs::base::backend;
using namespace sycl;
void TEST_CASE_ONE_API_BACKEND() {
Backend backend;
vector<uint> domainDims{16, 16, 4};
vector<uint> blockDims{16, 16, 4};
range<3> test_grid_dimensions(domainDims[0], domainDims[1], domainDims[2]);
range<3> test_block_dimensions(blockDims[0], blockDims[1], blockDims[2]);
size_t test_shared_memory = 512;
uint test_stream = 0;
auto r = backend.CreateKernelConfiguration(domainDims, blockDims, 512, test_stream);
REQUIRE(test_grid_dimensions.get(0) == r.mGridDimensions.get(0));
REQUIRE(test_grid_dimensions.get(1) == r.mGridDimensions.get(1));
REQUIRE(test_grid_dimensions.get(2) == r.mGridDimensions.get(2));
REQUIRE(test_block_dimensions.get(0) == r.mBlockDimensions.get(0));
REQUIRE(test_block_dimensions.get(1) == r.mBlockDimensions.get(1));
REQUIRE(test_block_dimensions.get(2) == r.mBlockDimensions.get(2));
REQUIRE(test_shared_memory == r.mSharedMemory);
REQUIRE(backend.GetExecutor(test_stream) == r.mExecutor);
}
TEST_CASE("ONE API BACKEND", "KERNEL CONFIGURATION CREATION") {
TEST_CASE_ONE_API_BACKEND();
}
| 2,050
|
C++
|
.cpp
| 45
| 42.288889
| 88
| 0.738431
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,063
|
string_list.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/memory/data-units/string_list.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <string.h>
#include <bs/base/memory/data-units/string_list.h>
namespace bs {
namespace base {
namespace memory {
void init_slist(string_list *list, int size) {
list->size = 0;
list->strings_list = (char **) malloc(sizeof(char *) * size);
list->max_size = size;
}
void add_slist(string_list *list, char *word) {
if (list->max_size == 0) {
return;
}
if (list->size == list->max_size) {
list->max_size *= MULT_RATE;
list->strings_list =
(char **) realloc(list->strings_list, sizeof(char *) * list->max_size);
}
list->strings_list[list->size] =
(char *) malloc(sizeof(char) * (strlen(word) + 1));
strncpy(list->strings_list[list->size], word, strlen(word) + 1);
list->size++;
}
char slist_contains(string_list *list, char *word) {
int i = 0;
for (i = 0; i < list->size; i++) {
if (strcmp(word, list->strings_list[i]) == 0) {
return 1;
}
}
return 0;
}
void destroy_slist(string_list *list) {
int i = 0;
for (i = 0; i < list->size; i++) {
free(list->strings_list[i]);
}
free(list->strings_list);
list->size = 0;
list->max_size = 0;
}
} //namespace memory
} //namespace base
} //namespace bs
| 2,519
|
C++
|
.cpp
| 64
| 28.03125
| 99
| 0.522681
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,064
|
mem_list.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/memory/data-units/mem_list.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <string.h>
#include <bs/base/memory/data-units/mem_list.h>
#include <bs/base/memory/utils//mem_utils.h>
#include <bs/base/memory/utils/logger.h>
namespace bs {
namespace base {
namespace memory {
void init_list(MEM_LIST *list) {
list->start = NULL;
list->end = NULL;
list->size = 0;
}
int matching_calls(allocation_type alc, deallocation_type dealc) {
if ((int) alc == (int) dealc) {
return 1;
}
if ((alc == CALLOC || alc == MALLOC || alc == A_REALLOC) &&
(dealc == FREE || dealc == D_REALLOC)) {
return 1;
}
return 0;
}
void call_type_to_string(char *str, int type, int allocation) {
if (allocation) {
switch (type) {
case MALLOC:
strncpy(str, "malloc", MAX_MSG_LEN);
break;
case _MM_MALLOC:
strncpy(str, "_mm_malloc", MAX_MSG_LEN);
break;
case A_REALLOC:
strncpy(str, "realloc", MAX_MSG_LEN);
break;
case NEW:
strncpy(str, "new", MAX_MSG_LEN);
break;
case CALLOC:
strncpy(str, "calloc", MAX_MSG_LEN);
break;
case NEW_ARR:
strncpy(str, "new[]", MAX_MSG_LEN);
break;
default:
strncpy(str, "Unknown function", MAX_MSG_LEN);
}
} else {
switch (type) {
case FREE:
strncpy(str, "free", MAX_MSG_LEN);
break;
case _MM_FREE:
strncpy(str, "_mm_free", MAX_MSG_LEN);
break;
case D_REALLOC:
strncpy(str, "realloc", MAX_MSG_LEN);
break;
case DELETE:
strncpy(str, "delete", MAX_MSG_LEN);
break;
case DELETE_ARR:
strncpy(str, "delete[]", MAX_MSG_LEN);
break;
default:
strncpy(str, "Unknown function", MAX_MSG_LEN);
}
}
}
void add_block(MEM_LIST *list, MEM_ELEM *elem) {
if (list->size == 0) {
list->start = elem;
list->end = elem;
elem->next = NULL;
elem->prev = NULL;
} else {
elem->next = NULL;
elem->prev = list->end;
list->end->next = elem;
list->end = elem;
}
list->size++;
}
MEM_ELEM *get_block(MEM_LIST *list, void *addr) {
// We search from the end : a newly allocated block is more probable to be
// deallocated.
MEM_ELEM *temp = list->end;
while (temp != NULL) {
if (temp->addr == addr) {
break;
}
temp = temp->prev;
}
return temp;
}
MEM_ELEM *free_block(MEM_LIST *current_blocks, void *addr) {
// Get block.
MEM_ELEM *elem = get_block(current_blocks, addr);
if (elem != NULL) {
// Remove block from current_blocks list.
if (current_blocks->size == 1) {
init_list(current_blocks);
} else {
if (current_blocks->start == elem) {
current_blocks->start = elem->next;
current_blocks->start->prev = NULL;
} else if (current_blocks->end == elem) {
current_blocks->end = elem->prev;
current_blocks->end->next = NULL;
} else {
elem->prev->next = elem->next;
elem->next->prev = elem->prev;
}
current_blocks->size--;
}
}
return elem;
}
void delete_list(MEM_LIST *list) {
MEM_ELEM *temp = list->start;
MEM_ELEM *temp2 = list->start;
while (temp != NULL) {
temp2 = temp->next;
delete_block(temp);
temp = temp2;
}
}
void print_list(MEM_LIST *list) {
if (list != NULL) {
MEM_ELEM *temp = list->start;
while (temp != NULL) {
print_block(temp);
temp = temp->next;
}
}
}
#if (MEM_TRACK == 1 || MEM_TRACK == 2)
MEM_ELEM *create_block(void *addr, size_t size, const char *file,
const char *func, int line, allocation_type acall) {
MEM_ELEM *elem = (MEM_ELEM *)(malloc)(sizeof(MEM_ELEM));
elem->addr = addr;
elem->size = size;
#if (MEM_TRACK == 2)
elem->free_line = -1;
#endif
elem->a_call = acall;
strncpy(elem->name, "\0", STRING_LEN);
strncpy(elem->malloc_file_name, file, STRING_LEN);
strncpy(elem->malloc_function_name, func, STRING_LEN);
elem->malloc_line = line;
return elem;
}
#elif (MEM_TRACK == 3)
MEM_ELEM *create_block(void *addr, size_t size, const char *file,
const char *func, int line, char **stack,
size_t stack_size, allocation_type acall) {
MEM_ELEM *elem = (MEM_ELEM *)(malloc)(sizeof(MEM_ELEM));
elem->addr = addr;
elem->size = size;
strncpy(elem->name, "\0", STRING_LEN);
strncpy(elem->malloc_file_name, file, STRING_LEN);
strncpy(elem->malloc_function_name, func, STRING_LEN);
elem->malloc_line = line;
elem->free_line = -1;
elem->a_call = acall;
elem->malloc_frame_size = stack_size;
elem->malloc_frame = stack;
return elem;
}
#else
MEM_ELEM *create_block(void *addr, size_t size, allocation_type acall) {
MEM_ELEM *elem = (MEM_ELEM *) (malloc)(sizeof(MEM_ELEM));
strncpy(elem->name, "\0", STRING_LEN);
elem->addr = addr;
elem->a_call = acall;
elem->size = size;
return elem;
}
#endif
#if (MEM_TRACK == 2)
void modify_block(MEM_ELEM *elem, const char *file, const char *func, int line,
deallocation_type dcall) {
strncpy(elem->free_file_name, file, STRING_LEN);
strncpy(elem->free_function_name, func, STRING_LEN);
elem->free_line = line;
elem->d_call = dcall;
}
#elif (MEM_TRACK == 3)
void modify_block(MEM_ELEM *elem, const char *file, const char *func, int line,
char **stack, size_t stack_size, deallocation_type dcall) {
strncpy(elem->free_file_name, file, STRING_LEN);
strncpy(elem->free_function_name, func, STRING_LEN);
elem->free_line = line;
elem->free_frame_size = stack_size;
elem->free_frame = stack;
elem->d_call = dcall;
}
#else
void modify_block(MEM_ELEM *elem, deallocation_type dcall) {
elem->d_call = dcall;
}
#endif
void delete_block(MEM_ELEM *elem) {
#if (MEM_TRACK >= 3)
(free)(elem->malloc_frame);
if (elem->free_line != -1) {
(free)(elem->free_frame);
}
#endif
(free)(elem);
}
#define MAX_MSG_LEN 1000
#ifdef MEM_TRACK_CONSOLE
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"
#else
#define RED ""
#define GRN ""
#define YEL ""
#define BLU ""
#define MAG ""
#define CYN ""
#define WHT ""
#define RESET ""
#endif
void name_block(MEM_ELEM *elem, char *name) {
strncpy(elem->name, name, STRING_LEN);
}
void print_block(MEM_ELEM *elem) {
static char msg[MAX_MSG_LEN];
char trace_line[MAX_MSG_LEN];
int i = 0;
#if (MEM_TRACK >= 0)
if (strcmp(elem->name, "\0") != 0) {
sprintf(msg, MAG "\tPointer Name : %s\n" RESET, elem->name);
log_msg(msg);
}
sprintf(msg,
MAG "\tMemory pointer : %p\n\t\t" GRN "Size Allocated : %lu\n" RESET,
elem->addr, elem->size);
log_msg(msg);
#endif
#if (MEM_TRACK >= 1)
sprintf(msg,
RED "\t\tAllocated In " RESET "(" GRN "FILE" RESET ":" CYN
"LINE" RESET ":" BLU "FUNCTION" RESET ") : " GRN "%s" RESET
":" CYN "%d" RESET ":" BLU "%s" RESET " \n",
elem->malloc_file_name, elem->malloc_line,
elem->malloc_function_name);
log_msg(msg);
call_type_to_string(trace_line, elem->a_call, 1);
sprintf(msg, CYN "\t\tAllocation method :" GRN " %s\n" RESET, trace_line);
log_msg(msg);
#endif
char file[MAX_MSG_LEN], func[MAX_MSG_LEN];
int l;
#if (MEM_TRACK >= 3)
log_msg(BLU "\t\tStack Trace At Allocation Call :\n" RESET);
strcpy(file, "no_info");
for (i = STACK_SKIP;
i < elem->malloc_frame_size && file[strlen(file) - 1] != 'h'; i++) {
extract_info(file, func, &l, elem->malloc_frame[i], 0);
get_stack_trace_line(trace_line, elem->malloc_frame[i]);
if (i != STACK_SKIP) {
decrement_line(trace_line);
}
sprintf(msg, WHT "\t\t\t%s\n" YEL "\t\t\t\t%s\n" RESET,
elem->malloc_frame[i], trace_line);
log_msg(msg);
}
#endif
#if (MEM_TRACK >= 2)
if (elem->free_line != -1) {
sprintf(msg,
RED "\t\tDeallocated In " RESET "(" GRN "FILE" RESET ":" CYN
"LINE" RESET ":" BLU "FUNCTION" RESET ") : " GRN "%s" RESET
":" CYN "%d" RESET ":" BLU "%s" RESET " \n",
elem->free_file_name, elem->free_line, elem->free_function_name);
log_msg(msg);
call_type_to_string(trace_line, elem->d_call, 0);
sprintf(msg, CYN "\t\tDeallocation method :" GRN " %s\n" RESET, trace_line);
log_msg(msg);
} else {
log_msg(RED "\t\tNo Deallocation Was Issued or Info could not be obtained "
"according to where this data belongs !\n" RESET);
}
#endif
#if (MEM_TRACK >= 3)
if (elem->free_line != -1) {
log_msg(BLU "\t\tStack Trace At Deallocation Call :\n" RESET);
strcpy(file, "no_info");
for (i = STACK_SKIP;
i < elem->free_frame_size && file[strlen(file) - 1] != 'h'; i++) {
extract_info(file, func, &l, elem->free_frame[i], 0);
get_stack_trace_line(trace_line, elem->free_frame[i]);
if (!(elem->d_call == D_REALLOC && i == STACK_SKIP)) {
decrement_line(trace_line);
}
sprintf(msg, WHT "\t\t\t%s\n" YEL "\t\t\t\t%s\n" RESET,
elem->free_frame[i], trace_line);
log_msg(msg);
}
}
#endif
}
} //namespace memory
} //namespace base
} //namespace bs
| 13,855
|
C++
|
.cpp
| 332
| 25.644578
| 94
| 0.438148
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,065
|
mem_utils.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/memory/utils/mem_utils.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <bs/base/memory/utils/mem_utils.h>
namespace bs {
namespace base {
namespace memory {
#define DELIMITER "()[] +"
#define BIG_STACK_SIZE 1000
static long int start_section = -1;
static char msg[1000];
extern char _start;
long int get_start_address(void) {
// If first call calculate start address.
if (start_section == -1) {
// Another way was by getting the biggest trace one can get, and calculating
// from it. Uncomment this and comment the simple working way on your own
// responsibility.
/*
void *array[BIG_STACK_SIZE + 1];
size_t size_f;
char **strings;
size_f = backtrace (array, BIG_STACK_SIZE + 1);
strings = backtrace_symbols (array, size_f);
char address1[MAX_MSG_LEN], file1[MAX_MSG_LEN], function1[MAX_MSG_LEN],
offset1[MAX_MSG_LEN]; extract_address(strings[size_f - 1], file1, function1,
offset1, address1); start_section = strtol(address1, NULL, 0) -
strtol(offset1, NULL, 0); (free)(strings);
*/
start_section = (unsigned long) &_start;
}
return start_section;
}
void get_trace_line(int offset, char *trace) {
char **strings;
size_t size_f;
strings = get_stack_trace(offset + 1, &size_f);
if (offset + 2 < size_f) {
strncpy(trace, strings[offset + 2], MAX_MSG_LEN);
} else {
strncpy(trace, "", MAX_MSG_LEN);
}
(free)(strings);
}
void extract_info(char *filename, char *function, int *line, char *trace,
char decr) {
char offset[MAX_MSG_LEN];
char address[MAX_MSG_LEN];
char line_trace[MAX_MSG_LEN];
int l = 0;
extract_address(trace, filename, function, offset, address);
get_stack_trace_line(line_trace, trace);
if (decr) {
decrement_line(line_trace);
}
char *token = strtok(line_trace, ":");
int i = 0;
while (token && i < 2) {
if (i == 0) {
strncpy(filename, token, MAX_MSG_LEN);
} else {
*line = atoi(token);
}
token = strtok(NULL, ":");
i++;
}
}
void filter_file_name(char *filtered_name, char *name) {
int index = strlen(name) - 1;
while (name[index] != '/' && index >= 0) {
index--;
}
strncpy(filtered_name, name + index + 1, MAX_MSG_LEN);
}
void get_stack_trace_line(char *line, char *trace) {
char address[MAX_MSG_LEN], file[MAX_MSG_LEN], function[MAX_MSG_LEN],
offset[MAX_MSG_LEN];
// Extract data from trace.
extract_address(trace, file, function, offset, address);
// Get addresses.
long int address_i = strtol(address, NULL, 0);
long int start_address = get_start_address();
FILE *fp;
char path[BIG_STACK_SIZE];
// Create the command to get the line.
sprintf(msg, "addr2line -e %s -j .text 0x%lx 2>&1\n", file,
address_i - start_address);
/* Open the command for reading. */
fp = popen(msg, "r");
if (fp == NULL) {
strncpy(line, "\0", MAX_MSG_LEN);
} else {
/* Read the output. */
while (fgets(path, sizeof(path) - 1, fp) != NULL) {
sprintf(msg, "%s", path);
strncpy(line, msg, MAX_MSG_LEN);
}
/* close */
pclose(fp);
if (line[0] == '?') {
strncpy(line, "Information could not be obtained !!", MAX_MSG_LEN);
} else {
process_trace_line(line);
if (line[strlen(line) - 1] == '\n') {
line[strlen(line) - 1] = '\0';
}
strncat(line, ":", MAX_MSG_LEN);
strncat(line, function, MAX_MSG_LEN);
if (line[strlen(line) - 1] == '\n') {
line[strlen(line) - 1] = '\0';
}
}
}
}
void process_trace_line(char *traceline) {
char s[MAX_MSG_LEN];
strncpy(s, traceline, MAX_MSG_LEN);
char *token = strtok(s, ":");
strncpy(traceline, "", MAX_MSG_LEN);
char temp[MAX_MSG_LEN];
int i = 0;
while (token && i < 2) {
if (i != 0) {
strncat(traceline, ":", MAX_MSG_LEN);
};
strncat(traceline, token, MAX_MSG_LEN);
token = strtok(NULL, ":");
i++;
}
}
void extract_address(char *trace, char *file, char *function, char *offset,
char *address) {
char s[MAX_MSG_LEN];
strcpy(s, trace);
char *token = strtok(s, DELIMITER);
int i = 0;
while (token && i < 4) {
if (i == 0) {
strncpy(file, token, MAX_MSG_LEN);
} else if (i == 1) {
strncpy(function, token, MAX_MSG_LEN);
} else if (i == 2) {
strncpy(offset, token, MAX_MSG_LEN);
} else if (i == 3) {
strncpy(address, token, MAX_MSG_LEN);
}
token = strtok(NULL, DELIMITER);
i++;
}
sprintf(s, "c++filt %s", function);
FILE *fp = popen(s, "r");
char out[MAX_MSG_LEN];
/* Read the output. */
while (fgets(out, sizeof(out) - 1, fp) != NULL) {
strncpy(function, out, MAX_MSG_LEN);
}
/* close */
pclose(fp);
if (function[strlen(function) - 1] == '\n') {
function[strlen(function) - 1] = '\0';
}
}
char **get_stack_trace(int depth, size_t *size_f) {
void *array[depth + 2];
char **strings;
*size_f = backtrace(array, depth + 2);
strings = backtrace_symbols(array, *size_f);
return strings;
}
void decrement_line(char *line) {
char s[MAX_MSG_LEN];
strncpy(s, line, MAX_MSG_LEN);
char *token = strtok(s, ":");
strncpy(line, "", MAX_MSG_LEN);
char temp[MAX_MSG_LEN];
int i = 0;
while (token) {
if (i != 0) {
strncat(line, ":", MAX_MSG_LEN);
}
strncpy(temp, token, MAX_MSG_LEN);
token = strtok(NULL, ":");
if (i == 1) {
int line_number = atoi(temp);
line_number--;
sprintf(temp, "%d", line_number);
}
strncat(line, temp, MAX_MSG_LEN);
i++;
}
if (strcmp(line, "-1") == 0) {
strncpy(line, "Information could not be obtained !", MAX_MSG_LEN);
}
}
} //namespace memory
} //namespace base
} //namespace bs
| 9,262
|
C++
|
.cpp
| 216
| 26.148148
| 96
| 0.431657
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,066
|
logger.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/memory/utils/logger.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <bs/base/memory/utils/logger.h>
namespace bs {
namespace base {
namespace memory {
#define INITIAL_BUFFER_SIZE 10000LLU
#define GROWTH_RATE 2
/**
* Logger internal settings.
**/
static char console_enable = 0;
static char file_enable = 0;
static char file_n[1000] = "";
static FILE *cur_file = NULL;
static long long unsigned buffer_size;
static long long unsigned current_size;
static char *buffer = NULL;
void init_logger(char ce, char fe, char *file_name) {
// Initialize internal buffer.
buffer_size = INITIAL_BUFFER_SIZE;
current_size = 0;
buffer = (char *) malloc(INITIAL_BUFFER_SIZE);
strncpy(buffer, "", buffer_size);
// Store settings.
console_enable = ce;
file_enable = fe;
if (fe == 1) {
// Open file in case outputing to file.
cur_file = fopen(file_name, "w");
strncpy(file_n, file_name, 1000);
}
}
void log_msg(char *message) {
if (buffer == NULL) {
// Print messages.
if (console_enable) {
printf("%s", message);
}
if (file_enable) {
if (strcmp(file_n, "") == 0) {
printf("no file to output on this : %s", message);
return;
}
char close_after_usage = 0;
if (cur_file == NULL) {
cur_file = fopen(file_n, "a");
close_after_usage = 1;
}
fprintf(cur_file, "%s", message);
if (close_after_usage) {
fclose(cur_file);
cur_file = NULL;
}
}
return;
}
int len_msg = strlen(message);
// Make buffer bigger if needed.
while (len_msg + current_size + 1 >= buffer_size) {
buffer_size *= GROWTH_RATE;
char *temp_buffer = (char *) realloc(buffer, buffer_size);
if (temp_buffer != NULL) {
buffer = temp_buffer;
} else {
log_flush();
}
}
// Add to buffer.
strncat(buffer + current_size, message, buffer_size - current_size - 1);
current_size += len_msg;
}
void close_logger(void) {
if (file_enable == 1) {
if (cur_file == NULL) {
cur_file = fopen(file_n, "a");
}
}
// Flush buffers.
log_flush();
// Close output file if file is opened.
if (file_enable == 1) {
fclose(cur_file);
}
// Free Buffer Space.
free(buffer);
buffer = NULL;
cur_file = NULL;
}
void log_flush(void) {
// Print messages.
if (console_enable) {
printf("%s", buffer);
}
if (file_enable) {
fprintf(cur_file, "%s", buffer);
}
// Reset buffer.
current_size = 0;
strncpy(buffer, "", buffer_size);
// Flush output.
if (console_enable) {
fflush(stdout);
}
if (file_enable) {
fflush(cur_file);
}
}
} //namespace memory
} //namespace base
} //namespace bs
| 4,920
|
C++
|
.cpp
| 130
| 23.030769
| 88
| 0.450324
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,067
|
memory_allocator.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/memory/managers/memory_allocator.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <unordered_map>
#include <bs/base/memory/managers/memory_allocator.h>
#include <bs/base/memory/managers/memory_tracker.h>
#define MASK_ALLOC_OFFSET(x) (x)
#define CACHELINE_BYTES 64
using namespace std;
namespace bs {
namespace base {
namespace memory {
/**
* @brief Define unordered_map called base_pointer it is key wil be pointer to void
* and its values will also be pointer to void and is called base_pointers
*/
static unordered_map<void *, void *> base_pointers;
void *mem_allocate(const unsigned long long size_of_type,
const unsigned long long number_of_elements, const string &name) {
return mem_allocate(size_of_type, number_of_elements, name, 0);
}
void *mem_allocate(const unsigned long long size_of_type,
const unsigned long long number_of_elements, const string &name,
uint half_length_padding) {
return mem_allocate(size_of_type, number_of_elements, name, 0, 0);
}
void *mem_allocate(const unsigned long long size_of_type,
const unsigned long long number_of_elements, const string &name,
uint half_length_padding, uint masking_allocation_factor) {
#ifndef __INTEL_COMPILER
/*!if the intel compiler is not defined
* this function is used to ensure the alignment of float variables
* assume vector length =4 then 16 bytes then 16 is for alignment
* MASK_ALLOC_OFFSET:for each array to be in different cache line
* so now ptr_base is aligned and start alignment at the half_length_padding
* example:
* assume size_of_type is size_of_float = 4 bytes *16 = 64 (cache_line size)
* and MASK_ALLOC_OFFSET(0)=0 and number of elements =6 so now we have for
* each array number of floats reserved equals (6+16) =22 floats which equals
* 1 cache line of size 64(16float) and extra 6 floats
*/
void *ptr_base =
malloc(size_of_type * (number_of_elements + 16 +
MASK_ALLOC_OFFSET(masking_allocation_factor)));
#else
/*!if the intel compiler is defined
* this function is used to ensure the alignment of float variables
* assume vector length =4 then 16 bytes then 16 is for alignment
* MASK_ALLOC_OFFSET:for each array to be in different cache line
* so now ptr_base is aligned and start alignment at the half_length_padding
* note:for _mm_malloc it needs the cache_line number of bytes to be able to
* do the alignment
*/
void *ptr_base = _mm_malloc(
(number_of_elements + 16 + MASK_ALLOC_OFFSET(masking_allocation_factor)) *
size_of_type,
CACHELINE_BYTES);
#endif
if (ptr_base == nullptr) {
return nullptr;
}
/*!this function is for memory tracking
* if the memory tracker is enabled it will work and add overhead
* if not,it will be converted to empty function so the compiler will optimize
* it it will keep track of the pointer ptr_base with the the variable called
* name (which is passed as attribute for the function) name.c_str():change
* string to array of characters and returns a pointer to character to an
* array that contains a null-terminated sequence of characters representing
* the current value of the basic_string object
*/
name_ptr(ptr_base, (char *) name.c_str());
/*!for the inner domain to be aligned without half_length we subtract the
* half_length_padding so ptr has an offset to make the alignment match the
* computational domain start so now ptr is aligned and start alignment at the
* inner domain example: assume half_length_padding=2 size_of_type is
* size_of_float = 4 bytes and MASK_ALLOC_OFFSET(0)=0 so &(((char
* *)ptr_base):points to the same address that ptr_base points to but as
* pointer to character (point to 1 byte) so with half_length_padding=2 it
* points to [14*size_of_float] so the ptr points to the 14 element of the
* reserved locations of pointer ptr_base and now element 14 and 15 points to
* the 2 half_length_padding and they are th end of the first cache line and
* the start of the inner domain will be at the start of the next cache line
* so now ptr is aligned and start alignment at the inner domain
*/
void *ptr =
&(((char *) ptr_base)[(16 - half_length_padding +
MASK_ALLOC_OFFSET(masking_allocation_factor)) *
size_of_type]);
/*!for the unordered map (base_pointers) the key is ptr which is aligned and
* starts alignment at the inner domain and the value is ptr_base which is
* aligned and start alignment at the half_length_padding
*/
base_pointers[ptr] = ptr_base;
// return the ptr: aligned pointer that start alignment at the inner domain
// which is the key of the global unordered map base_pointers
return ptr;
}
void mem_free(void *ptr) {
if (ptr == nullptr) {
return;
}
// get the value of key ptr which is a pointer that points to the same address
// that ptr_base points to
// and make org_ptr point to the same address so now ptr_base and org_ptr
// points to the same address
void *org_ptr = base_pointers[ptr];
#ifndef __INTEL_COMPILER
// if the intel compiler is not defined free the org_ptr
free(org_ptr);
#else
// if the intel compiler is defined _mm_free the org_ptr
_mm_free(org_ptr);
#endif
}
} //namespace memory
} //namespace base
} //namespace bs
| 7,464
|
C++
|
.cpp
| 133
| 41.947368
| 98
| 0.587777
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,068
|
memory_tracker.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/memory/managers/memory_tracker.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bs/base/memory/managers/memory_tracker.h>
namespace bs {
namespace base {
namespace memory {
#ifdef MEM_TRACK
#include <bs/base/memory/utils/logger.h>
#include <bs/base/memory/utils/mem_utils.h>
#include <bs/base/memory/data-units/mem_list.h>
#include <bs/base/memory/data-units/string_list.h>
#include <execinfo.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef MEM_STACK_SIZE
#define MEM_STACK_SIZE 10
#endif
#ifndef MEM_LOG_NAME
#define MEM_LOG_NAME "memory_track.log"
#endif
#define MAX_MSG_LEN 1000
#ifdef MEM_TRACK_CONSOLE
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"
#else
#define RED ""
#define GRN ""
#define YEL ""
#define BLU ""
#define MAG ""
#define CYN ""
#define WHT ""
#define RESET ""
#endif
static unsigned long long total_bytes_allocated;
static unsigned long long bytes_allocated_remaining;
static unsigned long long potential_leaks;
static long long num_mallocs;
static char msg[MAX_MSG_LEN];
static MEM_LIST current_list;
static MEM_LIST free_list;
static MEM_LIST potential_leaks_list;
static string_list file_filter = {0, 0, 0};
#ifdef MEM_TRACK_REG
static char file_filter_disable = 0;
#else
static char file_filter_disable = 1;
#endif
static char system_open = 0;
void allocation_call(void *ptr, size_t size, char const *file, int line,
char const *func, char *func_name, allocation_type alloc);
void deallocation_call(void *ptr, char const *file, int line, char const *func,
void (*dealloc_func)(void *), char *func_name,
deallocation_type deloc);
void allocation_call(void *ptr, size_t size, char const *file, int line,
char const *func, char *func_name, allocation_type alloc) {
if (ptr == NULL) {
sprintf(msg, YEL "WARNING : %s FAILED at %s:%d:%s\n" RESET, func_name, file,
line, func);
log_msg(msg);
} else {
MEM_ELEM *elem;
#if (MEM_TRACK == 0)
elem = create_block(ptr, size, alloc);
#elif (MEM_TRACK == 1 || MEM_TRACK == 2)
elem = create_block(ptr, size, file, func, line, alloc);
#elif (MEM_TRACK == 3)
char **strings;
size_t size_f;
strings = get_stack_trace(MEM_STACK_SIZE, &size_f);
elem = create_block(ptr, size, file, func, line, strings, size_f, alloc);
#else
#error Memory Tracker Level is unsupported only 0 to 3 are supported.
#endif
if (system_open) {
add_block(¤t_list, elem);
total_bytes_allocated += size;
bytes_allocated_remaining += size;
num_mallocs++;
} else {
sprintf(msg,
"System down allocation : pointer %p with size %lu allocated "
"with %s in %s:%d:%s\n",
ptr, size, func_name, file, line, func);
log_msg(msg);
delete_block(elem);
}
}
}
void deallocation_call(void *ptr, char const *file, int line, char const *func,
void (*dealloc_func)(void *), char *func_name,
deallocation_type deloc) {
if (system_open) {
MEM_ELEM *elem = free_block(¤t_list, ptr);
if (elem == NULL) {
if (system_open) {
sprintf(
msg,
RED
"ERROR : %s issued at an invalid pointer %p at %s:%d:%s\n" RESET,
func_name, ptr, file, line, func);
log_msg(msg);
} else {
sprintf(msg,
"System down deallocation : pointer %p deallocated with %s in "
"%s:%d:%s\n",
ptr, func_name, file, line, func);
log_msg(msg);
if (dealloc_func != NULL) {
(*dealloc_func)(ptr);
}
}
} else {
if (dealloc_func != NULL) {
(*dealloc_func)(ptr);
}
size_t size = elem->size;
#if (MEM_TRACK == 2)
modify_block(elem, file, func, line, deloc);
#elif (MEM_TRACK == 3)
char **strings;
size_t size_f;
strings = get_stack_trace(MEM_STACK_SIZE, &size_f);
modify_block(elem, file, func, line, strings, size_f, deloc);
#else
modify_block(elem, deloc);
#endif
if (matching_calls(elem->a_call, elem->d_call)) {
#if (MEM_TRACK >= 2)
#ifndef MEM_LEAKS_ONLY
add_block(&free_list, elem);
#else
delete_block(elem);
#endif
#else
delete_block(elem);
#endif
} else {
#if (MEM_TRACK >= 1)
add_block(&potential_leaks_list, elem);
#else
delete_block(elem);
#endif
potential_leaks++;
}
num_mallocs--;
bytes_allocated_remaining -= size;
}
} else {
sprintf(msg,
"System down de-allocation : pointer %p with de-allocated with %s "
"in %s:%d:%s\n",
ptr, func_name, file, line, func);
log_msg(msg);
}
}
#ifndef MEM_C_ONLY
void *operator new(size_t size) {
char file[MAX_MSG_LEN] = "file-name";
char ffile[MAX_MSG_LEN];
char func[MAX_MSG_LEN] = "func-name";
int l = 0;
char trace[MAX_MSG_LEN];
get_trace_line(1, trace);
extract_info(file, func, &l, trace, 0);
int itrace = 2;
char prefix[6];
char oldTrace[MAX_MSG_LEN];
for (int i = 0; i < 5; i++) {
prefix[i] = file[i];
}
prefix[5] = '\0';
while (strcmp(file, "addr2line") == 0 || strcmp(prefix, "/usr/") == 0) {
strncpy(oldTrace, trace, MAX_MSG_LEN);
get_trace_line(itrace, trace);
if (strcmp(trace, "") == 0 || strcmp(trace, oldTrace) == 0 ||
file[strlen(file) - 1] == 'h') {
break;
}
extract_info(file, func, &l, trace, 0);
itrace++;
for (int i = 0; i < 5; i++) {
prefix[i] = file[i];
}
prefix[5] = '\0';
}
if (strcmp(trace, "") == 0) {
get_trace_line(1, trace);
extract_info(file, func, &l, trace, 0);
}
filter_file_name(ffile, file);
void *ptr = (malloc)(size);
if (file_filter_disable || slist_contains(&file_filter, ffile)) {
allocation_call(ptr, size, file, l, func, "new", NEW);
}
return ptr;
}
void *operator new[](size_t size) {
char file[MAX_MSG_LEN] = "file-name";
char func[MAX_MSG_LEN] = "func-name";
char ffile[MAX_MSG_LEN];
int l = 0;
char trace[MAX_MSG_LEN];
get_trace_line(1, trace);
extract_info(file, func, &l, trace, 0);
int itrace = 2;
char prefix[6];
char oldTrace[MAX_MSG_LEN];
for (int i = 0; i < 5; i++) {
prefix[i] = file[i];
}
prefix[5] = '\0';
while (strcmp(file, "addr2line") == 0 || strcmp(prefix, "/usr/") == 0) {
strncpy(oldTrace, trace, MAX_MSG_LEN);
get_trace_line(itrace, trace);
if (strcmp(trace, "") == 0 || strcmp(trace, oldTrace) == 0 ||
file[strlen(file) - 1] == 'h') {
break;
}
extract_info(file, func, &l, trace, 0);
itrace++;
for (int i = 0; i < 5; i++) {
prefix[i] = file[i];
}
prefix[5] = '\0';
}
if (strcmp(trace, "") == 0) {
get_trace_line(1, trace);
extract_info(file, func, &l, trace, 0);
}
filter_file_name(ffile, file);
void *ptr = (malloc)(size);
if (file_filter_disable || slist_contains(&file_filter, ffile)) {
allocation_call(ptr, size, file, l, func, "new[]", NEW_ARR);
}
return ptr;
}
void operator delete(void *ptr) {
char file[MAX_MSG_LEN] = "file-name";
char func[MAX_MSG_LEN] = "func-name";
char ffile[MAX_MSG_LEN];
int l = 0;
char trace[MAX_MSG_LEN];
get_trace_line(1, trace);
extract_info(file, func, &l, trace, 1);
int itrace = 2;
while (strcmp(file, "addr2line") == 0) {
get_trace_line(itrace, trace);
extract_info(file, func, &l, trace, 1);
itrace++;
}
filter_file_name(ffile, file);
#ifdef MEM_TRACK_REG
MEM_ELEM *elem = get_block(¤t_list, ptr);
if (elem != NULL || file_filter_disable ||
slist_contains(&file_filter, ffile)) {
deallocation_call(ptr, file, l, func, &free, "delete", DELETE);
} else {
(free)(ptr);
}
#else
deallocation_call(ptr, file, l, func, &free, "delete", DELETE);
#endif
}
void operator delete[](void *ptr) {
char file[MAX_MSG_LEN] = "file-name";
char func[MAX_MSG_LEN] = "func-name";
char ffile[MAX_MSG_LEN];
int l = 0;
char trace[MAX_MSG_LEN];
get_trace_line(1, trace);
extract_info(file, func, &l, trace, 1);
int itrace = 2;
while (strcmp(file, "addr2line") == 0) {
get_trace_line(itrace, trace);
extract_info(file, func, &l, trace, 1);
itrace++;
}
filter_file_name(ffile, file);
#ifdef MEM_TRACK_REG
MEM_ELEM *elem = get_block(¤t_list, ptr);
if (elem != NULL || file_filter_disable ||
slist_contains(&file_filter, ffile)) {
deallocation_call(ptr, file, l, func, &free, "delete[]", DELETE_ARR);
} else {
(free)(ptr);
}
#else
deallocation_call(ptr, file, l, func, &free, "delete[]", DELETE_ARR);
#endif
}
#endif
void memory_track_startup(void) {
#ifdef MEM_TRACK_CONSOLE
char ce = 1;
char fe = 0;
#else
char ce = 0;
char fe = 1;
#endif
init_logger(ce, fe, MEM_LOG_NAME);
total_bytes_allocated = 0;
bytes_allocated_remaining = 0;
num_mallocs = 0;
potential_leaks = 0;
init_list(¤t_list);
init_list(&free_list);
init_list(&potential_leaks_list);
signal(SIGSEGV, seg_handler);
init_slist(&file_filter, 2);
system_open = 1;
}
void print_results(void) {
#if (MEM_TRACK >= 2)
log_msg("===================================================================="
"==============================================\n");
if (free_list.size > 0) {
log_msg(GRN "All Completed Allocations Data :\n" RESET);
print_list(&free_list);
} else {
log_msg(GRN "No Completed Allocations\n" RESET);
}
#endif
#if (MEM_TRACK >= 1)
log_msg("===================================================================="
"==============================================\n");
if (potential_leaks_list.size > 0) {
log_msg(RED "All Potenial Memory Leaks Data :\n" RESET);
print_list(&potential_leaks_list);
} else {
log_msg(GRN "No Potenial Leaks Found !\n" RESET);
} /**/
log_msg("===================================================================="
"==============================================\n");
if (current_list.size > 0) {
log_msg(RED "All Memory Leaks Data :\n" RESET);
print_list(¤t_list);
} else {
log_msg(GRN "No Memory Leaks Found !\n" RESET);
}
#endif
log_msg("===================================================================="
"==============================================\n");
sprintf(msg, BLU "Total bytes allocated during run : " RESET "%llu\n",
total_bytes_allocated);
log_msg(msg);
sprintf(msg, RED "Bytes still allocated :" RESET " %llu\n",
bytes_allocated_remaining);
log_msg(msg);
sprintf(msg, RED "Potential Leaks : " RESET "%llu\n", potential_leaks);
log_msg(msg);
sprintf(msg, YEL "Allocations - Deallocations : " RESET "%lld\n",
num_mallocs);
log_msg(msg);
log_msg("===================================================================="
"==============================================\n");
/**/
}
void memory_track_cleanup(void) {
system_open = 0;
printf("Begining Final Report Formatting :\n\tCompleted allocations list "
"size = %llu\n\tPotential leaks list size = %llu\n\tLeaks list size = "
"%llu\n\tLeak to total allocation percentage : %f\n",
free_list.size, potential_leaks_list.size, current_list.size,
total_bytes_allocated == 0 ? 0.0
: (((double) bytes_allocated_remaining) /
((double) total_bytes_allocated)) *
100.0);
sprintf(msg, "\n\n***********************************************************"
"*******************************************************\n");
log_msg(msg);
sprintf(msg, "*************************************************** End Report "
"***************************************************\n");
log_msg(msg);
sprintf(msg, "***************************************************************"
"***************************************************\n\n\n");
log_msg(msg);
print_results();
if (bytes_allocated_remaining == 0) {
printf(msg, GRN "No Memory Leak Detected !\n" RESET);
log_msg(msg);
} else {
sprintf(msg, RED "Memory Leaks Detected : %llu !\n" RESET, num_mallocs);
log_msg(msg);
}
delete_list(¤t_list);
delete_list(&free_list);
delete_list(&potential_leaks_list);
close_logger();
destroy_slist(&file_filter);
}
void mem_checkpoint(char *name) {
sprintf(msg, "Checkpoint Name : %s\n", name);
log_msg(msg);
print_results();
delete_list(&free_list);
delete_list(&potential_leaks_list);
init_list(&free_list);
init_list(&potential_leaks_list);
log_flush();
}
void name_ptr(void *ptr, char *name) {
MEM_ELEM *elem = get_block(¤t_list, ptr);
if (elem != NULL) {
name_block(elem, name);
}
}
void register_cpp_file(char *name) { add_slist(&file_filter, name); }
void seg_handler(int signum) {
int i;
char **strings;
size_t size_f;
strings = get_stack_trace(MEM_STACK_SIZE + 1, &size_f);
char temp[MAX_MSG_LEN];
log_msg("===================================================================="
"==============================================\n");
log_msg(RED "Segmentation fault detected !\n" RESET);
for (i = 3; i < size_f; i++) {
get_stack_trace_line(temp, strings[i]);
if (strcmp(temp, "\0") == 0 && i == 0) {
log_msg(YEL "No Support for 'addr2line' : only stack trace will be "
"printed\nUse objdump with -l flag to trace error\n" RESET);
}
if (i != 3) {
decrement_line(temp);
}
sprintf(msg, WHT "\t\t%s\n" RESET YEL "\t\t\t%s\n" RESET, strings[i], temp);
log_msg(msg);
}
(free)(strings);
exit(signum);
}
void *omalloc(size_t size, const char *file, int l, const char *func) {
void *ptr = (malloc)(size);
allocation_call(ptr, size, file, l, func, "malloc", MALLOC);
return ptr;
}
void *orealloc(void *ptr, size_t new_size, const char *file, int l,
const char *func) {
void *new_ptr = (realloc)(ptr, new_size);
deallocation_call(ptr, file, l, func, NULL, "realloc", D_REALLOC);
allocation_call(new_ptr, new_size, file, l, func, "realloc", A_REALLOC);
return new_ptr;
}
void *ocalloc(size_t num, size_t size, const char *file, int l,
const char *func) {
void *ptr = (calloc)(num, size);
size *= num;
allocation_call(ptr, size, file, l, func, "calloc", CALLOC);
return ptr;
}
void ofree(void *ptr, const char *file, int l, const char *func) {
deallocation_call(ptr, file, l, func, &free, "free", FREE);
}
#ifdef __INTEL_COMPILER
#undef _mm_malloc
// override _mm_malloc
void *omm_malloc(size_t size, size_t align, char const *file, int l,
char const *func) {
void *ptr = _mm_malloc(size, align);
allocation_call(ptr, size, file, l, func, "_mm_malloc", _MM_MALLOC);
return ptr;
}
#define _mm_malloc(size, align) \
omm_malloc(size, align, __FILE__, __LINE__, __FUNCTION__)
#undef _mm_free
// override _mm_free
void omm_free(void *ptr, char const *file, int l, char const *func) {
deallocation_call(ptr, file, l, func, &_mm_free, "_mm_free", _MM_FREE);
}
#define _mm_free(ptr) omm_free(ptr, __FILE__, __LINE__, __FUNCTION__)
#endif
#endif
} //namespace memory
} //namespace base
} //namespace bs
| 22,070
|
C++
|
.cpp
| 500
| 28.08
| 102
| 0.421564
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,069
|
FileLogger.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/logger/concrete/FileLogger.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <fstream>
#ifdef USING_SPDLOG
#include <spdlog/sinks/file_sinks.h>
#include <spdlog/logger.h>
#else
#include <fstream>
#include <sys/stat.h>
#endif
#include <bs/base/logger/concrete/FileLogger.hpp>
using namespace bs::base::logger;
FileLogger::FileLogger(const std::string &aFilePath) {
FileLogger::HandleFilePath(aFilePath);
this->mFilePath = aFilePath;
mFileStream.open(mFilePath);
}
FileLogger::~FileLogger() = default;
void
FileLogger::Configure(std::string aLoggerName) {
#ifdef USING_SPDLOG
std::shared_ptr<spdlog::sinks::simple_file_sink_mt> mSink = std::make_shared<spdlog::sinks::simple_file_sink_mt>(
mFilePath);
mpLogger = std::make_shared<spdlog::logger>(aLoggerName, mSink);
#endif
}
WriterMode
FileLogger::GetType() {
return WriterMode::FILE_MODE;
}
int
FileLogger::HandleFilePath(const std::string &aFilePath) {
auto directory = aFilePath;
auto pos = directory.rfind('/');
if (pos != std::string::npos) {
directory.erase(directory.begin() + pos, directory.end());
}
return mkdir(directory.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
void
FileLogger::Operate(std::string aStatement, Operation aOperation) {
this->mStatement = aStatement;
switch (aOperation) {
case Operation::INFO:
#ifdef USING_SPDLOG
mpLogger->info(mStatement);
#else
mFileStream.open(mFilePath, std::ios::app);
mFileStream << "[Info] " << mStatement << std::endl;
mFileStream.close();
#endif
break;
case Operation::ERROR:
#ifdef USING_SPDLOG
mpLogger->error(mStatement);
#else
mFileStream.open(mFilePath, std::ios::app);
mFileStream << "[Error] " << mStatement << std::endl;
mFileStream.close();
#endif
break;
case Operation::CRITICAL:
#ifdef USING_SPDLOG
mpLogger->critical(mStatement);
#else
mFileStream.open(mFilePath, std::ios::app);
mFileStream << "[Critical] " << mStatement << std::endl;
mFileStream.close();
#endif
case Operation::DEBUG:
#ifdef USING_SPDLOG
mpLogger->debug(mStatement);
#else
mFileStream.open(mFilePath, std::ios::app);
mFileStream << "[Debug] " << mStatement << std::endl;
mFileStream.close();
#endif
break;
default:
std::cout << "Undefined feature";
exit(0);
}
}
| 3,256
|
C++
|
.cpp
| 100
| 27.53
| 117
| 0.673678
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,070
|
ConsoleLogger.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/logger/concrete/ConsoleLogger.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#ifdef USING_SPDLOG
#include <spdlog/sinks/stdout_sinks.h>
#include <spdlog/logger.h>
#else
#include <iomanip>
#endif
#include <bs/base/logger/concrete/ConsoleLogger.hpp>
using namespace std;
using namespace bs::base::logger;
ConsoleLogger::ConsoleLogger() = default;
ConsoleLogger::~ConsoleLogger() = default;
void
ConsoleLogger::Configure(std::string aLoggerName) {
#ifdef USING_SPDLOG
std::shared_ptr<spdlog::sinks::stdout_sink_mt> mSink = std::make_shared<spdlog::sinks::stdout_sink_mt>();
this->mpLogger = std::make_shared<spdlog::logger>(aLoggerName, mSink);
#endif
}
WriterMode
ConsoleLogger::GetType() {
return WriterMode::CONSOLE_MODE;
}
void
ConsoleLogger::Operate(std::string aStatement, Operation aOperation) {
switch (aOperation) {
case Operation::INFO:
#ifdef USING_SPDLOG
this->mpLogger->info(aStatement);
#else
std::cout << left << setfill(' ') << setw(20) << "[info] " << aStatement << std::endl;
#endif
break;
case Operation::ERROR:
#ifdef USING_SPDLOG
this->mpLogger->error(aStatement);
#else
std::cout << left << setfill(' ') << setw(20) << "[Error] " << aStatement << std::endl;
#endif
break;
case Operation::CRITICAL:
#ifdef USING_SPDLOG
this->mpLogger->critical(aStatement);
#else
std::cout << left << setfill(' ') << setw(20) << "[Critical] " << aStatement << std::endl;
#endif
break;
case Operation::DEBUG:
#ifdef USING_SPDLOG
this->mpLogger->debug(aStatement);
#else
std::cout << left << setfill(' ') << setw(20) << "[Debug] " << aStatement << std::endl;
#endif
break;
default:
cout << "Undefined feature";
exit(0);
}
}
| 2,569
|
C++
|
.cpp
| 77
| 29
| 109
| 0.674334
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,071
|
LoggerSystem.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/logger/concrete/LoggerSystem.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bs/base/logger/concrete/LoggerSystem.hpp>
using namespace bs::base::logger;
LoggerSystem::LoggerSystem() {
this->mpLoggerChannels.push_back(new LoggerChannel(&this->mpCollection, INFO));
this->mpLoggerChannels.push_back(new LoggerChannel(&this->mpCollection, ERROR));
this->mpLoggerChannels.push_back(new LoggerChannel(&this->mpCollection, CRITICAL));
this->mpLoggerChannels.push_back(new LoggerChannel(&this->mpCollection, DEBUG));
}
void
LoggerSystem::RegisterLogger(Logger *aLogger) {
this->mpCollection.RegisterLogger(aLogger);
}
void
LoggerSystem::ConfigureLoggers(const std::string &aLoggerName, WriterMode aMode, Pattern aPattern) {
this->mpCollection.ConfigureLoggers(aLoggerName, aMode, aPattern);
}
LoggerChannel &
LoggerSystem::Info() {
return *this->mpLoggerChannels[0];
}
LoggerChannel &
LoggerSystem::Error() {
return *this->mpLoggerChannels[1];
}
LoggerChannel &
LoggerSystem::Critical() {
return *this->mpLoggerChannels[2];
}
LoggerChannel &
LoggerSystem::Debug() {
return *this->mpLoggerChannels[3];
}
| 1,861
|
C++
|
.cpp
| 51
| 34.156863
| 100
| 0.769316
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,072
|
LoggerChannel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/logger/concrete/LoggerChannel.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bs/base/logger/concrete/LoggerChannel.hpp>
using namespace bs::base::logger;
LoggerChannel::LoggerChannel(LoggerCollection *aCollection, Operation aOperation) {
this->mOperationType = aOperation;
this->mpCollection = aCollection;
}
LoggerChannel::~LoggerChannel() = default;
| 1,059
|
C++
|
.cpp
| 25
| 40.16
| 83
| 0.768707
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,073
|
LoggerCollection.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/logger/concrete/LoggerCollection.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bs/base/logger/concrete/LoggerCollection.hpp>
using namespace bs::base::logger;
LoggerCollection::LoggerCollection() = default;
LoggerCollection::~LoggerCollection() {
for (auto l : this->mpLoggersVector) { delete l; }
this->mpLoggersVector.clear();
}
void
LoggerCollection::RegisterLogger(Logger *aLogger) {
this->mpLoggersVector.push_back(aLogger);
}
void
LoggerCollection::ConfigureLoggers(const std::string &aLoggerName, WriterMode aMode, Pattern aPattern) {
this->mMode = aMode;
for (auto l : this->mpLoggersVector) {
if (l->GetType() == this->mMode || this->mMode == WriterMode::FILE_CONSOLE) {
l->Configure(aLoggerName);
l->SetPattern(aPattern);
}
}
}
void
LoggerCollection::Operate(const std::string &aStatement, Operation aOperation) {
for (auto l : this->mpLoggersVector) {
if (l->GetType() == this->mMode || this->mMode == WriterMode::FILE_CONSOLE) {
l->Operate(aStatement, aOperation);
}
}
}
| 1,805
|
C++
|
.cpp
| 48
| 33.958333
| 104
| 0.717802
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,074
|
JSONConfigurationMap.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/configurations/concrete/JSONConfigurationMap.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sstream>
#include <utility>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
using namespace bs::base::configurations;
JSONConfigurationMap::JSONConfigurationMap(nlohmann::json aJson)
: mJson(std::move(aJson)) {}
inline float
JSONConfigurationMap::GetValue(const std::string &aSectionKey,
const std::string &aPropertyKey,
float aDefaultValue) {
float val = aDefaultValue;
if (this->Contains(aSectionKey, aPropertyKey)) {
val = this->mJson[aSectionKey][aPropertyKey].get<float>();
}
return val;
}
uint
JSONConfigurationMap::GetValue(const std::string &aSectionKey,
const std::string &aPropertyKey,
int aDefaultValue) {
uint val = aDefaultValue;
if (this->Contains(aSectionKey, aPropertyKey)) {
val = this->mJson[aSectionKey][aPropertyKey].get<uint>();
}
return val;
}
double
JSONConfigurationMap::GetValue(const std::string &aSectionKey,
const std::string &aPropertyKey,
double aDefaultValue) {
double val = aDefaultValue;
if (this->Contains(aSectionKey, aPropertyKey)) {
val = this->mJson[aSectionKey][aPropertyKey].get<double>();
}
return val;
}
std::string
JSONConfigurationMap::GetValue(const std::string &aSectionKey,
const std::string &aPropertyKey,
std::string aDefaultValue) {
std::string val = aDefaultValue;
if (this->Contains(aSectionKey, aPropertyKey)) {
val = this->mJson[aSectionKey][aPropertyKey].get<std::string>();
}
return val;
}
bool
JSONConfigurationMap::GetValue(const std::string &aSectionKey,
const std::string &aPropertyKey,
bool aDefaultValue) {
bool val = aDefaultValue;
if (this->Contains(aSectionKey, aPropertyKey)) {
val = this->mJson[aSectionKey][aPropertyKey].get<bool>();
}
return val;
}
size_t
JSONConfigurationMap::Size() {
return this->mJson.size();
}
bool
JSONConfigurationMap::Contains(const std::string &aSectionKey) {
return mJson.contains(aSectionKey) && mJson[aSectionKey].is_object();
}
bool
JSONConfigurationMap::Contains(const std::string &aSectionKey,
const std::string &aPropertyKey) {
return this->Contains(aSectionKey) &&
mJson[aSectionKey].contains(aPropertyKey) &&
!mJson[aSectionKey][aPropertyKey].is_null();
}
std::string
JSONConfigurationMap::GetValue(const std::string &aPropertyKey,
const std::string &aDefaultValue) {
std::string val = aDefaultValue;
if (this->Contains(aPropertyKey)) {
val = this->mJson[aPropertyKey].get<std::string>();
}
return val;
}
void
JSONConfigurationMap::WriteValue(const std::string &aSectionKey,
const std::string &aPropertyKey,
std::string aValue) {
this->mJson[aSectionKey][aPropertyKey] = aValue;
}
std::string
JSONConfigurationMap::ToString() {
return this->mJson.dump(4);
}
std::vector<bs::base::configurations::ConfigurationMap *>
JSONConfigurationMap::GetConfigurationArray(std::string &aSectionKey) {
auto temp_map = this->mJson[aSectionKey];
std::vector<bs::base::configurations::ConfigurationMap *> submaps;
for (auto &m : temp_map) {
submaps.push_back(new JSONConfigurationMap(m));
}
return submaps;
}
std::vector<bs::base::configurations::ConfigurationMap *>
JSONConfigurationMap::GetConfigurationArray(std::string &aPropertyKey,
std::string &aSectionKey) {
auto temp_map = this->mJson[aPropertyKey][aSectionKey];
std::vector<bs::base::configurations::ConfigurationMap *> submaps;
for (auto &m : temp_map) {
submaps.push_back(new JSONConfigurationMap(m));
}
return submaps;
}
bool
JSONConfigurationMap::HasKey(const std::string &aSectionKey) {
return mJson.contains(aSectionKey);
}
std::string JSONConfigurationMap::GetKeyValue(const std::string &aPropertyKey,
const std::string &aDefaultValue) {
std::string val = aDefaultValue;
if (this->HasKey(aPropertyKey)) {
val = this->mJson[aPropertyKey].get<std::string>();
}
return val;
}
| 5,248
|
C++
|
.cpp
| 139
| 30.661871
| 81
| 0.663127
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,075
|
Backend.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/backend/omp/Backend.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vector>
#include <bs/base/exceptions/Exceptions.hpp>
#include <bs/base/backend/Backend.hpp>
using namespace bs::base::exceptions;
using namespace bs::base::backend;
Backend::Backend() {
throw NOT_IMPLEMENTED_EXCEPTION();
}
Backend::~Backend() = default;
KernelConfiguration
Backend::CreateKernelConfiguration(std::vector<uint> aDomainDims,
std::vector<uint> aBlockDims,
size_t aSharedMemoryBytes,
uint aExecutorId) {
throw NOT_IMPLEMENTED_EXCEPTION();
}
void
Backend::ErrorCheck(void *aResult, char *aFile, int aLine) {
throw NOT_IMPLEMENTED_EXCEPTION();
}
uint
Backend::CreateExecutor() {
throw NOT_IMPLEMENTED_EXCEPTION();
}
PoolType
Backend::GetExecutor(uint aExecutorID) {
throw NOT_IMPLEMENTED_EXCEPTION();
}
void *
Backend::Sync() {
throw NOT_IMPLEMENTED_EXCEPTION();
}
| 1,687
|
C++
|
.cpp
| 50
| 29.6
| 77
| 0.717712
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,076
|
Backend.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSBase/src/backend/oneapi/Backend.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS Base Package.
*
* BS Base Package is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BS Base Package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vector>
#include <bs/base/backend/Backend.hpp>
using namespace sycl;
using namespace bs::base::backend;
Backend::Backend() {
PoolType defaultStream;
this->mExecutorPool.emplace(0, defaultStream);
this->mDeviceQueue = nullptr;
this->mOneAPIAlgorithm = SYCL_ALGORITHM::CPU;
this->mWorkgroupNumber = 0;
this->mWorkgroupSize = 0;
}
Backend::~Backend() {
delete this->mDeviceQueue;
}
KernelConfiguration
Backend::CreateKernelConfiguration(std::vector<uint> aDomainDims,
std::vector<uint> aBlockDims,
size_t aSharedMemoryBytes,
uint aExecutorId) {
for (auto i = aDomainDims.size(); i < 3; i++) {
aDomainDims.push_back(1);
}
for (auto i = aBlockDims.size(); i < 3; i++) {
aBlockDims.push_back(1);
}
KernelConfiguration args;
sycl::range<3> GridDimensions{1, 1, 1};
sycl::range<3> BlockDimensions{1, 1, 1};
uint gridDim_x = aDomainDims[0];
uint gridDim_y = aDomainDims[1];
uint gridDim_z = aDomainDims[2];
BlockDimensions[0] = aBlockDims[0];
BlockDimensions[1] = aBlockDims[1];
BlockDimensions[2] = aBlockDims[2];
GridDimensions[0] = gridDim_x;
GridDimensions[1] = gridDim_y;
GridDimensions[2] = gridDim_z;
args.mBlockDimensions = BlockDimensions;
args.mGridDimensions = GridDimensions;
args.mExecutor = this->mExecutorPool[aExecutorId];
args.mSharedMemory = aSharedMemoryBytes;
return args;
}
uint
Backend::CreateExecutor() {
PoolType executor;
auto executor_idx = this->mExecutorPool.size();
this->mExecutorPool.emplace(executor_idx, executor);
return executor_idx;
}
PoolType
Backend::GetExecutor(uint aExecutorID) {
return this->mExecutorPool[aExecutorID];
}
void
Backend::SetDeviceQueue(cl::sycl::queue *aDeviceQueue) {
this->mDeviceQueue = aDeviceQueue;
if (this->mDeviceQueue->get_device().is_cpu()) {
this->mWorkgroupNumber =
this->mDeviceQueue->get_device().get_info<info::device::max_compute_units>();
this->mWorkgroupSize =
this->mDeviceQueue->get_device().get_info<info::device::native_vector_width_double>() * 2;
} else {
this->mWorkgroupNumber =
this->mDeviceQueue->get_device().get_info<info::device::max_compute_units>() * 4;
this->mWorkgroupSize =
this->mDeviceQueue->get_device().get_info<info::device::max_work_group_size>();
}
}
void
Backend::SetAlgorithm(SYCL_ALGORITHM aOneAPIAlgorithm) {
this->mOneAPIAlgorithm = aOneAPIAlgorithm;
}
| 3,406
|
C++
|
.cpp
| 92
| 31.630435
| 106
| 0.687197
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,077
|
main.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/examples/migration/main.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
/// { @todo To be removed when all NOT_IMPLEMENTED_EXCEPTION() are resolved
#include <bs/base/exceptions/concrete/NotImplementedException.hpp>
/// }
int main(int argc, char *argv[]) {
/// @todo To be implemented
throw bs::base::exceptions::NOT_IMPLEMENTED_EXCEPTION();
}
| 1,038
|
C++
|
.cpp
| 25
| 39.48
| 76
| 0.753953
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,078
|
TestCrossCorrelationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/components/independents/migration-accommodators/TestCrossCorrelationKernel.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <prerequisites/libraries/catch/catch.hpp>
#include <operations/components/independents/concrete/migration-accommodators/CrossCorrelationKernel.hpp>
#include <operations/configurations/MapKeys.h>
#include <operations/data-units/concrete/holders/FrameBuffer.hpp>
#include <operations/common/DataTypes.h>
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
#include <operations/test-utils/NumberHelpers.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::testutils;
void TEST_CASE_CROSS_CORRELATION_COMBINED_COMPENSATION(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
apConfigurationMap->WriteValue(OP_K_PROPRIETIES, OP_K_COMPENSATION, OP_K_COMPENSATION_COMBINED);
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_back = new FrameBuffer<float>();
auto pressure_forward = new FrameBuffer<float>();
auto *forward_gridbox = new GridBox;
apGridBox->SetNT(1);
apGridBox->Clone(forward_gridbox);
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_back->Allocate(window_size);
pressure_forward->Allocate(window_size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_back);
forward_gridbox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_forward);
Device::MemSet(pressure_back->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_forward->GetNativePointer(), 0.0f, window_size * sizeof(float));
auto uut = new CrossCorrelationKernel(apConfigurationMap);
uut->SetComputationParameters(apParameters);
uut->SetGridBox(apGridBox);
uut->AcquireConfiguration();
float temp_a[window_size];
float temp_b[window_size];
float ground_truth[window_size];
float stack_ground_truth[window_size];
for (int i = 0; i < window_size; i++) {
temp_a[i] = (int) ((float) rand() * 100.0f / RAND_MAX);
temp_b[i] = (int) ((float) rand() * 100.0f / RAND_MAX);
ground_truth[i] = temp_a[i] * temp_b[i];
stack_ground_truth[i] = ground_truth[i]
/ (sqrtf(temp_a[i] * temp_a[i] * temp_b[i] * temp_b[i]) + 1e-20f);
}
Device::MemCpy(apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer(), temp_b,
window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(forward_gridbox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer(), temp_a,
window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
uut->Correlate(forward_gridbox);
auto correlation_result = uut->GetShotCorrelation()->GetHostPointer();
int misses = 0;
uint offset = apParameters->GetHalfLength();
uint nxEnd = wnx - offset;
uint nyEnd = 1;
uint nzEnd = wnz - offset;
int y_start = 0;
if (ny != 1) {
y_start = offset;
nyEnd = wny - offset;
}
/// Loop over correlation test case
for (int j = y_start; j < nyEnd; j++) {
for (int k = offset; k < nzEnd; k++) {
for (int i = offset; i < nxEnd; i++) {
int index = j * wnx * wnz + k * wnx + i;
misses += !approximately_equal(correlation_result[index], ground_truth[index]);
}
}
}
REQUIRE(misses == 0);
misses = 0;
uut->Stack();
auto stack_result = uut->GetStackedShotCorrelation()->GetHostPointer();
offset = apParameters->GetHalfLength() + apParameters->GetBoundaryLength();
nxEnd = wnx - offset;
nzEnd = wnz - offset;
if (ny != 1) {
y_start = offset;
nyEnd = wny - offset;
}
/// Loop over stacked correlation test case
for (int i = offset; i < nxEnd; i++) {
for (int j = y_start; j < nyEnd; j++) {
for (int k = offset; k < nzEnd; k++) {
int window_index = j * wnx * wnz + k * wnx + i;
int grid_index = j * nx * nz + k * nx + i;
misses += !approximately_equal(stack_result[grid_index], stack_ground_truth[window_index]);
}
}
}
REQUIRE(misses == 0);
misses = 0;
uut->ResetShotCorrelation();
correlation_result = uut->GetShotCorrelation()->GetHostPointer();
for (int i = 0; i < window_size; i++) {
misses += correlation_result[i] != 0.0;
}
REQUIRE(misses == 0);
misses = 0;
for (int i = 0; i < window_size; i++) {
temp_a[i] = (int) ((float) rand() * 100.0f / RAND_MAX);
temp_b[i] = (int) ((float) rand() * 100.0f / RAND_MAX);
stack_ground_truth[i] += (temp_a[i] * temp_b[i])
/ (sqrtf(temp_a[i] * temp_a[i] * temp_b[i] * temp_b[i]) + 1e-20f);
}
Device::MemCpy(forward_gridbox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer(), temp_a,
window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer(), temp_b,
window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
uut->Correlate(forward_gridbox);
uut->Stack();
stack_result = uut->GetStackedShotCorrelation()->GetHostPointer();
/// Loop over stacked correlation test case - 2nd round
for (int i = offset; i < nxEnd; i++) {
for (int j = y_start; j < nyEnd; j++) {
for (int k = offset; k < nzEnd; k++) {
int window_index = j * wnx * wnz + k * wnx + i;
int grid_index = j * nx * nz + k * nx + i;
misses += !approximately_equal(stack_result[grid_index], stack_ground_truth[window_index]);
}
}
}
REQUIRE(misses == 0);
misses = 0;
auto migration_result = uut->GetMigrationData();
REQUIRE(migration_result->GetGridSize(X_AXIS) == nx);
REQUIRE(migration_result->GetGridSize(Y_AXIS) == ny);
REQUIRE(migration_result->GetGridSize(Z_AXIS) == nz);
REQUIRE(migration_result->GetCellDimensions(X_AXIS) ==
apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension());
REQUIRE(migration_result->GetCellDimensions(Y_AXIS) ==
apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension());
REQUIRE(migration_result->GetCellDimensions(Z_AXIS) ==
apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension());
REQUIRE(migration_result->GetGatherDimension() == 1);
REQUIRE(migration_result->GetResults().size() == 1);
auto migration_buffer = migration_result->GetResultAt(0)->GetData();
/// Loop over migration buffer test case - 2nd round
for (int i = offset; i < nxEnd; i++) {
for (int j = y_start; j < nyEnd; j++) {
for (int k = offset; k < nzEnd; k++) {
int window_index = j * wnx * wnz + k * wnx + i;
int grid_index = j * nx * nz + k * nx + i;
misses += !approximately_equal(migration_buffer[grid_index], stack_ground_truth[window_index]);
}
}
}
REQUIRE(misses == 0);
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete pressure_back;
delete pressure_forward;
delete forward_gridbox;
delete uut;
}
void TEST_CASE_CROSS_CORRELATION_NO_COMPENSATION(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
apConfigurationMap->WriteValue(OP_K_PROPRIETIES, OP_K_COMPENSATION, OP_K_COMPENSATION_NONE);
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_back = new FrameBuffer<float>();
auto pressure_forward = new FrameBuffer<float>();
auto forward_gridbox = new GridBox;
apGridBox->SetNT(1);
apGridBox->Clone(forward_gridbox);
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_back->Allocate(window_size);
pressure_forward->Allocate(window_size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_back);
forward_gridbox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_forward);
Device::MemSet(pressure_back->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_forward->GetNativePointer(), 0.0f, window_size * sizeof(float));
auto uut = new CrossCorrelationKernel(apConfigurationMap);
uut->SetComputationParameters(apParameters);
uut->SetGridBox(apGridBox);
uut->AcquireConfiguration();
float temp_a[window_size];
float temp_b[window_size];
float ground_truth[window_size];
for (int i = 0; i < window_size; i++) {
temp_a[i] = (float) rand() * 100 / RAND_MAX;
temp_b[i] = (float) rand() * 100 / RAND_MAX;
ground_truth[i] = temp_a[i] * temp_b[i];
}
Device::MemCpy(apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer(), temp_b,
window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(forward_gridbox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer(), temp_a,
window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
uut->Correlate(forward_gridbox);
auto correlation_result = uut->GetShotCorrelation()->GetHostPointer();
int misses = 0;
uint offset = apParameters->GetHalfLength();
uint nxEnd = wnx - offset;
uint nyEnd = 1;
uint nzEnd = wnz - offset;
int y_start = 0;
if (ny != 1) {
y_start = offset;
nyEnd = wny - offset;
}
/// Loop over correlation test case
for (int j = y_start; j < nyEnd; j++) {
for (int k = offset; k < nzEnd; k++) {
for (int i = offset; i < nxEnd; i++) {
int index = j * wnx * wnz + k * wnx + i;
misses += !approximately_equal(correlation_result[index], ground_truth[index]);
}
}
}
REQUIRE(misses == 0);
misses = 0;
uut->Stack();
auto stack_result = uut->GetStackedShotCorrelation()->GetHostPointer();
offset = apParameters->GetHalfLength() + apParameters->GetBoundaryLength();
nxEnd = wnx - offset;
nzEnd = wnz - offset;
if (ny != 1) {
y_start = offset;
nyEnd = wny - offset;
}
/// Loop over stacked correlation test case
for (int i = offset; i < nxEnd; i++) {
for (int j = y_start; j < nyEnd; j++) {
for (int k = offset; k < nzEnd; k++) {
int window_index = j * wnx * wnz + k * wnx + i;
int grid_index = j * nx * nz + k * nx + i;
misses += !approximately_equal(stack_result[grid_index], ground_truth[window_index]);
}
}
}
REQUIRE(misses == 0);
misses = 0;
uut->ResetShotCorrelation();
correlation_result = uut->GetShotCorrelation()->GetHostPointer();
for (int i = 0; i < window_size; i++) {
misses += correlation_result[i] != 0.0;
}
REQUIRE(misses == 0);
misses = 0;
for (int i = 0; i < window_size; i++) {
temp_a[i] = (float) rand() * 100 / RAND_MAX;
temp_b[i] = (float) rand() * 100 / RAND_MAX;
ground_truth[i] += temp_a[i] * temp_b[i];
}
Device::MemCpy(forward_gridbox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer(), temp_a,
window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer(), temp_b,
window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
uut->Correlate(forward_gridbox);
uut->Stack();
stack_result = uut->GetStackedShotCorrelation()->GetHostPointer();
/// Loop over stacked correlation test case - 2nd round
for (int i = offset; i < nxEnd; i++) {
for (int j = y_start; j < nyEnd; j++) {
for (int k = offset; k < nzEnd; k++) {
int window_index = j * wnx * wnz + k * wnx + i;
int grid_index = j * nx * nz + k * nx + i;
misses += !approximately_equal(stack_result[grid_index], ground_truth[window_index]);
}
}
}
REQUIRE(misses == 0);
misses = 0;
auto migration_result = uut->GetMigrationData();
REQUIRE(migration_result->GetGridSize(X_AXIS) == nx);
REQUIRE(migration_result->GetGridSize(Y_AXIS) == ny);
REQUIRE(migration_result->GetGridSize(Z_AXIS) == nz);
REQUIRE(migration_result->GetCellDimensions(X_AXIS) ==
apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension());
REQUIRE(migration_result->GetCellDimensions(Y_AXIS) ==
apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension());
REQUIRE(migration_result->GetCellDimensions(Z_AXIS) ==
apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension());
REQUIRE(migration_result->GetGatherDimension() == 1);
REQUIRE(migration_result->GetResults().size() == 1);
auto migration_buffer = migration_result->GetResultAt(0)->GetData();
/// Loop over migration buffer test case - 2nd round
for (int i = offset; i < nxEnd; i++) {
for (int j = y_start; j < nyEnd; j++) {
for (int k = offset; k < nzEnd; k++) {
int window_index = j * wnx * wnz + k * wnx + i;
int grid_index = j * nx * nz + k * nx + i;
misses += !approximately_equal(migration_buffer[grid_index], ground_truth[window_index]);
}
}
}
REQUIRE(misses == 0);
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete pressure_back;
delete pressure_forward;
delete forward_gridbox;
delete uut;
}
TEST_CASE("CrossCorrelation - No Compensation - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_CROSS_CORRELATION_NO_COMPENSATION(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("CrossCorrelation - No Compensation - 2D - Window", "[Window],[2D]") {
TEST_CASE_CROSS_CORRELATION_NO_COMPENSATION(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("CrossCorrelation - Combined Compensation - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_CROSS_CORRELATION_COMBINED_COMPENSATION(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("CrossCorrelation - Combined Compensation - 2D - Window", "[Window],[2D]") {
TEST_CASE_CROSS_CORRELATION_COMBINED_COMPENSATION(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
| 17,740
|
C++
|
.cpp
| 380
| 39.026316
| 111
| 0.629679
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,079
|
TestTwoPropagation.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/components/independents/forward-collectors/TestTwoPropagation.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <prerequisites/libraries/catch/catch.hpp>
#include <operations/components/independents/concrete/forward-collectors/TwoPropagation.hpp>
#include <operations/common/DataTypes.h>
#include <operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp>
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
#include <operations/test-utils/NumberHelpers.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::testutils;
using namespace operations::helpers;
void TEST_CASE_FORWARD_COLLECTOR_TWO(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
auto memory_handler = new WaveFieldsMemoryHandler(apConfigurationMap);
float nt = 300;
apGridBox->SetNT(nt);
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
float fetch_pres[window_size];
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
memory_handler->SetComputationParameters(apParameters);
auto dependent_components_map = new ComponentsMap<DependentComponent>();
dependent_components_map->Set(MEMORY_HANDLER, memory_handler);
auto configuration_map = new JSONConfigurationMap(R"(
{
"properties": {
"zfp-tolerance": 0.9,
"zfp-parallel": 4,
"zfp-relative": false,
"write-path": "./test-data",
"compression-type": "zfp",
"compression": false
}
}
)"_json);
auto forward_collector = new TwoPropagation(configuration_map);
forward_collector->SetComputationParameters(apParameters);
forward_collector->SetDependentComponents(dependent_components_map);
forward_collector->SetGridBox(apGridBox);
forward_collector->AcquireConfiguration();
/*
* Test for rest grid case true , means the wva fields should be zero
*/
Device::MemSet(pressure_curr->GetNativePointer(), 1.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 1.0f, window_size * sizeof(float));
int misses = 0;
forward_collector->ResetGrid(true);
auto grid_box = forward_collector->GetForwardGrid();
auto curr_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
auto prev_pressure = apGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetHostPointer();
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (curr_pressure[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses == 0);
/*
* Check that the wave fields are set to zero
*/
misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (prev_pressure[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses == 0);
forward_collector->ResetGrid(false);
auto init_grid_box = forward_collector->GetForwardGrid();
REQUIRE(init_grid_box->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize() == nx);
REQUIRE(init_grid_box->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize() == ny);
REQUIRE(init_grid_box->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize() == nz);
REQUIRE(init_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer() != nullptr);
REQUIRE(init_grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer() != nullptr);
REQUIRE(init_grid_box->Get(PARM | GB_VEL)->GetNativePointer() != nullptr);
auto pres_curr = grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto pres_prev = grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
auto pres_next = grid_box->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
/*
* Check that the pointers are swapped
*/
auto swap_grid_box = forward_collector->GetForwardGrid();
auto swap_pres_curr = swap_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto swap_pres_prev = swap_grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
auto swap_pres_next = swap_grid_box->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
REQUIRE(swap_pres_prev == pres_next);
auto fetch_grid_box = forward_collector->GetForwardGrid();
auto h_pressure = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int location = (wnx / 2) + (wnz / 2) * wnx + (wny / 2) * wnx * wnz;
h_pressure[location] = 1;
auto d_pressure = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
Device::MemCpy(d_pressure, h_pressure, window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
for (int it = 0; it < int(nt); it++) {
forward_collector->SaveForward();
}
Device::MemCpy(fetch_pres, d_pressure, window_size * sizeof(float), Device::COPY_DEVICE_TO_HOST);
/*
* Check that there is a propagation
*/
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (fetch_pres[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses > 0);
for (int it = int(nt); it > 0; it--) {
forward_collector->FetchForward();
}
auto fetch_backup_grid_box = forward_collector->GetForwardGrid();
auto fetch_pres_backup = fetch_backup_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
/*
* Check that the arrays is stored in a file , and the data from the file read is the same output of saving
*/
misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (fetch_pres[index] != fetch_pres_backup[index]) {
misses += 1;
}
}
}
}
REQUIRE(misses > 0);
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete dependent_components_map;
delete memory_handler;
delete forward_collector;
}
void TEST_CASE_FORWARD_COLLECTOR_TWO_INC_COMPRESSION_NO_TOLERANCE(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
float nt = 300;
apGridBox->SetNT(nt);
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
auto memory_handler = new WaveFieldsMemoryHandler(apConfigurationMap);
memory_handler->SetComputationParameters(apParameters);
auto dependent_components_map = new ComponentsMap<DependentComponent>();
dependent_components_map->Set(MEMORY_HANDLER, memory_handler);
auto configuration_map = new JSONConfigurationMap(R"(
{
"properties": {
"zfp-tolerance": 0.0,
"zfp-parallel": 1,
"zfp-relative": true,
"write-path": "test",
"compression-type": "zfp",
"compression": true
}
}
)"_json);
auto forward_collector = new TwoPropagation(configuration_map);
forward_collector->SetComputationParameters(apParameters);
forward_collector->SetDependentComponents(dependent_components_map);
forward_collector->SetGridBox(apGridBox);
forward_collector->AcquireConfiguration();
/*
* Test for rest grid case true , means the wva fields should be zero
*/
Device::MemSet(pressure_curr->GetNativePointer(), 1.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 1.0f, window_size * sizeof(float));
forward_collector->ResetGrid(true);
auto grid_box = forward_collector->GetForwardGrid();
auto curr_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
auto prev_pressure = apGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetHostPointer();
int misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (curr_pressure[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses == 0);
misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (prev_pressure[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses == 0);
forward_collector->ResetGrid(false);
auto init_grid_box = forward_collector->GetForwardGrid();
REQUIRE(init_grid_box->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize() == nx);
REQUIRE(init_grid_box->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize() == ny);
REQUIRE(init_grid_box->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize() == nz);
REQUIRE(init_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer() != nullptr);
REQUIRE(init_grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer() != nullptr);
REQUIRE(init_grid_box->Get(PARM | GB_VEL)->GetNativePointer() != nullptr);
auto pres_curr = grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto pres_prev = grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
auto pres_next = grid_box->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
auto swap_grid_box = forward_collector->GetForwardGrid();
auto swap_pres_curr = swap_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto swap_pres_prev = swap_grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
auto swap_pres_next = swap_grid_box->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
REQUIRE(swap_pres_prev == pres_next);
auto fetch_grid_box = forward_collector->GetForwardGrid();
auto h_pressure = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int location = (wnx / 2) + (wnz / 2) * wnx + (wny / 2) * wnx * wnz;
h_pressure[location] = 1;
auto d_pressure = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
Device::MemCpy(d_pressure, h_pressure, window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
for (int it = 0; it < int(nt); it++) {
forward_collector->SaveForward();
}
float fetch_pres[window_size];
Device::MemCpy(fetch_pres, d_pressure, window_size * sizeof(float), Device::COPY_DEVICE_TO_HOST);
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (fetch_pres[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses > 0);
for (int it = int(nt); it > 0; it--) {
forward_collector->FetchForward();
}
auto fetch_backup_grid_box = forward_collector->GetForwardGrid();
auto fetch_pres_backup = fetch_backup_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (fetch_pres[index] != fetch_pres_backup[index]) {
misses += 1;
}
}
}
}
REQUIRE(misses > 0);
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete dependent_components_map;
delete memory_handler;
delete forward_collector;
}
void TEST_CASE_FORWARD_COLLECTOR_TWO_INC_COMPRESSION_NO_RELATIVE(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
auto configuration_map = new JSONConfigurationMap(R"(
{
"properties": {
"zfp-tolerance": 0.9,
"zfp-relative": false,
"write-path": "test",
"zfp-parallel": 2,
"compression-type": "zfp",
"compression": true
}
}
)"_json);
float nt = 300;
apGridBox->SetNT(nt);
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
auto memory_handler = new WaveFieldsMemoryHandler(apConfigurationMap);
memory_handler->SetComputationParameters(apParameters);
auto dependent_components_map = new ComponentsMap<DependentComponent>();
dependent_components_map->Set(MEMORY_HANDLER, memory_handler);
auto forward_collector = new TwoPropagation(configuration_map);
forward_collector->SetComputationParameters(apParameters);
forward_collector->SetDependentComponents(dependent_components_map);
forward_collector->SetGridBox(apGridBox);
forward_collector->AcquireConfiguration();
/*
* Test for rest grid case true , means the wva fields should be zero
*/
Device::MemSet(pressure_curr->GetNativePointer(), 1.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 1.0f, window_size * sizeof(float));
forward_collector->ResetGrid(true);
auto grid_box = forward_collector->GetForwardGrid();
auto curr_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
auto prev_pressure = apGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetHostPointer();
int misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (curr_pressure[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses == 0);
misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (prev_pressure[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses == 0);
forward_collector->ResetGrid(false);
auto init_grid_box = forward_collector->GetForwardGrid();
REQUIRE(init_grid_box->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize() == nx);
REQUIRE(init_grid_box->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize() == ny);
REQUIRE(init_grid_box->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize() == nz);
REQUIRE(init_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer() != nullptr);
REQUIRE(init_grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer() != nullptr);
REQUIRE(init_grid_box->Get(PARM | GB_VEL)->GetNativePointer() != nullptr);
auto pres_curr = grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto pres_prev = grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
auto pres_next = grid_box->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
auto swap_grid_box = forward_collector->GetForwardGrid();
auto swap_pres_curr = swap_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto swap_pres_prev = swap_grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
auto swap_pres_next = swap_grid_box->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
REQUIRE(swap_pres_prev == pres_next);
auto fetch_grid_box = forward_collector->GetForwardGrid();
auto h_pressure = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int location = (wnx / 2) + (wnz / 2) * wnx + (wny / 2) * wnx * wnz;
h_pressure[location] = 1;
auto d_pressure = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
Device::MemCpy(d_pressure, h_pressure, window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
for (int it = 0; it < int(nt); it++) {
forward_collector->SaveForward();
}
float fetch_pres[window_size];
Device::MemCpy(fetch_pres, d_pressure, window_size * sizeof(float), Device::COPY_DEVICE_TO_HOST);
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (fetch_pres[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses > 0);
for (int it = int(nt); it > 0; it--) {
forward_collector->FetchForward();
}
auto fetch_backup_grid_box = forward_collector->GetForwardGrid();
auto fetch_pres_backup = fetch_backup_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (fetch_pres[index] != fetch_pres_backup[index]) {
misses += 1;
}
}
}
}
REQUIRE(misses > 0);
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete dependent_components_map;
delete memory_handler;
delete forward_collector;
}
void TEST_CASE_FORWARD_COLLECTOR_TWO_INC_COMPRESSION_NO_PARALLEL(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
float nt = 300;
apGridBox->SetNT(nt);
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
auto memory_handler = new WaveFieldsMemoryHandler(apConfigurationMap);
memory_handler->SetComputationParameters(apParameters);
auto dependent_components_map = new ComponentsMap<DependentComponent>();
dependent_components_map->Set(MEMORY_HANDLER, memory_handler);
auto configuration_map = new JSONConfigurationMap(R"(
{
"properties": {
"zfp-tolerance": 0.9,
"zfp-relative": true,
"write-path": "test",
"zfp-parallel": 1,
"compression-type": "zfp",
"compression": true
}
}
)"_json);
auto forward_collector = new TwoPropagation(configuration_map);
forward_collector->SetComputationParameters(apParameters);
forward_collector->SetDependentComponents(dependent_components_map);
forward_collector->SetGridBox(apGridBox);
forward_collector->AcquireConfiguration();
/*
* Test for rest grid case true , means the wva fields should be zero
*/
Device::MemSet(pressure_curr->GetNativePointer(), 1.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 1.0f, window_size * sizeof(float));
forward_collector->ResetGrid(true);
auto grid_box = forward_collector->GetForwardGrid();
auto curr_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
auto prev_pressure = apGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetHostPointer();
int misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (curr_pressure[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses == 0);
misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (prev_pressure[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses == 0);
forward_collector->ResetGrid(false);
auto init_grid_box = forward_collector->GetForwardGrid();
REQUIRE(init_grid_box->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize() == nx);
REQUIRE(init_grid_box->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize() == ny);
REQUIRE(init_grid_box->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize() == nz);
REQUIRE(init_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer() != nullptr);
REQUIRE(init_grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer() != nullptr);
REQUIRE(init_grid_box->Get(PARM | GB_VEL)->GetNativePointer() != nullptr);
auto pres_curr = grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto pres_prev = grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
auto pres_next = grid_box->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
auto swap_grid_box = forward_collector->GetForwardGrid();
auto swap_pres_curr = swap_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto swap_pres_prev = swap_grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
auto swap_pres_next = swap_grid_box->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
REQUIRE(swap_pres_prev == pres_next);
auto fetch_grid_box = forward_collector->GetForwardGrid();
auto h_pressure = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int location = (wnx / 2) + (wnz / 2) * wnx + (wny / 2) * wnx * wnz;
h_pressure[location] = 1;
auto d_pressure = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
Device::MemCpy(d_pressure, h_pressure, window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
for (int it = 0; it < int(nt); it++) {
forward_collector->SaveForward();
}
float fetch_pres[window_size];
Device::MemCpy(fetch_pres, d_pressure, window_size * sizeof(float), Device::COPY_DEVICE_TO_HOST);
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (fetch_pres[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses > 0);
for (int it = int(nt); it > 0; it--) {
forward_collector->FetchForward();
}
auto fetch_backup_grid_box = forward_collector->GetForwardGrid();
auto fetch_pres_backup = fetch_backup_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (fetch_pres[index] != fetch_pres_backup[index]) {
misses += 1;
}
}
}
}
REQUIRE(misses > 0);
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete dependent_components_map;
delete memory_handler;
delete forward_collector;
}
TEST_CASE("Two Forward Collector - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_FORWARD_COLLECTOR_TWO(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("Two Forward Collector - 2D - Window", "[Window],[2D]") {
TEST_CASE_FORWARD_COLLECTOR_TWO(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("Two Forward Collector Injection no tolerance - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_FORWARD_COLLECTOR_TWO_INC_COMPRESSION_NO_TOLERANCE(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("TwoForward Collector Injection no tolerance - 2D - Window", "[Window],[2D]") {
TEST_CASE_FORWARD_COLLECTOR_TWO_INC_COMPRESSION_NO_TOLERANCE(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("Two Forward Collector Injection no relative - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_FORWARD_COLLECTOR_TWO_INC_COMPRESSION_NO_RELATIVE(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("TwoForward Collector Injection no relative - 2D - Window", "[Window],[2D]") {
TEST_CASE_FORWARD_COLLECTOR_TWO_INC_COMPRESSION_NO_RELATIVE(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("Two Forward Collector Injection no parallel - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_FORWARD_COLLECTOR_TWO_INC_COMPRESSION_NO_PARALLEL(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("TwoForward Collector Injection no parallel - 2D - Window", "[Window],[2D]") {
TEST_CASE_FORWARD_COLLECTOR_TWO_INC_COMPRESSION_NO_PARALLEL(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
| 36,334
|
C++
|
.cpp
| 758
| 39.094987
| 111
| 0.604444
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,080
|
TestReversePropagation.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/components/independents/forward-collectors/TestReversePropagation.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <prerequisites/libraries/catch/catch.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <operations/components/independents/concrete/forward-collectors/ReversePropagation.hpp>
#include <operations/common/DataTypes.h>
#include <operations/components/dependency/concrete/HasDependents.hpp>
#include <operations/components/independents/concrete/computation-kernels/isotropic/SecondOrderComputationKernel.hpp>
#include <operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp>
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
#include <operations/test-utils/NumberHelpers.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::testutils;
using namespace operations::helpers;
/**
* @note
* 1. FetchForward();
* 1.0 apply computation step case no injection
*
* 2. SaveForward():
* 1.0 do nothing if there is no injection enabled
* - check that it internal time step is not increased (this->mTimeStep)
* i.e. can't do this, it is internal
*
* 3. void ResetGrid(bool is_forward_run);
* 2 cases:
* 2.0 reset wave field with zeros
* 2.1 forward : nothing more than resetting and then injection if enabled
* 2.2 backward : it swaps pointers , if no wave fields it allocates .
* 4. dataunits::GridBox *GetForwardGrid();
* 1 case:
* 1.0 check getting internal forward grid : means dims and current pressure
*/
void TEST_CASE_FORWARD_COLLECTOR_REVERSE_NO_INJECTION(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
auto aMemoryHandler = new WaveFieldsMemoryHandler(apConfigurationMap);
float nt = 5;
apGridBox->SetNT(nt);
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
aMemoryHandler->SetComputationParameters(apParameters);
auto computation_kernel = new SecondOrderComputationKernel(apConfigurationMap);
computation_kernel->SetGridBox(apGridBox);
computation_kernel->SetComputationParameters(apParameters);
auto dependent_components_map = new ComponentsMap<DependentComponent>();
dependent_components_map->Set(MEMORY_HANDLER, aMemoryHandler);
auto components_map = new ComponentsMap<Component>();
components_map->Set(COMPUTATION_KERNEL, computation_kernel);
auto forward_collector = new ReversePropagation(apConfigurationMap);
forward_collector->SetComputationParameters(apParameters);
forward_collector->SetDependentComponents(dependent_components_map);
forward_collector->SetComponentsMap(components_map);
forward_collector->SetGridBox(apGridBox);
forward_collector->AcquireConfiguration();
/*
* Test for rest grid case true , means the wva fields should be zero
*/
Device::MemSet(pressure_curr->GetNativePointer(), 1.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 1.0f, window_size * sizeof(float));
forward_collector->ResetGrid(true);
auto curr_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
auto prev_pressure = apGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetHostPointer();
int misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (curr_pressure[index] != 0) misses += 1;
}
}
}
REQUIRE(misses == 0);
misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (prev_pressure[index] != 0) misses += 1;
}
}
}
REQUIRE(misses == 0);
/*
* Test for get forward grid in false option
* and case of reset grid false , it return the internal grd
*/
forward_collector->ResetGrid(false);
auto grid_box = forward_collector->GetForwardGrid();
/*
REQUIRE(grid_box->GetActualGridSize(X_AXIS) == nx);
REQUIRE(grid_box->GetActualGridSize(Y_AXIS) == ny);
REQUIRE(grid_box->GetActualGridSize(Z_AXIS) == nz);*/
REQUIRE(grid_box->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize() == nx);
REQUIRE(grid_box->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize() == ny);
REQUIRE(grid_box->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize() == nz);
REQUIRE(grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer() != nullptr);
REQUIRE(grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer() != nullptr);
REQUIRE(grid_box->Get(PARM | GB_VEL)->GetNativePointer() != nullptr);
auto pres_curr = grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto pres_prev = grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
/*
* Check for swapping pointers after applying reset grid with false option
*/
forward_collector->ResetGrid(false);
auto swap_grid_box = forward_collector->GetForwardGrid();
auto swap_pres_curr = swap_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto swap_pres_prev = swap_grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
REQUIRE(swap_pres_curr == pres_prev);
REQUIRE(swap_pres_prev == pres_curr);
/*
* Testing fetch forward.
* A step function is applied
*/
auto fetch_grid_box = forward_collector->GetForwardGrid();
auto h_pressure = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int location = (wnx / 2) + (wnz / 2) * wnx + (wny / 2) * wnx * wnz;
h_pressure[location] = 1;
auto d_pressure = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
Device::MemCpy(d_pressure, h_pressure, window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
for (int it = 0; it < int(nt); it++) {
forward_collector->FetchForward();
}
auto fetch_pres = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (fetch_pres[index] != 0) misses += 1;
}
}
}
REQUIRE(misses > 0);
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete components_map;
delete dependent_components_map;
delete computation_kernel;
delete forward_collector;
}
void TEST_CASE_FORWARD_COLLECTOR_REVERSE_INC_INJECTION(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
auto configuration_map = new JSONConfigurationMap(R"(
{
"wave": {
"physics": "acoustic",
"approximation": "isotropic",
"equation-order": "second",
"grid-sampling": "uniform"
},
"type": "none",
"properties": {
"boundary-saving": true
}
}
)"_json);
auto memory_handler = new WaveFieldsMemoryHandler(configuration_map);
float nt = 5;
apGridBox->SetNT(nt);
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
uint half_length = apParameters->GetHalfLength();
uint bound_length = apParameters->GetBoundaryLength();
uint offset = half_length + bound_length;
uint start_y = 0;
uint end_y = 1;
uint start_z = offset;
uint end_z = wnz - offset;
uint start_x = offset;
uint end_x = wnx - offset;
if (ny > 1) {
start_y = offset;
end_y = wny - offset;
}
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
memory_handler->SetComputationParameters(apParameters);
auto computation_kernel = new SecondOrderComputationKernel(configuration_map);
computation_kernel->SetGridBox(apGridBox);
computation_kernel->SetComputationParameters(apParameters);
auto dependent_components_map = new ComponentsMap<DependentComponent>();
dependent_components_map->Set(MEMORY_HANDLER, memory_handler);
auto components_map = new ComponentsMap<Component>();
components_map->Set(COMPUTATION_KERNEL, computation_kernel);
auto forward_collector = new ReversePropagation(configuration_map);
forward_collector->SetComputationParameters(apParameters);
forward_collector->SetDependentComponents(dependent_components_map);
forward_collector->SetComponentsMap(components_map);
forward_collector->SetGridBox(apGridBox);
forward_collector->AcquireConfiguration();
/*
* Test for rest grid case true , means the wva fields should be zero
*/
Device::MemSet(pressure_curr->GetNativePointer(), 1.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 1.0f, window_size * sizeof(float));
forward_collector->ResetGrid(true);
auto curr_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
auto prev_pressure = apGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetHostPointer();
int misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (curr_pressure[index] != 0) misses += 1;
}
}
}
REQUIRE(misses == 0);
misses = 0;
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (prev_pressure[index] != 0) misses += 1;
}
}
}
REQUIRE(misses == 0);
/*
* Test for get forward grid in false option
* and case of reset grid false , it return the internal grd
*/
forward_collector->ResetGrid(false);
auto grid_box = forward_collector->GetForwardGrid();
REQUIRE(grid_box->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize() == nx);
REQUIRE(grid_box->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize() == ny);
REQUIRE(grid_box->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize() == nz);
REQUIRE(grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer() != nullptr);
REQUIRE(grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer() != nullptr);
REQUIRE(grid_box->Get(PARM | GB_VEL)->GetNativePointer() != nullptr);
auto pres_curr = grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto pres_prev = grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
/*
* Check for swapping pointers after applying reset grid with false option
*/
forward_collector->ResetGrid(false);
auto swap_grid_box = forward_collector->GetForwardGrid();
auto swap_pres_curr = swap_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto swap_pres_prev = swap_grid_box->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
REQUIRE(swap_pres_curr == pres_prev);
REQUIRE(swap_pres_prev == pres_curr);
/*
*testing fetch forward , means that a tep function is applied
*/
auto fetch_grid_box = forward_collector->GetForwardGrid();
auto h_pressure = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int location = (wnx / 2) + (wnz / 2) * wnx + (wny / 2) * wnx * wnz;
h_pressure[location] = 1;
auto d_pressure = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
Device::MemCpy(d_pressure, h_pressure, window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
for (int it = 0; it < int(nt); it++) {
forward_collector->SaveForward();
forward_collector->FetchForward();
}
/*
* Test save boundary and restore boundary
*/
auto fetch_pres = fetch_grid_box->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
for (int iy = 0; iy < wny; iy++) {
for (int iz = 0; iz < wnz; iz++) {
for (int ix = 0; ix < wnx; ix++) {
int index = iy * wnx * wnz + iz * wnx + ix;
if (fetch_pres[index] != 0) {
misses += 1;
}
}
}
}
REQUIRE(misses > 0);
forward_collector->ResetGrid(false);
auto backup_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
uint index = 0;
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = start_z; iz < end_z; iz++) {
for (int ix = 0; ix < half_length; ix++) {
backup_pressure[iy * wnz * wnx + iz * wnx + bound_length + ix] = 0.25;
index++;
backup_pressure[iy * wnz * wnx + iz * wnx + (wnx - bound_length - 1) - ix] = 0.25;
index++;
}
}
}
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = 0; iz < half_length; iz++) {
for (int ix = start_x; ix < end_x; ix++) {
backup_pressure[iy * wnz * wnx + (bound_length + iz) * wnx + ix] = 0.25;
index++;
backup_pressure[iy * wnz * wnx + (wnz - bound_length - 1 - iz) * wnx + ix] = 0.25;
index++;
}
}
}
if (ny > 1) {
for (int iy = 0; iy < half_length; iy++) {
for (int iz = start_z; iz < end_z; iz++) {
for (int ix = start_x; ix < end_x; ix++) {
backup_pressure[(bound_length + iy) * wnz * wnx + iz * wnx + ix] = 0.25;
index++;
backup_pressure[(wny - bound_length - 1 - iy) * wnz * wnx + iz * wnx + ix] = 0.25;
index++;
}
}
}
}
Device::MemCpy(apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer(), backup_pressure,
window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
forward_collector->SaveForward();
forward_collector->FetchForward();
auto fetch_backup_grid = forward_collector->GetForwardGrid();
auto fetch_backup_pres = fetch_backup_grid->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
misses = 0;
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = start_z; iz < end_z; iz++) {
for (int ix = 0; ix < half_length; ix++) {
if (fetch_backup_pres[iy * wnz * wnx + iz * wnx + bound_length + ix] != 0.25) {
misses += 1;
}
if (fetch_backup_pres[iy * wnz * wnx + iz * wnx + (wnx - bound_length - 1) - ix] != 0.25) {
misses += 1;
}
}
}
}
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = 0; iz < half_length; iz++) {
for (int ix = start_x; ix < end_x; ix++) {
if (fetch_backup_pres[iy * wnz * wnx + (bound_length + iz) * wnx + ix] != 0.25) {
misses += 1;
}
if (fetch_backup_pres[iy * wnz * wnx + (wnz - bound_length - 1 - iz) * wnx + ix] != 0.25) {
misses += 1;
}
}
}
}
if (ny > 1) {
for (int iy = 0; iy < half_length; iy++) {
for (int iz = start_z; iz < end_z; iz++) {
for (int ix = start_x; ix < end_x; ix++) {
if (fetch_backup_pres[(bound_length + iy) * wnz * wnx + iz * wnx + ix] != 0.25) {
misses += 1;
}
if (fetch_backup_pres[(wny - bound_length - 1 - iy) * wnz * wnx + iz * wnx + ix] != 0.250) {
misses += 1;
}
}
}
}
}
REQUIRE (misses == 0);
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete components_map;
delete dependent_components_map;
delete computation_kernel;
delete forward_collector;
}
TEST_CASE("Reverse Forward Collector - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_FORWARD_COLLECTOR_REVERSE_NO_INJECTION(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("Reverse Forward Collector - 2D - Window", "[Window],[2D]") {
TEST_CASE_FORWARD_COLLECTOR_REVERSE_NO_INJECTION(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("Reverse Forward Collector Injection - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_FORWARD_COLLECTOR_REVERSE_INC_INJECTION(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("Reverse Forward Collector Injection - 2D - Window", "[Window],[2D]") {
TEST_CASE_FORWARD_COLLECTOR_REVERSE_INC_INJECTION(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
| 23,038
|
C++
|
.cpp
| 491
| 38.725051
| 117
| 0.610873
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,081
|
TestSeismicTraceManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/components/independents/trace-managers/TestSeismicTraceManager.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <prerequisites/libraries/catch/catch.hpp>
#include <operations/components/independents/concrete/trace-managers/SeismicTraceManager.hpp>
#include <operations/common/DataTypes.h>
#include <operations/utils/io/write_utils.h>
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyTraceGenerator.hpp>
#include <operations/test-utils/NumberHelpers.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::testutils;
using namespace operations::utils::io;
#define TRACE_STRIDE_X 3
#define TRACE_STRIDE_Y 4
#define TRACE_STRIDE_Z 0
void TEST_CASE_TRACE_MANAGER(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
auto uut = new SeismicTraceManager(apConfigurationMap);
uut->SetComputationParameters(apParameters);
uut->SetGridBox(apGridBox);
uut->AcquireConfiguration();
/*
* Generates a dummy *.segy file
*/
std::stringstream ss;
ss << OPERATIONS_TEST_DATA_PATH << "/dummy_trace_" << wnx << "_" << wnz << "_" << wny << std::endl;
std::string file_name = ss.str();
auto ground_truth = generate_dummy_trace(file_name, apGridBox,
TRACE_STRIDE_X,
TRACE_STRIDE_Y);
file_name += ".segy";
std::vector<std::string> files;
files.push_back(file_name);
auto shots = uut->GetWorkingShots(files, 0, wnx * wny, "CSR");
int theoretical_shot_count = (wnx / TRACE_STRIDE_X);
if (wny > 1) {
theoretical_shot_count *= (wny / TRACE_STRIDE_Y);
}
int shot_count = shots.size();
REQUIRE(shot_count != 0);
REQUIRE(shot_count == theoretical_shot_count);
int shot_id = 0;
uut->ReadShot(files, shots[shot_id], "CSR");
uut->PreprocessShot();
REQUIRE(uut->GetTracesHolder()->Traces != nullptr);
REQUIRE(uut->GetTracesHolder()->PositionsX != nullptr);
REQUIRE(uut->GetTracesHolder()->PositionsY != nullptr);
auto source_point = uut->GetSourcePoint();
int start_idx = apParameters->GetBoundaryLength() + apParameters->GetHalfLength();
REQUIRE(source_point->x == start_idx);
REQUIRE(source_point->z == start_idx);
REQUIRE(source_point->y == start_idx * (apGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize() != 1));
REQUIRE(uut->GetTracesHolder()->PositionsX[0] == start_idx);
REQUIRE(uut->GetTracesHolder()->PositionsY[0] ==
start_idx * (apGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize() != 1));
REQUIRE(uut->GetTracesHolder()->SampleNT == wnz);
REQUIRE(uut->GetTracesHolder()->TraceSizePerTimeStep == 1);
REQUIRE(uut->GetTracesHolder()->ReceiversCountX == 1);
REQUIRE(uut->GetTracesHolder()->ReceiversCountY == 1);
int stride_x = wnx / TRACE_STRIDE_X;
auto traces = uut->GetTracesHolder()->Traces->GetHostPointer();
for (int i = 0; i < wnz; i++) {
auto diff = ground_truth[i * stride_x + shot_id] - traces[i];
REQUIRE(diff == Approx(diff).margin(std::numeric_limits<float>::epsilon()));
}
uint pos = (apParameters->GetBoundaryLength() + apParameters->GetHalfLength()) *
wnx + uut->GetTracesHolder()->PositionsX[0] +
uut->GetTracesHolder()->PositionsY[0] * wnx * wnz;
uut->ApplyTraces(apGridBox->GetNT() - 1);
traces = uut->GetTracesHolder()->Traces->GetHostPointer();
float test_value = traces[wnz - 1] * 1500 * 1500 * dt * dt;
REQUIRE(approximately_equal(pressure_curr->GetHostPointer()[pos], test_value, 0.01));
uut->ApplyTraces(1);
traces = uut->GetTracesHolder()->Traces->GetHostPointer();
test_value += traces[0] * 1500 * 1500 * dt * dt;
REQUIRE(approximately_equal(pressure_curr->GetHostPointer()[pos], test_value, 0.01));
uut->ApplyTraces(apGridBox->GetNT() / 2);
traces = uut->GetTracesHolder()->Traces->GetHostPointer();
test_value += traces[wnz / 2] * 1500 * 1500 * dt * dt;
REQUIRE(approximately_equal(pressure_curr->GetHostPointer()[pos], test_value, 0.01));
remove(file_name.c_str());
delete ground_truth;
delete pressure_curr;
delete pressure_prev;
delete velocity;
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete uut;
}
TEST_CASE("SeismicTraceManager - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_TRACE_MANAGER(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("SeismicTraceManager - 2D - Window", "[Window],[2D]") {
TEST_CASE_TRACE_MANAGER(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
| 8,240
|
C++
|
.cpp
| 171
| 42.099415
| 118
| 0.675682
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,082
|
TestRickerSourceInjector.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/components/independents/source-injectors/TestRickerSourceInjector.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <prerequisites/libraries/catch/catch.hpp>
#include <operations/components/independents/concrete/source-injectors/RickerSourceInjector.hpp>
#include <operations/common/DataTypes.h>
#include <operations/data-units/concrete/holders/FrameBuffer.hpp>
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
#include <operations/test-utils/NumberHelpers.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::testutils;
void TEST_CASE_RICKER_SOURCE_INJECTOR_TI(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr_horizontal = new FrameBuffer<float>();
auto pressure_prev_horizontal = new FrameBuffer<float>();
auto pressure_curr_vertical = new FrameBuffer<float>();
auto pressure_prev_vertical = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr_horizontal->Allocate(window_size);
pressure_prev_horizontal->Allocate(window_size);
pressure_curr_vertical->Allocate(window_size);
pressure_prev_vertical->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr_vertical);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev_vertical);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev_vertical);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_X, pressure_curr_horizontal);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_X, pressure_prev_horizontal);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_X, pressure_prev_horizontal);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr_horizontal->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev_horizontal->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_curr_vertical->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev_vertical->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
auto ricker_source_injector = new RickerSourceInjector(apConfigurationMap);
auto source_point = new Point3D(0, 0, 0);
uint location = 0;
ricker_source_injector->SetGridBox(apGridBox);
ricker_source_injector->SetComputationParameters(apParameters);
ricker_source_injector->SetSourcePoint(source_point);
SECTION("GetCutOffTimeStep") {
uint cut_off_frequency = (1.0 / apParameters->GetSourceFrequency()) / apGridBox->GetDT();
REQUIRE(ricker_source_injector->GetCutOffTimeStep() == Approx(cut_off_frequency));
}
SECTION("ApplySource") {
// Calculated by hand with time step=1 & dt=1 & source frequency=20
float ricker = 1;
ricker = ricker * velocity->GetHostPointer()[location];
float ground_truth_horizontal =
pressure_curr_horizontal->GetHostPointer()[location] + ricker;
float ground_truth_vertical =
pressure_curr_vertical->GetHostPointer()[location] + ricker;
uint time_step = 0;
ricker_source_injector->ApplySource(time_step);
float pressure_after_ricker_horizontal = apGridBox->Get(
WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer()[location];
float pressure_after_ricker_vertical = apGridBox->Get(
WAVE | GB_PRSS | CURR | DIR_X)->GetHostPointer()[location];
REQUIRE(ground_truth_horizontal == Approx(pressure_after_ricker_horizontal));
REQUIRE(ground_truth_vertical == Approx(pressure_after_ricker_vertical));
}
}
void TEST_CASE_RICKER_SOURCE_INJECTOR_ISO(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
auto ricker_source_injector = new RickerSourceInjector(apConfigurationMap);
auto source_point = new Point3D(0, 0, 0);
uint location = 0;
ricker_source_injector->SetGridBox(apGridBox);
ricker_source_injector->SetComputationParameters(apParameters);
ricker_source_injector->SetSourcePoint(source_point);
SECTION("GetCutOffTimeStep") {
uint cut_off_frequency = (1.0 / apParameters->GetSourceFrequency()) / apGridBox->GetDT();
REQUIRE(ricker_source_injector->GetCutOffTimeStep() == Approx(cut_off_frequency));
}
SECTION("ApplySource") {
// Calculated by hand with time step=1 & dt=1 & source frequency=20
float ricker = 1;
ricker = ricker * velocity->GetHostPointer()[location];
float ground_truth = pressure_curr->GetHostPointer()[location] + ricker;
uint time_step = 0;
ricker_source_injector->ApplySource(time_step);
float pressure_after_ricker =
apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer()[location];
REQUIRE(ground_truth == Approx(pressure_after_ricker));
}
}
void TEST_CASE_RICKER_SOURCE_INJECTOR(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
if (apParameters->GetApproximation() == ISOTROPIC) {
TEST_CASE_RICKER_SOURCE_INJECTOR_ISO(apGridBox, apParameters, apConfigurationMap);
}
}
/*
* Isotropic Test Cases
*/
TEST_CASE("RickerSourceInjector - 2D - No Window - ISO", "[No Window],[2D],[ISO]") {
TEST_CASE_RICKER_SOURCE_INJECTOR(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("RickerSourceInjector - 2D - Window - ISO", "[Window],[2D],[ISO]") {
TEST_CASE_RICKER_SOURCE_INJECTOR(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
| 10,648
|
C++
|
.cpp
| 206
| 44.475728
| 110
| 0.676258
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,083
|
TestSeismicModelHandler.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/components/independents/model-handlers/TestSeismicModelHandler.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <map>
#include <string>
#include <prerequisites/libraries/catch/catch.hpp>
#include <bs/base/logger/concrete/LoggerSystem.hpp>
#include <operations/components/independents/concrete/model-handlers/SeismicModelHandler.hpp>
#include <operations/common/DataTypes.h>
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyModelGenerator.hpp>
#include <operations/test-utils/NumberHelpers.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
#include <operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp>
#include <operations/components/dependency/concrete/HasDependents.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace bs::base::logger;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::testutils;
using namespace operations::helpers;
void TEST_CASE_SEISMIC_MODEL_HANDLER_CORE(GridBox *apGridBox,
ComputationParameters *apParameters) {
SECTION("LogicalGridSize") {
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize() == 23);
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize() == 23);
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetZAxis().GetLogicalAxisSize() == 23);
}
SECTION("CellDimensions") {
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension() == Approx(10));
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension() == Approx(10));
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension() == Approx(10));
}
SECTION("ReferencePoint") {
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetXAxis().GetReferencePoint() == 0);
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetYAxis().GetReferencePoint() == 0);
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetZAxis().GetReferencePoint() == 0);
}
SECTION("WindowStart") {
REQUIRE(apGridBox->GetWindowStart(X_AXIS) == 0);
REQUIRE(apGridBox->GetWindowStart(Y_AXIS) == 0);
REQUIRE(apGridBox->GetWindowStart(Z_AXIS) == 0);
}
SECTION("LogicalWindowSize") {
REQUIRE(apGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() == 23);
REQUIRE(apGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() == 23);
REQUIRE(apGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() == 23);
}
SECTION("ActualGridSize") {
#if defined(USING_DPCPP)
if (apParameters->IsUsingWindow()) {
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize() == 23);
} else {
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize() == 32);
}
#else
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize() == 23);
#endif
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize() == 23);
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize() == 23);
}
SECTION("ActualWindowSize") {
#if defined(USING_DPCPP)
REQUIRE(apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize() == 32);
#else
REQUIRE(apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize() == 23);
#endif
REQUIRE(apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize() == 23);
REQUIRE(apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize() == 23);
}
SECTION("ComputationGridSize") {
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetXAxis().GetComputationAxisSize() == 15);
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetYAxis().GetComputationAxisSize() == 15);
REQUIRE(apGridBox->GetAfterSamplingAxis()->GetZAxis().GetComputationAxisSize() == 15);
}
}
void TEST_CASE_SEISMIC_MODEL_HANDLER_APPROXIMATION(GridBox *apGridBox,
ComputationParameters *apParameters) {
SECTION("Wave Allocation") {
REQUIRE(apGridBox->Get(WAVE | GB_PRSS | CURR)->GetNativePointer() != nullptr);
REQUIRE(apGridBox->Get(WAVE | GB_PRSS | PREV)->GetNativePointer() != nullptr);
REQUIRE(apGridBox->Get(WAVE | GB_PRSS | NEXT)->GetNativePointer() != nullptr);
}
if (apParameters->GetApproximation() == ISOTROPIC) {
SECTION("Parameters Allocation") {
REQUIRE(apGridBox->Get(PARM | GB_VEL)->GetNativePointer() != nullptr);
REQUIRE(apGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer() != nullptr);
}
}
}
void TEST_CASE_SEISMIC_MODEL_HANDLER(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
auto model_handler = new SeismicModelHandler(apConfigurationMap);
model_handler->SetComputationParameters(apParameters);
auto memory_handler = new WaveFieldsMemoryHandler(apConfigurationMap);
memory_handler->SetComputationParameters(apParameters);
auto dependant_components_map = new ComponentsMap<DependentComponent>();
dependant_components_map->Set(MEMORY_HANDLER, memory_handler);
model_handler->SetDependentComponents(dependant_components_map);
/*
* Generates a dummy *.segy file
*/
// generate_dummy_model("dummy_model");
//
// map<std::string, std::string> file_names;
// file_names["velocity"] = OPERATIONS_TEST_DATA_PATH "/dummy_model.segy";
//
// auto grid_box = model_handler->ReadModel(file_names);
//
// remove(OPERATIONS_TEST_DATA_PATH "/dummy_model.segy");
LoggerSystem *Logger = LoggerSystem::GetInstance();
Logger->Info() << "Deprecated. Model Handler is not tested" << '\n';
// TEST_CASE_SEISMIC_MODEL_HANDLER_CORE(grid_box, apParameters);
// TEST_CASE_SEISMIC_MODEL_HANDLER_APPROXIMATION(grid_box, apParameters);
// delete grid_box;
delete model_handler;
delete memory_handler;
delete dependant_components_map;
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
}
/*
* Isotropic Test Cases
*/
TEST_CASE("SeismicModelHandler - 2D - No Window - ISO", "[No Window],[2D],[ISO]") {
TEST_CASE_SEISMIC_MODEL_HANDLER(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("SeismicModelHandler - 2D - Window - ISO", "[Window],[2D],[ISO]") {
TEST_CASE_SEISMIC_MODEL_HANDLER(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
| 7,905
|
C++
|
.cpp
| 161
| 43.21118
| 96
| 0.709225
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,084
|
TestSecondOrderComputationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/components/independents/computation-kernels/iso/TestSecondOrderComputationKernel.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <limits>
#include <prerequisites/libraries/catch/catch.hpp>
#include <bs/base/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/computation-kernels/isotropic/SecondOrderComputationKernel.hpp>
#include <operations/common/DataTypes.h>
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
#include <operations/test-utils/NumberHelpers.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace bs::base::memory;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::testutils;
void TEST_CASE_SECOND_ORDER_COMPUTATION_KERNEL(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
int start_y, end_y;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
/*
* SecondOrderComputationKernel setting.
*/
auto computation_kernel = new SecondOrderComputationKernel(apConfigurationMap);
computation_kernel->SetGridBox(apGridBox);
computation_kernel->SetComputationParameters(apParameters);
computation_kernel->SetMode(operations::components::KERNEL_MODE::FORWARD);
/*
* Source injection.
*/
auto h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int location = (wnx / 2) + (wnz / 2) * wnx + (wny / 2) * wnx * wnz;
h_pressure[location] = 1;
/*
* Technology settings for memory transfer.
*/
auto d_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
Device::MemCpy(d_pressure, h_pressure, window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
computation_kernel->Step();
h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
/*
* Variables initialization for kernel usage.
*/
int misses = 0;
int half_length = apParameters->GetHalfLength();
start_y = (ny > 1) ? half_length : 0;
end_y = (ny > 2) ? wny - half_length : 1;
/*
* [CHECK]
* The vertical and horizontal lines around the location centered
* are not zeros, and symmetrical
*/
for (int i = 1; i <= half_length; i++) {
if (h_pressure[location + i] == 0 || h_pressure[location - i] == 0 ||
h_pressure[location + i * wnx] == 0 || h_pressure[location - i * wnx] == 0) {
misses += 1;
}
if (h_pressure[location + i] > 1.0 || h_pressure[location - i] > 1.0 ||
h_pressure[location + i * wnx] > 1 || h_pressure[location - i * wnx] > 1) {
misses += 1;
}
if (!approximately_equal(h_pressure[location + i], h_pressure[location - i])) {
misses += 1;
}
if (!approximately_equal(h_pressure[location + i * wnx], h_pressure[location - i * wnx])) {
misses += 1;
}
if (!approximately_equal(h_pressure[location + i], h_pressure[location - i * wnx])) {
misses += 1;
}
if (ny > 1) {
if (h_pressure[location + i * wnx * wnz] == 0 ||
h_pressure[location - i * wnx * wnz] == 0) {
misses += 1;
}
if (h_pressure[location + i * wnx * wnz] > 1 ||
h_pressure[location - i * wnx * wnz] > 1) {
misses += 1;
}
if (!approximately_equal(h_pressure[location + i * wnx * wnz],
h_pressure[location - i * wnx * wnz])) {
misses += 1;
}
}
}
REQUIRE(misses == 0);
for (int t = 0; t < 20; t++) {
computation_kernel->Step();
}
misses = 0;
h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int index;
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = half_length; iz < wnz - half_length; iz++) {
for (int ix = half_length; ix < wnx - half_length; ix++) {
index = iy * wnx * wnz + iz * wnx + ix;
if (h_pressure[index] == 0) {
misses += 1;
}
}
}
}
REQUIRE(misses == 0);
/*
* [CHECK]
* Norm checking.
*/
for (int t = 0; t < 1000; t++) {
computation_kernel->Step();
if (t % 100 == 0) {
h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
float norm = calculate_norm(h_pressure, wnx, wnz, wny);
REQUIRE(Approx(norm).epsilon(1) == 1);
}
}
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
}
TEST_CASE("Isotropic Second Order - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_SECOND_ORDER_COMPUTATION_KERNEL(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("Isotropic Second Order - 2D - Window", "[Window],[2D]") {
TEST_CASE_SECOND_ORDER_COMPUTATION_KERNEL(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
| 8,531
|
C++
|
.cpp
| 196
| 35.994898
| 117
| 0.618265
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,085
|
TestStaggeredComputationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/components/independents/computation-kernels/iso/TestStaggeredComputationKernel.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <limits>
#include <prerequisites/libraries/catch/catch.hpp>
#include <bs/base/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/computation-kernels/isotropic/StaggeredComputationKernel.hpp>
#include <operations/common/DataTypes.h>
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
#include <operations/test-utils/NumberHelpers.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace bs::base::memory;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::testutils;
void TEST_CASE_STAGGERED_COMPUTATION_KERNEL(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_next = new FrameBuffer<float>();
auto particle_vel_x = new FrameBuffer<float>();
auto particle_vel_z = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
auto density = new FrameBuffer<float>();
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
int start_y, end_y;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_next->Allocate(window_size);
particle_vel_x->Allocate(window_size);
particle_vel_z->Allocate(window_size);
velocity->Allocate(size);
density->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_next);
apGridBox->RegisterWaveField(WAVE | GB_PRTC | CURR | DIR_Z, particle_vel_z);
apGridBox->RegisterWaveField(WAVE | GB_PRTC | CURR | DIR_X, particle_vel_x);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
apGridBox->RegisterParameter(PARM | GB_DEN, density);
float temp_vel[size];
float temp_den[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
temp_den[iz * nx + ix + (iy * nx * nz)] = 1.0f;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_next->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(particle_vel_z->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(particle_vel_x->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(density->GetNativePointer(), temp_den, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
if (ny > 1) {
auto particle_vel_y = new FrameBuffer<float>();
particle_vel_y->Allocate(window_size);
apGridBox->RegisterWaveField(WAVE | GB_PRTC | CURR | DIR_Y, particle_vel_y);
Device::MemSet(particle_vel_y->GetNativePointer(), 0.0f, window_size * sizeof(float));
}
/*
* StaggeredComputationKernel setting.
*/
auto computation_kernel = new StaggeredComputationKernel(apConfigurationMap);
computation_kernel->SetGridBox(apGridBox);
computation_kernel->SetComputationParameters(apParameters);
computation_kernel->SetMode(operations::components::KERNEL_MODE::FORWARD);
/*
* Source injection.
*/
auto h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int location = (wnx / 2) + (wnz / 2) * wnx + (wny / 2) * wnx * wnz;
h_pressure[location] = 1;
/*
* Technology settings for memory transfer.
*/
auto d_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
Device::MemCpy(d_pressure, h_pressure, window_size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
computation_kernel->Step();
h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
/*
* Variables initialization for kernel usage.
*/
int misses = 0;
int half_length = apParameters->GetHalfLength();
start_y = (ny > 1) ? half_length : 0;
end_y = (ny > 2) ? wny - half_length : 1;
/*
* [CHECK]
* The vertical and horizontal lines around the location centered
* are not zeros, and symmetrical
*/
for (int i = 1; i <= half_length; i++) {
if (h_pressure[location + i] == 0 || h_pressure[location - i] == 0 ||
h_pressure[location + i * wnx] == 0 || h_pressure[location - i * wnx] == 0) {
misses += 1;
}
if (h_pressure[location + i] > 1.0 || h_pressure[location - i] > 1.0 ||
h_pressure[location + i * wnx] > 1 || h_pressure[location - i * wnx] > 1) {
misses += 1;
}
if (!approximately_equal(h_pressure[location + i], h_pressure[location - i])) {
misses += 1;
}
if (!approximately_equal(h_pressure[location + i * wnx], h_pressure[location - i * wnx])) {
misses += 1;
}
if (!approximately_equal(h_pressure[location + i], h_pressure[location - i * wnx])) {
misses += 1;
}
if (ny > 1) {
if (h_pressure[location + i * wnx * wnz] == 0 ||
h_pressure[location - i * wnx * wnz] == 0) {
misses += 1;
}
if (h_pressure[location + i * wnx * wnz] > 1 ||
h_pressure[location - i * wnx * wnz] > 1) {
misses += 1;
}
if (!approximately_equal(h_pressure[location + i * wnx * wnz],
h_pressure[location - i * wnx * wnz])) {
misses += 1;
}
}
}
REQUIRE(misses == 0);
for (int t = 0; t < 20; t++) {
computation_kernel->Step();
}
misses = 0;
h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int index;
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = half_length; iz < wnz - half_length; iz++) {
for (int ix = half_length; ix < wnx - half_length; ix++) {
index = iy * wnx * wnz + iz * wnx + ix;
if (h_pressure[index] == 0) {
misses += 1;
}
}
}
}
REQUIRE(misses == 0);
/*
* [CHECK]
* Norm checking.
*/
for (int t = 0; t < 1000; t++) {
computation_kernel->Step();
if (t % 100 == 0) {
h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
float norm = calculate_norm(h_pressure, wnx, wnz, wny);
REQUIRE(Approx(norm).epsilon(1) == 1);
}
}
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
}
/* Both DPC++ and OpenMP Offload does not support staggered yet,
* so if one them is on we skip this test of 3D. */
TEST_CASE("Staggered Order - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_STAGGERED_COMPUTATION_KERNEL(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("Staggered Order - 2D - Window", "[Window],[2D]") {
TEST_CASE_STAGGERED_COMPUTATION_KERNEL(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
| 9,703
|
C++
|
.cpp
| 217
| 37.373272
| 115
| 0.624324
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,086
|
TestSpongeBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/components/independents/boundary-managers/TestSpongeBoundaryManager.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <prerequisites/libraries/catch/catch.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <operations/components/independents/concrete/boundary-managers/SpongeBoundaryManager.hpp>
#include <operations/components/independents/concrete/computation-kernels/isotropic/SecondOrderComputationKernel.hpp>
#include <operations/common/DataTypes.h>
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
#include <operations/test-utils/NumberHelpers.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::testutils;
void TEST_CASE_SPONGE(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
set_environment();
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
auto h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int location = (wnx / 2) + (wnz / 2) * wnx + (wny / 2) * wnx * wnz;
h_pressure[location] = 1;
auto SpongeConfigurationMap = new JSONConfigurationMap(R"(
{
"wave": {
"physics": "acoustic",
"approximation": "isotropic",
"equation-order": "second",
"grid-sampling": "uniform"
},
"type": "sponge",
"properties": {
"use-top-layer": true,
"reflect-coeff": 0.03,
"shift-ratio": 0.2,
"relax-cp": 0.9
}
}
)"_json);
auto boundary_manager = new SpongeBoundaryManager(SpongeConfigurationMap);
auto computation_kernel = new SecondOrderComputationKernel(SpongeConfigurationMap);
boundary_manager->SetComputationParameters(apParameters);
computation_kernel->SetComputationParameters(apParameters);
boundary_manager->AcquireConfiguration();
computation_kernel->AcquireConfiguration();
boundary_manager->SetGridBox(apGridBox);
computation_kernel->SetGridBox(apGridBox);
computation_kernel->SetBoundaryManager(boundary_manager);
computation_kernel->SetMode(operations::components::KERNEL_MODE::FORWARD);
boundary_manager->ExtendModel();
float old_norm, new_norm;
old_norm = calculate_norm(pressure_curr->GetHostPointer(), wnx, wnz, wny);
computation_kernel->Step();
for (int i = 1; i <= 10000; i++) {
computation_kernel->Step();
if (i % 2000 == 0) {
new_norm = calculate_norm(pressure_curr->GetHostPointer(), wnx, wnz, wny);
REQUIRE((new_norm < old_norm || approximately_equal(new_norm, old_norm)));
old_norm = new_norm;
}
}
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete pressure_curr;
delete pressure_prev;
}
TEST_CASE("Sponge Boundary Manager - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_SPONGE(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("Sponge Boundary Manager - 2D - Window", "[Window],[2D]") {
TEST_CASE_SPONGE(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
| 6,476
|
C++
|
.cpp
| 132
| 40.992424
| 117
| 0.659696
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,087
|
TestNoneBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/components/independents/boundary-managers/TestNoneBoundaryManager.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unordered_set>
#include <prerequisites/libraries/catch/catch.hpp>
#include <operations/components/independents/concrete/boundary-managers/NoBoundaryManager.hpp>
#include <operations/components/independents/concrete/computation-kernels/isotropic/SecondOrderComputationKernel.hpp>
#include <operations/common/DataTypes.h>
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
#include <operations/test-utils/NumberHelpers.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::testutils;
void TEST_CASE_NONE(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
auto h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int location = (wnx / 2) + (wnz / 2) * wnx + (wny / 2) * wnx * wnz;
h_pressure[location] = 1;
auto RandomConfigurationMap = new JSONConfigurationMap(R"(
{
"wave": {
"physics": "acoustic",
"approximation": "isotropic",
"equation-order": "second",
"grid-sampling": "uniform"
},
"type": "random",
"properties": {
"use-top-layer": true,
"reflect-coeff": 0.03,
"shift-ratio": 0.2,
"relax-cp": 0.9
}
}
)"_json);
auto boundary_manager = new NoBoundaryManager(apConfigurationMap);
auto computation_kernel = new SecondOrderComputationKernel(apConfigurationMap);
boundary_manager->SetComputationParameters(apParameters);
computation_kernel->SetComputationParameters(apParameters);
boundary_manager->AcquireConfiguration();
computation_kernel->AcquireConfiguration();
boundary_manager->SetGridBox(apGridBox);
computation_kernel->SetGridBox(apGridBox);
computation_kernel->SetBoundaryManager(boundary_manager);
boundary_manager->ExtendModel();
int hl = apParameters->GetHalfLength();
int bl = apParameters->GetBoundaryLength();
float *v = velocity->GetHostPointer();
int start_x = hl;
int start_z = hl;
int start_y = 0;
int end_x = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize() - hl;
int end_z = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetLogicalAxisSize() - hl;
int end_y = 1;
if (ny > 1) {
start_y = hl;
end_y = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize() - hl;
}
unordered_set<float> isUnique, isUnique_r;
int nz_nx = nz * nx;
for (int depth = start_y; depth < end_y; depth++) {
for (int row = start_z; row < end_z; row++) {
for (int column = 0; column < bl; column++) {
int idx = depth * nz_nx + row * nx + column + start_x;
int idx_r = depth * nz_nx + row * nx + (end_x - 1 - column);
REQUIRE(v[idx] == 0);
REQUIRE(v[idx_r] == 0);
}
}
}
isUnique.clear();
isUnique_r.clear();
for (int depth = start_y; depth < end_y; depth++) {
for (int row = 0; row < bl; row++) {
for (int column = start_x; column < end_x; column++) {
int idx = depth * nz_nx + (start_z + row) * nx + column;
int idx_r = depth * nz_nx + (end_z - 1 - row) * nx + column;
REQUIRE(v[idx] == 0);
REQUIRE(v[idx_r] == 0);
}
}
}
if (ny > 1) {
isUnique.clear();
isUnique_r.clear();
for (int depth = 0; depth < bl; depth++) {
for (int row = start_z; row < end_z; row++) {
for (int column = start_x; column < end_x; column++) {
int idx = (depth + start_y) * nz_nx + row * nx + column;
int idx_r = (end_y - 1 - depth) * nz_nx + row * nx + column;
REQUIRE(v[idx] == 0);
REQUIRE(v[idx_r] == 0);
}
}
}
}
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete RandomConfigurationMap;
delete pressure_curr;
delete pressure_prev;
}
TEST_CASE("None Boundary Manager - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_NONE(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("None Boundary Manager - 2D - Window", "[Window],[2D]") {
TEST_CASE_NONE(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
| 8,215
|
C++
|
.cpp
| 182
| 36.532967
| 117
| 0.61577
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,088
|
TestRandomBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/components/independents/boundary-managers/TestRandomBoundaryManager.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unordered_set>
#include <vector>
#include <algorithm>
#include <prerequisites/libraries/catch/catch.hpp>
#include <operations/components/independents/concrete/boundary-managers/RandomBoundaryManager.hpp>
#include <operations/components/independents/concrete/computation-kernels/isotropic/SecondOrderComputationKernel.hpp>
#include <operations/common/DataTypes.h>
#include <operations/configurations/MapKeys.h>
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
#include <operations/test-utils/NumberHelpers.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::testutils;
void TEST_CASE_RANDOM(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = 1500;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
auto h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
int location = (wnx / 2) + (wnz / 2) * wnx + (wny / 2) * wnx * wnz;
h_pressure[location] = 1;
auto boundary_manager_map = new JSONConfigurationMap(R"(
{
"wave": {
"physics": "acoustic",
"approximation": "isotropic",
"equation-order": "second",
"grid-sampling": "uniform"
},
"type": "random",
"properties": {
"use-top-layer": false,
"reflect-coeff": 0.03,
"shift-ratio": 0.2,
"relax-cp": 0.9,
"grain-side-length": 20
}
}
)"_json);
auto computation_kernel_map = new JSONConfigurationMap(R"(
{
"wave": {
"physics": "acoustic",
"approximation": "isotropic",
"equation-order": "second",
"grid-sampling": "uniform"
}
}
)"_json);
/* Some parsing should be done for having the value of grain,
* check the test of get parameter. */
auto boundary_manager = new RandomBoundaryManager(boundary_manager_map);
auto computation_kernel = new SecondOrderComputationKernel(computation_kernel_map);
boundary_manager->SetComputationParameters(apParameters);
computation_kernel->SetComputationParameters(apParameters);
boundary_manager->AcquireConfiguration();
computation_kernel->AcquireConfiguration();
boundary_manager->SetGridBox(apGridBox);
computation_kernel->SetGridBox(apGridBox);
computation_kernel->SetBoundaryManager(boundary_manager);
boundary_manager->ExtendModel();
int hl = apParameters->GetHalfLength();
int bl = apParameters->GetBoundaryLength();
float *v = velocity->GetHostPointer();
int start_x = hl;
int start_y = hl;
int start_z = hl;
int end_x = apGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - hl;
int end_y = apGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - hl;
int end_z = apGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - hl;
float dx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
if (ny > 1) {
start_y = hl + bl;
end_y = ny - hl;
}
// Grain size in meters.
int grain_side_length = 0;
grain_side_length = boundary_manager_map->GetValue(OP_K_PROPRIETIES, OP_K_GRAIN_SIDE_LENGTH, grain_side_length);
int stride_x = grain_side_length / dx;
int stride_z = grain_side_length / dz;
int stride_y = grain_side_length / dy;
if (ny != 1) {
stride_y = grain_side_length / dy;
}
vector<float> seeds;
vector<float> seeds_l;
vector<float> seeds_r;
int id_x;
int id_z;
int horizontal_seeds = ((end_z - bl - start_z - bl) / stride_z + 1) * (bl / stride_x);
int vertical_seeds = (bl / stride_z + 1) * ((end_x - start_x) / stride_x);
int index = 0;
for (int row = 0; row < bl; row++) {
for (int column = start_x; column < end_x; column++) {
index = (end_z - row - 1) * nx + column;
if (find(seeds.begin(), seeds.end(), v[index]) == seeds.end()) {
seeds.emplace_back(v[index]);
}
}
}
REQUIRE(seeds.size() >= vertical_seeds);
seeds.clear();
int index_l = 0;
int index_r = 0;
for (int row = start_z + bl; row < end_z - bl; row++) {
for (int column = 0; column < bl; column++) {
index_l = row * nx + column;
index_r = row * nx + (end_x - 1 - column);
if (find(seeds_l.begin(), seeds_l.end(), v[index_l]) == seeds_l.end()) {
seeds_l.emplace_back(v[index_l]);
}
if (find(seeds_r.begin(), seeds_r.end(), v[index_r]) == seeds_r.end()) {
seeds_r.emplace_back(v[index_r]);
}
}
}
REQUIRE(seeds_l.size() >= horizontal_seeds);
REQUIRE(seeds_r.size() >= horizontal_seeds);
seeds.clear();
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete boundary_manager_map;
delete pressure_curr;
delete pressure_prev;
}
TEST_CASE("Random Boundary Manager - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_RANDOM(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("Random Boundary Manager - 2D - Window", "[Window],[2D]") {
TEST_CASE_RANDOM(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
| 9,269
|
C++
|
.cpp
| 207
| 36.705314
| 117
| 0.629255
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,089
|
TestCPMLBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/components/independents/boundary-managers/TestCPMLBoundaryManager.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <prerequisites/libraries/catch/catch.hpp>
#include <bs/base/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/boundary-managers/CPMLBoundaryManager.hpp>
#include <operations/components/independents/concrete/computation-kernels/isotropic/SecondOrderComputationKernel.hpp>
#include <operations/common/DataTypes.h>
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
#include <operations/test-utils/NumberHelpers.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::testutils;
void TEST_CASE_CPML(GridBox *apGridBox,
ComputationParameters *apParameters,
ConfigurationMap *apConfigurationMap) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
/*
* Register and allocate parameters and wave fields in
* grid box according to the current test case.
*/
auto pressure_curr = new FrameBuffer<float>();
auto pressure_prev = new FrameBuffer<float>();
auto velocity = new FrameBuffer<float>();
/*
* Variables initialization for grid box.
*/
int nx, ny, nz;
int wnx, wnz, wny;
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
wnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
wny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
wnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint size = nx * ny * nz;
pressure_curr->Allocate(window_size);
pressure_prev->Allocate(window_size);
velocity->Allocate(size);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | CURR | DIR_Z, pressure_curr);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | PREV | DIR_Z, pressure_prev);
apGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, pressure_prev);
apGridBox->RegisterParameter(PARM | GB_VEL, velocity);
float temp_vel[size];
float dt = apGridBox->GetDT();
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
temp_vel[iz * nx + ix + (iy * nx * nz)] = (float) rand() * 100 / RAND_MAX;
temp_vel[iz * nx + ix + (iy * nx * nz)] *=
temp_vel[iz * nx + ix + (iy * nx * nz)] * dt * dt;
}
}
}
Device::MemSet(pressure_curr->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemSet(pressure_prev->GetNativePointer(), 0.0f, window_size * sizeof(float));
Device::MemCpy(velocity->GetNativePointer(), temp_vel, size * sizeof(float), Device::COPY_HOST_TO_DEVICE);
auto h_pressure = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer();
auto location = (wnx / 2) + (wnz / 2) * wnx + (wny / 2) * wnx * wnz;
h_pressure[location] = 1;
auto configuration_map = new JSONConfigurationMap(R"(
{
"wave": {
"physics": "acoustic",
"approximation": "isotropic",
"equation-order": "second",
"grid-sampling": "uniform"
},
"type": "cpml",
"properties": {
"use-top-layer": true,
"reflect-coeff": 0.03,
"shift-ratio": 0.2,
"relax-cp": 0.9
}
}
)"_json);
auto boundary_manager = new CPMLBoundaryManager(configuration_map);
auto computation_kernel = new SecondOrderComputationKernel(apConfigurationMap);
boundary_manager->SetComputationParameters(apParameters);
computation_kernel->SetComputationParameters(apParameters);
boundary_manager->AcquireConfiguration();
computation_kernel->AcquireConfiguration();
boundary_manager->SetGridBox(apGridBox);
computation_kernel->SetGridBox(apGridBox);
computation_kernel->SetBoundaryManager(boundary_manager);
computation_kernel->SetMode(operations::components::KERNEL_MODE::FORWARD);
boundary_manager->ExtendModel();
float old_norm, new_norm;
old_norm = calculate_norm(pressure_curr->GetHostPointer(), wnx, wnz, wny);
computation_kernel->Step();
for (int i = 1; i <= 1000; i++) {
computation_kernel->Step();
if (i % 100 == 0) {
new_norm = calculate_norm(pressure_curr->GetHostPointer(), wnx, wnz, wny);
auto check1 = new_norm < old_norm;
auto check2 =
approximately_equal(new_norm, old_norm)
== Approx(0).margin(std::numeric_limits<float>::epsilon());
REQUIRE((check1 || check2));
old_norm = new_norm;
}
}
delete apGridBox;
delete apParameters;
delete apConfigurationMap;
delete pressure_curr;
delete pressure_prev;
delete velocity;
}
TEST_CASE("CPML Boundary Manager - 2D - No Window", "[No Window],[2D]") {
TEST_CASE_CPML(
generate_grid_box(OP_TU_2D, OP_TU_NO_WIND),
generate_computation_parameters(OP_TU_NO_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
TEST_CASE("CPML Boundary Manager - 2D - Window", "[Window],[2D]") {
TEST_CASE_CPML(
generate_grid_box(OP_TU_2D, OP_TU_INC_WIND),
generate_computation_parameters(OP_TU_INC_WIND, ISOTROPIC),
generate_average_case_configuration_map_wave());
}
| 6,912
|
C++
|
.cpp
| 148
| 38.641892
| 117
| 0.65003
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,090
|
TestFrameBuffer.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/data-units/holders/TestFrameBuffer.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <prerequisites/libraries/catch/catch.hpp>
#include <operations/data-units/concrete/holders/FrameBuffer.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace operations::dataunits;
using namespace operations::testutils;
TEST_CASE("FrameBuffer - Undefined Size", "[FrameBuffer]") {
set_environment();
auto fb_int = new FrameBuffer<int>();
auto fb_float = new FrameBuffer<float>();
SECTION("Negative Testing before Allocation") {
REQUIRE(fb_int->GetNativePointer() == nullptr);
REQUIRE(fb_float->GetNativePointer() == nullptr);
}
SECTION("Allocate Memory Function Test") {
fb_int->Allocate(10, "int buffer");
fb_float->Allocate(10, O_8, "float");
REQUIRE(fb_int->GetNativePointer() != nullptr);
REQUIRE(fb_float->GetNativePointer() != nullptr);
SECTION("Memory Set Function Test") {
char test_value = 2;
int eval;
eval = test_value << 24 | test_value << 16 | test_value << 8 | test_value;
Device::MemSet(fb_int->GetNativePointer(), 2, sizeof(int) * 10);
Device::MemSet(fb_float->GetNativePointer(), 0, sizeof(float) * 10);
int misses = 0;
for (int i = 0; i < 10; i++) {
misses += (eval != fb_int->GetHostPointer()[i]);
misses += (0 != fb_float->GetHostPointer()[i]);
}
REQUIRE(misses == 0);
}
SECTION("Memory Copy Function Test") {
int test_value_int[10];
float test_value_float[10];
for (int i = 0; i < 10; i++) {
test_value_int[i] = i;
test_value_float[i] = 12.5 / i;
}
Device::MemCpy(fb_int->GetNativePointer(), test_value_int, sizeof(int) * 10);
Device::MemCpy(fb_float->GetNativePointer(), test_value_float, sizeof(float) * 10);
int misses = 0;
for (int i = 0; i < 10; i++) {
misses += (test_value_int[i] != fb_int->GetHostPointer()[i]);
misses += (test_value_float[i] != fb_float->GetHostPointer()[i]);
}
REQUIRE(misses == 0);
}
SECTION("Reflect Function Test") {
fb_int->GetHostPointer()[5] = 30;
fb_float->GetHostPointer()[5] = 0.3f;
fb_int->ReflectOnNative();
fb_float->ReflectOnNative();
REQUIRE(fb_int->GetHostPointer()[5] == 30);
REQUIRE(fb_float->GetHostPointer()[5] == 0.3f);
}
SECTION("Deallocate Function Test") {
fb_int->Free();
fb_float->Free();
REQUIRE(fb_int->GetHostPointer() == nullptr);
REQUIRE(fb_float->GetNativePointer() == nullptr);
}
}
delete fb_int;
delete fb_float;
}
TEST_CASE("FrameBuffer - Defined Size", "[FrameBuffer]") {
auto fb_int = new FrameBuffer<int>(10);
auto fb_float = new FrameBuffer<float>(10);
SECTION("Allocate Memory Test") {
REQUIRE(fb_int->GetHostPointer() != nullptr);
REQUIRE(fb_float->GetNativePointer() != nullptr);
}
SECTION("Memory SetTest Function Test") {
char test_value = 2;
int eval;
eval = test_value << 24 | test_value << 16 | test_value << 8 | test_value;
Device::MemSet(fb_int->GetNativePointer(), test_value, sizeof(int) * 10);
Device::MemSet(fb_float->GetNativePointer(), 0, sizeof(float) * 10);
int misses = 0;
for (int i = 0; i < 10; i++) {
misses += (eval != fb_int->GetHostPointer()[i]);
misses += (0 != fb_float->GetHostPointer()[i]);
}
REQUIRE(misses == 0);
}
SECTION("Memory Copy Function Test") {
int test_value_int[10];
float test_value_float[10];
for (int i = 0; i < 10; i++) {
test_value_int[i] = i;
test_value_float[i] = 12.5 / i;
}
Device::MemCpy(fb_int->GetNativePointer(), test_value_int, sizeof(int) * 10);
Device::MemCpy(fb_float->GetNativePointer(), test_value_float, sizeof(int) * 10);
int misses = 0;
for (int i = 0; i < 10; i++) {
misses += (test_value_int[i] != fb_int->GetHostPointer()[i]);
misses += (test_value_float[i] != fb_float->GetHostPointer()[i]);
}
REQUIRE(misses == 0);
}
SECTION("Reflect Function Test") {
fb_int->GetHostPointer()[5] = 30;
fb_float->GetHostPointer()[5] = 0.3;
fb_int->ReflectOnNative();
fb_float->ReflectOnNative();
REQUIRE(fb_int->GetHostPointer()[5] == 30);
REQUIRE(fb_float->GetHostPointer()[5] == 0.3f);
}
SECTION("Deallocate Function Test") {
fb_int->Free();
fb_float->Free();
REQUIRE(fb_int->GetHostPointer() == nullptr);
REQUIRE(fb_float->GetNativePointer() == nullptr);
}
delete fb_int;
delete fb_float;
}
| 5,755
|
C++
|
.cpp
| 137
| 33.489051
| 95
| 0.586937
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,091
|
TestComputationParameters.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/common/TestComputationParameters.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <prerequisites/libraries/catch/catch.hpp>
#include <operations/common/ComputationParameters.hpp>
#include <operations/test-utils/EnvironmentHandler.hpp>
using namespace std;
using namespace operations::common;
using namespace operations::testutils;
#define MARGIN std::numeric_limits<float>::epsilon()
void TEST_CASE_COMPUTATION_PARAMETERS() {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
auto cp = new ComputationParameters(O_2);
auto hl = O_2;
REQUIRE(hl == cp->GetHalfLength());
auto order = SECOND;
cp->SetEquationOrder(order);
REQUIRE(order == cp->GetEquationOrder());
auto physics = ACOUSTIC;
cp->SetPhysics(physics);
REQUIRE(physics == cp->GetPhysics());
auto approximation = ISOTROPIC;
cp->SetApproximation(approximation);
REQUIRE(approximation == cp->GetApproximation());
auto source_frequency = 12.5f;
cp->SetSourceFrequency(source_frequency);
REQUIRE(source_frequency == cp->GetSourceFrequency());
auto isotropic_radius = 5;
cp->SetIsotropicRadius(isotropic_radius);
REQUIRE(isotropic_radius == cp->GetIsotropicRadius());
auto boundary_length = 5;
cp->SetBoundaryLength(boundary_length);
REQUIRE(boundary_length == cp->GetBoundaryLength());
auto relaxed_dt = 0.9f;
cp->SetRelaxedDT(relaxed_dt);
REQUIRE(relaxed_dt == cp->GetRelaxedDT());
auto using_wind = true;
cp->SetIsUsingWindow(using_wind);
REQUIRE(using_wind == cp->IsUsingWindow());
auto wind_left = 1;
cp->SetLeftWindow(wind_left);
REQUIRE(wind_left == cp->GetLeftWindow());
auto wind_right = 2;
cp->SetRightWindow(wind_right);
REQUIRE(wind_right == cp->GetRightWindow());
auto wind_depth = 3;
cp->SetDepthWindow(wind_depth);
REQUIRE(wind_depth == cp->GetDepthWindow());
auto wind_back = 4;
cp->SetBackWindow(wind_back);
REQUIRE(wind_back == cp->GetBackWindow());
auto wind_front = 5;
cp->SetFrontWindow(wind_front);
REQUIRE(wind_front == cp->GetFrontWindow());
auto algorithm = RTM;
cp->SetAlgorithm(algorithm);
REQUIRE(algorithm == cp->GetAlgorithm());
auto block_x = 1;
cp->SetBlockX(block_x);
REQUIRE(block_x == cp->GetBlockX());
auto block_y = 2;
cp->SetBlockY(block_y);
REQUIRE(block_y == cp->GetBlockY());
auto block_z = 3;
cp->SetBlockZ(block_z);
REQUIRE(block_z == cp->GetBlockZ());
auto thread_cnt = 4;
cp->SetThreadCount(thread_cnt);
REQUIRE(thread_cnt == cp->GetThreadCount());
delete cp;
}
void TEST_CASE_COMPUTATION_PARAMETERS_FD_COEFFICIENTS(HALF_LENGTH aHalfLength) {
/*
* Environment setting (i.e. Backend setting initialization).
*/
set_environment();
auto cp = new ComputationParameters(aHalfLength);
if (aHalfLength == O_2) {
/*
* Accuracy = 2
* Half Length = 1
*/
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[0] == -2);
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[1] == 1);
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[0] == 0);
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[1] == 0.5);
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[0] == 0.0f);
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[1] == 1.0f);
} else if (aHalfLength == O_4) {
/*
* Accuracy = 4
* Half Length = 2
*/
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[0] ==
Approx(-2.5).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[1] ==
Approx(1.33333333333).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[2] ==
Approx(-0.08333333333).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[0] == 0.0f);
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[1] ==
Approx(2.0f / 3.0f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[2] ==
Approx(-1.0f / 12.0f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[0] == 0.0f);
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[1] ==
Approx(1.125f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[2] ==
Approx(-0.041666666666666664f).margin(MARGIN));
} else if (aHalfLength == O_8) {
/*
* Accuracy = 8
* Half Length = 4
*/
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[0] ==
Approx(-2.847222222).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[1] ==
Approx(1.6).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[2] ==
Approx(-0.2).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[3] ==
Approx(+2.53968e-2).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[4] ==
Approx(-1.785714e-3).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[0] == 0);
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[1] ==
Approx(0.8).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[2] ==
Approx(-0.2).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[3] ==
Approx(0.03809523809).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[4] ==
Approx(-0.00357142857).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[0] == 0.0f);
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[1] ==
Approx(1.1962890625f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[2] ==
Approx(-0.07975260416666667f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[3] ==
Approx(0.0095703125f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[4] ==
Approx(-0.0006975446428571429f).margin(MARGIN));
} else if (aHalfLength == O_12) {
/*
* Accuracy = 12
* Half Length = 6
*/
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[0] ==
Approx(-2.98277777778).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[1] ==
Approx(1.71428571429).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[2] ==
Approx(-0.26785714285).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[3] ==
Approx(0.05291005291).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[4] ==
Approx(-0.00892857142).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[5] ==
Approx(0.00103896103).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[6] ==
Approx(-0.00006012506).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[0] == 0.0);
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[1] ==
Approx(0.857142857143).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[2] ==
Approx(-0.267857142857).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[3] ==
Approx(0.0793650793651).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[4] ==
Approx(-0.0178571428571).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[5] ==
Approx(0.0025974025974).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[6] ==
Approx(-0.000180375180375).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[0] == 0.0f);
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[1] ==
Approx(1.2213363647460938f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[2] ==
Approx(-0.09693145751953125f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[3] ==
Approx(0.017447662353515626f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[4] ==
Approx(-0.002967289515904018f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[5] ==
Approx(0.0003590053982204861f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[6] ==
Approx(-2.184781161221591e-05f).margin(MARGIN));
} else if (aHalfLength == O_16) {
/*
* Accuracy = 16
* Half Length = 8
*/
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[0] ==
Approx(-3.05484410431).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[1] ==
Approx(1.77777777778).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[2] ==
Approx(-0.311111111111).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[3] ==
Approx(0.0754208754209).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[4] ==
Approx(-0.0176767676768).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[5] ==
Approx(0.00348096348096).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[6] ==
Approx(-0.000518000518001).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[7] ==
Approx(5.07429078858e-05).margin(MARGIN));
REQUIRE(cp->GetSecondDerivativeFDCoefficient()[8] ==
Approx(-2.42812742813e-06).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[0] ==
Approx(-6.93889390391e-17).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[1] ==
Approx(0.888888888889).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[2] ==
Approx(-0.311111111111).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[3] ==
Approx(0.113131313131).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[4] ==
Approx(-0.0353535353535).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[5] ==
Approx(0.00870240870241).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[6] ==
Approx(-0.001554001554).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[7] ==
Approx(0.0001776001776).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeFDCoefficient()[8] ==
Approx(-9.71250971251e-06).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[0] == 0.0f);
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[1] ==
Approx(1.2340910732746122f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[2] ==
Approx(-0.10664984583854668f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[3] ==
Approx(0.023036366701126076f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[4] ==
Approx(-0.005342385598591385f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[5] ==
Approx(0.0010772711700863268f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[6] ==
Approx(-0.00016641887751492495f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[7] ==
Approx(1.7021711056048922e-05f).margin(MARGIN));
REQUIRE(cp->GetFirstDerivativeStaggeredFDCoefficient()[8] ==
Approx(-8.523464202880773e-07f).margin(MARGIN));
}
delete cp;
}
TEST_CASE("Computation Parameters - Class",
"[ComputationParameters],[Class]") {
TEST_CASE_COMPUTATION_PARAMETERS();
}
TEST_CASE("Computation Parameters - FD Coefficients",
"[ComputationParameters],[FDCoefficients]") {
for (auto hl : {O_2, O_4, O_8, O_12, O_16}) {
TEST_CASE_COMPUTATION_PARAMETERS_FD_COEFFICIENTS(hl);
}
}
| 13,302
|
C++
|
.cpp
| 276
| 39.07971
| 80
| 0.649977
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,092
|
NumberHelpers.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/test-utils/src/NumberHelpers.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <limits>
#include <operations/test-utils/NumberHelpers.hpp>
namespace operations {
namespace testutils {
float calculate_norm(const float *mat, uint nx, uint nz, uint ny) {
float sum = 0;
uint nx_nz = nx * nz;
for (int iy = 0; iy < ny; iy++) {
for (int iz = 0; iz < nz; iz++) {
for (int ix = 0; ix < nx; ix++) {
float value = mat[iy * nx_nz + nx * iz + ix];
sum = sum + (value * value);
}
}
}
return sqrtf(sum);
}
bool approximately_equal(float a, float b, float tolerance) {
float epsilon = std::numeric_limits<float>::epsilon() + tolerance;
return fabs(a - b) <= ((fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon) ||
fabs(b - a) <= ((fabs(b) < fabs(a) ? fabs(a) : fabs(b)) * epsilon);
}
bool essentially_equal(float a, float b, float tolerance) {
float epsilon = std::numeric_limits<float>::epsilon();
return fabs(a - b) <= ((fabs(a) > fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}
bool definitely_greater_than(double a, double b, double tolerance) {
float epsilon = std::numeric_limits<double>::epsilon();
return (a - b) > ((fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}
bool definitely_less_than(float a, float b, float tolerance) {
float epsilon = std::numeric_limits<float>::epsilon();
return (b - a) > ((fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}
} //namespace testutils
} //namespace operations
| 2,476
|
C++
|
.cpp
| 54
| 37.296296
| 88
| 0.584507
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,093
|
EnvironmentHandler.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/test-utils/src/EnvironmentHandler.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/test-utils/EnvironmentHandler.hpp>
#ifdef USING_DPCPP
#include <bs/base/backend/Backend.hpp>
using namespace bs::base::backend;
#endif
namespace operations {
namespace testutils {
int set_environment() {
int rc = 0;
#ifdef USING_DPCPP
sycl::cpu_selector cpu_sel;
auto backend = Backend::GetInstance();
if (backend == nullptr) {
rc = 1;
} else {
backend->SetDeviceQueue(
new sycl::queue(cpu_sel));
rc = 0;
}
#endif
return rc;
}
} //namespace testutils
} //namespace operations
| 1,443
|
C++
|
.cpp
| 42
| 28.47619
| 76
| 0.666906
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,094
|
DummyModelGenerator.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/test-utils/src/dummy-data-generators/DummyModelGenerator.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <operations/test-utils/dummy-data-generators/DummyModelGenerator.hpp>
#include <operations/utils/io/write_utils.h>
using namespace std;
namespace operations {
namespace testutils {
float *generate_dummy_model(const std::string &aFileName) {
int nx = 5;
int ny = 5;
int nz = 5;
int nt = 1;
float dx = 1.0f;
float dy = 1.0f;
float dz = 10.0f;
float dt = 1.0;
bool is_traces = false;
string file_name = OPERATIONS_TEST_DATA_PATH "/" + aFileName + ".segy";
int size = nx * ny * nz;
auto data = new float[size];
for (int i = 0; i < size; i++) {
data[i] = 1;
}
nlohmann::json configuration_map;
bs::base::configurations::JSONConfigurationMap io_map(configuration_map);
bs::io::streams::SeismicWriter writer(bs::io::streams::SeismicWriter::ToWriterType("segy"),
&io_map);
writer.AcquireConfiguration();
writer.Initialize(file_name);
auto gathers = operations::utils::io::TransformToGather(data, nx, ny, nz, dx, dy, dz,
0, 0, 0, 0,
1, 1e3, 1e3);
writer.Write(gathers);
writer.Finalize();
for (auto g : gathers) {
delete g;
}
return data;
}
} //namespace testutils
} //namespace operations
| 2,465
|
C++
|
.cpp
| 58
| 31.741379
| 103
| 0.58125
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,095
|
DummyParametersGenerator.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/test-utils/src/dummy-data-generators/DummyParametersGenerator.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/test-utils/dummy-data-generators/DummyParametersGenerator.hpp>
using namespace operations::common;
ComputationParameters *
generate_computation_parameters_no_wind(APPROXIMATION aApproximation);
ComputationParameters *
generate_computation_parameters_inc_wind(APPROXIMATION aApproximation);
ComputationParameters *operations::testutils::generate_computation_parameters(
OP_TU_WIND aWindow, APPROXIMATION aApproximation) {
ComputationParameters *p = nullptr;
if (aWindow == OP_TU_NO_WIND) {
p = generate_computation_parameters_no_wind(aApproximation);
} else if (aWindow == OP_TU_INC_WIND) {
p = generate_computation_parameters_inc_wind(aApproximation);
}
return p;
}
ComputationParameters *
generate_computation_parameters_no_wind(APPROXIMATION aApproximation) {
/*
* Variables initialization for computation parameters.
*/
HALF_LENGTH half_length = O_8;
int boundary_length = 5;
float dt_relax = 0.9;
float source_frequency = 20;
int left_win = 0;
int right_win = 0;
int depth_win = 0;
int front_win = 0;
int back_win = 0;
EQUATION_ORDER equation_order = SECOND;
PHYSICS physics = ACOUSTIC;
APPROXIMATION approximation = aApproximation;
int n_threads = 1;
int block_x = 1;
int block_z = 1;
int block_y = 1;
int use_window = 0;
int grain_side_length = 10;
auto computation_parameters = new ComputationParameters(half_length);
computation_parameters->SetBoundaryLength(boundary_length);
computation_parameters->SetRelaxedDT(dt_relax);
computation_parameters->SetSourceFrequency(source_frequency);
computation_parameters->SetIsUsingWindow(use_window == 1);
computation_parameters->SetLeftWindow(left_win);
computation_parameters->SetRightWindow(right_win);
computation_parameters->SetDepthWindow(depth_win);
computation_parameters->SetFrontWindow(front_win);
computation_parameters->SetBackWindow(back_win);
computation_parameters->SetEquationOrder(equation_order);
computation_parameters->SetApproximation(approximation);
computation_parameters->SetPhysics(physics);
computation_parameters->SetThreadCount(n_threads);
computation_parameters->SetBlockX(block_x);
computation_parameters->SetBlockZ(block_z);
computation_parameters->SetBlockY(block_y);
return computation_parameters;
}
ComputationParameters *
generate_computation_parameters_inc_wind(APPROXIMATION aApproximation) {
/*
* Variables initialization for computation parameters.
*/
HALF_LENGTH half_length = O_8;
int boundary_length = 5;
float dt_relax = 0.9;
float source_frequency = 20;
int left_win = 12;
int right_win = 11;
int depth_win = 23;
int front_win = 0;
int back_win = 0;
EQUATION_ORDER equation_order = SECOND;
PHYSICS physics = ACOUSTIC;
APPROXIMATION approximation = aApproximation;
int n_threads = 1;
int block_x = 1;
int block_z = 1;
int block_y = 1;
int grain_side_length = 10;
int use_window = 1;
auto computation_parameters = new ComputationParameters(half_length);
computation_parameters->SetBoundaryLength(boundary_length);
computation_parameters->SetRelaxedDT(dt_relax);
computation_parameters->SetSourceFrequency(source_frequency);
computation_parameters->SetIsUsingWindow(use_window == 1);
computation_parameters->SetLeftWindow(left_win);
computation_parameters->SetRightWindow(right_win);
computation_parameters->SetDepthWindow(depth_win);
computation_parameters->SetFrontWindow(front_win);
computation_parameters->SetBackWindow(back_win);
computation_parameters->SetEquationOrder(equation_order);
computation_parameters->SetApproximation(approximation);
computation_parameters->SetPhysics(physics);
computation_parameters->SetThreadCount(n_threads);
computation_parameters->SetBlockX(block_x);
computation_parameters->SetBlockZ(block_z);
computation_parameters->SetBlockY(block_y);
return computation_parameters;
}
/// @todo { TO BE REMOVED
ComputationParameters *generate_average_case_parameters() {
HALF_LENGTH half_length = O_8;
int boundary_length = 5;
float dt_relax = 0.9;
float source_frequency = 20;
int left_win = 12;
int right_win = 11;
int depth_win = 23;
int front_win = 0;
int back_win = 0;
EQUATION_ORDER equation_order = SECOND;
PHYSICS physics = ACOUSTIC;
APPROXIMATION approximation = ISOTROPIC;
int n_threads = 1;
int block_x = 1;
int block_z = 1;
int block_y = 1;
int use_window = 0;
int grain_side_length = 10;
auto computation_parameters = new ComputationParameters(half_length);
computation_parameters->SetBoundaryLength(boundary_length);
computation_parameters->SetRelaxedDT(dt_relax);
computation_parameters->SetSourceFrequency(source_frequency);
computation_parameters->SetIsUsingWindow(use_window == 1);
computation_parameters->SetLeftWindow(left_win);
computation_parameters->SetRightWindow(right_win);
computation_parameters->SetDepthWindow(depth_win);
computation_parameters->SetFrontWindow(front_win);
computation_parameters->SetBackWindow(back_win);
computation_parameters->SetEquationOrder(equation_order);
computation_parameters->SetApproximation(approximation);
computation_parameters->SetPhysics(physics);
computation_parameters->SetThreadCount(n_threads);
computation_parameters->SetBlockX(block_x);
computation_parameters->SetBlockZ(block_z);
computation_parameters->SetBlockY(block_y);
return computation_parameters;
}
/// }
| 6,468
|
C++
|
.cpp
| 158
| 36.405063
| 83
| 0.748924
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,096
|
DummyConfigurationMapGenerator.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/test-utils/src/dummy-data-generators/DummyConfigurationMapGenerator.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/test-utils/dummy-data-generators/DummyConfigurationMapGenerator.hpp>
using json = nlohmann::json;
using namespace bs::base::configurations;
namespace operations {
namespace testutils {
JSONConfigurationMap *generate_average_case_configuration_map_wave() {
return new JSONConfigurationMap(R"(
{
"wave": {
"physics": "acoustic",
"approximation": "isotropic",
"equation-order": "first",
"grid-sampling": "uniform"
}
}
)"_json);
}
} //namespace testutils
} //namespace operations
| 1,477
|
C++
|
.cpp
| 37
| 32.459459
| 89
| 0.657601
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,097
|
DummyGridBoxGenerator.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/test-utils/src/dummy-data-generators/DummyGridBoxGenerator.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/test-utils/dummy-data-generators/DummyGridBoxGenerator.hpp>
using namespace operations::dataunits;
GridBox *generate_grid_box_no_wind_2d();
GridBox *generate_grid_box_inc_wind_2d();
GridBox *generate_grid_box_no_wind_3d();
GridBox *generate_grid_box_inc_wind_3d();
GridBox *operations::testutils::generate_grid_box(
OP_TU_DIMS aDims, OP_TU_WIND aWindow) {
GridBox *gb = nullptr;
if (aDims == OP_TU_2D && aWindow == OP_TU_NO_WIND) {
gb = generate_grid_box_no_wind_2d();
} else if (aDims == OP_TU_2D && aWindow == OP_TU_INC_WIND) {
gb = generate_grid_box_inc_wind_2d();
} else if (aDims == OP_TU_3D && aWindow == OP_TU_NO_WIND) {
gb = generate_grid_box_no_wind_3d();
} else if (aDims == OP_TU_3D && aWindow == OP_TU_INC_WIND) {
gb = generate_grid_box_inc_wind_3d();
}
return gb;
}
GridBox *generate_grid_box_no_wind_2d() {
/*
* Variables initialization for grid box.
*/
int hl = 4;
int nx = 23;
int ny = 1;
int nz = 23;
int wnx = nx;
int wny = ny;
int wnz = nz;
int sx = 0;
int sy = 0;
int sz = 0;
float dx = 6.25f;
float dy = 0.0f;
float dz = 6.25f;
float dt = 0.00207987f;
auto *grid_box = new GridBox();
/*
* Setting variables inside grid box.
*/
grid_box->SetAfterSamplingAxis(new Axis3D<unsigned int>(nx, ny, nz));
grid_box->SetInitialAxis(new Axis3D<unsigned int>(nx, ny, nz));
grid_box->SetWindowAxis(new Axis3D<unsigned int>(wnx, wny, wnz));
grid_box->GetAfterSamplingAxis()->GetXAxis().SetCellDimension(dx);
grid_box->GetAfterSamplingAxis()->GetYAxis().SetCellDimension(dy);
grid_box->GetAfterSamplingAxis()->GetZAxis().SetCellDimension(dz);
grid_box->GetInitialAxis()->GetXAxis().SetCellDimension(dx);
grid_box->GetInitialAxis()->GetYAxis().SetCellDimension(dy);
grid_box->GetInitialAxis()->GetZAxis().SetCellDimension(dz);
grid_box->GetInitialAxis()->GetXAxis().SetReferencePoint(sx);
grid_box->GetInitialAxis()->GetYAxis().SetReferencePoint(sy);
grid_box->GetInitialAxis()->GetZAxis().SetReferencePoint(sz);
grid_box->GetAfterSamplingAxis()->GetXAxis().SetReferencePoint(sx);
grid_box->GetAfterSamplingAxis()->GetYAxis().SetReferencePoint(sy);
grid_box->GetAfterSamplingAxis()->GetZAxis().SetReferencePoint(sz);
grid_box->SetDT(dt);
return grid_box;
}
GridBox *generate_grid_box_inc_wind_2d() {
/*
* Variables initialization for grid box.
*/
int hl = 4;
int nx = 23;
int ny = 1;
int nz = 23;
int wnx = 21;
int wny = 1;
int wnz = 21;
int sx = 0;
int sy = 0;
int sz = 0;
float dx = 6.25f;
float dy = 0.0f;
float dz = 6.25f;
float dt = 0.00207987f;
auto *grid_box = new GridBox();
/*
* Setting variables inside grid box.
*/
grid_box->SetAfterSamplingAxis(new Axis3D<unsigned int>(nx, ny, nz));
grid_box->SetInitialAxis(new Axis3D<unsigned int>(nx, ny, nz));
grid_box->SetWindowAxis(new Axis3D<unsigned int>(wnx, wny, wnz));
grid_box->GetAfterSamplingAxis()->GetXAxis().SetCellDimension(dx);
grid_box->GetAfterSamplingAxis()->GetYAxis().SetCellDimension(dy);
grid_box->GetAfterSamplingAxis()->GetZAxis().SetCellDimension(dz);
grid_box->GetInitialAxis()->GetXAxis().SetCellDimension(dx);
grid_box->GetInitialAxis()->GetYAxis().SetCellDimension(dy);
grid_box->GetInitialAxis()->GetZAxis().SetCellDimension(dz);
grid_box->GetInitialAxis()->GetXAxis().SetReferencePoint(sx);
grid_box->GetInitialAxis()->GetYAxis().SetReferencePoint(sy);
grid_box->GetInitialAxis()->GetZAxis().SetReferencePoint(sz);
grid_box->GetAfterSamplingAxis()->GetXAxis().SetReferencePoint(sx);
grid_box->GetAfterSamplingAxis()->GetYAxis().SetReferencePoint(sy);
grid_box->GetAfterSamplingAxis()->GetZAxis().SetReferencePoint(sz);
grid_box->SetDT(dt);
return grid_box;
}
GridBox *generate_grid_box_no_wind_3d() {
/*
* Variables initialization for grid box.
*/
int hl = 4;
int nx = 23;
int ny = 23;
int nz = 23;
int wnx = nx;
int wny = ny;
int wnz = nz;
int sx = 0;
int sy = 0;
int sz = 0;
float dx = 6.25f;
float dy = 6.25f;
float dz = 6.25f;
float dt = 0.00169821f;
auto *grid_box = new GridBox();
/*
* Setting variables inside grid box.
*/
grid_box->SetAfterSamplingAxis(new Axis3D<unsigned int>(nx, ny, nz));
grid_box->SetInitialAxis(new Axis3D<unsigned int>(nx, ny, nz));
grid_box->SetWindowAxis(new Axis3D<unsigned int>(wnx, wny, wnz));
grid_box->GetAfterSamplingAxis()->GetXAxis().SetCellDimension(dx);
grid_box->GetAfterSamplingAxis()->GetYAxis().SetCellDimension(dy);
grid_box->GetAfterSamplingAxis()->GetZAxis().SetCellDimension(dz);
grid_box->GetInitialAxis()->GetXAxis().SetCellDimension(dx);
grid_box->GetInitialAxis()->GetYAxis().SetCellDimension(dy);
grid_box->GetInitialAxis()->GetZAxis().SetCellDimension(dz);
grid_box->GetInitialAxis()->GetXAxis().SetReferencePoint(sx);
grid_box->GetInitialAxis()->GetYAxis().SetReferencePoint(sy);
grid_box->GetInitialAxis()->GetZAxis().SetReferencePoint(sz);
grid_box->GetAfterSamplingAxis()->GetXAxis().SetReferencePoint(sx);
grid_box->GetAfterSamplingAxis()->GetYAxis().SetReferencePoint(sy);
grid_box->GetAfterSamplingAxis()->GetZAxis().SetReferencePoint(sz);
grid_box->SetDT(dt);
return grid_box;
}
GridBox *generate_grid_box_inc_wind_3d() {
/*
* Variables initialization for grid box.
*/
int hl = 4;
int nx = 23;
int ny = 23;
int nz = 23;
int wnx = 21;
int wny = 21;
int wnz = 21;
int sx = 0;
int sy = 0;
int sz = 0;
float dx = 6.25f;
float dy = 6.25f;
float dz = 6.25f;
float dt = 0.00169821;
auto *grid_box = new GridBox();
/*
* Setting variables inside grid box.
*/
grid_box->SetAfterSamplingAxis(new Axis3D<unsigned int>(nx, ny, nz));
grid_box->SetInitialAxis(new Axis3D<unsigned int>(nx, ny, nz));
grid_box->SetWindowAxis(new Axis3D<unsigned int>(wnx, wny, wnz));
grid_box->GetAfterSamplingAxis()->GetXAxis().SetCellDimension(dx);
grid_box->GetAfterSamplingAxis()->GetYAxis().SetCellDimension(dy);
grid_box->GetAfterSamplingAxis()->GetZAxis().SetCellDimension(dz);
grid_box->GetInitialAxis()->GetXAxis().SetCellDimension(dx);
grid_box->GetInitialAxis()->GetYAxis().SetCellDimension(dy);
grid_box->GetInitialAxis()->GetZAxis().SetCellDimension(dz);
grid_box->GetInitialAxis()->GetXAxis().SetReferencePoint(sx);
grid_box->GetInitialAxis()->GetYAxis().SetReferencePoint(sy);
grid_box->GetInitialAxis()->GetZAxis().SetReferencePoint(sz);
grid_box->GetAfterSamplingAxis()->GetXAxis().SetReferencePoint(sx);
grid_box->GetAfterSamplingAxis()->GetYAxis().SetReferencePoint(sy);
grid_box->GetAfterSamplingAxis()->GetZAxis().SetReferencePoint(sz);
grid_box->SetDT(dt);
return grid_box;
}
| 7,847
|
C++
|
.cpp
| 198
| 34.742424
| 80
| 0.681878
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,098
|
DummyTraceGenerator.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/tests/test-utils/src/dummy-data-generators/DummyTraceGenerator.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <operations/test-utils/dummy-data-generators/DummyTraceGenerator.hpp>
#include <operations/utils/io/write_utils.h>
using namespace std;
namespace operations {
namespace testutils {
float *generate_dummy_trace(const std::string &aFileName,
dataunits::GridBox *apGridBox,
int trace_stride_x,
int trace_stride_y) {
// One trace every n points in x
uint nx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize() / trace_stride_x;
uint nz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint ny = 1;
uint nt = nz;
float dz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
float dx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension() * trace_stride_x;
float dy = 1.0f;
float dt = 1.0f;
if (apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize() > 1) {
// One trace every n points in y
ny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize() / trace_stride_y;
dy = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension() * trace_stride_y;
}
auto data = new float[nx * nz * ny];
for (int i = 0; i < nx * nz * ny; i++) {
data[i] = (float) rand() * 100 / RAND_MAX;
}
nlohmann::json configuration_map;
bs::base::configurations::JSONConfigurationMap io_map(configuration_map);
bs::io::streams::SeismicWriter writer(bs::io::streams::SeismicWriter::ToWriterType("segy"),
&io_map);
writer.AcquireConfiguration();
std::string path = aFileName;
writer.Initialize(path);
auto gathers = operations::utils::io::TransformToGather(data, 1, 1, nz, dx, dy, dt,
0, 0, 0, 0,
nx * ny, 1e3, 1e6);
writer.Write(gathers);
writer.Finalize();
for (auto g : gathers) {
delete g;
}
return data;
}
} //namespace testutils
} //namespace operations
| 3,244
|
C++
|
.cpp
| 65
| 37.538462
| 105
| 0.586359
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,099
|
CrossCorrelationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/migration-accommodators/CrossCorrelationKernel.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <vector>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/components/independents/concrete/migration-accommodators/CrossCorrelationKernel.hpp>
#define EPSILON 1e-20f
using namespace std;
using namespace bs::timer;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
template void CrossCorrelationKernel::Correlation<true, NO_COMPENSATION>(GridBox *apGridBox);
template void CrossCorrelationKernel::Correlation<false, NO_COMPENSATION>(GridBox *apGridBox);
template void CrossCorrelationKernel::Correlation<true, COMBINED_COMPENSATION>(GridBox *apGridBox);
template void CrossCorrelationKernel::Correlation<false, COMBINED_COMPENSATION>(GridBox *apGridBox);
template void CrossCorrelationKernel::Stack<true, NO_COMPENSATION>();
template void CrossCorrelationKernel::Stack<false, NO_COMPENSATION>();
template void CrossCorrelationKernel::Stack<true, COMBINED_COMPENSATION>();
template void CrossCorrelationKernel::Stack<false, COMBINED_COMPENSATION>();
template<bool _IS_2D, COMPENSATION_TYPE _COMPENSATION_TYPE>
void CrossCorrelationKernel::Correlation(GridBox *apGridBox) {
GridBox *source_gridbox = apGridBox;
GridBox *receiver_gridbox = this->mpGridBox;
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
float *source_base = source_gridbox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *receiver_base = receiver_gridbox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *corr_base = mpShotCorrelation->GetNativePointer();
float *source_illumination_base = mpSourceIllumination->GetNativePointer();
float *receiver_illumination_base = mpReceiverIllumination->GetNativePointer();
float *src_ptr;
float *rec_ptr;
float *source_i;
float *receive_i;
float *correlation_output;
uint offset = mpParameters->GetHalfLength();
int nxEnd = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - offset;
int nzEnd = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - offset;
int size = (wnx - 2 * offset) * (wnz - 2 * offset);
int flops_per_second = 3 * offset;
if (_COMPENSATION_TYPE == COMBINED_COMPENSATION) {
flops_per_second = 9 * offset;
}
ElasticTimer timer("Correlation::Correlate::Kernel",
size, 5, true,
flops_per_second);
timer.Start();
#pragma omp parallel default(shared)
{
const uint block_x = mpParameters->GetBlockX();
const uint block_z = mpParameters->GetBlockZ();
#pragma omp for schedule(static, 1) collapse(2)
for (int bz = offset; bz < nzEnd; bz += block_z) {
for (int bx = offset; bx < nxEnd; bx += block_x) {
int izEnd = fmin(bz + block_z, nzEnd);
int ixEnd = fmin(block_x, nxEnd - bx);
for (int iz = bz; iz < izEnd; ++iz) {
uint b_offset = iz * wnx + bx;
src_ptr = source_base + b_offset;
rec_ptr = receiver_base + b_offset;
correlation_output = corr_base + b_offset;
source_i = source_illumination_base + b_offset;
receive_i = receiver_illumination_base + b_offset;
#pragma vector aligned
#pragma ivdep
for (int ix = 0; ix < ixEnd; ix++) {
float value;
value = src_ptr[ix] * rec_ptr[ix];
correlation_output[ix] += value;
if (_COMPENSATION_TYPE == COMBINED_COMPENSATION) {
source_i[ix] += src_ptr[ix] * src_ptr[ix];
receive_i[ix] += rec_ptr[ix] * rec_ptr[ix];
}
}
}
}
}
}
timer.Stop();
}
template<bool _IS_2D, COMPENSATION_TYPE _COMPENSATION_TYPE>
void CrossCorrelationKernel::Stack() {
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
int constant = this->mpGridBox->GetWindowStart(X_AXIS) +
this->mpGridBox->GetWindowStart(Z_AXIS) * nx;
float *in = this->mpShotCorrelation->GetNativePointer();
float *out = this->mpTotalCorrelation->GetNativePointer() + constant;
float *in_src = this->mpSourceIllumination->GetNativePointer();
float *in_rcv = this->mpReceiverIllumination->GetNativePointer();
uint block_x = this->mpParameters->GetBlockX();
uint block_z = this->mpParameters->GetBlockZ();
uint offset = this->mpParameters->GetHalfLength() +
this->mpParameters->GetBoundaryLength();
int x_end = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - offset;
int z_end = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - offset;
int size = (wnx - 2 * offset) * (wnz - 2 * offset);
int flops_per_second = 2 * offset;
if (_COMPENSATION_TYPE == COMBINED_COMPENSATION) {
flops_per_second = 6 * offset;
}
float *input, *output, *input_src, *input_rcv;
ElasticTimer timer("Correlation::Stack::Kernel",
size, 4, true,
flops_per_second);
timer.Start();
#pragma omp parallel for schedule(static, 1) collapse(2)
for (int bz = offset; bz < z_end; bz += block_z) {
for (int bx = offset; bx < x_end; bx += block_x) {
int izEnd = fmin(bz + block_z, z_end);
int ixEnd = fmin(bx + block_x, x_end);
for (int iz = bz; iz < izEnd; iz++) {
uint offset_window = iz * wnx;
uint offset = iz * nx;
input = in + offset_window;
output = out + offset;
input_src = in_src + offset_window;
input_rcv = in_rcv + offset_window;
#pragma ivdep
#pragma vector aligned
for (int ix = bx; ix < ixEnd; ix++) {
if constexpr (_COMPENSATION_TYPE == COMBINED_COMPENSATION) {
output[ix] += (input[ix] / (sqrtf(input_src[ix] * input_rcv[ix]) + EPSILON));
} else {
output[ix] += input[ix];
}
}
}
}
}
timer.Stop();
}
| 7,625
|
C++
|
.cpp
| 153
| 41.169935
| 105
| 0.640269
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,100
|
SeismicTraceWriter.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/trace-writers/SeismicTraceWriter.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/components/independents/concrete/trace-writers/SeismicTraceWriter.hpp>
using namespace std;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
void SeismicTraceWriter::RecordTrace(uint time_step) {
int trace_size = mTraceNumber;
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz_wnx = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize() * wnx;
int std_offset = (mpParameters->GetBoundaryLength() + mpParameters->GetHalfLength()) * wnx;
float current_time = (time_step - 1) * this->mpGridBox->GetDT();
uint trace_step = uint(current_time / mTraceSampling);
if (time_step > 1) {
float previous_time = (time_step - 2) * this->mpGridBox->GetDT();
uint previous_trace_step = uint(previous_time / mTraceSampling);
if (previous_trace_step == trace_step) {
return;
}
}
trace_step = min(trace_step, mSampleNumber - 1);
auto positions_y = this->mpDPositionsY.GetNativePointer();
auto positions_x = this->mpDPositionsX.GetNativePointer();
auto values = this->mpDTraces.GetNativePointer();
float *pressure = this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
for (int i = 0; i < trace_size; i++) {
int offset = positions_y[i] * wnz_wnx + std_offset + positions_x[i];
values[(trace_step) * trace_size + i] = pressure[offset];
}
}
| 2,255
|
C++
|
.cpp
| 47
| 43.93617
| 95
| 0.716167
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,101
|
BoundarySaver.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/forward-collectors/boundary-saver/BoundarySaver.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/components/independents/concrete/forward-collectors/boundary-saver/BoundarySaver.h>
using namespace operations::components::helpers;
using namespace operations::common;
using namespace operations::dataunits;
void BoundarySaver::SaveBoundaries(uint aStep) {
uint index = 0;
uint size_of_boundaries = this->mBoundarySize;
uint time_step = aStep;
uint half_length = this->mpComputationParameters->GetHalfLength();
uint bound_length = this->mpComputationParameters->GetBoundaryLength();
uint offset = half_length + bound_length;
uint start_y = 0;
uint end_y = 1;
uint ny = this->mpMainGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
uint wnx = this->mpMainGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = this->mpMainGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint lnx = this->mpMainGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
uint lny = this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
uint lnz = this->mpMainGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
uint start_z = offset;
uint end_z = this->mpMainGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - offset;
uint start_x = offset;
uint end_x = this->mpMainGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - offset;
uint wnznx = wnx * wnz;
if (ny > 1) {
start_y = offset;
end_y = this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - offset;
}
float *current_pressure = this->mpMainGridBox->Get(this->mKey)->GetNativePointer();
float *backup_boundaries = this->mBackupBoundaries.GetNativePointer();
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = start_z; iz < end_z; iz++) {
for (int ix = 0; ix < half_length; ix++) {
backup_boundaries[time_step * size_of_boundaries + index] =
current_pressure[iy * wnznx + iz * wnx + bound_length + ix];
index++;
backup_boundaries[time_step * size_of_boundaries + index] =
current_pressure[iy * wnznx + iz * wnx + (lnx - bound_length - 1) - ix];
index++;
}
}
}
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = 0; iz < half_length; iz++) {
for (int ix = start_x; ix < end_x; ix++) {
backup_boundaries[time_step * size_of_boundaries + index] =
current_pressure[iy * wnznx + (bound_length + iz) * wnx + ix];
index++;
backup_boundaries[time_step * size_of_boundaries + index] =
current_pressure[iy * wnznx + (lnz - bound_length - 1 - iz) * wnx + ix];
index++;
}
}
}
if (ny > 1) {
for (int iy = 0; iy < half_length; iy++) {
for (int iz = start_z; iz < end_z; iz++) {
for (int ix = start_x; ix < end_x; ix++) {
backup_boundaries[time_step * size_of_boundaries + index] =
current_pressure[(bound_length + iy) * wnznx + iz * wnx + ix];
index++;
backup_boundaries[time_step * size_of_boundaries + index] =
current_pressure[(lny - bound_length - 1 - iy) * wnznx + iz * wnx + ix];
index++;
}
}
}
}
}
void BoundarySaver::RestoreBoundaries(uint aStep) {
uint index = 0;
uint size_of_boundaries = this->mBoundarySize;
uint time_step = aStep;
uint half_length = this->mpComputationParameters->GetHalfLength();
uint bound_length = this->mpComputationParameters->GetBoundaryLength();
uint offset = half_length + bound_length;
uint start_y = 0;
uint end_y = 1;
///WILL TEST
uint ny = mpMainGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
uint wnx = mpMainGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = mpMainGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = mpMainGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint lnx = mpMainGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
uint lny = mpMainGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
uint lnz = mpMainGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
uint start_z = offset;
uint end_z = mpMainGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - offset;
uint start_x = offset;
uint end_x = mpMainGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - offset;
uint wnznx = wnx * wnz;
if (ny > 1) {
start_y = offset;
end_y = mpMainGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - offset;
}
float *current_pressure = this->mpInternalGridBox->Get(this->mKey)->GetNativePointer();
float *backup_boundaries = this->mBackupBoundaries.GetNativePointer();
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = start_z; iz < end_z; iz++) {
for (int ix = 0; ix < half_length; ix++) {
current_pressure[iy * wnznx + iz * wnx + bound_length + ix] =
backup_boundaries[time_step * size_of_boundaries + index];
index++;
current_pressure[iy * wnznx + iz * wnx + (lnx - bound_length - 1) - ix] =
backup_boundaries[time_step * size_of_boundaries + index];
index++;
}
}
}
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = 0; iz < half_length; iz++) {
for (int ix = start_x; ix < end_x; ix++) {
current_pressure[iy * wnznx + (bound_length + iz) * wnx + ix] =
backup_boundaries[time_step * size_of_boundaries + index];
index++;
current_pressure[iy * wnznx + (lnz - bound_length - 1 - iz) * wnx + ix] =
backup_boundaries[time_step * size_of_boundaries + index];
index++;
}
}
}
if (ny > 1) {
for (int iy = 0; iy < half_length; iy++) {
for (int iz = start_z; iz < end_z; iz++) {
for (int ix = start_x; ix < end_x; ix++) {
current_pressure[(bound_length + iy) * wnznx + iz * wnx + ix] =
backup_boundaries[time_step * size_of_boundaries + index];
index++;
current_pressure[(lny - bound_length - 1 - iy) * wnznx + iz * wnx + ix] =
backup_boundaries[time_step * size_of_boundaries + index];
index++;
}
}
}
}
}
| 7,671
|
C++
|
.cpp
| 155
| 39.877419
| 104
| 0.594425
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,102
|
SeismicTraceManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/trace-managers/SeismicTraceManager.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bs/base/memory/MemoryManager.hpp>
#include <operations/components/independents/concrete/trace-managers/SeismicTraceManager.hpp>
using namespace std;
using namespace bs::base::memory;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
void SeismicTraceManager::ApplyTraces(int time_step) {
int trace_size = this->mpTracesHolder->TraceSizePerTimeStep;
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz_wnx = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize() * wnx;
int std_offset = (mpParameters->GetBoundaryLength() + mpParameters->GetHalfLength()) * wnx;
float current_time = (time_step - 1) * this->mpGridBox->GetDT();
float dt = this->mpGridBox->GetDT();
uint trace_step = uint(current_time / this->mpTracesHolder->SampleDT);
trace_step = min(trace_step, this->mpTracesHolder->SampleNT - 1);
auto traces = this->mpTracesHolder->Traces->GetNativePointer();
for (int i = 0; i < trace_size; i++) {
int offset = this->mpTracesHolder->PositionsY[i] * wnz_wnx + std_offset + this->mpTracesHolder->PositionsX[i];
float *pressure = this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *velocity = this->mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
pressure[offset] +=
traces[(trace_step) * trace_size + i] *
velocity[offset];
}
}
| 2,261
|
C++
|
.cpp
| 44
| 47.340909
| 118
| 0.725091
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,103
|
FrameBuffer.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/data-units/FrameBuffer.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstring>
#include <bs/base/memory/MemoryManager.hpp>
#include <operations/common/DataTypes.h>
#include <operations/data-units/concrete/holders/FrameBuffer.hpp>
using namespace bs::base::memory;
using namespace operations::dataunits;
template
class operations::dataunits::FrameBuffer<float>;
template
class operations::dataunits::FrameBuffer<int>;
template
class operations::dataunits::FrameBuffer<uint>;
static uint MASK_ALLOC_FACTOR = 0;
template<typename T>
FrameBuffer<T>::FrameBuffer() {
this->mpDataPointer = nullptr;
this->mpHostDataPointer = nullptr;
this->mAllocatedBytes = 0;
}
template<typename T>
FrameBuffer<T>::FrameBuffer(uint aSize) {
this->Allocate(aSize);
this->mpHostDataPointer = nullptr;
}
template<typename T>
FrameBuffer<T>::~FrameBuffer() {
this->Free();
}
template<typename T>
void FrameBuffer<T>::Allocate(uint aSize, const std::string &aName) {
this->mAllocatedBytes = sizeof(T) * aSize;
this->mpDataPointer = (T *) mem_allocate(sizeof(T), aSize, aName);
}
template<typename T>
void FrameBuffer<T>::Allocate(uint aSize, HALF_LENGTH aHalfLength, const std::string &aName) {
this->mAllocatedBytes = sizeof(T) * (aSize + 16);
this->mpDataPointer = (T *) mem_allocate(sizeof(T),
aSize,
aName,
aHalfLength,
MASK_ALLOC_FACTOR);
MASK_ALLOC_FACTOR += 16;
}
template<typename T>
void FrameBuffer<T>::Free() {
if (this->mpDataPointer != nullptr) {
mem_free(this->mpDataPointer);
this->mpDataPointer = nullptr;
this->mpHostDataPointer = nullptr;
}
this->mAllocatedBytes = 0;
}
template<typename T>
T *FrameBuffer<T>::GetNativePointer() {
return this->mpDataPointer;
}
template<typename T>
void FrameBuffer<T>::SetNativePointer(T *pT) {
this->mpDataPointer = pT;
}
template<typename T>
T *FrameBuffer<T>::GetHostPointer() {
this->mpHostDataPointer = this->mpDataPointer;
return this->mpHostDataPointer;
}
template<typename T>
T *FrameBuffer<T>::GetDiskFlushPointer() {
return this->GetHostPointer();
}
template<typename T>
void FrameBuffer<T>::ReflectOnNative() {
/* For omp native is the same as host, so no need to reflect. */
}
void Device::MemSet(void *apDst, int aVal, uint aSize) {
memset(apDst, aVal, aSize);
}
void Device::MemCpy(void *apDst, const void *apSrc, uint aSize, CopyDirection aCopyDirection) {
memcpy(apDst, apSrc, aSize);
}
| 3,340
|
C++
|
.cpp
| 97
| 30.030928
| 95
| 0.704531
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,104
|
RickerSourceInjector.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/source-injectors/RickerSourceInjector.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <math.h>
#include <operations/components/independents/concrete/source-injectors/RickerSourceInjector.hpp>
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
/**
* Implementation based on
* https://tel.archives-ouvertes.fr/tel-00954506v2/document .
* https://wiki.seg.org/wiki/Dictionary:Ricker_wavelet
*/
void RickerSourceInjector::ApplySource(int time_step) {
float dt = this->mpGridBox->GetDT();
float freq = this->mpParameters->GetSourceFrequency();
// std::cout << " cut off " << this->GetCutOffTimeStep() << std::endl;
if (time_step < this->GetCutOffTimeStep()) {
float a = M_PI * freq;
float a2 = a * a;
float t = time_step * dt;
float t2 = t * t;
// ricker function required should have negative polarity
float ricker = (1 - a2 * 2 * t2) * exp(-a2 * t2);
//std::cout << " ricker " << time_step << " : " << ricker << std::endl;
uint location = this->GetInjectionLocation();
ricker = ricker * this->mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer()[location];
float *pressure = this->mpGridBox->Get(WAVE | GB_PRSS | CURR)->GetNativePointer();
pressure[location] += ricker;
}
}
| 2,052
|
C++
|
.cpp
| 46
| 40.586957
| 99
| 0.697791
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,105
|
SeismicModelHandler.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/model-handlers/SeismicModelHandler.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/components/independents/concrete/model-handlers/SeismicModelHandler.hpp>
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
void SeismicModelHandler::SetupWindow() {
if (this->mpParameters->IsUsingWindow()) {
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
uint sx = this->mpGridBox->GetWindowStart(X_AXIS);
uint sy = this->mpGridBox->GetWindowStart(Y_AXIS);
uint sz = this->mpGridBox->GetWindowStart(Z_AXIS);
uint offset = this->mpParameters->GetHalfLength() +
this->mpParameters->GetBoundaryLength();
uint start_x = offset;
uint end_x = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - offset;
uint start_z = offset;
uint end_z = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - offset;
uint start_y = 0;
uint end_y = 1;
if (ny != 1) {
start_y = offset;
end_y = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - offset;
}
for (uint iy = start_y; iy < end_y; iy++) {
for (uint iz = start_z; iz < end_z; iz++) {
for (uint ix = start_x; ix < end_x; ix++) {
uint offset_window = iy * wnx * wnz + iz * wnx + ix;
uint offset_full = (iy + sy) * nx * nz + (iz + sz) * nx + ix + sx;
for (auto const ¶meter : this->mpGridBox->GetParameters()) {
float *window_param = this->mpGridBox->Get(WIND | parameter.first)->GetNativePointer();
float *param_ptr = this->mpGridBox->Get(parameter.first)->GetNativePointer();
window_param[offset_window] = param_ptr[offset_full];
}
}
}
}
}
}
void SeismicModelHandler::SetupPadding() {
}
| 3,096
|
C++
|
.cpp
| 61
| 42.442623
| 111
| 0.642715
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,106
|
WaveFieldsMemoryHandler.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/memory-handlers/WaveFieldsMemoryHandler.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp>
using namespace std;
using namespace bs::timer;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
void
WaveFieldsMemoryHandler::FirstTouch(
float *ptr, GridBox *apGridBox, bool enable_window) {
float *curr_base = ptr;
float *curr;
int nx, ny, nz;
if (enable_window) {
nx = apGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
ny = apGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
nz = apGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
} else {
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetLogicalAxisSize();
}
int nxnz = nx * nz;
int nxEnd = nx - this->mpParameters->GetHalfLength();
int nyEnd = 1;
int nzEnd = nz - this->mpParameters->GetHalfLength();
int y_start = 0;
if (ny > 1) {
y_start = this->mpParameters->GetHalfLength();
nyEnd = ny - this->mpParameters->GetHalfLength();
}
uint half_length = this->mpParameters->GetHalfLength();
int block_x = this->mpParameters->GetBlockX();
int block_y = this->mpParameters->GetBlockY();
int block_z = this->mpParameters->GetBlockZ();
if (enable_window) {
nx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
} else {
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
}
/// Access elements in the same way used in
/// the computation kernel step.
ElasticTimer timer("ComputationKernel::FirstTouch");
timer.Start();
#pragma omp parallel for schedule(static, 1) collapse(2)
for (int by = y_start; by < nyEnd; by += block_y) {
for (int bz = half_length; bz < nzEnd; bz += block_z) {
for (int bx = half_length; bx < nxEnd; bx += block_x) {
int izEnd = fmin(bz + block_z, nzEnd);
int iyEnd = fmin(by + block_y, nyEnd);
int ixEnd = fmin(block_x, nxEnd - bx);
for (int iy = by; iy < iyEnd; ++iy) {
for (int iz = bz; iz < izEnd; ++iz) {
curr = curr_base + iy * nxnz + iz * nx + bx;
#pragma ivdep
for (int ix = 0; ix < ixEnd; ++ix) {
curr[ix] = 0;
}
}
}
}
}
}
memset(ptr, 0, sizeof(float) * nx * nz * ny);
timer.Stop();
}
| 3,837
|
C++
|
.cpp
| 89
| 36.213483
| 96
| 0.642283
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,107
|
SecondOrderComputationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/computation-kernels/isotropic/SecondOrderComputationKernel.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/components/independents/concrete/computation-kernels/isotropic/SecondOrderComputationKernel.hpp>
#include <operations/components/independents/concrete/computation-kernels/BaseComputationHelpers.hpp>
#include <operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp>
using namespace std;
using namespace bs::timer;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
FORWARD_DECLARE_COMPUTE_TEMPLATE(SecondOrderComputationKernel, Compute)
template<KERNEL_MODE KERNEL_MODE_, bool IS_2D_, HALF_LENGTH HALF_LENGTH_>
void SecondOrderComputationKernel::Compute() {
/*
* Read parameters into local variables to be shared.
*/
float *prev_base = this->mpGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
float *curr_base = this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *next_base = this->mpGridBox->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
float *vel_base = this->mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
float *coeff_x = mpCoeffX->GetNativePointer();
float *coeff_z = mpCoeffZ->GetNativePointer();
int *vertical_index = mpVerticalIdx->GetNativePointer();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int block_x = this->mpParameters->GetBlockX();
int block_z = this->mpParameters->GetBlockZ();
int nx_end = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int nz_end = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int size = (wnx - 2 * HALF_LENGTH_) * (wnz - 2 * HALF_LENGTH_);
/// General note: floating point operations for forward is the same as backward
/// (calculated below are for forward). number of floating point operations for
/// the computation kernel in 2D for the half_length loop:6*k,where K is the
/// half_length 5 floating point operations outside the half_length loop Total
/// = 6*K+5 =6*K+5
int flops_per_second = 6 * HALF_LENGTH_ + 5;
ElasticTimer timer("ComputationKernel::Kernel",
size, 4, true,
flops_per_second);
/// @todo Redo calculations for operations since adjoint is different than forward.
timer.Start();
/*
* Start the computation by creating the threads.
*/
#pragma omp parallel default(shared)
{
float *prev, *curr, *next, *vel;
/// Three loops for cache blocking.
/// Utilizing the cache to the maximum to speed up computation.
#pragma omp for schedule(static, 1) collapse(2)
for (int bz = HALF_LENGTH_; bz < nz_end; bz += block_z) {
for (int bx = HALF_LENGTH_; bx < nx_end; bx += block_x) {
/// Calculate the endings appropriately
/// (Handle remainder of the cache blocking loops).
int ixEnd = min(block_x, nx_end - bx);
int izEnd = min(bz + block_z, nz_end);
/// Loop on the elements in the block.
for (int iz = bz; iz < izEnd; ++iz) {
// Pre-compute and advance the pointer to the start of the current
// start point of the processing.
int offset = iz * wnx + bx;
// Velocity moves with the full nx and nz not the windows ones.
prev = prev_base + offset;
curr = curr_base + offset;
next = next_base + offset;
vel = vel_base + offset;
#pragma vector aligned
#pragma vector vecremainder
#pragma omp simd
#pragma ivdep
for (int ix = 0; ix < ixEnd; ++ix) {
/// Calculate the finite difference using sequence of fma
/// instructions.
float value = 0;
/*
* 1 floating point operation
*/
value = fma(curr[ix], mCoeffXYZ, value);
/// Calculate Finite Difference in the x-direction.
/// 3 floating point operations
DERIVE_SEQ_AXIS_EQ_OFF(ix, 1, +, curr, coeff_x, value)
/// Calculate Finite Difference in the z-direction.
/// 3 floating point operations
DERIVE_ARRAY_AXIS_EQ_OFF(ix, vertical_index, +, curr, coeff_z, value)
/// Calculate the next pressure value according to
/// the second order acoustic wave equation.
/// 4 floating point operations.
next[ix] = (2 * curr[ix]) - prev[ix] + (vel[ix] * value);
}
}
}
}
}
timer.Stop();
}
void SecondOrderComputationKernel::PreprocessModel() {
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
float dt = this->mpGridBox->GetDT();
float dt2 = dt * dt;
float *velocity_values = this->mpGridBox->Get(PARM | GB_VEL)->GetNativePointer();
int full_nx = nx;
/// Preprocess the velocity model by calculating the
/// dt2 * c2 component of the wave equation.
#pragma omp parallel default(shared)
{
#pragma omp for schedule(static) collapse(2)
for (int z = 0; z < nz; ++z) {
for (int x = 0; x < nx; ++x) {
float value = velocity_values[z * full_nx + x];
velocity_values[z * full_nx + x] =
value * value * dt2;
}
}
}
}
| 6,705
|
C++
|
.cpp
| 134
| 40.522388
| 117
| 0.62139
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,108
|
StaggeredComputationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/computation-kernels/isotropic/StaggeredComputationKernel.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/components/independents/concrete/computation-kernels/isotropic/StaggeredComputationKernel.hpp>
#include <operations/components/independents/concrete/computation-kernels/BaseComputationHelpers.hpp>
#include <operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp>
using namespace std;
using namespace bs::timer;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
FORWARD_DECLARE_COMPUTE_TEMPLATE(StaggeredComputationKernel, ComputePressure)
FORWARD_DECLARE_COMPUTE_TEMPLATE(StaggeredComputationKernel, ComputeVelocity)
template<KERNEL_MODE KERNEL_MODE_, bool IS_2D_, HALF_LENGTH HALF_LENGTH_>
void StaggeredComputationKernel::ComputeVelocity() {
/*
* Read parameters into local variables to be shared.
*/
float *curr_base = this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *next_base = this->mpGridBox->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
float *particle_vel_x = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_X)->GetNativePointer();
float *particle_vel_z = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_Z)->GetNativePointer();
float *vel_base = this->mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
float *den_base = this->mpGridBox->Get(PARM | WIND | GB_DEN)->GetNativePointer();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
float dx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
float dt = this->mpGridBox->GetDT();
float *coefficients = this->mpParameters->GetFirstDerivativeStaggeredFDCoefficient();
int block_x = this->mpParameters->GetBlockX();
int block_z = this->mpParameters->GetBlockZ();
int nx_end = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int nz_end = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int nx = wnx;
int nz = wnz;
int size = (wnx - 2 * HALF_LENGTH_) * (wnz - 2 * HALF_LENGTH_);
/// General note: floating point operations for forward is the same as backward
/// (calculated below are for forward). number of floating point operations for
/// the pressure kernel in 2D for the half_length loop:6*k -2(for adding zeros)
/// =6*K-2 where K is the half_length 5 floating point operations outside the
/// half_length loop Total = 6*K-2+5 =6*K+3
int flops_per_pressure = 6 * HALF_LENGTH_ + 3;
// vel,curr,next,vel_x,vel_z
int num_of_arrays_pressure = 5;
/// General note: floating point operations for forward is the same as backward
/// (calculated below are for forward). number of floating point operations for
/// the velocity kernel in 2D for the half_length loop:6*k -2(for adding zeros)
/// =6*K-2 where K is the half_length 6 floating point operations outside the
/// half_length loop Total = 6*K-2+6 =6*K+4
int flops_per_velocity = 6 * HALF_LENGTH_ + 4;
// curr,den,vel_x(load),vel_x(store),vel_z(load),vel_z(store)
int num_of_arrays_velocity = 6;
/*
* Pre-compute the coefficients for each direction.
*/
float coefficients_x[HALF_LENGTH_];
float coefficients_z[HALF_LENGTH_];
int vertical[HALF_LENGTH_];
for (int i = 0; i < HALF_LENGTH_; i++) {
coefficients_x[i] = coefficients[i + 1];
coefficients_z[i] = coefficients[i + 1];
vertical[i] = (i + 1) * wnx;
}
// start the timers for the velocity kernel.
ElasticTimer timer("ComputationKernel::ComputeVelocity",
size,
num_of_arrays_velocity,
true,
flops_per_velocity);
timer.Start();
// Start the computation by creating the threads.
#pragma omp parallel default(shared)
{
float *prev, *next, *den, *vel, *vel_x, *vel_z;
/// Three loops for cache blocking.
/// Utilizing the cache to the maximum to speed up computation.
#pragma omp for schedule(static, 1) collapse(1)
for (int bz = HALF_LENGTH_; bz < nz_end; bz += block_z) {
for (int bx = HALF_LENGTH_; bx < nx_end; bx += block_x) {
/// Calculate the endings appropriately
/// (Handle remainder of the cache blocking loops).
int ixEnd = min(block_x, nx_end - bx);
int izEnd = min(bz + block_z, nz_end);
/// Loop on the elements in the block.
for (int iz = bz; iz < izEnd; ++iz) {
// Pre-compute in advance the pointer to the start of the current
// start point of the processing.
int offset = iz * wnx + bx;
prev = curr_base + offset;
den = den_base + offset;
vel = vel_base + offset;
vel_x = particle_vel_x + offset;
vel_z = particle_vel_z + offset;
#pragma vector aligned
#pragma vector vecremainder
#pragma omp simd
#pragma ivdep
for (int ix = 0; ix < ixEnd; ++ix) {
float value_x = 0;
float value_z = 0;
DERIVE_SEQ_AXIS(ix, 1, 0, -, prev, coefficients_x, value_x)
DERIVE_JUMP_AXIS(ix, wnx, 1, 0, -, prev, coefficients_z, value_z)
if constexpr (KERNEL_MODE_ != KERNEL_MODE::INVERSE) {
// 3 floating point operations
vel_x[ix] = vel_x[ix] - (den[ix] / dx) * value_x;
// 3 floating point operations
vel_z[ix] = vel_z[ix] - (den[ix] / dz) * value_z;
} else {
vel_x[ix] = vel_x[ix] + (den[ix] / dx) * value_x;
vel_z[ix] = vel_z[ix] + (den[ix] / dz) * value_z;
}
}
}
}
}
}
// the end of time of particle velocity kernel
timer.Stop();
}
template<KERNEL_MODE KERNEL_MODE_, bool IS_2D_, HALF_LENGTH HALF_LENGTH_>
void StaggeredComputationKernel::ComputePressure() {
/*
* Read parameters into local variables to be shared.
*/
float *curr_base = this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *next_base = this->mpGridBox->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
float *particle_vel_x = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_X)->GetNativePointer();
float *particle_vel_z = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_Z)->GetNativePointer();
float *vel_base = this->mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
float *den_base = this->mpGridBox->Get(PARM | WIND | GB_DEN)->GetNativePointer();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
float dx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
float dt = this->mpGridBox->GetDT();
float *coefficients = this->mpParameters->GetFirstDerivativeStaggeredFDCoefficient();
int block_x = this->mpParameters->GetBlockX();
int block_z = this->mpParameters->GetBlockZ();
int nx_end = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int nz_end = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int nx = wnx;
int nz = wnz;
int size = (wnx - 2 * HALF_LENGTH_) * (wnz - 2 * HALF_LENGTH_);
/// General note: floating point operations for forward is the same as backward
/// (calculated below are for forward). number of floating point operations for
/// the pressure kernel in 2D for the half_length loop:6*k -2(for adding zeros)
/// =6*K-2 where K is the half_length 5 floating point operations outside the
/// half_length loop Total = 6*K-2+5 =6*K+3
int flops_per_pressure = 6 * HALF_LENGTH_ + 3;
// vel,curr,next,vel_x,vel_z
int num_of_arrays_pressure = 5;
/*
* Pre-compute the coefficients for each direction.
*/
float coefficients_x[HALF_LENGTH_];
float coefficients_z[HALF_LENGTH_];
int vertical[HALF_LENGTH_];
for (int i = 0; i < HALF_LENGTH_; i++) {
coefficients_x[i] = coefficients[i + 1];
coefficients_z[i] = coefficients[i + 1];
vertical[i] = (i + 1) * wnx;
}
// start the timers for the velocity kernel.
ElasticTimer timer("ComputationKernel::ComputePressure",
size,
num_of_arrays_pressure,
true,
flops_per_pressure);
// start the timer of the pressure kernel
timer.Start();
#pragma omp parallel default(shared)
{
float *curr, *next, *den, *vel, *vel_x, *vel_z;
// Pressure Calculation
#pragma omp for schedule(static, 1) collapse(2)
for (int bz = HALF_LENGTH_; bz < nz_end; bz += block_z) {
for (int bx = HALF_LENGTH_; bx < nx_end; bx += block_x) {
// Calculate the endings appropriately (Handle remainder of the cache
// blocking loops).
int ixEnd = min(block_x, nx_end - bx);
int izEnd = min(bz + block_z, nz_end);
// Loop on the elements in the block.
for (int iz = bz; iz < izEnd; ++iz) {
// Pre-compute in advance the pointer to the start of the current
// start point of the processing.
int offset = iz * wnx + bx;
curr = curr_base + offset;
next = next_base + offset;
den = den_base + offset;
vel = vel_base + offset;
vel_x = particle_vel_x + offset;
vel_z = particle_vel_z + offset;
#pragma vector aligned
#pragma vector vecremainder
#pragma omp simd
#pragma ivdep
for (int ix = 0; ix < ixEnd; ++ix) {
float value_x = 0;
float value_z = 0;
DERIVE_SEQ_AXIS(ix, 0, 1, -, vel_x, coefficients_x, value_x)
DERIVE_JUMP_AXIS(ix, nx, 0, 1, -, vel_z, coefficients_z, value_z)
if constexpr (KERNEL_MODE_ != KERNEL_MODE::INVERSE) {
// 5 floating point operations
next[ix] =
curr[ix] - vel[ix] * ((value_x / dx) + (value_z / dz));
} else {
next[ix] =
curr[ix] + vel[ix] * ((value_x / dx) + (value_z / dz));
}
}
}
}
}
}
timer.Stop();
}
void StaggeredComputationKernel::PreprocessModel() {
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
float dt = this->mpGridBox->GetDT();
float dt2 = dt * dt;
float *velocity_values = this->mpGridBox->Get(PARM | GB_VEL)->GetNativePointer();
int full_nx = nx;
float *density_values = this->mpGridBox->Get(PARM | GB_DEN)->GetNativePointer();
/// Preprocess the velocity model by calculating the
/// dt * c2 * density component of the wave equation.
#pragma omp parallel default(shared)
{
#pragma omp for schedule(static) collapse(2)
for (int z = 0; z < nz; ++z) {
for (int x = 0; x < nx; ++x) {
float value = velocity_values[z * full_nx + x];
int offset = z * full_nx + x;
velocity_values[offset] =
value * value * dt * density_values[offset];
if (density_values[offset] != 0) {
density_values[offset] = dt / density_values[offset];
}
}
}
}
}
| 13,216
|
C++
|
.cpp
| 260
| 40.896154
| 115
| 0.601023
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,109
|
SpongeBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/boundary-managers/SpongeBoundaryManager.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <cmath>
#include <operations/components/independents/concrete/boundary-managers/SpongeBoundaryManager.hpp>
#include <operations/components/independents/concrete/boundary-managers/extensions/HomogenousExtension.hpp>
using namespace std;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
/// Based on
/// https://pubs.geoscienceworld.org/geophysics/article-abstract/50/4/705/71992/A-nonreflecting-boundary-condition-for-discrete?redirectedFrom=fulltext
void SpongeBoundaryManager::ApplyBoundaryOnField(float *next) {
/**
* Sponge boundary implementation.
**/
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lwnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lwnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
uint bound_length = mpParameters->GetBoundaryLength();
uint half_length = mpParameters->GetHalfLength();
float *sponge_coefficients = mpSpongeCoefficients->GetNativePointer();
#pragma omp parallel default(shared)
{
#pragma omp for schedule(static, 1) collapse(1)
for (int iz = half_length + bound_length - 1; iz >= half_length; iz--) {
#pragma ivdep
for (int ix = half_length + bound_length; ix <= lwnx - half_length - bound_length; ix++) {
next[iz * wnx + ix] *=
sponge_coefficients[iz - half_length];
next[(iz + wnz - 2 * iz - 1) * wnx + ix] *=
sponge_coefficients[iz - half_length];
}
}
}
#pragma omp parallel default(shared)
{
#pragma omp for schedule(static, 1) collapse(1)
for (int iz = half_length + bound_length; iz <= lwnz - half_length - bound_length; iz++) {
#pragma ivdep
for (int ix = half_length + bound_length - 1; ix >= half_length; ix--) {
next[iz * wnx + ix] *=
sponge_coefficients[ix - half_length];
next[iz * wnx + (ix + wnx - 2 * ix - 1)] *=
sponge_coefficients[ix - half_length];
}
}
}
int start_x = half_length;
int end_x = lwnx - half_length;
int start_z = half_length;
int end_z = lwnz - half_length;
// Zero-Corners in the boundaries wnx-wnz boundary intersection--boundaries not
// needed.
#pragma omp parallel default(shared)
{
#pragma omp for schedule(static, 1) collapse(1)
for (int row = 0; row < bound_length; row++) {
#pragma ivdep
for (int column = 0; column < bound_length; column++) {
/*!for values from z = half_length TO z = half_length +BOUND_LENGTH */
/*! and for x = half_length to x = half_length + BOUND_LENGTH */
/*! Top left boundary in other words */
next[(start_z + row) * wnx + column + start_x] *=
min(sponge_coefficients[column], sponge_coefficients[row]);
/*!for values from z = wnz-half_length TO z =
* wnz-half_length-BOUND_LENGTH*/
/*! and for x = half_length to x = half_length + BOUND_LENGTH */
/*! Bottom left boundary in other words */
next[(end_z - 1 - row) * wnx + column + start_x] *=
min(sponge_coefficients[column], sponge_coefficients[row]);
/*!for values from z = half_length TO z = half_length +BOUND_LENGTH */
/*! and for x = wnx-half_length to x = wnx-half_length - BOUND_LENGTH */
/*! Top right boundary in other words */
next[(start_z + row) * wnx + (end_x - 1 - column)] *=
min(sponge_coefficients[column], sponge_coefficients[row]);
/*!for values from z = wnz-half_length TO z =
* wnz-half_length-BOUND_LENGTH*/
/*! and for x = wnx-half_length to x = wnx - half_length - BOUND_LENGTH */
/*! Bottom right boundary in other words */
next[(end_z - 1 - row) * wnx + (end_x - 1 - column)] *=
min(sponge_coefficients[column], sponge_coefficients[row]);
}
}
}
}
| 5,117
|
C++
|
.cpp
| 103
| 41.009709
| 151
| 0.61958
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,110
|
CPMLBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/boundary-managers/CPMLBoundaryManager.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/components/independents/concrete/boundary-managers/CPMLBoundaryManager.hpp>
#include <operations/components/independents/concrete/computation-kernels/BaseComputationHelpers.hpp>
using namespace std;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
FORWARD_DECLARE_SINGLE_BOUND_TEMPLATE(CPMLBoundaryManager::CalculateFirstAuxiliary)
FORWARD_DECLARE_SINGLE_BOUND_TEMPLATE(CPMLBoundaryManager::CalculateCPMLValue)
template<int DIRECTION_, bool OPPOSITE_, int HALF_LENGTH_>
void CPMLBoundaryManager::CalculateFirstAuxiliary() {
int ix, iz;
float *curr_base = this->mpGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
int bound_length = this->mpParameters->GetBoundaryLength();
int block_x = this->mpParameters->GetBlockX();
int block_z = this->mpParameters->GetBlockZ();
int nxEnd = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int nzEnd = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_;
float *aux, *coeff_a, *coeff_b;
int z_start = HALF_LENGTH_;
int x_start = HALF_LENGTH_;
float *first_coeff_h;
int *distance;
float *first_coeff_h_1;
int *distance_1;
int WIDTH = bound_length + 2 * HALF_LENGTH_;
// decides the jump step for the stencil
if (DIRECTION_ == X_AXIS) {
coeff_a = mpCoeffax->GetNativePointer();
coeff_b = mpCoeffbx->GetNativePointer();
first_coeff_h = this->mpFirstCoeffx->GetNativePointer();
distance = this->mpDistanceDim1->GetNativePointer();
if (!OPPOSITE_) {
x_start = HALF_LENGTH_;
nxEnd = bound_length + HALF_LENGTH_;
aux = this->mpAux1xup->GetNativePointer();
} else {
x_start = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_ - bound_length;
nxEnd = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_;
aux = this->mpAux1xdown->GetNativePointer();
}
} else if (DIRECTION_ == Z_AXIS) {
coeff_a = this->mpCoeffaz->GetNativePointer();
coeff_b = this->mpCoeffbz->GetNativePointer();
first_coeff_h = this->mpFirstCoeffz->GetNativePointer();
distance = this->mpDistanceDim2->GetNativePointer();
if (!OPPOSITE_) {
z_start = HALF_LENGTH_;
nzEnd = bound_length + HALF_LENGTH_;
aux = this->mpAux1zup->GetNativePointer();
} else {
z_start = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_ - bound_length;
nzEnd = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_;
aux = this->mpAux1zdown->GetNativePointer();
}
} else {
throw bs::base::exceptions::UNSUPPORTED_FEATURE_EXCEPTION();
}
first_coeff_h_1 = &first_coeff_h[1];
distance_1 = &distance[1];
#pragma omp parallel default(shared)
{
#pragma omp for schedule(static, 1) collapse(1)
for (int bz = z_start; bz < nzEnd; bz += block_z) {
for (int bx = x_start; bx < nxEnd; bx += block_x) {
// Calculate the endings appropriately (Handle remainder of the cache
// blocking loops).
int ixEnd = min(bx + block_x, nxEnd);
int izEnd = min(bz + block_z, nzEnd);
for (iz = bz; iz < izEnd; iz++) {
int offset = iz * wnx;
float *curr = curr_base + offset;
#pragma ivdep
for (ix = bx; ix < ixEnd; ix++) {
float value = 0.0;
value = fma(curr[ix], first_coeff_h[0], value);
DERIVE_ARRAY_AXIS_EQ_OFF(ix, distance_1, -, curr, first_coeff_h_1, value)
int index = 0, coeff_ind = 0;
if (DIRECTION_ == X_AXIS) { // case x
if (OPPOSITE_) {
coeff_ind = ix - x_start;
index = iz * WIDTH + (ix - x_start + HALF_LENGTH_);
} else {
coeff_ind = bound_length - ix + HALF_LENGTH_ - 1;
index = iz * WIDTH + ix;
}
} else if (DIRECTION_ == Z_AXIS) { // case z
if (OPPOSITE_) {
coeff_ind = iz - z_start;
index = (iz - z_start + HALF_LENGTH_) * wnx + ix;
} else {
coeff_ind = bound_length - iz + HALF_LENGTH_ - 1;
index = iz * wnx + ix;
}
}
}
}
}
}
}
}
template<int direction, bool OPPOSITE_, int HALF_LENGTH_>
void CPMLBoundaryManager::CalculateCPMLValue() {
int ix, iz;
// direction 1 means in x , direction 2 means in z , else means in y;
float *curr_base = this->mpGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
float *next_base = this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
int bound_length = this->mpParameters->GetBoundaryLength();
int half_length = HALF_LENGTH_;
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
int block_x = this->mpParameters->GetBlockX();
int block_z = this->mpParameters->GetBlockZ();
float *vel_base = this->mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
int nxEnd = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - half_length;
int nzEnd = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - half_length;
float *aux_first, *aux_second, *coeff_a, *coeff_b;
int z_start = half_length;
int x_start = half_length;
int WIDTH = bound_length + 2 * half_length;
int *distance;
float *coeff_first_h;
float *coeff_h;
// decides the jump step for the stencil
if (direction == X_AXIS) {
coeff_a = this->mpCoeffax->GetNativePointer();
coeff_b = this->mpCoeffbx->GetNativePointer();
distance = this->mpDistanceDim1->GetNativePointer();
coeff_first_h = this->mpFirstCoeffx->GetNativePointer();
coeff_h = this->mpSecondCoeffx->GetNativePointer();
if (!OPPOSITE_) {
x_start = half_length;
nxEnd = bound_length + half_length;
aux_first = this->mpAux1xup->GetNativePointer();
aux_second = this->mpAux2xup->GetNativePointer();
} else {
x_start = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - half_length - bound_length;
nxEnd = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - half_length;
aux_first = this->mpAux1xdown->GetNativePointer();
aux_second = this->mpAux2xdown->GetNativePointer();
}
} else if (direction == Z_AXIS) {
coeff_a = this->mpCoeffaz->GetNativePointer();
coeff_b = this->mpCoeffbz->GetNativePointer();
distance = this->mpDistanceDim2->GetNativePointer();
coeff_first_h = this->mpFirstCoeffz->GetNativePointer();
coeff_h = this->mpSecondCoeffz->GetNativePointer();
if (!OPPOSITE_) {
z_start = half_length;
nzEnd = bound_length + half_length;
aux_first = this->mpAux1zup->GetNativePointer();
aux_second = this->mpAux2zup->GetNativePointer();
} else {
z_start = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - half_length - bound_length;
nzEnd = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - half_length;
aux_first = this->mpAux1zdown->GetNativePointer();
aux_second = this->mpAux2zdown->GetNativePointer();
}
} else {
throw bs::base::exceptions::UNSUPPORTED_FEATURE_EXCEPTION();
}
auto distance_1 = &distance[1];
auto coeff_h_1 = &coeff_h[1];
auto coeff_first_h_1 = &coeff_first_h[1];
#pragma omp parallel default(shared)
{
#pragma omp for schedule(static, 1) collapse(1)
for (int bz = z_start; bz < nzEnd; bz += block_z) {
for (int bx = x_start; bx < nxEnd; bx += block_x) {
// Calculate the endings appropriately (Handle remainder of the cache
// blocking loops).
int ixEnd = fmin(bx + block_x, nxEnd);
int izEnd = fmin(bz + block_z, nzEnd);
// Loop on the elements in the block.
for (iz = bz; iz < izEnd; ++iz) {
int offset = iz * wnx;
float *curr = curr_base + offset;
float *vel = vel_base + offset;
float *next = next_base + offset;
#pragma ivdep
for (ix = bx; ix < ixEnd; ix++) {
float pressure_value = 0.0;
float d_first_value = 0.0;
int index = 0;
int coeff_ind = 0;
float sum_val = 0.0;
float cpml_val = 0.0;
if (direction == X_AXIS) { // case x
if (OPPOSITE_) {
coeff_ind = ix - x_start;
index = iz * WIDTH + (ix - x_start + half_length);
} else {
coeff_ind = bound_length - ix + half_length - 1;
index = iz * WIDTH + ix;
}
} else if (direction == Z_AXIS) { // case z
if (OPPOSITE_) {
coeff_ind = iz - z_start;
index = (iz - z_start + half_length) * wnx + ix;
} else {
coeff_ind = bound_length - iz + half_length - 1;
index = iz * wnx + ix;
}
}
pressure_value = fma(curr[ix], coeff_h[0], pressure_value);
DERIVE_ARRAY_AXIS_EQ_OFF(ix, distance_1, +, curr, coeff_h_1, pressure_value)
// calculating the first derivative of the aux1
d_first_value = fma(aux_first[index], coeff_first_h[0], d_first_value);
DERIVE_ARRAY_AXIS_EQ_OFF(index, distance_1, -, aux_first, coeff_first_h_1,
d_first_value)
sum_val = d_first_value + pressure_value;
aux_second[index] = coeff_a[coeff_ind] * aux_second[index] +
coeff_b[coeff_ind] * sum_val;
cpml_val = vel[ix] * (d_first_value + aux_second[index]);
next[ix] += cpml_val;
}
}
}
}
}
}
| 12,591
|
C++
|
.cpp
| 244
| 38.67623
| 118
| 0.559399
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,111
|
StaggeredCPMLBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/boundary-managers/StaggeredCPMLBoundaryManager.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/components/independents/concrete/boundary-managers/StaggeredCPMLBoundaryManager.hpp>
#include <operations/components/independents/concrete/computation-kernels/BaseComputationHelpers.hpp>
using namespace std;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
FORWARD_DECLARE_BOUND_TEMPLATE(StaggeredCPMLBoundaryManager::CalculateVelocityFirstAuxiliary)
FORWARD_DECLARE_BOUND_TEMPLATE(StaggeredCPMLBoundaryManager::CalculateVelocityCPMLValue)
FORWARD_DECLARE_BOUND_TEMPLATE(StaggeredCPMLBoundaryManager::CalculatePressureFirstAuxiliary)
FORWARD_DECLARE_BOUND_TEMPLATE(StaggeredCPMLBoundaryManager::CalculatePressureCPMLValue)
template<bool ADJOINT_, int DIRECTION_, bool OPPOSITE_, int HALF_LENGTH_>
void StaggeredCPMLBoundaryManager::CalculateVelocityFirstAuxiliary() {
// Setup needed meta-information.
float dh;
if (DIRECTION_ == X_AXIS)
dh = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
else if (DIRECTION_ == Z_AXIS)
dh = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
else if (DIRECTION_ == Y_AXIS)
throw bs::base::exceptions::UNSUPPORTED_FEATURE_EXCEPTION();
float inv_dh = 1.0f / dh;
int z_start = HALF_LENGTH_;
int z_end = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int x_start = HALF_LENGTH_;
int x_end = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int b_l = mpParameters->GetBoundaryLength();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
// Set variables pointers.
float *aux_variable;
float *mpSmall_a;
float *mpSmall_b;
float *particle_velocity;
float *coeff = &mpParameters->GetFirstDerivativeStaggeredFDCoefficient()[1];
int aux_nx;
int aux_nz;
int jump;
switch (DIRECTION_) {
case X_AXIS:
x_end = HALF_LENGTH_ + b_l; //hl + bl
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_vel_x_right->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_vel_x_left->GetNativePointer();
}
particle_velocity = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_X)->GetNativePointer();
mpSmall_a = this->mpSmall_a_x->GetNativePointer();
mpSmall_b = this->mpSmall_b_x->GetNativePointer();
jump = 1;
aux_nx = b_l;
aux_nz = lnz - 2 * HALF_LENGTH_;
break;
case Z_AXIS:
z_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_vel_z_down->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_vel_z_up->GetNativePointer();
}
particle_velocity = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_Z)->GetNativePointer();
mpSmall_a = this->mpSmall_a_z->GetNativePointer();
mpSmall_b = this->mpSmall_b_z->GetNativePointer();
jump = wnx;
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = lnz - 2 * HALF_LENGTH_;
break;
default:
throw bs::base::exceptions::ILLOGICAL_EXCEPTION();
break;
}
// Compute.
#pragma omp parallel for collapse(2)
for (int j = z_start; j < z_end; ++j) {
for (int i = x_start; i < x_end; ++i) {
int active_bound_index;
int real_x = i;
int real_z = j;
float value = 0.0f;
// Setup indices for access.
if constexpr (DIRECTION_ == X_AXIS) {
active_bound_index = i;
if constexpr (OPPOSITE_) {
real_x = lnx - 1 - i;
}
} else if constexpr (DIRECTION_ == Z_AXIS) {
active_bound_index = j;
if constexpr (OPPOSITE_) {
real_z = lnz - 1 - j;
}
}
// Compute wanted derivative.
int offset;
offset = real_x + wnx * real_z;
DERIVE_JUMP_AXIS(offset, jump, 0, 1, -, particle_velocity, coeff, value)
int offset3 = b_l + HALF_LENGTH_ - 1 - active_bound_index;
int aux_offset = (i - HALF_LENGTH_) + (j - HALF_LENGTH_) * aux_nx;
aux_variable[aux_offset] =
mpSmall_a[offset3] *
aux_variable[aux_offset] +
mpSmall_b[offset3] * inv_dh *
value;
}
}
}
template<bool ADJOINT_, int DIRECTION_, bool OPPOSITE_, int HALF_LENGTH_>
void StaggeredCPMLBoundaryManager::CalculateVelocityCPMLValue() {
// Setup needed meta-information.
float dh;
if (DIRECTION_ == X_AXIS)
dh = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
else if (DIRECTION_ == Z_AXIS)
dh = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
else if (DIRECTION_ == Y_AXIS)
throw bs::base::exceptions::UNSUPPORTED_FEATURE_EXCEPTION();
//float dh_old = this->mpGridBox->GetCellDimensions(DIRECTION_);
float inv_dh = 1.0f / dh;
int z_start = HALF_LENGTH_;
int z_end = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int x_start = HALF_LENGTH_;
int x_end = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int b_l = mpParameters->GetBoundaryLength();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
// Set variables pointers.
float *aux_variable;
float *particle_velocity;
int aux_nx;
int aux_nz;
switch (DIRECTION_) {
case X_AXIS:
x_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_ptr_x_right->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_ptr_x_left->GetNativePointer();
}
particle_velocity = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_X)->GetNativePointer();
aux_nx = b_l;
aux_nz = lnz - 2 * HALF_LENGTH_;
break;
case Z_AXIS:
z_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_ptr_z_down->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_ptr_z_up->GetNativePointer();
}
particle_velocity = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_Z)->GetNativePointer();
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = lnz - 2 * HALF_LENGTH_;
break;
default:
throw bs::base::exceptions::ILLOGICAL_EXCEPTION();
break;
}
float *parameter_base;
parameter_base = this->mpGridBox->Get(PARM | WIND | GB_DEN)->GetNativePointer();
// Compute.
#pragma omp parallel for collapse(2)
for (int j = z_start; j < z_end; ++j) {
for (int i = x_start; i < x_end; ++i) {
int active_bound_index;
int real_x = i;
int real_z = j;
float value = 0.0f;
// Setup indices for access.
if constexpr (DIRECTION_ == X_AXIS) {
active_bound_index = i;
if constexpr (OPPOSITE_) {
real_x = lnx - 1 - i;
}
} else if constexpr (DIRECTION_ == Z_AXIS) {
active_bound_index = j;
if constexpr (OPPOSITE_) {
real_z = lnz - 1 - j;
}
}
// Compute wanted derivative.
int offset = real_x + wnx * real_z;
int aux_offset = (i - HALF_LENGTH_) + (j - HALF_LENGTH_) * aux_nx;
particle_velocity[offset] =
particle_velocity[offset] -
parameter_base[offset] * aux_variable[aux_offset];
}
}
}
template<bool ADJOINT_, int DIRECTION_, bool OPPOSITE_, int HALF_LENGTH_>
void StaggeredCPMLBoundaryManager::CalculatePressureFirstAuxiliary() {
// Setup needed meta-information.
float dh;
if (DIRECTION_ == X_AXIS)
dh = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
else if (DIRECTION_ == Z_AXIS)
dh = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
else if (DIRECTION_ == Y_AXIS)
throw bs::base::exceptions::UNSUPPORTED_FEATURE_EXCEPTION();
// float dh_old = this->mpGridBox->GetCellDimensions(DIRECTION_);
float *curr_base = this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float inv_dh = 1.0f / dh;
int z_start = HALF_LENGTH_;
int z_end = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int x_start = HALF_LENGTH_;
int x_end = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int b_l = mpParameters->GetBoundaryLength();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
// Set variables pointers.
float *aux_variable;
float *mpSmall_a;
float *mpSmall_b;
float *coeff = &mpParameters->GetFirstDerivativeStaggeredFDCoefficient()[1];
int aux_nx;
int aux_nz;
int jump;
switch (DIRECTION_) {
case X_AXIS:
x_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_ptr_x_right->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_ptr_x_left->GetNativePointer();
}
mpSmall_a = this->mpSmall_a_x->GetNativePointer();
mpSmall_b = this->mpSmall_b_x->GetNativePointer();
jump = 1;
aux_nx = b_l;
aux_nz = lnz - 2 * HALF_LENGTH_;
break;
case Z_AXIS:
z_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_ptr_z_down->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_ptr_z_up->GetNativePointer();
}
mpSmall_a = this->mpSmall_a_z->GetNativePointer();
mpSmall_b = this->mpSmall_b_z->GetNativePointer();
jump = wnx;
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = lnz - 2 * HALF_LENGTH_;
break;
default:
throw bs::base::exceptions::ILLOGICAL_EXCEPTION();
break;
}
// Compute.
#pragma omp parallel for collapse(2)
for (int j = z_start; j < z_end; ++j) {
for (int i = x_start; i < x_end; ++i) {
int active_bound_index;
int real_x = i;
int real_z = j;
float value = 0.0f;
// Setup indices for access.
if constexpr (DIRECTION_ == X_AXIS) {
active_bound_index = i;
if constexpr (OPPOSITE_) {
real_x = lnx - 1 - i;
}
} else if constexpr (DIRECTION_ == Z_AXIS) {
active_bound_index = j;
if constexpr (OPPOSITE_) {
real_z = lnz - 1 - j;
}
}
// Compute wanted derivative.
int offset;
offset = real_x + wnx * real_z;
DERIVE_JUMP_AXIS(offset, jump, 1, 0, -, curr_base, coeff, value)
int offset3 = b_l + HALF_LENGTH_ - 1 - active_bound_index;
int aux_offset = (i - HALF_LENGTH_) + (j - HALF_LENGTH_) * aux_nx;
aux_variable[aux_offset] =
mpSmall_a[offset3] *
aux_variable[aux_offset] +
mpSmall_b[offset3] * inv_dh *
value;
}
}
}
template<bool ADJOINT_, int DIRECTION_, bool OPPOSITE_, int HALF_LENGTH_>
void StaggeredCPMLBoundaryManager::CalculatePressureCPMLValue() {
// Setup needed meta-information.
int z_start = HALF_LENGTH_;
int z_end = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int x_start = HALF_LENGTH_;
int x_end = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int b_l = mpParameters->GetBoundaryLength();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
// Set variables pointers.
float *aux_variable;
int aux_nx;
int aux_nz;
switch (DIRECTION_) {
case X_AXIS:
x_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_vel_x_right->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_vel_x_left->GetNativePointer();
}
aux_nx = b_l;
aux_nz = lnz - 2 * HALF_LENGTH_;
break;
case Y_AXIS:
throw bs::base::exceptions::UNSUPPORTED_FEATURE_EXCEPTION();
case Z_AXIS:
z_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_vel_z_down->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_vel_z_up->GetNativePointer();
}
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = lnz - 2 * HALF_LENGTH_;
break;
default:
throw bs::base::exceptions::ILLOGICAL_EXCEPTION();
break;
}
float *parameter_base;
parameter_base = this->mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
float *curr_base = this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
// Compute.
#pragma omp parallel for collapse(2)
for (int j = z_start; j < z_end; ++j) {
for (int i = x_start; i < x_end; ++i) {
int real_x = i;
int real_z = j;
// Setup indices for access.
if constexpr (DIRECTION_ == X_AXIS) {
if constexpr (OPPOSITE_) {
real_x = lnx - 1 - i;
}
} else if constexpr (DIRECTION_ == Z_AXIS) {
if constexpr (OPPOSITE_) {
real_z = lnz - 1 - j;
}
}
// Compute wanted derivative.
int offset = real_x + wnx * real_z;
int aux_offset = (i - HALF_LENGTH_) + (j - HALF_LENGTH_) * aux_nx;
curr_base[offset] =
curr_base[offset] -
parameter_base[offset] * aux_variable[aux_offset];
}
}
}
| 16,407
|
C++
|
.cpp
| 374
| 33.933155
| 105
| 0.582937
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,112
|
RandomExtension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/boundary-managers/extensions/RandomExtension.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/components/independents/concrete/boundary-managers/extensions/RandomExtension.hpp>
using namespace std;
using namespace operations::components;
using namespace operations::components::addons;
using namespace bs::base::exceptions;
void RandomExtension::VelocityExtensionHelper(float *apPropertyArray,
int aStartX, int aStartY, int aStartZ,
int aEndX, int aEndY, int aEndZ,
int aNx, int aNy, int aNz,
uint aBoundaryLength) {
/*
* initialize values required for grain computing
*/
int dx = mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
int dy = mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
int dz = mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
int grain_side_length = this->mGrainSideLength; // in meters
int stride_x = grain_side_length / dx;
int stride_z = grain_side_length / dz;
int stride_y = 0;
if (aNy != 1) {
stride_y = grain_side_length / dy;
}
/*
* compute maximum value of the property
*/
float max_velocity = 0;
max_velocity = *max_element(apPropertyArray, apPropertyArray + aNx * aNy * aNz);
/*
* processing boundaries in X dimension "left and right bounds"
*/
/*
* populate random seeds
*/
vector<Point3D> seeds;
float temp = 0;
for (int row = aStartZ + aBoundaryLength; row < aEndZ - aBoundaryLength; row += stride_z) {
for (int column = 0; column < aBoundaryLength; column += stride_x) {
int index = row * aNx + column + aStartX;
temp = GET_RANDOM_VALUE(aBoundaryLength, column) * max_velocity;
apPropertyArray[index] = abs(apPropertyArray[row * aNx + aBoundaryLength + aStartX] - temp);
seeds.push_back(Point3D(column + aStartX, 1, row));
index = row * aNx + (aEndX - column - 1);
temp = GET_RANDOM_VALUE(aBoundaryLength, column) * max_velocity;
apPropertyArray[index] = abs(apPropertyArray[row * aNx + (aEndX - 1 - aBoundaryLength)] - temp);
seeds.push_back(Point3D((aEndX - column - 1), 1, row));
}
}
/*
* fill empty points
*/
for (int row = aStartZ + aBoundaryLength; row < aEndZ - aBoundaryLength; row++) {
for (int column = 0; column < aBoundaryLength; column++) {
Point3D left_point(column + aStartX, 1, row);
Point3D right_point((aEndX - column - 1), 1, row);
/*
* check if this point is a seed point
* same check works for both left and right points
*/
bool is_seed = false;
for (auto seed : seeds) {
if (left_point == seed) {
is_seed = true;
break;
}
}
if (is_seed) {
continue; // this is a seed point, don't fill
}
Point3D left_point_seed(0, 0, 0);
Point3D right_point_seed(0, 0, 0);
/*
* Get nearest seed
*/
for (auto seed : seeds) {
if (
(seed.x <= left_point.x) && (seed.x + stride_x > left_point.x) &&
(seed.z <= left_point.z) && (seed.z + stride_z > left_point.z)
) {
left_point_seed = seed;
}
if (
(seed.x >= right_point.x) && (seed.x - stride_x < right_point.x) &&
(seed.z <= right_point.z) && (seed.z + stride_z > right_point.z)
) {
right_point_seed = seed;
}
}
/*
* populate left point
*/
int id_x;
int id_z;
float px = RANDOM_VALUE;
float pz = RANDOM_VALUE;
float denom_x = (float) (left_point.x - left_point_seed.x) / stride_x;
float denom_z = (float) (left_point.z - left_point_seed.z) / stride_z;
if ((px <= denom_x) && (pz <= denom_z)) {
id_x = left_point_seed.x + stride_x;
id_z = left_point_seed.z + stride_z;
} else if ((px <= denom_x) && (pz > denom_z)) {
id_x = left_point_seed.x + stride_x;
id_z = left_point_seed.z;
} else if ((px > denom_x) && (pz <= denom_z)) {
id_x = left_point_seed.x;
id_z = left_point_seed.z + stride_z;
} else if ((px > denom_x) && (pz > denom_z)) {
id_x = left_point_seed.x;
id_z = left_point_seed.z;
}
if (id_z >= aEndZ - aBoundaryLength) {
id_z = left_point_seed.z;
}
apPropertyArray[left_point.z * aNx + left_point.x] = apPropertyArray[id_z * aNx + id_x];
/*
* populate right point
*/
px = RANDOM_VALUE;
pz = RANDOM_VALUE;
denom_x = (float) (right_point_seed.x - right_point.x) / stride_x;
denom_z = (float) (right_point.z - right_point_seed.z) / stride_z;
if ((px >= denom_x) && (pz <= denom_z)) {
id_x = right_point_seed.x;
id_z = right_point_seed.z + stride_z;
} else if ((px >= denom_x) && (pz > denom_z)) {
id_x = right_point_seed.x;
id_z = right_point_seed.z;
} else if ((px < denom_x) && (pz <= denom_z)) {
id_x = right_point_seed.x - stride_x;
id_z = right_point_seed.z + stride_z;
} else if ((px < denom_x) && (pz > denom_z)) {
id_x = right_point_seed.x - stride_x;
id_z = right_point_seed.z;
}
if (id_x >= aEndX) {
id_x = right_point_seed.x;
}
if (id_z >= aEndZ - aBoundaryLength) {
id_z = right_point_seed.z;
}
apPropertyArray[right_point.z * aNx + right_point.x] = apPropertyArray[id_z * aNx + id_x];
}
}
seeds.clear();
/*
* processing boundaries in Z dimension "bottom bound"
*/
/*
* populate random seeds
*/
for (int row = 0; row < aBoundaryLength; row += stride_z) {
for (int column = aStartX; column < aEndX; column += stride_x) {
int index = (aEndZ - row - 1) * aNx + column;
temp = GET_RANDOM_VALUE(aBoundaryLength, row) * max_velocity;
apPropertyArray[index] = abs(apPropertyArray[(aEndZ - 1 - aBoundaryLength) * aNx + column] - temp);
seeds.push_back(Point3D(column, 1, (aEndZ - row - 1)));
}
}
/*
* fill empty points
*/
for (int row = 0; row < aBoundaryLength; row++) {
for (int column = aStartX; column < aEndX; column++) {
Point3D bottom_point(column, 1, (aEndZ - row - 1));
/*
* check if this point is a seed point
*/
bool is_seed = false;
for (auto seed:seeds) {
if (bottom_point == seed) {
is_seed = true;
break;
}
}
if (is_seed) {
continue; // this is a seed point, don't fill
}
Point3D bottom_point_seed(0, 0, 0);
/*
* Get nearest seed
*/
for (auto seed:seeds) {
if (
(seed.x <= bottom_point.x) && (seed.x + stride_x > bottom_point.x) &&
(seed.z >= bottom_point.z) && (seed.z - stride_z < bottom_point.z)
) {
bottom_point_seed = seed;
}
}
/*
* populate left point
*/
int id_x;
int id_z;
float px = RANDOM_VALUE;
float pz = RANDOM_VALUE;
float denom_x = (float) (bottom_point.x - bottom_point_seed.x) / stride_x;
float denom_z = (float) (bottom_point_seed.z - bottom_point.z) / stride_z;
if ((px <= denom_x) && (pz >= denom_z)) {
id_x = bottom_point_seed.x + stride_x;
id_z = bottom_point_seed.z;
} else if ((px <= denom_x) && (pz < denom_z)) {
id_x = bottom_point_seed.x + stride_x;
id_z = bottom_point_seed.z - stride_z;
} else if ((px > denom_x) && (pz >= denom_z)) {
id_x = bottom_point_seed.x;
id_z = bottom_point_seed.z;
} else if ((px > denom_x) && (pz < denom_z)) {
id_x = bottom_point_seed.x;
id_z = bottom_point_seed.z - stride_z;
}
if (id_z >= aEndZ) {
id_z = bottom_point_seed.z;
}
apPropertyArray[bottom_point.z * aNx + bottom_point.x] = apPropertyArray[id_z * aNx + id_x];
}
}
seeds.clear();
}
void RandomExtension::TopLayerExtensionHelper(float *property_array,
int aStartX, int aStartY, int aStartZ,
int aEndX, int aEndY, int aEndZ,
int aNx, int aNy, int aNz, uint aBoundaryLength) {
// Do nothing, no top layer to extend in random boundaries.
}
void RandomExtension::TopLayerRemoverHelper(float *property_array,
int aStartX, int aStartY, int aStartZ,
int aEndX, int aEndY, int aEndZ,
int aNx, int aNy, int aNz, uint aBoundaryLength) {
// Do nothing, no top layer to remove in random boundaries.
}
| 10,809
|
C++
|
.cpp
| 249
| 30.477912
| 111
| 0.502332
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,113
|
MinExtension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/boundary-managers/extensions/MinExtension.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <cstdlib>
#include <operations/components/independents/concrete/boundary-managers/extensions/MinExtension.hpp>
using namespace std;
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::dataunits;
void MinExtension::VelocityExtensionHelper(float *property_array,
int start_x, int start_y, int start_z,
int end_x, int end_y, int end_z,
int nx, int ny, int nz,
uint boundary_length) {
/*!
* change the values of velocities at boundaries (HALF_LENGTH excluded) to
* zeros the start for x , y and z is at HALF_LENGTH and the end is at (nx -
* HALF_LENGTH) or (ny - HALF_LENGTH) or (nz- HALF_LENGTH)
*/
int nz_nx = nx * nz;
float target_velocity = 100000.0f, temp = 0;
// In case of 2D
if (ny == 1) {
end_y = 1;
start_y = 0;
// Get maximum property_array value in 2D domain.
for (int row = start_z + boundary_length; row < end_z - boundary_length;
row++) {
for (int column = start_x + boundary_length;
column < end_x - boundary_length; column++) {
target_velocity =
min(target_velocity, property_array[row * nx + column]);
}
}
} else {
// Get maximum property_array value.
for (int depth = start_y + boundary_length; depth < end_y - boundary_length;
depth++) {
for (int row = start_z + boundary_length; row < end_z - boundary_length;
row++) {
for (int column = start_x + boundary_length;
column < end_x - boundary_length; column++) {
target_velocity =
min(target_velocity,
property_array[depth * nz_nx + row * nx + column]);
}
}
}
// general case for 3D
/*!putting random values for velocities at the boundaries for y and with all
* x and z */
for (int depth = 0; depth < boundary_length; depth++) {
for (int row = start_z; row < end_z; row++) {
for (int column = start_x; column < end_x; column++) {
/*!for values from y = HALF_LENGTH TO y = HALF_LENGTH +BOUND_LENGTH*/
property_array[(depth + start_y) * nz_nx + row * nx + column] =
target_velocity;
/*!for values from y = ny-HALF_LENGTH TO y =
* ny-HALF_LENGTH-BOUND_LENGTH*/
property_array[(end_y - 1 - depth) * nz_nx + row * nx + column] =
target_velocity;
}
}
}
}
/*!putting random values for velocities at the boundaries for X and with all Y
* and Z */
for (int depth = start_y; depth < end_y; depth++) {
for (int row = start_z; row < end_z; row++) {
for (int column = 0; column < boundary_length; column++) {
/*!for values from x = HALF_LENGTH TO x= HALF_LENGTH +BOUND_LENGTH*/
property_array[depth * nz_nx + row * nx + column + start_x] =
target_velocity;
/*!for values from x = nx-HALF_LENGTH TO x =
* nx-HALF_LENGTH-BOUND_LENGTH*/
property_array[depth * nz_nx + row * nx + (end_x - 1 - column)] =
target_velocity;
}
}
}
/*!putting random values for velocities at the boundaries for z and with all x
* and y */
for (int depth = start_y; depth < end_y; depth++) {
for (int row = 0; row < boundary_length; row++) {
for (int column = start_x; column < end_x; column++) {
/*!for values from z = HALF_LENGTH TO z = HALF_LENGTH +BOUND_LENGTH */
// Remove top layer boundary : give value as zero since having top layer
// random boundaries will introduce too much noise.
property_array[depth * nz_nx + (start_z + row) * nx + column] = 0;
// If we want random, give this value :
// property_array[depth * nz_nx + (start_z + boundary_length) * nx +
// column] - temp;
/*!for values from z = nz-HALF_LENGTH TO z =
* nz-HALF_LENGTH-BOUND_LENGTH*/
property_array[depth * nz_nx + (end_z - 1 - row) * nx + column] =
target_velocity;
}
}
}
uint offset = 0;
// Random-Corners in the boundaries nx-nz boundary intersection at bottom--
// top boundaries not needed.
for (int depth = start_y; depth < end_y; depth++) {
for (int row = 0; row < boundary_length; row++) {
for (int column = 0; column < boundary_length; column++) {
offset = min(row, column);
/*!for values from z = HALF_LENGTH TO z = HALF_LENGTH +BOUND_LENGTH */
/*! and for x = HALF_LENGTH to x = HALF_LENGTH + BOUND_LENGTH */
/*! Top left boundary in other words */
property_array[depth * nz_nx + (start_z + row) * nx + column +
start_x] = 0;
/*!for values from z = nz-HALF_LENGTH TO z =
* nz-HALF_LENGTH-BOUND_LENGTH*/
/*! and for x = HALF_LENGTH to x = HALF_LENGTH + BOUND_LENGTH */
/*! Bottom left boundary in other words */
property_array[depth * nz_nx + (end_z - 1 - row) * nx + column +
start_x] = target_velocity;
/*!for values from z = HALF_LENGTH TO z = HALF_LENGTH +BOUND_LENGTH */
/*! and for x = nx-HALF_LENGTH to x = nx-HALF_LENGTH - BOUND_LENGTH */
/*! Top right boundary in other words */
property_array[depth * nz_nx + (start_z + row) * nx +
(end_x - 1 - column)] = 0;
/*!for values from z = nz-HALF_LENGTH TO z =
* nz-HALF_LENGTH-BOUND_LENGTH*/
/*! and for x = nx-HALF_LENGTH to x = nx - HALF_LENGTH - BOUND_LENGTH */
/*! Bottom right boundary in other words */
property_array[depth * nz_nx + (end_z - 1 - row) * nx +
(end_x - 1 - column)] = target_velocity;
}
}
}
// If 3-D, zero corners in the y-x and y-z plans.
if (ny > 1) {
// Random-Corners in the boundaries ny-nz boundary intersection at bottom--
// top boundaries not needed.
for (int depth = 0; depth < boundary_length; depth++) {
for (int row = 0; row < boundary_length; row++) {
for (int column = start_x; column < end_x; column++) {
offset = min(row, depth);
/*!for values from z = HALF_LENGTH TO z = HALF_LENGTH +BOUND_LENGTH */
/*! and for y = HALF_LENGTH to y = HALF_LENGTH + BOUND_LENGTH */
property_array[(depth + start_y) * nz_nx + (start_z + row) * nx +
column] = 0;
/*!for values from z = nz-HALF_LENGTH TO z =
* nz-HALF_LENGTH-BOUND_LENGTH*/
/*! and for y = HALF_LENGTH to y = HALF_LENGTH + BOUND_LENGTH */
property_array[(depth + start_y) * nz_nx + (end_z - 1 - row) * nx +
column] = target_velocity;
/*!for values from z = HALF_LENGTH TO z = HALF_LENGTH +BOUND_LENGTH */
/*! and for y = ny-HALF_LENGTH to y = ny-HALF_LENGTH - BOUND_LENGTH */
property_array[(end_y - 1 - depth) * nz_nx + (start_z + row) * nx +
column] = 0;
/*!for values from z = nz-HALF_LENGTH TO z =
* nz-HALF_LENGTH-BOUND_LENGTH */
/*! and for y = ny-HALF_LENGTH to y = ny - HALF_LENGTH - BOUND_LENGTH
*/
property_array[(end_y - 1 - depth) * nz_nx + (end_z - 1 - row) * nx +
column] = target_velocity;
}
}
}
// Zero-Corners in the boundaries nx-ny boundary intersection on the top
// layer--boundaries not needed.
for (int depth = 0; depth < boundary_length; depth++) {
for (int row = start_z; row < start_z + boundary_length; row++) {
for (int column = 0; column < boundary_length; column++) {
/*!for values from y = HALF_LENGTH TO y = HALF_LENGTH +BOUND_LENGTH */
/*! and for x = HALF_LENGTH to x = HALF_LENGTH + BOUND_LENGTH */
property_array[(depth + start_y) * nz_nx + row * nx + column +
start_x] = 0;
/*!for values from y = ny-HALF_LENGTH TO y =
* ny-HALF_LENGTH-BOUND_LENGTH*/
/*! and for x = HALF_LENGTH to x = HALF_LENGTH + BOUND_LENGTH */
property_array[(end_y - 1 - depth) * nz_nx + row * nx + column +
start_x] = 0;
/*!for values from y = HALF_LENGTH TO y = HALF_LENGTH +BOUND_LENGTH */
/*! and for x = nx-HALF_LENGTH to x = nx-HALF_LENGTH - BOUND_LENGTH */
property_array[(depth + start_y) * nz_nx + row * nx +
(end_x - 1 - column)] = 0;
/*!for values from y = ny-HALF_LENGTH TO y =
* ny-HALF_LENGTH-BOUND_LENGTH*/
/*! and for x = nx-HALF_LENGTH to x = nx - HALF_LENGTH - BOUND_LENGTH
*/
property_array[(end_y - 1 - depth) * nz_nx + row * nx +
(end_x - 1 - column)] = 0;
}
}
}
// Random-Corners in the boundaries nx-ny boundary intersection.
for (int depth = 0; depth < boundary_length; depth++) {
for (int row = start_z + boundary_length; row < end_z; row++) {
for (int column = 0; column < boundary_length; column++) {
offset = min(column, depth);
/*!for values from y = HALF_LENGTH TO y = HALF_LENGTH +BOUND_LENGTH */
/*! and for x = HALF_LENGTH to x = HALF_LENGTH + BOUND_LENGTH */
property_array[(depth + start_y) * nz_nx + row * nx + column +
start_x] = target_velocity;
/*!for values from y = ny-HALF_LENGTH TO y =
* ny-HALF_LENGTH-BOUND_LENGTH*/
/*! and for x = HALF_LENGTH to x = HALF_LENGTH + BOUND_LENGTH */
property_array[(end_y - 1 - depth) * nz_nx + row * nx + column +
start_x] = target_velocity;
/*!for values from y = HALF_LENGTH TO y = HALF_LENGTH +BOUND_LENGTH */
/*! and for x = nx-HALF_LENGTH to x = nx-HALF_LENGTH - BOUND_LENGTH */
property_array[(depth + start_y) * nz_nx + row * nx +
(end_x - 1 - column)] = target_velocity;
/*!for values from y = ny-HALF_LENGTH TO y =
* ny-HALF_LENGTH-BOUND_LENGTH*/
/*! and for x = nx-HALF_LENGTH to x = nx - HALF_LENGTH - BOUND_LENGTH
*/
property_array[(end_y - 1 - depth) * nz_nx + row * nx +
(end_x - 1 - column)] = target_velocity;
}
}
}
}
}
void MinExtension::TopLayerExtensionHelper(float *property_array,
int start_x, int start_z,
int start_y, int end_x, int end_y,
int end_z, int nx, int nz, int ny,
uint boundary_length) {
// Do nothing, no top layer to extend in random boundaries.
}
void MinExtension::TopLayerRemoverHelper(float *property_array, int start_x,
int start_z, int start_y, int end_x,
int end_y, int end_z, int nx,
int nz, int ny,
uint boundary_length) {
// Do nothing, no top layer to remove in random boundaries.
}
| 13,549
|
C++
|
.cpp
| 247
| 38.708502
| 100
| 0.492103
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,114
|
ZeroExtension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/boundary-managers/extensions/ZeroExtension.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/components/independents/concrete/boundary-managers/extensions/ZeroExtension.hpp>
using namespace std;
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::dataunits;
void ZeroExtension::VelocityExtensionHelper(float *property_array,
int start_x, int start_y, int start_z,
int end_x, int end_y, int end_z,
int nx, int ny, int nz,
uint boundary_length) {
/**
* Change the values of velocities at boundaries (HALF_LENGTH excluded) to
* zeros the start for x, y and z is at HALF_LENGTH and the end is at
* (nx - HALF_LENGTH) or (ny - HALF_LENGTH) or (nz- HALF_LENGTH)
*/
int nz_nx = nx * nz;
// In case of 2D
if (ny == 1) {
start_y = 0;
end_y = 1;
} else {
/// General case for 3D
/**
* Putting zero values for velocities at the boundaries for
* y and with all x and z
*/
for (int depth = 0; depth < boundary_length; depth++) {
for (int row = start_z; row < end_z; row++) {
for (int column = start_x; column < end_x; column++) {
/**
* For values from y = HALF_LENGTH
* TO y = HALF_LENGTH + BOUND_LENGTH
*/
property_array[(depth + start_y) * nz_nx + row * nx + column] = 0;
/**
* For values from y = ny - HALF_LENGTH
* TO y = ny - HALF_LENGTH - BOUND_LENGTH
*/
property_array[(end_y - 1 - depth) * nz_nx + row * nx + column] = 0;
}
}
}
}
/**
* Putting zero values for velocities at the boundaries for
* X and with all Y and Z
*/
for (int depth = start_y; depth < end_y; depth++) {
for (int row = start_z; row < end_z; row++) {
for (int column = 0; column < boundary_length; column++) {
/**
* For values from x = HALF_LENGTH
* TO x= HALF_LENGTH + BOUND_LENGTH
*/
property_array[depth * nz_nx + row * nx + column + start_x] = 0;
/**
* For values from x = nx - HALF_LENGTH
* TO x = nx - HALF_LENGTH - BOUND_LENGTH
*/
property_array[depth * nz_nx + row * nx + (end_x - 1 - column)] = 0;
}
}
}
/**
* Putting zero values for velocities at the boundaries
* for z and with all x and y
*/
for (int depth = start_y; depth < end_y; depth++) {
for (int row = 0; row < boundary_length; row++) {
for (int column = start_x; column < end_x; column++) {
/**
* For values from z = HALF_LENGTH
* TO z = HALF_LENGTH + BOUND_LENGTH
*/
property_array[depth * nz_nx + (start_z + row) * nx + column] = 0;
/**
* For values from z = nz - HALF_LENGTH
* TO z = nz - HALF_LENGTH - BOUND_LENGTH
*/
property_array[depth * nz_nx + (end_z - 1 - row) * nx + column] = 0;
}
}
}
}
void ZeroExtension::TopLayerExtensionHelper(float *property_array,
int start_x, int start_y, int start_z,
int end_x, int end_y, int end_z,
int nx, int ny, int nz, uint boundary_length) {
// Do nothing, no top layer to extend in random boundaries.
}
void ZeroExtension::TopLayerRemoverHelper(float *property_array, int start_x,
int start_z, int start_y,
int end_x, int end_y, int end_z,
int nx, int nz, int ny,
uint boundary_length) {
// Do nothing, no top layer to remove in random boundaries.
}
| 5,015
|
C++
|
.cpp
| 115
| 30.834783
| 101
| 0.511443
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,115
|
HomogenousExtension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp/boundary-managers/extensions/HomogenousExtension.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/components/independents/concrete/boundary-managers/extensions/HomogenousExtension.hpp>
using namespace std;
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::dataunits;
HomogenousExtension::HomogenousExtension(bool use_top_layer) {
this->mUseTop = use_top_layer;
}
void HomogenousExtension::VelocityExtensionHelper(float *property_array,
int start_x, int start_y, int start_z,
int end_x, int end_y, int end_z,
int nx, int ny, int nz,
uint boundary_length) {
/*!
* change the values of velocities at boundaries (HALF_LENGTH excluded) to
* zeros the start for x , y and z is at HALF_LENGTH and the end is at (nx -
* HALF_LENGTH) or (ny - HALF_LENGTH) or (nz- HALF_LENGTH)
*/
int nz_nx = nx * nz;
// In case of 2D
if (ny == 1) {
end_y = 1;
start_y = 0;
} else {
// general case for 3D
/*!putting the nearest property_array adjacent to the boundary as the value
* for all velocities at the boundaries for y and with all x and z */
for (int depth = 0; depth < boundary_length; depth++) {
for (int row = start_z; row < end_z; row++) {
for (int column = start_x; column < end_x; column++) {
/*!for values from y = HALF_LENGTH TO y = HALF_LENGTH +BOUND_LENGTH*/
property_array[(depth + start_y) * nz_nx + row * nx + column] =
property_array[(boundary_length + start_y) * nz_nx + row * nx +
column];
/*!for values from y = ny-HALF_LENGTH TO y =
* ny-HALF_LENGTH-BOUND_LENGTH*/
property_array[(end_y - 1 - depth) * nz_nx + row * nx + column] =
property_array[(end_y - 1 - boundary_length) * nz_nx + row * nx +
column];
}
}
}
}
/*!putting the nearest property_array adjacent to the boundary as the value
* for all velocities at the boundaries for x and with all z and y */
for (int depth = start_y; depth < end_y; depth++) {
for (int row = start_z; row < end_z; row++) {
for (int column = 0; column < boundary_length; column++) {
/*!for values from x = HALF_LENGTH TO x= HALF_LENGTH +BOUND_LENGTH*/
property_array[depth * nz_nx + row * nx + column + start_x] =
property_array[depth * nz_nx + row * nx + boundary_length +
start_x];
/*!for values from x = nx-HALF_LENGTH TO x =
* nx-HALF_LENGTH-BOUND_LENGTH*/
property_array[depth * nz_nx + row * nx + (end_x - 1 - column)] =
property_array[depth * nz_nx + row * nx +
(end_x - 1 - boundary_length)];
}
}
}
if (this->mUseTop) {
/*!putting the nearest property_array adjacent to the boundary as the value
* for all velocities at the boundaries for z and with all x and y */
for (int depth = start_y; depth < end_y; depth++) {
for (int row = 0; row < boundary_length; row++) {
for (int column = start_x; column < end_x; column++) {
/*!for values from z = HALF_LENGTH TO z = HALF_LENGTH +BOUND_LENGTH */
property_array[depth * nz_nx + (start_z + row) * nx + column] =
property_array[depth * nz_nx + (start_z + boundary_length) * nx +
column];
/*!for values from z = nz-HALF_LENGTH TO z =
* nz-HALF_LENGTH-BOUND_LENGTH*/
property_array[depth * nz_nx + (end_z - 1 - row) * nx + column] =
property_array[depth * nz_nx +
(end_z - 1 - boundary_length) * nx + column];
}
}
}
} else {
/*!putting the nearest property_array adjacent to the boundary as the value
* for all velocities at the boundaries for z and with all x and y */
for (int depth = start_y; depth < end_y; depth++) {
for (int row = 0; row < boundary_length; row++) {
for (int column = start_x; column < end_x; column++) {
/*!for values from z = nz-HALF_LENGTH TO z =
* nz-HALF_LENGTH-BOUND_LENGTH*/
property_array[depth * nz_nx + (end_z - 1 - row) * nx + column] =
property_array[depth * nz_nx +
(end_z - 1 - boundary_length) * nx + column];
}
}
}
}
}
void HomogenousExtension::TopLayerExtensionHelper(float *property_array,
int start_x, int start_y, int start_z,
int end_x, int end_y, int end_z,
int nx, int ny, int nz, uint boundary_length) {
if (this->mUseTop) {
int nz_nx = nx * nz;
/*!putting the nearest property_array adjacent to the boundary as the value
* for all velocities at the boundaries for z and with all x and y */
for (int depth = start_y; depth < end_y; depth++) {
for (int row = 0; row < boundary_length; row++) {
for (int column = start_x; column < end_x; column++) {
/*!for values from z = HALF_LENGTH TO z = HALF_LENGTH +BOUND_LENGTH */
property_array[depth * nz_nx + (start_z + row) * nx + column] =
property_array[depth * nz_nx + (start_z + boundary_length) * nx +
column];
}
}
}
}
}
void HomogenousExtension::TopLayerRemoverHelper(float *property_array,
int start_x, int start_y, int start_z,
int end_x, int end_y, int end_z,
int nx, int ny, int nz, uint boundary_length) {
if (this->mUseTop) {
int nz_nx = nx * nz;
/*!putting the nearest property_array adjacent to the boundary as the value
* for all velocities at the boundaries for z and with all x and y */
for (int depth = start_y; depth < end_y; depth++) {
for (int row = 0; row < boundary_length; row++) {
for (int column = start_x; column < end_x; column++) {
/*!for values from z = HALF_LENGTH TO z = HALF_LENGTH +BOUND_LENGTH */
property_array[depth * nz_nx + (start_z + row) * nx + column] = 0;
}
}
}
}
}
| 7,922
|
C++
|
.cpp
| 150
| 37.74
| 107
| 0.512619
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,116
|
CrossCorrelationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/migration-accommodators/CrossCorrelationKernel.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <omp.h>
#include <vector>
#include <cmath>
#include <operations/components/independents/concrete/migration-accommodators/CrossCorrelationKernel.hpp>
#define EPSILON 1e-20
using namespace std;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
template void CrossCorrelationKernel::Correlation<true, NO_COMPENSATION>(GridBox *apGridBox);
template void CrossCorrelationKernel::Correlation<false, NO_COMPENSATION>(GridBox *apGridBox);
template void CrossCorrelationKernel::Correlation<true, COMBINED_COMPENSATION>(GridBox *apGridBox);
template void CrossCorrelationKernel::Correlation<false, COMBINED_COMPENSATION>(GridBox *apGridBox);
template void CrossCorrelationKernel::Stack<true, NO_COMPENSATION>();
template void CrossCorrelationKernel::Stack<false, NO_COMPENSATION>();
template void CrossCorrelationKernel::Stack<true, COMBINED_COMPENSATION>();
template void CrossCorrelationKernel::Stack<false, COMBINED_COMPENSATION>();
template<bool _IS_2D, COMPENSATION_TYPE _COMPENSATION_TYPE>
void CrossCorrelationKernel::Correlation(GridBox *apGridBox) {
GridBox *source_gridbox = apGridBox;
GridBox *receiver_gridbox = mpGridBox;
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
float *source_base = source_gridbox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *receiver_base = receiver_gridbox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *correlation_output_base = mpShotCorrelation->GetNativePointer();
float *source_i_base = mpSourceIllumination->GetNativePointer();
float *receive_i_base = mpReceiverIllumination->GetNativePointer();
uint offset = mpParameters->GetHalfLength();
int nxEnd = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - offset;
int nyEnd;
int nzEnd = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - offset;
int y_start = 0;
if (!_IS_2D) {
y_start = offset;
nyEnd = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - offset;
} else {
y_start = 0;
nyEnd = 1;
}
const uint block_x = mpParameters->GetBlockX();
const uint block_y = mpParameters->GetBlockY();
const uint block_z = mpParameters->GetBlockZ();
int device_num = omp_get_default_device();
#pragma omp target is_device_ptr(source_base, receiver_base, correlation_output_base, source_i_base, receive_i_base) device(device_num)
#pragma omp teams distribute parallel for collapse(3)
for (int by = y_start; by < nyEnd; by += block_y) {
for (int bz = offset; bz < nzEnd; bz += block_z) {
for (int bx = offset; bx < nxEnd; bx += block_x) {
int izEnd = fmin(bz + block_z, nzEnd);
int iyEnd = fmin(by + block_y, nyEnd);
int ixEnd = fmin(block_x, nxEnd - bx);
float *src_ptr, *rec_ptr, *correlation_output, *source_i, *receive_i;
uint b_offset = 0;
float value = 0;
for (int iy = by; iy < iyEnd; ++iy) {
for (int iz = bz; iz < izEnd; ++iz) {
b_offset = iy * wnx * wnz + iz * wnx + bx;
src_ptr = source_base + b_offset;
rec_ptr = receiver_base + b_offset;
correlation_output = correlation_output_base + b_offset;
source_i = source_i_base + b_offset;
receive_i = receive_i_base + b_offset;
for (int ix = 0; ix < ixEnd; ++ix) {
value = src_ptr[ix] * rec_ptr[ix];
correlation_output[ix] += value;
if (_COMPENSATION_TYPE == COMBINED_COMPENSATION) {
source_i[ix] += src_ptr[ix] * src_ptr[ix];
receive_i[ix] += rec_ptr[ix] * rec_ptr[ix];
}
}
}
}
}
}
}
}
template<bool _IS_2D, COMPENSATION_TYPE _COMPENSATION_TYPE>
void CrossCorrelationKernel::Stack() {
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
int constant = this->mpGridBox->GetWindowStart(X_AXIS) +
this->mpGridBox->GetWindowStart(Z_AXIS) * nx +
this->mpGridBox->GetWindowStart(Y_AXIS) * nx * nz;
float *in = this->mpShotCorrelation->GetNativePointer();
float *out = this->mpTotalCorrelation->GetNativePointer() + constant;
float *in_src = this->mpSourceIllumination->GetNativePointer();
float *in_rcv = this->mpReceiverIllumination->GetNativePointer();
uint block_x = this->mpParameters->GetBlockX();
uint block_z = this->mpParameters->GetBlockZ();
uint block_y = this->mpParameters->GetBlockY();
uint offset = this->mpParameters->GetHalfLength() +
this->mpParameters->GetBoundaryLength();
int x_end = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - offset;
int y_end = 1;
int z_end = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - offset;
int y_start;
if (ny > 1) {
y_start = offset;
y_end = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - offset;
} else {
y_start = 0;
y_end = 1;
}
int device_num = omp_get_default_device();
#pragma omp target is_device_ptr(in, out, in_src, in_rcv) device(device_num)
#pragma omp teams distribute parallel for collapse(3) \
num_teams((ny / block_y) * (nz / block_z) * (nx / block_x)) \
thread_limit(block_y *block_z)
for (int by = y_start; by < y_end; by += block_y) {
for (int bz = offset; bz < z_end; bz += block_z) {
for (int bx = offset; bx < x_end; bx += block_x) {
float *input, *output, *input_src, *input_rcv;
uint offset_full, offset_window;
int izEnd = fmin(bz + block_z, z_end);
int iyEnd = fmin(by + block_y, y_end);
int ixEnd = fmin(bx + block_x, x_end);
for (int iy = by; iy < iyEnd; iy++) {
for (int iz = bz; iz < izEnd; iz++) {
offset_window = iy * wnx * wnz + iz * wnx;
offset_full = iy * nx * nz + iz * nx;
input = in + offset_window;
output = out + offset_full;
input_src = in_src + offset_window;
input_rcv = in_rcv + offset_window;
for (int ix = bx; ix < ixEnd; ix++) {
if constexpr (_COMPENSATION_TYPE == COMBINED_COMPENSATION) {
output[ix] += (input[ix] / (sqrtf(input_src[ix] * input_rcv[ix]) + EPSILON));
} else {
output[ix] += input[ix];
}
}
}
}
}
}
}
}
| 8,370
|
C++
|
.cpp
| 159
| 42.245283
| 135
| 0.606959
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,117
|
SeismicTraceWriter.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/trace-writers/SeismicTraceWriter.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/components/independents/concrete/trace-writers/SeismicTraceWriter.hpp>
#include <operations/utils/checks/Checks.hpp>
using namespace std;
using namespace bs::base::exceptions;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::utils::checks;
void SeismicTraceWriter::RecordTrace(uint time_step) {
int trace_size = this->mTraceNumber;
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz_wnx = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize() * wnx;
int std_offset = (this->mpParameters->GetBoundaryLength() + this->mpParameters->GetHalfLength()) * wnx;
float current_time = (time_step - 1) * this->mpGridBox->GetDT();
uint trace_step = uint(current_time / this->mTraceSampling);
if (time_step > 1) {
float previous_time = (time_step - 2) * this->mpGridBox->GetDT();
uint previous_trace_step = uint(previous_time / this->mTraceSampling);
if (previous_trace_step == trace_step) {
return;
}
}
trace_step = min(trace_step, this->mSampleNumber - 1);
auto positions_y = this->mpDPositionsY.GetNativePointer();
auto positions_x = this->mpDPositionsX.GetNativePointer();
auto values = this->mpDTraces.GetNativePointer();
float *pressure = this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
#pragma omp target is_device_ptr(pressure, values, positions_y, positions_x) device(device_num)
#pragma omp parallel for
for (int i = 0; i < trace_size; i++) {
int offset = positions_y[i] * wnz_wnx + std_offset + positions_x[i];
values[(trace_step) * trace_size + i] = pressure[offset];
}
}
| 2,672
|
C++
|
.cpp
| 56
| 43.75
| 107
| 0.719217
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,118
|
BoundarySaver.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/forward-collectors/boundary-saver/BoundarySaver.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <operations/components/independents/concrete/forward-collectors/boundary-saver/BoundarySaver.h>
#include <operations/utils/checks/Checks.hpp>
using namespace bs::base::exceptions;
using namespace operations::components::helpers;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::utils::checks;
#pragma omp declare target
void
ApplyBoundaries(uint start_y, uint start_z, uint start_x, uint end_y, uint end_z, uint end_x,
uint ny, uint wnx, uint wnznx, uint lny, uint lnz, uint lnx, uint index,
uint time_step, uint bound_length, uint half_length, uint size_of_boundaries,
float *current_pressure, float *backup_boundaries) {
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = start_z; iz < end_z; iz++) {
for (int ix = 0; ix < half_length; ix++) {
backup_boundaries[time_step * size_of_boundaries + index] =
current_pressure[iy * wnznx + iz * wnx + bound_length + ix];
index++;
backup_boundaries[time_step * size_of_boundaries + index] =
current_pressure[iy * wnznx + iz * wnx + (lnx - bound_length - 1) - ix];
index++;
}
}
}
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = 0; iz < half_length; iz++) {
for (int ix = start_x; ix < end_x; ix++) {
backup_boundaries[time_step * size_of_boundaries + index] =
current_pressure[iy * wnznx + (bound_length + iz) * wnx + ix];
index++;
backup_boundaries[time_step * size_of_boundaries + index] =
current_pressure[iy * wnznx + (lnz - bound_length - 1 - iz) * wnx + ix];
index++;
}
}
}
if (ny > 1) {
for (int iy = 0; iy < half_length; iy++) {
for (int iz = start_z; iz < end_z; iz++) {
for (int ix = start_x; ix < end_x; ix++) {
backup_boundaries[time_step * size_of_boundaries + index] =
current_pressure[(bound_length + iy) * wnznx + iz * wnx + ix];
index++;
backup_boundaries[time_step * size_of_boundaries + index] =
current_pressure[(lny - bound_length - 1 - iy) * wnznx + iz * wnx + ix];
index++;
}
}
}
}
}
#pragma omp end declare target
#pragma omp declare target
void
GetBoundaries(uint start_y, uint start_z, uint start_x, uint end_y, uint end_z, uint end_x,
uint ny, uint wnx, uint wnznx, uint lny, uint lnz, uint lnx, uint index,
uint time_step, uint bound_length, uint half_length, uint size_of_boundaries,
float *current_pressure, float *backup_boundaries) {
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = start_z; iz < end_z; iz++) {
for (int ix = 0; ix < half_length; ix++) {
current_pressure[iy * wnznx + iz * wnx + bound_length + ix] =
backup_boundaries[time_step * size_of_boundaries + index];
index++;
current_pressure[iy * wnznx + iz * wnx + (lnx - bound_length - 1) - ix] =
backup_boundaries[time_step * size_of_boundaries + index];
index++;
}
}
}
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = 0; iz < half_length; iz++) {
for (int ix = start_x; ix < end_x; ix++) {
current_pressure[iy * wnznx + (bound_length + iz) * wnx + ix] =
backup_boundaries[time_step * size_of_boundaries + index];
index++;
current_pressure[iy * wnznx + (lnz - bound_length - 1 - iz) * wnx + ix] =
backup_boundaries[time_step * size_of_boundaries + index];
index++;
}
}
}
if (ny > 1) {
for (int iy = 0; iy < half_length; iy++) {
for (int iz = start_z; iz < end_z; iz++) {
for (int ix = start_x; ix < end_x; ix++) {
current_pressure[(bound_length + iy) * wnznx + iz * wnx + ix] =
backup_boundaries[time_step * size_of_boundaries + index];
index++;
current_pressure[(lny - bound_length - 1 - iy) * wnznx + iz * wnx + ix] =
backup_boundaries[time_step * size_of_boundaries + index];
index++;
}
}
}
}
}
#pragma omp end declare target
void
BoundarySaver::SaveBoundaries(uint aStep) {
//finding gpu device
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
uint index = 0;
uint size_of_boundaries = this->mBoundarySize;
uint time_step = aStep;
uint half_length = this->mpComputationParameters->GetHalfLength();
uint bound_length = this->mpComputationParameters->GetBoundaryLength();
uint offset = half_length + bound_length;
uint start_y = 0;
uint end_y = 1;
uint ny = this->mpMainGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
uint wnx = this->mpMainGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = this->mpMainGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint lnx = this->mpMainGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
uint lny = this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
uint lnz = this->mpMainGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
uint start_z = offset;
uint end_z = this->mpMainGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - offset;
uint start_x = offset;
uint end_x = this->mpMainGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - offset;
uint wnznx = wnx * wnz;
if (ny > 1) {
start_y = offset;
end_y = this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - offset;
}
float *current_pressure = this->mpMainGridBox->Get(this->mKey)->GetNativePointer();
float *backup_boundaries = this->mBackupBoundaries.GetNativePointer();
#pragma omp target is_device_ptr(current_pressure, backup_boundaries) device(device_num)
ApplyBoundaries(start_y, start_z, start_x, end_y, end_z, end_x,
ny, wnx, wnznx, lny, lnz, lnx, index,
time_step, bound_length, half_length, size_of_boundaries, current_pressure, backup_boundaries);
}
void
BoundarySaver::RestoreBoundaries(uint aStep) {
/* Finding the GPU device. */
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
uint index = 0;
uint size_of_boundaries = this->mBoundarySize;
uint time_step = aStep;
uint half_length = this->mpComputationParameters->GetHalfLength();
uint bound_length = this->mpComputationParameters->GetBoundaryLength();
uint offset = half_length + bound_length;
uint start_y = 0;
uint end_y = 1;
///WILL TEST
uint ny = mpMainGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
uint wnx = mpMainGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = mpMainGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = mpMainGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint lnx = mpMainGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
uint lny = mpMainGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
uint lnz = mpMainGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
uint start_z = offset;
uint end_z = mpMainGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - offset;
uint start_x = offset;
uint end_x = mpMainGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - offset;
uint wnznx = wnx * wnz;
if (ny > 1) {
start_y = offset;
end_y = mpMainGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - offset;
}
float *current_pressure = this->mpInternalGridBox->Get(this->mKey)->GetNativePointer();
float *backup_boundaries = this->mBackupBoundaries.GetNativePointer();
#pragma omp target is_device_ptr(current_pressure, backup_boundaries) device(device_num)
GetBoundaries(start_y, start_z, start_x, end_y, end_z, end_x,
ny, wnx, wnznx, lny, lnz, lnx, index,
time_step, bound_length, half_length, size_of_boundaries, current_pressure, backup_boundaries);
}
| 9,606
|
C++
|
.cpp
| 194
| 40.391753
| 115
| 0.610708
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,119
|
SeismicTraceManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/trace-managers/SeismicTraceManager.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <omp.h>
#include <operations/components/independents/concrete/trace-managers/SeismicTraceManager.hpp>
#include <operations/utils/interpolation/Interpolator.hpp>
#include <operations/utils/io/read_utils.h>
#include <operations/utils/checks/Checks.hpp>
using namespace std;
using namespace bs::base::exceptions;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
using namespace operations::utils::checks;
using namespace operations::utils::io;
// Adding the traces and velocity values over the pressure array
#pragma omp declare target
void ApplyOnPressure(int aOffset, int aTraceOffset, float *aPressure, const float *aVelocity, const float *aTraces) {
aPressure[aOffset] += aTraces[aTraceOffset] * aVelocity[aOffset];
}
#pragma omp end declare target
void SeismicTraceManager::ApplyTraces(int time_step) {
int trace_size = this->mpTracesHolder->TraceSizePerTimeStep;
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wnz_wnx = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize() * wnx;
int std_offset = (mpParameters->GetBoundaryLength() + mpParameters->GetHalfLength()) * wnx;
float current_time = (time_step - 1) * this->mpGridBox->GetDT();
uint trace_step = uint(current_time / this->mpTracesHolder->SampleDT);
trace_step = min(trace_step, this->mpTracesHolder->SampleNT - 1);
float *pressure = this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *velocity = this->mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
float *traces = this->mpDTraces.GetNativePointer();
uint *pos_x = this->mpDPositionsX.GetNativePointer();
uint *pos_y = this->mpDPositionsY.GetNativePointer();
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
#pragma omp target is_device_ptr(pressure, velocity, traces, pos_y, pos_x) device(device_num)
#pragma omp parallel for
for (int i = 0; i < trace_size; i++) {
int trace_offset = (trace_step) * trace_size + i;
int offset = pos_y[i] * wnz_wnx + std_offset + pos_x[i];
ApplyOnPressure(offset, trace_offset, pressure, velocity, traces);
}
}
| 3,060
|
C++
|
.cpp
| 61
| 46.819672
| 117
| 0.743366
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,120
|
FrameBuffer.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/data-units/FrameBuffer.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include <omp.h>
#include <bs/base/exceptions/Exceptions.hpp>
#include <operations/common/DataTypes.h>
#include <operations/data-units/concrete/holders/FrameBuffer.hpp>
#include <operations/utils/checks/Checks.hpp>
using namespace bs::base::exceptions;
using namespace operations::dataunits;
using namespace operations::utils::checks;
/** @note
* For the omp offload compiler all the possibles values for the template should
* be declared before usage, or it won't compile
*/
template
class operations::dataunits::FrameBuffer<float>;
template
class operations::dataunits::FrameBuffer<int>;
template
class operations::dataunits::FrameBuffer<uint>;
template FrameBuffer<float>::FrameBuffer();
template FrameBuffer<float>::FrameBuffer(uint size);
template FrameBuffer<float>::~FrameBuffer();
template void FrameBuffer<float>::Allocate(uint aSize, const std::string &aName);
template void FrameBuffer<float>::Allocate(uint aSize, HALF_LENGTH aHalfLength, const std::string &aName);
template void FrameBuffer<float>::Free();
template float *FrameBuffer<float>::GetNativePointer();
template float *FrameBuffer<float>::GetHostPointer();
template float *FrameBuffer<float>::GetDiskFlushPointer();
template void FrameBuffer<float>::SetNativePointer(float *ptr);
template void FrameBuffer<float>::ReflectOnNative();
template FrameBuffer<int>::FrameBuffer();
template FrameBuffer<int>::FrameBuffer(uint size);
template FrameBuffer<int>::~FrameBuffer();
template void FrameBuffer<int>::Allocate(uint aSize, const std::string &aName);
template void FrameBuffer<int>::Allocate(uint aSize, HALF_LENGTH aHalfLength, const std::string &aName);
template void FrameBuffer<int>::Free();
template int *FrameBuffer<int>::GetNativePointer();
template int *FrameBuffer<int>::GetHostPointer();
template int *FrameBuffer<int>::GetDiskFlushPointer();
template void FrameBuffer<int>::SetNativePointer(int *ptr);
template void FrameBuffer<int>::ReflectOnNative();
template FrameBuffer<uint>::FrameBuffer();
template FrameBuffer<uint>::FrameBuffer(uint size);
template FrameBuffer<uint>::~FrameBuffer();
template void FrameBuffer<uint>::Allocate(uint aSize, const std::string &aName);
template void FrameBuffer<uint>::Allocate(uint aSize, HALF_LENGTH aHalfLength, const std::string &aName);
template void FrameBuffer<uint>::Free();
template uint *FrameBuffer<uint>::GetNativePointer();
template uint *FrameBuffer<uint>::GetHostPointer();
template uint *FrameBuffer<uint>::GetDiskFlushPointer();
template void FrameBuffer<uint>::SetNativePointer(uint *ptr);
template void FrameBuffer<uint>::ReflectOnNative();
template<typename T>
FrameBuffer<T>::FrameBuffer() {
mpDataPointer = nullptr;
mpHostDataPointer = nullptr;
mAllocatedBytes = 0;
}
template<typename T>
FrameBuffer<T>::FrameBuffer(uint size) {
Allocate(size);
mpHostDataPointer = nullptr;
}
template<typename T>
FrameBuffer<T>::~FrameBuffer() {
Free();
}
template<typename T>
void FrameBuffer<T>::Allocate(uint aSize, const std::string &aName) {
mAllocatedBytes = sizeof(T) * aSize;
/* Finding gpu device. */
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
mpDataPointer = (T *) omp_target_alloc(mAllocatedBytes, device_num);
if (no_space_exist(mpDataPointer)) {
throw DEVICE_NO_SPACE_EXCEPTION();
}
}
template<typename T>
void FrameBuffer<T>::Allocate(uint aSize, HALF_LENGTH aHalfLength, const std::string &aName) {
Allocate(aSize, aName);
}
template<typename T>
void FrameBuffer<T>::Free() {
if (!is_null_ptr(this->mpDataPointer)) {
/* Finding gpu device. */
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
omp_target_free(mpDataPointer, device_num);
this->mpDataPointer = nullptr;
}
if (!is_null_ptr(this->mpHostDataPointer)) {
free(mpHostDataPointer);
this->mpHostDataPointer = nullptr;
}
this->mAllocatedBytes = 0;
}
template<typename T>
T *FrameBuffer<T>::GetNativePointer() {
return mpDataPointer;
}
template<typename T>
T *FrameBuffer<T>::GetHostPointer() {
if (!is_null_ptr(this->mpDataPointer)) {
if (is_null_ptr(this->mpHostDataPointer)) {
this->mpHostDataPointer = (T *) std::malloc(this->mAllocatedBytes);
}
Device::MemCpy(this->mpHostDataPointer, this->mpDataPointer, this->mAllocatedBytes,
Device::COPY_DEVICE_TO_HOST);
} else {
throw NULL_POINTER_EXCEPTION();
}
return this->mpHostDataPointer;
}
template<typename T>
T *FrameBuffer<T>::GetDiskFlushPointer() {
return this->GetHostPointer();
}
template<typename T>
void FrameBuffer<T>::SetNativePointer(T *pT) {
this->mpDataPointer = pT;
}
template<typename T>
void FrameBuffer<T>::ReflectOnNative() {
Device::MemCpy(this->mpDataPointer, this->mpHostDataPointer, this->mAllocatedBytes, Device::COPY_HOST_TO_DEVICE);
}
void Device::MemSet(void *dest, int value, uint size) {
char *h_dest = new char[size];
memset(h_dest, value, size);
Device::MemCpy(dest, h_dest, size, Device::COPY_HOST_TO_DEVICE);
delete[] h_dest;
}
void Device::MemCpy(void *dest, const void *src, uint size, CopyDirection direction) {
/* Finding the host CPU. */
int host_num = omp_get_initial_device();
/* Finding the GPU device. */
int device_num = omp_get_default_device();
if (direction == COPY_HOST_TO_HOST) {
memcpy(dest, src, size);
} else if (direction == COPY_HOST_TO_DEVICE) {
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
omp_target_memcpy((void *) dest, (void *) src, size, 0, 0, device_num, host_num);
} else if (direction == COPY_DEVICE_TO_HOST) {
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
omp_target_memcpy((void *) dest, (void *) src, size, 0, 0, host_num, device_num);
} else if (direction == COPY_DEVICE_TO_DEVICE) {
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
omp_target_memcpy((void *) dest, (void *) src, size, 0, 0, device_num, device_num);
} else {
/* Default is considered to be copying from the host to the device,
* so it would be the same cased as COPY_HOST_TO_DEVICE. */
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
omp_target_memcpy((void *) dest, (void *) src, size, 0, 0, device_num, host_num);
}
}
| 7,453
|
C++
|
.cpp
| 185
| 36.135135
| 117
| 0.715317
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,541,121
|
RickerSourceInjector.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/source-injectors/RickerSourceInjector.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of SeismicToolbox.
*
* SeismicToolbox is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SeismicToolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <math.h>
#include <operations/components/independents/concrete/source-injectors/RickerSourceInjector.hpp>
#include <operations/utils/checks/Checks.hpp>
using namespace bs::base::exceptions;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
using namespace operations::utils::checks;
/**
* Implementation based on
* https://tel.archives-ouvertes.fr/tel-00954506v2/document .
*/
// Add the ricker value for the pressure array
#pragma omp declare target
void ApplySourceOnPressure(float aTemp, int aLocation, float *aPressure, float *aVelocity) {
float ricker = aTemp * aVelocity[aLocation];
aPressure[aLocation] += ricker;
}
#pragma omp end declare target
void RickerSourceInjector::ApplySource(int time_step) {
float dt = this->mpGridBox->GetDT();
float freq = this->mpParameters->GetSourceFrequency();
if (time_step < this->GetCutOffTimeStep()) {
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
float a = M_PI * freq;
float a2 = a * a;
float t = time_step * dt;
float t2 = t * t;
float temp = (1 - a2 * 2 * t2) * exp(-a2 * t2);
int location = this->GetInjectionLocation();
/* Finding gpu device. */
int device_num = omp_get_default_device();
float *vel = this->mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
float *pressure = this->mpGridBox->Get(WAVE | GB_PRSS | CURR)->GetNativePointer();
#pragma omp target is_device_ptr(pressure, vel) device(device_num)
ApplySourceOnPressure(temp, location, pressure, vel);
}
}
| 2,463
|
C++
|
.cpp
| 59
| 37.661017
| 96
| 0.717884
|
brightskiesinc/Reverse_Time_Migration
| 36
| 6
| 0
|
LGPL-3.0
|
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.