Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
96 changes: 96 additions & 0 deletions demos/compare_lib.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import os, glob, argparse
from astropy.table import Table
import matplotlib.pyplot as pl

pl.style.use("via")
pl.rcParams["font.size"] = 14

MARKERS = {"MILES": "o", "C3K_LR": "s", "C3K_HR": "^"}
COLORS = {"MIST": "k", "PDVA": "firebrick", "PRSC": "dodgerblue", "BPSS": "orange"}


def get_parser():
parser = argparse.ArgumentParser(description="Run pyFSPS AFE tests")
parser.add_argument(
"--dir",
type=str,
default="./lib_tests/sps_home-aa77c3_pyfsps-42635d_pyfslib-aa77c3",
help="Output directory for test results",
)
parser.add_argument(
"--kind",
type=str,
default="constneb",
choices=["const", "constneb", "tau1"],
help="Kind of SFH to plot spectrum of.",
)
parser.add_argument(
"--filters",
type=str,
nargs=2,
default=["bessell_B", "bessell_V"],
help="Two filters to plot color evolution for.",
)

return parser


if __name__ == "__main__":
parser = get_parser()
args = parser.parse_args()

dirn = args.dir
f1, f2 = args.filters

tbls = glob.glob(f"{dirn}/color_evol_*.csv")
tags = [
os.path.basename(t).replace("color_evol_", "").replace(".csv", "") for t in tbls
]
# tags = [f"{t}_sfh1" for t in tags]
tags = sorted(tags)
print(tags)
kind = args.kind

fig, ax = pl.subplots(figsize=(8, 6))
sfig, sax = pl.subplots(figsize=(8, 6))
for tag in tags:
isoc, slib, afe = tag.split("+")
marker = MARKERS.get(slib.upper(), "o")
color = COLORS.get(isoc.upper(), "k")
color = "cyan" if afe == "afe1" else color
color = "magenta" if afe == "afe1_afe0.3" else color
try:
table = Table.read(f"{dirn}/color_evol_{tag}.csv", format="csv")
ax.plot(
table["log_age"],
table[f1] - table[f2],
f"-{marker}",
color=color,
mec=color,
alpha=0.5,
label=f"{tag}, [a/Fe]=0.0",
)
spec = Table.read(f"{dirn}/spectrum_{tag}_{kind}.csv", format="csv")
sax.plot(spec["wave"], spec["spec"], "-", alpha=0.5, label=f"{tag}")
except Exception as e:
print(f"Error plotting {tag}: {e}")
pass

ax.set_xlabel("SSP Age (log yr)")
ax.set_ylabel("Color (B-V)")
ax.set_ylim(-0.6, 1.8)
ax.set_xlim(4.8, 10.4)
ax.grid(True)
# split the legend into two columns
ax.legend(loc="upper left", frameon=True, framealpha=0.5, fontsize="small", ncol=2)

sax.set_title("Spectra for different tags: constant SFH")
sax.set_xlabel("Wavelength (AA)")
sax.set_ylabel("Flux")
sax.set_xlim(3000, 10000)
sax.set_yscale("log")
sax.set_ylim(5e-5, 5e-3)
sax.grid(True)
sax.legend(loc="upper right", frameon=True, framealpha=0.5, fontsize="small")
fig.savefig(f"{dirn}/color_evol.png", dpi=300)
sfig.savefig(f"{dirn}/spectrum_{kind}.png", dpi=300)
64 changes: 44 additions & 20 deletions demos/feature_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
value of some variables.
"""

import os
import os, time

import matplotlib.pyplot as pl
from matplotlib.backends.backend_pdf import PdfPages
Expand Down Expand Up @@ -38,20 +38,42 @@ def prettify(fig, ax, label=None):
return fig, ax


def get_githash(dir):
"""
Get the current git hash for a repo
"""
import subprocess

cmd = ["git", "rev-parse", "HEAD"]
hash = subprocess.check_output(cmd, cwd=dir).decode("utf-8").strip()
return hash


if __name__ == "__main__":
pl.rc("text", usetex=True)
pl.rc("font", family="serif")
pl.rc("axes", grid=False)
pl.rc("xtick", direction="in")
pl.rc("ytick", direction="in")
pl.rc("xtick", top=True)
pl.rc("ytick", right=True)

pl.rcParams["font.family"] = "serif"
pl.rcParams["font.serif"] = ["cmr10"]
pl.rcParams["mathtext.fontset"] = "cm"
pl.rcParams["axes.formatter.use_mathtext"] = True
pl.rcParams["axes.grid"] = True
pl.rcParams["grid.alpha"] = 0.5
pl.rcParams["xtick.direction"] = "in"
pl.rcParams["ytick.direction"] = "in"

pyfsps_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
fsps_hash = get_githash(os.environ["SPS_HOME"])
pyfsps_hash = get_githash(os.path.dirname(__file__))
pyfsps_lib_hash = get_githash(os.path.join(pyfsps_dir, "src", "fsps", "libfsps"))
print(f"FSPS git hash: {fsps_hash}")
print(f"pyFSPS git hash: {pyfsps_hash}")
print(f"pyFSPS lib git hash: {pyfsps_lib_hash}")
hashtag = f"sps_home-{fsps_hash[:6]}_pyfsps-{pyfsps_hash[:6]}_pyfslib-{pyfsps_lib_hash[:6]}"

sps = fsps.StellarPopulation(zcontinuous=1)
ilib, slib, dlib = sps.libraries
ilib, slib, dlib = [s.decode("utf-8") for s in sps.libraries]
print(ilib, slib)
os.makedirs("./figures", exist_ok=True)
pdf = PdfPages("./figures/features.pdf")
os.makedirs(f"./figures/{hashtag}", exist_ok=True)
pdf = PdfPages(f"./figures/{hashtag}/features_{ilib}-{slib}-{dlib}.pdf")

# Basic spectrum
sps.params["sfh"] = 4
Expand All @@ -61,55 +83,57 @@ def prettify(fig, ax, label=None):
sps.params["imf_type"] = 2 # kroupa
sps.params["imf3"] = 2.3
fig, ax, spec = makefig(sps)
fig, ax = prettify(fig, ax, label=r"$\tau=5$, Age$=13.7$,\\n$\log Z/Z_\odot=0.0$")
fig, ax = prettify(
fig, ax, label=r"$\tau=5$, Age$=13.7$," + "\n" + r"$\log Z/Z_\odot=0.0$"
)
pdf.savefig(fig)
pl.close(fig)

# change IMF
sps.params["imf3"] = 2.5
fig, ax, spec = makefig(sps, oldspec=spec)
fig, ax = prettify(fig, ax, label=r"IMF slope")
fig, ax = prettify(fig, ax, label=f"IMF slope")
pdf.savefig(fig)

# Attenuate
sps.params["add_dust_emission"] = False
sps.params["dust2"] = 0.2
fig, ax, spec = makefig(sps, oldspec=spec)
fig, ax = prettify(fig, ax, label=r"Dust Attenuation")
fig, ax = prettify(fig, ax, label=f"Dust Attenuation")
pdf.savefig(fig)
pl.close(fig)

# Dust emission
sps.params["add_dust_emission"] = True
fig, ax, spec = makefig(sps, oldspec=spec)
fig, ax = prettify(fig, ax, label=r"Dust Emission")
fig, ax = prettify(fig, ax, label=f"Dust Emission")
pdf.savefig(fig)
pl.close(fig)

# Dust temperature
sps.params["duste_umin"] = 10
fig, ax, spec = makefig(sps, oldspec=spec)
fig, ax = prettify(fig, ax, label=r"Dust SED\\n({})".format(dlib))
fig, ax = prettify(fig, ax, label=f"Dust SED\n({dlib})")
pdf.savefig(fig)
pl.close(fig)

# AGN emission
sps.params["fagn"] = 0.3
fig, ax, spec = makefig(sps, oldspec=spec)
fig, ax = prettify(fig, ax, label=r"AGN dust\\n(Nenkova)")
fig, ax = prettify(fig, ax, label=f"AGN dust\n(Nenkova)")
pdf.savefig(fig)
pl.close(fig)

# Nebular emission
sps.params["add_neb_emission"] = True
sps.params["gas_logu"] = -3.5
fig, ax, spec = makefig(sps, oldspec=spec)
fig, ax = prettify(fig, ax, label=r"Neb. emission\\n(Byler)")
fig, ax = prettify(fig, ax, label=f"Neb. emission\n(Byler)")
pdf.savefig(fig)
pl.close(fig)

# change logu
sps.params["gas_logu"] = -1.0
sps.params["gas_logu"] = -1.5
fig, ax, spec = makefig(sps, oldspec=spec)
fig, ax = prettify(fig, ax, label=r"Change U$_{neb}$")
pdf.savefig(fig)
Expand All @@ -127,7 +151,7 @@ def prettify(fig, ax, label=None):
sps.params["zred"] = 6.0
sps.params["add_igm_absorption"] = True
fig, ax, spec = makefig(sps, oldspec=spec)
fig, ax = prettify(fig, ax, label=r"IGM attenuation\\n(Madau, $z=6$)")
fig, ax = prettify(fig, ax, label=f"IGM attenuation\n" + r"(Madau, $z=6$)")
pdf.savefig(fig)
pl.close(fig)

Expand Down
63 changes: 63 additions & 0 deletions demos/test_and_compare_lib.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#!/bin/bash

# This script cycles through the different FSPS libraries and runs afe.py to run
# tests and generate the color evolution plots and data.


PYFSPS_DIR=`realpath ../`
TESTDIR=$PYFSPS_DIR/demos
SPECLIBS=( C3K_LR C3K_HR MILES )
ISOCS=( MIST PADOVA PARSEC )

# Do AFE_FLAG=1 for MIST + C3K_LR (the defaults)
cd $PYFSPS_DIR
FFLAGS="-DAFE_FLAG=1"
echo "Recompiling with flags: ${FFLAGS}"
python -m pip uninstall -y fsps
FFLAGS=${FFLAGS} python -m pip install . --no-binary fsps
cd $TESTDIR
python test_lib.py

# Now do the other combinations of isochrones and spectral libraries. We will
# always use AFE_FLAG=0 (the default), but we will switch the isochrone and
# spectral library.
for iso in "${ISOCS[@]}"; do
for lib in "${SPECLIBS[@]}"; do
echo "Running tests for ${lib} and ${iso}"
cd $PYFSPS_DIR

FFLAGS=""

# Switch the isochrone
if [[ ${iso} != "MIST" ]]; then
FFLAGS=${FFLAGS}" -DMIST=0"
FFLAGS=${FFLAGS}" -D${iso}=1"
fi

# Switch the spectral library
if [[ ${lib} != "C3K_LR" ]]; then
FFLAGS=${FFLAGS}" -DC3K_LR=0"
FFLAGS=${FFLAGS}" -D${lib}=1"
fi

echo $FFLAGS

# Recompile with flags
echo "Recompiling with flags: ${FFLAGS}"
python -m pip uninstall -y fsps
FFLAGS=${FFLAGS} python -m pip install . --no-binary fsps

# run the tests
cd $TESTDIR
python test_lib.py
done
done

# Now do BPASS, which has no spectral library attached
cd $PYFSPS_DIR
FFLAGS="-DMIST=0 -DC3K_LR=0 -DBPASS=1"
echo "Recompiling with flags: ${FFLAGS}"
python -m pip uninstall -y fsps
FFLAGS=${FFLAGS} python -m pip install . --no-binary fsps
cd $TESTDIR
python test_lib.py
Loading
Loading