sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def data_import(self, json_response):
"""Import data from json response."""
if 'data' not in json_response:
raise PyVLXException('no element data found: {0}'.format(
json.dumps(json_response)))
data = json_response['data']
for item in data:
if 'ca... | Import data from json response. | entailment |
def load_window_opener(self, item):
"""Load window opener from JSON."""
window = Window.from_config(self.pyvlx, item)
self.add(window) | Load window opener from JSON. | entailment |
def load_roller_shutter(self, item):
"""Load roller shutter from JSON."""
rollershutter = RollerShutter.from_config(self.pyvlx, item)
self.add(rollershutter) | Load roller shutter from JSON. | entailment |
def load_blind(self, item):
"""Load blind from JSON."""
blind = Blind.from_config(self.pyvlx, item)
self.add(blind) | Load blind from JSON. | entailment |
def get_terminal_size(fallback=(80, 24)):
"""
Return tuple containing columns and rows of controlling terminal, trying harder
than shutil.get_terminal_size to find a tty before returning fallback.
Theoretically, stdout, stderr, and stdin could all be different ttys that could
cause us to get the wr... | Return tuple containing columns and rows of controlling terminal, trying harder
than shutil.get_terminal_size to find a tty before returning fallback.
Theoretically, stdout, stderr, and stdin could all be different ttys that could
cause us to get the wrong measurements (instead of using the fallback) but t... | entailment |
def run_diff(self):
"""
Run checks on self.files, printing diff of styled/unstyled output to stdout.
"""
files = tuple(self.files)
# Use same header as more.
header, footer = (termcolor.colored("{0}\n{{}}\n{0}\n".format(
":" * 14), "cyan"), "\n") if len(files)... | Run checks on self.files, printing diff of styled/unstyled output to stdout. | entailment |
def run_json(self):
"""
Run checks on self.files, printing json object
containing information relavent to the CS50 IDE plugin at the end.
"""
checks = {}
for file in self.files:
try:
results = self._check(file)
except Error as e:
... | Run checks on self.files, printing json object
containing information relavent to the CS50 IDE plugin at the end. | entailment |
def run_score(self):
"""
Run checks on self.files, printing raw percentage to stdout.
"""
diffs = 0
lines = 0
for file in self.files:
try:
results = self._check(file)
except Error as e:
termcolor.cprint(e.msg, "yell... | Run checks on self.files, printing raw percentage to stdout. | entailment |
def _check(self, file):
"""
Run apropriate check based on `file`'s extension and return it,
otherwise raise an Error
"""
if not os.path.exists(file):
raise Error("file \"{}\" not found".format(file))
_, extension = os.path.splitext(file)
try:
... | Run apropriate check based on `file`'s extension and return it,
otherwise raise an Error | entailment |
def split_diff(old, new):
"""
Returns a generator yielding the side-by-side diff of `old` and `new`).
"""
return map(lambda l: l.rstrip(),
icdiff.ConsoleDiff(cols=COLUMNS).make_table(old.splitlines(), new.splitlines())) | Returns a generator yielding the side-by-side diff of `old` and `new`). | entailment |
def unified(old, new):
"""
Returns a generator yielding a unified diff between `old` and `new`.
"""
for diff in difflib.ndiff(old.splitlines(), new.splitlines()):
if diff[0] == " ":
yield diff
elif diff[0] == "?":
continue
... | Returns a generator yielding a unified diff between `old` and `new`. | entailment |
def html_diff(self, old, new):
"""
Return HTML formatted character-based diff between old and new (used for CS50 IDE).
"""
def html_transition(old_type, new_type):
tags = []
for tag in [("/", old_type), ("", new_type)]:
if tag[1] not in ["+", "-"]:... | Return HTML formatted character-based diff between old and new (used for CS50 IDE). | entailment |
def char_diff(self, old, new):
"""
Return color-coded character-based diff between `old` and `new`.
"""
def color_transition(old_type, new_type):
new_color = termcolor.colored("", None, "on_red" if new_type ==
"-" else "on_green" if n... | Return color-coded character-based diff between `old` and `new`. | entailment |
def _char_diff(self, old, new, transition, fmt=lambda c: c):
"""
Returns a char-based diff between `old` and `new` where each character
is formatted by `fmt` and transitions between blocks are determined by `transition`.
"""
differ = difflib.ndiff(old, new)
# Type of di... | Returns a char-based diff between `old` and `new` where each character
is formatted by `fmt` and transitions between blocks are determined by `transition`. | entailment |
def count_lines(self, code):
"""
Count lines of code (by default ignores empty lines, but child could override to do more).
"""
return sum(bool(line.strip()) for line in code.splitlines()) | Count lines of code (by default ignores empty lines, but child could override to do more). | entailment |
def run(command, input=None, exit=0, shell=False):
"""
Run `command` passing it stdin from `input`, throwing a DependencyError if comand is not found.
Throws Error if exit code of command is not `exit` (unless `exit` is None).
"""
if isinstance(input, str):
input = in... | Run `command` passing it stdin from `input`, throwing a DependencyError if comand is not found.
Throws Error if exit code of command is not `exit` (unless `exit` is None). | entailment |
def frame_from_raw(raw):
"""Create and return frame from raw bytes."""
command, payload = extract_from_frame(raw)
frame = create_frame(command)
if frame is None:
PYVLXLOG.warning("Command %s not implemented, raw: %s", command, ":".join("{:02x}".format(c) for c in raw))
return None
fr... | Create and return frame from raw bytes. | entailment |
def create_frame(command):
"""Create and return empty Frame from Command."""
# pylint: disable=too-many-branches,too-many-return-statements
if command == Command.GW_ERROR_NTF:
return FrameErrorNotification()
if command == Command.GW_COMMAND_SEND_REQ:
return FrameCommandSendRequest()
... | Create and return empty Frame from Command. | entailment |
async def handle_frame(self, frame):
"""Handle incoming API frame, return True if this was the expected frame."""
if not isinstance(frame, FramePasswordEnterConfirmation):
return False
if frame.status == PasswordEnterConfirmationStatus.FAILED:
PYVLXLOG.warning('Failed to ... | Handle incoming API frame, return True if this was the expected frame. | entailment |
def get_payload(self):
"""Return Payload."""
return bytes(
[self.major_version >> 8 & 255, self.major_version & 255,
self.minor_version >> 8 & 255, self.minor_version & 255]) | Return Payload. | entailment |
def from_payload(self, payload):
"""Init frame from binary data."""
self.major_version = payload[0] * 256 + payload[1]
self.minor_version = payload[2] * 256 + payload[3] | Init frame from binary data. | entailment |
def data_received(self, data):
"""Handle data received."""
self.tokenizer.feed(data)
while self.tokenizer.has_tokens():
raw = self.tokenizer.get_next_token()
frame = frame_from_raw(raw)
if frame is not None:
self.frame_received_cb(frame) | Handle data received. | entailment |
async def connect(self):
"""Connect to gateway via SSL."""
tcp_client = TCPTransport(self.frame_received_cb, self.connection_closed_cb)
self.transport, _ = await self.loop.create_connection(
lambda: tcp_client,
host=self.config.host,
port=self.config.port,
... | Connect to gateway via SSL. | entailment |
def write(self, frame):
"""Write frame to Bus."""
if not isinstance(frame, FrameBase):
raise PyVLXException("Frame not of type FrameBase", frame_type=type(frame))
PYVLXLOG.debug("SEND: %s", frame)
self.transport.write(slip_pack(bytes(frame))) | Write frame to Bus. | entailment |
def create_ssl_context():
"""Create and return SSL Context."""
ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
return ssl_context | Create and return SSL Context. | entailment |
def frame_received_cb(self, frame):
"""Received message."""
PYVLXLOG.debug("REC: %s", frame)
for frame_received_cb in self.frame_received_cbs:
# pylint: disable=not-callable
self.loop.create_task(frame_received_cb(frame)) | Received message. | entailment |
def read_config(self, path):
"""Read configuration file."""
self.pyvlx.logger.info('Reading config file: ', path)
try:
with open(path, 'r') as filehandle:
doc = yaml.load(filehandle)
if 'config' not in doc:
raise PyVLXException('no ... | Read configuration file. | entailment |
async def process_frame(self, frame):
"""Update nodes via frame, usually received by house monitor."""
if isinstance(frame, FrameNodeStatePositionChangedNotification):
if frame.node_id not in self.pyvlx.nodes:
return
node = self.pyvlx.nodes[frame.node_id]
... | Update nodes via frame, usually received by house monitor. | entailment |
def add(self, scene):
"""Add scene, replace existing scene if scene with scene_id is present."""
if not isinstance(scene, Scene):
raise TypeError()
for i, j in enumerate(self.__scenes):
if j.scene_id == scene.scene_id:
self.__scenes[i] = scene
... | Add scene, replace existing scene if scene with scene_id is present. | entailment |
async def load(self):
"""Load scenes from KLF 200."""
get_scene_list = GetSceneList(pyvlx=self.pyvlx)
await get_scene_list.do_api_call()
if not get_scene_list.success:
raise PyVLXException("Unable to retrieve scene information")
for scene in get_scene_list.scenes:
... | Load scenes from KLF 200. | entailment |
def best_prefix(bytes, system=NIST):
"""Return a bitmath instance representing the best human-readable
representation of the number of bytes given by ``bytes``. In addition
to a numeric type, the ``bytes`` parameter may also be a bitmath type.
Optionally select a preferred unit system by specifying the ``system``
... | Return a bitmath instance representing the best human-readable
representation of the number of bytes given by ``bytes``. In addition
to a numeric type, the ``bytes`` parameter may also be a bitmath type.
Optionally select a preferred unit system by specifying the ``system``
keyword. Choices for ``system`` are ``bitmat... | entailment |
def query_device_capacity(device_fd):
"""Create bitmath instances of the capacity of a system block device
Make one or more ioctl request to query the capacity of a block
device. Perform any processing required to compute the final capacity
value. Return the device capacity in bytes as a :class:`bitmath.Byte`
inst... | Create bitmath instances of the capacity of a system block device
Make one or more ioctl request to query the capacity of a block
device. Perform any processing required to compute the final capacity
value. Return the device capacity in bytes as a :class:`bitmath.Byte`
instance.
Thanks to the following resources for ... | entailment |
def getsize(path, bestprefix=True, system=NIST):
"""Return a bitmath instance in the best human-readable representation
of the file size at `path`. Optionally, provide a preferred unit
system by setting `system` to either `bitmath.NIST` (default) or
`bitmath.SI`.
Optionally, set ``bestprefix`` to ``False`` to get ... | Return a bitmath instance in the best human-readable representation
of the file size at `path`. Optionally, provide a preferred unit
system by setting `system` to either `bitmath.NIST` (default) or
`bitmath.SI`.
Optionally, set ``bestprefix`` to ``False`` to get ``bitmath.Byte``
instances back. | entailment |
def listdir(search_base, followlinks=False, filter='*',
relpath=False, bestprefix=False, system=NIST):
"""This is a generator which recurses the directory tree
`search_base`, yielding 2-tuples of:
* The absolute/relative path to a discovered file
* A bitmath instance representing the "apparent size" of... | This is a generator which recurses the directory tree
`search_base`, yielding 2-tuples of:
* The absolute/relative path to a discovered file
* A bitmath instance representing the "apparent size" of the file.
- `search_base` - The directory to begin walking down.
- `followlinks` - Whether or not to follow symb... | entailment |
def parse_string(s):
"""Parse a string with units and try to make a bitmath object out of
it.
String inputs may include whitespace characters between the value and
the unit.
"""
# Strings only please
if not isinstance(s, (str, unicode)):
raise ValueError("parse_string only accepts string inputs... | Parse a string with units and try to make a bitmath object out of
it.
String inputs may include whitespace characters between the value and
the unit. | entailment |
def parse_string_unsafe(s, system=SI):
"""Attempt to parse a string with ambiguous units and try to make a
bitmath object out of it.
This may produce inaccurate results if parsing shell output. For
example `ls` may say a 2730 Byte file is '2.7K'. 2730 Bytes == 2.73 kB
~= 2.666 KiB. See the documentation for all of... | Attempt to parse a string with ambiguous units and try to make a
bitmath object out of it.
This may produce inaccurate results if parsing shell output. For
example `ls` may say a 2730 Byte file is '2.7K'. 2730 Bytes == 2.73 kB
~= 2.666 KiB. See the documentation for all of the important details.
Note the following ca... | entailment |
def format(fmt_str=None, plural=False, bestprefix=False):
"""Context manager for printing bitmath instances.
``fmt_str`` - a formatting mini-language compat formatting string. See
the @properties (above) for a list of available items.
``plural`` - True enables printing instances with 's's if they're
plural. False... | Context manager for printing bitmath instances.
``fmt_str`` - a formatting mini-language compat formatting string. See
the @properties (above) for a list of available items.
``plural`` - True enables printing instances with 's's if they're
plural. False (default) prints them as singular (no trailing 's').
``bestpref... | entailment |
def cli_script_main(cli_args):
"""
A command line interface to basic bitmath operations.
"""
choices = ALL_UNIT_TYPES
parser = argparse.ArgumentParser(
description='Converts from one type of size to another.')
parser.add_argument('--from-stdin', default=False, action='store_true',
... | A command line interface to basic bitmath operations. | entailment |
def _do_setup(self):
"""Setup basic parameters for this class.
`base` is the numeric base which when raised to `power` is equivalent
to 1 unit of the corresponding prefix. I.e., base=2, power=10
represents 2^10, which is the NIST Binary Prefix for 1 Kibibyte.
Likewise, for the SI prefix classes `base` will be... | Setup basic parameters for this class.
`base` is the numeric base which when raised to `power` is equivalent
to 1 unit of the corresponding prefix. I.e., base=2, power=10
represents 2^10, which is the NIST Binary Prefix for 1 Kibibyte.
Likewise, for the SI prefix classes `base` will be 10, and the `power`
for the Kil... | entailment |
def _norm(self, value):
"""Normalize the input value into the fundamental unit for this prefix
type.
:param number value: The input value to be normalized
:raises ValueError: if the input value is not a type of real number
"""
if isinstance(value, self.valid_types):
self._byte_value =... | Normalize the input value into the fundamental unit for this prefix
type.
:param number value: The input value to be normalized
:raises ValueError: if the input value is not a type of real number | entailment |
def system(self):
"""The system of units used to measure an instance"""
if self._base == 2:
return "NIST"
elif self._base == 10:
return "SI"
else:
# I don't expect to ever encounter this logic branch, but
# hey, it's better to have extra te... | The system of units used to measure an instance | entailment |
def unit(self):
"""The string that is this instances prefix unit name in agreement
with this instance value (singular or plural). Following the
convention that only 1 is singular. This will always be the singular
form when :attr:`bitmath.format_plural` is ``False`` (default value).
For example:
>>> KiB(1).... | The string that is this instances prefix unit name in agreement
with this instance value (singular or plural). Following the
convention that only 1 is singular. This will always be the singular
form when :attr:`bitmath.format_plural` is ``False`` (default value).
For example:
>>> KiB(1).unit == 'KiB'
>>> Byte(0... | entailment |
def from_other(cls, item):
"""Factory function to return instances of `item` converted into a new
instance of ``cls``. Because this is a class method, it may be called
from any bitmath class object without the need to explicitly
instantiate the class ahead of time.
*Implicit Parameter:*
* ``cls`` A bitmath cl... | Factory function to return instances of `item` converted into a new
instance of ``cls``. Because this is a class method, it may be called
from any bitmath class object without the need to explicitly
instantiate the class ahead of time.
*Implicit Parameter:*
* ``cls`` A bitmath class, implicitly set to the class of th... | entailment |
def format(self, fmt):
"""Return a representation of this instance formatted with user
supplied syntax"""
_fmt_params = {
'base': self.base,
'bin': self.bin,
'binary': self.binary,
'bits': self.bits,
'bytes': self.bytes,
'power': se... | Return a representation of this instance formatted with user
supplied syntax | entailment |
def best_prefix(self, system=None):
"""Optional parameter, `system`, allows you to prefer NIST or SI in
the results. By default, the current system is used (Bit/Byte default
to NIST).
Logic discussion/notes:
Base-case, does it need converting?
If the instance is less than one Byte, return the instance as a B... | Optional parameter, `system`, allows you to prefer NIST or SI in
the results. By default, the current system is used (Bit/Byte default
to NIST).
Logic discussion/notes:
Base-case, does it need converting?
If the instance is less than one Byte, return the instance as a Bit
instance.
Else, begin by recording the unit... | entailment |
def _norm(self, value):
"""Normalize the input value into the fundamental unit for this prefix
type"""
self._bit_value = value * self._unit_value
self._byte_value = self._bit_value / 8.0 | Normalize the input value into the fundamental unit for this prefix
type | entailment |
def calc_crc(raw):
"""Calculate cyclic redundancy check (CRC)."""
crc = 0
for sym in raw:
crc = crc ^ int(sym)
return crc | Calculate cyclic redundancy check (CRC). | entailment |
def extract_from_frame(data):
"""Extract payload and command from frame."""
if len(data) <= 4:
raise PyVLXException("could_not_extract_from_frame_too_short", data=data)
length = data[0] * 256 + data[1] - 1
if len(data) != length + 3:
raise PyVLXException("could_not_extract_from_frame_inv... | Extract payload and command from frame. | entailment |
def get_payload(self):
"""Return Payload."""
payload = bytes([self.node_id])
payload += string_to_bytes(self.name, 64)
payload += bytes([self.order >> 8 & 255, self.order & 255])
payload += bytes([self.placement])
payload += bytes([self.node_variation.value])
retu... | Return Payload. | entailment |
def from_payload(self, payload):
"""Init frame from binary data."""
self.node_id = payload[0]
self.name = bytes_to_string(payload[1:65])
self.order = payload[65] * 256 + payload[66]
self.placement = payload[67]
self.node_variation = NodeVariation(payload[68]) | Init frame from binary data. | entailment |
def from_payload(self, payload):
"""Init frame from binary data."""
self.status = NodeInformationStatus(payload[0])
self.node_id = payload[1] | Init frame from binary data. | entailment |
def _get_meta(obj):
"""Extract metadata, if any, from given object."""
if hasattr(obj, 'meta'): # Spectrum or model
meta = deepcopy(obj.meta)
elif isinstance(obj, dict): # Metadata
meta = deepcopy(obj)
else: # Number
meta = {}
return meta | Extract metadata, if any, from given object. | entailment |
def _merge_meta(left, right, result, clean=True):
"""Merge metadata from left and right onto results.
This is used during class initialization.
This should also be used by operators to merge metadata after
creating a new instance but before returning it.
Result's metadata is mod... | Merge metadata from left and right onto results.
This is used during class initialization.
This should also be used by operators to merge metadata after
creating a new instance but before returning it.
Result's metadata is modified in-place.
Parameters
----------
... | entailment |
def _process_generic_param(pval, def_unit, equivalencies=[]):
"""Process generic model parameter."""
if isinstance(pval, u.Quantity):
outval = pval.to(def_unit, equivalencies).value
else: # Assume already in desired unit
outval = pval
return outval | Process generic model parameter. | entailment |
def _process_wave_param(self, pval):
"""Process individual model parameter representing wavelength."""
return self._process_generic_param(
pval, self._internal_wave_unit, equivalencies=u.spectral()) | Process individual model parameter representing wavelength. | entailment |
def waveset(self):
"""Optimal wavelengths for sampling the spectrum or bandpass."""
w = get_waveset(self.model)
if w is not None:
utils.validate_wavelengths(w)
w = w * self._internal_wave_unit
return w | Optimal wavelengths for sampling the spectrum or bandpass. | entailment |
def waverange(self):
"""Range of `waveset`."""
if self.waveset is None:
x = [None, None]
else:
x = u.Quantity([self.waveset.min(), self.waveset.max()])
return x | Range of `waveset`. | entailment |
def _validate_wavelengths(self, wave):
"""Validate wavelengths for sampling."""
if wave is None:
if self.waveset is None:
raise exceptions.SynphotError(
'self.waveset is undefined; '
'Provide wavelengths for sampling.')
wave... | Validate wavelengths for sampling. | entailment |
def _validate_other_mul_div(other):
"""Conditions for other to satisfy before mul/div."""
if not isinstance(other, (u.Quantity, numbers.Number,
BaseUnitlessSpectrum, SourceSpectrum)):
raise exceptions.IncompatibleSources(
'Can only operate on... | Conditions for other to satisfy before mul/div. | entailment |
def integrate(self, wavelengths=None, **kwargs):
"""Perform integration.
This uses any analytical integral that the
underlying model has (i.e., ``self.model.integral``).
If unavailable, it uses the default fall-back integrator
set in the ``default_integrator`` configuration item... | Perform integration.
This uses any analytical integral that the
underlying model has (i.e., ``self.model.integral``).
If unavailable, it uses the default fall-back integrator
set in the ``default_integrator`` configuration item.
If wavelengths are provided, flux or throughput i... | entailment |
def avgwave(self, wavelengths=None):
"""Calculate the :ref:`average wavelength <synphot-formula-avgwv>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be... | Calculate the :ref:`average wavelength <synphot-formula-avgwv>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angstrom.
If `None`, `waveset` i... | entailment |
def barlam(self, wavelengths=None):
"""Calculate :ref:`mean log wavelength <synphot-formula-barlam>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in... | Calculate :ref:`mean log wavelength <synphot-formula-barlam>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angstrom.
If `None`, `waveset` is ... | entailment |
def pivot(self, wavelengths=None):
"""Calculate :ref:`pivot wavelength <synphot-formula-pivwv>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angs... | Calculate :ref:`pivot wavelength <synphot-formula-pivwv>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angstrom.
If `None`, `waveset` is used... | entailment |
def force_extrapolation(self):
"""Force the underlying model to extrapolate.
An example where this is useful: You create a source spectrum
with non-default extrapolation behavior and you wish to force
the underlying empirical model to extrapolate based on nearest point.
.. note... | Force the underlying model to extrapolate.
An example where this is useful: You create a source spectrum
with non-default extrapolation behavior and you wish to force
the underlying empirical model to extrapolate based on nearest point.
.. note::
This is only applicable to... | entailment |
def taper(self, wavelengths=None):
"""Taper the spectrum or bandpass.
The wavelengths to use for the first and last points are
calculated by using the same ratio as for the 2 interior points.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quant... | Taper the spectrum or bandpass.
The wavelengths to use for the first and last points are
calculated by using the same ratio as for the 2 interior points.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values ... | entailment |
def _get_arrays(self, wavelengths, **kwargs):
"""Get sampled spectrum or bandpass in user units."""
x = self._validate_wavelengths(wavelengths)
y = self(x, **kwargs)
if isinstance(wavelengths, u.Quantity):
w = x.to(wavelengths.unit, u.spectral())
else:
w ... | Get sampled spectrum or bandpass in user units. | entailment |
def _do_plot(x, y, title='', xlog=False, ylog=False,
left=None, right=None, bottom=None, top=None,
save_as=''): # pragma: no cover
"""Plot worker.
Parameters
----------
x, y : `~astropy.units.quantity.Quantity`
Wavelength and flux/throughpu... | Plot worker.
Parameters
----------
x, y : `~astropy.units.quantity.Quantity`
Wavelength and flux/throughput to plot.
kwargs
See :func:`plot`. | entailment |
def plot(self, wavelengths=None, **kwargs): # pragma: no cover
"""Plot the spectrum.
.. note:: Uses ``matplotlib``.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Qu... | Plot the spectrum.
.. note:: Uses ``matplotlib``.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angstrom.
If `None`, `waveset` is used... | entailment |
def _validate_flux_unit(new_unit, wav_only=False):
"""Make sure flux unit is valid."""
new_unit = units.validate_unit(new_unit)
acceptable_types = ['spectral flux density wav',
'photon flux density wav']
acceptable_names = ['PHOTLAM', 'FLAM']
if not w... | Make sure flux unit is valid. | entailment |
def normalize(self, renorm_val, band=None, wavelengths=None, force=False,
area=None, vegaspec=None):
"""Renormalize the spectrum to the given Quantity and band.
.. warning::
Redshift attribute (``z``) is reset to 0 in the normalized
spectrum even if ``self.z``... | Renormalize the spectrum to the given Quantity and band.
.. warning::
Redshift attribute (``z``) is reset to 0 in the normalized
spectrum even if ``self.z`` is non-zero.
This is because the normalization simply adds a scale
factor to the existing composite model... | entailment |
def _process_flux_param(self, pval, wave):
"""Process individual model parameter representing flux."""
if isinstance(pval, u.Quantity):
self._validate_flux_unit(pval.unit)
outval = units.convert_flux(self._redshift_model(wave), pval,
self._... | Process individual model parameter representing flux. | entailment |
def model(self):
"""Model of the spectrum with given redshift."""
if self.z == 0:
m = self._model
else:
# wavelength
if self._internal_wave_unit.physical_type == 'length':
rs = self._redshift_model.inverse
# frequency or wavenumber
... | Model of the spectrum with given redshift. | entailment |
def z(self, what):
"""Change redshift."""
if not isinstance(what, numbers.Real):
raise exceptions.SynphotError(
'Redshift must be a real scalar number.')
self._z = float(what)
self._redshift_model = RedshiftScaleFactor(self._z)
if self.z_type == 'wavel... | Change redshift. | entailment |
def _validate_other_add_sub(self, other):
"""Conditions for other to satisfy before add/sub."""
if not isinstance(other, self.__class__):
raise exceptions.IncompatibleSources(
'Can only operate on {0}.'.format(self.__class__.__name__)) | Conditions for other to satisfy before add/sub. | entailment |
def plot(self, wavelengths=None, flux_unit=None, area=None, vegaspec=None,
**kwargs): # pragma: no cover
"""Plot the spectrum.
.. note:: Uses :mod:`matplotlib`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
... | Plot the spectrum.
.. note:: Uses :mod:`matplotlib`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for integration.
If not a Quantity, assumed to be in Angstrom.
If `None`, ``self.wave... | entailment |
def to_fits(self, filename, wavelengths=None, flux_unit=None, area=None,
vegaspec=None, **kwargs):
"""Write the spectrum to a FITS file.
Parameters
----------
filename : str
Output filename.
wavelengths : array-like, `~astropy.units.quantity.Quantity... | Write the spectrum to a FITS file.
Parameters
----------
filename : str
Output filename.
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angstrom.
... | entailment |
def from_file(cls, filename, keep_neg=False, **kwargs):
"""Create a spectrum from file.
If filename has 'fits' or 'fit' suffix, it is read as FITS.
Otherwise, it is read as ASCII.
Parameters
----------
filename : str
Spectrum filename.
keep_neg : bo... | Create a spectrum from file.
If filename has 'fits' or 'fit' suffix, it is read as FITS.
Otherwise, it is read as ASCII.
Parameters
----------
filename : str
Spectrum filename.
keep_neg : bool
See `~synphot.models.Empirical1D`.
kwargs :... | entailment |
def from_vega(cls, **kwargs):
"""Load :ref:`Vega spectrum <synphot-vega-spec>`.
Parameters
----------
kwargs : dict
Keywords acceptable by :func:`~synphot.specio.read_remote_spec`.
Returns
-------
vegaspec : `SourceSpectrum`
Empirical Veg... | Load :ref:`Vega spectrum <synphot-vega-spec>`.
Parameters
----------
kwargs : dict
Keywords acceptable by :func:`~synphot.specio.read_remote_spec`.
Returns
-------
vegaspec : `SourceSpectrum`
Empirical Vega spectrum. | entailment |
def _validate_flux_unit(new_unit): # pragma: no cover
"""Make sure flux unit is valid."""
new_unit = units.validate_unit(new_unit)
if new_unit.decompose() != u.dimensionless_unscaled:
raise exceptions.SynphotError(
'Unit {0} is not dimensionless'.format(new_unit))
... | Make sure flux unit is valid. | entailment |
def check_overlap(self, other, wavelengths=None, threshold=0.01):
"""Check for wavelength overlap between two spectra.
Only wavelengths where ``self`` throughput is non-zero
are considered.
Example of full overlap::
|---------- other ----------|
|------ self... | Check for wavelength overlap between two spectra.
Only wavelengths where ``self`` throughput is non-zero
are considered.
Example of full overlap::
|---------- other ----------|
|------ self ------|
Examples of partial overlap::
|---------- self... | entailment |
def unit_response(self, area, wavelengths=None):
"""Calculate :ref:`unit response <synphot-formula-uresp>`
of this bandpass.
Parameters
----------
area : float or `~astropy.units.quantity.Quantity`
Area that flux covers. If not a Quantity, assumed to be in
... | Calculate :ref:`unit response <synphot-formula-uresp>`
of this bandpass.
Parameters
----------
area : float or `~astropy.units.quantity.Quantity`
Area that flux covers. If not a Quantity, assumed to be in
:math:`cm^{2}`.
wavelengths : array-like, `~astro... | entailment |
def rmswidth(self, wavelengths=None, threshold=None):
"""Calculate the :ref:`bandpass RMS width <synphot-formula-rmswidth>`.
Not to be confused with :func:`photbw`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Waveleng... | Calculate the :ref:`bandpass RMS width <synphot-formula-rmswidth>`.
Not to be confused with :func:`photbw`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to... | entailment |
def fwhm(self, **kwargs):
"""Calculate :ref:`synphot-formula-fwhm` of equivalent gaussian.
Parameters
----------
kwargs : dict
See :func:`photbw`.
Returns
-------
fwhm_val : `~astropy.units.quantity.Quantity`
FWHM of equivalent gaussian.
... | Calculate :ref:`synphot-formula-fwhm` of equivalent gaussian.
Parameters
----------
kwargs : dict
See :func:`photbw`.
Returns
-------
fwhm_val : `~astropy.units.quantity.Quantity`
FWHM of equivalent gaussian. | entailment |
def tpeak(self, wavelengths=None):
"""Calculate :ref:`peak bandpass throughput <synphot-formula-tpeak>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be... | Calculate :ref:`peak bandpass throughput <synphot-formula-tpeak>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angstrom.
If `None`, ``self.wa... | entailment |
def wpeak(self, wavelengths=None):
"""Calculate
:ref:`wavelength at peak throughput <synphot-formula-tpeak>`.
If there are multiple data points with peak throughput
value, only the first match is returned.
Parameters
----------
wavelengths : array-like, `~astrop... | Calculate
:ref:`wavelength at peak throughput <synphot-formula-tpeak>`.
If there are multiple data points with peak throughput
value, only the first match is returned.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
... | entailment |
def rectwidth(self, wavelengths=None):
"""Calculate :ref:`bandpass rectangular width <synphot-formula-rectw>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed... | Calculate :ref:`bandpass rectangular width <synphot-formula-rectw>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angstrom.
If `None`, ``self.... | entailment |
def efficiency(self, wavelengths=None):
"""Calculate :ref:`dimensionless efficiency <synphot-formula-qtlam>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed ... | Calculate :ref:`dimensionless efficiency <synphot-formula-qtlam>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angstrom.
If `None`, ``self.wa... | entailment |
def emflx(self, area, wavelengths=None):
"""Calculate
:ref:`equivalent monochromatic flux <synphot-formula-emflx>`.
Parameters
----------
area, wavelengths
See :func:`unit_response`.
Returns
-------
em_flux : `~astropy.units.quantity.Quantity... | Calculate
:ref:`equivalent monochromatic flux <synphot-formula-emflx>`.
Parameters
----------
area, wavelengths
See :func:`unit_response`.
Returns
-------
em_flux : `~astropy.units.quantity.Quantity`
Equivalent monochromatic flux. | entailment |
def from_file(cls, filename, **kwargs):
"""Creates a bandpass from file.
If filename has 'fits' or 'fit' suffix, it is read as FITS.
Otherwise, it is read as ASCII.
Parameters
----------
filename : str
Bandpass filename.
kwargs : dict
Ke... | Creates a bandpass from file.
If filename has 'fits' or 'fit' suffix, it is read as FITS.
Otherwise, it is read as ASCII.
Parameters
----------
filename : str
Bandpass filename.
kwargs : dict
Keywords acceptable by
:func:`~synphot.sp... | entailment |
def from_filter(cls, filtername, **kwargs):
"""Load :ref:`pre-defined filter bandpass <synphot-predefined-filter>`.
Parameters
----------
filtername : str
Filter name. Choose from 'bessel_j', 'bessel_h', 'bessel_k',
'cousins_r', 'cousins_i', 'johnson_u', 'johnson... | Load :ref:`pre-defined filter bandpass <synphot-predefined-filter>`.
Parameters
----------
filtername : str
Filter name. Choose from 'bessel_j', 'bessel_h', 'bessel_k',
'cousins_r', 'cousins_i', 'johnson_u', 'johnson_b', 'johnson_v',
'johnson_r', 'johnson_i',... | entailment |
async def handle_frame(self, frame):
"""Handle incoming API frame, return True if this was the expected frame."""
if isinstance(frame, FrameActivateSceneConfirmation) and frame.session_id == self.session_id:
if frame.status == ActivateSceneConfirmationStatus.ACCEPTED:
self.su... | Handle incoming API frame, return True if this was the expected frame. | entailment |
def request_frame(self):
"""Construct initiating frame."""
self.session_id = get_new_session_id()
return FrameActivateSceneRequest(scene_id=self.scene_id, session_id=self.session_id) | Construct initiating frame. | entailment |
def _init_bins(self, binset):
"""Calculated binned wavelength centers, edges, and flux.
By contrast, the native waveset and flux should be considered
samples of a continuous function.
Thus, it makes sense to interpolate ``self.waveset`` and
``self(self.waveset)``, but not `bins... | Calculated binned wavelength centers, edges, and flux.
By contrast, the native waveset and flux should be considered
samples of a continuous function.
Thus, it makes sense to interpolate ``self.waveset`` and
``self(self.waveset)``, but not `binset` and `binflux`. | entailment |
def sample_binned(self, wavelengths=None, flux_unit=None, **kwargs):
"""Sample binned observation without interpolation.
To sample unbinned data, use ``__call__``.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Waveleng... | Sample binned observation without interpolation.
To sample unbinned data, use ``__call__``.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angstrom... | entailment |
def _get_binned_arrays(self, wavelengths, flux_unit, area=None,
vegaspec=None):
"""Get binned observation in user units."""
x = self._validate_binned_wavelengths(wavelengths)
y = self.sample_binned(wavelengths=x, flux_unit=flux_unit, area=area,
... | Get binned observation in user units. | entailment |
def binned_waverange(self, cenwave, npix, **kwargs):
"""Calculate the wavelength range covered by the given number
of pixels centered on the given central wavelengths of
`binset`.
Parameters
----------
cenwave : float or `~astropy.units.quantity.Quantity`
Des... | Calculate the wavelength range covered by the given number
of pixels centered on the given central wavelengths of
`binset`.
Parameters
----------
cenwave : float or `~astropy.units.quantity.Quantity`
Desired central wavelength.
If not a Quantity, assumed ... | entailment |
def binned_pixelrange(self, waverange, **kwargs):
"""Calculate the number of pixels within the given wavelength
range and `binset`.
Parameters
----------
waverange : tuple of float or `~astropy.units.quantity.Quantity`
Lower and upper limits of the desired wavelength... | Calculate the number of pixels within the given wavelength
range and `binset`.
Parameters
----------
waverange : tuple of float or `~astropy.units.quantity.Quantity`
Lower and upper limits of the desired wavelength range.
If not a Quantity, assumed to be in Angst... | entailment |
def effective_wavelength(self, binned=True, wavelengths=None,
mode='efflerg'):
"""Calculate :ref:`effective wavelength <synphot-formula-effwave>`.
Parameters
----------
binned : bool
Sample data in native wavelengths if `False`.
Else,... | Calculate :ref:`effective wavelength <synphot-formula-effwave>`.
Parameters
----------
binned : bool
Sample data in native wavelengths if `False`.
Else, sample binned data (default).
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
... | entailment |
def effstim(self, flux_unit=None, wavelengths=None, area=None,
vegaspec=None):
"""Calculate :ref:`effective stimulus <synphot-formula-effstim>`
for given flux unit.
Parameters
----------
flux_unit : str or `~astropy.units.core.Unit` or `None`
The unit... | Calculate :ref:`effective stimulus <synphot-formula-effstim>`
for given flux unit.
Parameters
----------
flux_unit : str or `~astropy.units.core.Unit` or `None`
The unit of effective stimulus.
COUNT gives result in count/s (see :meth:`countrate` for more
... | entailment |
def countrate(self, area, binned=True, wavelengths=None, waverange=None,
force=False):
"""Calculate :ref:`effective stimulus <synphot-formula-effstim>`
in count/s.
Parameters
----------
area : float or `~astropy.units.quantity.Quantity`
Area that fl... | Calculate :ref:`effective stimulus <synphot-formula-effstim>`
in count/s.
Parameters
----------
area : float or `~astropy.units.quantity.Quantity`
Area that flux covers. If not a Quantity, assumed to be in
:math:`cm^{2}`.
binned : bool
Sample... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.