Download LIDE_generator_script/generator.py from ComplexMultiphaseFlows/LIDE: direct link, hf CLI and curl.
- Browser
- Download file 6.39 kB
-
https://huggingface.co/datasets/ComplexMultiphaseFlows/LIDE/resolve/fbf6416b311dfb5ecc25c45329ef5a2ee1aa86b9/LIDE_generator_script/generator.py
- Command line
-
hf download hf://datasets/ComplexMultiphaseFlows/LIDE@fbf6416b311dfb5ecc25c45329ef5a2ee1aa86b9/LIDE_generator_script/generator.py
-
curl -L -o generator.py https://huggingface.co/datasets/ComplexMultiphaseFlows/LIDE/resolve/fbf6416b311dfb5ecc25c45329ef5a2ee1aa86b9/LIDE_generator_script/generator.py
6.39 kB
| """ | |
| This script generates input files for ALPACA simulations of LIDE by varying key parameters using a Sobol sequence for sampling. | |
| Change the parameters in the 'param_bounds' array to modify the ranges for high pressure, low pressure, laser width, and droplet radii. | |
| First creates a set of .xml input files using "create_alpaca_input" function, then runs ALPACA on each generated input file using "run_alpaca" function. | |
| For this change the number of simualtions and paths at the end of the script. | |
| Keep the default.xml file in the same directory as this script as the code overwrites it to create new input files. | |
| """ | |
| import os | |
| import subprocess | |
| import logging | |
| import time | |
| import math | |
| import html | |
| import re | |
| from scipy.stats.qmc import Sobol, scale | |
| from scipy.stats import qmc | |
| import xmltodict | |
| import numpy as np | |
| import warnings | |
| def run_alpaca( | |
| xml_file, | |
| output_dir: str = None, | |
| mpiexec_path: str = None, | |
| exec_file_path: str = None, | |
| num_workers: int = 10, | |
| ): | |
| """ | |
| Runs ALPACA with different parameters in .xml file. | |
| Args: | |
| xml_file (str): Path to the input .xml file to be processed. | |
| mpiexec_path (str): Path to the mpiexec executable. Find using command "which mpiexec" in terminal. | |
| exec_file_path (str): Path to the ALPACA executable file. Default is "./build/ALPACA". | |
| num_workers (int): Number of cpu workers for parallel processing. | |
| output_dir (str): Directory where output files will be saved. | |
| """ | |
| # Setup logging | |
| logging.basicConfig( | |
| filename=os.path.join(str(output_dir), 'data_generator.log'), | |
| level=logging.INFO, | |
| format='%(asctime)s [%(levelname)s] %(message)s' | |
| ) | |
| # Check for executable ALAPACA location in command | |
| command = [str(mpiexec_path), "-n", str(num_workers), str(exec_file_path), str(xml_file), str(output_dir)] | |
| logging.info(f"Starting: {' '.join(command)}") | |
| start_time = time.time() | |
| result = subprocess.run(command, capture_output=True, text=True) | |
| end_time = time.time() | |
| elapsed = end_time - start_time | |
| length = math.ceil(elapsed / 60) | |
| if result.returncode == 0: | |
| logging.info(f"Completed {xml_file} successfully in {length:.2f} minutes; [{elapsed:.2f} seconds.]") | |
| logging.debug(f"Output:\n{result.stdout}") | |
| else: | |
| logging.error(f"ALPACA failed on {xml_file} with return code {result.returncode}") | |
| logging.error(f"stderr:\n{result.stderr}") | |
| def round_sig(x, sig=5): | |
| return float(f"{x:.{sig}g}") | |
| def create_alpaca_input( | |
| count: int, | |
| base_path: str , | |
| output_path: str | |
| ): | |
| """ | |
| Generates a set of ALPACA input files with varying parameters for high pressure, low pressure, laser width, and the two radii of the droplet. | |
| Args: | |
| count (int): Number of samples to generate. | |
| base_path (str): Path to the base .xml file that will be modified. | |
| output_path (str): Directory where the generated .xml files will be saved. Create the directory if it does not exist. | |
| """ | |
| warnings.warn(f"[WARNING] Make sure the default base_input file {base_path} exists and untouched !!!.") | |
| # Define the parameters | |
| param_bounds = np.array([ | |
| [1e10, 8e10], # high_pressure | |
| [1e5, 1e6], # low_pressure | |
| [2e-7, 15e-7], # laser_width | |
| [1e-5, 1.6e-5], #drop_radius_1 | |
| [1e-5, 1.6e-5] #drop_radius_2 | |
| ]) | |
| n_samples = count | |
| n_dims = param_bounds.shape[0] | |
| sampler = qmc.Sobol(d=n_dims, scramble=True, seed=10) | |
| samples_unit = sampler.random(n=n_samples) | |
| params = qmc.scale(samples_unit, param_bounds[:, 0], param_bounds[:, 1]) #[N, D] = [128, 5] | |
| params = np.vectorize(round_sig)(params, sig=5) | |
| width = params[:, 2] + 0.15e-6 | |
| # Modify default.xml file | |
| for i in range(n_samples): | |
| with open(base_path) as f: | |
| data = xmltodict.parse(f.read()) | |
| # Air | |
| air_0 = data["configuration"]["domain"]["initialConditions"]["material1"] | |
| air_1 = air_0.replace("0.35e-6", f"{width[i]}") | |
| air_2 = air_1.replace("1e-5", f"{params[i, 4]}") | |
| air_3 = air_2.replace("pressure := 10e9;", f"pressure := {params[i, 0]};") | |
| match = re.search(r'else\s*{(.*?)}', air_0, flags=re.DOTALL) | |
| else_block = match.group(1) | |
| modified_else = re.sub( | |
| r'pressure\s*:=\s*1e5;', | |
| f'pressure := {params[i, 1]};', | |
| match.group(1) | |
| ) | |
| air_4 = air_3.replace(else_block, modified_else) | |
| data["configuration"]["domain"]["initialConditions"]["material1"] = air_4 | |
| # Water | |
| water_0 = data["configuration"]["domain"]["initialConditions"]["material2"] | |
| water_1 = water_0.replace("pressure := 1e5;", f"pressure := {params[i, 1]};") | |
| data["configuration"]["domain"]["initialConditions"]["material2"] = water_1 | |
| # Interface | |
| geometry_list = data["configuration"]["domain"]["initialConditions"]["interface1"]["levelset"]["data"] | |
| # print(geometry_list) | |
| for geo in geometry_list: | |
| func = geo["function"].strip() | |
| if func == "Cylinder": | |
| geo["outerRadius"] = f"{params[i, 2]}" | |
| if func == "Ellipsoid": | |
| geo["semiAxis"] = f"{params[i, 3]}, {params[i, 4]}, 1e-5" | |
| formatted_params = ["{:.4e}".format(params[i, j]) for j in range(params.shape[1])] | |
| with open(output_path+ f"/hp{formatted_params[0]}_lp{formatted_params[1]}_laser{formatted_params[2]}_dropradx{formatted_params[3]}_droprady{formatted_params[4]}.xml", 'w') as f: | |
| f.write(xmltodict.unparse(data, pretty=True)) | |
| count = 2 # Number of samples to generate. keep it multiple of 2 for Sobol sequence | |
| inputs_output_path = "." | |
| data_output_path = "." | |
| create_alpaca_input(count=count, | |
| base_path="./default.xml", | |
| output_path=inputs_output_path) | |
| inputs = [] | |
| for file in os.listdir(inputs_output_path): | |
| if file.endswith(".xml"): | |
| inputs.append(os.path.join(".", file)) | |
| run_alpaca(xml_file=os.path.join(str(inputs_output_path), str(inputs[-1])), | |
| output_dir=str(data_output_path), | |
| mpiexec_path="mpiexec", | |
| exec_file_path="./build/ALPACA", | |
| num_workers=10) | |