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

Emissivity compiling and loading. #62

Merged
merged 74 commits into from
Oct 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
74 commits
Select commit Hold shift + click to select a range
4100544
Created CSP archistecture and basic sfh class
maxbriel Jun 2, 2020
f2d0f86
Added variables to constants
maxbriel Jun 5, 2020
6828272
implements utility functions & new test files
maxbriel Jun 5, 2020
d3cc2a5
Implements event rate calculation over time
maxbriel Jun 5, 2020
29a8d1e
BPASS data_files for testing file_loading
maxbriel Jun 5, 2020
95c6cb0
Adds `at_time` function to the event rate class
maxbriel Jun 9, 2020
536b6b9
Adds docstrings and extra tests
maxbriel Jun 10, 2020
9e95635
Implements calculate spectrum at_time and over_time functions
maxbriel Jun 11, 2020
f22c615
Add normalisation function for the BPASS spectrum
maxbriel Jun 11, 2020
e1bf600
fixed hrd plot
HeloiseS Jun 16, 2020
070282b
adding csp folder
HeloiseS Jun 16, 2020
a881b36
fixed merge conflict
HeloiseS Jun 16, 2020
dfb88cb
minor changes
HeloiseS Jun 16, 2020
9d4d49d
Moved tests to CSP folder + fix in function name _type_check
maxbriel Jun 18, 2020
5c1fb9a
added a hokitype error
HeloiseS Jun 18, 2020
276c1de
bringing it latest max update
HeloiseS Jun 18, 2020
d2f93d9
Added some code review for Max and minor stylistic changes
HeloiseS Jun 18, 2020
71f3604
Added some code review for Max and minor stylistic changes
HeloiseS Jun 18, 2020
36bd68b
Updated the tests
maxbriel Jun 18, 2020
6475bbd
Merge remote-tracking branch 'origin/csp' into csp
maxbriel Jun 18, 2020
760144d
bla
HeloiseS Jun 18, 2020
551b8e7
Adjust tests and docstrings
maxbriel Jun 18, 2020
14d7f4b
Adjust eventrate functions to take lists of functions
maxbriel Jun 19, 2020
810f560
fix merge comflict
HeloiseS Jun 21, 2020
41f4f9a
Disabled spectra test
maxbriel Jun 21, 2020
cb1f7b8
Merge update from max 'csp' of https://github.com/HeloiseS/hoki into csp
HeloiseS Jun 21, 2020
ee720e2
Added parametric star formation histories to SFH and refactored some …
HeloiseS Jun 22, 2020
fa26ff5
fixing CI
HeloiseS Jun 22, 2020
02f820a
Auto stash before merge of "csp" and "official_hoki/csp"
maxbriel Jun 22, 2020
23893b5
Merge remote-tracking branch 'official_hoki/csp' into csp
maxbriel Jun 22, 2020
666b351
upload files for remote work
maxbriel Jun 23, 2020
4bc4c20
Improve testing and functions
maxbriel Jun 24, 2020
224af19
Add SpectraCompiler test
maxbriel Jun 26, 2020
9520ebd
Adds extensive tests for the CSP package
maxbriel Jun 26, 2020
9e0c487
Update SpectraCompiler
maxbriel Jun 30, 2020
81ba83f
Documentation update + SFH input
maxbriel Jun 30, 2020
cbd3a89
Removed CSP from utils due to cyclical import
maxbriel Jun 30, 2020
2b08f82
Updated setup.cfg to include csp_test_data subfolder
maxbriel Jul 1, 2020
1a81f7d
Removes leftover print statement + prints loading precompiled failed
maxbriel Jul 1, 2020
1dad9b4
Correct metallicity mid-points
maxbriel Jul 8, 2020
9a7429f
Added the parametric star formation histories as public functions
HeloiseS Jul 10, 2020
1d22aef
at_time new default sample rate + load functions moved to hoki.load
maxbriel Jul 16, 2020
67cc7c7
Fixed typo
maxbriel Jul 16, 2020
cd64e00
Merge remote-tracking branch 'origin/csp' into csp
maxbriel Jul 16, 2020
2a41a9a
Removes cyclical import
maxbriel Jul 16, 2020
7085eb4
Adjusted tests that use SpectraCompiler
maxbriel Jul 16, 2020
dca1a03
Getting tox to work
maxbriel Jul 16, 2020
ece0273
private optimised mass_per_time_bin calculation
maxbriel Jul 31, 2020
bccb99f
Refactored Event Rate calculation from array data
maxbriel Jul 31, 2020
bed60cf
Removed dependency and added more doc information
maxbriel Jul 31, 2020
285c508
BUG: pass on kwarg to spectra compiler.
findesgh Aug 25, 2020
a8d6d72
Merge branch 'csp' of https://github.com/HeloiseS/hoki into csp
findesgh Aug 25, 2020
94b8534
Merge pull request #58 from findesgh/csp
maxbriel Aug 26, 2020
31031b9
Fix SpectraCompiler
maxbriel Aug 27, 2020
6bc3f73
BUG: use np instead of pd in SpectraCompiler.
Aug 28, 2020
7a54cdf
BUG: fix index and make test pass.
Aug 28, 2020
1e9556e
BUG: fix another regression bug.
Aug 28, 2020
0edb23e
Merge branch 'csp' of https://github.com/HeloiseS/hoki into csp_fix2
Aug 28, 2020
4ec8dab
Fix further regression bug.
Aug 28, 2020
0a2e307
Clean up loading module
maxbriel Aug 28, 2020
bdba1cb
Updates mass per bin calculation for vectorized funciton input
maxbriel Aug 28, 2020
be7b9fa
Renames CSPEventRate functions and adds grid functions
maxbriel Aug 28, 2020
f9a5a10
np.zeros to np.empty where possible
maxbriel Aug 28, 2020
30485f5
Merge pull request #60 from findesgh/csp_fix2
maxbriel Aug 28, 2020
0c74851
Merge remote-tracking branch 'origin/csp' into csp
maxbriel Aug 28, 2020
498a3ed
Fixed incorrect test of at_time and over_time
maxbriel Aug 29, 2020
ad2bc98
Set default sample rate for at_time
maxbriel Aug 29, 2020
f727fd7
Adds `cache` parameter to over_time_spectrum
maxbriel Aug 29, 2020
466efab
Adds grid functions for the spectra calculation
maxbriel Aug 29, 2020
6e81cc0
Adds return_time_edges to grid_over_time & bug fix sfh vectorisation
maxbriel Sep 2, 2020
2a6c95f
Emissivity compiling and loading.
Sep 9, 2020
6c883e1
Rename func, add existence of metallicity files, remove try/except
maxbriel Oct 5, 2020
0c8e094
Merge remote-tracking branch 'origin/dev1.6' into data_loading
maxbriel Oct 6, 2020
a1187cd
Finalise merge of `origin/dev1.6` into `data_loading`
maxbriel Oct 6, 2020
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
2 changes: 2 additions & 0 deletions hoki/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
"imf135_100", "imf135_300", "imf135all_100", "imf170_100",
"imf170_300"]

# wavelengths at which spectra are given [angstrom]
BPASS_WAVELENGTHS = np.arange(1, 100001)

# Create a deprecation warning when using dummy_dict
dummy_dict = {'timestep': 0, 'age': 1, 'log(R1)': 2, 'log(T1)': 3, 'log(L1)': 4, 'M1': 5, 'He_core1': 6, 'CO_core1': 7,
Expand Down
1 change: 0 additions & 1 deletion hoki/csp/tests/test_spectra.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from hoki.csp.spectra import CSPSpectra
from hoki.load import model_output
from hoki.constants import BPASS_NUM_METALLICITIES
import itertools
data_path = pkg_resources.resource_filename('hoki', 'data')

# Load Test spectra. Not an actual spectra.
Expand Down
200 changes: 119 additions & 81 deletions hoki/data_compilers.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"""
Author: Max Briel & Heloise Stevance
Author: Heloise Stevance, Max Briel, & Martin Glatzle

Objects and pipelines that compile BPASS data files into more convenient, more pythonic data types
"""

import abc
import numpy as np

from hoki.constants import (DEFAULT_BPASS_VERSION, MODELS_PATH,
OUTPUTS_PATH, dummy_dicts,
BPASS_IMFS, BPASS_METALLICITIES)
BPASS_IMFS, BPASS_METALLICITIES,
BPASS_WAVELENGTHS, BPASS_TIME_BINS)
import hoki.load
import pandas as pd
import re
Expand All @@ -17,6 +17,120 @@
from hoki.utils.exceptions import HokiFatalError, HokiUserWarning, HokiFormatError, HokiKeyError
from hoki.utils.hoki_object import HokiObject

class _CompilerBase(abc.ABC):
def __init__(self, input_folder, output_folder, imf, binary=True,
verbose=False):
if verbose:
_print_welcome()

# Check population type
star = "bin" if binary else "sin"

# check IMF key
if imf not in BPASS_IMFS:
raise HokiKeyError(
f"{imf} is not a BPASS IMF. Please select a correct IMF.")

# Setup the numpy output
output = np.empty(self._shape(), dtype=np.float64)

# loop over all the metallicities and load all the spectra
for num, metallicity in enumerate(BPASS_METALLICITIES):
print_progress_bar(num, 12)
# Check if file exists
assert isfile(f"{input_folder}/spectra-{star}-{imf}.{metallicity}.dat"),\
"HOKI ERROR: This file does not exist, or its path is incorrect."
output[num] = self._load_single(
f"{input_folder}/{self._input_name()}-{star}-{imf}.{metallicity}.dat"
)

np.save(f"{output_folder}/{self._output_name()}-{star}-{imf}", output)
# pickle the datafile
self.output = output
print(
f"Compiled data stored in {output_folder} as '{self._output_name()}-{star}-{imf}.npy'")
if verbose:
_print_exit_message()
return

@abc.abstractmethod
def _input_name(self):
return

@abc.abstractmethod
def _output_name(self):
return

@abc.abstractmethod
def _shape(self):
return

@abc.abstractmethod
def _load_single(self, path):
return

class SpectraCompiler(_CompilerBase):
"""
Pipeline to load the BPASS spectra txt files and save them as a 3D
`numpy.ndarray` binary file.

Attributes
output : `numpy.ndarray` (N_Z, N_age, N_lam) [(metallicity, log_age, wavelength)]
----------
A 3D numpy array containing all the BPASS spectra for a specific imf
and binary or single star population.
Usage: spectra[1][2][1000]
(gives L_\\odot for Z=0.0001 and log_age=6.2 at 999 Angstrom)
"""

def _input_name(self):
return "spectra"

def _output_name(self):
return "all_spectra"

def _shape(self):
return (
len(BPASS_METALLICITIES),
len(BPASS_TIME_BINS),
len(BPASS_WAVELENGTHS)
)

def _load_single(self, path):
return np.loadtxt(path).T[1:, :]


class EmissivityCompiler(_CompilerBase):
"""
Pipeline to load the BPASS ionizing txt files and save them as a 3D
`numpy.ndarray` binary file.

Attributes
----------
output : `numpy.ndarray` (N_Z, N_age, 4) [(metallicity, log_age, band)]
A 3D numpy array containing all the BPASS emissivities (Nion [1/s],
L_Halpha [ergs/s], L_FUV [ergs/s/A], L_NUV [ergs/s/A]) for a specific
imf and binary or single star population.
Usage: spectra[1][2][0]
(gives Nion for Z=0.0001 and log_age=6.2)
"""
def _input_name(self):
return "ionizing"

def _output_name(self):
return "all_ionizing"

def _shape(self):
return (
len(BPASS_METALLICITIES),
len(BPASS_TIME_BINS),
4
)

def _load_single(self, path):
return np.loadtxt(path)[:, 1:]


class ModelDataCompiler(HokiObject):
"""
Given a list of metalicities, a list of valid BPASS model attributes (in the dummy array), chosen types of model
Expand Down Expand Up @@ -202,81 +316,6 @@ def _select_input_files(z_list, directory=OUTPUTS_PATH,

return input_file_list

class SpectraCompiler():
"""
Pipeline to load the BPASS spectra txt files and save them as a 3D
`numpy.ndarray` binary file.

Attributes
----------
spectra : `numpy.ndarray` (13, 51, 100000) [(metallicity, log_age, wavelength)]
A 3D numpy array containing all the BPASS spectra for a specific imf
and binary or single star population.
Usage: spectra[1][2][1000]
(gives L_\\odot for Z=0.0001 and log_age=6.2 at 999 Angstrom)
"""

def __init__(self, spectra_folder, output_folder, imf, binary=True, verbose=False):
"""
Input
-----
spectra_folder : `str`
Path to the folder containing the spectra of the given imf.

output_folder : `str`
Path to the folder, where to output the pickled pandas.DataFrame

imf : `str`
BPASS IMF Identifiers
The accepted IMF identifiers are:
- `"imf_chab100"`
- `"imf_chab300"`
- `"imf100_100"`
- `"imf100_300"`
- `"imf135_100"`
- `"imf135_300"`
- `"imfall_300"`
- `"imf170_100"`
- `"imf170_300"`

binary : `bool`
If `True`, loads the binary files. Otherwise, just loads single stars.
Default=True

verbose : `bool`
If `True` prints out extra information for the user.
Default=False
"""
if verbose:
_print_welcome()

# Check population type
star = "bin" if binary else "sin"

# check IMF key
if imf not in BPASS_IMFS:
raise HokiKeyError(
f"{imf} is not a BPASS IMF. Please select a correct IMF.")

# Setup the numpy output
spectra = np.empty((13, 51, 100000), dtype=np.float64)

# loop over all the metallicities and load all the spectra
for num, metallicity in enumerate(BPASS_METALLICITIES):
print_progress_bar(num, 12)
assert isfile(f"{spectra_folder}/spectra-{star}-{imf}.{metallicity}.dat"),\
"HOKI ERROR: This file does not exist, or its path is incorrect."
spectra[num] = np.loadtxt(f"{spectra_folder}/spectra-{star}-{imf}.{metallicity}.dat").T[1:, :]

# pickle the datafile
np.save(f"{output_folder}/all_spectra-{star}-{imf}", spectra)
self.spectra = spectra
print(
f"Spectra file stored in {output_folder} as 'all_spectra-{star}-{imf}.npy'")
if verbose:
_print_exit_message()



def _print_welcome():
print('*************************************************')
Expand All @@ -285,11 +324,10 @@ def _print_welcome():
print("\n\nThis may take a while ;)\nGo get yourself a cup of tea, sit back and relax\nI'm working for you boo!")

print(
"\nNOTE: The progress bar doesn't move smoothly - it might accelerate or slow down - it's perfectly normal :D")
"\nNOTE: The progress bar doesn't move smoothly - it might accelerate or slow down - it's perfectly normal :D")


def _print_exit_message():

print('\n\n\n*************************************************')
print('******* JOB DONE! HAPPY SCIENCING! ******')
print('*************************************************')
74 changes: 73 additions & 1 deletion hoki/load.py
Original file line number Diff line number Diff line change
Expand Up @@ -571,10 +571,82 @@ def spectra_all_z(data_path, imf, binary=True):
spec = hoki.data_compilers.SpectraCompiler(
data_path, data_path, imf, binary=binary
)
spectra = spec.spectra
spectra = spec.output
return spectra


def emissivities_all_z(data_path, imf, binary=True):
"""
Load all BPASS emissivities from files.

Notes
-----
The first time this function is run on a folder it will generate an npy
file containing all the BPASS emissivities for faster loading in the
future. It stores the file in the same folder with the name:
`all_ionizing-[bin/sin]-[imf].npy`.

The emissivities are just read from file and not normalised.


Input
-----
data_path : `str`
The path to the folder containing the BPASS files.

binary : `bool`
Use the binary files or just the single stars. Default=True

imf : `str`
BPASS Identifier of the IMF to be used.
The accepted IMF identifiers are:
- `"imf_chab100"`
- `"imf_chab300"`
- `"imf100_100"`
- `"imf100_300"`
- `"imf135_100"`
- `"imf135_300"`
- `"imfall_300"`
- `"imf170_100"`
- `"imf170_300"`

Returns
-------
emissivities : `numpy.ndarray` (N_Z, N_age, 4) [(metallicity, log_age, band)]
A 3D numpy array containing all the BPASS emissivities (Nion [1/s],
L_Halpha [ergs/s], L_FUV [ergs/s/A], L_NUV [ergs/s/A]) for a specific
imf and binary or single star population.
Usage: spectra[1][2][0]
(gives Nion for Z=0.0001 and log_age=6.2)
"""
# Check population type
star = "bin" if binary else "sin"

# check IMF key
if imf not in BPASS_IMFS:
raise HokiKeyError(
f"{imf} is not a BPASS IMF. Please select a correct IMF.")

# check if data_path is a string
if not isinstance(data_path, str):
raise HokiTypeError("The folder location is expected to be a string.")

# Check if compiled spectra are already present in data folder
if os.path.isfile(f"{data_path}/all_ionizing-{star}-{imf}.npy"):
print("Load precompiled file.")
emissivities = np.load(f"{data_path}/all_ionizing-{star}-{imf}.npy")
print("Done Loading.")

# Compile the spectra for faster reading next time otherwise
else:
print("Compiled file not found. Data will be compiled.")
res = hoki.data_compilers.EmissivityCompiler(
data_path, data_path, imf, binary=binary
)
emissivities = res.output
return emissivities


#################
# #
#################
Expand Down
Binary file added hoki/tests/corner_plot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading