Add files using upload-large-folder tool
Browse filesFiles changed (2)
- SIDA_generator_script/default.xmlAdded+154
- SIDA_generator_script/generater.pyAdded+195
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154<?xml version="1.0" encoding="utf-8"?><configuration> <domain> <nodeSize>0.375e-3</nodeSize> <nodeRatio>16 ,64 , 1</nodeRatio> <centeredAlignment>False, False, False</centeredAlignment> <boundaryConditions> <material> <west>Symmetry</west> <east>ZeroGradient</east> <south>FixedValue</south> <valuesSouth> <density> 1.61 </density> <velocityX> 0.0 </velocityX> <velocityY> 106.07 </velocityY> <velocityZ> 0.0 </velocityZ> <pressure> 153338.5 </pressure> <dominantPhase> 1 </dominantPhase> <!-- For DEM simulations, a dominant phase via the material index must be specified. 1 = MaterialOne, ... --> </valuesSouth> <north>ZeroGradient</north> <bottom>ZeroGradient</bottom> <top>ZeroGradient</top> </material> </boundaryConditions> <initialConditions> <treeInitializationType>LevelBased</treeInitializationType> <topologyInitializationType>BottomUp</topologyInitializationType> <material1>// air if (y < 8.25e-3) { density :=1.61; velocityX :=0.0; velocityY :=106.07; velocityZ :=0.0; pressure :=153338.5; } else { density :=1.20; velocityX :=0.0; velocityY :=0.0; velocityZ :=0.0; pressure :=101325.0; }</material1> <material2>// water density :=1000; velocityX :=0.0; velocityY :=0.0; velocityZ :=0.0; pressure :=101325.0;</material2> <interface1> <levelset> <type>precompiled</type> <operator>or</operator> <data> <function>Sphere</function> <center>0.0, 9e-3, 0.0</center> <centerSign>-1</centerSign> <innerRadius>0.0</innerRadius> <outerRadius>0.5e-3</outerRadius> </data> </levelset> </interface1> </initialConditions> </domain> <materials> <numberOfMaterials>2</numberOfMaterials> <numberOfPositiveMaterials>2</numberOfPositiveMaterials> <material1> <type>Fluid</type> <equationOfState> <type>StiffenedGas</type> <gamma>1.4</gamma> <backgroundPressure>0.0</backgroundPressure> </equationOfState> <properties> <specificHeatCapacity>0.0</specificHeatCapacity> <thermalConductivity>0.0</thermalConductivity> <shearViscosity>0.0</shearViscosity> <bulkViscosity>0.0</bulkViscosity> </properties> </material1> <material2> <type>Fluid</type> <equationOfState> <type>StiffenedGas</type> <gamma>6.12</gamma> <backgroundPressure>3.43e8</backgroundPressure> </equationOfState> <properties> <specificHeatCapacity>0.0</specificHeatCapacity> <thermalConductivity>0.0</thermalConductivity> <shearViscosity>0.0</shearViscosity> <bulkViscosity>0.0</bulkViscosity> </properties> </material2> </materials> <materialPairings> <material1_2> <surfaceTensionCoefficient>0.036</surfaceTensionCoefficient> </material1_2> </materialPairings> <sourceTerms> <gravity>0, 0, 0</gravity> </sourceTerms> <multiResolution> <maximumLevel>0</maximumLevel> <refinementCriterion> <epsilonReference>0.01</epsilonReference> <levelOfEpsilonReference>0</levelOfEpsilonReference> </refinementCriterion> </multiResolution> <timeControl> <startTime>0.0</startTime> <endTime>15e-6</endTime> <CFLNumber>0.5</CFLNumber> </timeControl> <dimensionalization> <lengthReference>1.0</lengthReference> <velocityReference>1.0</velocityReference> <densityReference>1.0</densityReference> <temperatureReference>1.0</temperatureReference> <amountOfSubstanceReference>1.0</amountOfSubstanceReference> </dimensionalization> <restart> <restore> <mode>Off</mode> <fileName>./Alpaca/ALPACA_WORKSHOP/build/droplet_RDEMIC/restart/restart_.h5</fileName> </restore> <snapshots> <mode>Macro</mode> <type>Interval</type> <interval>50e-9</interval> <intervalsToKeep>2</intervalsToKeep> <stamps></stamps> </snapshots> </restart> <output> <timeNamingFactor>1.0e3</timeNamingFactor> <!-- <standard> <type>Interval</type> <interval>1e-6</interval> <stamps></stamps> <minimalLevel>0</minimalLevel> </standard> --> <subDomain> <type> Interval </type> <interval> 0.25e-6 </interval> <!-- <stamps> 0.0004, 0.0006 </stamps> --> <minimalLevel> 0 </minimalLevel> <box> <!-- The box to be used for the subdomain. --> <min> 0.0, 8.35e-3, 2.0 </min> <max> 1.3e-3, 11.05e-3, 3.0 </max> </box> </subDomain> </output></configuration>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195"""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.
This problem setup is based on Weber number, We=(rho_g_2 * u_g_2^2 * D0 / sigma) and Shock Mach number, Ma_s = u_s / c1By having these two at hand 1. we use Ma_s to calculate all the conditions on post-shock region using normal shock relations; the results will be initial condition for air in post-shock part.2. we use We to calculate corresponding sigma, surface tension coefficient.
"""
import osimport subprocessimport loggingimport timeimport mathimport htmlimport refrom scipy.stats.qmc import Sobol, scalefrom scipy.stats import qmcimport xmltodictimport numpy as npimport 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=4): 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 !!!.")
### fixed IC ### D0 = 2*1e-3 #for now; may change to 10e-6 later rho_drop = 1000 # [kg/m^3] rho_gas_1 = 1.20 # [kg/m^3] gamma = 1.4 p_gas_1 = 101325 # [Pa] p_drop = p_gas_1 Temp_1 = 300 # [Kelvin] c_1 = np.sqrt(gamma * 287 * Temp_1) # Speed of sound at Tempearture in Region 1 [m/s]
### Main params range ### param_bounds = np.array([ [3.5, 5], # Ma_s [500, 4e4], # We ])
n_samples = count n_dims = param_bounds.shape[0] sampler = qmc.Sobol(d=n_dims, scramble=True, seed=50) samples_unit = sampler.random(n=n_samples) params = qmc.scale(samples_unit, param_bounds[:, 0], param_bounds[:, 1]) #[N, D] = [count, n_dims] params = np.vectorize(round_sig)(params, sig=4) # round them to have only 4 float digits
Ma_2 = [] # add post-shock flow Mach number
### calculations for IC and Write the default input.xml### for i in range(n_samples):
with open(base_path) as f: data = xmltodict.parse(f.read())
# parama[:, 0] = Ma_s # parama[:, 1] = We # Ref. normal shock relations
u_s = params[i, 0] * c_1 u_1_rel = - u_s u_gas_1 = u_1_rel + u_s Temp_2 = Temp_1 * ( 1 + (2*gamma*(params[i, 0]*params[i, 0]-1)) / (gamma+1) ) * ( (2+(gamma-1)*params[i, 0]*params[i, 0]) / ((gamma+1)*params[i, 0]*params[i, 0]) ) c_2 = np.sqrt(gamma * 287 * Temp_2) Ma_2_rel = np.sqrt( (1+((gamma-1)/2)*params[i, 0]*params[i, 0]) / (gamma*params[i, 0]*params[i, 0]-((gamma-1)/2)) ) u_2_rel = Ma_2_rel * c_2 u_gas_2 = u_s - u_2_rel # >>> needed rho_gas_2 = rho_gas_1 * ((gamma+1)*params[i, 0]*params[i, 0]) / (2+(gamma-1)*params[i, 0]*params[i, 0]) # >>> needed p_gas_2 = p_gas_1 * (1 + (2*gamma*(params[i, 0]*params[i, 0]-1))/(gamma+1)) # >>> needed Ma_2.append(u_gas_2 / c_2) sigma = rho_gas_2 * u_gas_2*u_gas_2 * D0 / params[i, 1] # >>> needed
# BC data["configuration"]["domain"]["boundaryConditions"]["material"]["valuesSouth"]["density"] = rho_gas_2 data["configuration"]["domain"]["boundaryConditions"]["material"]["valuesSouth"]["pressure"] = p_gas_2 data["configuration"]["domain"]["boundaryConditions"]["material"]["valuesSouth"]["velocityY"] = u_gas_2
# IC - Air air_0 = data["configuration"]["domain"]["initialConditions"]["material1"] air_1 = air_0.replace("density :=1.61;", f"density := {rho_gas_2};") air_2 = air_1.replace("pressure :=153338.5;", f"pressure := {p_gas_2};") air_3 = air_2.replace("velocityY :=106.07;", f"velocityY := {u_gas_2};") data["configuration"]["domain"]["initialConditions"]["material1"] = air_3
# IC - Water drop is fixed
# Surface Tension data["configuration"]["materialPairings"]["material1_2"]["surfaceTensionCoefficient"] = sigma
with open(output_path+ f"/Mas{"{:.4f}".format(params[i, 0])}_We{"{:.4f}".format(params[i, 1])}_Maf{"{:.4f}".format(Ma_2[i])}.xml", 'w') as f: f.write(xmltodict.unparse(data, pretty=True))
Ma_2 = np.array(Ma_2).reshape(-1, 1) params = np.hstack((params, Ma_2)) #turns into [N, D] = [count, 3]
count = 2 # Number of samples to generate. keep it multiple of 2 for Sobol sequenceinputs_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)
SIDA_generator_script/default.xmlAdded+154
SIDA_generator_script/generater.pyAdded+195