text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_thread(self, thread_id, update_if_cached=True, raise_404=False):
"""Get a thread from 4chan via 4chan API. Args: thread_id (int):
Thread ID update_if_ca... |
# see if already cached
cached_thread = self._thread_cache.get(thread_id)
if cached_thread:
if update_if_cached:
cached_thread.update()
return cached_thread
res = self._requests_session.get(
self._url.thread_api_url(
t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def thread_exists(self, thread_id):
"""Check if a thread exists or has 404'd. Args: thread_id (int):
Thread ID Returns: bool: Whether the given thread exists on... |
return self._requests_session.head(
self._url.thread_api_url(
thread_id=thread_id
)
).ok |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_threads(self, page=1):
"""Returns all threads on a certain page. Gets a list of Thread objects for every thread on the given page. If a thread is already... |
url = self._url.page_url(page)
return self._request_threads(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_thread_ids(self):
"""Return the ID of every thread on this board. Returns: list of ints: List of IDs of every thread on this board. """ |
json = self._get_json(self._url.thread_list())
return [thread['no'] for page in json for thread in page['threads']] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_threads(self, expand=False):
"""Return every thread on this board. If not expanded, result is same as get_threads run across all board pages, with la... |
if not expand:
return self._request_threads(self._url.catalog())
thread_ids = self.get_all_thread_ids()
threads = [self.get_thread(id, raise_404=False) for id in thread_ids]
return filter(None, threads) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh_cache(self, if_want_update=False):
"""Update all threads currently stored in our cache.""" |
for thread in tuple(self._thread_cache.values()):
if if_want_update:
if not thread.want_update:
continue
thread.update() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modify_environment(self, env):
"""Maintaining compatibility with different CASA versions is a pain.""" |
# Ugh. I don't see any way out of special-casing the RPM-based
# installations ... which only exist on NRAO computers, AFAICT.
# Hardcoding 64-bitness, hopefully that won't come back to bite me.
is_rpm_install = self._rootdir.startswith('/usr/lib64/casapy/release/')
def path(*... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_bgband (evtpath, srcreg, bkgreg, ebins, env=None):
"""Compute background information for a source in one or more energy bands. evtpath Path to a CIAO... |
import numpy as np
import pandas as pd
from scipy.special import erfcinv, gammaln
if env is None:
from . import CiaoEnvironment
env = CiaoEnvironment ()
srcarea = get_region_area (env, evtpath, srcreg)
bkgarea = get_region_area (env, evtpath, bkgreg)
srccounts = [count_ev... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simple_srcflux(env, infile=None, psfmethod='arfcorr', conf=0.68, verbose=0, **kwargs):
"""Run the CIAO "srcflux" script and retrieve its results. *infile* Th... |
from ...io import Path
import shutil, signal, tempfile
if infile is None:
raise ValueError('must specify infile')
kwargs.update(dict(
infile = infile,
psfmethod = psfmethod,
conf = conf,
verbose = verbose,
clobber = 'yes',
outroot = 'sf',
))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_for_fk10_fig9(cls, shlib_path):
"""Create a calculator initialized to reproduce Figure 9 from FK10. This is mostly to provide a handy way to create a new... |
inst = (cls(shlib_path)
.set_thermal_background(2.1e7, 3e9)
.set_bfield(48)
.set_edist_powerlaw(0.016, 4.0, 3.7, 5e9/3)
.set_freqs(100, 0.5, 50)
.set_hybrid_parameters(12, 12)
.set_ignore_q_terms(False)
.set_obs_angle(50 * np.p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_bfield(self, B_G):
"""Set the strength of the local magnetic field. **Call signature** *B_G* The magnetic field strength, in Gauss Returns *self* for con... |
if not (B_G > 0):
raise ValueError('must have B_G > 0; got %r' % (B_G,))
self.in_vals[IN_VAL_B] = B_G
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_bfield_for_s0(self, s0):
"""Set B to probe a certain harmonic number. **Call signature** *s0* The harmonic number to probe at the lowest frequency Return... |
if not (s0 > 0):
raise ValueError('must have s0 > 0; got %r' % (s0,))
B0 = 2 * np.pi * cgs.me * cgs.c * self.in_vals[IN_VAL_FREQ0] / (cgs.e * s0)
self.in_vals[IN_VAL_B] = B0
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_edist_powerlaw(self, emin_mev, emax_mev, delta, ne_cc):
"""Set the energy distribution function to a power law. **Call signature** *emin_mev* The minimum... |
if not (emin_mev >= 0):
raise ValueError('must have emin_mev >= 0; got %r' % (emin_mev,))
if not (emax_mev >= emin_mev):
raise ValueError('must have emax_mev >= emin_mev; got %r, %r' % (emax_mev, emin_mev))
if not (delta >= 0):
raise ValueError('must have del... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_edist_powerlaw_gamma(self, gmin, gmax, delta, ne_cc):
"""Set the energy distribution function to a power law in the Lorentz factor **Call signature** *gm... |
if not (gmin >= 1):
raise ValueError('must have gmin >= 1; got %r' % (gmin,))
if not (gmax >= gmin):
raise ValueError('must have gmax >= gmin; got %r, %r' % (gmax, gmin))
if not (delta >= 0):
raise ValueError('must have delta >= 0; got %r, %r' % (delta,))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_freqs(self, n, f_lo_ghz, f_hi_ghz):
"""Set the frequency grid on which to perform the calculations. **Call signature** *n* The number of frequency points... |
if not (f_lo_ghz >= 0):
raise ValueError('must have f_lo_ghz >= 0; got %r' % (f_lo_ghz,))
if not (f_hi_ghz >= f_lo_ghz):
raise ValueError('must have f_hi_ghz >= f_lo_ghz; got %r, %r' % (f_hi_ghz, f_lo_ghz))
if not n >= 1:
raise ValueError('must have n >= 1; g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_obs_angle(self, theta_rad):
"""Set the observer angle relative to the field. **Call signature** *theta_rad* The angle between the ray path and the local ... |
self.in_vals[IN_VAL_THETA] = theta_rad * 180 / np.pi # rad => deg
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_one_freq(self, f_ghz):
"""Set the code to calculate results at just one frequency. **Call signature** *f_ghz* The frequency to sample, in GHz. Returns *s... |
if not (f_ghz >= 0):
raise ValueError('must have f_lo_ghz >= 0; got %r' % (f_lo_ghz,))
self.in_vals[IN_VAL_NFREQ] = 1
self.in_vals[IN_VAL_FREQ0] = f_ghz * 1e9 # GHz -> Hz
self.in_vals[IN_VAL_LOGDFREQ] = 1.0
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_padist_gaussian_loss_cone(self, boundary_rad, expwidth):
"""Set the pitch-angle distribution to a Gaussian loss cone. **Call signature** *boundary_rad* T... |
self.in_vals[IN_VAL_PADIST] = PADIST_GLC
self.in_vals[IN_VAL_LCBDY] = boundary_rad * 180 / np.pi # rad => deg
self.in_vals[IN_VAL_DELTAMU] = expwidth
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_thermal_background(self, T_K, nth_cc):
"""Set the properties of the background thermal plasma. **Call signature** *T_K* The temperature of the background... |
if not (T_K >= 0):
raise ValueError('must have T_K >= 0; got %r' % (T_K,))
if not (nth_cc >= 0):
raise ValueError('must have nth_cc >= 0; got %r, %r' % (nth_cc,))
self.in_vals[IN_VAL_T0] = T_K
self.in_vals[IN_VAL_N0] = nth_cc
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_trapezoidal_integration(self, n):
"""Set the code to use trapezoidal integration. **Call signature** *n* Use this many nodes Returns *self* for convenien... |
if not (n >= 2):
raise ValueError('must have n >= 2; got %r' % (n,))
self.in_vals[IN_VAL_INTEG_METH] = n + 1
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_rt_coefficients(self, depth0=None):
"""Figure out emission and absorption coefficients for the current parameters. **Argument** *depth0* (default None) ... |
if self.in_vals[IN_VAL_NFREQ] != 1:
raise Exception('must have nfreq=1 to run Calculator.find_rt_coefficients()')
if depth0 is not None:
depth = depth0
self.in_vals[IN_VAL_DEPTH] = depth0
else:
depth = self.in_vals[IN_VAL_DEPTH]
scale_fa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_rt_coefficients_tot_intens(self, depth0=None):
"""Figure out total-intensity emission and absorption coefficients for the current parameters. **Argument... |
j_O, alpha_O, j_X, alpha_X = self.find_rt_coefficients(depth0=depth0)
j_I = j_O + j_X
alpha_I = 0.5 * (alpha_O + alpha_X) # uhh... right?
return (j_I, alpha_I) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_path_func (*baseparts):
"""Return a function that joins paths onto some base directory.""" |
from os.path import join
base = join (*baseparts)
def path_func (*args):
return join (base, *args)
return path_func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def djoin (*args):
"""'dotless' join, for nicer paths.""" |
from os.path import join
i = 0
alen = len (args)
while i < alen and (args[i] == '' or args[i] == '.'):
i += 1
if i == alen:
return '.'
return join (*args[i:]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_symlink (src, dst):
"""Ensure the existence of a symbolic link pointing to src named dst. Returns a boolean indicating whether the symlink already exi... |
try:
os.symlink (src, dst)
except OSError as e:
if e.errno == 17: # EEXIST
return True
raise
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_dir (self, mode=0o777, parents=False):
"""Ensure that this path exists as a directory. This function calls :meth:`mkdir` on this path, but does not ra... |
if parents:
p = self.parent
if p == self:
return False # can never create root; avoids loop when parents=True
p.ensure_dir (mode, True)
made_it = False
try:
self.mkdir (mode)
made_it = True
except OSError as e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_tempfile (self, want='handle', resolution='try_unlink', suffix='', **kwargs):
"""Get a context manager that creates and cleans up a uniquely-named tempo... |
if want not in ('handle', 'path'):
raise ValueError ('unrecognized make_tempfile() "want" mode %r' % (want,))
if resolution not in ('unlink', 'try_unlink', 'keep', 'overwrite'):
raise ValueError ('unrecognized make_tempfile() "resolution" mode %r' % (resolution,))
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def try_unlink (self):
"""Try to unlink this path. If it doesn't exist, no error is returned. Returns a boolean indicating whether the path was really unlinked. ... |
try:
self.unlink ()
return True
except OSError as e:
if e.errno == 2:
return False # ENOENT
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_pickles (self):
"""Generate a sequence of objects by opening the path and unpickling items until EOF is reached. """ |
try:
import cPickle as pickle
except ImportError:
import pickle
with self.open (mode='rb') as f:
while True:
try:
obj = pickle.load (f)
except EOFError:
break
yield obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_text(self, encoding=None, errors=None, newline=None):
"""Read this path as one large chunk of text. This function reads in the entire file as one big pi... |
with self.open (mode='rt', encoding=encoding, errors=errors, newline=newline) as f:
return f.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_toml(self, encoding=None, errors=None, newline=None, **kwargs):
"""Read this path as a TOML document. The `TOML <https://github.com/toml-lang/toml>`_ pa... |
import pytoml
with self.open (mode='rt', encoding=encoding, errors=errors, newline=newline) as f:
return pytoml.load (f, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_yaml (self, encoding=None, errors=None, newline=None, **kwargs):
"""Read this path as a YAML document. The YAML parsing is done with the :mod:`yaml` mod... |
import yaml
with self.open (mode='rt', encoding=encoding, errors=errors, newline=newline) as f:
return yaml.load (f, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enumeration (cls):
"""A very simple decorator for creating enumerations. Unlike Python 3.4 enumerations, this just gives a way to use a class declaration to ... |
from pwkit import unicode_to_str
name = cls.__name__
pickle_compat = getattr (cls, '__pickle_compat__', False)
def __unicode__ (self):
return '<enumeration holder %s>' % name
def getattr_error (self, attr):
raise AttributeError ('enumeration %s does not contain attribute %s' % (na... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slice_around_gaps (values, maxgap):
"""Given an ordered array of values, generate a set of slices that traverse all of the values. Within each slice, no gap ... |
if not (maxgap > 0):
# above test catches NaNs, other weird cases
raise ValueError ('maxgap must be positive; got %r' % maxgap)
values = np.asarray (values)
delta = values[1:] - values[:-1]
if np.any (delta < 0):
raise ValueError ('values must be in nondecreasing order')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reduce_data_frame (df, chunk_slicers, avg_cols=(), uavg_cols=(), minmax_cols=(), nchunk_colname='nchunk', uncert_prefix='u', min_points_per_chunk=3):
""""Red... |
subds = [df.iloc[idx] for idx in chunk_slicers]
subds = [sd for sd in subds if sd.shape[0] >= min_points_per_chunk]
chunked = df.__class__ ({nchunk_colname: np.zeros (len (subds), dtype=np.int)})
# Some future-proofing: allow possibility of different ways of mapping
# from a column giving a value... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reduce_data_frame_evenly_with_gaps (df, valcol, target_len, maxgap, **kwargs):
""""Reduce" a DataFrame by collapsing rows in grouped chunks, grouping based o... |
return reduce_data_frame (df,
slice_evenly_with_gaps (df[valcol], target_len, maxgap),
**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def usmooth (window, uncerts, *data, **kwargs):
"""Smooth data series according to a window, weighting based on uncertainties. Arguments: window The smoothing wi... |
window = np.asarray (window)
uncerts = np.asarray (uncerts)
# Hacky keyword argument handling because you can't write "def foo (*args,
# k=0)".
k = kwargs.pop ('k', None)
if len (kwargs):
raise TypeError ("smooth() got an unexpected keyword argument '%s'"
% k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def weighted_variance (x, weights):
"""Return the variance of a weighted sample. The weighted sample mean is calculated and subtracted off, so the returned varia... |
n = len (x)
if n < 3:
raise ValueError ('cannot calculate meaningful variance of fewer '
'than three samples')
wt_mean = np.average (x, weights=weights)
return np.average (np.square (x - wt_mean), weights=weights) * n / (n - 1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unit_tophat_ee (x):
"""Tophat function on the unit interval, left-exclusive and right-exclusive. Returns 1 if 0 < x < 1, 0 otherwise. """ |
x = np.asarray (x)
x1 = np.atleast_1d (x)
r = ((0 < x1) & (x1 < 1)).astype (x.dtype)
if x.ndim == 0:
return np.asscalar (r)
return r |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_tophat_ee (lower, upper):
"""Return a ufunc-like tophat function on the defined range, left-exclusive and right-exclusive. Returns 1 if lower < x < uppe... |
if not np.isfinite (lower):
raise ValueError ('"lower" argument must be finite number; got %r' % lower)
if not np.isfinite (upper):
raise ValueError ('"upper" argument must be finite number; got %r' % upper)
def range_tophat_ee (x):
x = np.asarray (x)
x1 = np.atleast_1d (x)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_tophat_ei (lower, upper):
"""Return a ufunc-like tophat function on the defined range, left-exclusive and right-inclusive. Returns 1 if lower < x <= upp... |
if not np.isfinite (lower):
raise ValueError ('"lower" argument must be finite number; got %r' % lower)
if not np.isfinite (upper):
raise ValueError ('"upper" argument must be finite number; got %r' % upper)
def range_tophat_ei (x):
x = np.asarray (x)
x1 = np.atleast_1d (x)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_tophat_ie (lower, upper):
"""Return a ufunc-like tophat function on the defined range, left-inclusive and right-exclusive. Returns 1 if lower <= x < upp... |
if not np.isfinite (lower):
raise ValueError ('"lower" argument must be finite number; got %r' % lower)
if not np.isfinite (upper):
raise ValueError ('"upper" argument must be finite number; got %r' % upper)
def range_tophat_ie (x):
x = np.asarray (x)
x1 = np.atleast_1d (x)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_tophat_ii (lower, upper):
"""Return a ufunc-like tophat function on the defined range, left-inclusive and right-inclusive. Returns 1 if lower < x < uppe... |
if not np.isfinite (lower):
raise ValueError ('"lower" argument must be finite number; got %r' % lower)
if not np.isfinite (upper):
raise ValueError ('"upper" argument must be finite number; got %r' % upper)
def range_tophat_ii (x):
x = np.asarray (x)
x1 = np.atleast_1d (x)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_step_lcont (transition):
"""Return a ufunc-like step function that is left-continuous. Returns 1 if x > transition, 0 otherwise. """ |
if not np.isfinite (transition):
raise ValueError ('"transition" argument must be finite number; got %r' % transition)
def step_lcont (x):
x = np.asarray (x)
x1 = np.atleast_1d (x)
r = (x1 > transition).astype (x.dtype)
if x.ndim == 0:
return np.asscalar (r)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_step_rcont (transition):
"""Return a ufunc-like step function that is right-continuous. Returns 1 if x >= transition, 0 otherwise. """ |
if not np.isfinite (transition):
raise ValueError ('"transition" argument must be finite number; got %r' % transition)
def step_rcont (x):
x = np.asarray (x)
x1 = np.atleast_1d (x)
r = (x1 >= transition).astype (x.dtype)
if x.ndim == 0:
return np.asscalar (r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_fixed_temp_multi_apec(kTs, name_template='apec%d', norm=None):
"""Create a model summing multiple APEC components at fixed temperatures. *kTs* An iterab... |
total_model = None
sub_models = []
for i, kT in enumerate(kTs):
component = ui.xsapec(name_template % i)
component.kT = kT
ui.freeze(component.kT)
if norm is not None:
component.norm = norm
sub_models.append(component)
if total_model is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand_rmf_matrix(rmf):
"""Expand an RMF matrix stored in compressed form. *rmf* An RMF object as might be returned by ``sherpa.astro.ui.get_rmf()``. Returns... |
n_chan = rmf.e_min.size
n_energy = rmf.n_grp.size
expanded = np.zeros((n_energy, n_chan))
mtx_ofs = 0
grp_ofs = 0
for i in range(n_energy):
for j in range(rmf.n_grp[i]):
f = rmf.f_chan[grp_ofs]
n = rmf.n_chan[grp_ofs]
expanded[i,f:f+n] = rmf.matrix[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def derive_identity_arf(name, arf):
"""Create an "identity" ARF that has uniform sensitivity. *name* The name of the ARF object to be created; passed to Sherpa. ... |
from sherpa.astro.data import DataARF
from sherpa.astro.instrument import ARF1D
darf = DataARF(
name,
arf.energ_lo,
arf.energ_hi,
np.ones(arf.specresp.shape),
arf.bin_lo,
arf.bin_hi,
arf.exposure,
header = None,
)
return ARF1D(darf, p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_source_qq_data(id=None):
"""Get data for a quantile-quantile plot of the source data and model. *id* The dataset id for which to get the data; defaults i... |
sdata = ui.get_data(id=id)
kev = sdata.get_x()
obs_data = sdata.counts
model_data = ui.get_model(id=id)(kev)
return np.vstack((kev, obs_data, model_data)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bkg_qq_data(id=None, bkg_id=None):
"""Get data for a quantile-quantile plot of the background data and model. *id* The dataset id for which to get the da... |
bdata = ui.get_bkg(id=id, bkg_id=bkg_id)
kev = bdata.get_x()
obs_data = bdata.counts
model_data = ui.get_bkg_model(id=id, bkg_id=bkg_id)(kev)
return np.vstack((kev, obs_data, model_data)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_qq_plot(kev, obs, mdl, unit, key_text):
"""Make a quantile-quantile plot comparing events and a model. *kev* A 1D, sorted array of event energy bins mea... |
import omega as om
kev = np.asarray(kev)
obs = np.asarray(obs)
mdl = np.asarray(mdl)
c_obs = np.cumsum(obs)
c_mdl = np.cumsum(mdl)
mx = max(c_obs[-1], c_mdl[-1])
p = om.RectPlot()
p.addXY([0, mx], [0, mx], '1:1')
p.addXY(c_mdl, c_obs, key_text)
# HACK: this range of numb... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_multi_qq_plots(arrays, key_text):
"""Make a quantile-quantile plot comparing multiple sets of events and models. *arrays* X. *key_text* Text describing ... |
import omega as om
p = om.RectPlot()
p.addXY([0, 1.], [0, 1.], '1:1')
for index, array in enumerate(arrays):
kev, obs, mdl = array
c_obs = np.cumsum(obs)
c_mdl = np.cumsum(mdl)
mx = 0.5 * (c_obs[-1] + c_mdl[-1])
c_obs /= mx
c_mdl /= mx
p.addXY... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_spectrum_plot(model_plot, data_plot, desc, xmin_clamp=0.01, min_valid_x=None, max_valid_x=None):
"""Make a plot of a spectral model and data. *model_plo... |
import omega as om
model_x = np.concatenate((model_plot.xlo, [model_plot.xhi[-1]]))
model_x[0] = max(model_x[0], xmin_clamp)
model_y = np.concatenate((model_plot.y, [0.]))
# Sigh, sometimes Sherpa gives us bad values.
is_bad = ~np.isfinite(model_y)
if is_bad.sum():
from .cli impor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_file(local_filename, url, clobber=False):
"""Download the given file. Clobber overwrites file if exists.""" |
dir_name = os.path.dirname(local_filename)
mkdirs(dir_name)
if clobber or not os.path.exists(local_filename):
i = requests.get(url)
# if not exists
if i.status_code == 404:
print('Failed to download file:', local_filename, url)
return False
# write... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_json(local_filename, url, clobber=False):
"""Download the given JSON file, and pretty-print before we output it.""" |
with open(local_filename, 'w') as json_file:
json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': '))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_to_argb32 (data, cmin=None, cmax=None, stretch='linear', cmap='black_to_blue'):
"""Turn arbitrary data values into ARGB32 colors. There are three steps ... |
# This could be more efficient, but whatever. This lets us share code with
# the ndshow module.
clipper = Clipper ()
clipper.alloc_buffer (data)
clipper.set_tile_size ()
clipper.dmin = cmin if cmin is not None else data.min ()
clipper.dmax = cmax if cmax is not None else data.max ()
cl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_to_imagesurface (data, **kwargs):
"""Turn arbitrary data values into a Cairo ImageSurface. The method and arguments are the same as data_to_argb32, exce... |
import cairo
data = np.atleast_2d (data)
if data.ndim != 2:
raise ValueError ('input array may not have more than 2 dimensions')
argb32 = data_to_argb32 (data, **kwargs)
format = cairo.FORMAT_ARGB32
height, width = argb32.shape
stride = cairo.ImageSurface.format_stride_for_width ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_token(filename=TOKEN_PATH, envvar=TOKEN_ENVVAR):
""" Returns pipeline_token for API Tries local file first, then env variable """ |
if os.path.isfile(filename):
with open(filename) as token_file:
token = token_file.readline().strip()
else:
token = os.environ.get(envvar)
if not token:
raise ValueError("No token found.\n"
"{} file doesn't exist.\n{} environment va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stats (self, antnames):
"""XXX may be out of date.""" |
nbyant = np.zeros (self.nants, dtype=np.int)
sum = np.zeros (self.nants, dtype=np.complex)
sumsq = np.zeros (self.nants)
q = np.abs (self.normvis - 1)
for i in range (self.nsamps):
i1, i2 = self.blidxs[i]
nbyant[i1] += 1
nbyant[i2] += 1
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _qr_factor_packed(a, enorm, finfo):
"""Compute the packed pivoting Q-R factorization of a matrix. Parameters: a - An n-by-m matrix, m >= n. This will be *ove... |
machep = finfo.eps
n, m = a.shape
if m < n:
raise ValueError('"a" must be at least as tall as it is wide')
acnorm = np.empty(n, finfo.dtype)
for j in range(n):
acnorm[j] = enorm(a[j], finfo)
rdiag = acnorm.copy()
wa = acnorm.copy()
pmut = np.arange(n)
for i in r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _qr_factor_full(a, dtype=np.float):
"""Compute the QR factorization of a matrix, with pivoting. Parameters: a - An n-by-m arraylike, m >= n. dtype - (optiona... |
n, m = a.shape
# Compute the packed Q and R matrix information.
packed, pmut, rdiag, acnorm = \
_manual_qr_factor_packed(a, dtype)
# Now we unpack. Start with the R matrix, which is easy: we just
# have to piece it together from the strict lower triangle of 'a'
# and the diagonal in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _qrd_solve(r, pmut, ddiag, bqt, sdiag):
"""Solve an equation given a QR factored matrix and a diagonal. Parameters: r - **input-output** n-by-n array. The fu... |
n, m = r.shape
# "Copy r and bqt to preserve input and initialize s. In
# particular, save the diagonal elements of r in x." Recall that
# on input only the full lower triangle of R is meaningful, so we
# can mirror that into the upper triangle without issues.
for i in range(n):
r[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _qrd_solve_full(a, b, ddiag, dtype=np.float):
"""Solve the equation A^T x = B, D x = 0. Parameters: a - an n-by-m array, m >= n b - an m-vector ddiag - an n-... |
a = np.asarray(a, dtype)
b = np.asarray(b, dtype)
ddiag = np.asarray(ddiag, dtype)
n, m = a.shape
assert m >= n
assert b.shape == (m, )
assert ddiag.shape == (n, )
# The computation is straightforward.
q, r, pmut = _qr_factor_full(a)
bqt = np.dot(b, q.T)
x, s = _manual_q... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calc_covariance(r, pmut, tol=1e-14):
"""Calculate the covariance matrix of the fitted parameters Parameters: r - n-by-n matrix, the full upper triangle of R... |
# This routine could save an allocation by operating on r in-place,
# which might be worthwhile for large n, and is what the original
# Fortran does.
n = r.shape[1]
assert r.shape[0] >= n
r = r.copy()
# Form the inverse of R in the full lower triangle of R.
jrank = -1
abstol = to... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def invoke_tool (namespace, tool_class=None):
"""Invoke a tool and exit. `namespace` is a namespace-type dict from which the tool is initialized. It should conta... |
import sys
from .. import cli
cli.propagate_sigint ()
cli.unicode_stdio ()
cli.backtrace_on_usr1 ()
if tool_class is None:
for value in itervalues (namespace):
if is_strict_subclass (value, Multitool):
if tool_class is not None:
raise PKE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_arg_parser (self, **kwargs):
"""Return an instance of `argparse.ArgumentParser` used to process this tool's command-line arguments. """ |
import argparse
ap = argparse.ArgumentParser (
prog = kwargs['argv0'],
description = self.summary,
)
return ap |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register (self, cmd):
"""Register a new command with the tool. 'cmd' is expected to be an instance of `Command`, although here only the `cmd.name` attribute ... |
if cmd.name is None:
raise ValueError ('no name set for Command object %r' % cmd)
if cmd.name in self.commands:
raise ValueError ('a command named "%s" has already been '
'registered' % cmd.name)
self.commands[cmd.name] = cmd
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def invoke_command (self, cmd, args, **kwargs):
"""This function mainly exists to be overridden by subclasses.""" |
new_kwargs = kwargs.copy ()
new_kwargs['argv0'] = kwargs['argv0'] + ' ' + cmd.name
new_kwargs['parent'] = self
new_kwargs['parent_kwargs'] = kwargs
return cmd.invoke_with_usage (args, **new_kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_bibtex_collections(citednames, maindict, extradicts, allow_missing=False):
"""There must be a way to be efficient and stream output instead of loading ... |
allrecords = {}
for ed in extradicts:
allrecords.update(ed)
allrecords.update(maindict)
missing = []
from collections import OrderedDict
records = OrderedDict()
from itertools import chain
wantednames = sorted(chain(citednames, six.viewkeys(maindict)))
for name in wanted... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_bibtex_dict(stream, entries):
"""bibtexparser.write converts the entire database to one big string and writes it out in one go. I'm sure it will always... |
from bibtexparser.bwriter import BibTexWriter
writer = BibTexWriter()
writer.indent = ' '
writer.entry_separator = ''
first = True
for rec in entries:
if first:
first = False
else:
stream.write(b'\n')
stream.write(writer._entry_to_bibtex(rec).e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_bibtex_with_aux(auxpath, mainpath, extradir, parse=get_bibtex_dict, allow_missing=False):
"""Merge multiple BibTeX files into a single homogeneously-fo... |
auxpath = Path(auxpath)
mainpath = Path(mainpath)
extradir = Path(extradir)
with auxpath.open('rt') as aux:
citednames = sorted(cited_names_from_aux_file(aux))
main = mainpath.try_open(mode='rt')
if main is None:
maindict = {}
else:
maindict = parse(main)
m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def just_smart_bibtools(bib_style, aux, bib):
"""Tectonic has taken over most of the features that this tool used to provide, but here's a hack to keep my smart ... |
extradir = Path('.bibtex')
extradir.ensure_dir(parents=True)
bib_export(bib_style, aux, extradir / 'ZZ_bibtools.bib',
no_tool_ok=True, quiet=True, ignore_missing=True)
merge_bibtex_with_aux(aux, bib, extradir) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aap_to_bp (ant1, ant2, pol):
"""Create a basepol from antenna numbers and a CASA polarization code.""" |
if ant1 < 0:
raise ValueError ('first antenna is below 0: %s' % ant1)
if ant2 < ant1:
raise ValueError ('second antenna is below first: %s' % ant2)
if pol < 1 or pol > 12:
raise ValueError ('illegal polarization code %s' % pol)
fps = _pol_to_fpol[pol]
ap1 = (ant1 << 3) + (... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _finish_timeslot (self):
"""We have loaded in all of the visibilities in one timeslot. We can now compute the phase closure triples. XXX: we should only proc... |
for fpol, aps in self.ap_by_fpol.items ():
aps = sorted (aps)
nap = len (aps)
for i1, ap1 in enumerate (aps):
for i2 in range (i1, nap):
ap2 = aps[i2]
bp1 = (ap1, ap2)
info = self.data_by_bp.get (bp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_sample (self, ap1, ap2, ap3, triple, tflags):
"""We have computed one independent phase closure triple in one timeslot. """ |
# Frequency-resolved:
np.divide (triple, np.abs (triple), triple)
phase = np.angle (triple)
self.ap_spec_stats_by_ddid[self.cur_ddid].accum (ap1, phase, tflags + 0.)
self.ap_spec_stats_by_ddid[self.cur_ddid].accum (ap2, phase, tflags + 0.)
self.ap_spec_stats_by_ddid[sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_spectrum(path, smoothing=181, DF=-8.):
"""Load a Phoenix model atmosphere spectrum. path : string The file path to load. smoothing : integer Smoothing t... |
try:
ang, lflam = np.loadtxt(path, usecols=(0,1)).T
except ValueError:
# In some files, the numbers in the first columns fill up the
# whole 12-character column width, and are given in exponential
# notation with a 'D' character, so we must be more careful:
with open(pat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lbol_from_spt_dist_mag (sptnum, dist_pc, jmag, kmag, format='cgs'):
"""Estimate a UCD's bolometric luminosity given some basic parameters. sptnum: the spectr... |
bcj = bcj_from_spt (sptnum)
bck = bck_from_spt (sptnum)
n = np.zeros (sptnum.shape, dtype=np.int)
app_mbol = np.zeros (sptnum.shape)
w = np.isfinite (bcj) & np.isfinite (jmag)
app_mbol[w] += jmag[w] + bcj[w]
n[w] += 1
w = np.isfinite (bck) & np.isfinite (kmag)
app_mbol[w] += kmag... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map(self, func, iterable, chunksize=None):
"""Equivalent of `map` built-in, without swallowing KeyboardInterrupt. func The function to apply to the items. it... |
# The key magic is that we must call r.get() with a timeout, because a
# Condition.wait() without a timeout swallows KeyboardInterrupts.
r = self.map_async(func, iterable, chunksize)
while True:
try:
return r.get(self.wait_timeout)
except Timeout... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fmthours (radians, norm='wrap', precision=3, seps='::'):
"""Format an angle as sexagesimal hours in a string. Arguments are: radians The angle, in radians. n... |
return _fmtsexagesimal (radians * R2H, norm, 24, seps, precision=precision) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fmtdeglon (radians, norm='wrap', precision=2, seps='::'):
"""Format a longitudinal angle as sexagesimal degrees in a string. Arguments are: radians The angle... |
return _fmtsexagesimal (radians * R2D, norm, 360, seps, precision=precision) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fmtdeglat (radians, norm='raise', precision=2, seps='::'):
"""Format a latitudinal angle as sexagesimal degrees in a string. Arguments are: radians The angle... |
if norm == 'none':
pass
elif norm == 'raise':
if radians > halfpi or radians < -halfpi:
raise ValueError ('illegal latitude of %f radians' % radians)
elif norm == 'wrap':
radians = angcen (radians)
if radians > halfpi:
radians = pi - radians
e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fmtradec (rarad, decrad, precision=2, raseps='::', decseps='::', intersep=' '):
"""Format equatorial coordinates in a single sexagesimal string. Returns a st... |
return (fmthours (rarad, precision=precision + 1, seps=raseps) +
text_type (intersep) +
fmtdeglat (decrad, precision=precision, seps=decseps)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parsehours (hrstr):
"""Parse a string formatted as sexagesimal hours into an angle. This function converts a textual representation of an angle, measured in ... |
hr = _parsesexagesimal (hrstr, 'hours', False)
if hr >= 24:
raise ValueError ('illegal hour specification: ' + hrstr)
return hr * H2R |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parsedeglat (latstr):
"""Parse a latitude formatted as sexagesimal degrees into an angle. This function converts a textual representation of a latitude, meas... |
deg = _parsesexagesimal (latstr, 'latitude', True)
if abs (deg) > 90:
raise ValueError ('illegal latitude specification: ' + latstr)
return deg * D2R |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sphdist (lat1, lon1, lat2, lon2):
"""Calculate the distance between two locations on a sphere. lat1 The latitude of the first location. lon1 The longitude of... |
cd = np.cos (lon2 - lon1)
sd = np.sin (lon2 - lon1)
c2 = np.cos (lat2)
c1 = np.cos (lat1)
s2 = np.sin (lat2)
s1 = np.sin (lat1)
a = np.sqrt ((c2 * sd)**2 + (c1 * s2 - s1 * c2 * cd)**2)
b = s1 * s2 + c1 * c2 * cd
return np.arctan2 (a, b) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sphbear (lat1, lon1, lat2, lon2, tol=1e-15):
"""Calculate the bearing between two locations on a sphere. lat1 The latitude of the first location. lon1 The lo... |
# cross product on outer axis:
ocross = lambda a, b: np.cross (a, b, axisa=0, axisb=0, axisc=0)
# if args have shape S, this has shape (3, S)
v1 = np.asarray ([np.cos (lat1) * np.cos (lon1),
np.cos (lat1) * np.sin (lon1),
np.sin (lat1)])
v2 = np.asarray... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sphofs (lat1, lon1, r, pa, tol=1e-2, rmax=None):
"""Offset from one location on the sphere to another. This function is given a start location, expressed as ... |
if rmax is not None and np.abs (r) > rmax:
raise ValueError ('sphofs radius value %f is too big for '
'our approximation' % r)
lat2 = lat1 + r * np.cos (pa)
lon2 = lon1 + r * np.sin (pa) / np.cos (lat2)
if tol is not None:
s = sphdist (lat1, lon1, lat2, lon2)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parang (hourangle, declination, latitude):
"""Calculate the parallactic angle of a sky position. This computes the parallactic angle of a sky position expres... |
return -np.arctan2 (-np.sin (hourangle),
np.cos (declination) * np.tan (latitude)
- np.sin (declination) * np.cos (hourangle)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gaussian_convolve (maj1, min1, pa1, maj2, min2, pa2):
"""Convolve two Gaussians analytically. Given the shapes of two 2-dimensional Gaussians, this function ... |
c1 = np.cos (pa1)
s1 = np.sin (pa1)
c2 = np.cos (pa2)
s2 = np.sin (pa2)
a = (maj1*c1)**2 + (min1*s1)**2 + (maj2*c2)**2 + (min2*s2)**2
b = (maj1*s1)**2 + (min1*c1)**2 + (maj2*s2)**2 + (min2*c2)**2
g = 2 * ((min1**2 - maj1**2) * s1 * c1 + (min2**2 - maj2**2) * s2 * c2)
s = a + b
t =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gaussian_deconvolve (smaj, smin, spa, bmaj, bmin, bpa):
"""Deconvolve two Gaussians analytically. Given the shapes of 2-dimensional “source” and “beam” Gauss... |
# I've added extra code to ensure ``smaj >= bmaj``, ``smin >= bmin``, and
# increased the coefficient in front of "limit" from 0.1 to 0.5. Feel a
# little wary about that first change.
from numpy import cos, sin, sqrt, min, abs, arctan2
if smaj < bmaj:
smaj = bmaj
if smin < bmin:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_skyfield_data():
"""Load data files used in Skyfield. This will download files from the internet if they haven't been downloaded before. Skyfield downlo... |
import os.path
from astropy.config import paths
from skyfield.api import Loader
cache_dir = os.path.join(paths.get_cache_dir(), 'pwkit')
loader = Loader(cache_dir)
planets = loader('de421.bsp')
ts = loader.timescale()
return planets, ts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_2mass_epoch (tmra, tmdec, debug=False):
"""Given a 2MASS position, look up the epoch when it was observed. This function uses the CDS Vizier web service ... |
import codecs
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
postdata = b'''-mime=csv
-source=2MASS
-out=_q,JD
-c=%.6f %.6f
-c.eq=J2000''' % (tmra * R2D, tmdec * R2D)
jd = None
for line in codecs.getreader('utf-8')(urlopen (_vizurl, pos... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify (self, complain=True):
"""Validate that the attributes are self-consistent. This function does some basic checks of the object attributes to ensure th... |
import sys
if self.ra is None:
raise ValueError ('AstrometryInfo missing "ra"')
if self.dec is None:
raise ValueError ('AstrometryInfo missing "dec"')
if self._partial_info (self.promo_ra, self.promo_dec):
raise ValueError ('partial proper-motion in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fill_from_simbad (self, ident, debug=False):
"""Fill in astrometric information using the Simbad web service. This uses the CDS Simbad web service to look up... |
info = get_simbad_astrometry_info (ident, debug=debug)
posref = 'unknown'
for k, v in six.iteritems (info):
if '~' in v:
continue # no info
if k == 'COO(d;A)':
self.ra = float (v) * D2R
elif k == 'COO(d;D)':
s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fill_from_allwise (self, ident, catalog_ident='II/328/allwise'):
"""Fill in astrometric information from the AllWISE catalog using Astroquery. This uses the ... |
from astroquery.vizier import Vizier
import numpy.ma.core as ma_core
# We should match exactly one table and one row within that table, but
# for robustness we ignore additional results if they happen to
# appear. Strangely, querying for an invalid identifier yields a table
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def backtrace_on_usr1 ():
"""Install a signal handler such that this program prints a Python traceback upon receipt of SIGUSR1. This could be useful for checking... |
import signal
try:
signal.signal (signal.SIGUSR1, _print_backtrace_signal_handler)
except Exception as e:
warn ('failed to set up Python backtraces on SIGUSR1: %s', e) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fork_detached_process ():
"""Fork this process, creating a subprocess detached from the current context. Returns a :class:`pwkit.Holder` instance with inform... |
import os, struct
from .. import Holder
payload = struct.Struct ('L')
info = Holder ()
readfd, writefd = os.pipe ()
pid1 = os.fork ()
if pid1 > 0:
info.whoami = 'original'
info.pipe = os.fdopen (readfd, 'rb')
os.close (writefd)
retcode = os.waitpid (pid1, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pop_option (ident, argv=None):
"""A lame routine for grabbing command-line arguments. Returns a boolean indicating whether the option was present. If it was,... |
if argv is None:
from sys import argv
if len (ident) == 1:
ident = '-' + ident
else:
ident = '--' + ident
found = ident in argv
if found:
argv.remove (ident)
return found |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_usage (docstring, short, stream, exitcode):
"""Print program usage information and exit. :arg str docstring: the program help text This function just pr... |
if stream is None:
from sys import stdout as stream
if not short:
print ('Usage:', docstring.strip (), file=stream)
else:
intext = False
for l in docstring.splitlines ():
if intext:
if not len (l):
break
print ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrong_usage (docstring, *rest):
"""Print a message indicating invalid command-line arguments and exit with an error code. :arg str docstring: the program hel... |
intext = False
if len (rest) == 0:
detail = 'invalid command-line arguments'
elif len (rest) == 1:
detail = rest[0]
else:
detail = rest[0] % tuple (rest[1:])
print ('error:', detail, '\n', file=sys.stderr) # extra NL
show_usage (docstring, True, sys.stderr, 1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.