Skip to content

Commit

Permalink
Merge pull request #52 from FormingWorlds/logging
Browse files Browse the repository at this point in the history
Terminal logging
  • Loading branch information
nichollsh authored Aug 29, 2024
2 parents a5444ae + afc4175 commit aa6ab11
Show file tree
Hide file tree
Showing 25 changed files with 146 additions and 138 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ jobs:
- name: Test with pytest
run: |
export FWL_DATA="/home/runner/work/fwl_data"
export SOCRATES="/home/runner/work/JANUS/JANUS/SOCRATES"
export RAD_DIR="/home/runner/work/JANUS/JANUS/SOCRATES"
coverage run -m pytest
- name: Report coverage
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,5 @@ utils/*.ipynb*
build/
fwl_data*/
dist/
.pytest_cache

2 changes: 1 addition & 1 deletion docs/getting_started.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ If you install and compile [SOCRATES](https://github.com/nichollsh/SOCRATES) you
you can override the path using the `SOCRATES` environment variable, e.g.

```console
SOCRATES=/home/user/path/to/SOCRATES pytest
RAD_DIR=/home/user/path/to/SOCRATES pytest
```

### `FWL_DATA`
Expand Down
16 changes: 10 additions & 6 deletions examples/SocRadConv.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
import numpy as np
from importlib.resources import files

from janus.utils.logs import setup_logger
log = setup_logger()

from janus.modules import RadConvEqm, plot_fluxes, plot_emission
from janus.utils import atmos, CleanOutputDir, DownloadSpectralFiles, DownloadStellarSpectra, plot_adiabats, ReadBandEdges, StellarSpectrum
import mors
Expand All @@ -33,7 +36,7 @@
####################################
if __name__ == "__main__":

print("Start JANUS")
log.info("Start JANUS")

# Set up dirs
if os.environ.get('RAD_DIR') == None:
Expand Down Expand Up @@ -83,7 +86,7 @@
StellarSpectrum.PrepareStellarSpectrum(spec.wl, spec.fl, socstar)

# Move/prepare spectral file
print("Inserting stellar spectrum")
log.info("Inserting stellar spectrum")
StellarSpectrum.InsertStellarSpectrum(
str(FWL_DATA_DIR / 'spectral_files'/'Oak'/'318'/'Oak.sf'),
socstar,
Expand All @@ -99,10 +102,10 @@
if cfg['star']['stellar_heating'] == False:
atm.instellation = 0.
else:
mors.DownloadEvolutionTracks("/Baraffe")
mors.DownloadEvolutionTracks("Baraffe")
baraffe = mors.BaraffeTrack(star_mass)
atm.instellation = baraffe.BaraffeSolarConstant(time['star'], mean_distance)
print("Instellation:", round(atm.instellation), "W/m^2")
atm.instellation = baraffe.BaraffeSolarConstant(time['star'], mean_distance)
log.info("Instellation: %.2e W/m^2" % atm.instellation)

# Set up atmosphere with general adiabat
atm_dry, atm = RadConvEqm(dirs,
Expand Down Expand Up @@ -132,4 +135,5 @@
CleanOutputDir(dirs['output'])

end = t.time()
print("Runtime:", round(end - start,2), "s")
log.info("Runtime: %.2f s" % float(end-start))

22 changes: 13 additions & 9 deletions examples/demo_instellation.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
import os, shutil, toml
import numpy as np

from janus.utils.logs import setup_logger
log = setup_logger()

from janus.modules import MCPA_CBL
from janus.utils import atmos, CleanOutputDir, DownloadSpectralFiles, DownloadStellarSpectra, ReadBandEdges, StellarSpectrum

Expand All @@ -20,7 +23,7 @@

if __name__=='__main__':

print("Start")
log.info("Start")

# Set up dirs
if os.environ.get('RAD_DIR') == None:
Expand All @@ -37,7 +40,7 @@
os.mkdir(dirs["output"])

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

# Read spectrum
Expand All @@ -50,7 +53,7 @@


# Setup spectral file
print("Inserting stellar spectrum")
log.info("Inserting stellar spectrum")
StellarSpectrum.InsertStellarSpectrum(
str(FWL_DATA_DIR / 'spectral_files'/'Oak'/'318'/'Oak.sf'),
socstar,
Expand All @@ -66,7 +69,7 @@
# Star luminosity
time = { "planet": cfg['planet']['time'], "star": cfg['star']['time']}
star_mass = cfg['star']['star_mass']
mors.DownloadEvolutionTracks("/Baraffe")
mors.DownloadEvolutionTracks("Baraffe")
baraffe = mors.BaraffeTrack(star_mass)

# Define volatiles by mole fractions
Expand Down Expand Up @@ -94,7 +97,7 @@
ts_arr = [] # surface temperature
tr_arr = [] # tropopause temperature
for i in range(7):
print("Orbital separation = %.2f AU" % r_arr[i])
log.info("Orbital separation = %.2f AU" % r_arr[i])

atm.instellation = baraffe.BaraffeSolarConstant(time['star'], r_arr[i])
atmos.setTropopauseTemperature(atm)
Expand All @@ -121,14 +124,14 @@
# Save netcdf
atm.write_ncdf(dirs["output"]+"/profile%.2fAU.nc"%r_arr[i])

print(" ")
log.info(" ")

save_arr = [r_arr, asf_arr, OLR_arr, net_arr, ts_arr, tr_arr]
np.savetxt(dirs["output"]+"/data_%dK.csv"%T_magma,
np.array(save_arr).T, fmt="%.5e", delimiter=",",
header="r [AU], S_0 [W m-2], OLR [W m-2], net [W m-2], ts [K], tr[K] ")

print("Making plots")
log.info("Making plots")

plt.ioff()
fig,(ax1, ax2) = plt.subplots(2,1, figsize=(6,6.4))
Expand Down Expand Up @@ -188,4 +191,5 @@
CleanOutputDir(dirs['output'])

# Done
print("Done!")
log.info("Done!")

28 changes: 16 additions & 12 deletions examples/demo_runaway_greenhouse.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
from matplotlib.ticker import MultipleLocator
from importlib.resources import files

from janus.utils.logs import setup_logger
log = setup_logger()

from janus.modules import RadConvEqm
from janus.utils import atmos, CleanOutputDir, DownloadSpectralFiles, DownloadStellarSpectra, ReadBandEdges, StellarSpectrum
import mors
Expand All @@ -18,8 +21,8 @@

if __name__=='__main__':

print("Start")
print(" ")
log.info("Start")
log.info(" ")

# Set up dirs
if os.environ.get('RAD_DIR') == None:
Expand All @@ -36,7 +39,7 @@
os.mkdir(dirs["output"])

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

# Read spectrum
Expand All @@ -49,13 +52,13 @@


# Setup spectral file
print("Inserting stellar spectrum")
log.info("Inserting stellar spectrum")
StellarSpectrum.InsertStellarSpectrum(
str(FWL_DATA_DIR / 'spectral_files'/'Oak'/'318'/'Oak.sf'),
socstar,
dirs["output"]
)
print(" ")
log.info(" ")
band_edges = ReadBandEdges(dirs["output"]+"star.sf")

# Open config file
Expand All @@ -77,24 +80,24 @@
atm = atmos.from_file(cfg_file, band_edges, vol_mixing=vol_mixing, vol_partial={})

# Compute stellar heating
mors.DownloadEvolutionTracks("/Baraffe")
mors.DownloadEvolutionTracks("Baraffe")
baraffe = mors.BaraffeTrack(star_mass)
atm.instellation = baraffe.BaraffeSolarConstant(time['star'], mean_distance)

#Run Janus

# Run JANUS in a loop to generate runaway curve
print("Running JANUS...")
log.info("Running JANUS...")
Ts_arr = np.linspace(200, 2800, 20)
OLR_arr = []
for i in range(20):
print("T_surf = %d K" % Ts_arr[i])
log.info("T_surf = %d K" % Ts_arr[i])
atmos.setSurfaceTemperature(atm, Ts_arr[i])

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

OLR_arr.append(atm_moist.LW_flux_up[0])
print(" ")
log.info(" ")

OLR_arr = np.array(OLR_arr)
Ts_arr = np.array(Ts_arr)
Expand All @@ -110,7 +113,7 @@
dtype=float, skiprows=2, delimiter=',').T

# Setup plot
print("Making plot")
log.info("Making plot")
fig,ax = plt.subplots(1,1, figsize=(7,4))

# Plot data
Expand All @@ -134,11 +137,12 @@

fig.savefig(dirs["output"]+"runaway_demo.pdf", bbox_inches='tight')
fig.savefig(dirs["output"]+"runaway_demo.png", bbox_inches='tight', dpi=190)
print(" ")
log.info(" ")

# Tidy
CleanOutputDir(os.getcwd())
CleanOutputDir(dirs['output'])

# Done
print("Done!")
log.info("Done!")

1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ dependencies = [
'tomlkit',
'f90nml',
'fwl-mors',
'datetime'
]

[project.urls]
Expand Down
7 changes: 5 additions & 2 deletions src/janus/modules/compute_moist_adiabat.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
from janus.modules.water_cloud import simple_cloud
from janus.modules.relative_humidity import compute_Rh

import logging
log = logging.getLogger("fwl."+__name__)

import janus.utils.GeneralAdiabat as ga # Moist adiabat with multiple condensibles
import janus.utils.socrates as socrates

Expand Down Expand Up @@ -50,7 +53,7 @@ def compute_moist_adiabat(atm, dirs, standalone, trppD, rscatter=False):
atm_moist = socrates.radCompSoc(atm_moist, dirs, recalc=False, rscatter=rscatter)

if standalone == True:
print("w/o stratosphere (net, OLR): " + str(round(atm_moist.net_flux[0], 3)) +" , "+str(round(atm_moist.LW_flux_up[0], 3)) + " W/m^2")
log.info("w/o stratosphere (net, OLR): %.3f, %.3f W/m^2" % ( atm_moist.net_flux[0] , atm_moist.LW_flux_up[0]))

# Calculate tropopause
if (trppD == True) or (atm_moist.trppT > atm_moist.minT):
Expand All @@ -67,6 +70,6 @@ def compute_moist_adiabat(atm, dirs, standalone, trppD, rscatter=False):
atm_moist = socrates.radCompSoc(atm_moist, dirs, recalc=True, rscatter=rscatter)

if standalone == True:
print("w/ stratosphere (net, OLR): " + str(round(atm_moist.net_flux[0], 3)) + " , " + str(round(atm_moist.LW_flux_up[0], 3)) + " W/m^2")
log.info("w/ stratosphere (net, OLR): %.3f, %.3f W/m^2" % (atm_moist.net_flux[0] , atm_moist.LW_flux_up[0] ))

return atm_moist
14 changes: 6 additions & 8 deletions src/janus/modules/find_tropopause.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@

import numpy as np

import logging
log = logging.getLogger("fwl."+__name__)


def find_tropopause(atm_moist, dynamic: bool, verbose=True):
"""Computes tropopause location via two methods: dynamically based on heating rates, or by a set temperature value.
Expand All @@ -26,8 +30,7 @@ def find_tropopause(atm_moist, dynamic: bool, verbose=True):
# Heating criterion
if dynamic:

if verbose:
print("TROPOPAUSE SET BY HEATING")
log.debug("TROPOPAUSE SET BY HEATING")

# Find tropopause index
trpp_idx = 0
Expand All @@ -44,7 +47,6 @@ def find_tropopause(atm_moist, dynamic: bool, verbose=True):
if np.size(signchange_indices) > 0 and np.max(atm_moist.net_heating) > DeltaT_max_sign:

# First guess: maximum heating index
# print(np.argmax(atm_moist.net_heating))
max_heat_idx = np.argmax(atm_moist.net_heating)

# Lower height while heating still significant
Expand Down Expand Up @@ -84,18 +86,14 @@ def find_tropopause(atm_moist, dynamic: bool, verbose=True):
# If significant tropopause found or isothermal atmosphere from stellar heating
if trpp_idx != 0:

# # Print tropopause index for debugging
# print("Tropopause @ (index, P/Pa, T/K):", trpp_idx, round(atm_moist.pl[trpp_idx],3), round(atm_moist.tmpl[trpp_idx],3))

atm_moist.trppidx = trpp_idx # index
atm_moist.trppP = atm_moist.pl[trpp_idx] # pressure
atm_moist.trppT = atm_moist.tmpl[trpp_idx] # temperature

# Temperature criterion
else:

if verbose:
print("TROPOPAUSE SET BY CONTANT VALUE OF", atm_moist.trppT, "K")
log.debug("TROPOPAUSE SET BY CONTANT VALUE OF %.2f K"%atm_moist.trppT)

# Tropopause is triggered
if np.any(atm_moist.tmpl <= atm_moist.trppT) or np.any(atm_moist.tmp <= atm_moist.trppT):
Expand Down
12 changes: 0 additions & 12 deletions src/janus/modules/relative_humidity.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,23 +41,11 @@ def update_for_constant_RH(atm, R_h):
"""

p_sat = [ga.p_sat('H2O', atm.tmp[i]) for i in range(len(atm.p))]
#print("update_for_constant_RH: p_sat = ", p_sat)

i_lcl, lcl = find_intersection(p_sat, atm.p_vol['H2O'], tolerance=1e0)
#print("update_for_constant_RH: atm.p[i_lcl:] = ", atm.p[i_lcl:])
#print("update_for_constant_RH: atm.p_vol['H2O'][i_lcl:] = ", atm.p_vol['H2O'][i_lcl:])
#print("update_for_constant_RH: R_h[i_lcl:] = ", R_h[i_lcl:])
#print("update_for_constant_RH: atm.ps = ", atm.ps)
#print("update_for_constant_RH: atm.x_gas['H2O'][i_lcl:] = ", atm.x_gas['H2O'][i_lcl:])

#atm.p_vol['H2O'][i_lcl:] = R_h[i_lcl:] * p_sat[i_lcl:] # Updating the partial pressure of H2O from the LCL down
atm.p_vol['H2O'] = R_h * p_sat
#print("update_for_constant_RH: updated atm.p_vol['H2O'][i_lcl:] = ", atm.p_vol['H2O'][i_lcl:])
atm.p = sum(atm.p_vol[molecule] for molecule in atm.vol_list.keys()) # Updating the total pressure
#print("update_for_constant_RH: updated atm.p[i_lcl:] = ", atm.p[i_lcl:])
atm.ps = float(sum(atm.p_vol[molecule][-1] for molecule in atm.vol_list.keys())) # Not forgetting the surface pressure
#print("update_for_constant_RH: updated atm.ps = ", atm.ps)
#atm.x_gas['H2O'][i_lcl:] = R_h[i_lcl:] * p_sat[i_lcl:] / atm.p[i_lcl:] # Updating the mixing ratio of H2O
#print("atm.p_vol['H2O'][-1], atm.x_gas['H2O'], p_sat[-1] = ", atm.p_vol['H2O'][-1], atm.x_gas['H2O'][-1], p_sat[-1])

return atm
Loading

0 comments on commit aa6ab11

Please sign in to comment.