text stringlengths 81 112k |
|---|
Parse xml body sent by weixin.
:param content: A text of xml body.
def parse(self, content):
"""Parse xml body sent by weixin.
:param content: A text of xml body.
"""
raw = {}
try:
root = etree.fromstring(content)
except SyntaxError as e:
... |
Create the reply text for weixin.
The reply varies per reply type. The acceptable types are `text`,
`music`, `news`, `image`, `voice`, `video`. Each type accepts
different parameters, but they share some common parameters:
* username: the receiver's username
* type: the... |
Register a command helper function.
You can register the function::
def print_help(**kwargs):
username = kwargs.get('sender')
sender = kwargs.get('receiver')
return weixin.reply(
username, sender=sender, content='text reply'
... |
Default view function for Flask app.
This is a simple implementation for view func, you can add it to
your Flask app::
weixin = Weixin(app)
app.add_url_rule('/', view_func=weixin.view_func)
def view_func(self):
"""Default view function for Flask app.
This is a... |
Passes user inputs to GetGist() and calls get()
def run_getgist(filename, user, **kwargs):
"""Passes user inputs to GetGist() and calls get()"""
assume_yes = kwargs.get("yes_to_all")
getgist = GetGist(user=user, filename=filename, assume_yes=assume_yes)
getgist.get() |
Shortcut for run_getgist() reading username from env var
def run_getmy(filename, **kwargs):
"""Shortcut for run_getgist() reading username from env var"""
assume_yes = kwargs.get("yes_to_all")
user = getenv("GETGIST_USER")
getgist = GetGist(user=user, filename=filename, assume_yes=assume_yes)
getgi... |
Passes user inputs to GetGist() and calls put()
def run_putgist(filename, user, **kwargs):
"""Passes user inputs to GetGist() and calls put()"""
assume_yes = kwargs.get("yes_to_all")
private = kwargs.get("private")
getgist = GetGist(
user=user,
filename=filename,
assume_yes=assu... |
Reads the remote file from Gist and save it locally
def get(self):
"""Reads the remote file from Gist and save it locally"""
if self.gist:
content = self.github.read_gist_file(self.gist)
self.local.save(content) |
Reads local file & update the remote gist (or create a new one)
def put(self):
""" Reads local file & update the remote gist (or create a new one)"""
content = self.local.read()
if self.gist:
self.github.update(self.gist, content)
else:
self.github.create(content... |
Decorator to restrict some GitHubTools methods to run only with OAuth
def oauth_only(function):
"""Decorator to restrict some GitHubTools methods to run only with OAuth"""
def check_for_oauth(self, *args, **kwargs):
"""
Returns False if GitHubTools instance is not authenticated, or return
... |
Validate token and add the proper header for further requests.
:return: (None)
def add_oauth_header(self):
"""
Validate token and add the proper header for further requests.
:return: (None)
"""
# abort if no token
oauth_token = self._get_token()
if not oa... |
List generator containing gist relevant information
such as id, description, filenames and raw URL (dict).
def get_gists(self):
"""
List generator containing gist relevant information
such as id, description, filenames and raw URL (dict).
"""
# fetch all gists
if... |
Given the requested filename, it selects the proper gist; if more than
one gist is found with the given filename, user is asked to choose.
:allow_none: (bool) for `getgist` it should raise error if no gist is
found, but setting this argument to True avoid this error, which is
useful when... |
Returns the contents of file hosted inside a gist at GitHub.
:param gist: (dict) gist parsed by GitHubTools._parse()
:return: (bytes) content of a gist loaded from GitHub
def read_gist_file(self, gist):
"""
Returns the contents of file hosted inside a gist at GitHub.
:param gist... |
Updates the contents of file hosted inside a gist at GitHub.
:param gist: (dict) gist parsed by GitHubTools._parse_gist()
:param content: (str or bytes) to be written
:return: (bool) indicatind the success or failure of the update
def update(self, gist, content):
"""
Updates the... |
Create a new gist.
:param gist: (dict) gist parsed by GitHubTools._parse()
:param content: (str or bytes) to be written
:param public: (bool) defines if the gist is public or private
:return: (bool) indicatind the success or failure of the creation
def create(self, content, **kwargs):
... |
Asks user which gist to use in case of more than one gist matching the
instance filename.
:param matches: (list) of dictioaries generated within select_gists()
:return: (dict) of the selected gist
def _ask_which_gist(self, matches):
"""
Asks user which gist to use in case of mor... |
Receive a gist (dict) and parse it to GetGist
def _parse_gist(gist):
"""Receive a gist (dict) and parse it to GetGist"""
# parse files
files = list()
file_names = sorted(filename for filename in gist["files"].keys())
for name in file_names:
files.append(
... |
Sets the indent for standardized output
:param message: (str)
:return: (str)
def indent(self, message):
"""
Sets the indent for standardized output
:param message: (str)
:return: (str)
"""
indent = self.indent_char * self.indent_size
return indent... |
A helper to used like print() or click's secho() tunneling all the
outputs to sys.stdout or sys.stderr
:param message: (str)
:param color: (str) check click.secho() documentation
:return: (None) prints to sys.stdout or sys.stderr
def output(self, message, color=None):
"""
... |
Encapsulte requests.get to use this class instance header
def get(self, url, params=None, **kwargs):
"""Encapsulte requests.get to use this class instance header"""
return requests.get(url, params=params, headers=self.add_headers(**kwargs)) |
Encapsulte requests.patch to use this class instance header
def patch(self, url, data=None, **kwargs):
"""Encapsulte requests.patch to use this class instance header"""
return requests.patch(url, data=data, headers=self.add_headers(**kwargs)) |
Encapsulte requests.post to use this class instance header
def post(self, url, data=None, **kwargs):
"""Encapsulte requests.post to use this class instance header"""
return requests.post(url, data=data, headers=self.add_headers(**kwargs)) |
Save any given content to the instance file.
:param content: (str or bytes)
:return: (None)
def save(self, content):
"""
Save any given content to the instance file.
:param content: (str or bytes)
:return: (None)
"""
# backup existing file if needed
... |
Backups files with the same name of the instance filename
def backup(self):
"""Backups files with the same name of the instance filename"""
count = 0
name = "{}.bkp".format(self.filename)
backup = os.path.join(self.cwd, name)
while os.path.exists(backup):
count += 1
... |
Read the contents of a file.
:param filename: (str) path to a file in the local file system
:return: (str) contents of the file, or (False) if not found/not file
def read(self, file_path=None):
"""
Read the contents of a file.
:param filename: (str) path to a file in the local f... |
a faster way for characters to generate token strings cache
def char_matcher(mode):
"""
a faster way for characters to generate token strings cache
"""
def f_raw(inp_str, pos):
return mode if inp_str[pos] is mode else None
def f_collection(inp_str, pos):
ch = inp_str[pos]... |
generate token strings' cache
def str_matcher(mode):
"""
generate token strings' cache
"""
def f_raw(inp_str, pos):
return unique_literal_cache_pool[mode] if inp_str.startswith(mode, pos) else None
def f_collection(inp_str, pos):
for each in mode:
if inp_str.... |
generate token names' cache
:param regex_pat:
:return:
def regex_matcher(regex_pat):
"""
generate token names' cache
:param regex_pat:
:return:
"""
if isinstance(regex_pat, str):
regex_pat = re.compile(regex_pat)
def f(inp_str, pos):
m = regex_pat.match(... |
Stmts ::= TokenDef{0, 1} Equals*;
def ast_for_stmts(self, stmts: T) -> None:
"""
Stmts ::= TokenDef{0, 1} Equals*;
"""
if not stmts:
raise ValueError('no ast found!')
head, *equals = stmts
if head.name is NameEnum.TokenDef:
self.as... |
Perform a method on a resource.
Args:
method: requests.`method`
resource_uri: resource endpoint
Raises:
HTTPError
Returns:
JSON Response
def _request(self, method, resource_uri, **kwargs):
"""Perform a method on a resource.
Args:... |
Get a resource.
Args:
endpoint: resource endpoint.
def get(self, endpoint, **kwargs):
"""Get a resource.
Args:
endpoint: resource endpoint.
"""
return self._request(requests.get, endpoint, **kwargs) |
Create a resource.
Args:
endpoint: resource endpoint.
def post(self, endpoint, **kwargs):
"""Create a resource.
Args:
endpoint: resource endpoint.
"""
return self._request(requests.post, endpoint, **kwargs) |
Update a resource.
Args:
endpoint: resource endpoint.
def put(self, endpoint, **kwargs):
"""Update a resource.
Args:
endpoint: resource endpoint.
"""
return self._request(requests.put, endpoint, **kwargs) |
Static method defined to update paystack customer data by id.
Args:
customer_id: paystack customer id.
first_name: customer's first name(optional).
last_name: customer's last name(optional).
email: customer's email address(optional).
phone:customer's ... |
Accepts Slack formatted text and returns HTML.
def render(txt):
"""
Accepts Slack formatted text and returns HTML.
"""
# Removing links to other channels
txt = re.sub(r'<#[^\|]*\|(.*)>', r'#\g<1>', txt)
# Removing links to other users
txt = re.sub(r'<(@.*)>', r'\g<1>', txt)
# handle ... |
Add an open list tag corresponding to the specification in the
parser's LIST_TYPES.
def _open_list(self, list_type):
"""
Add an open list tag corresponding to the specification in the
parser's LIST_TYPES.
"""
if list_type in LIST_TYPES.keys():
tag = LIST_TYPE... |
Add an close list tag corresponding to the currently open
list found in current_parent_element.
def _close_list(self):
"""
Add an close list tag corresponding to the currently open
list found in current_parent_element.
"""
list_type = self.current_parent_element['attrs']... |
Called by HTMLParser.feed when a start tag is found.
def handle_starttag(self, tag, attrs):
"""
Called by HTMLParser.feed when a start tag is found.
"""
# Parse the tag attributes
attrs_dict = dict(t for t in attrs)
# If the tag is a predefined parent element
if... |
Called by HTMLParser.feed when an end tag is found.
def handle_endtag(self, tag):
"""
Called by HTMLParser.feed when an end tag is found.
"""
if tag in PARENT_ELEMENTS:
self.current_parent_element['tag'] = ''
self.current_parent_element['attrs'] = ''
if ... |
Called by HTMLParser.feed when text is found.
def handle_data(self, data):
"""
Called by HTMLParser.feed when text is found.
"""
if self.current_parent_element['tag'] == '':
self.cleaned_html += '<p>'
self.current_parent_element['tag'] = 'p'
self.cleaned... |
Removes formatting tags added to pre elements.
def _remove_pre_formatting(self):
"""
Removes formatting tags added to pre elements.
"""
preformatted_wrappers = [
'pre',
'code'
]
for wrapper in preformatted_wrappers:
for formatter in F... |
Goes through the txt input and cleans up any problematic HTML.
def clean(self):
"""
Goes through the txt input and cleans up any problematic HTML.
"""
# Calls handle_starttag, handle_endtag, and handle_data
self.feed()
# Clean up any parent tags left open
if sel... |
Unstrict template block for rendering authors:
<div class="author">
<img class="author-avatar" src="{author_avatar}">
<p class="author-name">
<a href="{author_link}">{author_name}</a>
</p>
<p class="user-handle">{author_handle}</p>
</div>
def render_author(**kwargs):... |
Unstrict template block for rendering metadata:
<div class="metadata">
<img class="metadata-logo" src="{service_logo}">
<p class="metadata-name">{service_name}</p>
<p class="metadata-timestamp">
<a href="{timestamp_link}">{timestamp}</a>
</p>
</div>
def render_metada... |
Unstrict template block for rendering an image:
<img alt="{alt_text}" title="{title}" src="{url}">
def render_image(**kwargs):
"""
Unstrict template block for rendering an image:
<img alt="{alt_text}" title="{title}" src="{url}">
"""
html = ''
url = kwargs.get('url', None)
if url:
... |
Strict template block for rendering twitter embeds.
def render_twitter(text, **kwargs):
"""
Strict template block for rendering twitter embeds.
"""
author = render_author(**kwargs['author'])
metadata = render_metadata(**kwargs['metadata'])
image = render_image(**kwargs['image'])
html = """... |
Cannon model params
def get_model(LAB_DIR):
""" Cannon model params """
coeffs = np.load("%s/coeffs.npz" %LAB_DIR)['arr_0']
scatters = np.load("%s/scatters.npz" %LAB_DIR)['arr_0']
chisqs = np.load("%s/chisqs.npz" %LAB_DIR)['arr_0']
pivots = np.load("%s/pivots.npz" %LAB_DIR)['arr_0']
return coef... |
Labels to make Cannon model spectra
def get_labels(ids_find):
""" Labels to make Cannon model spectra """
a = pyfits.open("%s/lamost_catalog_full.fits" %LAB_DIR)
data = a[1].data
a.close()
id_all = data['lamost_id']
id_all = np.array(id_all)
id_all = np.array([val.strip() for val in id_all]... |
Spectra to compare with models
def get_normed_spectra():
""" Spectra to compare with models """
wl = np.load("%s/wl.npz" %LAB_DIR)['arr_0']
filenames = np.array(
[SPEC_DIR + "/Spectra" + "/" + val for val in lamost_id])
grid, fluxes, ivars, npix, SNRs = lamost.load_spectra(
lamo... |
Pull the files from the LAMOST archive
def wget_files():
""" Pull the files from the LAMOST archive """
for f in lamost_id:
short = (f.split('-')[2]).split('_')[0]
filename = "%s/%s.gz" %(short,f)
DIR = "/Users/annaho/Data/Li_Giants/Spectra_APOKASC"
searchfor = "%s/%s.gz" %(DIR,... |
Labels to make Cannon model spectra
def get_labels():
""" Labels to make Cannon model spectra """
cannon_teff = data['cannon_teff_2']
cannon_logg = data['cannon_logg_2']
cannon_m_h = data['cannon_m_h']
cannon_alpha_m = data['cannon_alpha_m']
cannon_a_k = data['cannon_a_k']
labels = np.vstac... |
Normalize according to The Cannon
def cannon_normalize(spec_raw):
""" Normalize according to The Cannon """
spec = np.array([spec_raw])
wl = np.arange(0, spec.shape[1])
w = continuum_normalization.gaussian_weight_matrix(wl, L=50)
ivar = np.ones(spec.shape)*0.5
cont = continuum_normalization._fi... |
Resample spectrum onto desired grid
def resample(grid, wl, flux):
""" Resample spectrum onto desired grid """
flux_rs = (interpolate.interp1d(wl, flux))(grid)
return flux_rs |
Generate Cannon gradient spectra
Parameters
----------
labels: default values for [teff, logg, feh, cfe, nfe, afe, ak]
choose: val of cfe or nfe, whatever you're varying
low: lowest val of cfe or nfe, whatever you're varying
high: highest val of cfe or nfe, whatever you're varying
def gen_cann... |
X_u_template[0:2] are teff, logg, vturb in km/s
X_u_template[:,3] -> onward, put atomic number
atomic_number is 6 for C, 7 for N
def get_model_spec_ting(atomic_number):
"""
X_u_template[0:2] are teff, logg, vturb in km/s
X_u_template[:,3] -> onward, put atomic number
atomic_number is 6 for C... |
Using the dataset and model object, calculate the residuals and return
Parameters
----------
ds: dataset object
m: model object
Return
------
residuals: array of residuals, spec minus model spec
def get_residuals(ds, m):
""" Using the dataset and model object, calculate the residuals a... |
Load the model
Parameters
----------
direc: directory with all of the model files
Returns
-------
m: model object
def load_model():
""" Load the model
Parameters
----------
direc: directory with all of the model files
Returns
-------
m: model object
... |
Load the dataset for a single date
Parameters
----------
date: the date (string) for which to load the data & dataset
Returns
-------
ds: the dataset object
def load_dataset(date):
""" Load the dataset for a single date
Parameters
----------
date: the date (string) ... |
Fit a Gaussian to the data
def fit_gaussian(x, y, yerr, p0):
""" Fit a Gaussian to the data """
try:
popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True)
except RuntimeError:
return [0],[0]
return popt, pcov |
criteria for keeping an object
def select(yerrs, amps, amp_errs, widths):
""" criteria for keeping an object """
keep_1 = np.logical_and(amps < 0, widths > 1)
keep_2 = np.logical_and(np.abs(amps) > 3*yerrs, amp_errs < 3*np.abs(amps))
keep = np.logical_and(keep_1, keep_2)
return keep |
Load the data that we're using to search for Li-rich giants.
Store it in dataset and model objects.
def run_all():
""" Load the data that we're using to search for Li-rich giants.
Store it in dataset and model objects. """
DATA_DIR = "/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels"
dates ... |
Generate Cannon gradient spectra
Parameters
----------
labels: default values for [teff, logg, feh, cfe, nfe, afe, ak]
choose: val of cfe or nfe, whatever you're varying
low: lowest val of cfe or nfe, whatever you're varying
high: highest val of cfe or nfe, whatever you're varying
def gen_cann... |
Get approximate scatters from SNR
as determined in the code, snr_test.py
Order: Teff, logg, MH, CM, NM, alpha
def get_err(snr):
""" Get approximate scatters from SNR
as determined in the code, snr_test.py
Order: Teff, logg, MH, CM, NM, alpha """
quad_terms = np.array(
[3.11e-3, 1.1... |
Pull colors from catalog
Parameters
----------
catalog: filename
def get_colors(catalog):
"""
Pull colors from catalog
Parameters
----------
catalog: filename
"""
print("Get Colors")
a = pyfits.open(catalog)
data = a[1].data
a.close()
all_ids = data['LAMOST_ID... |
Generate best-fit spectra for all the test objects
Parameters
----------
md: model
The Cannon spectral model
ds: Dataset
Dataset object
Returns
-------
best_fluxes: ndarray
The best-fit test fluxes
best_ivars:
The best-fit test inverse variances
d... |
Run a series of diagnostics on the fitted spectra
Parameters
----------
model: model
best-fit Cannon spectral model
dataset: Dataset
original spectra
def overlay_spectra(model, dataset):
""" Run a series of diagnostics on the fitted spectra
Parameters
----------
... |
Stack spectrum fit residuals, sort by each label. Include histogram of
the RMS at each pixel.
Parameters
----------
cannon_set: Dataset
best-fit Cannon spectra
dataset: Dataset
original spectra
def residuals(cannon_set, dataset):
""" Stack spectrum fit residuals, sort by each ... |
Find and return continuum pixels given the flux and sigma cut
Parameters
----------
f_cut: float
the upper limit imposed on the quantity (fbar-1)
sig_cut: float
the upper limit imposed on the quantity (f_sig)
wl: numpy ndarray of length npixels
rest-frame wavelength vector
... |
Find continuum pix in spec, meeting a set target fraction
Parameters
----------
wl: numpy ndarray
rest-frame wavelength vector
fluxes: numpy ndarray
pixel intensities
ivars: numpy ndarray
inverse variances, parallel to fluxes
target_frac: float
the fractio... |
Find continuum pix in a spectrum split into chunks
Parameters
----------
wl: numpy ndarray
rest-frame wavelength vector
fluxes: numpy ndarray
pixel intensities
ivars: numpy ndarray
inverse variances, parallel to fluxes
frac: float
fraction of pixels in spectru... |
Load the reference data, and assign each object
a random integer from 0 to 7. Save the IDs.
def group_data():
""" Load the reference data, and assign each object
a random integer from 0 to 7. Save the IDs. """
tr_obj = np.load("%s/ref_id.npz" %direc_ref)['arr_0']
groups = np.random.randint(0, 8, s... |
Run the training step, given a dataset object.
def train(ds, ii):
""" Run the training step, given a dataset object. """
print("Loading model")
m = model.CannonModel(2)
print("Training...")
m.fit(ds)
np.savez("./ex%s_coeffs.npz" %ii, m.coeffs)
np.savez("./ex%s_scatters.npz" %ii, m.scatters)... |
Train a model, leaving out a group corresponding
to a random integer from 0 to 7, e.g. leave out 0.
Test on the remaining 1/8 of the sample.
def xvalidate():
""" Train a model, leaving out a group corresponding
to a random integer from 0 to 7, e.g. leave out 0.
Test on the remaining 1/8 of the sa... |
Calculate standard deviation weighted by errors
def weighted_std(values, weights):
""" Calculate standard deviation weighted by errors """
average = np.average(values, weights=weights)
variance = np.average((values-average)**2, weights=weights)
return np.sqrt(variance) |
Estimate the scatter in a region of the spectrum
taken to be continuum
def estimate_noise(fluxes, contmask):
""" Estimate the scatter in a region of the spectrum
taken to be continuum """
nstars = fluxes.shape[0]
scatter = np.zeros(nstars)
for i,spec in enumerate(fluxes):
cont = spec[c... |
Pull out wl, flux, ivar from files of training spectra
def load_ref_spectra():
""" Pull out wl, flux, ivar from files of training spectra """
data_dir = "/Users/annaho/Data/AAOmega/ref_spectra"
# Load the files & count the number of training objects
ff = glob.glob("%s/*.txt" %data_dir)
nstars = len... |
Use all the above functions to set data up for The Cannon
def load_data():
data_dir = "/Users/annaho/Data/AAOmega"
out_dir = "%s/%s" %(data_dir, "Run_13_July")
""" Use all the above functions to set data up for The Cannon """
ff, wl, tr_flux, tr_ivar = load_ref_spectra()
""" pick one that doesn't... |
take the scatters and skylines and make final ivars
def make_full_ivar():
""" take the scatters and skylines and make final ivars """
# skylines come as an ivar
# don't use them for now, because I don't really trust them...
# skylines = np.load("%s/skylines.npz" %DATA_DIR)['arr_0']
ref_flux = np.... |
Return the sinusoid cont func evaluated at input x for the continuum.
Parameters
----------
x: float or np.array
data, input to function
p: ndarray
coefficients of fitting function
L: float
width of x data
y: float or np.array
output data corresponding to input ... |
Calculate a weighted median for values above a particular quantile cut
Used in pseudo continuum normalization
Parameters
----------
values: np ndarray of floats
the values to take the median of
weights: np ndarray of floats
the weights associated with the values
quantile: float... |
Returns the weighted mean block of spectra
Parameters
----------
wl: numpy ndarray
wavelength vector
flux: numpy ndarray
block of flux values
ivar: numpy ndarray
block of ivar values
L: float
width of Gaussian used to assign weights
Returns
-------
... |
Continuum normalize by dividing by a Gaussian-weighted smoothed spectrum
Parameters
----------
dataset: Dataset
the dataset to continuum normalize
L: float
the width of the Gaussian used for weighting
Returns
-------
dataset: Dataset
updated dataset
def _cont_norm_... |
Fit a continuum to a continuum pixels in a segment of spectra
Functional form can be either sinusoid or chebyshev, with specified degree
Parameters
----------
fluxes: numpy ndarray of shape (nstars, npixels)
training set or test set pixel intensities
ivars: numpy ndarray of shape (nstars,... |
Run fit_cont, dealing with spectrum in regions or chunks
This is useful if a spectrum has gaps.
Parameters
----------
fluxes: ndarray of shape (nstars, npixels)
training set or test set pixel intensities
ivars: numpy ndarray of shape (nstars, npixels)
inverse variances, parallel t... |
Perform continuum normalization using a running quantile
Parameters
----------
wl: numpy ndarray
wavelength vector
fluxes: numpy ndarray of shape (nstars, npixels)
pixel intensities
ivars: numpy ndarray of shape (nstars, npixels)
inverse variances, parallel to fluxes
q:... |
The same as _cont_norm_running_quantile() above,
but using multi-processing.
Bo Zhang (NAOC)
def _cont_norm_running_quantile_mp(wl, fluxes, ivars, q, delta_lambda,
n_proc=2, verbose=False):
"""
The same as _cont_norm_running_quantile() above,
but using multi-proc... |
Perform continuum normalization using running quantile, for spectrum
that comes in chunks
def _cont_norm_running_quantile_regions(wl, fluxes, ivars, q, delta_lambda,
ranges, verbose=True):
""" Perform continuum normalization using running quantile, for spectrum
that ... |
Perform continuum normalization using running quantile, for spectrum
that comes in chunks.
The same as _cont_norm_running_quantile_regions(),
but using multi-processing.
Bo Zhang (NAOC)
def _cont_norm_running_quantile_regions_mp(wl, fluxes, ivars, q, delta_lambda,
... |
Continuum-normalize a continuous segment of spectra.
Parameters
----------
fluxes: numpy ndarray
pixel intensities
ivars: numpy ndarray
inverse variances, parallel to fluxes
contmask: boolean mask
True indicates that pixel is continuum
Returns
-------
norm_flu... |
Perform continuum normalization for spectra in chunks
Useful for spectra that have gaps
Parameters
---------
fluxes: numpy ndarray
pixel intensities
ivars: numpy ndarray
inverse variances, parallel to fluxes
cont: numpy ndarray
the continuum
ranges: list or np ndarr... |
Run training step: solve for best-fit spectral model
def train(self, ds):
""" Run training step: solve for best-fit spectral model """
if self.useErrors:
self.coeffs, self.scatters, self.new_tr_labels, self.chisqs, self.pivots, self.scales = _train_model_new(ds)
else:
se... |
After inferring labels for the test spectra,
infer the model spectra and update the dataset
model_spectra attribute.
Parameters
----------
ds: Dataset object
def infer_spectra(self, ds):
"""
After inferring labels for the test spectra,
infer the... |
Plot baseline spec with continuum pix overlaid
Parameters
----------
def plot_contpix(self, x, y, contpix_x, contpix_y, figname):
""" Plot baseline spec with continuum pix overlaid
Parameters
----------
"""
fig, axarr = plt.subplots(2, sharex=True)
pl... |
Call plot_contpix once for each nth of the spectrum
def diagnostics_contpix(self, data, nchunks=10, fig = "baseline_spec_with_cont_pix"):
""" Call plot_contpix once for each nth of the spectrum """
if data.contmask is None:
print("No contmask set")
else:
coeffs_all = sel... |
Produce a set of diagnostic plots for the model
Parameters
----------
(optional) chisq_dist_plot_name: str
Filename of output saved plot
def diagnostics_plot_chisq(self, ds, figname = "modelfit_chisqs.png"):
""" Produce a set of diagnostic plots for the model
Par... |
asteroseismic scaling relations
def calc_mass(nu_max, delta_nu, teff):
""" asteroseismic scaling relations """
NU_MAX = 3140.0 # microHz
DELTA_NU = 135.03 # microHz
TEFF = 5777.0
return (nu_max/NU_MAX)**3 * (delta_nu/DELTA_NU)**(-4) * (teff/TEFF)**1.5 |
Table A2 in Martig 2016
def calc_mass_2(mh,cm,nm,teff,logg):
""" Table A2 in Martig 2016 """
CplusN = calc_sum(mh,cm,nm)
t = teff/4000.
return (95.8689 - 10.4042*mh - 0.7266*mh**2
+ 41.3642*cm - 5.3242*cm*mh - 46.7792*cm**2
+ 15.0508*nm - 0.9342*nm*mh - 30.5159*nm*cm - 1.6083*nm... |
Make a *sick* corner plot showing the projections of a data set in a
multi-dimensional space. kwargs are passed to hist2d() or used for
`matplotlib` styling.
Parameters
----------
xs : array_like (nsamples, ndim)
The samples. This should be a 1- or 2-dimensional array. For a 1-D
arr... |
Like numpy.percentile, but:
* Values of q are quantiles [0., 1.] rather than percentiles [0., 100.]
* scalar q not supported (q must be iterable)
* optional weights on x
def quantile(x, q, weights=None):
"""
Like numpy.percentile, but:
* Values of q are quantiles [0., 1.] rather than percenti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.