### Setup Model API Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Sets up the creation of essential parameters and directories for the model. ```APIDOC ## POST /api/setup_model ### Description Sets up the creation of essential parameters and directories for the model. ### Method POST ### Endpoint /api/setup_model ### Parameters #### Request Body - **rpm_factors** (dict, optional) - The rock physics model factors for generating the synthetic cube. By default the rpm factors come from a default in the main.py file ### Response #### Success Response (200) - **None** (None) - Indicates successful setup. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Model Directory Setup Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Generates all necessary directory structures on disk for the model. ```APIDOC ## POST /api/parameters/make_directories ### Description Creates the required directory structure on the file system for storing model data. ### Method POST ### Endpoint /api/parameters/make_directories ### Response #### Success Response (200) - **message** (str) - Confirmation message that directories have been created. #### Response Example { "message": "Model directories created successfully." } ``` -------------------------------- ### Setup model and directories Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Methods to initialize model parameters, create required file system directories, and write configuration files. ```python def setup_model(self, rpm_factors=None) -> None: """ Setup Model ----------- Sets up the creation of essential parameters and directories Parameters ---------- rpm_factors : `dict`, optional The rock physics model factors for generating the synthetic cube. By default the rpm factors come from a default in the main.py file Returns ------- None """ # Set model parameters self._set_model_parameters(self.model_dir_name) self.make_directories() self.write_key_file() self._setup_rpm_scaling_factors(rpm_factors) # Write model parameters to logfile self._write_initial_model_parameters_to_logfile() def make_directories(self) -> None: """ Make directories. ----------------- Creates the necessary directories to run the model. This function creates the directories on disk necessary for the model to run. Parameters ---------- self : `Parameters` Returns ------- None """ print(f"\nModel folder: {self.work_subfolder}") self.sqldict["model_id"] = pathlib.Path(self.work_subfolder).name for folder in [self.project_folder, self.work_subfolder, self.temp_folder]: try: os.stat(folder) except OSError: print(f"Creating directory: {folder}") # Try making folders (can fail if multiple models are being built simultaneously in a new dir) try: os.mkdir(folder) except OSError: pass try: os.system(f"chmod -R 777 {self.work_subfolder}") except OSError: print(f"Could not chmod {self.work_subfolder}. Continuing...") pass ``` -------------------------------- ### Setup Default FFT Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/wavelets.html Initializes a default FFT configuration with specified digitization and convolution parameters. ```python def default_fft(digi=4, convolutions=4): """Setup a default fft""" Nyquist = 0.5 * 1000.0 / digi _, s = ricker(0.12 * Nyquist, digi, convolutions=convolutions) return s, fftfreq(len(s), d=digi / 1000.0) ``` -------------------------------- ### Setup RPM scaling factors Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Initializes rock physics model scaling factors and logs them to the model parameters file. ```python def _setup_rpm_scaling_factors(self, rpm_factors: dict) -> None: """ Setup Rock Physics Model scaling factors ---------------------------------------- Method to initialize all the rock physics model scaling factors. Method also writes the values to the model_parameters log file. Parameters ---------- TODO remove the default in the main.py or have a single source of truth rpm_factors : `dict` Dictionary containing the scaling factors for the RPM. If no RPM factors are provided, the default values are used. Returns ------- None """ ``` -------------------------------- ### Setup HDF5 Environment Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Configures HDF5 file structures, including thread settings and compression filters. ```python def hdf_setup(self, hdf_name: str) -> None: """ Setup HDF files --------------- This method sets up the HDF structures Parameters ---------- hdf_name : str The name of the HDF file to be created Returns ------- None """ num_threads = min(8, mp.cpu_count() - 1) tables.set_blosc_max_threads(num_threads) self.hdf_filename = os.path.join(self.temp_folder, hdf_name) self.filters = tables.Filters( complevel=5, complib="blosc" ) # compression with fast write speed self.h5file = tables.open_file(self.hdf_filename, "w") self.h5file.create_group("/", "ModelData") ``` -------------------------------- ### Setup Model Configuration Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Initializes model parameters, creates required directories, writes key files, and sets RPM scaling factors. It also logs the initial model parameters. ```python def setup_model(self, rpm_factors=None) -> None: """ Setup Model ----------- Sets up the creation of essential parameters and directories Parameters ---------- rpm_factors : `dict`, optional The rock physics model factors for generating the synthetic cube. By default the rpm factors come from a default in the main.py file Returns ------- None """ # Set model parameters self._set_model_parameters(self.model_dir_name) self.make_directories() self.write_key_file() self._setup_rpm_scaling_factors(rpm_factors) # Write model parameters to logfile self._write_initial_model_parameters_to_logfile() ``` -------------------------------- ### Setup Model Parameters and Directories Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Initializes model parameters and creates required directories for seismic data synthesis. It optionally accepts rock physics model factors. ```python def setup_model(self, rpm_factors=None) -> None: """ Setup Model ----------- Sets up the creation of essential parameters and directories Parameters ---------- rpm_factors : `dict`, optional The rock physics model factors for generating the synthetic cube. By default the rpm factors come from a default in the main.py file Returns ------- None """ # Set model parameters self._set_model_parameters(self.model_dir_name) self.make_directories() self.write_key_file() self._setup_rpm_scaling_factors(rpm_factors) # Write model parameters to logfile self._write_initial_model_parameters_to_logfile() ``` -------------------------------- ### Setup Model API Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html This endpoint is used to set up the creation of essential parameters and directories for the seismic synthesis model. It can optionally accept rock physics model factors. ```APIDOC ## POST /api/models/setup ### Description Sets up the creation of essential parameters and directories for the seismic synthesis model. ### Method POST ### Endpoint /api/models/setup ### Parameters #### Request Body - **rpm_factors** (dict) - Optional - The rock physics model factors for generating the synthetic cube. By default, the rpm factors come from a default in the main.py file. ### Request Example ```json { "rpm_factors": { "vp_rho": 0.25, "vs_vp": 0.5, "rho_intercept": 1.8, "poisson_intercept": 0.3 } } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful setup. #### Response Example ```json { "message": "Model setup complete." } ``` ``` -------------------------------- ### Main Execution Block Example Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Horizons.html This block demonstrates how to initialize parameters, set up the model, build depth maps, and then create the facies array using the create_facies_array function. It's typically used for running the script directly. ```python if __name__ == "__main__": par = Parameters(user_config="../config/config_bps.json", test_mode=100) par.setup_model() # p.cube_shape = (100, 100, 1250) zmaps, onlaps, fan_list, fan_thickness = build_unfaulted_depth_maps(par) facies = create_facies_array(par, zmaps, onlaps, fan_list) print(facies) ``` -------------------------------- ### Write Initial Model Parameters to Logfile Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Logs the initial model parameters to a logfile. This includes the git commit hash, start time, project folder, cube shape, incident angles, number of faults, filter size, and salt insertion parameters. ```python def _write_initial_model_parameters_to_logfile(self) -> None: """ Write Initial Model Parameters to Logfile ---------------------------------------- Method that writes the initial parameters set for the model to the logfile. Parameters ---------- None Returns ------- None """ _sha = self._get_commit_hash() self.write_to_logfile( f"SHA: {_sha}", mainkey="model_parameters", subkey="sha", val=_sha ) self.write_to_logfile( f"modeling start time: {self.start_time}", mainkey="model_parameters", subkey="start_time", val=self.start_time, ) self.write_to_logfile( f"project_folder: {self.project_folder}", mainkey="model_parameters", subkey="project_folder", val=self.project_folder, ) self.write_to_logfile( f"work_subfolder: {self.work_subfolder}", mainkey="model_parameters", subkey="work_subfolder", val=self.work_subfolder, ) self.write_to_logfile( f"cube_shape: {self.cube_shape}", mainkey="model_parameters", subkey="cube_shape", val=self.cube_shape, ) self.write_to_logfile( f"incident_angles: {self.incident_angles}", mainkey="model_parameters", subkey="incident_angles", val=self.incident_angles, ) self.write_to_logfile( f"number_faults: {self.number_faults}", mainkey="model_parameters", subkey="number_faults", val=self.number_faults, ) self.write_to_logfile( f"lateral_filter_size: {self.lateral_filter_size}", mainkey="model_parameters", subkey="lateral_filter_size", val=self.lateral_filter_size, ) self.write_to_logfile( f"salt_inserted: {self.include_salt}", mainkey="model_parameters", subkey="salt_inserted", val=self.include_salt, ) self.write_to_logfile( f"salt noise_stretch_factor: {self.noise_stretch_factor:.2f}", mainkey="model_parameters", subkey="salt_noise ``` -------------------------------- ### Get Fault Mode Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Faults.html Retrieves the current fault mode configuration. ```APIDOC ## GET /sede-open/synthoseis/fault_mode ### Description Returns a dictionary containing the fault parameters. ### Method GET ### Endpoint /sede-open/synthoseis/fault_mode ### Response #### Success Response (200) - **fault_mode** (dict) - Dictionary containing the fault parameters. #### Response Example { "fault_mode": { "param1": "value1", "param2": "value2" } } ``` -------------------------------- ### GET /internal/commit-hash Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Retrieves the current git commit hash of the repository. ```APIDOC ## GET /internal/commit-hash ### Description Retrieves the commit hash of the current git repository. ### Method GET ### Response #### Success Response (200) - **sha** (string) - The commit hash of the current git repository. ``` -------------------------------- ### GET /build_meshgrid Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Geomodels.html Creates a meshgrid using the data stored in the Geomodel. ```APIDOC ## GET /build_meshgrid ### Description Creates a meshgrid using the data in the Geomodel based on the configured cube shape. ### Method GET ### Endpoint /build_meshgrid ### Response #### Success Response (200) - **meshgrid** (np.darray) - A meshgrid of the data in the Geomodel. ``` -------------------------------- ### hdf_setup Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Initializes the HDF file structure and sets up compression filters. ```APIDOC ## hdf_setup ### Description This method sets up the HDF structures, including configuring thread counts, compression filters, and creating the initial file group. ### Parameters #### Path Parameters - **hdf_name** (str) - Required - The name of the HDF file to be created ### Response #### Success Response (200) - **None** (None) ``` -------------------------------- ### HDF: hdf_setup Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Initializes the HDF5 file structure and sets up compression filters. ```APIDOC ## POST /hdf/setup ### Description Sets up the HDF structures and initializes the file with compression. ### Parameters #### Request Body - **hdf_name** (str) - Required - The name of the HDF file to be created ``` -------------------------------- ### Get Fault Centre Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Faults.html Calculates the center of a fault plane within seismic data. ```APIDOC ## POST /api/faults/get_fault_centre ### Description Retrieves the center of a fault plane by intersecting an ellipsoid with a cube and analyzing seismic data. ### Method POST ### Endpoint /api/faults/get_fault_centre ### Parameters #### Request Body - **ellipsoid** (array) - Required - The ellipsoid data. - **wb_time_map** (array) - Required - The time map data. - **z_on_ellipse** (array) - Required - Z-coordinates on the ellipse. - **index** (int) - Required - Index for data selection. ### Request Example ```json { "ellipsoid": [[[0.1, 0.2], [0.3, 0.4]], [[0.5, 0.6], [0.7, 0.8]]], "wb_time_map": [[1.0, 2.0], [3.0, 4.0]], "z_on_ellipse": [0.1, 0.2], "index": 0 } ``` ### Response #### Success Response (200) - **direction** (int) - The calculated direction or an indicator if no intersection is found. #### Response Example ```json { "direction": 1 } ``` ``` -------------------------------- ### Internal Method: _setup_rpm_scaling_factors Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Initializes Rock Physics Model (RPM) scaling factors and logs them to the model parameters file. ```APIDOC ## _setup_rpm_scaling_factors ### Description Initializes all rock physics model scaling factors and writes these values to the model_parameters log file. ### Method Internal Python Method ### Parameters - **rpm_factors** (dict) - Required - Dictionary containing the scaling factors for the RPM. If not provided, default values are used. ``` -------------------------------- ### Get Fault Parameters Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Faults.html Retrieves the fault parameters using a factory design pattern. ```APIDOC ## GET /fault_parameters ### Description Returns the fault parameters. Factory design pattern used to select fault parameters. ### Method GET ### Endpoint /fault_parameters ### Parameters #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **fault_mode** (dict) - Dictionary containing the fault parameters. #### Response Example { "fault_mode": { "example_param_1": "value1", "example_param_2": "value2" } } ``` -------------------------------- ### GET /infilled_cube_shape Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Geomodels.html Calculates and returns the shape of the infilled cube based on configuration parameters. ```APIDOC ## GET /infilled_cube_shape ### Description Calculates the dimensions of the infilled cube using the configured cube shape, padding samples, and infill factor. ### Method GET ### Endpoint /infilled_cube_shape ### Response #### Success Response (200) - **cube_shape** (tuple) - The calculated dimensions of the infilled cube. ``` -------------------------------- ### GET /fault_parameters Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Faults.html Retrieves the parameters used for fault generation using a factory design pattern. ```APIDOC ## GET /fault_parameters ### Description Returns the fault parameters used for the simulation. This method utilizes a factory design pattern to select the appropriate parameters based on the current configuration. ### Method GET ### Endpoint /fault_parameters ### Response #### Success Response (200) - **fault_parameters** (object) - The collection of parameters (a, b, c, x0, y0, z0, throw, tilt_pct, etc.) used for fault generation. ``` -------------------------------- ### Get Search Term Function Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Closures.html Retrieves the current search term from the URL's query parameters. ```javascript function getSearchTerm() { return (new URL(window.location)).searchParams.get("search"); } ``` -------------------------------- ### Initialize Model Parameters Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Initializes directory paths, reads configuration from JSON, and sets up various model-specific parameters. ```python def _set_model_parameters(self, dname: str) -> None: """ Set Model Parameters ---------------------------------------- Method that sets model parameters from user-provided config.json file Parameters ---------- dname : `str` Directory name specified in the configuration file, or the default is used Returns ------- None """ self.current_dir = os.getcwd() self.start_time = datetime.datetime.now() self.date_stamp = self.year_plus_fraction() # Read from input json self.parameters_json = self._read_json() self._read_user_params() # Directories model_dir = f"{dname}__{self.date_stamp}" temp_dir = f"temp_folder__{self.date_stamp}" self.work_subfolder = os.path.abspath( os.path.join(self.project_folder, model_dir) ) self.temp_folder = os.path.abspath( os.path.join(self.work_folder, f"temp_folder__{self.date_stamp}") ) if self.runid: self.work_subfolder = f"{self.work_subfolder}_{self.runid}" self.temp_folder = f"{self.temp_folder}_{self.runid}" # Various model parameters, not in config self.num_lyr_lut = self.cube_shape[2] * 2 * self.infill_factor # 2500 voxels = 25x25x4m voxels size, 25% porosity and closures > ~40,000 bbl # Use the minimum voxel count as initial closure size filter self.closure_min_voxels = min( self.closure_min_voxels_simple, self.closure_min_voxels_faulted, self.closure_min_voxels_onlap, ) self.order = self.bandwidth_ord if self.test_mode: self._set_test_mode(self.test_mode, self.test_mode) # Random choices are separated into this method self._randomly_chosen_model_parameters() # Fault choices self._fault_settings() # Logfile self.logfile = os.path.join( ``` -------------------------------- ### Get Fault Plane Sobel Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Faults.html Detects fault planes in seismic data using Sobel filters. ```APIDOC ## POST /api/faults/get_fault_plane_sobel ### Description Detects fault planes in a given ellipsoid data using Sobel edge detection and maximum filtering. ### Method POST ### Endpoint /api/faults/get_fault_plane_sobel ### Parameters #### Request Body - **test_ellipsoid** (array) - Required - The input ellipsoid data array. ### Request Example ```json { "test_ellipsoid": [[[0.1, 0.2], [0.3, 0.4]], [[0.5, 0.6], [0.7, 0.8]]] } ``` ### Response #### Success Response (200) - **fault_segments** (array) - The detected fault segments. #### Response Example ```json { "fault_segments": [[[0.0, 0.0], [0.0, 0.0]], [[0.0, 0.0], [0.0, 0.0]]] } ``` ``` -------------------------------- ### Initialize SaltModel Class Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Salt.html Initializes the SaltModel class with project parameters and sets up the HDF5 file for salt segments. ```python class SaltModel: def __init__(self, parameters) -> None: """ Initialization function ----------------------- Initializes the SaltModel class. Parameters ---------- parameters : datagenerator.Parameters The parameters of the project. Returns ------- None """ self.cfg = parameters cube_shape = ( self.cfg.cube_shape[0], self.cfg.cube_shape[1], self.cfg.cube_shape[2] + self.cfg.pad_samples, ) self.salt_segments = self.cfg.hdf_init("salt_segments", shape=cube_shape) self.points = [] ``` -------------------------------- ### Get Next Markov State Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Horizons.html Returns the next state based on the current state and the transition matrix. ```python def next_state(self, current_state): """Returns the state of the random variable at the next instance. Parameters ---------- current_state :str The current state of the system """ return np.random.choice( self.states, p=self.transition[self.index_dict[current_state], :] ) ``` -------------------------------- ### Initialize HDF5 File Structure Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Sets up HDF5 file environment with compression filters and creates the ModelData group. ```python def hdf_setup(self, hdf_name: str) -> None: """ Setup HDF files --------------- This method sets up the HDF structures Parameters ---------- hdf_name : str The name of the HDF file to be created Returns ------- None """ num_threads = min(8, mp.cpu_count() - 1) tables.set_blosc_max_threads(num_threads) self.hdf_filename = os.path.join(self.temp_folder, hdf_name) self.filters = tables.Filters( complevel=5, complib="blosc" ) # compression with fast write speed self.h5file = tables.open_file(self.hdf_filename, "w") self.h5file.create_group("/", "ModelData") ``` -------------------------------- ### SaltModel.__init__ Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Salt.html Initializes the SaltModel class with project parameters and prepares the HDF5 storage for salt segments. ```APIDOC ## SaltModel.__init__ ### Description Initializes the SaltModel class and sets up the internal configuration and HDF5 storage for salt segments. ### Parameters #### Request Body - **parameters** (datagenerator.Parameters) - Required - The parameters of the project. ``` -------------------------------- ### Generate Sequence of Markov States Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Horizons.html Generates a sequence of states of a specified length starting from a given state. ```python def generate_states(self, current_state, num=100): """Generate states of the system with length num Parameters ---------- current_state : str The state of the current random variable num : int, optional [description], by default 100 """ future_states = [] for _ in range(num): next_state = self.next_state(current_state) future_states.append(next_state) current_state = next_state return np.array(future_states) ``` -------------------------------- ### Get Fault Mode Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Faults.html Determines the appropriate fault parameterization method based on the configuration mode and clustering settings. ```python def _get_fault_mode(self): if self.cfg.mode == 0: return self._fault_params_random elif self.cfg.mode == 1.0: if self.cfg.clustering == 0: return self._fault_params_self_branching elif self.cfg.clustering == 1: return self._fault_params_stairs elif self.cfg.clustering == 2: return self._fault_params_relay_ramps else: raise ValueError(self.cfg.clustering) elif self.cfg.mode == 2.0: return self._fault_params_horst_graben else: raise ValueError(self.cfg.mode) ``` -------------------------------- ### Initialize Matplotlib for Plotting Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Faults.html Imports the matplotlib library and initializes a figure for plotting. This is a setup step for creating visualizations. ```python import os from datagenerator.util import import_matplotlib plt = import_matplotlib() plt.figure(1, figsize=(15, 10)) plt.clf() ``` -------------------------------- ### Initialize SaltModel Class Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Salt.html Initializes the SaltModel class with project parameters. It sets up the cube shape and initializes the salt segments storage. ```python def __init__(self, parameters) -> None: """ Initialization function ----------------------- Initializes the SaltModel class. Parameters ---------- parameters : datagenerator.Parameters The parameters of the project. Returns ------- None """ self.cfg = parameters cube_shape = ( self.cfg.cube_shape[0], self.cfg.cube_shape[1], self.cfg.cube_shape[2] + self.cfg.pad_samples, ) self.salt_segments = self.cfg.hdf_init("salt_segments", shape=cube_shape) self.points = [] ``` -------------------------------- ### Get Fault Plane Sobel Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Faults.html Applies a Sobel filter to identify fault planes within a 3D ellipsoid volume. ```python @staticmethod def get_fault_plane_sobel(test_ellipsoid): from scipy.ndimage import sobel from scipy.ndimage import maximum_filter test_ellipsoid[test_ellipsoid <= 1.0] = 0.0 inside = np.zeros_like(test_ellipsoid) ``` -------------------------------- ### GET /get_displacement_vector Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Faults.html Calculates a displacement vector based on provided geological parameters, including semi-axes, origin, throw, and tilt. ```APIDOC ## GET /get_displacement_vector ### Description Calculates a displacement vector for fault modeling. It computes random shear zone widths and gouge percentiles, rotates a 3D ellipsoid, and determines fault segments and centers. ### Parameters #### Path Parameters - **semi_axes** (tuple) - Required - The semi axes of the ellipsoid. - **origin** (tuple) - Required - The origin coordinates. - **throw** (float) - Required - The throw of the fault to use. - **tilt** (float) - Required - The tilt of the fault. - **wb** (object) - Required - Water bottom or boundary data. - **index** (int) - Required - Index for storing random values. - **fp** (dict) - Required - Fault properties dictionary for storing results. ### Response #### Success Response (200) - **stretch_times** (np.ndarray) - The stretch times. - **stretch_times_classification** (np.ndarray) - Stretch times classification. - **interpolation** (bool) - Whether or not to interpolate. - **hockey_stick** (int) - The hockey stick value. - **fault_segments** (np.ndarray) - The calculated fault segments. ``` -------------------------------- ### Initialize Parameters Object Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Constructor for the Parameters class, setting up default configurations and state dictionaries. ```python def __init__(self, user_config: str = CONFIG_PATH, test_mode=None, runid=None): """ Initialize the Parameters object. Parameters ---------- user_config : `str`, optional This is the path on disk that points to a `.json` file that contains the configurations for each run, by default CONFIG_PATH test_mode : `int`, optional The parameter that sets the running mode, by default 0 runid : `str`, optional This is the runid of the run, this comes in handy when you have many runs with various permutations of parameters, by default None """ # reset the parameter dict in case we are building models within a loop, and the shared_state dict is not empty self._shared_state = {} super().__init__() self.model_dir_name: str = "seismic" self.parameter_file = user_config self.test_mode = test_mode self.runid = runid self.rpm_scaling_factors = dict() self.sqldict = defaultdict(dict) ``` -------------------------------- ### Initialize 3D Plotter and Volumetric Slices Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/util.html Sets up the initial plotter state and creates x, y, and z slices from a volume with lighting and scalar bars. ```python vp.show(box, newPlotter=True, interactive=False) # inits visibles = [None, None, None] cmap = cmaps[0] dims = vol.dimensions() i_init = 0 msh = vol.xSlice(i_init).pointColors(cmap=cmap).lighting("", la, ld, 0) msh.addScalarBar(pos=(0.04, 0.0), horizontal=True, titleFontSize=0) vp.renderer.AddActor(msh) visibles[0] = msh j_init = 0 msh2 = vol.ySlice(j_init).pointColors(cmap=cmap).lighting("", la, ld, 0) msh2.addScalarBar(pos=(0.04, 0.0), horizontal=True, titleFontSize=0) vp.renderer.AddActor(msh) visibles[1] = msh2 k_init = 0 msh3 = vol.zSlice(k_init).pointColors(cmap=cmap).lighting("", la, ld, 0, 0) msh3.addScalarBar(pos=(0.04, 0.0), horizontal=True, titleFontSize=0) vp.renderer.AddActor(msh3) visibles[2] = msh3 ``` -------------------------------- ### SaltModel Initialization Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Salt.html Initializes the SaltModel class with project parameters and prepares the salt segments storage. ```APIDOC ## SaltModel.__init__ ### Description Initializes the SaltModel class and sets up the HDF5 storage for salt segments based on the provided configuration. ### Parameters #### Request Body - **parameters** (datagenerator.Parameters) - Required - The parameters of the project. ``` -------------------------------- ### Get Delta Z Properties Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Seismic.html Retrieves randomized property shifts for density and velocity if the layer index is beyond the first random layer. ```python def get_delta_z_properties(self, z, half_range): if z > self.first_random_lyr: delta_z_rho, delta_z_vp, delta_z_vs = self.random_z_rho_vp_vs( dmin=-half_range, dmax=half_range ) else: delta_z_rho, delta_z_vp, delta_z_vs = (0, 0, 0) return delta_z_rho, delta_z_vp, delta_z_vs ``` -------------------------------- ### Initialize SaltModel Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Salt.html Initializes the SaltModel class with project parameters. It sets up the configuration and initializes the salt segments array based on cube shape and padding. ```python class SaltModel: """ Salt Model Class ---------------- This class creates a 3D salt body and inserts it into the input cube. """ def __init__(self, parameters) -> None: """ Initialization function ----------------------- Initializes the SaltModel class. Parameters ---------- parameters : datagenerator.Parameters The parameters of the project. Returns ------- None """ self.cfg = parameters cube_shape = ( self.cfg.cube_shape[0], self.cfg.cube_shape[1], self.cfg.cube_shape[2] + self.cfg.pad_samples, ) self.salt_segments = self.cfg.hdf_init("salt_segments", shape=cube_shape) self.points = [] ``` -------------------------------- ### Get Fault Plane via Sobel Filter Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Faults.html Identifies fault segments by applying a Sobel filter to an ellipsoid mask and normalizing with a maximum filter. ```python @staticmethod def get_fault_plane_sobel(test_ellipsoid): from scipy.ndimage import sobel from scipy.ndimage import maximum_filter test_ellipsoid[test_ellipsoid <= 1.0] = 0.0 inside = np.zeros_like(test_ellipsoid) inside[test_ellipsoid <= 1.0] = 1.0 # method 2 edge = ( np.abs(sobel(inside, axis=0)) + np.abs(sobel(inside, axis=1)) + np.abs(sobel(inside, axis=-1)) ) edge_max = maximum_filter(edge, size=(5, 5, 5)) edge_max[edge_max == 0.0] = 1e6 fault_segments = edge / edge_max fault_segments[np.isnan(fault_segments)] = 0.0 fault_segments[fault_segments < 0.5] = 0.0 fault_segments[fault_segments > 0.5] = 1.0 return fault_segments ``` -------------------------------- ### Run a Synthoseis model Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator.html Execute the main generation script using a specified configuration file and run parameters. ```bash conda activate synthoseis python main.py --config config/example.json --num_runs 1 --run_id seismic_example ``` -------------------------------- ### Initialize Markov Chain State Manager Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Horizons.html Initializes the Markov Chain with sand fraction and thickness parameters, calculating the transition matrix. ```python self.sand_fraction = sand_fraction self.sand_thickness = sand_thickness self.states = states self.index_dict = { self.states[index]: index for index in range(len(self.states)) } self.state_dict = { index: self.states[index] for index in range(len(self.states)) } self._transition_matrix() ``` -------------------------------- ### Get Delta Z Layer Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Seismic.html Calculates a random vertical shift for a layer if it exceeds the first random layer threshold, with optional verbose logging. ```python def get_delta_z_layer(self, z, half_range, z_cells): if z > self.first_random_lyr: delta_z_layer = int(np.random.uniform(-half_range, half_range)) else: delta_z_layer = 0 if self.cfg.verbose: print(f" .... Layer {z}: voxel_count = {len(z_cells)}") print(f" .... Layer {z}: delta_z_layer = {delta_z_layer}") print( f" .... Layer {z}: z-range (m): {np.min(z_cells) * self.cfg.digi}, " f"{np.max(z_cells) * self.cfg.digi}" ) return delta_z_layer ``` -------------------------------- ### Run FluvSim Simulation Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/fluvsim.html Sets up, compiles, and runs the FluvSim Fortran code. It copies the Fortran source, creates a parameters file, compiles the code, executes the simulation, and optionally plots the results. Ensure 'create_fluvsim_params' is available and FluvSim Fortran code is in the correct location. ```python def run_fluvsim(nx=100, ny=100, maxthickness=50, work_folder='/scratch', quiet=True): current_dir = os.getcwd() code_dir = os.path.join(os.path.abspath(os.path.dirname(__file__))) code_file = os.path.join(code_dir, "fluvsim.f90") workfolder_code_file = os.path.join(work_folder, "fluvsim.f90") os.system("cp " + code_file + " " + workfolder_code_file) try: workfolder_output = os.path.abspath(os.path.join(work_folder, "output")) os.system("mkdir -p " + workfolder_output + "&>/scratch/outputfile") except OSError: pass os.chdir(work_folder) fortran_code_file = os.path.abspath(os.path.join(work_folder, "fluvsim.f90")) compiled_fortran_code_file = "./fluvsim.o" return_code_2 = os.system( "gfortran " + fortran_code_file + " -o " + compiled_fortran_code_file ) if return_code_2 != 0: print("...retrieving fluvsim.o from code repository....") os.system( "cp -p " + os.path.join(code_dir, "fluvsim2.o") + " " + compiled_fortran_code_file ) create_fluvsim_params( nx=nx, ny=ny, maxthickness=maxthickness, work_folder=work_folder ) os.chdir(work_folder) os.system( compiled_fortran_code_file + "&>" + os.path.join(work_folder, "fluvsim_output.txt") ) facies = read_fluvsim_output(nx, ny, maxthickness, work_folder=work_folder) if quiet: # TODO save plots to output dir? xsection = 10 ysection = 10 zsection = 30 plt.figure(1, figsize=(15, 9)) plt.subplot(2, 1, 1) temp = facies[xsection, :, :] plt.imshow(np.rot90(temp)) plt.title("xsection = " + str(xsection)) plt.subplot(2, 1, 2) temp = facies[:, ysection, :] plt.imshow(np.rot90(temp)) plt.title("ysection = " + str(ysection)) plt.figure(2, figsize=(10, 10)) temp = facies[:, :, zsection] plt.imshow(temp) plt.title("zsection = " + str(zsection)) plt.show() os.chdir(current_dir) return facies ``` -------------------------------- ### Get Delta Z Properties for Randomization Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Seismic.html Calculates random variations (delta_z_rho, delta_z_vp, delta_z_vs) for seismic properties if the current layer is above the randomization threshold. ```python def get_delta_z_properties(self, z, half_range): if z > self.first_random_lyr: delta_z_rho, delta_z_vp, delta_z_vs = self.random_z_rho_vp_vs( dmin=-half_range, dmax=half_range ) else: delta_z_rho, delta_z_vp, delta_z_vs = (0, 0, 0) return delta_z_rho, delta_z_vp, delta_z_vs ``` -------------------------------- ### Create Model Directories Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Creates the necessary project, work, and temporary directories on disk. It also attempts to set directory permissions using chmod. ```python def make_directories(self) -> None: """ Make directories. ----------------- Creates the necessary directories to run the model. This function creates the directories on disk necessary for the model to run. Parameters ---------- self : `Parameters` Returns ------- None """ print(f"\nModel folder: {self.work_subfolder}") self.sqldict["model_id"] = pathlib.Path(self.work_subfolder).name for folder in [self.project_folder, self.work_subfolder, self.temp_folder]: try: os.stat(folder) except OSError: print(f"Creating directory: {folder}") # Try making folders (can fail if multiple models are being built simultaneously in a new dir) try: os.mkdir(folder) except OSError: pass try: os.system(f"chmod -R 777 {self.work_subfolder}") except OSError: print(f"Could not chmod {self.work_subfolder}. Continuing...") pass ``` -------------------------------- ### Get Channel Bank Coordinates Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/meanderpy.html Calculates the coordinates of channel banks given a centerline and a channel width. This function is essential for defining the boundaries of a channel. ```python def get_channel_banks(x, y, W): """function for finding coordinates of channel banks, given a centerline and a channel width x,y - coordinates of centerline ``` -------------------------------- ### Log Model Parameters to Configuration Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Closures.html Logs statistical metrics for unit thicknesses to the configuration logfile. ```python subkey="sand_unit_thickness_combined_min", val=np.min(avg_sand_thickness), ) self.cfg.write_to_logfile( msg=None, mainkey="model_parameters", subkey="sand_unit_thickness_combined_max", val=np.max(avg_sand_thickness), ) # self.cfg.write_to_logfile( msg=None, mainkey="model_parameters", subkey="shale_unit_thickness_combined_mean", val=np.mean(avg_shale_thickness), ) self.cfg.write_to_logfile( msg=None, mainkey="model_parameters", subkey="shale_unit_thickness_combined_std", val=np.std(avg_shale_thickness), ) self.cfg.write_to_logfile( msg=None, mainkey="model_parameters", subkey="shale_unit_thickness_combined_min", val=np.min(avg_shale_thickness), ) self.cfg.write_to_logfile( msg=None, mainkey="model_parameters", subkey="shale_unit_thickness_combined_max", val=np.max(avg_shale_thickness), ) self.cfg.write_to_logfile( msg=None, mainkey="model_parameters", subkey="overall_unit_thickness_combined_mean", val=np.mean(avg_unit_thickness), ) self.cfg.write_to_logfile( msg=None, mainkey="model_parameters", subkey="overall_unit_thickness_combined_std", val=np.std(avg_unit_thickness), ) self.cfg.write_to_logfile( msg=None, mainkey="model_parameters", subkey="overall_unit_thickness_combined_min", val=np.min(avg_unit_thickness), ) self.cfg.write_to_logfile( msg=None, mainkey="model_parameters", subkey="overall_unit_thickness_combined_max", val=np.max(avg_unit_thickness), ) ``` -------------------------------- ### Get Delta Z Layer for Randomization Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Seismic.html Determines a random vertical shift (delta_z_layer) for voxels above a certain layer threshold. Includes verbose printing of layer information. ```python def get_delta_z_layer(self, z, half_range, z_cells): if z > self.first_random_lyr: delta_z_layer = int(np.random.uniform(-half_range, half_range)) else: delta_z_layer = 0 if self.cfg.verbose: print(f" .... Layer {z}: voxel_count = {len(z_cells)}") print(f" .... Layer {z}: delta_z_layer = {delta_z_layer}") print( f" .... Layer {z}: z-range (m): {np.min(z_cells) * self.cfg.digi}, " f"{np.max(z_cells) * self.cfg.digi}" ) return delta_z_layer ``` -------------------------------- ### Get Git Commit Hash Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Parameters.html Retrieves the git commit hash of the current repository. Returns 'cwd not a git repository' if the current directory is not part of a git repository. ```python def _get_commit_hash(self) -> str: """ Get Commit Hash ------------- Gets the commit hash of the current git repository. #TODO Explain what this is for exactly Parameters ---------- None Returns ------- sha : `str` The commit hash of the current git repository """ try: sha = ( subprocess.check_output(["git", "rev-parse", "HEAD"]) .decode("utf-8") .strip() ) except CalledProcessError: sha = "cwd not a git repository" return sha ``` -------------------------------- ### default_fft Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/wavelets.html Sets up a default FFT configuration. ```APIDOC ## default_fft(digi=4, convolutions=4) ### Description Initializes a default FFT setup using a Ricker wavelet. ### Parameters - **digi** (int) - Optional - Digitization parameter (default: 4). - **convolutions** (int) - Optional - Number of convolutions (default: 4). ### Response - **s** (array) - Wavelet array. - **freq** (array) - Frequency array. ``` -------------------------------- ### Initialize Relay Ramps Parameters Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Faults.html Sets up initial configuration bounds for relay ramp fault generation. ```python def _fault_params_relay_ramps(self): print(" ... relay ramps") # Initialize value for first fault # Maximum of 3 fault per ramp x0_min = int(self.cfg.cube_shape[0] / 4.0) x0_max = int(self.cfg.cube_shape[0] / 2.0) y0_min = int(self.cfg.cube_shape[1] / 4.0) y0_max = int(self.cfg.cube_shape[1] / 2.0) ``` -------------------------------- ### ChannelBelt3D.__init__ Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/meanderpy.html Initializes a new ChannelBelt3D object with the necessary spatial and stratigraphic data. ```APIDOC ## ChannelBelt3D.__init__ ### Description Initializes the ChannelBelt3D object with model parameters and spatial data. ### Parameters - **model_type** (string) - Required - Type of model to be built; can be either 'fluvial' or 'submarine'. - **topo** (numpy.ndarray) - Required - Set of topographic surfaces (3D array). - **strat** (numpy.ndarray) - Required - Set of stratigraphic surfaces (3D array). - **facies** (numpy.ndarray) - Required - Facies volume (3D array). - **facies_code** (dict) - Required - Dictionary of facies codes, e.g., {0:'oxbow', 1:'point bar', 2:'levee'}. - **dx** (float) - Required - Gridcell size in meters. - **channels** (list) - Required - List of channel objects that form the 3D model. ``` -------------------------------- ### Initialize BasinFloorFans Class Source: https://github.com/sede-open/synthoseis/blob/master/docs/datagenerator/Horizons.html Initializes the BasinFloorFans class with parameters and the maximum number of layers. The fan lookup table generation is commented out. ```python class BasinFloorFans(Horizons): def __init__(self, parameters, max_layers): self.cfg = parameters self.max_layers = max_layers self.fan_layers = None # self._generate_fan_lookup_table() ```