From 33810d6190831fee00eb3fed53492c1db058972d Mon Sep 17 00:00:00 2001
From: loikki <loic.hausammann@protonmail.ch>
Date: Mon, 27 May 2019 15:08:14 +0200
Subject: [PATCH] Use ParameterFile in scripts

---
 pyswiftsim/__init__.py       | 12 ++++++++++--
 scripts/pyswift_cooling_rate | 28 +++++++++++++++-------------
 tests/test_cooling.yml       | 25 -------------------------
 3 files changed, 25 insertions(+), 40 deletions(-)
 delete mode 100644 tests/test_cooling.yml

diff --git a/pyswiftsim/__init__.py b/pyswiftsim/__init__.py
index f726238..4aac52c 100644
--- a/pyswiftsim/__init__.py
+++ b/pyswiftsim/__init__.py
@@ -144,11 +144,18 @@ class ParameterFile:
             # add space between sections
             print()
 
-    def __init__(self, overwrite=None):
+    def __init__(self, overwrite=None, existing=None):
+        if overwrite is not None and existing is not None:
+            raise Exception("Cannot overwrite default parameters and"
+                            " use existing parameter file")
         self.overwrite = overwrite
         self.d = self.default_parameters
+        self.existing = existing
 
     def __enter__(self):
+        if self.existing is not None:
+            return self.existing
+
         f = NamedTemporaryFile(delete=False)
         self.filename = f.name
 
@@ -158,4 +165,5 @@ class ParameterFile:
         return self.filename
 
     def __exit__(self, *args):
-        os.remove(self.filename)
+        if self.existing is None:
+            os.remove(self.filename)
diff --git a/scripts/pyswift_cooling_rate b/scripts/pyswift_cooling_rate
index 8b08db1..262629c 100644
--- a/scripts/pyswift_cooling_rate
+++ b/scripts/pyswift_cooling_rate
@@ -18,7 +18,7 @@
 # ########################################################################
 
 from pyswiftsim.libcooling import coolingRate
-from pyswiftsim import downloadCoolingTable
+import pyswiftsim
 
 from copy import deepcopy
 import numpy as np
@@ -254,23 +254,25 @@ if __name__ == "__main__":
     opt = parseArguments()
 
     if opt.table:
-        downloadCoolingTable()
+        pyswiftsim.downloadCoolingTable()
 
-    if not os.path.isfile(opt.params):
+    if opt.params is not None and not os.path.isfile(opt.params):
         raise Exception(
             "The parameter file '{}' does not exist".format(opt.params))
 
-    parser = getParser(opt.params)
-    us = parser["InternalUnitSystem"]
+    with pyswiftsim.ParameterFile(existing=opt.params) as filename:
 
-    d = generate_initial_condition(us, opt)
+        parser = getParser(filename)
+        us = parser["InternalUnitSystem"]
 
-    # du / dt
-    print("Computing cooling...")
+        d = generate_initial_condition(us, opt)
 
-    rate = coolingRate(opt.params,
-                       d["density"].astype(np.float32),
-                       d["energy"].astype(np.float32),
-                       with_cosmo, d["time_step"])
+        # du / dt
+        print("Computing cooling...")
 
-    plot_solution(rate, d, us, opt)
+        rate = coolingRate(filename,
+                           d["density"].astype(np.float32),
+                           d["energy"].astype(np.float32),
+                           with_cosmo, d["time_step"])
+
+        plot_solution(rate, d, us, opt)
diff --git a/tests/test_cooling.yml b/tests/test_cooling.yml
deleted file mode 100644
index a30e9ed..0000000
--- a/tests/test_cooling.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-# Define the system of units to use internally. 
-InternalUnitSystem:
-  UnitMass_in_cgs:     1.989e43   # Grams
-  UnitLength_in_cgs:   3.085e21   # Centimeters
-  UnitVelocity_in_cgs: 1e5   # Centimeters per second
-  UnitCurrent_in_cgs:  1   # Amperes
-  UnitTemp_in_cgs:     1   # Kelvin
-
-# Cooling with Grackle 3.0
-GrackleCooling:
-  CloudyTable: CloudyData_UVB=HM2012.h5 # Name of the Cloudy Table (available on the grackle bitbucket repository)
-  WithUVbackground: 1                   # Enable or not the UV background
-  Redshift: 0                           # Redshift to use (-1 means time based redshift)
-  WithMetalCooling: 1                   # Enable or not the metal cooling
-  ProvideVolumetricHeatingRates: 0      # (optional) User provide volumetric heating rates
-  ProvideSpecificHeatingRates: 0        # (optional) User provide specific heating rates
-  SelfShieldingMethod: 0                # (optional) Grackle (<= 3) or Gear self shielding method
-  OutputMode: 0                         # (optional) Write in output corresponding primordial chemistry mode
-  MaxSteps: 10000                       # (optional) Max number of step when computing the initial composition
-  ConvergenceLimit: 1e-2                # (optional) Convergence threshold (relative) for initial composition
-
-# 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.
-- 
GitLab