Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
86 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
0cafab8
Utils for binning of spectra.
Aug 6, 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
d2b2e34
Typo.
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
a5a747e
Fix limit checks on bin_edges.
findesgh Aug 31, 2020
6e81cc0
Adds return_time_edges to grid_over_time & bug fix sfh vectorisation
maxbriel Sep 2, 2020
22699a0
Bug fix in nr_time_bins (grid_over_time functions)
maxbriel Sep 21, 2020
9b2c46d
Docs string cleanup
maxbriel Sep 28, 2020
7ddd2a0
Merge branch 'dev1.6' into csp
maxbriel Sep 29, 2020
9a4c65b
Solve cyclical import error
maxbriel Sep 29, 2020
a7d1203
Fix tox and remove corner plot
maxbriel Sep 29, 2020
c96e92e
REFACTOR: wave to wl.
findesgh Oct 2, 2020
256ef8d
DOC: update to docstrings.
findesgh Oct 3, 2020
bdbccb4
Overhaul how bins work.
findesgh Oct 3, 2020
7801d16
File check, combined data_compiler tests, renames func+variables
maxbriel Oct 4, 2020
7ee73c0
Merge branch 'csp' into rebin
findesgh Oct 6, 2020
4a7ddb0
Merge branch 'dev1.6' into rebin
findesgh Oct 6, 2020
5737d0e
REFACTOR: bin_spectra to bin_luminosity.
Oct 8, 2020
c690259
REFACTOR: move binning utils to spec.
Oct 8, 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
172 changes: 169 additions & 3 deletions hoki/spec.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
"""
Module to hold functions and utilities to be applied to spectra,
especially BPASS synthetic spectra
Module to hold functions and utilities to be applied to spectra, especially
BPASS synthetic spectra
"""
import numpy as np
from numba import jit
import numbers


def dopcor(df, z, wl_col_index=0):
Expand All @@ -14,4 +17,167 @@ def dopcor(df, z, wl_col_index=0):
"""
wl_dopcor = (df.iloc[:, wl_col_index].values) - (df.iloc[:, wl_col_index].values * z)
df.iloc[:, wl_col_index] = wl_dopcor
return
return


def bin_luminosity(wl, spectra, bins=10):
"""
Bin spectra conserving luminosity.

Given spectra sampled at certain wavelengths/frequencies will compute their
values in given wavelength/frequency bins. These values are bin averages
computed using trapezoidal integration, which ensures that the luminosity
per bin is conserved. Of course, only downsampling really makes sense here,
i.e. the input spectra should be well sampled compared to the desired
output bins.

Effectively converts input spectra to step functions of
wavelength/frequency. Note, in particular, that this means that only
rectangle rule integration can sensibly be performed on the output
spectra. Other integration methods are not meaningful.

Parameters
----------
wl : `numpy.ndarray` (N_wl,)
Wavelengths or frequencies at which spectra are known.
spectra : `numpy.ndarray` (N, N_wl)
The spectra to bin given as L_lambda [Energy/Time/Wavelength] or L_nu
[Energy/Time/Frequency] in accordance with `wl`.
bins : int or `numpy.ndarray` (N_edges,), optional
Either an integer giving the number `N_bins` of desired equal-width
bins or an array of bin edges, required to lie within the range given
by `wl`. In the latter case, `N_bins=N_edges-1`.

Returns
-------
wl_new : `numpy.ndarray` (N_bins,)
The wavelength/frequency values to which spectra were binned,
i.e. centre bin values.
spectra_new : `numpy.ndarray` (N, N_bins)
The binned spectra.

Notes
-----
For the actual integration, `wl` has to be sorted in ascending or
descending order. If this is not the case, `wl` and `spectra` will be
sorted/re-ordered. `bins` will always be sorted in the same order as `wl`
as it is assumed to generally be relatively small.

Although the language used here refers to spectra, the primary intended
application area, the code can naturally be used to bin any function with
given samples, conserving its integral bin-wise.
"""
for arr, ndim in zip([wl, spectra, bins], [[1], [2], [0, 1]]):
if np.ndim(arr) not in ndim:
raise ValueError("Wrong dimensionality of input arrays.")
if spectra.shape[1] != len(wl):
raise ValueError("Shapes of `wl` and `spectra` are incompatible.")

diff = np.diff(wl)
if np.all(diff > 0):
asc = True
elif np.all(diff < 0):
asc = False
else:
if np.any(diff == 0):
raise ValueError("Identical values provided in `wl`.")
ids = np.argsort(wl)
wl = wl[ids]
spectra = spectra[:, ids]
asc = True

if isinstance(bins, numbers.Integral):
bins = np.linspace(wl[0], wl[-1], num=bins+1)
else:
if asc:
bins = np.sort(bins)
else:
bins = bins[np.argsort(-1*bins)]
if not (np.amax(bins) <= np.amax(wl) and np.amin(bins) >= np.amin(wl)):
raise ValueError("Bin edges outside of valid range!")

wl_new = (bins[1:] + bins[:-1])/2
spectra_new = _binwise_trapz_sorted(wl, spectra, bins) \
/ np.diff(bins)

return wl_new, spectra_new


@jit(nopython=True, nogil=True, cache=True)
def _binwise_trapz_sorted(x, y, bin_edges):
"""
Trapezoidal integration over bins.

Integrate each row of `y(x)` over each bin defined by `bin_edges` using
trapezoidal integration. The values of `bin_edges` do not have to coincide
with values given in `x`, the rows of `y` are linearly interpolated
correspondingly.

Parameters
----------
x : `numpy.ndarray` (N_x,)
`x`-values corresponding to each column of `y`. Assumed to be sorted in
ascending or descending order. Integrated values will be negative for
descending order.
y : `numpy.ndarray` (N, N_x)
N functions of `x` evaluated at each of its values.
bin_edges : `numpy.ndarray` (N_bins+1,)
Edges of the bins over which to perform integration. Assumed to be
sorted in same order as `x` and to span a range <= the range spanned by
`x`.

Returns
-------
res : `numpy.ndarray` (N, N_bins)
Integral over each bin of each row of `y`.
"""
res = np.empty((y.shape[0], len(bin_edges)-1))

i1 = 0
i2 = 0
y1 = np.empty((y.shape[0]))
y2 = np.empty((y.shape[0]))
for j in range(res.shape[1]):
x1 = bin_edges[j]
x2 = bin_edges[j+1]

# ascending
if x[0] < x[1]:
# Find last element <x1 and last element <x2 in x.
while x1 > x[i1+1]:
i1 += 1
i2 = i1
while x2 > x[i2+1]:
i2 += 1
# descending
elif x[0] > x[1]:
# Find last element >x1 and last element >x2 in x.
while x1 < x[i1+1]:
i1 += 1
i2 = i1
while x2 < x[i2+1]:
i2 += 1
else:
raise ValueError("Identical values in `x`!")

# Find y1=y(x1) and y2=y(x2) by interpolation.
y1 = (
(x[i1+1]-x1)*y[:, i1] + (x1-x[i1])*y[:, i1+1]
) / (x[i1+1]-x[i1])
y2 = (
(x[i2+1]-x2)*y[:, i2] + (x2-x[i2])*y[:, i2+1]
) / (x[i2+1]-x[i2])

if i1 == i2:
# Have only area from x1 to x2.
res[:, j] = (x2-x1)*(y1+y2)/2
else:
# Area from x1 to x(i1+1).
res[:, j] = (x[i1+1]-x1)*(y1+y[:, i1+1])/2
# Add area from x(i1+1) to x(i2-1).
for i in range(i1+1, i2):
res[:, j] += (x[i+1]-x[i])*(y[:, i]+y[:, i+1])/2
# Add area from x(i2) to x2.
res[:, j] += (x2-x[i2])*(y2+y[:, i2])/2

return res
Loading