Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|> assert bs > 0
return bs
@property
def nsites(self):
"""See docs for `Model` abstract base class."""
return self._nsites
@property
def freeparams(self):
"""See docs for `Model` abstract base class."""
return self._freeparams
@property
def mu(self):
"""See docs for `Model` abstract base class."""
return self._mu
@mu.setter
def mu(self, value):
"""Set new `mu` value."""
self._mu = value
def _calculate_correctedF3X4(self):
"""Calculate `phi` based on the empirical `e_pw` values"""
def F(phi):
phi_reshape = phi.reshape((3, N_NT))
functionList = []
stop_frequency = []
<|code_end|>
. Write the next line using the current file imports:
import copy
import six
import abc
import warnings
import numpy
import scipy.misc
import scipy.optimize
import scipy.linalg
import scipy.stats
import scipy.special
import doctest
from phydmslib.numutils import (broadcastMatrixMultiply,
broadcastMatrixVectorMultiply,
broadcastGetCols)
from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION,
CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX,
STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA,
INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT,
CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX,
CODON_NT)
and context from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# ALMOST_ZERO = 1.0e-6
#
# CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int')
#
# STOP_CODON_TO_NT_INDICES = []
#
# N_STOP = 0
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_NT = dict(enumerate('ACGT'))
#
# CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
#
# CODON_TO_AA = []
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool')
, which may include functions, classes, or code. Output only the next line. | for x in range(N_STOP): |
Given the following code snippet before the placeholder: <|code_start|> Element `r` is diagonal of :math:`\mathbf{D_r}` diagonal matrix,
:math:`\mathbf{P_r} = \mathbf{A_r}^{-1} \mathbf{D_r} \mathbf{A_r}`
`A` (`numpy.ndarray` floats, shape `(nsites, N_CODON, N_CODON)`)
Element r is :math:`\mathbf{A_r}` matrix.
`Ainv` (`numpy.ndarray` floats, shape `(nsites, N_CODON, N_CODON)`)
Element r is :math:`\mathbf{A_r}^{-1}` matrix.
`B` (dict)
Keyed by strings in `freeparams`, each value is `numpy.ndarray`
of floats giving `B` matrix for that parameter. The shape
is `(nsites, N_CODON, N_CODON)` except for *eta*, for which
it is `(N_NT - 1, nsites, N_CODON, N_CODON)` with the first
index ranging over each element in `eta`.
"""
# class variables
ALLOWEDPARAMS = ['kappa', 'omega', 'beta', 'eta', 'mu']
_REPORTPARAMS = ['kappa', 'omega', 'beta', 'phi']
_PARAMLIMITS = {'kappa': (0.01, 100.0),
'omega': (1.0e-5, 100.0),
'beta': (1.0e-5, 10),
'eta': (0.01, 0.99),
'phi': (0.001, 0.999),
'pi': (ALMOST_ZERO, 1),
'mu': (1.0e-3, 1.0e3),
}
PARAMTYPES = {'kappa': float,
'omega': float,
'beta': float,
'pi': float,
'mu': float,
<|code_end|>
, predict the next line using imports from the current file:
import copy
import six
import abc
import warnings
import numpy
import scipy.misc
import scipy.optimize
import scipy.linalg
import scipy.stats
import scipy.special
import doctest
from phydmslib.numutils import (broadcastMatrixMultiply,
broadcastMatrixVectorMultiply,
broadcastGetCols)
from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION,
CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX,
STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA,
INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT,
CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX,
CODON_NT)
and context including class names, function names, and sometimes code from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# ALMOST_ZERO = 1.0e-6
#
# CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int')
#
# STOP_CODON_TO_NT_INDICES = []
#
# N_STOP = 0
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_NT = dict(enumerate('ACGT'))
#
# CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
#
# CODON_TO_AA = []
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool')
. Output only the next line. | 'eta': (numpy.ndarray, (N_NT - 1,)), |
Given snippet: <|code_start|> minimum value for {0}, {1}, is equal to or \
larger than the new maximum value, {2}"\
.format(param, value[param][0], value[param][1])
self._PARAMLIMITS = value.copy()
def __init__(self, prefs, kappa=2.0, omega=0.5, beta=1.0, mu=1.0,
phi=numpy.ones(N_NT) / N_NT,
freeparams=('kappa', 'omega', 'beta', 'mu', 'eta')):
"""Initialize an `ExpCM` object.
Args:
`prefs` (list)
List of dicts giving amino-acid preferences for
each site. Each dict keyed by amino acid letter
codes, value is pref > 0 and < 1. Must sum to 1
at each site.
`kappa`, `omega`, `beta`, `mu`, `phi`
Model params described in main class doc string.
`freeparams` (list of strings)
Specifies free parameters.
"""
self._nsites = len(prefs)
assert self.nsites > 0, "No preferences specified"
assert all(map(lambda x: x in self.ALLOWEDPARAMS, freeparams)),\
("Invalid entry in freeparams\nGot: {0}\nAllowed: {1}"
.format(', '.join(freeparams), ', '.join(self.ALLOWEDPARAMS)))
self._freeparams = list(freeparams) # `freeparams` is property
# put prefs in pi
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import copy
import six
import abc
import warnings
import numpy
import scipy.misc
import scipy.optimize
import scipy.linalg
import scipy.stats
import scipy.special
import doctest
from phydmslib.numutils import (broadcastMatrixMultiply,
broadcastMatrixVectorMultiply,
broadcastGetCols)
from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION,
CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX,
STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA,
INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT,
CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX,
CODON_NT)
and context:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# ALMOST_ZERO = 1.0e-6
#
# CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int')
#
# STOP_CODON_TO_NT_INDICES = []
#
# N_STOP = 0
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_NT = dict(enumerate('ACGT'))
#
# CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
#
# CODON_TO_AA = []
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool')
which might include code, classes, or functions. Output only the next line. | self.pi = numpy.ndarray((self.nsites, N_AA), dtype='float') |
Here is a snippet: <|code_start|>
@property
def logprior(self):
"""Is zero, as no prior is defined over this model."""
return 0.0
def dlogprior(self, param):
"""Zero for all `param`, as no prior defined over this model."""
assert param in self.freeparams, "Invalid param: {0}".format(param)
return 0.0
@property
def stationarystate(self):
"""See docs for `Model` abstract base class."""
return self.prx
def dstationarystate(self, param):
"""See docs for `Model` abstract base class."""
return self.dprx[param]
@property
def paramsReport(self):
"""See docs for `Model` abstract base class."""
report = {}
for param in self._REPORTPARAMS:
pvalue = getattr(self, param)
if isinstance(pvalue, float):
report[param] = pvalue
elif isinstance(pvalue, numpy.ndarray) and pvalue.shape == (N_NT,):
for w in range(N_NT - 1):
<|code_end|>
. Write the next line using the current file imports:
import copy
import six
import abc
import warnings
import numpy
import scipy.misc
import scipy.optimize
import scipy.linalg
import scipy.stats
import scipy.special
import doctest
from phydmslib.numutils import (broadcastMatrixMultiply,
broadcastMatrixVectorMultiply,
broadcastGetCols)
from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION,
CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX,
STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA,
INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT,
CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX,
CODON_NT)
and context from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# ALMOST_ZERO = 1.0e-6
#
# CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int')
#
# STOP_CODON_TO_NT_INDICES = []
#
# N_STOP = 0
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_NT = dict(enumerate('ACGT'))
#
# CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
#
# CODON_TO_AA = []
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool')
, which may include functions, classes, or code. Output only the next line. | report['{0}{1}'.format(param, INDEX_TO_NT[w])] = pvalue[w] |
Next line prediction: <|code_start|> for j in range(paramlength):
dM_param[j] = (broadcastMatrixVectorMultiply(self.A,
broadcastGetCols(broadcastMatrixMultiply(self.B[param][j] * V, self.Ainv), tips))) # noqa: E501
if gaps is not None:
if not paramisvec:
dM_param[gaps] = numpy.zeros(N_CODON, dtype='float')
else:
dM_param[:, gaps] = numpy.zeros(N_CODON, dtype='float')
return dM_param
def _eta_from_phi(self):
"""Update `eta` using current `phi`."""
self.eta = numpy.ndarray(N_NT - 1, dtype='float')
etaprod = 1.0
for w in range(N_NT - 1):
self.eta[w] = 1.0 - self.phi[w] / etaprod
etaprod *= self.eta[w]
_checkParam('eta', self.eta, self.PARAMLIMITS, self.PARAMTYPES)
def _update_phi(self):
"""Update `phi` using current `eta`."""
etaprod = 1.0
for w in range(N_NT - 1):
self.phi[w] = etaprod * (1 - self.eta[w])
etaprod *= self.eta[w]
self.phi[N_NT - 1] = etaprod
def _update_Qxy(self):
"""Update `Qxy` using current `kappa` and `phi`."""
for w in range(N_NT):
<|code_end|>
. Use current file imports:
(import copy
import six
import abc
import warnings
import numpy
import scipy.misc
import scipy.optimize
import scipy.linalg
import scipy.stats
import scipy.special
import doctest
from phydmslib.numutils import (broadcastMatrixMultiply,
broadcastMatrixVectorMultiply,
broadcastGetCols)
from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION,
CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX,
STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA,
INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT,
CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX,
CODON_NT))
and context including class names, function names, or small code snippets from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# ALMOST_ZERO = 1.0e-6
#
# CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int')
#
# STOP_CODON_TO_NT_INDICES = []
#
# N_STOP = 0
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_NT = dict(enumerate('ACGT'))
#
# CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
#
# CODON_TO_AA = []
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool')
. Output only the next line. | numpy.copyto(self.Qxy, self.phi[w], where=CODON_NT_MUT[w]) |
Using the snippet: <|code_start|> self.beta, dx=dbeta,
n=1, order=5)
dphi_dbeta_halfdx = scipy.misc.derivative(self._compute_empirical_phi,
self.beta, dx=dbeta / 2,
n=1, order=5)
assert numpy.allclose(self.dphi_dbeta, dphi_dbeta_halfdx, atol=1e-5,
rtol=1e-4), ("The numerical derivative "
"dphi_dbeta differs considerably "
"in value for step dbeta = {0} and "
"a step half that size, giving "
"values of {1} and {2}."
.format(dbeta, self.dphi_dbeta,
dphi_dbeta_halfdx))
def _compute_empirical_phi(self, beta):
"""Returns empirical `phi` at the given value of `beta`.
Does **not** set `phi` attribute, simply returns what
should be value of `phi` given the current `g` and
`pi_codon` attributes, plus the passed value of `beta`.
Note that it uses the passed value of `beta`, **not**
the current `beta` attribute.
Initial guess is current value of `phi` attribute.
"""
def F(phishort):
"""Difference between `g` and expected `g` given `phishort`."""
phifull = numpy.append(phishort, 1 - phishort.sum())
phiprod = numpy.ones(N_CODON, dtype='float')
for w in range(N_NT):
<|code_end|>
, determine the next line of code. You have imports:
import copy
import six
import abc
import warnings
import numpy
import scipy.misc
import scipy.optimize
import scipy.linalg
import scipy.stats
import scipy.special
import doctest
from phydmslib.numutils import (broadcastMatrixMultiply,
broadcastMatrixVectorMultiply,
broadcastGetCols)
from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION,
CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX,
STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA,
INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT,
CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX,
CODON_NT)
and context (class names, function names, or code) available:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# ALMOST_ZERO = 1.0e-6
#
# CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int')
#
# STOP_CODON_TO_NT_INDICES = []
#
# N_STOP = 0
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_NT = dict(enumerate('ACGT'))
#
# CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
#
# CODON_TO_AA = []
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool')
. Output only the next line. | phiprod *= phifull[w]**CODON_NT_COUNT[w] |
Using the snippet: <|code_start|> for w in range(N_NT - 1):
self.eta[w] = 1.0 - self.phi[w] / etaprod
etaprod *= self.eta[w]
_checkParam('eta', self.eta, self.PARAMLIMITS, self.PARAMTYPES)
def _update_phi(self):
"""Update `phi` using current `eta`."""
etaprod = 1.0
for w in range(N_NT - 1):
self.phi[w] = etaprod * (1 - self.eta[w])
etaprod *= self.eta[w]
self.phi[N_NT - 1] = etaprod
def _update_Qxy(self):
"""Update `Qxy` using current `kappa` and `phi`."""
for w in range(N_NT):
numpy.copyto(self.Qxy, self.phi[w], where=CODON_NT_MUT[w])
self.Qxy[CODON_TRANSITION] *= self.kappa
def _update_pi_vars(self):
"""Update variables that depend on `pi`.
These are `pi_codon`, `ln_pi_codon`, `piAx_piAy`, `piAx_piAy_beta`,
`ln_piAx_piAy_beta`.
Update using current `pi` and `beta`.
"""
with numpy.errstate(divide='raise', under='raise', over='raise',
invalid='raise'):
for r in range(self.nsites):
<|code_end|>
, determine the next line of code. You have imports:
import copy
import six
import abc
import warnings
import numpy
import scipy.misc
import scipy.optimize
import scipy.linalg
import scipy.stats
import scipy.special
import doctest
from phydmslib.numutils import (broadcastMatrixMultiply,
broadcastMatrixVectorMultiply,
broadcastGetCols)
from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION,
CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX,
STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA,
INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT,
CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX,
CODON_NT)
and context (class names, function names, or code) available:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# ALMOST_ZERO = 1.0e-6
#
# CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int')
#
# STOP_CODON_TO_NT_INDICES = []
#
# N_STOP = 0
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_NT = dict(enumerate('ACGT'))
#
# CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
#
# CODON_TO_AA = []
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool')
. Output only the next line. | self.pi_codon[r] = self.pi[r][CODON_TO_AA] |
Here is a snippet: <|code_start|>
Args:
`prefs` (list)
List of dicts giving amino-acid preferences for
each site. Each dict keyed by amino acid letter
codes, value is pref > 0 and < 1. Must sum to 1
at each site.
`kappa`, `omega`, `beta`, `mu`, `phi`
Model params described in main class doc string.
`freeparams` (list of strings)
Specifies free parameters.
"""
self._nsites = len(prefs)
assert self.nsites > 0, "No preferences specified"
assert all(map(lambda x: x in self.ALLOWEDPARAMS, freeparams)),\
("Invalid entry in freeparams\nGot: {0}\nAllowed: {1}"
.format(', '.join(freeparams), ', '.join(self.ALLOWEDPARAMS)))
self._freeparams = list(freeparams) # `freeparams` is property
# put prefs in pi
self.pi = numpy.ndarray((self.nsites, N_AA), dtype='float')
assert (isinstance(prefs, list) and
all((isinstance(x, dict) for x in prefs))),\
"prefs is not a list of dicts"
for r in range(self.nsites):
assert set(prefs[r].keys()) == set(AA_TO_INDEX.keys()),\
"prefs not keyed by amino acids for site {0}".format(r)
assert abs(1 - sum(prefs[r].values())) <= ALMOST_ZERO,\
"prefs don't sum to one for site {0}".format(r)
<|code_end|>
. Write the next line using the current file imports:
import copy
import six
import abc
import warnings
import numpy
import scipy.misc
import scipy.optimize
import scipy.linalg
import scipy.stats
import scipy.special
import doctest
from phydmslib.numutils import (broadcastMatrixMultiply,
broadcastMatrixVectorMultiply,
broadcastGetCols)
from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION,
CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX,
STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA,
INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT,
CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX,
CODON_NT)
and context from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# ALMOST_ZERO = 1.0e-6
#
# CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int')
#
# STOP_CODON_TO_NT_INDICES = []
#
# N_STOP = 0
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_NT = dict(enumerate('ACGT'))
#
# CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
#
# CODON_TO_AA = []
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool')
, which may include functions, classes, or code. Output only the next line. | for (a, aa) in INDEX_TO_AA.items(): |
Here is a snippet: <|code_start|> def __init__(self, prefs, kappa=2.0, omega=0.5, beta=1.0, mu=1.0,
phi=numpy.ones(N_NT) / N_NT,
freeparams=('kappa', 'omega', 'beta', 'mu', 'eta')):
"""Initialize an `ExpCM` object.
Args:
`prefs` (list)
List of dicts giving amino-acid preferences for
each site. Each dict keyed by amino acid letter
codes, value is pref > 0 and < 1. Must sum to 1
at each site.
`kappa`, `omega`, `beta`, `mu`, `phi`
Model params described in main class doc string.
`freeparams` (list of strings)
Specifies free parameters.
"""
self._nsites = len(prefs)
assert self.nsites > 0, "No preferences specified"
assert all(map(lambda x: x in self.ALLOWEDPARAMS, freeparams)),\
("Invalid entry in freeparams\nGot: {0}\nAllowed: {1}"
.format(', '.join(freeparams), ', '.join(self.ALLOWEDPARAMS)))
self._freeparams = list(freeparams) # `freeparams` is property
# put prefs in pi
self.pi = numpy.ndarray((self.nsites, N_AA), dtype='float')
assert (isinstance(prefs, list) and
all((isinstance(x, dict) for x in prefs))),\
"prefs is not a list of dicts"
for r in range(self.nsites):
<|code_end|>
. Write the next line using the current file imports:
import copy
import six
import abc
import warnings
import numpy
import scipy.misc
import scipy.optimize
import scipy.linalg
import scipy.stats
import scipy.special
import doctest
from phydmslib.numutils import (broadcastMatrixMultiply,
broadcastMatrixVectorMultiply,
broadcastGetCols)
from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION,
CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX,
STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA,
INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT,
CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX,
CODON_NT)
and context from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# ALMOST_ZERO = 1.0e-6
#
# CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int')
#
# STOP_CODON_TO_NT_INDICES = []
#
# N_STOP = 0
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_NT = dict(enumerate('ACGT'))
#
# CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
#
# CODON_TO_AA = []
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool')
, which may include functions, classes, or code. Output only the next line. | assert set(prefs[r].keys()) == set(AA_TO_INDEX.keys()),\ |
Given the code snippet: <|code_start|> where=CODON_NONSYN)
def _update_Prxy(self):
"""Update `Prxy` using current `Frxy` and `Qxy`."""
self.Prxy = self.Frxy * self.Qxy
_fill_diagonals(self.Prxy, self._diag_indices)
def _update_Prxy_diag(self):
"""Update `D`, `A`, `Ainv` from `Prxy`, `prx`."""
for r in range(self.nsites):
pr_half = self.prx[r]**0.5
pr_neghalf = self.prx[r]**-0.5
# symm_pr = numpy.dot(numpy.diag(pr_half), numpy.dot(self.Prxy[r],
# numpy.diag(pr_neghalf)))
symm_pr = ((pr_half * (self.Prxy[r] * pr_neghalf).transpose())
.transpose())
# assert numpy.allclose(symm_pr, symm_pr.transpose())
(evals, evecs) = scipy.linalg.eigh(symm_pr)
# assert numpy.allclose(scipy.linalg.inv(evecs), evecs.transpose())
# assert numpy.allclose(symm_pr, numpy.dot(evecs,
# numpy.dot(numpy.diag(evals), evecs.transpose())))
self.D[r] = evals
self.Ainv[r] = evecs.transpose() * pr_half
self.A[r] = (pr_neghalf * evecs.transpose()).transpose()
def _update_prx(self):
"""Update `prx` from `phi`, `pi_codon`, and `beta`."""
qx = numpy.ones(N_CODON, dtype='float')
for j in range(3):
for w in range(N_NT):
<|code_end|>
, generate the next line using the imports in this file:
import copy
import six
import abc
import warnings
import numpy
import scipy.misc
import scipy.optimize
import scipy.linalg
import scipy.stats
import scipy.special
import doctest
from phydmslib.numutils import (broadcastMatrixMultiply,
broadcastMatrixVectorMultiply,
broadcastGetCols)
from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION,
CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX,
STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA,
INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT,
CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX,
CODON_NT)
and context (functions, classes, or occasionally code) from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# ALMOST_ZERO = 1.0e-6
#
# CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int')
#
# STOP_CODON_TO_NT_INDICES = []
#
# N_STOP = 0
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_NT = dict(enumerate('ACGT'))
#
# CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
#
# CODON_TO_AA = []
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool')
. Output only the next line. | qx[CODON_NT[j][w]] *= self.phi[w] |
Predict the next line for this snippet: <|code_start|> kappa=self.kappa,
omega=self.omega,
mu=10.0,
phi=self.phi)
treefile = os.path.abspath(
os.path.join(os.path.dirname(__file__),
"./NP_data/NP_tree.newick"))
self.tree = Bio.Phylo.read(treefile, "newick")
self.tree.root_at_midpoint()
# simulate alignment using realmodel
evolver = pyvolve.Evolver(
partitions=phydmslib.simulate.pyvolvePartitions(self.realmodel),
tree=pyvolve.read_tree(file=treefile))
alignmentfile = "_temp_fitprefs_simulatedalignment.fasta"
info = "_temp_info.txt"
rates = "_temp_ratefile.txt"
evolver(seqfile=alignmentfile, infofile=info, ratefile=rates)
self.alignment = phydmslib.file_io.ReadCodonAlignment(alignmentfile,
True)
assert len(self.alignment[0][1]) == nsites * 3
for f in [alignmentfile, info, rates]:
os.remove(f)
self.codoncounts = {r: {INDEX_TO_CODON[c]: 0 for c in range(N_CODON)}
for r in range(nsites)}
self.aacounts = {r: {a: 0 for a in range(N_AA)} for r in range(nsites)}
for (_head, seq) in self.alignment:
for r, i in enumerate(range(0, nsites+1, 3)):
self.codoncounts[r][seq[i: i+3]] += 1
<|code_end|>
with the help of current file imports:
import random
import unittest
import copy
import os
import phydmslib.models
import phydmslib.file_io
import phydmslib.simulate
import phydmslib.treelikelihood
import pyvolve
import numpy
import Bio
from phydmslib.constants import (CODON_TO_INDEX, CODON_TO_AA, N_NT, N_AA,
INDEX_TO_CODON, AA_TO_INDEX, N_CODON)
and context from other files:
# Path: phydmslib/constants.py
# CODON_TO_INDEX = {}
#
# CODON_TO_AA = []
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_CODON = {}
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_CODON = len(CODON_TO_INDEX)
, which may contain function names, class names, or code. Output only the next line. | self.aacounts[r][CODON_TO_AA[CODON_TO_INDEX[seq[i: i+3]]]] += 1 |
Given the code snippet: <|code_start|> kappa=self.kappa,
omega=self.omega,
mu=10.0,
phi=self.phi)
treefile = os.path.abspath(
os.path.join(os.path.dirname(__file__),
"./NP_data/NP_tree.newick"))
self.tree = Bio.Phylo.read(treefile, "newick")
self.tree.root_at_midpoint()
# simulate alignment using realmodel
evolver = pyvolve.Evolver(
partitions=phydmslib.simulate.pyvolvePartitions(self.realmodel),
tree=pyvolve.read_tree(file=treefile))
alignmentfile = "_temp_fitprefs_simulatedalignment.fasta"
info = "_temp_info.txt"
rates = "_temp_ratefile.txt"
evolver(seqfile=alignmentfile, infofile=info, ratefile=rates)
self.alignment = phydmslib.file_io.ReadCodonAlignment(alignmentfile,
True)
assert len(self.alignment[0][1]) == nsites * 3
for f in [alignmentfile, info, rates]:
os.remove(f)
self.codoncounts = {r: {INDEX_TO_CODON[c]: 0 for c in range(N_CODON)}
for r in range(nsites)}
self.aacounts = {r: {a: 0 for a in range(N_AA)} for r in range(nsites)}
for (_head, seq) in self.alignment:
for r, i in enumerate(range(0, nsites+1, 3)):
self.codoncounts[r][seq[i: i+3]] += 1
<|code_end|>
, generate the next line using the imports in this file:
import random
import unittest
import copy
import os
import phydmslib.models
import phydmslib.file_io
import phydmslib.simulate
import phydmslib.treelikelihood
import pyvolve
import numpy
import Bio
from phydmslib.constants import (CODON_TO_INDEX, CODON_TO_AA, N_NT, N_AA,
INDEX_TO_CODON, AA_TO_INDEX, N_CODON)
and context (functions, classes, or occasionally code) from other files:
# Path: phydmslib/constants.py
# CODON_TO_INDEX = {}
#
# CODON_TO_AA = []
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_CODON = {}
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_CODON = len(CODON_TO_INDEX)
. Output only the next line. | self.aacounts[r][CODON_TO_AA[CODON_TO_INDEX[seq[i: i+3]]]] += 1 |
Predict the next line after this snippet: <|code_start|>Written by Jesse Bloom.
"""
class test_TreeLikelihood_ExpCM_fitprefs(unittest.TestCase):
"""Test `ExpCM_fitprefs` in `TreeLikelihood`."""
MODEL = phydmslib.models.ExpCM_fitprefs
def setUp(self):
"""Set up for tests."""
numpy.random.seed(1)
random.seed(1)
nsites = 1
minpref = 0.001
self.prefs = []
self.realprefs = []
for _r in range(nsites):
rprefs = numpy.random.dirichlet([0.5] * N_AA)
rprefs[rprefs < minpref] = minpref
rprefs /= rprefs.sum()
self.prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
numpy.random.shuffle(rprefs)
self.realprefs.append(dict(zip(sorted(AA_TO_INDEX.keys()),
rprefs)))
self.kappa = 3.0
self.omega = 3.0
<|code_end|>
using the current file's imports:
import random
import unittest
import copy
import os
import phydmslib.models
import phydmslib.file_io
import phydmslib.simulate
import phydmslib.treelikelihood
import pyvolve
import numpy
import Bio
from phydmslib.constants import (CODON_TO_INDEX, CODON_TO_AA, N_NT, N_AA,
INDEX_TO_CODON, AA_TO_INDEX, N_CODON)
and any relevant context from other files:
# Path: phydmslib/constants.py
# CODON_TO_INDEX = {}
#
# CODON_TO_AA = []
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_CODON = {}
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_CODON = len(CODON_TO_INDEX)
. Output only the next line. | self.phi = numpy.random.dirichlet([5] * N_NT) |
Predict the next line for this snippet: <|code_start|>"""Tests `TreeLikelihood` with `ExpCM_fitprefs` and `ExpCM_fitprefs2`.
Written by Jesse Bloom.
"""
class test_TreeLikelihood_ExpCM_fitprefs(unittest.TestCase):
"""Test `ExpCM_fitprefs` in `TreeLikelihood`."""
MODEL = phydmslib.models.ExpCM_fitprefs
def setUp(self):
"""Set up for tests."""
numpy.random.seed(1)
random.seed(1)
nsites = 1
minpref = 0.001
self.prefs = []
self.realprefs = []
for _r in range(nsites):
<|code_end|>
with the help of current file imports:
import random
import unittest
import copy
import os
import phydmslib.models
import phydmslib.file_io
import phydmslib.simulate
import phydmslib.treelikelihood
import pyvolve
import numpy
import Bio
from phydmslib.constants import (CODON_TO_INDEX, CODON_TO_AA, N_NT, N_AA,
INDEX_TO_CODON, AA_TO_INDEX, N_CODON)
and context from other files:
# Path: phydmslib/constants.py
# CODON_TO_INDEX = {}
#
# CODON_TO_AA = []
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_CODON = {}
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_CODON = len(CODON_TO_INDEX)
, which may contain function names, class names, or code. Output only the next line. | rprefs = numpy.random.dirichlet([0.5] * N_AA) |
Given the code snippet: <|code_start|> self.model = self.MODEL(self.prefs,
prior=None,
kappa=self.kappa,
omega=self.omega,
phi=self.phi)
self.realmodel = phydmslib.models.ExpCM(self.realprefs,
kappa=self.kappa,
omega=self.omega,
mu=10.0,
phi=self.phi)
treefile = os.path.abspath(
os.path.join(os.path.dirname(__file__),
"./NP_data/NP_tree.newick"))
self.tree = Bio.Phylo.read(treefile, "newick")
self.tree.root_at_midpoint()
# simulate alignment using realmodel
evolver = pyvolve.Evolver(
partitions=phydmslib.simulate.pyvolvePartitions(self.realmodel),
tree=pyvolve.read_tree(file=treefile))
alignmentfile = "_temp_fitprefs_simulatedalignment.fasta"
info = "_temp_info.txt"
rates = "_temp_ratefile.txt"
evolver(seqfile=alignmentfile, infofile=info, ratefile=rates)
self.alignment = phydmslib.file_io.ReadCodonAlignment(alignmentfile,
True)
assert len(self.alignment[0][1]) == nsites * 3
for f in [alignmentfile, info, rates]:
os.remove(f)
<|code_end|>
, generate the next line using the imports in this file:
import random
import unittest
import copy
import os
import phydmslib.models
import phydmslib.file_io
import phydmslib.simulate
import phydmslib.treelikelihood
import pyvolve
import numpy
import Bio
from phydmslib.constants import (CODON_TO_INDEX, CODON_TO_AA, N_NT, N_AA,
INDEX_TO_CODON, AA_TO_INDEX, N_CODON)
and context (functions, classes, or occasionally code) from other files:
# Path: phydmslib/constants.py
# CODON_TO_INDEX = {}
#
# CODON_TO_AA = []
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_CODON = {}
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_CODON = len(CODON_TO_INDEX)
. Output only the next line. | self.codoncounts = {r: {INDEX_TO_CODON[c]: 0 for c in range(N_CODON)} |
Continue the code snippet: <|code_start|>"""Tests `TreeLikelihood` with `ExpCM_fitprefs` and `ExpCM_fitprefs2`.
Written by Jesse Bloom.
"""
class test_TreeLikelihood_ExpCM_fitprefs(unittest.TestCase):
"""Test `ExpCM_fitprefs` in `TreeLikelihood`."""
MODEL = phydmslib.models.ExpCM_fitprefs
def setUp(self):
"""Set up for tests."""
numpy.random.seed(1)
random.seed(1)
nsites = 1
minpref = 0.001
self.prefs = []
self.realprefs = []
for _r in range(nsites):
rprefs = numpy.random.dirichlet([0.5] * N_AA)
rprefs[rprefs < minpref] = minpref
rprefs /= rprefs.sum()
<|code_end|>
. Use current file imports:
import random
import unittest
import copy
import os
import phydmslib.models
import phydmslib.file_io
import phydmslib.simulate
import phydmslib.treelikelihood
import pyvolve
import numpy
import Bio
from phydmslib.constants import (CODON_TO_INDEX, CODON_TO_AA, N_NT, N_AA,
INDEX_TO_CODON, AA_TO_INDEX, N_CODON)
and context (classes, functions, or code) from other files:
# Path: phydmslib/constants.py
# CODON_TO_INDEX = {}
#
# CODON_TO_AA = []
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_CODON = {}
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_CODON = len(CODON_TO_INDEX)
. Output only the next line. | self.prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) |
Next line prediction: <|code_start|> self.model = self.MODEL(self.prefs,
prior=None,
kappa=self.kappa,
omega=self.omega,
phi=self.phi)
self.realmodel = phydmslib.models.ExpCM(self.realprefs,
kappa=self.kappa,
omega=self.omega,
mu=10.0,
phi=self.phi)
treefile = os.path.abspath(
os.path.join(os.path.dirname(__file__),
"./NP_data/NP_tree.newick"))
self.tree = Bio.Phylo.read(treefile, "newick")
self.tree.root_at_midpoint()
# simulate alignment using realmodel
evolver = pyvolve.Evolver(
partitions=phydmslib.simulate.pyvolvePartitions(self.realmodel),
tree=pyvolve.read_tree(file=treefile))
alignmentfile = "_temp_fitprefs_simulatedalignment.fasta"
info = "_temp_info.txt"
rates = "_temp_ratefile.txt"
evolver(seqfile=alignmentfile, infofile=info, ratefile=rates)
self.alignment = phydmslib.file_io.ReadCodonAlignment(alignmentfile,
True)
assert len(self.alignment[0][1]) == nsites * 3
for f in [alignmentfile, info, rates]:
os.remove(f)
<|code_end|>
. Use current file imports:
(import random
import unittest
import copy
import os
import phydmslib.models
import phydmslib.file_io
import phydmslib.simulate
import phydmslib.treelikelihood
import pyvolve
import numpy
import Bio
from phydmslib.constants import (CODON_TO_INDEX, CODON_TO_AA, N_NT, N_AA,
INDEX_TO_CODON, AA_TO_INDEX, N_CODON))
and context including class names, function names, or small code snippets from other files:
# Path: phydmslib/constants.py
# CODON_TO_INDEX = {}
#
# CODON_TO_AA = []
#
# N_NT = len(INDEX_TO_NT)
#
# N_AA = len(INDEX_TO_AA)
#
# INDEX_TO_CODON = {}
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_CODON = len(CODON_TO_INDEX)
. Output only the next line. | self.codoncounts = {r: {INDEX_TO_CODON[c]: 0 for c in range(N_CODON)} |
Using the snippet: <|code_start|> self.assertTrue(numpy.allclose(kappa, self.expcm.kappa))
self.assertTrue(numpy.allclose(beta, self.expcm.beta))
self.assertTrue(
numpy.allclose(
numpy.repeat(1.0, self.nsites),
self.expcm.stationarystate.sum(axis=1)))
# now check ExpCM attributes / derivates, updating several times
for _update in range(2):
self.params = {
"omega": random.uniform(*self.expcm.PARAMLIMITS["omega"]),
"kappa": random.uniform(*self.expcm.PARAMLIMITS["kappa"]),
"beta": random.uniform(0.5, 2.5),
"eta": numpy.array(
[random.uniform(*self.expcm.PARAMLIMITS["eta"])
for i in range(N_NT - 1)]),
"mu": random.uniform(0.05, 3.0)}
self.expcm.updateParams(self.params)
self.check_ExpCM_attributes()
self.check_ExpCM_derivatives()
self.check_ExpCM_matrix_exponentials()
def check_ExpCM_attributes(self):
"""Make sure `ExpCM` has the expected attribute values."""
self.assertEqual(self.nsites, self.expcm.nsites)
# make sure Prxy has rows summing to zero
self.assertFalse(numpy.isnan(self.expcm.Prxy).any())
self.assertFalse(numpy.isinf(self.expcm.Prxy).any())
<|code_end|>
, determine the next line of code. You have imports:
import random
import unittest
import numpy
import scipy.linalg
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import (N_CODON, NT_TO_INDEX, CODON_TO_AA,
INDEX_TO_CODON, INDEX_TO_AA, CODON_SINGLEMUT,
CODON_TRANSITION, CODON_NONSYN, N_NT,
AA_TO_INDEX, N_AA)
and context (class names, function names, or code) available:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()}
#
# CODON_TO_AA = []
#
# INDEX_TO_CODON = {}
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
. Output only the next line. | diag = numpy.eye(N_CODON, dtype="bool") |
Continue the code snippet: <|code_start|> self.expcm.Prxy[r])))
if r > 0:
self.assertFalse(
numpy.allclose(
0,
numpy.dot(self.expcm.prx[r], self.expcm.Prxy[r - 1])))
def check_ExpCM_derivatives(self):
"""Use `sympy` to check values & derivatives of `ExpCM` attributes."""
(Prxy, Qxy, phiw, beta, omega,
eta0, eta1, eta2, kappa) = sympy.symbols("Prxy, Qxy, phiw, beta, "
"omega, eta0, eta1, eta2, "
"kappa")
values = {"beta": self.params["beta"],
"omega": self.params["omega"],
"kappa": self.params["kappa"],
"eta0": self.params["eta"][0],
"eta1": self.params["eta"][1],
"eta2": self.params["eta"][2]}
# check Prxy
for r in range(self.nsites):
for x in range(N_CODON):
pirAx = self.prefs[r][INDEX_TO_AA[CODON_TO_AA[x]]]
for y in [yy for yy in range(N_CODON) if yy != x]:
pirAy = self.prefs[r][INDEX_TO_AA[CODON_TO_AA[y]]]
if not CODON_SINGLEMUT[x][y]:
Prxy = 0
else:
<|code_end|>
. Use current file imports:
import random
import unittest
import numpy
import scipy.linalg
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import (N_CODON, NT_TO_INDEX, CODON_TO_AA,
INDEX_TO_CODON, INDEX_TO_AA, CODON_SINGLEMUT,
CODON_TRANSITION, CODON_NONSYN, N_NT,
AA_TO_INDEX, N_AA)
and context (classes, functions, or code) from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()}
#
# CODON_TO_AA = []
#
# INDEX_TO_CODON = {}
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
. Output only the next line. | w = NT_TO_INDEX[ |
Given the following code snippet before the placeholder: <|code_start|> self.assertTrue(numpy.allclose(1, self.expcm.prx[r].sum()))
# prx is eigenvector or Prxy for the same r, but not different r
for r in range(self.nsites):
self.assertTrue(
numpy.allclose(0, numpy.dot(self.expcm.prx[r],
self.expcm.Prxy[r])))
if r > 0:
self.assertFalse(
numpy.allclose(
0,
numpy.dot(self.expcm.prx[r], self.expcm.Prxy[r - 1])))
def check_ExpCM_derivatives(self):
"""Use `sympy` to check values & derivatives of `ExpCM` attributes."""
(Prxy, Qxy, phiw, beta, omega,
eta0, eta1, eta2, kappa) = sympy.symbols("Prxy, Qxy, phiw, beta, "
"omega, eta0, eta1, eta2, "
"kappa")
values = {"beta": self.params["beta"],
"omega": self.params["omega"],
"kappa": self.params["kappa"],
"eta0": self.params["eta"][0],
"eta1": self.params["eta"][1],
"eta2": self.params["eta"][2]}
# check Prxy
for r in range(self.nsites):
for x in range(N_CODON):
<|code_end|>
, predict the next line using imports from the current file:
import random
import unittest
import numpy
import scipy.linalg
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import (N_CODON, NT_TO_INDEX, CODON_TO_AA,
INDEX_TO_CODON, INDEX_TO_AA, CODON_SINGLEMUT,
CODON_TRANSITION, CODON_NONSYN, N_NT,
AA_TO_INDEX, N_AA)
and context including class names, function names, and sometimes code from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()}
#
# CODON_TO_AA = []
#
# INDEX_TO_CODON = {}
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
. Output only the next line. | pirAx = self.prefs[r][INDEX_TO_AA[CODON_TO_AA[x]]] |
Here is a snippet: <|code_start|> if r > 0:
self.assertFalse(
numpy.allclose(
0,
numpy.dot(self.expcm.prx[r], self.expcm.Prxy[r - 1])))
def check_ExpCM_derivatives(self):
"""Use `sympy` to check values & derivatives of `ExpCM` attributes."""
(Prxy, Qxy, phiw, beta, omega,
eta0, eta1, eta2, kappa) = sympy.symbols("Prxy, Qxy, phiw, beta, "
"omega, eta0, eta1, eta2, "
"kappa")
values = {"beta": self.params["beta"],
"omega": self.params["omega"],
"kappa": self.params["kappa"],
"eta0": self.params["eta"][0],
"eta1": self.params["eta"][1],
"eta2": self.params["eta"][2]}
# check Prxy
for r in range(self.nsites):
for x in range(N_CODON):
pirAx = self.prefs[r][INDEX_TO_AA[CODON_TO_AA[x]]]
for y in [yy for yy in range(N_CODON) if yy != x]:
pirAy = self.prefs[r][INDEX_TO_AA[CODON_TO_AA[y]]]
if not CODON_SINGLEMUT[x][y]:
Prxy = 0
else:
w = NT_TO_INDEX[
<|code_end|>
. Write the next line using the current file imports:
import random
import unittest
import numpy
import scipy.linalg
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import (N_CODON, NT_TO_INDEX, CODON_TO_AA,
INDEX_TO_CODON, INDEX_TO_AA, CODON_SINGLEMUT,
CODON_TRANSITION, CODON_NONSYN, N_NT,
AA_TO_INDEX, N_AA)
and context from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()}
#
# CODON_TO_AA = []
#
# INDEX_TO_CODON = {}
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
, which may include functions, classes, or code. Output only the next line. | [ynt for (xnt, ynt) in zip(INDEX_TO_CODON[x], |
Continue the code snippet: <|code_start|> self.assertTrue(numpy.allclose(1, self.expcm.prx[r].sum()))
# prx is eigenvector or Prxy for the same r, but not different r
for r in range(self.nsites):
self.assertTrue(
numpy.allclose(0, numpy.dot(self.expcm.prx[r],
self.expcm.Prxy[r])))
if r > 0:
self.assertFalse(
numpy.allclose(
0,
numpy.dot(self.expcm.prx[r], self.expcm.Prxy[r - 1])))
def check_ExpCM_derivatives(self):
"""Use `sympy` to check values & derivatives of `ExpCM` attributes."""
(Prxy, Qxy, phiw, beta, omega,
eta0, eta1, eta2, kappa) = sympy.symbols("Prxy, Qxy, phiw, beta, "
"omega, eta0, eta1, eta2, "
"kappa")
values = {"beta": self.params["beta"],
"omega": self.params["omega"],
"kappa": self.params["kappa"],
"eta0": self.params["eta"][0],
"eta1": self.params["eta"][1],
"eta2": self.params["eta"][2]}
# check Prxy
for r in range(self.nsites):
for x in range(N_CODON):
<|code_end|>
. Use current file imports:
import random
import unittest
import numpy
import scipy.linalg
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import (N_CODON, NT_TO_INDEX, CODON_TO_AA,
INDEX_TO_CODON, INDEX_TO_AA, CODON_SINGLEMUT,
CODON_TRANSITION, CODON_NONSYN, N_NT,
AA_TO_INDEX, N_AA)
and context (classes, functions, or code) from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()}
#
# CODON_TO_AA = []
#
# INDEX_TO_CODON = {}
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
. Output only the next line. | pirAx = self.prefs[r][INDEX_TO_AA[CODON_TO_AA[x]]] |
Using the snippet: <|code_start|> for r in range(self.nsites):
self.assertTrue(
numpy.allclose(0, numpy.dot(self.expcm.prx[r],
self.expcm.Prxy[r])))
if r > 0:
self.assertFalse(
numpy.allclose(
0,
numpy.dot(self.expcm.prx[r], self.expcm.Prxy[r - 1])))
def check_ExpCM_derivatives(self):
"""Use `sympy` to check values & derivatives of `ExpCM` attributes."""
(Prxy, Qxy, phiw, beta, omega,
eta0, eta1, eta2, kappa) = sympy.symbols("Prxy, Qxy, phiw, beta, "
"omega, eta0, eta1, eta2, "
"kappa")
values = {"beta": self.params["beta"],
"omega": self.params["omega"],
"kappa": self.params["kappa"],
"eta0": self.params["eta"][0],
"eta1": self.params["eta"][1],
"eta2": self.params["eta"][2]}
# check Prxy
for r in range(self.nsites):
for x in range(N_CODON):
pirAx = self.prefs[r][INDEX_TO_AA[CODON_TO_AA[x]]]
for y in [yy for yy in range(N_CODON) if yy != x]:
pirAy = self.prefs[r][INDEX_TO_AA[CODON_TO_AA[y]]]
<|code_end|>
, determine the next line of code. You have imports:
import random
import unittest
import numpy
import scipy.linalg
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import (N_CODON, NT_TO_INDEX, CODON_TO_AA,
INDEX_TO_CODON, INDEX_TO_AA, CODON_SINGLEMUT,
CODON_TRANSITION, CODON_NONSYN, N_NT,
AA_TO_INDEX, N_AA)
and context (class names, function names, or code) available:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()}
#
# CODON_TO_AA = []
#
# INDEX_TO_CODON = {}
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
. Output only the next line. | if not CODON_SINGLEMUT[x][y]: |
Given the code snippet: <|code_start|> "eta0": self.params["eta"][0],
"eta1": self.params["eta"][1],
"eta2": self.params["eta"][2]}
# check Prxy
for r in range(self.nsites):
for x in range(N_CODON):
pirAx = self.prefs[r][INDEX_TO_AA[CODON_TO_AA[x]]]
for y in [yy for yy in range(N_CODON) if yy != x]:
pirAy = self.prefs[r][INDEX_TO_AA[CODON_TO_AA[y]]]
if not CODON_SINGLEMUT[x][y]:
Prxy = 0
else:
w = NT_TO_INDEX[
[ynt for (xnt, ynt) in zip(INDEX_TO_CODON[x],
INDEX_TO_CODON[y])
if xnt != ynt][0]]
if w == 0:
phiw = 1 - eta0
elif w == 1:
phiw = eta0 * (1 - eta1)
elif w == 2:
phiw = eta0 * eta1 * (1 - eta2)
elif w == 3:
phiw = eta0 * eta1 * eta2
else:
raise ValueError("Invalid w")
self.assertTrue(
numpy.allclose(float(phiw.subs(values)),
self.expcm.phi[w]))
<|code_end|>
, generate the next line using the imports in this file:
import random
import unittest
import numpy
import scipy.linalg
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import (N_CODON, NT_TO_INDEX, CODON_TO_AA,
INDEX_TO_CODON, INDEX_TO_AA, CODON_SINGLEMUT,
CODON_TRANSITION, CODON_NONSYN, N_NT,
AA_TO_INDEX, N_AA)
and context (functions, classes, or occasionally code) from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()}
#
# CODON_TO_AA = []
#
# INDEX_TO_CODON = {}
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
. Output only the next line. | if CODON_TRANSITION[x][y]: |
Predict the next line after this snippet: <|code_start|> pirAx = self.prefs[r][INDEX_TO_AA[CODON_TO_AA[x]]]
for y in [yy for yy in range(N_CODON) if yy != x]:
pirAy = self.prefs[r][INDEX_TO_AA[CODON_TO_AA[y]]]
if not CODON_SINGLEMUT[x][y]:
Prxy = 0
else:
w = NT_TO_INDEX[
[ynt for (xnt, ynt) in zip(INDEX_TO_CODON[x],
INDEX_TO_CODON[y])
if xnt != ynt][0]]
if w == 0:
phiw = 1 - eta0
elif w == 1:
phiw = eta0 * (1 - eta1)
elif w == 2:
phiw = eta0 * eta1 * (1 - eta2)
elif w == 3:
phiw = eta0 * eta1 * eta2
else:
raise ValueError("Invalid w")
self.assertTrue(
numpy.allclose(float(phiw.subs(values)),
self.expcm.phi[w]))
if CODON_TRANSITION[x][y]:
Qxy = kappa * phiw
else:
Qxy = phiw
self.assertTrue(
numpy.allclose(
float(Qxy.subs(values)), self.expcm.Qxy[x][y]))
<|code_end|>
using the current file's imports:
import random
import unittest
import numpy
import scipy.linalg
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import (N_CODON, NT_TO_INDEX, CODON_TO_AA,
INDEX_TO_CODON, INDEX_TO_AA, CODON_SINGLEMUT,
CODON_TRANSITION, CODON_NONSYN, N_NT,
AA_TO_INDEX, N_AA)
and any relevant context from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()}
#
# CODON_TO_AA = []
#
# INDEX_TO_CODON = {}
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
. Output only the next line. | if CODON_NONSYN[x][y]: |
Given snippet: <|code_start|>"""Tests `phydmslib.models.ExpCM` class.
Written by Jesse Bloom.
Uses `sympy` to make sure attributes and derivatives of attributes
are correct for `ExpCM` implemented in `phydmslib.models`.
"""
class testExpCM(unittest.TestCase):
"""Tests ``ExpCM`` model."""
def test_ExpCM(self):
"""Initialize `ExpCM`, test values, update, test again."""
# create preferences
random.seed(1)
numpy.random.seed(1)
self.nsites = 2
self.prefs = []
minpref = 0.01
for _r in range(self.nsites):
rprefs = numpy.random.dirichlet([0.5] * N_AA)
rprefs[rprefs < minpref] = minpref
rprefs /= rprefs.sum()
self.prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
# create initial ExpCM
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import random
import unittest
import numpy
import scipy.linalg
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import (N_CODON, NT_TO_INDEX, CODON_TO_AA,
INDEX_TO_CODON, INDEX_TO_AA, CODON_SINGLEMUT,
CODON_TRANSITION, CODON_NONSYN, N_NT,
AA_TO_INDEX, N_AA)
and context:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()}
#
# CODON_TO_AA = []
#
# INDEX_TO_CODON = {}
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
which might include code, classes, or functions. Output only the next line. | phi = numpy.random.dirichlet([2] * N_NT) |
Predict the next line after this snippet: <|code_start|>"""Tests `phydmslib.models.ExpCM` class.
Written by Jesse Bloom.
Uses `sympy` to make sure attributes and derivatives of attributes
are correct for `ExpCM` implemented in `phydmslib.models`.
"""
class testExpCM(unittest.TestCase):
"""Tests ``ExpCM`` model."""
def test_ExpCM(self):
"""Initialize `ExpCM`, test values, update, test again."""
# create preferences
random.seed(1)
numpy.random.seed(1)
self.nsites = 2
self.prefs = []
minpref = 0.01
for _r in range(self.nsites):
rprefs = numpy.random.dirichlet([0.5] * N_AA)
rprefs[rprefs < minpref] = minpref
rprefs /= rprefs.sum()
<|code_end|>
using the current file's imports:
import random
import unittest
import numpy
import scipy.linalg
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import (N_CODON, NT_TO_INDEX, CODON_TO_AA,
INDEX_TO_CODON, INDEX_TO_AA, CODON_SINGLEMUT,
CODON_TRANSITION, CODON_NONSYN, N_NT,
AA_TO_INDEX, N_AA)
and any relevant context from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()}
#
# CODON_TO_AA = []
#
# INDEX_TO_CODON = {}
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
. Output only the next line. | self.prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) |
Continue the code snippet: <|code_start|>"""Tests `phydmslib.models.ExpCM` class.
Written by Jesse Bloom.
Uses `sympy` to make sure attributes and derivatives of attributes
are correct for `ExpCM` implemented in `phydmslib.models`.
"""
class testExpCM(unittest.TestCase):
"""Tests ``ExpCM`` model."""
def test_ExpCM(self):
"""Initialize `ExpCM`, test values, update, test again."""
# create preferences
random.seed(1)
numpy.random.seed(1)
self.nsites = 2
self.prefs = []
minpref = 0.01
for _r in range(self.nsites):
<|code_end|>
. Use current file imports:
import random
import unittest
import numpy
import scipy.linalg
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import (N_CODON, NT_TO_INDEX, CODON_TO_AA,
INDEX_TO_CODON, INDEX_TO_AA, CODON_SINGLEMUT,
CODON_TRANSITION, CODON_NONSYN, N_NT,
AA_TO_INDEX, N_AA)
and context (classes, functions, or code) from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()}
#
# CODON_TO_AA = []
#
# INDEX_TO_CODON = {}
#
# INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY'))
#
# CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool')
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
. Output only the next line. | rprefs = numpy.random.dirichlet([0.5] * N_AA) |
Predict the next line after this snippet: <|code_start|>"""Tests invquadratic prior in `ExpCM_fitprefs`.
Written by Jesse Bloom.
"""
class test_fitprefs_invquadraticprior(unittest.TestCase):
"""Test `ExpCM_fitprefs` with inverse quadratic prior."""
MODEL = phydmslib.models.ExpCM_fitprefs
def setUp(self):
"""Set up for tests."""
numpy.random.seed(1)
random.seed(1)
nsites = 1
minpref = 0.001
self.prefs = []
for _r in range(nsites):
<|code_end|>
using the current file's imports:
import random
import unittest
import copy
import numpy
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import N_AA, N_NT, AA_TO_INDEX
and any relevant context from other files:
# Path: phydmslib/constants.py
# N_AA = len(INDEX_TO_AA)
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
. Output only the next line. | rprefs = numpy.random.dirichlet([0.7] * N_AA) |
Next line prediction: <|code_start|>"""Tests invquadratic prior in `ExpCM_fitprefs`.
Written by Jesse Bloom.
"""
class test_fitprefs_invquadraticprior(unittest.TestCase):
"""Test `ExpCM_fitprefs` with inverse quadratic prior."""
MODEL = phydmslib.models.ExpCM_fitprefs
def setUp(self):
"""Set up for tests."""
numpy.random.seed(1)
random.seed(1)
nsites = 1
minpref = 0.001
self.prefs = []
for _r in range(nsites):
rprefs = numpy.random.dirichlet([0.7] * N_AA)
rprefs[rprefs < minpref] = minpref
rprefs[0] = rprefs[1] + 1.0e-8 # near equal prefs handled OK
rprefs /= rprefs.sum()
self.prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
self.expcm_fitprefs = self.MODEL(self.prefs,
prior=('invquadratic', 150.0, 0.5),
kappa=3.0, omega=0.3,
<|code_end|>
. Use current file imports:
(import random
import unittest
import copy
import numpy
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import N_AA, N_NT, AA_TO_INDEX)
and context including class names, function names, or small code snippets from other files:
# Path: phydmslib/constants.py
# N_AA = len(INDEX_TO_AA)
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
. Output only the next line. | phi=numpy.random.dirichlet([5] * N_NT) |
Based on the snippet: <|code_start|>"""Tests invquadratic prior in `ExpCM_fitprefs`.
Written by Jesse Bloom.
"""
class test_fitprefs_invquadraticprior(unittest.TestCase):
"""Test `ExpCM_fitprefs` with inverse quadratic prior."""
MODEL = phydmslib.models.ExpCM_fitprefs
def setUp(self):
"""Set up for tests."""
numpy.random.seed(1)
random.seed(1)
nsites = 1
minpref = 0.001
self.prefs = []
for _r in range(nsites):
rprefs = numpy.random.dirichlet([0.7] * N_AA)
rprefs[rprefs < minpref] = minpref
rprefs[0] = rprefs[1] + 1.0e-8 # near equal prefs handled OK
rprefs /= rprefs.sum()
<|code_end|>
, predict the immediate next line with the help of imports:
import random
import unittest
import copy
import numpy
import scipy.optimize
import sympy
import phydmslib.models
from phydmslib.constants import N_AA, N_NT, AA_TO_INDEX
and context (classes, functions, sometimes code) from other files:
# Path: phydmslib/constants.py
# N_AA = len(INDEX_TO_AA)
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
. Output only the next line. | self.prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) |
Next line prediction: <|code_start|> beta=beta,
omega2=omega2)
# now check ExpCM attributes / derivates, updating several times
for _update in range(2):
self.params = {
"omega": random.uniform(0.1, 2),
"kappa": random.uniform(0.5, 10),
"beta": random.uniform(0.5, 3),
"mu": random.uniform(0.05, 5.0),
"omega2": random.uniform(0.1, 0.3),
}
self.model.updateParams(self.params)
self.assertTrue(numpy.allclose(g, self.model.g))
self.check_empirical_phi()
self.check_dQxy_dbeta()
self.check_dprx_dbeta()
self.check_ExpCM_attributes()
self.check_ExpCM_derivatives()
self.check_ExpCM_matrix_exponentials()
def check_empirical_phi(self):
"""Check that `phi` gives right `g`, and has right derivative."""
nt_freqs = [0] * N_NT
for r in range(self.nsites):
<|code_end|>
. Use current file imports:
(import random
import unittest
import scipy.linalg
import scipy.optimize
import numpy
import phydmslib.models
from phydmslib.constants import (N_CODON, N_NT, AA_TO_INDEX, N_AA,
CODON_NT_COUNT))
and context including class names, function names, or small code snippets from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
. Output only the next line. | for x in range(N_CODON): |
Based on the snippet: <|code_start|>"""Tests `phydmslib.models.ExpCM_empirical_phi_divpressure` class.
Written by Jesse Bloom.
Edited by Sarah Hilton
"""
class test_compare_ExpCM_emp_phi_with_without_divpress(unittest.TestCase):
"""Tests ``ExpCM`` with and without div pressure."""
def test_compare(self):
"""Make sure all attributes are the same when `divpressure` is 0."""
random.seed(1)
numpy.random.seed(1)
nsites = 6
prefs = []
minpref = 0.01
for _r in range(nsites):
rprefs = numpy.random.dirichlet([0.5] * N_AA)
rprefs[rprefs < minpref] = minpref
rprefs /= rprefs.sum()
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
<|code_end|>
, predict the immediate next line with the help of imports:
import random
import unittest
import scipy.linalg
import scipy.optimize
import numpy
import phydmslib.models
from phydmslib.constants import (N_CODON, N_NT, AA_TO_INDEX, N_AA,
CODON_NT_COUNT)
and context (classes, functions, sometimes code) from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
. Output only the next line. | g = numpy.random.dirichlet([3] * N_NT) |
Predict the next line for this snippet: <|code_start|>"""Tests `phydmslib.models.ExpCM_empirical_phi_divpressure` class.
Written by Jesse Bloom.
Edited by Sarah Hilton
"""
class test_compare_ExpCM_emp_phi_with_without_divpress(unittest.TestCase):
"""Tests ``ExpCM`` with and without div pressure."""
def test_compare(self):
"""Make sure all attributes are the same when `divpressure` is 0."""
random.seed(1)
numpy.random.seed(1)
nsites = 6
prefs = []
minpref = 0.01
for _r in range(nsites):
rprefs = numpy.random.dirichlet([0.5] * N_AA)
rprefs[rprefs < minpref] = minpref
rprefs /= rprefs.sum()
<|code_end|>
with the help of current file imports:
import random
import unittest
import scipy.linalg
import scipy.optimize
import numpy
import phydmslib.models
from phydmslib.constants import (N_CODON, N_NT, AA_TO_INDEX, N_AA,
CODON_NT_COUNT)
and context from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
, which may contain function names, class names, or code. Output only the next line. | prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) |
Next line prediction: <|code_start|>"""Tests `phydmslib.models.ExpCM_empirical_phi_divpressure` class.
Written by Jesse Bloom.
Edited by Sarah Hilton
"""
class test_compare_ExpCM_emp_phi_with_without_divpress(unittest.TestCase):
"""Tests ``ExpCM`` with and without div pressure."""
def test_compare(self):
"""Make sure all attributes are the same when `divpressure` is 0."""
random.seed(1)
numpy.random.seed(1)
nsites = 6
prefs = []
minpref = 0.01
for _r in range(nsites):
<|code_end|>
. Use current file imports:
(import random
import unittest
import scipy.linalg
import scipy.optimize
import numpy
import phydmslib.models
from phydmslib.constants import (N_CODON, N_NT, AA_TO_INDEX, N_AA,
CODON_NT_COUNT))
and context including class names, function names, or small code snippets from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
. Output only the next line. | rprefs = numpy.random.dirichlet([0.5] * N_AA) |
Next line prediction: <|code_start|> # now check ExpCM attributes / derivates, updating several times
for _update in range(2):
self.params = {
"omega": random.uniform(0.1, 2),
"kappa": random.uniform(0.5, 10),
"beta": random.uniform(0.5, 3),
"mu": random.uniform(0.05, 5.0),
"omega2": random.uniform(0.1, 0.3),
}
self.model.updateParams(self.params)
self.assertTrue(numpy.allclose(g, self.model.g))
self.check_empirical_phi()
self.check_dQxy_dbeta()
self.check_dprx_dbeta()
self.check_ExpCM_attributes()
self.check_ExpCM_derivatives()
self.check_ExpCM_matrix_exponentials()
def check_empirical_phi(self):
"""Check that `phi` gives right `g`, and has right derivative."""
nt_freqs = [0] * N_NT
for r in range(self.nsites):
for x in range(N_CODON):
for w in range(N_NT):
<|code_end|>
. Use current file imports:
(import random
import unittest
import scipy.linalg
import scipy.optimize
import numpy
import phydmslib.models
from phydmslib.constants import (N_CODON, N_NT, AA_TO_INDEX, N_AA,
CODON_NT_COUNT))
and context including class names, function names, or small code snippets from other files:
# Path: phydmslib/constants.py
# N_CODON = len(CODON_TO_INDEX)
#
# N_NT = len(INDEX_TO_NT)
#
# AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()}
#
# N_AA = len(INDEX_TO_AA)
#
# CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int')
. Output only the next line. | nt_freqs[w] += self.model.prx[r][x] * CODON_NT_COUNT[w][x] |
Given the following code snippet before the placeholder: <|code_start|> subject = ("ITP: bugwarrior -- Pull tickets from github, "
"bitbucket, bugzilla, jira, trac, and others into "
"taskwarrior")
severity = "wishlist"
source = ""
forwarded = ""
pending = "pending"
class FakeBTSLib:
def get_bugs(self, *args, **kwargs):
return [810629]
def get_status(self, bug_num):
if bug_num == [810629]:
return [FakeBTSBug]
class TestBTSService(AbstractServiceTest, ServiceTest):
maxDiff = None
SERVICE_CONFIG = {
'service': 'bts',
'bts.email': 'irl@debian.org',
'bts.packages': 'bugwarrior',
}
def setUp(self):
super().setUp()
<|code_end|>
, predict the next line using imports from the current file:
from unittest import mock
from bugwarrior.services import bts
from .base import ServiceTest, AbstractServiceTest
and context including class names, function names, and sometimes code from other files:
# Path: bugwarrior/services/bts.py
# UDD_BUGS_SEARCH = "https://udd.debian.org/bugs/"
# SUBJECT = 'btssubject'
# URL = 'btsurl'
# NUMBER = 'btsnumber'
# PACKAGE = 'btspackage'
# SOURCE = 'btssource'
# FORWARDED = 'btsforwarded'
# STATUS = 'btsstatus'
# UDAS = {
# SUBJECT: {
# 'type': 'string',
# 'label': 'Debian BTS Subject',
# },
# URL: {
# 'type': 'string',
# 'label': 'Debian BTS URL',
# },
# NUMBER: {
# 'type': 'numeric',
# 'label': 'Debian BTS Number',
# },
# PACKAGE: {
# 'type': 'string',
# 'label': 'Debian BTS Package',
# },
# SOURCE: {
# 'type': 'string',
# 'label': 'Debian BTS Source Package',
# },
# FORWARDED: {
# 'type': 'string',
# 'label': 'Debian BTS Forwarded URL',
# },
# STATUS: {
# 'type': 'string',
# 'label': 'Debian BTS Status',
# }
# }
# UNIQUE_KEY = (URL, )
# PRIORITY_MAP = {
# 'wishlist': 'L',
# 'minor': 'L',
# 'normal': 'M',
# 'important': 'M',
# 'serious': 'H',
# 'grave': 'H',
# 'critical': 'H',
# }
# ISSUE_CLASS = BTSIssue
# CONFIG_SCHEMA = BTSConfig
# class BTSConfig(config.ServiceConfig, prefix='bts'):
# class BTSIssue(Issue):
# class BTSService(IssueService, ServiceClient):
# def require_email_or_packages(cls, values):
# def udd_needs_email(cls, values):
# def to_taskwarrior(self):
# def get_default_description(self):
# def get_priority(self):
# def get_owner(self, issue):
# def _record_for_bug(self, bug):
# def _get_udd_bugs(self):
# def annotations(self, issue, issue_obj):
# def issues(self):
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
. Output only the next line. | self.service = self.get_mock_service(bts.BTSService) |
Here is a snippet: <|code_start|>
class FakeBTSBug:
bug_num = 810629
package = "wnpp"
subject = ("ITP: bugwarrior -- Pull tickets from github, "
"bitbucket, bugzilla, jira, trac, and others into "
"taskwarrior")
severity = "wishlist"
source = ""
forwarded = ""
pending = "pending"
class FakeBTSLib:
def get_bugs(self, *args, **kwargs):
return [810629]
def get_status(self, bug_num):
if bug_num == [810629]:
return [FakeBTSBug]
<|code_end|>
. Write the next line using the current file imports:
from unittest import mock
from bugwarrior.services import bts
from .base import ServiceTest, AbstractServiceTest
and context from other files:
# Path: bugwarrior/services/bts.py
# UDD_BUGS_SEARCH = "https://udd.debian.org/bugs/"
# SUBJECT = 'btssubject'
# URL = 'btsurl'
# NUMBER = 'btsnumber'
# PACKAGE = 'btspackage'
# SOURCE = 'btssource'
# FORWARDED = 'btsforwarded'
# STATUS = 'btsstatus'
# UDAS = {
# SUBJECT: {
# 'type': 'string',
# 'label': 'Debian BTS Subject',
# },
# URL: {
# 'type': 'string',
# 'label': 'Debian BTS URL',
# },
# NUMBER: {
# 'type': 'numeric',
# 'label': 'Debian BTS Number',
# },
# PACKAGE: {
# 'type': 'string',
# 'label': 'Debian BTS Package',
# },
# SOURCE: {
# 'type': 'string',
# 'label': 'Debian BTS Source Package',
# },
# FORWARDED: {
# 'type': 'string',
# 'label': 'Debian BTS Forwarded URL',
# },
# STATUS: {
# 'type': 'string',
# 'label': 'Debian BTS Status',
# }
# }
# UNIQUE_KEY = (URL, )
# PRIORITY_MAP = {
# 'wishlist': 'L',
# 'minor': 'L',
# 'normal': 'M',
# 'important': 'M',
# 'serious': 'H',
# 'grave': 'H',
# 'critical': 'H',
# }
# ISSUE_CLASS = BTSIssue
# CONFIG_SCHEMA = BTSConfig
# class BTSConfig(config.ServiceConfig, prefix='bts'):
# class BTSIssue(Issue):
# class BTSService(IssueService, ServiceClient):
# def require_email_or_packages(cls, values):
# def udd_needs_email(cls, values):
# def to_taskwarrior(self):
# def get_default_description(self):
# def get_priority(self):
# def get_owner(self, issue):
# def _record_for_bug(self, bug):
# def _get_udd_bugs(self):
# def annotations(self, issue, issue_obj):
# def issues(self):
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
, which may include functions, classes, or code. Output only the next line. | class TestBTSService(AbstractServiceTest, ServiceTest): |
Based on the snippet: <|code_start|>
class FakeBTSBug:
bug_num = 810629
package = "wnpp"
subject = ("ITP: bugwarrior -- Pull tickets from github, "
"bitbucket, bugzilla, jira, trac, and others into "
"taskwarrior")
severity = "wishlist"
source = ""
forwarded = ""
pending = "pending"
class FakeBTSLib:
def get_bugs(self, *args, **kwargs):
return [810629]
def get_status(self, bug_num):
if bug_num == [810629]:
return [FakeBTSBug]
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import mock
from bugwarrior.services import bts
from .base import ServiceTest, AbstractServiceTest
and context (classes, functions, sometimes code) from other files:
# Path: bugwarrior/services/bts.py
# UDD_BUGS_SEARCH = "https://udd.debian.org/bugs/"
# SUBJECT = 'btssubject'
# URL = 'btsurl'
# NUMBER = 'btsnumber'
# PACKAGE = 'btspackage'
# SOURCE = 'btssource'
# FORWARDED = 'btsforwarded'
# STATUS = 'btsstatus'
# UDAS = {
# SUBJECT: {
# 'type': 'string',
# 'label': 'Debian BTS Subject',
# },
# URL: {
# 'type': 'string',
# 'label': 'Debian BTS URL',
# },
# NUMBER: {
# 'type': 'numeric',
# 'label': 'Debian BTS Number',
# },
# PACKAGE: {
# 'type': 'string',
# 'label': 'Debian BTS Package',
# },
# SOURCE: {
# 'type': 'string',
# 'label': 'Debian BTS Source Package',
# },
# FORWARDED: {
# 'type': 'string',
# 'label': 'Debian BTS Forwarded URL',
# },
# STATUS: {
# 'type': 'string',
# 'label': 'Debian BTS Status',
# }
# }
# UNIQUE_KEY = (URL, )
# PRIORITY_MAP = {
# 'wishlist': 'L',
# 'minor': 'L',
# 'normal': 'M',
# 'important': 'M',
# 'serious': 'H',
# 'grave': 'H',
# 'critical': 'H',
# }
# ISSUE_CLASS = BTSIssue
# CONFIG_SCHEMA = BTSConfig
# class BTSConfig(config.ServiceConfig, prefix='bts'):
# class BTSIssue(Issue):
# class BTSService(IssueService, ServiceClient):
# def require_email_or_packages(cls, values):
# def udd_needs_email(cls, values):
# def to_taskwarrior(self):
# def get_default_description(self):
# def get_priority(self):
# def get_owner(self, issue):
# def _record_for_bug(self, bug):
# def _get_udd_bugs(self):
# def annotations(self, issue, issue_obj):
# def issues(self):
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
. Output only the next line. | class TestBTSService(AbstractServiceTest, ServiceTest): |
Next line prediction: <|code_start|>
class TestTaigaIssue(AbstractServiceTest, ServiceTest):
SERVICE_CONFIG = {
'service': 'taiga',
'taiga.base_uri': 'https://one',
'taiga.auth_token': 'two',
}
record = {
'id': 400,
'project': 4,
'ref': 40,
'subject': 'this is a title',
'tags': [
'single',
[
'bugwarrior',
None
],
[
'task',
'#c0ffee'
]
],
}
def setUp(self):
super().setUp()
<|code_end|>
. Use current file imports:
(import responses
from bugwarrior.services.taiga import TaigaService
from .base import ServiceTest, AbstractServiceTest)
and context including class names, function names, or small code snippets from other files:
# Path: bugwarrior/services/taiga.py
# class TaigaService(IssueService, ServiceClient):
# ISSUE_CLASS = TaigaIssue
# CONFIG_SCHEMA = TaigaConfig
#
# def __init__(self, *args, **kw):
# super().__init__(*args, **kw)
# self.auth_token = self.get_password('auth_token')
# self.session = requests.session()
# self.session.headers.update({
# 'Accept': 'application/json',
# 'Authorization': 'Bearer %s' % self.auth_token,
# })
#
# @staticmethod
# def get_keyring_service(config):
# return f"taiga://{config.base_uri}"
#
# def get_service_metadata(self):
# return {
# 'url': self.config.base_uri,
# 'label_template': self.config.label_template,
# }
#
# def get_owner(self, issue):
# # TODO
# raise NotImplementedError(
# "This service has not implemented support for 'only_if_assigned'.")
#
# def _issues(self, userid, task_type, task_type_plural, task_type_short):
# log.debug('Getting %s' % task_type_plural)
#
# response = self.session.get(
# self.config.base_uri + '/api/v1/' + task_type_plural,
# params={'assigned_to': userid, 'status__is_closed': "false"})
# tasks = response.json()
#
# for task in tasks:
# project = self.get_project(task['project'])
# extra = {
# 'project': project['slug'],
# 'annotations': self.annotations(task, project, task_type, task_type_short),
# 'url': self.build_url(task, project, task_type_short),
# }
# yield self.get_issue_for_record(task, extra)
#
# def issues(self):
# url = self.config.base_uri + '/api/v1/users/me'
# me = self.session.get(url)
# data = me.json()
#
# # Check for errors and bail if we failed.
# if '_error_message' in data:
# raise RuntimeError("{_error_type} {_error_message}".format(**data))
#
# # Otherwise, proceed.
# userid = data['id']
#
# yield from self._issues(userid, 'userstory', 'userstories', 'us')
#
# if self.config.include_tasks:
# yield from self._issues(userid, 'task', 'tasks', 'task')
#
# @cache.cache_on_arguments()
# def get_project(self, project_id):
# url = '%s/api/v1/projects/%i' % (self.config.base_uri, project_id)
# return self.json_response(self.session.get(url))
#
# def build_url(self, task, project, task_type):
# return '%s/project/%s/%s/%i' % (
# self.config.base_uri, project['slug'], task_type, task['ref'])
#
# def annotations(self, task, project, task_type, task_type_short):
# url = f"{self.config.base_uri}/api/v1/history/{task_type}/{task['id']}"
# response = self.session.get(url)
# history = response.json()
# return self.build_annotations(
# ((
# item['user']['username'],
# item['comment'],
# ) for item in history if item['comment']),
# self.build_url(task, project, task_type_short)
# )
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
. Output only the next line. | self.service = self.get_mock_service(TaigaService) |
Based on the snippet: <|code_start|>
class TestGerritIssue(AbstractServiceTest, ServiceTest):
SERVICE_CONFIG = {
'service': 'gerrit',
'gerrit.base_uri': 'https://one.com',
'gerrit.username': 'two',
'gerrit.password': 'three',
}
record = {
'project': 'nova',
'_number': 1,
'branch': 'master',
'topic': 'test-topic',
'subject': 'this is a title',
'messages': [{'author': {'username': 'Iam Author'},
'message': 'this is a message',
'_revision_number': 1}],
}
def setUp(self):
super().setUp()
responses.add(
responses.HEAD,
self.SERVICE_CONFIG['gerrit.base_uri'] + '/a/',
headers={'www-authenticate': 'digest'})
with responses.mock:
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import responses
from bugwarrior.services.gerrit import GerritService
from .base import ServiceTest, AbstractServiceTest
and context (classes, functions, sometimes code) from other files:
# Path: bugwarrior/services/gerrit.py
# class GerritService(IssueService, ServiceClient):
# ISSUE_CLASS = GerritIssue
# CONFIG_SCHEMA = GerritConfig
#
# def __init__(self, *args, **kw):
# super().__init__(*args, **kw)
# self.password = self.get_password('password', self.config.username)
# self.session = requests.session()
# self.session.headers.update({
# 'Accept': 'application/json',
# 'Accept-Encoding': 'gzip',
# })
# self.query_string = (
# self.config.query + '&o=MESSAGES&o=DETAILED_ACCOUNTS')
#
# if self.config.ssl_ca_path:
# self.session.verify = self.config.ssl_ca_path
#
# # uses digest authentication if supported by the server, fallback to basic
# # gerrithub.io supports only basic
# response = self.session.head(self.config.base_uri + '/a/')
# if 'digest' in response.headers.get('www-authenticate', '').lower():
# self.session.auth = requests.auth.HTTPDigestAuth(
# self.config.username, self.password)
# else:
# self.session.auth = requests.auth.HTTPBasicAuth(
# self.config.username, self.password)
#
# @staticmethod
# def get_keyring_service(config):
# return f"gerrit://{config.base_uri}"
#
# def get_service_metadata(self):
# return {
# 'url': self.config.base_uri,
# }
#
# def get_owner(self, issue):
# # TODO
# raise NotImplementedError(
# "This service has not implemented support for 'only_if_assigned'.")
#
# def issues(self):
# # Construct the whole url by hand here, because otherwise requests will
# # percent-encode the ':' characters, which gerrit doesn't like.
# url = self.config.base_uri + '/a/changes/?q=' + self.query_string
# response = self.session.get(url)
# response.raise_for_status()
# # The response has some ")]}'" garbage prefixed.
# body = response.text[4:]
# changes = json.loads(body)
#
# for change in changes:
# extra = {
# 'url': self.build_url(change),
# 'annotations': self.annotations(change),
# }
# yield self.get_issue_for_record(change, extra)
#
# def build_url(self, change):
# return '%s/#/c/%i/' % (self.config.base_uri, change['_number'])
#
# def annotations(self, change):
# entries = []
# for item in change['messages']:
# for key in ['name', 'username', 'email']:
# if key in item['author']:
# username = item['author'][key]
# break
# else:
# username = item['author']['_account_id']
# # Gerrit messages are really messy
# message = item['message']\
# .lstrip('Patch Set ')\
# .lstrip("%s:" % item['_revision_number'])\
# .strip()\
# .replace('\n', ' ')
# entries.append((username, message,))
#
# return self.build_annotations(entries, self.build_url(change))
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
. Output only the next line. | self.service = self.get_mock_service(GerritService) |
Based on the snippet: <|code_start|> "id": 35546,
"name": "Adam Coddington"
},
"created_on": arbitrary_created.isoformat(),
"due_on": "2016-12-30T16:40:29Z",
"description": "This is a test issue.",
"done_ratio": 0,
"id": 363901,
"priority": {
"id": 4,
"name": "Normal"
},
"project": {
"id": 27375,
"name": "Boiled Cabbage - Yum"
},
"status": {
"id": 1,
"name": "New"
},
"subject": "Biscuits",
"tracker": {
"id": 4,
"name": "Task"
},
"updated_on": arbitrary_updated.isoformat(),
}
def setUp(self):
super().setUp()
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import dateutil
import responses
from unittest import mock
from bugwarrior.services.redmine import RedMineService
from .base import ServiceTest, AbstractServiceTest
and context (classes, functions, sometimes code) from other files:
# Path: bugwarrior/services/redmine.py
# class RedMineService(IssueService):
# ISSUE_CLASS = RedMineIssue
# CONFIG_SCHEMA = RedMineConfig
#
# def __init__(self, *args, **kw):
# super().__init__(*args, **kw)
#
# self.key = self.get_password('key')
#
# password = (self.get_password('password', self.config.login)
# if self.config.login else None)
# auth = ((self.config.login, password)
# if (self.config.login and password) else None)
# self.client = RedMineClient(self.config.url,
# self.key,
# auth,
# self.config.issue_limit,
# self.config.verify_ssl)
#
# def get_service_metadata(self):
# return {
# 'project_name': self.config.project_name,
# 'url': self.config.url,
# }
#
# @staticmethod
# def get_keyring_service(config):
# return f"redmine://{config.login}@{config.url}/"
#
# def get_owner(self, issue):
# # Issue filtering is implemented as part of the api query.
# pass
#
# def issues(self):
# issues = self.client.find_issues(
# self.config.issue_limit, self.config.only_if_assigned)
# log.debug(" Found %i total.", len(issues))
# for issue in issues:
# yield self.get_issue_for_record(issue)
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
. Output only the next line. | self.service = self.get_mock_service(RedMineService) |
Given snippet: <|code_start|>
class StringCompatTest(unittest.TestCase):
"""This class implements method to test correct and compatible
implementation of __str__ and __repr__ methods"""
def test_issue_str(self):
"check Issue class"
record = {}
origin = {'target': 'target',
'default_priority': 'prio',
'templates': 'templates',
'add_tags': []}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from unittest.mock import MagicMock
from .test_service import DumbIssue
and context:
# Path: tests/test_service.py
# class DumbIssue(services.Issue):
# """
# Implement the required methods but they shouldn't be called.
# """
# def get_default_description(self):
# raise NotImplementedError
#
# def to_taskwarrior(self):
# raise NotImplementedError
which might include code, classes, or functions. Output only the next line. | issue = DumbIssue(record, origin) |
Given snippet: <|code_start|> if main_config.merge_tags:
if main_config.replace_tags:
replace_left('tags', task, issue_dict, main_config.static_tags)
else:
merge_left('tags', task, issue_dict)
issue_dict.pop('annotations', None)
issue_dict.pop('tags', None)
task.update(issue_dict)
if task.get_changes(keep=True):
issue_updates['changed'].append(task)
else:
issue_updates['existing'].append(task)
except MultipleMatches as e:
log.exception("Multiple matches: %s", str(e))
except NotFound:
issue_updates['new'].append(issue_dict)
notreally = ' (not really)' if dry_run else ''
# Add new issues
log.info("Adding %i tasks", len(issue_updates['new']))
for issue in issue_updates['new']:
log.info("Adding task %s%s", issue['description'], notreally)
if dry_run:
continue
if notify:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import os
import re
import subprocess
import requests
import dogpile.cache
import logging
from taskw import TaskWarriorShellout
from taskw.exceptions import TaskwarriorError
from bugwarrior.notifications import send_notification
from bugwarrior.services import get_service
from bugwarrior.services import get_service
and context:
# Path: bugwarrior/notifications.py
# def send_notification(issue, op, conf):
# notify_backend = conf.backend
#
# if notify_backend == 'pynotify':
# warnings.warn("pynotify is deprecated. Use backend=gobject. "
# "See https://github.com/ralphbean/bugwarrior/issues/336")
# notify_backend = 'gobject'
#
# # Notifications for growlnotify on Mac OS X
# if notify_backend == 'growlnotify':
# import gntp.notifier
# growl = gntp.notifier.GrowlNotifier(
# applicationName="Bugwarrior",
# notifications=["New Updates", "New Messages"],
# defaultNotifications=["New Messages"],
# )
# growl.register()
# if op == 'bw_finished':
# growl.notify(
# noteType="New Messages",
# title="Bugwarrior",
# description="Finished querying for new issues.\n%s" %
# issue['description'],
# sticky=conf.finished_querying_sticky,
# icon="https://upload.wikimedia.org/wikipedia/"
# "en/5/59/Taskwarrior_logo.png",
# priority=1,
# )
# return
# message = "%s task: %s" % (op, issue['description'])
# metadata = _get_metadata(issue)
# if metadata is not None:
# message += metadata
# growl.notify(
# noteType="New Messages",
# title="Bugwarrior",
# description=message,
# sticky=conf.task_crud_sticky,
# icon="https://upload.wikimedia.org/wikipedia/"
# "en/5/59/Taskwarrior_logo.png",
# priority=1,
# )
# return
# elif notify_backend == 'gobject':
# _cache_logo()
#
# import gi
# gi.require_version('Notify', '0.7')
# from gi.repository import Notify
# Notify.init("bugwarrior")
#
# if op == 'bw finished':
# message = "Finished querying for new issues.\n%s" %\
# issue['description']
# else:
# message = "%s task: %s" % (op, issue['description'])
# metadata = _get_metadata(issue)
# if metadata is not None:
# message += metadata
#
# Notify.Notification.new("Bugwarrior", message, logo_path).show()
which might include code, classes, or functions. Output only the next line. | send_notification(issue, 'Created', conf['notifications']) |
Predict the next line after this snippet: <|code_start|> arbitrary_issue = {
'priority': 0,
'project': 'something',
'due_on': {
'formatted_date': arbitrary_due_on.isoformat(),
},
'permalink': 'http://wherever/',
'task_id': 10,
'project_name': 'something',
'project_id': 10,
'id': 30,
'type': 'issue',
'created_on': {
'formatted_date': arbitrary_created_on.isoformat(),
},
'created_by_name': 'Tester',
'body': _body.rstrip(),
'name': 'Anonymous',
'milestone': 'Sprint 1',
'estimated_time': 1,
'tracked_time': 10,
'label': 'ON_HOLD',
'assignee_id': 2,
'label_id': 1,
}
def setUp(self):
super().setUp()
self.maxDiff = None
with mock.patch('pyac.library.activeCollab.call_api'):
<|code_end|>
using the current file's imports:
import datetime
import unittest
import pypandoc
import pytz
from unittest import mock
from bugwarrior.services.activecollab import (
ActiveCollabService
)
from .base import ServiceTest, AbstractServiceTest
and any relevant context from other files:
# Path: bugwarrior/services/activecollab.py
# class ActiveCollabService(IssueService):
# ISSUE_CLASS = ActiveCollabIssue
# CONFIG_SCHEMA = ActiveCollabConfig
#
# def __init__(self, *args, **kw):
# super().__init__(*args, **kw)
#
# self.client = ActiveCollabClient(
# self.config.url, self.config.key, self.config.user_id
# )
# self.activecollab = activeCollab(url=self.config.url,
# key=self.config.key,
# user_id=self.config.user_id)
#
# def _comments(self, issue):
# comments = self.activecollab.get_comments(
# issue['project_id'],
# issue['task_id']
# )
# comments_formatted = []
# if comments is not None:
# for comment in comments:
# comments_formatted.append(
# dict(user=comment['created_by']['display_name'],
# body=comment['body']))
# return comments_formatted
#
# def get_owner(self, issue):
# if issue['assignee_id']:
# return issue['assignee_id']
#
# def annotations(self, issue, issue_obj):
# if 'type' not in issue:
# # Subtask
# return []
# comments = self._comments(issue)
# if comments is None:
# return []
#
# return self.build_annotations(
# ((
# c['user'],
# pypandoc.convert_text(c['body'], 'md', format='html').rstrip()
# ) for c in comments),
# issue_obj.get_processed_url(issue_obj.record['permalink']),
# )
#
# def issues(self):
# data = self.activecollab.get_my_tasks()
# label_data = self.activecollab.get_assignment_labels()
# labels = dict()
# for item in label_data:
# labels[item['id']] = re.sub(r'\W+', '_', item['name'])
# task_count = 0
# issues = []
# for key, record in data.items():
# for task_id, task in record['assignments'].items():
# task_count = task_count + 1
# # Add tasks
# if task['assignee_id'] == self.config.user_id:
# task['label'] = labels.get(task['label_id'])
# issues.append(task)
# if 'subtasks' in task:
# for subtask_id, subtask in task['subtasks'].items():
# # Add subtasks
# task_count = task_count + 1
# if subtask['assignee_id'] is self.config.user_id:
# # Add some data from the parent task
# subtask['label'] = labels.get(subtask['label_id'])
# subtask['project_id'] = task['project_id']
# subtask['project'] = task['project']
# subtask['task_id'] = task['task_id']
# subtask['milestone'] = task['milestone']
# issues.append(subtask)
# log.debug(" Found %i total", task_count)
# log.debug(" Pruned down to %i", len(issues))
# for issue in issues:
# issue_obj = self.get_issue_for_record(issue)
# extra = {
# 'annotations': self.annotations(issue, issue_obj)
# }
# issue_obj.update_extra(extra)
# yield issue_obj
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
. Output only the next line. | self.service = self.get_mock_service(ActiveCollabService) |
Continue the code snippet: <|code_start|>
class FakeActiveCollabLib:
def __init__(self, arbitrary_issue):
self.arbitrary_issue = arbitrary_issue
def get_my_tasks(self):
return {'arbitrary_key': {'assignments': {
self.arbitrary_issue['task_id']: self.arbitrary_issue}}}
def get_assignment_labels(self):
return []
def get_comments(self, *args):
return []
<|code_end|>
. Use current file imports:
import datetime
import unittest
import pypandoc
import pytz
from unittest import mock
from bugwarrior.services.activecollab import (
ActiveCollabService
)
from .base import ServiceTest, AbstractServiceTest
and context (classes, functions, or code) from other files:
# Path: bugwarrior/services/activecollab.py
# class ActiveCollabService(IssueService):
# ISSUE_CLASS = ActiveCollabIssue
# CONFIG_SCHEMA = ActiveCollabConfig
#
# def __init__(self, *args, **kw):
# super().__init__(*args, **kw)
#
# self.client = ActiveCollabClient(
# self.config.url, self.config.key, self.config.user_id
# )
# self.activecollab = activeCollab(url=self.config.url,
# key=self.config.key,
# user_id=self.config.user_id)
#
# def _comments(self, issue):
# comments = self.activecollab.get_comments(
# issue['project_id'],
# issue['task_id']
# )
# comments_formatted = []
# if comments is not None:
# for comment in comments:
# comments_formatted.append(
# dict(user=comment['created_by']['display_name'],
# body=comment['body']))
# return comments_formatted
#
# def get_owner(self, issue):
# if issue['assignee_id']:
# return issue['assignee_id']
#
# def annotations(self, issue, issue_obj):
# if 'type' not in issue:
# # Subtask
# return []
# comments = self._comments(issue)
# if comments is None:
# return []
#
# return self.build_annotations(
# ((
# c['user'],
# pypandoc.convert_text(c['body'], 'md', format='html').rstrip()
# ) for c in comments),
# issue_obj.get_processed_url(issue_obj.record['permalink']),
# )
#
# def issues(self):
# data = self.activecollab.get_my_tasks()
# label_data = self.activecollab.get_assignment_labels()
# labels = dict()
# for item in label_data:
# labels[item['id']] = re.sub(r'\W+', '_', item['name'])
# task_count = 0
# issues = []
# for key, record in data.items():
# for task_id, task in record['assignments'].items():
# task_count = task_count + 1
# # Add tasks
# if task['assignee_id'] == self.config.user_id:
# task['label'] = labels.get(task['label_id'])
# issues.append(task)
# if 'subtasks' in task:
# for subtask_id, subtask in task['subtasks'].items():
# # Add subtasks
# task_count = task_count + 1
# if subtask['assignee_id'] is self.config.user_id:
# # Add some data from the parent task
# subtask['label'] = labels.get(subtask['label_id'])
# subtask['project_id'] = task['project_id']
# subtask['project'] = task['project']
# subtask['task_id'] = task['task_id']
# subtask['milestone'] = task['milestone']
# issues.append(subtask)
# log.debug(" Found %i total", task_count)
# log.debug(" Pruned down to %i", len(issues))
# for issue in issues:
# issue_obj = self.get_issue_for_record(issue)
# extra = {
# 'annotations': self.annotations(issue, issue_obj)
# }
# issue_obj.update_extra(extra)
# yield issue_obj
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
. Output only the next line. | class TestActiveCollabIssues(AbstractServiceTest, ServiceTest): |
Given the following code snippet before the placeholder: <|code_start|>
class FakeActiveCollabLib:
def __init__(self, arbitrary_issue):
self.arbitrary_issue = arbitrary_issue
def get_my_tasks(self):
return {'arbitrary_key': {'assignments': {
self.arbitrary_issue['task_id']: self.arbitrary_issue}}}
def get_assignment_labels(self):
return []
def get_comments(self, *args):
return []
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import unittest
import pypandoc
import pytz
from unittest import mock
from bugwarrior.services.activecollab import (
ActiveCollabService
)
from .base import ServiceTest, AbstractServiceTest
and context including class names, function names, and sometimes code from other files:
# Path: bugwarrior/services/activecollab.py
# class ActiveCollabService(IssueService):
# ISSUE_CLASS = ActiveCollabIssue
# CONFIG_SCHEMA = ActiveCollabConfig
#
# def __init__(self, *args, **kw):
# super().__init__(*args, **kw)
#
# self.client = ActiveCollabClient(
# self.config.url, self.config.key, self.config.user_id
# )
# self.activecollab = activeCollab(url=self.config.url,
# key=self.config.key,
# user_id=self.config.user_id)
#
# def _comments(self, issue):
# comments = self.activecollab.get_comments(
# issue['project_id'],
# issue['task_id']
# )
# comments_formatted = []
# if comments is not None:
# for comment in comments:
# comments_formatted.append(
# dict(user=comment['created_by']['display_name'],
# body=comment['body']))
# return comments_formatted
#
# def get_owner(self, issue):
# if issue['assignee_id']:
# return issue['assignee_id']
#
# def annotations(self, issue, issue_obj):
# if 'type' not in issue:
# # Subtask
# return []
# comments = self._comments(issue)
# if comments is None:
# return []
#
# return self.build_annotations(
# ((
# c['user'],
# pypandoc.convert_text(c['body'], 'md', format='html').rstrip()
# ) for c in comments),
# issue_obj.get_processed_url(issue_obj.record['permalink']),
# )
#
# def issues(self):
# data = self.activecollab.get_my_tasks()
# label_data = self.activecollab.get_assignment_labels()
# labels = dict()
# for item in label_data:
# labels[item['id']] = re.sub(r'\W+', '_', item['name'])
# task_count = 0
# issues = []
# for key, record in data.items():
# for task_id, task in record['assignments'].items():
# task_count = task_count + 1
# # Add tasks
# if task['assignee_id'] == self.config.user_id:
# task['label'] = labels.get(task['label_id'])
# issues.append(task)
# if 'subtasks' in task:
# for subtask_id, subtask in task['subtasks'].items():
# # Add subtasks
# task_count = task_count + 1
# if subtask['assignee_id'] is self.config.user_id:
# # Add some data from the parent task
# subtask['label'] = labels.get(subtask['label_id'])
# subtask['project_id'] = task['project_id']
# subtask['project'] = task['project']
# subtask['task_id'] = task['task_id']
# subtask['milestone'] = task['milestone']
# issues.append(subtask)
# log.debug(" Found %i total", task_count)
# log.debug(" Pruned down to %i", len(issues))
# for issue in issues:
# issue_obj = self.get_issue_for_record(issue)
# extra = {
# 'annotations': self.annotations(issue, issue_obj)
# }
# issue_obj.update_extra(extra)
# yield issue_obj
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
. Output only the next line. | class TestActiveCollabIssues(AbstractServiceTest, ServiceTest): |
Given the code snippet: <|code_start|> self.config.add_section('general')
self.config.set('general', 'targets', 'my_service')
self.config.set('general', 'static_fields', 'project, priority')
self.config.set('general', 'taskrc', self.taskrc)
self.config.add_section('my_service')
self.config.set('my_service', 'service', 'github')
self.config.set('my_service', 'github.login', 'ralphbean')
self.config.set('my_service', 'github.password', 'abc123')
self.config.set('my_service', 'github.username', 'ralphbean')
self.write_rc(self.config)
def write_rc(self, conf):
"""
Write configparser object to temporary bugwarriorrc path.
"""
rcfile = os.path.join(self.tempdir, '.config/bugwarrior/bugwarriorrc')
if not os.path.exists(os.path.dirname(rcfile)):
os.makedirs(os.path.dirname(rcfile))
with open(rcfile, 'w') as configfile:
conf.write(configfile)
return rcfile
@mock.patch(
'bugwarrior.services.github.GithubService.issues', fake_github_issues)
def test_success(self):
"""
A normal bugwarrior-pull invocation.
"""
with self.caplog.at_level(logging.INFO):
<|code_end|>
, generate the next line using the imports in this file:
import os
import logging
from unittest import mock
from click.testing import CliRunner
from bugwarrior import command
from bugwarrior.config.load import BugwarriorConfigParser
from .base import ConfigTest
from .test_github import ARBITRARY_ISSUE, ARBITRARY_EXTRA
and context (functions, classes, or occasionally code) from other files:
# Path: bugwarrior/command.py
# def _get_section_name(flavor):
# def _try_load_config(main_section, interactive=False):
# def pull(dry_run, flavor, interactive, debug):
# def vault():
# def targets():
# def list():
# def clear(target, username):
# def set(target, username):
# def uda(flavor):
#
# Path: bugwarrior/config/load.py
# class BugwarriorConfigParser(configparser.ConfigParser):
# def __init__(self, *args, allow_no_value=True, **kwargs):
# super().__init__(*args, allow_no_value=allow_no_value, **kwargs)
#
# def getint(self, section, option):
# """ Accepts both integers and empty values. """
# try:
# return super().getint(section, option)
# except ValueError:
# if self.get(section, option) == '':
# return None
# else:
# raise ValueError(
# "{section}.{option} must be an integer or empty.".format(
# section=section, option=option))
#
# @staticmethod
# def optionxform(option):
# """ Do not lowercase key names. """
# return option
#
# Path: tests/base.py
# class ConfigTest(unittest.TestCase):
# """
# Creates config files, configures the environment, and cleans up afterwards.
# """
# def setUp(self):
# self.old_environ = os.environ.copy()
# self.tempdir = tempfile.mkdtemp(prefix='bugwarrior')
#
# # Create temporary config files.
# self.taskrc = os.path.join(self.tempdir, '.taskrc')
# self.lists_path = os.path.join(self.tempdir, 'lists')
# os.mkdir(self.lists_path)
# with open(self.taskrc, 'w+') as fout:
# fout.write('data.location=%s\n' % self.lists_path)
#
# # Configure environment.
# os.environ['HOME'] = self.tempdir
# os.environ.pop(config.BUGWARRIORRC, None)
# os.environ.pop('TASKRC', None)
# os.environ.pop('XDG_CONFIG_HOME', None)
# os.environ.pop('XDG_CONFIG_DIRS', None)
#
# def tearDown(self):
# shutil.rmtree(self.tempdir, ignore_errors=True)
# os.environ = self.old_environ
#
# @pytest.fixture(autouse=True)
# def inject_fixtures(self, caplog):
# self.caplog = caplog
#
# def validate(self):
# conf = schema.validate_config(self.config, 'general', 'configpath')
# conf['general'].data = data.BugwarriorData(self.lists_path)
# conf['general'].interactive = False
# return conf
#
# def assertValidationError(self, expected):
#
# with self.assertRaises(SystemExit):
# self.validate()
#
# # Only one message should be logged.
# self.assertEqual(len(self.caplog.records), 1)
#
# self.assertIn(expected, self.caplog.records[0].message)
#
# Path: tests/test_github.py
# ARBITRARY_ISSUE = {
# 'title': 'Hallo',
# 'html_url': 'https://github.com/arbitrary_username/arbitrary_repo/pull/1',
# 'url': 'https://api.github.com/repos/arbitrary_username/arbitrary_repo/issues/1',
# 'number': 10,
# 'body': 'Something',
# 'user': {'login': 'arbitrary_login'},
# 'milestone': {'title': 'alpha'},
# 'labels': [{'name': 'bugfix'}],
# 'created_at': ARBITRARY_CREATED.isoformat(),
# 'closed_at': ARBITRARY_CLOSED.isoformat(),
# 'updated_at': ARBITRARY_UPDATED.isoformat(),
# 'repo': 'arbitrary_username/arbitrary_repo',
# 'state': 'closed'
# }
#
# ARBITRARY_EXTRA = {
# 'project': 'one',
# 'type': 'issue',
# 'annotations': [],
# 'body': 'Something',
# 'namespace': 'arbitrary_username',
# }
. Output only the next line. | self.runner.invoke(command.pull, args=('--debug')) |
Continue the code snippet: <|code_start|>
def fake_github_issues(self):
yield from [self.get_issue_for_record(ARBITRARY_ISSUE, ARBITRARY_EXTRA)]
def fake_bz_issues(self):
yield from [{
'annotations': [],
'bugzillabugid': 1234567,
'bugzillastatus': 'NEW',
'bugzillasummary': 'This is the issue summary',
'bugzillaurl': 'https://http://one.com//show_bug.cgi?id=1234567',
'bugzillaproduct': 'Product',
'bugzillacomponent': 'Something',
'description': '(bw)Is#1234567 - This is the issue summary .. https://http://one.com//show_bug.cgi?id=1234567',
'priority': 'H',
'project': 'Something',
'tags': []}]
class TestPull(ConfigTest):
def setUp(self):
super().setUp()
self.runner = CliRunner()
<|code_end|>
. Use current file imports:
import os
import logging
from unittest import mock
from click.testing import CliRunner
from bugwarrior import command
from bugwarrior.config.load import BugwarriorConfigParser
from .base import ConfigTest
from .test_github import ARBITRARY_ISSUE, ARBITRARY_EXTRA
and context (classes, functions, or code) from other files:
# Path: bugwarrior/command.py
# def _get_section_name(flavor):
# def _try_load_config(main_section, interactive=False):
# def pull(dry_run, flavor, interactive, debug):
# def vault():
# def targets():
# def list():
# def clear(target, username):
# def set(target, username):
# def uda(flavor):
#
# Path: bugwarrior/config/load.py
# class BugwarriorConfigParser(configparser.ConfigParser):
# def __init__(self, *args, allow_no_value=True, **kwargs):
# super().__init__(*args, allow_no_value=allow_no_value, **kwargs)
#
# def getint(self, section, option):
# """ Accepts both integers and empty values. """
# try:
# return super().getint(section, option)
# except ValueError:
# if self.get(section, option) == '':
# return None
# else:
# raise ValueError(
# "{section}.{option} must be an integer or empty.".format(
# section=section, option=option))
#
# @staticmethod
# def optionxform(option):
# """ Do not lowercase key names. """
# return option
#
# Path: tests/base.py
# class ConfigTest(unittest.TestCase):
# """
# Creates config files, configures the environment, and cleans up afterwards.
# """
# def setUp(self):
# self.old_environ = os.environ.copy()
# self.tempdir = tempfile.mkdtemp(prefix='bugwarrior')
#
# # Create temporary config files.
# self.taskrc = os.path.join(self.tempdir, '.taskrc')
# self.lists_path = os.path.join(self.tempdir, 'lists')
# os.mkdir(self.lists_path)
# with open(self.taskrc, 'w+') as fout:
# fout.write('data.location=%s\n' % self.lists_path)
#
# # Configure environment.
# os.environ['HOME'] = self.tempdir
# os.environ.pop(config.BUGWARRIORRC, None)
# os.environ.pop('TASKRC', None)
# os.environ.pop('XDG_CONFIG_HOME', None)
# os.environ.pop('XDG_CONFIG_DIRS', None)
#
# def tearDown(self):
# shutil.rmtree(self.tempdir, ignore_errors=True)
# os.environ = self.old_environ
#
# @pytest.fixture(autouse=True)
# def inject_fixtures(self, caplog):
# self.caplog = caplog
#
# def validate(self):
# conf = schema.validate_config(self.config, 'general', 'configpath')
# conf['general'].data = data.BugwarriorData(self.lists_path)
# conf['general'].interactive = False
# return conf
#
# def assertValidationError(self, expected):
#
# with self.assertRaises(SystemExit):
# self.validate()
#
# # Only one message should be logged.
# self.assertEqual(len(self.caplog.records), 1)
#
# self.assertIn(expected, self.caplog.records[0].message)
#
# Path: tests/test_github.py
# ARBITRARY_ISSUE = {
# 'title': 'Hallo',
# 'html_url': 'https://github.com/arbitrary_username/arbitrary_repo/pull/1',
# 'url': 'https://api.github.com/repos/arbitrary_username/arbitrary_repo/issues/1',
# 'number': 10,
# 'body': 'Something',
# 'user': {'login': 'arbitrary_login'},
# 'milestone': {'title': 'alpha'},
# 'labels': [{'name': 'bugfix'}],
# 'created_at': ARBITRARY_CREATED.isoformat(),
# 'closed_at': ARBITRARY_CLOSED.isoformat(),
# 'updated_at': ARBITRARY_UPDATED.isoformat(),
# 'repo': 'arbitrary_username/arbitrary_repo',
# 'state': 'closed'
# }
#
# ARBITRARY_EXTRA = {
# 'project': 'one',
# 'type': 'issue',
# 'annotations': [],
# 'body': 'Something',
# 'namespace': 'arbitrary_username',
# }
. Output only the next line. | self.config = BugwarriorConfigParser() |
Predict the next line for this snippet: <|code_start|>
def fake_github_issues(self):
yield from [self.get_issue_for_record(ARBITRARY_ISSUE, ARBITRARY_EXTRA)]
def fake_bz_issues(self):
yield from [{
'annotations': [],
'bugzillabugid': 1234567,
'bugzillastatus': 'NEW',
'bugzillasummary': 'This is the issue summary',
'bugzillaurl': 'https://http://one.com//show_bug.cgi?id=1234567',
'bugzillaproduct': 'Product',
'bugzillacomponent': 'Something',
'description': '(bw)Is#1234567 - This is the issue summary .. https://http://one.com//show_bug.cgi?id=1234567',
'priority': 'H',
'project': 'Something',
'tags': []}]
<|code_end|>
with the help of current file imports:
import os
import logging
from unittest import mock
from click.testing import CliRunner
from bugwarrior import command
from bugwarrior.config.load import BugwarriorConfigParser
from .base import ConfigTest
from .test_github import ARBITRARY_ISSUE, ARBITRARY_EXTRA
and context from other files:
# Path: bugwarrior/command.py
# def _get_section_name(flavor):
# def _try_load_config(main_section, interactive=False):
# def pull(dry_run, flavor, interactive, debug):
# def vault():
# def targets():
# def list():
# def clear(target, username):
# def set(target, username):
# def uda(flavor):
#
# Path: bugwarrior/config/load.py
# class BugwarriorConfigParser(configparser.ConfigParser):
# def __init__(self, *args, allow_no_value=True, **kwargs):
# super().__init__(*args, allow_no_value=allow_no_value, **kwargs)
#
# def getint(self, section, option):
# """ Accepts both integers and empty values. """
# try:
# return super().getint(section, option)
# except ValueError:
# if self.get(section, option) == '':
# return None
# else:
# raise ValueError(
# "{section}.{option} must be an integer or empty.".format(
# section=section, option=option))
#
# @staticmethod
# def optionxform(option):
# """ Do not lowercase key names. """
# return option
#
# Path: tests/base.py
# class ConfigTest(unittest.TestCase):
# """
# Creates config files, configures the environment, and cleans up afterwards.
# """
# def setUp(self):
# self.old_environ = os.environ.copy()
# self.tempdir = tempfile.mkdtemp(prefix='bugwarrior')
#
# # Create temporary config files.
# self.taskrc = os.path.join(self.tempdir, '.taskrc')
# self.lists_path = os.path.join(self.tempdir, 'lists')
# os.mkdir(self.lists_path)
# with open(self.taskrc, 'w+') as fout:
# fout.write('data.location=%s\n' % self.lists_path)
#
# # Configure environment.
# os.environ['HOME'] = self.tempdir
# os.environ.pop(config.BUGWARRIORRC, None)
# os.environ.pop('TASKRC', None)
# os.environ.pop('XDG_CONFIG_HOME', None)
# os.environ.pop('XDG_CONFIG_DIRS', None)
#
# def tearDown(self):
# shutil.rmtree(self.tempdir, ignore_errors=True)
# os.environ = self.old_environ
#
# @pytest.fixture(autouse=True)
# def inject_fixtures(self, caplog):
# self.caplog = caplog
#
# def validate(self):
# conf = schema.validate_config(self.config, 'general', 'configpath')
# conf['general'].data = data.BugwarriorData(self.lists_path)
# conf['general'].interactive = False
# return conf
#
# def assertValidationError(self, expected):
#
# with self.assertRaises(SystemExit):
# self.validate()
#
# # Only one message should be logged.
# self.assertEqual(len(self.caplog.records), 1)
#
# self.assertIn(expected, self.caplog.records[0].message)
#
# Path: tests/test_github.py
# ARBITRARY_ISSUE = {
# 'title': 'Hallo',
# 'html_url': 'https://github.com/arbitrary_username/arbitrary_repo/pull/1',
# 'url': 'https://api.github.com/repos/arbitrary_username/arbitrary_repo/issues/1',
# 'number': 10,
# 'body': 'Something',
# 'user': {'login': 'arbitrary_login'},
# 'milestone': {'title': 'alpha'},
# 'labels': [{'name': 'bugfix'}],
# 'created_at': ARBITRARY_CREATED.isoformat(),
# 'closed_at': ARBITRARY_CLOSED.isoformat(),
# 'updated_at': ARBITRARY_UPDATED.isoformat(),
# 'repo': 'arbitrary_username/arbitrary_repo',
# 'state': 'closed'
# }
#
# ARBITRARY_EXTRA = {
# 'project': 'one',
# 'type': 'issue',
# 'annotations': [],
# 'body': 'Something',
# 'namespace': 'arbitrary_username',
# }
, which may contain function names, class names, or code. Output only the next line. | class TestPull(ConfigTest): |
Predict the next line after this snippet: <|code_start|> 'activecollab2.projects': '1:one, 2:two'
}
arbitrary_due_on = (
datetime.datetime.now() - datetime.timedelta(hours=1)
).replace(tzinfo=pytz.UTC)
arbitrary_created_on = (
datetime.datetime.now() - datetime.timedelta(hours=2)
).replace(tzinfo=pytz.UTC)
arbitrary_issue = {
'project': 'something',
'priority': 2,
'due_on': arbitrary_due_on.isoformat(),
'permalink': 'http://wherever/',
'ticket_id': 10,
'project_id': 20,
'type': 'Ticket',
'created_on': arbitrary_created_on.isoformat(),
'created_by_id': '10',
'body': 'Ticket Body',
'name': 'Anonymous',
'assignees': [
{'user_id': SERVICE_CONFIG['activecollab2.user_id'],
'is_owner': True}
],
'description': 'Further detail.',
}
def setUp(self):
super().setUp()
<|code_end|>
using the current file's imports:
import re
import datetime
import pytz
import responses
from bugwarrior.services.activecollab2 import ActiveCollab2Service
from .base import ServiceTest, AbstractServiceTest
and any relevant context from other files:
# Path: bugwarrior/services/activecollab2.py
# class ActiveCollab2Service(IssueService):
# ISSUE_CLASS = ActiveCollab2Issue
# CONFIG_SCHEMA = ActiveCollab2Config
#
# def __init__(self, *args, **kw):
# super().__init__(*args, **kw)
#
# self.client = ActiveCollab2Client(self.config.url,
# self.config.key,
# self.config.user_id,
# self.config.projects,
# self.target)
#
# def get_owner(self, issue):
# # TODO
# raise NotImplementedError(
# "This service has not implemented support for 'only_if_assigned'.")
#
# def issues(self):
# # Loop through each project
# start = time.time()
# issue_generators = []
# projects = self.config.projects
# for project in projects:
# for project_id, project_name in project.items():
# log.debug(
# " Getting tasks for #" + project_id +
# " " + project_name + '"')
# issue_generators.append(
# self.client.get_issue_generator(
# self.config.user_id, project_id, project_name
# )
# )
#
# log.debug(" Elapsed Time: %s" % (time.time() - start))
#
# for record in itertools.chain(*issue_generators):
# yield self.get_issue_for_record(record)
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
. Output only the next line. | self.service = self.get_mock_service(ActiveCollab2Service) |
Using the snippet: <|code_start|>
class TestLoggingPath(unittest.TestCase):
def setUp(self):
self.dir = os.getcwd()
os.chdir(os.path.expanduser('~'))
def test_log_relative_path(self):
self.assertEqual(
<|code_end|>
, determine the next line of code. You have imports:
import os
import unittest
from bugwarrior.config import schema, load
from ..base import ConfigTest
and context (class names, function names, or code) available:
# Path: bugwarrior/config/schema.py
# class StrippedTrailingSlashUrl(pydantic.AnyUrl):
# class UrlSchemeError(pydantic.errors.UrlSchemeError):
# class NoSchemeUrl(StrippedTrailingSlashUrl):
# class ConfigList(frozenset):
# class ExpandedPath(type(pathlib.Path())): # type: ignore
# class LoggingPath(ExpandedPath):
# class TaskrcPath(ExpandedPath):
# class PydanticConfig(pydantic.BaseConfig):
# class MainSectionConfig(pydantic.BaseModel):
# class Config(PydanticConfig):
# class Hooks(pydantic.BaseModel):
# class Notifications(pydantic.BaseModel):
# class SchemaBase(pydantic.BaseSettings):
# class ValidationErrorEnhancedMessages(list):
# class ServiceConfigMetaclass(pydantic.main.ModelMetaclass):
# class PydanticServiceConfig(PydanticConfig):
# class ServiceConfig(_ServiceConfig, # type: ignore # (dynamic base class)
# metaclass=ServiceConfigMetaclass, prefix=None):
# def validate(cls, value, field, config):
# def validate_parts(
# cls, parts: typing.Dict[str, str]) -> typing.Dict[str, str]:
# def __get_validators__(cls):
# def validate(cls, value):
# def __get_validators__(cls):
# def validate(cls, path):
# def validate(cls, path):
# def validate(cls, path):
# def alias_generator(string: str) -> str:
# def __init__(self, error: pydantic.ValidationError, targets, main_section):
# def __str__(self):
# def display_error_loc(e):
# def display_error(self, e, error, model):
# def flatten(self, err, loc=None):
# def raise_validation_error(msg, config_path, no_errors=1):
# def validate_config(config, main_section, config_path):
# def __new__(mcs, name, bases, namespace, prefix, **kwargs):
# def alias_generator(string: str) -> str:
# DEFAULT: dict # configparser feature
#
# Path: bugwarrior/config/load.py
# BUGWARRIORRC = "BUGWARRIORRC"
# def configure_logging(logfile, loglevel):
# def get_config_path():
# def remove_inactive_flavors(rawconfig, main_section):
# def load_config(main_section, interactive):
# def __init__(self, *args, allow_no_value=True, **kwargs):
# def getint(self, section, option):
# def optionxform(option):
# class BugwarriorConfigParser(configparser.ConfigParser):
#
# Path: tests/base.py
# class ConfigTest(unittest.TestCase):
# """
# Creates config files, configures the environment, and cleans up afterwards.
# """
# def setUp(self):
# self.old_environ = os.environ.copy()
# self.tempdir = tempfile.mkdtemp(prefix='bugwarrior')
#
# # Create temporary config files.
# self.taskrc = os.path.join(self.tempdir, '.taskrc')
# self.lists_path = os.path.join(self.tempdir, 'lists')
# os.mkdir(self.lists_path)
# with open(self.taskrc, 'w+') as fout:
# fout.write('data.location=%s\n' % self.lists_path)
#
# # Configure environment.
# os.environ['HOME'] = self.tempdir
# os.environ.pop(config.BUGWARRIORRC, None)
# os.environ.pop('TASKRC', None)
# os.environ.pop('XDG_CONFIG_HOME', None)
# os.environ.pop('XDG_CONFIG_DIRS', None)
#
# def tearDown(self):
# shutil.rmtree(self.tempdir, ignore_errors=True)
# os.environ = self.old_environ
#
# @pytest.fixture(autouse=True)
# def inject_fixtures(self, caplog):
# self.caplog = caplog
#
# def validate(self):
# conf = schema.validate_config(self.config, 'general', 'configpath')
# conf['general'].data = data.BugwarriorData(self.lists_path)
# conf['general'].interactive = False
# return conf
#
# def assertValidationError(self, expected):
#
# with self.assertRaises(SystemExit):
# self.validate()
#
# # Only one message should be logged.
# self.assertEqual(len(self.caplog.records), 1)
#
# self.assertIn(expected, self.caplog.records[0].message)
. Output only the next line. | schema.LoggingPath.validate('bugwarrior.log'), |
Based on the snippet: <|code_start|> )
def test_log_envvar(self):
self.assertEqual(
schema.LoggingPath.validate('$HOME/bugwarrior.log'),
'bugwarrior.log',
)
def tearDown(self):
os.chdir(self.dir)
class TestConfigList(unittest.TestCase):
def test_configlist(self):
self.assertEqual(
schema.ConfigList.validate('project_bar,project_baz'),
['project_bar', 'project_baz']
)
def test_configlist_jinja(self):
self.assertEqual(
schema.ConfigList.validate(
"work, jira, {{jirastatus|lower|replace(' ','_')}}"),
['work', 'jira', "{{jirastatus|lower|replace(' ','_')}}"]
)
class TestValidation(ConfigTest):
def setUp(self):
super().setUp()
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import unittest
from bugwarrior.config import schema, load
from ..base import ConfigTest
and context (classes, functions, sometimes code) from other files:
# Path: bugwarrior/config/schema.py
# class StrippedTrailingSlashUrl(pydantic.AnyUrl):
# class UrlSchemeError(pydantic.errors.UrlSchemeError):
# class NoSchemeUrl(StrippedTrailingSlashUrl):
# class ConfigList(frozenset):
# class ExpandedPath(type(pathlib.Path())): # type: ignore
# class LoggingPath(ExpandedPath):
# class TaskrcPath(ExpandedPath):
# class PydanticConfig(pydantic.BaseConfig):
# class MainSectionConfig(pydantic.BaseModel):
# class Config(PydanticConfig):
# class Hooks(pydantic.BaseModel):
# class Notifications(pydantic.BaseModel):
# class SchemaBase(pydantic.BaseSettings):
# class ValidationErrorEnhancedMessages(list):
# class ServiceConfigMetaclass(pydantic.main.ModelMetaclass):
# class PydanticServiceConfig(PydanticConfig):
# class ServiceConfig(_ServiceConfig, # type: ignore # (dynamic base class)
# metaclass=ServiceConfigMetaclass, prefix=None):
# def validate(cls, value, field, config):
# def validate_parts(
# cls, parts: typing.Dict[str, str]) -> typing.Dict[str, str]:
# def __get_validators__(cls):
# def validate(cls, value):
# def __get_validators__(cls):
# def validate(cls, path):
# def validate(cls, path):
# def validate(cls, path):
# def alias_generator(string: str) -> str:
# def __init__(self, error: pydantic.ValidationError, targets, main_section):
# def __str__(self):
# def display_error_loc(e):
# def display_error(self, e, error, model):
# def flatten(self, err, loc=None):
# def raise_validation_error(msg, config_path, no_errors=1):
# def validate_config(config, main_section, config_path):
# def __new__(mcs, name, bases, namespace, prefix, **kwargs):
# def alias_generator(string: str) -> str:
# DEFAULT: dict # configparser feature
#
# Path: bugwarrior/config/load.py
# BUGWARRIORRC = "BUGWARRIORRC"
# def configure_logging(logfile, loglevel):
# def get_config_path():
# def remove_inactive_flavors(rawconfig, main_section):
# def load_config(main_section, interactive):
# def __init__(self, *args, allow_no_value=True, **kwargs):
# def getint(self, section, option):
# def optionxform(option):
# class BugwarriorConfigParser(configparser.ConfigParser):
#
# Path: tests/base.py
# class ConfigTest(unittest.TestCase):
# """
# Creates config files, configures the environment, and cleans up afterwards.
# """
# def setUp(self):
# self.old_environ = os.environ.copy()
# self.tempdir = tempfile.mkdtemp(prefix='bugwarrior')
#
# # Create temporary config files.
# self.taskrc = os.path.join(self.tempdir, '.taskrc')
# self.lists_path = os.path.join(self.tempdir, 'lists')
# os.mkdir(self.lists_path)
# with open(self.taskrc, 'w+') as fout:
# fout.write('data.location=%s\n' % self.lists_path)
#
# # Configure environment.
# os.environ['HOME'] = self.tempdir
# os.environ.pop(config.BUGWARRIORRC, None)
# os.environ.pop('TASKRC', None)
# os.environ.pop('XDG_CONFIG_HOME', None)
# os.environ.pop('XDG_CONFIG_DIRS', None)
#
# def tearDown(self):
# shutil.rmtree(self.tempdir, ignore_errors=True)
# os.environ = self.old_environ
#
# @pytest.fixture(autouse=True)
# def inject_fixtures(self, caplog):
# self.caplog = caplog
#
# def validate(self):
# conf = schema.validate_config(self.config, 'general', 'configpath')
# conf['general'].data = data.BugwarriorData(self.lists_path)
# conf['general'].interactive = False
# return conf
#
# def assertValidationError(self, expected):
#
# with self.assertRaises(SystemExit):
# self.validate()
#
# # Only one message should be logged.
# self.assertEqual(len(self.caplog.records), 1)
#
# self.assertIn(expected, self.caplog.records[0].message)
. Output only the next line. | self.config = load.BugwarriorConfigParser() |
Predict the next line for this snippet: <|code_start|> self.assertEqual(
schema.LoggingPath.validate('~/bugwarrior.log'),
'bugwarrior.log',
)
def test_log_envvar(self):
self.assertEqual(
schema.LoggingPath.validate('$HOME/bugwarrior.log'),
'bugwarrior.log',
)
def tearDown(self):
os.chdir(self.dir)
class TestConfigList(unittest.TestCase):
def test_configlist(self):
self.assertEqual(
schema.ConfigList.validate('project_bar,project_baz'),
['project_bar', 'project_baz']
)
def test_configlist_jinja(self):
self.assertEqual(
schema.ConfigList.validate(
"work, jira, {{jirastatus|lower|replace(' ','_')}}"),
['work', 'jira', "{{jirastatus|lower|replace(' ','_')}}"]
)
<|code_end|>
with the help of current file imports:
import os
import unittest
from bugwarrior.config import schema, load
from ..base import ConfigTest
and context from other files:
# Path: bugwarrior/config/schema.py
# class StrippedTrailingSlashUrl(pydantic.AnyUrl):
# class UrlSchemeError(pydantic.errors.UrlSchemeError):
# class NoSchemeUrl(StrippedTrailingSlashUrl):
# class ConfigList(frozenset):
# class ExpandedPath(type(pathlib.Path())): # type: ignore
# class LoggingPath(ExpandedPath):
# class TaskrcPath(ExpandedPath):
# class PydanticConfig(pydantic.BaseConfig):
# class MainSectionConfig(pydantic.BaseModel):
# class Config(PydanticConfig):
# class Hooks(pydantic.BaseModel):
# class Notifications(pydantic.BaseModel):
# class SchemaBase(pydantic.BaseSettings):
# class ValidationErrorEnhancedMessages(list):
# class ServiceConfigMetaclass(pydantic.main.ModelMetaclass):
# class PydanticServiceConfig(PydanticConfig):
# class ServiceConfig(_ServiceConfig, # type: ignore # (dynamic base class)
# metaclass=ServiceConfigMetaclass, prefix=None):
# def validate(cls, value, field, config):
# def validate_parts(
# cls, parts: typing.Dict[str, str]) -> typing.Dict[str, str]:
# def __get_validators__(cls):
# def validate(cls, value):
# def __get_validators__(cls):
# def validate(cls, path):
# def validate(cls, path):
# def validate(cls, path):
# def alias_generator(string: str) -> str:
# def __init__(self, error: pydantic.ValidationError, targets, main_section):
# def __str__(self):
# def display_error_loc(e):
# def display_error(self, e, error, model):
# def flatten(self, err, loc=None):
# def raise_validation_error(msg, config_path, no_errors=1):
# def validate_config(config, main_section, config_path):
# def __new__(mcs, name, bases, namespace, prefix, **kwargs):
# def alias_generator(string: str) -> str:
# DEFAULT: dict # configparser feature
#
# Path: bugwarrior/config/load.py
# BUGWARRIORRC = "BUGWARRIORRC"
# def configure_logging(logfile, loglevel):
# def get_config_path():
# def remove_inactive_flavors(rawconfig, main_section):
# def load_config(main_section, interactive):
# def __init__(self, *args, allow_no_value=True, **kwargs):
# def getint(self, section, option):
# def optionxform(option):
# class BugwarriorConfigParser(configparser.ConfigParser):
#
# Path: tests/base.py
# class ConfigTest(unittest.TestCase):
# """
# Creates config files, configures the environment, and cleans up afterwards.
# """
# def setUp(self):
# self.old_environ = os.environ.copy()
# self.tempdir = tempfile.mkdtemp(prefix='bugwarrior')
#
# # Create temporary config files.
# self.taskrc = os.path.join(self.tempdir, '.taskrc')
# self.lists_path = os.path.join(self.tempdir, 'lists')
# os.mkdir(self.lists_path)
# with open(self.taskrc, 'w+') as fout:
# fout.write('data.location=%s\n' % self.lists_path)
#
# # Configure environment.
# os.environ['HOME'] = self.tempdir
# os.environ.pop(config.BUGWARRIORRC, None)
# os.environ.pop('TASKRC', None)
# os.environ.pop('XDG_CONFIG_HOME', None)
# os.environ.pop('XDG_CONFIG_DIRS', None)
#
# def tearDown(self):
# shutil.rmtree(self.tempdir, ignore_errors=True)
# os.environ = self.old_environ
#
# @pytest.fixture(autouse=True)
# def inject_fixtures(self, caplog):
# self.caplog = caplog
#
# def validate(self):
# conf = schema.validate_config(self.config, 'general', 'configpath')
# conf['general'].data = data.BugwarriorData(self.lists_path)
# conf['general'].interactive = False
# return conf
#
# def assertValidationError(self, expected):
#
# with self.assertRaises(SystemExit):
# self.validate()
#
# # Only one message should be logged.
# self.assertEqual(len(self.caplog.records), 1)
#
# self.assertIn(expected, self.caplog.records[0].message)
, which may contain function names, class names, or code. Output only the next line. | class TestValidation(ConfigTest): |
Given the code snippet: <|code_start|>
class TestTeamworkIssue(AbstractServiceTest, ServiceTest):
SERVICE_CONFIG = {
'service': 'teamwork_projects',
'teamwork_projects.host': 'https://test.teamwork_projects.com',
'teamwork_projects.token': 'arbitrary_token',
}
@responses.activate
def setUp(self):
super().setUp()
self.add_response(
'https://test.teamwork_projects.com/authenticate.json',
json={
'account': {
'userId': 5,
'firstname': 'Greg',
'lastname': 'McCoy'
}
}
)
<|code_end|>
, generate the next line using the imports in this file:
from .base import ServiceTest, AbstractServiceTest
from bugwarrior.services.teamwork_projects import TeamworkService, TeamworkClient
from dateutil.tz import tzutc
import responses
import datetime
and context (functions, classes, or occasionally code) from other files:
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
#
# Path: bugwarrior/services/teamwork_projects.py
# class TeamworkService(IssueService):
# ISSUE_CLASS = TeamworkIssue
# CONFIG_SCHEMA = TeamworkConfig
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.client = TeamworkClient(self.config.host, self.config.token)
# user = self.client.authenticate()
# self.user_id = user["account"]["userId"]
# self.name = user["account"]["firstname"] + " " + user["account"]["lastname"]
#
# def get_comments(self, issue):
# if self.main_config.annotation_comments:
# if issue.get("comments-count", 0) > 0:
# endpoint = "/tasks/{task_id}/comments.json".format(task_id=issue["id"])
# comments = self.client.call_api("GET", endpoint)
# comment_list = []
# for comment in comments["comments"]:
# url = self.config.host + "/#/tasks/" + str(issue["id"])
# author = "{first} {last}".format(
# first=comment["author-firstname"],
# last=comment["author-lastname"],
# )
# text = comment["body"]
# comment_list.append((author, text))
# return self.build_annotations(comment_list, None)
# return []
#
# def get_owner(self, issue):
# # TODO
# raise NotImplementedError(
# "This service has not implemented support for 'only_if_assigned'.")
#
# def issues(self):
# response = self.client.call_api("GET", "/tasks.json")#, data= { "responsible-party-ids": self.user_id })
# for issue in response["todo-items"]:
# # Determine if issue is need by if following comments, changes or assigned
# if issue["userFollowingComments"] or issue["userFollowingChanges"]\
# or (self.user_id in issue.get("responsible-party-ids", "")):
# issue_obj = self.get_issue_for_record(issue)
# extra = {
# "host": self.config.host,
# 'annotations': self.get_comments(issue),
# }
# issue_obj.update_extra(extra)
# yield issue_obj
#
# class TeamworkClient(ServiceClient):
#
# def __init__(self, host, token):
# self.host = host
# self.token = token
#
# def authenticate(self):
# response = requests.get(self.host + "/authenticate.json", auth=(self.token, ""))
# return self.json_response(response)
#
# def call_api(self, method, endpoint, data=None):
# response = requests.get(self.host + endpoint, auth=(self.token, ""), params=data)
# return self.json_response(response)
. Output only the next line. | self.service = self.get_mock_service(TeamworkService) |
Based on the snippet: <|code_start|>
class TestTemplates(ServiceTest):
def setUp(self):
super().setUp()
self.arbitrary_default_description = 'Construct Library on Terminus'
self.arbitrary_issue = {
'project': 'end_of_empire',
'priority': 'H',
}
def get_issue(
self, templates=None, issue=None, description=None, add_tags=None
):
templates = {} if templates is None else templates
origin = {
'annotation_length': 100, # Arbitrary
'default_priority': 'H', # Arbitrary
'description_length': 100, # Arbitrary
'templates': templates,
'shorten': False, # Arbitrary
'add_tags': add_tags if add_tags else [],
}
<|code_end|>
, predict the immediate next line with the help of imports:
from .base import ServiceTest
from .test_service import DumbIssue
and context (classes, functions, sometimes code) from other files:
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# Path: tests/test_service.py
# class DumbIssue(services.Issue):
# """
# Implement the required methods but they shouldn't be called.
# """
# def get_default_description(self):
# raise NotImplementedError
#
# def to_taskwarrior(self):
# raise NotImplementedError
. Output only the next line. | issue = DumbIssue({}, origin) |
Predict the next line for this snippet: <|code_start|>
class TestTeamlabIssue(AbstractServiceTest, ServiceTest):
SERVICE_CONFIG = {
'service': 'teamlab',
'teamlab.hostname': 'something',
'teamlab.login': 'alkjdsf',
'teamlab.password': 'lkjklj',
'teamlab.project_name': 'abcdef',
}
arbitrary_issue = {
'title': 'Hello',
'id': 10,
'projectOwner': {
'id': 140,
},
'status': 1,
}
def setUp(self):
super().setUp()
with mock.patch(
'bugwarrior.services.teamlab.TeamLabClient.authenticate'
):
<|code_end|>
with the help of current file imports:
from unittest import mock
from bugwarrior.services.teamlab import TeamLabService
from .base import ServiceTest, AbstractServiceTest
import responses
and context from other files:
# Path: bugwarrior/services/teamlab.py
# class TeamLabService(IssueService):
# ISSUE_CLASS = TeamLabIssue
# CONFIG_SCHEMA = TeamLabConfig
#
# def __init__(self, *args, **kw):
# super().__init__(*args, **kw)
#
# _password = self.get_password('password', self.config.login)
#
# self.client = TeamLabClient(self.config.hostname)
# self.client.authenticate(self.config.login, _password)
#
# self.project_name = self.config.project_name or self.config.hostname
#
# @staticmethod
# def get_keyring_service(config):
# return f"teamlab://{config.login}@{config.hostname}"
#
# def get_service_metadata(self):
# return {
# 'hostname': self.config.hostname,
# 'project_name': self.project_name,
# }
#
# def get_owner(self, issue):
# # TODO
# raise NotImplementedError(
# "This service has not implemented support for 'only_if_assigned'.")
#
# def issues(self):
# issues = self.client.get_task_list()
# log.debug(" Remote has %i total issues.", len(issues))
#
# # Filter out closed tasks.
# issues = [i for i in issues if i["status"] == 1]
# log.debug(" Remote has %i active issues.", len(issues))
#
# for issue in issues:
# yield self.get_issue_for_record(issue)
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
, which may contain function names, class names, or code. Output only the next line. | self.service = self.get_mock_service(TeamLabService) |
Given snippet: <|code_start|>
class TestGetConfigPath(ConfigTest):
def create(self, path):
"""
Create an empty file in the temporary directory, return the full path.
"""
fpath = os.path.join(self.tempdir, path)
if not os.path.exists(os.path.dirname(fpath)):
os.makedirs(os.path.dirname(fpath))
open(fpath, 'a').close()
return fpath
def test_default(self):
"""
If it exists, use the file at $XDG_CONFIG_HOME/bugwarrior/bugwarriorrc
"""
rc = self.create('.config/bugwarrior/bugwarriorrc')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from unittest import TestCase
from bugwarrior.config import load
from ..base import ConfigTest
and context:
# Path: bugwarrior/config/load.py
# BUGWARRIORRC = "BUGWARRIORRC"
# def configure_logging(logfile, loglevel):
# def get_config_path():
# def remove_inactive_flavors(rawconfig, main_section):
# def load_config(main_section, interactive):
# def __init__(self, *args, allow_no_value=True, **kwargs):
# def getint(self, section, option):
# def optionxform(option):
# class BugwarriorConfigParser(configparser.ConfigParser):
#
# Path: tests/base.py
# class ConfigTest(unittest.TestCase):
# """
# Creates config files, configures the environment, and cleans up afterwards.
# """
# def setUp(self):
# self.old_environ = os.environ.copy()
# self.tempdir = tempfile.mkdtemp(prefix='bugwarrior')
#
# # Create temporary config files.
# self.taskrc = os.path.join(self.tempdir, '.taskrc')
# self.lists_path = os.path.join(self.tempdir, 'lists')
# os.mkdir(self.lists_path)
# with open(self.taskrc, 'w+') as fout:
# fout.write('data.location=%s\n' % self.lists_path)
#
# # Configure environment.
# os.environ['HOME'] = self.tempdir
# os.environ.pop(config.BUGWARRIORRC, None)
# os.environ.pop('TASKRC', None)
# os.environ.pop('XDG_CONFIG_HOME', None)
# os.environ.pop('XDG_CONFIG_DIRS', None)
#
# def tearDown(self):
# shutil.rmtree(self.tempdir, ignore_errors=True)
# os.environ = self.old_environ
#
# @pytest.fixture(autouse=True)
# def inject_fixtures(self, caplog):
# self.caplog = caplog
#
# def validate(self):
# conf = schema.validate_config(self.config, 'general', 'configpath')
# conf['general'].data = data.BugwarriorData(self.lists_path)
# conf['general'].interactive = False
# return conf
#
# def assertValidationError(self, expected):
#
# with self.assertRaises(SystemExit):
# self.validate()
#
# # Only one message should be logged.
# self.assertEqual(len(self.caplog.records), 1)
#
# self.assertIn(expected, self.caplog.records[0].message)
which might include code, classes, or functions. Output only the next line. | self.assertEqual(load.get_config_path(), rc) |
Given snippet: <|code_start|>
class TestData(ConfigTest):
def setUp(self):
super().setUp()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import json
from bugwarrior.config import data, load, schema
from ..base import ConfigTest
and context:
# Path: bugwarrior/config/data.py
# def get_data_path(taskrc):
# def __init__(self, data_path):
# def get_data(self):
# def get(self, key):
# def set(self, key, value):
# class BugwarriorData:
#
# Path: bugwarrior/config/load.py
# BUGWARRIORRC = "BUGWARRIORRC"
# def configure_logging(logfile, loglevel):
# def get_config_path():
# def remove_inactive_flavors(rawconfig, main_section):
# def load_config(main_section, interactive):
# def __init__(self, *args, allow_no_value=True, **kwargs):
# def getint(self, section, option):
# def optionxform(option):
# class BugwarriorConfigParser(configparser.ConfigParser):
#
# Path: bugwarrior/config/schema.py
# class StrippedTrailingSlashUrl(pydantic.AnyUrl):
# class UrlSchemeError(pydantic.errors.UrlSchemeError):
# class NoSchemeUrl(StrippedTrailingSlashUrl):
# class ConfigList(frozenset):
# class ExpandedPath(type(pathlib.Path())): # type: ignore
# class LoggingPath(ExpandedPath):
# class TaskrcPath(ExpandedPath):
# class PydanticConfig(pydantic.BaseConfig):
# class MainSectionConfig(pydantic.BaseModel):
# class Config(PydanticConfig):
# class Hooks(pydantic.BaseModel):
# class Notifications(pydantic.BaseModel):
# class SchemaBase(pydantic.BaseSettings):
# class ValidationErrorEnhancedMessages(list):
# class ServiceConfigMetaclass(pydantic.main.ModelMetaclass):
# class PydanticServiceConfig(PydanticConfig):
# class ServiceConfig(_ServiceConfig, # type: ignore # (dynamic base class)
# metaclass=ServiceConfigMetaclass, prefix=None):
# def validate(cls, value, field, config):
# def validate_parts(
# cls, parts: typing.Dict[str, str]) -> typing.Dict[str, str]:
# def __get_validators__(cls):
# def validate(cls, value):
# def __get_validators__(cls):
# def validate(cls, path):
# def validate(cls, path):
# def validate(cls, path):
# def alias_generator(string: str) -> str:
# def __init__(self, error: pydantic.ValidationError, targets, main_section):
# def __str__(self):
# def display_error_loc(e):
# def display_error(self, e, error, model):
# def flatten(self, err, loc=None):
# def raise_validation_error(msg, config_path, no_errors=1):
# def validate_config(config, main_section, config_path):
# def __new__(mcs, name, bases, namespace, prefix, **kwargs):
# def alias_generator(string: str) -> str:
# DEFAULT: dict # configparser feature
#
# Path: tests/base.py
# class ConfigTest(unittest.TestCase):
# """
# Creates config files, configures the environment, and cleans up afterwards.
# """
# def setUp(self):
# self.old_environ = os.environ.copy()
# self.tempdir = tempfile.mkdtemp(prefix='bugwarrior')
#
# # Create temporary config files.
# self.taskrc = os.path.join(self.tempdir, '.taskrc')
# self.lists_path = os.path.join(self.tempdir, 'lists')
# os.mkdir(self.lists_path)
# with open(self.taskrc, 'w+') as fout:
# fout.write('data.location=%s\n' % self.lists_path)
#
# # Configure environment.
# os.environ['HOME'] = self.tempdir
# os.environ.pop(config.BUGWARRIORRC, None)
# os.environ.pop('TASKRC', None)
# os.environ.pop('XDG_CONFIG_HOME', None)
# os.environ.pop('XDG_CONFIG_DIRS', None)
#
# def tearDown(self):
# shutil.rmtree(self.tempdir, ignore_errors=True)
# os.environ = self.old_environ
#
# @pytest.fixture(autouse=True)
# def inject_fixtures(self, caplog):
# self.caplog = caplog
#
# def validate(self):
# conf = schema.validate_config(self.config, 'general', 'configpath')
# conf['general'].data = data.BugwarriorData(self.lists_path)
# conf['general'].interactive = False
# return conf
#
# def assertValidationError(self, expected):
#
# with self.assertRaises(SystemExit):
# self.validate()
#
# # Only one message should be logged.
# self.assertEqual(len(self.caplog.records), 1)
#
# self.assertIn(expected, self.caplog.records[0].message)
which might include code, classes, or functions. Output only the next line. | self.data = data.BugwarriorData(self.lists_path) |
Next line prediction: <|code_start|> permissions = oct(os.stat(self.data.datafile).st_mode & 0o777)
# python2 -> 0600, python3 -> 0o600
self.assertIn(permissions, ['0600', '0o600'])
def test_get_set(self):
# "touch" data file.
with open(self.data.datafile, 'w+') as handle:
json.dump({'old': 'stuff'}, handle)
self.data.set('key', 'value')
self.assertEqual(self.data.get('key'), 'value')
self.assertEqual(
self.data.get_data(), {'old': 'stuff', 'key': 'value'})
self.assert0600()
def test_set_first_time(self):
self.data.set('key', 'value')
self.assertEqual(self.data.get('key'), 'value')
self.assert0600()
def test_path_attribute(self):
self.assertEqual(self.data.path, self.lists_path)
class TestGetDataPath(ConfigTest):
def setUp(self):
super().setUp()
<|code_end|>
. Use current file imports:
(import os
import json
from bugwarrior.config import data, load, schema
from ..base import ConfigTest)
and context including class names, function names, or small code snippets from other files:
# Path: bugwarrior/config/data.py
# def get_data_path(taskrc):
# def __init__(self, data_path):
# def get_data(self):
# def get(self, key):
# def set(self, key, value):
# class BugwarriorData:
#
# Path: bugwarrior/config/load.py
# BUGWARRIORRC = "BUGWARRIORRC"
# def configure_logging(logfile, loglevel):
# def get_config_path():
# def remove_inactive_flavors(rawconfig, main_section):
# def load_config(main_section, interactive):
# def __init__(self, *args, allow_no_value=True, **kwargs):
# def getint(self, section, option):
# def optionxform(option):
# class BugwarriorConfigParser(configparser.ConfigParser):
#
# Path: bugwarrior/config/schema.py
# class StrippedTrailingSlashUrl(pydantic.AnyUrl):
# class UrlSchemeError(pydantic.errors.UrlSchemeError):
# class NoSchemeUrl(StrippedTrailingSlashUrl):
# class ConfigList(frozenset):
# class ExpandedPath(type(pathlib.Path())): # type: ignore
# class LoggingPath(ExpandedPath):
# class TaskrcPath(ExpandedPath):
# class PydanticConfig(pydantic.BaseConfig):
# class MainSectionConfig(pydantic.BaseModel):
# class Config(PydanticConfig):
# class Hooks(pydantic.BaseModel):
# class Notifications(pydantic.BaseModel):
# class SchemaBase(pydantic.BaseSettings):
# class ValidationErrorEnhancedMessages(list):
# class ServiceConfigMetaclass(pydantic.main.ModelMetaclass):
# class PydanticServiceConfig(PydanticConfig):
# class ServiceConfig(_ServiceConfig, # type: ignore # (dynamic base class)
# metaclass=ServiceConfigMetaclass, prefix=None):
# def validate(cls, value, field, config):
# def validate_parts(
# cls, parts: typing.Dict[str, str]) -> typing.Dict[str, str]:
# def __get_validators__(cls):
# def validate(cls, value):
# def __get_validators__(cls):
# def validate(cls, path):
# def validate(cls, path):
# def validate(cls, path):
# def alias_generator(string: str) -> str:
# def __init__(self, error: pydantic.ValidationError, targets, main_section):
# def __str__(self):
# def display_error_loc(e):
# def display_error(self, e, error, model):
# def flatten(self, err, loc=None):
# def raise_validation_error(msg, config_path, no_errors=1):
# def validate_config(config, main_section, config_path):
# def __new__(mcs, name, bases, namespace, prefix, **kwargs):
# def alias_generator(string: str) -> str:
# DEFAULT: dict # configparser feature
#
# Path: tests/base.py
# class ConfigTest(unittest.TestCase):
# """
# Creates config files, configures the environment, and cleans up afterwards.
# """
# def setUp(self):
# self.old_environ = os.environ.copy()
# self.tempdir = tempfile.mkdtemp(prefix='bugwarrior')
#
# # Create temporary config files.
# self.taskrc = os.path.join(self.tempdir, '.taskrc')
# self.lists_path = os.path.join(self.tempdir, 'lists')
# os.mkdir(self.lists_path)
# with open(self.taskrc, 'w+') as fout:
# fout.write('data.location=%s\n' % self.lists_path)
#
# # Configure environment.
# os.environ['HOME'] = self.tempdir
# os.environ.pop(config.BUGWARRIORRC, None)
# os.environ.pop('TASKRC', None)
# os.environ.pop('XDG_CONFIG_HOME', None)
# os.environ.pop('XDG_CONFIG_DIRS', None)
#
# def tearDown(self):
# shutil.rmtree(self.tempdir, ignore_errors=True)
# os.environ = self.old_environ
#
# @pytest.fixture(autouse=True)
# def inject_fixtures(self, caplog):
# self.caplog = caplog
#
# def validate(self):
# conf = schema.validate_config(self.config, 'general', 'configpath')
# conf['general'].data = data.BugwarriorData(self.lists_path)
# conf['general'].interactive = False
# return conf
#
# def assertValidationError(self, expected):
#
# with self.assertRaises(SystemExit):
# self.validate()
#
# # Only one message should be logged.
# self.assertEqual(len(self.caplog.records), 1)
#
# self.assertIn(expected, self.caplog.records[0].message)
. Output only the next line. | rawconfig = load.BugwarriorConfigParser() |
Here is a snippet: <|code_start|>
self.data.set('key', 'value')
self.assertEqual(self.data.get('key'), 'value')
self.assertEqual(
self.data.get_data(), {'old': 'stuff', 'key': 'value'})
self.assert0600()
def test_set_first_time(self):
self.data.set('key', 'value')
self.assertEqual(self.data.get('key'), 'value')
self.assert0600()
def test_path_attribute(self):
self.assertEqual(self.data.path, self.lists_path)
class TestGetDataPath(ConfigTest):
def setUp(self):
super().setUp()
rawconfig = load.BugwarriorConfigParser()
rawconfig.add_section('general')
rawconfig.set('general', 'targets', 'my_service')
rawconfig.add_section('my_service')
rawconfig.set('my_service', 'service', 'github')
rawconfig.set('my_service', 'github.login', 'ralphbean')
rawconfig.set('my_service', 'github.password', 'abc123')
rawconfig.set('my_service', 'github.username', 'ralphbean')
<|code_end|>
. Write the next line using the current file imports:
import os
import json
from bugwarrior.config import data, load, schema
from ..base import ConfigTest
and context from other files:
# Path: bugwarrior/config/data.py
# def get_data_path(taskrc):
# def __init__(self, data_path):
# def get_data(self):
# def get(self, key):
# def set(self, key, value):
# class BugwarriorData:
#
# Path: bugwarrior/config/load.py
# BUGWARRIORRC = "BUGWARRIORRC"
# def configure_logging(logfile, loglevel):
# def get_config_path():
# def remove_inactive_flavors(rawconfig, main_section):
# def load_config(main_section, interactive):
# def __init__(self, *args, allow_no_value=True, **kwargs):
# def getint(self, section, option):
# def optionxform(option):
# class BugwarriorConfigParser(configparser.ConfigParser):
#
# Path: bugwarrior/config/schema.py
# class StrippedTrailingSlashUrl(pydantic.AnyUrl):
# class UrlSchemeError(pydantic.errors.UrlSchemeError):
# class NoSchemeUrl(StrippedTrailingSlashUrl):
# class ConfigList(frozenset):
# class ExpandedPath(type(pathlib.Path())): # type: ignore
# class LoggingPath(ExpandedPath):
# class TaskrcPath(ExpandedPath):
# class PydanticConfig(pydantic.BaseConfig):
# class MainSectionConfig(pydantic.BaseModel):
# class Config(PydanticConfig):
# class Hooks(pydantic.BaseModel):
# class Notifications(pydantic.BaseModel):
# class SchemaBase(pydantic.BaseSettings):
# class ValidationErrorEnhancedMessages(list):
# class ServiceConfigMetaclass(pydantic.main.ModelMetaclass):
# class PydanticServiceConfig(PydanticConfig):
# class ServiceConfig(_ServiceConfig, # type: ignore # (dynamic base class)
# metaclass=ServiceConfigMetaclass, prefix=None):
# def validate(cls, value, field, config):
# def validate_parts(
# cls, parts: typing.Dict[str, str]) -> typing.Dict[str, str]:
# def __get_validators__(cls):
# def validate(cls, value):
# def __get_validators__(cls):
# def validate(cls, path):
# def validate(cls, path):
# def validate(cls, path):
# def alias_generator(string: str) -> str:
# def __init__(self, error: pydantic.ValidationError, targets, main_section):
# def __str__(self):
# def display_error_loc(e):
# def display_error(self, e, error, model):
# def flatten(self, err, loc=None):
# def raise_validation_error(msg, config_path, no_errors=1):
# def validate_config(config, main_section, config_path):
# def __new__(mcs, name, bases, namespace, prefix, **kwargs):
# def alias_generator(string: str) -> str:
# DEFAULT: dict # configparser feature
#
# Path: tests/base.py
# class ConfigTest(unittest.TestCase):
# """
# Creates config files, configures the environment, and cleans up afterwards.
# """
# def setUp(self):
# self.old_environ = os.environ.copy()
# self.tempdir = tempfile.mkdtemp(prefix='bugwarrior')
#
# # Create temporary config files.
# self.taskrc = os.path.join(self.tempdir, '.taskrc')
# self.lists_path = os.path.join(self.tempdir, 'lists')
# os.mkdir(self.lists_path)
# with open(self.taskrc, 'w+') as fout:
# fout.write('data.location=%s\n' % self.lists_path)
#
# # Configure environment.
# os.environ['HOME'] = self.tempdir
# os.environ.pop(config.BUGWARRIORRC, None)
# os.environ.pop('TASKRC', None)
# os.environ.pop('XDG_CONFIG_HOME', None)
# os.environ.pop('XDG_CONFIG_DIRS', None)
#
# def tearDown(self):
# shutil.rmtree(self.tempdir, ignore_errors=True)
# os.environ = self.old_environ
#
# @pytest.fixture(autouse=True)
# def inject_fixtures(self, caplog):
# self.caplog = caplog
#
# def validate(self):
# conf = schema.validate_config(self.config, 'general', 'configpath')
# conf['general'].data = data.BugwarriorData(self.lists_path)
# conf['general'].interactive = False
# return conf
#
# def assertValidationError(self, expected):
#
# with self.assertRaises(SystemExit):
# self.validate()
#
# # Only one message should be logged.
# self.assertEqual(len(self.caplog.records), 1)
#
# self.assertIn(expected, self.caplog.records[0].message)
, which may include functions, classes, or code. Output only the next line. | self.config = schema.validate_config( |
Using the snippet: <|code_start|> server = FakeTracServer()
def __init__(self, record):
self.record = record
@staticmethod
def query_tickets(query):
return ['something']
def get_ticket(self, ticket):
return (1, None, None, self.record)
class TestTracIssue(AbstractServiceTest, ServiceTest):
SERVICE_CONFIG = {
'service': 'trac',
'trac.base_uri': 'ljlkajsdfl.com',
'trac.username': 'something',
'trac.password': 'somepwd',
}
arbitrary_issue = {
'url': 'http://some/url.com/',
'summary': 'Some Summary',
'number': 204,
'priority': 'critical',
'component': 'testcomponent',
}
def setUp(self):
super().setUp()
<|code_end|>
, determine the next line of code. You have imports:
from bugwarrior.services.trac import TracService
from .base import ServiceTest, AbstractServiceTest
and context (class names, function names, or code) available:
# Path: bugwarrior/services/trac.py
# class TracService(IssueService):
# ISSUE_CLASS = TracIssue
# CONFIG_SCHEMA = TracConfig
#
# def __init__(self, *args, **kw):
# super().__init__(*args, **kw)
# if self.config.username:
# password = self.get_password('password', self.config.username)
#
# auth = urllib.parse.quote_plus(
# f'{self.config.username}:{password}@')
# else:
# auth = ''
#
# self.trac = None
# uri = f'{self.config.scheme}://{auth}{self.config.base_uri}/'
# if self.config.no_xmlrpc:
# self.uri = uri
# else:
# self.trac = offtrac.TracServer(uri + 'login/xmlrpc')
#
# @staticmethod
# def get_keyring_service(config):
# return f"https://{config.username}@{config.base_uri}/"
#
# def annotations(self, tag, issue, issue_obj):
# annotations = []
# # without offtrac, we can't get issue comments
# if self.trac is None:
# return annotations
# changelog = self.trac.server.ticket.changeLog(issue['number'])
# for time, author, field, oldvalue, newvalue, permament in changelog:
# if field == 'comment':
# annotations.append((author, newvalue, ))
#
# url = issue_obj.get_processed_url(issue['url'])
# return self.build_annotations(annotations, url)
#
# def get_owner(self, issue):
# tag, issue = issue
# return issue.get('owner', None) or None
#
# def issues(self):
# base_url = "https://" + self.config.base_uri
# if self.trac:
# tickets = self.trac.query_tickets('status!=closed&max=0')
# tickets = list(map(self.trac.get_ticket, tickets))
# issues = [(self.target, ticket[3]) for ticket in tickets]
# for i in range(len(issues)):
# issues[i][1]['url'] = "%s/ticket/%i" % (base_url, tickets[i][0])
# issues[i][1]['number'] = tickets[i][0]
# else:
# resp = requests.get(
# self.uri + 'query',
# params={
# 'status': '!closed',
# 'max': '0',
# 'format': 'csv',
# 'col': ['id', 'summary', 'owner', 'priority', 'component'],
# })
# if resp.status_code != 200:
# raise RuntimeError("Trac responded with %s" % resp)
# # strip Trac's bogus BOM
# text = resp.text[1:].lstrip('\ufeff')
# tickets = list(csv.DictReader(StringIO.StringIO(text.encode('utf-8'))))
# issues = [(self.target, ticket) for ticket in tickets]
# for i in range(len(issues)):
# issues[i][1]['url'] = "%s/ticket/%s" % (base_url, tickets[i]['id'])
# issues[i][1]['number'] = int(tickets[i]['id'])
#
# log.debug(" Found %i total.", len(issues))
#
# issues = list(filter(self.include, issues))
# log.debug(" Pruned down to %i", len(issues))
#
# for project, issue in issues:
# issue_obj = self.get_issue_for_record(issue)
# extra = {
# 'annotations': self.annotations(project, issue, issue_obj),
# 'project': project,
# }
# issue_obj.update_extra(extra)
# yield issue_obj
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
. Output only the next line. | self.service = self.get_mock_service(TracService) |
Given the following code snippet before the placeholder: <|code_start|>
class FakeTracTicket:
@staticmethod
def changeLog(issuenumber):
return []
class FakeTracServer:
ticket = FakeTracTicket()
class FakeTracLib:
server = FakeTracServer()
def __init__(self, record):
self.record = record
@staticmethod
def query_tickets(query):
return ['something']
def get_ticket(self, ticket):
return (1, None, None, self.record)
<|code_end|>
, predict the next line using imports from the current file:
from bugwarrior.services.trac import TracService
from .base import ServiceTest, AbstractServiceTest
and context including class names, function names, and sometimes code from other files:
# Path: bugwarrior/services/trac.py
# class TracService(IssueService):
# ISSUE_CLASS = TracIssue
# CONFIG_SCHEMA = TracConfig
#
# def __init__(self, *args, **kw):
# super().__init__(*args, **kw)
# if self.config.username:
# password = self.get_password('password', self.config.username)
#
# auth = urllib.parse.quote_plus(
# f'{self.config.username}:{password}@')
# else:
# auth = ''
#
# self.trac = None
# uri = f'{self.config.scheme}://{auth}{self.config.base_uri}/'
# if self.config.no_xmlrpc:
# self.uri = uri
# else:
# self.trac = offtrac.TracServer(uri + 'login/xmlrpc')
#
# @staticmethod
# def get_keyring_service(config):
# return f"https://{config.username}@{config.base_uri}/"
#
# def annotations(self, tag, issue, issue_obj):
# annotations = []
# # without offtrac, we can't get issue comments
# if self.trac is None:
# return annotations
# changelog = self.trac.server.ticket.changeLog(issue['number'])
# for time, author, field, oldvalue, newvalue, permament in changelog:
# if field == 'comment':
# annotations.append((author, newvalue, ))
#
# url = issue_obj.get_processed_url(issue['url'])
# return self.build_annotations(annotations, url)
#
# def get_owner(self, issue):
# tag, issue = issue
# return issue.get('owner', None) or None
#
# def issues(self):
# base_url = "https://" + self.config.base_uri
# if self.trac:
# tickets = self.trac.query_tickets('status!=closed&max=0')
# tickets = list(map(self.trac.get_ticket, tickets))
# issues = [(self.target, ticket[3]) for ticket in tickets]
# for i in range(len(issues)):
# issues[i][1]['url'] = "%s/ticket/%i" % (base_url, tickets[i][0])
# issues[i][1]['number'] = tickets[i][0]
# else:
# resp = requests.get(
# self.uri + 'query',
# params={
# 'status': '!closed',
# 'max': '0',
# 'format': 'csv',
# 'col': ['id', 'summary', 'owner', 'priority', 'component'],
# })
# if resp.status_code != 200:
# raise RuntimeError("Trac responded with %s" % resp)
# # strip Trac's bogus BOM
# text = resp.text[1:].lstrip('\ufeff')
# tickets = list(csv.DictReader(StringIO.StringIO(text.encode('utf-8'))))
# issues = [(self.target, ticket) for ticket in tickets]
# for i in range(len(issues)):
# issues[i][1]['url'] = "%s/ticket/%s" % (base_url, tickets[i]['id'])
# issues[i][1]['number'] = int(tickets[i]['id'])
#
# log.debug(" Found %i total.", len(issues))
#
# issues = list(filter(self.include, issues))
# log.debug(" Pruned down to %i", len(issues))
#
# for project, issue in issues:
# issue_obj = self.get_issue_for_record(issue)
# extra = {
# 'annotations': self.annotations(project, issue, issue_obj),
# 'project': project,
# }
# issue_obj.update_extra(extra)
# yield issue_obj
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
. Output only the next line. | class TestTracIssue(AbstractServiceTest, ServiceTest): |
Next line prediction: <|code_start|>
class FakeTracTicket:
@staticmethod
def changeLog(issuenumber):
return []
class FakeTracServer:
ticket = FakeTracTicket()
class FakeTracLib:
server = FakeTracServer()
def __init__(self, record):
self.record = record
@staticmethod
def query_tickets(query):
return ['something']
def get_ticket(self, ticket):
return (1, None, None, self.record)
<|code_end|>
. Use current file imports:
(from bugwarrior.services.trac import TracService
from .base import ServiceTest, AbstractServiceTest)
and context including class names, function names, or small code snippets from other files:
# Path: bugwarrior/services/trac.py
# class TracService(IssueService):
# ISSUE_CLASS = TracIssue
# CONFIG_SCHEMA = TracConfig
#
# def __init__(self, *args, **kw):
# super().__init__(*args, **kw)
# if self.config.username:
# password = self.get_password('password', self.config.username)
#
# auth = urllib.parse.quote_plus(
# f'{self.config.username}:{password}@')
# else:
# auth = ''
#
# self.trac = None
# uri = f'{self.config.scheme}://{auth}{self.config.base_uri}/'
# if self.config.no_xmlrpc:
# self.uri = uri
# else:
# self.trac = offtrac.TracServer(uri + 'login/xmlrpc')
#
# @staticmethod
# def get_keyring_service(config):
# return f"https://{config.username}@{config.base_uri}/"
#
# def annotations(self, tag, issue, issue_obj):
# annotations = []
# # without offtrac, we can't get issue comments
# if self.trac is None:
# return annotations
# changelog = self.trac.server.ticket.changeLog(issue['number'])
# for time, author, field, oldvalue, newvalue, permament in changelog:
# if field == 'comment':
# annotations.append((author, newvalue, ))
#
# url = issue_obj.get_processed_url(issue['url'])
# return self.build_annotations(annotations, url)
#
# def get_owner(self, issue):
# tag, issue = issue
# return issue.get('owner', None) or None
#
# def issues(self):
# base_url = "https://" + self.config.base_uri
# if self.trac:
# tickets = self.trac.query_tickets('status!=closed&max=0')
# tickets = list(map(self.trac.get_ticket, tickets))
# issues = [(self.target, ticket[3]) for ticket in tickets]
# for i in range(len(issues)):
# issues[i][1]['url'] = "%s/ticket/%i" % (base_url, tickets[i][0])
# issues[i][1]['number'] = tickets[i][0]
# else:
# resp = requests.get(
# self.uri + 'query',
# params={
# 'status': '!closed',
# 'max': '0',
# 'format': 'csv',
# 'col': ['id', 'summary', 'owner', 'priority', 'component'],
# })
# if resp.status_code != 200:
# raise RuntimeError("Trac responded with %s" % resp)
# # strip Trac's bogus BOM
# text = resp.text[1:].lstrip('\ufeff')
# tickets = list(csv.DictReader(StringIO.StringIO(text.encode('utf-8'))))
# issues = [(self.target, ticket) for ticket in tickets]
# for i in range(len(issues)):
# issues[i][1]['url'] = "%s/ticket/%s" % (base_url, tickets[i]['id'])
# issues[i][1]['number'] = int(tickets[i]['id'])
#
# log.debug(" Found %i total.", len(issues))
#
# issues = list(filter(self.include, issues))
# log.debug(" Pruned down to %i", len(issues))
#
# for project, issue in issues:
# issue_obj = self.get_issue_for_record(issue)
# extra = {
# 'annotations': self.annotations(project, issue, issue_obj),
# 'project': project,
# }
# issue_obj.update_extra(extra)
# yield issue_obj
#
# Path: tests/base.py
# class ServiceTest(ConfigTest):
# GENERAL_CONFIG = {
# 'interactive': False,
# 'annotation_length': 100,
# 'description_length': 100,
# }
# SERVICE_CONFIG = {
# }
#
# @classmethod
# def setUpClass(cls):
# cls.maxDiff = None
#
# def get_mock_service(
# self, service_class, section='unspecified',
# config_overrides=None, general_overrides=None
# ):
# options = {
# 'general': {**self.GENERAL_CONFIG, 'targets': section},
# section: self.SERVICE_CONFIG.copy(),
# }
# if config_overrides:
# options[section].update(config_overrides)
# if general_overrides:
# options['general'].update(general_overrides)
#
# service_config = service_class.CONFIG_SCHEMA(**options[section])
# main_config = schema.MainSectionConfig(**options['general'])
# main_config.data = data.BugwarriorData(self.lists_path)
#
# return service_class(service_config, main_config, section)
#
# @staticmethod
# def add_response(url, **kwargs):
# responses.add(responses.GET, url, match_querystring=True, **kwargs)
#
# class AbstractServiceTest(abc.ABC):
# """ Ensures that certain test methods are implemented for each service. """
# @abc.abstractmethod
# def test_to_taskwarrior(self):
# """ Test Service.to_taskwarrior(). """
# raise NotImplementedError
#
# @abc.abstractmethod
# def test_issues(self):
# """
# Test Service.issues().
#
# - When the API is accessed via requests, use the responses library to
# mock requests.
# - When the API is accessed via a third party library, substitute a fake
# implementation class for it.
# """
# raise NotImplementedError
. Output only the next line. | class TestTracIssue(AbstractServiceTest, ServiceTest): |
Based on the snippet: <|code_start|>#!/usr/bin/env python
"""Perform object finding and association."""
components = ['label','objects','associate','candidate','plot','www']
def load_candidates(filename,threshold=0):
""" Load candidates for plotting """
candidates = fitsio.read(filename,lower=True,trim_strings=True)
candidates = candidates[candidates['ts'] >= threshold]
return candidates
def run(self):
if 'label' in self.opts.run:
<|code_end|>
, predict the immediate next line with the help of imports:
import os, glob
import time
import fitsio
import numpy as np
import ugali.candidate.associate
from os.path import exists, join
from ugali.analysis.pipeline import Pipeline
from ugali.analysis.search import CandidateSearch
from ugali.utils.logger import logger
from ugali.utils.shell import mkdir
from ugali.utils.www import create_index_html
and context (classes, functions, sometimes code) from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | logger.info("Running 'label'...") |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
try:
except ImportError:
DATABASES = {
'sdss':['dr10'],
'des' :['sva1','sva1_gold','y1a1','y2n','y2q1'],
}
def databaseFactory(survey,release):
if survey == 'sdss':
return SDSSDatabase(release = release)
elif survey == 'des':
if release == 'y1a1':
return Y1A1Database()
elif release == 'y2n':
return Y2NDatabase()
elif release == 'y2q1':
return Y2Q1Database()
else:
msg = "Unrecognized release: %s"%release
raise Exception(msg)
return DESDatabase(release = release)
else:
<|code_end|>
, predict the next line using imports from the current file:
import os, sys
import re
import io
import subprocess
import numpy as np
import http.client as httpcl
import httplib as httpcl
import healpy as hp
import ugali.utils.projector
import despydb.desdbi
import ugali.utils.parser
from ugali.utils.logger import logger
from ugali.utils.shell import mkdir
from ugali.utils.config import Config
and context including class names, function names, and sometimes code from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | logger.error("Unrecognized survey: %s"%survey) |
Predict the next line after this snippet: <|code_start|>
matplotlib.use('Agg')
#try: os.environ['DISPLAY']
#except KeyError: matplotlib.use('Agg')
components = ['mcmc','membership','results','plot','collect','scan']
components = ['mcmc','membership','results','plot']
def make_filenames(config,label):
config = ugali.utils.config.Config(config)
outdir=config['output']['mcmcdir']
samfile=join(outdir,config['output']['mcmcfile']%label)
srcfile=samfile.replace('.npy','.yaml')
memfile=samfile.replace('.npy','.fits')
ret = dict(outfile=samfile,samfile=samfile,srcfile=srcfile,memfile=memfile)
return ret
def do_results(args):
""" Write the results output file """
config,name,label,coord = args
filenames = make_filenames(config,label)
srcfile = filenames['srcfile']
samples = filenames['samfile']
if not exists(srcfile):
<|code_end|>
using the current file's imports:
import os
import shutil
import matplotlib
import numpy
import numpy as np
import yaml
import fitsio
import ugali.analysis.source
import ugali.analysis.loglike
import ugali.analysis.results
import ugali.utils.config
import ugali.utils.plotting
import pylab as plt
from os.path import join,exists,basename,splitext
from collections import OrderedDict as odict
from multiprocessing import Pool
from ugali.analysis.pipeline import Pipeline
from ugali.analysis.scan import Scan
from ugali.utils.logger import logger
from ugali.utils.shell import mkdir
from ugali.analysis.results import write_results
from ugali.analysis.loglike import write_membership
and any relevant context from other files:
# Path: ugali/analysis/scan.py
# class Scan(object):
# """
# The base of a likelihood analysis scan.
#
# FIXME: This really does nothing now and should be absorbed into
# GridSearch (confusing now).
# """
# def __init__(self, config, coords):
# self.config = Config(config)
# # Should only be one coordinate
# if len(coords) != 1: raise Exception('Must specify one coordinate.')
# self.lon,self.lat,radius = coords[0]
# self._setup()
#
#
# def _setup(self):
# self.observation = createObservation(self.config,self.lon,self.lat)
# self.source = createSource(self.config,'scan',lon=self.lon,lat=self.lat)
# loglike=LogLikelihood(self.config,self.observation,self.source)
# self.grid = GridSearch(self.config,loglike)
#
# @property
# def loglike(self):
# return self.grid.loglike
#
# def run(self, coords=None, debug=False):
# """
# Run the likelihood grid search
# """
# #self.grid.precompute()
# self.grid.search(coords=coords)
# return self.grid
#
# def write(self, outfile):
# self.grid.write(outfile)
#
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | logger.warning("Couldn't find %s; skipping..."%srcfile) |
Based on the snippet: <|code_start|> return np.savetxt(filename,data,header=','.join(data.dtype.names),delimiter=',',**kwargs)
elif ext in ('.txt','.dat'):
return np.savetxt(filename,data,**kwargs)
msg = "Unrecognized file type: %s"%filename
raise ValueError(msg)
def check_formula(formula):
""" Check that a formula is valid. """
if not (('data[' in formula) and (']' in formula)):
msg = 'Invalid formula:\n %s'%formula
raise ValueError(msg)
def parse_formula(formula):
""" Return the columns used in a formula. """
check_formula(formula)
columns = []
for x in formula.split('data[')[1:]:
col = x.split(']')[0].replace('"','').replace("'",'')
columns += [col]
return columns
def add_column(filename,column,formula,force=False):
""" Add a column to a FITS file.
ADW: Could this be replaced by a ftool?
"""
columns = parse_formula(formula)
<|code_end|>
, predict the immediate next line with the help of imports:
import shutil
import os
import itertools
import warnings
import fitsio
import numpy as np
import healpy as hp
import warnings
from collections import OrderedDict as odict
from ugali.utils.logger import logger
from ugali.utils.mlab import isstring
from multiprocessing import Pool
from multiprocessing import Pool
from multiprocessing import Pool
and context (classes, functions, sometimes code) from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | logger.info("Running file: %s"%filename) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
"""
Simulate the likelihood search.
"""
#components = ['simulate','analyze','merge','plot']
components = ['analyze','merge']
def run(self):
outdir=mkdir(self.config['output']['simdir'])
logdir=mkdir(join(outdir,'log'))
# Actually copy config instead of re-writing
shutil.copy(self.config.filename,outdir)
configfile = join(outdir,os.path.basename(self.config.filename))
if 'simulate' in self.opts.run:
<|code_end|>
using the current file's imports:
import os
import time
import glob
import shutil
import numpy as np
import numpy.lib.recfunctions as recfuncs
import fitsio
import ugali.analysis.loglike
import ugali.simulation.simulator
import ugali.utils.skymap
import ugali.utils.plotting
import pylab as plt
import pylab as plt
from os.path import join, splitext, exists
from ugali.analysis.pipeline import Pipeline
from ugali.utils.shell import mkdir
from ugali.utils.logger import logger
from ugali.utils.healpix import pix2ang
and any relevant context from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
#
# Path: ugali/utils/healpix.py
# def pix2ang(nside, pix, nest=False):
# """
# Return (lon, lat) in degrees instead of (theta, phi) in radians
# """
# theta, phi = hp.pix2ang(nside, pix, nest=nest)
# lon = phi2lon(phi)
# lat = theta2lat(theta)
# return lon, lat
. Output only the next line. | logger.info("Running 'simulate'...") |
Continue the code snippet: <|code_start|> Initialize a configuration object from a filename or a dictionary.
Provides functionality to merge with a default configuration.
Parameters:
config: filename, dict, or Config object (deep copied)
default: default configuration to merge
Returns:
config
"""
self.update(self._load(default))
self.update(self._load(config))
self._formatFilepaths()
# For back-compatibility...
self.params = self
# Run some basic validation
# ADW: This should be run after creating filenames
self._validate()
# Filenames from this config (masked by existence)
# ADW: We should not recreate filenames if they already exist
# in the input config
if not hasattr(self,'filenames'):
try:
self.filenames = self._createFilenames()
except:
exc_type,exc_value,exc_traceback = sys.exc_info()
<|code_end|>
. Use current file imports:
import os,sys
import pprint
import copy
import glob
import numpy as np
import healpy as hp
import yaml
import ugali.utils.config # To recognize own type
from os.path import join, exists
from collections import OrderedDict as odict
from ugali.utils.logger import logger
from ugali.utils.mlab import isstring
and context (classes, functions, or code) from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | logger.warning("%s %s"%(exc_type,exc_value)) |
Next line prediction: <|code_start|> (10,('r',float)),
(11,('i',float)),
(12,('z',float)),
(13,('y',float)),
(16,('stage',float))
]),
lsst = odict([
(2, ('mass_init',float)),
(3, ('mass_act',float)),
(6, ('log_lum',float)),
(9, ('u',float)),
(10,('g',float)),
(11,('r',float)),
(12,('i',float)),
(13,('z',float)),
(14,('Y',float)),
(15,('stage',float))
]),
)
def _parse(self,filename):
"""
Reads an isochrone in the Dotter 2016 format and determines
the age (Gyr), metallicity (Z), and creates arrays with the
initial stellar mass and corresponding magnitudes for each
step along the isochrone.
"""
try:
columns = self.columns[self.survey.lower()]
except KeyError as e:
<|code_end|>
. Use current file imports:
(import os
import sys
import glob
import copy
import tempfile
import subprocess
import shutil
import numpy as np
from collections import OrderedDict as odict
from urllib.parse import urlencode
from urllib.request import urlopen, Request
from urllib import urlencode
from urllib2 import urlopen, Request
from ugali.utils.logger import logger
from ugali.isochrone.parsec import Isochrone
from ugali.isochrone.model import get_iso_dir)
and context including class names, function names, or small code snippets from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
#
# Path: ugali/isochrone/parsec.py
# class ParsecIsochrone(Isochrone):
# class Bressan2012(ParsecIsochrone):
# class Marigo2017(ParsecIsochrone):
# def z2feh(cls, z):
# def feh2z(cls, feh):
# def query_server(self,outfile,age,metallicity):
# def verify(cls, filename, survey, age, metallicity):
# def _parse(self,filename):
# def _parse(self,filename):
#
# Path: ugali/isochrone/model.py
# def sum_mags(mags, weights=None):
# def jester_mag_v(g_sdss, r_sdss):
# def __init__(self, **kwargs):
# def _setup(self, **kwargs):
# def _parse(self,filename):
# def get_dirname(self):
# def todict(self):
# def distance(self):
# def sample(self, mode='data', mass_steps=1000, mass_min=0.1, full_data_range=False):
# def stellar_mass(self, mass_min=0.1, steps=10000):
# def stellar_luminosity(self, steps=10000):
# def absolute_magnitude(self, richness=1, steps=1e4):
# def absolute_magnitude_martin(self, richness=1, steps=1e4, n_trials=1000, mag_bright=None, mag_faint=23., alpha=0.32, seed=None):
# def simulate(self, stellar_mass, distance_modulus=None, **kwargs):
# def observableFractionCMDX(self, mask, distance_modulus, mass_min=0.1):
# def observableFractionCMD(self, mask, distance_modulus, mass_min=0.1):
# def observableFractionCDF(self, mask, distance_modulus, mass_min=0.1):
# def observableFractionMMD(self, mask, distance_modulus, mass_min=0.1):
# def signalMMD(self, mask, distance_modulus, mass_min=0.1, nsigma=5, delta_mag=0.03, mass_steps=1000, method='step'):
# def histogram2d(self,distance_modulus=None,delta_mag=0.03,steps=10000):
# def pdf_mmd(self, lon, lat, mag_1, mag_2, distance_modulus, mask, delta_mag=0.03, steps=1000):
# def pdf(self, mag_1, mag_2, mag_err_1, mag_err_2,
# distance_modulus=None, delta_mag=0.03, steps=10000):
# def raw_separation(self,mag_1,mag_2,steps=10000):
# def separation(self, mag_1, mag_2):
# def interp_iso(iso_mag_1,iso_mag_2,mag_1,mag_2):
# def __init__(self,**kwargs):
# def __str__(self,indent=0):
# def z2feh(cls, z):
# def feh2z(cls, feh):
# def feh(self):
# def params2filename(cls,age,metallicity):
# def filename2params(cls,filename):
# def create_grid(self,abins=None,zbins=None):
# def create_tree(self,grid=None):
# def get_filename(self):
# def _cache(self,name=None):
# def _parse(self,filename):
# def print_info(self,age,metallicity):
# def query_server(self,outfile,age,metallicity):
# def verify(cls,filename,survey,age,metallicity):
# def download(self,age=None,metallicity=None,outdir=None,force=False):
# def absolute_magnitude(distance_modulus,g,r,prob=None):
# class IsochroneModel(Model):
# class Isochrone(IsochroneModel):
# V = jester_mag_v(sdss_g,sdss_r)
# V = jester_mag_v(sdss_g, sdss_r)
# V = jester_mag_v(sdss_g[cut]-iso.distance_modulus,
# sdss_r[cut]-iso.distance_modulus)
# V = g - 0.487*(g - r) - 0.0249
. Output only the next line. | logger.warning('Unrecognized survey: %s'%(self.survey)) |
Using the snippet: <|code_start|># MESA Isochrones
# http://waps.cfa.harvard.edu/MIST/iso_form.php
# survey system
dict_output = odict([
('des','DECam'),
('sdss','SDSSugriz'),
('ps1','PanSTARRS'),
('lsst','LSST'),
])
mesa_defaults = {
'version':'1.0',
'v_div_vcrit':'vvcrit0.4',
'age_scale':'linear',
'age_type':'single',
'age_value':10e9, # yr if scale='linear'; log10(yr) if scale='log10'
'age_range_low':'',
'age_range_high':'',
'age_range_delta':'',
'age_list':'',
'FeH_value':-3.0,
'theory_output':'basic',
'output_option':'photometry',
'output':'DECam',
'Av_value':0,
}
mesa_defaults_10 = dict(mesa_defaults,version='1.0')
<|code_end|>
, determine the next line of code. You have imports:
import os
import sys
import glob
import copy
import tempfile
import subprocess
import shutil
import numpy as np
from collections import OrderedDict as odict
from urllib.parse import urlencode
from urllib.request import urlopen, Request
from urllib import urlencode
from urllib2 import urlopen, Request
from ugali.utils.logger import logger
from ugali.isochrone.parsec import Isochrone
from ugali.isochrone.model import get_iso_dir
and context (class names, function names, or code) available:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
#
# Path: ugali/isochrone/parsec.py
# class ParsecIsochrone(Isochrone):
# class Bressan2012(ParsecIsochrone):
# class Marigo2017(ParsecIsochrone):
# def z2feh(cls, z):
# def feh2z(cls, feh):
# def query_server(self,outfile,age,metallicity):
# def verify(cls, filename, survey, age, metallicity):
# def _parse(self,filename):
# def _parse(self,filename):
#
# Path: ugali/isochrone/model.py
# def sum_mags(mags, weights=None):
# def jester_mag_v(g_sdss, r_sdss):
# def __init__(self, **kwargs):
# def _setup(self, **kwargs):
# def _parse(self,filename):
# def get_dirname(self):
# def todict(self):
# def distance(self):
# def sample(self, mode='data', mass_steps=1000, mass_min=0.1, full_data_range=False):
# def stellar_mass(self, mass_min=0.1, steps=10000):
# def stellar_luminosity(self, steps=10000):
# def absolute_magnitude(self, richness=1, steps=1e4):
# def absolute_magnitude_martin(self, richness=1, steps=1e4, n_trials=1000, mag_bright=None, mag_faint=23., alpha=0.32, seed=None):
# def simulate(self, stellar_mass, distance_modulus=None, **kwargs):
# def observableFractionCMDX(self, mask, distance_modulus, mass_min=0.1):
# def observableFractionCMD(self, mask, distance_modulus, mass_min=0.1):
# def observableFractionCDF(self, mask, distance_modulus, mass_min=0.1):
# def observableFractionMMD(self, mask, distance_modulus, mass_min=0.1):
# def signalMMD(self, mask, distance_modulus, mass_min=0.1, nsigma=5, delta_mag=0.03, mass_steps=1000, method='step'):
# def histogram2d(self,distance_modulus=None,delta_mag=0.03,steps=10000):
# def pdf_mmd(self, lon, lat, mag_1, mag_2, distance_modulus, mask, delta_mag=0.03, steps=1000):
# def pdf(self, mag_1, mag_2, mag_err_1, mag_err_2,
# distance_modulus=None, delta_mag=0.03, steps=10000):
# def raw_separation(self,mag_1,mag_2,steps=10000):
# def separation(self, mag_1, mag_2):
# def interp_iso(iso_mag_1,iso_mag_2,mag_1,mag_2):
# def __init__(self,**kwargs):
# def __str__(self,indent=0):
# def z2feh(cls, z):
# def feh2z(cls, feh):
# def feh(self):
# def params2filename(cls,age,metallicity):
# def filename2params(cls,filename):
# def create_grid(self,abins=None,zbins=None):
# def create_tree(self,grid=None):
# def get_filename(self):
# def _cache(self,name=None):
# def _parse(self,filename):
# def print_info(self,age,metallicity):
# def query_server(self,outfile,age,metallicity):
# def verify(cls,filename,survey,age,metallicity):
# def download(self,age=None,metallicity=None,outdir=None,force=False):
# def absolute_magnitude(distance_modulus,g,r,prob=None):
# class IsochroneModel(Model):
# class Isochrone(IsochroneModel):
# V = jester_mag_v(sdss_g,sdss_r)
# V = jester_mag_v(sdss_g, sdss_r)
# V = jester_mag_v(sdss_g[cut]-iso.distance_modulus,
# sdss_r[cut]-iso.distance_modulus)
# V = g - 0.487*(g - r) - 0.0249
. Output only the next line. | class Dotter2016(Isochrone): |
Continue the code snippet: <|code_start|>dict_output = odict([
('des','DECam'),
('sdss','SDSSugriz'),
('ps1','PanSTARRS'),
('lsst','LSST'),
])
mesa_defaults = {
'version':'1.0',
'v_div_vcrit':'vvcrit0.4',
'age_scale':'linear',
'age_type':'single',
'age_value':10e9, # yr if scale='linear'; log10(yr) if scale='log10'
'age_range_low':'',
'age_range_high':'',
'age_range_delta':'',
'age_list':'',
'FeH_value':-3.0,
'theory_output':'basic',
'output_option':'photometry',
'output':'DECam',
'Av_value':0,
}
mesa_defaults_10 = dict(mesa_defaults,version='1.0')
class Dotter2016(Isochrone):
""" MESA isochrones from Dotter 2016:
http://waps.cfa.harvard.edu/MIST/interp_isos.html
"""
<|code_end|>
. Use current file imports:
import os
import sys
import glob
import copy
import tempfile
import subprocess
import shutil
import numpy as np
from collections import OrderedDict as odict
from urllib.parse import urlencode
from urllib.request import urlopen, Request
from urllib import urlencode
from urllib2 import urlopen, Request
from ugali.utils.logger import logger
from ugali.isochrone.parsec import Isochrone
from ugali.isochrone.model import get_iso_dir
and context (classes, functions, or code) from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
#
# Path: ugali/isochrone/parsec.py
# class ParsecIsochrone(Isochrone):
# class Bressan2012(ParsecIsochrone):
# class Marigo2017(ParsecIsochrone):
# def z2feh(cls, z):
# def feh2z(cls, feh):
# def query_server(self,outfile,age,metallicity):
# def verify(cls, filename, survey, age, metallicity):
# def _parse(self,filename):
# def _parse(self,filename):
#
# Path: ugali/isochrone/model.py
# def sum_mags(mags, weights=None):
# def jester_mag_v(g_sdss, r_sdss):
# def __init__(self, **kwargs):
# def _setup(self, **kwargs):
# def _parse(self,filename):
# def get_dirname(self):
# def todict(self):
# def distance(self):
# def sample(self, mode='data', mass_steps=1000, mass_min=0.1, full_data_range=False):
# def stellar_mass(self, mass_min=0.1, steps=10000):
# def stellar_luminosity(self, steps=10000):
# def absolute_magnitude(self, richness=1, steps=1e4):
# def absolute_magnitude_martin(self, richness=1, steps=1e4, n_trials=1000, mag_bright=None, mag_faint=23., alpha=0.32, seed=None):
# def simulate(self, stellar_mass, distance_modulus=None, **kwargs):
# def observableFractionCMDX(self, mask, distance_modulus, mass_min=0.1):
# def observableFractionCMD(self, mask, distance_modulus, mass_min=0.1):
# def observableFractionCDF(self, mask, distance_modulus, mass_min=0.1):
# def observableFractionMMD(self, mask, distance_modulus, mass_min=0.1):
# def signalMMD(self, mask, distance_modulus, mass_min=0.1, nsigma=5, delta_mag=0.03, mass_steps=1000, method='step'):
# def histogram2d(self,distance_modulus=None,delta_mag=0.03,steps=10000):
# def pdf_mmd(self, lon, lat, mag_1, mag_2, distance_modulus, mask, delta_mag=0.03, steps=1000):
# def pdf(self, mag_1, mag_2, mag_err_1, mag_err_2,
# distance_modulus=None, delta_mag=0.03, steps=10000):
# def raw_separation(self,mag_1,mag_2,steps=10000):
# def separation(self, mag_1, mag_2):
# def interp_iso(iso_mag_1,iso_mag_2,mag_1,mag_2):
# def __init__(self,**kwargs):
# def __str__(self,indent=0):
# def z2feh(cls, z):
# def feh2z(cls, feh):
# def feh(self):
# def params2filename(cls,age,metallicity):
# def filename2params(cls,filename):
# def create_grid(self,abins=None,zbins=None):
# def create_tree(self,grid=None):
# def get_filename(self):
# def _cache(self,name=None):
# def _parse(self,filename):
# def print_info(self,age,metallicity):
# def query_server(self,outfile,age,metallicity):
# def verify(cls,filename,survey,age,metallicity):
# def download(self,age=None,metallicity=None,outdir=None,force=False):
# def absolute_magnitude(distance_modulus,g,r,prob=None):
# class IsochroneModel(Model):
# class Isochrone(IsochroneModel):
# V = jester_mag_v(sdss_g,sdss_r)
# V = jester_mag_v(sdss_g, sdss_r)
# V = jester_mag_v(sdss_g[cut]-iso.distance_modulus,
# sdss_r[cut]-iso.distance_modulus)
# V = g - 0.487*(g - r) - 0.0249
. Output only the next line. | _dirname = os.path.join(get_iso_dir(),'{survey}','dotter2016') |
Given the following code snippet before the placeholder: <|code_start|>class Projector:
"""
Class for performing two-dimensional map projections from the celestial sphere.
"""
def __init__(self, lon_ref, lat_ref, proj_type = 'ait'):
self.lon_ref = lon_ref
self.lat_ref = lat_ref
self.proj_type = proj_type
if proj_type.lower() == 'ait':
self.rotator = SphericalRotator(lon_ref, lat_ref, zenithal=False)
self.sphere_to_image_func = aitoffSphereToImage
self.image_to_sphere_func = aitoffImageToSphere
elif proj_type.lower() == 'tan':
self.rotator = SphericalRotator(lon_ref, lat_ref, zenithal=True)
self.sphere_to_image_func = gnomonicSphereToImage
self.image_to_sphere_func = gnomonicImageToSphere
elif proj_type.lower() == 'car':
def rotate(lon,lat,invert=False):
if invert:
return lon + np.array([lon_ref]), lat + np.array([lat_ref])
else:
return lon - np.array([lon_ref]), lat - np.array([lat_ref])
self.rotator = SphericalRotator(lon_ref, lat_ref, zenithal=False)
# Monkey patch the rotate function
self.rotator.rotate = rotate
self.sphere_to_image_func = cartesianSphereToImage
self.image_to_sphere_func = cartesianImageToSphere
else:
<|code_end|>
, predict the next line using imports from the current file:
import re
import numpy as np
import healpy
import astropy.units as u
import astropy.units as u
import astropy.units as u
import ephem
from ugali.utils.logger import logger
from ugali.utils.mlab import isstring
from astropy.coordinates import SkyCoord
from astropy.coordinates import SkyCoord
from astropy.coordinates import SkyCoord
from scipy.spatial import cKDTree
and context including class names, function names, and sometimes code from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | logger.warn('%s not recognized'%(proj_type)) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
if __name__ == "__main__":
usage = "Usage: %prog [options] results1.fits results2.fits ... "
description = "Script for merging multiple results files."
parser = OptionParser(usage=usage,description=description)
parser.add_option('-o','--outfile',default="merged.fits")
parser.add_option('-v','--verbose',action='store_true')
(opts, args) = parser.parse_args()
<|code_end|>
, generate the next line using the imports in this file:
import ugali.utils.skymap
from ugali.utils.logger import logger
from optparse import OptionParser
and context (functions, classes, or occasionally code) from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | if opts.verbose: logger.setLevel(logger.DEBUG) |
Given snippet: <|code_start|> -------
None
"""
assert mc_source_id_start >= 1, "Starting mc_source_id must be >= 1"
assert n % n_chunk == 0, "Total number of satellites must be divisible by the chunk size"
nside_pix = 256 # NSIDE = 128 -> 27.5 arcmin, NSIDE = 256 -> 13.7 arcmin
if not os.path.exists(tag): os.makedirs(tag)
if isinstance(config,str): config = yaml.load(open(config))
assert config['survey'] in ['des', 'ps1', 'lsst']
infile_ebv = config['ebv']
infile_fracdet = config['fracdet']
infile_maglim_g = config['maglim_g']
infile_maglim_r = config['maglim_r']
infile_density = config['stellar_density']
range_distance = config.get('range_distance',[5., 500.])
range_stellar_mass = config.get('range_stellar_mass',[1.e1, 1.e6])
range_r_physical = config.get('range_r_physical',[1.e-3, 2.0])
range_ellipticity = config.get('range_ellipticity',[0.1, 0.8])
range_position_angle= config.get('range_position_angle',[0.0, 180.0])
choice_age = config.get('choice_age',[10., 12.0, 13.5])
choice_metal = config.get('choice_metal',[0.00010,0.00020])
dwarf_file = config.get('known_dwarfs',None)
m_density = np.load(infile_density)
nside_density = hp.npix2nside(len(m_density))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import copy
import collections
import yaml
import numpy as np
import scipy.interpolate
import healpy as hp
import fitsio
import astropy.io.fits as pyfits
import ugali.utils.projector
import ugali.utils.healpix
import ugali.analysis.source
import ugali.analysis.kernel
import ugali.analysis.imf
import ugali.analysis.results
import ugali.simulation.population
import pylab
import argparse
from collections import OrderedDict as odict
from ugali.isochrone import factory as isochrone_factory
from ugali.utils.healpix import read_map
and context:
# Path: ugali/utils/healpix.py
# def read_map(filename, nest=False, hdu=None, h=False, verbose=True):
# """Read a healpix map from a fits file. Partial-sky files,
# if properly identified, are expanded to full size and filled with UNSEEN.
# Uses fitsio to mirror much (but not all) of the functionality of healpy.read_map
#
# Parameters:
# -----------
# filename : str
# the fits file name
# nest : bool, optional
# If True return the map in NEST ordering, otherwise in RING ordering;
# use fits keyword ORDERING to decide whether conversion is needed or not
# If None, no conversion is performed.
# hdu : int, optional
# the header number to look at (start at 0)
# h : bool, optional
# If True, return also the header. Default: False.
# verbose : bool, optional
# If True, print a number of diagnostic messages
#
# Returns
# -------
# m [, header] : array, optionally with header appended
# The map read from the file, and the header if *h* is True.
# """
# import fitsio
# data,hdr = fitsio.read(filename,header=True,ext=hdu)
#
# nside = int(hdr.get('NSIDE'))
# if verbose: print('NSIDE = {0:d}'.format(nside))
#
# if not hp.isnsideok(nside):
# raise ValueError('Wrong nside parameter.')
# sz=hp.nside2npix(nside)
#
# ordering = hdr.get('ORDERING','UNDEF').strip()
# if verbose: print('ORDERING = {0:s} in fits file'.format(ordering))
#
# schm = hdr.get('INDXSCHM', 'UNDEF').strip()
# if verbose: print('INDXSCHM = {0:s}'.format(schm))
# if schm == 'EXPLICIT':
# partial = True
# elif schm == 'IMPLICIT':
# partial = False
#
# # monkey patch on a field method
# fields = data.dtype.names
#
# # Could be done more efficiently (but complicated) by reordering first
# if hdr['INDXSCHM'] == 'EXPLICIT':
# m = hp.UNSEEN*np.ones(sz,dtype=data[fields[1]].dtype)
# m[data[fields[0]]] = data[fields[1]]
# else:
# m = data[fields[0]].ravel()
#
# if (not hp.isnpixok(m.size) or (sz>0 and sz != m.size)) and verbose:
# print('nside={0:d}, sz={1:d}, m.size={2:d}'.format(nside,sz,m.size))
# raise ValueError('Wrong nside parameter.')
# if nest is not None:
# if nest and ordering.startswith('RING'):
# idx = hp.nest2ring(nside,np.arange(m.size,dtype=np.int32))
# m = m[idx]
# if verbose: print('Ordering converted to NEST')
# elif (not nest) and ordering.startswith('NESTED'):
# idx = hp.ring2nest(nside,np.arange(m.size,dtype=np.int32))
# m = m[idx]
# if verbose: print('Ordering converted to RING')
#
# if h: return m, hdr
# else: return m
which might include code, classes, or functions. Output only the next line. | m_fracdet = read_map(infile_fracdet, nest=False) #.astype(np.float16) |
Given the code snippet: <|code_start|> for k,v in header.items():
fitshdr.add_record({'name':k,'value':v})
# ADW: Should this be a debug?
logger.info("Writing %s..."%filename)
fitsio.write(filename,data,extname='PIX_DATA',header=fitshdr,clobber=True)
def read_partial_map(filenames, column, fullsky=True, **kwargs):
"""
Read a partial HEALPix file(s) and return pixels and values/map. Can
handle 3D healpix maps (pix, value, zdim). Returned array has
shape (dimz,npix).
Parameters:
-----------
filenames : list of input filenames
column : column of interest
fullsky : partial or fullsky map
kwargs : passed to fitsio.read
Returns:
--------
(nside,pix,map) : pixel array and healpix map (partial or fullsky)
"""
# Make sure that PIXEL is in columns
#kwargs['columns'] = ['PIXEL',column]
kwargs['columns'] = ['PIXEL'] + np.atleast_1d(column).tolist()
filenames = np.atleast_1d(filenames)
header = fitsio.read_header(filenames[0],ext=kwargs.get('ext',1))
<|code_end|>
, generate the next line using the imports in this file:
from collections import OrderedDict as odict
from ugali.utils import fileio
from ugali.utils.logger import logger
import numpy
import numpy as np
import healpy as hp
import fitsio
import ugali.utils.projector
import ugali.utils.fileio
import fitsio
import fitsio
import fitsio
import fitsio
import fitsio
import argparse
and context (functions, classes, or occasionally code) from other files:
# Path: ugali/utils/fileio.py
# def read(filename,**kwargs):
# def write(filename,data,**kwargs):
# def check_formula(formula):
# def parse_formula(formula):
# def add_column(filename,column,formula,force=False):
# def load_header(kwargs):
# def load_headers(filenames,multiproc=False,**kwargs):
# def load_file(kwargs):
# def load_files(filenames,multiproc=False,**kwargs):
# def load(args):
# def load_infiles(infiles,columns=None,multiproc=False):
# def insert_columns(filename,data,ext=1,force=False,colnum=None):
# def write_fits(filename,data,header=None,force=False):
#
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | data = fileio.load_files(filenames,**kwargs) |
Based on the snippet: <|code_start|> -----------
filename : output file name
data : dictionary or recarray of data to write (must contain 'PIXEL')
nside : healpix nside of data
coord : 'G'alactic, 'C'elestial, 'E'cliptic
ordering : 'RING' or 'NEST'
kwargs : Passed to fitsio.write
Returns:
--------
None
"""
# ADW: Do we want to make everything uppercase?
if isinstance(data,dict):
names = list(data.keys())
else:
names = data.dtype.names
if 'PIXEL' not in names:
msg = "'PIXEL' column not found."
raise ValueError(msg)
hdr = header_odict(nside=nside,coord=coord,nest=nest)
fitshdr = fitsio.FITSHDR(list(hdr.values()))
if header is not None:
for k,v in header.items():
fitshdr.add_record({'name':k,'value':v})
# ADW: Should this be a debug?
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import OrderedDict as odict
from ugali.utils import fileio
from ugali.utils.logger import logger
import numpy
import numpy as np
import healpy as hp
import fitsio
import ugali.utils.projector
import ugali.utils.fileio
import fitsio
import fitsio
import fitsio
import fitsio
import fitsio
import argparse
and context (classes, functions, sometimes code) from other files:
# Path: ugali/utils/fileio.py
# def read(filename,**kwargs):
# def write(filename,data,**kwargs):
# def check_formula(formula):
# def parse_formula(formula):
# def add_column(filename,column,formula,force=False):
# def load_header(kwargs):
# def load_headers(filenames,multiproc=False,**kwargs):
# def load_file(kwargs):
# def load_files(filenames,multiproc=False,**kwargs):
# def load(args):
# def load_infiles(infiles,columns=None,multiproc=False):
# def insert_columns(filename,data,ext=1,force=False,colnum=None):
# def write_fits(filename,data,header=None,force=False):
#
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | logger.info("Writing %s..."%filename) |
Predict the next line for this snippet: <|code_start|> 'output_kind': 0,
'photsys_file': photsys_dict['des'],
#'photsys_version': 'yang',
'submit_form': 'Submit'}
defaults_27 = dict(defaults_cmd,cmd_version='2.7')
defaults_28 = dict(defaults_cmd,cmd_version='2.8')
defaults_29 = dict(defaults_cmd,cmd_version='2.9')
defaults_30 = dict(defaults_cmd,cmd_version='3.0')
class Download(object):
isochrone = None
def __init__(self,survey='des',**kwargs):
self.survey=survey.lower()
def create_grid(self,abins,zbins):
arange = np.linspace(abins[0],abins[1],abins[2]+1)
zrange = np.logspace(np.log10(zbins[0]),np.log10(zbins[1]),zbins[2]+1)
aa,zz = np.meshgrid(arange,zrange)
return aa.flatten(),zz.flatten()
def print_info(self,age,metallicity):
params = dict(age=age,z=metallicity)
params['name'] = self.__class__.__name__
params['survey'] = self.survey
params['feh'] = self.isochrone.z2feh(metallicity)
msg = 'Downloading: %(name)s (survey=%(survey)s, age=%(age).1fGyr, Z=%(z).5f, Fe/H=%(feh).3f)'%params
<|code_end|>
with the help of current file imports:
import os
import re
import subprocess
import copy
import numpy as np
import ugali.utils.parser
from urllib.parse import urlencode
from urllib.request import urlopen
from urllib import urlencode
from urllib2 import urlopen
from multiprocessing import Pool
from collections import OrderedDict as odict
from ugali.utils.logger import logger
from ugali.utils.shell import mkdir
from ugali.analysis.isochrone import Padova
from ugali.utils.factory import factory
from http.client import HTTPConnection
from httplib import HTTPConnection
and context from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
, which may contain function names, class names, or code. Output only the next line. | logger.info(msg) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
"""Run the likelihood search."""
components = ['scan','merge','tar','plot','check']
defaults = ['scan','merge']
def run(self):
if 'scan' in self.opts.run:
<|code_end|>
. Use current file imports:
import glob
import os
import numpy as np
import ugali.utils.skymap
import matplotlib
import pylab as plt
import ugali.utils.plotting as plotting
import fitsio
import numpy as np
import healpy as hp
from os.path import join, exists, basename
from ugali.analysis.farm import Farm
from ugali.analysis.pipeline import Pipeline
from ugali.utils.shell import mkdir
from ugali.utils.logger import logger
from ugali.utils import healpix
from ugali.utils.skymap import inFootprint
and context (classes, functions, or code) from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
#
# Path: ugali/utils/healpix.py
# def superpixel(subpix, nside_subpix, nside_superpix):
# def subpixel(superpix, nside_superpix, nside_subpix):
# def d_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def u_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def ud_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def phi2lon(phi): return np.degrees(phi)
# def lon2phi(lon): return np.radians(lon)
# def theta2lat(theta): return 90. - np.degrees(theta)
# def lat2theta(lat): return np.radians(90. - lat)
# def pix2ang(nside, pix, nest=False):
# def ang2pix(nside, lon, lat, nest=False):
# def ang2vec(lon, lat):
# def get_nside(m):
# def healpixMap(nside, lon, lat, fill_value=0., nest=False):
# def in_pixels(lon,lat,pixels,nside):
# def index_pix_in_pixels(pix,pixels,sort=False,outside=-1):
# def index_lonlat_in_pixels(lon,lat,pixels,nside,sort=False,outside=-1):
# def query_disc(nside, vec, radius, inclusive=False, fact=4, nest=False):
# def ang2disc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False):
# def get_interp_val(m, lon, lat, *args, **kwargs):
# def header_odict(nside,nest=False,coord=None, partial=True):
# def write_partial_map(filename, data, nside, coord=None, nest=False,
# header=None,dtype=None,**kwargs):
# def read_partial_map(filenames, column, fullsky=True, **kwargs):
# def merge_partial_maps(filenames,outfile,**kwargs):
# def merge_likelihood_headers(filenames, outfile, **kwargs):
# def merge_likelihood_headers2(filenames, outfile, **kwargs):
# def read_map(filename, nest=False, hdu=None, h=False, verbose=True):
. Output only the next line. | logger.info("Running 'scan'...") |
Based on the snippet: <|code_start|>#!/usr/bin/env python
"""Run the likelihood search."""
components = ['scan','merge','tar','plot','check']
defaults = ['scan','merge']
def run(self):
if 'scan' in self.opts.run:
logger.info("Running 'scan'...")
farm = Farm(self.config,verbose=self.opts.verbose)
farm.submit_all(coords=self.opts.coords,queue=self.opts.queue,debug=self.opts.debug)
if 'merge' in self.opts.run:
logger.info("Running 'merge'...")
mergefile = self.config.mergefile
roifile = self.config.roifile
filenames = self.config.likefile.split('_%')[0]+'_*.fits'
infiles = np.array(sorted(glob.glob(filenames)))
if 'mergedir' in self.config['output']:
mkdir(self.config['output']['mergedir'])
pixels = np.char.rpartition(np.char.rpartition(infiles,'_')[:,0],'_')[:,-1]
pixels = pixels.astype(int)
<|code_end|>
, predict the immediate next line with the help of imports:
import glob
import os
import numpy as np
import ugali.utils.skymap
import matplotlib
import pylab as plt
import ugali.utils.plotting as plotting
import fitsio
import numpy as np
import healpy as hp
from os.path import join, exists, basename
from ugali.analysis.farm import Farm
from ugali.analysis.pipeline import Pipeline
from ugali.utils.shell import mkdir
from ugali.utils.logger import logger
from ugali.utils import healpix
from ugali.utils.skymap import inFootprint
and context (classes, functions, sometimes code) from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
#
# Path: ugali/utils/healpix.py
# def superpixel(subpix, nside_subpix, nside_superpix):
# def subpixel(superpix, nside_superpix, nside_subpix):
# def d_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def u_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def ud_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def phi2lon(phi): return np.degrees(phi)
# def lon2phi(lon): return np.radians(lon)
# def theta2lat(theta): return 90. - np.degrees(theta)
# def lat2theta(lat): return np.radians(90. - lat)
# def pix2ang(nside, pix, nest=False):
# def ang2pix(nside, lon, lat, nest=False):
# def ang2vec(lon, lat):
# def get_nside(m):
# def healpixMap(nside, lon, lat, fill_value=0., nest=False):
# def in_pixels(lon,lat,pixels,nside):
# def index_pix_in_pixels(pix,pixels,sort=False,outside=-1):
# def index_lonlat_in_pixels(lon,lat,pixels,nside,sort=False,outside=-1):
# def query_disc(nside, vec, radius, inclusive=False, fact=4, nest=False):
# def ang2disc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False):
# def get_interp_val(m, lon, lat, *args, **kwargs):
# def header_odict(nside,nest=False,coord=None, partial=True):
# def write_partial_map(filename, data, nside, coord=None, nest=False,
# header=None,dtype=None,**kwargs):
# def read_partial_map(filenames, column, fullsky=True, **kwargs):
# def merge_partial_maps(filenames,outfile,**kwargs):
# def merge_likelihood_headers(filenames, outfile, **kwargs):
# def merge_likelihood_headers2(filenames, outfile, **kwargs):
# def read_map(filename, nest=False, hdu=None, h=False, verbose=True):
. Output only the next line. | superpixel = healpix.superpixel(pixels, |
Predict the next line after this snippet: <|code_start|>NSIDE = 4096
FACTOR = 4
PIX = np.array([104582830, 43361203, 142027178])
U_GRADE_PIX_NEST = np.array([[418331320, 418331321, 418331322, 418331323],
[173444812, 173444813, 173444814, 173444815],
[568108712, 568108713, 568108714, 568108715]])
U_GRADE_PIX_RING = np.array([[418356572, 418323804, 418323803, 418291036],
[173492070, 173459302, 173459301, 173426534],
[568152916, 568120148, 568120147, 568087380]])
D_GRADE_PIX_NEST = PIX//FACTOR
D_GRADE_PIX_RING = np.array([26142551, 10842585, 35509461])
UD_GRADE_PIX = np.repeat(PIX,4).reshape(-1,4)
DU_GRADE_PIX_NEST = np.array([[104582828, 104582829, 104582830, 104582831],
[ 43361200, 43361201, 43361202, 43361203],
[142027176, 142027177, 142027178, 142027179]])
DU_GRADE_PIX_RING = np.array([[104582830, 104566446, 104566445, 104550062],
[ 43393971, 43377587, 43377586, 43361203],
[142059946, 142043562, 142043561, 142027178]])
class TestHealpix(unittest.TestCase):
"""Test healpix module"""
def test_ud_grade_ipix(self):
# Same NSIDE
<|code_end|>
using the current file's imports:
import unittest
import numpy as np
import healpy as hp
import fitsio
from ugali.utils import healpix
from ugali.utils.logger import logger
and any relevant context from other files:
# Path: ugali/utils/healpix.py
# def superpixel(subpix, nside_subpix, nside_superpix):
# def subpixel(superpix, nside_superpix, nside_subpix):
# def d_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def u_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def ud_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def phi2lon(phi): return np.degrees(phi)
# def lon2phi(lon): return np.radians(lon)
# def theta2lat(theta): return 90. - np.degrees(theta)
# def lat2theta(lat): return np.radians(90. - lat)
# def pix2ang(nside, pix, nest=False):
# def ang2pix(nside, lon, lat, nest=False):
# def ang2vec(lon, lat):
# def get_nside(m):
# def healpixMap(nside, lon, lat, fill_value=0., nest=False):
# def in_pixels(lon,lat,pixels,nside):
# def index_pix_in_pixels(pix,pixels,sort=False,outside=-1):
# def index_lonlat_in_pixels(lon,lat,pixels,nside,sort=False,outside=-1):
# def query_disc(nside, vec, radius, inclusive=False, fact=4, nest=False):
# def ang2disc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False):
# def get_interp_val(m, lon, lat, *args, **kwargs):
# def header_odict(nside,nest=False,coord=None, partial=True):
# def write_partial_map(filename, data, nside, coord=None, nest=False,
# header=None,dtype=None,**kwargs):
# def read_partial_map(filenames, column, fullsky=True, **kwargs):
# def merge_partial_maps(filenames,outfile,**kwargs):
# def merge_likelihood_headers(filenames, outfile, **kwargs):
# def merge_likelihood_headers2(filenames, outfile, **kwargs):
# def read_map(filename, nest=False, hdu=None, h=False, verbose=True):
#
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | np.testing.assert_equal(healpix.ud_grade_ipix(PIX,NSIDE,NSIDE),PIX) |
Predict the next line after this snippet: <|code_start|> if opts.verbose: logger.setLevel(logger.DEBUG)
map = ugali.utils.skymap.readSparseHealpixMaps(args,opts.field)
if opts.coord.upper() == "GAL":
coord = 'G'
elif opts.coord.upper() == "CEL":
coord = 'GC'
if opts.proj.upper() == "MOL":
#map = numpy.where( map < 20, healpy.UNSEEN, map)
healpy.mollview(map,coord=coord,xsize=1000,min=20)
elif opts.proj.upper() == "CAR":
healpy.cartview(map,coord=coord,xsize=1000)
else:
raise Exception("...")
healpy.graticule()
if opts.targets:
targets = numpy.genfromtxt(opts.targets,unpack=True,dtype=None)
if not targets.shape: targets = targets.reshape(-1)
coord = 'CG' # For RA/DEC input
healpy.projscatter(targets['f1'],targets['f2'],
lonlat=True,coord=coord,marker='o',c='w')
fig = plt.gcf()
# This is pretty hackish (but is how healpy does it...)
for ax in fig.get_axes():
if isinstance(ax,healpy.projaxes.SphericalProjAxes): break
for target in targets:
text = TARGETS[target[0]][0]
kwargs = TARGETS[target[0]][1]
<|code_end|>
using the current file's imports:
import healpy
import pylab as plt
import numpy
import ugali.utils.skymap
from ugali.utils.projector import celToGal
from ugali.utils.logger import logger
from optparse import OptionParser
and any relevant context from other files:
# Path: ugali/utils/projector.py
# def celToGal(ra, dec):
# """
# Converts Celestial J2000 (deg) to Calactic (deg) coordinates
# """
# dec = np.radians(dec)
# sin_dec = np.sin(dec)
# cos_dec = np.cos(dec)
#
# ra = np.radians(ra)
# ra_gp = np.radians(192.85948)
# de_gp = np.radians(27.12825)
#
# sin_ra_gp = np.sin(ra - ra_gp)
# cos_ra_gp = np.cos(ra - ra_gp)
#
# lcp = np.radians(122.932)
# sin_b = (np.sin(de_gp) * sin_dec) \
# + (np.cos(de_gp) * cos_dec * cos_ra_gp)
# lcpml = np.arctan2(cos_dec * sin_ra_gp,
# (np.cos(de_gp) * sin_dec) \
# - (np.sin(de_gp) * cos_dec * cos_ra_gp))
# bb = np.arcsin(sin_b)
# ll = (lcp - lcpml + (2. * np.pi)) % (2. * np.pi)
# return np.degrees(ll), np.degrees(bb)
#
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | glon,glat = celToGal(target[1],target[2]) |
Next line prediction: <|code_start|>leo_II = ["Leo II" ,dict(default_kwargs,xytext=(-4,0),ha='right'), ],
leo_IV = ["Leo IV" ,dict(default_kwargs,xytext=(5,-1),ha='left'), ],
leo_T = ["Leo T" ,dict(default_kwargs,xytext=(4,5),ha='left'), ],
leo_V = ["Leo V" ,dict(default_kwargs,xytext=(4,5),ha='left'), ],
lmc = ["LMC" ,default_kwargs, ],
pisces_II = ["Psc II" ,default_kwargs, ],
sagittarius = ["Sgr" ,default_kwargs, ],
sculptor = ["Scl" ,default_kwargs, ],
segue_1 = ["Seg 1" ,dict(default_kwargs,xytext=(4,2),ha='left'), ],
segue_2 = ["Seg 2" ,default_kwargs, ],
sextans = ["Sex" ,dict(default_kwargs,xytext=(-2,-5),ha='right'),],
smc = ["SMC" ,default_kwargs, ],
ursa_major_I = ["UMa I" ,dict(default_kwargs,xytext=(5,-5),ha='left'), ],
ursa_major_II = ["UMa II" ,dict(default_kwargs,xytext=(4,4)), ],
ursa_minor = ["UMi" ,default_kwargs, ],
willman_1 = ["Wil 1" ,dict(default_kwargs,xytext=(5,1),ha='left'), ],
)
if __name__ == "__main__":
usage = "Usage: %prog [options] input"
description = "python script"
parser = OptionParser(usage=usage,description=description)
parser.add_option('-o','--outfile',default='allsky_maglims.png')
parser.add_option('-t','--targets',default=None)
parser.add_option('-c','--coord',default='GAL')
parser.add_option('-p','--proj',default='MOL',choices=['MOL','CAR'])
parser.add_option('-f','--field',default='MAGLIM')
parser.add_option('-v','--verbose', action='store_true')
(opts, args) = parser.parse_args()
<|code_end|>
. Use current file imports:
(import healpy
import pylab as plt
import numpy
import ugali.utils.skymap
from ugali.utils.projector import celToGal
from ugali.utils.logger import logger
from optparse import OptionParser)
and context including class names, function names, or small code snippets from other files:
# Path: ugali/utils/projector.py
# def celToGal(ra, dec):
# """
# Converts Celestial J2000 (deg) to Calactic (deg) coordinates
# """
# dec = np.radians(dec)
# sin_dec = np.sin(dec)
# cos_dec = np.cos(dec)
#
# ra = np.radians(ra)
# ra_gp = np.radians(192.85948)
# de_gp = np.radians(27.12825)
#
# sin_ra_gp = np.sin(ra - ra_gp)
# cos_ra_gp = np.cos(ra - ra_gp)
#
# lcp = np.radians(122.932)
# sin_b = (np.sin(de_gp) * sin_dec) \
# + (np.cos(de_gp) * cos_dec * cos_ra_gp)
# lcpml = np.arctan2(cos_dec * sin_ra_gp,
# (np.cos(de_gp) * sin_dec) \
# - (np.sin(de_gp) * cos_dec * cos_ra_gp))
# bb = np.arcsin(sin_b)
# ll = (lcp - lcpml + (2. * np.pi)) % (2. * np.pi)
# return np.degrees(ll), np.degrees(bb)
#
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | if opts.verbose: logger.setLevel(logger.DEBUG) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
#import mangle
if __name__ == "__main__":
usage = "Usage: %prog [options] mangle1.ply [mangle2.ply ...]"
description = "python script"
parser = OptionParser(usage=usage,description=description)
(opts, args) = parser.parse_args()
nside = 2**8
print("Creating ra, dec...")
pix = np.arange(healpy.nside2npix(nside))
ra,dec = pixToAng(nside,pix)
for infile in args:
print("Testing %i HEALPix pixels ..."%len(pix))
<|code_end|>
. Write the next line using the current file imports:
import healpy
import numpy as np
import pylab as plt
from ugali.preprocess.maglims import inMangle
from ugali.utils.projector import pixToAng
from optparse import OptionParser
and context from other files:
# Path: ugali/preprocess/maglims.py
# def inMangle(polyfile,ra,dec):
# coords = tempfile.NamedTemporaryFile(suffix='.txt',delete=False)
# logger.debug("Writing coordinates to %s"%coords.name)
# np.savetxt(coords, np.array( [ra,dec] ).T, fmt='%.6g' )
# coords.close()
#
# weights = tempfile.NamedTemporaryFile(suffix='.txt',delete=False)
# cmd = "polyid -W %s %s %s"%(polyfile,coords.name,weights.name)
# logger.debug(cmd)
# subprocess.call(cmd,shell=True)
#
# tmp = tempfile.NamedTemporaryFile(suffix='.txt',delete=False)
# cmd = """awk '{if($3==""){$3=0} print $1, $2, $3}' %s > %s"""%(weights.name,tmp.name)
# logger.debug(cmd)
# subprocess.call(cmd,shell=True)
#
# data = np.loadtxt(tmp.name,unpack=True,skiprows=1)[-1]
# for f in [coords,weights,tmp]:
# logger.debug("Removing %s"%f.name)
# os.remove(f.name)
#
# return data > 0
#
# Path: ugali/utils/projector.py
# class SphericalRotator:
# class Projector:
# def __init__(self, lon_ref, lat_ref, zenithal=False):
# def setReference(self, lon_ref, lat_ref, zenithal=False):
# def cartesian(self,lon,lat):
# def rotate(self, lon, lat, invert=False):
# def __init__(self, lon_ref, lat_ref, proj_type = 'ait'):
# def rotate(lon,lat,invert=False):
# def sphereToImage(self, lon, lat):
# def imageToSphere(self, x, y):
# def sphere2image(lon_ref,lat_ref,lon,lat):
# def image2sphere(lon_ref,lat_ref,x,y):
# def cartesianSphereToImage(lon, lat):
# def cartesianImageToSphere(x,y):
# def aitoffSphereToImage(lon, lat):
# def aitoffImageToSphere(x, y):
# def gnomonicSphereToImage(lon, lat):
# def gnomonicImageToSphere(x, y):
# def angsep2(lon_1, lat_1, lon_2, lat_2):
# def angsep(lon1,lat1,lon2,lat2):
# def galToCel(ll, bb):
# def celToGal(ra, dec):
# def estimate_angle(angle, origin, new_frame, offset=1e-7):
# def gal2cel_angle(glon,glat,angle,offset=1e-7):
# def cel2gal_angle(ra,dec,angle,offset=1e-7):
# def dec2hms(dec):
# def dec2dms(dec):
# def hms2dec(hms):
# def dms2dec(dms):
# def sr2deg(solid_angle):
# def deg2sr(solid_angle):
# def distanceToDistanceModulus(distance):
# def distanceModulusToDistance(distance_modulus):
# def ang2const(lon,lat,coord='gal'):
# def ang2iau(lon,lat,coord='gal'):
# def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1):
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
, which may include functions, classes, or code. Output only the next line. | inside = inMangle(infile,ra,dec) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
#import mangle
if __name__ == "__main__":
usage = "Usage: %prog [options] mangle1.ply [mangle2.ply ...]"
description = "python script"
parser = OptionParser(usage=usage,description=description)
(opts, args) = parser.parse_args()
nside = 2**8
print("Creating ra, dec...")
pix = np.arange(healpy.nside2npix(nside))
<|code_end|>
, predict the next line using imports from the current file:
import healpy
import numpy as np
import pylab as plt
from ugali.preprocess.maglims import inMangle
from ugali.utils.projector import pixToAng
from optparse import OptionParser
and context including class names, function names, and sometimes code from other files:
# Path: ugali/preprocess/maglims.py
# def inMangle(polyfile,ra,dec):
# coords = tempfile.NamedTemporaryFile(suffix='.txt',delete=False)
# logger.debug("Writing coordinates to %s"%coords.name)
# np.savetxt(coords, np.array( [ra,dec] ).T, fmt='%.6g' )
# coords.close()
#
# weights = tempfile.NamedTemporaryFile(suffix='.txt',delete=False)
# cmd = "polyid -W %s %s %s"%(polyfile,coords.name,weights.name)
# logger.debug(cmd)
# subprocess.call(cmd,shell=True)
#
# tmp = tempfile.NamedTemporaryFile(suffix='.txt',delete=False)
# cmd = """awk '{if($3==""){$3=0} print $1, $2, $3}' %s > %s"""%(weights.name,tmp.name)
# logger.debug(cmd)
# subprocess.call(cmd,shell=True)
#
# data = np.loadtxt(tmp.name,unpack=True,skiprows=1)[-1]
# for f in [coords,weights,tmp]:
# logger.debug("Removing %s"%f.name)
# os.remove(f.name)
#
# return data > 0
#
# Path: ugali/utils/projector.py
# class SphericalRotator:
# class Projector:
# def __init__(self, lon_ref, lat_ref, zenithal=False):
# def setReference(self, lon_ref, lat_ref, zenithal=False):
# def cartesian(self,lon,lat):
# def rotate(self, lon, lat, invert=False):
# def __init__(self, lon_ref, lat_ref, proj_type = 'ait'):
# def rotate(lon,lat,invert=False):
# def sphereToImage(self, lon, lat):
# def imageToSphere(self, x, y):
# def sphere2image(lon_ref,lat_ref,lon,lat):
# def image2sphere(lon_ref,lat_ref,x,y):
# def cartesianSphereToImage(lon, lat):
# def cartesianImageToSphere(x,y):
# def aitoffSphereToImage(lon, lat):
# def aitoffImageToSphere(x, y):
# def gnomonicSphereToImage(lon, lat):
# def gnomonicImageToSphere(x, y):
# def angsep2(lon_1, lat_1, lon_2, lat_2):
# def angsep(lon1,lat1,lon2,lat2):
# def galToCel(ll, bb):
# def celToGal(ra, dec):
# def estimate_angle(angle, origin, new_frame, offset=1e-7):
# def gal2cel_angle(glon,glat,angle,offset=1e-7):
# def cel2gal_angle(ra,dec,angle,offset=1e-7):
# def dec2hms(dec):
# def dec2dms(dec):
# def hms2dec(hms):
# def dms2dec(dms):
# def sr2deg(solid_angle):
# def deg2sr(solid_angle):
# def distanceToDistanceModulus(distance):
# def distanceModulusToDistance(distance_modulus):
# def ang2const(lon,lat,coord='gal'):
# def ang2iau(lon,lat,coord='gal'):
# def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1):
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
. Output only the next line. | ra,dec = pixToAng(nside,pix) |
Predict the next line for this snippet: <|code_start|>"""
Documentation.
"""
pylab.ion()
############################################################
def validateSatellite(config, isochrone, kernel, stellar_mass, distance_modulus, trials=1, debug=False, seed=0):
"""
Tool for simple MC validation studies -- specifically to create multiple realizations of
a satellite given an CompositeIsochrone object, Kernel object, stellar mass (M_sol) for normalization,
and distance_modulus.
"""
<|code_end|>
with the help of current file imports:
import numpy
import pylab
import ugali.analysis.farm
import ugali.observation.catalog
import ugali.observation.roi
import ugali.observation.mask
import ugali.simulation.simulator
import ugali.utils.bayesian_efficiency
from ugali.utils.logger import logger
and context from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
, which may contain function names, class names, or code. Output only the next line. | logger.info('=== Validate Satellite ===') |
Here is a snippet: <|code_start|> epsilon = 1.e-10
if config.params['catalog']['band_1_detection']:
bins_mag_1 = numpy.arange(config.params['mag']['min'] - mag_buffer,
config.params['mag']['max'] + mag_buffer + epsilon,
delta_mag)
bins_mag_2 = numpy.arange(config.params['mag']['min'] - config.params['color']['max'] - mag_buffer,
config.params['mag']['max'] - config.params['color']['min'] + mag_buffer + epsilon,
delta_mag)
else:
bins_mag_1 = numpy.arange(config.params['mag']['min'] + config.params['color']['min'] - mag_buffer,
config.params['mag']['max'] + config.params['color']['max'] + mag_buffer + epsilon,
delta_mag)
bins_mag_2 = numpy.arange(config.params['mag']['min'] - mag_buffer,
config.params['mag']['max'] + mag_buffer + epsilon,
delta_mag)
# Output binning configuration
#print config.params['catalog']['band_1_detection']
#print config.params['mag']['min'], config.params['mag']['max']
#print config.params['color']['min'], config.params['color']['max']
#print bins_mag_1[0], bins_mag_1[-1], len(bins_mag_1)
#print bins_mag_2[0], bins_mag_2[-1], len(bins_mag_2)
isochrone_mass_init, isochrone_mass_pdf, isochrone_mass_act, isochrone_mag_1, isochrone_mag_2 = isochrone.sample(mass_steps=mass_steps)
hdul = pyfits.HDUList()
for index_distance_modulus, distance_modulus in enumerate(distance_modulus_array):
<|code_end|>
. Write the next line using the current file imports:
import time
import numpy
import scipy.signal
import astropy.io.fits as pyfits
import ugali.utils.config
import ugali.utils.binning
import ugali.isochrone
if plot: import ugali.utils.plotting
if plot: import ugali.utils.plotting
from ugali.utils.logger import logger
and context from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
, which may include functions, classes, or code. Output only the next line. | logger.debug('(%i/%i)'%(index_distance_modulus, len(distance_modulus_array))) |
Here is a snippet: <|code_start|> def add_seed(self,**kwargs):
self.add_argument('--seed',default=None,type=int,
help='Random seed.',**kwargs)
def add_version(self,**kwargs):
self.add_argument('-V','--version',action='version',
version='ugali '+__version__,
help='Print version.',**kwargs)
def add_run(self,**kwargs):
self.add_argument('-r','--run', default=[], action='append',
help="Analysis component(s) to run.", **kwargs)
def _parse_verbose(self,opts):
if vars(opts).get('verbose') or vars(opts).get('debug'):
logger.setLevel(logger.DEBUG)
def _parse_coords(self,opts):
""" Parse target coordinates in various ways...
"""
# The coordinates are mutually exclusive, so
# shouldn't have to worry about over-writing them.
if 'coords' in vars(opts): return
radius = vars(opts).get('radius',0)
gal = None
if vars(opts).get('gal') is not None:
gal = opts.gal
elif vars(opts).get('cel') is not None:
gal = cel2gal(*opts.cel)
elif vars(opts).get('hpx') is not None:
<|code_end|>
. Write the next line using the current file imports:
import os
import argparse
import numpy as np
import numpy.lib.recfunctions as recfuncs
import fitsio
import yaml
from ugali.utils.healpix import pix2ang
from ugali.utils.projector import cel2gal
from ugali.utils.logger import logger
from ugali import __version__
from numpy.lib import NumpyVersion
and context from other files:
# Path: ugali/utils/healpix.py
# def pix2ang(nside, pix, nest=False):
# """
# Return (lon, lat) in degrees instead of (theta, phi) in radians
# """
# theta, phi = hp.pix2ang(nside, pix, nest=nest)
# lon = phi2lon(phi)
# lat = theta2lat(theta)
# return lon, lat
#
# Path: ugali/utils/projector.py
# class SphericalRotator:
# class Projector:
# def __init__(self, lon_ref, lat_ref, zenithal=False):
# def setReference(self, lon_ref, lat_ref, zenithal=False):
# def cartesian(self,lon,lat):
# def rotate(self, lon, lat, invert=False):
# def __init__(self, lon_ref, lat_ref, proj_type = 'ait'):
# def rotate(lon,lat,invert=False):
# def sphereToImage(self, lon, lat):
# def imageToSphere(self, x, y):
# def sphere2image(lon_ref,lat_ref,lon,lat):
# def image2sphere(lon_ref,lat_ref,x,y):
# def cartesianSphereToImage(lon, lat):
# def cartesianImageToSphere(x,y):
# def aitoffSphereToImage(lon, lat):
# def aitoffImageToSphere(x, y):
# def gnomonicSphereToImage(lon, lat):
# def gnomonicImageToSphere(x, y):
# def angsep2(lon_1, lat_1, lon_2, lat_2):
# def angsep(lon1,lat1,lon2,lat2):
# def galToCel(ll, bb):
# def celToGal(ra, dec):
# def estimate_angle(angle, origin, new_frame, offset=1e-7):
# def gal2cel_angle(glon,glat,angle,offset=1e-7):
# def cel2gal_angle(ra,dec,angle,offset=1e-7):
# def dec2hms(dec):
# def dec2dms(dec):
# def hms2dec(hms):
# def dms2dec(dms):
# def sr2deg(solid_angle):
# def deg2sr(solid_angle):
# def distanceToDistanceModulus(distance):
# def distanceModulusToDistance(distance_modulus):
# def ang2const(lon,lat,coord='gal'):
# def ang2iau(lon,lat,coord='gal'):
# def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1):
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
#
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
, which may include functions, classes, or code. Output only the next line. | gal = pix2ang(*opts.hpx) |
Continue the code snippet: <|code_start|> help='Force the overwrite of files',**kwargs)
def add_seed(self,**kwargs):
self.add_argument('--seed',default=None,type=int,
help='Random seed.',**kwargs)
def add_version(self,**kwargs):
self.add_argument('-V','--version',action='version',
version='ugali '+__version__,
help='Print version.',**kwargs)
def add_run(self,**kwargs):
self.add_argument('-r','--run', default=[], action='append',
help="Analysis component(s) to run.", **kwargs)
def _parse_verbose(self,opts):
if vars(opts).get('verbose') or vars(opts).get('debug'):
logger.setLevel(logger.DEBUG)
def _parse_coords(self,opts):
""" Parse target coordinates in various ways...
"""
# The coordinates are mutually exclusive, so
# shouldn't have to worry about over-writing them.
if 'coords' in vars(opts): return
radius = vars(opts).get('radius',0)
gal = None
if vars(opts).get('gal') is not None:
gal = opts.gal
elif vars(opts).get('cel') is not None:
<|code_end|>
. Use current file imports:
import os
import argparse
import numpy as np
import numpy.lib.recfunctions as recfuncs
import fitsio
import yaml
from ugali.utils.healpix import pix2ang
from ugali.utils.projector import cel2gal
from ugali.utils.logger import logger
from ugali import __version__
from numpy.lib import NumpyVersion
and context (classes, functions, or code) from other files:
# Path: ugali/utils/healpix.py
# def pix2ang(nside, pix, nest=False):
# """
# Return (lon, lat) in degrees instead of (theta, phi) in radians
# """
# theta, phi = hp.pix2ang(nside, pix, nest=nest)
# lon = phi2lon(phi)
# lat = theta2lat(theta)
# return lon, lat
#
# Path: ugali/utils/projector.py
# class SphericalRotator:
# class Projector:
# def __init__(self, lon_ref, lat_ref, zenithal=False):
# def setReference(self, lon_ref, lat_ref, zenithal=False):
# def cartesian(self,lon,lat):
# def rotate(self, lon, lat, invert=False):
# def __init__(self, lon_ref, lat_ref, proj_type = 'ait'):
# def rotate(lon,lat,invert=False):
# def sphereToImage(self, lon, lat):
# def imageToSphere(self, x, y):
# def sphere2image(lon_ref,lat_ref,lon,lat):
# def image2sphere(lon_ref,lat_ref,x,y):
# def cartesianSphereToImage(lon, lat):
# def cartesianImageToSphere(x,y):
# def aitoffSphereToImage(lon, lat):
# def aitoffImageToSphere(x, y):
# def gnomonicSphereToImage(lon, lat):
# def gnomonicImageToSphere(x, y):
# def angsep2(lon_1, lat_1, lon_2, lat_2):
# def angsep(lon1,lat1,lon2,lat2):
# def galToCel(ll, bb):
# def celToGal(ra, dec):
# def estimate_angle(angle, origin, new_frame, offset=1e-7):
# def gal2cel_angle(glon,glat,angle,offset=1e-7):
# def cel2gal_angle(ra,dec,angle,offset=1e-7):
# def dec2hms(dec):
# def dec2dms(dec):
# def hms2dec(hms):
# def dms2dec(dms):
# def sr2deg(solid_angle):
# def deg2sr(solid_angle):
# def distanceToDistanceModulus(distance):
# def distanceModulusToDistance(distance_modulus):
# def ang2const(lon,lat,coord='gal'):
# def ang2iau(lon,lat,coord='gal'):
# def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1):
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
#
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | gal = cel2gal(*opts.cel) |
Next line prediction: <|code_start|> help="Batch queue for execution.",**kwargs)
def add_ncores(self,**kwargs):
self.add_argument('--ncores',
help="Number of cores to use.",**kwargs)
def add_config(self,**kwargs):
self.add_argument('config',metavar='config.yaml',
help='Configuration file (yaml or python dict).',**kwargs)
def add_force(self,**kwargs):
self.add_argument('-f','--force',action='store_true',
help='Force the overwrite of files',**kwargs)
def add_seed(self,**kwargs):
self.add_argument('--seed',default=None,type=int,
help='Random seed.',**kwargs)
def add_version(self,**kwargs):
self.add_argument('-V','--version',action='version',
version='ugali '+__version__,
help='Print version.',**kwargs)
def add_run(self,**kwargs):
self.add_argument('-r','--run', default=[], action='append',
help="Analysis component(s) to run.", **kwargs)
def _parse_verbose(self,opts):
if vars(opts).get('verbose') or vars(opts).get('debug'):
<|code_end|>
. Use current file imports:
(import os
import argparse
import numpy as np
import numpy.lib.recfunctions as recfuncs
import fitsio
import yaml
from ugali.utils.healpix import pix2ang
from ugali.utils.projector import cel2gal
from ugali.utils.logger import logger
from ugali import __version__
from numpy.lib import NumpyVersion)
and context including class names, function names, or small code snippets from other files:
# Path: ugali/utils/healpix.py
# def pix2ang(nside, pix, nest=False):
# """
# Return (lon, lat) in degrees instead of (theta, phi) in radians
# """
# theta, phi = hp.pix2ang(nside, pix, nest=nest)
# lon = phi2lon(phi)
# lat = theta2lat(theta)
# return lon, lat
#
# Path: ugali/utils/projector.py
# class SphericalRotator:
# class Projector:
# def __init__(self, lon_ref, lat_ref, zenithal=False):
# def setReference(self, lon_ref, lat_ref, zenithal=False):
# def cartesian(self,lon,lat):
# def rotate(self, lon, lat, invert=False):
# def __init__(self, lon_ref, lat_ref, proj_type = 'ait'):
# def rotate(lon,lat,invert=False):
# def sphereToImage(self, lon, lat):
# def imageToSphere(self, x, y):
# def sphere2image(lon_ref,lat_ref,lon,lat):
# def image2sphere(lon_ref,lat_ref,x,y):
# def cartesianSphereToImage(lon, lat):
# def cartesianImageToSphere(x,y):
# def aitoffSphereToImage(lon, lat):
# def aitoffImageToSphere(x, y):
# def gnomonicSphereToImage(lon, lat):
# def gnomonicImageToSphere(x, y):
# def angsep2(lon_1, lat_1, lon_2, lat_2):
# def angsep(lon1,lat1,lon2,lat2):
# def galToCel(ll, bb):
# def celToGal(ra, dec):
# def estimate_angle(angle, origin, new_frame, offset=1e-7):
# def gal2cel_angle(glon,glat,angle,offset=1e-7):
# def cel2gal_angle(ra,dec,angle,offset=1e-7):
# def dec2hms(dec):
# def dec2dms(dec):
# def hms2dec(hms):
# def dms2dec(dms):
# def sr2deg(solid_angle):
# def deg2sr(solid_angle):
# def distanceToDistanceModulus(distance):
# def distanceModulusToDistance(distance_modulus):
# def ang2const(lon,lat,coord='gal'):
# def ang2iau(lon,lat,coord='gal'):
# def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1):
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
#
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | logger.setLevel(logger.DEBUG) |
Using the snippet: <|code_start|> 'FeH_value':-3.0,
'theory_output':'basic',
'output_option':'photometry',
'output':'DECam',
'Av_value':0,
}
mesa_defaults_10 = dict(mesa_defaults,version='1.0')
class Dotter2008(Download):
""" Dartmouth isochrones from Dotter et al. 2008:
http://stellar.dartmouth.edu/models/isolf_new.html
"""
defaults = copy.deepcopy(dartmouth_defaults)
isochrone=iso.Dotter2008
abins = np.arange(1., 13.5 + 0.1, 0.1)
zbins = np.arange(7e-5,1e-3 + 1e-5,1e-5)
def query_server(self, outfile, age, metallicity):
z = metallicity
feh = self.isochrone.z2feh(z)
params = dict(self.defaults)
params['age']=age
params['feh']='%.6f'%feh
params['clr']=dict_clr[self.survey]
url = 'http://stellar.dartmouth.edu/models/isolf_new.php'
query = url + '?' + urlencode(params)
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import requests
import sys
import copy
import tempfile
import subprocess
import shutil
import numpy
import numpy as np
import ugali.utils.logger
import ugali.utils.shell
import ugali.analysis.isochrone as iso
import ugali.utils.parser
from urllib.parse import urlencode
from urllib.request import urlopen
from urllib import urlencode
from urllib2 import urlopen
from multiprocessing import Pool
from collections import OrderedDict as odict
from ugali.utils.logger import logger
from ugali.utils.shell import mkdir
from ugali.preprocess.padova import Download
from ugali.utils.factory import factory
from http.client import HTTPConnection
from httplib import HTTPConnection
and context (class names, function names, or code) available:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
#
# Path: ugali/preprocess/padova.py
# class Download(object):
#
# isochrone = None
#
# def __init__(self,survey='des',**kwargs):
# self.survey=survey.lower()
#
# def create_grid(self,abins,zbins):
# arange = np.linspace(abins[0],abins[1],abins[2]+1)
# zrange = np.logspace(np.log10(zbins[0]),np.log10(zbins[1]),zbins[2]+1)
# aa,zz = np.meshgrid(arange,zrange)
# return aa.flatten(),zz.flatten()
#
# def print_info(self,age,metallicity):
# params = dict(age=age,z=metallicity)
# params['name'] = self.__class__.__name__
# params['survey'] = self.survey
# params['feh'] = self.isochrone.z2feh(metallicity)
# msg = 'Downloading: %(name)s (survey=%(survey)s, age=%(age).1fGyr, Z=%(z).5f, Fe/H=%(feh).3f)'%params
# logger.info(msg)
# return msg
#
# def query_server(self,outfile,age,metallicity):
# msg = "'query_server' not implemented by base class."
# logger.error(msg)
# raise RuntimeError(msg)
#
# @classmethod
# def verify(cls,filename,survey,age,metallicity):
# msg = "'verify' not implemented by base class."
# logger.error(msg)
# raise RuntimeError(msg)
#
# def download(self,age,metallicity,outdir=None,force=False):
# """
# Check valid parameter range and download isochrones from:
# http://stev.oapd.inaf.it/cgi-bin/cmd
# """
# if outdir is None: outdir = './'
# basename = self.isochrone.params2filename(age,metallicity)
# outfile = os.path.join(outdir,basename)
#
# if os.path.exists(outfile) and not force:
# try:
# self.verify(outfile,self.survey,age,metallicity)
# logger.info("Found %s; skipping..."%(outfile))
# return
# except Exception as e:
# msg = "Overwriting corrupted %s..."%(outfile)
# logger.warn(msg)
# #os.remove(outfile)
#
# mkdir(outdir)
#
# self.print_info(age,metallicity)
#
# try:
# self.query_server(outfile,age,metallicity)
# except Exception as e:
# logger.debug(str(e))
# raise RuntimeError('Bad server response')
#
# if not os.path.exists(outfile):
# raise RuntimeError('Download failed')
#
# try:
# self.verify(outfile,self.survey,age,metallicity)
# except Exception as e:
# msg = "Output file is corrupted."
# logger.error(msg)
# #os.remove(outfile)
# raise(e)
#
# return outfile
. Output only the next line. | logger.debug(query) |
Based on the snippet: <|code_start|># MESA Isochrones
# http://waps.cfa.harvard.edu/MIST/iso_form.php
# survey system
dict_output = odict([
('des' ,'DECam'),
('sdss','SDSSugriz'),
('ps1' ,'PanSTARRS'),
('lsst','LSST'),
])
mesa_defaults = {
'version':'1.0',
'v_div_vcrit':'vvcrit0.4',
'age_scale':'linear',
'age_type':'single',
'age_value':10e9, # yr if scale='linear'; log10(yr) if scale='log10'
'age_range_low':'',
'age_range_high':'',
'age_range_delta':'',
'age_list':'',
'FeH_value':-3.0,
'theory_output':'basic',
'output_option':'photometry',
'output':'DECam',
'Av_value':0,
}
mesa_defaults_10 = dict(mesa_defaults,version='1.0')
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import re
import requests
import sys
import copy
import tempfile
import subprocess
import shutil
import numpy
import numpy as np
import ugali.utils.logger
import ugali.utils.shell
import ugali.analysis.isochrone as iso
import ugali.utils.parser
from urllib.parse import urlencode
from urllib.request import urlopen
from urllib import urlencode
from urllib2 import urlopen
from multiprocessing import Pool
from collections import OrderedDict as odict
from ugali.utils.logger import logger
from ugali.utils.shell import mkdir
from ugali.preprocess.padova import Download
from ugali.utils.factory import factory
from http.client import HTTPConnection
from httplib import HTTPConnection
and context (classes, functions, sometimes code) from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
#
# Path: ugali/preprocess/padova.py
# class Download(object):
#
# isochrone = None
#
# def __init__(self,survey='des',**kwargs):
# self.survey=survey.lower()
#
# def create_grid(self,abins,zbins):
# arange = np.linspace(abins[0],abins[1],abins[2]+1)
# zrange = np.logspace(np.log10(zbins[0]),np.log10(zbins[1]),zbins[2]+1)
# aa,zz = np.meshgrid(arange,zrange)
# return aa.flatten(),zz.flatten()
#
# def print_info(self,age,metallicity):
# params = dict(age=age,z=metallicity)
# params['name'] = self.__class__.__name__
# params['survey'] = self.survey
# params['feh'] = self.isochrone.z2feh(metallicity)
# msg = 'Downloading: %(name)s (survey=%(survey)s, age=%(age).1fGyr, Z=%(z).5f, Fe/H=%(feh).3f)'%params
# logger.info(msg)
# return msg
#
# def query_server(self,outfile,age,metallicity):
# msg = "'query_server' not implemented by base class."
# logger.error(msg)
# raise RuntimeError(msg)
#
# @classmethod
# def verify(cls,filename,survey,age,metallicity):
# msg = "'verify' not implemented by base class."
# logger.error(msg)
# raise RuntimeError(msg)
#
# def download(self,age,metallicity,outdir=None,force=False):
# """
# Check valid parameter range and download isochrones from:
# http://stev.oapd.inaf.it/cgi-bin/cmd
# """
# if outdir is None: outdir = './'
# basename = self.isochrone.params2filename(age,metallicity)
# outfile = os.path.join(outdir,basename)
#
# if os.path.exists(outfile) and not force:
# try:
# self.verify(outfile,self.survey,age,metallicity)
# logger.info("Found %s; skipping..."%(outfile))
# return
# except Exception as e:
# msg = "Overwriting corrupted %s..."%(outfile)
# logger.warn(msg)
# #os.remove(outfile)
#
# mkdir(outdir)
#
# self.print_info(age,metallicity)
#
# try:
# self.query_server(outfile,age,metallicity)
# except Exception as e:
# logger.debug(str(e))
# raise RuntimeError('Bad server response')
#
# if not os.path.exists(outfile):
# raise RuntimeError('Download failed')
#
# try:
# self.verify(outfile,self.survey,age,metallicity)
# except Exception as e:
# msg = "Output file is corrupted."
# logger.error(msg)
# #os.remove(outfile)
# raise(e)
#
# return outfile
. Output only the next line. | class Dotter2008(Download): |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
#CATALOGS = ['McConnachie12','Rykoff14', 'Harris96', 'Corwen04', 'Nilson73', 'Webbink85', 'Kharchenko13', 'WEBDA14']
CATALOGS = ['McConnachie12', 'Harris96', 'Corwen04', 'Nilson73', 'Webbink85', 'Kharchenko13', 'Bica08', 'WEBDA14', 'ExtraDwarfs','ExtraClusters']
if __name__ == "__main__":
description = "python script"
parser = ugali.utils.parser.Parser(description=description)
parser.add_coords(required=True,radius=True,targets=True)
parser.add_argument('-n','--nnearest',default=1,type=int)
opts = parser.parse_args()
catalog = ugali.candidate.associate.SourceCatalog()
for i in CATALOGS:
catalog += ugali.candidate.associate.catalogFactory(i)
for name,(glon,glat,radius) in zip(opts.names, opts.coords):
<|code_end|>
using the current file's imports:
import ugali.candidate.associate
import ugali.utils.parser
import numpy as np
import argparse
from ugali.utils.projector import gal2cel,ang2const,ang2iau
and any relevant context from other files:
# Path: ugali/utils/projector.py
# class SphericalRotator:
# class Projector:
# def __init__(self, lon_ref, lat_ref, zenithal=False):
# def setReference(self, lon_ref, lat_ref, zenithal=False):
# def cartesian(self,lon,lat):
# def rotate(self, lon, lat, invert=False):
# def __init__(self, lon_ref, lat_ref, proj_type = 'ait'):
# def rotate(lon,lat,invert=False):
# def sphereToImage(self, lon, lat):
# def imageToSphere(self, x, y):
# def sphere2image(lon_ref,lat_ref,lon,lat):
# def image2sphere(lon_ref,lat_ref,x,y):
# def cartesianSphereToImage(lon, lat):
# def cartesianImageToSphere(x,y):
# def aitoffSphereToImage(lon, lat):
# def aitoffImageToSphere(x, y):
# def gnomonicSphereToImage(lon, lat):
# def gnomonicImageToSphere(x, y):
# def angsep2(lon_1, lat_1, lon_2, lat_2):
# def angsep(lon1,lat1,lon2,lat2):
# def galToCel(ll, bb):
# def celToGal(ra, dec):
# def estimate_angle(angle, origin, new_frame, offset=1e-7):
# def gal2cel_angle(glon,glat,angle,offset=1e-7):
# def cel2gal_angle(ra,dec,angle,offset=1e-7):
# def dec2hms(dec):
# def dec2dms(dec):
# def hms2dec(hms):
# def dms2dec(dms):
# def sr2deg(solid_angle):
# def deg2sr(solid_angle):
# def distanceToDistanceModulus(distance):
# def distanceModulusToDistance(distance_modulus):
# def ang2const(lon,lat,coord='gal'):
# def ang2iau(lon,lat,coord='gal'):
# def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1):
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
. Output only the next line. | ra,dec = gal2cel(glon,glat) |
Next line prediction: <|code_start|>#!/usr/bin/env python
#CATALOGS = ['McConnachie12','Rykoff14', 'Harris96', 'Corwen04', 'Nilson73', 'Webbink85', 'Kharchenko13', 'WEBDA14']
CATALOGS = ['McConnachie12', 'Harris96', 'Corwen04', 'Nilson73', 'Webbink85', 'Kharchenko13', 'Bica08', 'WEBDA14', 'ExtraDwarfs','ExtraClusters']
if __name__ == "__main__":
description = "python script"
parser = ugali.utils.parser.Parser(description=description)
parser.add_coords(required=True,radius=True,targets=True)
parser.add_argument('-n','--nnearest',default=1,type=int)
opts = parser.parse_args()
catalog = ugali.candidate.associate.SourceCatalog()
for i in CATALOGS:
catalog += ugali.candidate.associate.catalogFactory(i)
for name,(glon,glat,radius) in zip(opts.names, opts.coords):
ra,dec = gal2cel(glon,glat)
iau = ang2iau(glon,glat)
<|code_end|>
. Use current file imports:
(import ugali.candidate.associate
import ugali.utils.parser
import numpy as np
import argparse
from ugali.utils.projector import gal2cel,ang2const,ang2iau)
and context including class names, function names, or small code snippets from other files:
# Path: ugali/utils/projector.py
# class SphericalRotator:
# class Projector:
# def __init__(self, lon_ref, lat_ref, zenithal=False):
# def setReference(self, lon_ref, lat_ref, zenithal=False):
# def cartesian(self,lon,lat):
# def rotate(self, lon, lat, invert=False):
# def __init__(self, lon_ref, lat_ref, proj_type = 'ait'):
# def rotate(lon,lat,invert=False):
# def sphereToImage(self, lon, lat):
# def imageToSphere(self, x, y):
# def sphere2image(lon_ref,lat_ref,lon,lat):
# def image2sphere(lon_ref,lat_ref,x,y):
# def cartesianSphereToImage(lon, lat):
# def cartesianImageToSphere(x,y):
# def aitoffSphereToImage(lon, lat):
# def aitoffImageToSphere(x, y):
# def gnomonicSphereToImage(lon, lat):
# def gnomonicImageToSphere(x, y):
# def angsep2(lon_1, lat_1, lon_2, lat_2):
# def angsep(lon1,lat1,lon2,lat2):
# def galToCel(ll, bb):
# def celToGal(ra, dec):
# def estimate_angle(angle, origin, new_frame, offset=1e-7):
# def gal2cel_angle(glon,glat,angle,offset=1e-7):
# def cel2gal_angle(ra,dec,angle,offset=1e-7):
# def dec2hms(dec):
# def dec2dms(dec):
# def hms2dec(hms):
# def dms2dec(dms):
# def sr2deg(solid_angle):
# def deg2sr(solid_angle):
# def distanceToDistanceModulus(distance):
# def distanceModulusToDistance(distance_modulus):
# def ang2const(lon,lat,coord='gal'):
# def ang2iau(lon,lat,coord='gal'):
# def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1):
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
. Output only the next line. | const = ang2const(glon,glat)[0] |
Using the snippet: <|code_start|>#!/usr/bin/env python
#CATALOGS = ['McConnachie12','Rykoff14', 'Harris96', 'Corwen04', 'Nilson73', 'Webbink85', 'Kharchenko13', 'WEBDA14']
CATALOGS = ['McConnachie12', 'Harris96', 'Corwen04', 'Nilson73', 'Webbink85', 'Kharchenko13', 'Bica08', 'WEBDA14', 'ExtraDwarfs','ExtraClusters']
if __name__ == "__main__":
description = "python script"
parser = ugali.utils.parser.Parser(description=description)
parser.add_coords(required=True,radius=True,targets=True)
parser.add_argument('-n','--nnearest',default=1,type=int)
opts = parser.parse_args()
catalog = ugali.candidate.associate.SourceCatalog()
for i in CATALOGS:
catalog += ugali.candidate.associate.catalogFactory(i)
for name,(glon,glat,radius) in zip(opts.names, opts.coords):
ra,dec = gal2cel(glon,glat)
<|code_end|>
, determine the next line of code. You have imports:
import ugali.candidate.associate
import ugali.utils.parser
import numpy as np
import argparse
from ugali.utils.projector import gal2cel,ang2const,ang2iau
and context (class names, function names, or code) available:
# Path: ugali/utils/projector.py
# class SphericalRotator:
# class Projector:
# def __init__(self, lon_ref, lat_ref, zenithal=False):
# def setReference(self, lon_ref, lat_ref, zenithal=False):
# def cartesian(self,lon,lat):
# def rotate(self, lon, lat, invert=False):
# def __init__(self, lon_ref, lat_ref, proj_type = 'ait'):
# def rotate(lon,lat,invert=False):
# def sphereToImage(self, lon, lat):
# def imageToSphere(self, x, y):
# def sphere2image(lon_ref,lat_ref,lon,lat):
# def image2sphere(lon_ref,lat_ref,x,y):
# def cartesianSphereToImage(lon, lat):
# def cartesianImageToSphere(x,y):
# def aitoffSphereToImage(lon, lat):
# def aitoffImageToSphere(x, y):
# def gnomonicSphereToImage(lon, lat):
# def gnomonicImageToSphere(x, y):
# def angsep2(lon_1, lat_1, lon_2, lat_2):
# def angsep(lon1,lat1,lon2,lat2):
# def galToCel(ll, bb):
# def celToGal(ra, dec):
# def estimate_angle(angle, origin, new_frame, offset=1e-7):
# def gal2cel_angle(glon,glat,angle,offset=1e-7):
# def cel2gal_angle(ra,dec,angle,offset=1e-7):
# def dec2hms(dec):
# def dec2dms(dec):
# def hms2dec(hms):
# def dms2dec(dms):
# def sr2deg(solid_angle):
# def deg2sr(solid_angle):
# def distanceToDistanceModulus(distance):
# def distanceModulusToDistance(distance_modulus):
# def ang2const(lon,lat,coord='gal'):
# def ang2iau(lon,lat,coord='gal'):
# def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1):
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
. Output only the next line. | iau = ang2iau(glon,glat) |
Based on the snippet: <|code_start|> ra1950 = ugali.utils.projector.hms2dec(ra)
dec1950 = ugali.utils.projector.dms2dec(dec)
ra2000,dec2000 = ugali.utils.idl.jprecess(ra1950,dec1950)
self.data['ra'] = ra2000
self.data['dec'] = dec2000
glon,glat = cel2gal(self.data['ra'],self.data['dec'])
self.data['glon'],self.data['glat'] = glon,glat
class Kharchenko13(SourceCatalog):
"""
Global survey of star clusters in the Milky Way
http://vizier.cfa.harvard.edu/viz-bin/Cat?J/A%2bA/558/A53
NOTE: CEL and GAL coordinates are consistent to < 0.01 deg.
"""
def _load(self,filename):
kwargs = dict(delimiter=[4,18,20,8,8],usecols=[1,3,4],dtype=['S18',float,float])
if filename is None:
filename = os.path.join(self.DATADIR,"J_AA_558_A53/catalog.dat")
self.filename = filename
raw = np.genfromtxt(filename,**kwargs)
self.data.resize(len(raw))
self.data['name'] = np.char.strip(raw['f0'])
self.data['glon'] = raw['f1']
self.data['glat'] = raw['f2']
<|code_end|>
, predict the immediate next line with the help of imports:
import os,sys
import inspect
import numpy as np
import fitsio
import ugali.utils.projector
import ugali.utils.idl
import argparse
from os.path import join,abspath,split
from collections import OrderedDict as odict
from numpy.lib.recfunctions import stack_arrays
from ugali.utils.projector import gal2cel, cel2gal
from ugali.utils.healpix import ang2pix
from ugali.utils.shell import get_ugali_dir, get_cat_dir
from ugali.utils.logger import logger
and context (classes, functions, sometimes code) from other files:
# Path: ugali/utils/projector.py
# class SphericalRotator:
# class Projector:
# def __init__(self, lon_ref, lat_ref, zenithal=False):
# def setReference(self, lon_ref, lat_ref, zenithal=False):
# def cartesian(self,lon,lat):
# def rotate(self, lon, lat, invert=False):
# def __init__(self, lon_ref, lat_ref, proj_type = 'ait'):
# def rotate(lon,lat,invert=False):
# def sphereToImage(self, lon, lat):
# def imageToSphere(self, x, y):
# def sphere2image(lon_ref,lat_ref,lon,lat):
# def image2sphere(lon_ref,lat_ref,x,y):
# def cartesianSphereToImage(lon, lat):
# def cartesianImageToSphere(x,y):
# def aitoffSphereToImage(lon, lat):
# def aitoffImageToSphere(x, y):
# def gnomonicSphereToImage(lon, lat):
# def gnomonicImageToSphere(x, y):
# def angsep2(lon_1, lat_1, lon_2, lat_2):
# def angsep(lon1,lat1,lon2,lat2):
# def galToCel(ll, bb):
# def celToGal(ra, dec):
# def estimate_angle(angle, origin, new_frame, offset=1e-7):
# def gal2cel_angle(glon,glat,angle,offset=1e-7):
# def cel2gal_angle(ra,dec,angle,offset=1e-7):
# def dec2hms(dec):
# def dec2dms(dec):
# def hms2dec(hms):
# def dms2dec(dms):
# def sr2deg(solid_angle):
# def deg2sr(solid_angle):
# def distanceToDistanceModulus(distance):
# def distanceModulusToDistance(distance_modulus):
# def ang2const(lon,lat,coord='gal'):
# def ang2iau(lon,lat,coord='gal'):
# def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1):
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
#
# Path: ugali/utils/healpix.py
# def ang2pix(nside, lon, lat, nest=False):
# """
# Input (lon, lat) in degrees instead of (theta, phi) in radians
# """
# theta = np.radians(90. - lat)
# phi = np.radians(lon)
# return hp.ang2pix(nside, theta, phi, nest=nest)
#
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | ra,dec = gal2cel(self.data['glon'],self.data['glat']) |
Given the code snippet: <|code_start|> if np.isnan([self.data['glon'],self.data['glat']]).any():
raise ValueError("Incompatible values")
def __getitem__(self, key):
"""
Support indexing, slicing and direct access.
"""
try:
return self.data[key]
except ValueError as message:
if key in self.data['name']:
return self.data[self.data['name'] == key]
else:
raise ValueError(message)
def __add__(self, other):
ret = SourceCatalog()
ret.data = np.concatenate([self.data,other.data])
return ret
def __len__(self):
""" Return the length of the collection.
"""
return len(self.data)
def _load(self,filename):
pass
def match(self,lon,lat,coord='gal',tol=0.1,nnearest=1):
if coord.lower() == 'cel':
<|code_end|>
, generate the next line using the imports in this file:
import os,sys
import inspect
import numpy as np
import fitsio
import ugali.utils.projector
import ugali.utils.idl
import argparse
from os.path import join,abspath,split
from collections import OrderedDict as odict
from numpy.lib.recfunctions import stack_arrays
from ugali.utils.projector import gal2cel, cel2gal
from ugali.utils.healpix import ang2pix
from ugali.utils.shell import get_ugali_dir, get_cat_dir
from ugali.utils.logger import logger
and context (functions, classes, or occasionally code) from other files:
# Path: ugali/utils/projector.py
# class SphericalRotator:
# class Projector:
# def __init__(self, lon_ref, lat_ref, zenithal=False):
# def setReference(self, lon_ref, lat_ref, zenithal=False):
# def cartesian(self,lon,lat):
# def rotate(self, lon, lat, invert=False):
# def __init__(self, lon_ref, lat_ref, proj_type = 'ait'):
# def rotate(lon,lat,invert=False):
# def sphereToImage(self, lon, lat):
# def imageToSphere(self, x, y):
# def sphere2image(lon_ref,lat_ref,lon,lat):
# def image2sphere(lon_ref,lat_ref,x,y):
# def cartesianSphereToImage(lon, lat):
# def cartesianImageToSphere(x,y):
# def aitoffSphereToImage(lon, lat):
# def aitoffImageToSphere(x, y):
# def gnomonicSphereToImage(lon, lat):
# def gnomonicImageToSphere(x, y):
# def angsep2(lon_1, lat_1, lon_2, lat_2):
# def angsep(lon1,lat1,lon2,lat2):
# def galToCel(ll, bb):
# def celToGal(ra, dec):
# def estimate_angle(angle, origin, new_frame, offset=1e-7):
# def gal2cel_angle(glon,glat,angle,offset=1e-7):
# def cel2gal_angle(ra,dec,angle,offset=1e-7):
# def dec2hms(dec):
# def dec2dms(dec):
# def hms2dec(hms):
# def dms2dec(dms):
# def sr2deg(solid_angle):
# def deg2sr(solid_angle):
# def distanceToDistanceModulus(distance):
# def distanceModulusToDistance(distance_modulus):
# def ang2const(lon,lat,coord='gal'):
# def ang2iau(lon,lat,coord='gal'):
# def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1):
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
#
# Path: ugali/utils/healpix.py
# def ang2pix(nside, lon, lat, nest=False):
# """
# Input (lon, lat) in degrees instead of (theta, phi) in radians
# """
# theta = np.radians(90. - lat)
# phi = np.radians(lon)
# return hp.ang2pix(nside, theta, phi, nest=nest)
#
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | glon, glat = cel2gal(lon,lat) |
Given the following code snippet before the placeholder: <|code_start|>class ExtraClusters(SourceCatalog):
"""
Collection of recently discovered star clusters
"""
def _load(self,filename):
kwargs = dict(delimiter=',')
if filename is None:
filename = os.path.join(self.DATADIR,"extras/extra_clusters.csv")
self.filename = filename
raw = np.recfromcsv(filename,**kwargs)
self.data.resize(len(raw))
self.data['name'] = raw['name']
self.data['ra'] = raw['ra']
self.data['dec'] = raw['dec']
self.data['glon'],self.data['glat'] = cel2gal(raw['ra'],raw['dec'])
def catalogFactory(name, **kwargs):
"""
Factory for various catalogs.
"""
fn = lambda member: inspect.isclass(member) and member.__module__==__name__
catalogs = odict(inspect.getmembers(sys.modules[__name__], fn))
if name not in list(catalogs.keys()):
msg = "%s not found in catalogs:\n %s"%(name,list(catalogs.keys()))
<|code_end|>
, predict the next line using imports from the current file:
import os,sys
import inspect
import numpy as np
import fitsio
import ugali.utils.projector
import ugali.utils.idl
import argparse
from os.path import join,abspath,split
from collections import OrderedDict as odict
from numpy.lib.recfunctions import stack_arrays
from ugali.utils.projector import gal2cel, cel2gal
from ugali.utils.healpix import ang2pix
from ugali.utils.shell import get_ugali_dir, get_cat_dir
from ugali.utils.logger import logger
and context including class names, function names, and sometimes code from other files:
# Path: ugali/utils/projector.py
# class SphericalRotator:
# class Projector:
# def __init__(self, lon_ref, lat_ref, zenithal=False):
# def setReference(self, lon_ref, lat_ref, zenithal=False):
# def cartesian(self,lon,lat):
# def rotate(self, lon, lat, invert=False):
# def __init__(self, lon_ref, lat_ref, proj_type = 'ait'):
# def rotate(lon,lat,invert=False):
# def sphereToImage(self, lon, lat):
# def imageToSphere(self, x, y):
# def sphere2image(lon_ref,lat_ref,lon,lat):
# def image2sphere(lon_ref,lat_ref,x,y):
# def cartesianSphereToImage(lon, lat):
# def cartesianImageToSphere(x,y):
# def aitoffSphereToImage(lon, lat):
# def aitoffImageToSphere(x, y):
# def gnomonicSphereToImage(lon, lat):
# def gnomonicImageToSphere(x, y):
# def angsep2(lon_1, lat_1, lon_2, lat_2):
# def angsep(lon1,lat1,lon2,lat2):
# def galToCel(ll, bb):
# def celToGal(ra, dec):
# def estimate_angle(angle, origin, new_frame, offset=1e-7):
# def gal2cel_angle(glon,glat,angle,offset=1e-7):
# def cel2gal_angle(ra,dec,angle,offset=1e-7):
# def dec2hms(dec):
# def dec2dms(dec):
# def hms2dec(hms):
# def dms2dec(dms):
# def sr2deg(solid_angle):
# def deg2sr(solid_angle):
# def distanceToDistanceModulus(distance):
# def distanceModulusToDistance(distance_modulus):
# def ang2const(lon,lat,coord='gal'):
# def ang2iau(lon,lat,coord='gal'):
# def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1):
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
# DEGREE = 360.
# HOUR = 24.
# MINUTE = 60.
# SECOND = 3600.
#
# Path: ugali/utils/healpix.py
# def ang2pix(nside, lon, lat, nest=False):
# """
# Input (lon, lat) in degrees instead of (theta, phi) in radians
# """
# theta = np.radians(90. - lat)
# phi = np.radians(lon)
# return hp.ang2pix(nside, theta, phi, nest=nest)
#
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | logger.error(msg) |
Predict the next line after this snippet: <|code_start|> out = self.popen(cmd)
stdout = out.communicate()[0]
# There is an extra newline at the end
return stdout.split('\n')[:-1]
def bcomp(self, path):
""" Return completed logfile(s).
Parameters:
-----------
path : path to logfile(s)
Returns:
--------
files : completed logfiles and message
"""
cmd='grep -r "^Successfully completed." %s'%path
out = self.popen(cmd)
stdout = out.communicate()[0]
# There is an extra newline at the end
return stdout.split('\n')[:-1]
def throttle(self,max_jobs=None,sleep=60):
if max_jobs is None: max_jobs = self.max_jobs
if max_jobs is None: return
while True:
njobs = self.njobs()
if njobs < max_jobs:
return
else:
<|code_end|>
using the current file's imports:
import os
import subprocess, subprocess as sub
import getpass
import copy
import time
import resource
import numpy as np
import argparse
from collections import OrderedDict as odict
from itertools import chain
from ugali.utils.logger import logger
and any relevant context from other files:
# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
# FORMATS = {'DEFAULT' : "%(message)s",
# logging.WARNING : "WARNING: %(message)s",
# logging.ERROR : "ERROR: %(message)s"}
# def format(self, record):
# def file_found(filename,force):
. Output only the next line. | logger.info('%i jobs already in queue, waiting...'%(njobs)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.