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,541,122
|
SeismicModelHandler.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/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 <omp.h>
#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;
}
int device_num = omp_get_default_device();
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();
#pragma omp target is_device_ptr(window_param, param_ptr) device(device_num)
#pragma omp teams distribute parallel for collapse(3) schedule(static, 1)
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;
window_param[offset_window] = param_ptr[offset_full];
}
}
}
}
}
}
void SeismicModelHandler::SetupPadding() {
// Left empty as there is nothing to pad for omp offload technology
}
| 3,373
|
C++
|
.cpp
| 66
| 43.378788
| 99
| 0.655015
|
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,123
|
WaveFieldsMemoryHandler.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/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 <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp>
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) {
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();
}
{
ScopeTimer t("ComputationKernel::FirstTouch");
/* Set the device arrays to zero. */
Device::MemSet(ptr, 0.0f, nx * ny * nz * sizeof(float));
}
}
| 1,846
|
C++
|
.cpp
| 42
| 40.119048
| 96
| 0.734149
|
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,124
|
SecondOrderComputationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/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 <omp.h>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/components/independents/concrete/computation-kernels/isotropic/SecondOrderComputationKernel.hpp>
#include <operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp>
#include <operations/components/independents/concrete/computation-kernels/BaseComputationHelpers.hpp>
using namespace std;
using namespace bs::base::exceptions;
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();
if (is_null_ptr(prev_base) || is_null_ptr(curr_base) || is_null_ptr(next_base) || is_null_ptr(vel_base)) {
throw NULL_POINTER_EXCEPTION();
}
float *coeff_x = mpCoeffX->GetNativePointer();
float *coeff_z = mpCoeffZ->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.
*/
//finding the gpu device
int device_num = omp_get_default_device();
// all the arrays are now on the device , checked to be all present and then we use teams to make all
// the EU work on the arrays and then distribute for making all threads in the EU execute the shared part of the loop
// we control the number of teams and thread per team
#pragma omp target is_device_ptr(prev_base, curr_base, next_base, vel_base, coeff_x, coeff_z) device(device_num)
#pragma omp teams distribute collapse(2) \
num_teams((block_z) * (wnx/ block_x)) \
thread_limit(block_x)
{
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(bx + block_x, nx_end);
int izEnd = min(bz + block_z, nz_end);
/// Loop on the elements in the block.
#pragma omp parallel for simd schedule(static, 1)
for (auto ix = bx; ix < ixEnd; ix++) {
// Pre-compute and advance the pointer to the start of the current
// start point of the processing.
auto gid = ix + (bz * wnx);
// the front and back arrays are temp arrays where you store the elements above and below the current element in the x row
// the first loop is at the x direction and the inner loop is at the z direction
float front[HALF_LENGTH_ + 1];
float back[HALF_LENGTH_];
// set the values for the front array , it is a (hl +1) size
// the front also have the current element of x at 0 index
front[0] = curr_base[gid];
front[1] = curr_base[gid + wnx * 1];
if (HALF_LENGTH_ > 1) {
front[2] = curr_base[gid + wnx * 2];
}
if (HALF_LENGTH_ > 2) {
front[3] = curr_base[gid + wnx * 3];
front[4] = curr_base[gid + wnx * 4];
}
if (HALF_LENGTH_ > 4) {
front[5] = curr_base[gid + wnx * 5];
front[6] = curr_base[gid + wnx * 6];
}
if (HALF_LENGTH_ > 6) {
front[7] = curr_base[gid + wnx * 7];
front[8] = curr_base[gid + wnx * 8];
}
// set the values for the back arrays
back[0] = curr_base[gid - wnx];
if (HALF_LENGTH_ > 1) {
back[1] = curr_base[gid - 2 * wnx];
}
if (HALF_LENGTH_ > 2) {
back[2] = curr_base[gid - 3 * wnx];
back[3] = curr_base[gid - 4 * wnx];
}
if (HALF_LENGTH_ > 4) {
back[4] = curr_base[gid - 5 * wnx];
back[5] = curr_base[gid - 6 * wnx];
}
if (HALF_LENGTH_ > 6) {
back[6] = curr_base[gid - 7 * wnx];
back[7] = curr_base[gid - 8 * wnx];
}
// applying the computation kernel on the current element
// for the vertical direction we use the front and back elements
for (auto iz = bz; iz < izEnd; iz++) {
float value = 0;
value = fma(front[0], mCoeffXYZ, value);
value = fma(front[1] + back[0], coeff_z[0], value);
if (HALF_LENGTH_ > 1) {
value = fma(front[2] + back[1], coeff_z[1], value);
}
if (HALF_LENGTH_ > 2) {
value = fma(front[3] + back[2], coeff_z[2], value);
value = fma(front[4] + back[3], coeff_z[3], value);
}
if (HALF_LENGTH_ > 4) {
value = fma(front[5] + back[4], coeff_z[4], value);
value = fma(front[6] + back[5], coeff_z[5], value);
}
if (HALF_LENGTH_ > 6) {
value = fma(front[7] + back[6], coeff_z[6], value);
value = fma(front[8] + back[7], coeff_z[7], value);
}
// use this macro to continue the computation for the horizontal elements
DERIVE_SEQ_AXIS_EQ_OFF(gid, 1, +, curr_base, coeff_x, value)
// adding the calculated value
next_base[gid] = (2 * front[0]) - prev_base[gid] + (vel_base[gid] * value);
// updating the pointer for the next cell , we move one row down
gid += wnx;
// updating the values of back and front arrays by a shift of one element down vertically
if (HALF_LENGTH_ > 6) {
back[7] = back[6];
back[6] = back[5];
}
if (HALF_LENGTH_ > 4) {
back[5] = back[4];
back[4] = back[3];
}
if (HALF_LENGTH_ > 2) {
back[3] = back[2];
back[2] = back[1];
}
if (HALF_LENGTH_ > 1) {
back[1] = back[0];
}
back[0] = front[0];
front[0] = front[1];
if (HALF_LENGTH_ > 1) {
front[1] = front[2];
}
if (HALF_LENGTH_ > 2) {
front[2] = front[3];
front[3] = front[4];
}
if (HALF_LENGTH_ > 4) {
front[4] = front[5];
front[5] = front[6];
}
if (HALF_LENGTH_ > 6) {
front[6] = front[7];
front[7] = front[8];
}
// updating the last element of front to have the value of the new current element
front[HALF_LENGTH_] = curr_base[gid + HALF_LENGTH_ * wnx];
}
}
}
}
}
timer.Stop();
}
void
SecondOrderComputationKernel::PreprocessModel() {
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().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;
int full_nx_nz = nx * nz;
// finding the gpu device
int device_num = omp_get_default_device();
/// Preprocess the velocity model by calculating the
/// dt2 * c2 component of the wave equation.
#pragma omp target is_device_ptr(velocity_values) device(device_num)
#pragma omp teams distribute parallel for collapse(2) schedule(static, 1)
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;
}
}
}
| 11,335
|
C++
|
.cpp
| 221
| 37.235294
| 123
| 0.529486
|
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,125
|
StaggeredComputationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/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 "operations/components/independents/concrete/computation-kernels/isotropic/StaggeredComputationKernel.hpp"
#include "operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp"
#include <operations/data-units/concrete/holders/FrameBuffer.hpp>
#include <omp.h>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/components/independents/concrete/computation-kernels/BaseComputationHelpers.hpp>
using namespace std;
using namespace bs::timer;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
using namespace bs::base::exceptions;
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() {
float *curr_base = this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *den_base = this->mpGridBox->Get(PARM | WIND | GB_DEN)->GetNativePointer();
float *vel_base = this->mpGridBox->Get(PARM | WIND | GB_VEL)->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();
if (is_null_ptr(curr_base) || is_null_ptr(den_base) || is_null_ptr(particle_vel_x) || is_null_ptr(particle_vel_z)) {
throw NULL_POINTER_EXCEPTION();
}
float *coeff_x = mpCoeff->GetNativePointer();
float *coeff_z = mpCoeff->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();
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_);
int flops_per_velocity = 6 * HALF_LENGTH_ + 4;
int num_of_arrays_velocity = 6;
ElasticTimer timer("ComputationKernel::ComputeVelocity",
size, num_of_arrays_velocity, true,
flops_per_velocity);
timer.Start();
int device_num = omp_get_default_device();
#pragma omp target is_device_ptr(curr_base, den_base, vel_base, particle_vel_x, particle_vel_z, coeff_x, coeff_z) device(device_num)
#pragma omp teams distribute collapse(2) \
num_teams((block_z) * (wnx/ block_x)) \
thread_limit(block_x)
{
for (int bz = HALF_LENGTH_; bz < nz_end; bz += block_z) {
for (int bx = HALF_LENGTH_; bx < nx_end; bx += block_x) {
int ixEnd = min(bx + block_x, nx_end);
int izEnd = min(bz + block_z, nz_end);
#pragma omp parallel for simd schedule(static, 1)
for (auto ix = bx; ix < ixEnd; ix++) {
// Pre-compute and advance the pointer to the start of the current
// start point of the processing.
auto gid = ix + (bz * wnx);
for (auto iz = bz; iz < izEnd; iz++) {
float value_x = 0, value_z = 0;
DERIVE_SEQ_AXIS(gid, 1, 0, -, curr_base, coeff_x, value_x)
DERIVE_JUMP_AXIS(gid, wnx, 1, 0, -, curr_base, coeff_z, value_z)
if constexpr(KERNEL_MODE_ != KERNEL_MODE::INVERSE) {
particle_vel_x[gid] = particle_vel_x[gid] - (den_base[gid] / dx) * value_x;
particle_vel_z[gid] = particle_vel_z[gid] - (den_base[gid] / dz) * value_z;
} else {
particle_vel_x[gid] = particle_vel_x[gid] + (den_base[gid] / dx) * value_x;
particle_vel_z[gid] = particle_vel_z[gid] + (den_base[gid] / dz) * value_z;
}
gid += wnx;
}
}
}
}
}
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();
if (is_null_ptr(curr_base) || is_null_ptr(next_base) || is_null_ptr(vel_base) || is_null_ptr(particle_vel_x) ||
is_null_ptr(particle_vel_z) || is_null_ptr(den_base)) {
throw NULL_POINTER_EXCEPTION();
}
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();
float dx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
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_);
int flops_per_pressure = 6 * HALF_LENGTH_ + 3;
int num_of_arrays_pressure = 5;
float *coeff_x = mpCoeff->GetNativePointer();
float *coeff_z = mpCoeff->GetNativePointer();
ElasticTimer timer("ComputationKernel::ComputePressure",
size, num_of_arrays_pressure, true,
flops_per_pressure);
timer.Start();
int device_num = omp_get_default_device();
#pragma omp target is_device_ptr(curr_base, next_base, den_base, particle_vel_x, particle_vel_z, vel_base, coeff_x, coeff_z) device(device_num)
#pragma omp teams distribute collapse(2) \
num_teams((block_z) * (wnx/ block_x)) \
thread_limit(block_x)
{
for (int bz = HALF_LENGTH_; bz < nz_end; bz += block_z) {
for (int bx = HALF_LENGTH_; bx < nx_end; bx += block_x) {
int ixEnd = min(bx + block_x, nx_end);
int izEnd = min(bz + block_z, nz_end);
#pragma omp parallel for simd schedule(static, 1)
for (auto ix = bx; ix < ixEnd; ix++) {
auto gid = ix + (bz * wnx);
for (auto iz = bz; iz < izEnd; iz++) {
float value_x = 0, value_z = 0;
DERIVE_SEQ_AXIS(gid, 0, 1, -, particle_vel_x, coeff_x, value_x)
DERIVE_JUMP_AXIS(gid, wnx, 0, 1, -, particle_vel_z, coeff_z, value_z)
if constexpr (KERNEL_MODE_ != KERNEL_MODE::INVERSE) {
next_base[gid] = curr_base[gid] - vel_base[gid] * ((value_x / dx) + (value_z / dz));
} else {
next_base[gid] = curr_base[gid] + vel_base[gid] * ((value_x / dx) + (value_z / dz));
}
gid += wnx;
}
}
}
}
}
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 *velocity_values = this->mpGridBox->Get(PARM | GB_VEL)->GetNativePointer();
float *density_values = this->mpGridBox->Get(PARM | GB_DEN)->GetNativePointer();
int full_nx = nx;
int device_num = omp_get_default_device();
#pragma omp target is_device_ptr(velocity_values, density_values) device(device_num)
#pragma omp teams distribute 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];
}
}
}
}
| 9,913
|
C++
|
.cpp
| 179
| 46.340782
| 143
| 0.620298
|
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,126
|
SpongeBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/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>
#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;
/* Implementation 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.
**/
/* Finding the GPU device. */
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lwnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lwny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int lwnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
uint bound_length = mpParameters->GetBoundaryLength();
uint half_length = mpParameters->GetHalfLength();
int y_start = half_length + bound_length;
int y_end = lwny - half_length - bound_length;
if (wny == 1) {
y_start = 0;
y_end = 1;
}
float *sponge_coefficients = mpSpongeCoefficients->GetNativePointer();
#pragma omp target is_device_ptr( next, sponge_coefficients) device(device_num)
#pragma parallel for collapse(3)
for (int iy = y_start; iy < y_end; iy++) {
for (int iz = half_length + bound_length - 1; iz >= half_length; iz--) {
for (int ix = half_length + bound_length; ix <= lwnx - half_length - bound_length; ix++) {
next[iy * wnx * wnz + iz * wnx + ix] *=
sponge_coefficients[iz - half_length];
next[iy * wnx * wnz + (iz + wnz - 2 * iz - 1) * wnx + ix] *=
sponge_coefficients[iz - half_length];
}
}
}
#pragma omp target is_device_ptr( next, sponge_coefficients) device(device_num)
#pragma parallel for collapse(3)
for (int iy = y_start; iy < y_end; iy++) {
for (int iz = half_length + bound_length; iz <= lwnz - half_length - bound_length; iz++) {
for (int ix = half_length + bound_length - 1; ix >= half_length; ix--) {
next[iy * wnx * wnz + iz * wnx + ix] *=
sponge_coefficients[ix - half_length];
next[iy * wnx * wnz + iz * wnx + (ix + wnx - 2 * ix - 1)] *=
sponge_coefficients[ix - half_length];
}
}
}
if (wny > 1) {
#pragma omp target is_device_ptr( next, sponge_coefficients) device(device_num)
#pragma parallel for collapse(3)
for (int iy = half_length + bound_length - 1; iy >= half_length; iy--) {
for (int iz = half_length + bound_length; iz <= lwnz - half_length - bound_length; iz++) {
for (int ix = half_length + bound_length; ix <= lwnx - half_length - bound_length; ix++) {
next[iy * wnx * wnz + iz * wnx + ix] *=
sponge_coefficients[iy - half_length];
next[(iy + wny - 2 * iy - 1) * wnx * wnz + iz * wnx + ix] *=
sponge_coefficients[iy - half_length];
}
}
}
}
int start_y = y_start;
int end_y = y_end;
int start_x = half_length;
int end_x = lwnx - half_length;
int start_z = half_length;
int end_z = lwnz - half_length;
int nz_nx = wnz * wnx;
// Zero-Corners in the boundaries nx-nz boundary intersection--boundaries not
// needed.
#pragma omp target is_device_ptr( next, sponge_coefficients) device(device_num)
#pragma parallel for collapse(3)
for (int depth = start_y; depth < end_y; depth++) {
for (int row = 0; row < bound_length; row++) {
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[depth * nz_nx + (start_z + row) * wnx + column + start_x] *=
min(sponge_coefficients[column], sponge_coefficients[row]);
/*!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 */
next[depth * nz_nx + (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 = nx-half_length to x = nx-half_length - BOUND_LENGTH */
/*! Top right boundary in other words */
next[depth * nz_nx + (start_z + row) * wnx + (end_x - 1 - column)] *=
min(sponge_coefficients[column], sponge_coefficients[row]);
/*!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 */
next[depth * nz_nx + (end_z - 1 - row) * wnx + (end_x - 1 - column)] *=
min(sponge_coefficients[column], sponge_coefficients[row]);
}
}
}
// If 3-D, zero corners in the y-x and y-z plans.
if (wny > 1) {
// Zero-Corners in the boundaries ny-nz boundary intersection--boundaries
// not needed.
#pragma omp target is_device_ptr( next, sponge_coefficients) device(device_num)
#pragma parallel for collapse(3)
for (int depth = 0; depth < bound_length; depth++) {
for (int row = 0; row < bound_length; row++) {
for (int column = start_x; column < end_x; column++) {
/*!for values from z = half_length TO z = half_length +BOUND_LENGTH */
/*! and for y = half_length to y = half_length + BOUND_LENGTH */
next[(depth + start_y) * nz_nx + (start_z + row) * wnx + column] *=
min(sponge_coefficients[depth], sponge_coefficients[row]);
/*!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 */
next[(depth + start_y) * nz_nx + (end_z - 1 - row) * wnx + column] *=
min(sponge_coefficients[depth], sponge_coefficients[row]);
/*!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 */
next[(end_y - 1 - depth) * nz_nx + (start_z + row) * wnx + column] *=
min(sponge_coefficients[depth], sponge_coefficients[row]);
/*!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
*/
next[(end_y - 1 - depth) * nz_nx + (end_z - 1 - row) * wnx + column] *=
min(sponge_coefficients[depth], sponge_coefficients[row]);
}
}
}
// Zero-Corners in the boundaries nx-ny boundary intersection--boundaries
// not needed.
#pragma omp target is_device_ptr( next, sponge_coefficients) device(device_num)
#pragma parallel for collapse(3)
for (int depth = 0; depth < bound_length; depth++) {
for (int row = start_z; row < end_z; row++) {
for (int column = 0; column < bound_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 */
next[(depth + start_y) * nz_nx + row * wnx + column + start_x] *=
min(sponge_coefficients[column], sponge_coefficients[depth]);
/*!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 */
next[(end_y - 1 - depth) * nz_nx + row * wnx + column + start_x] *=
min(sponge_coefficients[column], sponge_coefficients[depth]);
/*!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 */
next[(depth + start_y) * nz_nx + row * wnx + (end_x - 1 - column)] *=
min(sponge_coefficients[column], sponge_coefficients[depth]);
/*!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
*/
next[(end_y - 1 - depth) * nz_nx + row * wnx + (end_x - 1 - column)] *=
min(sponge_coefficients[column], sponge_coefficients[depth]);
}
}
}
}
}
| 10,870
|
C++
|
.cpp
| 195
| 44.123077
| 150
| 0.567096
|
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,127
|
CPMLBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/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 <omp.h>
#include <operations/components/independents/concrete/boundary-managers/CPMLBoundaryManager.hpp>
#include <operations/components/independents/concrete/computation-kernels/BaseComputationHelpers.hpp>
#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;
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() {
/* Finding the GPU device. */
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
int ix, iy, iz;
float *curr_base = this->mpGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = this->mpGridBox->GetWindowAxis()->GetYAxis().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 bound_length = this->mpParameters->GetBoundaryLength();
int block_x = this->mpParameters->GetBlockX();
int block_y = this->mpParameters->GetBlockY();
int block_z = this->mpParameters->GetBlockZ();
int nxEnd = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int nyEnd = 1;
int nzEnd = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int wnxnz = wnx * wnz;
int y_start = 0;
if (ny != 1) {
y_start = HALF_LENGTH_;
nyEnd = this->mpGridBox->GetWindowAxis()->GetYAxis().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 {
coeff_a = this->mpCoeffay->GetNativePointer();
coeff_b = this->mpCoeffby->GetNativePointer();
first_coeff_h = this->mpFirstCoeffy->GetNativePointer();
distance = this->mpDistanceDim3->GetNativePointer();
if (!OPPOSITE_) {
y_start = HALF_LENGTH_;
nyEnd = bound_length + HALF_LENGTH_;
aux = this->mpAux1yup->GetNativePointer();
} else {
y_start = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_ - bound_length;
nyEnd = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_;
aux = this->mpAux1ydown->GetNativePointer();
}
}
first_coeff_h_1 = &first_coeff_h[1];
distance_1 = &distance[1];
#pragma omp target is_device_ptr( coeff_a, coeff_b, aux, curr_base, first_coeff_h, first_coeff_h_1, distance_1 ) device(device_num)
#pragma omp teams distribute parallel for collapse(3)
for (int by = y_start; by < nyEnd; by += block_y) {
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);
int iyEnd = min(by + block_y, nyEnd);
for (iy = by; iy < iyEnd; iy++) {
for (iz = bz; iz < izEnd; iz++) {
int offset = iy * wnxnz + iz * wnx;
float *curr = curr_base + offset;
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 =
iy * wnz * WIDTH + iz * WIDTH + (ix - x_start + HALF_LENGTH_);
} else {
coeff_ind = bound_length - ix + HALF_LENGTH_ - 1;
index = iy * wnz * WIDTH + iz * WIDTH + ix;
}
} else if (DIRECTION_ == Z_AXIS) { // case z
if (OPPOSITE_) {
coeff_ind = iz - z_start;
index = iy * wnx * WIDTH + (iz - z_start + HALF_LENGTH_) * wnx + ix;
} else {
coeff_ind = bound_length - iz + HALF_LENGTH_ - 1;
index = iy * wnx * WIDTH + iz * wnx + ix;
}
} else { // case y
if (OPPOSITE_) {
coeff_ind = iy - y_start;
index = (iy - y_start + HALF_LENGTH_) * wnx * wnz + (iz * wnx) + ix;
} else {
coeff_ind = bound_length - iy + HALF_LENGTH_ - 1;
index = iy * wnx * wnz + (iz * wnx) + ix;
}
} // case y
aux[index] =
coeff_a[coeff_ind] * aux[index] + coeff_b[coeff_ind] * value;
}
}
}
}
}
}
}
template<int direction, bool OPPOSITE_, int HALF_LENGTH_>
void CPMLBoundaryManager::CalculateCPMLValue() {
/* Finding the GPU device. */
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
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 ix, iy, iz;
// direction 1 means in x , direction 2 means in z , else means in y
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = this->mpGridBox->GetWindowAxis()->GetYAxis().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 block_x = this->mpParameters->GetBlockX();
int block_y = this->mpParameters->GetBlockY();
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 nyEnd = 1;
int nzEnd = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - half_length;
int wnxnz = wnx * wnz;
int nxnz = nx * nz;
int y_start = 0;
if (ny > 1) {
y_start = half_length;
nyEnd = this->mpGridBox->GetWindowAxis()->GetYAxis().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 {
coeff_a = this->mpCoeffay->GetNativePointer();
coeff_b = this->mpCoeffby->GetNativePointer();
distance = this->mpDistanceDim3->GetNativePointer();
coeff_first_h = this->mpFirstCoeffy->GetNativePointer();
coeff_h = this->mpSecondCoeffy->GetNativePointer();
if (!OPPOSITE_) {
y_start = half_length;
nyEnd = bound_length + half_length;
aux_first = this->mpAux1yup->GetNativePointer();
aux_second = this->mpAux2yup->GetNativePointer();
} else {
y_start = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - half_length - bound_length;
nyEnd = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - half_length;
aux_first = this->mpAux1ydown->GetNativePointer();
aux_second = this->mpAux2ydown->GetNativePointer();
}
}
auto distance_1 = &distance[1];
auto coeff_h_1 = &coeff_h[1];
auto coeff_first_h_1 = &coeff_first_h[1];
#pragma omp target is_device_ptr(curr_base, vel_base, next_base, coeff_h, coeff_h_1, distance_1, aux_first, aux_second, coeff_a, coeff_b ) device(device_num)
#pragma omp teams distribute parallel for collapse(3)
for (int by = y_start; by < nyEnd; by += block_y) {
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);
int iyEnd = fmin(by + block_y, nyEnd);
// Loop on the elements in the block.
for (iy = by; iy < iyEnd; ++iy) {
for (iz = bz; iz < izEnd; ++iz) {
int offset = iy * wnxnz + iz * wnx;
float *curr = curr_base + offset;
float *vel = vel_base + offset;
float *next = next_base + offset;
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 =
iy * wnz * WIDTH + iz * WIDTH + (ix - x_start + half_length);
} else {
coeff_ind = bound_length - ix + half_length - 1;
index = iy * wnz * WIDTH + iz * WIDTH + ix;
}
} else if (direction == Z_AXIS) { // case z
if (OPPOSITE_) {
coeff_ind = iz - z_start;
index = iy * wnx * WIDTH + (iz - z_start + half_length) * wnx + ix;
} else {
coeff_ind = bound_length - iz + half_length - 1;
index = iy * wnx * WIDTH + iz * wnx + ix;
}
} else { // case y
if (OPPOSITE_) {
coeff_ind = iy - y_start;
index = (iy - y_start + half_length) * wnx * wnz + (iz * wnx) + ix;
} else {
coeff_ind = bound_length - iy + half_length - 1;
index = iy * wnx * wnz + (iz * wnx) + ix;
}
} // case y
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;
}
}
}
}
}
}
}
| 17,698
|
C++
|
.cpp
| 330
| 39.293939
| 157
| 0.538528
|
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,128
|
StaggeredCPMLBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/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>
#include "omp.h"
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() {
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)
dh = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float inv_dh = 1.0f / dh;
int y_start = 0;
int y_end = 1;
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 wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
int wnzwnx = wnx * wnz;
if (wny > 1) {
y_start = HALF_LENGTH_;
y_end = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_;
}
// Set variables pointers.
float *aux_variable;
float *mpSmall_a;
float *mpSmall_b;
float *particle_velocity;
float *coeff = &mpCoeff->GetNativePointer()[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_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 Y_AXIS:
y_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_vel_y_down->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_vel_y_up->GetNativePointer();
}
particle_velocity = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_Y)->GetNativePointer();
mpSmall_a = this->mpSmall_a_y->GetNativePointer();
mpSmall_b = this->mpSmall_b_y->GetNativePointer();
jump = wnzwnx;
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = b_l;
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;
}
int aux_nxnz = aux_nx * aux_nz;
// Compute.
int device_num = omp_get_device_num();
#pragma omp target is_device_ptr(mpSmall_a, mpSmall_b, aux_variable, particle_velocity, coeff ) device(device_num)
#pragma omp teams distribute parallel for collapse(3)
for (int k = y_start; k < y_end; ++k) {
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;
int real_y = k;
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;
}
} else {
active_bound_index = k;
if constexpr(OPPOSITE_) {
real_y = lny - 1 - k;
}
}
// Compute wanted derivative.
int offset;
offset = real_x + wnx * real_z + real_y * wnzwnx;
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 +
(k - y_start) * aux_nxnz;
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() {
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)
dh = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float inv_dh = 1.0f / dh;
int y_start = 0;
int y_end = 1;
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 wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
int wnzwnx = wnx * wnz;
if (wny > 1) {
y_start = HALF_LENGTH_;
y_end = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_;
}
// 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 Y_AXIS:
y_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_ptr_y_down->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_ptr_y_up->GetNativePointer();
}
particle_velocity = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_Y)->GetNativePointer();
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = b_l;
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;
}
int aux_nxnz = aux_nx * aux_nz;
float *parameter_base;
parameter_base = this->mpGridBox->Get(PARM | WIND | GB_DEN)->GetNativePointer();
// Compute.
int device_num = omp_get_device_num();
#pragma omp target is_device_ptr(parameter_base, aux_variable, particle_velocity ) device(device_num)
#pragma omp teams distribute parallel for collapse(3)
for (int k = y_start; k < y_end; ++k) {
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;
int real_y = k;
float value = 0.0f;
// 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;
}
} else {
if constexpr(OPPOSITE_) {
real_y = lny - 1 - k;
}
}
// Compute wanted derivative.
int offset = real_x + wnx * real_z + real_y * wnzwnx;
int aux_offset = (i - HALF_LENGTH_) + (j - HALF_LENGTH_) * aux_nx +
(k - y_start) * aux_nxnz;
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() {
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)
dh = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
// 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 y_start = 0;
int y_end = 1;
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 wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
int wnzwnx = wnx * wnz;
if (wny > 1) {
y_start = HALF_LENGTH_;
y_end = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_;
}
// Set variables pointers.
float *aux_variable;
float *mpSmall_a;
float *mpSmall_b;
float *coeff = &mpCoeff->GetNativePointer()[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 Y_AXIS:
y_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_ptr_y_down->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_ptr_y_up->GetNativePointer();
}
mpSmall_a = this->mpSmall_a_y->GetNativePointer();
mpSmall_b = this->mpSmall_b_y->GetNativePointer();
jump = wnzwnx;
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = b_l;
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;
}
int aux_nxnz = aux_nx * aux_nz;
// Compute.
int device_num = omp_get_device_num();
#pragma omp target is_device_ptr(curr_base, mpSmall_a, mpSmall_b, aux_variable, coeff ) device(device_num)
#pragma omp teams distribute parallel for collapse(3)
for (int k = y_start; k < y_end; ++k) {
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;
int real_y = k;
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;
}
} else {
active_bound_index = k;
if constexpr(OPPOSITE_) {
real_y = lny - 1 - k;
}
}
// Compute wanted derivative.
int offset;
offset = real_x + wnx * real_z + real_y * wnzwnx;
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 +
(k - y_start) * aux_nxnz;
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() {
int y_start = 0;
int y_end = 1;
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 wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
int wnzwnx = wnx * wnz;
if (wny > 1) {
y_start = HALF_LENGTH_;
y_end = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_;
}
// 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:
y_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_vel_y_down->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_vel_y_up->GetNativePointer();
}
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = b_l;
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();
}
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = lnz - 2 * HALF_LENGTH_;
break;
default:
throw bs::base::exceptions::ILLOGICAL_EXCEPTION();
break;
}
int aux_nxnz = aux_nx * aux_nz;
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();
int device_num = omp_get_device_num();
#pragma omp target is_device_ptr(curr_base, parameter_base, aux_variable) device(device_num)
#pragma omp teams distribute parallel for collapse(3)
for (int k = y_start; k < y_end; ++k) {
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;
int real_y = k;
// 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;
}
} else {
if constexpr(OPPOSITE_) {
real_y = lny - 1 - k;
}
}
// Compute wanted derivative.
int offset = real_x + wnx * real_z + real_y * wnzwnx;
int aux_offset = (i - HALF_LENGTH_) + (j - HALF_LENGTH_) * aux_nx +
(k - y_start) * aux_nxnz;
curr_base[offset] = curr_base[offset] - parameter_base[offset] * aux_variable[aux_offset];
}
}
}
}
| 21,964
|
C++
|
.cpp
| 496
| 33.102823
| 114
| 0.554979
|
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,129
|
RandomExtension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/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"
#include <operations/utils/checks/Checks.hpp>
using namespace std;
using namespace bs::base::exceptions;
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::utils::checks;
/**
* @brief generates random seeds on the left and right boundaries (x boundaries)
*
* @param apRandom pointer to the parameter that would have random boundaries
* @param apSeeds pointer to the seeds allocated memory
* @param aStrideX distance between 2 adjacent seeds in x direction
* @param aStrideZ distance between 2 adjacent seeds in z direction
* @param aStartX domain start in x direction
* @param aEndX domain end in x direction
* @param aStartZ domain start in z direction
* @param aEndZ domain end in z direction
* @param aNx domain width
* @param aBoundaryLength length of the boundaries
* @param aMaxVelocity maximum value of the parameter
*/
void Randomize(float *apRandom, Point3D *apSeeds, int aStrideX, int aStrideZ, int aStartX, int aEndX,
int aStartZ, int aEndZ, int aNx, int aBoundaryLength, float aMaxVelocity) {
int index_v = 0;
int seed_index = 0;
int index = 0;
for (int row = aStartZ + aBoundaryLength; row < aEndZ - aBoundaryLength; row += aStrideZ) {
for (int column = 0; column < aBoundaryLength; column += aStrideX) {
index = row * aNx + column + aStartX;
float r_val = GET_RANDOM_VALUE(aBoundaryLength, column) * aMaxVelocity;
apRandom[index] = abs(apRandom[row * aNx + aBoundaryLength + aStartX] - r_val);
apSeeds[seed_index] = Point3D(column + aStartX, 1, row);
seed_index++;
index = row * aNx + (aEndX - column - 1);
r_val = GET_RANDOM_VALUE(aBoundaryLength, column) * aMaxVelocity;
apRandom[index] = abs(apRandom[row * aNx + (aEndX - 1 - aBoundaryLength)] - r_val);
apSeeds[seed_index] = Point3D((aEndX - column - 1), 1, row);
seed_index++;
}
}
}
/**
* @brief generates random seeds on the bottom boundary of the domain (z boundaries)
*
* @param apRandom pointer to the parameter that would have random boundaries
* @param apSeedsV pointer to the seeds allocated memory for z boundaries only
* @param aStrideX distance between 2 adjacent seeds in x direction
* @param aStrideZ distance between 2 adjacent seeds in z direction
* @param aStartX domain start in x direction
* @param aEndX domain end in x direction
* @param aStartZ domain start in z direction
* @param aEndZ domain end in z direction
* @param aNx domain width
* @param aBoundaryLength length of the boundaries
* @param aMaxVelocity maximum value of the parameter
*/
void RandomizeV(float *apRandom, Point3D *apSeedsV, int aStrideX, int aStrideZ, int aStartX, int aEndX,
int aStartZ, int aEndZ, int aNx, int aBoundaryLength, float aMaxVelocity) {
float temp = 0;
int index = 0;
int index_v = 0;
for (int row = 0; row < aBoundaryLength; row += aStrideZ) {
for (int column = aStartX; column < aEndX; column += aStrideX) {
int index = (aEndZ - row - 1) * aNx + column;
temp = GET_RANDOM_VALUE(aBoundaryLength, row) * aMaxVelocity;
apRandom[index] = abs(apRandom[(aEndZ - 1 - aBoundaryLength) * aNx + column] - temp);
apSeedsV[index_v] = Point3D(column, 1, (aEndZ - row - 1));
index_v++;
}
}
}
/**
* @brief generates 2 random values per point in the boundary, these would be used
* in the grain filling around the initial seeds
*
* @param apArrayX Random values for vertical distance from seeds calcuation
* @param apArrayZ Random values for horizontal distance from seeds calculation
* @param aStartX domain start in x direction
* @param aEndX domain end in x direction
* @param aStartZ domain start in z direction
* @param aEndZ domain end in z direction
* @param aNx domain width
* @param aNz domain hight
* @param aBoundaryLength length of the boundaries
*/
void SetRandom(float *apArrayX, float *apArrayZ, int aStartX, int aEndX, int aStartZ, int aEndZ, int aNx, int aNz,
int aBoundaryLength) {
int index = 0;
for (int row = aStartZ + aBoundaryLength; row < aEndZ - aBoundaryLength; row++) {
for (int column = 0; column < aBoundaryLength; column++) {
index = row * aNx + column + aStartX;
apArrayX[index] = RANDOM_VALUE;
apArrayZ[index] = RANDOM_VALUE;
index = row * aNx + (aEndX - column - 1);
apArrayX[index] = RANDOM_VALUE;
apArrayZ[index] = RANDOM_VALUE;
}
}
}
/**
* @brief generates 2 random values per point in the boundary, these would be used
* in the grain filling around the initial seeds
* this one would be used in the bottom boundaries only (z boundaries)
*
* @param apArrayX Random values for vertical distance from seeds calcuation
* @param apArrayZ Random values for horizontal distance from seeds calculation
* @param aStartX domain start in x direction
* @param aEndX domain end in x direction
* @param aStartZ domain start in z direction
* @param aEndZ domain end in z direction
* @param aNx domain width
* @param aNz domain hight
* @param aBoundaryLength length of the boundaries
*/
void SetRandomV(float *apArrayX, float *apArrayZ, int aStartX, int aEndX, int aStartZ, int aEndZ, int aNx, int aNz,
int aBoundaryLength) {
int index = 0;
for (int row = 0; row < aBoundaryLength; row++) {
for (int column = aStartX; column < aEndX; column++) {
index = (aEndZ - row - 1) * aNx + column;
apArrayX[index] = RANDOM_VALUE;
apArrayZ[index] = RANDOM_VALUE;
}
}
}
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
*/
// finding the gpu device
int device_num = omp_get_default_device();
int host_num = omp_get_initial_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
int dx = mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
int dy = mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
int dz = mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
int grain_sidelength = this->mGrainSideLength; // in meters
int stride_x = grain_sidelength / dx;
int stride_z = grain_sidelength / dz;
int stride_y = 0;
if (aNy != 1) {
stride_y = grain_sidelength / dy;
}
uint size = aNx * aNz * aNy;
uint allocated_size = size * sizeof(float);
float max_velocity = 0;
int calculated_size =
((aEndZ - aBoundaryLength - aStartZ - aBoundaryLength) / stride_z + 1) * (aBoundaryLength / stride_x + 1);
calculated_size *= 2;
uint allocated_bytes = calculated_size * sizeof(Point3D);
Point3D *seeds = (Point3D *) omp_target_alloc(allocated_bytes, device_num);
Point3D *seeds_h = (Point3D *) malloc(allocated_bytes);
int vertical_calculated_size = (aBoundaryLength / stride_z + 1) * ((aEndX - aStartX) / stride_x + 1);
uint v_allocated_bytes = vertical_calculated_size * sizeof(Point3D);
Point3D *seeds_v = (Point3D *) omp_target_alloc(v_allocated_bytes, device_num);
Point3D *seeds_v_h = (Point3D *) malloc(v_allocated_bytes);
float *arr_x = (float *) omp_target_alloc(allocated_size, device_num);
float *arr_z = (float *) omp_target_alloc(allocated_size, device_num);
float *arr_x_h = (float *) malloc(allocated_size);
float *arr_z_h = (float *) malloc(allocated_size);
float *random = (float *) malloc(allocated_size);
omp_target_memcpy(random, apPropertyArray, allocated_size, 0, 0, host_num, device_num);
float temp = 0;
int seed_index = 0;
max_velocity = *max_element(random, random + aNx * aNy * aNz);
Randomize(random, seeds_h, stride_x, stride_z, aStartX, aEndX, aStartZ, aEndZ, aNx, aBoundaryLength, max_velocity);
SetRandom(arr_x_h, arr_z_h, aStartX, aEndX, aStartZ, aEndZ, aNx, aNz, aBoundaryLength);
omp_target_memcpy(seeds, seeds_h, allocated_bytes, 0, 0, device_num, host_num);
omp_target_memcpy(arr_x, arr_x_h, allocated_size, 0, 0, device_num, host_num);
omp_target_memcpy(arr_z, arr_z_h, allocated_size, 0, 0, device_num, host_num);
omp_target_memcpy(apPropertyArray, random, allocated_size, 0, 0, device_num, host_num);
#pragma omp target is_device_ptr( apPropertyArray, seeds, arr_x, arr_z) device(device_num)
#pragma omp parallel for
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);
Point3D seed(0, 0, 0);
int index = row * aNx + column + aStartX;
bool is_seed = false;
for (int s = 0; s < calculated_size; s++) {
if (left_point == seeds[s]) {
is_seed = true;
break;
}
}
Point3D left_point_seed(0, 0, 0);
Point3D right_point_seed(0, 0, 0);
if (!is_seed) {
for (int s = 0; s < calculated_size; s++) {
seed = seeds[s];
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 = Point3D(seeds[s].x, seeds[s].y, seeds[s].z);
}
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 = Point3D(seeds[s].x, seeds[s].y, seeds[s].z);
}
}
int id_x;
int id_z;
float px, pz;
px = arr_x[index];
pz = arr_z[index];
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];
index = row * aNx + (aEndX - column - 1);
px = arr_x[index];
pz = arr_z[index];
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];
}
}
}
omp_target_memcpy(random, apPropertyArray, allocated_size, 0, 0, host_num, device_num);
RandomizeV(random, seeds_v_h, stride_x, stride_z, aStartX, aEndX, aStartZ, aEndZ, aNx, aBoundaryLength,
max_velocity);
SetRandomV(arr_x_h, arr_z_h, aStartX, aEndX, aStartZ, aEndZ, aNx, aNz, aBoundaryLength);
omp_target_memcpy(seeds_v, seeds_v_h, v_allocated_bytes, 0, 0, device_num, host_num);
omp_target_memcpy(arr_x, arr_x_h, allocated_size, 0, 0, device_num, host_num);
omp_target_memcpy(arr_z, arr_z_h, allocated_size, 0, 0, device_num, host_num);
omp_target_memcpy(apPropertyArray, random, allocated_size, 0, 0, device_num, host_num);
#pragma omp target is_device_ptr( apPropertyArray, seeds_v, arr_x, arr_z) device(device_num)
#pragma omp parallel for
for (int row = 0; row < aBoundaryLength; row++) {
for (int column = aStartX; column < aEndX; column++) {
int index = (aEndZ - row - 1) * aNx + column;
Point3D bottom_point(column, 1, aEndZ - row - 1);
Point3D seed_v(0, 0, 0);
bool is_seed = false;
for (int s = 0; s < vertical_calculated_size; s++) {
if (bottom_point == seeds_v[s]) {
is_seed = true;
break;
}
}
Point3D bottom_point_seed(0, 0, 0);
if (!is_seed) {
for (int s = 0; s < vertical_calculated_size; s++) {
seed_v = seeds_v[s];
if (
(seed_v.x <= bottom_point.x) && (seed_v.x + stride_x > bottom_point.x) &&
(seed_v.z >= bottom_point.z) && (seed_v.z - stride_z < bottom_point.z)
) {
bottom_point_seed = seed_v;
}
}
int id_x;
int id_z;
float px, pz;
px = arr_x[index];
pz = arr_z[index];
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];
}
}
}
omp_target_free(seeds, device_num);
omp_target_free(seeds_v, device_num);
omp_target_free(arr_x, device_num);
omp_target_free(arr_z, device_num);
free(random);
free(arr_x_h);
free(arr_z_h);
free(seeds_v_h);
free(seeds_h);
}
void RandomExtension::TopLayerExtensionHelper(float *apPropertyArray,
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 *apPropertyArray,
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.
}
| 18,539
|
C++
|
.cpp
| 363
| 39.889807
| 119
| 0.561135
|
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,130
|
MinExtension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/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 <omp.h>
#include <algorithm>
#include <cstdlib>
#include <operations/components/independents/concrete/boundary-managers/extensions/MinExtension.hpp>
#include <operations/utils/checks/Checks.hpp>
using namespace std;
using namespace bs::base::exceptions;
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::dataunits;
using namespace operations::utils::checks;
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)
*/
// finding the gpu device
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
int nz_nx = nx * nz;
float *deviceMinValue = (float *) omp_target_alloc(1 * sizeof(float), device_num);
float maxFloat = 100000.0f;
Device::MemCpy(deviceMinValue, &maxFloat, sizeof(float), Device::COPY_HOST_TO_DEVICE);
// Get maximum property_array value in 2D domain.
#pragma omp target is_device_ptr(property_array, deviceMinValue) device(device_num)
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++) {
deviceMinValue[0] =
min(deviceMinValue[0], property_array[row * nx + column]);
}
}
/*!putting random values for velocities at the boundaries for X and with all Y
* and Z */
#pragma omp target is_device_ptr(property_array, deviceMinValue) device(device_num)
#pragma omp parallel for collapse(2)
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[row * nx + column + start_x] =
deviceMinValue[0];
/*!for values from x = nx-HALF_LENGTH TO x =
* nx-HALF_LENGTH-BOUND_LENGTH*/
property_array[row * nx + (end_x - 1 - column)] =
deviceMinValue[0];
}
}
/*!putting random values for velocities at the boundaries for z and with all x
* and y */
#pragma omp target is_device_ptr(property_array, deviceMinValue) device(device_num)
#pragma omp parallel for collapse(2)
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[(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[(end_z - 1 - row) * nx + column] =
deviceMinValue[0];
}
}
}
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.
}
| 5,265
|
C++
|
.cpp
| 107
| 38.785047
| 100
| 0.602255
|
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,131
|
ZeroExtension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/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 <omp.h>
#include <operations/components/independents/concrete/boundary-managers/extensions/ZeroExtension.hpp>
#include <operations/utils/checks/Checks.hpp>
using namespace std;
using namespace bs::base::exceptions;
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::dataunits;
using namespace operations::utils::checks;
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)
*/
//finding gpu device
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
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
*/
#pragma omp target is_device_ptr( property_array) device(device_num)
#pragma omp parallel for collapse(3)
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
*/
#pragma omp target is_device_ptr( property_array) device(device_num)
#pragma omp parallel for collapse(3)
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
*/
#pragma omp target is_device_ptr( property_array) device(device_num)
#pragma omp parallel for collapse(3)
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,646
|
C++
|
.cpp
| 130
| 31.753846
| 101
| 0.537818
|
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,132
|
HomogenousExtension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/omp-offload/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 <omp.h>
#include <operations/components/independents/concrete/boundary-managers/extensions/HomogenousExtension.hpp>
#include <operations/utils/checks/Checks.hpp>
using namespace std;
using namespace bs::base::exceptions;
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::dataunits;
using namespace operations::utils::checks;
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)
*/
// finding the gpu device
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
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 */
#pragma omp target is_device_ptr( property_array) device(device_num)
#pragma omp parallel for collapse(3)
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 */
#pragma omp target is_device_ptr( property_array) device(device_num)
#pragma omp parallel for collapse(3)
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 */
#pragma omp target is_device_ptr( property_array) device(device_num)
#pragma omp parallel for collapse(3)
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 */
#pragma omp target is_device_ptr( property_array) device(device_num)
#pragma omp parallel for collapse(3)
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 */
// finding the gpu device
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
#pragma omp target is_device_ptr( property_array) device(device_num)
#pragma omp parallel for collapse(3)
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 to zero
* for all velocities at the boundaries for z and with all x and y */
// finding the gpu device
int device_num = omp_get_default_device();
if (is_device_not_exist()) {
throw DEVICE_NOT_FOUND_EXCEPTION();
}
#pragma omp target is_device_ptr( property_array) device(device_num)
#pragma omp parallel for collapse(3)
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;
}
}
}
}
}
| 9,244
|
C++
|
.cpp
| 181
| 37.674033
| 107
| 0.53944
|
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,133
|
CrossCorrelationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
#include <bs/base/api/cpp/BSBase.hpp>
#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 cl::sycl;
using namespace bs::base::backend;
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) {
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int compute_nx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize();
int compute_ny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetComputationAxisSize();
int compute_nz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize();
int block_x = mpParameters->GetBlockX();
int block_y = mpParameters->GetBlockY();
int block_z = mpParameters->GetBlockZ();
int half_length = mpParameters->GetHalfLength();
int y_offset = half_length;
if (_IS_2D) {
y_offset = 0;
}
int size = (wnx - 2 * half_length) * (wnz - 2 * half_length);
int flops_per_second = 3 * half_length;
if (_COMPENSATION_TYPE == COMPENSATION_TYPE::COMBINED_COMPENSATION) {
flops_per_second = 9 * half_length;
}
ElasticTimer timer("Correlation::Correlate::Kernel",
size, 5, true,
flops_per_second);
float *source = apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *receiver = mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
timer.Start();
if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::CPU) {
float *output_buffer = mpShotCorrelation->GetNativePointer();
float *src_buffer = mpSourceIllumination->GetNativePointer();
float *dest_buffer = mpReceiverIllumination->GetNativePointer();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
size_t num_groups = Backend::GetInstance()->GetWorkgroupNumber();
size_t wgsize = Backend::GetInstance()->GetWorkgroupSize();
size_t z_stride = compute_nz / num_groups;
auto global_range = range<1>(num_groups);
auto local_range = range<1>(wgsize);
const int hl = mpParameters->GetHalfLength();
cgh.parallel_for_work_group(global_range, local_range, [=](group<1> grp) {
size_t z_id = grp.get_id(0) * z_stride + hl;
size_t end_z = (z_id + z_stride) < (compute_nz + hl) ? (z_id + z_stride) : (compute_nz + hl);
grp.parallel_for_work_item([&](h_item<1> it) {
for (size_t iz = z_id; iz < end_z; iz++) {
size_t offset = iz * wnx + it.get_local_id(0);
for (size_t ix = hl; ix < compute_nx; ix += wgsize) {
size_t idx = offset + ix;
output_buffer[idx] += source[idx] * receiver[idx];
if (_COMPENSATION_TYPE == COMPENSATION_TYPE::COMBINED_COMPENSATION) {
src_buffer[idx] += source[idx] * source[idx];
dest_buffer[idx] += receiver[idx] * receiver[idx];
}
}
}
});
});
});
} else {
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<3>(compute_nx, compute_nz, compute_ny);
auto local_range = range<3>(block_x, block_z, block_y);
auto starting_offset = id<3>(half_length, half_length, y_offset);
auto global_nd_range = nd_range<3>(global_range,
local_range,
starting_offset);
float *output_buffer = mpShotCorrelation->GetNativePointer();
float *src_buffer = mpSourceIllumination->GetNativePointer();
float *dest_buffer = mpReceiverIllumination->GetNativePointer();
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int idx = it.get_global_id(2) * wnz * wnx + it.get_global_id(1) * wnx + it.get_global_id(0);
output_buffer[idx] += source[idx] * receiver[idx];
if (_COMPENSATION_TYPE == COMPENSATION_TYPE::COMBINED_COMPENSATION) {
src_buffer[idx] += source[idx] * source[idx];
dest_buffer[idx] += receiver[idx] * receiver[idx];
}
});
});
}
Backend::GetInstance()->GetDeviceQueue()->wait();
timer.Stop();
}
template<bool _IS_2D, COMPENSATION_TYPE _COMPENSATION_TYPE>
void CrossCorrelationKernel::Stack() {
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int orig_x = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int orig_y = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int orig_z = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
int offset = this->mpParameters->GetHalfLength() + this->mpParameters->GetBoundaryLength();
int constant_offset = offset + offset * nx;
int constant_offset_win = offset + offset * wnx;
if (!_IS_2D) {
constant_offset += offset * nx * nz;
constant_offset_win += offset * wnx * wnz;
}
int size = (wnx - 2 * offset) * (wnz - 2 * offset);
int flops_per_second = 6 * offset;
if (_COMPENSATION_TYPE == NO_COMPENSATION) {
flops_per_second = 2 * offset;
}
ElasticTimer timer("Correlation::Stack::Kernel",
size, 4, true,
flops_per_second);
size_t sizeTotal = nx * nz * ny;
timer.Start();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<3>(orig_x - 2 * offset, orig_z - 2 * offset,
orig_y);
int wsx = mpGridBox->GetWindowStart(X_AXIS);
int wsz = mpGridBox->GetWindowStart(Z_AXIS);
int wsy = mpGridBox->GetWindowStart(Y_AXIS);
float *stack_buf = mpTotalCorrelation->GetNativePointer() + wsx + wsz * nx + wsy * nx * nz;
float *cor_buf = mpShotCorrelation->GetNativePointer();
float *cor_src = mpSourceIllumination->GetNativePointer();
float *cor_rcv = mpReceiverIllumination->GetNativePointer();
if (_COMPENSATION_TYPE == NO_COMPENSATION) {
cgh.parallel_for(global_range, [=](id<3> idx) {
uint offset_window = idx[0] + idx[1] * wnx + idx[2] * wnx * wnz
+ constant_offset_win;
uint offset = idx[0] + idx[1] * nx + idx[2] * nx * nz
+ constant_offset;
stack_buf[offset] += cor_buf[offset_window];
});
} else {
cgh.parallel_for(global_range, [=](id<3> idx) {
uint offset_window = idx[0] + idx[1] * wnx + idx[2] * wnx * wnz
+ constant_offset_win;
uint offset = idx[0] + idx[1] * nx + idx[2] * nx * nz
+ constant_offset;
stack_buf[offset] += (cor_buf[offset_window] /
(sqrtf(cor_src[offset_window] * cor_rcv[offset_window]) + EPSILON));
});
}
});
Backend::GetInstance()->GetDeviceQueue()->wait();
timer.Stop();
}
| 9,810
|
C++
|
.cpp
| 181
| 44.165746
| 109
| 0.618983
|
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,134
|
SeismicTraceWriter.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <iostream>
#include <operations/components/independents/concrete/trace-writers/SeismicTraceWriter.hpp>
#include <bs/base/backend/Backend.hpp>
using namespace std;
using namespace cl::sycl;
using namespace bs::base::backend;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
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 = std::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();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<1>(trace_size);
auto local_range = range<1>(1);
auto global_nd_range = nd_range<1>(global_range, local_range);
cgh.parallel_for(global_nd_range, [=](nd_item<1> it) {
int i = it.get_global_id(0);
int offset = positions_y[i] * wnz_wnx + std_offset + positions_x[i];
values[(trace_step) * trace_size + i] = pressure[offset];
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
| 2,753
|
C++
|
.cpp
| 58
| 42.862069
| 95
| 0.702642
|
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,135
|
BoundarySaver.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 = lnz - offset;
uint start_x = offset;
uint end_x = lnx - offset;
uint wnznx = wnx * wnz;
if (ny > 1) {
start_y = offset;
end_y = lny - offset;
}
float *current_pressure = this->mpMainGridBox->Get(this->mKey)->GetHostPointer();
float *backup_boundaries = this->mBackupBoundaries.GetHostPointer();
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++;
}
}
}
}
this->mBackupBoundaries.ReflectOnNative();
}
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;
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 = lnz - offset;
uint start_x = offset;
uint end_x = lnx - offset;
uint wnznx = wnx * wnz;
if (ny > 1) {
start_y = offset;
end_y = lny - offset;
}
float *current_pressure = this->mpInternalGridBox->Get(this->mKey)->GetHostPointer();
float *backup_boundaries = this->mBackupBoundaries.GetHostPointer();
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++;
}
}
}
}
// Reflect changes that occurred to host buffer on native buffer
this->mpInternalGridBox->Get(this->mKey)->ReflectOnNative();
}
| 7,492
|
C++
|
.cpp
| 157
| 38.159236
| 104
| 0.587479
|
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,136
|
SeismicTraceManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/trace-managers/SeismicTraceManager.hpp>
using namespace std;
using namespace cl::sycl;
using namespace bs::base::backend;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
void SeismicTraceManager::ApplyTraces(int time_step) {
int trace_size = 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) * mpGridBox->GetDT();
float dt = mpGridBox->GetDT();
uint trace_step = uint(current_time / mpTracesHolder->SampleDT);
trace_step = std::min(trace_step, mpTracesHolder->SampleNT - 1);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<1>(trace_size);
auto local_range = range<1>(1);
auto global_nd_range = nd_range<1>(global_range, local_range);
float *current = mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *trace_values = mpDTraces.GetNativePointer();
float *w_vel = mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
uint *x_pos = mpDPositionsX.GetNativePointer();
uint *y_pos = mpDPositionsY.GetNativePointer();
cgh.parallel_for(global_nd_range, [=](nd_item<1> it) {
int i = it.get_global_id(0);
int offset = y_pos[i] * wnz_wnx + std_offset + x_pos[i];
current[offset] += trace_values[(trace_step) * trace_size + i] * w_vel[offset];
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
| 2,632
|
C++
|
.cpp
| 52
| 46.038462
| 95
| 0.707118
|
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,137
|
FrameBuffer.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <bs/base/api/cpp/BSBase.hpp>
#include <operations/common/DataTypes.h>
#include <operations/data-units/concrete/holders/FrameBuffer.hpp>
using namespace bs::base::backend;
using namespace operations::dataunits;
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 aSize);
template FrameBuffer<float>::~FrameBuffer();
template void FrameBuffer<float>::Allocate(uint size, 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 aSize);
template FrameBuffer<int>::~FrameBuffer();
template void FrameBuffer<int>::Allocate(uint size, 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 aSize);
template FrameBuffer<uint>::~FrameBuffer();
template void FrameBuffer<uint>::Allocate(uint size, 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 aSize) {
Allocate(aSize);
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;
auto dev = Backend::GetInstance()->GetDeviceQueue()->get_device();
auto ctxt = Backend::GetInstance()->GetDeviceQueue()->get_context();
mpDataPointer = (T *) malloc_device(mAllocatedBytes, dev, ctxt);
}
template<typename T>
void FrameBuffer<T>::Allocate(uint aSize, HALF_LENGTH aHalfLength, const std::string &aName) {
mAllocatedBytes = sizeof(T) * aSize;
auto dev = Backend::GetInstance()->GetDeviceQueue()->get_device();
auto ctxt = Backend::GetInstance()->GetDeviceQueue()->get_context();
mpDataPointer = (T *) malloc_device(mAllocatedBytes, dev, ctxt);
}
template<typename T>
void FrameBuffer<T>::Free() {
if (mpDataPointer != nullptr) {
sycl::free(mpDataPointer, *Backend::GetInstance()->GetDeviceQueue());
mpDataPointer = nullptr;
if (mpHostDataPointer != nullptr) {
sycl::free(mpHostDataPointer, *Backend::GetInstance()->GetDeviceQueue());
mpHostDataPointer = nullptr;
}
}
mAllocatedBytes = 0;
}
template<typename T>
T *FrameBuffer<T>::GetNativePointer() {
return mpDataPointer;
}
template<typename T>
T *FrameBuffer<T>::GetHostPointer() {
if (mAllocatedBytes > 0) {
auto ctxt = Backend::GetInstance()->GetDeviceQueue()->get_context();
if (mpHostDataPointer == nullptr) {
mpHostDataPointer = (T *) malloc_host(mAllocatedBytes, ctxt);
}
Device::MemCpy(mpHostDataPointer, mpDataPointer, mAllocatedBytes,
Device::COPY_DEVICE_TO_HOST);
}
return mpHostDataPointer;
}
template<typename T>
T *FrameBuffer<T>::GetDiskFlushPointer() {
return this->GetHostPointer();
}
template<typename T>
void FrameBuffer<T>::SetNativePointer(T *pT) {
mpDataPointer = pT;
}
template<typename T>
void FrameBuffer<T>::ReflectOnNative() {
Device::MemCpy(mpDataPointer, mpHostDataPointer, mAllocatedBytes, Device::COPY_HOST_TO_DEVICE);
}
void Device::MemSet(void *apDst, int aVal, uint aSize) {
Backend::GetInstance()->GetDeviceQueue()->submit([&](sycl::handler &cgh) {
cgh.memset(apDst, aVal, aSize);
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
void Device::MemCpy(void *apDst, const void *apSrc, uint aSize, CopyDirection aCopyDirection) {
Backend::GetInstance()->GetDeviceQueue()->submit([&](sycl::handler &cgh) {
cgh.memcpy(apDst, apSrc, aSize);
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
| 6,023
|
C++
|
.cpp
| 143
| 38.804196
| 106
| 0.748498
|
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,138
|
RickerSourceInjector.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <cmath>
#include <bs/base/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/source-injectors/RickerSourceInjector.hpp>
using namespace cl::sycl;
using namespace bs::base::backend;
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 = mpGridBox->GetDT();
float freq = mpParameters->GetSourceFrequency();
int location = this->GetInjectionLocation();
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);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto pressure = mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
auto win_vel = mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
cgh.single_task([=]() {
pressure[location] += (ricker * win_vel[location]);
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
}
}
| 2,281
|
C++
|
.cpp
| 55
| 35.781818
| 98
| 0.672982
|
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,139
|
SeismicModelHandler.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <vector>
#include <bs/base/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/model-handlers/SeismicModelHandler.hpp>
#define make_divisible(v, d) (v + (d - (v % d)))
using namespace std;
using namespace cl::sycl;
using namespace bs::base::backend;
using namespace bs::base::logger;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
void SeismicModelHandler::SetupWindow() {
if (mpParameters->IsUsingWindow()) {
uint wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
uint ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
uint nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
uint sx = mpGridBox->GetWindowStart(X_AXIS);
uint sz = mpGridBox->GetWindowStart(Z_AXIS);
uint sy = mpGridBox->GetWindowStart(Y_AXIS);
uint offset = mpParameters->GetHalfLength() + mpParameters->GetBoundaryLength();
uint start_x = offset;
uint end_x = mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - offset;
uint start_z = offset;
uint end_z = mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - offset;
uint start_y = 0;
uint end_y = 1;
if (ny != 1) {
start_y = offset;
end_y = mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - offset;
}
vector<uint> gridDims{end_x - start_x, end_y - start_y, end_z - start_z};
vector<uint> blockDims{1, 1, 1};
auto configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
for (auto const ¶meter : mpGridBox->GetParameters()) {
Backend::GetInstance()->GetDeviceQueue()->submit([&](sycl::handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
float *vel = mpGridBox->Get(parameter.first)->GetNativePointer();
float *w_vel = mpGridBox->Get(WIND | parameter.first)->GetNativePointer();
cgh.parallel_for(global_nd_range, [=](sycl::nd_item<3> it) {
int x = it.get_global_id(0) + start_x;
int y = it.get_global_id(1) + start_y;
int z = it.get_global_id(2) + start_z;
uint offset_window = y * wnx * wnz + z * wnx + x;
uint offset_full = (y + sy) * nx * nz + (z + sz) * nx + x + sx;
w_vel[offset_window] = vel[offset_full];
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
}
}
void SeismicModelHandler::SetupPadding() {
LoggerSystem *Logger = LoggerSystem::GetInstance();
auto grid = mpGridBox;
auto parameters = mpParameters;
uint block_x = parameters->GetBlockX();
uint block_z = parameters->GetBlockZ();
uint nx = grid->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
uint ny = grid->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
uint nz = grid->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
uint inx = nx - 2 * parameters->GetHalfLength();
uint inz = nz - 2 * parameters->GetHalfLength();
uint rear_x_padding = 0, rear_z_padding = 0;
uint aux_front_x_padding = 0, aux_rear_x_padding = 0;
// Store old values of nx,nz,ny to use in boundaries/etc....
if (block_x > inx) {
block_x = inx;
Logger->Info() << "Block Factor x > domain size... Reduced to domain size" << '\n';
}
if (block_z > inz) {
block_z = inz;
Logger->Info() << "Block Factor z > domain size... Reduced to domain size" << '\n';
}
if (block_x % 16 != 0 && block_x != 1) {
block_x = make_divisible(
block_x,
16); // Ensure block in x is divisible by 16(biggest vector length).
Logger->Info() << "Adjusting block factor in x to make it divisible by "
"16(Possible Vector Length)..." << '\n';
}
if (inx % block_x != 0) {
Logger->Info() << "Adding padding to make domain divisible by block size in x-axis" << '\n';
uint inx_axis_dev = make_divisible(inx, block_x);
rear_x_padding = inx_axis_dev - inx;
grid->GetWindowAxis()->GetXAxis().AddComputationalPadding(OP_DIREC_REAR, rear_x_padding);
}
if (inz % block_z != 0) {
Logger->Info()
<< "Adding padding to make domain divisible by block size in z-axis" << '\n';
uint inz_axis_dev = make_divisible(inz, block_z);
rear_z_padding = inz_axis_dev - inz;
grid->GetWindowAxis()->GetZAxis().AddComputationalPadding(OP_DIREC_REAR, rear_z_padding);
}
int actual_nx = grid->GetWindowAxis()->GetXAxis().GetActualAxisSize();
if (actual_nx % 16 != 0) {
//TODO this needs to be non-computational padding.
// Logger->Info() << "Adding padding to ensure alignment of each row" << '\n';
// uint actual_nx_dev = make_divisible(actual_nx, 16);
//
// aux_front_x_padding = (actual_nx_dev - actual_nx) / 2;
// aux_rear_x_padding = (actual_nx_dev - actual_nx) - aux_front_x_padding;
//
// grid->GetWindowAxis()->GetXAxis().AddComputationalPadding(OP_DIREC_FRONT,
// front_x_padding + aux_front_x_padding);
// grid->GetWindowAxis()->GetXAxis().AddComputationalPadding(OP_DIREC_REAR, rear_x_padding + aux_rear_x_padding);
}
parameters->SetBlockX(block_x);
parameters->SetBlockZ(block_z);
if (!parameters->IsUsingWindow()) {
this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().AddComputationalPadding(OP_DIREC_REAR, rear_x_padding +
aux_rear_x_padding);
this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().AddComputationalPadding(OP_DIREC_REAR, rear_z_padding);
}
}
| 7,089
|
C++
|
.cpp
| 135
| 44.577778
| 120
| 0.626518
|
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,140
|
WaveFieldsMemoryHandler.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <bs/base/api/cpp/BSBase.hpp>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp>
using namespace cl::sycl;
using namespace bs::base::backend;
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) {
if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::CPU) {
int nx, ny, nz, compute_nx, compute_nz;
if (enable_window) {
nx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
compute_nx = apGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize();
compute_nz = apGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize();
} else {
nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
compute_nx = apGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize();
compute_nz = apGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize();
}
ElasticTimer timer("ComputationKernel::FirstTouch");
timer.Start();
if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::CPU) {
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
size_t num_groups = Backend::GetInstance()->GetWorkgroupNumber();
size_t wgsize = Backend::GetInstance()->GetWorkgroupSize();
size_t z_stride = compute_nz / num_groups;
auto global_range = range<1>(num_groups);
auto local_range = range<1>(wgsize);
const size_t wnx = nx;
const int hl = mpParameters->GetHalfLength();
float *curr_base = ptr;
cgh.parallel_for_work_group(global_range, local_range, [=](group<1> grp) {
size_t z_id = grp.get_id(0) * z_stride + hl;
size_t end_z =
(z_id + z_stride) < (compute_nz + hl) ? (z_id + z_stride) : (compute_nz + hl);
grp.parallel_for_work_item([&](h_item<1> it) {
for (size_t iz = z_id; iz < end_z; iz++) {
size_t offset = iz * wnx + it.get_local_id(0);
for (size_t ix = hl; ix < compute_nx; ix += wgsize) {
size_t idx = offset + ix;
curr_base[idx] = 0;
}
}
});
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
Device::MemSet(ptr, 0, nx * nz * ny * sizeof(float));
timer.Stop();
}
}
| 3,950
|
C++
|
.cpp
| 76
| 41.315789
| 106
| 0.606986
|
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,141
|
SecondOrderComputationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <cstring>
#include <chrono>
#include <fstream>
#include <bs/base/api/cpp/BSBase.hpp>
#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>
using namespace std;
using namespace cl::sycl;
using namespace bs::base::backend;
using namespace bs::base::memory;
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. */
size_t nx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
size_t nz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
float *prev_base = mpGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
float *curr_base = mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *next_base = mpGridBox->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
float *vel_base = mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
/* Pre-compute the coefficients for each direction. */
int hl = HALF_LENGTH_;
int flops_per_second = 6 * HALF_LENGTH_ + 5;
int size = (nx - 2 * HALF_LENGTH_) * (nz - 2 * HALF_LENGTH_);
ElasticTimer timer("ComputationKernel::Kernel", size, 4, true,
flops_per_second);
auto t_start = std::chrono::high_resolution_clock::now();
timer.Start();
if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::CPU) {
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
size_t num_groups = Backend::GetInstance()->GetWorkgroupNumber();
size_t wgsize = Backend::GetInstance()->GetWorkgroupSize();
int compute_nz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize();
int compute_nx = mpParameters->GetHalfLength() +
this->mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize();
size_t z_stride = (compute_nz + num_groups - 1) / num_groups;
// auto global_range = range<2>(full_x, full_z);
// auto local_range = range<2>(full_x, block_z);
auto global_range = range<1>(num_groups);
auto local_range = range<1>(wgsize);
const size_t wnx = nx;
const size_t wnz = nz;
const float *current = curr_base;
const float *prev = prev_base;
float *next = next_base;
const float *vel = vel_base;
const float *c_x = mpCoeffX->GetNativePointer();
const float *c_z = mpCoeffZ->GetNativePointer();
const int *v = mpVerticalIdx->GetNativePointer();
const float c_xyz = mCoeffXYZ;
cgh.parallel_for_work_group(global_range, local_range, [=](group<1> grp) {
size_t z_id = grp.get_id(0) * z_stride + HALF_LENGTH_;
size_t end_z =
(z_id + z_stride) < (compute_nz + HALF_LENGTH_) ?
(z_id + z_stride) : (compute_nz +
HALF_LENGTH_);
grp.parallel_for_work_item([&](h_item<1> it) {
for (size_t iz = z_id; iz < end_z; iz++) {
size_t offset = iz * wnx + it.get_local_id(0);
for (size_t ix = HALF_LENGTH_; ix < compute_nx; ix += wgsize) {
size_t idx = offset + ix;
float value = current[idx] * c_xyz;
DERIVE_SEQ_AXIS_EQ_OFF(idx, 1, +, current, c_x, value)
DERIVE_ARRAY_AXIS_EQ_OFF(idx, v, +, current, c_z, value)
next[idx] = (2 * current[idx]) - prev[idx] + (vel[idx] * value);
}
}
});
});
});
} else if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::GPU_SHARED) {
int compute_nz = mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize();
int compute_nx = mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<2>(compute_nz, compute_nx);
auto local_range = range<2>(mpParameters->GetBlockZ(), mpParameters->GetBlockX());
sycl::nd_range<2> workgroup_range(global_range, local_range);
const float *current = curr_base;
const float *prev = prev_base;
float *next = next_base;
const float *vel = vel_base;
const float *c_x = mpCoeffX->GetNativePointer();
const float *c_z = mpCoeffZ->GetNativePointer();
const float c_xyz = mCoeffXYZ;
const int *v = mpVerticalIdx->GetNativePointer();
const int idx_range = mpParameters->GetBlockZ();
const int local_nx = mpParameters->GetBlockX() + 2 * hl;
auto localRange_ptr_cur = range<1>(((mpParameters->GetBlockX() + (2 * hl)) *
(mpParameters->GetBlockZ() + (2 * hl))));
/* Create an accessor for SLM buffer. */
accessor<float, 1, access::mode::read_write, access::target::local> tab(
localRange_ptr_cur, cgh);
cgh.parallel_for(workgroup_range, [=](nd_item<2> it) {
float *local = tab.get_pointer();
int idx =
it.get_global_id(1) + hl + (it.get_global_id(0) + hl) * nx;
size_t id0 = it.get_local_id(1);
size_t id1 = it.get_local_id(0);
size_t identifiant = (id0 + hl) + (id1 + hl) * local_nx;
float c_x_loc[HALF_LENGTH_];
float c_z_loc[HALF_LENGTH_];
int v_loc[HALF_LENGTH_];
/* Set local coefficient. */
for (unsigned int iter = 0; iter < HALF_LENGTH_; iter++) {
c_x_loc[iter] = c_x[iter];
c_z_loc[iter] = c_z[iter];
v_loc[iter] = (iter + 1) * local_nx;
}
bool copyHaloX = false;
bool copyHaloY = false;
const unsigned int items_X = it.get_local_range(1);
/* Set shared memory. */
local[identifiant] = current[idx];
if (id0 < HALF_LENGTH_) {
copyHaloX = true;
}
if (id1 < HALF_LENGTH_) {
copyHaloY = true;
}
if (copyHaloX) {
local[identifiant - HALF_LENGTH_] = current[idx - HALF_LENGTH_];
local[identifiant + items_X] = current[idx + items_X];
}
if (copyHaloY) {
local[identifiant - HALF_LENGTH_ * local_nx] =
current[idx - HALF_LENGTH_ * nx];
local[identifiant + idx_range * local_nx] =
current[idx + idx_range * nx];
}
it.barrier(access::fence_space::local_space);
float value = 0;
value = fma(local[identifiant], c_xyz, value);
for (int iter = 1; iter <= HALF_LENGTH_; iter++) {
value = fma(local[identifiant - iter], c_x_loc[iter - 1], value);
value = fma(local[identifiant + iter], c_x_loc[iter - 1], value);
}
for (int iter = 1; iter <= HALF_LENGTH_; iter++) {
value = fma(local[identifiant - v_loc[iter - 1]],
c_z_loc[iter - 1], value);
value = fma(local[identifiant + v_loc[iter - 1]],
c_z_loc[iter - 1], value);
}
value = fma(vel[idx], value, -prev[idx]);
value = fma(2.0f, local[identifiant], value);
next[idx] = value;
});
});
} else if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::GPU_SEMI_SHARED) {
int compute_nz = mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize() / mpParameters->GetBlockZ();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<2>(compute_nz, mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize());
auto local_range = range<2>(1, mpParameters->GetBlockX());
sycl::nd_range<2> workgroup_range(global_range, local_range);
const float *current = curr_base;
const float *prev = prev_base;
float *next = next_base;
const float *vel = vel_base;
const float *c_x = mpCoeffX->GetNativePointer();
const float *c_z = mpCoeffZ->GetNativePointer();
const float c_xyz = mCoeffXYZ;
const int *v = mpVerticalIdx->GetNativePointer();
const int idx_range = mpParameters->GetBlockZ();
const int local_nx = mpParameters->GetBlockX() + 2 * hl;
const int local_nz = mpParameters->GetBlockZ() + 2 * hl;
auto localRange_ptr_cur = range<1>(((mpParameters->GetBlockX() + (2 * hl)) *
(mpParameters->GetBlockZ() + (2 * hl))));
// Create an accessor for SLM buffer
accessor<float, 1, access::mode::read_write, access::target::local> tab(
localRange_ptr_cur, cgh);
cgh.parallel_for(workgroup_range, [=](nd_item<2> it) {
float *local = tab.get_pointer();
int idx = it.get_global_id(1) + hl +
(it.get_global_id(0) * idx_range + hl) * nx;
size_t id0 = it.get_local_id(1);
size_t identifiant = (id0 + hl) + hl * local_nx;
float c_x_loc[HALF_LENGTH_];
float c_z_loc[HALF_LENGTH_];
int v_loc[HALF_LENGTH_];
// Set local coeff.
for (unsigned int iter = 0; iter < HALF_LENGTH_; iter++) {
c_x_loc[iter] = c_x[iter];
c_z_loc[iter] = c_z[iter];
v_loc[iter] = (iter + 1) * local_nx;
}
bool copyHaloX = false;
if (id0 < HALF_LENGTH_)
copyHaloX = true;
const unsigned int items_X = it.get_local_range(1);
int load_identifiant = identifiant - hl * local_nx;
int load_idx = idx - hl * nx;
// Set Shared Memory.
for (int i = 0; i < local_nz; i++) {
local[load_identifiant] = current[load_idx];
if (copyHaloX) {
local[load_identifiant - HALF_LENGTH_] =
current[load_idx - HALF_LENGTH_];
local[load_identifiant + items_X] = current[load_idx + items_X];
}
load_idx += nx;
load_identifiant += local_nx;
}
it.barrier(access::fence_space::local_space);
for (int i = 0; i < idx_range; i++) {
float value = 0;
value = fma(local[identifiant], c_xyz, value);
for (int iter = 1; iter <= HALF_LENGTH_; iter++) {
value =
fma(local[identifiant - iter], c_x_loc[iter - 1], value);
value =
fma(local[identifiant + iter], c_x_loc[iter - 1], value);
}
for (int iter = 1; iter <= HALF_LENGTH_; iter++) {
value = fma(local[identifiant - v_loc[iter - 1]],
c_z_loc[iter - 1], value);
value = fma(local[identifiant + v_loc[iter - 1]],
c_z_loc[iter - 1], value);
}
value = fma(vel[idx], value, -prev[idx]);
value = fma(2.0f, local[identifiant], value);
next[idx] = value;
idx += nx;
identifiant += local_nx;
}
});
});
} else if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::GPU) {
int compute_nz = mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize() / mpParameters->GetBlockZ();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<2>(compute_nz, mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize());
auto local_range = range<2>(1, mpParameters->GetBlockX());
sycl::nd_range<2> workgroup_range(global_range, local_range);
const float *current = curr_base;
const float *prev = prev_base;
float *next = next_base;
const float *vel = vel_base;
const float *c_x = mpCoeffX->GetNativePointer();
const float *c_z = mpCoeffZ->GetNativePointer();
const float c_xyz = mCoeffXYZ;
const int *v = mpVerticalIdx->GetNativePointer();
const int idx_range = mpParameters->GetBlockZ();
const int pad = 0;
auto localRange_ptr_cur =
range<1>((mpParameters->GetBlockX() + (2 * hl) + pad));
/* Create an accessor for SLM buffer. */
accessor<float, 1, access::mode::read_write, access::target::local> tab(
localRange_ptr_cur, cgh);
cgh.parallel_for(workgroup_range, [=](nd_item<2> it) {
float *local = tab.get_pointer();
int idx = it.get_global_id(1) + hl +
(it.get_global_id(0) * idx_range + hl) * nx;
int id0 = it.get_local_id(1);
int identifiant = (id0 + hl);
float c_x_loc[HALF_LENGTH_];
float c_z_loc[HALF_LENGTH_];
int v_end = v[HALF_LENGTH_ - 1];
float front[HALF_LENGTH_ + 1];
float back[HALF_LENGTH_];
for (unsigned int iter = 0; iter <= HALF_LENGTH_; iter++) {
front[iter] = current[idx + nx * iter];
}
for (int iter = 1; iter <= HALF_LENGTH_; iter++) {
back[iter - 1] = current[idx - nx * iter];
c_x_loc[iter - 1] = c_x[iter - 1];
c_z_loc[iter - 1] = c_z[iter - 1];
}
bool copyHaloX = false;
if (id0 < HALF_LENGTH_)
copyHaloX = true;
const unsigned int items_X = it.get_local_range(1);
for (int i = 0; i < idx_range; i++) {
it.barrier(access::fence_space::local_space);
local[identifiant] = front[0];
if (copyHaloX) {
local[identifiant - HALF_LENGTH_] = current[idx - HALF_LENGTH_];
local[identifiant + items_X] = current[idx + items_X];
}
it.barrier(access::fence_space::local_space);
float value = 0;
value = fma(local[identifiant], c_xyz, value);
for (int iter = 1; iter <= HALF_LENGTH_; iter++) {
value =
fma(local[identifiant - iter], c_x_loc[iter - 1], value);
value =
fma(local[identifiant + iter], c_x_loc[iter - 1], value);
}
for (int iter = 1; iter <= HALF_LENGTH_; iter++) {
value = fma(front[iter], c_z_loc[iter - 1], value);
value = fma(back[iter - 1], c_z_loc[iter - 1], value);
}
value = fma(vel[idx], value, -prev[idx]);
value = fma(2.0f, local[identifiant], value);
next[idx] = value;
idx += nx;
for (unsigned int iter = HALF_LENGTH_ - 1; iter > 0; iter--) {
back[iter] = back[iter - 1];
}
back[0] = front[0];
for (unsigned int iter = 0; iter < HALF_LENGTH_; iter++) {
front[iter] = front[iter + 1];
}
// Only one new data-point read from global memory
// in z-dimension (depth)
front[HALF_LENGTH_] = current[idx + v_end];
}
});
});
}
Backend::GetInstance()->GetDeviceQueue()->wait();
timer.Stop();
auto t_end = std::chrono::high_resolution_clock::now();
double elapsed_time_ms = std::chrono::duration<double, std::milli>(t_end - t_start).count();
}
void SecondOrderComputationKernel::PreprocessModel() {
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
float dt2 = mpGridBox->GetDT() * mpGridBox->GetDT();
/*
* Preprocess the velocity model by calculating the dt2 * c2 component of
* the wave equation.
*/
Backend::GetInstance()->GetDeviceQueue()->submit(
[&](sycl::handler &cgh) {
auto global_range = range<2>(nx, nz);
float *vel_device = mpGridBox->Get(PARM | GB_VEL)->GetNativePointer();
cgh.parallel_for(global_range, [=](sycl::id<2> idx) {
int x = idx[0];
int z = idx[1];
float value = vel_device[z * nx + x];
vel_device[z * nx + x] =
value * value * dt2;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
| 19,193
|
C++
|
.cpp
| 357
| 38.285714
| 118
| 0.512414
|
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,142
|
StaggeredComputationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <bs/base/api/cpp/BSBase.hpp>
#include "operations/components/independents/concrete/computation-kernels/isotropic/StaggeredComputationKernel.hpp"
#include "operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp"
#include "operations/components/independents/concrete/computation-kernels/BaseComputationHelpers.hpp"
#include <bs/timer/api/cpp/BSTimer.hpp>
#include "fstream"
using namespace cl::sycl;
using namespace operations::components;
using namespace operations::dataunits;
using namespace operations::common;
using namespace bs::base::backend;
using namespace std;
using namespace bs::timer;
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::ComputePressure() {
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_y;
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 wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
float dx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
int block_x = this->mpParameters->GetBlockX();
int block_y = this->mpParameters->GetBlockY();
int block_z = this->mpParameters->GetBlockZ();
int wnxnz = wnx * wnz;
int nx = wnx;
int nz = wnz;
int nxnz = nx * nz;
int size = (wnx - 2 * HALF_LENGTH_) * (wnz - 2 * HALF_LENGTH_);
int flops_per_pressure = 6 * HALF_LENGTH_ + 3;
int num_of_arrays_pressure = 5;
ElasticTimer timer("ComputationKernel::ComputePressure",
size,
num_of_arrays_pressure,
true,
flops_per_pressure);
timer.Start();
if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::CPU) {
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
size_t num_groups = Backend::GetInstance()->GetWorkgroupNumber();
size_t wgsize = Backend::GetInstance()->GetWorkgroupSize();
int compute_nz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize();
int compute_nx = mpParameters->GetHalfLength() +
this->mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize();
size_t z_stride = (compute_nz + num_groups - 1) / num_groups;
auto global_range = range<1>(num_groups);
auto local_range = range<1>(wgsize);
const size_t wnx = nx;
const size_t wnz = nz;
float *coeff_x = mpCoeff->GetHostPointer();
float *coeff_z = mpCoeff->GetHostPointer();
const float *current = curr_base;
const float *vel = vel_base;
float *next = next_base;
float *vel_x = particle_vel_x;
float *vel_z = particle_vel_z;
float *den = den_base;
cgh.parallel_for_work_group(global_range, local_range, [=](group<1> grp) {
size_t z_id = grp.get_id(0) * z_stride + HALF_LENGTH_;
size_t end_z =
(z_id + z_stride) < (compute_nz + HALF_LENGTH_) ?
(z_id + z_stride) : (compute_nz + HALF_LENGTH_);
grp.parallel_for_work_item([&](h_item<1> it) {
for (size_t iz = z_id; iz < end_z; iz++) {
size_t offset = iz * wnx + it.get_local_id(0);
for (size_t ix = HALF_LENGTH_; ix < compute_nx; ix += wgsize) {
float value_x = 0;
float value_z = 0;
size_t idx = offset + ix;
DERIVE_SEQ_AXIS(idx, 0, 1, -, vel_x, coeff_x, value_x)
DERIVE_JUMP_AXIS(idx, wnx, 0, 1, -, vel_z, coeff_z, value_z)
if constexpr (KERNEL_MODE_ != KERNEL_MODE::INVERSE) {
next[idx] = current[idx] - vel[idx] * ((value_x / dx) + (value_z / dz));
} else {
next[idx] = current[idx] + vel[idx] * ((value_x / dx) + (value_z / dz));
}
}
}
});
});
});
} else if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::GPU_SHARED) {
int compute_nz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize();
int compute_nx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<2>(compute_nz, compute_nx);
auto local_range = range<2>(block_z, block_x);
auto workgroup_range = nd_range<2>(global_range, local_range);
const float *current = curr_base;
float *next = next_base;
const float *vel = vel_base;
float *vel_x = particle_vel_x;
float *vel_z = particle_vel_z;
const float *coeff = mpCoeff->GetNativePointer();
float *den = den_base;
const int idx_range = block_z;
const int local_nx = block_x + 2 * HALF_LENGTH_;
const int local_nz = block_z + 2 * HALF_LENGTH_;
auto localRange_ptr_cur = range<1>(((block_x + (2 * HALF_LENGTH_)) *
(block_z + (2 * HALF_LENGTH_))));
accessor<float, 1, access::mode::read_write, access::target::local> tab(localRange_ptr_cur, cgh);
cgh.parallel_for(workgroup_range, [=](nd_item<2> it) {
int idx = it.get_global_id(1) + HALF_LENGTH_ + (it.get_global_id(0) + HALF_LENGTH_) * nx;
int id0 = it.get_local_id(1);
int id1 = it.get_local_id(0);
float coeff_x_device[HALF_LENGTH_];
float coeff_z_device[HALF_LENGTH_];
for (int iter = 0; iter < HALF_LENGTH_; iter++) {
coeff_x_device[iter] = coeff[iter];
coeff_z_device[iter] = coeff[iter];
}
float value_x = 0;
float value_z = 0;
DERIVE_SEQ_AXIS(idx, 0, 1, -, vel_x, coeff_x_device, value_x)
DERIVE_JUMP_AXIS(idx, wnx, 0, 1, -, vel_z, coeff_z_device, value_z)
if constexpr (KERNEL_MODE_ != KERNEL_MODE::INVERSE) {
next[idx] = current[idx] - vel[idx] * ((value_x / dx) + (value_z / dz));
} else {
next[idx] = current[idx] + vel[idx] * ((value_x / dx) + (value_z / dz));
}
});
});
} else if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::GPU_SEMI_SHARED) {
int compute_nz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize() / block_z;
int compute_nx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<2>(compute_nz, compute_nx);
auto local_range = range<2>(1, block_x);
auto workgroup_range = nd_range<2>(global_range, local_range);
const float *current = curr_base;
float *next = next_base;
const float *vel = vel_base;
float *vel_x = particle_vel_x;
float *vel_z = particle_vel_z;
float *den = den_base;
const int idx_range = block_z;
const int local_nx = block_x + 2 * HALF_LENGTH_;
const float *coeff = mpCoeff->GetNativePointer();
auto localRange_ptr_cur = range<1>(((block_x + (2 * HALF_LENGTH_)) *
(block_z + (2 * HALF_LENGTH_))));
accessor<float, 1, access::mode::read_write, access::target::local> tab(
localRange_ptr_cur, cgh);
cgh.parallel_for(workgroup_range,
[=](nd_item<2> it) {
int idx = it.get_global_id(1) + HALF_LENGTH_ +
(it.get_global_id(0) * idx_range +
HALF_LENGTH_) * nx;
size_t id0 = it.get_local_id(1);
size_t offset = (id0 + HALF_LENGTH_) +
HALF_LENGTH_ * local_nx;
float coeff_x_device[HALF_LENGTH_];
float coeff_z_device[HALF_LENGTH_];
for (unsigned int iter = 0;
iter < HALF_LENGTH_; iter++) {
coeff_x_device[iter] = coeff[iter];
coeff_z_device[iter] = coeff[iter];
}
for (int i = 0; i < idx_range; i++) {
float value_x = 0, value_z = 0;
DERIVE_SEQ_AXIS(idx, 0, 1, -, vel_x, coeff_x_device, value_x)
DERIVE_JUMP_AXIS(idx, wnx, 0, 1, -, vel_z, coeff_z_device, value_z)
if constexpr (KERNEL_MODE_ != KERNEL_MODE::INVERSE) {
next[idx] = current[idx] - vel[idx] * ((value_x / dx) + (value_z / dz));
} else {
next[idx] = current[idx] + vel[idx] * ((value_x / dx) + (value_z / dz));
}
idx += nx;
}
});
});
} else if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::GPU) {
int compute_nz = mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize() / block_z;
int compute_nx = mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<2>(compute_nz, compute_nx);
auto local_range = range<2>(1, block_x);
auto workgroup_range = nd_range<2>(global_range, local_range);
const float *current = curr_base;
float *next = next_base;
float *vel_x = particle_vel_x;
float *vel_z = particle_vel_z;
float *vel = vel_base;
float *den = den_base;
const int idx_range = block_z;
const int local_nx = block_x + 2 * HALF_LENGTH_;
const int local_nz = block_x + 2 * HALF_LENGTH_;
const int pad = 0;
float *coeff = mpCoeff->GetNativePointer();
auto localRange_ptr_cur =
range<1>((block_x + (2 * HALF_LENGTH_) + pad));
accessor<float, 1, access::mode::read_write, access::target::local> tab(
localRange_ptr_cur, cgh);
cgh.parallel_for(workgroup_range,
[=](nd_item<2> it) {
int idx = it.get_global_id(1) + HALF_LENGTH_ +
(it.get_global_id(0) * idx_range +
HALF_LENGTH_) * nx;
int id0 = it.get_local_id(1);
float coeff_x_device[HALF_LENGTH_];
float coeff_z_device[HALF_LENGTH_];
for (int iter = 0; iter < HALF_LENGTH_; iter++) {
coeff_x_device[iter] = coeff[iter];
coeff_z_device[iter] = coeff[iter];
}
for (int i = 0; i < idx_range; i++) {
float value_x = 0, value_z = 0;
DERIVE_SEQ_AXIS(idx, 0, 1, -, vel_x, coeff_x_device, value_x)
DERIVE_JUMP_AXIS(idx, wnx, 0, 1, -, vel_z, coeff_z_device, value_z)
if constexpr (KERNEL_MODE_ != KERNEL_MODE::INVERSE) {
next[idx] = current[idx] - vel[idx] * ((value_x / dx) + (value_z / dz));
} else {
next[idx] = current[idx] + vel[idx] * ((value_x / dx) + (value_z / dz));
}
idx += nx;
}
});
});
}
Backend::GetInstance()->GetDeviceQueue()->wait();
timer.Stop();
}
template<KERNEL_MODE KERNEL_MODE_, bool IS_2D_, HALF_LENGTH HALF_LENGTH_>
void StaggeredComputationKernel::ComputeVelocity() {
float *curr_base = mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float *particle_vel_x = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_X)->GetNativePointer();
float *particle_vel_y;
float *particle_vel_z = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_Z)->GetNativePointer();
float *den_base = mpGridBox->Get(PARM | WIND | GB_DEN)->GetNativePointer();
float *vel_base = mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
float dx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
int block_x = this->mpParameters->GetBlockX();
int block_y = this->mpParameters->GetBlockY();
int block_z = this->mpParameters->GetBlockZ();
int nx = wnx;
int nz = wnz;
int size = (wnx - 2 * HALF_LENGTH_) * (wnz - 2 * HALF_LENGTH_);
int flops_per_velocity = 6 * HALF_LENGTH_ + 4;
int num_of_arrays_velocity = 6;
ElasticTimer timer("ComputationKernel::ComputeVelocity",
size,
num_of_arrays_velocity,
true,
flops_per_velocity);
timer.Start();
if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::CPU) {
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
size_t num_groups = Backend::GetInstance()->GetWorkgroupNumber();
size_t wgsize = Backend::GetInstance()->GetWorkgroupSize();
int compute_nz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize();
int compute_nx = mpParameters->GetHalfLength() +
this->mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize();
size_t z_stride = (compute_nz + num_groups - 1) / num_groups;
auto global_range = range<1>(num_groups);
auto local_range = range<1>(wgsize);
const float *current = curr_base;
float *vel_x = particle_vel_x;
float *vel_z = particle_vel_z;
const float *den = den_base;
const size_t wnx = nx;
const size_t wnz = nz;
float *coeff_x = mpCoeff->GetHostPointer();
float *coeff_z = mpCoeff->GetHostPointer();
float *vel = vel_base;
cgh.parallel_for_work_group(global_range, local_range, [=](group<1> grp) {
size_t z_id = grp.get_id(0) * z_stride + HALF_LENGTH_;
size_t end_z =
(z_id + z_stride) < (compute_nz + HALF_LENGTH_) ?
(z_id + z_stride) : (compute_nz + HALF_LENGTH_);
grp.parallel_for_work_item([&](h_item<1> it) {
for (size_t iz = z_id; iz < end_z; iz++) {
size_t offset = iz * wnx + it.get_local_id(0);
for (size_t ix = HALF_LENGTH_; ix < compute_nx; ix += wgsize) {
size_t idx = offset + ix;
float value_x = 0;
float value_z = 0;
DERIVE_SEQ_AXIS(idx, 1, 0, -, current, coeff_x, value_x)
DERIVE_JUMP_AXIS(idx, wnx, 1, 0, -, current, coeff_z, value_z)
if constexpr(KERNEL_MODE_ != KERNEL_MODE::INVERSE) {
vel_x[idx] = vel_x[idx] - (den[idx] / dx) * value_x;
vel_z[idx] = vel_z[idx] - (den[idx] / dz) * value_z;
} else {
vel_x[idx] = vel_x[idx] + (den[idx] / dx) * value_x;
vel_z[idx] = vel_z[idx] + (den[idx] / dz) * value_z;
}
}
}
});
});
});
} else if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::GPU_SHARED) {
int compute_nz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize();
int compute_nx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<2>(compute_nz, compute_nx);
auto local_range = range<2>(block_z, block_x);
sycl::nd_range<2> workgroup_range(global_range, local_range);
const float *current = curr_base;
const float *den = den_base;
float *vel = vel_base;
float *vel_x = particle_vel_x;
float *vel_z = particle_vel_z;
const float *coeff = mpCoeff->GetNativePointer();
const int idx_range = mpParameters->GetBlockZ();
const int local_nx = mpParameters->GetBlockX() + 2 * HALF_LENGTH_;
auto localRange_ptr_cur = range<1>(((mpParameters->GetBlockX() + (2 * HALF_LENGTH_)) *
(mpParameters->GetBlockZ() + (2 * HALF_LENGTH_))));
accessor<float, 1, access::mode::read_write, access::target::local> tab(
localRange_ptr_cur, cgh);
cgh.parallel_for(workgroup_range,
[=](nd_item<2> it) {
float *local = tab.get_pointer();
int idx =
it.get_global_id(1) + HALF_LENGTH_ +
(it.get_global_id(0) + HALF_LENGTH_) * nx;
size_t id0 = it.get_local_id(1);
size_t id1 = it.get_local_id(0);
size_t offset = (id0 + HALF_LENGTH_) +
(id1 + HALF_LENGTH_) * local_nx;
float coeff_x_device[HALF_LENGTH_];
float coeff_z_device[HALF_LENGTH_];
for (int iter = 0; iter < HALF_LENGTH_; iter++) {
coeff_x_device[iter] = coeff[iter];
coeff_z_device[iter] = coeff[iter];
}
bool copyHaloX = false;
bool copyHaloY = false;
const unsigned int items_X = it.get_local_range(1);
local[offset] = current[idx];
if (id0 < HALF_LENGTH_) {
copyHaloX = true;
}
if (id1 < HALF_LENGTH_) {
copyHaloY = true;
}
if (copyHaloX) {
local[offset - HALF_LENGTH_] = current[idx -
HALF_LENGTH_];
local[offset + items_X] = current[idx +
items_X];
}
if (copyHaloY) {
local[offset -
HALF_LENGTH_ * local_nx] = current[idx -
HALF_LENGTH_ *
nx];
local[offset + idx_range * local_nx] = current[
idx + idx_range * nx];
}
it.barrier(access::fence_space::local_space);
float value_x = 0;
float value_z = 0;
for (int iter = 0; iter < HALF_LENGTH_; ++iter) {
value_x += coeff_x_device[iter] *
(local[offset + (iter + 1)] -
local[offset - iter]);
value_z += coeff_z_device[iter] *
(local[offset +
((iter + 1) * local_nx)] -
local[offset - (iter * local_nx)]);
}
if constexpr (KERNEL_MODE_ != KERNEL_MODE::INVERSE) {
vel_x[idx] =
vel_x[idx] - (den[idx] / dx) * value_x;
vel_z[idx] =
vel_z[idx] - (den[idx] / dz) * value_z;
} else {
vel_x[idx] =
vel_x[idx] + (den[idx] / dx) * value_x;
vel_z[idx] =
vel_z[idx] + (den[idx] / dz) * value_z;
}
});
});
} else if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::GPU_SEMI_SHARED) {
int compute_nz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize() / block_z;
int compute_nx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<2>(compute_nz, compute_nx);
auto local_range = range<2>(1, block_x);
auto workgroup_range = nd_range<2>(global_range, local_range);
const float *current = curr_base;
float *vel_x = particle_vel_x;
float *vel_z = particle_vel_z;
const float *den = den_base;
float *vel = vel_base;
const int idx_range = block_z;
const int local_nx = block_x + 2 * HALF_LENGTH_;
const int local_nz = block_z + 2 * HALF_LENGTH_;
float *coeff = mpCoeff->GetNativePointer();
auto localRange_ptr_cur = range<1>(((block_x + (2 * HALF_LENGTH_)) *
(block_z + (2 * HALF_LENGTH_))));
accessor<float, 1, access::mode::read_write, access::target::local> tab(
localRange_ptr_cur, cgh);
cgh.parallel_for(workgroup_range,
[=](nd_item<2> it) {
float *local = tab.get_pointer();
int idx = it.get_global_id(1) + HALF_LENGTH_ +
(it.get_global_id(0) * idx_range +
HALF_LENGTH_) * nx;
size_t id0 = it.get_local_id(1);
size_t offset = (id0 + HALF_LENGTH_) +
HALF_LENGTH_ * local_nx;
float coeff_x_device[HALF_LENGTH_];
float coeff_z_device[HALF_LENGTH_];
for (unsigned int iter = 0;
iter < HALF_LENGTH_; iter++) {
coeff_x_device[iter] = coeff[iter];
coeff_z_device[iter] = coeff[iter];
}
bool copyHaloX = false;
if (id0 < HALF_LENGTH_)
copyHaloX = true;
const unsigned int items_X = it.get_local_range(1);
int load_offset = offset - HALF_LENGTH_ * local_nx;
int load_idx = idx - HALF_LENGTH_ * nx;
for (int i = 0; i < local_nz; i++) {
local[load_offset] = current[load_idx];
if (copyHaloX) {
local[load_offset -
HALF_LENGTH_] = current[load_idx -
HALF_LENGTH_];
local[load_offset + items_X] = current[
load_idx + items_X];
}
load_idx += nx;
load_offset += local_nx;
}
it.barrier(access::fence_space::local_space);
for (int i = 0; i < idx_range; i++) {
float value_x = 0, value_z = 0;
for (int iter = 0;
iter < HALF_LENGTH_; ++iter) {
value_x += coeff_x_device[iter] *
(local[offset + (iter + 1)] -
local[offset - iter]);
value_z += coeff_z_device[iter] *
(local[offset + ((iter + 1) *
local_nx)] -
local[offset -
(iter * local_nx)]);
}
if constexpr (KERNEL_MODE_ != KERNEL_MODE::INVERSE) {
vel_x[idx] =
vel_x[idx] - (den[idx] / dx) * value_x;
vel_z[idx] =
vel_z[idx] - (den[idx] / dz) * value_z;
} else {
vel_x[idx] =
vel_x[idx] + (den[idx] / dx) * value_x;
vel_z[idx] =
vel_z[idx] + (den[idx] / dz) * value_z;
}
idx += nx;
offset += local_nx;
}
});
});
} else if (Backend::GetInstance()->GetAlgorithm() == SYCL_ALGORITHM::GPU) {
int compute_nz = mpGridBox->GetWindowAxis()->GetZAxis().GetComputationAxisSize() / mpParameters->GetBlockZ();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<2>(compute_nz, mpGridBox->GetWindowAxis()->GetXAxis().GetComputationAxisSize());
auto local_range = range<2>(1, block_x);
auto workgroup_range = nd_range<2>(global_range, local_range);
const float *current = curr_base;
float *vel_x = particle_vel_x;
float *vel_z = particle_vel_z;
const float *den = den_base;
const int idx_range = block_z;
const int local_nx = block_x + 2 * HALF_LENGTH_;
// const int local_nz = block_z + 2 * HALF_LENGTH_;
const int pad = 0;
float *coeff = mpCoeff->GetNativePointer();
const int *v = mpVerticalIdx->GetNativePointer();
auto localRange_ptr_cur =
range<1>((block_x + (2 * HALF_LENGTH_) + pad));
accessor<float, 1, access::mode::read_write, access::target::local> tab(
localRange_ptr_cur, cgh);
cgh.parallel_for(workgroup_range,
[=](nd_item<2> it) {
float *local = tab.get_pointer();
int idx = it.get_global_id(1) + HALF_LENGTH_ +
(it.get_global_id(0) * idx_range +
HALF_LENGTH_) * nx;
int id0 = it.get_local_id(1);
int offset = (id0 + HALF_LENGTH_);
float coeff_x_device[HALF_LENGTH_];
float coeff_z_device[HALF_LENGTH_];
int v_end = v[HALF_LENGTH_ - 1];
float front[HALF_LENGTH_ + 1];
float back[HALF_LENGTH_];
for (unsigned int iter = 0;
iter <= HALF_LENGTH_; iter++) {
front[iter] = current[idx + nx * iter];
}
for (int iter = 1; iter <= HALF_LENGTH_; iter++) {
back[iter - 1] = current[idx - nx * iter];
coeff_x_device[iter - 1] = coeff[iter - 1];
coeff_z_device[iter - 1] = coeff[iter - 1];
}
bool copyHaloX = false;
if (id0 < HALF_LENGTH_)
copyHaloX = true;
const unsigned int items_X = it.get_local_range(1);
for (int i = 0; i < idx_range; i++) {
it.barrier(access::fence_space::local_space);
local[offset] = front[0];
if (copyHaloX) {
local[offset - HALF_LENGTH_] = current[
idx - HALF_LENGTH_];
local[offset + items_X] = current[idx +
items_X];
}
it.barrier(access::fence_space::local_space);
float value_x = 0, value_z = 0;
for (int iter = 0;
iter < HALF_LENGTH_; ++iter) {
value_x += coeff_x_device[iter] *
(current[idx + (iter + 1)] -
current[idx - iter]);
value_z += coeff_z_device[iter] *
(current[idx +
((iter + 1) * nx)] -
current[idx - (iter * nx)]);
}
if constexpr (KERNEL_MODE_ != KERNEL_MODE::INVERSE) {
vel_x[idx] =
vel_x[idx] - (den[idx] / dx) * value_x;
vel_z[idx] =
vel_z[idx] - (den[idx] / dz) * value_z;
} else {
vel_x[idx] =
vel_x[idx] + (den[idx] / dx) * value_x;
vel_z[idx] =
vel_z[idx] + (den[idx] / dz) * value_z;
}
idx += nx;
}
});
});
}
Backend::GetInstance()->GetDeviceQueue()->wait();
timer.Stop();
}
void StaggeredComputationKernel::PreprocessModel() {
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
float dt = this->mpGridBox->GetDT();
int full_nx = nx;
int full_nx_nz = nx * nz;
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_range = range<3>(nx, ny, nz);
auto local_range = range<3>(1, 1, 1);
auto global_nd_range = nd_range<3>(global_range, local_range);
float *velocity_values = this->mpGridBox->Get(PARM | GB_VEL)->GetNativePointer();
float *density_values = this->mpGridBox->Get(PARM | GB_DEN)->GetNativePointer();
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int x = it.get_global_id(0);
int y = it.get_global_id(1);
int z = it.get_global_id(2);
int offset = y * full_nx_nz + z * full_nx + x;
float value = velocity_values[offset];
velocity_values[offset] = value * value * dt * density_values[offset];
if (density_values[offset] != 0) {
density_values[offset] = dt / density_values[offset];
}
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
| 36,673
|
C++
|
.cpp
| 602
| 37.586379
| 118
| 0.439144
|
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,143
|
SpongeBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <bs/base/backend/Backend.hpp>
using namespace std;
using namespace cl::sycl;
using namespace bs::base::backend;
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 nx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int ny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int nz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
int original_nx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetAxisSize();
int original_nz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetAxisSize();
uint bound_length = mpParameters->GetBoundaryLength();
uint half_length = mpParameters->GetHalfLength();
int y_start = half_length + bound_length;
int y_end = lny - half_length - bound_length;
float *dev_sponge_coeffs = this->mpSpongeCoefficients->GetNativePointer();
if (ny == 1) {
y_start = 0;
y_end = 1;
}
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.parallel_for(range<3>(original_nx,
y_end - y_start,
(half_length + bound_length - 1) - (half_length) + 1),
[=](id<3> i) {
int ix = i[0] + (half_length + bound_length);
int iy = i[1] + y_start;
int iz = (half_length + bound_length - 1) - 1 - i[2] + 1;
next[iy * nx * nz + iz * nx + ix] *= dev_sponge_coeffs[iz - half_length];
next[iy * nx * nz + (iz + lnz - 2 * iz - 1) * nx +
ix] *= dev_sponge_coeffs[iz - half_length];
});
});
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.parallel_for(range<3>((half_length + bound_length - 1) - (half_length) + 1,
y_end - y_start,
original_nz),
[=](id<3> i) {
int ix = (half_length + bound_length - 1) - 1 - i[0] + 1;
int iy = i[1] + y_start;
int iz = i[2] + (half_length + bound_length);
next[iy * nx * nz + iz * nx + ix] *= dev_sponge_coeffs[ix - half_length];
next[iy * nx * nz + iz * nx +
(ix + lnx - 2 * ix - 1)] *= dev_sponge_coeffs[ix - half_length];
});
});
if (ny > 1) {
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.parallel_for(range<3>(original_nx,
(half_length + bound_length - 1) - (half_length) + 1,
original_nz), [=](id<3> i) {
int ix = i[0] + (half_length + bound_length);
int iy = (half_length + bound_length - 1) - 1 - i[1] + 1;
int iz = i[2] + (half_length + bound_length);
next[iy * nx * nz + iz * nx + ix] *= dev_sponge_coeffs[iy - half_length];
next[(iy + lny - 2 * iy - 1) * nx * nz + iz * nx + ix] *= dev_sponge_coeffs[iy -
half_length];
});
});
}
int start_y = y_start;
int start_x = half_length;
int start_z = half_length;
int end_y = y_end;
int end_x = lnx - half_length;
int end_z = lnz - half_length;
int nz_nx = nx * nz;
// Zero-Corners in the boundaries nx-nz boundary intersection--boundaries not needed.
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.parallel_for(range<3>(end_y - start_y,
bound_length,
bound_length), [=](id<3> i) {
int depth = i[0] + start_y;
int row = i[1];
int column = i[2];
next[depth * nz_nx + (start_z + row) * nx + column + start_x] *= std::min(dev_sponge_coeffs[column],
dev_sponge_coeffs[row]);
next[depth * nz_nx + (end_z - 1 - row) * nx + column + start_x] *= std::min(dev_sponge_coeffs[column],
dev_sponge_coeffs[row]);
next[depth * nz_nx + (start_z + row) * nx + (end_x - 1 - column)] *= std::min(dev_sponge_coeffs[column],
dev_sponge_coeffs[row]);
next[depth * nz_nx + (end_z - 1 - row) * nx + (end_x - 1 - column)] *= std::min(dev_sponge_coeffs[column],
dev_sponge_coeffs[row]);
});
});
// If 3-D, zero corners in the y-x and y-z plans.
if (ny > 1) {
// Zero-Corners in the boundaries ny-nz boundary intersection--boundaries not needed.
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.parallel_for(range<3>(bound_length,
bound_length,
end_x - start_x), [=](id<3> i) {
int depth = i[0];
int row = i[1];
int column = i[2] + start_x;
next[(depth + start_y) * nz_nx + (start_z + row) * nx + column] *= std::min(dev_sponge_coeffs[depth],
dev_sponge_coeffs[row]);
next[(depth + start_y) * nz_nx + (end_z - 1 - row) * nx + column] *= std::min(dev_sponge_coeffs[depth],
dev_sponge_coeffs[row]);
next[(end_y - 1 - depth) * nz_nx + (start_z + row) * nx + column] *= std::min(dev_sponge_coeffs[depth],
dev_sponge_coeffs[row]);
next[(end_y - 1 - depth) * nz_nx + (end_z - 1 - row) * nx + column] *= std::min(
dev_sponge_coeffs[depth],
dev_sponge_coeffs[row]);
});
});
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.parallel_for(range<3>(bound_length,
end_z - start_z,
bound_length), [=](id<3> i) {
int depth = i[0];
int row = i[1] + start_z;
int column = i[2];
next[(depth + start_y) * nz_nx + row * nx + column + start_x] *= std::min(dev_sponge_coeffs[column],
dev_sponge_coeffs[depth]);
next[(end_y - 1 - depth) * nz_nx + row * nx + column + start_x] *= std::min(dev_sponge_coeffs[column],
dev_sponge_coeffs[depth]);
next[(depth + start_y) * nz_nx + row * nx + (end_x - 1 - column)] *= std::min(dev_sponge_coeffs[column],
dev_sponge_coeffs[depth]);
next[(end_y - 1 - depth) * nz_nx + row * nx + (end_x - 1 - column)] *= std::min(
dev_sponge_coeffs[column],
dev_sponge_coeffs[depth]);
});
});
}
Backend::GetInstance()->GetDeviceQueue()->wait();
}
| 9,303
|
C++
|
.cpp
| 158
| 40.449367
| 151
| 0.478499
|
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,144
|
CPMLBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <bs/base/backend/Backend.hpp>
#include <operations/components/independents/concrete/boundary-managers/CPMLBoundaryManager.hpp>
#include <operations/components/independents/concrete/computation-kernels/BaseComputationHelpers.hpp>
using namespace cl::sycl;
using namespace bs::base::backend;
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() {
//DIRECTION_ 1 means in x , DIRECTION_ 2 means in z , else means in y;
float *curr_base = mpGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int bound_length = this->mpParameters->GetBoundaryLength();
int WIDTH = bound_length + 2 * HALF_LENGTH_;
int ny = mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
int nxEnd = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int nyEnd = 1;
int nzEnd = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int wnxnz = wnx * wnz;
int y_start = 0;
if (ny != 1) {
y_start = HALF_LENGTH_;
nyEnd = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_;
}
float *aux = nullptr, *coeff_a = nullptr, *coeff_b = nullptr;
int z_start = HALF_LENGTH_;
int x_start = HALF_LENGTH_;
float *first_coeff_h;
int *distance;
float *first_coeff_h_1;
int *distance_1;
// 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 {
coeff_a = this->mpCoeffay->GetNativePointer();
coeff_b = this->mpCoeffby->GetNativePointer();
first_coeff_h = this->mpFirstCoeffy->GetNativePointer();
distance = this->mpDistanceDim3->GetNativePointer();
if (!OPPOSITE_) {
y_start = HALF_LENGTH_;
nyEnd = bound_length + HALF_LENGTH_;
aux = this->mpAux1yup->GetNativePointer();
} else {
y_start = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_ - bound_length;
nyEnd = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_;
aux = this->mpAux1ydown->GetNativePointer();
}
}
first_coeff_h_1 = &first_coeff_h[1];
distance_1 = &distance[1];
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.parallel_for(range<3>(nxEnd - x_start,
nyEnd - y_start,
nzEnd - z_start),
[=](id<3> i) {
int ix = i[0] + x_start;
int iy = i[1] + y_start;
int iz = i[2] + z_start;
int offset = iy * wnxnz + iz * wnx;
float *curr = curr_base + offset;
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 = iy * wnz * WIDTH + iz * WIDTH + (ix - x_start + HALF_LENGTH_);
} else {
coeff_ind = bound_length - ix + HALF_LENGTH_ - 1;
index = iy * wnz * WIDTH + iz * WIDTH + ix;
}
} else if (DIRECTION_ == Z_AXIS) { // case z
if (OPPOSITE_) {
coeff_ind = iz - z_start;
index = iy * wnx * WIDTH + (iz - z_start + HALF_LENGTH_) * wnx + ix;
} else {
coeff_ind = bound_length - iz + HALF_LENGTH_ - 1;
index = iy * wnx * WIDTH + iz * wnx + ix;
}
} else { // case y
if (OPPOSITE_) {
coeff_ind = iy - y_start;
index = (iy - y_start + HALF_LENGTH_) * wnx * wnz + (iz * wnx) + ix;
} else {
coeff_ind = bound_length - iy + HALF_LENGTH_ - 1;
index = iy * wnx * wnz + (iz * wnx) + ix;
}
} // case y
aux[index] =
coeff_a[coeff_ind] * aux[index] + coeff_b[coeff_ind] * value;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
template<int DIRECTION_, bool OPPOSITE_, int HALF_LENGTH_>
void CPMLBoundaryManager::CalculateCPMLValue() {
float *curr_base = mpGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
float *next_base = mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
int bound_length = this->mpParameters->GetBoundaryLength();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
float *vel_base = mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer();
int nxEnd = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int nyEnd = 1;
int nzEnd = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - HALF_LENGTH_;
int wnxnz = wnx * wnz;
int y_start = 0;
if (wny > 1) {
y_start = HALF_LENGTH_;
nyEnd = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_;
}
float *aux_first = nullptr, *aux_second = nullptr,
*coeff_a = nullptr, *coeff_b = nullptr;
int z_start = HALF_LENGTH_;
int x_start = HALF_LENGTH_;
int WIDTH = bound_length + 2 * HALF_LENGTH_;
int half_length = 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 {
coeff_a = this->mpCoeffay->GetNativePointer();
coeff_b = this->mpCoeffby->GetNativePointer();
distance = this->mpDistanceDim3->GetNativePointer();
coeff_first_h = this->mpFirstCoeffy->GetNativePointer();
coeff_h = this->mpSecondCoeffy->GetNativePointer();
if (!OPPOSITE_) {
y_start = half_length;
nyEnd = bound_length + half_length;
aux_first = this->mpAux1yup->GetNativePointer();
aux_second = this->mpAux2yup->GetNativePointer();
} else {
y_start = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - half_length - bound_length;
nyEnd = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - half_length;
aux_first = this->mpAux1ydown->GetNativePointer();
aux_second = this->mpAux2ydown->GetNativePointer();
}
}
auto distance_1 = &distance[1];
auto coeff_h_1 = &coeff_h[1];
auto coeff_first_h_1 = &coeff_first_h[1];
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.parallel_for(range<3>(nxEnd - x_start,
nyEnd - y_start,
nzEnd - z_start),
[=](id<3> i) {
int ix = i[0] + x_start;
int iy = i[1] + y_start;
int iz = i[2] + z_start;
int offset = iy * wnxnz + iz * wnx;
float *curr = curr_base + offset;
float *vel = vel_base + offset;
float *next = next_base + offset;
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 =
iy * wnz * WIDTH + iz * WIDTH + (ix - x_start + half_length);
} else {
coeff_ind = bound_length - ix + half_length - 1;
index = iy * wnz * WIDTH + iz * WIDTH + ix;
}
} else if (DIRECTION_ == Z_AXIS) { // case z
if (OPPOSITE_) {
coeff_ind = iz - z_start;
index = iy * wnx * WIDTH + (iz - z_start + half_length) * wnx + ix;
} else {
coeff_ind = bound_length - iz + half_length - 1;
index = iy * wnx * WIDTH + iz * wnx + ix;
}
} else { // case y
if (OPPOSITE_) {
coeff_ind = iy - y_start;
index = (iy - y_start + half_length) * wnx * wnz + (iz * wnx) + ix;
} else {
coeff_ind = bound_length - iy + half_length - 1;
index = iy * wnx * wnz + (iz * wnx) + ix;
}
}// case y
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 dervative 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;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
| 15,755
|
C++
|
.cpp
| 287
| 38.947735
| 118
| 0.521322
|
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,145
|
StaggeredCPMLBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <bs/base/api/cpp/BSBase.hpp>
#include "operations/components/independents/concrete/boundary-managers/StaggeredCPMLBoundaryManager.hpp"
#include <operations/components/independents/concrete/computation-kernels/BaseComputationHelpers.hpp>
#include <bs/base/exceptions/concrete/NotImplementedException.hpp>
#include <bs/base/exceptions/concrete/IllogicalException.hpp>
using namespace cl::sycl;
using namespace operations::components;
using namespace bs::base::backend;
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() {
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)
dh = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float inv_dh = 1.0f / dh;
int y_start = 0;
int y_end = 1;
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 wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
int wnzwnx = wnx * wnz;
if (wny > 1) {
y_start = HALF_LENGTH_;
y_end = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_;
}
float *aux_variable;
float *small_a;
float *small_b;
float *particle_velocity;
float *coeff = &mpCoeff->GetNativePointer()[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_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();
small_a = this->mpSmall_a_x->GetNativePointer();
small_b = this->mpSmall_b_x->GetNativePointer();
jump = 1;
aux_nx = b_l;
aux_nz = lnz - 2 * HALF_LENGTH_;
break;
case Y_AXIS:
y_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_vel_y_down->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_vel_y_up->GetNativePointer();
}
particle_velocity = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_Y)->GetNativePointer();
small_a = this->mpSmall_a_y->GetNativePointer();
small_b = this->mpSmall_b_y->GetNativePointer();
jump = wnzwnx;
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = b_l;
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();
small_a = this->mpSmall_a_z->GetNativePointer();
small_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();
}
int aux_nxnz = aux_nx * aux_nz;
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.parallel_for(range<3>(x_end - x_start,
y_end - y_start,
z_end - z_start), [=](id<3> i) {
int active_bound_index;
int x = i[0] + x_start;
int y = i[1] + y_start;
int z = i[2] + z_start;
int real_x = i[0] + x_start;
int real_y = i[1] + y_start;
int real_z = i[2] + z_start;
float value = 0.0f;
if constexpr (DIRECTION_ == X_AXIS) {
active_bound_index = x;
if constexpr(OPPOSITE_) {
real_x = lnx - 1 - x;
}
} else if constexpr(DIRECTION_ == Z_AXIS) {
active_bound_index = z;
if constexpr(OPPOSITE_) {
real_z = lnz - 1 - z;
}
} else {
active_bound_index = y;
if constexpr(OPPOSITE_) {
real_y = lny - 1 - y;
}
}
int offset;
offset = real_x + wnx * real_z + real_y * wnzwnx;
DERIVE_JUMP_AXIS(offset, jump, 0, 1, -, particle_velocity, coeff, value)
int offset3 = b_l + HALF_LENGTH_ - 1 - active_bound_index;
int aux_offset = (x - HALF_LENGTH_) + (z - HALF_LENGTH_) * aux_nx +
(y - y_start) * aux_nxnz;
aux_variable[aux_offset] = small_a[offset3] *
aux_variable[aux_offset] +
small_b[offset3] * inv_dh *
value;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
template<bool ADJOINT_, int DIRECTION_, bool OPPOSITE_, int HALF_LENGTH_>
void StaggeredCPMLBoundaryManager::CalculateVelocityCPMLValue() {
int y_start = 0;
int y_end = 1;
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 wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
int wnzwnx = wnx * wnz;
if (wny > 1) {
y_start = HALF_LENGTH_;
y_end = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_;
}
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 Y_AXIS:
y_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_ptr_y_down->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_ptr_y_up->GetNativePointer();
}
particle_velocity = this->mpGridBox->Get(WAVE | GB_PRTC | CURR | DIR_Y)->GetNativePointer();
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = b_l;
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;
}
int aux_nxnz = aux_nx * aux_nz;
float *parameter_base;
parameter_base = this->mpGridBox->Get(PARM | WIND | GB_DEN)->GetNativePointer();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.parallel_for(range<3>(x_end - x_start,
y_end - y_start,
z_end - z_start),
[=](id<3> i) {
int x = i[0] + x_start;
int y = i[1] + y_start;
int z = i[2] + z_start;
int real_x = i[0] + x_start;
int real_y = i[1] + y_start;
int real_z = i[2] + z_start;
if constexpr (DIRECTION_ == X_AXIS) {
if constexpr(OPPOSITE_) {
real_x = lnx - 1 - x;
}
} else if constexpr(DIRECTION_ == Z_AXIS) {
if constexpr(OPPOSITE_) {
real_z = lnz - 1 - z;
}
} else {
if constexpr(OPPOSITE_) {
real_y = lny - 1 - y;
}
}
int offset = real_x + wnx * real_z + real_y * wnzwnx;
int aux_offset = (x - HALF_LENGTH_) + (z - HALF_LENGTH_) * aux_nx +
(y - y_start) * aux_nxnz;
particle_velocity[offset] =
particle_velocity[offset] -
parameter_base[offset] * aux_variable[aux_offset];
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
template<bool ADJOINT_, int DIRECTION_, bool OPPOSITE_, int HALF_LENGTH_>
void StaggeredCPMLBoundaryManager::CalculatePressureFirstAuxiliary() {
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)
dh = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float *curr_base = this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
float inv_dh = 1.0f / dh;
int y_start = 0;
int y_end = 1;
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 wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
int wnzwnx = wnx * wnz;
if (wny > 1) {
y_start = HALF_LENGTH_;
y_end = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_;
}
float *aux_variable;
float *small_a;
float *small_b;
float *coeff = &mpCoeff->GetNativePointer()[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();
}
small_a = this->mpSmall_a_x->GetNativePointer();
small_b = this->mpSmall_b_x->GetNativePointer();
jump = 1;
aux_nx = b_l;
aux_nz = lnz - 2 * HALF_LENGTH_;
break;
case Y_AXIS:
y_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_ptr_y_down->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_ptr_y_up->GetNativePointer();
}
small_a = this->mpSmall_a_y->GetNativePointer();
small_b = this->mpSmall_b_y->GetNativePointer();
jump = wnzwnx;
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = b_l;
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();
}
small_a = this->mpSmall_a_z->GetNativePointer();
small_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();
}
int aux_nxnz = aux_nx * aux_nz;
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.parallel_for(range<3>(x_end - x_start,
y_end - y_start,
z_end - z_start), [=](id<3> i) {
int active_bound_index;
int x = i[0] + x_start;
int y = i[1] + y_start;
int z = i[2] + z_start;
int real_x = i[0] + x_start;
int real_y = i[1] + y_start;
int real_z = i[2] + z_start;
float value = 0.0f;
if constexpr (DIRECTION_ == X_AXIS) {
active_bound_index = x;
if constexpr(OPPOSITE_) {
real_x = lnx - 1 - x;
}
} else if constexpr(DIRECTION_ == Z_AXIS) {
active_bound_index = z;
if constexpr(OPPOSITE_) {
real_z = lnz - 1 - z;
}
} else {
active_bound_index = y;
if constexpr(OPPOSITE_) {
real_y = lny - 1 - y;
}
}
int offset;
offset = real_x + wnx * real_z + real_y * wnzwnx;
DERIVE_JUMP_AXIS(offset, jump, 1, 0, -, curr_base, coeff, value)
int offset3 = b_l + HALF_LENGTH_ - 1 - active_bound_index;
int aux_offset = (x - HALF_LENGTH_) + (z - HALF_LENGTH_) * aux_nx +
(y - y_start) * aux_nxnz;
aux_variable[aux_offset] =
small_a[offset3] *
aux_variable[aux_offset] +
small_b[offset3] * inv_dh *
value;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
template<bool ADJOINT_, int DIRECTION_, bool OPPOSITE_, int HALF_LENGTH_>
void StaggeredCPMLBoundaryManager::CalculatePressureCPMLValue() {
int y_start = 0;
int y_end = 1;
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 wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
int wnzwnx = wnx * wnz;
if (wny > 1) {
y_start = HALF_LENGTH_;
y_end = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - HALF_LENGTH_;
}
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:
y_end = HALF_LENGTH_ + b_l;
if (OPPOSITE_) {
aux_variable = this->mpAuxiliary_vel_y_down->GetNativePointer();
} else {
aux_variable = this->mpAuxiliary_vel_y_up->GetNativePointer();
}
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = b_l;
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();
}
aux_nx = lnx - 2 * HALF_LENGTH_;
aux_nz = lnz - 2 * HALF_LENGTH_;
break;
default:
throw bs::base::exceptions::ILLOGICAL_EXCEPTION();
break;
}
int aux_nxnz = aux_nx * aux_nz;
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();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.parallel_for(range<3>(x_end - x_start,
y_end - y_start,
z_end - z_start),
[=](id<3> i) {
int x = i[0] + x_start;
int y = i[1] + y_start;
int z = i[2] + z_start;
int real_x = i[0] + x_start;
int real_y = i[1] + y_start;
int real_z = i[2] + z_start;
if constexpr (DIRECTION_ == X_AXIS) {
if constexpr(OPPOSITE_) {
real_x = lnx - 1 - x;
}
} else if constexpr(DIRECTION_ == Z_AXIS) {
if constexpr(OPPOSITE_) {
real_z = lnz - 1 - z;
}
} else {
if constexpr(OPPOSITE_) {
real_y = lny - 1 - y;
}
}
int offset = real_x + wnx * real_z + real_y * wnzwnx;
int aux_offset = (x - HALF_LENGTH_) + (z - HALF_LENGTH_) * aux_nx +
(y - y_start) * aux_nxnz;
curr_base[offset] =
curr_base[offset] - parameter_base[offset] * aux_variable[aux_offset];
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
| 21,910
|
C++
|
.cpp
| 473
| 33.348837
| 107
| 0.529588
|
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,146
|
RandomExtension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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"
#include <bs/base/backend/Backend.hpp>
using namespace cl::sycl;
using namespace std;
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::dataunits;
using namespace bs::base::backend;
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_sidelength = this->mGrainSideLength; // in meters
int stride_x = grain_sidelength / dx;
int stride_z = grain_sidelength / dz;
int stride_y = 0;
if (aNy != 1) {
stride_y = grain_sidelength / dy;
}
/**
* copy to host memory
*/
int allocated_memory = aNx * aNy * aNz * sizeof(float);
float *property_array_host = (float *) malloc(allocated_memory);
Device::MemCpy(property_array_host, apPropertyArray, allocated_memory);
/*
* compute maximum value of the property
*/
float max_velocity = 0;
max_velocity = *max_element(property_array_host, property_array_host + 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;
property_array_host[index] = abs(property_array_host[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;
property_array_host[index] = abs(property_array_host[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 {
id_x = left_point_seed.x;
id_z = left_point_seed.z;
}
if (id_z >= aEndZ - aBoundaryLength) {
id_z = left_point_seed.z;
}
property_array_host[left_point.z * aNx + left_point.x] = property_array_host[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;
}
property_array_host[right_point.z * aNx + right_point.x] = property_array_host[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;
property_array_host[index] = abs(property_array_host[(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;
}
property_array_host[bottom_point.z * aNx + bottom_point.x] = property_array_host[id_z * aNx + id_x];
}
}
seeds.clear();
/**
* reflect to device memory
*/
Device::MemCpy(apPropertyArray, property_array_host, allocated_memory);
}
void
RandomExtension::TopLayerExtensionHelper(float *apPropertyArray,
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.
}
void
RandomExtension::TopLayerRemoverHelper(float *apPropertyArray,
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.
}
| 11,349
|
C++
|
.cpp
| 266
| 30.12406
| 119
| 0.509116
|
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,147
|
MinExtension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <vector>
#include <operations/components/independents/concrete/boundary-managers/extensions/MinExtension.hpp>
#include <bs/base/backend/Backend.hpp>
using namespace std;
using namespace cl::sycl;
using namespace bs::base::backend;
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 min_velocity = MAXFLOAT;
float *dev_min_velocity = (float *) cl::sycl::malloc_device(
sizeof(float) * 1,
Backend::GetInstance()->GetDeviceQueue()->get_device(),
Backend::GetInstance()->GetDeviceQueue()->get_context());
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.memcpy(dev_min_velocity, &min_velocity, sizeof(float) * 1);
});
Backend::GetInstance()->GetDeviceQueue()->wait();
// In case of 2D
if (ny == 1) {
end_y = 1;
start_y = 0;
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.single_task([=]() {
// Get maximum property_array value
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++) {
if (dev_min_velocity[0] > property_array[row * nx + column]) {
dev_min_velocity[0] = property_array[row * nx + column];
}
}
}
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.memcpy(&min_velocity, dev_min_velocity, sizeof(float) * 1);
});
Backend::GetInstance()->GetDeviceQueue()->wait();
} else {
// Get maximum property_array value.
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.single_task([=]() {
// 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++) {
if (dev_min_velocity[0] >
property_array[depth * nz_nx + row * nx + column]) {
dev_min_velocity[0] =
property_array[depth * nz_nx + row * nx + column];
}
}
}
}
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
cgh.memcpy(&min_velocity, dev_min_velocity, sizeof(float) * 1);
});
Backend::GetInstance()->GetDeviceQueue()->wait();
/*!putting random values for velocities at the boundaries for y and with all
* x and z */
vector<uint> gridDims{(uint) end_x - start_x, boundary_length, (uint) end_z - start_z};
vector<uint> blockDims{1, 1, 1};
auto configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0) + start_x;
int depth = it.get_global_id(1);
int row = it.get_global_id(2) + start_z;
/*! Create temporary value */
float temp =
min_velocity;
/*!for values from x = HALF_LENGTH TO x= HALF_LENGTH +BOUND_LENGTH*/
int p_idx = (depth + start_y) * nz_nx + row * nx + column;
property_array[p_idx] = temp;
/*! Create temporary value */
temp = min_velocity;
/*!for values from x = nx-HALF_LENGTH TO x =
* nx-HALF_LENGTH-BOUND_LENGTH*/
p_idx = (end_y - 1 - depth) * nz_nx + row * nx + column;
property_array[p_idx] = temp;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
/*!putting random values for velocities at the boundaries for X and with all Y
* and Z */
vector<uint> gridDims{boundary_length, (uint) end_y - start_y, (uint) end_z - start_z};
vector<uint> blockDims{1, 1, 1};
auto configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0);
int depth = it.get_global_id(1) + start_y;
int row = it.get_global_id(2) + start_z;
/*! Create temporary value */
float temp = min_velocity;
/*!for values from x = HALF_LENGTH TO x= HALF_LENGTH +BOUND_LENGTH*/
int p_idx = depth * nz_nx + row * nx + column + start_x;
property_array[p_idx] = temp;
/*! Create temporary value */
temp = min_velocity;
/*!for values from x = nx-HALF_LENGTH TO x =
* nx-HALF_LENGTH-BOUND_LENGTH*/
p_idx = depth * nz_nx + row * nx + (end_x - 1 - column);
property_array[p_idx] = temp;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
/*!putting random values for velocities at the boundaries for z and with all x
* and y */
gridDims = {(uint) end_x - start_x, (uint) end_y - start_y, boundary_length};
configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0) + start_x;
int depth = it.get_global_id(1) + start_y;
int row = it.get_global_id(2);
/*! Create temporary value */
float temp = min_velocity;
/*!for values from x = HALF_LENGTH TO x= HALF_LENGTH +BOUND_LENGTH*/
int p_idx = depth * nz_nx + (start_z + row) * nx + column;
// Remove top layer boundary : give value as zero since having top
// layer random boundaries will introduce too much noise.
property_array[p_idx] = 0; //_abs(property_array[p2_idx] - temp);
/*! Create temporary value */
temp = min_velocity;
/*!for values from x = nx-HALF_LENGTH TO x =
* nx-HALF_LENGTH-BOUND_LENGTH*/
p_idx = depth * nz_nx + (end_z - 1 - row) * nx + column;
property_array[p_idx] = temp;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
// Random-Corners in the boundaries nx-nz boundary intersection at bottom--
// top boundaries not needed.
gridDims = {(uint) boundary_length, (uint) end_y - start_y, boundary_length};
configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0);
int depth = it.get_global_id(1) + start_y;
int row = it.get_global_id(2);
uint offset = std::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 */
float temp = min_velocity;
int p_idx = depth * nz_nx + (end_z - 1 - row) * nx + column + start_x;
property_array[p_idx] = temp;
/*!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 */
temp = min_velocity;
/*!for values from x = nx-HALF_LENGTH TO x =
* nx-HALF_LENGTH-BOUND_LENGTH*/
p_idx = depth * nz_nx + (end_z - 1 - row) * nx + (end_x - 1 - column);
property_array[p_idx] = temp;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
// 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.
vector<uint> gridDims{(uint) end_x - start_x, boundary_length, boundary_length};
vector<uint> blockDims{1, 1, 1};
auto configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0) + start_x;
int depth = it.get_global_id(1);
int row = it.get_global_id(2);
uint offset = std::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 */
float temp = min_velocity;
int p_idx =
(depth + start_y) * nz_nx + (end_z - 1 - row) * nx + column;
property_array[p_idx] = temp;
/*!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 */
temp = min_velocity;
/*!for values from x = nx-HALF_LENGTH TO x =
* nx-HALF_LENGTH-BOUND_LENGTH*/
p_idx =
(end_y - 1 - depth) * nz_nx + (end_z - 1 - row) * nx + column;
property_array[p_idx] = temp;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
// Zero-Corners in the boundaries nx-ny boundary intersection on the top
// layer--boundaries not needed.
gridDims = {boundary_length, boundary_length, boundary_length};
configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0);
int depth = it.get_global_id(1);
int row = it.get_global_id(2) + start_z;
/*!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;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
// Random-Corners in the boundaries nx-ny boundary intersection.
gridDims = {boundary_length, boundary_length, boundary_length};
configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0);
int depth = it.get_global_id(1);
int row = it.get_global_id(2) + start_z;
uint offset = std::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 */
float temp = min_velocity;
property_array[(depth + start_y) * nz_nx + row * nx + column +
start_x] = temp;
/*!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 */
temp = min_velocity;
property_array[(end_y - 1 - depth) * nz_nx + row * nx + column +
start_x] = temp;
/*!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
*/
temp = min_velocity;
property_array[(depth + start_y) * nz_nx + row * nx +
(end_x - 1 - column)] = temp;
/*!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 */
temp = min_velocity;
property_array[(end_y - 1 - depth) * nz_nx + row * nx +
(end_x - 1 - column)] = temp;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
}
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.
}
| 18,988
|
C++
|
.cpp
| 352
| 39.90625
| 100
| 0.529453
|
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,148
|
ZeroExtension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <vector>
#include <bs/base/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/boundary-managers/extensions/ZeroExtension.hpp>
using namespace std;
using namespace cl::sycl;
using namespace bs::base::backend;
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) {
end_y = 1;
start_y = 0;
} else {
// general case for 3D
/*!putting zero values for velocities at the boundaries for y and with all x
* and z */
vector<uint> gridDims = {(uint) end_x - start_x, boundary_length, (uint) end_z - start_z};
vector<uint> blockDims = {1, 1, 1};
auto configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0) + start_x;
int depth = it.get_global_id(1);
int row = it.get_global_id(2) + start_z;
/*!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 */
vector<uint> gridDims{boundary_length, (uint) end_y - start_y, (uint) end_z - start_z};
vector<uint> blockDims{1, 1, 1};
auto configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0);
int depth = it.get_global_id(1) + start_y;
int row = it.get_global_id(2) + start_z;
/*!for values from y = HALF_LENGTH TO y = HALF_LENGTH +BOUND_LENGTH*/
property_array[depth * nz_nx + row * nx + column + start_x] = 0;
/*!for values from y = ny-HALF_LENGTH TO y =
* ny-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 */
gridDims = {(uint) end_x - start_x, (uint) end_y - start_y, boundary_length};
configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0) + start_x;
int depth = it.get_global_id(1) + start_y;
int row = it.get_global_id(2);
/*!for values from y = HALF_LENGTH TO y = HALF_LENGTH +BOUND_LENGTH*/
property_array[depth * nz_nx + (start_z + row) * nx + column] = 0;
/*!for values from y = ny-HALF_LENGTH TO y =
* ny-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,943
|
C++
|
.cpp
| 113
| 41.699115
| 101
| 0.588377
|
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,149
|
HomogenousExtension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/concrete/oneapi/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 <vector>
#include <operations/components/independents/concrete/boundary-managers/extensions/HomogenousExtension.hpp>
#include <bs/base/backend/Backend.hpp>
using namespace std;
using namespace cl::sycl;
using namespace bs::base::backend;
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 */
vector<uint> gridDims{(uint) end_x - start_x, boundary_length, (uint) end_z - start_z};
vector<uint> blockDims{1, 1, 1};
auto configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0) + start_x;
int depth = it.get_global_id(1);
int row = it.get_global_id(2) + start_z;
/*!for values from y = HALF_LENGTH TO y= HALF_LENGTH +BOUND_LENGTH*/
int p_idx = (depth + start_y) * nz_nx + row * nx + column;
int p2_idx =
(boundary_length + start_y) * nz_nx + row * nx + column;
property_array[p_idx] = property_array[p2_idx];
/*!for values from y = ny-HALF_LENGTH TO y =
* ny-HALF_LENGTH-BOUND_LENGTH*/
p_idx = (end_y - 1 - depth) * nz_nx + row * nx + column;
p2_idx = (end_y - 1 - boundary_length) * nz_nx + row * nx + column;
property_array[p_idx] = property_array[p2_idx];
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
/*!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 */
vector<uint> gridDims{boundary_length, (uint) end_y - start_y, (uint) end_z - start_z};
vector<uint> blockDims{1, 1, 1};
auto configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0);
int depth = it.get_global_id(1) + start_y;
int row = it.get_global_id(2) + start_z;
/*!for values from x = HALF_LENGTH TO x= HALF_LENGTH +BOUND_LENGTH*/
int p_idx = depth * nz_nx + row * nx + column + start_x;
int p2_idx = depth * nz_nx + row * nx + boundary_length + start_x;
property_array[p_idx] = property_array[p2_idx];
/*!for values from x = nx-HALF_LENGTH TO x =
* nx-HALF_LENGTH-BOUND_LENGTH*/
p_idx = depth * nz_nx + row * nx + (end_x - 1 - column);
p2_idx = depth * nz_nx + row * nx + (end_x - 1 - boundary_length);
property_array[p_idx] = property_array[p2_idx];
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
bool extend_top = 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 */
gridDims = {(uint) end_x - start_x, (uint) end_y - start_y, boundary_length};
configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0) + start_x;
int depth = it.get_global_id(1) + start_y;
int row = it.get_global_id(2);
/*!for values from z = HALF_LENGTH TO z = HALF_LENGTH +BOUND_LENGTH */
int p_idx = depth * nz_nx + (start_z + row) * nx + column;
int p2_idx =
depth * nz_nx + (start_z + boundary_length) * nx + column;
if (extend_top) {
property_array[p_idx] = property_array[p2_idx];
}
/*!for values from z = nz-HALF_LENGTH TO z =
* nz-HALF_LENGTH-BOUND_LENGTH*/
p_idx = depth * nz_nx + (end_z - 1 - row) * nx + column;
p2_idx = depth * nz_nx + (end_z - 1 - boundary_length) * nx + column;
property_array[p_idx] = property_array[p2_idx];
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
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;
if (ny == 1) {
start_y = 0;
end_y = 1;
}
/*!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 */
vector<uint> gridDims{(uint) end_x - start_x, (uint) end_y - start_y, boundary_length};
vector<uint> blockDims{1, 1, 1};
auto configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0) + start_x;
int depth = it.get_global_id(1) + start_y;
int row = it.get_global_id(2);
/*!for values from z = HALF_LENGTH TO z = HALF_LENGTH +BOUND_LENGTH */
int p_idx = depth * nz_nx + (start_z + row) * nx + column;
int p2_idx =
depth * nz_nx + (start_z + boundary_length) * nx + column;
property_array[p_idx] = property_array[p2_idx];
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
}
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) {
if (ny == 1) {
start_y = 0;
end_y = 1;
}
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 */
vector<uint> gridDims{(uint) end_x - start_x, (uint) end_y - start_y, boundary_length};
vector<uint> blockDims{1, 1, 1};
auto configs = Backend::GetInstance()->CreateKernelConfiguration(gridDims, blockDims);
Backend::GetInstance()->GetDeviceQueue()->submit([&](handler &cgh) {
auto global_nd_range = nd_range<3>(configs.mGridDimensions, configs.mBlockDimensions);
cgh.parallel_for(global_nd_range, [=](nd_item<3> it) {
int column = it.get_global_id(0) + start_x;
int depth = it.get_global_id(1) + start_y;
int row = it.get_global_id(2);
/*!for values from z = HALF_LENGTH TO z = HALF_LENGTH +BOUND_LENGTH */
int p_idx = depth * nz_nx + (start_z + row) * nx + column;
property_array[p_idx] = 0;
});
});
Backend::GetInstance()->GetDeviceQueue()->wait();
}
}
| 9,812
|
C++
|
.cpp
| 182
| 42.351648
| 107
| 0.575414
|
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,150
|
WaveFieldsMemoryHandler.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/dependents/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/base/api/cpp/BSBase.hpp>
#include <operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp>
using namespace bs::base::logger;
using namespace bs::base::memory;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
WaveFieldsMemoryHandler::WaveFieldsMemoryHandler(
bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
}
WaveFieldsMemoryHandler::~WaveFieldsMemoryHandler() = default;
void WaveFieldsMemoryHandler::AcquireConfiguration() {}
void WaveFieldsMemoryHandler::CloneWaveFields(GridBox *_src, GridBox *_dst) {
uint wnx = _src->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = _src->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = _src->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint const window_size = wnx * wny * wnz;
/// Allocating and zeroing wave fields.
for (auto wave_field : _src->GetWaveFields()) {
if (!GridBox::Includes(wave_field.first, NEXT)) {
auto frame_buffer = new FrameBuffer<float>();
frame_buffer->Allocate(window_size,
mpParameters->GetHalfLength(),
GridBox::Stringify(wave_field.first));
this->FirstTouch(frame_buffer->GetNativePointer(), _src, true);
_dst->RegisterWaveField(wave_field.first, frame_buffer);
Device::MemCpy(_dst->Get(wave_field.first)->GetNativePointer(),
_src->Get(wave_field.first)->GetNativePointer(),
window_size * sizeof(float));
GridBox::Key wave_field_new = wave_field.first;
if (GridBox::Includes(wave_field_new, GB_PRSS | PREV)) {
GridBox::Replace(&wave_field_new, PREV, NEXT);
_dst->RegisterWaveField(wave_field_new, frame_buffer);
} else if (this->mpParameters->GetEquationOrder() == FIRST &&
GridBox::Includes(wave_field_new, GB_PRSS | CURR)) {
GridBox::Replace(&wave_field_new, CURR, NEXT);
_dst->RegisterWaveField(wave_field_new, frame_buffer);
}
}
}
}
void WaveFieldsMemoryHandler::CopyWaveFields(GridBox *_src, GridBox *_dst) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
uint wnx = _src->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = _src->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = _src->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint const window_size = wnx * wny * wnz;
for (auto wave_field : _src->GetWaveFields()) {
auto src = _src->Get(wave_field.first)->GetNativePointer();
auto dst = _dst->Get(wave_field.first)->GetNativePointer();
if (src != nullptr && dst != nullptr) {
Device::MemCpy(dst, src, window_size * sizeof(float));
} else {
Logger->Error() << "No Wave Fields allocated to be copied... "
<< "Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
}
void WaveFieldsMemoryHandler::FreeWaveFields(GridBox *apGridBox) {
for (auto &wave_field : apGridBox->GetWaveFields()) {
if (!GridBox::Includes(wave_field.first, NEXT)) {
wave_field.second->Free();
}
}
}
void WaveFieldsMemoryHandler::SetComputationParameters(
ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
| 4,605
|
C++
|
.cpp
| 95
| 40.884211
| 96
| 0.664139
|
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,151
|
CrossCorrelationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/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 <cstdlib>
#include <iostream>
#include <vector>
#include <cmath>
#include <bs/base/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/migration-accommodators/CrossCorrelationKernel.hpp>
#include <operations/utils/sampling/Sampler.hpp>
#include <operations/configurations/MapKeys.h>
#define EPSILON 1e-20
using namespace std;
using namespace bs::base::logger;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::utils::sampling;
CrossCorrelationKernel::CrossCorrelationKernel(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mCompensationType = NO_COMPENSATION;
}
CrossCorrelationKernel::~CrossCorrelationKernel() {
delete this->mpShotCorrelation;
delete this->mpTotalCorrelation;
delete this->mpSourceIllumination;
delete this->mpReceiverIllumination;
}
void CrossCorrelationKernel::AcquireConfiguration() {
LoggerSystem *Logger = LoggerSystem::GetInstance();
string compensation = "no";
compensation = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_COMPENSATION, compensation);
if (compensation.empty()) {
Logger->Error() << "No entry for migration-accommodator.compensation key : supported values [ "
"no | source | receiver | combined ]" << '\n';
Logger->Error() << "Terminating..." << '\n';
exit(EXIT_FAILURE);
} else if (compensation == OP_K_COMPENSATION_NONE) {
this->SetCompensation(NO_COMPENSATION);
Logger->Info() << "No illumination compensation is requested" << '\n';
} else if (compensation == OP_K_COMPENSATION_COMBINED) {
this->SetCompensation(COMBINED_COMPENSATION);
Logger->Info() << "Applying combined illumination compensation" << '\n';
} else {
Logger->Info() << "Invalid value for migration-accommodator.compensation key : supported values [ "
OP_K_COMPENSATION_NONE " | "
OP_K_COMPENSATION_COMBINED " ]" << '\n';
Logger->Info() << "Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void CrossCorrelationKernel::Correlate(dataunits::DataUnit *apDataUnit) {
auto grid_box = (GridBox *) apDataUnit;
uint ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
if (ny == 1) {
switch (this->mCompensationType) {
case NO_COMPENSATION:
Correlation<true, NO_COMPENSATION>(grid_box);
break;
case COMBINED_COMPENSATION:
Correlation<true, COMBINED_COMPENSATION>(grid_box);
break;
}
} else {
switch (this->mCompensationType) {
case NO_COMPENSATION:
Correlation<false, NO_COMPENSATION>(grid_box);
break;
case COMBINED_COMPENSATION:
Correlation<false, COMBINED_COMPENSATION>(grid_box);
break;
}
}
}
void CrossCorrelationKernel::Stack() {
if (this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize() == 1) {
switch (this->mCompensationType) {
case NO_COMPENSATION:
Stack < true, NO_COMPENSATION > ();
break;
case COMBINED_COMPENSATION:
Stack < true, COMBINED_COMPENSATION > ();
break;
}
} else {
switch (this->mCompensationType) {
case NO_COMPENSATION:
Stack < false, NO_COMPENSATION > ();
break;
case COMBINED_COMPENSATION:
Stack < false, COMBINED_COMPENSATION > ();
break;
}
}
}
void CrossCorrelationKernel::SetComputationParameters(ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void CrossCorrelationKernel::SetCompensation(COMPENSATION_TYPE aCOMPENSATION_TYPE) {
mCompensationType = aCOMPENSATION_TYPE;
}
void CrossCorrelationKernel::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpGridBox = apGridBox;
if (this->mpGridBox == nullptr) {
Logger->Error() << "No GridBox provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
InitializeInternalElements();
}
void CrossCorrelationKernel::InitializeInternalElements() {
// Grid.
uint nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
uint ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
uint nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
uint grid_size = nx * ny * nz;
uint grid_bytes = grid_size * sizeof(float);
/* Window initialization. */
uint wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
uint window_bytes = window_size * sizeof(float);
mpShotCorrelation = new FrameBuffer<float>();
mpShotCorrelation->Allocate(window_size, mpParameters->GetHalfLength(), "shot_correlation");
Device::MemSet(mpShotCorrelation->GetNativePointer(), 0, window_bytes);
mpSourceIllumination = new FrameBuffer<float>();
mpSourceIllumination->Allocate(window_size, mpParameters->GetHalfLength(), "source_illumination");
Device::MemSet(mpSourceIllumination->GetNativePointer(), 0, window_bytes);
mpReceiverIllumination = new FrameBuffer<float>();
mpReceiverIllumination->Allocate(window_size, mpParameters->GetHalfLength(), "receiver_illumination");
Device::MemSet(mpReceiverIllumination->GetNativePointer(), 0, window_bytes);
mpTotalCorrelation = new FrameBuffer<float>();
mpTotalCorrelation->Allocate(grid_size, mpParameters->GetHalfLength(), "stacked_shot_correlation");
Device::MemSet(mpTotalCorrelation->GetNativePointer(), 0, grid_bytes);
}
void CrossCorrelationKernel::ResetShotCorrelation() {
uint window_bytes = sizeof(float) *
this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize() *
this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize() *
this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
Device::MemSet(this->mpShotCorrelation->GetNativePointer(), 0, window_bytes);
Device::MemSet(this->mpSourceIllumination->GetNativePointer(), 0, window_bytes);
Device::MemSet(this->mpReceiverIllumination->GetNativePointer(), 0, window_bytes);
}
FrameBuffer<float> *CrossCorrelationKernel::GetShotCorrelation() {
return this->mpShotCorrelation;
}
FrameBuffer<float> *CrossCorrelationKernel::GetStackedShotCorrelation() {
return this->mpTotalCorrelation;
}
MigrationData *CrossCorrelationKernel::GetMigrationData() {
vector<Result *> results;
uint nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
uint ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
uint nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
auto *result = new float[nx * ny * nz];
memcpy(result, this->mpTotalCorrelation->GetHostPointer(),
nx * nz * ny * sizeof(float));
results.push_back(new Result(result));
return new MigrationData(nx,
ny,
nz,
this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension(),
this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension(),
this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension(),
this->mpGridBox->GetParameterGatherHeader(),
results);
}
void CrossCorrelationKernel::SetSourcePoint(Point3D *apSourcePoint) {
this->mSourcePoint = *apSourcePoint;
}
uint
CrossCorrelationKernel::CalculateDipAngleDepth(double aDipAngle, int aCurrentPositionX, int aCurrentPositionY) const {
/* Opposite = Adjacent * tan(theta) */
float theta = (M_PI / 2) - aDipAngle;
return ceil(tan(theta) * fabs(sqrt(
pow(((int) this->mSourcePoint.x) - aCurrentPositionX, 2)
+ pow(((int) this->mSourcePoint.y) - aCurrentPositionY, 2))));
}
| 9,569
|
C++
|
.cpp
| 200
| 40.48
| 118
| 0.682179
|
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,152
|
SeismicTraceWriter.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/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 <iostream>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <bs/base/logger/concrete/LoggerSystem.hpp>
#include <operations/components/independents/concrete/trace-writers/SeismicTraceWriter.hpp>
#include <operations/configurations/MapKeys.h>
#include <operations/utils/io/write_utils.h>
using namespace std;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::base::logger;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
SeismicTraceWriter::SeismicTraceWriter(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
}
SeismicTraceWriter::~SeismicTraceWriter() = default;
void SeismicTraceWriter::AcquireConfiguration() {
LoggerSystem *Logger = LoggerSystem::GetInstance();
// Initialize writer.
std::string writer_type = "segy";
writer_type = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_TYPE,
writer_type);
try {
SeismicWriter::ToWriterType(writer_type);
} catch (exception &e) {
Logger->Error() << "Invalid trace writer type provided : " << e.what() << '\n';
Logger->Error() << "Terminating..." << '\n';
exit(EXIT_FAILURE);
}
Logger->Info() << "Trace writer will use " << writer_type << " format." << '\n';
nlohmann::json configuration_map =
nlohmann::json::parse(this->mpConfigurationMap->ToString());
bs::base::configurations::JSONConfigurationMap io_conf_map(configuration_map);
this->mpSeismicWriter = new SeismicWriter(
SeismicWriter::ToWriterType(writer_type), &io_conf_map);
this->mpSeismicWriter->AcquireConfiguration();
std::string output = "modeling_output";
output = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_OUTPUT_FILE,
output);
this->mpSeismicWriter->Initialize(output);
Logger->Info() << "Trace writer will write in " <<
output + this->mpSeismicWriter->GetExtension() << '\n';
}
void SeismicTraceWriter::SetComputationParameters(
ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void SeismicTraceWriter::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpGridBox = apGridBox;
if (this->mpGridBox == nullptr) {
Logger->Error() << "No GridBox provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void SeismicTraceWriter::StartRecordingInstance(TracesHolder &aTracesHolder) {
mSampleNumber = aTracesHolder.SampleNT;
mTraceNumber = aTracesHolder.TraceSizePerTimeStep;
mTraceSampling = aTracesHolder.SampleDT;
mpDTraces.Allocate(mSampleNumber * mTraceNumber,
"Device traces");
mpDPositionsX.Allocate(mTraceNumber, "trace x positions");
mpDPositionsY.Allocate(mTraceNumber, "trace y positions");
uint wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint const window_size = wnx * wny * wnz;
for (auto const &wave_field : this->mpGridBox->GetWaveFields()) {
Device::MemSet(wave_field.second->GetNativePointer(), 0.0f, window_size * sizeof(float));
}
Device::MemSet(mpDTraces.GetNativePointer(), 0,
mSampleNumber * mTraceNumber * sizeof(float));
Device::MemCpy(mpDPositionsX.GetNativePointer(), aTracesHolder.PositionsX,
mTraceNumber * sizeof(uint),
Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(mpDPositionsY.GetNativePointer(), aTracesHolder.PositionsY,
mTraceNumber * sizeof(uint),
Device::COPY_HOST_TO_DEVICE);
}
void SeismicTraceWriter::Finalize() {
this->mpSeismicWriter->Finalize();
delete this->mpSeismicWriter;
this->mpSeismicWriter = nullptr;
}
void SeismicTraceWriter::FinishRecordingInstance(uint shot_id) {
auto trace_values = mpDTraces.GetHostPointer();
auto locations_x = mpDPositionsX.GetHostPointer();
auto locations_y = mpDPositionsY.GetHostPointer();
uint ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
auto gather = new Gather();
for (int trace_index = 0; trace_index < mTraceNumber; trace_index++) {
auto trace = new Trace(mSampleNumber);
int16_t factor = -1000;
trace->SetTraceHeaderKeyValue(TraceHeaderKey::SCALCO, factor);
auto local_ix = this->mpGridBox->GetWindowStart(X_AXIS)
+ locations_x[trace_index]
- this->mpParameters->GetBoundaryLength()
- this->mpParameters->GetHalfLength();
auto local_iy = this->mpGridBox->GetWindowStart(Y_AXIS)
+ locations_y[trace_index]
- this->mpParameters->GetBoundaryLength()
- this->mpParameters->GetHalfLength();
float loc_x = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetReferencePoint() +
local_ix * this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float loc_y = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetReferencePoint() +
local_iy * this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
if (ny == 1) {
loc_y = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetReferencePoint();
}
trace->SetScaledCoordinateHeader(TraceHeaderKey::SX, loc_x);
trace->SetScaledCoordinateHeader(TraceHeaderKey::SY, loc_y);
trace->SetScaledCoordinateHeader(TraceHeaderKey::GX, loc_x);
trace->SetScaledCoordinateHeader(TraceHeaderKey::GY, loc_y);
uint16_t sampling = mTraceSampling * 1e6;
trace->SetTraceHeaderKeyValue(TraceHeaderKey::DT, sampling);
trace->SetTraceHeaderKeyValue(TraceHeaderKey::FLDR, shot_id);
trace->SetTraceData(new float[mSampleNumber]);
for (int is = 0; is < mSampleNumber; is++) {
trace->GetTraceData()[is] =
trace_values[is * mTraceNumber + trace_index];
}
gather->AddTrace(trace);
}
gather->SetSamplingRate(mTraceSampling * 1e6f);
string val = to_string(shot_id);
gather->SetUniqueKeyValue(TraceHeaderKey::FLDR, val);
this->mpSeismicWriter->Write(gather);
delete gather;
mpDTraces.Free();
mpDPositionsX.Free();
mpDPositionsY.Free();
}
| 7,759
|
C++
|
.cpp
| 156
| 42.294872
| 104
| 0.683947
|
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,153
|
TwoPropagation.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/forward-collectors/TwoPropagation.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 <sys/stat.h>
#include <bs/base/api/cpp/BSBase.hpp>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/components/independents/concrete/forward-collectors/TwoPropagation.hpp>
#include <operations/configurations/MapKeys.h>
#include <operations/utils/compressor/Compressor.hpp>
using namespace std;
using namespace bs::timer;
using namespace bs::base::logger;
using namespace bs::base::memory;
using namespace operations::helpers;
using namespace operations::components;
using namespace operations::components::helpers;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::utils::compressors;
static float *initial_internalGridbox_curr = nullptr;
TwoPropagation::TwoPropagation(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mpInternalGridBox = new GridBox();
this->mpForwardPressure = nullptr;
this->mIsMemoryFit = false;
this->mTimeCounter = 0;
this->mIsCompression = false;
this->mZFP_Tolerance = 0.01f;
this->mZFP_Parallel = true;
this->mZFP_IsRelative = false;
this->mMaxNT = 0;
}
TwoPropagation::~TwoPropagation() {
if (this->mpForwardPressureHostMemory != nullptr) {
mem_free(this->mpForwardPressureHostMemory);
}
delete this->mpForwardPressure;
this->mpInternalGridBox->Set(WAVE | GB_PRSS | CURR | DIR_Z, initial_internalGridbox_curr);
this->mpWaveFieldsMemoryHandler->FreeWaveFields(this->mpInternalGridBox);
delete this->mpInternalGridBox;
}
void TwoPropagation::AcquireConfiguration() {
if (this->mpConfigurationMap->Contains(OP_K_PROPRIETIES, OP_K_COMPRESSION)) {
this->mIsCompression = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_COMPRESSION,
this->mIsCompression);
}
if (this->mpConfigurationMap->Contains(OP_K_PROPRIETIES, OP_K_WRITE_PATH)) {
std::string write_path = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_WRITE_PATH,
this->mWritePath);
mkdir(write_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
this->mWritePath = write_path + "/two_prop";
mkdir(this->mWritePath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
if (this->mpConfigurationMap->Contains(OP_K_PROPRIETIES, OP_K_ZFP_TOLERANCE)) {
this->mZFP_Tolerance = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_ZFP_TOLERANCE,
this->mZFP_Tolerance);
}
if (this->mpConfigurationMap->Contains(OP_K_PROPRIETIES, OP_K_ZFP_PARALLEL)) {
this->mZFP_Parallel = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_ZFP_PARALLEL,
this->mZFP_Parallel);
}
if (this->mpConfigurationMap->Contains(OP_K_PROPRIETIES, OP_K_ZFP_RELATIVE)) {
this->mZFP_IsRelative = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_ZFP_RELATIVE,
this->mZFP_IsRelative);
}
}
void TwoPropagation::FetchForward() {
uint wnx = this->mpMainGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = this->mpMainGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint const window_size = wnx * wny * wnz;
// Retrieve data from files to host buffer
if ((this->mTimeCounter + 1) % this->mMaxNT == 0) {
if (this->mIsCompression) { ;
string str = this->mWritePath + "/temp_" + to_string(this->mTimeCounter / this->mMaxNT);
{
ScopeTimer t("ForwardCollector::Decompression");
Compressor::Decompress(this->mpForwardPressureHostMemory, wnx, wny, wnz,
this->mMaxNT,
(double) this->mZFP_Tolerance,
this->mZFP_Parallel,
str.c_str(),
this->mZFP_IsRelative);
}
} else {
string str = this->mWritePath + "/temp_" + to_string(this->mTimeCounter / this->mMaxNT);
{
ScopeTimer t("IO::ReadForward");
bin_file_load(str.c_str(), this->mpForwardPressureHostMemory, this->mMaxNT * window_size);
}
}
}
// Retrieve data from host buffer
if ((this->mTimeCounter + 1) % this->mMaxDeviceNT == 0) {
int host_index = (this->mTimeCounter + 1) / this->mMaxDeviceNT - 1;
Device::MemCpy(this->mpForwardPressure->GetNativePointer(),
this->mpForwardPressureHostMemory +
(host_index % this->mpMaxNTRatio) * (this->mMaxDeviceNT * window_size),
this->mMaxDeviceNT * window_size * sizeof(float),
Device::COPY_HOST_TO_DEVICE);
}
this->mpInternalGridBox->Set(WAVE | GB_PRSS | CURR | DIR_Z,
this->mpForwardPressure->GetNativePointer() +
((this->mTimeCounter) % this->mMaxDeviceNT) * window_size);
this->mTimeCounter--;
}
void TwoPropagation::ResetGrid(bool aIsForwardRun) {
uint wnx = this->mpMainGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = this->mpMainGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint const window_size = wnx * wny * wnz;
if (aIsForwardRun) {
this->mpMainGridBox->CloneMetaData(this->mpInternalGridBox);
this->mpMainGridBox->CloneParameters(this->mpInternalGridBox);
if (this->mpInternalGridBox->GetWaveFields().empty()) {
this->mpWaveFieldsMemoryHandler->CloneWaveFields(this->mpMainGridBox,
this->mpInternalGridBox);
// save the pressure pointer for deletion afterwards
initial_internalGridbox_curr = mpInternalGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
} else {
this->mpWaveFieldsMemoryHandler->CopyWaveFields(this->mpMainGridBox,
this->mpInternalGridBox);
}
this->mTimeCounter = 0;
if (this->mpForwardPressureHostMemory == nullptr) {
/// Add one for empty timeframe at the start of the simulation
/// (The first previous) since SaveForward is called before each step.
this->mMaxNT = this->mpMainGridBox->GetNT() + 1;
this->mMaxDeviceNT = 100; // save 100 frames in the Device memory, then reflect to host memory
this->mpForwardPressureHostMemory = (float *) mem_allocate(
(sizeof(float)), this->mMaxNT * window_size, "forward_pressure");
this->mpForwardPressure = new FrameBuffer<float>();
this->mpForwardPressure->Allocate(window_size * this->mMaxDeviceNT);
if (this->mpForwardPressureHostMemory != nullptr) {
this->mIsMemoryFit = true;
} else {
this->mIsMemoryFit = false;
while (this->mpForwardPressureHostMemory == nullptr) {
this->mMaxNT = this->mMaxNT / 2;
this->mpForwardPressureHostMemory = (float *) mem_allocate(
(sizeof(float)), this->mMaxNT * window_size, "forward_pressure");
}
mem_free(this->mpForwardPressureHostMemory);
// another iteration as a safety measure
this->mMaxNT = this->mMaxNT / 2;
this->mpForwardPressureHostMemory = (float *) mem_allocate(
(sizeof(float)), this->mMaxNT * window_size, "forward_pressure");
}
mpMaxNTRatio = mMaxNT / this->mMaxDeviceNT;
}
this->mpTempCurr = this->mpMainGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer();
this->mpTempNext = this->mpMainGridBox->Get(WAVE | GB_PRSS | NEXT | DIR_Z)->GetNativePointer();
Device::MemSet(this->mpForwardPressure->GetNativePointer(), 0.0f,
window_size * sizeof(float));
Device::MemSet(this->mpForwardPressure->GetNativePointer() + window_size, 0.0f,
window_size * sizeof(float));
if (this->mpParameters->GetEquationOrder() == SECOND) {
this->mpTempPrev = this->mpMainGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z)->GetNativePointer();
Device::MemSet(this->mpForwardPressure->GetNativePointer() + 2 * window_size, 0.0f,
window_size * sizeof(float));
}
if (this->mpParameters->GetEquationOrder() == SECOND) {
this->mpMainGridBox->Set(WAVE | GB_PRSS | PREV | DIR_Z, this->mpForwardPressure->GetNativePointer());
this->mpMainGridBox->Set(WAVE | GB_PRSS | CURR | DIR_Z,
this->mpForwardPressure->GetNativePointer() + window_size);
// Save forward is called before the kernel in the engine.
// When called will advance pressure next to the right point.
this->mpMainGridBox->Set(WAVE | GB_PRSS | NEXT | DIR_Z,
this->mpForwardPressure->GetNativePointer() + window_size);
} else {
this->mpMainGridBox->Set(WAVE | GB_PRSS | CURR | DIR_Z, this->mpForwardPressure->GetNativePointer());
this->mpMainGridBox->Set(WAVE | GB_PRSS | NEXT | DIR_Z,
this->mpForwardPressure->GetNativePointer() + window_size);
}
} else {
Device::MemSet(this->mpTempCurr, 0.0f, window_size * sizeof(float));
if (this->mpParameters->GetEquationOrder() == SECOND) {
Device::MemSet(this->mpTempPrev, 0.0f, window_size * sizeof(float));
}
for (auto const &wave_field : this->mpMainGridBox->GetWaveFields()) {
if (GridBox::Includes(wave_field.first, GB_PRTC)) {
Device::MemSet(wave_field.second->GetNativePointer(), 0.0f, window_size * sizeof(float));
}
}
if (!this->mIsMemoryFit) {
this->mTimeCounter++;
this->mpInternalGridBox->Set(WAVE | GB_PRSS | CURR | DIR_Z,
this->mpMainGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer());
} else {
// Pressure size will be minimized in FetchForward call at first step.
this->mpInternalGridBox->Set(WAVE | GB_PRSS | CURR | DIR_Z,
this->mpMainGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer() +
window_size);
}
if (this->mpParameters->GetEquationOrder() == SECOND) {
this->mpMainGridBox->Set(WAVE | GB_PRSS | PREV | DIR_Z, this->mpTempPrev);
}
this->mpMainGridBox->Set(WAVE | GB_PRSS | CURR | DIR_Z, this->mpTempCurr);
this->mpMainGridBox->Set(WAVE | GB_PRSS | NEXT | DIR_Z, this->mpTempNext);
}
}
void TwoPropagation::SaveForward() {
uint wnx = this->mpMainGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = this->mpMainGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint const window_size = wnx * wny * wnz;
this->mTimeCounter++;
// Transfer from Device memory to host memory
if ((this->mTimeCounter + 1) % this->mMaxDeviceNT == 0) {
int host_index = (this->mTimeCounter + 1) / this->mMaxDeviceNT - 1;
Device::MemCpy(
this->mpForwardPressureHostMemory +
(host_index % this->mpMaxNTRatio) * (this->mMaxDeviceNT * window_size),
this->mpForwardPressure->GetNativePointer(),
this->mMaxDeviceNT * window_size * sizeof(float),
Device::COPY_DEVICE_TO_HOST);
}
// Save host memory to file
if ((this->mTimeCounter + 1) % this->mMaxNT == 0) {
if (this->mIsCompression) {
string str = this->mWritePath + "/temp_" + to_string(this->mTimeCounter / this->mMaxNT);
{
ScopeTimer t("ForwardCollector::Compression");;
Compressor::Compress(this->mpForwardPressureHostMemory, wnx, wny, wnz,
this->mMaxNT,
(double) this->mZFP_Tolerance,
this->mZFP_Parallel,
str.c_str(),
this->mZFP_IsRelative);
}
} else {
string str =
this->mWritePath + "/temp_" + to_string(this->mTimeCounter / this->mMaxNT);
{
ScopeTimer t("IO::WriteForward");
bin_file_save(str.c_str(), this->mpForwardPressureHostMemory, this->mMaxNT * window_size);
}
}
}
this->mpMainGridBox->Set(WAVE | GB_PRSS | CURR | DIR_Z,
this->mpForwardPressure->GetNativePointer() +
((this->mTimeCounter) % this->mMaxDeviceNT) * window_size);
this->mpMainGridBox->Set(WAVE | GB_PRSS | NEXT | DIR_Z,
this->mpForwardPressure->GetNativePointer() +
((this->mTimeCounter + 1) % this->mMaxDeviceNT) * window_size);
if (this->mpParameters->GetEquationOrder() == SECOND) {
this->mpMainGridBox->Set(WAVE | GB_PRSS | PREV | DIR_Z,
this->mpForwardPressure->GetNativePointer() +
((this->mTimeCounter - 1) % this->mMaxDeviceNT) * window_size);
}
}
void TwoPropagation::SetComputationParameters(ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void TwoPropagation::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpMainGridBox = apGridBox;
if (this->mpMainGridBox == nullptr) {
Logger->Error() << "Not a compatible GridBox... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
/*
* in case of two propagation the next buffer and previous buffer get separated
* so we need to register a new wave field with actual allocated memory
*/
auto framebuffer = new FrameBuffer<float>();
this->mpMainGridBox->RegisterWaveField(WAVE | GB_PRSS | NEXT | DIR_Z, framebuffer);
framebuffer->Allocate(
this->mpMainGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize() *
this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize() *
this->mpMainGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize(),
mpParameters->GetHalfLength(),
"next pressure");
}
void TwoPropagation::SetDependentComponents(
ComponentsMap<DependentComponent> *apDependentComponentsMap) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
HasDependents::SetDependentComponents(apDependentComponentsMap);
this->mpWaveFieldsMemoryHandler =
(WaveFieldsMemoryHandler *)
this->GetDependentComponentsMap()->Get(MEMORY_HANDLER);
if (this->mpWaveFieldsMemoryHandler == nullptr) {
Logger->Error() << "No Wave Fields Memory Handler provided... " << "Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
GridBox *TwoPropagation::GetForwardGrid() {
return this->mpInternalGridBox;
}
| 16,893
|
C++
|
.cpp
| 309
| 42.546926
| 118
| 0.607517
|
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,154
|
ReversePropagation.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/forward-collectors/ReversePropagation.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/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/forward-collectors/ReversePropagation.hpp>
#include <operations/configurations/MapKeys.h>
#include <operations/components/independents/concrete/forward-collectors/boundary-saver/BoundarySaver.h>
using namespace bs::base::logger;
using namespace operations::components;
using namespace operations::components::helpers;
using namespace operations::helpers;
using namespace operations::common;
using namespace operations::dataunits;
ReversePropagation::ReversePropagation(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mpInternalGridBox = new GridBox();
this->mpComputationKernel = nullptr;
this->mInjectionEnabled = false;
this->mTimeStep = 0;
}
ReversePropagation::~ReversePropagation() {
this->mpWaveFieldsMemoryHandler->FreeWaveFields(this->mpInternalGridBox);
delete this->mpInternalGridBox;
delete this->mpComputationKernel;
for (auto boundary_saver : this->mBoundarySavers) {
delete boundary_saver;
}
}
void ReversePropagation::AcquireConfiguration() {
this->mInjectionEnabled = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_BOUNDARY_SAVING,
this->mInjectionEnabled);
auto computation_kernel = (ComputationKernel *) (this->mpComponentsMap->Get(COMPUTATION_KERNEL));
this->mpComputationKernel = (ComputationKernel *) computation_kernel->Clone();
this->mpComputationKernel->SetDependentComponents(this->GetDependentComponentsMap());
this->mpComputationKernel->SetMode(KERNEL_MODE::INVERSE);
this->mpComputationKernel->SetComputationParameters(this->mpParameters);
this->mpComputationKernel->SetGridBox(this->mpInternalGridBox);
this->mpComputationKernel->SetDependentComponents(this->GetDependentComponentsMap());
}
void ReversePropagation::FetchForward() {
this->mpComputationKernel->Step();
if (this->mInjectionEnabled) {
this->mTimeStep--;
for (auto boundary_saver : this->mBoundarySavers) {
boundary_saver->RestoreBoundaries(this->mTimeStep);
}
}
}
void ReversePropagation::ResetGrid(bool is_forward_run) {
uint wnx = this->mpMainGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = this->mpMainGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint const window_size = wnx * wny * wnz;
if (!is_forward_run) {
this->mpMainGridBox->CloneMetaData(this->mpInternalGridBox);
this->mpMainGridBox->CloneParameters(this->mpInternalGridBox);
if (this->mpInternalGridBox->GetWaveFields().empty()) {
this->mpWaveFieldsMemoryHandler->CloneWaveFields(this->mpMainGridBox,
this->mpInternalGridBox);
} else {
this->mpWaveFieldsMemoryHandler->CopyWaveFields(this->mpMainGridBox,
this->mpInternalGridBox);
}
/*
* Swapping
*/
if (this->mpParameters->GetApproximation() == ISOTROPIC) {
if (this->mpParameters->GetEquationOrder() == FIRST) {
// Swap next and current to reverse time.
this->mpInternalGridBox->Swap(WAVE | GB_PRSS | NEXT | DIR_Z,
WAVE | GB_PRSS | CURR | DIR_Z);
} else if (this->mpParameters->GetEquationOrder() == SECOND) {
// Swap previous and current to reverse time.
this->mpInternalGridBox->Swap(WAVE | GB_PRSS | PREV | DIR_Z,
WAVE | GB_PRSS | CURR | DIR_Z);
// Only use two pointers, prev is same as next.
this->mpInternalGridBox->Set(WAVE | GB_PRSS | NEXT | DIR_Z,
this->mpInternalGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z));
}
}
} else {
if (this->mInjectionEnabled) {
this->Inject();
}
}
for (auto const &wave_field : this->mpMainGridBox->GetWaveFields()) {
Device::MemSet(wave_field.second->GetNativePointer(), 0.0f, window_size * sizeof(float));
}
}
void ReversePropagation::SaveForward() {
if (this->mInjectionEnabled) {
for (auto boundary_saver : this->mBoundarySavers) {
boundary_saver->SaveBoundaries(this->mTimeStep);
}
this->mTimeStep++;
}
}
void ReversePropagation::Inject() {
this->mTimeStep = 0;
if (this->mBoundarySavers.empty()) {
auto boundary_saver = new BoundarySaver();
boundary_saver->Initialize(
WAVE | GB_PRSS | CURR | DIR_Z,
this->mpInternalGridBox,
this->mpMainGridBox, this->mpParameters);
this->mBoundarySavers.push_back(boundary_saver);
if (this->mpParameters->GetApproximation() == ISOTROPIC) {
if (this->mpParameters->GetEquationOrder() == FIRST) {
auto boundary_saver_particle_x = new BoundarySaver();
boundary_saver_particle_x->Initialize(
WAVE | GB_PRTC | CURR | DIR_X,
this->mpInternalGridBox,
this->mpMainGridBox, this->mpParameters);
this->mBoundarySavers.push_back(boundary_saver_particle_x);
auto boundary_saver_particle_z = new BoundarySaver();
boundary_saver_particle_z->Initialize(
WAVE | GB_PRTC | CURR | DIR_Z,
this->mpInternalGridBox,
this->mpMainGridBox, this->mpParameters);
this->mBoundarySavers.push_back(boundary_saver_particle_z);
uint wny = this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
if (wny > 1) {
auto boundary_saver_particle_y = new BoundarySaver();
boundary_saver_particle_y->Initialize(
WAVE | GB_PRTC | CURR | DIR_Y,
this->mpInternalGridBox,
this->mpMainGridBox, this->mpParameters);
this->mBoundarySavers.push_back(boundary_saver_particle_y);
}
}
}
}
}
void ReversePropagation::SetComputationParameters(ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void ReversePropagation::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpMainGridBox = apGridBox;
if (this->mpMainGridBox == nullptr) {
Logger->Error() << "Not a compatible GridBox... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void ReversePropagation::SetDependentComponents(
ComponentsMap<DependentComponent> *apDependentComponentsMap) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
HasDependents::SetDependentComponents(apDependentComponentsMap);
this->mpWaveFieldsMemoryHandler =
(WaveFieldsMemoryHandler *)
this->GetDependentComponentsMap()->Get(MEMORY_HANDLER);
if (this->mpWaveFieldsMemoryHandler == nullptr) {
Logger->Error() << "No Wave Fields Memory Handler provided... "
<< "Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
GridBox *ReversePropagation::GetForwardGrid() {
return this->mpInternalGridBox;
}
| 8,666
|
C++
|
.cpp
| 180
| 38.383333
| 106
| 0.645535
|
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,155
|
BoundarySaver.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/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;
BoundarySaver::BoundarySaver() : mKey(0), mBoundarySize(0),
mpMainGridBox(nullptr),
mpInternalGridBox(nullptr),
mpComputationParameters(nullptr) {
}
void BoundarySaver::Initialize(dataunits::GridBox::Key aActiveKey,
dataunits::GridBox *apInternalGridBox,
dataunits::GridBox *apMainGridBox,
common::ComputationParameters *apParameters) {
this->mKey = aActiveKey;
this->mpInternalGridBox = apInternalGridBox;
this->mpComputationParameters = apParameters;
this->mpMainGridBox = apMainGridBox;
uint half_length = this->mpComputationParameters->GetHalfLength();
uint nxi = this->mpMainGridBox->GetWindowAxis()->GetXAxis().GetAxisSize();
uint nyi = this->mpMainGridBox->GetWindowAxis()->GetYAxis().GetAxisSize();
uint nzi = this->mpMainGridBox->GetWindowAxis()->GetZAxis().GetAxisSize();
this->mBoundarySize =
nxi * nyi * half_length * 2 + nzi * nyi * half_length * 2;
if (nyi != 1) {
this->mBoundarySize += nxi * nzi * half_length * 2;
}
this->mBackupBoundaries.Allocate(
this->mBoundarySize * (this->mpMainGridBox->GetNT() + 1),
"Backup Boundaries");
}
BoundarySaver::~BoundarySaver() {
this->mBackupBoundaries.Free();
}
| 2,400
|
C++
|
.cpp
| 51
| 39.921569
| 104
| 0.68774
|
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,156
|
file_handler.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/forward-collectors/file-handler/file_handler.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/file-handler/file_handler.h>
void operations::components::helpers::bin_file_save(
const char *file_name, const float *data, const size_t &size) {
std::ofstream stream(file_name, std::ios::out | std::ios::binary);
if (!stream.is_open()) {
exit(EXIT_FAILURE);
}
stream.write(reinterpret_cast<const char *>(data), size * sizeof(float));
stream.close();
}
void operations::components::helpers::bin_file_load(
const char *file_name, float *data, const size_t &size) {
std::ifstream stream(file_name, std::ios::binary | std::ios::in);
if (!stream.is_open()) {
exit(EXIT_FAILURE);
}
stream.read(reinterpret_cast<char *>(data), std::streamsize(size * sizeof(float)));
stream.close();
}
| 1,583
|
C++
|
.cpp
| 37
| 39.324324
| 101
| 0.716969
|
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,157
|
SeismicTraceManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/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 <iostream>
#include <utility>
#include <cmath>
#include <bs/base/api/cpp/BSBase.hpp>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/components/independents/concrete/trace-managers/SeismicTraceManager.hpp>
#include <operations/configurations/MapKeys.h>
#include <operations/utils/interpolation/Interpolator.hpp>
#include <operations/utils/io/read_utils.h>
using namespace std;
using namespace bs::base::logger;
using namespace bs::base::memory;
using namespace bs::timer;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::utils::interpolation;
SeismicTraceManager::SeismicTraceManager(
bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mInterpolation = NONE;
this->mpTracesHolder = new TracesHolder();
this->mShotStride = 1;
}
SeismicTraceManager::~SeismicTraceManager() {
if (this->mpTracesHolder->Traces != nullptr) {
delete this->mpTracesHolder->Traces;
mem_free(this->mpTracesHolder->PositionsX);
mem_free(this->mpTracesHolder->PositionsY);
}
delete this->mpSeismicReader;
delete this->mpTracesHolder;
}
void SeismicTraceManager::AcquireConfiguration() {
LoggerSystem *Logger = LoggerSystem::GetInstance();
if (this->mpConfigurationMap->Contains(OP_K_PROPRIETIES, OP_K_INTERPOLATION)) {
string interpolation = OP_K_NONE;
interpolation = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_INTERPOLATION,
interpolation);
if (interpolation == OP_K_NONE) {
this->mInterpolation = NONE;
} else if (interpolation == OP_K_SPLINE) {
this->mInterpolation = SPLINE;
}
} else {
Logger->Error() << "Invalid value for trace-manager->interpolation key : "
"supported values [ none | spline ]" << '\n';
Logger->Info() << "Using default trace-manager->interpolation value: none..." << '\n';
}
this->mShotStride = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_SHOT_STRIDE, this->mShotStride);
Logger->Info() << "Using Shot Stride = " << this->mShotStride << " for trace-manager" << '\n';
// Initialize reader.
bool header_only = false;
header_only = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_HEADER_ONLY,
header_only);
std::string reader_type = "segy";
reader_type = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_TYPE,
reader_type);
try {
SeismicReader::ToReaderType(reader_type);
} catch (exception &e) {
Logger->Error() << "Invalid trace manager type provided : " << e.what() << '\n';
Logger->Error() << "Terminating..." << '\n';
exit(EXIT_FAILURE);
}
Logger->Info() << "Trace manager will use " << reader_type << " format." << '\n';
nlohmann::json configuration_map =
nlohmann::json::parse(this->mpConfigurationMap->ToString());
bs::base::configurations::JSONConfigurationMap io_conf_map(configuration_map);
this->mpSeismicReader = new SeismicReader(
SeismicReader::ToReaderType(reader_type), &io_conf_map);
this->mpSeismicReader->AcquireConfiguration();
this->mpSeismicReader->SetHeaderOnlyMode(header_only);
}
void SeismicTraceManager::SetComputationParameters(ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void SeismicTraceManager::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpGridBox = apGridBox;
if (this->mpGridBox == nullptr) {
Logger->Error() << "No GridBox provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void SeismicTraceManager::ReadShot(vector<string> file_names,
uint shot_number,
string sort_key) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
if (this->mpTracesHolder->Traces != nullptr) {
delete this->mpTracesHolder->Traces;
mem_free(this->mpTracesHolder->PositionsX);
mem_free(this->mpTracesHolder->PositionsY);
this->mpTracesHolder->Traces = nullptr;
this->mpTracesHolder->PositionsX = nullptr;
this->mpTracesHolder->PositionsY = nullptr;
}
Gather *gather;
{
ScopeTimer t("IO::ReadSelectedShotFromSegyFile");
gather = this->mpSeismicReader->Read({std::to_string(shot_number)});
}
if (gather == nullptr) {
Logger->Error() << "Didn't find a suitable file to read shot ID "
<< shot_number
<< " from..." << '\n';
exit(EXIT_FAILURE);
} else {
Logger->Info() << "Reading trace for shot ID "
<< shot_number << '\n';
}
utils::io::ParseGatherToTraces(gather,
&this->mpSourcePoint,
this->mpTracesHolder,
&this->mpTracesHolder->PositionsX,
&this->mpTracesHolder->PositionsY,
this->mpGridBox,
this->mpParameters,
&this->mTotalTime);
delete gather;
}
void SeismicTraceManager::PreprocessShot() {
Interpolator::Interpolate(this->mpTracesHolder,
this->mpGridBox->GetNT(),
this->mTotalTime,
this->mInterpolation);
mpDTraces.Free();
mpDPositionsX.Free();
mpDPositionsY.Free();
mpDTraces.Allocate(this->mpTracesHolder->SampleNT * this->mpTracesHolder->TraceSizePerTimeStep,
"Device traces");
mpDPositionsX.Allocate(this->mpTracesHolder->TraceSizePerTimeStep, "trace x positions");
mpDPositionsY.Allocate(this->mpTracesHolder->TraceSizePerTimeStep, "trace y positions");
Device::MemCpy(mpDTraces.GetNativePointer(), this->mpTracesHolder->Traces->GetNativePointer(),
this->mpTracesHolder->SampleNT * this->mpTracesHolder->TraceSizePerTimeStep * sizeof(float),
Device::COPY_DEVICE_TO_DEVICE);
Device::MemCpy(mpDPositionsX.GetNativePointer(), this->mpTracesHolder->PositionsX,
this->mpTracesHolder->TraceSizePerTimeStep * sizeof(uint),
Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(mpDPositionsY.GetNativePointer(), this->mpTracesHolder->PositionsY,
this->mpTracesHolder->TraceSizePerTimeStep * sizeof(uint),
Device::COPY_HOST_TO_DEVICE);
}
void SeismicTraceManager::ApplyIsotropicField() {
/// @todo To be implemented.
}
void SeismicTraceManager::RevertIsotropicField() {
/// @todo To be implemented.
}
TracesHolder *SeismicTraceManager::GetTracesHolder() {
return this->mpTracesHolder;
}
Point3D *SeismicTraceManager::GetSourcePoint() {
return &this->mpSourcePoint;
}
vector<uint> SeismicTraceManager::GetWorkingShots(
vector<string> file_names, uint min_shot, uint max_shot, string type) {
std::vector<TraceHeaderKey> gather_keys = {TraceHeaderKey::FLDR};
std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> sorting_keys;
this->mpSeismicReader->Initialize(gather_keys, sorting_keys, file_names);
auto keys = this->mpSeismicReader->GetIdentifiers();
vector<uint> all_shots;
for (auto key : keys) {
size_t unique_val = std::stoull(key[0]);
if (unique_val >= min_shot && unique_val <= max_shot) {
all_shots.push_back(unique_val);
}
}
vector<uint> selected_shots;
for (int i = 0; i < all_shots.size(); i += this->mShotStride) {
selected_shots.push_back(all_shots[i]);
}
return selected_shots;
}
| 9,120
|
C++
|
.cpp
| 199
| 37.432161
| 114
| 0.650747
|
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,158
|
RickerSourceInjector.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/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 <cmath>
#include <bs/base/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/source-injectors/RickerSourceInjector.hpp>
#include <operations/configurations/MapKeys.h>
using namespace bs::base::logger;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
RickerSourceInjector::RickerSourceInjector(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mMaxFrequencyAmplitudePercentage = 0.05;
}
RickerSourceInjector::~RickerSourceInjector() = default;
void RickerSourceInjector::AcquireConfiguration() {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mMaxFrequencyAmplitudePercentage = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES,
OP_K_MAX_FREQ_AMP_PERCENT,
this->mMaxFrequencyAmplitudePercentage);
if (this->mMaxFrequencyAmplitudePercentage < 0 || this->mMaxFrequencyAmplitudePercentage > 1) {
throw std::runtime_error("Max Frequency Amplitude Percentage must be between 0(exclusive) and 1");
}
float peak_frequency = this->mpParameters->GetSourceFrequency();
float amp_peak = (2.0f * expf(-1)) / (sqrtf(M_PI) * peak_frequency);
float target_amp =
mMaxFrequencyAmplitudePercentage * amp_peak; //Target the cutoff peak frequency, when less than 1% of peak
float max_freq = peak_frequency;
float cur_amp = (2 * powf(max_freq, 2) * expf(-powf(max_freq / peak_frequency, 2)))
/ (sqrtf(M_PI) * powf(peak_frequency, 3));
while (cur_amp > target_amp) {
max_freq += 1;
cur_amp = (2 * powf(max_freq, 2) * expf(-powf(max_freq / peak_frequency, 2)))
/ (sqrtf(M_PI) * powf(peak_frequency, 3));
}
this->mMaxFrequency = max_freq;
Logger->Info() << "Using Ricker with peak frequency " << peak_frequency
<< " and max frequency " << mMaxFrequency << '\n';
}
void RickerSourceInjector::ApplyIsotropicField() {
/// @todo To be implemented.
uint location = this->GetInjectionLocation();
uint isotropic_radius = this->mpParameters->GetIsotropicRadius();
// Loop on circular field
// 1. epsilon[location] = 0.0f
// 2. delta[location] = 0.0f
}
void RickerSourceInjector::RevertIsotropicField() {
/// @todo To be implemented.
}
int RickerSourceInjector::GetCutOffTimeStep() {
// At which time does the source injection finish.
float dt = this->mpGridBox->GetDT();
float freq = this->mpParameters->GetSourceFrequency();
return roundf((1.0f / freq) / dt);
}
int RickerSourceInjector::GetPrePropagationNT() {
// What time does the source need before the zero time step.
float dt = this->mpGridBox->GetDT();
float freq = this->mpParameters->GetSourceFrequency();
return roundf(((1.0f / freq) / dt));
}
float RickerSourceInjector::GetMaxFrequency() {
return this->mMaxFrequency;
}
void RickerSourceInjector::SetComputationParameters(ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void RickerSourceInjector::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpGridBox = apGridBox;
if (this->mpGridBox == nullptr) {
Logger->Error() << "No GridBox provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void RickerSourceInjector::SetSourcePoint(Point3D *apSourcePoint) {
this->mpSourcePoint = apSourcePoint;
}
uint RickerSourceInjector::GetInjectionLocation() {
uint x = this->mpSourcePoint->x;
uint y = this->mpSourcePoint->y;
uint z = this->mpSourcePoint->z;
uint wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint location = y * wnx * wnz + z * wnx + x;
return location;
}
| 5,186
|
C++
|
.cpp
| 111
| 41.063063
| 120
| 0.694774
|
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,159
|
SeismicModelHandler.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/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 <set>
#include <prerequisites/libraries/nlohmann/json.hpp>
#include <bs/base/api/cpp/BSBase.hpp>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <bs/io/api/cpp/BSIO.hpp>
#include <operations/components/independents/concrete/model-handlers/SeismicModelHandler.hpp>
#include <operations/utils/sampling/Sampler.hpp>
#include <operations/utils/interpolation/Interpolator.hpp>
#include <operations/utils/io/read_utils.h>
#include <operations/configurations/MapKeys.h>
using namespace std;
using namespace bs::base::logger;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::timer;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::helpers;
using namespace operations::utils::sampling;
using namespace operations::utils::io;
SeismicModelHandler::SeismicModelHandler(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mpGridBox = new GridBox();
this->mReaderType = "segy";
// Default as unit will be centimeter and scaling to meter.
this->mDepthSamplingScaler = 1e3;
};
SeismicModelHandler::~SeismicModelHandler() = default;
void SeismicModelHandler::AcquireConfiguration() {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mReaderType = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_TYPE,
this->mReaderType);
try {
SeismicReader::ToReaderType(this->mReaderType);
} catch (exception &e) {
Logger->Error() << "Invalid model handler type provided : " << e.what() << '\n';
Logger->Error() << "Terminating..." << '\n';
exit(EXIT_FAILURE);
}
this->mDepthSamplingScaler = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES,
OP_K_DEPTH_SAMPLING_SCALING,
this->mDepthSamplingScaler);
Logger->Info() << "Model handler will use " << this->mReaderType << " format." << '\n';
}
void SeismicModelHandler::SetComputationParameters(ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void SeismicModelHandler::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpGridBox = apGridBox;
if (this->mpGridBox == nullptr) {
Logger->Error() << "No GridBox provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void SeismicModelHandler::SetDependentComponents(
ComponentsMap<DependentComponent> *apDependentComponentsMap) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
HasDependents::SetDependentComponents(apDependentComponentsMap);
this->mpWaveFieldsMemoryHandler =
(WaveFieldsMemoryHandler *)
this->GetDependentComponentsMap()->Get(MEMORY_HANDLER);
if (this->mpWaveFieldsMemoryHandler == nullptr) {
Logger->Error() << "No Wave Fields Memory Handler provided... "
<< "Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
GridBox *SeismicModelHandler::ReadModel(map<string, string> file_names) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->Initialize(file_names);
int initial_nx = this->mpGridBox->GetInitialAxis()->GetXAxis().GetLogicalAxisSize();
int initial_ny = this->mpGridBox->GetInitialAxis()->GetYAxis().GetLogicalAxisSize();
int initial_nz = this->mpGridBox->GetInitialAxis()->GetZAxis().GetLogicalAxisSize();
int actual_nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int actual_ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
int actual_nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
int logical_nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize();
int logical_ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
int logical_nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetLogicalAxisSize();
int model_size = actual_nx * actual_ny * actual_nz;
int logical_size = logical_nx * logical_ny * logical_nz;
int initial_size = initial_nx * initial_ny * initial_nz;
int offset = this->mpParameters->GetBoundaryLength() + this->mpParameters->GetHalfLength();
int offset_y = actual_ny > 1 ? this->mpParameters->GetBoundaryLength() + this->mpParameters->GetHalfLength() : 0;
nlohmann::json configuration_map =
nlohmann::json::parse(this->mpConfigurationMap->ToString());
bs::base::configurations::JSONConfigurationMap io_conf_map(
configuration_map);
Reader *seismic_io_reader = new SeismicReader(
SeismicReader::ToReaderType(this->mReaderType),
&io_conf_map);
seismic_io_reader->AcquireConfiguration();
map<string, float> maximums;
for (auto const ¶meter : this->PARAMS_NAMES) {
maximums[parameter.second] = 0.0f;
}
for (auto const ¶meter : this->PARAMS_NAMES) {
GridBox::Key param_key = parameter.first;
string param_name = parameter.second;
vector<Gather *> gathers;
if (file_names.find(param_name) == file_names.end() ||
file_names[param_name].empty()) {
} else {
auto channelName = "IO::Read" + param_name + "FromInputFile";
ElasticTimer timer(channelName.c_str());
timer.Start();
std::vector<TraceHeaderKey> empty_gather_keys;
std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> sorting_keys;
std::vector<std::string> paths = {file_names[param_name]};
seismic_io_reader->Initialize(empty_gather_keys, sorting_keys,
paths);
gathers = seismic_io_reader->ReadAll();
timer.Stop();
}
auto parameter_host_buffer = new float[initial_size];
auto resized_host_buffer = new float[model_size];
auto logical_host_buffer = new float[logical_size];
memset(parameter_host_buffer, 0, initial_size * sizeof(float));
memset(resized_host_buffer, 0, model_size * sizeof(float));
memset(logical_host_buffer, 0, logical_size * sizeof(float));
uint index = 0;
if (gathers.empty()) {
Logger->Info() << "Please provide " << param_name << " model file..." << '\n';
float default_value = 0.0f;
// Unless density, assume acoustic and fill with zeros.
// For density, assume constant density.
if (param_name == "density") {
default_value = 1.0f;
}
for (unsigned int k = offset_y; k < initial_ny - offset_y; k++) {
for (unsigned int i = offset; i < initial_nx - offset; i++) {
for (unsigned int j = offset; j < initial_nz - offset; j++) {
index = k * initial_nx * initial_nz + j * initial_nx + i;
parameter_host_buffer[index] = default_value;
}
}
}
} else {
auto gather = CombineGather(gathers);
RemoveDuplicatesFromGather(gather);
/// sort data
vector<pair<TraceHeaderKey, Gather::SortDirection>> sorting_keys = {
{TraceHeaderKey::SY, Gather::SortDirection::ASC},
{TraceHeaderKey::SX, Gather::SortDirection::ASC}
};
gather->SortGather(sorting_keys);
/// Reading and maximum identification
for (unsigned int k = offset_y; k < initial_ny - offset_y; k++) {
for (unsigned int i = offset; i < initial_nx - offset; i++) {
for (unsigned int j = offset; j < initial_nz - offset; j++) {
uint index = k * initial_nx * initial_nz + j * initial_nx + i;
uint trace_index = (k - offset_y) * (initial_nx - 2 * offset) + (i - offset);
float temp =
parameter_host_buffer[index] =
gather->GetTrace(trace_index)->GetTraceData()[j - offset];
if (temp > maximums[param_name]) {
maximums[param_name] = temp;
}
}
}
}
delete gather;
gathers.clear();
seismic_io_reader->Finalize();
}
Sampler::Resize(parameter_host_buffer, logical_host_buffer,
mpGridBox->GetInitialAxis(), mpGridBox->GetAfterSamplingAxis(),
mpParameters);
for (unsigned int k = offset_y; k < logical_ny - offset_y; k++) {
for (unsigned int j = offset; j < logical_nz - offset; j++) {
for (unsigned int i = offset; i < logical_nx - offset; i++) {
uint actual_index = k * actual_nx * actual_nz + j * actual_nx + i;
uint logical_index = k * logical_nx * logical_nz + j * logical_nx + i;
resized_host_buffer[actual_index] = logical_host_buffer[logical_index];
}
}
}
auto parameter_ptr = this->mpGridBox->Get(param_key)->GetNativePointer();
Device::MemCpy(parameter_ptr, resized_host_buffer, sizeof(float) * model_size, Device::COPY_HOST_TO_DEVICE);
delete[] parameter_host_buffer;
delete[] resized_host_buffer;
delete[] logical_host_buffer;
}
this->mpGridBox->SetDT(GetSuitableDT(
this->mpParameters->GetSecondDerivativeFDCoefficient(),
maximums, this->mpParameters->GetHalfLength(), this->mpParameters->GetRelaxedDT()));
delete seismic_io_reader;
return this->mpGridBox;
}
void SeismicModelHandler::Initialize(map<string, string> file_names) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
if (file_names["velocity"].empty()) {
Logger->Error() << "Please provide a velocity model... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
nlohmann::json configuration_map =
nlohmann::json::parse(this->mpConfigurationMap->ToString());
bs::base::configurations::JSONConfigurationMap io_conf_map(
configuration_map);
Reader *seismic_io_reader = new SeismicReader(
SeismicReader::ToReaderType(this->mReaderType),
&io_conf_map);
ElasticTimer timer("IO::ReadVelocityMetadata");
timer.Start();
std::vector<TraceHeaderKey> empty_gather_keys;
vector<pair<TraceHeaderKey, Gather::SortDirection>> sorting_keys = {
{TraceHeaderKey::SY, Gather::SortDirection::ASC},
{TraceHeaderKey::SX, Gather::SortDirection::ASC}
};
std::vector<std::string> paths = {file_names["velocity"]};
seismic_io_reader->Initialize(empty_gather_keys, sorting_keys,
paths);
seismic_io_reader->SetHeaderOnlyMode(true);
vector<Gather *> gathers;
gathers = seismic_io_reader->ReadAll();
timer.Stop();
auto gather = CombineGather(gathers);
RemoveDuplicatesFromGather(gather);
gather->SortGather(sorting_keys);
set<float> x_locations;
set<float> y_locations;
for (uint i = 0; i < gather->GetNumberTraces(); i++) {
x_locations.emplace(
gather->GetTrace(i)->GetScaledCoordinateHeader(TraceHeaderKey::SX));
y_locations.emplace(
gather->GetTrace(i)->GetScaledCoordinateHeader(TraceHeaderKey::SY));
}
uint x_size = x_locations.size();
uint y_size = y_locations.size();
uint z_size = gather->GetTrace(0)->GetNumberOfSamples();
if (y_size > 1) {
this->mpGridBox->SetInitialAxis(new Axis3D<unsigned int>(x_size, y_size, z_size));
this->mpGridBox->GetInitialAxis()->GetYAxis().AddBoundary(OP_DIREC_BOTH,
this->mpParameters->GetBoundaryLength());
this->mpGridBox->GetInitialAxis()->GetYAxis().AddHalfLengthPadding(OP_DIREC_BOTH,
this->mpParameters->GetHalfLength());
} else {
this->mpGridBox->SetInitialAxis(new Axis3D<unsigned int>(x_size, 1, z_size));
this->mpGridBox->GetInitialAxis()->GetYAxis().AddBoundary(OP_DIREC_BOTH, 0);
this->mpGridBox->GetInitialAxis()->GetYAxis().AddHalfLengthPadding(OP_DIREC_BOTH, 0);
}
this->mpGridBox->GetInitialAxis()->GetXAxis().AddBoundary(OP_DIREC_BOTH,
this->mpParameters->GetBoundaryLength()); //x_size =5395
this->mpGridBox->GetInitialAxis()->GetZAxis().AddBoundary(OP_DIREC_BOTH, this->mpParameters->GetBoundaryLength());
this->mpGridBox->GetInitialAxis()->GetXAxis().AddHalfLengthPadding(OP_DIREC_BOTH,
this->mpParameters->GetHalfLength());
this->mpGridBox->GetInitialAxis()->GetZAxis().AddHalfLengthPadding(OP_DIREC_BOTH,
this->mpParameters->GetHalfLength());
float dx, dy, dz, dt;
dx = *(++x_locations.begin()) - (*x_locations.begin());
if (y_locations.size() > 1) {
dy = *(++y_locations.begin()) - (*y_locations.begin());
} else {
dy = 0;
}
// If given model is a 2D line.
if (IsLineGather(gather)) {
dx = sqrt(dx * dx + dy * dy);
dy = 0;
y_size = 1;
this->mpGridBox->GetInitialAxis()->SetYAxis(y_size);
this->mpGridBox->GetInitialAxis()->GetYAxis().AddBoundary(OP_DIREC_BOTH, 0);
this->mpGridBox->GetInitialAxis()->GetYAxis().AddHalfLengthPadding(OP_DIREC_BOTH, 0);
}
if (this->mpGridBox->GetInitialAxis()->GetYAxis().GetLogicalAxisSize() == 1) {
Logger->Info() << "Operating on a 2D model" << '\n';
} else {
Logger->Info() << "Operating on a 3D model" << '\n';
}
dz = gather->GetSamplingRate() / this->mDepthSamplingScaler;
this->mpGridBox->GetInitialAxis()->GetXAxis().SetCellDimension(dx);
this->mpGridBox->GetInitialAxis()->GetYAxis().SetCellDimension(dy);
this->mpGridBox->GetInitialAxis()->GetZAxis().SetCellDimension(dz);
this->mpGridBox->GetInitialAxis()->GetXAxis().SetReferencePoint(gather->GetTrace(0)->GetScaledCoordinateHeader(
TraceHeaderKey::SX));
this->mpGridBox->GetInitialAxis()->GetZAxis().SetReferencePoint(0);
this->mpGridBox->GetInitialAxis()->GetYAxis().SetReferencePoint(gather->GetTrace(0)->GetScaledCoordinateHeader(
TraceHeaderKey::SY));
this->mpGridBox->SetAfterSamplingAxis(new Axis3D<unsigned int>(*this->mpGridBox->GetInitialAxis()));
Logger->Info() << "Reference X \t: " << this->mpGridBox->GetInitialAxis()->GetXAxis().GetReferencePoint() << '\n';
Logger->Info() << "Reference Y \t: " << this->mpGridBox->GetInitialAxis()->GetYAxis().GetReferencePoint() << '\n';
Logger->Info() << "Reference Z \t: " << this->mpGridBox->GetInitialAxis()->GetZAxis().GetReferencePoint() << '\n';
/// If there is no window then window size equals full model size
if (this->mpParameters->IsUsingWindow()) {
this->mpGridBox->SetWindowStart(X_AXIS, 0);
this->mpGridBox->SetWindowStart(Y_AXIS, 0);
this->mpGridBox->SetWindowStart(Z_AXIS, 0);
unsigned int window_size = this->mpParameters->GetLeftWindow() + this->mpParameters->GetRightWindow() + 1;
this->mpGridBox->SetWindowAxis(new Axis3D<unsigned int>(0, 0, 0)); //so solve segmentation fault
if (this->mpParameters->GetLeftWindow() == 0 && this->mpParameters->GetRightWindow() == 0) {
this->mpGridBox->GetWindowAxis()->SetXAxis(x_size);
this->mpGridBox->GetWindowAxis()->GetXAxis().AddBoundary(OP_DIREC_BOTH,
this->mpParameters->GetBoundaryLength());
this->mpGridBox->GetWindowAxis()->GetXAxis().AddHalfLengthPadding(OP_DIREC_BOTH,
this->mpParameters->GetHalfLength());
} else {
this->mpGridBox->GetWindowAxis()->SetXAxis(min(window_size, x_size));
this->mpGridBox->GetWindowAxis()->GetXAxis().AddBoundary(OP_DIREC_BOTH,
this->mpParameters->GetBoundaryLength());
this->mpGridBox->GetWindowAxis()->GetXAxis().AddHalfLengthPadding(OP_DIREC_BOTH,
this->mpParameters->GetHalfLength());
}
if (this->mpParameters->GetDepthWindow() == 0) {
this->mpGridBox->GetWindowAxis()->SetZAxis(z_size);
this->mpGridBox->GetWindowAxis()->GetZAxis().AddBoundary(OP_DIREC_BOTH,
this->mpParameters->GetBoundaryLength());
this->mpGridBox->GetWindowAxis()->GetZAxis().AddHalfLengthPadding(OP_DIREC_BOTH,
this->mpParameters->GetHalfLength());
} else {
this->mpGridBox->GetWindowAxis()->SetZAxis(min(window_size, z_size));
this->mpGridBox->GetWindowAxis()->GetZAxis().AddBoundary(OP_DIREC_BOTH,
this->mpParameters->GetBoundaryLength());
this->mpGridBox->GetWindowAxis()->GetZAxis().AddHalfLengthPadding(OP_DIREC_BOTH,
this->mpParameters->GetHalfLength());
}
if ((this->mpParameters->GetFrontWindow() == 0 &&
this->mpParameters->GetBackWindow() == 0) ||
y_size == 1) {
this->mpGridBox->GetWindowAxis()->SetYAxis(y_size);
this->mpGridBox->GetWindowAxis()->GetYAxis().AddBoundary(OP_DIREC_BOTH, 0);
this->mpGridBox->GetWindowAxis()->GetYAxis().AddHalfLengthPadding(OP_DIREC_BOTH, 0);
} else {
this->mpGridBox->GetWindowAxis()->SetYAxis(min(window_size, y_size));
this->mpGridBox->GetWindowAxis()->GetYAxis().AddBoundary(OP_DIREC_BOTH,
this->mpParameters->GetBoundaryLength());
this->mpGridBox->GetWindowAxis()->GetYAxis().AddHalfLengthPadding(OP_DIREC_BOTH,
this->mpParameters->GetHalfLength());
}
this->mpGridBox->GetWindowAxis()->GetXAxis().SetCellDimension(dx);
this->mpGridBox->GetWindowAxis()->GetYAxis().SetCellDimension(dy);
this->mpGridBox->GetWindowAxis()->GetZAxis().SetCellDimension(dz);
} else {
this->mpGridBox->SetWindowStart(X_AXIS, 0);
this->mpGridBox->SetWindowStart(Y_AXIS, 0);
this->mpGridBox->SetWindowStart(Z_AXIS, 0);
this->mpGridBox->SetWindowAxis(new Axis3D<unsigned int>(*this->mpGridBox->GetInitialAxis()));
}
// Assume minimum velocity to be 1500 m/s for now.
uint initial_logical_x = this->mpGridBox->GetInitialAxis()->GetXAxis().GetLogicalAxisSize();
uint initial_logical_y = this->mpGridBox->GetInitialAxis()->GetYAxis().GetLogicalAxisSize();
uint initial_logical_z = this->mpGridBox->GetInitialAxis()->GetZAxis().GetLogicalAxisSize();
Sampler::CalculateAdaptiveCellDimensions(mpGridBox, mpParameters, 1500,
this->mpParameters->GetMaxPropagationFrequency());
this->SetupPadding();
this->RegisterWaveFields(initial_logical_x, initial_logical_y, initial_logical_z);
this->RegisterParameters(initial_logical_x, initial_logical_y, initial_logical_z);
this->AllocateWaveFields();
this->AllocateParameters();
seismic_io_reader->Finalize();
delete seismic_io_reader;
this->mpGridBox->SetParameterGatherHeader(gather);
}
void SeismicModelHandler::RegisterWaveFields(uint nx, uint ny, uint nz) {
/// Register wave field by order
if (this->mpParameters->GetEquationOrder() == FIRST) {
this->WAVE_FIELDS_NAMES.push_back(WAVE | GB_PRTC | CURR | DIR_Z);
this->WAVE_FIELDS_NAMES.push_back(WAVE | GB_PRTC | CURR | DIR_X);
if (ny > 1) {
this->WAVE_FIELDS_NAMES.push_back(WAVE | GB_PRTC | CURR | DIR_Y);
}
/// Register wave field by approximation
if (this->mpParameters->GetApproximation() == ISOTROPIC) {
this->WAVE_FIELDS_NAMES.push_back(WAVE | GB_PRSS | CURR);
this->WAVE_FIELDS_NAMES.push_back(WAVE | GB_PRSS | NEXT);
}
} else if (this->mpParameters->GetEquationOrder() == SECOND) {
/// Register wave field by approximation
if (this->mpParameters->GetApproximation() == ISOTROPIC) {
this->WAVE_FIELDS_NAMES.push_back(WAVE | GB_PRSS | CURR);
this->WAVE_FIELDS_NAMES.push_back(WAVE | GB_PRSS | PREV);
this->WAVE_FIELDS_NAMES.push_back(WAVE | GB_PRSS | NEXT);
}
}
}
void SeismicModelHandler::RegisterParameters(uint nx, uint ny, uint nz) {
/// Register parameters by order
this->PARAMS_NAMES.push_back(std::make_pair(PARM | GB_VEL, "velocity"));
if (this->mpParameters->GetEquationOrder() == FIRST) {
this->PARAMS_NAMES.push_back(std::make_pair(PARM | GB_DEN, "density"));
}
}
void SeismicModelHandler::AllocateWaveFields() {
uint wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wny * wnz;
/// Allocating and zeroing wave fields.
for (auto wave_field : this->WAVE_FIELDS_NAMES) {
if (!GridBox::Includes(wave_field, NEXT)) {
auto frame_buffer = new FrameBuffer<float>();
frame_buffer->Allocate(window_size,
mpParameters->GetHalfLength(),
GridBox::Stringify(wave_field));
this->mpWaveFieldsMemoryHandler->FirstTouch(frame_buffer->GetNativePointer(), this->mpGridBox, true);
this->mpGridBox->RegisterWaveField(wave_field, frame_buffer);
if (GridBox::Includes(wave_field, GB_PRSS | PREV)) {
GridBox::Replace(&wave_field, PREV, NEXT);
this->mpGridBox->RegisterWaveField(wave_field, frame_buffer);
} else if (this->mpParameters->GetEquationOrder() == FIRST &&
GridBox::Includes(wave_field, GB_PRSS | CURR)) {
GridBox::Replace(&wave_field, CURR, NEXT);
this->mpGridBox->RegisterWaveField(wave_field, frame_buffer);
}
}
}
}
void SeismicModelHandler::AllocateParameters() {
uint nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
uint ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
uint nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
uint grid_size = nx * nz * ny;
uint wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint window_size = wnx * wnz * wny;
if (this->mpParameters->IsUsingWindow()) {
for (auto const ¶meter : this->PARAMS_NAMES) {
GridBox::Key param_key = parameter.first;
string param_name = parameter.second;
auto frame_buffer = new FrameBuffer<float>();
frame_buffer->Allocate(grid_size,
mpParameters->GetHalfLength(),
param_name);
this->mpWaveFieldsMemoryHandler->FirstTouch(frame_buffer->GetNativePointer(), this->mpGridBox);
auto frame_buffer_window = new FrameBuffer<float>();
frame_buffer_window->Allocate(window_size,
mpParameters->GetHalfLength(),
param_name);
this->mpWaveFieldsMemoryHandler->FirstTouch(frame_buffer_window->GetNativePointer(), this->mpGridBox, true);
this->mpGridBox->RegisterParameter(param_key, frame_buffer, frame_buffer_window);
}
} else {
for (auto const ¶meter : this->PARAMS_NAMES) {
GridBox::Key param_key = parameter.first;
string param_name = parameter.second;
auto frame_buffer = new FrameBuffer<float>();
frame_buffer->Allocate(grid_size,
mpParameters->GetHalfLength(),
param_name);
this->mpWaveFieldsMemoryHandler->FirstTouch(frame_buffer->GetNativePointer(), this->mpGridBox);
this->mpGridBox->RegisterParameter(param_key, frame_buffer);
}
}
}
float SeismicModelHandler::GetSuitableDT
(float *coefficients, map<string, float> maximums, int half_length, float dt_relax) {
float dx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
uint ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
// Calculate dt through finite difference stability equation
float dxSquare = 1 / (dx * dx);
float dySquare;
if (ny != 1)
dySquare = 1 / (dy * dy);
else // case of 2D
dySquare = 0.0;
float dzSquare = 1 / (dz * dz);
float distanceM = 1 / (sqrtf(dxSquare + dySquare + dzSquare));
/// The sum of absolute value of weights for second derivative if
/// du per dt. we use second order so the weights are (-1,2,1)
float a1 = 4;
float a2 = 0;
for (int i = 1; i <= half_length; i++) {
a2 += fabs(coefficients[i]);
}
a2 *= 2.0;
/// The sum of absolute values for second derivative id
/// du per dx ( one dimension only )
a2 += fabs(coefficients[0]);
float dt = ((sqrtf(a1 / a2)) * distanceM) / maximums["velocity"] * dt_relax;
return dt;
}
void SeismicModelHandler::PostProcessMigration(MigrationData *apMigrationData) {
int initial_nx = this->mpGridBox->GetInitialAxis()->GetXAxis().GetLogicalAxisSize(); //logical
int initial_ny = this->mpGridBox->GetInitialAxis()->GetYAxis().GetLogicalAxisSize();
int initial_nz = this->mpGridBox->GetInitialAxis()->GetZAxis().GetLogicalAxisSize();
int actual_nx = apMigrationData->GetGridSize(X_AXIS);
int actual_ny = apMigrationData->GetGridSize(Y_AXIS);
int actual_nz = apMigrationData->GetGridSize(Z_AXIS);
size_t gather_num = apMigrationData->GetGatherDimension();
int offset = mpParameters->GetBoundaryLength() + mpParameters->GetHalfLength();
int base_nx = this->mpGridBox->GetInitialAxis()->GetXAxis().GetAxisSize();
int base_ny = this->mpGridBox->GetInitialAxis()->GetYAxis().GetAxisSize();
int base_nz = this->mpGridBox->GetInitialAxis()->GetZAxis().GetAxisSize();
int logical_nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize();
int logical_ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
int logical_nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetLogicalAxisSize();
int after_actual_nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int after_actual_nz = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
int after_actual_ny = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
size_t initial_frame = initial_nx * initial_ny * initial_nz;
size_t base_frame = base_nx * base_ny * base_nz;
size_t base_size = base_frame * gather_num;
size_t actual_frame = actual_nx * actual_nz * actual_ny;
size_t after_logical_frame = logical_nx * logical_ny * logical_nz;
auto parameter_host_buffer = new float[initial_frame];
auto after_logical_buffer = new float[after_logical_frame];
for (auto const &result : apMigrationData->GetResults()) {
auto unpadded_parameter_host_buffer = new float[base_size];
auto original = result->GetData();
for (uint frame_index = 0; frame_index < gather_num; frame_index++) {
auto frame_ptr = &unpadded_parameter_host_buffer[frame_index * base_frame];
memset(parameter_host_buffer, 0, initial_frame * sizeof(float));
memset(frame_ptr, 0, base_frame * sizeof(float));
auto original_frame = &(original[frame_index * actual_frame]);
// Set data to without computational/non-computation padding
for (int iy = 0; iy < logical_ny; iy++) {
for (int iz = 0; iz < logical_nz; iz++) {
for (int ix = 0; ix < logical_nx; ix++) {
int index = iy * logical_nz * logical_nx + iz * logical_nx + ix;
int alt_index = iy * after_actual_nz * after_actual_nx + iz * after_actual_nx + ix;
after_logical_buffer[index] = original_frame[alt_index];
}
}
}
// Resize to initial
Sampler::Resize(after_logical_buffer, parameter_host_buffer,
mpGridBox->GetAfterSamplingAxis(),
mpGridBox->GetInitialAxis(),
mpParameters);
// Remove padding.
for (int iy = 0; iy < base_ny; iy++) {
for (int iz = 0; iz < base_nz; iz++) {
for (int ix = 0; ix < base_nx; ix++) {
int index = iy * base_nz * base_nx + iz * base_nx + ix;
int padded_index = (iz + offset) * initial_nx + ix + offset;
if (initial_ny != 1) {
padded_index += ((iy + offset) * initial_nx * initial_nz);
}
frame_ptr[index] = parameter_host_buffer[padded_index];
}
}
}
}
// Set result.
delete[] original;
result->SetData(unpadded_parameter_host_buffer);
}
delete[] parameter_host_buffer;
delete[] after_logical_buffer;
// Update migration data results.
apMigrationData->SetGridSize(X_AXIS, base_nx);
apMigrationData->SetGridSize(Z_AXIS, base_nz);
apMigrationData->SetGridSize(Y_AXIS, base_ny);
apMigrationData->SetCellDimensions(X_AXIS, mpGridBox->GetInitialAxis()->GetXAxis().GetCellDimension());
apMigrationData->SetCellDimensions(Y_AXIS, mpGridBox->GetInitialAxis()->GetYAxis().GetCellDimension());
apMigrationData->SetCellDimensions(Z_AXIS, mpGridBox->GetInitialAxis()->GetZAxis().GetCellDimension());
}
| 32,420
|
C++
|
.cpp
| 574
| 45.062718
| 120
| 0.617187
|
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,160
|
SecondOrderComputationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/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 <iostream>
#include <cmath>
#include <bs/base/api/cpp/BSBase.hpp>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/components/independents/concrete/computation-kernels/isotropic/SecondOrderComputationKernel.hpp>
#include <operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp>
using namespace std;
using namespace bs::timer;
using namespace bs::base::logger;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
SecondOrderComputationKernel::SecondOrderComputationKernel(
bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mpMemoryHandler = new WaveFieldsMemoryHandler(apConfigurationMap);
this->mpBoundaryManager = nullptr;
}
SecondOrderComputationKernel::SecondOrderComputationKernel(
const SecondOrderComputationKernel &aSecondOrderComputationKernel) {
this->mpConfigurationMap = aSecondOrderComputationKernel.mpConfigurationMap;
this->mpMemoryHandler = new WaveFieldsMemoryHandler(this->mpConfigurationMap);
this->mpBoundaryManager = nullptr;
}
SecondOrderComputationKernel::~SecondOrderComputationKernel() = default;
void SecondOrderComputationKernel::AcquireConfiguration() {}
ComputationKernel *SecondOrderComputationKernel::Clone() {
return new SecondOrderComputationKernel(*this);
}
template<KERNEL_MODE KERNEL_MODE_>
void SecondOrderComputationKernel::Compute() {
int logical_ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
if (logical_ny == 1) {
this->Compute<KERNEL_MODE_, true>();
} else {
this->Compute<KERNEL_MODE_, false>();
}
}
template<KERNEL_MODE KERNEL_MODE_, bool IS_2D_>
void SecondOrderComputationKernel::Compute() {
switch (mpParameters->GetHalfLength()) {
case O_2:
Compute < KERNEL_MODE_, IS_2D_, O_2 > ();
break;
case O_4:
Compute < KERNEL_MODE_, IS_2D_, O_4 > ();
break;
case O_8:
Compute < KERNEL_MODE_, IS_2D_, O_8 > ();
break;
case O_12:
Compute < KERNEL_MODE_, IS_2D_, O_12 > ();
break;
case O_16:
Compute < KERNEL_MODE_, IS_2D_, O_16 > ();
break;
}
}
void SecondOrderComputationKernel::Step() {
// Take a step in time.
if (mpCoeffX == nullptr) {
InitializeVariables();
}
if (this->mMode == KERNEL_MODE::FORWARD) {
this->Compute<KERNEL_MODE::FORWARD>();
} else if (this->mMode == KERNEL_MODE::INVERSE) {
this->Compute<KERNEL_MODE::INVERSE>();
} else if (this->mMode == KERNEL_MODE::ADJOINT) {
this->Compute<KERNEL_MODE::ADJOINT>();
} else {
throw bs::base::exceptions::ILLOGICAL_EXCEPTION();
}
// Swap pointers : Next to current, current to prev and unwanted prev to next
// to be overwritten.
if (this->mpGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z) ==
this->mpGridBox->Get(WAVE | GB_PRSS | NEXT | DIR_Z)) {
// two pointers case : curr becomes both next and prev, while next becomes
// current.
this->mpGridBox->Swap(WAVE | GB_PRSS | PREV | DIR_Z, WAVE | GB_PRSS | CURR | DIR_Z);
this->mpGridBox->Set(WAVE | GB_PRSS | NEXT | DIR_Z,
this->mpGridBox->Get(WAVE | GB_PRSS | PREV | DIR_Z));
} else {
// three pointers : normal swapping between the three pointers.
this->mpGridBox->Swap(WAVE | GB_PRSS | PREV | DIR_Z, WAVE | GB_PRSS | CURR | DIR_Z);
this->mpGridBox->Swap(WAVE | GB_PRSS | CURR | DIR_Z, WAVE | GB_PRSS | NEXT | DIR_Z);
}
{
ScopeTimer t("BoundaryManager::ApplyBoundary");
if (this->mpBoundaryManager != nullptr) {
this->mpBoundaryManager->ApplyBoundary();
}
}
}
void SecondOrderComputationKernel::SetComputationParameters(ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void SecondOrderComputationKernel::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpGridBox = apGridBox;
if (this->mpGridBox == nullptr) {
Logger->Error() << "No GridBox provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
MemoryHandler *SecondOrderComputationKernel::GetMemoryHandler() {
return this->mpMemoryHandler;
}
void SecondOrderComputationKernel::InitializeVariables() {
int wnx = mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
float dx2 = 1 / (mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension() *
mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension());
float dz2 = 1 / (mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension() *
mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension());
float dy2 = 1;
float *coeff = mpParameters->GetSecondDerivativeFDCoefficient();
bool is_2D = wny == 1;
if (!is_2D) {
dy2 = 1 / (mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension() *
mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension());
}
int hl = mpParameters->GetHalfLength();
int array_length = hl;
float coeff_x[hl];
float coeff_y[hl];
float coeff_z[hl];
int vertical[hl];
int front[hl];
for (int i = 0; i < hl; i++) {
coeff_x[i] = coeff[i + 1] * dx2;
coeff_z[i] = coeff[i + 1] * dz2;
vertical[i] = (i + 1) * (wnx);
if (!is_2D) {
coeff_y[i] = coeff[i + 1] * dy2;
front[i] = (i + 1) * wnx * wnz;
}
}
mpCoeffX = new FrameBuffer<float>(array_length);
mpCoeffY = new FrameBuffer<float>(array_length);
mpCoeffZ = new FrameBuffer<float>(array_length);
mpFrontalIdx = new FrameBuffer<int>(array_length);
mpVerticalIdx = new FrameBuffer<int>(array_length);
if (is_2D) {
mCoeffXYZ = coeff[0] * (dx2 + dz2);
} else {
mCoeffXYZ = coeff[0] * (dx2 + dy2 + dz2);
}
Device::MemCpy(mpCoeffX->GetNativePointer(), coeff_x, array_length * sizeof(float));
Device::MemCpy(mpCoeffZ->GetNativePointer(), coeff_z, array_length * sizeof(float));
Device::MemCpy(mpVerticalIdx->GetNativePointer(), vertical, array_length * sizeof(int));
if (!is_2D) {
Device::MemCpy(mpCoeffY->GetNativePointer(), coeff_y, array_length * sizeof(float));
Device::MemCpy(mpFrontalIdx->GetNativePointer(), front, array_length * sizeof(int));
}
}
| 7,771
|
C++
|
.cpp
| 179
| 37.463687
| 117
| 0.672754
|
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,161
|
StaggeredComputationKernel.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/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 out<<x_end - x_start<<" " <<y_end - y_start <<" "<< z_end - z_start<<sycl::endl;
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 <bs/base/api/cpp/BSBase.hpp>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/components/independents/concrete/computation-kernels/isotropic/StaggeredComputationKernel.hpp>
#include <operations/components/dependents/concrete/memory-handlers/WaveFieldsMemoryHandler.hpp>
using namespace std;
using namespace bs::base::logger;
using namespace bs::timer;
using namespace operations::components;
using namespace operations::common;
using namespace operations::dataunits;
StaggeredComputationKernel::StaggeredComputationKernel(
bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mpMemoryHandler = new WaveFieldsMemoryHandler(this->mpConfigurationMap);
this->mpBoundaryManager = nullptr;
this->mpCoeff = nullptr;
}
StaggeredComputationKernel::StaggeredComputationKernel(const StaggeredComputationKernel &aStaggeredComputationKernel) {
this->mpConfigurationMap = aStaggeredComputationKernel.mpConfigurationMap;
this->mpMemoryHandler = new WaveFieldsMemoryHandler(this->mpConfigurationMap);
this->mpBoundaryManager = nullptr;
this->mpCoeff = nullptr;
}
StaggeredComputationKernel::~StaggeredComputationKernel() {
delete this->mpCoeff;
}
void StaggeredComputationKernel::AcquireConfiguration() {}
ComputationKernel *StaggeredComputationKernel::Clone() {
return new StaggeredComputationKernel(*this);
}
template<KERNEL_MODE KERNEL_MODE_>
void StaggeredComputationKernel::ComputeAll() {
int logical_ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
if (logical_ny == 1) {
this->ComputeAll<KERNEL_MODE_, true>();
} else {
this->ComputeAll<KERNEL_MODE_, false>();
}
}
template<KERNEL_MODE KERNEL_MODE_, bool IS_2D_>
void StaggeredComputationKernel::ComputeAll() {
switch (mpParameters->GetHalfLength()) {
case O_2:
ComputeAll < KERNEL_MODE_, IS_2D_, O_2 > ();
break;
case O_4:
ComputeAll < KERNEL_MODE_, IS_2D_, O_4 > ();
break;
case O_8:
ComputeAll < KERNEL_MODE_, IS_2D_, O_8 > ();
break;
case O_12:
ComputeAll < KERNEL_MODE_, IS_2D_, O_12 > ();
break;
case O_16:
ComputeAll < KERNEL_MODE_, IS_2D_, O_16 > ();
break;
}
}
template<KERNEL_MODE KERNEL_MODE_, bool IS_2D_, HALF_LENGTH HALF_LENGTH_>
void StaggeredComputationKernel::ComputeAll() {
this->ComputeVelocity<KERNEL_MODE_, IS_2D_, HALF_LENGTH_>();
ElasticTimer timer("BoundaryManager::ApplyBoundary(Velocity)");
timer.Start();
if (this->mpBoundaryManager != nullptr) {
this->mpBoundaryManager->ApplyBoundary(1);
}
timer.Stop();
this->ComputePressure<KERNEL_MODE_, IS_2D_, HALF_LENGTH_>();
}
void StaggeredComputationKernel::Step() {
if (this->mpCoeff == nullptr) {
InitializeVariables();
}
// Take a step in time.
if (this->mMode == KERNEL_MODE::FORWARD) {
this->ComputeAll<KERNEL_MODE::FORWARD>();
} else if (this->mMode == KERNEL_MODE::INVERSE) {
this->ComputeAll<KERNEL_MODE::INVERSE>();
} else if (this->mMode == KERNEL_MODE::ADJOINT) {
this->ComputeAll<KERNEL_MODE::ADJOINT>();
} else {
throw bs::base::exceptions::ILLOGICAL_EXCEPTION();
}
this->mpGridBox->Swap(WAVE | GB_PRSS | NEXT | DIR_Z, WAVE | GB_PRSS | CURR | DIR_Z);
{
ScopeTimer t("BoundaryManager::ApplyBoundary(Pressure)");
if (this->mpBoundaryManager != nullptr) {
this->mpBoundaryManager->ApplyBoundary(0);
}
}
}
void StaggeredComputationKernel::SetComputationParameters(ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void StaggeredComputationKernel::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpGridBox = apGridBox;
if (this->mpGridBox == nullptr) {
Logger->Error() << "No GridBox provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
MemoryHandler *StaggeredComputationKernel::GetMemoryHandler() {
return this->mpMemoryHandler;
}
void StaggeredComputationKernel::InitializeVariables() {
int wnx = mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
float *coeff = mpParameters->GetFirstDerivativeStaggeredFDCoefficient();
int hl = mpParameters->GetHalfLength();
int array_length = hl;
float coeff_local[hl];
int vertical[hl];
for (int i = 0; i < hl; i++) {
coeff_local[i] = coeff[i + 1];
vertical[i] = (i + 1) * (wnx);
}
mpCoeff = new FrameBuffer<float>(array_length);
mpVerticalIdx = new FrameBuffer<int>(array_length);
Device::MemCpy(mpCoeff->GetNativePointer(), coeff_local,
array_length * sizeof(float));
Device::MemCpy(mpVerticalIdx->GetNativePointer(), vertical, array_length * sizeof(int));
}
| 6,116
|
C++
|
.cpp
| 149
| 36.013423
| 119
| 0.698434
|
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,162
|
NoBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/boundary-managers/NoBoundaryManager.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/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/boundary-managers/NoBoundaryManager.hpp>
#include <operations/components/independents/concrete/boundary-managers/extensions/ZeroExtension.hpp>
using namespace bs::base::logger;
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::common;
using namespace operations::dataunits;
NoBoundaryManager::NoBoundaryManager(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
}
void NoBoundaryManager::AcquireConfiguration() {}
NoBoundaryManager::~NoBoundaryManager() {
for (auto const &extension : this->mvExtensions) {
delete extension;
}
this->mvExtensions.clear();
}
void NoBoundaryManager::ExtendModel() {
for (auto const &extension : this->mvExtensions) {
extension->ExtendProperty();
}
}
void NoBoundaryManager::ReExtendModel() {
for (auto const &extension : this->mvExtensions) {
extension->ReExtendProperty();
}
}
void NoBoundaryManager::ApplyBoundary(uint kernel_id) {
// Do nothing for perfect reflection.
}
void NoBoundaryManager::SetComputationParameters(ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void NoBoundaryManager::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpGridBox = apGridBox;
if (this->mpGridBox == nullptr) {
Logger->Error() << "No GridBox provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
InitializeExtensions();
}
void NoBoundaryManager::InitializeExtensions() {
uint params_size = this->mpGridBox->GetParameters().size();
for (int i = 0; i < params_size; ++i) {
this->mvExtensions.push_back(new ZeroExtension());
}
for (auto const &extension : this->mvExtensions) {
extension->SetHalfLength(this->mpParameters->GetHalfLength());
extension->SetBoundaryLength(this->mpParameters->GetBoundaryLength());
}
uint index = 0;
for (auto const ¶meter : this->mpGridBox->GetParameters()) {
this->mvExtensions[index]->SetGridBox(this->mpGridBox);
this->mvExtensions[index]->SetProperty(parameter.second->GetNativePointer(),
this->mpGridBox->Get(WIND | parameter.first)->GetNativePointer());
index++;
}
}
void NoBoundaryManager::AdjustModelForBackward() {
for (auto const &extension : this->mvExtensions) {
extension->AdjustPropertyForBackward();
}
}
| 3,634
|
C++
|
.cpp
| 88
| 36.829545
| 113
| 0.725701
|
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,163
|
SpongeBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/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 <bs/base/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/boundary-managers/SpongeBoundaryManager.hpp>
#include <operations/configurations/MapKeys.h>
#include <operations/components/independents/concrete/boundary-managers/extensions/HomogenousExtension.hpp>
using namespace std;
using namespace bs::base::logger;
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::common;
using namespace operations::dataunits;
/// Based on
/// https://pubs.geoscienceworld.org/geophysics/article-abstract/50/4/705/71992/A-nonreflecting-boundary-condition-for-discrete?redirectedFrom=fulltext
SpongeBoundaryManager::SpongeBoundaryManager(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mUseTopLayer = true;
}
void SpongeBoundaryManager::AcquireConfiguration() {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mUseTopLayer = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_USE_TOP_LAYER, this->mUseTopLayer);
if (this->mUseTopLayer) {
Logger->Info()
<< "Using top boundary layer for forward modelling. To disable it set <boundary-manager.use-top-layer=false>"
<< '\n';
} else {
Logger->Info()
<< "Not using top boundary layer for forward modelling. To enable it set <boundary-manager.use-top-layer=true>"
<< '\n';
}
}
float SpongeBoundaryManager::Calculation(int index) {
float value;
uint bound_length = mpParameters->GetBoundaryLength();
value = expf(-powf((0.1f / bound_length) * (bound_length - index), 2));
return value;
}
void SpongeBoundaryManager::ApplyBoundary(uint kernel_id) {
if (kernel_id == 0) {
ApplyBoundaryOnField(this->mpGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetNativePointer());
}
}
void SpongeBoundaryManager::ExtendModel() {
for (auto const &extension : this->mvExtensions) {
extension->ExtendProperty();
}
}
void SpongeBoundaryManager::ReExtendModel() {
for (auto const &extension : this->mvExtensions) {
extension->ReExtendProperty();
}
}
SpongeBoundaryManager::~SpongeBoundaryManager() {
for (auto const &extension : this->mvExtensions) {
delete extension;
}
this->mvExtensions.clear();
delete this->mpSpongeCoefficients;
}
void SpongeBoundaryManager::SetComputationParameters(ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void SpongeBoundaryManager::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpGridBox = apGridBox;
if (this->mpGridBox == nullptr) {
Logger->Error() << "No GridBox provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
InitializeExtensions();
uint bound_length = this->mpParameters->GetBoundaryLength();
auto temp_arr = new float[bound_length];
for (int i = 0; i < bound_length; i++) {
temp_arr[i] = Calculation(i);
}
mpSpongeCoefficients = new FrameBuffer<float>(bound_length);
Device::MemCpy(mpSpongeCoefficients->GetNativePointer(), temp_arr, bound_length * sizeof(float));
delete[] temp_arr;
}
void SpongeBoundaryManager::InitializeExtensions() {
uint params_size = this->mpGridBox->GetParameters().size();
for (int i = 0; i < params_size; ++i) {
this->mvExtensions.push_back(new HomogenousExtension(mUseTopLayer));
}
for (auto const &extension : this->mvExtensions) {
extension->SetHalfLength(this->mpParameters->GetHalfLength());
extension->SetBoundaryLength(this->mpParameters->GetBoundaryLength());
}
uint index = 0;
for (auto const ¶meter : this->mpGridBox->GetParameters()) {
this->mvExtensions[index]->SetGridBox(this->mpGridBox);
this->mvExtensions[index]->SetProperty(parameter.second->GetNativePointer(),
this->mpGridBox->Get(WIND | parameter.first)->GetNativePointer());
index++;
}
}
void SpongeBoundaryManager::AdjustModelForBackward() {
for (auto const &extension : this->mvExtensions) {
extension->AdjustPropertyForBackward();
}
}
| 5,340
|
C++
|
.cpp
| 124
| 38.16129
| 151
| 0.715524
|
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,164
|
RandomBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/boundary-managers/RandomBoundaryManager.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 <cstdlib>
#include <ctime>
#include <bs/base/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/boundary-managers/RandomBoundaryManager.hpp>
#include <operations/components/independents/concrete/boundary-managers/extensions/MinExtension.hpp>
#include <operations/components/independents/concrete/boundary-managers/extensions/RandomExtension.hpp>
#include <operations/configurations/MapKeys.h>
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::common;
using namespace operations::dataunits;
using namespace bs::base::logger;
RandomBoundaryManager::RandomBoundaryManager(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
srand(time(NULL));
this->mpConfigurationMap = apConfigurationMap;
this->mGrainSideLength = 0;
}
void RandomBoundaryManager::AcquireConfiguration() {
this->mGrainSideLength = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_GRAIN_SIDE_LENGTH,
this->mGrainSideLength);
LoggerSystem *Logger = LoggerSystem::GetInstance();
if (this->mGrainSideLength <= 0) {
Logger->Error() << "No valid value provided for key 'grain_side_length'..." << '\n';
Logger->Info() << "Using default value for grain_side_length 0f 200" << '\n';
this->mGrainSideLength = 200;
} else {
Logger->Info() << "Random Boundary manager will use grains of side length = " << this->mGrainSideLength
<< " meters." << '\n';
}
}
RandomBoundaryManager::~RandomBoundaryManager() {
for (auto const &extension : this->mvExtensions) {
delete extension;
}
this->mvExtensions.clear();
}
void
RandomBoundaryManager::ExtendModel() {
for (auto const &extension : this->mvExtensions) {
extension->ExtendProperty();
}
}
void
RandomBoundaryManager::ReExtendModel() {
for (auto const &extension : this->mvExtensions) {
extension->ExtendProperty();
extension->ReExtendProperty();
}
}
void
RandomBoundaryManager::ApplyBoundary(uint kernel_id) {
// Do nothing for random boundaries.
}
void
RandomBoundaryManager::SetComputationParameters(ComputationParameters *apParameters) {
auto logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void
RandomBoundaryManager::SetGridBox(GridBox *apGridBox) {
auto logger = LoggerSystem::GetInstance();
this->mpGridBox = apGridBox;
if (this->mpGridBox == nullptr) {
logger->Error() << "No GridBox provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
InitializeExtensions();
}
void
RandomBoundaryManager::InitializeExtensions() {
this->mvExtensions.push_back(new RandomExtension(this->mGrainSideLength));
uint params_size = this->mpGridBox->GetParameters().size();
for (int i = 0; i < params_size - 1; ++i) {
this->mvExtensions.push_back(new MinExtension());
}
for (auto const &extension : this->mvExtensions) {
extension->SetHalfLength(this->mpParameters->GetHalfLength());
extension->SetBoundaryLength(this->mpParameters->GetBoundaryLength());
}
uint index = 0;
for (auto const ¶meter : this->mpGridBox->GetParameters()) {
this->mvExtensions[index]->SetGridBox(this->mpGridBox);
this->mvExtensions[index]->SetProperty(parameter.second->GetNativePointer(),
this->mpGridBox->Get(WIND | parameter.first)->GetNativePointer());
index++;
}
}
void
RandomBoundaryManager::AdjustModelForBackward() {
for (auto const &extension : this->mvExtensions) {
extension->AdjustPropertyForBackward();
}
}
| 4,715
|
C++
|
.cpp
| 115
| 35.93913
| 113
| 0.709607
|
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,165
|
CPMLBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/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 <algorithm>
#include <cmath>
#include <bs/base/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/boundary-managers/CPMLBoundaryManager.hpp>
#include <operations/configurations/MapKeys.h>
#include <operations/components/independents/concrete/boundary-managers/extensions/HomogenousExtension.hpp>
#ifndef PWR2
#define PWR2(EXP) ((EXP) * (EXP))
#endif
using namespace bs::base::logger;
using namespace bs::base::configurations;
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::common;
using namespace operations::dataunits;
CPMLBoundaryManager::CPMLBoundaryManager(ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mReflectCoefficient = 0.1;
this->mShiftRatio = 0.1;
this->mRelaxCoefficient = 0.1;
this->mUseTopLayer = true;
this->mpExtension = nullptr;
this->mpCoeffax = nullptr;
this->mpCoeffbx = nullptr;
this->mpCoeffaz = nullptr;
this->mpCoeffbz = nullptr;
this->mpCoeffay = nullptr;
this->mpCoeffby = nullptr;
this->mpAux1xup = nullptr;
this->mpAux1xdown = nullptr;
this->mpAux1zup = nullptr;
this->mpAux1zdown = nullptr;
this->mpAux1yup = nullptr;
this->mpAux1ydown = nullptr;
this->mpAux2xup = nullptr;
this->mpAux2xdown = nullptr;
this->mpAux2zup = nullptr;
this->mpAux2zdown = nullptr;
this->mpAux2yup = nullptr;
this->mpAux2ydown = nullptr;
this->mpFirstCoeffx = nullptr;
this->mpFirstCoeffz = nullptr;
this->mpFirstCoeffy = nullptr;
this->mpSecondCoeffx = nullptr;
this->mpSecondCoeffz = nullptr;
this->mpSecondCoeffy = nullptr;
this->mpDistanceDim1 = nullptr;
this->mpDistanceDim2 = nullptr;
this->mpDistanceDim3 = nullptr;
this->mpParameters = nullptr;
this->mpGridBox = nullptr;
this->mMaxVel = 0;
}
void CPMLBoundaryManager::AcquireConfiguration() {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mUseTopLayer = this->mpConfigurationMap->GetValue(
OP_K_PROPRIETIES,
OP_K_USE_TOP_LAYER, this->mUseTopLayer);
if (this->mUseTopLayer) {
Logger->Info() << "Using top boundary layer for forward modelling."
" To disable it set <boundary-manager.use-top-layer=false>" << '\n';
} else {
Logger->Info() << "Not using top boundary layer for forward modelling."
" To enable it set <boundary-manager.use-top-layer=true>" << '\n';
}
if (this->mpConfigurationMap->Contains(OP_K_PROPRIETIES,
OP_K_REFLECT_COEFFICIENT)) {
Logger->Info() << "Parsing user defined reflect coefficient" << '\n';
this->mReflectCoefficient = this->mpConfigurationMap->GetValue(
OP_K_PROPRIETIES,
OP_K_REFLECT_COEFFICIENT,
this->mReflectCoefficient);
}
if (this->mpConfigurationMap->Contains(OP_K_PROPRIETIES, OP_K_SHIFT_RATIO)) {
Logger->Info() << "Parsing user defined shift ratio" << '\n';
this->mShiftRatio = this->mpConfigurationMap->GetValue(
OP_K_PROPRIETIES,
OP_K_SHIFT_RATIO, this->mShiftRatio);
}
if (this->mpConfigurationMap->Contains(OP_K_PROPRIETIES, OP_K_RELAX_COEFFICIENT)) {
Logger->Info() << "Parsing user defined relax coefficient" << '\n';
this->mRelaxCoefficient = this->mpConfigurationMap->GetValue(
OP_K_PROPRIETIES,
OP_K_RELAX_COEFFICIENT,
this->mRelaxCoefficient);
}
this->mpExtension = new HomogenousExtension(this->mUseTopLayer);
this->mpExtension->SetHalfLength(
this->mpParameters->GetHalfLength());
this->mpExtension->SetBoundaryLength(
this->mpParameters->GetBoundaryLength());
}
template<int DIRECTION_>
void CPMLBoundaryManager::FillCPMLCoefficients() {
float pml_reg_len = this->mpParameters->GetBoundaryLength();
float dh = 0.0;
float *coeff_a;
float *coeff_b;
if (pml_reg_len == 0) {
pml_reg_len = 1;
}
float d0 = 0;
// Case x :
if (DIRECTION_ == X_AXIS) {
dh = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
coeff_a = this->mpCoeffax->GetNativePointer();
coeff_b = this->mpCoeffbx->GetNativePointer();
// Case z :
} else if (DIRECTION_ == Z_AXIS) {
dh = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
coeff_a = this->mpCoeffaz->GetNativePointer();
coeff_b = this->mpCoeffbz->GetNativePointer();
// Case y :
} else {
dh = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
coeff_a = this->mpCoeffay->GetNativePointer();
coeff_b = this->mpCoeffby->GetNativePointer();
}
float dt = this->mpGridBox->GetDT();
// Compute damping vector
d0 = (-logf(this->mReflectCoefficient) * ((3 * mMaxVel) / (pml_reg_len * dh)) *
this->mRelaxCoefficient) /
pml_reg_len;
uint bound_length = this->mpParameters->GetBoundaryLength();
float coeff_a_temp[bound_length];
float coeff_b_temp[bound_length];
for (int i = this->mpParameters->GetBoundaryLength(); i > 0; i--) {
float damping_ratio = PWR2(i) * d0;
coeff_a_temp[i - 1] = expf(-dt * (damping_ratio + this->mShiftRatio));
coeff_b_temp[i - 1] = (damping_ratio / (damping_ratio + this->mShiftRatio)) *
(coeff_a_temp[i - 1] - 1);
}
Device::MemCpy(coeff_a, coeff_a_temp, bound_length * sizeof(float),
Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(coeff_b, coeff_b_temp, bound_length * sizeof(float),
Device::COPY_HOST_TO_DEVICE);
}
template<int HALF_LENGTH_>
void CPMLBoundaryManager::ApplyAllCPML() {
int ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
CalculateFirstAuxiliary<X_AXIS, true, HALF_LENGTH_>();
CalculateFirstAuxiliary<Z_AXIS, true, HALF_LENGTH_>();
CalculateFirstAuxiliary<X_AXIS, false, HALF_LENGTH_>();
CalculateFirstAuxiliary<Z_AXIS, false, HALF_LENGTH_>();
CalculateCPMLValue<X_AXIS, true, HALF_LENGTH_>();
CalculateCPMLValue<Z_AXIS, true, HALF_LENGTH_>();
CalculateCPMLValue<X_AXIS, false, HALF_LENGTH_>();
CalculateCPMLValue<Z_AXIS, false, HALF_LENGTH_>();
}
void CPMLBoundaryManager::InitializeVariables() {
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize();
int ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetLogicalAxisSize();
int actual_nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int actual_nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
float dx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
float dt = this->mpGridBox->GetDT();
int bound_length = this->mpParameters->GetBoundaryLength();
int half_length = this->mpParameters->GetHalfLength();
float *host_velocity_base = this->mpGridBox->Get(PARM | GB_VEL)->GetHostPointer();
float max_velocity = 0;
for (int k = 0; k < ny; ++k) {
for (int j = 0; j < nz; ++j) {
for (int i = 0; i < nx; ++i) {
int offset = i + actual_nx * j + k * actual_nx * actual_nz;
float velocity_real = host_velocity_base[offset];
if (velocity_real > max_velocity) {
max_velocity = velocity_real;
}
}
}
}
max_velocity = max_velocity / (dt * dt);
this->mMaxVel = sqrtf(max_velocity);
this->mpCoeffax = new FrameBuffer<float>(bound_length);
this->mpCoeffbx = new FrameBuffer<float>(bound_length);
this->mpCoeffaz = new FrameBuffer<float>(bound_length);
this->mpCoeffbz = new FrameBuffer<float>(bound_length);
int width = bound_length + (2 * this->mpParameters->GetHalfLength());
int y_size = width * wnx * wnz;
int x_size = width * wny * wnz;
int z_size = width * wnx * wny;
this->mpAux1xup = new FrameBuffer<float>(x_size);
this->mpAux1xdown = new FrameBuffer<float>(x_size);
this->mpAux2xup = new FrameBuffer<float>(x_size);
this->mpAux2xdown = new FrameBuffer<float>(x_size);
Device::MemSet(mpAux1xup->GetNativePointer(), 0.0,
sizeof(float) * x_size);
Device::MemSet(mpAux1xdown->GetNativePointer(), 0.0,
sizeof(float) * x_size);
Device::MemSet(mpAux2xup->GetNativePointer(), 0.0,
sizeof(float) * x_size);
Device::MemSet(mpAux2xdown->GetNativePointer(), 0.0,
sizeof(float) * x_size);
this->mpAux1zup = new FrameBuffer<float>(z_size);
this->mpAux1zdown = new FrameBuffer<float>(z_size);
this->mpAux2zup = new FrameBuffer<float>(z_size);
this->mpAux2zdown = new FrameBuffer<float>(z_size);
Device::MemSet(mpAux1zup->GetNativePointer(), 0.0,
sizeof(float) * z_size);
Device::MemSet(mpAux1zdown->GetNativePointer(), 0.0,
sizeof(float) * z_size);
Device::MemSet(mpAux2zup->GetNativePointer(), 0.0,
sizeof(float) * z_size);
Device::MemSet(mpAux2zdown->GetNativePointer(), 0.0,
sizeof(float) * z_size);
FillCPMLCoefficients<X_AXIS>();
FillCPMLCoefficients<Z_AXIS>();
if (ny > 1) {
this->mpCoeffay = new FrameBuffer<float>(bound_length);
this->mpCoeffby = new FrameBuffer<float>(bound_length);
this->mpAux1yup = new FrameBuffer<float>(y_size);
this->mpAux1ydown = new FrameBuffer<float>(y_size);
this->mpAux2yup = new FrameBuffer<float>(y_size);
this->mpAux2ydown = new FrameBuffer<float>(y_size);
Device::MemSet(mpAux1yup->GetNativePointer(), 0.0,
sizeof(float) * y_size);
Device::MemSet(mpAux1ydown->GetNativePointer(), 0.0,
sizeof(float) * y_size);
Device::MemSet(mpAux2yup->GetNativePointer(), 0.0,
sizeof(float) * y_size);
Device::MemSet(mpAux2ydown->GetNativePointer(), 0.0,
sizeof(float) * y_size);
FillCPMLCoefficients<Y_AXIS>();
}
int helper_array_len = half_length + 1;
int distance_1[helper_array_len];
int distance_2[helper_array_len];
int distance_3[helper_array_len];
float coeff_first_x[helper_array_len];
float coeff_first_y[helper_array_len];
float coeff_first_z[helper_array_len];
float coeff_second_x[helper_array_len];
float coeff_second_y[helper_array_len];
float coeff_second_z[helper_array_len];
if (dy == 0) {
dy = 1;
}
float dx2 = dx * dx;
float dz2 = dz * dz;
float dy2 = dy * dy;
for (int i = 0; i < helper_array_len; i++) {
distance_1[i] = i;
distance_2[i] = i * wnx;
distance_3[i] = i * wnz * wnx;
coeff_first_x[i] = this->mpParameters->GetFirstDerivativeFDCoefficient()[i] / dx;
coeff_first_y[i] = this->mpParameters->GetFirstDerivativeFDCoefficient()[i] / dy;
coeff_first_z[i] = this->mpParameters->GetFirstDerivativeFDCoefficient()[i] / dz;
coeff_second_x[i] = this->mpParameters->GetSecondDerivativeFDCoefficient()[i] / dx2;
coeff_second_y[i] = this->mpParameters->GetSecondDerivativeFDCoefficient()[i] / dy2;
coeff_second_z[i] = this->mpParameters->GetSecondDerivativeFDCoefficient()[i] / dz2;
}
this->mpFirstCoeffx = new FrameBuffer<float>(helper_array_len);
this->mpFirstCoeffy = new FrameBuffer<float>(helper_array_len);
this->mpFirstCoeffz = new FrameBuffer<float>(helper_array_len);
this->mpSecondCoeffx = new FrameBuffer<float>(helper_array_len);
this->mpSecondCoeffy = new FrameBuffer<float>(helper_array_len);
this->mpSecondCoeffz = new FrameBuffer<float>(helper_array_len);
this->mpDistanceDim1 = new FrameBuffer<int>(helper_array_len);
this->mpDistanceDim2 = new FrameBuffer<int>(helper_array_len);
this->mpDistanceDim3 = new FrameBuffer<int>(helper_array_len);
Device::MemCpy(this->mpDistanceDim1->GetNativePointer(),
distance_1, helper_array_len * sizeof(int),
Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(this->mpDistanceDim2->GetNativePointer(),
distance_2, helper_array_len * sizeof(int),
Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(this->mpDistanceDim3->GetNativePointer(),
distance_3, helper_array_len * sizeof(int),
Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(this->mpFirstCoeffx->GetNativePointer(),
coeff_first_x, helper_array_len * sizeof(float),
Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(this->mpFirstCoeffy->GetNativePointer(),
coeff_first_y, helper_array_len * sizeof(float),
Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(this->mpFirstCoeffz->GetNativePointer(),
coeff_first_z, helper_array_len * sizeof(float),
Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(this->mpSecondCoeffx->GetNativePointer(),
coeff_second_x, helper_array_len * sizeof(float),
Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(this->mpSecondCoeffy->GetNativePointer(),
coeff_second_y, helper_array_len * sizeof(float),
Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(this->mpSecondCoeffz->GetNativePointer(),
coeff_second_z, helper_array_len * sizeof(float),
Device::COPY_HOST_TO_DEVICE);
}
void CPMLBoundaryManager::ResetVariables() {
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
int width =
this->mpParameters->GetBoundaryLength()
+ (2 * this->mpParameters->GetHalfLength());
int y_size = width * wnx * wnz;
int x_size = width * wny * wnz;
int z_size = width * wnx * wny;
Device::MemSet(mpAux1xup->GetNativePointer(), 0.0,
sizeof(float) * x_size);
Device::MemSet(mpAux1xdown->GetNativePointer(), 0.0,
sizeof(float) * x_size);
Device::MemSet(mpAux2xup->GetNativePointer(), 0.0,
sizeof(float) * x_size);
Device::MemSet(mpAux2xdown->GetNativePointer(), 0.0,
sizeof(float) * x_size);
Device::MemSet(mpAux1zup->GetNativePointer(), 0.0,
sizeof(float) * z_size);
Device::MemSet(mpAux1zdown->GetNativePointer(), 0.0,
sizeof(float) * z_size);
Device::MemSet(mpAux2zup->GetNativePointer(), 0.0,
sizeof(float) * z_size);
Device::MemSet(mpAux2zdown->GetNativePointer(), 0.0,
sizeof(float) * z_size);
if (this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize() > 1) {
Device::MemSet(mpAux1yup->GetNativePointer(), 0.0,
sizeof(float) * y_size);
Device::MemSet(mpAux1ydown->GetNativePointer(), 0.0,
sizeof(float) * y_size);
Device::MemSet(mpAux2yup->GetNativePointer(), 0.0,
sizeof(float) * y_size);
Device::MemSet(mpAux2ydown->GetNativePointer(), 0.0,
sizeof(float) * y_size);
}
}
void CPMLBoundaryManager::ExtendModel() {
this->mpExtension->ExtendProperty();
this->InitializeVariables();
}
void CPMLBoundaryManager::ReExtendModel() {
this->mpExtension->ReExtendProperty();
this->ResetVariables();
}
CPMLBoundaryManager::~CPMLBoundaryManager() {
delete this->mpExtension;
delete (mpCoeffax);
delete (mpCoeffbx);
delete (mpCoeffaz);
delete (mpCoeffbz);
delete (mpAux1xup);
delete (mpAux1xdown);
delete (mpAux1zup);
delete (mpAux1zdown);
delete (mpAux2xup);
delete (mpAux2xdown);
delete (mpAux2zup);
delete (mpAux2zdown);
if (mpAux1yup != nullptr) {
delete (mpCoeffay);
delete (mpCoeffby);
delete (mpAux1yup);
delete (mpAux1ydown);
delete (mpAux2yup);
delete (mpAux2ydown);
}
delete this->mpFirstCoeffx;
delete this->mpFirstCoeffz;
delete this->mpFirstCoeffy;
delete this->mpSecondCoeffx;
delete this->mpSecondCoeffz;
delete this->mpSecondCoeffy;
delete this->mpDistanceDim1;
delete this->mpDistanceDim2;
delete this->mpDistanceDim3;
}
void CPMLBoundaryManager::SetComputationParameters(ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void CPMLBoundaryManager::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpGridBox = apGridBox;
if (this->mpGridBox == nullptr) {
Logger->Error() << "No GridBox provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
this->mpExtension->SetGridBox(this->mpGridBox);
this->mpExtension->SetProperty(
this->mpGridBox->Get(PARM | GB_VEL)->GetNativePointer(),
this->mpGridBox->Get(PARM | WIND | GB_VEL)->GetNativePointer());
}
void CPMLBoundaryManager::ApplyBoundary(uint kernel_id) {
if (kernel_id == 0) {
switch (this->mpParameters->GetHalfLength()) {
case O_2:
ApplyAllCPML<O_2>();
break;
case O_4:
ApplyAllCPML<O_4>();
break;
case O_8:
ApplyAllCPML<O_8>();
break;
case O_12:
ApplyAllCPML<O_12>();
break;
case O_16:
ApplyAllCPML<O_16>();
break;
}
}
}
void CPMLBoundaryManager::AdjustModelForBackward() {
this->mpExtension->AdjustPropertyForBackward();
this->ResetVariables();
}
| 19,611
|
C++
|
.cpp
| 434
| 37.211982
| 107
| 0.64381
|
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,166
|
StaggeredCPMLBoundaryManager.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/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 <algorithm>
#include <cmath>
#include <bs/base/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/boundary-managers/StaggeredCPMLBoundaryManager.hpp>
#include <operations/configurations/MapKeys.h>
#include <operations/components/independents/concrete/boundary-managers/extensions/HomogenousExtension.hpp>
#ifndef PWR2
#define PWR2(EXP) ((EXP) * (EXP))
#endif
using namespace bs::base::logger;
using namespace operations::components;
using namespace operations::components::addons;
using namespace operations::common;
using namespace operations::dataunits;
StaggeredCPMLBoundaryManager::StaggeredCPMLBoundaryManager(
bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mReflectCoefficient = 0.1;
this->mShiftRatio = 0.1;
this->mRelaxCoefficient = 1;
this->mUseTopLayer = true;
this->mMaxVelocity = 0;
this->mpCoeff = 0;
}
void
StaggeredCPMLBoundaryManager::AcquireConfiguration() {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mUseTopLayer = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_USE_TOP_LAYER, this->mUseTopLayer);
if (this->mUseTopLayer) {
Logger->Info()
<< "Using top boundary layer for forward modelling. To disable it set <boundary-manager.use-top-layer=false>"
<< '\n';
} else {
Logger->Info()
<< "Not using top boundary layer for forward modelling. To enable it set <boundary-manager.use-top-layer=true>"
<< '\n';
}
if (this->mpConfigurationMap->Contains(OP_K_PROPRIETIES, OP_K_REFLECT_COEFFICIENT)) {
Logger->Info() << "Parsing user defined reflect coefficient" << '\n';
this->mReflectCoefficient = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_REFLECT_COEFFICIENT,
this->mReflectCoefficient);
}
if (this->mpConfigurationMap->Contains(OP_K_PROPRIETIES, OP_K_SHIFT_RATIO)) {
Logger->Info() << "Parsing user defined shift ratio" << '\n';
this->mShiftRatio = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_SHIFT_RATIO, this->mShiftRatio);
}
if (this->mpConfigurationMap->Contains(OP_K_PROPRIETIES, OP_K_RELAX_COEFFICIENT)) {
Logger->Info() << "Parsing user defined relax coefficient" << '\n';
this->mRelaxCoefficient = this->mpConfigurationMap->GetValue(OP_K_PROPRIETIES, OP_K_RELAX_COEFFICIENT,
this->mRelaxCoefficient);
}
}
void
StaggeredCPMLBoundaryManager::ExtendModel() {
for (auto const &extension: this->mvExtensions) {
extension->ExtendProperty();
}
}
void
StaggeredCPMLBoundaryManager::ReExtendModel() {
for (auto const &extension: this->mvExtensions) {
extension->ReExtendProperty();
}
ZeroAuxiliaryVariables();
}
StaggeredCPMLBoundaryManager::~StaggeredCPMLBoundaryManager() {
for (auto const &extension: this->mvExtensions) {
delete extension;
}
this->mvExtensions.clear();
delete mpSmall_a_x;
delete mpSmall_a_y;
delete mpSmall_a_z;
delete mpSmall_b_x;
delete mpSmall_b_y;
delete mpSmall_b_z;
delete mpAuxiliary_vel_x_left;
delete mpAuxiliary_vel_x_right;
delete mpAuxiliary_ptr_x_left;
delete mpAuxiliary_ptr_x_right;
delete mpAuxiliary_vel_z_up;
delete mpAuxiliary_vel_z_down;
delete mpAuxiliary_ptr_z_up;
delete mpAuxiliary_ptr_z_down;
delete mpAuxiliary_vel_y_up;
delete mpAuxiliary_vel_y_down;
delete mpAuxiliary_ptr_y_up;
delete mpAuxiliary_ptr_y_down;
delete mpCoeff;
}
void
StaggeredCPMLBoundaryManager::SetComputationParameters(ComputationParameters *apParameters) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpParameters = (ComputationParameters *) apParameters;
if (this->mpParameters == nullptr) {
Logger->Error() << "No computation parameters provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
}
void
StaggeredCPMLBoundaryManager::SetGridBox(GridBox *apGridBox) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mpGridBox = apGridBox;
if (this->mpGridBox == nullptr) {
Logger->Error() << "No GridBox provided... Terminating..." << '\n';
exit(EXIT_FAILURE);
}
InitializeExtensions();
int nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize();
int ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
int nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetLogicalAxisSize();
int actual_nx = this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int actual_ny = this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
int actual_nz = this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
int wnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int wnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
int b_l = mpParameters->GetBoundaryLength();
HALF_LENGTH h_l = mpParameters->GetHalfLength();
// get the size of grid
int grid_total_size = wnx * wnz * wny;
// the size of the boundary in x without half_length is x=b_l and z=nz-2*h_l
int bound_size_x = b_l * (wnz - 2 * h_l);
// the size of the boundary in z without half_length is x=nx-2*h_l and z=b_l
int bound_size_z = b_l * (wnx - 2 * h_l);
int bound_size_y = 0;
bool is_2d;
int y_start;
int y_end;
if (wny == 1) {
is_2d = 1;
y_start = 0;
y_end = 1;
} else {
y_start = h_l;
y_end = wny - h_l;
is_2d = 0;
// size of boundary in y without half_length x=nx-2*h_l z=nz-2*h_l y= b_l
bound_size_y = b_l * (wnx - 2 * h_l) * (wnz - 2 * h_l);
// if 3d multiply by y size without half_length which is ny-2*h_l
bound_size_x = bound_size_x * (wny - 2 * h_l);
bound_size_z = bound_size_z * (wny - 2 * h_l);
}
// allocate the small arrays for coefficients
mpSmall_a_x = new FrameBuffer<float>(b_l);
mpSmall_a_y = new FrameBuffer<float>(b_l);
mpSmall_a_z = new FrameBuffer<float>(b_l);
mpSmall_b_x = new FrameBuffer<float>(b_l);
mpSmall_b_y = new FrameBuffer<float>(b_l);
mpSmall_b_z = new FrameBuffer<float>(b_l);
// allocate the auxiliary variables for the boundary length for velocity in x
// direction
mpAuxiliary_vel_x_left = new FrameBuffer<float>(bound_size_x);
mpAuxiliary_vel_x_right = new FrameBuffer<float>(bound_size_x);
// allocate the auxiliary variables for the boundary length for velocity in z
// direction
mpAuxiliary_vel_z_up = new FrameBuffer<float>(bound_size_z);
mpAuxiliary_vel_z_down = new FrameBuffer<float>(bound_size_z);
// allocate the auxiliary variables for the boundary length for pressure in x
// direction
mpAuxiliary_ptr_x_left = new FrameBuffer<float>(bound_size_x);
mpAuxiliary_ptr_x_right = new FrameBuffer<float>(bound_size_x);
// allocate the auxiliary variables for the boundary length for pressure in z
// direction
mpAuxiliary_ptr_z_up = new FrameBuffer<float>(bound_size_z);
mpAuxiliary_ptr_z_down = new FrameBuffer<float>(bound_size_z);
// get the maximum velocity
float *velocity_base = this->mpGridBox->Get(PARM | GB_VEL)->GetHostPointer();
for (int k = 0; k < ny; ++k) {
for (int j = 0; j < nz; ++j) {
for (int i = 0; i < nx; ++i) {
int offset = i + actual_nx * j + k * actual_nx * actual_nz;
float velocity_real = velocity_base[offset];
if (velocity_real > this->mMaxVelocity) {
this->mMaxVelocity = velocity_real;
}
}
}
}
/// Put values for the small arrays
StaggeredCPMLBoundaryManager::FillCPMLCoefficients(
mpSmall_a_x->GetNativePointer(), mpSmall_b_x->GetNativePointer(), b_l, h_l,
this->mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension(), this->mpGridBox->GetDT(),
this->mMaxVelocity, this->mShiftRatio, this->mReflectCoefficient, this->mRelaxCoefficient);
StaggeredCPMLBoundaryManager::FillCPMLCoefficients(
mpSmall_a_z->GetNativePointer(), mpSmall_b_z->GetNativePointer(), b_l, h_l,
this->mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension(), this->mpGridBox->GetDT(),
this->mMaxVelocity, this->mShiftRatio, this->mReflectCoefficient, this->mRelaxCoefficient);
if (ny > 1) {
// allocate the auxiliary variables for the boundary length for velocity in y
// direction
mpAuxiliary_vel_y_up = new FrameBuffer<float>(bound_size_y);
mpAuxiliary_vel_y_down = new FrameBuffer<float>(bound_size_y);
// allocate the auxiliary variables for the boundary length for pressure in y
// direction
mpAuxiliary_ptr_y_up = new FrameBuffer<float>(bound_size_y);
mpAuxiliary_ptr_y_down = new FrameBuffer<float>(bound_size_y);
StaggeredCPMLBoundaryManager::FillCPMLCoefficients(
mpSmall_a_y->GetNativePointer(), mpSmall_b_y->GetNativePointer(), b_l, h_l,
this->mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension(), this->mpGridBox->GetDT(),
this->mMaxVelocity, this->mShiftRatio, this->mReflectCoefficient, this->mRelaxCoefficient);
}
}
void
StaggeredCPMLBoundaryManager::InitializeExtensions() {
uint params_size = this->mpGridBox->GetParameters().size();
for (int i = 0; i < params_size; ++i) {
this->mvExtensions.push_back(new HomogenousExtension(this->mUseTopLayer));
}
for (auto const &extension: this->mvExtensions) {
extension->SetHalfLength(this->mpParameters->GetHalfLength());
extension->SetBoundaryLength(this->mpParameters->GetBoundaryLength());
}
uint index = 0;
for (auto const ¶meter: this->mpGridBox->GetParameters()) {
this->mvExtensions[index]->SetGridBox(this->mpGridBox);
this->mvExtensions[index]->SetProperty(parameter.second->GetNativePointer(),
this->mpGridBox->Get(WIND | parameter.first)->GetNativePointer());
index++;
}
}
void
StaggeredCPMLBoundaryManager::AdjustModelForBackward() {
for (auto const &extension: this->mvExtensions) {
extension->AdjustPropertyForBackward();
}
ZeroAuxiliaryVariables();
}
// this function used to reset the auxiliary variables to zero
void
StaggeredCPMLBoundaryManager::ZeroAuxiliaryVariables() {
int wny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int lnx = this->mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
int lny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
int lnz = this->mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
HALF_LENGTH half_length = mpParameters->GetHalfLength();
int b_l = mpParameters->GetBoundaryLength();
int index_2d = 0;
if (wny != 1) {
index_2d = half_length;
}
int bound_x = (lny - 2 * index_2d) * (lnz - 2 * half_length) * b_l;
int bound_z = (lny - 2 * index_2d) * b_l * (lnx - 2 * half_length);
int bound_y = b_l * (lnx - 2 * half_length) * (lnz - 2 * half_length);
// X-Variables.
Device::MemSet(this->mpAuxiliary_vel_x_left->GetNativePointer(), 0,
bound_x * sizeof(float));
Device::MemSet(this->mpAuxiliary_vel_x_right->GetNativePointer(), 0,
bound_x * sizeof(float));
Device::MemSet(this->mpAuxiliary_ptr_x_left->GetNativePointer(), 0,
bound_x * sizeof(float));
Device::MemSet(this->mpAuxiliary_ptr_x_right->GetNativePointer(), 0,
bound_x * sizeof(float));
// Z-Variables
Device::MemSet(this->mpAuxiliary_vel_z_up->GetNativePointer(), 0,
bound_z * sizeof(float));
Device::MemSet(this->mpAuxiliary_vel_z_down->GetNativePointer(), 0,
bound_z * sizeof(float));
Device::MemSet(this->mpAuxiliary_ptr_z_up->GetNativePointer(), 0,
bound_z * sizeof(float));
Device::MemSet(this->mpAuxiliary_ptr_z_down->GetNativePointer(), 0,
bound_z * sizeof(float));
// for the auxiliaries in the z boundaries for all x and y
if (wny != 1) {
Device::MemSet(this->mpAuxiliary_vel_y_up->GetNativePointer(), 0,
bound_y * sizeof(float));
Device::MemSet(this->mpAuxiliary_vel_y_down->GetNativePointer(), 0,
bound_y * sizeof(float));
Device::MemSet(this->mpAuxiliary_ptr_y_up->GetNativePointer(), 0,
bound_y * sizeof(float));
Device::MemSet(this->mpAuxiliary_ptr_y_down->GetNativePointer(), 0,
bound_y * sizeof(float));
}
}
void
StaggeredCPMLBoundaryManager::FillCPMLCoefficients(
float *apCoeff_a, float *apCoeff_b, int aBoundaryLength, int aHalfLength, float aDh, float aDt,
float aMaxVel, float aShiftRatio, float aReflectCoeff, float aRelaxCp) {
float pml_reg_len = aBoundaryLength;
float coeff_a_temp[aBoundaryLength];
float coeff_b_temp[aBoundaryLength];
if (pml_reg_len == 0) {
pml_reg_len = 1;
}
float d0 = 0;
// compute damping vector ...
d0 =
(-logf(aReflectCoeff) * ((3 * aMaxVel) / (pml_reg_len * aDh)) * aRelaxCp) /
pml_reg_len;
for (int i = aBoundaryLength; i > 0; i--) {
float damping_ratio = i * i * d0;
coeff_a_temp[i - 1] = expf(-aDt * (damping_ratio + aShiftRatio));
coeff_b_temp[i - 1] =
(damping_ratio / (damping_ratio + aShiftRatio)) * (coeff_a_temp[i - 1] - 1);
}
Device::MemCpy(apCoeff_a, coeff_a_temp, aBoundaryLength * sizeof(float),
dataunits::Device::COPY_HOST_TO_DEVICE);
Device::MemCpy(apCoeff_b, coeff_b_temp, aBoundaryLength * sizeof(float),
dataunits::Device::COPY_HOST_TO_DEVICE);
mpCoeff = new FrameBuffer<float>(aHalfLength);
Device::MemCpy(mpCoeff->GetNativePointer(), mpParameters->GetFirstDerivativeStaggeredFDCoefficient(),
aHalfLength * sizeof(float),
dataunits::Device::COPY_HOST_TO_DEVICE);
}
void
StaggeredCPMLBoundaryManager::ApplyBoundary(uint aKernelId) {
if (aKernelId == 0) {
if (this->mAdjoint) {
this->ApplyPressureCPML<true>();
} else {
this->ApplyPressureCPML<false>();
}
} else {
if (this->mAdjoint) {
this->ApplyVelocityCPML<true>();
} else {
this->ApplyVelocityCPML<false>();
}
}
}
template<bool ADJOINT_, int HALF_LENGTH_>
void
StaggeredCPMLBoundaryManager::ApplyVelocityCPML() {
int ny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
this->CalculatePressureFirstAuxiliary<ADJOINT_, X_AXIS, false, HALF_LENGTH_>();
this->CalculatePressureFirstAuxiliary<ADJOINT_, X_AXIS, true, HALF_LENGTH_>();
this->CalculatePressureFirstAuxiliary<ADJOINT_, Z_AXIS, false, HALF_LENGTH_>();
this->CalculatePressureFirstAuxiliary<ADJOINT_, Z_AXIS, true, HALF_LENGTH_>();
if (ny > 1) {
this->CalculatePressureFirstAuxiliary<ADJOINT_, Y_AXIS, false, HALF_LENGTH_>();
this->CalculatePressureFirstAuxiliary<ADJOINT_, Y_AXIS, true, HALF_LENGTH_>();
}
this->CalculateVelocityCPMLValue<ADJOINT_, X_AXIS, false, HALF_LENGTH_>();
this->CalculateVelocityCPMLValue<ADJOINT_, X_AXIS, true, HALF_LENGTH_>();
this->CalculateVelocityCPMLValue<ADJOINT_, Z_AXIS, false, HALF_LENGTH_>();
this->CalculateVelocityCPMLValue<ADJOINT_, Z_AXIS, true, HALF_LENGTH_>();
if (ny > 1) {
this->CalculateVelocityCPMLValue<ADJOINT_, Y_AXIS, false, HALF_LENGTH_>();
this->CalculateVelocityCPMLValue<ADJOINT_, Y_AXIS, true, HALF_LENGTH_>();
}
}
template<bool ADJOINT_, int HALF_LENGTH_>
void
StaggeredCPMLBoundaryManager::ApplyPressureCPML() {
int ny = this->mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
this->CalculateVelocityFirstAuxiliary<ADJOINT_, X_AXIS, false, HALF_LENGTH_>();
this->CalculateVelocityFirstAuxiliary<ADJOINT_, X_AXIS, true, HALF_LENGTH_>();
this->CalculateVelocityFirstAuxiliary<ADJOINT_, Z_AXIS, false, HALF_LENGTH_>();
this->CalculateVelocityFirstAuxiliary<ADJOINT_, Z_AXIS, true, HALF_LENGTH_>();
if (ny > 1) {
this->CalculateVelocityFirstAuxiliary<ADJOINT_, Y_AXIS, false, HALF_LENGTH_>();
this->CalculateVelocityFirstAuxiliary<ADJOINT_, Y_AXIS, true, HALF_LENGTH_>();
}
this->CalculatePressureCPMLValue<ADJOINT_, X_AXIS, false, HALF_LENGTH_>();
this->CalculatePressureCPMLValue<ADJOINT_, X_AXIS, true, HALF_LENGTH_>();
this->CalculatePressureCPMLValue<ADJOINT_, Z_AXIS, false, HALF_LENGTH_>();
this->CalculatePressureCPMLValue<ADJOINT_, Z_AXIS, true, HALF_LENGTH_>();
if (ny > 1) {
this->CalculatePressureCPMLValue<ADJOINT_, Y_AXIS, false, HALF_LENGTH_>();
this->CalculatePressureCPMLValue<ADJOINT_, Y_AXIS, true, HALF_LENGTH_>();
}
}
template<bool ADJOINT_>
void
StaggeredCPMLBoundaryManager::ApplyVelocityCPML() {
switch (this->mpParameters->GetHalfLength()) {
case O_2:
ApplyVelocityCPML < ADJOINT_, O_2 > ();
break;
case O_4:
ApplyVelocityCPML < ADJOINT_, O_4 > ();
break;
case O_8:
ApplyVelocityCPML < ADJOINT_, O_8 > ();
break;
case O_12:
ApplyVelocityCPML < ADJOINT_, O_12 > ();
break;
case O_16:
ApplyVelocityCPML < ADJOINT_, O_16 > ();
break;
}
}
template<bool ADJOINT_>
void
StaggeredCPMLBoundaryManager::ApplyPressureCPML() {
switch (this->mpParameters->GetHalfLength()) {
case O_2:
ApplyPressureCPML < ADJOINT_, O_2 > ();
break;
case O_4:
ApplyPressureCPML < ADJOINT_, O_4 > ();
break;
case O_8:
ApplyPressureCPML < ADJOINT_, O_8 > ();
break;
case O_12:
ApplyPressureCPML < ADJOINT_, O_12 > ();
break;
case O_16:
ApplyPressureCPML < ADJOINT_, O_16 > ();
break;
}
}
| 19,416
|
C++
|
.cpp
| 422
| 38.78436
| 127
| 0.657982
|
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,167
|
Extension.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/components/primitive/independents/boundary-managers/extensions/Extension.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/api/cpp/BSBase.hpp>
#include <operations/components/independents/concrete/boundary-managers/extensions/Extension.hpp>
using namespace std;
using namespace bs::base::memory;
using namespace operations::components::addons;
using namespace operations::dataunits;
Extension::Extension()
: mBoundaryLength(0),
mHalfLength(0) {}
Extension::~Extension() = default;
void Extension::SetHalfLength(uint aHalfLength) {
this->mHalfLength = aHalfLength;
}
void Extension::SetBoundaryLength(uint aBoundaryLength) {
this->mBoundaryLength = aBoundaryLength;
}
void Extension::SetGridBox(GridBox *apGridBox) {
this->mpGridBox = apGridBox;
}
void Extension::SetProperty(float *apProperty, float *aWindowProperty) {
this->mProperties = apProperty;
this->mpWindowProperties = aWindowProperty;
}
void Extension::ExtendProperty() {
int nx = mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int ny = mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
int nz = mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
/**
* The nx , ny and nz includes the inner domain + BOUND_LENGTH + HALF_LENGTH in
* all dimensions and we want to extend the velocities at boundaries only with
* the HALF_LENGTH excluded
*/
int start_x = mHalfLength;
int start_y = mHalfLength;
int start_z = mHalfLength;
int end_x = mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize() - mHalfLength;
int end_y = mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize() - mHalfLength;
int end_z = mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetLogicalAxisSize() - mHalfLength;
/**
* Change the values of velocities at
* boundaries (HALF_LENGTH excluded) to zeros.
*/
VelocityExtensionHelper(this->mProperties,
start_x, start_y, start_z,
end_x, end_y, end_z,
nx, ny, nz,
mBoundaryLength);
}
void Extension::ReExtendProperty() {
/**
* Re-Extend the velocities in case of window model.
*/
int nx = mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int ny = mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
int nz = mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
/**
* The window size is a struct containing the window nx, ny and nz
* with the HALF_LENGTH and BOUND_LENGTH in all dimensions.
*/
int wnx = mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
/**
* The window size is a struct containing the window nx, ny and nz
* with the HALF_LENGTH and BOUND_LENGTH in all dimensions.
*/
if (mProperties == mpWindowProperties) {
/// No window model, no need to re-extend so return from function
/**
* The nx, ny and nz includes the inner domain + BOUND_LENGTH +HALF_LENGTH
* in all dimensions and we want to extend the velocities at boundaries only
* with the HALF_LENGTH excluded
*/
int start_x = mHalfLength;
int start_y = mHalfLength;
int start_z = mHalfLength;
int end_x = mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - mHalfLength;
int end_y = mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - mHalfLength;
int end_z = mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - mHalfLength;
/**
* No window model, no need to re-extend.
* Just re-extend the top boundary.
*/
this->TopLayerExtensionHelper(this->mProperties,
start_x, start_y, start_z,
end_x, end_y, end_z,
nx, ny, nz,
mBoundaryLength);
return;
} else {
/// Window model.
/**
* We want to work in velocities inside window but with the HALF_LENGTH
* excluded in all dimensions to reach the bound_length so it is applied in
* start points by adding HALF_LENGTH also at end by subtract HALF_LENGTH.
*/
int start_x = mHalfLength;
int start_y = mHalfLength;
int start_z = mHalfLength;
int end_x = mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - mHalfLength;
int end_y = mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - mHalfLength;
int end_z = mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - mHalfLength;
/// Extend the velocities at boundaries by zeros
this->VelocityExtensionHelper(this->mpWindowProperties,
start_x, start_y, start_z,
end_x, end_y, end_z,
wnx, wny, wnz,
mBoundaryLength);
}
}
void Extension::AdjustPropertyForBackward() {
int nx = mpGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
int ny = mpGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
int nz = mpGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
/**
* The window size is a struct containing the window nx, ny, and nz
* with the HALF_LENGTH and BOUND_LENGTH in all dimensions.
*/
int wnx = mpGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
int wny = mpGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
int wnz = mpGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
/**
* The window size is a struct containing the window nx, ny, and nz
* with the HALF_LENGTH and BOUND_LENGTH in all dimensions.
*/
/**
* We want to work in velocities inside window but with the HALF_LENGTH
* excluded in all dimensions to reach the bound_length so it is applied in
* start points by adding HALF_LENGTH also at end by subtract HALF_LENGTH.
*/
int start_x = mHalfLength;
int start_y = mHalfLength;
int start_z = mHalfLength;
int end_x = mpGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - mHalfLength;
int end_y = mpGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - mHalfLength;
int end_z = mpGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() - mHalfLength;
if (ny == 1) {
end_y = 1;
start_y = 0;
}
this->TopLayerRemoverHelper(this->mpWindowProperties,
start_x, start_y, start_z,
end_x, end_y, end_z,
wnx, wny, wnz,
mBoundaryLength);
}
| 7,712
|
C++
|
.cpp
| 164
| 38.640244
| 97
| 0.653175
|
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,168
|
GridBox.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/data-units/concrete/GridBox.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/api/cpp/BSBase.hpp>
#include <operations/data-units/concrete/holders/GridBox.hpp>
using namespace bs::base::exceptions;
using namespace bs::base::logger;
using namespace operations::dataunits;
GridBox::GridBox() {
this->mpParameterHeadersGather = nullptr;
this->mpWindowProperties = new WindowProperties();
this->mpInitialAxis = nullptr;
this->mpAfterSamplingAxis = nullptr;
this->mpWindowAxis = nullptr;
}
GridBox::~GridBox() {
delete this->mpWindowProperties;
delete this->mpInitialAxis;
delete this->mpAfterSamplingAxis;
delete this->mpWindowAxis;
};
void GridBox::SetDT(float _dt) {
if (_dt <= 0) {
throw ILLOGICAL_EXCEPTION();
}
this->mDT = _dt;
}
void GridBox::SetNT(float _nt) {
if (_nt <= 0) {
throw bs::base::exceptions::ILLOGICAL_EXCEPTION();
}
this->mNT = _nt;
}
/**
* @brief Window start per axe setter.
* @param[in] axis Axe direction
* @param[in] val Value to be set
* @throw ILLOGICAL_EXCEPTION()
*/
void GridBox::SetWindowStart(uint axis, uint val) {
if (is_out_of_range(axis)) {
throw AXIS_EXCEPTION();
}
if (axis == Y_AXIS) {
this->mpWindowProperties->window_start.y = val;
} else if (axis == Z_AXIS) {
this->mpWindowProperties->window_start.z = val;
} else if (axis == X_AXIS) {
this->mpWindowProperties->window_start.x = val;
}
}
uint GridBox::GetWindowStart(uint axis) {
if (is_out_of_range(axis)) {
throw AXIS_EXCEPTION();
}
uint val;
if (axis == Y_AXIS) {
val = this->mpWindowProperties->window_start.y;
} else if (axis == Z_AXIS) {
val = this->mpWindowProperties->window_start.z;
} else if (axis == X_AXIS) {
val = this->mpWindowProperties->window_start.x;
}
return val;
}
void GridBox::RegisterWaveField(u_int16_t key, FrameBuffer<float> *ptr_wave_field) {
key |= WAVE;
this->mWaveFields[key] = ptr_wave_field;
}
void GridBox::RegisterParameter(u_int16_t key,
FrameBuffer<float> *ptr_parameter,
FrameBuffer<float> *ptr_parameter_window) {
key |= PARM;
this->mParameters[key] = ptr_parameter;
key |= WIND;
if (ptr_parameter_window == nullptr) {
this->mWindowParameters[key] = ptr_parameter;
} else {
this->mWindowParameters[key] = ptr_parameter_window;
}
}
void GridBox::RegisterMasterWaveField() {
/// @todo To be implemented.
throw NOT_IMPLEMENTED_EXCEPTION();
}
float *GridBox::GetMasterWaveField() {
/// @todo To be implemented.
throw NOT_IMPLEMENTED_EXCEPTION();
}
FrameBuffer<float> *GridBox::Get(u_int16_t key) {
if (this->mWaveFields.find(key) != this->mWaveFields.end()) {
return this->mWaveFields[key];
} else if (this->mParameters.find(key) != this->mParameters.end()) {
return this->mParameters[key];
} else if (this->mWindowParameters.find(key) != this->mWindowParameters.end()) {
return this->mWindowParameters[key];
}
throw NO_KEY_FOUND_EXCEPTION();
}
void GridBox::Set(u_int16_t key, FrameBuffer<float> *val) {
if (this->mWaveFields.find(key) != this->mWaveFields.end()) {
this->mWaveFields[key] = val;
} else if (this->mParameters.find(key) != this->mParameters.end()) {
this->mParameters[key] = val;
} else if (this->mWindowParameters.find(key) != this->mWindowParameters.end()) {
this->mWindowParameters[key] = val;
} else {
throw NO_KEY_FOUND_EXCEPTION();
}
}
void GridBox::Set(u_int16_t key, float *val) {
if (this->mWaveFields.find(key) != this->mWaveFields.end()) {
this->mWaveFields[key]->SetNativePointer(val);
} else if (this->mParameters.find(key) != this->mParameters.end()) {
this->mParameters[key]->SetNativePointer(val);
} else if (this->mWindowParameters.find(key) != this->mWindowParameters.end()) {
this->mWindowParameters[key]->SetNativePointer(val);
} else {
throw NO_KEY_FOUND_EXCEPTION();
}
}
void GridBox::Reset(u_int16_t key) {
this->Set(key, (FrameBuffer<float> *)
nullptr);
}
void GridBox::Swap(u_int16_t _src, u_int16_t _dst) {
if (this->mWaveFields.find(_src) == this->mWaveFields.end() ||
this->mWaveFields.find(_dst) == this->mWaveFields.end()) {
throw NO_KEY_FOUND_EXCEPTION();
}
FrameBuffer<float> *src, *dest;
if (this->mWaveFields.find(_src) != this->mWaveFields.end() &&
this->mWaveFields.find(_dst) != this->mWaveFields.end()) {
src = this->mWaveFields[_src];
dest = this->mWaveFields[_dst];
this->mWaveFields[_dst] = src;
this->mWaveFields[_src] = dest;
}
}
void GridBox::Clone(GridBox *apGridBox) {
this->CloneMetaData(apGridBox);
this->CloneWaveFields(apGridBox);
this->CloneParameters(apGridBox);
}
void GridBox::CloneMetaData(GridBox *apGridBox) {
apGridBox->SetNT(this->GetNT());
apGridBox->SetDT(this->GetDT());
apGridBox->SetInitialAxis(new Axis3D<unsigned int>(*this->GetInitialAxis()));
apGridBox->SetAfterSamplingAxis(new Axis3D<unsigned int>(*this->GetAfterSamplingAxis()));
apGridBox->SetWindowAxis(new Axis3D<unsigned int>(*this->GetWindowAxis()));
}
void GridBox::CloneWaveFields(GridBox *apGridBox) {
for (auto const ¶meter : this->GetParameters()) {
apGridBox->RegisterWaveField(parameter.first,
parameter.second);
}
}
void GridBox::CloneParameters(GridBox *apGridBox) {
for (auto const ¶meter : this->GetParameters()) {
apGridBox->RegisterParameter(parameter.first,
this->Get(parameter.first),
this->Get(WIND | parameter.first));
}
}
void GridBox::Report(REPORT_LEVEL aReportLevel) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
Logger->Info() << "GridBox Report " << '\n';
Logger->Info() << "==============================" << '\n';
uint index = 0;
Logger->Info() << "Actual Grid Size: " << '\n';
Logger->Info() << "- nx\t: " << this->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize() << '\n';
Logger->Info() << "- ny\t: " << this->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize() << '\n';
Logger->Info() << "- nz\t: " << this->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize() << '\n';
Logger->Info() << "- nt\t: " << GetNT() << '\n';
Logger->Info() << "Logical Grid Size: " << '\n';
Logger->Info() << "- nx\t: " << this->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize() << '\n';
Logger->Info() << "- ny\t: " << this->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize() << '\n';
Logger->Info() << "- nz\t: " << this->GetAfterSamplingAxis()->GetZAxis().GetLogicalAxisSize() << '\n';
Logger->Info() << "Actual Window Size: " << '\n';
Logger->Info() << "- wnx\t: " << this->GetWindowAxis()->GetXAxis().GetActualAxisSize() << '\n';
Logger->Info() << "- wny\t: " << this->GetWindowAxis()->GetYAxis().GetActualAxisSize() << '\n';
Logger->Info() << "- wnz\t: " << this->GetWindowAxis()->GetZAxis().GetActualAxisSize() << '\n';
Logger->Info() << "Logical Window Size: " << '\n';
Logger->Info() << "- wnx\t: " << this->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() << '\n';
Logger->Info() << "- wny\t: " << this->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() << '\n';
Logger->Info() << "- wnz\t: " << this->GetWindowAxis()->GetZAxis().GetLogicalAxisSize() << '\n';
Logger->Info() << "Computation Grid Size: " << '\n';
Logger->Info() << "- x elements\t: " << this->GetWindowAxis()->GetXAxis().GetComputationAxisSize() << '\n';
Logger->Info() << "- y elements\t: " << this->GetWindowAxis()->GetYAxis().GetComputationAxisSize() << '\n';
Logger->Info() << "- z elements\t: " << this->GetWindowAxis()->GetZAxis().GetComputationAxisSize() << '\n';
Logger->Info() << "Cell Dimensions: " << '\n';
Logger->Info() << "- dx\t: " << this->GetAfterSamplingAxis()->GetXAxis().GetCellDimension() << '\n';
Logger->Info() << "- dy\t: " << this->GetAfterSamplingAxis()->GetYAxis().GetCellDimension() << '\n';
Logger->Info() << "- dz\t: " << this->GetAfterSamplingAxis()->GetZAxis().GetCellDimension() << '\n';
Logger->Info() << "- dt\t: " << GetDT() << '\n';
Logger->Info() << "Wave Fields: " << '\n';
Logger->Info() << "- Count\t: " << GetWaveFields().size() << '\n';
Logger->Info() << "- Names\t: " << '\n';
index = 0;
for (auto const &wave_field : GetWaveFields()) {
Logger->Info() << "\t" << ++index << ". "
<< Beautify(Stringify(wave_field.first))
<< '\n';
}
Logger->Info() << "Parameters: " << '\n';
Logger->Info() << "- Count\t: " << GetParameters().size() << '\n';
Logger->Info() << "- Names\t: " << '\n';
index = 0;
for (auto const ¶meter : GetParameters()) {
Logger->Info() << "\t" << ++index << ". "
<< Beautify(Stringify(parameter.first)) << '\n';
}
}
bool GridBox::Has(u_int16_t key) {
if (this->mWaveFields.find(key) != this->mWaveFields.end()) {
return true;
} else if (this->mParameters.find(key) != this->mParameters.end()) {
return true;
} else if (this->mWindowParameters.find(key) != this->mWindowParameters.end()) {
return true;
}
return false;
}
void GridBox::Replace(u_int16_t *key, u_int16_t _src, u_int16_t _dest) {
*key = ~_src & *key;
SetBits(key, _dest);
}
/**
* @brief Converts a given key (i.e. u_int16_t) to string.
* @param[in] key
* @return[out] String value
*/
std::string GridBox::Stringify(u_int16_t key) {
std::string str = "";
/// Window
if (Includes(key, WIND)) {
str += "window_";
}
/// Wave Field / Parameter
if (Includes(key, WAVE)) {
str += "wave_";
/// Pressure / Particle
if (Includes(key, GB_PRSS)) {
str += "pressure_";
} else if (Includes(key, GB_PRTC)) {
str += "particle_";
}
} else if (Includes(key, PARM)) {
str += "parameter_";
/// Parameter
if (Includes(key, GB_DEN)) {
str += "density_";
} else if (Includes(key, GB_PHI)) {
str += "phi_";
} else if (Includes(key, GB_THT)) {
str += "theta_";
} else if (Includes(key, GB_EPS)) {
str += "epsilon_";
} else if (Includes(key, GB_DLT)) {
str += "delta_";
} else if (Includes(key, GB_VEL)) {
str += "velocity_";
} else if (Includes(key, GB_VEL_RMS)) {
str += "velocity_rms_";
} else if (Includes(key, GB_VEL_AVG)) {
str += "velocity_avg_";
} else if (Includes(key, GB_TIME_AVG)) {
str += "time_avg_";
}
}
/// Time
if (Includes(key, PREV)) {
str += "prev_";
} else if (Includes(key, NEXT)) {
str += "next_";
} else if (Includes(key, CURR)) {
str += "curr_";
}
/// Direction
if (Includes(key, DIR_X)) {
str += "x_";
} else if (Includes(key, DIR_Y)) {
str += "y_";
} else if (Includes(key, DIR_Z)) {
str += "z_";
}
return str;
}
std::string GridBox::Beautify(std::string str) {
return this->Capitalize(this->ReplaceAll(str, "_", " "));
}
std::string GridBox::Capitalize(std::string str) {
bool cap = true;
for (unsigned int i = 0; i <= str.length(); i++) {
if (isalpha(str[i]) && cap == true) {
str[i] = toupper(str[i]);
cap = false;
} else if (isspace(str[i])) {
cap = true;
}
}
return str;
}
std::string GridBox::ReplaceAll(std::string str,
const std::string &from,
const std::string &to) {
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
return str;
}
| 12,980
|
C++
|
.cpp
| 328
| 33.323171
| 111
| 0.591603
|
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,169
|
RegularAxis.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/data-units/concrete/holders/axis/primitive/RegularAxis.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/api/cpp/BSBase.hpp>
#include <operations/data-units/concrete/holders/axis/concrete/RegularAxis.hpp>
using namespace bs::base::exceptions;
using namespace operations::dataunits::axis;
template
class operations::dataunits::axis::RegularAxis<unsigned short int>;
template
class operations::dataunits::axis::RegularAxis<unsigned int>;
template
class operations::dataunits::axis::RegularAxis<unsigned long int>;
template RegularAxis<unsigned short int>::RegularAxis(unsigned short int);
template RegularAxis<unsigned int>::RegularAxis(unsigned int);
template RegularAxis<unsigned long int>::RegularAxis(unsigned long int);
template RegularAxis<unsigned short int>::RegularAxis(const RegularAxis &aRegularAxis);
template RegularAxis<unsigned int>::RegularAxis(const RegularAxis &aRegularAxis);
template RegularAxis<unsigned long int>::RegularAxis(const RegularAxis &aRegularAxis);
template RegularAxis<unsigned short int> &
RegularAxis<unsigned short int>::operator=(const RegularAxis<unsigned short int> &aRegularAxis);
template RegularAxis<unsigned int> &
RegularAxis<unsigned int>::operator=(const RegularAxis<unsigned int> &aRegularAxis);
template RegularAxis<unsigned long int> &
RegularAxis<unsigned long int>::operator=(const RegularAxis<unsigned long int> &aRegularAxis);
template int
RegularAxis<unsigned short int>::AddBoundary(int aDirection, unsigned short int);
template int
RegularAxis<unsigned int>::AddBoundary(int aDirection, unsigned int);
template int
RegularAxis<unsigned long int>::AddBoundary(int aDirection, unsigned long int);
template int
RegularAxis<unsigned short int>::AddHalfLengthPadding(int aDirection,
unsigned short int aHalfLengthPadding);
template int
RegularAxis<unsigned int>::AddHalfLengthPadding(int aDirection,
unsigned int aHalfLengthPadding);
template int
RegularAxis<unsigned long int>::AddHalfLengthPadding(int aDirection,
unsigned long int aHalfLengthPadding);
template int
RegularAxis<unsigned short int>::AddComputationalPadding(int aDirection,
unsigned short aComputationalPadding);
template int
RegularAxis<unsigned int>::AddComputationalPadding(int aDirection, unsigned int aComputationalPadding);
template int
RegularAxis<unsigned long int>::AddComputationalPadding(int aDirection,
unsigned long int aComputationalPadding);
template unsigned short int
RegularAxis<unsigned short int>::GetLogicalAxisSize();
template unsigned int
RegularAxis<unsigned int>::GetLogicalAxisSize();
template unsigned long int
RegularAxis<unsigned long int>::GetLogicalAxisSize();
template unsigned short int
RegularAxis<unsigned short int>::GetActualAxisSize();
template unsigned int
RegularAxis<unsigned int>::GetActualAxisSize();
template unsigned long int
RegularAxis<unsigned long int>::GetActualAxisSize();
template unsigned short int
RegularAxis<unsigned short int>::GetComputationAxisSize();
template unsigned int
RegularAxis<unsigned int>::GetComputationAxisSize();
template unsigned long int
RegularAxis<unsigned long int>::GetComputationAxisSize();
template<typename T>
RegularAxis<T>::RegularAxis(T mAxisSize) :
mAxisSize(mAxisSize),
mFrontHalfLengthPadding(0),
mRearHalfLengthPadding(0),
mFrontBoundaryLength(0),
mRearBoundaryLength(0),
mFrontComputationalPadding(0),
mRearComputationalPadding(0),
mCellDimension(0),
mReferencePoint(0) {}
template<typename T>
RegularAxis<T>::RegularAxis(const RegularAxis<T> &aRegularAxis):
mAxisSize(aRegularAxis.GetAxisSize()),
mFrontHalfLengthPadding(aRegularAxis.GetFrontHalfLengthPadding()),
mRearHalfLengthPadding(aRegularAxis.GetRearHalfLengthPadding()),
mFrontBoundaryLength(aRegularAxis.GetFrontBoundaryLength()),
mRearBoundaryLength(aRegularAxis.GetRearBoundaryLength()),
mFrontComputationalPadding(aRegularAxis.GetFrontComputationalPadding()),
mRearComputationalPadding(aRegularAxis.GetRearComputationalPadding()),
mReferencePoint(aRegularAxis.GetReferencePoint()),
mCellDimension(aRegularAxis.GetCellDimension()) {}
template<typename T>
RegularAxis<T> &RegularAxis<T>::operator=(const RegularAxis<T> &aRegularAxis) {
if (&aRegularAxis != this) {
this->mAxisSize = aRegularAxis.GetAxisSize();
this->mFrontHalfLengthPadding = aRegularAxis.GetFrontHalfLengthPadding();
this->mRearHalfLengthPadding = aRegularAxis.GetRearHalfLengthPadding();
this->mFrontBoundaryLength = aRegularAxis.mFrontBoundaryLength;
this->mRearBoundaryLength = aRegularAxis.mRearBoundaryLength;
this->mFrontComputationalPadding = aRegularAxis.GetFrontComputationalPadding();
this->mRearComputationalPadding = aRegularAxis.GetRearComputationalPadding();
this->mCellDimension = aRegularAxis.GetCellDimension();
this->mReferencePoint = aRegularAxis.GetReferencePoint();
}
return *this;
}
template<typename T>
int RegularAxis<T>::AddBoundary(int aDirection, T aBoundaryLength) {
if (is_direction_out_of_range(aDirection)) {
throw DIRECTION_EXCEPTION();
}
if (aDirection == OP_DIREC_FRONT) {
this->mFrontBoundaryLength = aBoundaryLength;
} else if (aDirection == OP_DIREC_REAR) {
this->mRearBoundaryLength = aBoundaryLength;
} else if (aDirection == OP_DIREC_BOTH) {
this->mFrontBoundaryLength = aBoundaryLength;
this->mRearBoundaryLength = aBoundaryLength;
}
return 1;
}
template<typename T>
int RegularAxis<T>::AddHalfLengthPadding(int aDirection, T aHalfLengthPadding) {
if (is_direction_out_of_range(aDirection)) {
throw DIRECTION_EXCEPTION();
}
if (aDirection == OP_DIREC_FRONT) {
this->mFrontHalfLengthPadding = aHalfLengthPadding;
} else if (aDirection == OP_DIREC_REAR) {
this->mRearHalfLengthPadding = aHalfLengthPadding;
} else if (aDirection == OP_DIREC_BOTH) {
this->mFrontHalfLengthPadding = aHalfLengthPadding;
this->mRearHalfLengthPadding = aHalfLengthPadding;
}
return 1;
}
template<typename T>
int RegularAxis<T>::AddComputationalPadding(int aDirection, T aComputationalPadding) {
if (is_direction_out_of_range(aDirection)) {
throw DIRECTION_EXCEPTION();
}
if (aDirection == OP_DIREC_FRONT) {
this->mFrontComputationalPadding = aComputationalPadding;
} else if (aDirection == OP_DIREC_REAR) {
this->mRearComputationalPadding = aComputationalPadding;
} else if (aDirection == OP_DIREC_BOTH) {
this->mFrontComputationalPadding = aComputationalPadding;
this->mRearComputationalPadding = aComputationalPadding;
}
return 1;
}
template<typename T>
T RegularAxis<T>::GetLogicalAxisSize() {
return this->mAxisSize +
this->mFrontBoundaryLength + this->mRearBoundaryLength +
this->mFrontHalfLengthPadding + this->mRearHalfLengthPadding;
}
template<typename T>
T RegularAxis<T>::GetActualAxisSize() {
return this->mAxisSize +
this->mFrontBoundaryLength + this->mRearBoundaryLength +
this->mFrontHalfLengthPadding + this->mRearHalfLengthPadding +
this->mFrontComputationalPadding + this->mRearComputationalPadding;
}
template<typename T>
T RegularAxis<T>::GetComputationAxisSize() {
return this->mAxisSize +
this->mFrontBoundaryLength + this->mRearBoundaryLength +
this->mFrontComputationalPadding + this->mRearComputationalPadding;
}
| 8,500
|
C++
|
.cpp
| 182
| 41.005495
| 103
| 0.752691
|
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,170
|
Axis3D.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/data-units/concrete/holders/axis/primitive/Axis3D.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/data-units/concrete/holders/axis/concrete/Axis3D.hpp>
using namespace operations::dataunits::axis;
template
class operations::dataunits::axis::Axis3D<unsigned short int>;
template
class operations::dataunits::axis::Axis3D<unsigned int>;
template
class operations::dataunits::axis::Axis3D<unsigned long int>;
template
Axis3D<unsigned short int>::Axis3D(unsigned short int aXSize, unsigned short int aYSize, unsigned short int aZSize);
template
Axis3D<unsigned int>::Axis3D(unsigned int aXSize, unsigned int aYSize, unsigned int aZSize);
template
Axis3D<unsigned long int>::Axis3D(unsigned long int aXSize, unsigned long int aYSize, unsigned long int aZSize);
template
Axis3D<unsigned short int>::Axis3D(Axis3D &aAxis3D);
template
Axis3D<unsigned int>::Axis3D(Axis3D &aAxis3D);
template
Axis3D<unsigned long int>::Axis3D(Axis3D &aAxis3D);
template
Axis3D<unsigned short int> &Axis3D<unsigned short int>::operator=(Axis3D<unsigned short int> &aAxis3D);
template
Axis3D<unsigned int> &Axis3D<unsigned int>::operator=(Axis3D<unsigned int> &aAxis3D);
template
Axis3D<unsigned long int> &Axis3D<unsigned long int>::operator=(Axis3D<unsigned long int> &aAxis3D);
template
Axis3D<unsigned short int>::~Axis3D();
template
Axis3D<unsigned int>::~Axis3D();
template
Axis3D<unsigned long int>::~Axis3D();
template<typename T>
Axis3D<T>::Axis3D(T aXSize, T aYSize, T aZSize) {
this->mXAxis = RegularAxis<T>(aXSize);
this->mYAxis = RegularAxis<T>(aYSize);
this->mZAxis = RegularAxis<T>(aZSize);
this->mAxisVector.push_back(&this->mXAxis);
this->mAxisVector.push_back(&this->mYAxis);
this->mAxisVector.push_back(&this->mZAxis);
}
template<typename T>
Axis3D<T>::Axis3D(Axis3D &aAxis3D) {
this->mXAxis = RegularAxis<T>(aAxis3D.GetXAxis());
this->mYAxis = RegularAxis<T>(aAxis3D.GetYAxis());
this->mZAxis = RegularAxis<T>(aAxis3D.GetZAxis());
this->mAxisVector.push_back(&this->mXAxis);
this->mAxisVector.push_back(&this->mYAxis);
this->mAxisVector.push_back(&this->mZAxis);
}
template<typename T>
Axis3D<T> &Axis3D<T>::operator=(Axis3D<T> &aAxis3D) {
if (&aAxis3D != this) {
this->mXAxis = RegularAxis<T>(aAxis3D.GetXAxis());
this->mYAxis = RegularAxis<T>(aAxis3D.GetYAxis());
this->mZAxis = RegularAxis<T>(aAxis3D.GetZAxis());
this->mAxisVector.push_back(&this->mXAxis);
this->mAxisVector.push_back(&this->mYAxis);
this->mAxisVector.push_back(&this->mZAxis);
}
return *this;
}
template<typename T>
Axis3D<T>::~Axis3D() {
this->mAxisVector.clear();
}
| 3,348
|
C++
|
.cpp
| 84
| 37.047619
| 116
| 0.74946
|
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,171
|
Sampler.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/utils/sampling/Sampler.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>
#include <operations/utils/sampling/Sampler.hpp>
#include <operations/utils/interpolation/Interpolator.hpp>
using namespace operations::utils::sampling;
using namespace operations::dataunits;
using namespace operations::common;
using namespace operations::utils::interpolation;
void Sampler::Resize(float *input, float *output, Axis3D<unsigned int> *apInputGridBox,
Axis3D<unsigned int> *apOutputGridBox, ComputationParameters *apParameters) {
std::string name;
int pre_x = apInputGridBox->GetXAxis().GetLogicalAxisSize();
int pre_y = apInputGridBox->GetYAxis().GetLogicalAxisSize();
int pre_z = apInputGridBox->GetZAxis().GetLogicalAxisSize();
int post_x = apOutputGridBox->GetXAxis().GetLogicalAxisSize();
int post_y = apOutputGridBox->GetYAxis().GetLogicalAxisSize();
int post_z = apOutputGridBox->GetZAxis().GetLogicalAxisSize();
if (pre_x != post_x || pre_z != post_z || pre_y != post_y) {
Interpolator::InterpolateTrilinear(
input,
output,
pre_x, pre_z, pre_y,
post_x, post_z, post_y,
apParameters->GetBoundaryLength(),
apParameters->GetHalfLength());
} else {
memcpy(output, input, sizeof(float) * pre_x * pre_z * pre_y);
}
}
void Sampler::CalculateAdaptiveCellDimensions(GridBox *apGridBox, ComputationParameters *apParameters,
int aMinimumVelocity, float aMaxFrequency) {
float old_nx = apGridBox->GetInitialAxis()->GetXAxis().GetAxisSize();
float old_ny = apGridBox->GetInitialAxis()->GetYAxis().GetAxisSize();
float old_nz = apGridBox->GetInitialAxis()->GetZAxis().GetAxisSize();
float old_dx = apGridBox->GetInitialAxis()->GetXAxis().GetCellDimension();
float old_dy = apGridBox->GetInitialAxis()->GetYAxis().GetCellDimension();
float old_dz = apGridBox->GetInitialAxis()->GetZAxis().GetCellDimension();
float maximum_frequency = aMaxFrequency;
float minimum_wavelength = aMinimumVelocity / maximum_frequency;
int stencil_order = apParameters->GetHalfLength();
float minimum_wavelength_points = 4;
switch (stencil_order) {
case O_2:
minimum_wavelength_points = 10;
break;
case O_4:
minimum_wavelength_points = 5;
break;
case O_8:
minimum_wavelength_points = 4;
break;
case O_12:
minimum_wavelength_points = 3.5;
break;
case O_16:
minimum_wavelength_points = 3.2;
break;
default:
minimum_wavelength_points = 4;
}
float meters_per_cell = (minimum_wavelength / minimum_wavelength_points) * 0.9; // safety factor
float new_dx = meters_per_cell;
float new_dz = meters_per_cell;
float new_dy = 1;
if (old_ny > 1) {
new_dy = meters_per_cell;
}
int new_domain_x = (old_nx * old_dx) / new_dx;
int new_domain_z = (old_nz * old_dz) / new_dz;
int new_domain_y = (old_ny * old_dy) / new_dy;
apGridBox->GetAfterSamplingAxis()->SetXAxis(new_domain_x);
apGridBox->GetAfterSamplingAxis()->SetZAxis(new_domain_z);
apGridBox->GetAfterSamplingAxis()->GetXAxis().AddBoundary(OP_DIREC_BOTH, apParameters->GetBoundaryLength());
apGridBox->GetAfterSamplingAxis()->GetZAxis().AddBoundary(OP_DIREC_BOTH, apParameters->GetBoundaryLength());
apGridBox->GetAfterSamplingAxis()->GetXAxis().AddHalfLengthPadding(OP_DIREC_BOTH, apParameters->GetHalfLength());
apGridBox->GetAfterSamplingAxis()->GetZAxis().AddHalfLengthPadding(OP_DIREC_BOTH, apParameters->GetHalfLength());
if (old_ny == 1) {
apGridBox->GetAfterSamplingAxis()->SetYAxis(1);
apGridBox->GetAfterSamplingAxis()->GetYAxis().AddBoundary(OP_DIREC_BOTH, 0);
apGridBox->GetAfterSamplingAxis()->GetYAxis().AddHalfLengthPadding(OP_DIREC_BOTH, 0);
} else {
apGridBox->GetAfterSamplingAxis()->SetYAxis(new_domain_y);
apGridBox->GetAfterSamplingAxis()->GetYAxis().AddBoundary(OP_DIREC_BOTH, apParameters->GetBoundaryLength());
apGridBox->GetAfterSamplingAxis()->GetYAxis().AddHalfLengthPadding(OP_DIREC_BOTH,
apParameters->GetHalfLength());
}
apGridBox->GetAfterSamplingAxis()->GetXAxis().SetCellDimension(new_dx);
apGridBox->GetAfterSamplingAxis()->GetYAxis().SetCellDimension(new_dy);
apGridBox->GetAfterSamplingAxis()->GetZAxis().SetCellDimension(new_dz);
unsigned int old_window_nx = apGridBox->GetWindowAxis()->GetXAxis().GetAxisSize();
unsigned int old_window_nz = apGridBox->GetWindowAxis()->GetZAxis().GetAxisSize();
unsigned int old_window_ny = apGridBox->GetWindowAxis()->GetYAxis().GetAxisSize();
int new_window_nx = ((old_window_nx) * old_dx) / new_dx;
int new_window_nz = ((old_window_nz) * old_dz) / new_dz;
int new_window_ny = old_window_ny;
if (old_window_ny > 1) {
new_window_ny = ((old_window_ny) * old_dy) / new_dy;
}
apGridBox->SetWindowAxis(new Axis3D<unsigned int>(new_window_nx, new_window_ny, new_window_nz));
if (old_window_ny > 1) {
apGridBox->GetWindowAxis()->GetYAxis().AddBoundary(OP_DIREC_BOTH, apParameters->GetBoundaryLength());
apGridBox->GetWindowAxis()->GetYAxis().AddHalfLengthPadding(OP_DIREC_BOTH, apParameters->GetHalfLength());
} else {
apGridBox->GetWindowAxis()->GetYAxis().AddBoundary(OP_DIREC_BOTH, 0);
apGridBox->GetWindowAxis()->GetYAxis().AddHalfLengthPadding(OP_DIREC_BOTH, 0);
}
apGridBox->GetWindowAxis()->GetXAxis().AddBoundary(OP_DIREC_BOTH, apParameters->GetBoundaryLength());
apGridBox->GetWindowAxis()->GetZAxis().AddBoundary(OP_DIREC_BOTH, apParameters->GetBoundaryLength());
apGridBox->GetWindowAxis()->GetXAxis().AddHalfLengthPadding(OP_DIREC_BOTH, apParameters->GetHalfLength());
apGridBox->GetWindowAxis()->GetZAxis().AddHalfLengthPadding(OP_DIREC_BOTH, apParameters->GetHalfLength());
int new_right_window = apParameters->GetRightWindow() * old_dx / new_dx;
int new_left_window = apParameters->GetLeftWindow() * old_dx / new_dx;
int new_front_window = apParameters->GetFrontWindow() * old_dy / new_dy;
int new_back_window = apParameters->GetBackWindow() * old_dy / new_dy;
int new_depth_window = apParameters->GetDepthWindow() * old_dz / new_dz;
apParameters->SetRightWindow(new_right_window);
apParameters->SetLeftWindow(new_left_window);
apParameters->SetFrontWindow(new_front_window);
apParameters->SetBackWindow(new_back_window);
apParameters->SetDepthWindow(new_depth_window);
}
| 7,503
|
C++
|
.cpp
| 138
| 47.101449
| 117
| 0.690291
|
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,172
|
noise_filtering.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/utils/filters/noise_filtering.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 <iostream>
#include <cmath>
#include <bs/base/logger/concrete/LoggerSystem.hpp>
#include <operations/utils/filters/noise_filtering.h>
using namespace bs::base::logger;
namespace operations {
namespace utils {
namespace filters {
float laplace_3x3[9] = {
1, 1, 1,
1, -8, 1,
1, 1, 1};
float laplace_9x9[81] = {
0, 1, 1, 2, 2, 2, 1, 1, 0,
1, 2, 4, 5, 5, 5, 4, 2, 1,
1, 4, 5, 3, 0, 3, 5, 4, 1,
2, 5, 3, -12, -24, -12, 3, 5, 2,
2, 5, 0, -24, -40, -24, 0, 5, 2,
2, 5, 3, -12, -24, -12, 3, 5, 2,
1, 4, 5, 3, 0, 3, 5, 4, 1,
1, 2, 4, 5, 5, 5, 4, 2, 1,
0, 1, 1, 2, 2, 2, 1, 1, 0,
};
float sobel_x[9] = {
1, 0, -1,
2, 0, -2,
1, 0, -1};
float sobel_y[9] = {
1, 2, 1,
0, 0, 0,
-1, -2, -1};
float bandpass_3x3[9] = {
-1, 2, -1,
2, -4, 2,
-1, 2, -1,
};
float gauss_5x5[25] = {
1, 4, 7, 4, 1,
4, 16, 26, 16, 4,
7, 25, 41, 25, 7,
4, 16, 26, 16, 4,
1, 4, 7, 4, 1,
};
void convolution(const float *mat, float *dst,
const float *kernel, int kernel_size, uint nz, uint nx) {
int hl = kernel_size / 2;
for (uint row = hl; row < nz - hl; row++) {
for (uint col = hl; col < nx - hl; col++) {
float value = 0;
for (int i = 0; i < kernel_size; i++) {
for (int j = 0; j < kernel_size; j++) {
value += kernel[i * kernel_size + j]
* mat[(row + i - hl)
* nx + (col + j - hl)];
}
}
dst[row * nx + col] = value;
}
}
}
void magnitude(const float *Gx, const float *Gy, float *G, uint size) {
for (uint idx = 0; idx < size; idx++) {
G[idx] = std::sqrt((Gx[idx] * Gx[idx]) + (Gy[idx] * Gy[idx]));
}
}
void row_normalize(float *data, float *output, size_t nx, size_t nz) {
/* normalizes each row so that the new value is ranging from 0 to 1, it skips the boundaries in seek for min and max value */
for (int iz = 0; iz < nz; iz++) { // normalize for each row (i.e. for each depth)
float min = data[iz * nx];
float max = min;
for (int ix = 0; ix < nx; ix++) { // finds the max and min per row
min = fminf(min, data[iz * nx + ix]);
max = fmaxf(max, data[iz * nx + ix]);
}
float range = max - min;
for (int ix = 0; ix <
nx; ix++) { // subtract min value and divide by max-min, so that new value ranges from 0 to 1 (except for boundaries)
if (range != 0) {
output[iz * nx + ix] = (data[iz * nx + ix] - min) / range;
} else {
output[iz * nx + ix] = 0;
}
}
}
}
void z_normalize(float *input, float *output, uint nz, uint nx) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
float sum = 0.0;
float mean;
float standardDeviation = 0.0;
uint item_count = nx * nz;
for (int i = 0; i < item_count; ++i) {
sum += input[i];
}
mean = sum / item_count;
Logger->Info() << "mean = " << mean << '\n';
for (int i = 0; i < item_count; ++i) {
standardDeviation += std::pow(input[i] - mean, 2);
}
standardDeviation = std::sqrt(standardDeviation / item_count);
Logger->Info() << "Standard Deviation\t: " << standardDeviation << '\n';
for (int i = 0; i < item_count; i++) {
output[i] = (input[i] - mean) / standardDeviation;
}
}
void normalize(float *input, uint size, float max, float min) {
for (int i = 0; i < size; i++) {
input[i] = 1023 * ((input[i] - min) / (max - min));
}
}
void denormalize(float *input, uint size, float max, float min) {
for (int i = 0; i < size; i++) {
input[i] = (input[i] / 1023) * (max - min) + min;
}
}
void histogram_equalize(float *input, float *output, uint nz, uint nx) {
uint item_count = nx * nz;
float min = input[0];
float max = min;
float hist[1024] = {0};
float new_gray_level[1024] = {0};
float cumulative_frequency = 0;
for (int i = 0; i < item_count; ++i) {
min = fminf(min, input[i]);
max = fmaxf(max, input[i]);
}
// scale to 0-1023
normalize(input, item_count, max, min);
for (int i = 0; i < item_count; i++) {
hist[(int) input[i]]++;
}
for (int i = 0; i < 1024; i++) {
cumulative_frequency += hist[i];
new_gray_level[i] = std::round(
((cumulative_frequency) * 1023) / float(item_count));
}
for (int i = 0; i < item_count; i++) {
output[i] = new_gray_level[(int) input[i]];
}
denormalize(output, item_count, max, min);
}
// AGC inspired by the work done on the old RTM code by Karim/Essam/Bassiony.
void apply_agc(const float *original, float *agc_trace,
int nx, int ny, int nz, int window) {
// do signal gain using a window to the left of each sample, and to the right of each sample.
// (left,right) here refer to each trace.
window = std::min(window, nz - 1);
// For each trace.
for (unsigned int iy = 0; iy < ny; iy++) {
for (unsigned int ix = 0; ix < nx; ix++) {
uint trace_offset = iy * nx * nz + ix;
// Actual window size.
int window_size = (window + 1);
float sum = 0.0f;
// Initial start.
for (int iz = 0; iz <= window; iz++) {
float value = original[trace_offset + iz * nx];
sum += (value * value);
}
float rms = sum / float(window_size);
if (rms > 0.0f) {
agc_trace[trace_offset] = original[trace_offset] / sqrtf(rms);
} else {
agc_trace[trace_offset] = 0.0f;
}
// Window not full at left side.
for (int iz = 1; iz <= window; iz++) {
if (iz + window < nz) {
uint new_trace_offset = trace_offset + ((iz + window) * nx);
float value = original[new_trace_offset];
window_size++;
sum += (value * value);
rms = sum / float(window_size);
}
if (rms > 0.0f) {
agc_trace[trace_offset + iz * nx] = original[trace_offset + iz * nx] / sqrtf(rms);
} else {
agc_trace[trace_offset + iz * nx] = 0.0f;
}
}
// Window on both sides.
for (int iz = window + 1; iz <= nz - window; iz++) {
float value = original[trace_offset + (iz + window) * nx];
sum += (value * value);
value = original[trace_offset + (iz - window - 1) * nx];
sum -= (value * value);
rms = sum / float(window_size);
if (rms > 0.0f) {
agc_trace[trace_offset + iz * nx] = original[trace_offset + iz * nx] / sqrtf(rms);
} else {
agc_trace[trace_offset + iz * nx] = 0.0f;
}
}
if (nz > window + 1) {
// Window not full at right side.
for (int iz = nz - window + 1; iz < nz; iz++) {
int before_iz = iz - window - 1;
if (before_iz < 0) {
float value = original[trace_offset + (iz - window - 1) * nx];
sum -= (value * value);
window_size--;
rms = sum / float(window_size);
}
if (rms > 0.0f) {
agc_trace[trace_offset + iz * nx] = original[trace_offset + iz * nx] / sqrtf(rms);
} else {
agc_trace[trace_offset + iz * nx] = 0.0f;
}
}
}
}
}
}
void filter_stacked_correlation(float *input_frame, float *output_frame,
uint nx, uint ny, uint nz,
float dx, float dz, float dy) {
//auto *temp = new float[nx * nz * ny];
convolution(input_frame, output_frame, laplace_9x9, 9, nz, nx);
//apply_agc(temp, output_frame, nx, ny, nz, 500);
//delete[] temp;
}
void apply_laplace_filter(float *input_frame, float *output_frame,
unsigned int nx, unsigned int ny, unsigned int nz) {
convolution(input_frame, output_frame, laplace_9x9, 9, nz, nx);
}
} //namespace filters
} //namespace utils
} //namespace operations
| 12,109
|
C++
|
.cpp
| 247
| 28.991903
| 154
| 0.389551
|
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,173
|
Interpolator.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/utils/interpolation/Interpolator.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 <operations/utils/interpolation/Interpolator.hpp>
#include <bs/base/logger/concrete/LoggerSystem.hpp>
#include <bs/base/memory/MemoryManager.hpp>
using namespace bs::base::logger;
using namespace bs::base::memory;
using namespace operations::utils::interpolation;
using namespace operations::dataunits;
float lerp1(float t, float a, float b);
float lerp2(float *t_xy, const float *vertices);
float lerp3(float *t_xyz, const float *vertices);
void interpolate_2D(const float *old_grid,
float *new_grid,
int old_nx, int old_nz,
int new_nx, int new_nz,
int bound_length,
int half_length);
void interpolate_3D(const float *old_grid,
float *new_grid,
int old_nx, int old_nz, int old_ny,
int new_nx, int new_nz, int new_ny,
int bound_length,
int half_length);
float *
Interpolator::Interpolate(TracesHolder *apTraceHolder, uint actual_nt, float total_time, INTERPOLATION aInterpolation) {
if (aInterpolation == SPLINE) {
Interpolator::InterpolateLinear(apTraceHolder, actual_nt, total_time);
}
return nullptr;
}
float *Interpolator::InterpolateLinear(TracesHolder *apTraceHolder, uint actual_nt, float total_time) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
uint sample_nt = apTraceHolder->SampleNT;
if (actual_nt <= sample_nt) {
Logger->Error() << "Interpolation terminated..." << '\n';
Logger->Info() << "Actual size should be at least equal sample size..." << '\n';
return nullptr;
}
auto *interpolated_trace = (float *) mem_allocate(
sizeof(float), actual_nt * apTraceHolder->TraceSizePerTimeStep,
"interpolated-traces");
double step = ((float) sample_nt) / actual_nt;
double t_curr, t_next, t_intr, trace_curr, trace_next, slope, fx;
auto num_elements_per_time_step = apTraceHolder->TraceSizePerTimeStep;
auto traces = apTraceHolder->Traces->GetHostPointer();
for (int i = 0; i < num_elements_per_time_step; ++i) {
int idx = 0;
for (int t = 0; t < sample_nt - 1; ++t) {
t_curr = t;
t_next = t + 1;
trace_curr = traces[t * num_elements_per_time_step + i];
trace_next = traces[(t + 1) * num_elements_per_time_step + i];
slope = (trace_next - trace_curr) / (t_next - t_curr);
while (true) {
t_intr = idx * step;
if (t_intr > t_next || idx == actual_nt - 1) {
break;
}
fx = trace_curr + (slope * (t_intr - t_curr));
interpolated_trace[idx++ * num_elements_per_time_step + i] = fx;
}
}
}
apTraceHolder->Traces->Free();
apTraceHolder->Traces->Allocate(actual_nt * apTraceHolder->TraceSizePerTimeStep);
Device::MemCpy(apTraceHolder->Traces->GetNativePointer(), interpolated_trace,
actual_nt * num_elements_per_time_step * sizeof(float),
dataunits::Device::COPY_HOST_TO_DEVICE);
mem_free(interpolated_trace);
apTraceHolder->SampleNT = actual_nt;
apTraceHolder->SampleDT = total_time / actual_nt;
return apTraceHolder->Traces->GetNativePointer();
}
void Interpolator::InterpolateTrilinear(float *old_grid, float *new_grid,
int old_nx, int old_nz, int old_ny,
int new_nx, int new_nz, int new_ny,
int bound_length,
int half_length) {
if (old_ny > 1) {
interpolate_3D(old_grid, new_grid,
old_nx, old_nz, old_ny,
new_nx, new_nz, new_ny,
bound_length,
half_length);
} else {
interpolate_2D(old_grid, new_grid,
old_nx, old_nz,
new_nx, new_nz,
bound_length,
half_length);
}
}
inline float lerp1(float t, float a, float b) {
if (t < 0) return a;
if (t > 1) return b;
return (a * (1 - t)) + (b * t);
}
float lerp2(float *t_xy, const float *vertices) {
float *v_00_10, *v_01_11, *results_lerp1;
float result;
v_00_10 = (float *) malloc(2 * sizeof(float));
v_01_11 = (float *) malloc(2 * sizeof(float));
results_lerp1 = (float *) malloc(2 * sizeof(float));
for (int i = 0; i < 2; i++) {
v_00_10[i] = vertices[i];
v_01_11[i] = vertices[i + 2];
}
results_lerp1[0] = lerp1(t_xy[0], v_00_10[0], v_00_10[1]);
results_lerp1[1] = lerp1(t_xy[0], v_01_11[0], v_01_11[1]);
result = lerp1(t_xy[1], results_lerp1[0], results_lerp1[1]);
free(v_00_10);
free(v_01_11);
free(results_lerp1);
return result;
}
float lerp3(float *t_xyz, const float *vertices) {
float *v_000_100_010_110, *v_001_101_011_111, *results_lerp2, *t_xy;
float result;
v_000_100_010_110 = (float *) malloc(4 * sizeof(float));
v_001_101_011_111 = (float *) malloc(4 * sizeof(float));
t_xy = (float *) malloc(2 * sizeof(float));
results_lerp2 = (float *) malloc(2 * sizeof(float));
for (int i = 0; i < 4; i++) {
v_000_100_010_110[i] = vertices[i];
v_001_101_011_111[i] = vertices[i + 4];
}
t_xy[0] = t_xyz[0];
t_xy[1] = t_xyz[1];
results_lerp2[0] = lerp2(t_xy, v_000_100_010_110);
results_lerp2[1] = lerp2(t_xy, v_001_101_011_111);
result = lerp1(t_xyz[2], results_lerp2[0], results_lerp2[1]);
free(v_000_100_010_110);
free(v_001_101_011_111);
free(results_lerp2);
free(t_xy);
return result;
}
void interpolate_2D(const float *old_grid,
float *new_grid,
int old_nx, int old_nz,
int new_nx, int new_nz,
int bound_length,
int half_length) {
int old_domain_size_x = old_nx - (2 * bound_length) - (2 * half_length);
int old_domain_size_z = old_nz - (2 * bound_length) - (2 * half_length);
int new_domain_size_x = new_nx - (2 * bound_length) - (2 * half_length);
int new_domain_size_z = new_nz - (2 * bound_length) - (2 * half_length);
auto *vertices = (float *) malloc(4 * sizeof(float));
auto *t_xy = (float *) malloc(2 * sizeof(float));
float old_grid_ix_float;
float old_grid_iz_float;
int old_grid_ix_int;
int old_grid_iz_int;
int offsets[4][2] = {{0, 0},
{1, 0},
{0, 1},
{1, 1}};
int idx;
for (int iz = 0; iz < new_domain_size_z; iz++) {
for (int ix = 0; ix < new_domain_size_x; ix++) {
idx = ((iz + (bound_length + half_length)) * new_nx) + ix + (bound_length + half_length);
old_grid_ix_float = (float) ix * (old_domain_size_x - 1) / (new_domain_size_x);
old_grid_iz_float = (float) iz * (old_domain_size_z - 1) / (new_domain_size_z);
old_grid_ix_int = (int) old_grid_ix_float + (bound_length + half_length);
old_grid_iz_int = (int) old_grid_iz_float + (bound_length + half_length);
t_xy[0] = old_grid_ix_float - old_grid_ix_int;
t_xy[1] = old_grid_iz_float - old_grid_iz_int;
int og_idx;
for (int i = 0; i < 4; i++) {
og_idx = ((old_grid_iz_int + offsets[i][1]) * old_nx) +
(old_grid_ix_int + offsets[i][0]);
vertices[i] = old_grid[og_idx];
}
new_grid[idx] = lerp2(t_xy, vertices);
}
}
free(vertices);
free(t_xy);
}
void interpolate_3D(const float *old_grid,
float *new_grid,
int old_nx, int old_nz, int old_ny,
int new_nx, int new_nz, int new_ny,
int bound_length,
int half_length) {
int old_domain_size_x = old_nx - (2 * bound_length) - (2 * half_length);
int old_domain_size_z = old_nz - (2 * bound_length) - (2 * half_length);
int old_domain_size_y = old_ny - (2 * bound_length) - (2 * half_length);
int new_domain_size_x = new_nx - (2 * bound_length) - (2 * half_length);
int new_domain_size_z = new_nz - (2 * bound_length) - (2 * half_length);
int new_domain_size_y = new_ny - (2 * bound_length) - (2 * half_length);
auto *vertices = (float *) malloc(8 * sizeof(float));
auto *t_xyz = (float *) malloc(3 * sizeof(float));
float old_grid_ix_float;
float old_grid_iy_float;
float old_grid_iz_float;
int old_grid_ix_int;
int old_grid_iz_int;
int old_grid_iy_int;
int offsets[8][3] = {{0, 0, 0},
{1, 0, 0},
{0, 1, 0},
{1, 1, 0},
{0, 0, 1},
{1, 0, 1},
{0, 1, 1},
{1, 1, 1}};
int idx;
for (int iy = 0; iy < new_domain_size_y; iy++) {
for (int iz = 0; iz < new_domain_size_z; iz++) {
for (int ix = 0; ix < new_domain_size_x; ix++) {
idx = ((iy + bound_length + half_length) * new_nz * new_nx)
+ ((iz + (bound_length + half_length)) * new_nx)
+ ix + (bound_length + half_length);
old_grid_ix_float = (float) ix * (old_domain_size_x - 1) / (new_domain_size_x);
old_grid_iz_float = (float) iz * (old_domain_size_z - 1) / (new_domain_size_z);
old_grid_iy_float = (float) iy * (old_domain_size_y - 1) / (new_domain_size_y);
old_grid_ix_int = (int) old_grid_ix_float + (bound_length + half_length);
old_grid_iz_int = (int) old_grid_iz_float + (bound_length + half_length);
old_grid_iy_int = (int) old_grid_iy_float + (bound_length + half_length);
t_xyz[0] = old_grid_ix_float - old_grid_ix_int;
t_xyz[1] = old_grid_iz_float - old_grid_iz_int;
t_xyz[2] = old_grid_iy_float - old_grid_iy_int;
int og_idx;
for (int i = 0; i < 8; i++) {
og_idx = ((old_grid_iy_int + offsets[i][2]) * old_nz * old_nx)
+ ((old_grid_iz_int + offsets[i][1]) * old_nx)
+ (old_grid_ix_int + offsets[i][0]);
vertices[i] = old_grid[og_idx];
}
new_grid[idx] = lerp3(t_xyz, vertices);
}
}
}
free(vertices);
free(t_xyz);
}
| 11,511
|
C++
|
.cpp
| 255
| 34.694118
| 120
| 0.542102
|
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,174
|
Compressor.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/utils/compressor/Compressor.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 <cstdio>
#include <cstdlib>
#include <bs/base/logger/concrete/LoggerSystem.hpp>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/utils/compressor/Compressor.hpp>
#ifdef ZFP_COMPRESSION
#include <zfp.h>
#endif
#define ZFP_MAX_PAR_BLOCKS 512
#define MIN_BLOCK_SIZE 4
using namespace bs::timer;
using namespace bs::base::logger;
using namespace operations::utils::compressors;
void apply_zfp(float *array, int nx, int ny, int nz, int nt,
FILE *file, int decompress, bool zfp_is_relative, double tolerance);
/**
* @brief Compresses multidimensional array using ZFP algorithm.
*/
void compress_zfp(float *array, int nx, int ny, int nz, int nt,
double tolerance, FILE *file, bool zfp_is_relative);
/**
* @brief Decompresses multidimensional array using ZFP algorithm.
*/
void decompress_zfp(float *array, int nx, int ny, int nz, int nt,
double tolerance, FILE *file, bool zfp_is_relative);
/**
* @brief Compresses multidimensional array.
*/
void compress_normal(FILE *file, const float *data, int nx, int ny, int nz, int nt);
/**
* @brief Decompresses multidimensional array.
*/
void decompress_normal(FILE *file, float *data, int nx, int ny, int nz, int nt);
void Compressor::Compress(float *array, int nx, int ny, int nz, int nt, double tolerance,
unsigned int codecType, const char *filename,
bool zfp_is_relative) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
FILE *compressed_file = fopen(filename, "wb");
if (compressed_file == nullptr) {
Logger->Error() << "Opening compressed file" << filename << "to write to failed..." << '\n';
exit(EXIT_FAILURE);
}
#ifdef ZFP_COMPRESSION
switch (codecType) {
case 1:
apply_zfp(array, nx, ny, nz, nt, compressed_file, 0, zfp_is_relative, tolerance);
break;
case 2:
compress_zfp(array, nx, ny, nz, nt, tolerance, compressed_file, zfp_is_relative);
break;
default:
Logger->Error() << "*** Invalid codec Type, Terminating" << '\n';
exit(EXIT_FAILURE);
}
#else
compress_normal(compressed_file, array, nx, ny, nz, nt);
#endif
fclose(compressed_file);
}
void Compressor::Decompress(float *array, int nx, int ny, int nz, int nt, double tolerance,
unsigned int codecType, const char *filename,
bool zfp_is_relative) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
FILE *compressed_file = fopen(filename, "rb");
if (compressed_file == nullptr) {
Logger->Error() << "Opening compressed file " << filename << " to read from failed..." << '\n';
exit(EXIT_FAILURE);
}
#ifdef ZFP_COMPRESSION
switch (codecType) {
case 1:
apply_zfp(array, nx, ny, nz, nt, compressed_file, 1, zfp_is_relative, tolerance);
break;
case 2:
decompress_zfp(array, nx, ny, nz, nt, tolerance, compressed_file, zfp_is_relative);
break;
default:
Logger->Error() << "***Invalid codec Type, Terminating" << '\n';
exit(EXIT_FAILURE);
}
#else
decompress_normal(compressed_file, array, nx, ny, nz, nt);
#endif
fclose(compressed_file);
}
void apply_zfp(float *array, int nx, int ny, int nz, int nt,
FILE *file, int decompress, bool zfp_is_relative, double tolerance) {
#ifdef ZFP_COMPRESSION
auto logger = LoggerSystem::GetInstance();
/// Compressed stream
zfp_stream *zfp;
/// Storage for compressed stream
void *buffer;
/// Byte size of compressed buffer
size_t buffer_size;
/// Bit stream to write to or read from
bitstream *stream;
/// Array meta data
zfp_field *size_field;
/// Array scalar type
zfp_type type;
type = zfp_type_float;
// Allocate meta data for a compressed stream
zfp = zfp_stream_open(nullptr);
// Set compression mode and parameters via one of three functions
/*
* zfp_stream_set_rate(zfp, rate, type, 3, 0);
* zfp_stream_set_precision(zfp, precision, type);
*/
if (zfp_is_relative) {
// Concerned with relative error (precision)
zfp_stream_set_precision(zfp, tolerance);
} else {
// Concerned with absolute error (accuracy)
/*
* /// Old ZFP version
* zfp_stream_set_accuracy(zfp[block], tolerance, type);
*/
zfp_stream_set_accuracy(zfp, tolerance);
}
// Chooses between 1D, 2D or 3D representation
if ((nx > 1) && (ny > 1) && (nz > 1)) {
// Handle 3D
size_field = zfp_field_3d(array, type, nx, ny, nz);
} else if ((nx > 1) && (nz > 1)) {
// Handle 2D
size_field = zfp_field_2d(array, type, nx, nz);
} else {
// Handle 1D
size_field = zfp_field_1d(array, type, nz);
}
// Allocate buffer for compressed data
buffer_size = zfp_stream_maximum_size(zfp, size_field);
zfp_field_free(size_field);
buffer = malloc(buffer_size);
// Associate bit stream with allocated buffer
stream = stream_open(buffer, buffer_size);
zfp_stream_set_bit_stream(zfp, stream);
int pressure_size = nx * ny * nz;
float *off_arr;
for (int i = 0; i < nt; i++) {
off_arr = &array[i * pressure_size];
// Array meta data
zfp_field *field;
// Byte size of compressed stream
size_t zfp_size;
// Allocate meta-data for the 3D array a[nz][ny][nx]
ElasticTimer compressor_timer("Compressor::ZFP::SetupProperties");
compressor_timer.Start();
// To choose between 1d,2d or 3d representation
if ((nx > 1) && (ny > 1) && (nz > 1)) {// handle 3d
field = zfp_field_3d(off_arr, type, nx, ny, nz);
} else if ((nx > 1) && (nz > 1)) {// handle 2d
field = zfp_field_2d(off_arr, type, nx, nz);
} else {// handle 1d
field = zfp_field_1d(off_arr, type, nz);
}
zfp_stream_rewind(zfp);
compressor_timer.Stop();
/* Compress or decompress entire array. */
if (decompress) {
/* Read compressed stream and decompress array. */
{
ScopeTimer t("Compressor::ZFP::IO::Decompression");
fread(&zfp_size, 1, sizeof(zfp_size), file);
fread(buffer, 1, zfp_size, file);
}
{
ScopeTimer t("Compressor::ZFP::Decompress");
if (!zfp_decompress(zfp, field)) {
logger->Error() << "decompression failed" << '\n';
exit(EXIT_FAILURE);
}
}
} else {
/* Compress array and output compressed stream. */
ElasticTimer compress_timer("Compressor::ZFP::Compress");
compressor_timer.Start();
zfp_size = zfp_compress(zfp, field);
compressor_timer.Stop();
if (!zfp_size) {
logger->Error() << "compression failed" << '\n';
exit(EXIT_FAILURE);
} else {
{
ScopeTimer t("Compressor::ZFP::IO::Compression");
fwrite(&zfp_size, 1, sizeof(zfp_size), file);
fwrite(buffer, 1, zfp_size, file);
}
}
}
zfp_field_free(field);
}
/*
* Clean up
*/
zfp_stream_close(zfp);
stream_close(stream);
free(buffer);
#endif
}
void compress_zfp(float *array, int nx, int ny, int nz, int nt,
double tolerance, FILE *file,
bool zfp_is_relative) {
#ifdef ZFP_COMPRESSION
LoggerSystem *Logger = LoggerSystem::GetInstance();
unsigned int total_blocks = 0;
// Calculating the number of blocks to be written, a block
// will consist of a number of rows in nx dimension
total_blocks = (nz + MIN_BLOCK_SIZE - 1) / MIN_BLOCK_SIZE;
int pressure_size = nx * ny * nz;
/// Array scalar type
zfp_type type;
/// Array meta data
auto **field = (zfp_field **) malloc(sizeof(zfp_field *) * total_blocks);
/// Compressed stream
auto **zfp = (zfp_stream **) malloc(sizeof(zfp_stream *) * total_blocks);
/// Storage for compressed stream
void **buffer = (void **) malloc(sizeof(void *) * total_blocks);
/// Byte size of compressed buffer
auto *buffer_size = (size_t *) malloc(sizeof(size_t) * total_blocks);
/// Bit stream to write to or read from
auto **stream = (bitstream **) malloc(sizeof(bitstream *) * total_blocks);
/// Byte size of compressed stream
auto *zfp_size = (size_t *) malloc(sizeof(size_t) * total_blocks);
int *block_dim = (int *) malloc(sizeof(int) * total_blocks);
type = zfp_type_float;
#pragma omp parallel for schedule(static)
for (unsigned int block = 0; block < total_blocks; block++) {
block_dim[block] = ((block < (total_blocks - 1)) ? MIN_BLOCK_SIZE : nz % MIN_BLOCK_SIZE);
if (block_dim[block] == 0) {
block_dim[block] = MIN_BLOCK_SIZE;
}
// Determine the size of a block before compression
if ((nx > 1) && (ny > 1) && (nz > 1)) { // handle 3d
field[block] = zfp_field_3d(&array[block * MIN_BLOCK_SIZE * ny * nx], type, nx, ny, block_dim[block]);
} else { // handle 2d
field[block] = zfp_field_2d(&array[block * MIN_BLOCK_SIZE * nx], type, nx, block_dim[block]);
}
// Allocate meta data for a compressed stream.
zfp[block] = zfp_stream_open(nullptr);
if (zfp_is_relative) { // we are concerned with relative error (precision)
zfp_stream_set_precision(zfp[block], tolerance);
} else {
// We are concerned with absolute error (accuracy)
// zfp_stream_set_accuracy(zfp[block], tolerance, type);
// Old ZFP version
zfp_stream_set_accuracy(zfp[block], tolerance); // New ZFP version
}
// Allocate buffer for compressed data
buffer_size[block] = zfp_stream_maximum_size(zfp[block], field[block]);
buffer[block] = malloc(buffer_size[block]);
// Associate bit stream with allocated buffer
stream[block] = stream_open(buffer[block], buffer_size[block]);
zfp_stream_set_bit_stream(zfp[block], stream[block]);
}
/*
* Clean up
*/
for (int block = 0; block < total_blocks; block++) {
zfp_field_free(field[block]);
}
float *off_arr;
for (int i = 0; i < nt; i++) {
off_arr = &array[i * pressure_size];
ElasticTimer compress_timer("Compressor::ZFP::Compress");
compress_timer.Start();
/*
* Loop on blocks, each is compressed and then written
*/
#pragma omp parallel for schedule(static)
for (unsigned int block = 0; block < total_blocks; block++) {
// Determine the size of a block before compression
if ((nx > 1) && (ny > 1) && (nz > 1)) { // handle 3d
field[block] = zfp_field_3d(&off_arr[block * MIN_BLOCK_SIZE * ny * nx], type, nx, ny, block_dim[block]);
} else { // handle 2d
field[block] = zfp_field_2d(&off_arr[block * MIN_BLOCK_SIZE * nx], type, nx, block_dim[block]);
}
zfp_stream_rewind(zfp[block]);
// Compress entire arrayCompressor::ZFP::Compress
zfp_size[block] = zfp_compress(zfp[block], field[block]);
if (!zfp_size[block]) {
Logger->Error() << "compression failed" << '\n';
exit(EXIT_FAILURE);
}
}
compress_timer.Stop();
ElasticTimer io_compressor_timer("Compressor::ZFP::IO::Compression");
io_compressor_timer.Start();
/*
* Write Block Sizes serially
*/
for (int block = 0; block < total_blocks; block++) {
fwrite(&zfp_size[block], sizeof(zfp_size[block]), 1, file); // write the size of the block after compression
fwrite(buffer[block], 1, zfp_size[block], file); // write the actual compressed data
}
io_compressor_timer.Stop();
/*
* Clean up
*/
for (int block = 0; block < total_blocks; block++) {
zfp_field_free(field[block]);
}
}
for (int block = 0; block < total_blocks; block++) {
zfp_stream_close(zfp[block]);
stream_close(stream[block]);
free(buffer[block]);
}
free(field);
free(zfp);
free(buffer);
free(buffer_size);
free(stream);
free(zfp_size);
free(block_dim);
#endif
}
void decompress_zfp(float *array, int nx, int ny, int nz, int nt,
double tolerance, FILE *file,
bool zfp_is_relative) {
#ifdef ZFP_COMPRESSION
LoggerSystem *Logger = LoggerSystem::GetInstance();
unsigned int totalBlocks = 0;
// Calculating the number of blocks to be written, a block
// will consist of a number of rows in nx dimension
totalBlocks = (nz + MIN_BLOCK_SIZE - 1) / MIN_BLOCK_SIZE;
int pressure_size = nx * ny * nz;
/// Array scalar type
zfp_type type;
/// Array meta data
auto **field = (zfp_field **) malloc(sizeof(zfp_field *) * totalBlocks);
/// Compressed stream
auto **zfp = (zfp_stream **) malloc(sizeof(zfp_stream *) * totalBlocks);
/// Storage for compressed stream
void **buffer = (void **) malloc(sizeof(void *) * totalBlocks);
/// Byte size of compressed buffer
auto *buffer_size = (size_t *) malloc(sizeof(size_t) * totalBlocks);
/// Bit stream to write to or read from
auto **stream = (bitstream **) malloc(sizeof(bitstream *) * totalBlocks);
/// Byte size of compressed stream
auto *zfp_size = (size_t *) malloc(sizeof(size_t) * totalBlocks);
int *block_dim = (int *) malloc(sizeof(int) * totalBlocks);
type = zfp_type_float;
#pragma omp parallel for schedule(static)
for (unsigned int block = 0; block < totalBlocks; block++) {
block_dim[block] = ((block < (totalBlocks - 1)) ? MIN_BLOCK_SIZE : nz % MIN_BLOCK_SIZE);
if (block_dim[block] == 0) {
block_dim[block] = MIN_BLOCK_SIZE;
}
// Determine the size of a block before compression
if ((nx > 1) && (ny > 1) && (nz > 1)) {
// Handle 3D
field[block] = zfp_field_3d(&array[block * MIN_BLOCK_SIZE * ny * nx], type, nx, ny, block_dim[block]);
} else {
// Handle 2D
field[block] = zfp_field_2d(&array[block * MIN_BLOCK_SIZE * nx], type, nx, block_dim[block]);
}
// Allocate meta data for a compressed stream
zfp[block] = zfp_stream_open(nullptr);
if (zfp_is_relative) {
// We are concerned with relative error (precision)
zfp_stream_set_precision(zfp[block], tolerance);
} else {
// We are concerned with absolute error (accuracy)
// zfp_stream_set_accuracy(zfp[block], tolerance, type); // Old ZFP
// version
zfp_stream_set_accuracy(zfp[block], tolerance); // New ZFP version
}
// Allocate buffer for compressed data
buffer_size[block] = zfp_stream_maximum_size(zfp[block], field[block]);
buffer[block] = malloc(buffer_size[block]);
// Associate bit stream with allocated buffer
stream[block] = stream_open(buffer[block], buffer_size[block]);
zfp_stream_set_bit_stream(zfp[block], stream[block]);
}
/*
* Clean up
*/
for (int block = 0; block < totalBlocks; block++) {
zfp_field_free(field[block]);
}
float *off_arr;
for (int i = 0; i < nt; i++) {
off_arr = &array[i * pressure_size];
ElasticTimer io_decompress_timer("Compressor::ZFP::IO::Decompression");
io_decompress_timer.Start();
/*
* Read Block Sizes in serial
*/
for (int block = 0; block < totalBlocks; block++) {
// Write the size of the block after compression
fread(&zfp_size[block], sizeof(zfp_size[block]), 1, file);
// Write the actual compressed data
fread(buffer[block], 1, zfp_size[block], file);
}
io_decompress_timer.Stop();
ElasticTimer decompress_timer("Compressor::ZFP::Decompress");
decompress_timer.Start();
/*
* Loop on blocks, each is compressed and then written
*/
#pragma omp parallel for schedule(static)
for (unsigned int block = 0; block < totalBlocks; block++) {
// Determine the size of a block before compression
if ((nx > 1) && (ny > 1) && (nz > 1)) {
// Handle 3D
field[block] = zfp_field_3d(&off_arr[block * MIN_BLOCK_SIZE * ny * nx], type, nx, ny, block_dim[block]);
} else {
// Handle 2D
field[block] = zfp_field_2d(&off_arr[block * MIN_BLOCK_SIZE * nx], type, nx, block_dim[block]);
}
zfp_stream_rewind(zfp[block]);
// Decompress entire array
if (!zfp_decompress(zfp[block], field[block])) {
Logger->Error() << "Decompression failed" << '\n';
exit(EXIT_FAILURE);
}
}
decompress_timer.Stop();
/*
* Clean up
*/
for (int block = 0; block < totalBlocks; block++) {
zfp_field_free(field[block]);
}
}
for (int block = 0; block < totalBlocks; block++) {
zfp_stream_close(zfp[block]);
stream_close(stream[block]);
free(buffer[block]);
}
free(field);
free(zfp);
free(buffer);
free(buffer_size);
free(stream);
free(zfp_size);
free(block_dim);
#endif
}
void compress_normal(FILE *file, const float *data, int nx, int ny, int nz, int nt) {
int size = nx * ny * nz;
const float *offset_arr;
{
ScopeTimer t("Compressor::Normal::Compress");
for (int i = 0; i < nt; i++) {
offset_arr = &data[i * size];
fwrite(offset_arr, 1, size * sizeof(float), file);
}
}
}
void decompress_normal(FILE *file, float *data, int nx, int ny, int nz, int nt) {
int size = nx * ny * nz;
float *offset_arr;
{
ScopeTimer t("Compressor::Normal::Decompress");
for (int i = 0; i < nt; i++) {
offset_arr = &data[i * size];
fread(offset_arr, 1, size * sizeof(float), file);
}
}
}
| 19,378
|
C++
|
.cpp
| 481
| 32.201663
| 120
| 0.58851
|
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,175
|
read_utils.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/utils/io/read_utils.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 <unordered_set>
#include <algorithm>
#include <bs/base/memory/MemoryManager.hpp>
#include <operations/utils/io/read_utils.h>
using namespace std;
using namespace bs::base::memory;
using namespace bs::io::dataunits;
using namespace operations::utils::io;
using namespace operations::dataunits;
using namespace operations::common;
Gather *operations::utils::io::CombineGather(std::vector<Gather *> &aGatherVector) {
int gather_count = aGatherVector.size();
for (int gather_index = 1; gather_index < gather_count; gather_index++) {
int trace_count = aGatherVector[gather_index]->GetNumberTraces();
for (int trace_index = 0; trace_index < trace_count; trace_index++) {
aGatherVector[0]->AddTrace(aGatherVector[gather_index]->GetTrace(trace_index));
}
delete aGatherVector[gather_index];
}
auto gather = aGatherVector[0];
aGatherVector.clear();
aGatherVector.push_back(gather);
return gather;
}
void operations::utils::io::RemoveDuplicatesFromGather(Gather *apGather) {
int size = apGather->GetNumberTraces();
unordered_map<float, unordered_set<float>> unique_positions;
for (int i = 0; i < size; i++) {
auto cur_sx = apGather->GetTrace(i)->GetScaledCoordinateHeader(TraceHeaderKey::SX);
auto cur_sy = apGather->GetTrace(i)->GetScaledCoordinateHeader(TraceHeaderKey::SY);
if (unique_positions.find(cur_sx) == unique_positions.end()) {
unique_positions[cur_sx] = {};
unique_positions[cur_sx].emplace(cur_sy);
} else {
if (unique_positions[cur_sx].find(cur_sy) == unique_positions[cur_sx].end()) {
unique_positions[cur_sx].emplace(cur_sy);
} else {
apGather->RemoveTrace(i);
i--;
size--;
}
}
}
}
bool operations::utils::io::IsLineGather(Gather *apGather) {
int count = apGather->GetNumberTraces();
bool return_value = true;
float tolerance = 0.1; /// 10% tolerance
float initial_y_diff = (apGather->GetTrace(0)->GetScaledCoordinateHeader(TraceHeaderKey::SY) -
apGather->GetTrace(1)->GetScaledCoordinateHeader(TraceHeaderKey::SY));
float initial_x_diff = (apGather->GetTrace(0)->GetScaledCoordinateHeader(TraceHeaderKey::SX) -
apGather->GetTrace(1)->GetScaledCoordinateHeader(TraceHeaderKey::SX));
float initial_slope = 0;
if (initial_x_diff != 0 && initial_y_diff != 0) {
initial_slope = initial_y_diff / initial_x_diff;
}
for (int i = 2; i < count; i++) {
float y_diff = (apGather->GetTrace(0)->GetScaledCoordinateHeader(TraceHeaderKey::SY) -
apGather->GetTrace(i)->GetScaledCoordinateHeader(TraceHeaderKey::SY));
float x_diff = (apGather->GetTrace(0)->GetScaledCoordinateHeader(TraceHeaderKey::SX) -
apGather->GetTrace(i)->GetScaledCoordinateHeader(TraceHeaderKey::SX));
if (initial_x_diff != 0 && initial_y_diff != 0) {
if (x_diff == 0) {
return_value = false;
break;
}
float slope = y_diff / x_diff;
if (!(fabsf(slope - initial_slope) <=
tolerance * (fabs(slope) < fabs(initial_slope) ? fabs(initial_slope) : fabs(slope)))) {
return_value = false;
break;
}
} else {
if ((initial_x_diff == 0 && x_diff != 0) || (initial_y_diff == 0 && y_diff != 0)) {
return_value = false;
break;
}
}
}
return return_value;
}
void operations::utils::io::ParseGatherToTraces(
bs::io::dataunits::Gather *apGather, Point3D *apSource, TracesHolder *apTraces,
uint **x_position, uint **y_position,
GridBox *apGridBox, ComputationParameters *apParameters,
float *total_time) {
uint ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
std::unordered_set<uint> x_dim;
std::unordered_set<uint> y_dim;
// No need to sort as we deal with each trace with its position independently.
// Get source point.
float source_org_x;
float source_org_y;
float source_org_z;
uint offset = apParameters->GetHalfLength() + apParameters->GetBoundaryLength();
uint window_left_size = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize() - 2 * offset -
apParameters->GetRightWindow();
uint window_back_size = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize() - 2 * offset -
apParameters->GetFrontWindow();
source_org_x = apGather->GetTrace(0)->GetScaledCoordinateHeader(TraceHeaderKey::SX)
- apGridBox->GetAfterSamplingAxis()->GetXAxis().GetReferencePoint();
source_org_z = 0;
source_org_y = apGather->GetTrace(0)->GetScaledCoordinateHeader(TraceHeaderKey::SY)
- apGridBox->GetAfterSamplingAxis()->GetYAxis().GetReferencePoint();
if (ny == 1) {
source_org_x = sqrtf(source_org_x * source_org_x + source_org_y * source_org_y);
source_org_y = 0;
}
apSource->x = round(source_org_x / apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension());
apSource->z = round(source_org_z / apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension());
apSource->y = round(source_org_y / apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension());
// If window model, need to setup the starting point of the window and adjust source point.
// Handle 3 cases : no room for left window, no room for right window, room for both.
// Those 3 cases can apply to y-direction as well if 3D.
if (apParameters->IsUsingWindow()) {
apGridBox->SetWindowStart(X_AXIS, 0);
// No room for left window.
if (apSource->x < apParameters->GetLeftWindow() ||
(apParameters->GetLeftWindow() == 0 && apParameters->GetRightWindow() == 0)) {
apGridBox->SetWindowStart(X_AXIS, 0);
// No room for right window.
} else if (apSource->x >= window_left_size) {
uint window_start = window_left_size - 1 - apParameters->GetLeftWindow();
apGridBox->SetWindowStart(X_AXIS, window_start);
apSource->x = apSource->x - window_start;
} else {
apGridBox->SetWindowStart(X_AXIS, ((int) apSource->x) - apParameters->GetLeftWindow());
apSource->x = apParameters->GetLeftWindow();
}
apGridBox->SetWindowStart(Y_AXIS, 0);
if (ny != 1) {
if (apSource->y < apParameters->GetBackWindow() ||
(apParameters->GetFrontWindow() == 0 && apParameters->GetBackWindow() == 0)) {
apGridBox->SetWindowStart(Y_AXIS, 0);
} else if (apSource->y >= window_back_size) {
uint window_start = window_back_size - 1 - apParameters->GetBackWindow();
apGridBox->SetWindowStart(Y_AXIS, window_start);
apSource->y = apSource->y - window_start;
} else {
apGridBox->SetWindowStart(Y_AXIS, ((int) apSource->y) - apParameters->GetBackWindow());
apSource->y = apParameters->GetBackWindow();
}
}
}
apSource->x += offset;
apSource->z += offset;
if (ny > 1) {
apSource->y += offset;
}
// Begin traces parsing.
// Remove traces outside the window.
uint intern_x = apGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize() - 2 * offset;
uint intern_y = apGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize() - 2 * offset;
for (int i = ((int) apGather->GetNumberTraces()) - 1; i >= 0; i--) {
bool erased = false;
float gx_loc = apGather->GetTrace(i)->GetScaledCoordinateHeader(TraceHeaderKey::GX)
- apGridBox->GetAfterSamplingAxis()->GetXAxis().GetReferencePoint();
float gy_loc = apGather->GetTrace(i)->GetScaledCoordinateHeader(TraceHeaderKey::GY)
- apGridBox->GetAfterSamplingAxis()->GetYAxis().GetReferencePoint();
if (ny == 1) {
gx_loc = sqrtf(gx_loc * gx_loc + gy_loc * gy_loc);
gy_loc = 0;
}
uint gx = round(gx_loc / apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension());
uint gy = round(gy_loc / apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension());
if (gx < apGridBox->GetWindowStart(X_AXIS) || gx >= apGridBox->GetWindowStart(X_AXIS) + intern_x) {
apGather->RemoveTrace(i);
erased = true;
} else if (apGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize() != 1) {
if (gy < apGridBox->GetWindowStart(Y_AXIS) || gy >= apGridBox->GetWindowStart(Y_AXIS) + intern_y) {
apGather->RemoveTrace(i);
erased = true;
}
}
if (!erased) {
x_dim.insert(gx_loc);
y_dim.insert(gy_loc);
}
}
/* Set meta data. */
apTraces->SampleDT = apGather->GetSamplingRate() / (float) 1e6;
int sample_nt = apGather->GetTrace(0)->GetNumberOfSamples();
int num_elements_per_time_step = apGather->GetNumberTraces();
apTraces->TraceSizePerTimeStep = apGather->GetNumberTraces();
apTraces->ReceiversCountX = x_dim.size();
apTraces->ReceiversCountY = y_dim.size();
apTraces->SampleNT = sample_nt;
/// We dont have total time , but we have the nt from the
/// segy file , so we can modify the nt according to the
/// ratio between the recorded dt and the suitable dt
apGridBox->SetNT(int(sample_nt * apTraces->SampleDT / apGridBox->GetDT()));
*total_time = sample_nt * apTraces->SampleDT;
*x_position = (uint *) mem_allocate(
sizeof(uint), num_elements_per_time_step, "traces x-position");
*y_position = (uint *) mem_allocate(
sizeof(uint), num_elements_per_time_step, "traces y-position");
auto traces = (float *) mem_allocate(sizeof(float), sample_nt * num_elements_per_time_step, "traces_tmp");
for (int trace_index = 0; trace_index < num_elements_per_time_step; trace_index++) {
for (int t = 0; t < sample_nt; t++) {
traces[t * num_elements_per_time_step + trace_index]
= apGather->GetTrace(trace_index)->GetTraceData()[t];
}
float gx_loc = apGather->GetTrace(trace_index)->GetScaledCoordinateHeader(TraceHeaderKey::GX)
- apGridBox->GetAfterSamplingAxis()->GetXAxis().GetReferencePoint();
float gy_loc = apGather->GetTrace(trace_index)->GetScaledCoordinateHeader(TraceHeaderKey::GY)
- apGridBox->GetAfterSamplingAxis()->GetYAxis().GetReferencePoint();
if (ny == 1) {
gx_loc = sqrtf(gx_loc * gx_loc + gy_loc * gy_loc);
gy_loc = 0;
}
uint gx = round(gx_loc / apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension());
uint gy = round(gy_loc / apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension());
gx -= apGridBox->GetWindowStart(X_AXIS);
gy -= apGridBox->GetWindowStart(Y_AXIS);
(*x_position)[trace_index] = gx + offset;
if (apGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize() > 1) {
(*y_position)[trace_index] = gy + offset;
} else {
(*y_position)[trace_index] = gy;
}
}
/* Setup traces data to the arrays. */
apTraces->Traces = new FrameBuffer<float>;
apTraces->Traces->Allocate(sample_nt * num_elements_per_time_step, "traces");
Device::MemCpy(apTraces->Traces->GetNativePointer(), traces,
sample_nt * num_elements_per_time_step * sizeof(float),
Device::COPY_HOST_TO_DEVICE);
mem_free(traces);
}
| 12,696
|
C++
|
.cpp
| 248
| 42.298387
| 111
| 0.629174
|
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,176
|
write_utils.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/utils/io/write_utils.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>
#include <operations/utils/io/write_utils.h>
using namespace std;
using namespace bs::io::dataunits;
using namespace operations::utils::io;
vector<Gather *>
operations::utils::io::TransformToGather(const float *apData, uint aNX, uint aNY, uint aNS,
float aDX, float aDY, float aDS, float aSX, float aSY,
int aOffsetX, int aOffsetY, uint aShots, float aSpaceScale,
float aSampleScale) {
std::vector<Gather *> results;
uint full_cube_size = aNX * aNY * aNS;
for (int shot = 0; shot < aShots; shot++) {
auto gather = new Gather();
for (int iy = 0; iy < aNY; iy++) {
for (int ix = 0; ix < aNX; ix++) {
auto trace = new Trace(aNS);
int16_t factor = -aSpaceScale;
trace->SetTraceHeaderKeyValue(TraceHeaderKey::SCALCO, factor);
float loc_x = aSX + (ix + aOffsetX) * aDX;
float loc_y = aSY + (iy + aOffsetY) * aDY;
trace->SetScaledCoordinateHeader(TraceHeaderKey::SX, loc_x);
trace->SetScaledCoordinateHeader(TraceHeaderKey::SY, loc_y);
trace->SetScaledCoordinateHeader(TraceHeaderKey::GX, loc_x);
trace->SetScaledCoordinateHeader(TraceHeaderKey::GY, loc_y);
uint16_t sampling = aDS * aSampleScale;
trace->SetTraceHeaderKeyValue(TraceHeaderKey::DT, sampling);
trace->SetTraceHeaderKeyValue(TraceHeaderKey::FLDR, shot + 1);
trace->SetTraceData(new float[aNS]);
for (int is = 0; is < aNS; is++) {
trace->GetTraceData()[is] = apData[shot * full_cube_size + iy * aNX * aNS + is * aNX + ix];
}
gather->AddTrace(trace);
}
}
gather->SetSamplingRate(aDS * aSampleScale);
string val = to_string(shot + 1);
gather->SetUniqueKeyValue(TraceHeaderKey::FLDR, val);
results.push_back(gather);
}
return results;
}
vector<Gather *>
operations::utils::io::TransformToGather(const float *apData, uint aNX, uint aNY, uint aNS,
float aDS,
Gather *apMetaDataGather, uint aShots,
float aSampleScale) {
std::vector<Gather *> results;
uint full_cube_size = aNX * aNY * aNS;
for (int shot = 0; shot < aShots; shot++) {
auto gather = new Gather();
for (int iy = 0; iy < aNY; iy++) {
for (int ix = 0; ix < aNX; ix++) {
auto trace = new Trace(aNS);
auto header_map = apMetaDataGather->GetTrace(iy * aNX + ix)->GetTraceHeaders();
auto new_headers_map = ((std::unordered_map<TraceHeaderKey, std::string> *) trace->GetTraceHeaders());
new_headers_map->insert(header_map->begin(), header_map->end());
uint16_t sampling = aDS * aSampleScale;
trace->SetTraceHeaderKeyValue(TraceHeaderKey::DT, sampling);
trace->SetTraceHeaderKeyValue(TraceHeaderKey::FLDR, shot + 1);
trace->SetTraceData(new float[aNS]);
for (int is = 0; is < aNS; is++) {
trace->GetTraceData()[is] = apData[shot * full_cube_size + iy * aNX * aNS + is * aNX + ix];
}
gather->AddTrace(trace);
}
}
gather->SetSamplingRate(aDS * aSampleScale);
string val = to_string(shot + 1);
gather->SetUniqueKeyValue(TraceHeaderKey::FLDR, val);
results.push_back(gather);
}
return results;
}
| 4,497
|
C++
|
.cpp
| 92
| 37.673913
| 118
| 0.586003
|
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,177
|
RTMEngine.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/engines/concrete/RTMEngine.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/logger/concrete/LoggerSystem.hpp>
#include <bs/base/memory/MemoryManager.hpp>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/engines/concrete/RTMEngine.hpp>
#define PB_STR "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
#define PB_WIDTH 50
using namespace std;
using namespace bs::base::exceptions;
using namespace bs::base::logger;
using namespace bs::base::memory;
using namespace bs::base::configurations;
using namespace bs::timer;
using namespace operations::configurations;
using namespace operations::engines;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::helpers::callbacks;
void print_progress(double percentage, const char *str = nullptr) {
int val = (int) (percentage * 100);
int left_pad = (int) (percentage * PB_WIDTH);
int right_pad = PB_WIDTH - left_pad;
printf("\r%s\t%3d%% [%.*s%*s]", str, val, left_pad, PB_STR, right_pad, "");
fflush(stdout);
}
RTMEngine::RTMEngine(RTMEngineConfigurations *apConfiguration,
ComputationParameters *apParameters) {
this->mpConfiguration = apConfiguration;
this->mpParameters = apParameters;
this->mpCallbacks = new CallbackCollection();
}
RTMEngine::RTMEngine(RTMEngineConfigurations *apConfiguration,
ComputationParameters *apParameters,
helpers::callbacks::CallbackCollection *apCallbackCollection) {
this->mpConfiguration = apConfiguration;
this->mpParameters = apParameters;
this->mpCallbacks = apCallbackCollection;
}
RTMEngine::~RTMEngine() {
delete this->mpConfiguration;
delete this->mpParameters;
delete this->mpCallbacks;
}
vector<uint>
RTMEngine::GetValidShots() {
LoggerSystem *Logger = LoggerSystem::GetInstance();
Logger->Info() << "Detecting available shots for processing..." << '\n';
ElasticTimer timer("Engine::GetValidShots");
timer.Start();
vector<uint> possible_shots =
this->mpConfiguration->GetTraceManager()->GetWorkingShots(
this->mpConfiguration->GetTraceFiles(),
this->mpConfiguration->GetSortMin(),
this->mpConfiguration->GetSortMax(),
this->mpConfiguration->GetSortKey());
timer.Stop();
if (possible_shots.empty()) {
Logger->Error() << "No valid shots detected... terminating." << '\n';
exit(EXIT_FAILURE);
}
Logger->Info() << "Valid shots detected to process\t: "
<< possible_shots.size() << '\n';
return possible_shots;
}
GridBox *
RTMEngine::Initialize() {
ScopeTimer t("Engine::Initialization");
#ifndef NDEBUG
this->mpCallbacks->BeforeInitialization(this->mpParameters);
#endif
/// Set computation parameters to all components with
/// parameters given to the constructor for all needed functions.
for (auto const &component :
this->mpConfiguration->GetComponents()->ExtractValues()) {
component->SetComputationParameters(this->mpParameters);
}
/// Set computation parameters to all dependent components with
/// parameters given to the constructor for all needed functions.
for (auto const &dependent_component :
this->mpConfiguration->GetDependentComponents()->ExtractValues()) {
dependent_component->SetComputationParameters(this->mpParameters);
}
/// Set dependent components to all components with for all
/// needed functions.
for (auto const &component :
this->mpConfiguration->GetComponents()->ExtractValues()) {
component->SetDependentComponents(
this->mpConfiguration->GetDependentComponents());
}
/// Set Components Map to all components.
for (auto const &component :
this->mpConfiguration->GetComponents()->ExtractValues()) {
component->SetComponentsMap(this->mpConfiguration->GetComponents());
}
/// Acquire Configuration to all components with
/// parameters given to the constructor for all needed functions.
for (auto const &component :
this->mpConfiguration->GetComponents()->ExtractValues()) {
component->AcquireConfiguration();
}
this->mpParameters->SetMaxPropagationFrequency(
this->mpConfiguration->GetSourceInjector()->GetMaxFrequency());
GridBox *gb;
{
ScopeTimer timer("ModelHandler::ReadModel");
gb = this->mpConfiguration->GetModelHandler()->ReadModel(this->mpConfiguration->GetModelFiles());
}
/// Set the GridBox with the parameters given to the constructor for
/// all needed functions.
for (auto const &component :
this->mpConfiguration->GetComponents()->ExtractValues()) {
component->SetGridBox(gb);
}
{
ScopeTimer timer("ModelHandler::PreprocessModel");
this->mpConfiguration->GetComputationKernel()->PreprocessModel();
}
{
ScopeTimer timer("BoundaryManager::ExtendModel");
this->mpConfiguration->GetBoundaryManager()->ExtendModel();
}
#ifndef NDEBUG
this->mpCallbacks->AfterInitialization(gb);
#endif
this->mpConfiguration->GetComputationKernel()->SetBoundaryManager(
this->mpConfiguration->GetBoundaryManager());
gb->Report(VERBOSE);
return gb;
}
void
RTMEngine::MigrateShots(vector<uint> shot_numbers, GridBox *apGridBox) {
for (auto shot_number : shot_numbers) {
this->MigrateShots(shot_number, apGridBox);
}
}
void
RTMEngine::MigrateShots(uint shot_id, GridBox *apGridBox) {
ScopeTimer t("Engine::MigrateShot");
this->mpConfiguration->GetMigrationAccommodator()->ResetShotCorrelation();
{
ScopeTimer timer("TraceManager::ReadShot");
this->mpConfiguration->GetTraceManager()->ReadShot(
this->mpConfiguration->GetTraceFiles(), shot_id, this->mpConfiguration->GetSortKey());
}
#ifndef NDEBUG
this->mpCallbacks->BeforeShotPreprocessing(
this->mpConfiguration->GetTraceManager()->GetTracesHolder());
#endif
{
ScopeTimer timer("TraceManager::PreprocessShot");
this->mpConfiguration->GetTraceManager()->PreprocessShot();
}
#ifndef NDEBUG
this->mpCallbacks->AfterShotPreprocessing(
this->mpConfiguration->GetTraceManager()->GetTracesHolder());
#endif
this->mpConfiguration->GetSourceInjector()->SetSourcePoint(
this->mpConfiguration->GetTraceManager()->GetSourcePoint());
{
ScopeTimer timer("ModelHandler::SetupWindow");
this->mpConfiguration->GetModelHandler()->SetupWindow();
}
{
ScopeTimer timer("BoundaryManager::ReExtendModel");
this->mpConfiguration->GetBoundaryManager()->ReExtendModel();
}
{
ScopeTimer timer("ForwardCollector::ResetGrid(Forward)");
this->mpConfiguration->GetForwardCollector()->ResetGrid(true);
}
#ifndef NDEBUG
this->mpCallbacks->BeforeForwardPropagation(apGridBox);
#endif
this->Forward(apGridBox);
{
ScopeTimer timer("ForwardCollector::ResetGrid(Backward)");
this->mpConfiguration->GetForwardCollector()->ResetGrid(false);
}
{
ScopeTimer timer("BoundaryManager::AdjustModelForBackward");
this->mpConfiguration->GetBoundaryManager()->AdjustModelForBackward();
}
#ifndef NDEBUG
this->mpCallbacks->BeforeBackwardPropagation(apGridBox);
#endif
this->Backward(apGridBox);
#ifndef NDEBUG
this->mpCallbacks->BeforeShotStacking(
apGridBox,
this->mpConfiguration->GetMigrationAccommodator()->GetShotCorrelation());
#endif
this->mpConfiguration->GetMigrationAccommodator()->SetSourcePoint(
this->mpConfiguration->GetTraceManager()->GetSourcePoint());
{
ScopeTimer timer("Correlation::Stack");
this->mpConfiguration->GetMigrationAccommodator()->Stack();
}
#ifndef NDEBUG
this->mpCallbacks->AfterShotStacking(
apGridBox,
this->mpConfiguration->GetMigrationAccommodator()->GetStackedShotCorrelation());
#endif
}
MigrationData *
RTMEngine::Finalize(GridBox *apGridBox) {
#ifndef NDEBUG
this->mpCallbacks->AfterMigration(
apGridBox,
this->mpConfiguration->GetMigrationAccommodator()->GetStackedShotCorrelation());
#endif
MigrationData *md;
{
ScopeTimer t("CorrelationKernel::GetMigrationData");
md = this->mpConfiguration->GetMigrationAccommodator()->GetMigrationData();
}
{
ScopeTimer t("ModelHandler::PostProcessMigration");
this->mpConfiguration->GetModelHandler()->PostProcessMigration(md);
}
delete apGridBox;
return md;
}
void
RTMEngine::Forward(GridBox *apGridBox) {
ScopeTimer t("Engine::Forward");
auto logger = LoggerSystem::GetInstance();
this->mpConfiguration->GetComputationKernel()->SetMode(
components::KERNEL_MODE::FORWARD);
int time_steps = this->mpConfiguration->GetSourceInjector()->GetPrePropagationNT();
// Do prequel source injection before main forward propagation.
for (int it = -time_steps; it < 1; it++) {
{
ScopeTimer timer("SourceInjector::ApplySource");
this->mpConfiguration->GetSourceInjector()->ApplySource(it);
}
{
ScopeTimer timer("Forward::ComputationKernel::Step");
this->mpConfiguration->GetComputationKernel()->Step();
}
#ifndef NDEBUG
this->mpCallbacks->AfterForwardStep(apGridBox, it);
#endif
}
uint one_percent = apGridBox->GetNT() / 100 + 1;
for (int it = 1; it < apGridBox->GetNT(); it++) {
{
ScopeTimer timer("ForwardCollector::SaveForward");
this->mpConfiguration->GetForwardCollector()->SaveForward();
}
{
ScopeTimer timer("SourceInjector::ApplySource");
this->mpConfiguration->GetSourceInjector()->ApplySource(it);
}
{
ScopeTimer timer("Forward::ComputationKernel::Step");
this->mpConfiguration->GetComputationKernel()->Step();
}
#ifndef NDEBUG
this->mpCallbacks->AfterForwardStep(apGridBox, it);
#endif
if ((it % one_percent) == 0) {
print_progress(((float) it) / apGridBox->GetNT(), "Forward Propagation");
}
}
print_progress(1, "Forward Propagation");
logger->Info() << " ... Done" << '\n';
}
void
RTMEngine::Backward(GridBox *apGridBox) {
ScopeTimer t("Engine::Backward");
auto logger = LoggerSystem::GetInstance();
this->mpConfiguration->GetComputationKernel()->SetMode(
components::KERNEL_MODE::ADJOINT);
uint onePercent = apGridBox->GetNT() / 100 + 1;
for (uint it = apGridBox->GetNT() - 1; it > 0; it--) {
{
ScopeTimer timer("TraceManager::ApplyTraces");
this->mpConfiguration->GetTraceManager()->ApplyTraces(it);
}
{
ScopeTimer timer("Backward::ComputationKernel::Step");
this->mpConfiguration->GetComputationKernel()->Step();
}
{
ScopeTimer timer("ForwardCollector::FetchForward");
this->mpConfiguration->GetForwardCollector()->FetchForward();
}
#ifndef NDEBUG
this->mpCallbacks->AfterFetchStep(
this->mpConfiguration->GetForwardCollector()->GetForwardGrid(), it);
this->mpCallbacks->AfterBackwardStep(apGridBox, it);
#endif
{
ScopeTimer timer("Correlation::Correlate");
this->mpConfiguration->GetMigrationAccommodator()->Correlate(
this->mpConfiguration->GetForwardCollector()->GetForwardGrid());
}
if ((it % onePercent) == 0) {
print_progress(((float) (apGridBox->GetNT() - it)) / apGridBox->GetNT(), "Backward Propagation");
}
}
print_progress(1, "Backward Propagation");
logger->Info() << " ... Done" << '\n';
}
| 12,689
|
C++
|
.cpp
| 321
| 33.099688
| 109
| 0.679591
|
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,178
|
ModellingEngine.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/engines/concrete/ModellingEngine.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 <bs/base/logger/concrete/LoggerSystem.hpp>
#include <bs/timer/api/cpp/BSTimer.hpp>
#include <operations/engines/concrete/ModellingEngine.hpp>
#define PB_STR "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
#define PB_WIDTH 50
using namespace std;
using namespace bs::timer;
using namespace bs::base::configurations;
using namespace bs::base::logger;
using namespace bs::base::memory;
using namespace operations::configurations;
using namespace operations::engines;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::helpers::callbacks;
void print_modelling_progress(double percentage, const char *str = nullptr) {
int val = (int) (percentage * 100);
int left_pad = (int) (percentage * PB_WIDTH);
int right_pad = PB_WIDTH - left_pad;
printf("\r%s\t%3d%% [%.*s%*s]", str, val, left_pad, PB_STR, right_pad, "");
fflush(stdout);
}
/*!
* GetInstance():This is the so-called Singleton design pattern.
* Its distinguishing feature is that there can only ever be exactly one
* instance of that class and the pattern ensures that. The class has a private
* constructor and a statically-created instance that is returned with the
* GetInstance method. You cannot create an instance from the outside and thus
* get the object only through said method.Since instance is static in the
* GetInstance method it will retain its value between multiple invocations. It
* is allocated and constructed some where before it's first used. E.g. in this
* answer it seems like GCC initializes the static variable at the time the
* function is first used.
*/
/*!
* Constructor to start the modelling engine given the appropriate engine
* configuration.
* @param apConfiguration
* The configuration which will control the actual work of the engine.
* @param apParameters
* The computation parameters that will control the simulations settings like
* boundary length, order of numerical solution.
*/
ModellingEngine::ModellingEngine(ModellingEngineConfigurations *apConfiguration,
ComputationParameters *apParameters) {
this->mpConfiguration = apConfiguration;
/**
* Callbacks are like hooks that you can register function to be called in
* specific events(etc. after the forward propagation, after each time step,
* and so on) this enables the user to add functionalities,take snapshots
* or track state in different approaches. A callback is the class actually
* implementing the functions to capture or track state like norm, images, csv
* and so on. They are registered to a callback collection which is what links
* them to the engine. The engine would inform the callback collection at the
* time of each event, and the callback collection would then inform each
* callback registered to it.
*/
this->mpCallbacks = new CallbackCollection();
this->mpParameters = apParameters;
}
/**
* Constructor to start the modelling engine given the appropriate engine
* configuration.
* @param apConfiguration
* The configuration which will control the actual work of the engine.
* @param apParameters
* The computation parameters that will control the simulations settings like
* boundary length, order of numerical solution.
* @param apCallbackCollection
* The callbacks registered to be called in the right time.
*/
ModellingEngine::ModellingEngine(ModellingEngineConfigurations *apConfiguration,
ComputationParameters *apParameters,
helpers::callbacks::CallbackCollection *apCallbackCollection) {
/// Modeling configuration of the class is that given as
/// argument to the constructor
this->mpConfiguration = apConfiguration;
/// Callback of the class is that given as argument to the constructor
this->mpCallbacks = apCallbackCollection;
/// Computation parameters of this class is that given as
/// argument to the constructor.
this->mpParameters = apParameters;
}
ModellingEngine::~ModellingEngine() = default;
/**
* Run the initialization steps for the modelling engine.
*/
GridBox *ModellingEngine::Initialize() {
ScopeTimer t("Engine::Initialization");
#ifndef NDEBUG
this->mpCallbacks->BeforeInitialization(this->mpParameters);
#endif
/// Set computation parameters to all components with
/// parameters given to the constructor for all needed functions.
for (auto component :
this->mpConfiguration->GetComponents()->ExtractValues()) {
component->SetComputationParameters(this->mpParameters);
}
/// Set computation parameters to all dependent components with
/// parameters given to the constructor for all needed functions.
for (auto const &dependent_component :
this->mpConfiguration->GetDependentComponents()->ExtractValues()) {
dependent_component->SetComputationParameters(this->mpParameters);
}
/// Set dependent components to all components with for all
/// needed functions.
for (auto const &component :
this->mpConfiguration->GetComponents()->ExtractValues()) {
component->SetDependentComponents(
this->mpConfiguration->GetDependentComponents());
}
/// Set Components Map to all components.
for (auto const &component :
this->mpConfiguration->GetComponents()->ExtractValues()) {
component->SetComponentsMap(this->mpConfiguration->GetComponents());
}
/// Acquire Configuration to all components with
/// parameters given to the constructor for all needed functions.
for (auto const &component :
this->mpConfiguration->GetComponents()->ExtractValues()) {
component->AcquireConfiguration();
}
this->mpParameters->SetMaxPropagationFrequency(
this->mpConfiguration->GetSourceInjector()->GetMaxFrequency());
ElasticTimer timer("ModelHandler::ReadModel");
timer.Start();
auto gb = this->mpConfiguration->GetModelHandler()->ReadModel(
this->mpConfiguration->GetModelFiles());
timer.Stop();
/// Set the GridBox with the parameters given to the constructor for
/// all needed functions.
for (auto component :
this->mpConfiguration->GetComponents()->ExtractValues()) {
component->SetGridBox(gb);
}
/**
* All pre-processing needed to be done on the model before the beginning of
* the reverse time migration, should be applied in this function.
*/
{
ScopeTimer timer("ModelHandler::PreprocessModel");
this->mpConfiguration->GetComputationKernel()->PreprocessModel();
}
/**
* Extends the velocities/densities to the added boundary parts to the
* velocity/density of the model appropriately. This is only called once after
* the initialization of the model.
*/
{
ScopeTimer timer("BoundaryManager::ExtendModel");
this->mpConfiguration->GetBoundaryManager()->ExtendModel();
}
#ifndef NDEBUG
this->mpCallbacks->AfterInitialization(gb);
#endif
this->mpConfiguration->GetComputationKernel()->SetBoundaryManager(
this->mpConfiguration->GetBoundaryManager());
gb->Report(VERBOSE);
return gb;
}
vector<uint> ModellingEngine::GetValidShots() {
auto logger = LoggerSystem::GetInstance();
logger->Info() << "Detecting available shots for processing..." << '\n';
ElasticTimer timer("Engine::GetValidShots");
timer.Start();
vector<uint> possible_shots =
this->mpConfiguration->GetTraceManager()->GetWorkingShots(
this->mpConfiguration->GetTraceFiles(),
this->mpConfiguration->GetSortMin(),
this->mpConfiguration->GetSortMax(),
this->mpConfiguration->GetSortKey());
timer.Stop();
if (possible_shots.empty()) {
logger->Error() << "No valid shots detected... terminating." << '\n';
exit(EXIT_FAILURE);
}
logger->Info() << "Valid shots detected to process\t: "
<< possible_shots.size() << '\n';
return possible_shots;
}
void ModellingEngine::MigrateShots(vector<uint> aShotNumbers, GridBox *apGridBox) {
for (auto shot_number : aShotNumbers) {
this->MigrateShots(shot_number, apGridBox);
}
}
void ModellingEngine::MigrateShots(uint shot_id, GridBox *apGridBox) {
ScopeTimer t("Engine::Model");
{
ScopeTimer timer("TraceManager::ReadShot");
this->mpConfiguration->GetTraceManager()->ReadShot(
this->mpConfiguration->GetTraceFiles(), shot_id, this->mpConfiguration->GetSortKey());
}
#ifndef NDEBUG
this->mpCallbacks->BeforeShotPreprocessing(
this->mpConfiguration->GetTraceManager()->GetTracesHolder());
#endif
{
ScopeTimer timer("TraceManager::PreprocessShot");
this->mpConfiguration->GetTraceManager()->PreprocessShot();
}
#ifndef NDEBUG
this->mpCallbacks->AfterShotPreprocessing(
this->mpConfiguration->GetTraceManager()->GetTracesHolder());
#endif
this->mpConfiguration->GetSourceInjector()->SetSourcePoint(
this->mpConfiguration->GetTraceManager()->GetSourcePoint());
{
ScopeTimer timer("ModelHandler::SetupWindow");
this->mpConfiguration->GetModelHandler()->SetupWindow();
}
{
ScopeTimer timer("BoundaryManager::ReExtendModel");
this->mpConfiguration->GetBoundaryManager()->ReExtendModel();
}
#ifndef NDEBUG
/// If in the debug mode use the call back of BeforeForwardPropagation and
/// give it our updated GridBox
this->mpCallbacks->BeforeForwardPropagation(apGridBox);
#endif
/// If not in the debug mode(release mode) call the Forward function of
/// this class and give it our updated GridBox
/*!
* Begin the forward propagation and recording of the traces.
*/
this->Forward(apGridBox, shot_id);
}
MigrationData *ModellingEngine::Finalize(GridBox *apGridBox) {
this->mpConfiguration->GetTraceWriter()->Finalize();
return nullptr;
}
void ModellingEngine::Forward(GridBox *apGridBox, uint shot_id) {
ScopeTimer t("Engine::Forward");
auto logger = LoggerSystem::GetInstance();
{
ScopeTimer timer("TraceWriter::StartRecordingInstance");
this->mpConfiguration->GetTraceWriter()->StartRecordingInstance(
*this->mpConfiguration->GetTraceManager()->GetTracesHolder()
);
}
this->mpConfiguration->GetComputationKernel()->SetMode(
components::KERNEL_MODE::FORWARD);
int timesteps = this->mpConfiguration->GetSourceInjector()->GetPrePropagationNT();
// Do prequel source injection before main forward propagation.
for (int it = -timesteps; it < 1; it++) {
{
ScopeTimer timer("SourceInjector::ApplySource");
this->mpConfiguration->GetSourceInjector()->ApplySource(it);
}
{
ScopeTimer timer("Forward::ComputationKernel::Step");
this->mpConfiguration->GetComputationKernel()->Step();
}
#ifndef NDEBUG
this->mpCallbacks->AfterForwardStep(apGridBox, it);
#endif
}
uint onePercent = apGridBox->GetNT() / 100 + 1;
for (uint t = 1; t < apGridBox->GetNT(); t++) {
{
ScopeTimer timer("SourceInjector::ApplySource");
this->mpConfiguration->GetSourceInjector()->ApplySource(t);
}
{
ScopeTimer timer("Forward::ComputationKernel::Step");
this->mpConfiguration->GetComputationKernel()->Step();
}
#ifndef NDEBUG
/// If in the debug mode use the call back of AfterForwardStep and give
/// it the updated gridBox
this->mpCallbacks->AfterForwardStep(apGridBox, t);
#endif
/// If not in the debug mode (release mode) we use call the RecordTrace()
{
ScopeTimer timer("TraceWriter::RecordTrace");
this->mpConfiguration->GetTraceWriter()->RecordTrace(t);
}
/**
* Records the traces from the domain according to the configuration given
* in the initialize function.
*/
if ((t % onePercent) == 0) {
print_modelling_progress(((float) t) / apGridBox->GetNT(), "Forward Propagation");
}
}
print_modelling_progress(1, "Forward Propagation");
logger->Info() << " ... Done" << '\n';
{
ScopeTimer timer("TraceWriter::FinishRecordingInstance");
this->mpConfiguration->GetTraceWriter()->FinishRecordingInstance(shot_id);
}
}
| 13,428
|
C++
|
.cpp
| 310
| 37.4
| 102
| 0.69945
|
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,179
|
WriterCallback.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/helpers/callbacks/concrete/WriterCallback.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 <vector>
#include <sys/stat.h>
#include <bs/base/logger/concrete/LoggerSystem.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <operations/helpers/callbacks/concrete/WriterCallback.h>
#include <operations/common/DataTypes.h>
#include <operations/utils/io/write_utils.h>
#define CAT_STR_TO_CHR(a, b) ((char *)string(a + b).c_str())
#define SPACE_SAMPLE_SCALE 1e3
#define TIME_SAMPLE_SCALE 1e6
using namespace std;
using namespace bs::base::logger;
using namespace bs::base::configurations;
using namespace bs::io::streams;;
using namespace operations::helpers::callbacks;
using namespace operations::common;
using namespace operations::dataunits;
using namespace operations::utils::io;
/// Helper functions to be relocated/replaced
/// after further implementations
/// {
bool is_path_exist(const std::string &s) {
struct stat buffer;
return (stat(s.c_str(), &buffer) == 0);
}
u_int16_t get_callbacks_map(const string &key) {
/// Initialized upon first call to the function.
static std::map<std::string, u_int16_t> callbacks_params_map = {
{"velocity", PARM | GB_VEL},
{"delta", PARM | GB_DLT},
{"epsilon", PARM | GB_EPS},
{"theta", PARM | GB_THT},
{"phi", PARM | GB_PHI},
{"density", PARM | GB_DEN}
};
return callbacks_params_map.at(key);
}
std::map<std::string, u_int16_t> get_params_map() {
/// Initialized upon first call to the function.
static std::map<std::string, u_int16_t> callbacks_params_map = {
{"velocity", PARM | GB_VEL},
{"delta", PARM | GB_DLT},
{"epsilon", PARM | GB_EPS},
{"theta", PARM | GB_THT},
{"phi", PARM | GB_PHI},
{"density", PARM | GB_DEN}
};
return callbacks_params_map;
}
std::map<std::string, u_int16_t> get_pressure_map() {
// Initialized upon the first call to the function
static std::map<std::string, u_int16_t> callbacks_pressure_map = {
{"vertical", WAVE | GB_PRSS | CURR | DIR_Z},
{"horizontal", WAVE | GB_PRSS | CURR | DIR_X}
};
return callbacks_pressure_map;
}
/// }
/// End of helper functions
float *Unpad(const float *apOriginalArray, uint nx, uint ny, uint nz,
uint nx_original, uint ny_original, uint nz_original) {
if (nx == nx_original && nz == nz_original && ny == ny_original) {
return nullptr;
} else {
auto copy_array = new float[ny_original * nz_original * nx_original];
for (uint iy = 0; iy < ny_original; iy++) {
for (uint iz = 0; iz < nz_original; iz++) {
for (uint ix = 0; ix < nx_original; ix++) {
copy_array[iy * nz_original * nx_original + iz * nx_original + ix] =
apOriginalArray[iy * nz * nx + iz * nx + ix];
}
}
}
return copy_array;
}
}
WriterCallback::WriterCallback(uint aShowEach,
bool aWriteParams,
bool aWriteForward,
bool aWriteBackward,
bool aWriteReverse,
bool aWriteMigration,
bool aWriteReExtendedParams,
bool aWriteSingleShotCorrelation,
bool aWriteEachStackedShot, bool aWriteTracesRaw,
bool aWriteTracesPreprocessed,
const std::vector<std::string> &aVecParams,
const std::vector<std::string> &aVecReExtendedParams,
const string &aWritePath,
std::vector<std::string> &aTypes,
std::vector<std::string> &aUnderlyingConfigurations) {
LoggerSystem *Logger = LoggerSystem::GetInstance();
this->mShowEach = aShowEach;
this->mShotCount = 0;
this->mIsWriteParams = aWriteParams;
this->mIsWriteForward = aWriteForward;
this->mIsWriteBackward = aWriteBackward;
this->mIsWriteReverse = aWriteReverse;
this->mIsWriteMigration = aWriteMigration;
this->mIsWriteReExtendedParams = aWriteReExtendedParams;
this->mIsWriteSingleShotCorrelation = aWriteSingleShotCorrelation;
this->mIsWriteEachStackedShot = aWriteEachStackedShot;
this->mIsWriteTracesRaw = aWriteTracesRaw;
this->mIsWriteTracesPreprocessed = aWriteTracesPreprocessed;
this->mParamsVec = aVecParams;
this->mReExtendedParamsVec = aVecReExtendedParams;
if (this->mParamsVec.empty()) {
for (auto const &pair : get_params_map()) {
this->mParamsVec.push_back(pair.first);
}
}
if (this->mReExtendedParamsVec.empty()) {
for (auto const &pair: get_params_map()) {
this->mReExtendedParamsVec.push_back(pair.first);
}
}
this->mWritePath = aWritePath;
this->mWriterTypes = aTypes;
mkdir(aWritePath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
Logger->Info() << "Writer callback aTypes to be written : " << '\n';
for (int i = 0; i < aTypes.size(); i++) {
auto type = aTypes[i];
try {
SeismicWriter::ToWriterType(type);
} catch (exception &e) {
Logger->Error() << "Invalid type provided to writer callback : " << e.what() << '\n';
Logger->Error() << "Terminating..." << '\n';
exit(EXIT_FAILURE);
}
Logger->Info() << "\tType #" << (i + 1) << " : " << type << '\n';
nlohmann::json configuration = nlohmann::json::parse(aUnderlyingConfigurations[i]);
JSONConfigurationMap io_conf_map(configuration);
this->mWriters.push_back(new SeismicWriter(SeismicWriter::ToWriterType(type),
&io_conf_map));
this->mWriters.back()->AcquireConfiguration();
std::string mod_path = this->mWritePath + "/output_" + type;
mkdir(mod_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (aWriteReExtendedParams) {
mkdir(CAT_STR_TO_CHR(mod_path, "/parameters"),
S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
if (aWriteSingleShotCorrelation) {
mkdir(CAT_STR_TO_CHR(mod_path, "/shots"),
S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
if (aWriteEachStackedShot) {
mkdir(CAT_STR_TO_CHR(mod_path, "/stacked_shots"),
S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
if (aWriteForward) {
mkdir(CAT_STR_TO_CHR(mod_path, "/forward"),
S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
if (aWriteReverse) {
mkdir(CAT_STR_TO_CHR(mod_path, "/reverse"),
S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
if (aWriteBackward) {
mkdir(CAT_STR_TO_CHR(mod_path, "/backward"),
S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
if (aWriteTracesRaw) {
mkdir(CAT_STR_TO_CHR(mod_path, "/traces_raw"),
S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
if (aWriteTracesPreprocessed) {
mkdir(CAT_STR_TO_CHR(mod_path, "/traces"),
S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
}
}
WriterCallback::~WriterCallback() {
for (auto writer : this->mWriters) {
delete writer;
}
}
void
WriterCallback::WriteResult(uint nx, uint ny, uint ns, float dx, float dy, float ds, const float *data,
const std::string &filename, float sample_scale) {
auto gathers = TransformToGather(data, nx, ny, ns, dx, dy, ds,
0, 0, 0, 0,
1, 1e3, sample_scale);
for (int i_writer = 0; i_writer < this->mWriterTypes.size(); i_writer++) {
std::string path = this->mWritePath + "/output_" + this->mWriterTypes[i_writer] + filename;
this->mWriters[i_writer]->Initialize(path);
this->mWriters[i_writer]->Write(gathers);
this->mWriters[i_writer]->Finalize();
}
for (auto g : gathers) {
delete g;
}
}
void
WriterCallback::BeforeInitialization(ComputationParameters *apParameters) {}
void
WriterCallback::AfterInitialization(GridBox *apGridBox) {
if (this->mIsWriteParams) {
uint pnx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
uint pny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
uint pnz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
uint nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize();
uint ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
uint nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetLogicalAxisSize();
float dx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
for (const auto ¶m : this->mParamsVec) {
if (apGridBox->Has(get_callbacks_map(param))) {
float *arr = apGridBox->Get(get_callbacks_map(param))->GetDiskFlushPointer();
float *unpadded_arr = Unpad(arr, pnx, pny, pnz, nx, ny, nz);
if (unpadded_arr) {
arr = unpadded_arr;
}
uint nt = apGridBox->GetNT();
WriteResult(nx, ny, nz, dx, dy, dz, arr,
"/" + param, SPACE_SAMPLE_SCALE);
delete unpadded_arr;
}
}
}
}
void
WriterCallback::BeforeShotPreprocessing(TracesHolder *traces) {
if (this->mIsWriteTracesRaw) {
uint nx = traces->TraceSizePerTimeStep;
uint ny = 1;
uint nt = traces->SampleNT;
float dt = traces->SampleDT;
float dx = 1.0;
float dy = 1.0;
WriteResult(nx, ny, nt, dx, dy, dt, traces->Traces->GetDiskFlushPointer(),
"/traces_raw/trace_" +
to_string(this->mShotCount), TIME_SAMPLE_SCALE);
}
}
void
WriterCallback::AfterShotPreprocessing(TracesHolder *traces) {
if (this->mIsWriteTracesPreprocessed) {
uint nx = traces->TraceSizePerTimeStep;
uint ny = 1;
uint nt = traces->SampleNT;
float dt = traces->SampleDT;
float dx = 1.0;
float dy = 1.0;
WriteResult(nx, ny, nt, dx, dy, dt, traces->Traces->GetDiskFlushPointer(),
"/traces/trace_" +
to_string(this->mShotCount), TIME_SAMPLE_SCALE);
}
}
void
WriterCallback::BeforeForwardPropagation(GridBox *apGridBox) {
if (this->mIsWriteReExtendedParams) {
uint pwnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint pwny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint pwnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint wnx = apGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
uint wny = apGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
uint wnz = apGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
float dx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
for (const auto ¶m : this->mReExtendedParamsVec) {
if (apGridBox->Has(get_callbacks_map(param))) {
float *arr = apGridBox->Get(get_callbacks_map(param) | WIND)->GetDiskFlushPointer();
float *unpadded_arr = Unpad(arr, pwnx, pwny, pwnz, wnx, wny, wnz);
if (unpadded_arr) {
arr = unpadded_arr;
}
WriteResult(wnx, wny, wnz, dx, dy, dz, arr,
"/parameters/" + param + "_" +
to_string(this->mShotCount), SPACE_SAMPLE_SCALE);
delete unpadded_arr;
}
}
}
}
void
WriterCallback::AfterForwardStep(GridBox *apGridBox, int time_step) {
if (mIsWriteForward && time_step % mShowEach == 0) {
uint pwnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint pwny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint pwnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint wnx = apGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
uint wny = apGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
uint wnz = apGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
float dx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
for (const auto &pressure : get_pressure_map()) {
if (apGridBox->Has(pressure.second)) {
for (auto &type : this->mWriterTypes) {
if (!is_path_exist(string(this->mWritePath + "/output_"
+ type + "/forward/" + pressure.first)))
mkdir(CAT_STR_TO_CHR(this->mWritePath + "/output_"
+ type + "/forward/", pressure.first),
S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
float *arr = apGridBox->Get(pressure.second)->GetDiskFlushPointer();
float *unpadded_arr = Unpad(arr, pwnx, pwny, pwnz, wnx, wny, wnz);
if (unpadded_arr) {
arr = unpadded_arr;
}
WriteResult(wnx, wny, wnz, dx, dy, dz, arr,
"/forward/" + pressure.first
+ "/forward_" + pressure.first + "_" +
to_string(time_step), SPACE_SAMPLE_SCALE);
delete unpadded_arr;
}
}
}
}
void
WriterCallback::BeforeBackwardPropagation(GridBox *apGridBox) {
if (mIsWriteReExtendedParams) {
uint pwnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint pwny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint pwnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint wnx = apGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
uint wny = apGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
uint wnz = apGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
float dx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
for (const auto ¶m : this->mReExtendedParamsVec) {
if (apGridBox->Has(get_callbacks_map(param))) {
float *arr = apGridBox->Get(get_callbacks_map(param) | WIND)->GetDiskFlushPointer();
float *unpadded_arr = Unpad(arr, pwnx, pwny, pwnz, wnx, wny, wnz);
if (unpadded_arr) {
arr = unpadded_arr;
}
WriteResult(wnx, wny, wnz, dx, dy, dz, arr,
"/parameters/" + param + "_backward_" +
to_string(mShotCount), SPACE_SAMPLE_SCALE);
delete unpadded_arr;
}
}
}
}
void
WriterCallback::AfterBackwardStep(
GridBox *apGridBox, int time_step) {
if (mIsWriteBackward && time_step % mShowEach == 0) {
uint pwnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint pwny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint pwnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint wnx = apGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
uint wny = apGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
uint wnz = apGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
float dx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
for (const auto &pressure : get_pressure_map()) {
if (apGridBox->Has(pressure.second)) {
for (auto &type : this->mWriterTypes) {
if (!is_path_exist(string(this->mWritePath + "/output_"
+ type + "/backward/" + pressure.first)))
mkdir(CAT_STR_TO_CHR(this->mWritePath + "/output_"
+ type + "/backward/", pressure.first),
S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
float *arr = apGridBox->Get(pressure.second)->GetDiskFlushPointer();
float *unpadded_arr = Unpad(arr, pwnx, pwny, pwnz, wnx, wny, wnz);
if (unpadded_arr) {
arr = unpadded_arr;
}
WriteResult(wnx, wny, wnz, dx, dy, dz, arr,
"/backward/" + pressure.first
+ "/backward_" + pressure.first + "_" +
to_string(time_step), SPACE_SAMPLE_SCALE);
delete unpadded_arr;
}
}
}
}
void
WriterCallback::AfterFetchStep(
GridBox *apGridBox, int time_step) {
if (mIsWriteReverse && time_step % mShowEach == 0) {
uint pwnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint pwny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint pwnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint wnx = apGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
uint wny = apGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
uint wnz = apGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
float dx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
for (const auto &pressure : get_pressure_map()) {
if (apGridBox->Has(pressure.second)) {
for (auto &type : this->mWriterTypes) {
if (!is_path_exist(string(this->mWritePath + "/output_"
+ type + "/reverse/" + pressure.first)))
mkdir(CAT_STR_TO_CHR(this->mWritePath + "/output_"
+ type + "/reverse/", pressure.first),
S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
float *arr = apGridBox->Get(pressure.second)->GetDiskFlushPointer();
float *unpadded_arr = Unpad(arr, pwnx, pwny, pwnz, wnx, wny, wnz);
if (unpadded_arr) {
arr = unpadded_arr;
}
WriteResult(wnx, wny, wnz, dx, dy, dz, arr,
"/reverse/" + pressure.first
+ "/reverse_" + pressure.first + "_" +
to_string(time_step), SPACE_SAMPLE_SCALE);
delete unpadded_arr;
}
}
}
}
void
WriterCallback::BeforeShotStacking(
GridBox *apGridBox, FrameBuffer<float> *shot_correlation) {
if (mIsWriteSingleShotCorrelation) {
uint pwnx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint pwny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint pwnz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
uint wnx = apGridBox->GetWindowAxis()->GetXAxis().GetLogicalAxisSize();
uint wny = apGridBox->GetWindowAxis()->GetYAxis().GetLogicalAxisSize();
uint wnz = apGridBox->GetWindowAxis()->GetZAxis().GetLogicalAxisSize();
float dx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
float *arr = shot_correlation->GetDiskFlushPointer();
float *unpadded_arr = Unpad(arr, pwnx, pwny, pwnz, wnx, wny, wnz);
if (unpadded_arr) {
arr = unpadded_arr;
}
WriteResult(wnx, wny, wnz, dx, dy, dz, arr,
"/shots/correlation_" +
to_string(mShotCount), SPACE_SAMPLE_SCALE);
delete unpadded_arr;
}
}
void
WriterCallback::AfterShotStacking(
GridBox *apGridBox, FrameBuffer<float> *stacked_shot_correlation) {
if (mIsWriteEachStackedShot) {
uint pnx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
uint pny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
uint pnz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
uint nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize();
uint ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
uint nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetLogicalAxisSize();
float dx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
float *arr = stacked_shot_correlation->GetDiskFlushPointer();
float *unpadded_arr = Unpad(arr, pnx, pny, pnz, nx, ny, nz);
if (unpadded_arr) {
arr = unpadded_arr;
}
float dt = apGridBox->GetDT();
WriteResult(nx, ny, nz, dx, dy, dz, arr,
"/stacked_shots/stacked_correlation_" +
to_string(mShotCount), SPACE_SAMPLE_SCALE);
delete unpadded_arr;
}
this->mShotCount++;
}
void
WriterCallback::AfterMigration(
GridBox *apGridBox, FrameBuffer<float> *stacked_shot_correlation) {
if (mIsWriteMigration) {
uint pnx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetActualAxisSize();
uint pny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetActualAxisSize();
uint pnz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetActualAxisSize();
uint nx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetLogicalAxisSize();
uint ny = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetLogicalAxisSize();
uint nz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetLogicalAxisSize();
float dx = apGridBox->GetAfterSamplingAxis()->GetXAxis().GetCellDimension();
float dy = apGridBox->GetAfterSamplingAxis()->GetYAxis().GetCellDimension();
float dz = apGridBox->GetAfterSamplingAxis()->GetZAxis().GetCellDimension();
float *arr = stacked_shot_correlation->GetDiskFlushPointer();
float *unpadded_arr = Unpad(arr, pnx, pny, pnz, nx, ny, nz);
if (unpadded_arr) {
arr = unpadded_arr;
}
WriteResult(nx, ny, nz, dx, dy, dz, arr,
"/migration", SPACE_SAMPLE_SCALE);
delete unpadded_arr;
}
}
| 24,774
|
C++
|
.cpp
| 502
| 38.336653
| 103
| 0.595251
|
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,180
|
NormWriter.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/helpers/callbacks/concrete/NormWriter.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 <sys/stat.h>
#include <operations/helpers/callbacks/concrete/NormWriter.h>
#include <operations/helpers/callbacks/interface/Extensions.hpp>
#define CAT_STR(a, b) (a + b)
using namespace std;
using namespace operations::helpers::callbacks;
using namespace operations::dataunits;
using namespace operations::common;
NormWriter::NormWriter(uint aShowEach,
bool aWriteForward,
bool aWriteBackward,
bool aWriteReverse,
const string &aWritePath) {
this->show_each = aShowEach;
this->write_forward = aWriteForward;
this->write_backward = aWriteBackward;
this->write_reverse = aWriteReverse;
this->write_path = aWritePath;
mkdir(aWritePath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
this->write_path = this->write_path + "/norm";
mkdir(this->write_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (this->write_forward) {
forward_norm_stream = new ofstream(this->write_path + "/forward_norm" + this->GetExtension());
}
if (this->write_reverse) {
reverse_norm_stream = new ofstream(this->write_path + "/reverse_norm" + this->GetExtension());
}
if (this->write_backward) {
backward_norm_stream =
new ofstream(this->write_path + "/backward_norm" + this->GetExtension());
}
}
NormWriter::~NormWriter() {
if (this->write_forward) {
delete forward_norm_stream;
}
if (this->write_reverse) {
delete reverse_norm_stream;
}
if (this->write_backward) {
delete backward_norm_stream;
}
}
void
NormWriter::BeforeInitialization(ComputationParameters *apParameters) {
this->offset = apParameters->GetBoundaryLength() + apParameters->GetHalfLength();
}
void
NormWriter::AfterInitialization(GridBox *apGridBox) {}
void
NormWriter::BeforeShotPreprocessing(TracesHolder *apTraces) {}
void
NormWriter::AfterShotPreprocessing(TracesHolder *apTraces) {}
void
NormWriter::BeforeForwardPropagation(GridBox *apGridBox) {}
void
NormWriter::AfterForwardStep(GridBox *apGridBox, int aTimeStep) {
if (write_forward && aTimeStep % show_each == 0) {
uint nx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint ny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint nz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
float norm = NormWriter::Solve(apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer(), nx, nz, ny);
(*this->forward_norm_stream) << aTimeStep << "\t" << norm << endl;
}
}
void
NormWriter::BeforeBackwardPropagation(GridBox *apGridBox) {}
void
NormWriter::AfterBackwardStep(GridBox *apGridBox, int aTimeStep) {
if (write_backward && aTimeStep % show_each == 0) {
uint nx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint ny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint nz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
float norm = NormWriter::Solve(apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer(), nx, nz, ny);
(*this->backward_norm_stream) << aTimeStep << "\t" << norm << endl;
}
}
void
NormWriter::AfterFetchStep(GridBox *apGridBox,
int aTimeStep) {
if (write_reverse && aTimeStep % show_each == 0) {
uint nx = apGridBox->GetWindowAxis()->GetXAxis().GetActualAxisSize();
uint ny = apGridBox->GetWindowAxis()->GetYAxis().GetActualAxisSize();
uint nz = apGridBox->GetWindowAxis()->GetZAxis().GetActualAxisSize();
float norm = NormWriter::Solve(apGridBox->Get(WAVE | GB_PRSS | CURR | DIR_Z)->GetHostPointer(), nx, nz, ny);
(*this->reverse_norm_stream) << aTimeStep << "\t" << norm << endl;
}
}
void
NormWriter::BeforeShotStacking(
GridBox *apGridBox, FrameBuffer<float> *apShotCorrelation) {}
void
NormWriter::AfterShotStacking(
GridBox *apGridBox, FrameBuffer<float> *apStackedShotCorrelation) {}
void
NormWriter::AfterMigration(
GridBox *apGridBox, FrameBuffer<float> *apStackedShotCorrelation) {}
float NormWriter::Solve(const float *apMatrix, uint nx, uint nz, uint ny) {
float sum = 0;
uint nx_nz = nx * nz;
int end_x = nx - this->offset;
int end_z = nz - this->offset;
int start_y = 0;
int end_y = 1;
if (ny > 1) {
start_y = this->offset;
end_y = ny - this->offset;
}
for (int iy = start_y; iy < end_y; iy++) {
for (int iz = this->offset; iz < end_z; iz++) {
for (int ix = this->offset; ix < end_x; ix++) {
auto value = apMatrix[iy * nx_nz + nx * iz + ix];
sum += (value * value);
}
}
}
return sqrtf(sum);
}
std::string NormWriter::GetExtension() {
return OP_K_EXT_NRM;
}
| 5,676
|
C++
|
.cpp
| 140
| 35.107143
| 116
| 0.669816
|
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,181
|
CallbackCollection.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/src/helpers/callbacks/primitive/CallbackCollection.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/helpers/callbacks/primitive/CallbackCollection.hpp>
using namespace std;
using namespace operations::helpers::callbacks;
using namespace operations::common;
using namespace operations::dataunits;
void CallbackCollection::RegisterCallback(Callback *apCallback) {
this->callbacks.push_back(apCallback);
}
void CallbackCollection::BeforeInitialization(
ComputationParameters *apParameters) {
for (auto it : this->callbacks) {
it->BeforeInitialization(apParameters);
}
}
void CallbackCollection::AfterInitialization(GridBox *apGridBox) {
for (auto it : this->callbacks) {
it->AfterInitialization(apGridBox);
}
}
void CallbackCollection::BeforeShotPreprocessing(TracesHolder *apTraces) {
for (auto it : this->callbacks) {
it->BeforeShotPreprocessing(apTraces);
}
}
void CallbackCollection::AfterShotPreprocessing(TracesHolder *apTraces) {
for (auto it : this->callbacks) {
it->AfterShotPreprocessing(apTraces);
}
}
void CallbackCollection::BeforeForwardPropagation(GridBox *apGridBox) {
for (auto it : this->callbacks) {
it->BeforeForwardPropagation(apGridBox);
}
}
void CallbackCollection::AfterForwardStep(GridBox *apGridBox, int time_step) {
for (auto it : this->callbacks) {
it->AfterForwardStep(apGridBox, time_step);
}
}
void CallbackCollection::BeforeBackwardPropagation(GridBox *apGridBox) {
for (auto it : this->callbacks) {
it->BeforeBackwardPropagation(apGridBox);
}
}
void CallbackCollection::AfterBackwardStep(
GridBox *apGridBox, int time_step) {
for (auto it : this->callbacks) {
it->AfterBackwardStep(apGridBox, time_step);
}
}
void CallbackCollection::AfterFetchStep(
GridBox *apGridBox, int time_step) {
for (auto it : this->callbacks) {
it->AfterFetchStep(apGridBox, time_step);
}
}
void CallbackCollection::BeforeShotStacking(
GridBox *apGridBox, FrameBuffer<float> *shot_correlation) {
for (auto it : this->callbacks) {
it->BeforeShotStacking(apGridBox, shot_correlation);
}
}
void CallbackCollection::AfterShotStacking(
GridBox *apGridBox, FrameBuffer<float> *stacked_shot_correlation) {
for (auto it : this->callbacks) {
it->AfterShotStacking(apGridBox, stacked_shot_correlation);
}
}
void CallbackCollection::AfterMigration(
GridBox *apGridBox, FrameBuffer<float> *stacked_shot_correlation) {
for (auto it : this->callbacks) {
it->AfterMigration(apGridBox, stacked_shot_correlation);
}
}
vector<Callback *> &CallbackCollection::GetCallbacks() {
return this->callbacks;
}
| 3,434
|
C++
|
.cpp
| 95
| 32.178947
| 78
| 0.739615
|
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,182
|
main.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/examples/segy/reader/main.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/nlohmann/json.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <bs/io/streams/concrete/readers/SegyReader.hpp>
#include <bs/io/utils/displayers/Displayer.hpp>
#include <bs/io/utils/timer/ExecutionTimer.hpp>
#include <bs/io/configurations/MapKeys.h>
using namespace std;
using namespace bs::base::configurations;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::io::utils::timer;
using namespace bs::io::utils::displayers;
int main(int argc, char *argv[]) {
nlohmann::json configuration_map;
configuration_map[IO_K_PROPERTIES][IO_K_TEXT_HEADERS_ONLY] = false;
configuration_map[IO_K_PROPERTIES][IO_K_TEXT_HEADERS_STORE] = false;
std::vector<TraceHeaderKey> gather_keys = {TraceHeaderKey::FLDR};
std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> sorting_keys;
std::vector<std::string> paths = {DATA_PATH "/shots0601_0800.segy",
DATA_PATH "/vel_z6.25m_x12.5m_exact.segy"};
SegyReader r(new JSONConfigurationMap(configuration_map));
r.AcquireConfiguration();
r.Initialize(gather_keys, sorting_keys, paths);
ExecutionTimer::Evaluate([&]() {
r.ReadAll();
}, true);
Displayer::PrintTextHeader(r.GetTextHeader());
if (r.HasExtendedTextHeader()) {
Displayer::PrintTextHeader(r.GetExtendedTextHeader());
}
}
| 2,192
|
C++
|
.cpp
| 50
| 40.06
| 81
| 0.734742
|
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,183
|
main.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/examples/segy/writer/main.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <sys/stat.h>
#include <prerequisites/libraries/nlohmann/json.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <bs/io/streams/concrete/readers/SegyReader.hpp>
#include <bs/io/streams/concrete/writers/SegyWriter.hpp>
#include <bs/io/utils/timer/ExecutionTimer.hpp>
#include <bs/io/configurations/MapKeys.h>
using namespace std;
using json = nlohmann::json;
using namespace bs::base::configurations;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::io::utils::timer;
int main(int argc, char *argv[]) {
mkdir(WRITE_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
/*
* Reading SEG-Y file.
*/
json read_configuration;
read_configuration[IO_K_PROPERTIES][IO_K_TEXT_HEADERS_ONLY] = false;
read_configuration[IO_K_PROPERTIES][IO_K_TEXT_HEADERS_STORE] = false;
std::vector<TraceHeaderKey> gather_keys = {TraceHeaderKey::FLDR};
std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> sorting_keys;
std::vector<std::string> paths = {DATA_PATH "/shots0601_0800.segy",
DATA_PATH "/vel_z6.25m_x12.5m_exact.segy"};
SegyReader r(new JSONConfigurationMap(read_configuration));
r.AcquireConfiguration();
r.Initialize(gather_keys, sorting_keys, paths);
ExecutionTimer::Evaluate([&]() {
r.ReadAll();
}, true);
/*
* Writing SEG-Y file.
*/
json write_configuration;
write_configuration[IO_K_PROPERTIES][IO_K_WRITE_LITTLE_ENDIAN] = false;
std::string path = WRITE_PATH "/result";
std::vector<Gather *> gathers;
SegyWriter w(new JSONConfigurationMap(write_configuration));
w.AcquireConfiguration();
w.Initialize(path);
/* Get gather number */
std::cout << std::endl << "Normal writing case:" << std::endl;
ExecutionTimer::Evaluate([&]() {
w.Write(gathers);
}, true);
/* Finalize and closes all opened internal streams. */
w.Finalize();
}
| 2,752
|
C++
|
.cpp
| 68
| 36.279412
| 81
| 0.708927
|
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,184
|
main.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/examples/segy-to-image/main.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <sys/stat.h>
#include <prerequisites/libraries/nlohmann/json.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <bs/io/api/cpp/BSIO.hpp>
#include <bs/io/utils/timer/ExecutionTimer.hpp>
using namespace std;
using json = nlohmann::json;
using namespace bs::base::configurations;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::io::utils::timer;
int main(int argc, char *argv[]) {
mkdir(WRITE_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
json configuration_map;
configuration_map[IO_K_PROPERTIES][IO_K_TEXT_HEADERS_ONLY] = false;
configuration_map[IO_K_PROPERTIES][IO_K_TEXT_HEADERS_STORE] = false;
std::vector<TraceHeaderKey> gather_keys = {TraceHeaderKey::FLDR};
std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> sorting_keys;
std::vector<std::string> paths = {DATA_PATH "/vel_z6.25m_x12.5m_exact.segy",};
SeismicReader sr(
SeismicReader::ToReaderType("segy"),
new JSONConfigurationMap(configuration_map));
sr.AcquireConfiguration();
/* Initializing + Indexing. */
std::cout << std::endl << "Initializing + Indexing:" << std::endl;
ExecutionTimer::Evaluate([&]() {
sr.Initialize(gather_keys, sorting_keys, paths);
}, true);
/* Normal case. */
vector<Gather *> gathers;
std::cout << std::endl << "Normal reading case:" << std::endl;
ExecutionTimer::Evaluate([&]() {
gathers = sr.ReadAll();
}, true);
/* Finalize and closes all opened internal streams. */
sr.Finalize();
/* Image writer. */
json configuration_map_writer;
configuration_map_writer[IO_K_PROPERTIES][IO_K_PERCENTILE] = 98.5;
SeismicWriter iw(
SeismicWriter::ToWriterType("image"),
new JSONConfigurationMap(configuration_map_writer));
iw.AcquireConfiguration();
/* Initializing. */
std::string path = WRITE_PATH "/velocity";
iw.Initialize(path);
/* Normal case. */
std::cout << std::endl << "Normal writing case:" << std::endl;
ExecutionTimer::Evaluate([&]() {
iw.Write(gathers);
}, true);
/* Finalize and closes all opened internal streams. */
iw.Finalize();
}
| 2,996
|
C++
|
.cpp
| 73
| 36.69863
| 82
| 0.694559
|
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,185
|
main.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/examples/indexer/main.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/utils/timer/ExecutionTimer.hpp>
#include <bs/io/indexers/FileIndexer.hpp>
#include <bs/io/indexers/IndexMap.hpp>
using namespace std;
using namespace bs::io::indexers;
using namespace bs::io::dataunits;
using namespace bs::io::utils::timer;
int main(int argc, char *argv[]) {
vector<TraceHeaderKey> vec = {TraceHeaderKey::FLDR};
string file_path = DATA_PATH "/shots0601_0800.segy";
std::string key = "FLDR";
FileIndexer fi(file_path, key);
fi.Initialize();
ExecutionTimer::Evaluate([&]() {
fi.Index(vec);
}, true);
}
| 1,330
|
C++
|
.cpp
| 36
| 34.277778
| 73
| 0.729604
|
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,186
|
main.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/examples/segy-indexing/main.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <sys/stat.h>
#include <prerequisites/libraries/nlohmann/json.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <bs/io/api/cpp/BSIO.hpp>
#include <bs/io/utils/timer/ExecutionTimer.hpp>
using namespace std;
using json = nlohmann::json;
using namespace bs::base::configurations;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::io::utils::timer;
int main(int argc, char *argv[]) {
mkdir(WRITE_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
json configuration_map;
configuration_map[IO_K_PROPERTIES][IO_K_TEXT_HEADERS_ONLY] = false;
configuration_map[IO_K_PROPERTIES][IO_K_TEXT_HEADERS_STORE] = false;
std::vector<TraceHeaderKey> gather_keys = {TraceHeaderKey::FLDR};
std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> sorting_keys;
std::vector<std::string> paths = {DATA_PATH "/shots0601_0800.segy",
DATA_PATH "/vel_z6.25m_x12.5m_exact.segy"};
SeismicReader r(SeismicReader::ToReaderType("segy"),
new JSONConfigurationMap(configuration_map));
r.AcquireConfiguration();
/* Initializing + Indexing. */
std::cout << std::endl << "Initializing + Indexing:" << std::endl;
ExecutionTimer::Evaluate([&]() {
r.Initialize(gather_keys, sorting_keys, paths);
}, true);
/* Normal case. */
std::cout << std::endl << "Normal reading case [1]:" << std::endl;
ExecutionTimer::Evaluate([&]() {
r.Read({"604"});
}, true);
/* Normal case. */
std::cout << std::endl << "Normal reading case [2]:" << std::endl;
ExecutionTimer::Evaluate([&]() {
vector<string> vec = {"729"};
r.Read(vec);
}, true);
/* Not available case. */
std::cout << std::endl << "Not available reading case:" << std::endl;
ExecutionTimer::Evaluate([&]() {
vector<string> vec = {"6329"};
r.Read(vec);
}, true);
/* Get gather number */
std::cout << std::endl << "Get gather number case:" << std::endl;
unsigned int num;
ExecutionTimer::Evaluate([&]() {
num = r.GetNumberOfGathers();
}, true);
std::cout << "Number of gathers : " << num << std::endl;
/* Get gather number */
std::cout << std::endl << "Get gather number case:" << std::endl;
std::vector<std::vector<std::string>> keys;
ExecutionTimer::Evaluate([&]() {
keys = r.GetIdentifiers();
}, true);
std::cout << "Number of gathers : " << keys.size() << std::endl;
/* Finalize and closes all opened internal streams. */
r.Finalize();
}
| 3,374
|
C++
|
.cpp
| 81
| 36.790123
| 81
| 0.655267
|
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,187
|
main.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/mains/Sorter/main.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/nlohmann/json.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <bs/io/api/cpp/BSIO.hpp>
#include <bs/io/utils/convertors/KeysConvertor.hpp>
#include <bs/io/utils/timer/ExecutionTimer.hpp>
using namespace std;
using json = nlohmann::json;
using namespace bs::base::configurations;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::io::utils::timer;
bool sortvector(const vector<long long int> &v1, const vector<long long int> &v2) {
for (int i = 0; i < v1.size(); i++) {
if (v1[i] < v2[i]) {
return true;
}
}
return false;
}
int main(int argc, char *argv[]) {
if (argc < 7) {
std::cout << "Invalid number of parameters..." << std::endl;
std::cout << "Expected command : Sorter "
"<input_format> <input_path> <input_configuration> "
"<output_format> <output_path> <output_configuration> "
"<gather_key_1, gather_key_2,...> <+sort_key_1,-sort_key_2,...>"
<< std::endl;
exit(0);
}
std::string input_format = argv[1];
std::string input_path = argv[2];
std::string input_configuration = argv[3];
std::string output_format = argv[4];
std::string output_path = argv[5];
std::string output_configuration = argv[6];
string intermediate;
std::vector<TraceHeaderKey> gather_keys;
std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> sorting_keys;
if (argc >= 8) {
stringstream gathers_string(argv[7]);
while (getline(gathers_string, intermediate, ',')) {
gather_keys.push_back(bs::io::utils::convertors::KeysConvertor::ToTraceHeaderKey(intermediate));
}
} else {
gather_keys.emplace_back(TraceHeaderKey::FLDR);
}
if (argc >= 9) {
stringstream sorting_keys_string(argv[8]);
while (getline(sorting_keys_string, intermediate, ',')) {
auto sort_direction = bs::io::dataunits::Gather::SortDirection::ASC;
if (intermediate[0] == '-' || intermediate[0] == '+') {
if (intermediate[0] == '-') {
sort_direction = bs::io::dataunits::Gather::SortDirection::DES;
}
intermediate = intermediate.substr(1);
}
auto p = std::make_pair(bs::io::utils::convertors::KeysConvertor::ToTraceHeaderKey(intermediate),
sort_direction);
sorting_keys.push_back(p);
}
} else {
auto p = std::make_pair(TraceHeaderKey::FLDR, bs::io::dataunits::Gather::SortDirection::ASC);
sorting_keys.emplace_back(p);
}
std::ifstream fin(input_configuration);
json configuration_map;
fin >> configuration_map;
fin.close();
stringstream paths_keys_string(input_path);
std::vector<std::string> paths;
while (getline(paths_keys_string, intermediate, ',')) {
paths.push_back(intermediate);
}
SeismicReader sr(
SeismicReader::ToReaderType(input_format),
new JSONConfigurationMap(configuration_map));
sr.AcquireConfiguration();
json configuration_map_writer;
std::ifstream fin2(output_configuration);
fin2 >> configuration_map_writer;
fin2.close();
SeismicWriter iw(
SeismicWriter::ToWriterType(output_format),
new JSONConfigurationMap(configuration_map_writer));
iw.AcquireConfiguration();
/* Initializing. */
std::string path = output_path;
iw.Initialize(path);
/* Initializing + Indexing. */
std::cout << std::endl << "Initializing + Indexing:" << std::endl;
ExecutionTimer::Evaluate([&]() {
sr.Initialize(gather_keys, sorting_keys, paths);
}, true);
/* Normal case. */
std::vector<std::vector<std::string>> unique_values;
std::cout << std::endl << "Get unique identifiers:" << std::endl;
ExecutionTimer::Evaluate([&]() {
unique_values = sr.GetIdentifiers();
}, true);
std::vector<std::vector<long long int>> unique_values_to_be_sorted;
std::cout << std::endl << "Casting unique identifiers(string to double):" << std::endl;
ExecutionTimer::Evaluate([&]() {
for (const auto &unique_value : unique_values) {
std::vector<long long int> doubles;
doubles.reserve(unique_value.size());
for (const auto &temp: unique_value) {
doubles.push_back(std::stod(temp));
}
unique_values_to_be_sorted.push_back(doubles);
}
}, true);
std::cout << std::endl << "Sorting unique identifiers:" << std::endl;
ExecutionTimer::Evaluate([&]() {
std::sort(unique_values_to_be_sorted.begin(),
unique_values_to_be_sorted.end(), sortvector);
}, true);
Gather *gather;
unique_values.clear();
std::cout << std::endl << "Casting unique identifiers(double to string):" << std::endl;
ExecutionTimer::Evaluate([&]() {
for (const auto &unique_value : unique_values_to_be_sorted) {
std::vector<std::string> strings;
strings.reserve(unique_value.size());
for (const auto &temp: unique_value) {
strings.push_back(to_string(temp));
}
unique_values.push_back(strings);
}
}, true);
std::cout << std::endl << "Reading, Sorting, & writing sorted gathers:" << std::endl;
long read_microseconds = 0;
long write_microseconds = 0;
long sort_microseconds = 0;
ExecutionTimer::Evaluate([&]() {
for (const auto &value: unique_values) {
read_microseconds += ExecutionTimer::Evaluate([&]() {
gather = sr.Read(value);
}, false);
sort_microseconds += ExecutionTimer::Evaluate([&]() {
gather->SortGather(sorting_keys);
}, false);
write_microseconds += ExecutionTimer::Evaluate([&]() {
iw.Write(gather);
}, false);
delete gather;
}
}, true);
std::cout << "Read Time : " << (read_microseconds / (1e6f)) << " SEC" << std::endl;
std::cout << "Sort Time : " << (sort_microseconds / (1e6f)) << " SEC" << std::endl;
std::cout << "Write Time : " << (write_microseconds / (1e6f)) << " SEC" << std::endl;
/* Finalize and closes all opened internal streams. */
std::cout << std::endl << "Finalizing Reader:" << std::endl;
ExecutionTimer::Evaluate([&]() {
sr.Finalize();
}, true);
/* Finalize and closes all opened internal streams. */
std::cout << std::endl << "Finalizing Reader:" << std::endl;
ExecutionTimer::Evaluate([&]() {
iw.Finalize();
}, true);
return 0;
}
| 7,571
|
C++
|
.cpp
| 181
| 34.287293
| 109
| 0.612877
|
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,188
|
main.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/mains/ReaderMetrics/main.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/nlohmann/json.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <bs/io/api/cpp/BSIO.hpp>
#include <bs/io/utils/timer/ExecutionTimer.hpp>
#include <bs/io/utils/convertors/KeysConvertor.hpp>
using namespace std;
using json = nlohmann::json;
using namespace bs::base::configurations;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::io::utils::timer;
int main(int argc, char *argv[]) {
if (argc < 4) {
std::cout << "Invalid number of parameters..." << std::endl;
std::cout << "Expected command : ReaderMetrics "
"<input_format> <input_path> <input_configuration> <gather_key_1,gather_key_2> "
<< std::endl;
exit(0);
}
std::string input_format = argv[1];
std::string input_path = argv[2];
std::string input_configuration = argv[3];
std::ifstream fin(input_configuration);
json configuration_map;
fin >> configuration_map;
fin.close();
string intermediate;
std::vector<TraceHeaderKey> gather_keys;
if (argc >= 5) {
stringstream gathers_string(argv[4]);
while (getline(gathers_string, intermediate, ',')) {
gather_keys.push_back(bs::io::utils::convertors::KeysConvertor::ToTraceHeaderKey(intermediate));
}
} else {
gather_keys.emplace_back(TraceHeaderKey::FLDR);
}
std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> sorting_keys;
stringstream paths_keys_string(input_path);
std::vector<std::string> paths;
while (getline(paths_keys_string, intermediate, ',')) {
paths.push_back(intermediate);
}
SeismicReader sr(
SeismicReader::ToReaderType(input_format),
new JSONConfigurationMap(configuration_map));
sr.AcquireConfiguration();
/* Initializing + Indexing. */
std::cout << std::endl << "Initializing + Indexing:" << std::endl;
ExecutionTimer::Evaluate([&]() {
sr.Initialize(gather_keys, sorting_keys, paths);
}, true);
std::vector<std::vector<std::string>> unique_identifiers;
std::cout << std::endl << "Getting unique identifiers:" << std::endl;
ExecutionTimer::Evaluate([&]() {
unique_identifiers = sr.GetIdentifiers();
}, true);
/** Read only one shot that exists */
Gather *gather;
std::vector<std::string> unique_values;
unique_values.emplace_back("0");
std::cout << std::endl << "Read one non existing shot: " << std::endl;
ExecutionTimer::Evaluate([&]() {
gather = sr.Read(unique_values);
if (gather != nullptr && gather->GetNumberTraces() > 0) {
std::cout << std::endl << "A gather has been read!!!" << std::endl;
}
}, true);
delete gather;
if (!unique_identifiers.empty()) {
unique_values = unique_identifiers[unique_identifiers.size() / 2];
std::cout << std::endl << "Read one existing shot: " << std::endl;
ExecutionTimer::Evaluate([&]() {
gather = sr.Read(unique_values);
}, true);
delete gather;
}
if (unique_identifiers.size() > 9) {
std::cout << std::endl << "Window ten shots : " << std::endl;
vector<Gather *> gathers;
std::vector<std::vector<std::string>> window_headers;
unsigned long starting_index = unique_identifiers.size() / 2 - 5;
window_headers.reserve(10);
for (int i = 0; i < 10; i++) {
window_headers.push_back(unique_identifiers[starting_index + i]);
}
ExecutionTimer::Evaluate([&]() {
gathers = sr.Read(window_headers);
}, true);
}
if (unique_identifiers.size() > 99) {
vector<Gather *> gathers;
std::vector<std::vector<std::string>> window_headers;
unsigned long starting_index = unique_identifiers.size() / 2 - 50;
window_headers.reserve(100);
for (int i = 0; i < 100; i++) {
window_headers.push_back(unique_identifiers[starting_index + i]);
}
std::cout << std::endl << "Window hundred shots : " << std::endl;
ExecutionTimer::Evaluate([&]() {
gathers = sr.Read(window_headers);
}, true);
}
/* Finalize and closes all opened internal streams. */
std::cout << std::endl << "Finalizing Reader:" << std::endl;
ExecutionTimer::Evaluate([&]() {
sr.Finalize();
}, true);
return 0;
}
| 5,231
|
C++
|
.cpp
| 128
| 34.601563
| 108
| 0.63767
|
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,189
|
main.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/mains/Converter/main.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/nlohmann/json.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <bs/io/api/cpp/BSIO.hpp>
#include <bs/io/utils/timer/ExecutionTimer.hpp>
using namespace std;
using json = nlohmann::json;
using namespace bs::base::configurations;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::io::utils::timer;
int main(int argc, char *argv[]) {
if (argc < 7) {
std::cout << "Invalid number of parameters..." << std::endl;
std::cout << "Expected command : Converter "
"<input_format> <input_path> <input_configuration> "
"<output_format> <output_path> <output_configuration> <batch_size-optional>"
<< std::endl;
exit(0);
}
std::string input_format = argv[1];
std::string input_path = argv[2];
std::string input_configuration = argv[3];
std::string output_format = argv[4];
std::string output_path = argv[5];
std::string output_configuration = argv[6];
unsigned int batch_size = 1;
if (argc > 7) {
batch_size = stoi(argv[7]);
}
if (batch_size < 1) {
std::cout << "Batch size must be larger than 0..." << std::endl;
exit(0);
}
std::ifstream fin(input_configuration);
json configuration_map;
fin >> configuration_map;
fin.close();
std::vector<TraceHeaderKey> gather_keys = {TraceHeaderKey::FLDR};
std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> sorting_keys;
/** from command line */
stringstream paths_keys_string(input_path);
std::string intermediate;
std::vector<std::string> paths;
while (getline(paths_keys_string, intermediate, ',')) {
paths.push_back(intermediate);
}
/** from command line */
SeismicReader sr(
SeismicReader::ToReaderType(input_format),
new JSONConfigurationMap(configuration_map));
sr.AcquireConfiguration();
json configuration_map_writer;
std::ifstream fin2(output_configuration);
fin2 >> configuration_map_writer;
fin2.close();
/** From command line */
SeismicWriter iw(
SeismicWriter::ToWriterType(output_format),
new JSONConfigurationMap(configuration_map_writer));
iw.AcquireConfiguration();
/** From command line */
/* Initializing. */
std::string path = output_path;
iw.Initialize(path);
/* Initializing + Indexing. */
std::cout << std::endl << "Initializing + Indexing:" << std::endl;
ExecutionTimer::Evaluate([&]() {
sr.Initialize(gather_keys, sorting_keys, paths);
}, true);
/* Get number of gathers */
unsigned int num_of_gathers;
std::cout << std::endl << "Number of gathers:" << std::endl;
ExecutionTimer::Evaluate([&]() {
num_of_gathers = sr.GetNumberOfGathers();
}, true);
std::cout << "Number of gathers: " << num_of_gathers << std::endl;
std::vector<Gather *> gathers;
std::cout << std::endl << "Conversion:" << std::endl;
long read_microseconds = 0;
long write_microseconds = 0;
ExecutionTimer::Evaluate([&]() {
for (unsigned int i = 0; i < num_of_gathers; i += batch_size) {
int actual_batch_size = std::min(batch_size, num_of_gathers - i);
read_microseconds += ExecutionTimer::Evaluate([&]() {
for (unsigned int j = 0; j < actual_batch_size; j++) {
gathers.push_back(sr.Read(i));
}
}, false);
write_microseconds += ExecutionTimer::Evaluate([&]() {
iw.Write(gathers);
}, false);
for (auto gather : gathers) {
delete gather;
}
gathers.clear();
}
}, true);
std::cout << "Conversion Read Time : " << (read_microseconds / (1e6f)) << " SEC" << std::endl;
std::cout << "Conversion Write Time : " << (write_microseconds / (1e6f)) << " SEC" << std::endl;
/* Finalize and closes all opened internal streams. */
std::cout << std::endl << "Finalizing Reader:" << std::endl;
ExecutionTimer::Evaluate([&]() {
sr.Finalize();
}, true);
/* Finalize and closes all opened internal streams. */
std::cout << std::endl << "Finalizing Reader:" << std::endl;
ExecutionTimer::Evaluate([&]() {
iw.Finalize();
}, true);
return 0;
}
| 5,179
|
C++
|
.cpp
| 130
| 33.530769
| 100
| 0.628975
|
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,190
|
TestSeismic.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/streams/concrete/TestSeismic.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <sys/stat.h>
#include <prerequisites/libraries/catch/catch.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <bs/io/streams/concrete/readers/SeismicReader.hpp>
#include <bs/io/streams/concrete/writers/SeismicWriter.hpp>
#include <bs/io/data-units/concrete/Gather.hpp>
#include <bs/io/configurations/MapKeys.h>
#include <bs/io/test-utils/DataGenerator.hpp>
using namespace std;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::base::configurations;
using namespace bs::io::testutils;
using json = nlohmann::json;
void
TEST_SEISMIC_FORMAT() {
/* Create tests results directory. */
string dir(IO_TESTS_RESULTS_PATH);
mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
json node;
node[IO_K_PROPERTIES][IO_K_WRITE_LITTLE_ENDIAN] = false;
node[IO_K_PROPERTIES][IO_K_FLOAT_FORMAT] = 1;
node[IO_K_PROPERTIES][IO_K_TEXT_HEADERS_ONLY] = false;
node[IO_K_PROPERTIES][IO_K_TEXT_HEADERS_STORE] = false;
vector<Gather *> gathers;
Gather *gather1 = DataGenerator::GenerateGather(1, 10, 1);
gathers.push_back(gather1);
Gather *gather2 = DataGenerator::GenerateGather(1, 10, 10);
gathers.push_back(gather2);
int traces_before = 20;
JSONConfigurationMap writer_map = JSONConfigurationMap(node);
/* SEG-Y Writer. */
SeismicWriter w1(WriterType::SEGY, &writer_map);
w1.AcquireConfiguration();
string file_path_segy(IO_TESTS_RESULTS_PATH "/SEGYFile");
w1.Initialize(file_path_segy);
REQUIRE(w1.Write(gathers) == 0);
w1.Finalize();
/* SU Writer. */
SeismicWriter w2(WriterType::SU, &writer_map);
w2.AcquireConfiguration();
string file_path_su("SUFile");
w2.Initialize(file_path_su);
REQUIRE(w2.Write(gathers) == 0);
w2.Finalize();
/* SEG-Y Reader. */
SeismicReader r1(ReaderType::SEGY, &writer_map);
r1.AcquireConfiguration();
vector<TraceHeaderKey> keys = {TraceHeaderKey::FLDR};
pair<TraceHeaderKey, bs::io::dataunits::Gather::SortDirection> p1(TraceHeaderKey::FLDR,
bs::io::dataunits::Gather::SortDirection::ASC);
vector<pair<TraceHeaderKey, bs::io::dataunits::Gather::SortDirection>> sort_keys = {p1};
vector<string> write_paths = {file_path_segy + ".segy"};
r1.Initialize(keys, sort_keys, write_paths);
vector<Gather *> read_gathers1 = r1.ReadAll();
size_t traces_after = 0;
for (auto &g : read_gathers1) {
traces_after += g->GetNumberTraces();
}
REQUIRE(traces_before == traces_after);
REQUIRE(read_gathers1.size() == 19);
REQUIRE(SeismicWriter::ToString(WriterType::BINARY) == "binary");
REQUIRE(SeismicReader::ToReaderType("json") == ReaderType::JSON);
/* JSON Reader. */
SeismicReader r2(ReaderType::JSON, nullptr);
vector<string> read_paths = {IO_TESTS_WORKLOADS_PATH "synthetic_velocity.json"};
r2.Initialize(keys, sort_keys, read_paths);
vector<Gather *> read_gathers2 = r2.ReadAll();
REQUIRE(read_gathers2.size() == 1);
REQUIRE(read_gathers2[0]->GetNumberTraces() == 500);
}
/**
* REQUIRED TESTS:
*
* N.B. This test shall test both SeismicWriter and SeismicReader.
*
* 1. Dummy gather to be generated and written to files with all supported formats and then shall be read
* using the SeismicReader and output gather shall then be compared against the formerly generated one.
* The provided reader types should be all the supported ones, having an iterator to iterate upon all
* to assure all readers follow the same pattern.
*
* 2. All functions individually to return desired output in same test case yet different sections,
* also different permutations of configuration map shall be used to assure correct variations.
*
* 3. RC values to be tested and required against its ground truth
* (i.e. both failure and success cases shall be tested)
*/
TEST_CASE("Seismic Format Test") {
TEST_SEISMIC_FORMAT();
}
| 4,769
|
C++
|
.cpp
| 108
| 39.916667
| 117
| 0.712497
|
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,191
|
TestSegy.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/streams/concrete/TestSegy.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <sys/stat.h>
#include <prerequisites/libraries/catch/catch.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <bs/io/streams/concrete/readers/SegyReader.hpp>
#include <bs/io/streams/concrete/writers/SegyWriter.hpp>
#include <bs/io/data-units/concrete/Gather.hpp>
#include <bs/io/configurations/MapKeys.h>
#include <bs/io/test-utils/DataGenerator.hpp>
using namespace std;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::io::testutils;
using namespace bs::base::configurations;
using json = nlohmann::json;
void
TEST_SEGY_FORMAT() {
/* Create tests results directory. */
string dir(IO_TESTS_RESULTS_PATH);
mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
json node;
node[IO_K_PROPERTIES][IO_K_WRITE_LITTLE_ENDIAN] = false;
node[IO_K_PROPERTIES][IO_K_FLOAT_FORMAT] = 1;
JSONConfigurationMap writer_map = JSONConfigurationMap(node);
vector<Gather *> gathers;
Gather *gather1 = DataGenerator::GenerateGather(1, 10, 1);
gathers.push_back(gather1);
Gather *gather2 = DataGenerator::GenerateGather(1, 10, 10);
gathers.push_back(gather2);
int traces_before = 20;
SegyWriter writer(&writer_map);
writer.AcquireConfiguration();
string file_path(IO_TESTS_RESULTS_PATH "/SEGYFile");
writer.Initialize(file_path);
REQUIRE(writer.Write(gathers) == 0);
writer.Finalize();
node[IO_K_PROPERTIES][IO_K_TEXT_HEADERS_ONLY] = false;
node[IO_K_PROPERTIES][IO_K_TEXT_HEADERS_STORE] = false;
JSONConfigurationMap reader_map = JSONConfigurationMap(node);
SegyReader reader(&reader_map);
reader.AcquireConfiguration();
vector<TraceHeaderKey> keys = {TraceHeaderKey::FLDR};
pair<TraceHeaderKey, Gather::SortDirection> p1(TraceHeaderKey::FLDR,
Gather::SortDirection::ASC);
vector<pair<TraceHeaderKey, Gather::SortDirection>> sort_keys = {p1};
vector<string> paths = {file_path + ".segy"};
reader.Initialize(keys, sort_keys, paths);
vector<Gather *> read_gathers = reader.ReadAll();
size_t traces_after = 0;
for (auto g : read_gathers) {
traces_after += g->GetNumberTraces();
}
REQUIRE(traces_before == traces_after);
REQUIRE(read_gathers.size() == 19);
vector<vector<string>> header_values;
vector<string> g1 = {"10"};
vector<string> g2 = {"9"};
header_values.push_back(g1);
header_values.push_back(g2);
vector<Gather *> read_gathers2 = reader.Read(header_values);
REQUIRE(read_gathers2.size() == 2);
traces_after = 0;
for (auto g: read_gathers2) {
traces_after += g->GetNumberTraces();
}
REQUIRE(traces_after == 3);
vector<vector<string>> ids = reader.GetIdentifiers();
REQUIRE(ids.size() == 19);
Gather *temp = reader.Read(0);
REQUIRE(temp->GetNumberTraces() == 2);
reader.Finalize();
}
/**
* REQUIRED TESTS:
*
* N.B. This test shall test both SegyWriter and SegyReader.
*
* 1. Dummy gather to be generated and written to a file with a *.segy format and then shall be read
* using the SegyReader and output gather shall then be compared against the formerly generated one.
*
* 2. All functions individually to return desired output in same test case yet different sections,
* also different permutations of configuration map shall be used to assure correct variations.
*
* 3. RC values to be tested and required against its ground truth
* (i.e. both failure and success cases shall be tested)
*/
TEST_CASE("Segy Format Test") {
TEST_SEGY_FORMAT();
}
| 4,371
|
C++
|
.cpp
| 106
| 37.113208
| 103
| 0.711253
|
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,192
|
TestSU.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/streams/concrete/TestSU.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <sys/stat.h>
#include <prerequisites/libraries/catch/catch.hpp>
#include <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <bs/io/streams/concrete/readers/SUReader.hpp>
#include <bs/io/streams/concrete/writers/SUWriter.hpp>
#include <bs/io/data-units/concrete/Gather.hpp>
#include <bs/io/configurations/MapKeys.h>
#include <bs/io/test-utils/DataGenerator.hpp>
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::base::configurations;
using namespace bs::io::testutils;
using json = nlohmann::json;
using std::vector;
void
TEST_SU_FORMAT() {
/* Create tests results directory. */
std::string dir(IO_TESTS_RESULTS_PATH);
mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
SECTION("Write Big Endian") {
json node;
node[IO_K_PROPERTIES][IO_K_WRITE_LITTLE_ENDIAN] = false;
node[IO_K_PROPERTIES][IO_K_WRITE_PATH] = std::string(IO_TESTS_RESULTS_PATH);
JSONConfigurationMap map = JSONConfigurationMap(node);
vector<Gather *> gathers;
Gather *gather1 = DataGenerator::GenerateGather(0, 10, 1);
gathers.push_back(gather1);
Gather *gather2 = DataGenerator::GenerateGather(0, 10, 10);
gathers.push_back(gather2);
SUWriter w(&map);
w.AcquireConfiguration();
std::string filePath("SUFile");
w.Initialize(filePath);
REQUIRE(w.Write(gathers) == 0);
w.Finalize();
}
SECTION("Write Little Endian") {
json node;
node[IO_K_PROPERTIES][IO_K_WRITE_LITTLE_ENDIAN] = true;
node[IO_K_PROPERTIES][IO_K_WRITE_PATH] = std::string(IO_TESTS_RESULTS_PATH);
JSONConfigurationMap map = JSONConfigurationMap(node);
vector<Gather *> gathers;
Gather *gather1 = DataGenerator::GenerateGather(0, 10, 1);
gathers.push_back(gather1);
Gather *gather2 = DataGenerator::GenerateGather(0, 10, 10);
gathers.push_back(gather2);
SUWriter w(&map);
w.AcquireConfiguration();
std::string filePath("SUFile");
w.Initialize(filePath);
REQUIRE(w.Write(gathers) == 0);
w.Finalize();
}
}
/**
* REQUIRED TESTS:
*
* N.B. This test shall test both SUWriter and SUReader.
*
* 1. Dummy gather to be generated and written to a file with a *.su format and then shall be read
* using the SegyReader and output gather shall then be compared against the formerly generated one.
*
* 2. All functions individually to return desired output in same test case yet different sections,
* also different permutations of configuration map shall be used to assure correct variations.
*
* 3. RC values to be tested and required against its ground truth
* (i.e. both failure and success cases shall be tested)
*/
TEST_CASE("SU Format Test") {
TEST_SU_FORMAT();
}
| 3,605
|
C++
|
.cpp
| 89
| 35.876404
| 103
| 0.70329
|
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,193
|
TestJson.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/streams/concrete/TestJson.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <bs/base/configurations/concrete/JSONConfigurationMap.hpp>
#include <bs/io/streams/concrete/readers/JsonReader.hpp>
#include <bs/io/data-units/concrete/Gather.hpp>
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::base::configurations;
using json = nlohmann::json;
using std::vector;
using std::pair;
void
TEST_JSON() {
JsonReader r(nullptr);
vector<TraceHeaderKey> keys = {TraceHeaderKey::FLDR};
pair<TraceHeaderKey, Gather::SortDirection> p1(TraceHeaderKey::FLDR,
Gather::SortDirection::ASC);
vector<pair<TraceHeaderKey, Gather::SortDirection>> sort_keys = {p1};
vector<std::string> paths = {IO_TESTS_WORKLOADS_PATH "/synthetic_velocity.json"};
r.Initialize(keys, sort_keys, paths);
vector<Gather *> read_gathers = r.ReadAll();
REQUIRE(read_gathers.size() == 1);
REQUIRE(read_gathers[0]->GetNumberTraces() == 500);
vector<vector<std::string>> ids = r.GetIdentifiers();
vector<vector<std::string>> header_values;
vector<std::string> g1 = {"1"};
vector<std::string> g2 = {"9"};
header_values.push_back(g1);
header_values.push_back(g2);
vector<Gather *> read_gathers2 = r.Read(header_values);
REQUIRE(read_gathers2.size() == 1);
REQUIRE(read_gathers2[0]->GetNumberTraces() == 500);
Gather *temp = r.Read(0);
REQUIRE(temp->GetNumberTraces() == 500);
r.Finalize();
}
/**
* REQUIRED TESTS:
*
* N.B. This test shall test only JsonReader.
*
* 1. Dummy json map to be generated that describe a desired output model and the create it's gather
* object that reflects to that map.
*
* 2. All functions individually to return desired output in same test case yet different sections,
* also different permutations of configuration map shall be used to assure correct variations.
*
* 3. RC values to be tested and required against its ground truth
* (i.e. both failure and success cases shall be tested)
*/
TEST_CASE("JsonReader") {
TEST_JSON();
}
| 2,864
|
C++
|
.cpp
| 71
| 36.732394
| 100
| 0.71552
|
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,194
|
TestTraceHeader.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/data-units/data-types/TestTraceHeader.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/data-units/data-types/TraceHeaderKey.hpp>
using namespace std;
using namespace bs::io::dataunits;
void
TEST_TRACE_HDR() {
SECTION("Constructor") {
TraceHeaderKey hdr(TraceHeaderKey::Key::FLDR);
REQUIRE(hdr.GetKey() == TraceHeaderKey::Key::FLDR);
}
SECTION("Copy Constructor") {
TraceHeaderKey hdr(2);
REQUIRE(hdr.GetKey() == TraceHeaderKey::Key::FLDR);
}
SECTION("Logical Operators") {
TraceHeaderKey hdr1(TraceHeaderKey::Key::FLDR);
TraceHeaderKey hdr2(2);
TraceHeaderKey hdr3(TraceHeaderKey::Key::TRACL);
REQUIRE(hdr1 == hdr2);
REQUIRE(hdr1 != hdr3);
REQUIRE(hdr1 > hdr3);
REQUIRE(hdr3 < hdr1);
}
SECTION("To String") {
TraceHeaderKey hdr1(TraceHeaderKey::Key::FLDR);
TraceHeaderKey hdr2(TraceHeaderKey::Key::TRACL);
vector<TraceHeaderKey> keys;
keys.push_back(hdr1);
keys.push_back(hdr2);
REQUIRE(TraceHeaderKey::GatherKeysToString(keys) == "FLDR_TRACL_");
vector<string> values;
values.emplace_back("1");
values.emplace_back("10");
REQUIRE(TraceHeaderKey::GatherValuesToString(values) == "1_10_");
vector<string> res = TraceHeaderKey::StringToGatherValues("1_10_");
REQUIRE(res[0] == "1");
REQUIRE(res[1] == "10");
REQUIRE(hdr1.ToString() == "FLDR");
}
}
/**
* REQUIRED TESTS:
* 1. All functions individually to return desired output in same test case yet different sections.
* 2. Copy constructor to copy correctly.
* 3. Move constructor to move correctly.
* 4. Logical operators to compare correctly.
*/
TEST_CASE("TraceHeaderKey") {
TEST_TRACE_HDR();
}
| 2,518
|
C++
|
.cpp
| 68
| 32
| 99
| 0.683778
|
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,195
|
TestTrace.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/data-units/concrete/TestTrace.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <bs/io/data-units/concrete/Trace.hpp>
using namespace bs::io::dataunits;
void
TEST_TRACE() {
SECTION("Constructor") {
Trace t(10);
REQUIRE(t.GetTraceHeaderKeyValue<int>(TraceHeaderKey(TraceHeaderKey::Key::NS)) == 10);
}
SECTION("Move Constructor") {
Trace t(3);
auto ground_truth_data = (float *) malloc(3 * sizeof(float));
ground_truth_data[0] = 1.0;
ground_truth_data[1] = 2.3;
ground_truth_data[2] = 5.6;
t.SetTraceData(ground_truth_data);
Trace temp = std::move(t);
float *test_data = temp.GetTraceData();
REQUIRE(test_data[0] == ground_truth_data[0]);
REQUIRE(test_data[1] == ground_truth_data[1]);
REQUIRE(test_data[2] == ground_truth_data[2]);
}
SECTION("HasHeader") {
int ns = 3;
Trace t(ns);
REQUIRE(t.HasTraceHeader(TraceHeaderKey::NS));
/* FLDR is not set. */
REQUIRE(!t.HasTraceHeader(TraceHeaderKey::FLDR));
REQUIRE(t.GetNumberOfSamples() == ns);
/* Only NS header is set. */
REQUIRE(t.GetTraceHeaders()->size() == 1);
int fldr = 1;
t.SetTraceHeaderKeyValue(TraceHeaderKey::FLDR, fldr);
/* FLDR is now set. */
REQUIRE(t.HasTraceHeader(TraceHeaderKey::FLDR));
/* FLDR and NS header are now set. */
REQUIRE(t.GetTraceHeaders()->size() == 2);
}
SECTION("Set_Scaled_Coordinate") {
Trace t(3);
float ground_truth_location = 2.0f;
t.SetScaledCoordinateHeader(TraceHeaderKey(TraceHeaderKey::SCALCO), ground_truth_location);
REQUIRE(t.GetTraceHeaderKeyValue<float>(TraceHeaderKey::SCALCO) == ground_truth_location);
}
}
/**
* REQUIRED TESTS:
*
* 1. All functions individually to return desired output in same test case yet different sections.
* 2. Data pointers to be tested that they are unique pointers.
* 3. Copy constructor to copy correctly.
* 4. Move constructor to move correctly.
* 5. Logical operators to compare correctly.
*/
TEST_CASE("TraceTest", "[Trace]") {
TEST_TRACE();
}
| 2,915
|
C++
|
.cpp
| 76
| 33.078947
| 99
| 0.669146
|
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,196
|
TestGather.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/data-units/concrete/TestGather.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/data-units/concrete/Gather.hpp>
#include <bs/io/test-utils/DataGenerator.hpp>
using namespace std;
using namespace bs::io::dataunits;
using namespace bs::io::testutils;
void
TEST_GATHER() {
vector<Trace *> traces = DataGenerator::GenerateTraceVector(0, 10, 1);
SECTION("Constructors") {
unordered_map<TraceHeaderKey, string> unique_keys;
unique_keys[TraceHeaderKey::NS] = "0";
Gather g1(unique_keys, traces);
REQUIRE(g1.GetNumberTraces() == 10);
REQUIRE(g1.GetUniqueKeyValue<int>(TraceHeaderKey::NS) == 0);
Gather g2(TraceHeaderKey::NS, "0", traces);
REQUIRE(g1.GetNumberTraces() == 10);
REQUIRE(g1.GetUniqueKeyValue<int>(TraceHeaderKey::NS) == 0);
Gather g3(unique_keys);
REQUIRE(g1.GetUniqueKeyValue<int>(TraceHeaderKey::NS) == 0);
}
SECTION("Add/Remove Trace") {
unordered_map<TraceHeaderKey, string> unique_keys;
unique_keys[TraceHeaderKey::NS] = "0";
Gather g(unique_keys, traces);
Trace trace(0);
Trace *t = &trace;
g.AddTrace(t);
REQUIRE(g.GetNumberTraces() == 11);
g.RemoveTrace(1);
REQUIRE(g.GetNumberTraces() == 10);
}
SECTION("Sorting") {
unordered_map<TraceHeaderKey, string> unique_keys;
unique_keys[TraceHeaderKey::NS] = "0";
Gather g(unique_keys, traces);
vector<pair<TraceHeaderKey, Gather::SortDirection>> sorting_keys = {
{TraceHeaderKey::FLDR, Gather::DES}
};
g.SortGather(sorting_keys);
vector<Trace *> all_traces = g.GetAllTraces();
int fldr = all_traces[0]->GetTraceHeaderKeyValue<int>(TraceHeaderKey::FLDR);
int temp;
for (auto t : all_traces) {
temp = t->GetTraceHeaderKeyValue<int>(TraceHeaderKey::FLDR);
REQUIRE(temp <= fldr);
fldr = temp;
}
}
}
/**
* REQUIRED TESTS:
*
* 1. All functions individually to return desired output in same test case yet different sections.
* 2. Copy constructor to copy correctly.
* 3. Move constructor to move correctly.
* 4. Logical operators to compare correctly.
*/
TEST_CASE("GatherTest", "[Gather]") {
TEST_GATHER();
}
| 3,028
|
C++
|
.cpp
| 79
| 32.721519
| 99
| 0.670985
|
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,197
|
TestTraceHelper.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/data-units/helpers/TestTraceHelper.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/data-units/helpers/TraceHelper.hpp>
#include <bs/io/utils/convertors/NumbersConvertor.hpp>
#include <bs/io/data-units/concrete/Trace.hpp>
#include <bs/io/test-utils/DataGenerator.hpp>
using namespace bs::io::lookups;
using namespace bs::io::dataunits;
using namespace bs::io::dataunits::helpers;
using namespace bs::io::testutils;
using namespace bs::io::utils::convertors;
void
TEST_TRACE_HELPER() {
Trace *trace;
TraceHeaderLookup thl{};
BinaryHeaderLookup bhl{};
SECTION("No Weighting Needed") {
int16_t format = 1;
int16_t trwf = 2;
bhl.FORMAT = NumbersConvertor::ToLittleEndian(format);; /* Converted to 2 in Little Endian Conversion. */
thl.TRWF = NumbersConvertor::ToLittleEndian(trwf);
trace = DataGenerator::GenerateTrace(10, 1);
float data[10];
memcpy(data, trace->GetTraceData(), 10 * sizeof(float));
TraceHelper::Weight(trace, thl, bhl);
REQUIRE(memcmp(data, trace->GetTraceData(), 10 * sizeof(float)) == 0);
}
SECTION("Weighting") {
int16_t format = 2;
int16_t trwf = 2;
bhl.FORMAT = NumbersConvertor::ToLittleEndian(format); /* Converted to 2 in Little Endian Conversion. */
thl.TRWF = NumbersConvertor::ToLittleEndian(trwf);
trace = DataGenerator::GenerateTrace(10, 1);
float data[10];
memcpy(data, trace->GetTraceData(), 10 * sizeof(float));
TraceHelper::Weight(trace, thl, bhl);
float *weighted = trace->GetTraceData();
for (int i = 0; i < 10; i++) {
REQUIRE(weighted[i] == data[i] * std::pow(2.0, -2));
}
REQUIRE(thl.TRWF == 0);
}
}
/**
* REQUIRED TESTS:
*
* 1. Dummy trace to be generated and then weighting to be applied upon
* it's data and headers and compare results to ground truth.
*/
TEST_CASE("TraceHelper") {
TEST_TRACE_HELPER();
}
| 2,692
|
C++
|
.cpp
| 69
| 34.463768
| 113
| 0.686447
|
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,198
|
TestNumbersConvertor.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/utils/convertors/TestNumbersConvertor.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/utils/convertors/NumbersConvertor.hpp>
using namespace bs::io::utils::convertors;
void
TEST_NUM_CONV() {
/**
* Please note that the comments in the NumbersConvertor.cpp file may have been copied incorrectly from the
* FloatingPointFormatter.cpp file
*/
SECTION("Short Int Little Endian") {
short int x = 258;
REQUIRE(NumbersConvertor::ToLittleEndian(x) == 513);
}
SECTION("Short Int Array Little Endian") {
short int x[] = {258, 257, -2};
short int *y = NumbersConvertor::ToLittleEndian(x, 3);
short int g[] = {513, 257, -257};
for (int i = 0; i < 3; i++) {
REQUIRE(y[i] == g[i]);
}
}
SECTION("Unsigned Short Int Little Endian") {
unsigned short int x = 258;
REQUIRE(NumbersConvertor::ToLittleEndian(x) == 513);
}
SECTION("Unsigned Short Int Array Little Endian") {
unsigned short int x[] = {258, 257, 256};
unsigned short int *y = NumbersConvertor::ToLittleEndian(x, 3);
unsigned short int g[] = {513, 257, 1};
for (int i = 0; i < 3; i++) {
REQUIRE(y[i] == g[i]);
}
}
SECTION("Int Little Endian") {
int x = 1074266625; // 2^0 + 2^9 + 2^19 + 2^30
REQUIRE(NumbersConvertor::ToLittleEndian(x) == 16910400);
}
SECTION("Int Array Little Endian") {
int x[] = {1, 256, -2};
int *y = NumbersConvertor::ToLittleEndian(x, 3);
int g[] = {16777216, 65536, -16777217};
for (int i = 0; i < 3; i++) {
REQUIRE(y[i] == g[i]);
}
}
SECTION("Unsigned Int Little Endian") {
unsigned int x = 1074266625; // 2^0 + 2^9 + 2^19 + 2^30
REQUIRE(NumbersConvertor::ToLittleEndian(x) == 16910400);
}
SECTION("Unsigned Int Array Little Endian") {
unsigned int x[] = {1, 256, 16777216};
unsigned int *y = NumbersConvertor::ToLittleEndian(x, 3);
unsigned int g[] = {16777216, 65536, 1};
for (int i = 0; i < 3; i++) {
REQUIRE(y[i] == g[i]);
}
}
SECTION("Float Little Endian") {
float x = 1.1;
auto g = (unsigned char *) &x;
float y = NumbersConvertor::ToLittleEndian(x);
auto p = (unsigned char *) &y;
for (int i = 0; i < sizeof(float); i++) {
REQUIRE(p[i] == g[sizeof(float) - i - 1]);
}
}
SECTION("Float Array Little Endian") {
float x[] = {1.1, 2.0, -3.1};
float temp[3];
memcpy(temp, x, 3 * sizeof(float));
unsigned char *g[3];
g[0] = (unsigned char *) &(x[0]);
g[1] = (unsigned char *) &(x[1]);
g[2] = (unsigned char *) &(x[2]);
float *y = NumbersConvertor::ToLittleEndian(temp, 3);
unsigned char *p[3];
p[0] = (unsigned char *) &(y[0]);
p[1] = (unsigned char *) &(y[1]);
p[2] = (unsigned char *) &(y[2]);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < sizeof(float); j++) {
REQUIRE(p[i][j] == g[i][sizeof(float) - j - 1]);
}
}
}
SECTION("Signed Char Little Endian") {
signed char x = 'O';
REQUIRE(NumbersConvertor::ToLittleEndian(x) == 'O');
}
SECTION("Signed Char Array Little Endian") {
signed char x[] = {'O', 'P', 'Q', 'R'};
signed char g[] = {'O', 'P', 'Q', 'R'};
signed char *y = NumbersConvertor::ToLittleEndian(x, 4);
for (int i = 0; i < 4; i++) {
REQUIRE(y[i] == g[i]);
}
}
SECTION("To Little Endian") {
int x[] = {1, 256, -2};
char *temp = (char *) x;
int g_int[] = {16777216, 65536, -16777217};
int *y_int = (int *) NumbersConvertor::ToLittleEndian(temp, 3, 1);
for (int i = 0; i < 3; i++) {
REQUIRE(y_int[i] == g_int[i]);
}
short int k = 258;
auto z = (short int *) NumbersConvertor::ToLittleEndian((char *) &k, 1, 0);
REQUIRE(*z == 258);
auto y_short = (short int *) NumbersConvertor::ToLittleEndian((char *) &k, 1, 3);
REQUIRE(*y_short == 513);
}
}
/**
* REQUIRED TESTS:
*
* N.B. This test shall test only NumbersConvertor.
*
* 1. All functions individually to return desired output in same test case yet different sections,
* also different permutations of configuration map shall be used to assure correct variations.
*
* 2. RC values -if any- to be tested and required against its ground truth
* (i.e. both failure and success cases shall be tested)
*/
TEST_CASE("Numbers Convertor") {
TEST_NUM_CONV();
}
| 5,456
|
C++
|
.cpp
| 144
| 31.104167
| 111
| 0.569347
|
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,199
|
TestFloatingPointFormatter.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/utils/convertors/TestFloatingPointFormatter.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/utils/convertors/FloatingPointFormatter.hpp>
#define IBM_EPS 4.7683738e-7 /* Worst case error */
using namespace bs::io::utils::convertors;
void
TEST_FLOAT_FORMAT() {
SECTION("Float Array Size") {
REQUIRE(FloatingPointFormatter::GetFloatArrayRealSize(4, 1) == 16);
REQUIRE(FloatingPointFormatter::GetFloatArrayRealSize(4, 2) == 16);
REQUIRE(FloatingPointFormatter::GetFloatArrayRealSize(4, 3) == 8);
REQUIRE(FloatingPointFormatter::GetFloatArrayRealSize(4, 8) == 4);
}
SECTION("To IBM") {
float src[2] = {0.23, 1.234567};
float dst[2];
FloatingPointFormatter::Format((char *) src, (char *) dst, 2 * sizeof(float), 2, 1, 0);
REQUIRE(dst[0] == 115316.500000);
REQUIRE(dst[1] == -1573480.125000);
}
SECTION("From IBM") {
float src[2] = {115316.500000, -1573480.125000};
float dst[2];
FloatingPointFormatter::Format((char *) src, (char *) dst, 2 * sizeof(float), 2, 1, 1);
REQUIRE(((dst[0] < 0.23 + IBM_EPS) && (dst[0] > 0.23 - IBM_EPS)));
REQUIRE(((dst[1] < 1.234567 + IBM_EPS) && (dst[1] > 1.234567 - IBM_EPS)));
}
}
/**
* REQUIRED TESTS:
*
* N.B. This test shall test only FloatingPointFormatter.
*
* 1. All functions individually to return desired output in same test case yet different sections,
* also different permutations of configuration map shall be used to assure correct variations.
*
* 2. RC values -if any- to be tested and required against its ground truth
* (i.e. both failure and success cases shall be tested)
*/
TEST_CASE("Floating Point Formatter") {
TEST_FLOAT_FORMAT();
}
| 2,460
|
C++
|
.cpp
| 59
| 37.661017
| 99
| 0.687317
|
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,200
|
TestKeysConvertor.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/utils/convertors/TestKeysConvertor.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <bs/io/utils/convertors/KeysConvertor.hpp>
using namespace bs::io::utils::convertors;
using namespace bs::io::dataunits;
using std::string;
void
TEST_KEY_CONV() {
SECTION("ToTraceHeaderKeyTest") {
string temp("FLDR");
REQUIRE(KeysConvertor::ToTraceHeaderKey(temp) == TraceHeaderKey::FLDR);
string temp1("ns");
REQUIRE(KeysConvertor::ToTraceHeaderKey(temp1) == TraceHeaderKey::NS);
string temp2("mInUtE");
REQUIRE(KeysConvertor::ToTraceHeaderKey(temp2) == TraceHeaderKey::MINUTE);
string temp3("foo");
REQUIRE_THROWS(KeysConvertor::ToTraceHeaderKey(temp3) != TraceHeaderKey::NS);
}
}
/**
* REQUIRED TESTS:
*
* N.B. This test shall test only KeysConvertor.
*
* 1. All functions individually to return desired output in same test case yet different sections,
* also different permutations of configuration map shall be used to assure correct variations.
*
* 2. RC values -if any- to be tested and required against its ground truth
* (i.e. both failure and success cases shall be tested)
*/
TEST_CASE("Keys Convertor") {
TEST_KEY_CONV();
}
| 1,953
|
C++
|
.cpp
| 51
| 35.058824
| 99
| 0.731888
|
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,201
|
TestStringsConvertor.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/utils/convertors/TestStringsConvertor.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <prerequisites/libraries/catch/catch.hpp>
#include <bs/io/utils/convertors/StringsConvertor.hpp>
using namespace bs::io::utils::convertors;
void TEST_CASE_STRING_CONV() {
const std::string s = "22";
SECTION("String to Unsigned Short") {
unsigned short t1 = 22;
REQUIRE(StringsConvertor::ToULong(s) == t1);
}
SECTION("String to Int") {
int t1 = 22;
REQUIRE(StringsConvertor::ToInt(s) == t1);
}
SECTION("String to Long") {
long t1 = 22;
REQUIRE(StringsConvertor::ToLong(s) == t1);
}
SECTION("String to Unsigned Long") {
unsigned long t1 = 22;
REQUIRE(StringsConvertor::ToULong(s) == t1);
}
SECTION("EBCDIC_TO_ASCII_CHAR") {
unsigned char c = '\x96';
c = StringsConvertor::E2A(c);
REQUIRE(c == 'o');
}
SECTION("EBCDIC_TO_ASCII") {
unsigned char str[] = "\xc8\x85\x93\x93\x96\x40\xa3\x88\x85\x99\x85\x5a";
StringsConvertor::E2A(str, 12);
REQUIRE(strcmp((const char *) str, "Hello there!") == 0);
}
}
/**
* REQUIRED TESTS:
*
* N.B. This test shall test only StringsConvertor.
*
* 1. All functions individually to return desired output in same test case yet different sections,
* also different permutations of configuration map shall be used to assure correct variations.
*
* 2. RC values -if any- to be tested and required against its ground truth
* (i.e. both failure and success cases shall be tested)
*/
TEST_CASE("Strings Convertor") {
TEST_CASE_STRING_CONV();
}
| 2,322
|
C++
|
.cpp
| 65
| 31.523077
| 99
| 0.680927
|
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,202
|
TestChecker.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/utils/checkers/TestChecker.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/utils/checkers/Checker.hpp>
using namespace bs::io::utils::checkers;
void
TEST_CASE_CHECKER() {
SECTION("Testing Endianness Of Machine") {
unsigned int i = 1;
char *c = (char *) &i;
bool little = (*c);
REQUIRE(Checker::IsLittleEndianMachine() == little);
}
}
/**
* REQUIRED TESTS:
*
* N.B. This test shall test only Checker.
*
* 1. All functions individually to return desired output in same test case yet different sections,
* also different permutations of configuration map shall be used to assure correct variations.
*
* 2. RC values -if any- to be tested and required against its ground truth
* (i.e. both failure and success cases shall be tested)
*/
TEST_CASE("Checker") {
TEST_CASE_CHECKER();
}
| 1,571
|
C++
|
.cpp
| 44
| 32.931818
| 99
| 0.722368
|
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,203
|
DataGenerator.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/test-utils/src/DataGenerator.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/test-utils/DataGenerator.hpp>
using namespace std;
using namespace bs::io::testutils;
using namespace bs::io::dataunits;
DataGenerator::DataGenerator() = default;
Trace *
DataGenerator::GenerateTrace(uint16_t aNS, int32_t aFLDR) {
auto trace = new Trace(aNS);
/* Data generation. */
auto trace_data = new float[aNS];
for (int i = 0; i < aNS; ++i) {
trace_data[i] = (float) rand() * 100 / RAND_MAX;
}
trace->SetTraceData((float *) trace_data);
/* Trace header keys generation. */
trace->SetTraceHeaderKeyValue(TraceHeaderKey::NS, aNS);
trace->SetTraceHeaderKeyValue(TraceHeaderKey::FLDR, aFLDR);
return trace;
}
vector<Trace *> DataGenerator::GenerateTraceVector(uint16_t aNS, int aCount, int32_t aStartFLDR) {
std::vector<Trace *> vec;
vec.reserve(aCount);
auto fldr = aStartFLDR;
for (int i = 0; i < aCount; ++i) {
vec.push_back(DataGenerator::GenerateTrace(aNS, fldr++));
}
return vec;
}
vector<Trace *> DataGenerator::GenerateTraceVector(uint16_t aNS, const std::vector<int32_t> &aFLDR) {
std::vector<Trace *> vec;
vec.reserve(aFLDR.size());
for (const auto &fldr : aFLDR) {
vec.push_back(DataGenerator::GenerateTrace(aNS, fldr));
}
return vec;
}
Gather *
DataGenerator::GenerateGather(uint16_t aNS, int aCount, int32_t aStartFLDR) {
auto g = new Gather();
g->AddTrace(DataGenerator::GenerateTraceVector(aNS, aCount, aStartFLDR));
return g;
}
| 2,227
|
C++
|
.cpp
| 60
| 33.65
| 101
| 0.707328
|
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,204
|
SUWriter.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/streams/concrete/writers/SUWriter.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <sys/stat.h>
#include <cstring>
#include <bs/base/common/ExitCodes.hpp>
#include <bs/io/streams/concrete/writers/SUWriter.hpp>
#include <bs/io/configurations/MapKeys.h>
#include <bs/io/lookups/tables/TraceHeaderLookup.hpp>
#include <bs/io/lookups/mappers/HeaderMapper.hpp>
#include <bs/io/lookups/mappers/SegyHeaderMapper.hpp>
#include <bs/io/utils/convertors/NumbersConvertor.hpp>
#include <bs/io/utils/convertors/KeysConvertor.hpp>
#include <bs/io/utils/checkers/Checker.hpp>
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::io::lookups;
using namespace bs::io::utils::convertors;
using namespace bs::io::utils::checkers;
SUWriter::SUWriter(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mWriteLittleEndian = false;
}
SUWriter::~SUWriter() = default;
void
SUWriter::AcquireConfiguration() {
this->mWriteLittleEndian = this->mpConfigurationMap->GetValue(
IO_K_PROPERTIES, IO_K_WRITE_LITTLE_ENDIAN, this->mWriteLittleEndian);
this->mFilePath = this->mpConfigurationMap->GetValue(
IO_K_PROPERTIES, IO_K_WRITE_PATH, this->mFilePath);
}
int
SUWriter::Initialize(std::string &aFilePath) {
mkdir(this->mFilePath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
this->mOutputStream = std::ofstream(this->mFilePath + aFilePath + this->GetExtension(),
std::ios::out | std::ios::binary);
if (!this->mOutputStream) {
std::cout << "Cannot open file!" << std::endl;
}
return BS_BASE_RC_SUCCESS;
}
int
SUWriter::Finalize() {
this->mOutputStream.close();
return 0;
}
std::string
SUWriter::GetExtension() {
return IO_K_EXT_SU;
}
int
SUWriter::Write(io::dataunits::Gather *aGather) {
bool swap_bytes = true;
if ((this->mWriteLittleEndian && Checker::IsLittleEndianMachine()) ||
(!this->mWriteLittleEndian && !Checker::IsLittleEndianMachine())) {
swap_bytes = false;
}
for (int i = 0; i < aGather->GetNumberTraces(); ++i) {
auto trace = aGather->GetTrace(i);
auto trace_data = trace->GetTraceData();
TraceHeaderLookup trace_header{};
memset(&trace_header, 0, sizeof(trace_header));
HeaderMapper::MapTraceToHeader((char *) &trace_header, *trace,
SegyHeaderMapper::mLocationTable,
swap_bytes);
uint16_t ns = trace->GetNumberOfSamples();
this->mOutputStream.write((char *) &trace_header, IO_SIZE_TRACE_HEADER);
float *processed_data = trace_data;
if (swap_bytes) {
processed_data = new float[ns];
memcpy(processed_data, trace_data, ns * sizeof(float));
processed_data = NumbersConvertor::ToLittleEndian(processed_data, ns);
}
this->mOutputStream.write((char *) processed_data, ns * sizeof(float));
if (swap_bytes) {
delete[] processed_data;
}
}
if (!this->mOutputStream.good()) {
std::cout << "Error occurred at writing time!" << std::endl;
return 1;
}
return 0;
}
int
SUWriter::Write(std::vector<dataunits::Gather *> aGathers) {
if (!this->mOutputStream) {
std::cout << "Cannot open file!" << std::endl;
return 1;
}
for (auto &e : aGathers) {
this->Write(e);
}
return 0;
}
| 4,199
|
C++
|
.cpp
| 111
| 32.432432
| 91
| 0.671902
|
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,205
|
CSVWriter.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/streams/concrete/writers/CSVWriter.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <sys/stat.h>
#include <bs/base/common/ExitCodes.hpp>
#include <bs/io/streams/concrete/writers/CSVWriter.hpp>
#include <bs/io/configurations/MapKeys.h>
using namespace bs::io::streams;
CSVWriter::CSVWriter(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
}
CSVWriter::~CSVWriter() = default;
void
CSVWriter::AcquireConfiguration() {
this->mFilePath = this->mpConfigurationMap->GetValue(
IO_K_PROPERTIES, IO_K_WRITE_PATH, this->mFilePath);
}
int
CSVWriter::Initialize(std::string &aFilePath) {
int rc = BS_BASE_RC_SUCCESS;
mkdir(this->mFilePath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
this->mOutputStream = std::ofstream(this->mFilePath + aFilePath + this->GetExtension(),
std::ios::out | std::ios::binary);
if (!this->mOutputStream) {
std::cout << "Cannot open file!" << std::endl;
rc = BS_BASE_RC_FAILURE;
}
return rc;
}
int
CSVWriter::Finalize() {
this->mOutputStream.close();
return BS_BASE_RC_SUCCESS;
}
std::string
CSVWriter::GetExtension() {
return IO_K_EXT_CSV;
}
int
CSVWriter::Write(io::dataunits::Gather *aGather) {
auto n_x = aGather->GetNumberTraces();
auto n_z = aGather->GetTrace(0)->GetNumberOfSamples();
this->mOutputStream << n_x << "," << n_z << "\n";
for (int iz = 0; iz < n_z; ++iz) {
for (int ix = 0; ix < n_x; ++ix) {
auto trace = aGather->GetTrace(ix);
auto trace_data = trace->GetTraceData();
auto val = trace_data[iz];
this->mOutputStream << val << ',';
}
this->mOutputStream << '\n';
}
int rc = BS_BASE_RC_SUCCESS;
if (!this->mOutputStream.good()) {
std::cout << "Error occurred at writing time!" << std::endl;
rc = BS_BASE_RC_FAILURE;
}
return rc;
}
int
CSVWriter::Write(std::vector<dataunits::Gather *> aGathers) {
int rc = BS_BASE_RC_SUCCESS;
if (!this->mOutputStream) {
std::cout << "Cannot open file!" << std::endl;
rc = BS_BASE_RC_FAILURE;
} else {
for (auto &e : aGathers) {
this->Write(e);
}
}
return rc;
}
| 2,989
|
C++
|
.cpp
| 88
| 29.215909
| 91
| 0.649238
|
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,206
|
SeismicWriter.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/streams/concrete/writers/SeismicWriter.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/streams/concrete/writers/SeismicWriter.hpp>
#include <bs/io/streams/concrete/writers/CSVWriter.hpp>
#include <bs/io/streams/concrete/writers/SUWriter.hpp>
#include <bs/io/streams/concrete/writers/BinaryWriter.hpp>
#include <bs/io/streams/concrete/writers/ImageWriter.hpp>
#include <bs/io/streams/concrete/writers/SegyWriter.hpp>
using namespace bs::io::streams;
using namespace bs::base::configurations;
using namespace bs::io::dataunits;
using namespace std;
std::unordered_map<std::string, WriterType> SeismicWriter::mWriterMap = {
{"segy", WriterType::SEGY},
{"binary", WriterType::BINARY},
{"csv", WriterType::CSV},
{"su", WriterType::SU},
{"image", WriterType::IMAGE},
};
SeismicWriter::SeismicWriter(WriterType aType, ConfigurationMap *apConfigurationMap) {
switch (aType) {
case WriterType::SEGY:
this->mpWriter = new SegyWriter(apConfigurationMap);
break;
case WriterType::BINARY:
this->mpWriter = new BinaryWriter(apConfigurationMap);
break;
case WriterType::CSV:
this->mpWriter = new CSVWriter(apConfigurationMap);
break;
case WriterType::SU:
this->mpWriter = new SUWriter(apConfigurationMap);
break;
case WriterType::IMAGE:
this->mpWriter = new ImageWriter(apConfigurationMap);
break;
}
}
WriterType SeismicWriter::ToWriterType(const std::string &aString) {
if (mWriterMap.find(aString) == mWriterMap.end()) {
std::string supported = "Invalid string : supported formats are [";
for (const auto &it : mWriterMap) {
supported += it.first + " ";
}
supported += "]";
throw runtime_error(supported);
}
return mWriterMap[aString];
}
std::string SeismicWriter::ToString(WriterType aType) {
std::string representation;
for (const auto &it : mWriterMap) {
if (it.second == aType) {
representation = it.first;
break;
}
}
if (representation.empty()) {
throw runtime_error("Unsupported writer type...");
}
return representation;
}
SeismicWriter::~SeismicWriter() {
delete this->mpWriter;
}
void SeismicWriter::AcquireConfiguration() {
this->mpWriter->AcquireConfiguration();
}
string SeismicWriter::GetExtension() {
return this->mpWriter->GetExtension();
}
int SeismicWriter::Initialize(string &aFilePath) {
return this->mpWriter->Initialize(aFilePath);
}
int SeismicWriter::Finalize() {
return this->mpWriter->Finalize();
}
int SeismicWriter::Write(vector<dataunits::Gather *> aGathers) {
return this->mpWriter->Write(aGathers);
}
int SeismicWriter::Write(io::dataunits::Gather *aGather) {
return this->mpWriter->Write(aGather);
}
| 3,567
|
C++
|
.cpp
| 99
| 30.959596
| 86
| 0.691951
|
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,207
|
ImageWriter.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/streams/concrete/writers/ImageWriter.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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>
#ifdef USING_OPENCV
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#endif
#include <bs/base/common/ExitCodes.hpp>
#include <bs/io/streams/concrete/writers/ImageWriter.hpp>
#include <bs/io/configurations/MapKeys.h>
using namespace bs::io::streams;
using namespace std;
ImageWriter::ImageWriter(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mPercentile = 100;
}
void
ImageWriter::AcquireConfiguration() {
this->mPercentile = this->mpConfigurationMap->GetValue(IO_K_PROPERTIES,
IO_K_PERCENTILE,
this->mPercentile);
}
float *
ImageWriter::NormalizeArrayByPercentile(const float *apInputArray,
int aWidth,
int aHeight,
float aPercentile) {
float max_val = -std::numeric_limits<float>::max();
vector<float> values;
auto normalized_image = new float[aWidth * aHeight];
values.push_back(0);
for (int i = 0; i < aWidth * aHeight; i++) {
if (apInputArray[i] != 0) {
values.push_back(fabs(apInputArray[i]));
}
}
std::sort(values.begin(), values.end());
int index = (int) ((aPercentile / 100.0) * ((double) (values.size() - 1)));
if (index < 0) {
index = 0;
}
max_val = values[index];
for (int i = 0; i < aWidth * aHeight; i++) {
if (fabs(apInputArray[i]) > max_val) {
if (apInputArray[i] > 0) {
normalized_image[i] = max_val;
} else {
normalized_image[i] = -max_val;
}
} else {
normalized_image[i] = apInputArray[i];
}
}
return normalized_image;
}
int
ImageWriter::WriteArrayToPNG(const float *apArray,
int aWidth,
int aHeight,
float aPercentile,
const char *apFilename) {
auto rc = BS_BASE_RC_FAILURE;
#ifdef USING_OPENCV
float *ptr_new = ImageWriter::NormalizeArrayByPercentile(apArray,
aWidth,
aHeight,
aPercentile);
const cv::Mat data(aHeight, aWidth,
CV_32FC1, const_cast<float *>(ptr_new));
cv::Mat data_displayed(aHeight, aWidth, CV_8UC1);
float minV = *min_element(data.begin<float>(), data.end<float>());
float maxV = *max_element(data.begin<float>(), data.end<float>());
cv::Mat data_scaled = (data - minV) / (maxV - minV);
data_scaled.convertTo(data_displayed, CV_8UC1, 255.0, 0);
try {
cv::imwrite(apFilename, data_displayed);
rc = BS_BASE_RC_SUCCESS;
} catch (cv::Exception &ex) {
rc = BS_BASE_RC_FAILURE;
}
delete[] ptr_new;
#endif
return rc;
}
std::string
ImageWriter::GetExtension() {
return IO_K_EXT_IMG;
}
int
ImageWriter::Initialize(std::string &aFilePath) {
this->mFilePath = aFilePath;
return BS_BASE_RC_SUCCESS;
}
int
ImageWriter::Finalize() {
return BS_BASE_RC_SUCCESS;
}
int
ImageWriter::Write(std::vector<dataunits::Gather *> aGathers) {
int index = 0;
auto rc = BS_BASE_RC_SUCCESS;
for (auto gather : aGathers) {
rc = this->WriteGather(gather, "_gather_id_" + to_string(index) + this->GetExtension());
if (rc != BS_BASE_RC_SUCCESS) {
break;
}
index++;
}
return rc;
}
int
ImageWriter::Write(io::dataunits::Gather *aGather) {
return this->WriteGather(aGather, "");
}
int
ImageWriter::WriteGather(io::dataunits::Gather *apGather,
const std::string &aPostfix) {
auto width = apGather->GetNumberTraces();
auto height = apGather->GetTrace(0)->GetNumberOfSamples();
auto array = new float[width * height];
for (int ix = 0; ix < width; ix++) {
for (int iz = 0; iz < height; iz++) {
array[iz * width + ix] = apGather->GetTrace(ix)->GetTraceData()[iz];
}
}
auto rc = ImageWriter::WriteArrayToPNG(array, (int) width, height, this->mPercentile,
(this->mFilePath + aPostfix).c_str());
delete[] array;
return rc;
}
| 5,257
|
C++
|
.cpp
| 147
| 27.340136
| 96
| 0.58641
|
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,208
|
SegyWriter.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/streams/concrete/writers/SegyWriter.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/common/ExitCodes.hpp>
#include <bs/io/streams/concrete/writers/SegyWriter.hpp>
#include <bs/io/streams/helpers/OutStreamHelper.hpp>
#include <bs/io/lookups/tables/TextHeaderLookup.hpp>
#include <bs/io/lookups/tables/BinaryHeaderLookup.hpp>
#include <bs/io/lookups/tables/TraceHeaderLookup.hpp>
#include <bs/io/lookups/mappers/HeaderMapper.hpp>
#include <bs/io/lookups/mappers/SegyHeaderMapper.hpp>
#include <bs/io/utils/convertors/NumbersConvertor.hpp>
#include <bs/io/utils/convertors/FloatingPointFormatter.hpp>
#include <bs/io/common/Definitions.hpp>
#include <bs/io/configurations/MapKeys.h>
using namespace bs::io::streams;
using namespace bs::io::streams::helpers;
using namespace bs::io::lookups;
using namespace bs::io::utils::convertors;
SegyWriter::SegyWriter(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mOutStreamHelpers = nullptr;
this->mWriteLittleEndian = true;
this->mBinaryHeaderWritten = false;
this->mFormat = 1;
}
SegyWriter::~SegyWriter() {
delete this->mOutStreamHelpers;
}
void
SegyWriter::AcquireConfiguration() {
this->mWriteLittleEndian = this->mpConfigurationMap->GetValue(
IO_K_PROPERTIES, IO_K_WRITE_LITTLE_ENDIAN, this->mWriteLittleEndian);
this->mFormat = this->mpConfigurationMap->GetValue(
IO_K_PROPERTIES, IO_K_FLOAT_FORMAT, this->mFormat);
}
std::string
SegyWriter::GetExtension() {
return IO_K_EXT_SGY;
}
int
SegyWriter::Initialize(std::string &aFilePath) {
this->mFilePath = aFilePath + this->GetExtension();
this->mOutStreamHelpers = new OutStreamHelper(this->mFilePath);
this->mOutStreamHelpers->Open();
char text_header[IO_SIZE_TEXT_HEADER];
memset(text_header, 0, IO_SIZE_TEXT_HEADER);
std::string temp = IO_DEF_BRIGHTSKIES_COPY_WRITES;
memcpy(text_header, temp.c_str(), temp.size());
text_header[temp.size()] = '\0';
this->mOutStreamHelpers->WriteBytesBlock(text_header, IO_SIZE_TEXT_HEADER);
this->mBinaryHeaderWritten = false;
return BS_BASE_RC_SUCCESS;
}
int
SegyWriter::Finalize() {
this->mOutStreamHelpers->Close();
return BS_BASE_RC_SUCCESS;
}
int
SegyWriter::Write(std::vector<dataunits::Gather *> aGathers) {
int rc = 0;
for (const auto &it : aGathers) {
rc += this->Write(it);
}
/* Check that all Write() functions returned BS_BASE_RC_SUCCESS signal. */
return aGathers.empty() ? BS_BASE_RC_SUCCESS : (rc / aGathers.size()) == BS_BASE_RC_SUCCESS;
}
int
SegyWriter::Write(io::dataunits::Gather *aGather) {
if (!this->mBinaryHeaderWritten) {
BinaryHeaderLookup binary_header{};
memset(&binary_header, 0, sizeof(binary_header));
uint16_t format = this->mFormat;
binary_header.FORMAT = NumbersConvertor::ToLittleEndian(format);
uint16_t hdt = aGather->GetSamplingRate();
binary_header.HDT = NumbersConvertor::ToLittleEndian(hdt);
uint16_t hns = 0;
if (aGather->GetNumberTraces() > 0) {
hns = aGather->GetTrace(0)->GetNumberOfSamples();
}
binary_header.HNS = NumbersConvertor::ToLittleEndian(hns);
this->mOutStreamHelpers->WriteBytesBlock((char *) &binary_header, IO_SIZE_BINARY_HEADER);
this->mBinaryHeaderWritten = true;
}
int rc;
for (auto &g : aGather->GetAllTraces()) {
rc = 0;
TraceHeaderLookup trace_header{};
memset(&trace_header, 0, sizeof(trace_header));
HeaderMapper::MapTraceToHeader((char *) &trace_header, *g,
SegyHeaderMapper::mLocationTable);
uint16_t ns = g->GetNumberOfSamples();
/* Write header of trace. */
rc += this->mOutStreamHelpers->WriteBytesBlock((char *) &trace_header,
IO_SIZE_TRACE_HEADER);
/* Format and write data of trace. */
auto trace_formatted_size = FloatingPointFormatter::GetFloatArrayRealSize(ns, this->mFormat);
auto trace_data = new char[trace_formatted_size];
FloatingPointFormatter::Format((char *) g->GetTraceData(), trace_data,
ns * sizeof(float),
ns,
this->mFormat, false);
this->mOutStreamHelpers->WriteBytesBlock(trace_data, trace_formatted_size);
delete[] trace_data;
}
return rc;
}
| 5,204
|
C++
|
.cpp
| 123
| 36.300813
| 101
| 0.686131
|
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,209
|
BinaryWriter.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/streams/concrete/writers/BinaryWriter.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <sys/stat.h>
#include <bs/base/common/ExitCodes.hpp>
#include <bs/io/streams/concrete/writers/BinaryWriter.hpp>
#include <bs/io/configurations/MapKeys.h>
using namespace bs::io::streams;
BinaryWriter::BinaryWriter(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
}
BinaryWriter::~BinaryWriter() = default;
void
BinaryWriter::AcquireConfiguration() {
//TODO add option to dump headers in a separate file(Either in text format, or in SU format).
this->mFilePath = this->mpConfigurationMap->GetValue(
IO_K_PROPERTIES, IO_K_WRITE_PATH, this->mFilePath);
}
int
BinaryWriter::Initialize(std::string &aFilePath) {
mkdir(this->mFilePath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
this->mOutputStream = std::ofstream(this->mFilePath + aFilePath + this->GetExtension(),
std::ios::out | std::ios::binary);
if (!this->mOutputStream) {
std::cout << "Cannot open file!" << std::endl;
}
return BS_BASE_RC_SUCCESS;
}
int
BinaryWriter::Finalize() {
this->mOutputStream.close();
return 0;
}
std::string
BinaryWriter::GetExtension() {
return IO_K_EXT_BIN;
}
int
BinaryWriter::Write(io::dataunits::Gather *aGather) {
for (int i = 0; i < aGather->GetNumberTraces(); ++i) {
auto trace = aGather->GetTrace(i);
auto n_s = trace->GetNumberOfSamples();
auto trace_data = trace->GetTraceData();
this->mOutputStream.write((char *) trace_data, n_s * sizeof(float));
}
if (!this->mOutputStream.good()) {
std::cout << "Error occurred at writing time!" << std::endl;
return 1;
}
return 0;
}
int
BinaryWriter::Write(std::vector<dataunits::Gather *> aGathers) {
if (!this->mOutputStream) {
std::cout << "Cannot open file!" << std::endl;
return 1;
}
for (auto &e : aGathers) {
this->Write(e);
}
return 0;
}
| 2,735
|
C++
|
.cpp
| 78
| 30.897436
| 97
| 0.683693
|
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,210
|
JsonReader.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/streams/concrete/readers/JsonReader.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <fstream>
#include <prerequisites/libraries/nlohmann/json.hpp>
#include <bs/base/common/ExitCodes.hpp>
#include <bs/base/exceptions/Exceptions.hpp>
#include <bs/io/streams/concrete/readers/JsonReader.hpp>
#include <bs/io/utils/convertors/KeysConvertor.hpp>
#include <bs/io/utils/synthetic-generators/concrete/ParameterMetaDataGenerator.hpp>
#include <bs/io/utils/synthetic-generators/concrete/ShotsMetaDataGenerator.hpp>
#include <bs/io/utils/synthetic-generators/concrete/PlaneReflectorGenerator.hpp>
#include <bs/io/configurations/MapKeys.h>
using namespace std;
using namespace bs::base::exceptions;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
using namespace bs::io::generators;
using namespace bs::io::utils::convertors;
JsonReader::JsonReader(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mEnableHeaderOnly = false;
this->mpMetaGenerator = nullptr;
}
JsonReader::~JsonReader() {
delete this->mpMetaGenerator;
for (auto const &ptr : this->mReflectorGenerators) {
delete ptr;
}
}
void
JsonReader::AcquireConfiguration() {
}
std::string
JsonReader::GetExtension() {
return IO_K_EXT_JSON;
}
int
JsonReader::Initialize(std::vector<std::string> &aGatherKeys,
std::vector<std::pair<std::string, dataunits::Gather::SortDirection>> &aSortingKeys,
std::vector<std::string> &aPaths) {
for (auto &e : aGatherKeys) {
auto gather_key = KeysConvertor::ToTraceHeaderKey(e);
this->mGatherKeys.push_back(gather_key);
}
for (auto &e : aSortingKeys) {
auto key = KeysConvertor::ToTraceHeaderKey(e.first);
auto sort_dir = e.second;
this->mSortingKeys.emplace_back(key, sort_dir);
}
this->mFilePath = aPaths[0];
this->GenerateComponents();
return BS_BASE_RC_SUCCESS;
}
int
JsonReader::Initialize(std::vector<TraceHeaderKey> &aGatherKeys,
std::vector<std::pair<TraceHeaderKey, dataunits::Gather::SortDirection>> &aSortingKeys,
std::vector<std::string> &aPaths) {
this->mGatherKeys = aGatherKeys;
this->mSortingKeys = aSortingKeys;
this->mFilePath = aPaths[0];
this->GenerateComponents();
return BS_BASE_RC_SUCCESS;
}
int
JsonReader::Finalize() {
return BS_BASE_RC_SUCCESS;
}
void
JsonReader::SetHeaderOnlyMode(bool aEnableHeaderOnly) {
this->mEnableHeaderOnly = aEnableHeaderOnly;
}
unsigned int
JsonReader::GetNumberOfGathers() {
return this->mpMetaGenerator->GetGatherNumber();
}
std::vector<std::vector<std::string>>
JsonReader::GetIdentifiers() {
std::vector<std::vector<std::string>> unique_identifiers;
unique_identifiers = this->mpMetaGenerator->GetGatherUniqueValues();
return unique_identifiers;
}
void
JsonReader::FillTraceData(std::vector<Gather *> &aGathers) {
for (auto &g : aGathers) {
auto traces = g->GetAllTraces();
for (auto &t : traces) {
float ix = t->GetTraceHeaderKeyValue<int>(TraceHeaderKey::SYN_X_IND);
float iy = t->GetTraceHeaderKeyValue<int>(TraceHeaderKey::SYN_Y_IND);
vector<pair<float, int>> reflector_pairs;
for (int i = 0; i < this->mReflectorGenerators.size(); i++) {
float depth = this->mReflectorGenerators[i]->GetReflectorDepth(ix, iy);
reflector_pairs.emplace_back(depth, i);
}
sort(reflector_pairs.begin(), reflector_pairs.end(),
[](pair<float, int> a, pair<float, int> b) {
return a.first < b.first;
});
int reflector_index = 0;
for (int iz = 0; iz < t->GetNumberOfSamples(); iz++) {
auto &reflector = reflector_pairs[reflector_index];
if (iz < reflector.first) {
auto gen = this->mReflectorGenerators[reflector.second];
t->GetTraceData()[iz] = gen->GetBeforeValue();
} else if (reflector_index == this->mReflectorGenerators.size() - 1) {
auto gen = this->mReflectorGenerators[reflector.second];
t->GetTraceData()[iz] = gen->GetAfterValue();
} else {
while (reflector_index < this->mReflectorGenerators.size() - 1 &&
iz > reflector_pairs[reflector_index + 1].first) {
reflector_index++;
}
auto &reflector_before = reflector_pairs[reflector_index];
if (reflector_index == this->mReflectorGenerators.size() - 1) {
auto gen = this->mReflectorGenerators[reflector_before.second];
t->GetTraceData()[iz] = gen->GetAfterValue();
} else {
auto &reflector_after = reflector_pairs[reflector_index + 1];
auto value_before = this->mReflectorGenerators[reflector_before.second]->GetAfterValue();
auto value_after = this->mReflectorGenerators[reflector_after.second]->GetBeforeValue();
auto depth_before = reflector_before.first;
auto depth_after = reflector_after.first;
auto divisor = (depth_after - depth_before);
if (divisor == 0) {
t->GetTraceData()[iz] = value_after;
} else {
t->GetTraceData()[iz] = value_before +
((value_after - value_before) * (iz - depth_before)) /
(depth_after - depth_before);
}
}
}
}
}
}
}
std::vector<Gather *>
JsonReader::ReadAll() {
/* Vector to be returned. */
std::vector<Gather *> return_gathers = this->mpMetaGenerator->GetAllTraces();
if (!this->mEnableHeaderOnly) {
this->FillTraceData(return_gathers);
}
return return_gathers;
}
std::vector<Gather *>
JsonReader::Read(std::vector<std::vector<std::string>> aHeaderValues) {
/* Vector to be returned. */
std::vector<Gather *> return_gathers = this->mpMetaGenerator->GetTraces(aHeaderValues);
if (!this->mEnableHeaderOnly) {
this->FillTraceData(return_gathers);
}
return return_gathers;
}
Gather *
JsonReader::Read(std::vector<std::string> aHeaderValues) {
Gather *return_gather;
return_gather = this->Read(vector<vector<string>>{aHeaderValues})[0];
return return_gather;
}
Gather *
JsonReader::Read(unsigned int aIndex) {
auto identifiers = this->GetIdentifiers();
if (aIndex >= identifiers.size()) {
throw ILLOGICAL_EXCEPTION();
}
return this->Read(identifiers[aIndex]);
}
void
JsonReader::GenerateComponents() {
std::ifstream in(this->mFilePath);
nlohmann::json descriptor;
in >> descriptor;
if (!descriptor.contains("meta-data")) {
throw ILLOGICAL_EXCEPTION();
}
nlohmann::json meta_data = descriptor["meta-data"];
std::string type = meta_data["type"];
delete this->mpMetaGenerator;
if (type == "parameter") {
this->mpMetaGenerator = new ParameterMetaDataGenerator(meta_data);
} else if (type == "traces") {
this->mpMetaGenerator = new ShotsMetaDataGenerator(meta_data);
} else {
throw UNSUPPORTED_FEATURE_EXCEPTION();
}
this->mpMetaGenerator->SetGenerationKey(this->mGatherKeys);
for (auto const &ptr : this->mReflectorGenerators) {
delete ptr;
}
this->mReflectorGenerators.clear();
if (descriptor.contains("data")) {
nlohmann::json data = descriptor["data"];
if (data.contains("reflector")) {
nlohmann::json reflector_data = data["reflector"];
for (auto it = reflector_data.begin(); it != reflector_data.end(); ++it) {
auto object = it.value();
std::string object_type = object["type"];
if (object_type == "plane") {
auto gen = new PlaneReflectorGenerator();
gen->ParseValues(object);
this->mReflectorGenerators.push_back(gen);
} else {
throw UNSUPPORTED_FEATURE_EXCEPTION();
}
}
}
}
}
| 9,196
|
C++
|
.cpp
| 224
| 32.535714
| 113
| 0.624958
|
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,211
|
SUReader.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/streams/concrete/readers/SUReader.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/streams/concrete/readers/SUReader.hpp>
using namespace bs::io::streams;
| 824
|
C++
|
.cpp
| 20
| 39.25
| 73
| 0.753117
|
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,212
|
SegyReader.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/streams/concrete/readers/SegyReader.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/common/ExitCodes.hpp>
#include <bs/base/exceptions/Exceptions.hpp>
#include <bs/io/streams/concrete/readers/SegyReader.hpp>
#include <bs/io/streams/helpers/InStreamHelper.hpp>
#include <bs/io/data-units/helpers/TraceHelper.hpp>
#include <bs/io/lookups/tables/TextHeaderLookup.hpp>
#include <bs/io/lookups/tables/BinaryHeaderLookup.hpp>
#include <bs/io/lookups/tables/TraceHeaderLookup.hpp>
#include <bs/io/utils/convertors/NumbersConvertor.hpp>
#include <bs/io/utils/convertors/StringsConvertor.hpp>
#include <bs/io/utils/convertors/FloatingPointFormatter.hpp>
#include <bs/io/configurations/MapKeys.h>
#define IO_K_FIRST_OCCURRENCE 0 /* First occurrence position */
using namespace bs::base::exceptions;
using namespace bs::io::streams;
using namespace bs::io::streams::helpers;
using namespace bs::io::lookups;
using namespace bs::io::indexers;
using namespace bs::io::dataunits;
using namespace bs::io::dataunits::helpers;
using namespace bs::io::utils::convertors;
SegyReader::SegyReader(bs::base::configurations::ConfigurationMap *apConfigurationMap) {
this->mpConfigurationMap = apConfigurationMap;
this->mEnableHeaderOnly = false;
this->mHasExtendedTextHeader = false;
this->mStoreTextHeaders = false;
this->mTextHeader = nullptr;
this->mExtendedHeader = nullptr;
}
SegyReader::~SegyReader() {
delete this->mTextHeader;
if (this->mHasExtendedTextHeader) {
delete this->mExtendedHeader;
}
}
void
SegyReader::AcquireConfiguration() {
this->mEnableHeaderOnly = this->mpConfigurationMap->GetValue(
IO_K_PROPERTIES, IO_K_TEXT_HEADERS_ONLY, this->mEnableHeaderOnly);
this->mStoreTextHeaders = this->mpConfigurationMap->GetValue(
IO_K_PROPERTIES, IO_K_TEXT_HEADERS_STORE, this->mStoreTextHeaders);
}
std::string
SegyReader::GetExtension() {
return IO_K_EXT_SGY;
}
int
SegyReader::Initialize(std::vector<std::string> &aGatherKeys,
std::vector<std::pair<std::string, Gather::SortDirection>> &aSortingKeys,
std::vector<std::string> &aPaths) {
/// @todo To be removed
/// {
throw NOT_IMPLEMENTED_EXCEPTION();
/// }
}
int
SegyReader::Initialize(std::vector<TraceHeaderKey> &aGatherKeys,
std::vector<std::pair<TraceHeaderKey, dataunits::Gather::SortDirection>> &aSortingKeys,
std::vector<std::string> &aPaths) {
/* Reset All Variables to start from scratch */
this->mInStreamHelpers.clear();
this->mFileIndexers.clear();
this->mIndexMaps.clear();
this->mEnableHeaderOnly = false;
this->mHasExtendedTextHeader = false;
this->mStoreTextHeaders = false;
this->mTextHeader = nullptr;
this->mExtendedHeader = nullptr;
/* Internal variables initializations. */
this->mGatherKeys = aGatherKeys;
this->mSortingKeys = aSortingKeys;
this->mPaths = aPaths;
/* Initialize streams. */
for (auto &it : this->mPaths) {
this->mInStreamHelpers.push_back(new InStreamHelper(it));
}
/* Open streams. */
for (auto &it : this->mInStreamHelpers) {
it->Open();
}
/* Read text header in the given file. */
if (this->mStoreTextHeaders) {
this->mTextHeader = this->mInStreamHelpers[IO_K_FIRST_OCCURRENCE]->ReadTextHeader(IO_POS_S_TEXT_HEADER);
}
/* Read binary header in the given file and check whether an
* extended text header is available or not for later reading */
this->mBinaryHeaderLookup = this->mInStreamHelpers[IO_K_FIRST_OCCURRENCE]->ReadBinaryHeader(IO_POS_S_BINARY_HEADER);
this->mHasExtendedTextHeader = NumbersConvertor::ToLittleEndian(this->mBinaryHeaderLookup.EXT_HEAD);
/* Read extended text header in the given file if found. */
if (this->mHasExtendedTextHeader && this->mStoreTextHeaders) {
this->mExtendedHeader = this->mInStreamHelpers[IO_K_FIRST_OCCURRENCE]->ReadTextHeader(IO_POS_S_EXT_TEXT_HEADER);
}
/* Index passed files. */
this->Index();
return BS_BASE_RC_SUCCESS;
}
int
SegyReader::Finalize() {
int rc = 0;
/* Close streams. */
for (auto &it : this->mInStreamHelpers) {
rc += it->Close();
}
/* Check that all Write() functions returned BS_BASE_RC_SUCCESS signal. */
return (rc / this->mInStreamHelpers.size()) == BS_BASE_RC_SUCCESS;
}
void
SegyReader::SetHeaderOnlyMode(bool aEnableHeaderOnly) {
this->mEnableHeaderOnly = aEnableHeaderOnly;
}
std::vector<Gather *>
SegyReader::ReadAll() {
std::vector<Gather *> gathers;
std::unordered_map<std::string, std::vector<dataunits::Trace *>> gather_map;
auto format = NumbersConvertor::ToLittleEndian(this->mBinaryHeaderLookup.FORMAT);
for (const auto &it : this->mInStreamHelpers) {
unsigned long long file_size = it->GetFileSize();
size_t start_pos = IO_POS_S_TRACE_HEADER;
while (true) {
if (start_pos + IO_SIZE_TRACE_HEADER >= file_size) {
break;
}
/* Read trace header in the given file. */
auto thl = it->ReadTraceHeader(start_pos);
/* Read trace data in the given file. */
auto trace = it->ReadFormattedTraceData(start_pos + IO_SIZE_TRACE_HEADER, thl, this->mBinaryHeaderLookup);
auto &map = *trace->GetTraceHeaders();
std::vector<std::string> values;
values.reserve(this->mGatherKeys.size());
for (const auto &i : this->mGatherKeys) {
values.push_back(map.find(i)->second);
}
std::string value = TraceHeaderKey::GatherValuesToString(values);
gather_map[value].push_back(trace);
/* Update stream position pointer. */
start_pos += IO_SIZE_TRACE_HEADER +
FloatingPointFormatter::GetFloatArrayRealSize(NumbersConvertor::ToLittleEndian(thl.NS),
format);
}
}
auto hdt = NumbersConvertor::ToLittleEndian(this->mBinaryHeaderLookup.HDT);
for (auto const &traces : gather_map) {
auto g = new Gather();
std::string key = traces.first;
std::vector<std::string> keys = TraceHeaderKey::StringToGatherValues(key);
for (int i = 0; i < keys.size(); i++) {
g->SetUniqueKeyValue(this->mGatherKeys[i],
keys[i]);
}
g->AddTrace(traces.second);
g->SetSamplingRate(hdt);
gathers.push_back(g);
}
return gathers;
}
Gather *
SegyReader::Read(std::vector<std::string> aHeaderValues) {
if (aHeaderValues.size() != this->mGatherKeys.size()) {
return nullptr;
}
std::unordered_map<int, std::vector<dataunits::Trace *>> gather_map;
auto gather = new Gather();
gather->SetSamplingRate(NumbersConvertor::ToLittleEndian(this->mBinaryHeaderLookup.HDT));
std::string key = TraceHeaderKey::GatherKeysToString(this->mGatherKeys);
std::string value = TraceHeaderKey::GatherValuesToString(aHeaderValues);
for (int ig = 0; ig < this->mIndexMaps.size(); ++ig) {
auto bytes = this->mIndexMaps[ig].Get(key, value);
if (!bytes.empty()) {
auto stream = this->mInStreamHelpers[ig];
for (auto &pos : bytes) {
/* Read trace header in the given file. */
auto thl = stream->ReadTraceHeader(pos);
/* Read trace data in the given file. */
auto trace = stream->ReadFormattedTraceData(pos + IO_SIZE_TRACE_HEADER, thl,
this->mBinaryHeaderLookup);
gather->AddTrace(trace);
}
}
}
for (int i = 0; i < aHeaderValues.size(); i++) {
gather->SetUniqueKeyValue(this->mGatherKeys[i],
aHeaderValues[i]);
}
return gather;
}
std::vector<Gather *>
SegyReader::Read(std::vector<std::vector<std::string>> aHeaderValues) {
std::vector<Gather *> results;
for (const auto &header_value : aHeaderValues) {
Gather *gather = this->Read(header_value);
if (gather != nullptr) {
results.push_back(gather);
}
}
return results;
}
Gather *
SegyReader::Read(unsigned int aIndex) {
auto identifiers = this->GetIdentifiers();
if (aIndex >= identifiers.size()) {
throw ILLOGICAL_EXCEPTION();
}
return this->Read(identifiers[aIndex]);
}
std::vector<std::vector<std::string>>
SegyReader::GetIdentifiers() {
std::vector<std::vector<std::string>> keys;
for (auto &mIndexMap : this->mIndexMaps) {
auto map = mIndexMap.Get();
std::string key = TraceHeaderKey::GatherKeysToString(this->mGatherKeys);
for (const auto &entry : map[key]) {
if (!entry.second.empty()) {
std::vector<std::string> val = TraceHeaderKey::StringToGatherValues(entry.first);
keys.push_back(val);
}
}
}
return keys;
}
unsigned int
SegyReader::GetNumberOfGathers() {
unsigned int gather_number = 0;
for (auto &mIndexMap : this->mIndexMaps) {
auto map = mIndexMap.Get();
std::string key = TraceHeaderKey::GatherKeysToString(this->mGatherKeys);
for (const auto &entry : map[key]) {
if (!entry.second.empty()) {
gather_number++;
}
}
}
return gather_number;
}
bool
SegyReader::HasExtendedTextHeader() const {
return this->mHasExtendedTextHeader;
}
unsigned char *
SegyReader::GetTextHeader() {
unsigned char *text_header = nullptr;
if (this->mTextHeader != nullptr) {
text_header = StringsConvertor::E2A(this->mTextHeader, IO_SIZE_TEXT_HEADER);
}
return text_header;
}
unsigned char *
SegyReader::GetExtendedTextHeader() {
unsigned char *text_header = nullptr;
if (this->mTextHeader != nullptr) {
text_header = StringsConvertor::E2A(this->mExtendedHeader, IO_SIZE_TEXT_HEADER);
}
return text_header;
}
int
SegyReader::Index() {
this->mFileIndexers.reserve(this->mPaths.size());
std::string key = TraceHeaderKey::GatherKeysToString(this->mGatherKeys);
for (auto &it : this->mPaths) {
this->mFileIndexers.push_back(FileIndexer(it, key));
}
for (auto &it : this->mFileIndexers) {
it.Initialize();
this->mIndexMaps.push_back(it.Index(this->mGatherKeys));
it.Finalize();
}
return BS_BASE_RC_SUCCESS;
}
| 11,261
|
C++
|
.cpp
| 285
| 32.887719
| 120
| 0.658347
|
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,213
|
SeismicReader.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/streams/concrete/readers/SeismicReader.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/streams/concrete/readers/SeismicReader.hpp>
#include <bs/io/streams/concrete/readers/SegyReader.hpp>
#include <bs/io/streams/concrete/readers/JsonReader.hpp>
#include <bs/io/streams/concrete/readers/SUReader.hpp>
using namespace std;
using namespace bs::base::configurations;
using namespace bs::io::streams;
using namespace bs::io::dataunits;
std::unordered_map<std::string, ReaderType> SeismicReader::mReaderMap = {
{"segy", ReaderType::SEGY},
{"json", ReaderType::JSON},
{"su", ReaderType::SU},
};
SeismicReader::SeismicReader(ReaderType aType, ConfigurationMap *apConfigurationMap) {
switch (aType) {
case ReaderType::SEGY:
this->mpReader = new SegyReader(apConfigurationMap);
break;
case ReaderType::JSON:
this->mpReader = new JsonReader(apConfigurationMap);
break;
case ReaderType::SU:
// this->mpReader = new SUReader(apConfigurationMap);
break;
}
}
SeismicReader::~SeismicReader() {
delete this->mpReader;
}
ReaderType
SeismicReader::ToReaderType(const std::string &aString) {
if (mReaderMap.find(aString) == mReaderMap.end()) {
std::string supported = "Invalid string : supported formats are [";
for (const auto &it : mReaderMap) {
supported += it.first + " ";
}
supported += "]";
throw runtime_error(supported);
}
return mReaderMap[aString];
}
std::string
SeismicReader::ToString(ReaderType aType) {
std::string representation;
for (const auto &it : mReaderMap) {
if (it.second == aType) {
representation = it.first;
break;
}
}
if (representation.empty()) {
throw runtime_error("Unsupported reader type...");
}
return representation;
}
void
SeismicReader::AcquireConfiguration() {
this->mpReader->AcquireConfiguration();
}
string SeismicReader::GetExtension() {
return this->mpReader->GetExtension();
}
int
SeismicReader::Initialize(vector<std::string> &aGatherKeys,
vector<std::pair<std::string, Gather::SortDirection>> &aSortingKeys,
vector<std::string> &aPaths) {
return this->mpReader->Initialize(aGatherKeys, aSortingKeys, aPaths);
}
int
SeismicReader::Initialize(vector<dataunits::TraceHeaderKey> &aGatherKeys,
vector<std::pair<TraceHeaderKey, Gather::SortDirection>> &aSortingKeys,
vector<std::string> &aPaths) {
return this->mpReader->Initialize(aGatherKeys, aSortingKeys, aPaths);
}
int
SeismicReader::Finalize() {
return this->mpReader->Finalize();
}
void
SeismicReader::SetHeaderOnlyMode(bool aEnableHeaderOnly) {
this->mpReader->SetHeaderOnlyMode(aEnableHeaderOnly);
}
unsigned int
SeismicReader::GetNumberOfGathers() {
return this->mpReader->GetNumberOfGathers();
}
vector<std::vector<std::string>>
SeismicReader::GetIdentifiers() {
return this->mpReader->GetIdentifiers();
}
vector<Gather *>
SeismicReader::ReadAll() {
return this->mpReader->ReadAll();
}
vector<Gather *>
SeismicReader::Read(std::vector<std::vector<std::string>> aHeaderValues) {
return this->mpReader->Read(aHeaderValues);
}
Gather *
SeismicReader::Read(std::vector<std::string> aHeaderValues) {
return this->mpReader->Read(aHeaderValues);
}
Gather *
SeismicReader::Read(unsigned int aIndex) {
return this->mpReader->Read(aIndex);
}
| 4,214
|
C++
|
.cpp
| 124
| 29.395161
| 97
| 0.700491
|
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,214
|
InStreamHelper.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/streams/helpers/InStreamHelper.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/common/ExitCodes.hpp>
#include <bs/io/streams/helpers/InStreamHelper.hpp>
#include <bs/base/exceptions/Exceptions.hpp>
#include <bs/io/utils/convertors/NumbersConvertor.hpp>
#include <bs/io/utils/convertors/FloatingPointFormatter.hpp>
#include <bs/io/lookups/mappers/HeaderMapper.hpp>
#include <bs/io/lookups/mappers/SegyHeaderMapper.hpp>
#include <bs/io/data-units/helpers/TraceHelper.hpp>
using namespace bs::io::streams::helpers;
using namespace bs::io::dataunits;
using namespace bs::io::dataunits::helpers;
using namespace bs::io::lookups;
using namespace bs::base::exceptions;
using namespace bs::io::utils::convertors;
InStreamHelper::InStreamHelper(std::string &aFilePath)
: mFilePath(aFilePath), mFileSize(-1) {}
InStreamHelper::~InStreamHelper() = default;
size_t
InStreamHelper::Open() {
this->mInStream.open(this->mFilePath.c_str(), std::ifstream::in);
if (this->mInStream.fail()) {
throw bs::base::exceptions::FILE_NOT_FOUND_EXCEPTION();
}
return this->GetFileSize();
}
int
InStreamHelper::Close() {
this->mInStream.close();
return BS_BASE_RC_SUCCESS;
}
unsigned char *
InStreamHelper::ReadBytesBlock(size_t aStartPosition, size_t aBlockSize) {
if (aStartPosition + aBlockSize > this->GetFileSize()) {
throw INDEX_OUT_OF_BOUNDS_EXCEPTION();
}
auto buffer = new unsigned char[aBlockSize];
memset(buffer, '\0', sizeof(unsigned char) * aBlockSize);
this->mInStream.seekg(aStartPosition, std::fstream::beg);
this->mInStream.read((char *) buffer, aBlockSize);
return buffer;
}
unsigned char *
InStreamHelper::ReadTextHeader(size_t aStartPosition) {
if (aStartPosition + IO_SIZE_TEXT_HEADER > this->GetFileSize()) {
throw INDEX_OUT_OF_BOUNDS_EXCEPTION();
}
return this->ReadBytesBlock(aStartPosition, IO_SIZE_TEXT_HEADER);
}
BinaryHeaderLookup
InStreamHelper::ReadBinaryHeader(size_t aStartPosition) {
if (aStartPosition + IO_SIZE_BINARY_HEADER > this->GetFileSize()) {
throw INDEX_OUT_OF_BOUNDS_EXCEPTION();
}
auto bhl_buffer = this->ReadBytesBlock(aStartPosition, IO_SIZE_BINARY_HEADER);
BinaryHeaderLookup bhl{};
std::memcpy(&bhl, bhl_buffer, sizeof(BinaryHeaderLookup));
delete bhl_buffer;
return bhl;
}
TraceHeaderLookup
InStreamHelper::ReadTraceHeader(size_t aStartPosition) {
if (aStartPosition + IO_SIZE_TRACE_HEADER > this->GetFileSize()) {
throw INDEX_OUT_OF_BOUNDS_EXCEPTION();
}
auto thl_buffer = this->ReadBytesBlock(aStartPosition, IO_SIZE_TRACE_HEADER);
TraceHeaderLookup thl{};
std::memcpy(&thl, thl_buffer, sizeof(TraceHeaderLookup));
delete thl_buffer;
return thl;
}
Trace *
InStreamHelper::ReadFormattedTraceData(size_t aStartPosition,
TraceHeaderLookup &aTraceHeaderLookup,
BinaryHeaderLookup &aBinaryHeaderLookup) {
auto trace_size = InStreamHelper::GetTraceDataSize(aTraceHeaderLookup, aBinaryHeaderLookup);
if (aStartPosition + trace_size > this->GetFileSize()) {
throw INDEX_OUT_OF_BOUNDS_EXCEPTION();
}
auto trace_data = new char[trace_size];
this->mInStream.seekg(aStartPosition, std::fstream::beg);
this->mInStream.read(trace_data, trace_size);
size_t sample_number = InStreamHelper::GetSamplesNumber(aTraceHeaderLookup, aBinaryHeaderLookup);
auto trace_data_formatted = new char[sample_number * sizeof(float)];
FloatingPointFormatter::Format(trace_data, trace_data_formatted,
trace_size,
sample_number,
NumbersConvertor::ToLittleEndian(aBinaryHeaderLookup.FORMAT),
true);
auto trace = new Trace(NumbersConvertor::ToLittleEndian(aTraceHeaderLookup.NS));
trace->SetTraceData((float *) trace_data_formatted);
delete[] trace_data;
/* Weight trace data values according to the target formats. */
TraceHelper::Weight(trace, aTraceHeaderLookup, aBinaryHeaderLookup);
/* Set trace headers */
HeaderMapper::MapHeaderToTrace((const char *) &aTraceHeaderLookup, *trace,
SegyHeaderMapper::mLocationTable);
// Set the number of samples to the appropriate one from either binary header or trace
// header. Just in case it is not in trace header, since then the mapper won't set
// it correctly.
trace->SetTraceHeaderKeyValue(TraceHeaderKey::NS, sample_number);
return trace;
}
size_t
InStreamHelper::GetFileSize() {
if (this->mFileSize == -1) {
size_t curr_offset = this->mInStream.tellg();
this->mInStream.seekg(0, std::fstream::end);
this->mFileSize = this->mInStream.tellg();
this->mInStream.seekg(curr_offset, std::fstream::beg);
}
return this->mFileSize;
}
size_t
InStreamHelper::GetCurrentPosition() {
return this->mInStream.tellg();
}
size_t
InStreamHelper::GetTraceDataSize(const TraceHeaderLookup &aTraceHeaderLookup,
const BinaryHeaderLookup &aBinaryHeaderLookup) {
auto format = NumbersConvertor::ToLittleEndian(aBinaryHeaderLookup.FORMAT);
auto samples_number = InStreamHelper::GetSamplesNumber(aTraceHeaderLookup, aBinaryHeaderLookup);
return FloatingPointFormatter::GetFloatArrayRealSize(samples_number, format);
}
size_t
InStreamHelper::GetSamplesNumber(const TraceHeaderLookup &aTraceHeaderLookup,
const BinaryHeaderLookup &aBinaryHeaderLookup) {
auto ns = NumbersConvertor::ToLittleEndian(aTraceHeaderLookup.NS);
auto hns = NumbersConvertor::ToLittleEndian(aBinaryHeaderLookup.HNS);
auto samples_number = ns;
if (samples_number == 0) {
samples_number = hns;
}
return samples_number;
}
| 6,590
|
C++
|
.cpp
| 153
| 37.418301
| 101
| 0.714486
|
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,215
|
OutStreamHelper.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/streams/helpers/OutStreamHelper.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/common/ExitCodes.hpp>
#include <bs/io/streams/helpers/OutStreamHelper.hpp>
using namespace bs::io::streams::helpers;
OutStreamHelper::OutStreamHelper(std::string &aFilePath, bool aModify)
: mFilePath(aFilePath), mFileSize(0), mModify(aModify) {}
OutStreamHelper::~OutStreamHelper() = default;
size_t
OutStreamHelper::Open() {
if (this->mModify) {
this->mOutStream.open(this->mFilePath.c_str(), std::ofstream::out | std::ofstream::in);
this->mFileSize = -1;
} else {
this->mOutStream.open(this->mFilePath.c_str(), std::ofstream::out);
}
if (this->mOutStream.fail()) {
std::cerr << "Error opening file " << this->mFilePath << std::endl;
exit(EXIT_FAILURE);
}
return this->GetFileSize();
}
int
OutStreamHelper::Close() {
this->mOutStream.close();
return BS_BASE_RC_SUCCESS;
}
size_t
OutStreamHelper::WriteBytesBlock(const char *aData, size_t aBlockSize) {
this->mOutStream.seekp(this->mFileSize, std::fstream::beg);
this->mOutStream.write((char *) aData, sizeof(unsigned char) * aBlockSize);
this->mFileSize += aBlockSize;
return this->GetFileSize();
}
size_t
OutStreamHelper::WriteBytesBlock(const char *aData, size_t aBlockSize,
size_t aStartingPosition) {
this->mOutStream.seekp(aStartingPosition, std::fstream::beg);
this->mOutStream.write((char *) aData, sizeof(unsigned char) * aBlockSize);
size_t final_file_size = aStartingPosition + aBlockSize;
if (final_file_size > this->mFileSize) {
this->mFileSize = final_file_size;
}
return this->GetFileSize();
}
size_t
OutStreamHelper::GetFileSize() {
if (this->mFileSize == -1) {
size_t curr_offset = this->mOutStream.tellp();
this->mOutStream.seekp(0, std::fstream::end);
this->mFileSize = this->mOutStream.tellp();
this->mOutStream.seekp(curr_offset, std::fstream::beg);
}
return this->mFileSize;
}
| 2,739
|
C++
|
.cpp
| 72
| 33.791667
| 95
| 0.696422
|
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,216
|
Trace.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/data-units/concrete/Trace.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/data-units/concrete/Trace.hpp>
using namespace bs::io::dataunits;
Trace::Trace(const unsigned short aNS) {
this->mTraceHeaderMap[TraceHeaderKey(TraceHeaderKey::NS)] = std::to_string(aNS);
}
Trace::Trace(Trace &&aTrace) noexcept
: mpTraceData(std::move(aTrace.mpTraceData)) {}
Trace::Trace(const Trace &aTrace) {}
Trace::~Trace() = default;
Trace &
Trace::operator=(Trace &&aTrace) noexcept {
this->mTraceHeaderMap = aTrace.mTraceHeaderMap;
this->mpTraceData = std::move(aTrace.mpTraceData);
return *this;
}
void
Trace::SetScaledCoordinateHeader(TraceHeaderKey aKey, float aLocation) {
float scale_coordinate = 0;
if (this->HasTraceHeader(TraceHeaderKey::SCALCO)) {
scale_coordinate = this->GetTraceHeaderKeyValue<int16_t>(TraceHeaderKey::SCALCO);
}
if (scale_coordinate == 0) {
scale_coordinate = 1;
}
uint32_t val;
if (scale_coordinate > 0) {
val = (uint32_t) (aLocation / scale_coordinate);
} else {
scale_coordinate *= -1;
val = (uint32_t) (aLocation * scale_coordinate);
}
this->SetTraceHeaderKeyValue(aKey, val);
}
float
Trace::GetScaledCoordinateHeader(TraceHeaderKey aKey) {
float scale_coordinate = 0;
if (this->HasTraceHeader(TraceHeaderKey::SCALCO)) {
scale_coordinate = this->GetTraceHeaderKeyValue<int16_t>(TraceHeaderKey::SCALCO);
}
if (scale_coordinate == 0) {
scale_coordinate = 1;
}
float val;
if (scale_coordinate > 0) {
val = (float) this->GetTraceHeaderKeyValue<uint32_t>(aKey) * scale_coordinate;
} else {
scale_coordinate *= -1;
val = (float) this->GetTraceHeaderKeyValue<uint32_t>(aKey) / scale_coordinate;
}
return val;
}
| 2,489
|
C++
|
.cpp
| 69
| 32.014493
| 89
| 0.702075
|
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,217
|
Gather.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/data-units/concrete/Gather.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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 <utility>
#include <algorithm>
#include <unordered_map>
#include <bs/io/data-units/concrete/Gather.hpp>
#include <bs/io/data-units/data-types/TraceHeaderKey.hpp>
using namespace bs::io::dataunits;
Gather::Gather()
: mUniqueKeys(), mTraces() {}
Gather::Gather(std::unordered_map<TraceHeaderKey, std::string> &aUniqueKeys,
const std::vector<Trace *> &aTraces) {
this->mUniqueKeys = std::move(aUniqueKeys);
for (auto &trace : aTraces) {
this->mTraces.push_back(trace);
}
}
Gather::Gather(TraceHeaderKey aUniqueKey,
const std::string &aUniqueKeyValue,
const std::vector<Trace *> &aTraces) {
this->mUniqueKeys.insert({aUniqueKey, aUniqueKeyValue});
for (auto &trace : aTraces) {
this->mTraces.push_back(trace);
}
}
Gather::Gather(std::unordered_map<TraceHeaderKey, std::string> &aUniqueKeys)
: mTraces() {
this->mUniqueKeys = std::move(aUniqueKeys);
}
void
Gather::SortGather(const std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> &aSortingKeys) {
if (!aSortingKeys.empty()) {
sort(this->mTraces.begin(), this->mTraces.end(), trace_compare_t(aSortingKeys));
}
}
trace_compare_t::trace_compare_t(
const std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> &aSortingKeys) {
for (auto &e : aSortingKeys) {
mSortingKeys.push_back(e);
}
mKeysSize = aSortingKeys.size();
}
bool
trace_compare_t::operator()(Trace *aTrace_1, Trace *aTrace_2) const {
int i = 0;
bool swap = false;
bool ascending;
float trace_1_header, trace_2_header;
do {
trace_1_header = aTrace_1->GetTraceHeaderKeyValue<float>(mSortingKeys[i].first);
trace_2_header = aTrace_2->GetTraceHeaderKeyValue<float>(mSortingKeys[i].first);
if (trace_1_header != trace_2_header) {
break;
}
i++;
} while (i < mKeysSize);
if (i < mKeysSize) {
ascending = mSortingKeys[i].second;
if (ascending == Gather::SortDirection::ASC) {
swap = trace_1_header < trace_2_header;
} else {
swap = trace_1_header > trace_2_header;
}
}
return swap;
}
| 2,966
|
C++
|
.cpp
| 83
| 30.86747
| 103
| 0.674443
|
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,218
|
TraceHelper.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/data-units/helpers/TraceHelper.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/base/common/ExitCodes.hpp>
#include <bs/io/data-units/helpers/TraceHelper.hpp>
#include <bs/io/utils/convertors/NumbersConvertor.hpp>
using namespace bs::io::dataunits;
using namespace bs::io::dataunits::helpers;
using namespace bs::io::lookups;
using namespace bs::io::utils::convertors;
int
TraceHelper::Weight(Trace *&apTrace,
TraceHeaderLookup &aTraceHeaderLookup,
BinaryHeaderLookup &aBinaryHeaderLookup) {
return TraceHelper::WeightData(apTrace, aTraceHeaderLookup, aBinaryHeaderLookup);
}
int
TraceHelper::WeightData(Trace *&apTrace,
TraceHeaderLookup &aTraceHeaderLookup,
BinaryHeaderLookup &aBinaryHeaderLookup) {
auto format = NumbersConvertor::ToLittleEndian(aBinaryHeaderLookup.FORMAT);
/* Scale data. */
if (!(format == 1 || format == 5)) {
auto trwf = NumbersConvertor::ToLittleEndian(aTraceHeaderLookup.TRWF);
if (trwf != 0) {
float scale = std::pow(2.0, -trwf);
auto data = apTrace->GetTraceData();
for (int i = 0; i < apTrace->GetNumberOfSamples(); ++i) {
data[i] *= scale;
}
}
trwf = 0;
aTraceHeaderLookup.TRWF = NumbersConvertor::ToLittleEndian(trwf);
}
return BS_BASE_RC_SUCCESS;
}
| 2,089
|
C++
|
.cpp
| 52
| 34.557692
| 85
| 0.689163
|
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,219
|
Displayers.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/utils/displayers/Displayers.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/utils/displayers/Displayer.hpp>
#include <bs/io/lookups/tables/TextHeaderLookup.hpp>
using namespace bs::io::utils::displayers;
void
Displayer::PrintTextHeader(unsigned char *apTextHeader) {
if (apTextHeader == nullptr) {
std::cerr << "Error: Null pointer received. Nothing to be printed." << std::endl;
return;
}
for (size_t i = 0; i < IO_SIZE_TEXT_HEADER; i++) {
if ((i % 80) == 0)
std::cout << std::endl;
std::cout << apTextHeader[i];
}
std::cout << std::endl;
}
| 1,306
|
C++
|
.cpp
| 35
| 33.828571
| 89
| 0.696443
|
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,220
|
StringsConvertor.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/utils/convertors/StringsConvertor.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/exceptions/Exceptions.hpp>
#include <bs/io/utils/convertors/StringsConvertor.hpp>
using namespace bs::base::exceptions;
using namespace bs::io::utils::convertors;
short
StringsConvertor::ToShort(const std::string &aStr) {
/// @todo To be removed
/// {
throw NOT_IMPLEMENTED_EXCEPTION();
/// }
}
unsigned short
StringsConvertor::ToUShort(const std::string &aStr) {
return std::stoul(aStr);
}
int
StringsConvertor::ToInt(const std::string &aStr) {
return std::stoi(aStr);
}
unsigned int
StringsConvertor::ToUInt(const std::string &aStr) {
/// @todo To be removed
/// {
throw NOT_IMPLEMENTED_EXCEPTION();
/// }
}
long
StringsConvertor::ToLong(const std::string &aStr) {
return std::stol(aStr);
}
unsigned long
StringsConvertor::ToULong(const std::string &aStr) {
return std::stoul(aStr);
}
unsigned char *
StringsConvertor::E2A(unsigned char *apSrc, size_t aSize) {
for (size_t i = 0; i < aSize; i++) {
apSrc[i] = E2A(apSrc[i]);
}
return apSrc;
}
unsigned char
StringsConvertor::E2A(unsigned char aSrc) {
return StringsConvertor::mE2ATable[(int) (aSrc)];
}
unsigned char StringsConvertor::mE2ATable[256] = {
0, 1, 2, 3, 236, 9, 202, 127, 226, 210, 211, 11, 12, 13, 14, 15, 16, 17, 18, 19, 239,
197, 8, 203, 24, 25, 220, 216, 28, 29, 30, 31, 183, 184, 185, 187, 196, 10, 23, 27,
204, 205, 207, 208, 209, 5, 6, 7, 217, 218, 22, 221, 222, 223, 224, 4, 227, 229, 233,
235, 20, 21, 158, 26, 32, 201, 131, 132, 133, 160, 242, 134, 135, 164, 213, 046, 60,
40, 43, 179, 38, 130, 136, 137, 138, 161, 140, 139, 141, 225, 33, 36, 42, 41, 59, 94,
45, 47, 178, 142, 180, 181, 182, 143, 128, 165, 124, 44, 37, 95, 62, 63, 186, 144, 188,
189, 190, 243, 192, 193, 194, 96, 58, 35, 64, 39, 61, 34, 195, 97, 98, 99, 100, 101, 102,
103, 104, 105, 174, 175, 198, 199, 200, 241, 248, 106, 107, 108, 109, 110, 111, 112, 113,
114, 166, 167, 145, 206, 146, 15, 230, 126, 115, 116, 117, 118, 119, 120, 121, 122, 173,
168, 212, 91, 214, 215, 155, 156, 157, 250, 159, 21, 20, 172, 171, 252, 170, 254, 228,
93, 191, 231, 123, 65, 66, 67, 68, 69, 70, 71, 72, 73, 232, 147, 148, 149, 162, 237, 125, 74, 75,
76, 77, 78, 79, 80, 81, 82, 238, 150, 129, 151, 163, 152, 92, 240, 83, 84, 85, 86, 87, 88, 89, 90,
253, 245, 153, 247, 246, 249, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 219, 251, 154, 244, 234, 255
};
| 3,216
|
C++
|
.cpp
| 78
| 37.589744
| 106
| 0.64256
|
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,221
|
NumbersConvertor.cpp
|
brightskiesinc_Reverse_Time_Migration/libs/BSIO/src/utils/convertors/NumbersConvertor.cpp
|
/**
* Copyright (C) 2021 by Brightskies inc
*
* This file is part of BS I/O.
*
* BS I/O 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 I/O 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/io/utils/convertors/NumbersConvertor.hpp>
using namespace bs::io::utils::convertors;
char *
NumbersConvertor::ToLittleEndian(char *apSrc, size_t aSize, short aFormat) {
int rc = 0;
switch (aFormat) {
case 1:
/// Convert IBM float to native floats.
NumbersConvertor::ToLittleEndian((int *) apSrc, aSize);
break;
case 2:
/// Convert 4 byte two's complement integer to native floats.
/// @todo To be done
/// {
/// NumbersConvertor::ToLittleEndian((long *) apSrc, aSize);
/// }
break;
case 3:
/// Convert 2 byte two's complement integer to native floats.
NumbersConvertor::ToLittleEndian((short *) apSrc, aSize);
break;
case 5:
/// Convert IEEE float to native floats.
NumbersConvertor::ToLittleEndian((short *) apSrc, aSize);
break;
case 8:
/// Convert 1 byte two's complement integer to native floats.
NumbersConvertor::ToLittleEndian((signed char *) apSrc, aSize);
break;
}
return apSrc;
}
short int *
NumbersConvertor::ToLittleEndian(short int *apSrc, size_t aSize) {
for (int i = 0; i < aSize; ++i) {
apSrc[i] = ToLittleEndian(apSrc[i]);
}
return apSrc;
}
short int
NumbersConvertor::ToLittleEndian(short int aSrc) {
short int tmp = aSrc >> 8 & 0xFF;
return (aSrc << 8) | (tmp);
}
unsigned short int *
NumbersConvertor::ToLittleEndian(unsigned short int *apSrc, size_t aSize) {
for (int i = 0; i < aSize; ++i) {
apSrc[i] = ToLittleEndian(apSrc[i]);
}
return apSrc;
}
unsigned short int
NumbersConvertor::ToLittleEndian(unsigned short int aSrc) {
unsigned short int tmp = aSrc >> 8 & 0xFF;
return (aSrc << 8) | (tmp);
}
int *
NumbersConvertor::ToLittleEndian(int *apSrc, size_t aSize) {
for (int i = 0; i < aSize; ++i) {
apSrc[i] = ToLittleEndian(apSrc[i]);
}
return apSrc;
}
float *
NumbersConvertor::ToLittleEndian(float *apSrc, size_t aSize) {
for (int i = 0; i < aSize; ++i) {
apSrc[i] = ToLittleEndian(apSrc[i]);
}
return apSrc;
}
int
NumbersConvertor::ToLittleEndian(int aSrc) {
unsigned short int tmp1 = (aSrc >> 16 & 0x0000FFFF);
unsigned short int tmp2 = (aSrc & 0x0000FFFF);
tmp2 = NumbersConvertor::ToLittleEndian(tmp2);
tmp1 = NumbersConvertor::ToLittleEndian(tmp1);
int aDst = (int) tmp2;
aDst = aDst << 16;
aDst = aDst | (int) tmp1;
return aDst;
}
float
NumbersConvertor::ToLittleEndian(float aSrc) {
int int_src = *((int *) (&aSrc));
unsigned short int tmp1 = (int_src >> 16 & 0x0000FFFF);
unsigned short int tmp2 = (int_src & 0x0000FFFF);
tmp2 = NumbersConvertor::ToLittleEndian(tmp2);
tmp1 = NumbersConvertor::ToLittleEndian(tmp1);
int aDst = (int) tmp2;
aDst = aDst << 16;
aDst = aDst | (int) tmp1;
float dst = *((float *) (&aDst));
return dst;
}
unsigned int *
NumbersConvertor::ToLittleEndian(unsigned int *apSrc, size_t aSize) {
for (int i = 0; i < aSize; ++i) {
apSrc[i] = ToLittleEndian(apSrc[i]);
}
return apSrc;
}
unsigned int
NumbersConvertor::ToLittleEndian(unsigned int aSrc) {
unsigned short int tmp1 = (aSrc >> 16 & 0x0000FFFF);
unsigned short int tmp2 = (aSrc & 0x0000FFFF);
tmp2 = NumbersConvertor::ToLittleEndian(tmp2);
tmp1 = NumbersConvertor::ToLittleEndian(tmp1);
auto aDst = (unsigned int) tmp2;
aDst = aDst << 16;
aDst = aDst | (unsigned int) tmp1;
return aDst;
}
signed char *
NumbersConvertor::ToLittleEndian(signed char *apSrc, size_t aSize) {
for (int i = 0; i < aSize; ++i) {
apSrc[i] = ToLittleEndian(apSrc[i]);
}
return apSrc;
}
signed char
NumbersConvertor::ToLittleEndian(signed char aSrc) {
return aSrc;
}
| 4,641
|
C++
|
.cpp
| 141
| 27.985816
| 76
| 0.651708
|
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.