Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor testing code #41

Merged
merged 17 commits into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ src/janus/data/spectral_files/sp_b318_HITRAN_a16_2203

output/
utils/*.ipynb*
.coverage
build/
fwl_data*/
dist/
1 change: 1 addition & 0 deletions src/janus/data/tests/config_instellation.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pl_mass = 5.972e24
[star]
time = 100e+6 # yr
star_mass = 1.0 # M_sun, mass of star
mean_distance = 0.3 # au, orbital distance

[atmos]
T_surf = 2800.0
Expand Down
8 changes: 0 additions & 8 deletions src/janus/data/tests/data_instellation.csv

This file was deleted.

21 changes: 0 additions & 21 deletions src/janus/data/tests/data_runaway_greenhouse.csv

This file was deleted.

2 changes: 1 addition & 1 deletion src/janus/utils/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def DownloadSpectralFiles(fname: str="",nband: int=256):
elif fname in ("Kynesgrove","Legacy","Mallard","Oak","Reach","stellar_spectra"):
folder_list = [fname]
else:
print(f"Unrecognised folder name: {fname}")
raise ValueError(f"Unrecognised folder name: {fname}")

folders = [folder for folder in folder_list if not (data_dir / folder).exists()]

Expand Down
10 changes: 10 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import os

if not os.environ.get('RAD_DIR'):
raise Exception(
'Socrates environment variables not set! Have you installed Socrates and sourced set_rad_env?'
)
if not os.environ.get('FWL_DATA'):
raise Exception(
'The FWL_DATA environment variable where spectral and evolution tracks data will be downloaded needs to be set up!'
)
73 changes: 73 additions & 0 deletions tests/helpers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import os
from contextlib import contextmanager
from importlib.resources import files
from pathlib import Path

import mors
import toml
from janus.utils import (
DownloadSpectralFiles,
DownloadStellarSpectra,
ReadBandEdges,
StellarSpectrum,
atmos,
)

DATA_DRC = files('janus') / 'data' / 'tests'
FWL_DATA = os.environ.get('FWL_DATA')


@contextmanager
def work_directory(path: Path | str):
"""Changes working directory and returns to previous on exit.

Parameters
----------
path : Path | str
Temporarily change to this directory.
"""
prev_cwd = Path.cwd().resolve()
try:
os.chdir(path)
yield
finally: # In any case, no matter what happens, go back eventually
os.chdir(prev_cwd)


def get_spectrum_data(drc):
DownloadSpectralFiles('Oak')
DownloadStellarSpectra()

spec = mors.Spectrum()
spec.LoadTSV(FWL_DATA + '/stellar_spectra/Named/sun.txt')
socstar = os.path.join(drc, 'socstar.txt')
StellarSpectrum.PrepareStellarSpectrum(spec.wl, spec.fl, socstar)

StellarSpectrum.InsertStellarSpectrum(
FWL_DATA + '/spectral_files/Oak/318/Oak.sf',
socstar,
drc,
)
band_edges = ReadBandEdges(drc + 'star.sf')

return band_edges


def get_atmosphere_config(*, band_edges, cfg_name: str, distance: float):
cfg_file = DATA_DRC / cfg_name

with open(cfg_file) as f:
cfg = toml.load(f)

star_time = cfg['star']['time']
star_mass = cfg['star']['star_mass']

vol_mixing = {'H2O': 1.0, 'CO2': 0.0, 'N2': 0.0}

atm = atmos.from_file(cfg_file, band_edges, vol_mixing=vol_mixing, vol_partial={})

mors.DownloadEvolutionTracks('/Baraffe')
baraffe = mors.BaraffeTrack(star_mass)
atm.instellation = baraffe.BaraffeSolarConstant(star_time, distance)

return atm, cfg
113 changes: 27 additions & 86 deletions tests/test_instellation.py
Original file line number Diff line number Diff line change
@@ -1,96 +1,37 @@
#!/usr/bin/env python3

from importlib.resources import files
import os, shutil, toml
import numpy as np

from numpy.testing import assert_allclose
from helpers import get_atmosphere_config, get_spectrum_data, work_directory
from janus.modules import MCPA_CBL
from janus.utils import atmos, CleanOutputDir, DownloadSpectralFiles, DownloadStellarSpectra, ReadBandEdges, StellarSpectrum
import mors

def test_instellation():

# Set up dirs
if os.environ.get('RAD_DIR') == None:
raise Exception("Socrates environment variables not set! Have you installed Socrates and sourced set_rad_env?")
if os.environ.get('FWL_DATA') == None:
raise Exception("The FWL_DATA environment variable where spectral and evolution tracks data will be downloaded needs to be set up!")
dirs = {
"janus": str(files("janus"))+"/",
"output": os.path.abspath(os.getcwd())+"/output/"
}
import pytest

# Tidy directory
if os.path.exists(dirs["output"]):
shutil.rmtree(dirs["output"])
os.mkdir(dirs["output"])

#Download required spectral files
DownloadSpectralFiles("Oak")
DownloadStellarSpectra()
TEST_DATA = (
(0.3, (2.34297e03, 1.94397e03, -4.67185e01, 3.00023e03, 4.19568e02)),
(1.4, (1.07585e02, 4.15768e02, 3.24365e02, 2.99838e03, 1.94222e02)),
)
stefsmeets marked this conversation as resolved.
Show resolved Hide resolved

# Read spectrum
spec = mors.Spectrum()
spec.LoadTSV(os.environ.get('FWL_DATA')+"/stellar_spectra/Named/sun.txt")

# Convert to SOCRATES format
socstar = os.path.join(dirs["output"], "socstar.txt")
StellarSpectrum.PrepareStellarSpectrum(spec.wl, spec.fl, socstar)
@pytest.mark.parametrize("inp,expected", TEST_DATA)
def test_instellation(tmpdir, inp, expected):
out_drc = str(tmpdir) + "/"

# Setup spectral file
print("Inserting stellar spectrum")
StellarSpectrum.InsertStellarSpectrum(
os.environ.get('FWL_DATA')+"/spectral_files/Oak/318/Oak.sf",
socstar,
dirs["output"]
band_edges = get_spectrum_data(out_drc)
atm, cfg = get_atmosphere_config(
band_edges=band_edges,
distance=inp,
cfg_name="config_instellation.toml",
)
band_edges = ReadBandEdges(dirs["output"]+"star.sf")

# Open config file
cfg_file = dirs["janus"]+"data/tests/config_instellation.toml"
with open(cfg_file, 'r') as f:
cfg = toml.load(f)

# Star luminosity
time = { "planet": cfg['planet']['time'], "star": cfg['star']['time']}
star_mass = cfg['star']['star_mass']
mors.DownloadEvolutionTracks("/Baraffe")
baraffe = mors.BaraffeTrack(star_mass)

# Define volatiles by mole fractions
vol_mixing = {
"H2O" : 1.0,
"CO2" : 0.0,
"N2" : 0.0
}

#Get reference data
ref = np.loadtxt(dirs["janus"]+"data/tests/data_instellation.csv",
dtype=float, skiprows=1, delimiter=',')

# Create atmosphere object
atm = atmos.from_file(cfg_file, band_edges, vol_mixing=vol_mixing, vol_partial={})

r_arr = np.linspace(0.3, 1.4, 7) # orbital distance range [AU]
for i in range(7):
print("Orbital separation = %.2f AU" % r_arr[i])

atm.instellation = baraffe.BaraffeSolarConstant(time['star'], r_arr[i])
atmos.setTropopauseTemperature(atm)

atm = MCPA_CBL(dirs, atm, False, rscatter = True, T_surf_max=9.0e99, T_surf_guess = atm.trppT+100)

out = [atm.SW_flux_down[0], atm.LW_flux_up[0], atm.net_flux[0], atm.ts, atm.trppT]

print_out = "%.5e,"%float(r_arr[i])
print_out += ",".join(["%.5e"%o for o in out])
print("Calculated:",print_out)
atm.setTropopauseTemperature()

# print_out = ",".join(["%.5e"%o for o in ref[i]])
# print("Target:",print_out)
with work_directory(tmpdir):
atm = MCPA_CBL(
{"output": out_drc},
atm,
False,
rscatter=True,
T_surf_max=9.0e99,
T_surf_guess=atm.trppT + 100,
)

np.testing.assert_allclose(out, ref[i][1:6], rtol=1e-5, atol=0)
ret = (atm.SW_flux_down[0], atm.LW_flux_up[0], atm.net_flux[0], atm.ts, atm.trppT)

# Tidy
CleanOutputDir(os.getcwd())
CleanOutputDir(dirs['output'])
assert_allclose(ret, expected, rtol=1e-5, atol=0)
107 changes: 26 additions & 81 deletions tests/test_runaway_greenhouse.py
Original file line number Diff line number Diff line change
@@ -1,92 +1,37 @@
#!/usr/bin/env python3

import os, shutil, toml
import numpy as np
from matplotlib.ticker import MultipleLocator
from importlib.resources import files

from helpers import get_atmosphere_config, get_spectrum_data, work_directory
from janus.modules import RadConvEqm
from janus.utils import atmos, CleanOutputDir, DownloadSpectralFiles, DownloadStellarSpectra, ReadBandEdges, StellarSpectrum
import mors

def test_runaway_greenhouse():

# Set up dirs
if os.environ.get('RAD_DIR') == None:
raise Exception("Socrates environment variables not set! Have you installed Socrates and sourced set_rad_env?")
if os.environ.get('FWL_DATA') == None:
raise Exception("The FWL_DATA environment variable where spectral and evolution tracks data will be downloaded needs to be set up!")
dirs = {
"janus": str(files("janus"))+"/",
"output": os.path.abspath(os.getcwd())+"/output/"
}

# Tidy directory
if os.path.exists(dirs["output"]):
shutil.rmtree(dirs["output"])
os.mkdir(dirs["output"])

#Download required spectral files
DownloadSpectralFiles("Oak")
DownloadStellarSpectra()

# Read spectrum
spec = mors.Spectrum()
spec.LoadTSV(os.environ.get('FWL_DATA')+"/stellar_spectra/Named/sun.txt")

# Convert to SOCRATES format
socstar = os.path.join(dirs["output"], "socstar.txt")
StellarSpectrum.PrepareStellarSpectrum(spec.wl, spec.fl, socstar)

# Setup spectral file
print("Inserting stellar spectrum")
StellarSpectrum.InsertStellarSpectrum(
os.environ.get('FWL_DATA')+"/spectral_files/Oak/318/Oak.sf",
socstar,
dirs["output"]
)
band_edges = ReadBandEdges(dirs["output"]+"star.sf")

# Open config file
cfg_file = dirs["janus"]+"data/tests/config_runaway.toml"
with open(cfg_file, 'r') as f:
cfg = toml.load(f)

# Planet
time = { "planet": cfg['planet']['time'], "star": cfg['star']['time']}
star_mass = cfg['star']['star_mass']
mean_distance = cfg['star']['mean_distance']
import pytest

vol_mixing = {
"H2O" : 1.0,
"CO2" : 0.0,
"N2" : 0.0
}

#Get reference values
OLR_ref = np.loadtxt(dirs["janus"]+"data/tests/data_runaway_greenhouse.csv",
dtype=float, skiprows=1, delimiter=',')
TEST_DATA = (
(200.00000000,9.07314e+01),
(1705.26315789,2.78884e+02),
(2800.00000000,6.58174e+03),
stefsmeets marked this conversation as resolved.
Show resolved Hide resolved
)

# Create atmosphere object
atm = atmos.from_file(cfg_file, band_edges, vol_mixing=vol_mixing, vol_partial={})

# Compute stellar heating from Baraffe evolution tracks
mors.DownloadEvolutionTracks("/Baraffe")
baraffe = mors.BaraffeTrack(star_mass)
atm.instellation = baraffe.BaraffeSolarConstant(time['star'], mean_distance)
@pytest.mark.parametrize("inp,expected", TEST_DATA)
def test_runaway_greenhouse(tmpdir, inp, expected):
out_drc = str(tmpdir) + '/'

#Run Janus
Ts_arr = np.linspace(200, 2800, 20)
for i in range(20):
band_edges = get_spectrum_data(out_drc)
atm, cfg = get_atmosphere_config(band_edges=band_edges, distance=0.3, cfg_name='config_runaway.toml')

atmos.setSurfaceTemperature(atm, Ts_arr[i])
time = {'planet': cfg['planet']['time'], 'star': cfg['star']['time']}

_, atm_moist = RadConvEqm(dirs, time, atm, standalone=True, cp_dry=False, trppD=False, rscatter=False)
atm.setSurfaceTemperature(inp)

out = atm_moist.LW_flux_up[0]
print("Output %.5e; Reference %.5e" % (out, OLR_ref[i][1]))
np.testing.assert_allclose(out, OLR_ref[i][1], rtol=1e-5, atol=0)
with work_directory(tmpdir):
_, atm_moist = RadConvEqm(
{'output': out_drc},
time,
atm,
standalone=True,
cp_dry=False,
trppD=False,
rscatter=False,
)

# Tidy
CleanOutputDir(os.getcwd())
CleanOutputDir(dirs['output'])
ret = atm_moist.LW_flux_up[0]
np.testing.assert_allclose(ret, expected, rtol=1e-5, atol=0)
Loading