diff --git a/examples/EvrardCollapse_3D/evrard.yml b/examples/EvrardCollapse_3D/evrard.yml new file mode 100644 index 0000000000000000000000000000000000000000..006a22e65d3f674f124ce6c4994e752ba39cd1e1 --- /dev/null +++ b/examples/EvrardCollapse_3D/evrard.yml @@ -0,0 +1,44 @@ +# Define the system of units to use internally. +InternalUnitSystem: + UnitMass_in_cgs: 1 # Grams + UnitLength_in_cgs: 1 # Centimeters + UnitVelocity_in_cgs: 1 # Centimeters per second + UnitCurrent_in_cgs: 1 # Amperes + UnitTemp_in_cgs: 1 # Kelvin + +# Parameters governing the time integration +TimeIntegration: + time_begin: 0. # The starting time of the simulation (in internal units). + time_end: 0.8 # The end time of the simulation (in internal units). + dt_min: 1e-7 # The minimal time-step size of the simulation (in internal units). + dt_max: 1e-3 # The maximal time-step size of the simulation (in internal units). + +# Parameters governing the snapshots +Snapshots: + basename: evrard # Common part of the name of output files + time_first: 0. # Time of the first output (in internal units) + delta_time: 0.1 # Time difference between consecutive outputs (in internal units) + +# Parameters governing the conserved quantities statistics +Statistics: + delta_time: 1e-2 # Time between statistics output + +# Parameters for the hydrodynamics scheme +SPH: + resolution_eta: 1.2348 # Target smoothing length in units of the mean inter-particle separation (1.2348 == 48Ngbs with the cubic spline kernel). + CFL_condition: 0.1 # Courant-Friedrich-Levy condition for time integration. + +# Parameters for the self-gravity scheme +Gravity: + eta: 0.025 # Constant dimensionless multiplier for time integration. + epsilon: 0.001 # Softening length (in internal units). + theta: 0.9 + a_smooth: 1.25 # (Optional) Smoothing scale in top-level cell sizes to smooth the long-range forces over (this is the default value). + r_cut: 4.5 # (Optional) Cut-off in number of top-level cells beyond which no FMM forces are computed (this is the default value). + +# Parameters related to the initial conditions +InitialConditions: + file_name: ./evrard.hdf5 # The file to read + +PhysicalConstants: + G: 1. diff --git a/examples/EvrardCollapse_3D/getReference.sh b/examples/EvrardCollapse_3D/getReference.sh new file mode 100755 index 0000000000000000000000000000000000000000..f8de6015c89ea78169c078217f04cc539f28efa8 --- /dev/null +++ b/examples/EvrardCollapse_3D/getReference.sh @@ -0,0 +1,2 @@ +#! /bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ReferenceSolutions/evrardCollapse3D_exact.txt diff --git a/examples/EvrardCollapse_3D/makeIC.py b/examples/EvrardCollapse_3D/makeIC.py new file mode 100644 index 0000000000000000000000000000000000000000..b68f0da0e1869ce54ae7ab2ad3b33b8c3deb8b51 --- /dev/null +++ b/examples/EvrardCollapse_3D/makeIC.py @@ -0,0 +1,95 @@ +################################################################################ +# This file is part of SWIFT. +# Copyright (c) 2017 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +################################################################################ + +import h5py +from numpy import * + +# Generates a swift IC file for the Evrard collapse + +# Parameters +gamma = 5. / 3. # Gas adiabatic index +M = 1. # total mass of the sphere +R = 1. # radius of the sphere +u0 = 0.05 / M # initial thermal energy +fileName = "evrard.hdf5" +numPart = 100000 + +r = R * sqrt(random.random(numPart)) +phi = 2. * pi * random.random(numPart) +cos_theta = 2. * random.random(numPart) - 1. + +sin_theta = sqrt(1. - cos_theta**2) +cos_phi = cos(phi) +sin_phi = sin(phi) + +pos = zeros((numPart, 3)) +pos[:,0] = r * sin_theta * cos_phi +pos[:,1] = r * sin_theta * sin_phi +pos[:,2] = r * cos_theta + +# shift particles to put the sphere in the centre of the box +pos += array([50. * R, 50. * R, 50. * R]) + +h = ones(numPart) * 2. * R / numPart**(1. / 3.) + +# Generate extra arrays +v = zeros((numPart, 3)) +ids = linspace(1, numPart, numPart) +m = ones(numPart) * M / numPart +u = ones(numPart) * u0 + +#-------------------------------------------------- + +#File +file = h5py.File(fileName, 'w') + +# Header +grp = file.create_group("/Header") +grp.attrs["BoxSize"] = [100. * R, 100. * R, 100. * R] +grp.attrs["NumPart_Total"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFilesPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = 0 +grp.attrs["Dimension"] = 3 + +#Runtime parameters +grp = file.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 0 + +#Units +grp = file.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = file.create_group("/PartType0") +grp.create_dataset('Coordinates', data=pos, dtype='d') +grp.create_dataset('Velocities', data=v, dtype='f') +grp.create_dataset('Masses', data=m, dtype='f') +grp.create_dataset('SmoothingLength', data=h, dtype='f') +grp.create_dataset('InternalEnergy', data=u, dtype='f') +grp.create_dataset('ParticleIDs', data=ids, dtype='L') + +file.close() diff --git a/examples/EvrardCollapse_3D/plotSolution.py b/examples/EvrardCollapse_3D/plotSolution.py new file mode 100644 index 0000000000000000000000000000000000000000..8422b9c45fd573f3d0ae36324d6e39ab23cceb25 --- /dev/null +++ b/examples/EvrardCollapse_3D/plotSolution.py @@ -0,0 +1,172 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2016 Matthieu Schaller (matthieu.schaller@durham.ac.uk) +# 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +################################################################################ + +# Compares the swift result for the 2D spherical Sod shock with a high +# resolution 2D reference result + +import matplotlib +matplotlib.use("Agg") +from pylab import * +from scipy import stats +import h5py + +# Parameters +gas_gamma = 5./3. # Polytropic index +rho_L = 1. # Density left state +rho_R = 0.125 # Density right state +v_L = 0. # Velocity left state +v_R = 0. # Velocity right state +P_L = 1. # Pressure left state +P_R = 0.1 # Pressure right state + +# Plot parameters +params = {'axes.labelsize': 10, +'axes.titlesize': 10, +'font.size': 12, +'legend.fontsize': 12, +'xtick.labelsize': 10, +'ytick.labelsize': 10, +'text.usetex': True, + 'figure.figsize' : (9.90,6.45), +'figure.subplot.left' : 0.045, +'figure.subplot.right' : 0.99, +'figure.subplot.bottom' : 0.05, +'figure.subplot.top' : 0.99, +'figure.subplot.wspace' : 0.15, +'figure.subplot.hspace' : 0.12, +'lines.markersize' : 6, +'lines.linewidth' : 3., +'text.latex.unicode': True +} +rcParams.update(params) +rc('font',**{'family':'sans-serif','sans-serif':['Times']}) + +snap = int(sys.argv[1]) + +# Read the simulation data +sim = h5py.File("evrard_%04d.hdf5"%snap, "r") +boxSize = sim["/Header"].attrs["BoxSize"][0] +time = sim["/Header"].attrs["Time"][0] +scheme = sim["/HydroScheme"].attrs["Scheme"] +kernel = sim["/HydroScheme"].attrs["Kernel function"] +neighbours = sim["/HydroScheme"].attrs["Kernel target N_ngb"] +eta = sim["/HydroScheme"].attrs["Kernel eta"] +git = sim["Code"].attrs["Git Revision"] + +coords = sim["/PartType0/Coordinates"] +x = sqrt((coords[:,0] - 0.5 * boxSize)**2 + (coords[:,1] - 0.5 * boxSize)**2 + \ + (coords[:,2] - 0.5 * boxSize)**2) +vels = sim["/PartType0/Velocities"] +v = sqrt(vels[:,0]**2 + vels[:,1]**2 + vels[:,2]**2) +u = sim["/PartType0/InternalEnergy"][:] +S = sim["/PartType0/Entropy"][:] +P = sim["/PartType0/Pressure"][:] +rho = sim["/PartType0/Density"][:] + +# Bin the data +x_bin_edge = logspace(-3., log10(2.), 100) +x_bin = 0.5*(x_bin_edge[1:] + x_bin_edge[:-1]) +rho_bin,_,_ = stats.binned_statistic(x, rho, statistic='mean', bins=x_bin_edge) +v_bin,_,_ = stats.binned_statistic(x, v, statistic='mean', bins=x_bin_edge) +P_bin,_,_ = stats.binned_statistic(x, P, statistic='mean', bins=x_bin_edge) +S_bin,_,_ = stats.binned_statistic(x, S, statistic='mean', bins=x_bin_edge) +u_bin,_,_ = stats.binned_statistic(x, u, statistic='mean', bins=x_bin_edge) +rho2_bin,_,_ = stats.binned_statistic(x, rho**2, statistic='mean', bins=x_bin_edge) +v2_bin,_,_ = stats.binned_statistic(x, v**2, statistic='mean', bins=x_bin_edge) +P2_bin,_,_ = stats.binned_statistic(x, P**2, statistic='mean', bins=x_bin_edge) +S2_bin,_,_ = stats.binned_statistic(x, S**2, statistic='mean', bins=x_bin_edge) +u2_bin,_,_ = stats.binned_statistic(x, u**2, statistic='mean', bins=x_bin_edge) +rho_sigma_bin = np.sqrt(rho2_bin - rho_bin**2) +v_sigma_bin = np.sqrt(v2_bin - v_bin**2) +P_sigma_bin = np.sqrt(P2_bin - P_bin**2) +S_sigma_bin = np.sqrt(S2_bin - S_bin**2) +u_sigma_bin = np.sqrt(u2_bin - u_bin**2) + +ref = loadtxt("evrardCollapse3D_exact.txt") + +# Plot the interesting quantities +figure() + +# Velocity profile -------------------------------- +subplot(231) +semilogx(x, -v, '.', color='r', ms=0.2) +semilogx(ref[:,0], ref[:,2], "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, -v_bin, yerr=v_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Velocity}}~v_r$", labelpad=0) +xlim(1.e-3, 2.) +ylim(-1.7, 0.1) + +# Density profile -------------------------------- +subplot(232) +loglog(x, rho, '.', color='r', ms=0.2) +loglog(ref[:,0], ref[:,1], "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, rho_bin, yerr=rho_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Density}}~\\rho$", labelpad=0) +xlim(1.e-3, 2.) +ylim(1.e-2, 1.e4) + +# Pressure profile -------------------------------- +subplot(233) +loglog(x, P, '.', color='r', ms=0.2) +loglog(ref[:,0], ref[:,3], "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, P_bin, yerr=P_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Pressure}}~P$", labelpad=0) +xlim(1.e-3, 2.) +ylim(1.e-4, 1.e3) + +# Internal energy profile ------------------------- +subplot(234) +loglog(x, u, '.', color='r', ms=0.2) +loglog(ref[:,0], ref[:,3] / ref[:,1] / (gas_gamma - 1.), "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, u_bin, yerr=u_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Internal~Energy}}~u$", labelpad=0) +xlim(1.e-3, 2.) +ylim(1.e-2, 2.) + +# Entropy profile --------------------------------- +subplot(235) +semilogx(x, S, '.', color='r', ms=0.2) +semilogx(ref[:,0], ref[:,3] / ref[:,1]**gas_gamma, "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, S_bin, yerr=S_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Entropy}}~S$", labelpad=0) +xlim(1.e-3, 2.) +ylim(0., 0.25) + +# Information ------------------------------------- +subplot(236, frameon=False) + +text(-0.49, 0.9, "Evrard collapse with $\\gamma=%.3f$ in 3D\nat $t=%.2f$"%(gas_gamma,time), fontsize=10) +plot([-0.49, 0.1], [0.62, 0.62], 'k-', lw=1) +text(-0.49, 0.5, "$\\textsc{Swift}$ %s"%git, fontsize=10) +text(-0.49, 0.4, scheme, fontsize=10) +text(-0.49, 0.3, kernel, fontsize=10) +text(-0.49, 0.2, "$%.2f$ neighbours ($\\eta=%.3f$)"%(neighbours, eta), fontsize=10) +xlim(-0.5, 0.5) +ylim(0, 1) +xticks([]) +yticks([]) + +tight_layout() +savefig("EvrardCollapse.png", dpi=200) diff --git a/examples/EvrardCollapse_3D/run.sh b/examples/EvrardCollapse_3D/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..abb7614f66fc877aa670db9b0e1335fbfe2e85d2 --- /dev/null +++ b/examples/EvrardCollapse_3D/run.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +# Generate the initial conditions if they are not present. +if [ ! -e evrard.hdf5 ] +then + echo "Generating initial conditions for the Evrard collapse example..." + python makeIC.py +fi + +# Run SWIFT +../swift -s -G -t 4 evrard.yml 2>&1 | tee output.log + +# Get the high resolution 1D reference result if not present. +if [ ! -e evrardCollapse3D_exact.txt ] +then + echo "Fetching the reference result for the Evrard collapse example..." + ./getReference.sh +fi + +# Plot the solution +python plotSolution.py 8 diff --git a/examples/GreshoVortex_3D/getGlass.sh b/examples/GreshoVortex_3D/getGlass.sh new file mode 100755 index 0000000000000000000000000000000000000000..d5c5f590ac37c9c9431d626a2ea61b0c12c1513c --- /dev/null +++ b/examples/GreshoVortex_3D/getGlass.sh @@ -0,0 +1,2 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ICs/glassCube_64.hdf5 diff --git a/examples/GreshoVortex_3D/gresho.yml b/examples/GreshoVortex_3D/gresho.yml new file mode 100644 index 0000000000000000000000000000000000000000..df941450196a7de6cd1471e1d258756ca8c36fb1 --- /dev/null +++ b/examples/GreshoVortex_3D/gresho.yml @@ -0,0 +1,36 @@ +# Define the system of units to use internally. +InternalUnitSystem: + UnitMass_in_cgs: 1 # Grams + UnitLength_in_cgs: 1 # Centimeters + UnitVelocity_in_cgs: 1 # Centimeters per second + UnitCurrent_in_cgs: 1 # Amperes + UnitTemp_in_cgs: 1 # Kelvin + +Scheduler: + max_top_level_cells: 15 + +# Parameters governing the time integration +TimeIntegration: + time_begin: 0. # The starting time of the simulation (in internal units). + time_end: 1. # The end time of the simulation (in internal units). + dt_min: 1e-6 # The minimal time-step size of the simulation (in internal units). + dt_max: 1e-2 # The maximal time-step size of the simulation (in internal units). + +# Parameters governing the snapshots +Snapshots: + basename: gresho # Common part of the name of output files + time_first: 0. # Time of the first output (in internal units) + delta_time: 1e-1 # Time difference between consecutive outputs (in internal units) + +# Parameters governing the conserved quantities statistics +Statistics: + delta_time: 1e-2 # Time between statistics output + +# Parameters for the hydrodynamics scheme +SPH: + resolution_eta: 1.2348 # Target smoothing length in units of the mean inter-particle separation (1.2348 == 48Ngbs with the cubic spline kernel). + CFL_condition: 0.1 # Courant-Friedrich-Levy condition for time integration. + +# Parameters related to the initial conditions +InitialConditions: + file_name: ./greshoVortex.hdf5 # The file to read diff --git a/examples/GreshoVortex_3D/makeIC.py b/examples/GreshoVortex_3D/makeIC.py new file mode 100644 index 0000000000000000000000000000000000000000..cba2158016bc86f58b6e89f83cbfb473798e1cf7 --- /dev/null +++ b/examples/GreshoVortex_3D/makeIC.py @@ -0,0 +1,120 @@ +################################################################################ +# This file is part of SWIFT. +# Copyright (c) 2016 Matthieu Schaller (matthieu.schaller@durham.ac.uk) +# 2017 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +################################################################################ + +import h5py +from numpy import * + +# Generates a swift IC file for the Gresho-Chan vortex in a periodic box + +# Parameters +gamma = 5./3. # Gas adiabatic index +rho0 = 1 # Gas density +P0 = 0. # Constant additional pressure (should have no impact on the dynamics) +fileOutputName = "greshoVortex.hdf5" +fileGlass = "glassCube_64.hdf5" +#--------------------------------------------------- + +# Get position and smoothing lengths from the glass +fileInput = h5py.File(fileGlass, 'r') +coords = fileInput["/PartType0/Coordinates"][:,:] +h = fileInput["/PartType0/SmoothingLength"][:] +ids = fileInput["/PartType0/ParticleIDs"][:] +boxSize = fileInput["/Header"].attrs["BoxSize"][0] +numPart = size(h) +fileInput.close() + +# Now generate the rest +m = ones(numPart) * rho0 * boxSize**3 / numPart +u = zeros(numPart) +v = zeros((numPart, 3)) + +for i in range(numPart): + + x = coords[i,0] + y = coords[i,1] + + r2 = (x - boxSize / 2)**2 + (y - boxSize / 2)**2 + r = sqrt(r2) + + v_phi = 0. + if r < 0.2: + v_phi = 5.*r + elif r < 0.4: + v_phi = 2. - 5.*r + else: + v_phi = 0. + v[i,0] = -v_phi * (y - boxSize / 2) / r + v[i,1] = v_phi * (x - boxSize / 2) / r + v[i,2] = 0. + + P = P0 + if r < 0.2: + P = P + 5. + 12.5*r2 + elif r < 0.4: + P = P + 9. + 12.5*r2 - 20.*r + 4.*log(r/0.2) + else: + P = P + 3. + 4.*log(2.) + u[i] = P / ((gamma - 1.)*rho0) + + + +#File +fileOutput = h5py.File(fileOutputName, 'w') + +# Header +grp = fileOutput.create_group("/Header") +grp.attrs["BoxSize"] = [boxSize, boxSize, boxSize] +grp.attrs["NumPart_Total"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFileOutputsPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = [0, 0, 0, 0, 0, 0] +grp.attrs["Dimension"] = 3 + +#Runtime parameters +grp = fileOutput.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 1 + +#Units +grp = fileOutput.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = fileOutput.create_group("/PartType0") +ds = grp.create_dataset('Coordinates', (numPart, 3), 'd') +ds[()] = coords +ds = grp.create_dataset('Velocities', (numPart, 3), 'f') +ds[()] = v +ds = grp.create_dataset('Masses', (numPart, 1), 'f') +ds[()] = m.reshape((numPart,1)) +ds = grp.create_dataset('SmoothingLength', (numPart,1), 'f') +ds[()] = h.reshape((numPart,1)) +ds = grp.create_dataset('InternalEnergy', (numPart,1), 'f') +ds[()] = u.reshape((numPart,1)) +ds = grp.create_dataset('ParticleIDs', (numPart,1), 'L') +ds[()] = ids.reshape((numPart,1)) + +fileOutput.close() diff --git a/examples/GreshoVortex_3D/plotSolution.py b/examples/GreshoVortex_3D/plotSolution.py new file mode 100644 index 0000000000000000000000000000000000000000..8fddf148bd169310d5e69ffbfa4a6de099068c69 --- /dev/null +++ b/examples/GreshoVortex_3D/plotSolution.py @@ -0,0 +1,227 @@ +################################################################################ +# This file is part of SWIFT. +# Copyright (c) 2016 Matthieu Schaller (matthieu.schaller@durham.ac.uk) +# 2017 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +################################################################################ + +# Computes the analytical solution of the Gresho-Chan vortex and plots the SPH +# answer + +# Parameters +gas_gamma = 5./3. # Gas adiabatic index +rho0 = 1 # Gas density +P0 = 0. # Constant additional pressure (should have no impact on the + # dynamics) + +# --------------------------------------------------------------- +# Don't touch anything after this. +# --------------------------------------------------------------- + +import matplotlib +matplotlib.use("Agg") +from pylab import * +from scipy import stats +import h5py + +# Plot parameters +params = {'axes.labelsize': 10, +'axes.titlesize': 10, +'font.size': 12, +'legend.fontsize': 12, +'xtick.labelsize': 10, +'ytick.labelsize': 10, +'text.usetex': True, + 'figure.figsize' : (9.90,6.45), +'figure.subplot.left' : 0.045, +'figure.subplot.right' : 0.99, +'figure.subplot.bottom' : 0.05, +'figure.subplot.top' : 0.99, +'figure.subplot.wspace' : 0.15, +'figure.subplot.hspace' : 0.12, +'lines.markersize' : 6, +'lines.linewidth' : 3., +'text.latex.unicode': True +} +rcParams.update(params) +rc('font',**{'family':'sans-serif','sans-serif':['Times']}) + + +snap = int(sys.argv[1]) + +# Generate the analytic solution at this time +N = 200 +R_max = 0.8 +solution_r = arange(0, R_max, R_max / N) +solution_P = zeros(N) +solution_v_phi = zeros(N) +solution_v_r = zeros(N) + +for i in range(N): + if solution_r[i] < 0.2: + solution_P[i] = P0 + 5. + 12.5*solution_r[i]**2 + solution_v_phi[i] = 5.*solution_r[i] + elif solution_r[i] < 0.4: + solution_P[i] = P0 + 9. + 12.5*solution_r[i]**2 - 20.*solution_r[i] + 4.*log(solution_r[i]/0.2) + solution_v_phi[i] = 2. -5.*solution_r[i] + else: + solution_P[i] = P0 + 3. + 4.*log(2.) + solution_v_phi[i] = 0. + +solution_rho = ones(N) * rho0 +solution_s = solution_P / solution_rho**gas_gamma +solution_u = solution_P /((gas_gamma - 1.)*solution_rho) + +# Read the simulation data +sim = h5py.File("gresho_%04d.hdf5"%snap, "r") +boxSize = sim["/Header"].attrs["BoxSize"][0] +time = sim["/Header"].attrs["Time"][0] +scheme = sim["/HydroScheme"].attrs["Scheme"] +kernel = sim["/HydroScheme"].attrs["Kernel function"] +neighbours = sim["/HydroScheme"].attrs["Kernel target N_ngb"] +eta = sim["/HydroScheme"].attrs["Kernel eta"] +git = sim["Code"].attrs["Git Revision"] + +pos = sim["/PartType0/Coordinates"][:,:] +x = pos[:,0] - boxSize / 2 +y = pos[:,1] - boxSize / 2 +vel = sim["/PartType0/Velocities"][:,:] +r = sqrt(x**2 + y**2) +v_r = (x * vel[:,0] + y * vel[:,1]) / r +v_phi = (-y * vel[:,0] + x * vel[:,1]) / r +v_norm = sqrt(vel[:,0]**2 + vel[:,1]**2) +rho = sim["/PartType0/Density"][:] +u = sim["/PartType0/InternalEnergy"][:] +S = sim["/PartType0/Entropy"][:] +P = sim["/PartType0/Pressure"][:] + +# Bin te data +r_bin_edge = np.arange(0., 1., 0.02) +r_bin = 0.5*(r_bin_edge[1:] + r_bin_edge[:-1]) +rho_bin,_,_ = stats.binned_statistic(r, rho, statistic='mean', bins=r_bin_edge) +v_bin,_,_ = stats.binned_statistic(r, v_phi, statistic='mean', bins=r_bin_edge) +P_bin,_,_ = stats.binned_statistic(r, P, statistic='mean', bins=r_bin_edge) +S_bin,_,_ = stats.binned_statistic(r, S, statistic='mean', bins=r_bin_edge) +u_bin,_,_ = stats.binned_statistic(r, u, statistic='mean', bins=r_bin_edge) +rho2_bin,_,_ = stats.binned_statistic(r, rho**2, statistic='mean', bins=r_bin_edge) +v2_bin,_,_ = stats.binned_statistic(r, v_phi**2, statistic='mean', bins=r_bin_edge) +P2_bin,_,_ = stats.binned_statistic(r, P**2, statistic='mean', bins=r_bin_edge) +S2_bin,_,_ = stats.binned_statistic(r, S**2, statistic='mean', bins=r_bin_edge) +u2_bin,_,_ = stats.binned_statistic(r, u**2, statistic='mean', bins=r_bin_edge) +rho_sigma_bin = np.sqrt(rho2_bin - rho_bin**2) +v_sigma_bin = np.sqrt(v2_bin - v_bin**2) +P_sigma_bin = np.sqrt(P2_bin - P_bin**2) +S_sigma_bin = np.sqrt(S2_bin - S_bin**2) +u_sigma_bin = np.sqrt(u2_bin - u_bin**2) + + +# Plot the interesting quantities +figure() + + +# Azimuthal velocity profile ----------------------------- +subplot(231) + +plot(r, v_phi, '.', color='r', ms=0.5) +plot(solution_r, solution_v_phi, '--', color='k', alpha=0.8, lw=1.2) +errorbar(r_bin, v_bin, yerr=v_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +plot([0.2, 0.2], [-100, 100], ':', color='k', alpha=0.4, lw=1.2) +plot([0.4, 0.4], [-100, 100], ':', color='k', alpha=0.4, lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Azimuthal~velocity}}~v_\\phi$", labelpad=0) +xlim(0,R_max) +ylim(-0.1, 1.2) + +# Radial density profile -------------------------------- +subplot(232) + +plot(r, rho, '.', color='r', ms=0.5) +plot(solution_r, solution_rho, '--', color='k', alpha=0.8, lw=1.2) +errorbar(r_bin, rho_bin, yerr=rho_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +plot([0.2, 0.2], [-100, 100], ':', color='k', alpha=0.4, lw=1.2) +plot([0.4, 0.4], [-100, 100], ':', color='k', alpha=0.4, lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Density}}~\\rho$", labelpad=0) +xlim(0,R_max) +ylim(rho0-0.3, rho0 + 0.3) +#yticks([-0.2, -0.1, 0., 0.1, 0.2]) + +# Radial pressure profile -------------------------------- +subplot(233) + +plot(r, P, '.', color='r', ms=0.5) +plot(solution_r, solution_P, '--', color='k', alpha=0.8, lw=1.2) +errorbar(r_bin, P_bin, yerr=P_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +plot([0.2, 0.2], [-100, 100], ':', color='k', alpha=0.4, lw=1.2) +plot([0.4, 0.4], [-100, 100], ':', color='k', alpha=0.4, lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Pressure}}~P$", labelpad=0) +xlim(0, R_max) +ylim(4.9 + P0, P0 + 6.1) + +# Internal energy profile -------------------------------- +subplot(234) + +plot(r, u, '.', color='r', ms=0.5) +plot(solution_r, solution_u, '--', color='k', alpha=0.8, lw=1.2) +errorbar(r_bin, u_bin, yerr=u_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +plot([0.2, 0.2], [-100, 100], ':', color='k', alpha=0.4, lw=1.2) +plot([0.4, 0.4], [-100, 100], ':', color='k', alpha=0.4, lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Internal~Energy}}~u$", labelpad=0) +xlim(0,R_max) +ylim(7.3, 9.1) + + +# Radial entropy profile -------------------------------- +subplot(235) + +plot(r, S, '.', color='r', ms=0.5) +plot(solution_r, solution_s, '--', color='k', alpha=0.8, lw=1.2) +errorbar(r_bin, S_bin, yerr=S_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +plot([0.2, 0.2], [-100, 100], ':', color='k', alpha=0.4, lw=1.2) +plot([0.4, 0.4], [-100, 100], ':', color='k', alpha=0.4, lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Entropy}}~S$", labelpad=0) +xlim(0, R_max) +ylim(4.9 + P0, P0 + 6.1) + +# Image -------------------------------------------------- +#subplot(234) +#scatter(pos[:,0], pos[:,1], c=v_norm, cmap="PuBu", edgecolors='face', s=4, vmin=0, vmax=1) +#text(0.95, 0.95, "$|v|$", ha="right", va="top") +#xlim(0,1) +#ylim(0,1) +#xlabel("$x$", labelpad=0) +#ylabel("$y$", labelpad=0) + +# Information ------------------------------------- +subplot(236, frameon=False) + +text(-0.49, 0.9, "Gresho-Chan vortex with $\\gamma=%.3f$ at $t=%.2f$"%(gas_gamma,time), fontsize=10) +text(-0.49, 0.8, "Background $\\rho_0=%.3f$"%rho0, fontsize=10) +text(-0.49, 0.7, "Background $P_0=%.3f$"%P0, fontsize=10) +plot([-0.49, 0.1], [0.62, 0.62], 'k-', lw=1) +text(-0.49, 0.5, "$\\textsc{Swift}$ %s"%git, fontsize=10) +text(-0.49, 0.4, scheme, fontsize=10) +text(-0.49, 0.3, kernel, fontsize=10) +text(-0.49, 0.2, "$%.2f$ neighbours ($\\eta=%.3f$)"%(neighbours, eta), fontsize=10) +xlim(-0.5, 0.5) +ylim(0, 1) +xticks([]) +yticks([]) + +savefig("GreshoVortex.png", dpi=200) diff --git a/examples/GreshoVortex_3D/run.sh b/examples/GreshoVortex_3D/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..da7d6cee111aebcfd2fcb0f3508af80ef73cbeb0 --- /dev/null +++ b/examples/GreshoVortex_3D/run.sh @@ -0,0 +1,19 @@ +#!/bin/bash + + # Generate the initial conditions if they are not present. +if [ ! -e glassCube_64.hdf5 ] +then + echo "Fetching initial glass file for the Gresho-Chan vortex example..." + ./getGlass.sh +fi +if [ ! -e greshoVortex.hdf5 ] +then + echo "Generating initial conditions for the Gresho-Chan vortex example..." + python makeIC.py +fi + +# Run SWIFT +../swift -s -t 4 gresho.yml 2>&1 | tee output.log + +# Plot the solution +python plotSolution.py 11 diff --git a/examples/InteractingBlastWaves_1D/getReference.sh b/examples/InteractingBlastWaves_1D/getReference.sh new file mode 100755 index 0000000000000000000000000000000000000000..9b6e884850571f7dfbc3f2018235118447bc00be --- /dev/null +++ b/examples/InteractingBlastWaves_1D/getReference.sh @@ -0,0 +1,2 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ReferenceSolutions/interactingBlastWaves1D_exact.txt diff --git a/examples/InteractingBlastWaves_1D/plotSolution.py b/examples/InteractingBlastWaves_1D/plotSolution.py index 342b67eae1061a9a94675a59f53ebf9e4ba7717f..1719162dec34626d6f4ecb8267c4d06f85b3db26 100644 --- a/examples/InteractingBlastWaves_1D/plotSolution.py +++ b/examples/InteractingBlastWaves_1D/plotSolution.py @@ -17,21 +17,116 @@ # ############################################################################## -import h5py +import numpy as np import matplotlib matplotlib.use("Agg") import pylab as pl +import h5py import sys +# Parameters +gamma = 1.4 # Polytropic index + +# Plot parameters +params = {'axes.labelsize': 10, +'axes.titlesize': 10, +'font.size': 12, +'legend.fontsize': 12, +'xtick.labelsize': 10, +'ytick.labelsize': 10, +'text.usetex': True, + 'figure.figsize' : (9.90,6.45), +'figure.subplot.left' : 0.045, +'figure.subplot.right' : 0.99, +'figure.subplot.bottom' : 0.05, +'figure.subplot.top' : 0.99, +'figure.subplot.wspace' : 0.15, +'figure.subplot.hspace' : 0.12, +'lines.markersize' : 6, +'lines.linewidth' : 3., +'text.latex.unicode': True +} +pl.rcParams.update(params) +pl.rc('font',**{'family':'sans-serif','sans-serif':['Times']}) + +# Read the snapshot index from the command line argument snap = int(sys.argv[1]) -sim = h5py.File("interactingBlastWaves_%04d.hdf5" % snap, "r") -coords = sim["/PartType0/Coordinates"] -rho = sim["/PartType0/Density"] +# Open the file and read the relevant data +file = h5py.File("interactingBlastWaves_{0:04d}.hdf5".format(snap), "r") +x = file["/PartType0/Coordinates"][:,0] +rho = file["/PartType0/Density"] +v = file["/PartType0/Velocities"][:,0] +u = file["/PartType0/InternalEnergy"] +S = file["/PartType0/Entropy"] +P = file["/PartType0/Pressure"] +time = file["/Header"].attrs["Time"][0] + +scheme = file["/HydroScheme"].attrs["Scheme"] +kernel = file["/HydroScheme"].attrs["Kernel function"] +neighbours = file["/HydroScheme"].attrs["Kernel target N_ngb"][0] +eta = file["/HydroScheme"].attrs["Kernel eta"][0] +git = file["Code"].attrs["Git Revision"] + +ref = np.loadtxt("interactingBlastWaves1D_exact.txt") + +# Plot the interesting quantities +fig, ax = pl.subplots(2, 3) + +# Velocity profile +ax[0][0].plot(x, v, "r.", markersize = 4.) +ax[0][0].plot(ref[:,0], ref[:,2], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][0].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[0][0].set_ylabel("${\\rm{Velocity}}~v_x$", labelpad = 0) +ax[0][0].set_xlim(0., 1.) +ax[0][0].set_ylim(-1., 15.) + +# Density profile +ax[0][1].plot(x, rho, "r.", markersize = 4.) +ax[0][1].plot(ref[:,0], ref[:,1], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][1].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[0][1].set_ylabel("${\\rm{Density}}~\\rho$", labelpad = 0) +ax[0][1].set_xlim(0., 1.) + +# Pressure profile +ax[0][2].plot(x, P, "r.", markersize = 4.) +ax[0][2].plot(ref[:,0], ref[:,3], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][2].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[0][2].set_ylabel("${\\rm{Pressure}}~P$", labelpad = 0) +ax[0][2].set_xlim(0., 1.) + +# Internal energy profile +ax[1][0].plot(x, u, "r.", markersize = 4.) +ax[1][0].plot(ref[:,0], ref[:,3] / ref[:,1] / (gamma - 1.), "k--", alpha = 0.8, + linewidth = 1.2) +ax[1][0].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[1][0].set_ylabel("${\\rm{Internal~Energy}}~u$", labelpad = 0) +ax[1][0].set_xlim(0., 1.) + +# Entropy profile +ax[1][1].plot(x, S, "r.", markersize = 4.) +ax[1][1].plot(ref[:,0], ref[:,3] / ref[:,1]**gamma, "k--", alpha = 0.8, + linewidth = 1.2) +ax[1][1].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[1][1].set_ylabel("${\\rm{Entropy}}~S$", labelpad = 0) +ax[1][1].set_xlim(0., 1.) + +# Run information +ax[1][2].set_frame_on(False) +ax[1][2].text(-0.49, 0.9, + "Interacting blast waves test\nwith $\\gamma={0:.3f}$ in 1D at $t = {1:.2f}$".format( + gamma, time), fontsize = 10) +ax[1][2].plot([-0.49, 0.1], [0.62, 0.62], "k-", lw = 1) +ax[1][2].text(-0.49, 0.5, "$\\textsc{{Swift}}$ {0}".format(git), fontsize = 10) +ax[1][2].text(-0.49, 0.4, scheme, fontsize = 10) +ax[1][2].text(-0.49, 0.3, kernel, fontsize = 10) +ax[1][2].text(-0.49, 0.2, + "${0:.2f}$ neighbours ($\\eta={1:.3f}$)".format(neighbours, eta), + fontsize = 10) +ax[1][2].set_xlim(-0.5, 0.5) +ax[1][2].set_ylim(0., 1.) +ax[1][2].set_xticks([]) +ax[1][2].set_yticks([]) -pl.xlabel("$x$") -pl.ylabel("$\\rho{}$") -pl.xlim(0.4, 1.) -pl.ylim(0., 7.) -pl.plot(coords[:,0], rho, "k.") -pl.savefig("InteractingBlastWaves.png") +pl.tight_layout() +pl.savefig("InteractingBlastWaves.png", dpi = 200) diff --git a/examples/InteractingBlastWaves_1D/run.sh b/examples/InteractingBlastWaves_1D/run.sh index 65a1a109857da6e32663451430b3284aa7207d5a..31717bd806ddd6c98c24dfc1def6f79dddff42ff 100755 --- a/examples/InteractingBlastWaves_1D/run.sh +++ b/examples/InteractingBlastWaves_1D/run.sh @@ -1,6 +1,6 @@ #!/bin/bash - # Generate the initial conditions if they are not present. +# Generate the initial conditions if they are not present. if [ ! -e interactingBlastWaves.hdf5 ] then echo "Generating initial conditions for the Sedov blast example..." @@ -10,5 +10,12 @@ fi # Run SWIFT ../swift -s -t 1 interactingBlastWaves.yml 2>&1 | tee output.log +# Get the high resolution reference solution if not present. +if [ ! -e interactingBlastWaves1D_exact.txt ] +then + echo "Fetching reference solution for the interacting blast waves test..." + ./getReference.sh +fi + # Plot the solution python plotSolution.py 4 diff --git a/examples/KelvinHelmholtzGrowthRate_2D/getGlass.sh b/examples/KelvinHelmholtzGrowthRate_2D/getGlass.sh new file mode 100755 index 0000000000000000000000000000000000000000..ae3c977064f5e7a408aa249c5fd9089b3c52ecb1 --- /dev/null +++ b/examples/KelvinHelmholtzGrowthRate_2D/getGlass.sh @@ -0,0 +1,2 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ICs/glassPlane_128.hdf5 diff --git a/examples/KelvinHelmholtzGrowthRate_2D/kelvinHelmholtzGrowthRate.yml b/examples/KelvinHelmholtzGrowthRate_2D/kelvinHelmholtzGrowthRate.yml new file mode 100644 index 0000000000000000000000000000000000000000..380dc2ab3a530e89b952aa41f425e50709d73ee9 --- /dev/null +++ b/examples/KelvinHelmholtzGrowthRate_2D/kelvinHelmholtzGrowthRate.yml @@ -0,0 +1,33 @@ +# Define the system of units to use internally. +InternalUnitSystem: + UnitMass_in_cgs: 1 # Grams + UnitLength_in_cgs: 1 # Centimeters + UnitVelocity_in_cgs: 1 # Centimeters per second + UnitCurrent_in_cgs: 1 # Amperes + UnitTemp_in_cgs: 1 # Kelvin + +# Parameters governing the time integration +TimeIntegration: + time_begin: 0. # The starting time of the simulation (in internal units). + time_end: 4. # The end time of the simulation (in internal units). + dt_min: 1e-6 # The minimal time-step size of the simulation (in internal units). + dt_max: 1e-2 # The maximal time-step size of the simulation (in internal units). + +# Parameters governing the snapshots +Snapshots: + basename: kelvinHelmholtzGrowthRate # Common part of the name of output files + time_first: 0. # Time of the first output (in internal units) + delta_time: 0.04 # Time difference between consecutive outputs (in internal units) + +# Parameters governing the conserved quantities statistics +Statistics: + delta_time: 1e-2 # Time between statistics output + +# Parameters for the hydrodynamics scheme +SPH: + resolution_eta: 1.2348 # Target smoothing length in units of the mean inter-particle separation (1.2348 == 48Ngbs with the cubic spline kernel). + CFL_condition: 0.1 # Courant-Friedrich-Levy condition for time integration. + +# Parameters related to the initial conditions +InitialConditions: + file_name: ./kelvinHelmholtzGrowthRate.hdf5 # The file to read diff --git a/examples/KelvinHelmholtzGrowthRate_2D/makeIC.py b/examples/KelvinHelmholtzGrowthRate_2D/makeIC.py new file mode 100644 index 0000000000000000000000000000000000000000..f21d0c0abf9b15f8253f627bcb1da43ae276fb35 --- /dev/null +++ b/examples/KelvinHelmholtzGrowthRate_2D/makeIC.py @@ -0,0 +1,100 @@ +################################################################################ +# This file is part of SWIFT. +# Copyright (c) 2016 Matthieu Schaller (matthieu.schaller@durham.ac.uk) +# 2017 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +################################################################################ + +import h5py +import numpy as np + +# Generates a swift IC file for the Kelvin-Helmholtz vortex in a periodic box + +# Parameters +gamma = 5./3. # Gas adiabatic index +P0 = 2.5 # Pressure +rho0 = 1. # Density +d = 0.0317 # Thickness of the transition layer +B = 0.0005 # Amplitude of the seed velocity + +fileOutputName = "kelvinHelmholtzGrowthRate.hdf5" + +#--------------------------------------------------- + +glass = h5py.File("glassPlane_128.hdf5", 'r') +pos = glass["/PartType0/Coordinates"][:, :] +h = glass["/PartType0/SmoothingLength"][:] + +N = len(h) +vol = 1. + +# Generate extra arrays +v = np.zeros((N, 3)) +ids = np.linspace(1, N, N) +m = np.ones(N) * rho0 * vol / N +u = np.ones(N) * P0 / (rho0 * (gamma - 1.)) + +v[pos[:, 1] <= 0.25 - d, 0] = -0.5 +v[(pos[:, 1] < 0.25 + d) & (pos[:, 1] > 0.25 - d), 0] = \ + -0.5 + \ + 0.5 * (pos[(pos[:, 1] < 0.25 + d) & (pos[:, 1] > 0.25 - d), 1] + d - 0.25) / d +v[(pos[:, 1] <= 0.75 - d) & (pos[:, 1] >= 0.25 + d), 0] = 0.5 +v[(pos[:, 1] < 0.75 + d) & (pos[:, 1] > 0.75 - d), 0] = \ + 0.5 - \ + 0.5 * (pos[(pos[:, 1] < 0.75 + d) & (pos[:, 1] > 0.75 - d), 1] + d - 0.75) / d +v[pos[:, 1] >= 0.75 + d, 0] = -0.5 + +v[:, 1] = B * np.sin(4. * np.pi * pos[:, 0]) * \ + (np.exp(-(pos[:, 1] - 0.25)**2 / 32. / d**2) + \ + np.exp(-(pos[:, 1] - 0.75)**2 / 32. / d**2)) + +#File +fileOutput = h5py.File(fileOutputName, 'w') + +# Header +grp = fileOutput.create_group("/Header") +grp.attrs["BoxSize"] = [1., 1., 1.] +grp.attrs["NumPart_Total"] = [N, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [N, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFileOutputsPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = [0, 0, 0, 0, 0, 0] +grp.attrs["Dimension"] = 2 + +#Runtime parameters +grp = fileOutput.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 1 + +#Units +grp = fileOutput.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = fileOutput.create_group("/PartType0") +grp.create_dataset("Coordinates", data = pos, dtype = 'd') +grp.create_dataset("Velocities", data = v, dtype = 'f') +grp.create_dataset("Masses", data = m, dtype = 'f') +grp.create_dataset("SmoothingLength", data = h, dtype = 'f') +grp.create_dataset("InternalEnergy", data = u, dtype = 'f') +grp.create_dataset("ParticleIDs", data = ids, dtype = 'L') + +fileOutput.close() diff --git a/examples/KelvinHelmholtzGrowthRate_2D/makeIC_regular.py b/examples/KelvinHelmholtzGrowthRate_2D/makeIC_regular.py new file mode 100644 index 0000000000000000000000000000000000000000..5029165a6a328b6c706d37b632b14cbcd51501d0 --- /dev/null +++ b/examples/KelvinHelmholtzGrowthRate_2D/makeIC_regular.py @@ -0,0 +1,106 @@ +################################################################################ +# This file is part of SWIFT. +# Copyright (c) 2016 Matthieu Schaller (matthieu.schaller@durham.ac.uk) +# 2017 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +################################################################################ + +import h5py +import numpy as np + +# Generates a swift IC file for the Kelvin-Helmholtz vortex in a periodic box + +# Parameters +gamma = 5./3. # Gas adiabatic index +P0 = 2.5 # Pressure +rho0 = 1. # Density +d = 0.0317 # Thickness of the transition layer +B = 0.0005 # Amplitude of the seed velocity +N1D = 128 # Number of particles in one dimension + +fileOutputName = "kelvinHelmholtzGrowthRate.hdf5" + +#--------------------------------------------------- + +N = N1D ** 2 +x = np.linspace(0., 1., N1D + 1) +x = 0.5 * (x[1:] + x[:-1]) +y = x +xx, yy = np.meshgrid(x, y) +pos = np.zeros((N, 3)) +pos[:, 0] = xx.reshape((N)) +pos[:, 1] = yy.reshape((N)) +h = np.ones(N) * 2. / N1D + +vol = 1. + +# Generate extra arrays +v = np.zeros((N, 3)) +ids = np.linspace(1, N, N) +m = np.ones(N) * rho0 * vol / N +u = np.ones(N) * P0 / (rho0 * (gamma - 1.)) + +v[pos[:, 1] <= 0.25 - d, 0] = -0.5 +v[(pos[:, 1] < 0.25 + d) & (pos[:, 1] > 0.25 - d), 0] = \ + -0.5 + \ + 0.5 * (pos[(pos[:, 1] < 0.25 + d) & (pos[:, 1] > 0.25 - d), 1] + d - 0.25) / d +v[(pos[:, 1] <= 0.75 - d) & (pos[:, 1] >= 0.25 + d), 0] = 0.5 +v[(pos[:, 1] < 0.75 + d) & (pos[:, 1] > 0.75 - d), 0] = \ + 0.5 - \ + 0.5 * (pos[(pos[:, 1] < 0.75 + d) & (pos[:, 1] > 0.75 - d), 1] + d - 0.75) / d +v[pos[:, 1] >= 0.75 + d, 0] = -0.5 + +v[:, 1] = B * np.sin(4. * np.pi * pos[:, 0]) * \ + (np.exp(-(pos[:, 1] - 0.25)**2 / 32. / d**2) + \ + np.exp(-(pos[:, 1] - 0.75)**2 / 32. / d**2)) + +#File +fileOutput = h5py.File(fileOutputName, 'w') + +# Header +grp = fileOutput.create_group("/Header") +grp.attrs["BoxSize"] = [1., 1., 1.] +grp.attrs["NumPart_Total"] = [N, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [N, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFileOutputsPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = [0, 0, 0, 0, 0, 0] +grp.attrs["Dimension"] = 2 + +#Runtime parameters +grp = fileOutput.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 1 + +#Units +grp = fileOutput.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = fileOutput.create_group("/PartType0") +grp.create_dataset("Coordinates", data = pos, dtype = 'd') +grp.create_dataset("Velocities", data = v, dtype = 'f') +grp.create_dataset("Masses", data = m, dtype = 'f') +grp.create_dataset("SmoothingLength", data = h, dtype = 'f') +grp.create_dataset("InternalEnergy", data = u, dtype = 'f') +grp.create_dataset("ParticleIDs", data = ids, dtype = 'L') + +fileOutput.close() diff --git a/examples/KelvinHelmholtzGrowthRate_2D/plotSolution.py b/examples/KelvinHelmholtzGrowthRate_2D/plotSolution.py new file mode 100644 index 0000000000000000000000000000000000000000..b2e3e1766a2b7d2618611aca9fb938ab87d78872 --- /dev/null +++ b/examples/KelvinHelmholtzGrowthRate_2D/plotSolution.py @@ -0,0 +1,47 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2017 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +################################################################################ + +import numpy as np +import h5py +import matplotlib +matplotlib.use("Agg") +import pylab as pl +import sys + +if len(sys.argv) < 2: + print "No final snapshot number provided!" + exit() +lastsnap = int(sys.argv[1]) + +# Read the simulation data +t = np.zeros(lastsnap + 1) +ey = np.zeros(lastsnap + 1) +for i in range(lastsnap + 1): + file = h5py.File("kelvinHelmholtzGrowthRate_{0:04d}.hdf5".format(i), 'r') + t_snap = float(file["/Header"].attrs["Time"]) + vy = file["/PartType0/Velocities"][:,1] + m = file["/PartType0/Masses"][:] + + ey_snap = 0.5 * m * vy**2 + + t[i] = t_snap + ey[i] = ey_snap.sum() + +pl.semilogy(t, ey, "k.") +pl.savefig("kelvinHelmholtzGrowthRate.png") diff --git a/examples/KelvinHelmholtzGrowthRate_2D/run.sh b/examples/KelvinHelmholtzGrowthRate_2D/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..3e6e026f66b14846a5c6e8e9daf99797dc3ff87a --- /dev/null +++ b/examples/KelvinHelmholtzGrowthRate_2D/run.sh @@ -0,0 +1,15 @@ +#!/bin/bash + + # Generate the initial conditions if they are not present. +if [ ! -e kelvinHelmholtzGrowthRate.hdf5 ] +then + echo "Generating initial conditions for the Kelvin-Helmholtz growth rate " \ + "example..." + python makeIC.py +fi + +# Run SWIFT +../swift -s -t 1 kelvinHelmholtzGrowthRate.yml 2>&1 | tee output.log + +# Plot the solution +python plotSolution.py 100 diff --git a/examples/KelvinHelmholtzGrowthRate_3D/getGlass.sh b/examples/KelvinHelmholtzGrowthRate_3D/getGlass.sh new file mode 100755 index 0000000000000000000000000000000000000000..d5c5f590ac37c9c9431d626a2ea61b0c12c1513c --- /dev/null +++ b/examples/KelvinHelmholtzGrowthRate_3D/getGlass.sh @@ -0,0 +1,2 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ICs/glassCube_64.hdf5 diff --git a/examples/KelvinHelmholtzGrowthRate_3D/kelvinHelmholtzGrowthRate.yml b/examples/KelvinHelmholtzGrowthRate_3D/kelvinHelmholtzGrowthRate.yml new file mode 100644 index 0000000000000000000000000000000000000000..380dc2ab3a530e89b952aa41f425e50709d73ee9 --- /dev/null +++ b/examples/KelvinHelmholtzGrowthRate_3D/kelvinHelmholtzGrowthRate.yml @@ -0,0 +1,33 @@ +# Define the system of units to use internally. +InternalUnitSystem: + UnitMass_in_cgs: 1 # Grams + UnitLength_in_cgs: 1 # Centimeters + UnitVelocity_in_cgs: 1 # Centimeters per second + UnitCurrent_in_cgs: 1 # Amperes + UnitTemp_in_cgs: 1 # Kelvin + +# Parameters governing the time integration +TimeIntegration: + time_begin: 0. # The starting time of the simulation (in internal units). + time_end: 4. # The end time of the simulation (in internal units). + dt_min: 1e-6 # The minimal time-step size of the simulation (in internal units). + dt_max: 1e-2 # The maximal time-step size of the simulation (in internal units). + +# Parameters governing the snapshots +Snapshots: + basename: kelvinHelmholtzGrowthRate # Common part of the name of output files + time_first: 0. # Time of the first output (in internal units) + delta_time: 0.04 # Time difference between consecutive outputs (in internal units) + +# Parameters governing the conserved quantities statistics +Statistics: + delta_time: 1e-2 # Time between statistics output + +# Parameters for the hydrodynamics scheme +SPH: + resolution_eta: 1.2348 # Target smoothing length in units of the mean inter-particle separation (1.2348 == 48Ngbs with the cubic spline kernel). + CFL_condition: 0.1 # Courant-Friedrich-Levy condition for time integration. + +# Parameters related to the initial conditions +InitialConditions: + file_name: ./kelvinHelmholtzGrowthRate.hdf5 # The file to read diff --git a/examples/KelvinHelmholtzGrowthRate_3D/makeIC.py b/examples/KelvinHelmholtzGrowthRate_3D/makeIC.py new file mode 100644 index 0000000000000000000000000000000000000000..a9bc20559b9fbb5da400ba5de2563cd715f473d5 --- /dev/null +++ b/examples/KelvinHelmholtzGrowthRate_3D/makeIC.py @@ -0,0 +1,100 @@ +################################################################################ +# This file is part of SWIFT. +# Copyright (c) 2016 Matthieu Schaller (matthieu.schaller@durham.ac.uk) +# 2017 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +################################################################################ + +import h5py +import numpy as np + +# Generates a swift IC file for the Kelvin-Helmholtz vortex in a periodic box + +# Parameters +gamma = 5./3. # Gas adiabatic index +P0 = 2.5 # Pressure +rho0 = 1. # Density +d = 0.0317 # Thickness of the transition layer +B = 0.0005 # Amplitude of the seed velocity + +fileOutputName = "kelvinHelmholtzGrowthRate.hdf5" + +#--------------------------------------------------- + +glass = h5py.File("glassCube_64.hdf5", 'r') +pos = glass["/PartType0/Coordinates"][:, :] +h = glass["/PartType0/SmoothingLength"][:] + +N = len(h) +vol = 1. + +# Generate extra arrays +v = np.zeros((N, 3)) +ids = np.linspace(1, N, N) +m = np.ones(N) * rho0 * vol / N +u = np.ones(N) * P0 / (rho0 * (gamma - 1.)) + +v[pos[:, 1] <= 0.25 - d, 0] = -0.5 +v[(pos[:, 1] < 0.25 + d) & (pos[:, 1] > 0.25 - d), 0] = \ + -0.5 + \ + 0.5 * (pos[(pos[:, 1] < 0.25 + d) & (pos[:, 1] > 0.25 - d), 1] + d - 0.25) / d +v[(pos[:, 1] <= 0.75 - d) & (pos[:, 1] >= 0.25 + d), 0] = 0.5 +v[(pos[:, 1] < 0.75 + d) & (pos[:, 1] > 0.75 - d), 0] = \ + 0.5 - \ + 0.5 * (pos[(pos[:, 1] < 0.75 + d) & (pos[:, 1] > 0.75 - d), 1] + d - 0.75) / d +v[pos[:, 1] >= 0.75 + d, 0] = -0.5 + +v[:, 1] = B * np.sin(4. * np.pi * pos[:, 0]) * \ + (np.exp(-(pos[:, 1] - 0.25)**2 / 32. / d**2) + \ + np.exp(-(pos[:, 1] - 0.75)**2 / 32. / d**2)) + +#File +fileOutput = h5py.File(fileOutputName, 'w') + +# Header +grp = fileOutput.create_group("/Header") +grp.attrs["BoxSize"] = [1., 1., 1.] +grp.attrs["NumPart_Total"] = [N, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [N, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFileOutputsPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = [0, 0, 0, 0, 0, 0] +grp.attrs["Dimension"] = 3 + +#Runtime parameters +grp = fileOutput.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 1 + +#Units +grp = fileOutput.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = fileOutput.create_group("/PartType0") +grp.create_dataset("Coordinates", data = pos, dtype = 'd') +grp.create_dataset("Velocities", data = v, dtype = 'f') +grp.create_dataset("Masses", data = m, dtype = 'f') +grp.create_dataset("SmoothingLength", data = h, dtype = 'f') +grp.create_dataset("InternalEnergy", data = u, dtype = 'f') +grp.create_dataset("ParticleIDs", data = ids, dtype = 'L') + +fileOutput.close() diff --git a/examples/KelvinHelmholtzGrowthRate_3D/makeIC_regular.py b/examples/KelvinHelmholtzGrowthRate_3D/makeIC_regular.py new file mode 100644 index 0000000000000000000000000000000000000000..aa7dd8f214f8ece1c1d142bf02bd653cd35f9973 --- /dev/null +++ b/examples/KelvinHelmholtzGrowthRate_3D/makeIC_regular.py @@ -0,0 +1,108 @@ +################################################################################ +# This file is part of SWIFT. +# Copyright (c) 2016 Matthieu Schaller (matthieu.schaller@durham.ac.uk) +# 2017 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +################################################################################ + +import h5py +import numpy as np + +# Generates a swift IC file for the Kelvin-Helmholtz vortex in a periodic box + +# Parameters +gamma = 5./3. # Gas adiabatic index +P0 = 2.5 # Pressure +rho0 = 1. # Density +d = 0.0317 # Thickness of the transition layer +B = 0.0005 # Amplitude of the seed velocity +N1D = 64 # Number of particles in one dimension + +fileOutputName = "kelvinHelmholtzGrowthRate.hdf5" + +#--------------------------------------------------- + +N = N1D ** 3 +x = np.linspace(0., 1., N1D + 1) +x = 0.5 * (x[1:] + x[:-1]) +y = x +z = x +xx, yy, zz = np.meshgrid(x, y, z) +pos = np.zeros((N, 3)) +pos[:, 0] = xx.reshape((N)) +pos[:, 1] = yy.reshape((N)) +pos[:, 2] = zz.reshape((N)) +h = np.ones(N) * 2. / N1D + +vol = 1. + +# Generate extra arrays +v = np.zeros((N, 3)) +ids = np.linspace(1, N, N) +m = np.ones(N) * rho0 * vol / N +u = np.ones(N) * P0 / (rho0 * (gamma - 1.)) + +v[pos[:, 1] <= 0.25 - d, 0] = -0.5 +v[(pos[:, 1] < 0.25 + d) & (pos[:, 1] > 0.25 - d), 0] = \ + -0.5 + \ + 0.5 * (pos[(pos[:, 1] < 0.25 + d) & (pos[:, 1] > 0.25 - d), 1] + d - 0.25) / d +v[(pos[:, 1] <= 0.75 - d) & (pos[:, 1] >= 0.25 + d), 0] = 0.5 +v[(pos[:, 1] < 0.75 + d) & (pos[:, 1] > 0.75 - d), 0] = \ + 0.5 - \ + 0.5 * (pos[(pos[:, 1] < 0.75 + d) & (pos[:, 1] > 0.75 - d), 1] + d - 0.75) / d +v[pos[:, 1] >= 0.75 + d, 0] = -0.5 + +v[:, 1] = B * np.sin(4. * np.pi * pos[:, 0]) * \ + (np.exp(-(pos[:, 1] - 0.25)**2 / 32. / d**2) + \ + np.exp(-(pos[:, 1] - 0.75)**2 / 32. / d**2)) + +#File +fileOutput = h5py.File(fileOutputName, 'w') + +# Header +grp = fileOutput.create_group("/Header") +grp.attrs["BoxSize"] = [1., 1., 1.] +grp.attrs["NumPart_Total"] = [N, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [N, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFileOutputsPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = [0, 0, 0, 0, 0, 0] +grp.attrs["Dimension"] = 3 + +#Runtime parameters +grp = fileOutput.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 1 + +#Units +grp = fileOutput.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = fileOutput.create_group("/PartType0") +grp.create_dataset("Coordinates", data = pos, dtype = 'd') +grp.create_dataset("Velocities", data = v, dtype = 'f') +grp.create_dataset("Masses", data = m, dtype = 'f') +grp.create_dataset("SmoothingLength", data = h, dtype = 'f') +grp.create_dataset("InternalEnergy", data = u, dtype = 'f') +grp.create_dataset("ParticleIDs", data = ids, dtype = 'L') + +fileOutput.close() diff --git a/examples/KelvinHelmholtzGrowthRate_3D/plotSolution.py b/examples/KelvinHelmholtzGrowthRate_3D/plotSolution.py new file mode 100644 index 0000000000000000000000000000000000000000..b2e3e1766a2b7d2618611aca9fb938ab87d78872 --- /dev/null +++ b/examples/KelvinHelmholtzGrowthRate_3D/plotSolution.py @@ -0,0 +1,47 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2017 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +################################################################################ + +import numpy as np +import h5py +import matplotlib +matplotlib.use("Agg") +import pylab as pl +import sys + +if len(sys.argv) < 2: + print "No final snapshot number provided!" + exit() +lastsnap = int(sys.argv[1]) + +# Read the simulation data +t = np.zeros(lastsnap + 1) +ey = np.zeros(lastsnap + 1) +for i in range(lastsnap + 1): + file = h5py.File("kelvinHelmholtzGrowthRate_{0:04d}.hdf5".format(i), 'r') + t_snap = float(file["/Header"].attrs["Time"]) + vy = file["/PartType0/Velocities"][:,1] + m = file["/PartType0/Masses"][:] + + ey_snap = 0.5 * m * vy**2 + + t[i] = t_snap + ey[i] = ey_snap.sum() + +pl.semilogy(t, ey, "k.") +pl.savefig("kelvinHelmholtzGrowthRate.png") diff --git a/examples/KelvinHelmholtzGrowthRate_3D/run.sh b/examples/KelvinHelmholtzGrowthRate_3D/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..3e6e026f66b14846a5c6e8e9daf99797dc3ff87a --- /dev/null +++ b/examples/KelvinHelmholtzGrowthRate_3D/run.sh @@ -0,0 +1,15 @@ +#!/bin/bash + + # Generate the initial conditions if they are not present. +if [ ! -e kelvinHelmholtzGrowthRate.hdf5 ] +then + echo "Generating initial conditions for the Kelvin-Helmholtz growth rate " \ + "example..." + python makeIC.py +fi + +# Run SWIFT +../swift -s -t 1 kelvinHelmholtzGrowthRate.yml 2>&1 | tee output.log + +# Plot the solution +python plotSolution.py 100 diff --git a/examples/SodShockSpherical_2D/getGlass.sh b/examples/SodShockSpherical_2D/getGlass.sh new file mode 100755 index 0000000000000000000000000000000000000000..f4cb4ebcb4b452b2b123462bc97eed532f43ba25 --- /dev/null +++ b/examples/SodShockSpherical_2D/getGlass.sh @@ -0,0 +1,3 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ICs/glassPlane_128.hdf5 +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ICs/glassPlane_48.hdf5 diff --git a/examples/SodShockSpherical_2D/getReference.sh b/examples/SodShockSpherical_2D/getReference.sh new file mode 100755 index 0000000000000000000000000000000000000000..8b152badc65ece3b519fa660001acc792ee3f3dc --- /dev/null +++ b/examples/SodShockSpherical_2D/getReference.sh @@ -0,0 +1,2 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ReferenceSolutions/sodShockSpherical2D_exact.txt diff --git a/examples/SodShockSpherical_2D/makeIC.py b/examples/SodShockSpherical_2D/makeIC.py new file mode 100644 index 0000000000000000000000000000000000000000..ac9f6e193769d7466f5b8e41a408da2350777be6 --- /dev/null +++ b/examples/SodShockSpherical_2D/makeIC.py @@ -0,0 +1,125 @@ +############################################################################### + # This file is part of SWIFT. + # Copyright (c) 2016 Matthieu Schaller (matthieu.schaller@durham.ac.uk) + # + # This program 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. + # + # This program 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 General Public License for more details. + # + # You should have received a copy of the GNU Lesser General Public License + # along with this program. If not, see <http://www.gnu.org/licenses/>. + # + ############################################################################## + +import h5py +from numpy import * + +# Generates a swift IC file for the 2D Sod Shock in a periodic box + +# Parameters +gamma = 5./3. # Gas adiabatic index +x_min = -1. +x_max = 1. +rho_L = 1. # Density left state +rho_R = 0.140625 # Density right state +v_L = 0. # Velocity left state +v_R = 0. # Velocity right state +P_L = 1. # Pressure left state +P_R = 0.1 # Pressure right state +fileName = "sodShock.hdf5" + + +#--------------------------------------------------- +boxSize = (x_max - x_min) + +glass_L = h5py.File("glassPlane_128.hdf5", "r") +glass_R = h5py.File("glassPlane_48.hdf5", "r") + +pos_L = glass_L["/PartType0/Coordinates"][:,:] +pos_R = glass_R["/PartType0/Coordinates"][:,:] +h_L = glass_L["/PartType0/SmoothingLength"][:] +h_R = glass_R["/PartType0/SmoothingLength"][:] + +radius_L = sqrt((pos_L[:,0] - 0.5)**2 + (pos_L[:,1] - 0.5)**2) +index_L = radius_L < 0.25 +pos_LL = pos_L[index_L] +h_LL = h_L[index_L] + +radius_R = sqrt((pos_R[:,0] - 0.5)**2 + (pos_R[:,1] - 0.5)**2) +index_R = radius_R > 0.25 +pos_RR = pos_R[index_R] +h_RR = h_R[index_R] + +# Merge things +pos = append(pos_LL, pos_RR, axis=0) +h = append(h_LL, h_RR) + +numPart_L = size(h_LL) +numPart_R = size(h_RR) +numPart = size(h) + +vol_L = pi * 0.25**2 +vol_R = 1. - pi * 0.25**2 + +# Generate extra arrays +v = zeros((numPart, 3)) +ids = linspace(1, numPart, numPart) +m = zeros(numPart) +u = zeros(numPart) + +for i in range(numPart): + x = sqrt((pos[i,0]-0.5)**2+(pos[i,1]-0.5)**2) + + if x < 0.25: #left + u[i] = P_L / (rho_L * (gamma - 1.)) + m[i] = rho_L * vol_L / numPart_L + v[i,0] = v_L + else: #right + u[i] = P_R / (rho_R * (gamma - 1.)) + m[i] = rho_R * vol_R / numPart_R + v[i,0] = v_R + +#File +file = h5py.File(fileName, 'w') + +# Header +grp = file.create_group("/Header") +grp.attrs["BoxSize"] = [1., 1., 1.] +grp.attrs["NumPart_Total"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFilesPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = 0 +grp.attrs["Dimension"] = 2 + +#Runtime parameters +grp = file.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 1 + +#Units +grp = file.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = file.create_group("/PartType0") +grp.create_dataset('Coordinates', data=pos, dtype='d') +grp.create_dataset('Velocities', data=v, dtype='f') +grp.create_dataset('Masses', data=m, dtype='f') +grp.create_dataset('SmoothingLength', data=h, dtype='f') +grp.create_dataset('InternalEnergy', data=u, dtype='f') +grp.create_dataset('ParticleIDs', data=ids, dtype='L') + + +file.close() diff --git a/examples/SodShockSpherical_2D/plotSolution.py b/examples/SodShockSpherical_2D/plotSolution.py new file mode 100644 index 0000000000000000000000000000000000000000..57b7f7ddc64bc25df031eb0cba7547f40d46b31a --- /dev/null +++ b/examples/SodShockSpherical_2D/plotSolution.py @@ -0,0 +1,163 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2016 Matthieu Schaller (matthieu.schaller@durham.ac.uk) +# 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +################################################################################ + +# Compares the swift result for the 2D spherical Sod shock with a high +# resolution 2D reference result + +import matplotlib +matplotlib.use("Agg") +from pylab import * +from scipy import stats +import h5py + +# Parameters +gas_gamma = 5./3. # Polytropic index +rho_L = 1. # Density left state +rho_R = 0.140625 # Density right state +v_L = 0. # Velocity left state +v_R = 0. # Velocity right state +P_L = 1. # Pressure left state +P_R = 0.1 # Pressure right state + +# Plot parameters +params = {'axes.labelsize': 10, +'axes.titlesize': 10, +'font.size': 12, +'legend.fontsize': 12, +'xtick.labelsize': 10, +'ytick.labelsize': 10, +'text.usetex': True, + 'figure.figsize' : (9.90,6.45), +'figure.subplot.left' : 0.045, +'figure.subplot.right' : 0.99, +'figure.subplot.bottom' : 0.05, +'figure.subplot.top' : 0.99, +'figure.subplot.wspace' : 0.15, +'figure.subplot.hspace' : 0.12, +'lines.markersize' : 6, +'lines.linewidth' : 3., +'text.latex.unicode': True +} +rcParams.update(params) +rc('font',**{'family':'sans-serif','sans-serif':['Times']}) + +snap = int(sys.argv[1]) + +# Read the simulation data +sim = h5py.File("sodShock_%04d.hdf5"%snap, "r") +boxSize = sim["/Header"].attrs["BoxSize"][0] +time = sim["/Header"].attrs["Time"][0] +scheme = sim["/HydroScheme"].attrs["Scheme"] +kernel = sim["/HydroScheme"].attrs["Kernel function"] +neighbours = sim["/HydroScheme"].attrs["Kernel target N_ngb"] +eta = sim["/HydroScheme"].attrs["Kernel eta"] +git = sim["Code"].attrs["Git Revision"] + +coords = sim["/PartType0/Coordinates"] +x = sqrt((coords[:,0] - 0.5)**2 + (coords[:,1] - 0.5)**2) +vels = sim["/PartType0/Velocities"] +v = sqrt(vels[:,0]**2 + vels[:,1]**2) +u = sim["/PartType0/InternalEnergy"][:] +S = sim["/PartType0/Entropy"][:] +P = sim["/PartType0/Pressure"][:] +rho = sim["/PartType0/Density"][:] + +# Bin the data +rho_bin,x_bin_edge,_ = \ + stats.binned_statistic(x, rho, statistic='mean', bins=100) +x_bin = 0.5*(x_bin_edge[1:] + x_bin_edge[:-1]) +v_bin,_,_ = stats.binned_statistic(x, v, statistic='mean', bins=x_bin_edge) +P_bin,_,_ = stats.binned_statistic(x, P, statistic='mean', bins=x_bin_edge) +S_bin,_,_ = stats.binned_statistic(x, S, statistic='mean', bins=x_bin_edge) +u_bin,_,_ = stats.binned_statistic(x, u, statistic='mean', bins=x_bin_edge) +rho2_bin,_,_ = stats.binned_statistic(x, rho**2, statistic='mean', bins=x_bin_edge) +v2_bin,_,_ = stats.binned_statistic(x, v**2, statistic='mean', bins=x_bin_edge) +P2_bin,_,_ = stats.binned_statistic(x, P**2, statistic='mean', bins=x_bin_edge) +S2_bin,_,_ = stats.binned_statistic(x, S**2, statistic='mean', bins=x_bin_edge) +u2_bin,_,_ = stats.binned_statistic(x, u**2, statistic='mean', bins=x_bin_edge) +rho_sigma_bin = np.sqrt(rho2_bin - rho_bin**2) +v_sigma_bin = np.sqrt(v2_bin - v_bin**2) +P_sigma_bin = np.sqrt(P2_bin - P_bin**2) +S_sigma_bin = np.sqrt(S2_bin - S_bin**2) +u_sigma_bin = np.sqrt(u2_bin - u_bin**2) + +ref = loadtxt("sodShockSpherical2D_exact.txt") + +# Plot the interesting quantities +figure() + +# Velocity profile -------------------------------- +subplot(231) +plot(x, v, '.', color='r', ms=0.2) +plot(ref[:,0], ref[:,2], "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, v_bin, yerr=v_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Velocity}}~v_r$", labelpad=0) + +# Density profile -------------------------------- +subplot(232) +plot(x, rho, '.', color='r', ms=0.2) +plot(ref[:,0], ref[:,1], "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, rho_bin, yerr=rho_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Density}}~\\rho$", labelpad=0) + +# Pressure profile -------------------------------- +subplot(233) +plot(x, P, '.', color='r', ms=0.2) +plot(ref[:,0], ref[:,3], "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, P_bin, yerr=P_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Pressure}}~P$", labelpad=0) + +# Internal energy profile ------------------------- +subplot(234) +plot(x, u, '.', color='r', ms=0.2) +plot(ref[:,0], ref[:,3] / ref[:,1] / (gas_gamma - 1.), "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, u_bin, yerr=u_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Internal~Energy}}~u$", labelpad=0) + +# Entropy profile --------------------------------- +subplot(235) +plot(x, S, '.', color='r', ms=0.2) +plot(ref[:,0], ref[:,3] / ref[:,1]**gas_gamma, "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, S_bin, yerr=S_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Entropy}}~S$", labelpad=0) + +# Information ------------------------------------- +subplot(236, frameon=False) + +text(-0.49, 0.9, "Sod shock with $\\gamma=%.3f$ in 2D at $t=%.2f$"%(gas_gamma,time), fontsize=10) +text(-0.49, 0.8, "Left:~~ $(P_L, \\rho_L, v_L) = (%.3f, %.3f, %.3f)$"%(P_L, rho_L, v_L), fontsize=10) +text(-0.49, 0.7, "Right: $(P_R, \\rho_R, v_R) = (%.3f, %.3f, %.3f)$"%(P_R, rho_R, v_R), fontsize=10) +plot([-0.49, 0.1], [0.62, 0.62], 'k-', lw=1) +text(-0.49, 0.5, "$\\textsc{Swift}$ %s"%git, fontsize=10) +text(-0.49, 0.4, scheme, fontsize=10) +text(-0.49, 0.3, kernel, fontsize=10) +text(-0.49, 0.2, "$%.2f$ neighbours ($\\eta=%.3f$)"%(neighbours, eta), fontsize=10) +xlim(-0.5, 0.5) +ylim(0, 1) +xticks([]) +yticks([]) + + +savefig("SodShock.png", dpi=200) diff --git a/examples/SodShockSpherical_2D/run.sh b/examples/SodShockSpherical_2D/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..d662d20f40ef9e221285d5820e867607804e9dbe --- /dev/null +++ b/examples/SodShockSpherical_2D/run.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +# Generate the initial conditions if they are not present. +if [ ! -e glassPlane_128.hdf5 ] +then + echo "Fetching initial glass file for the Sod shock example..." + ./getGlass.sh +fi +if [ ! -e sodShock.hdf5 ] +then + echo "Generating initial conditions for the Sod shock example..." + python makeIC.py +fi + +# Run SWIFT +../swift -s -t 1 sodShock.yml 2>&1 | tee output.log + +# Get the high resolution 1D reference solution if not present. +if [ ! -e sodShockSpherical2D_exact.txt ] +then + echo "Fetching reference solution for 2D spherical Sod shock example..." + ./getReference.sh +fi +python plotSolution.py 1 diff --git a/examples/SodShockSpherical_2D/sodShock.yml b/examples/SodShockSpherical_2D/sodShock.yml new file mode 100644 index 0000000000000000000000000000000000000000..a26ab95b21c782ce83310038432ac08df0e024c3 --- /dev/null +++ b/examples/SodShockSpherical_2D/sodShock.yml @@ -0,0 +1,34 @@ +# Define the system of units to use internally. +InternalUnitSystem: + UnitMass_in_cgs: 1 # Grams + UnitLength_in_cgs: 1 # Centimeters + UnitVelocity_in_cgs: 1 # Centimeters per second + UnitCurrent_in_cgs: 1 # Amperes + UnitTemp_in_cgs: 1 # Kelvin + +# Parameters governing the time integration +TimeIntegration: + time_begin: 0. # The starting time of the simulation (in internal units). + time_end: 0.1 # The end time of the simulation (in internal units). + dt_min: 1e-7 # The minimal time-step size of the simulation (in internal units). + dt_max: 1e-2 # The maximal time-step size of the simulation (in internal units). + +# Parameters governing the snapshots +Snapshots: + basename: sodShock # Common part of the name of output files + time_first: 0. # Time of the first output (in internal units) + delta_time: 0.1 # Time difference between consecutive outputs (in internal units) + +# Parameters governing the conserved quantities statistics +Statistics: + delta_time: 1e-2 # Time between statistics output + +# Parameters for the hydrodynamics scheme +SPH: + resolution_eta: 1.2348 # Target smoothing length in units of the mean inter-particle separation (1.2348 == 48Ngbs with the cubic spline kernel). + CFL_condition: 0.1 # Courant-Friedrich-Levy condition for time integration. + +# Parameters related to the initial conditions +InitialConditions: + file_name: ./sodShock.hdf5 # The file to read + diff --git a/examples/SodShockSpherical_3D/getGlass.sh b/examples/SodShockSpherical_3D/getGlass.sh new file mode 100755 index 0000000000000000000000000000000000000000..f61b61d4e6c51b44576fd7cdd6242cb9f0133039 --- /dev/null +++ b/examples/SodShockSpherical_3D/getGlass.sh @@ -0,0 +1,3 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ICs/glassCube_64.hdf5 +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ICs/glassCube_32.hdf5 diff --git a/examples/SodShockSpherical_3D/getReference.sh b/examples/SodShockSpherical_3D/getReference.sh new file mode 100755 index 0000000000000000000000000000000000000000..133d2fb8da9cbbfdc796140afc84a0859b9ca61e --- /dev/null +++ b/examples/SodShockSpherical_3D/getReference.sh @@ -0,0 +1,2 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ReferenceSolutions/sodShockSpherical3D_exact.txt diff --git a/examples/SodShockSpherical_3D/makeIC.py b/examples/SodShockSpherical_3D/makeIC.py new file mode 100644 index 0000000000000000000000000000000000000000..be8f9b61a1beef00f49786860ce94287b30e2ab3 --- /dev/null +++ b/examples/SodShockSpherical_3D/makeIC.py @@ -0,0 +1,127 @@ +############################################################################### + # This file is part of SWIFT. + # Copyright (c) 2016 Matthieu Schaller (matthieu.schaller@durham.ac.uk) + # + # This program 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. + # + # This program 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 General Public License for more details. + # + # You should have received a copy of the GNU Lesser General Public License + # along with this program. If not, see <http://www.gnu.org/licenses/>. + # + ############################################################################## + +import h5py +from numpy import * + +# Generates a swift IC file for the 3D Sod Shock in a periodic box + +# Parameters +gamma = 5./3. # Gas adiabatic index +x_min = -1. +x_max = 1. +rho_L = 1. # Density left state +rho_R = 0.125 # Density right state +v_L = 0. # Velocity left state +v_R = 0. # Velocity right state +P_L = 1. # Pressure left state +P_R = 0.1 # Pressure right state +fileName = "sodShock.hdf5" + + +#--------------------------------------------------- +boxSize = (x_max - x_min) + +glass_L = h5py.File("glassCube_64.hdf5", "r") +glass_R = h5py.File("glassCube_32.hdf5", "r") + +pos_L = glass_L["/PartType0/Coordinates"][:,:] +pos_R = glass_R["/PartType0/Coordinates"][:,:] +h_L = glass_L["/PartType0/SmoothingLength"][:] +h_R = glass_R["/PartType0/SmoothingLength"][:] + +radius_L = sqrt((pos_L[:,0] - 0.5)**2 + (pos_L[:,1] - 0.5)**2 + \ + (pos_L[:,2] - 0.5)**2) +index_L = radius_L < 0.25 +pos_LL = pos_L[index_L] +h_LL = h_L[index_L] + +radius_R = sqrt((pos_R[:,0] - 0.5)**2 + (pos_R[:,1] - 0.5)**2 + \ + (pos_R[:,2] - 0.5)**2) +index_R = radius_R > 0.25 +pos_RR = pos_R[index_R] +h_RR = h_R[index_R] + +# Merge things +pos = append(pos_LL, pos_RR, axis=0) +h = append(h_LL, h_RR) + +numPart_L = size(h_LL) +numPart_R = size(h_RR) +numPart = size(h) + +vol_L = 4. * pi / 3. * 0.25**3 +vol_R = 1. - 4. * pi / 3. * 0.25**3 + +# Generate extra arrays +v = zeros((numPart, 3)) +ids = linspace(1, numPart, numPart) +m = zeros(numPart) +u = zeros(numPart) + +for i in range(numPart): + x = sqrt((pos[i,0]-0.5)**2+(pos[i,1]-0.5)**2+(pos[i,2]-0.5)**2) + + if x < 0.25: #left + u[i] = P_L / (rho_L * (gamma - 1.)) + m[i] = rho_L * vol_L / numPart_L + v[i,0] = v_L + else: #right + u[i] = P_R / (rho_R * (gamma - 1.)) + m[i] = rho_R * vol_R / numPart_R + v[i,0] = v_R + +#File +file = h5py.File(fileName, 'w') + +# Header +grp = file.create_group("/Header") +grp.attrs["BoxSize"] = [1., 1., 1.] +grp.attrs["NumPart_Total"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFilesPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = 0 +grp.attrs["Dimension"] = 3 + +#Runtime parameters +grp = file.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 1 + +#Units +grp = file.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = file.create_group("/PartType0") +grp.create_dataset('Coordinates', data=pos, dtype='d') +grp.create_dataset('Velocities', data=v, dtype='f') +grp.create_dataset('Masses', data=m, dtype='f') +grp.create_dataset('SmoothingLength', data=h, dtype='f') +grp.create_dataset('InternalEnergy', data=u, dtype='f') +grp.create_dataset('ParticleIDs', data=ids, dtype='L') + + +file.close() diff --git a/examples/SodShockSpherical_3D/plotSolution.py b/examples/SodShockSpherical_3D/plotSolution.py new file mode 100644 index 0000000000000000000000000000000000000000..539bfba799e3231bd26ae2eb39c271baa1fa6a4b --- /dev/null +++ b/examples/SodShockSpherical_3D/plotSolution.py @@ -0,0 +1,164 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2016 Matthieu Schaller (matthieu.schaller@durham.ac.uk) +# 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +################################################################################ + +# Compares the swift result for the 2D spherical Sod shock with a high +# resolution 2D reference result + +import matplotlib +matplotlib.use("Agg") +from pylab import * +from scipy import stats +import h5py + +# Parameters +gas_gamma = 5./3. # Polytropic index +rho_L = 1. # Density left state +rho_R = 0.125 # Density right state +v_L = 0. # Velocity left state +v_R = 0. # Velocity right state +P_L = 1. # Pressure left state +P_R = 0.1 # Pressure right state + +# Plot parameters +params = {'axes.labelsize': 10, +'axes.titlesize': 10, +'font.size': 12, +'legend.fontsize': 12, +'xtick.labelsize': 10, +'ytick.labelsize': 10, +'text.usetex': True, + 'figure.figsize' : (9.90,6.45), +'figure.subplot.left' : 0.045, +'figure.subplot.right' : 0.99, +'figure.subplot.bottom' : 0.05, +'figure.subplot.top' : 0.99, +'figure.subplot.wspace' : 0.15, +'figure.subplot.hspace' : 0.12, +'lines.markersize' : 6, +'lines.linewidth' : 3., +'text.latex.unicode': True +} +rcParams.update(params) +rc('font',**{'family':'sans-serif','sans-serif':['Times']}) + +snap = int(sys.argv[1]) + +# Read the simulation data +sim = h5py.File("sodShock_%04d.hdf5"%snap, "r") +boxSize = sim["/Header"].attrs["BoxSize"][0] +time = sim["/Header"].attrs["Time"][0] +scheme = sim["/HydroScheme"].attrs["Scheme"] +kernel = sim["/HydroScheme"].attrs["Kernel function"] +neighbours = sim["/HydroScheme"].attrs["Kernel target N_ngb"] +eta = sim["/HydroScheme"].attrs["Kernel eta"] +git = sim["Code"].attrs["Git Revision"] + +coords = sim["/PartType0/Coordinates"] +x = sqrt((coords[:,0] - 0.5)**2 + (coords[:,1] - 0.5)**2 + \ + (coords[:,2] - 0.5)**2) +vels = sim["/PartType0/Velocities"] +v = sqrt(vels[:,0]**2 + vels[:,1]**2 + vels[:,2]**2) +u = sim["/PartType0/InternalEnergy"][:] +S = sim["/PartType0/Entropy"][:] +P = sim["/PartType0/Pressure"][:] +rho = sim["/PartType0/Density"][:] + +# Bin the data +rho_bin,x_bin_edge,_ = \ + stats.binned_statistic(x, rho, statistic='mean', bins=100) +x_bin = 0.5*(x_bin_edge[1:] + x_bin_edge[:-1]) +v_bin,_,_ = stats.binned_statistic(x, v, statistic='mean', bins=x_bin_edge) +P_bin,_,_ = stats.binned_statistic(x, P, statistic='mean', bins=x_bin_edge) +S_bin,_,_ = stats.binned_statistic(x, S, statistic='mean', bins=x_bin_edge) +u_bin,_,_ = stats.binned_statistic(x, u, statistic='mean', bins=x_bin_edge) +rho2_bin,_,_ = stats.binned_statistic(x, rho**2, statistic='mean', bins=x_bin_edge) +v2_bin,_,_ = stats.binned_statistic(x, v**2, statistic='mean', bins=x_bin_edge) +P2_bin,_,_ = stats.binned_statistic(x, P**2, statistic='mean', bins=x_bin_edge) +S2_bin,_,_ = stats.binned_statistic(x, S**2, statistic='mean', bins=x_bin_edge) +u2_bin,_,_ = stats.binned_statistic(x, u**2, statistic='mean', bins=x_bin_edge) +rho_sigma_bin = np.sqrt(rho2_bin - rho_bin**2) +v_sigma_bin = np.sqrt(v2_bin - v_bin**2) +P_sigma_bin = np.sqrt(P2_bin - P_bin**2) +S_sigma_bin = np.sqrt(S2_bin - S_bin**2) +u_sigma_bin = np.sqrt(u2_bin - u_bin**2) + +ref = loadtxt("sodShockSpherical3D_exact.txt") + +# Plot the interesting quantities +figure() + +# Velocity profile -------------------------------- +subplot(231) +plot(x, v, '.', color='r', ms=0.2) +plot(ref[:,0], ref[:,2], "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, v_bin, yerr=v_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Velocity}}~v_r$", labelpad=0) + +# Density profile -------------------------------- +subplot(232) +plot(x, rho, '.', color='r', ms=0.2) +plot(ref[:,0], ref[:,1], "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, rho_bin, yerr=rho_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Density}}~\\rho$", labelpad=0) + +# Pressure profile -------------------------------- +subplot(233) +plot(x, P, '.', color='r', ms=0.2) +plot(ref[:,0], ref[:,3], "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, P_bin, yerr=P_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Pressure}}~P$", labelpad=0) + +# Internal energy profile ------------------------- +subplot(234) +plot(x, u, '.', color='r', ms=0.2) +plot(ref[:,0], ref[:,3] / ref[:,1] / (gas_gamma - 1.), "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, u_bin, yerr=u_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Internal~Energy}}~u$", labelpad=0) + +# Entropy profile --------------------------------- +subplot(235) +plot(x, S, '.', color='r', ms=0.2) +plot(ref[:,0], ref[:,3] / ref[:,1]**gas_gamma, "k--", alpha=0.8, lw=1.2) +errorbar(x_bin, S_bin, yerr=S_sigma_bin, fmt='.', ms=8.0, color='b', lw=1.2) +xlabel("${\\rm{Radius}}~r$", labelpad=0) +ylabel("${\\rm{Entropy}}~S$", labelpad=0) + +# Information ------------------------------------- +subplot(236, frameon=False) + +text(-0.49, 0.9, "Sod shock with $\\gamma=%.3f$ in 3D at $t=%.2f$"%(gas_gamma,time), fontsize=10) +text(-0.49, 0.8, "Left:~~ $(P_L, \\rho_L, v_L) = (%.3f, %.3f, %.3f)$"%(P_L, rho_L, v_L), fontsize=10) +text(-0.49, 0.7, "Right: $(P_R, \\rho_R, v_R) = (%.3f, %.3f, %.3f)$"%(P_R, rho_R, v_R), fontsize=10) +plot([-0.49, 0.1], [0.62, 0.62], 'k-', lw=1) +text(-0.49, 0.5, "$\\textsc{Swift}$ %s"%git, fontsize=10) +text(-0.49, 0.4, scheme, fontsize=10) +text(-0.49, 0.3, kernel, fontsize=10) +text(-0.49, 0.2, "$%.2f$ neighbours ($\\eta=%.3f$)"%(neighbours, eta), fontsize=10) +xlim(-0.5, 0.5) +ylim(0, 1) +xticks([]) +yticks([]) + + +savefig("SodShock.png", dpi=200) diff --git a/examples/SodShockSpherical_3D/run.sh b/examples/SodShockSpherical_3D/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..faf979869e175172ce31db6ac5021daf1758f3b0 --- /dev/null +++ b/examples/SodShockSpherical_3D/run.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +# Generate the initial conditions if they are not present. +if [ ! -e glassCube_64.hdf5 ] +then + echo "Fetching initial glass file for the Sod shock example..." + ./getGlass.sh +fi +if [ ! -e sodShock.hdf5 ] +then + echo "Generating initial conditions for the Sod shock example..." + python makeIC.py +fi + +# Run SWIFT +../swift -s -t 4 sodShock.yml 2>&1 | tee output.log + +# Get the high resolution 1D reference solution if not present. +if [ ! -e sodShockSpherical3D_exact.txt ] +then + echo "Fetching reference solution for 3D spherical Sod shock example..." + ./getReference.sh +fi +python plotSolution.py 1 diff --git a/examples/SodShockSpherical_3D/sodShock.yml b/examples/SodShockSpherical_3D/sodShock.yml new file mode 100644 index 0000000000000000000000000000000000000000..a26ab95b21c782ce83310038432ac08df0e024c3 --- /dev/null +++ b/examples/SodShockSpherical_3D/sodShock.yml @@ -0,0 +1,34 @@ +# Define the system of units to use internally. +InternalUnitSystem: + UnitMass_in_cgs: 1 # Grams + UnitLength_in_cgs: 1 # Centimeters + UnitVelocity_in_cgs: 1 # Centimeters per second + UnitCurrent_in_cgs: 1 # Amperes + UnitTemp_in_cgs: 1 # Kelvin + +# Parameters governing the time integration +TimeIntegration: + time_begin: 0. # The starting time of the simulation (in internal units). + time_end: 0.1 # The end time of the simulation (in internal units). + dt_min: 1e-7 # The minimal time-step size of the simulation (in internal units). + dt_max: 1e-2 # The maximal time-step size of the simulation (in internal units). + +# Parameters governing the snapshots +Snapshots: + basename: sodShock # Common part of the name of output files + time_first: 0. # Time of the first output (in internal units) + delta_time: 0.1 # Time difference between consecutive outputs (in internal units) + +# Parameters governing the conserved quantities statistics +Statistics: + delta_time: 1e-2 # Time between statistics output + +# Parameters for the hydrodynamics scheme +SPH: + resolution_eta: 1.2348 # Target smoothing length in units of the mean inter-particle separation (1.2348 == 48Ngbs with the cubic spline kernel). + CFL_condition: 0.1 # Courant-Friedrich-Levy condition for time integration. + +# Parameters related to the initial conditions +InitialConditions: + file_name: ./sodShock.hdf5 # The file to read + diff --git a/examples/VacuumSpherical_2D/getGlass.sh b/examples/VacuumSpherical_2D/getGlass.sh new file mode 100755 index 0000000000000000000000000000000000000000..ae3c977064f5e7a408aa249c5fd9089b3c52ecb1 --- /dev/null +++ b/examples/VacuumSpherical_2D/getGlass.sh @@ -0,0 +1,2 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ICs/glassPlane_128.hdf5 diff --git a/examples/VacuumSpherical_2D/getReference.sh b/examples/VacuumSpherical_2D/getReference.sh new file mode 100755 index 0000000000000000000000000000000000000000..01080400dba430852f0245d42fb5e30f971721a8 --- /dev/null +++ b/examples/VacuumSpherical_2D/getReference.sh @@ -0,0 +1,2 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ReferenceSolutions/vacuumSpherical2D_exact.txt diff --git a/examples/VacuumSpherical_2D/makeIC.py b/examples/VacuumSpherical_2D/makeIC.py new file mode 100644 index 0000000000000000000000000000000000000000..498f1b5bc5277188d8ff8d34a5ec24cd314332d4 --- /dev/null +++ b/examples/VacuumSpherical_2D/makeIC.py @@ -0,0 +1,101 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +############################################################################### + +import numpy as np +import h5py + +# Generates an overdensity within a vacuum to test the vacuum resolving +# capabilities of the code + +# Parameters +gamma = 5. / 3. # Gas adiabatic index + +fileName = "vacuum.hdf5" + +#--------------------------------------------------- +glass = h5py.File("glassPlane_128.hdf5", "r") + +# Read particle positions and h from the glass +pos = glass["/PartType0/Coordinates"][:,:] +h = glass["/PartType0/SmoothingLength"][:] * 0.3 + +# Make 4 copies of the glass to have more particles +pos *= 0.5 +h *= 0.5 +pos = np.append(pos, pos + np.array([0.5, 0., 0.]), axis = 0) +h = np.append(h, h) +pos = np.append(pos, pos + np.array([0., 0.5, 0.]), axis = 0) +h = np.append(h, h) + +radius = np.sqrt((pos[:,0] - 0.5)**2 + (pos[:,1] - 0.5)**2) +index = radius < 0.25 +pos = pos[index] +h = h[index] + +numPart = len(h) +vol = np.pi * 0.25**2 + +# Generate extra arrays +v = np.zeros((numPart, 3)) +ids = np.linspace(1, numPart, numPart) +m = np.zeros(numPart) +u = np.zeros(numPart) + +m[:] = 1. * vol / numPart +u[:] = 1. / (1. * (gamma - 1.)) + +#-------------------------------------------------- + +#File +file = h5py.File(fileName, 'w') + +# Header +grp = file.create_group("/Header") +grp.attrs["BoxSize"] = [1., 1., 1.] +grp.attrs["NumPart_Total"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFilesPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = 0 +grp.attrs["Dimension"] = 2 + +#Runtime parameters +grp = file.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 1 + +#Units +grp = file.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = file.create_group("/PartType0") +grp.create_dataset('Coordinates', data=pos, dtype='d') +grp.create_dataset('Velocities', data=v, dtype='f') +grp.create_dataset('Masses', data=m, dtype='f') +grp.create_dataset('SmoothingLength', data=h, dtype='f') +grp.create_dataset('InternalEnergy', data=u, dtype='f') +grp.create_dataset('ParticleIDs', data=ids, dtype='L') + +file.close() diff --git a/examples/VacuumSpherical_2D/plotSolution.py b/examples/VacuumSpherical_2D/plotSolution.py new file mode 100644 index 0000000000000000000000000000000000000000..6a65206ae20ccf79392054d047ba6be04f169f3e --- /dev/null +++ b/examples/VacuumSpherical_2D/plotSolution.py @@ -0,0 +1,192 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +############################################################################## + +import numpy as np +import matplotlib +matplotlib.use("Agg") +import pylab as pl +import h5py +import sys +import scipy.stats as stats + +# Parameters +gamma = 5. / 3. # Polytropic index +rhoL = 1. # Initial density in the non vacuum state +vL = 0. # Initial velocity in the non vacuum state +PL = 1. # Initial pressure in the non vacuum state +rhoR = 0. # Initial vacuum density +vR = 0. # Initial vacuum velocity +PR = 0. # Initial vacuum pressure + +# Plot parameters +params = {'axes.labelsize': 10, +'axes.titlesize': 10, +'font.size': 12, +'legend.fontsize': 12, +'xtick.labelsize': 10, +'ytick.labelsize': 10, +'text.usetex': True, + 'figure.figsize' : (9.90,6.45), +'figure.subplot.left' : 0.045, +'figure.subplot.right' : 0.99, +'figure.subplot.bottom' : 0.05, +'figure.subplot.top' : 0.99, +'figure.subplot.wspace' : 0.15, +'figure.subplot.hspace' : 0.12, +'lines.markersize' : 6, +'lines.linewidth' : 3., +'text.latex.unicode': True +} +pl.rcParams.update(params) +pl.rc('font',**{'family':'sans-serif','sans-serif':['Times']}) + +# Read the snapshot index from the command line argument +snap = int(sys.argv[1]) + +# Open the file and read the relevant data +file = h5py.File("vacuum_{0:04d}.hdf5".format(snap), "r") +coords = file["/PartType0/Coordinates"] +x = np.sqrt((coords[:,0] - 0.5)**2 + (coords[:,1] - 0.5)**2) +rho = file["/PartType0/Density"][:] +vels = file["/PartType0/Velocities"] +v = np.sqrt(vels[:,0]**2 + vels[:,1]**2) +u = file["/PartType0/InternalEnergy"][:] +S = file["/PartType0/Entropy"][:] +P = file["/PartType0/Pressure"][:] +time = file["/Header"].attrs["Time"][0] + +scheme = file["/HydroScheme"].attrs["Scheme"] +kernel = file["/HydroScheme"].attrs["Kernel function"] +neighbours = file["/HydroScheme"].attrs["Kernel target N_ngb"][0] +eta = file["/HydroScheme"].attrs["Kernel eta"][0] +git = file["Code"].attrs["Git Revision"] + +# Bin the data values +# We let scipy choose the bins and then reuse them for all other quantities +rho_bin, x_bin_edge, _ = \ + stats.binned_statistic(x, rho, statistic = "mean", bins = 50) +rho2_bin, _, _ = \ + stats.binned_statistic(x, rho**2, statistic = "mean", bins = x_bin_edge) +rho_sigma_bin = np.sqrt(rho2_bin - rho_bin**2) + +v_bin, _, _ = \ + stats.binned_statistic(x, v, statistic = "mean", bins = x_bin_edge) +v2_bin, _, _ = \ + stats.binned_statistic(x, v**2, statistic = "mean", bins = x_bin_edge) +v_sigma_bin = np.sqrt(v2_bin - v_bin**2) + +P_bin, _, _ = \ + stats.binned_statistic(x, P, statistic = "mean", bins = x_bin_edge) +P2_bin, _, _ = \ + stats.binned_statistic(x, P**2, statistic = "mean", bins = x_bin_edge) +P_sigma_bin = np.sqrt(P2_bin - P_bin**2) + +u_bin, _, _ = \ + stats.binned_statistic(x, u, statistic = "mean", bins = x_bin_edge) +u2_bin, _, _ = \ + stats.binned_statistic(x, u**2, statistic = "mean", bins = x_bin_edge) +u_sigma_bin = np.sqrt(u2_bin - u_bin**2) + +S_bin, _, _ = \ + stats.binned_statistic(x, S, statistic = "mean", bins = x_bin_edge) +S2_bin, _, _ = \ + stats.binned_statistic(x, S**2, statistic = "mean", bins = x_bin_edge) +S_sigma_bin = np.sqrt(S2_bin - S_bin**2) + +x_bin = 0.5 * (x_bin_edge[1:] + x_bin_edge[:-1]) + +ref = np.loadtxt("vacuumSpherical2D_exact.txt") + +# Plot the interesting quantities +fig, ax = pl.subplots(2, 3) + +# Velocity profile +ax[0][0].plot(x, v, "r.", markersize = 0.2) +ax[0][0].plot(ref[:,0], ref[:,2], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][0].errorbar(x_bin, v_bin, yerr = v_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[0][0].set_xlabel("${\\rm{Radius}}~r$", labelpad = 0) +ax[0][0].set_ylabel("${\\rm{Velocity}}~v_r$", labelpad = 0) +ax[0][0].set_xlim(0., 0.4) +ax[0][0].set_ylim(-0.1, 3.2) + +# Density profile +ax[0][1].plot(x, rho, "r.", markersize = 0.2) +ax[0][1].plot(ref[:,0], ref[:,1], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][1].errorbar(x_bin, rho_bin, yerr = rho_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[0][1].set_xlabel("${\\rm{Radius}}~r$", labelpad = 0) +ax[0][1].set_ylabel("${\\rm{Density}}~\\rho$", labelpad = 0) +ax[0][1].set_xlim(0., 0.4) + +# Pressure profile +ax[0][2].plot(x, P, "r.", markersize = 0.2) +ax[0][2].plot(ref[:,0], ref[:,3], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][2].errorbar(x_bin, P_bin, yerr = P_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[0][2].set_xlabel("${\\rm{Radius}}~r$", labelpad = 0) +ax[0][2].set_ylabel("${\\rm{Pressure}}~P$", labelpad = 0) +ax[0][2].set_xlim(0., 0.4) + +# Internal energy profile +ax[1][0].plot(x, u, "r.", markersize = 0.2) +ax[1][0].plot(ref[:,0], ref[:,3] / ref[:,1] / (gamma - 1.), "k--", alpha = 0.8, + linewidth = 1.2) +ax[1][0].errorbar(x_bin, u_bin, yerr = u_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[1][0].set_xlabel("${\\rm{Radius}}~r$", labelpad = 0) +ax[1][0].set_ylabel("${\\rm{Internal~Energy}}~u$", labelpad = 0) +ax[1][0].set_xlim(0., 0.4) + +# Entropy profile +ax[1][1].plot(x, S, "r.", markersize = 0.2) +ax[1][1].plot(ref[:,0], ref[:,3] / ref[:,1]**gamma, "k--", alpha = 0.8, + linewidth = 1.2) +ax[1][1].errorbar(x_bin, S_bin, yerr = S_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[1][1].set_xlabel("${\\rm{Radius}}~r$", labelpad = 0) +ax[1][1].set_ylabel("${\\rm{Entropy}}~S$", labelpad = 0) +ax[1][1].set_xlim(0., 0.4) +ax[1][1].set_ylim(0., 4.) + +# Run information +ax[1][2].set_frame_on(False) +ax[1][2].text(-0.49, 0.9, + "Vacuum test with $\\gamma={0:.3f}$ in 1D at $t = {1:.2f}$".format( + gamma, time), fontsize = 10) +ax[1][2].text(-0.49, 0.8, + "Left:~~ $(P_L, \\rho_L, v_L) = ({0:.3f}, {1:.3f}, {2:.3f})$".format( + PL, rhoL, vL), fontsize = 10) +ax[1][2].text(-0.49, 0.7, + "Right: $(P_R, \\rho_R, v_R) = ({0:.3f}, {1:.3f}, {2:.3f})$".format( + PR, rhoR, vR), fontsize = 10) +ax[1][2].plot([-0.49, 0.1], [0.62, 0.62], "k-", lw = 1) +ax[1][2].text(-0.49, 0.5, "$\\textsc{{Swift}}$ {0}".format(git), fontsize = 10) +ax[1][2].text(-0.49, 0.4, scheme, fontsize = 10) +ax[1][2].text(-0.49, 0.3, kernel, fontsize = 10) +ax[1][2].text(-0.49, 0.2, + "${0:.2f}$ neighbours ($\\eta={1:.3f}$)".format(neighbours, eta), + fontsize = 10) +ax[1][2].set_xlim(-0.5, 0.5) +ax[1][2].set_ylim(0., 1.) +ax[1][2].set_xticks([]) +ax[1][2].set_yticks([]) + +pl.tight_layout() +pl.savefig("Vacuum.png", dpi = 200) diff --git a/examples/VacuumSpherical_2D/run.sh b/examples/VacuumSpherical_2D/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..51d32b4de679877741b7ecd74238fecb785579e7 --- /dev/null +++ b/examples/VacuumSpherical_2D/run.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +# Generate the initial conditions if they are not present. +if [ ! -e glassPlane_128.hdf5 ] +then + echo "Fetching initial glass file for the 2D vacuum expansion example..." + ./getGlass.sh +fi +if [ ! -e vacuum.hdf5 ] +then + echo "Generating initial conditions for the 2D vacuum expansion example..." + python makeIC.py +fi + +# Run SWIFT +../swift -s -t 4 vacuum.yml 2>&1 | tee output.log + +# Get the 1D high resolution reference result if not present. +if [ ! -e vacuumSpherical2D_exact.txt ] +then + echo "Fetching reference solution for the 2D vacuum expansion test..." + ./getReference.sh +fi + +# Plot the result +python plotSolution.py 1 diff --git a/examples/VacuumSpherical_2D/vacuum.yml b/examples/VacuumSpherical_2D/vacuum.yml new file mode 100644 index 0000000000000000000000000000000000000000..881b155b62c7f1f2af12a1d013ff5c05f1c16a88 --- /dev/null +++ b/examples/VacuumSpherical_2D/vacuum.yml @@ -0,0 +1,34 @@ +# Define the system of units to use internally. +InternalUnitSystem: + UnitMass_in_cgs: 1 # Grams + UnitLength_in_cgs: 1 # Centimeters + UnitVelocity_in_cgs: 1 # Centimeters per second + UnitCurrent_in_cgs: 1 # Amperes + UnitTemp_in_cgs: 1 # Kelvin + +# Parameters governing the time integration +TimeIntegration: + time_begin: 0. # The starting time of the simulation (in internal units). + time_end: 0.05 # The end time of the simulation (in internal units). + dt_min: 1e-10 # The minimal time-step size of the simulation (in internal units). + dt_max: 1e-2 # The maximal time-step size of the simulation (in internal units). + +# Parameters governing the snapshots +Snapshots: + basename: vacuum # Common part of the name of output files + time_first: 0. # Time of the first output (in internal units) + delta_time: 0.05 # Time difference between consecutive outputs (in internal units) + +# Parameters governing the conserved quantities statistics +Statistics: + delta_time: 1e-2 # Time between statistics output + +# Parameters for the hydrodynamics scheme +SPH: + resolution_eta: 1.2348 # Target smoothing length in units of the mean inter-particle separation (1.2348 == 48Ngbs with the cubic spline kernel). + CFL_condition: 0.1 # Courant-Friedrich-Levy condition for time integration. + +# Parameters related to the initial conditions +InitialConditions: + file_name: ./vacuum.hdf5 # The file to read + diff --git a/examples/VacuumSpherical_3D/getGlass.sh b/examples/VacuumSpherical_3D/getGlass.sh new file mode 100755 index 0000000000000000000000000000000000000000..d5c5f590ac37c9c9431d626a2ea61b0c12c1513c --- /dev/null +++ b/examples/VacuumSpherical_3D/getGlass.sh @@ -0,0 +1,2 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ICs/glassCube_64.hdf5 diff --git a/examples/VacuumSpherical_3D/getReference.sh b/examples/VacuumSpherical_3D/getReference.sh new file mode 100755 index 0000000000000000000000000000000000000000..49784c313f0c8758d88970169c30d39c58745ec4 --- /dev/null +++ b/examples/VacuumSpherical_3D/getReference.sh @@ -0,0 +1,2 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ReferenceSolutions/vacuumSpherical3D_exact.txt diff --git a/examples/VacuumSpherical_3D/makeIC.py b/examples/VacuumSpherical_3D/makeIC.py new file mode 100644 index 0000000000000000000000000000000000000000..d67a30707a904268a09641210a6a3bfcbf305dad --- /dev/null +++ b/examples/VacuumSpherical_3D/makeIC.py @@ -0,0 +1,104 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +############################################################################### + +import numpy as np +import h5py + +# Generates an overdensity within a vacuum to test the vacuum resolving +# capabilities of the code + +# Parameters +gamma = 5. / 3. # Gas adiabatic index + +fileName = "vacuum.hdf5" + +#--------------------------------------------------- +glass = h5py.File("glassCube_64.hdf5", "r") + +# Read particle positions and h from the glass +pos = glass["/PartType0/Coordinates"][:,:] +h = glass["/PartType0/SmoothingLength"][:] * 0.3 + +# Make 8 copies of the glass to get more particles +pos *= 0.5 +h *= 0.5 +pos = np.append(pos, pos + np.array([0.5, 0., 0.]), axis = 0) +pos = np.append(pos, pos + np.array([0., 0.5, 0.]), axis = 0) +pos = np.append(pos, pos + np.array([0., 0., 0.5]), axis = 0) +h = np.append(h, h) +h = np.append(h, h) +h = np.append(h, h) + +radius = np.sqrt((pos[:,0] - 0.5)**2 + (pos[:,1] - 0.5)**2 + \ + (pos[:,2] - 0.5)**2) +index = radius < 0.25 +pos = pos[index] +h = h[index] + +numPart = len(h) +vol = 4. * np.pi / 3. * 0.25**3 + +# Generate extra arrays +v = np.zeros((numPart, 3)) +ids = np.linspace(1, numPart, numPart) +m = np.zeros(numPart) +u = np.zeros(numPart) + +m[:] = 1. * vol / numPart +u[:] = 1. / (1. * (gamma - 1.)) + +#-------------------------------------------------- + +#File +file = h5py.File(fileName, 'w') + +# Header +grp = file.create_group("/Header") +grp.attrs["BoxSize"] = [1., 1., 1.] +grp.attrs["NumPart_Total"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFilesPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = 0 +grp.attrs["Dimension"] = 3 + +#Runtime parameters +grp = file.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 1 + +#Units +grp = file.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = file.create_group("/PartType0") +grp.create_dataset('Coordinates', data=pos, dtype='d') +grp.create_dataset('Velocities', data=v, dtype='f') +grp.create_dataset('Masses', data=m, dtype='f') +grp.create_dataset('SmoothingLength', data=h, dtype='f') +grp.create_dataset('InternalEnergy', data=u, dtype='f') +grp.create_dataset('ParticleIDs', data=ids, dtype='L') + +file.close() diff --git a/examples/VacuumSpherical_3D/plotSolution.py b/examples/VacuumSpherical_3D/plotSolution.py new file mode 100644 index 0000000000000000000000000000000000000000..c73e48ee2d311692cdf4aa3b0e52f4766b339df8 --- /dev/null +++ b/examples/VacuumSpherical_3D/plotSolution.py @@ -0,0 +1,193 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +############################################################################## + +import numpy as np +import matplotlib +matplotlib.use("Agg") +import pylab as pl +import h5py +import sys +import scipy.stats as stats + +# Parameters +gamma = 5. / 3. # Polytropic index +rhoL = 1. # Initial density in the non vacuum state +vL = 0. # Initial velocity in the non vacuum state +PL = 1. # Initial pressure in the non vacuum state +rhoR = 0. # Initial vacuum density +vR = 0. # Initial vacuum velocity +PR = 0. # Initial vacuum pressure + +# Plot parameters +params = {'axes.labelsize': 10, +'axes.titlesize': 10, +'font.size': 12, +'legend.fontsize': 12, +'xtick.labelsize': 10, +'ytick.labelsize': 10, +'text.usetex': True, + 'figure.figsize' : (9.90,6.45), +'figure.subplot.left' : 0.045, +'figure.subplot.right' : 0.99, +'figure.subplot.bottom' : 0.05, +'figure.subplot.top' : 0.99, +'figure.subplot.wspace' : 0.15, +'figure.subplot.hspace' : 0.12, +'lines.markersize' : 6, +'lines.linewidth' : 3., +'text.latex.unicode': True +} +pl.rcParams.update(params) +pl.rc('font',**{'family':'sans-serif','sans-serif':['Times']}) + +# Read the snapshot index from the command line argument +snap = int(sys.argv[1]) + +# Open the file and read the relevant data +file = h5py.File("vacuum_{0:04d}.hdf5".format(snap), "r") +coords = file["/PartType0/Coordinates"] +x = np.sqrt((coords[:,0] - 0.5)**2 + (coords[:,1] - 0.5)**2 + \ + (coords[:,2] - 0.5)**2) +rho = file["/PartType0/Density"][:] +vels = file["/PartType0/Velocities"] +v = np.sqrt(vels[:,0]**2 + vels[:,1]**2 + vels[:,2]**2) +u = file["/PartType0/InternalEnergy"][:] +S = file["/PartType0/Entropy"][:] +P = file["/PartType0/Pressure"][:] +time = file["/Header"].attrs["Time"][0] + +scheme = file["/HydroScheme"].attrs["Scheme"] +kernel = file["/HydroScheme"].attrs["Kernel function"] +neighbours = file["/HydroScheme"].attrs["Kernel target N_ngb"][0] +eta = file["/HydroScheme"].attrs["Kernel eta"][0] +git = file["Code"].attrs["Git Revision"] + +# Bin the data values +# We let scipy choose the bins and then reuse them for all other quantities +rho_bin, x_bin_edge, _ = \ + stats.binned_statistic(x, rho, statistic = "mean", bins = 50) +rho2_bin, _, _ = \ + stats.binned_statistic(x, rho**2, statistic = "mean", bins = x_bin_edge) +rho_sigma_bin = np.sqrt(rho2_bin - rho_bin**2) + +v_bin, _, _ = \ + stats.binned_statistic(x, v, statistic = "mean", bins = x_bin_edge) +v2_bin, _, _ = \ + stats.binned_statistic(x, v**2, statistic = "mean", bins = x_bin_edge) +v_sigma_bin = np.sqrt(v2_bin - v_bin**2) + +P_bin, _, _ = \ + stats.binned_statistic(x, P, statistic = "mean", bins = x_bin_edge) +P2_bin, _, _ = \ + stats.binned_statistic(x, P**2, statistic = "mean", bins = x_bin_edge) +P_sigma_bin = np.sqrt(P2_bin - P_bin**2) + +u_bin, _, _ = \ + stats.binned_statistic(x, u, statistic = "mean", bins = x_bin_edge) +u2_bin, _, _ = \ + stats.binned_statistic(x, u**2, statistic = "mean", bins = x_bin_edge) +u_sigma_bin = np.sqrt(u2_bin - u_bin**2) + +S_bin, _, _ = \ + stats.binned_statistic(x, S, statistic = "mean", bins = x_bin_edge) +S2_bin, _, _ = \ + stats.binned_statistic(x, S**2, statistic = "mean", bins = x_bin_edge) +S_sigma_bin = np.sqrt(S2_bin - S_bin**2) + +x_bin = 0.5 * (x_bin_edge[1:] + x_bin_edge[:-1]) + +ref = np.loadtxt("vacuumSpherical3D_exact.txt") + +# Plot the interesting quantities +fig, ax = pl.subplots(2, 3) + +# Velocity profile +ax[0][0].plot(x, v, "r.", markersize = 0.2) +ax[0][0].plot(ref[:,0], ref[:,2], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][0].errorbar(x_bin, v_bin, yerr = v_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[0][0].set_xlabel("${\\rm{Radius}}~r$", labelpad = 0) +ax[0][0].set_ylabel("${\\rm{Velocity}}~v_r$", labelpad = 0) +ax[0][0].set_xlim(0., 0.4) +ax[0][0].set_ylim(-0.1, 3.2) + +# Density profile +ax[0][1].plot(x, rho, "r.", markersize = 0.2) +ax[0][1].plot(ref[:,0], ref[:,1], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][1].errorbar(x_bin, rho_bin, yerr = rho_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[0][1].set_xlabel("${\\rm{Radius}}~r$", labelpad = 0) +ax[0][1].set_ylabel("${\\rm{Density}}~\\rho$", labelpad = 0) +ax[0][1].set_xlim(0., 0.4) + +# Pressure profile +ax[0][2].plot(x, P, "r.", markersize = 0.2) +ax[0][2].plot(ref[:,0], ref[:,3], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][2].errorbar(x_bin, P_bin, yerr = P_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[0][2].set_xlabel("${\\rm{Radius}}~r$", labelpad = 0) +ax[0][2].set_ylabel("${\\rm{Pressure}}~P$", labelpad = 0) +ax[0][2].set_xlim(0., 0.4) + +# Internal energy profile +ax[1][0].plot(x, u, "r.", markersize = 0.2) +ax[1][0].plot(ref[:,0], ref[:,3] / ref[:,1] / (gamma - 1.), "k--", alpha = 0.8, + linewidth = 1.2) +ax[1][0].errorbar(x_bin, u_bin, yerr = u_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[1][0].set_xlabel("${\\rm{Radius}}~r$", labelpad = 0) +ax[1][0].set_ylabel("${\\rm{Internal~Energy}}~u$", labelpad = 0) +ax[1][0].set_xlim(0., 0.4) + +# Entropy profile +ax[1][1].plot(x, S, "r.", markersize = 0.2) +ax[1][1].plot(ref[:,0], ref[:,3] / ref[:,1]**gamma, "k--", alpha = 0.8, + linewidth = 1.2) +ax[1][1].errorbar(x_bin, S_bin, yerr = S_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[1][1].set_xlabel("${\\rm{Radius}}~r$", labelpad = 0) +ax[1][1].set_ylabel("${\\rm{Entropy}}~S$", labelpad = 0) +ax[1][1].set_xlim(0., 0.4) +ax[1][1].set_ylim(0., 4.) + +# Run information +ax[1][2].set_frame_on(False) +ax[1][2].text(-0.49, 0.9, + "Vacuum test with $\\gamma={0:.3f}$ in 1D at $t = {1:.2f}$".format( + gamma, time), fontsize = 10) +ax[1][2].text(-0.49, 0.8, + "Left:~~ $(P_L, \\rho_L, v_L) = ({0:.3f}, {1:.3f}, {2:.3f})$".format( + PL, rhoL, vL), fontsize = 10) +ax[1][2].text(-0.49, 0.7, + "Right: $(P_R, \\rho_R, v_R) = ({0:.3f}, {1:.3f}, {2:.3f})$".format( + PR, rhoR, vR), fontsize = 10) +ax[1][2].plot([-0.49, 0.1], [0.62, 0.62], "k-", lw = 1) +ax[1][2].text(-0.49, 0.5, "$\\textsc{{Swift}}$ {0}".format(git), fontsize = 10) +ax[1][2].text(-0.49, 0.4, scheme, fontsize = 10) +ax[1][2].text(-0.49, 0.3, kernel, fontsize = 10) +ax[1][2].text(-0.49, 0.2, + "${0:.2f}$ neighbours ($\\eta={1:.3f}$)".format(neighbours, eta), + fontsize = 10) +ax[1][2].set_xlim(-0.5, 0.5) +ax[1][2].set_ylim(0., 1.) +ax[1][2].set_xticks([]) +ax[1][2].set_yticks([]) + +pl.tight_layout() +pl.savefig("Vacuum.png", dpi = 200) diff --git a/examples/VacuumSpherical_3D/run.sh b/examples/VacuumSpherical_3D/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..a136929678f745f6a3d0859ba146e1bc1c6c43d0 --- /dev/null +++ b/examples/VacuumSpherical_3D/run.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +# Generate the initial conditions if they are not present. +if [ ! -e glassCube_64.hdf5 ] +then + echo "Fetching initial glass file for the 3D vacuum expansion example..." + ./getGlass.sh +fi +if [ ! -e vacuum.hdf5 ] +then + echo "Generating initial conditions for the 3D vacuum expansion example..." + python makeIC.py +fi + +# Run SWIFT +../swift -s -t 16 vacuum.yml 2>&1 | tee output.log + +# Get the reference solution if it is not present. +if [ ! -e vacuumSpherical3D_exact.txt ] +then + echo "Fetching reference solution for the 3D vacuum expansion test..." + ./getReference.sh +fi + +# Plot the result +python plotSolution.py 1 diff --git a/examples/VacuumSpherical_3D/vacuum.yml b/examples/VacuumSpherical_3D/vacuum.yml new file mode 100644 index 0000000000000000000000000000000000000000..881b155b62c7f1f2af12a1d013ff5c05f1c16a88 --- /dev/null +++ b/examples/VacuumSpherical_3D/vacuum.yml @@ -0,0 +1,34 @@ +# Define the system of units to use internally. +InternalUnitSystem: + UnitMass_in_cgs: 1 # Grams + UnitLength_in_cgs: 1 # Centimeters + UnitVelocity_in_cgs: 1 # Centimeters per second + UnitCurrent_in_cgs: 1 # Amperes + UnitTemp_in_cgs: 1 # Kelvin + +# Parameters governing the time integration +TimeIntegration: + time_begin: 0. # The starting time of the simulation (in internal units). + time_end: 0.05 # The end time of the simulation (in internal units). + dt_min: 1e-10 # The minimal time-step size of the simulation (in internal units). + dt_max: 1e-2 # The maximal time-step size of the simulation (in internal units). + +# Parameters governing the snapshots +Snapshots: + basename: vacuum # Common part of the name of output files + time_first: 0. # Time of the first output (in internal units) + delta_time: 0.05 # Time difference between consecutive outputs (in internal units) + +# Parameters governing the conserved quantities statistics +Statistics: + delta_time: 1e-2 # Time between statistics output + +# Parameters for the hydrodynamics scheme +SPH: + resolution_eta: 1.2348 # Target smoothing length in units of the mean inter-particle separation (1.2348 == 48Ngbs with the cubic spline kernel). + CFL_condition: 0.1 # Courant-Friedrich-Levy condition for time integration. + +# Parameters related to the initial conditions +InitialConditions: + file_name: ./vacuum.hdf5 # The file to read + diff --git a/examples/Vacuum_1D/makeIC.py b/examples/Vacuum_1D/makeIC.py new file mode 100644 index 0000000000000000000000000000000000000000..067304ec951182da862cf2812cdc68a51a56d23b --- /dev/null +++ b/examples/Vacuum_1D/makeIC.py @@ -0,0 +1,88 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +############################################################################## + +# Generates an overdensity within a vacuum to test the vacuum handling +# capabilities of the code + +import numpy as np +import h5py + +fileName = "vacuum.hdf5" +numPart = 100 +boxSize = 1. +gamma = 5. / 3. + +coords = np.zeros((numPart, 3)) +v = np.zeros((numPart, 3)) +m = np.zeros(numPart) +h = np.zeros(numPart) +u = np.zeros(numPart) +ids = np.arange(numPart, dtype = 'L') +rho = np.zeros(numPart) + +# first set the positions, as we try to do a reasonable volume estimate to +# set the masses +for i in range(numPart): + # we only generate particles in the range [0.25, 0.75] + coords[i,0] = 0.25 + 0.5 * (i + 0.5) / numPart + rho[i] = 1. + P = 1. + u[i] = P / (gamma - 1.) / rho[i] + m[i] = rho[i] * 0.5 / numPart + # reasonable smoothing length estimate + h[i] = 1. / numPart + +#File +file = h5py.File(fileName, 'w') + +# Header +grp = file.create_group("/Header") +grp.attrs["BoxSize"] = boxSize +grp.attrs["NumPart_Total"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFilesPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = 0 +grp.attrs["Dimension"] = 1 + +#Runtime parameters +grp = file.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 1 + +#Units +grp = file.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = file.create_group("/PartType0") +grp.create_dataset('Coordinates', data=coords, dtype='d') +grp.create_dataset('Velocities', data=v, dtype='f') +grp.create_dataset('Masses', data=m, dtype='f') +grp.create_dataset('SmoothingLength', data=h, dtype='f') +grp.create_dataset('InternalEnergy', data=u, dtype='f') +grp.create_dataset('ParticleIDs', data=ids, dtype='L') +grp.create_dataset('Density', data=rho, dtype='f') + +file.close() diff --git a/examples/Vacuum_1D/plotSolution.py b/examples/Vacuum_1D/plotSolution.py new file mode 100644 index 0000000000000000000000000000000000000000..fceac10c25fd58b5bbcb6e31884cd62b4cfd61f5 --- /dev/null +++ b/examples/Vacuum_1D/plotSolution.py @@ -0,0 +1,180 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +############################################################################## + +import numpy as np +import matplotlib +matplotlib.use("Agg") +import pylab as pl +import h5py +import sys + +# Parameters +gamma = 5. / 3. # Polytropic index +rhoL = 1. # Initial density in the non vacuum state +vL = 0. # Initial velocity in the non vacuum state +PL = 1. # Initial pressure in the non vacuum state +rhoR = 0. # Initial vacuum density +vR = 0. # Initial vacuum velocity +PR = 0. # Initial vacuum pressure + +# Plot parameters +params = {'axes.labelsize': 10, +'axes.titlesize': 10, +'font.size': 12, +'legend.fontsize': 12, +'xtick.labelsize': 10, +'ytick.labelsize': 10, +'text.usetex': True, + 'figure.figsize' : (9.90,6.45), +'figure.subplot.left' : 0.045, +'figure.subplot.right' : 0.99, +'figure.subplot.bottom' : 0.05, +'figure.subplot.top' : 0.99, +'figure.subplot.wspace' : 0.15, +'figure.subplot.hspace' : 0.12, +'lines.markersize' : 6, +'lines.linewidth' : 3., +'text.latex.unicode': True +} +pl.rcParams.update(params) +pl.rc('font',**{'family':'sans-serif','sans-serif':['Times']}) + +# Read the snapshot index from the command line argument +snap = int(sys.argv[1]) + +# Open the file and read the relevant data +file = h5py.File("vacuum_{0:04d}.hdf5".format(snap), "r") +x = file["/PartType0/Coordinates"][:,0] +rho = file["/PartType0/Density"] +v = file["/PartType0/Velocities"][:,0] +u = file["/PartType0/InternalEnergy"] +S = file["/PartType0/Entropy"] +P = file["/PartType0/Pressure"] +time = file["/Header"].attrs["Time"][0] + +scheme = file["/HydroScheme"].attrs["Scheme"] +kernel = file["/HydroScheme"].attrs["Kernel function"] +neighbours = file["/HydroScheme"].attrs["Kernel target N_ngb"][0] +eta = file["/HydroScheme"].attrs["Kernel eta"][0] +git = file["Code"].attrs["Git Revision"] + +# Get the analytic solution, which is just the solution of the corresponding +# vacuum Riemann problem evaluated at the correct time + +# left state sound speed (and rarefaction wave speed) +aL = np.sqrt(gamma * PL / rhoL) + +# vacuum front speed +SL = vL + 2. / (gamma - 1.) * aL + +# we evaluate the solution centred on 0., and shift to the correct position +# afterwards +xa = np.arange(-0.25, 0.25, 0.001) +rhoa = np.zeros(len(xa)) +va = np.zeros(len(xa)) +Pa = np.zeros(len(xa)) + +for i in range(len(xa)): + dxdt = xa[i] / time + if dxdt > vL - aL: + if dxdt < SL: + # rarefaction regime + # factor that appears in both the density and pressure expression + fac = 2. / (gamma + 1.) + \ + (gamma - 1.) / (gamma + 1.) * (vL - dxdt) / aL + rhoa[i] = rhoL * fac**(2. / (gamma - 1.)) + va[i] = 2. / (gamma + 1.) * (aL + 0.5 * (gamma - 1.) * vL + dxdt) + Pa[i] = PL * fac**(2. * gamma / (gamma - 1.)) + else: + # vacuum regime + rhoa[i] = 0. + va[i] = 0. + Pa[i] = 0. + else: + # left state regime + rhoa[i] = rhoL + va[i] = vL + Pa[i] = PL + +ua = Pa / (gamma - 1.) / rhoa +Sa = Pa / rhoa**gamma + +# Plot the interesting quantities +fig, ax = pl.subplots(2, 3) + +# Velocity profile +ax[0][0].plot(x, v, "r.", markersize = 4.) +ax[0][0].plot(xa + 0.75, va, "k--", alpha = 0.8, linewidth = 1.2) +ax[0][0].plot(xa + 0.25, -va[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][0].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[0][0].set_ylabel("${\\rm{Velocity}}~v_x$", labelpad = 0) + +# Density profile +ax[0][1].plot(x, rho, "r.", markersize = 4.) +ax[0][1].plot(xa + 0.75, rhoa, "k--", alpha = 0.8, linewidth = 1.2) +ax[0][1].plot(xa + 0.25, rhoa[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][1].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[0][1].set_ylabel("${\\rm{Density}}~\\rho$", labelpad = 0) + +# Pressure profile +ax[0][2].plot(x, P, "r.", markersize = 4.) +ax[0][2].plot(xa + 0.75, Pa, "k--", alpha = 0.8, linewidth = 1.2) +ax[0][2].plot(xa + 0.25, Pa[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][2].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[0][2].set_ylabel("${\\rm{Pressure}}~P$", labelpad = 0) + +# Internal energy profile +ax[1][0].plot(x, u, "r.", markersize = 4.) +ax[1][0].plot(xa + 0.75, ua, "k--", alpha = 0.8, linewidth = 1.2) +ax[1][0].plot(xa + 0.25, ua[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[1][0].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[1][0].set_ylabel("${\\rm{Internal~Energy}}~u$", labelpad = 0) + +# Entropy profile +ax[1][1].plot(x, S, "r.", markersize = 4.) +ax[1][1].plot(xa + 0.75, Sa, "k--", alpha = 0.8, linewidth = 1.2) +ax[1][1].plot(xa + 0.25, Sa[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[1][1].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[1][1].set_ylabel("${\\rm{Entropy}}~S$", labelpad = 0) + +# Run information +ax[1][2].set_frame_on(False) +ax[1][2].text(-0.49, 0.9, + "Vacuum test with $\\gamma={0:.3f}$ in 1D at $t = {1:.2f}$".format( + gamma, time), fontsize = 10) +ax[1][2].text(-0.49, 0.8, + "Left:~~ $(P_L, \\rho_L, v_L) = ({0:.3f}, {1:.3f}, {2:.3f})$".format( + PL, rhoL, vL), fontsize = 10) +ax[1][2].text(-0.49, 0.7, + "Right: $(P_R, \\rho_R, v_R) = ({0:.3f}, {1:.3f}, {2:.3f})$".format( + PR, rhoR, vR), fontsize = 10) +ax[1][2].plot([-0.49, 0.1], [0.62, 0.62], "k-", lw = 1) +ax[1][2].text(-0.49, 0.5, "$\\textsc{{Swift}}$ {0}".format(git), fontsize = 10) +ax[1][2].text(-0.49, 0.4, scheme, fontsize = 10) +ax[1][2].text(-0.49, 0.3, kernel, fontsize = 10) +ax[1][2].text(-0.49, 0.2, + "${0:.2f}$ neighbours ($\\eta={1:.3f}$)".format(neighbours, eta), + fontsize = 10) +ax[1][2].set_xlim(-0.5, 0.5) +ax[1][2].set_ylim(0., 1.) +ax[1][2].set_xticks([]) +ax[1][2].set_yticks([]) + +pl.tight_layout() +pl.savefig("Vacuum.png", dpi = 200) diff --git a/examples/Vacuum_1D/run.sh b/examples/Vacuum_1D/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..b141f91f877c5b553281e53cdf02fbea948b0a97 --- /dev/null +++ b/examples/Vacuum_1D/run.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +# Generate the initial conditions if they are not present. +if [ ! -e vacuum.hdf5 ] +then + echo "Generating initial conditions for the 1D vacuum expansion example..." + python makeIC.py +fi + +# Run SWIFT +../swift -s -t 1 vacuum.yml 2>&1 | tee output.log + +# Plot the result +python plotSolution.py 1 diff --git a/examples/Vacuum_1D/vacuum.yml b/examples/Vacuum_1D/vacuum.yml new file mode 100644 index 0000000000000000000000000000000000000000..5ef5ce3da68febb086a14ad1a2207711f680d9ff --- /dev/null +++ b/examples/Vacuum_1D/vacuum.yml @@ -0,0 +1,34 @@ +# Define the system of units to use internally. +InternalUnitSystem: + UnitMass_in_cgs: 1 # Grams + UnitLength_in_cgs: 1 # Centimeters + UnitVelocity_in_cgs: 1 # Centimeters per second + UnitCurrent_in_cgs: 1 # Amperes + UnitTemp_in_cgs: 1 # Kelvin + +# Parameters governing the time integration +TimeIntegration: + time_begin: 0. # The starting time of the simulation (in internal units). + time_end: 0.1 # The end time of the simulation (in internal units). + dt_min: 1e-10 # The minimal time-step size of the simulation (in internal units). + dt_max: 1e-2 # The maximal time-step size of the simulation (in internal units). + +# Parameters governing the snapshots +Snapshots: + basename: vacuum # Common part of the name of output files + time_first: 0. # Time of the first output (in internal units) + delta_time: 0.1 # Time difference between consecutive outputs (in internal units) + +# Parameters governing the conserved quantities statistics +Statistics: + delta_time: 1e-2 # Time between statistics output + +# Parameters for the hydrodynamics scheme +SPH: + resolution_eta: 1.2348 # Target smoothing length in units of the mean inter-particle separation (1.2348 == 48Ngbs with the cubic spline kernel). + CFL_condition: 0.1 # Courant-Friedrich-Levy condition for time integration. + +# Parameters related to the initial conditions +InitialConditions: + file_name: ./vacuum.hdf5 # The file to read + diff --git a/examples/Vacuum_2D/getGlass.sh b/examples/Vacuum_2D/getGlass.sh new file mode 100755 index 0000000000000000000000000000000000000000..ae3c977064f5e7a408aa249c5fd9089b3c52ecb1 --- /dev/null +++ b/examples/Vacuum_2D/getGlass.sh @@ -0,0 +1,2 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ICs/glassPlane_128.hdf5 diff --git a/examples/Vacuum_2D/makeIC.py b/examples/Vacuum_2D/makeIC.py new file mode 100644 index 0000000000000000000000000000000000000000..ef267c092cafdb95457d5adad1e6858df0e14bd3 --- /dev/null +++ b/examples/Vacuum_2D/makeIC.py @@ -0,0 +1,95 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +############################################################################### + +import numpy as np +import h5py + +# Generates an overdensity within a vacuum to test the vacuum resolving +# capabilities of the code + +# Parameters +gamma = 5. / 3. # Gas adiabatic index + +fileName = "vacuum.hdf5" + +#--------------------------------------------------- +glass = h5py.File("glassPlane_128.hdf5", "r") + +# Read particle positions and h from the glass +pos = glass["/PartType0/Coordinates"][:,:] +h = glass["/PartType0/SmoothingLength"][:] * 0.3 + +# Shrink the glass to half its size, move it to the centre of the box, and +# clone it in the y direction +pos = 0.5 * pos + np.array([0.25, 0., 0.]) +h *= 0.5 +pos = np.append(pos, pos + np.array([0., 0.5, 0.]), axis = 0) +h = np.append(h, h) + +numPart = len(h) +vol = 0.5 + +# Generate extra arrays +v = np.zeros((numPart, 3)) +ids = np.linspace(1, numPart, numPart) +m = np.zeros(numPart) +u = np.zeros(numPart) + +m[:] = 1. * vol / numPart +u[:] = 1. / (1. * (gamma - 1.)) + +#-------------------------------------------------- + +#File +file = h5py.File(fileName, 'w') + +# Header +grp = file.create_group("/Header") +grp.attrs["BoxSize"] = [1., 1., 1.] +grp.attrs["NumPart_Total"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFilesPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = 0 +grp.attrs["Dimension"] = 2 + +#Runtime parameters +grp = file.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 1 + +#Units +grp = file.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = file.create_group("/PartType0") +grp.create_dataset('Coordinates', data=pos, dtype='d') +grp.create_dataset('Velocities', data=v, dtype='f') +grp.create_dataset('Masses', data=m, dtype='f') +grp.create_dataset('SmoothingLength', data=h, dtype='f') +grp.create_dataset('InternalEnergy', data=u, dtype='f') +grp.create_dataset('ParticleIDs', data=ids, dtype='L') + +file.close() diff --git a/examples/Vacuum_2D/plotSolution.py b/examples/Vacuum_2D/plotSolution.py new file mode 100644 index 0000000000000000000000000000000000000000..4d197234237df10b8cdbf197048a65991da023cf --- /dev/null +++ b/examples/Vacuum_2D/plotSolution.py @@ -0,0 +1,225 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +############################################################################## + +import numpy as np +import matplotlib +matplotlib.use("Agg") +import pylab as pl +import h5py +import sys +import scipy.stats as stats + +# Parameters +gamma = 5. / 3. # Polytropic index +rhoL = 1. # Initial density in the non vacuum state +vL = 0. # Initial velocity in the non vacuum state +PL = 1. # Initial pressure in the non vacuum state +rhoR = 0. # Initial vacuum density +vR = 0. # Initial vacuum velocity +PR = 0. # Initial vacuum pressure + +# Plot parameters +params = {'axes.labelsize': 10, +'axes.titlesize': 10, +'font.size': 12, +'legend.fontsize': 12, +'xtick.labelsize': 10, +'ytick.labelsize': 10, +'text.usetex': True, + 'figure.figsize' : (9.90,6.45), +'figure.subplot.left' : 0.045, +'figure.subplot.right' : 0.99, +'figure.subplot.bottom' : 0.05, +'figure.subplot.top' : 0.99, +'figure.subplot.wspace' : 0.15, +'figure.subplot.hspace' : 0.12, +'lines.markersize' : 6, +'lines.linewidth' : 3., +'text.latex.unicode': True +} +pl.rcParams.update(params) +pl.rc('font',**{'family':'sans-serif','sans-serif':['Times']}) + +# Read the snapshot index from the command line argument +snap = int(sys.argv[1]) + +# Open the file and read the relevant data +file = h5py.File("vacuum_{0:04d}.hdf5".format(snap), "r") +x = file["/PartType0/Coordinates"][:,0] +rho = file["/PartType0/Density"][:] +v = file["/PartType0/Velocities"][:,0] +u = file["/PartType0/InternalEnergy"][:] +S = file["/PartType0/Entropy"][:] +P = file["/PartType0/Pressure"][:] +time = file["/Header"].attrs["Time"][0] + +scheme = file["/HydroScheme"].attrs["Scheme"] +kernel = file["/HydroScheme"].attrs["Kernel function"] +neighbours = file["/HydroScheme"].attrs["Kernel target N_ngb"][0] +eta = file["/HydroScheme"].attrs["Kernel eta"][0] +git = file["Code"].attrs["Git Revision"] + +# Get the analytic solution, which is just the solution of the corresponding +# vacuum Riemann problem evaluated at the correct time + +# left state sound speed (and rarefaction wave speed) +aL = np.sqrt(gamma * PL / rhoL) + +# vacuum front speed +SL = vL + 2. / (gamma - 1.) * aL + +# we evaluate the solution centred on 0., and shift to the correct position +# afterwards +xa = np.arange(-0.25, 0.25, 0.001) +rhoa = np.zeros(len(xa)) +va = np.zeros(len(xa)) +Pa = np.zeros(len(xa)) + +for i in range(len(xa)): + dxdt = xa[i] / time + if dxdt > vL - aL: + if dxdt < SL: + # rarefaction regime + # factor that appears in both the density and pressure expression + fac = 2. / (gamma + 1.) + \ + (gamma - 1.) / (gamma + 1.) * (vL - dxdt) / aL + rhoa[i] = rhoL * fac**(2. / (gamma - 1.)) + va[i] = 2. / (gamma + 1.) * (aL + 0.5 * (gamma - 1.) * vL + dxdt) + Pa[i] = PL * fac**(2. * gamma / (gamma - 1.)) + else: + # vacuum regime + rhoa[i] = 0. + va[i] = 0. + Pa[i] = 0. + else: + # left state regime + rhoa[i] = rhoL + va[i] = vL + Pa[i] = PL + +ua = Pa / (gamma - 1.) / rhoa +Sa = Pa / rhoa**gamma + +# Bin the data values +# We let scipy choose the bins and then reuse them for all other quantities +rho_bin, x_bin_edge, _ = \ + stats.binned_statistic(x, rho, statistic = "mean", bins = 50) +rho2_bin, _, _ = \ + stats.binned_statistic(x, rho**2, statistic = "mean", bins = x_bin_edge) +rho_sigma_bin = np.sqrt(rho2_bin - rho_bin**2) + +v_bin, _, _ = \ + stats.binned_statistic(x, v, statistic = "mean", bins = x_bin_edge) +v2_bin, _, _ = \ + stats.binned_statistic(x, v**2, statistic = "mean", bins = x_bin_edge) +v_sigma_bin = np.sqrt(v2_bin - v_bin**2) + +P_bin, _, _ = \ + stats.binned_statistic(x, P, statistic = "mean", bins = x_bin_edge) +P2_bin, _, _ = \ + stats.binned_statistic(x, P**2, statistic = "mean", bins = x_bin_edge) +P_sigma_bin = np.sqrt(P2_bin - P_bin**2) + +u_bin, _, _ = \ + stats.binned_statistic(x, u, statistic = "mean", bins = x_bin_edge) +u2_bin, _, _ = \ + stats.binned_statistic(x, u**2, statistic = "mean", bins = x_bin_edge) +u_sigma_bin = np.sqrt(u2_bin - u_bin**2) + +S_bin, _, _ = \ + stats.binned_statistic(x, S, statistic = "mean", bins = x_bin_edge) +S2_bin, _, _ = \ + stats.binned_statistic(x, S**2, statistic = "mean", bins = x_bin_edge) +S_sigma_bin = np.sqrt(S2_bin - S_bin**2) + +x_bin = 0.5 * (x_bin_edge[1:] + x_bin_edge[:-1]) + +# Plot the interesting quantities +fig, ax = pl.subplots(2, 3) + +# Velocity profile +ax[0][0].plot(x, v, "r.", markersize = 0.2) +ax[0][0].plot(xa + 0.75, va, "k--", alpha = 0.8, linewidth = 1.2) +ax[0][0].plot(xa + 0.25, -va[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][0].errorbar(x_bin, v_bin, yerr = v_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[0][0].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[0][0].set_ylabel("${\\rm{Velocity}}~v_x$", labelpad = 0) + +# Density profile +ax[0][1].plot(x, rho, "r.", markersize = 0.2) +ax[0][1].plot(xa + 0.75, rhoa, "k--", alpha = 0.8, linewidth = 1.2) +ax[0][1].plot(xa + 0.25, rhoa[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][1].errorbar(x_bin, rho_bin, yerr = rho_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[0][1].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[0][1].set_ylabel("${\\rm{Density}}~\\rho$", labelpad = 0) + +# Pressure profile +ax[0][2].plot(x, P, "r.", markersize = 0.2) +ax[0][2].plot(xa + 0.75, Pa, "k--", alpha = 0.8, linewidth = 1.2) +ax[0][2].plot(xa + 0.25, Pa[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][2].errorbar(x_bin, P_bin, yerr = P_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[0][2].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[0][2].set_ylabel("${\\rm{Pressure}}~P$", labelpad = 0) + +# Internal energy profile +ax[1][0].plot(x, u, "r.", markersize = 0.2) +ax[1][0].plot(xa + 0.75, ua, "k--", alpha = 0.8, linewidth = 1.2) +ax[1][0].plot(xa + 0.25, ua[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[1][0].errorbar(x_bin, u_bin, yerr = u_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[1][0].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[1][0].set_ylabel("${\\rm{Internal~Energy}}~u$", labelpad = 0) + +# Entropy profile +ax[1][1].plot(x, S, "r.", markersize = 0.2) +ax[1][1].plot(xa + 0.75, Sa, "k--", alpha = 0.8, linewidth = 1.2) +ax[1][1].plot(xa + 0.25, Sa[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[1][1].errorbar(x_bin, S_bin, yerr = S_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[1][1].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[1][1].set_ylabel("${\\rm{Entropy}}~S$", labelpad = 0) + +# Run information +ax[1][2].set_frame_on(False) +ax[1][2].text(-0.49, 0.9, + "Vacuum test with $\\gamma={0:.3f}$ in 1D at $t = {1:.2f}$".format( + gamma, time), fontsize = 10) +ax[1][2].text(-0.49, 0.8, + "Left:~~ $(P_L, \\rho_L, v_L) = ({0:.3f}, {1:.3f}, {2:.3f})$".format( + PL, rhoL, vL), fontsize = 10) +ax[1][2].text(-0.49, 0.7, + "Right: $(P_R, \\rho_R, v_R) = ({0:.3f}, {1:.3f}, {2:.3f})$".format( + PR, rhoR, vR), fontsize = 10) +ax[1][2].plot([-0.49, 0.1], [0.62, 0.62], "k-", lw = 1) +ax[1][2].text(-0.49, 0.5, "$\\textsc{{Swift}}$ {0}".format(git), fontsize = 10) +ax[1][2].text(-0.49, 0.4, scheme, fontsize = 10) +ax[1][2].text(-0.49, 0.3, kernel, fontsize = 10) +ax[1][2].text(-0.49, 0.2, + "${0:.2f}$ neighbours ($\\eta={1:.3f}$)".format(neighbours, eta), + fontsize = 10) +ax[1][2].set_xlim(-0.5, 0.5) +ax[1][2].set_ylim(0., 1.) +ax[1][2].set_xticks([]) +ax[1][2].set_yticks([]) + +pl.tight_layout() +pl.savefig("Vacuum.png", dpi = 200) diff --git a/examples/Vacuum_2D/run.sh b/examples/Vacuum_2D/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..5c0b2ca5e19e33e813b7ff478ed4494752c0a2a5 --- /dev/null +++ b/examples/Vacuum_2D/run.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +# Generate the initial conditions if they are not present. +if [ ! -e glassPlane_128.hdf5 ] +then + echo "Fetching initial glass file for the 2D vacuum expansion example..." + ./getGlass.sh +fi +if [ ! -e vacuum.hdf5 ] +then + echo "Generating initial conditions for the 2D vacuum expansion example..." + python makeIC.py +fi + +# Run SWIFT +../swift -s -t 4 vacuum.yml 2>&1 | tee output.log + +# Plot the result +python plotSolution.py 1 diff --git a/examples/Vacuum_2D/vacuum.yml b/examples/Vacuum_2D/vacuum.yml new file mode 100644 index 0000000000000000000000000000000000000000..5ef5ce3da68febb086a14ad1a2207711f680d9ff --- /dev/null +++ b/examples/Vacuum_2D/vacuum.yml @@ -0,0 +1,34 @@ +# Define the system of units to use internally. +InternalUnitSystem: + UnitMass_in_cgs: 1 # Grams + UnitLength_in_cgs: 1 # Centimeters + UnitVelocity_in_cgs: 1 # Centimeters per second + UnitCurrent_in_cgs: 1 # Amperes + UnitTemp_in_cgs: 1 # Kelvin + +# Parameters governing the time integration +TimeIntegration: + time_begin: 0. # The starting time of the simulation (in internal units). + time_end: 0.1 # The end time of the simulation (in internal units). + dt_min: 1e-10 # The minimal time-step size of the simulation (in internal units). + dt_max: 1e-2 # The maximal time-step size of the simulation (in internal units). + +# Parameters governing the snapshots +Snapshots: + basename: vacuum # Common part of the name of output files + time_first: 0. # Time of the first output (in internal units) + delta_time: 0.1 # Time difference between consecutive outputs (in internal units) + +# Parameters governing the conserved quantities statistics +Statistics: + delta_time: 1e-2 # Time between statistics output + +# Parameters for the hydrodynamics scheme +SPH: + resolution_eta: 1.2348 # Target smoothing length in units of the mean inter-particle separation (1.2348 == 48Ngbs with the cubic spline kernel). + CFL_condition: 0.1 # Courant-Friedrich-Levy condition for time integration. + +# Parameters related to the initial conditions +InitialConditions: + file_name: ./vacuum.hdf5 # The file to read + diff --git a/examples/Vacuum_3D/getGlass.sh b/examples/Vacuum_3D/getGlass.sh new file mode 100755 index 0000000000000000000000000000000000000000..d5c5f590ac37c9c9431d626a2ea61b0c12c1513c --- /dev/null +++ b/examples/Vacuum_3D/getGlass.sh @@ -0,0 +1,2 @@ +#!/bin/bash +wget http://virgodb.cosma.dur.ac.uk/swift-webstorage/ICs/glassCube_64.hdf5 diff --git a/examples/Vacuum_3D/makeIC.py b/examples/Vacuum_3D/makeIC.py new file mode 100644 index 0000000000000000000000000000000000000000..09c3cb4d6f5525d54fab59643ab4a7d0540a2a92 --- /dev/null +++ b/examples/Vacuum_3D/makeIC.py @@ -0,0 +1,97 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +############################################################################### + +import numpy as np +import h5py + +# Generates an overdensity within a vacuum to test the vacuum resolving +# capabilities of the code + +# Parameters +gamma = 5. / 3. # Gas adiabatic index + +fileName = "vacuum.hdf5" + +#--------------------------------------------------- +glass = h5py.File("glassCube_64.hdf5", "r") + +# Read particle positions and h from the glass +pos = glass["/PartType0/Coordinates"][:,:] +h = glass["/PartType0/SmoothingLength"][:] * 0.3 + +# Shrink the glass to half its size, move it to the centre of the box, and +# clone it in the y and z directions +pos = 0.5 * pos + np.array([0.25, 0., 0.]) +h *= 0.5 +pos = np.append(pos, pos + np.array([0., 0.5, 0.]), axis = 0) +pos = np.append(pos, pos + np.array([0., 0., 0.5]), axis = 0) +h = np.append(h, h) +h = np.append(h, h) + +numPart = len(h) +vol = 0.5 + +# Generate extra arrays +v = np.zeros((numPart, 3)) +ids = np.linspace(1, numPart, numPart) +m = np.zeros(numPart) +u = np.zeros(numPart) + +m[:] = 1. * vol / numPart +u[:] = 1. / (1. * (gamma - 1.)) + +#-------------------------------------------------- + +#File +file = h5py.File(fileName, 'w') + +# Header +grp = file.create_group("/Header") +grp.attrs["BoxSize"] = [1., 1., 1.] +grp.attrs["NumPart_Total"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["NumPart_Total_HighWord"] = [0, 0, 0, 0, 0, 0] +grp.attrs["NumPart_ThisFile"] = [numPart, 0, 0, 0, 0, 0] +grp.attrs["Time"] = 0.0 +grp.attrs["NumFilesPerSnapshot"] = 1 +grp.attrs["MassTable"] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] +grp.attrs["Flag_Entropy_ICs"] = 0 +grp.attrs["Dimension"] = 3 + +#Runtime parameters +grp = file.create_group("/RuntimePars") +grp.attrs["PeriodicBoundariesOn"] = 1 + +#Units +grp = file.create_group("/Units") +grp.attrs["Unit length in cgs (U_L)"] = 1. +grp.attrs["Unit mass in cgs (U_M)"] = 1. +grp.attrs["Unit time in cgs (U_t)"] = 1. +grp.attrs["Unit current in cgs (U_I)"] = 1. +grp.attrs["Unit temperature in cgs (U_T)"] = 1. + +#Particle group +grp = file.create_group("/PartType0") +grp.create_dataset('Coordinates', data=pos, dtype='d') +grp.create_dataset('Velocities', data=v, dtype='f') +grp.create_dataset('Masses', data=m, dtype='f') +grp.create_dataset('SmoothingLength', data=h, dtype='f') +grp.create_dataset('InternalEnergy', data=u, dtype='f') +grp.create_dataset('ParticleIDs', data=ids, dtype='L') + +file.close() diff --git a/examples/Vacuum_3D/plotSolution.py b/examples/Vacuum_3D/plotSolution.py new file mode 100644 index 0000000000000000000000000000000000000000..4d197234237df10b8cdbf197048a65991da023cf --- /dev/null +++ b/examples/Vacuum_3D/plotSolution.py @@ -0,0 +1,225 @@ +############################################################################### +# This file is part of SWIFT. +# Copyright (c) 2018 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) +# +# This program 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. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +############################################################################## + +import numpy as np +import matplotlib +matplotlib.use("Agg") +import pylab as pl +import h5py +import sys +import scipy.stats as stats + +# Parameters +gamma = 5. / 3. # Polytropic index +rhoL = 1. # Initial density in the non vacuum state +vL = 0. # Initial velocity in the non vacuum state +PL = 1. # Initial pressure in the non vacuum state +rhoR = 0. # Initial vacuum density +vR = 0. # Initial vacuum velocity +PR = 0. # Initial vacuum pressure + +# Plot parameters +params = {'axes.labelsize': 10, +'axes.titlesize': 10, +'font.size': 12, +'legend.fontsize': 12, +'xtick.labelsize': 10, +'ytick.labelsize': 10, +'text.usetex': True, + 'figure.figsize' : (9.90,6.45), +'figure.subplot.left' : 0.045, +'figure.subplot.right' : 0.99, +'figure.subplot.bottom' : 0.05, +'figure.subplot.top' : 0.99, +'figure.subplot.wspace' : 0.15, +'figure.subplot.hspace' : 0.12, +'lines.markersize' : 6, +'lines.linewidth' : 3., +'text.latex.unicode': True +} +pl.rcParams.update(params) +pl.rc('font',**{'family':'sans-serif','sans-serif':['Times']}) + +# Read the snapshot index from the command line argument +snap = int(sys.argv[1]) + +# Open the file and read the relevant data +file = h5py.File("vacuum_{0:04d}.hdf5".format(snap), "r") +x = file["/PartType0/Coordinates"][:,0] +rho = file["/PartType0/Density"][:] +v = file["/PartType0/Velocities"][:,0] +u = file["/PartType0/InternalEnergy"][:] +S = file["/PartType0/Entropy"][:] +P = file["/PartType0/Pressure"][:] +time = file["/Header"].attrs["Time"][0] + +scheme = file["/HydroScheme"].attrs["Scheme"] +kernel = file["/HydroScheme"].attrs["Kernel function"] +neighbours = file["/HydroScheme"].attrs["Kernel target N_ngb"][0] +eta = file["/HydroScheme"].attrs["Kernel eta"][0] +git = file["Code"].attrs["Git Revision"] + +# Get the analytic solution, which is just the solution of the corresponding +# vacuum Riemann problem evaluated at the correct time + +# left state sound speed (and rarefaction wave speed) +aL = np.sqrt(gamma * PL / rhoL) + +# vacuum front speed +SL = vL + 2. / (gamma - 1.) * aL + +# we evaluate the solution centred on 0., and shift to the correct position +# afterwards +xa = np.arange(-0.25, 0.25, 0.001) +rhoa = np.zeros(len(xa)) +va = np.zeros(len(xa)) +Pa = np.zeros(len(xa)) + +for i in range(len(xa)): + dxdt = xa[i] / time + if dxdt > vL - aL: + if dxdt < SL: + # rarefaction regime + # factor that appears in both the density and pressure expression + fac = 2. / (gamma + 1.) + \ + (gamma - 1.) / (gamma + 1.) * (vL - dxdt) / aL + rhoa[i] = rhoL * fac**(2. / (gamma - 1.)) + va[i] = 2. / (gamma + 1.) * (aL + 0.5 * (gamma - 1.) * vL + dxdt) + Pa[i] = PL * fac**(2. * gamma / (gamma - 1.)) + else: + # vacuum regime + rhoa[i] = 0. + va[i] = 0. + Pa[i] = 0. + else: + # left state regime + rhoa[i] = rhoL + va[i] = vL + Pa[i] = PL + +ua = Pa / (gamma - 1.) / rhoa +Sa = Pa / rhoa**gamma + +# Bin the data values +# We let scipy choose the bins and then reuse them for all other quantities +rho_bin, x_bin_edge, _ = \ + stats.binned_statistic(x, rho, statistic = "mean", bins = 50) +rho2_bin, _, _ = \ + stats.binned_statistic(x, rho**2, statistic = "mean", bins = x_bin_edge) +rho_sigma_bin = np.sqrt(rho2_bin - rho_bin**2) + +v_bin, _, _ = \ + stats.binned_statistic(x, v, statistic = "mean", bins = x_bin_edge) +v2_bin, _, _ = \ + stats.binned_statistic(x, v**2, statistic = "mean", bins = x_bin_edge) +v_sigma_bin = np.sqrt(v2_bin - v_bin**2) + +P_bin, _, _ = \ + stats.binned_statistic(x, P, statistic = "mean", bins = x_bin_edge) +P2_bin, _, _ = \ + stats.binned_statistic(x, P**2, statistic = "mean", bins = x_bin_edge) +P_sigma_bin = np.sqrt(P2_bin - P_bin**2) + +u_bin, _, _ = \ + stats.binned_statistic(x, u, statistic = "mean", bins = x_bin_edge) +u2_bin, _, _ = \ + stats.binned_statistic(x, u**2, statistic = "mean", bins = x_bin_edge) +u_sigma_bin = np.sqrt(u2_bin - u_bin**2) + +S_bin, _, _ = \ + stats.binned_statistic(x, S, statistic = "mean", bins = x_bin_edge) +S2_bin, _, _ = \ + stats.binned_statistic(x, S**2, statistic = "mean", bins = x_bin_edge) +S_sigma_bin = np.sqrt(S2_bin - S_bin**2) + +x_bin = 0.5 * (x_bin_edge[1:] + x_bin_edge[:-1]) + +# Plot the interesting quantities +fig, ax = pl.subplots(2, 3) + +# Velocity profile +ax[0][0].plot(x, v, "r.", markersize = 0.2) +ax[0][0].plot(xa + 0.75, va, "k--", alpha = 0.8, linewidth = 1.2) +ax[0][0].plot(xa + 0.25, -va[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][0].errorbar(x_bin, v_bin, yerr = v_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[0][0].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[0][0].set_ylabel("${\\rm{Velocity}}~v_x$", labelpad = 0) + +# Density profile +ax[0][1].plot(x, rho, "r.", markersize = 0.2) +ax[0][1].plot(xa + 0.75, rhoa, "k--", alpha = 0.8, linewidth = 1.2) +ax[0][1].plot(xa + 0.25, rhoa[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][1].errorbar(x_bin, rho_bin, yerr = rho_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[0][1].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[0][1].set_ylabel("${\\rm{Density}}~\\rho$", labelpad = 0) + +# Pressure profile +ax[0][2].plot(x, P, "r.", markersize = 0.2) +ax[0][2].plot(xa + 0.75, Pa, "k--", alpha = 0.8, linewidth = 1.2) +ax[0][2].plot(xa + 0.25, Pa[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[0][2].errorbar(x_bin, P_bin, yerr = P_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[0][2].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[0][2].set_ylabel("${\\rm{Pressure}}~P$", labelpad = 0) + +# Internal energy profile +ax[1][0].plot(x, u, "r.", markersize = 0.2) +ax[1][0].plot(xa + 0.75, ua, "k--", alpha = 0.8, linewidth = 1.2) +ax[1][0].plot(xa + 0.25, ua[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[1][0].errorbar(x_bin, u_bin, yerr = u_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[1][0].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[1][0].set_ylabel("${\\rm{Internal~Energy}}~u$", labelpad = 0) + +# Entropy profile +ax[1][1].plot(x, S, "r.", markersize = 0.2) +ax[1][1].plot(xa + 0.75, Sa, "k--", alpha = 0.8, linewidth = 1.2) +ax[1][1].plot(xa + 0.25, Sa[::-1], "k--", alpha = 0.8, linewidth = 1.2) +ax[1][1].errorbar(x_bin, S_bin, yerr = S_sigma_bin, fmt = ".", + markersize = 8., color = "b", linewidth = 1.2) +ax[1][1].set_xlabel("${\\rm{Position}}~x$", labelpad = 0) +ax[1][1].set_ylabel("${\\rm{Entropy}}~S$", labelpad = 0) + +# Run information +ax[1][2].set_frame_on(False) +ax[1][2].text(-0.49, 0.9, + "Vacuum test with $\\gamma={0:.3f}$ in 1D at $t = {1:.2f}$".format( + gamma, time), fontsize = 10) +ax[1][2].text(-0.49, 0.8, + "Left:~~ $(P_L, \\rho_L, v_L) = ({0:.3f}, {1:.3f}, {2:.3f})$".format( + PL, rhoL, vL), fontsize = 10) +ax[1][2].text(-0.49, 0.7, + "Right: $(P_R, \\rho_R, v_R) = ({0:.3f}, {1:.3f}, {2:.3f})$".format( + PR, rhoR, vR), fontsize = 10) +ax[1][2].plot([-0.49, 0.1], [0.62, 0.62], "k-", lw = 1) +ax[1][2].text(-0.49, 0.5, "$\\textsc{{Swift}}$ {0}".format(git), fontsize = 10) +ax[1][2].text(-0.49, 0.4, scheme, fontsize = 10) +ax[1][2].text(-0.49, 0.3, kernel, fontsize = 10) +ax[1][2].text(-0.49, 0.2, + "${0:.2f}$ neighbours ($\\eta={1:.3f}$)".format(neighbours, eta), + fontsize = 10) +ax[1][2].set_xlim(-0.5, 0.5) +ax[1][2].set_ylim(0., 1.) +ax[1][2].set_xticks([]) +ax[1][2].set_yticks([]) + +pl.tight_layout() +pl.savefig("Vacuum.png", dpi = 200) diff --git a/examples/Vacuum_3D/run.sh b/examples/Vacuum_3D/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..5029626f67659bba1f22600bb5bd38859dd805ce --- /dev/null +++ b/examples/Vacuum_3D/run.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +# Generate the initial conditions if they are not present. +if [ ! -e glassCube_64.hdf5 ] +then + echo "Fetching initial glass file for the 3D vacuum expansion example..." + ./getGlass.sh +fi +if [ ! -e vacuum.hdf5 ] +then + echo "Generating initial conditions for the 3D vacuum expansion example..." + python makeIC.py +fi + +# Run SWIFT +../swift -s -t 16 vacuum.yml 2>&1 | tee output.log + +# Plot the result +python plotSolution.py 1 diff --git a/examples/Vacuum_3D/vacuum.yml b/examples/Vacuum_3D/vacuum.yml new file mode 100644 index 0000000000000000000000000000000000000000..5ef5ce3da68febb086a14ad1a2207711f680d9ff --- /dev/null +++ b/examples/Vacuum_3D/vacuum.yml @@ -0,0 +1,34 @@ +# Define the system of units to use internally. +InternalUnitSystem: + UnitMass_in_cgs: 1 # Grams + UnitLength_in_cgs: 1 # Centimeters + UnitVelocity_in_cgs: 1 # Centimeters per second + UnitCurrent_in_cgs: 1 # Amperes + UnitTemp_in_cgs: 1 # Kelvin + +# Parameters governing the time integration +TimeIntegration: + time_begin: 0. # The starting time of the simulation (in internal units). + time_end: 0.1 # The end time of the simulation (in internal units). + dt_min: 1e-10 # The minimal time-step size of the simulation (in internal units). + dt_max: 1e-2 # The maximal time-step size of the simulation (in internal units). + +# Parameters governing the snapshots +Snapshots: + basename: vacuum # Common part of the name of output files + time_first: 0. # Time of the first output (in internal units) + delta_time: 0.1 # Time difference between consecutive outputs (in internal units) + +# Parameters governing the conserved quantities statistics +Statistics: + delta_time: 1e-2 # Time between statistics output + +# Parameters for the hydrodynamics scheme +SPH: + resolution_eta: 1.2348 # Target smoothing length in units of the mean inter-particle separation (1.2348 == 48Ngbs with the cubic spline kernel). + CFL_condition: 0.1 # Courant-Friedrich-Levy condition for time integration. + +# Parameters related to the initial conditions +InitialConditions: + file_name: ./vacuum.hdf5 # The file to read + diff --git a/src/const.h b/src/const.h index dd7e1e267246c0f73e760191a071c6e24b96cfe8..85d64f5f3bf97b3f6ca6df8f230e0e0990687d34 100644 --- a/src/const.h +++ b/src/const.h @@ -68,7 +68,7 @@ #define GIZMO_UNPHYSICAL_RESCUE /* Show a warning message if an unphysical value was reset (only works if GIZMO_UNPHYSICAL_RESCUE is also selected). */ -//#define GIZMO_UNPHYSICAL_WARNING +#define GIZMO_UNPHYSICAL_WARNING /* Parameters that control how GIZMO handles pathological particle configurations. */ diff --git a/src/hydro/Gizmo/hydro.h b/src/hydro/Gizmo/hydro.h index a7ccde6a9bcd2ea87e16b89e07bcb4782e7044ad..b8c2c5e405e116acf5632b42b3b5fb60ae3e0d4e 100644 --- a/src/hydro/Gizmo/hydro.h +++ b/src/hydro/Gizmo/hydro.h @@ -645,18 +645,6 @@ __attribute__((always_inline)) INLINE static void hydro_kick_extra( /* Make sure the gpart knows the mass has changed. */ p->gpart->mass = p->conserved.mass; -#if !defined(EOS_ISOTHERMAL_GAS) - /* If the energy needs to be updated, we need to do it before the momentum - is updated, as the old value of the momentum enters the equations. */ - p->conserved.energy += dt * (p->conserved.momentum[0] * a_grav[0] + - p->conserved.momentum[1] * a_grav[1] + - p->conserved.momentum[2] * a_grav[2]); - - p->conserved.energy += dt * (a_grav[0] * p->gravity.mflux[0] + - a_grav[1] * p->gravity.mflux[1] + - a_grav[2] * p->gravity.mflux[2]); -#endif - /* Kick the momentum for half a time step */ /* Note that this also affects the particle movement, as the velocity for the particles is set after this. */