Search is not available for this dataset
text
stringlengths
75
104k
def plot(self, binned=True, wavelengths=None, flux_unit=None, area=None, vegaspec=None, **kwargs): # pragma: no cover """Plot the observation. .. note:: Uses ``matplotlib``. Parameters ---------- binned : bool Plot data in native wavelengths if `False`...
def as_spectrum(self, binned=True, wavelengths=None): """Reduce the observation to an empirical source spectrum. An observation is a complex object with some restrictions on its capabilities. At times, it would be useful to work with the observation as a simple object that is easier to ...
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if not isinstance(frame, FrameSetNodeNameConfirmation): return False self.success = frame.status == SetNodeNameConfirmationStatus.OK return True
async def do_api_call(self): """Start. Sending and waiting for answer.""" self.pyvlx.connection.register_frame_received_cb( self.response_rec_callback) await self.send_frame() await self.start_timeout() await self.response_received_or_timeout.wait() await self...
async def start_timeout(self): """Start timeout.""" self.timeout_handle = self.pyvlx.connection.loop.call_later( self.timeout_in_seconds, self.timeout)
async def main(): """Load devices and scenes, run first scene.""" pyvlx = PyVLX('pyvlx.yaml') # Alternative: # pyvlx = PyVLX(host="192.168.2.127", password="velux123", timeout=60) await pyvlx.load_devices() print(pyvlx.devices[1]) print(pyvlx.devices['Fenster 4']) await pyvlx.load_scen...
async def set_state(self, parameter): """Set switch to desired state.""" command_send = CommandSend(pyvlx=self.pyvlx, node_id=self.node_id, parameter=parameter) await command_send.do_api_call() if not command_send.success: raise PyVLXException("Unable to send command") ...
def etau_madau(wave, z, **kwargs): """Madau 1995 extinction for a galaxy at given redshift. This is the Lyman-alpha prescription from the photo-z code BPZ. The Lyman-alpha forest approximately has an effective "throughput" which is a function of redshift and rest-frame wavelength. One would mul...
def extinction_curve(self, ebv, wavelengths=None): """Generate extinction curve. .. math:: A(V) = R(V) \\; \\times \\; E(B-V) THRU = 10^{-0.4 \\; A(V)} Parameters ---------- ebv : float or `~astropy.units.quantity.Quantity` :math:`E(B-V)` v...
def to_fits(self, filename, wavelengths=None, **kwargs): """Write the reddening law to a FITS file. :math:`R(V)` column is automatically named 'Av/E(B-V)'. Parameters ---------- filename : str Output filename. wavelengths : array-like, `~astropy.units.quant...
def from_file(cls, filename, **kwargs): """Create a reddening law from file. If filename has 'fits' or 'fit' suffix, it is read as FITS. Otherwise, it is read as ASCII. Parameters ---------- filename : str Reddening law filename. kwargs : dict ...
def from_extinction_model(cls, modelname, **kwargs): """Load :ref:`pre-defined extinction model <synphot_reddening>`. Parameters ---------- modelname : str Extinction model name. Choose from 'lmc30dor', 'lmcavg', 'mwavg', 'mwdense', 'mwrv21', 'mwrv40', 'smcbar', ...
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if not isinstance(frame, FrameGetVersionConfirmation): return False self.version = frame.version self.success = True return True
def validate_payload_len(self, payload): """Validate payload len.""" if not hasattr(self, "PAYLOAD_LEN"): # No fixed payload len, e.g. within FrameGetSceneListNotification return # pylint: disable=no-member if len(payload) != self.PAYLOAD_LEN: raise Py...
def build_frame(command, payload): """Build raw bytes from command and payload.""" packet_length = 2 + len(payload) + 1 ret = struct.pack("BB", 0, packet_length) ret += struct.pack(">H", command.value) ret += payload ret += struct.pack("B", calc_crc(ret)) return r...
async def run(self, wait_for_completion=True): """Run scene. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ activate_scene = ActivateScene( pyvlx=self.pyvlx, wait_for_comp...
def add(self, scene): """Add scene.""" if not isinstance(scene, Scene): raise TypeError() self.__scenes.append(scene)
async def load(self): """Load scenes from KLF 200.""" json_response = await self.pyvlx.interface.api_call('scenes', 'get') self.data_import(json_response)
def data_import(self, json_response): """Import scenes 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: self....
def load_scene(self, item): """Load scene from json.""" scene = Scene.from_config(self.pyvlx, item) self.add(scene)
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if not isinstance(frame, FrameGetStateConfirmation): return False self.success = True self.gateway_state = frame.gateway_state self.gateway_sub_state = fr...
def parse_raw(self, raw): """Parse alias array from raw bytes.""" if not isinstance(raw, bytes): raise PyVLXException("AliasArray::invalid_type_if_raw", type_raw=type(raw)) if len(raw) != 21: raise PyVLXException("AliasArray::invalid_size", size=len(raw)) nbr_of_a...
def decode(raw): """Decode SLIP message.""" return raw \ .replace(bytes([SLIP_ESC, SLIP_ESC_END]), bytes([SLIP_END])) \ .replace(bytes([SLIP_ESC, SLIP_ESC_ESC]), bytes([SLIP_ESC]))
def encode(raw): """Encode SLIP message.""" return raw \ .replace(bytes([SLIP_ESC]), bytes([SLIP_ESC, SLIP_ESC_ESC])) \ .replace(bytes([SLIP_END]), bytes([SLIP_ESC, SLIP_ESC_END]))
def get_next_slip(raw): """ Get the next slip packet from raw data. Returns the extracted packet plus the raw data with the remaining data stream. """ if not is_slip(raw): return None, raw length = raw[1:].index(SLIP_END) slip_packet = decode(raw[1:length+1]) new_raw = raw[lengt...
async def set_utc(pyvlx): """Enable house status monitor.""" setutc = SetUTC(pyvlx=pyvlx) await setutc.do_api_call() if not setutc.success: raise PyVLXException("Unable to set utc.")
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if not isinstance(frame, FrameSetUTCConfirmation): return False self.success = True return True
def _slow_calcbinflux(len_binwave, i_beg, i_end, avflux, deltaw): """Python implementation of ``calcbinflux``. This is only used if ``synphot.synphot_utils`` C-extension import fails. See docstrings.py """ binflux = np.empty(shape=(len_binwave, ), dtype=np.float64) intwave = np.empty(shap...
def calculate_bin_edges(centers): """Calculate the edges of wavelength bins given the centers. The algorithm calculates bin edges as the midpoints between bin centers and treats the first and last bins as symmetric about their centers. Parameters ---------- centers : array-like or `~astropy.un...
def calculate_bin_widths(edges): """Calculate the widths of wavelengths bins given their edges. Parameters ---------- edges : array-like or `~astropy.units.quantity.Quantity` Sequence of bin edges. Must be 1D and have at least two values. If not a Quantity, assumed to be in Angstrom. ...
def calculate_bin_centers(edges): """Calculate the centers of wavelengths bins given their edges. Parameters ---------- edges : array-like or `~astropy.units.quantity.Quantity` Sequence of bin edges. Must be 1D and have at least two values. If not a Quantity, assumed to be in Angstrom. ...
def wave_range(bins, cenwave, npix, mode='round'): """Calculate the wavelength range covered by the given number of pixels centered on the given central wavelength of the given bins. Parameters ---------- bins : array-like Wavelengths at bin centers, each centered on a pixel. Must b...
def pixel_range(bins, waverange, mode='round'): """Calculate the number of pixels within the given wavelength range and the given bins. Parameters ---------- bins : array-like Wavelengths at bin centers, each centered on a pixel. Must be 1D array. waverange : tuple of float ...
async def connect(self): """Connect to KLF 200.""" PYVLXLOG.warning("Connecting to KLF 200.") await self.connection.connect() login = Login(pyvlx=self, password=self.config.password) await login.do_api_call() if not login.success: raise PyVLXException("Login t...
async def update_version(self): """Retrieve version and protocol version from API.""" get_version = GetVersion(pyvlx=self) await get_version.do_api_call() if not get_version.success: raise PyVLXException("Unable to retrieve version") self.version = get_version.version...
async def send_frame(self, frame): """Send frame to API via connection.""" if not self.connection.connected: await self.connect() await self.update_version() await set_utc(pyvlx=self) await house_status_monitor_enable(pyvlx=self) self.connection.wr...
def from_config(cls, pyvlx, item): """Read scene from configuration.""" name = item['name'] ident = item['id'] return cls(pyvlx, ident, name)
async def api_call(self, verb, action, params=None, add_authorization_token=True, retry=False): """Send api call.""" if add_authorization_token and not self.token: await self.refresh_token() try: return await self._api_call_impl(verb, action, params, add_authorization_to...
async def refresh_token(self): """Refresh API token from KLF 200.""" json_response = await self.api_call('auth', 'login', {'password': self.config.password}, add_authorization_token=False) if 'token' not in json_response: raise PyVLXException('no element token found in response: {0}'...
def create_body(action, params): """Create http body for rest request.""" body = {} body['action'] = action if params is not None: body['params'] = params return body
def evaluate_response(json_response): """Evaluate rest response.""" if 'errors' in json_response and json_response['errors']: Interface.evaluate_errors(json_response) elif 'result' not in json_response: raise PyVLXException('no element result found in response: {0}'.form...
def evaluate_errors(json_response): """Evaluate rest errors.""" if 'errors' not in json_response or \ not isinstance(json_response['errors'], list) or \ not json_response['errors'] or \ not isinstance(json_response['errors'][0], int): raise PyVLXException('Co...
def get_payload(self): """Return Payload.""" ret = bytes([self.node_id]) ret += string_to_bytes(self.name, 64) return ret
def from_payload(self, payload): """Init frame from binary data.""" self.node_id = payload[0] self.name = bytes_to_string(payload[1:65])
def from_payload(self, payload): """Init frame from binary data.""" self.status = SetNodeNameConfirmationStatus(payload[0]) self.node_id = payload[1]
def convert_frame_to_node(pyvlx, frame): """Convert FrameGet[All]Node[s]InformationNotification into Node object.""" # pylint: disable=too-many-return-statements if frame.node_type == NodeTypeWithSubtype.WINDOW_OPENER: return Window(pyvlx=pyvlx, node_id=frame.node_id, name=frame.name, rain_sensor=Fa...
def temperature(self, what): """Set temperature.""" self._temperature = units.validate_quantity(what, u.K)
def thermal_source(self): """Apply emissivity to an existing beam to produce a thermal source spectrum (without optical counterpart). Thermal source spectrum is calculated as follow: #. Create a blackbody spectrum in PHOTLAM per square arcsec with `temperature`. ...
def from_file(cls, filename, temperature_key='DEFT', beamfill_key='BEAMFILL', **kwargs): """Creates a thermal spectral element from file. .. note:: Only FITS format is supported. Parameters ---------- filename : str Thermal spectral el...
def from_payload(self, payload): """Init frame from binary data.""" self.status = AllNodesInformationStatus(payload[0]) self.number_of_nodes = payload[1]
def get_payload(self): """Return Payload.""" payload = bytes() payload += bytes([self.node_id]) payload += bytes([self.order >> 8 & 255, self.order & 255]) payload += bytes([self.placement]) payload += bytes(string_to_bytes(self.name, 64)) payload += bytes([self.v...
def from_payload(self, payload): """Init frame from binary data.""" self.node_id = payload[0] self.order = payload[1] * 256 + payload[2] self.placement = payload[3] self.name = bytes_to_string(payload[4:68]) self.velocity = Velocity(payload[68]) self.node_type = N...
def from_parameter(self, parameter): """Set internal raw state from parameter.""" if not isinstance(parameter, Parameter): raise Exception("parameter::from_parameter_wrong_object") self.raw = parameter.raw
def from_int(value): """Create raw out of position vlaue.""" if not isinstance(value, int): raise PyVLXException("value_has_to_be_int") if not Parameter.is_valid_int(value): raise PyVLXException("value_out_of_range") return bytes([value >> 8 & 255, value & 255])
def is_valid_int(value): """Test if value can be rendered out of int.""" if 0 <= value <= Parameter.MAX: # This includes ON and OFF return True if value == Parameter.UNKNOWN_VALUE: return True if value == Parameter.CURRENT_POSITION: return True ...
def from_raw(raw): """Test if raw packets are valid for initialization of Position.""" if not isinstance(raw, bytes): raise PyVLXException("Position::raw_must_be_bytes") if len(raw) != 2: raise PyVLXException("Position::raw_must_be_two_bytes") if raw != Position.f...
def from_percent(position_percent): """Create raw value out of percent position.""" if not isinstance(position_percent, int): raise PyVLXException("Position::position_percent_has_to_be_int") if position_percent < 0: raise PyVLXException("Position::position_percent_has_to_...
def product(self): """Return product as human readable string.""" if self.product_group == 14 and self.product_type == 3: return "KLF 200" return "Unknown Product: {}:{}".format(self.product_group, self.product_type)
def get_payload(self): """Return Payload.""" ret = self._software_version ret += bytes([self.hardware_version, self.product_group, self.product_type]) return ret
def from_payload(self, payload): """Init frame from binary data.""" self._software_version = payload[0:6] self.hardware_version = payload[6] self.product_group = payload[7] self.product_type = payload[8]
def get_payload(self): """Return Payload.""" ret = bytes([self.session_id >> 8 & 255, self.session_id & 255]) ret += bytes([self.originator.value]) ret += bytes([self.priority.value]) ret += bytes([self.scene_id]) ret += bytes([self.velocity.value]) return ret
def from_payload(self, payload): """Init frame from binary data.""" self.session_id = payload[0]*256 + payload[1] self.originator = Originator(payload[2]) self.priority = Priority(payload[3]) self.scene_id = payload[4] self.velocity = Velocity(payload[5])
def get_payload(self): """Return Payload.""" ret = bytes([self.status.value]) ret += bytes([self.session_id >> 8 & 255, self.session_id & 255]) return ret
def from_payload(self, payload): """Init frame from binary data.""" self.status = ActivateSceneConfirmationStatus(payload[0]) self.session_id = payload[1]*256 + payload[2]
def get_payload(self): """Return Payload.""" # Session id ret = bytes([self.session_id >> 8 & 255, self.session_id & 255]) ret += bytes([self.originator.value]) ret += bytes([self.priority.value]) ret += bytes([0]) # ParameterActive pointing to main parameter (MP) ...
def from_payload(self, payload): """Init frame from binary data.""" self.session_id = payload[0]*256 + payload[1] self.originator = Originator(payload[2]) self.priority = Priority(payload[3]) len_node_ids = payload[41] if len_node_ids > 20: raise PyVLXExcepti...
def from_payload(self, payload): """Init frame from binary data.""" self.session_id = payload[0]*256 + payload[1] self.status = CommandSendConfirmationStatus(payload[2])
def get_payload(self): """Return Payload.""" ret = bytes([self.session_id >> 8 & 255, self.session_id & 255]) ret += bytes([self.status_id]) ret += bytes([self.index_id]) ret += bytes([self.node_parameter]) ret += bytes([self.parameter_value >> 8 & 255, self.parameter_val...
def from_payload(self, payload): """Init frame from binary data.""" self.session_id = payload[0]*256 + payload[1] self.status_id = payload[2] self.index_id = payload[3] self.node_parameter = payload[4] self.parameter_value = payload[5]*256 + payload[6]
def get_payload(self): """Return Payload.""" ret = bytes([self.session_id >> 8 & 255, self.session_id & 255]) ret += bytes([self.index_id]) ret += bytes([self.node_parameter]) ret += bytes([self.seconds >> 8 & 255, self.seconds & 255]) return ret
def from_payload(self, payload): """Init frame from binary data.""" self.session_id = payload[0]*256 + payload[1] self.index_id = payload[2] self.node_parameter = payload[3] self.seconds = payload[4]*256 + payload[5]
async def main(loop): """Log packets from Bus.""" # Setting debug PYVLXLOG.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) PYVLXLOG.addHandler(stream_handler) # Connecting to KLF 200 pyvlx = PyVLX('pyvlx.yaml', loop=loop) await...
async def rename(self, name): """Change name of node.""" set_node_name = SetNodeName(pyvlx=self.pyvlx, node_id=self.node_id, name=name) await set_node_name.do_api_call() if not set_node_name.success: raise PyVLXException("Unable to rename node") self.name = name
async def set_position(self, position, wait_for_completion=True): """Set window to desired position. Parameters: * position: Position object containing the target position. * wait_for_completion: If set, function will return after device has reached target positi...
async def open(self, wait_for_completion=True): """Open window. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=Position(position_percent=0), ...
async def close(self, wait_for_completion=True): """Close window. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=Position(position_percent=100), ...
async def stop(self, wait_for_completion=True): """Stop window. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=CurrentPosition(), wait_fo...
def _get_sampleset(model): """Return sampleset of a model or `None` if undefined. Model could be a real model or evaluated sampleset.""" if isinstance(model, Model): if hasattr(model, 'sampleset'): w = model.sampleset() else: w = None else: w = model # Al...
def _merge_sampleset(model1, model2): """Simple merge of samplesets.""" w1 = _get_sampleset(model1) w2 = _get_sampleset(model2) return merge_wavelengths(w1, w2)
def _shift_wavelengths(model1, model2): """One of the models is either ``RedshiftScaleFactor`` or ``Scale``. Possible combos:: RedshiftScaleFactor | Model Scale | Model Model | Scale """ if isinstance(model1, _models.RedshiftScaleFactor): val = _get_sampleset(model2) ...
def get_waveset(model): """Get optimal wavelengths for sampling a given model. Parameters ---------- model : `~astropy.modeling.Model` Model. Returns ------- waveset : array-like or `None` Optimal wavelengths. `None` if undefined. Raises ------ synphot.exceptio...
def _get_meta(model): """Return metadata of a model. Model could be a real model or evaluated metadata.""" if isinstance(model, Model): w = model.meta else: w = model # Already metadata return w
def _merge_meta(model1, model2): """Simple merge of samplesets.""" w1 = _get_meta(model1) w2 = _get_meta(model2) return metadata.merge(w1, w2, metadata_conflicts='silent')
def get_metadata(model): """Get metadata for a given model. Parameters ---------- model : `~astropy.modeling.Model` Model. Returns ------- metadata : dict Metadata for the model. Raises ------ synphot.exceptions.SynphotError Invalid model. """ ...
def lambda_max(self): """Peak wavelength in Angstrom when the curve is expressed as power density.""" return ((const.b_wien.value / self.temperature) * u.m).to(u.AA).value
def bounding_box(self, factor=10.0): """Tuple defining the default ``bounding_box`` limits, ``(x_low, x_high)``. .. math:: x_{\\textnormal{low}} = 0 x_{\\textnormal{high}} = \\log(\\lambda_{\\textnormal{max}} \\;\ (1 + \\textnormal{factor})) Parame...
def sampleset(self, factor_bbox=10.0, num=1000): """Return ``x`` array that samples the feature. Parameters ---------- factor_bbox : float Factor for ``bounding_box`` calculations. num : int Number of points to generate. """ w1, w2 = sel...
def evaluate(x, temperature): """Evaluate the model. Parameters ---------- x : number or ndarray Wavelengths in Angstrom. temperature : number Temperature in Kelvin. Returns ------- y : number or ndarray Blackbody rad...
def evaluate(self, x, temperature): """Evaluate the model. Parameters ---------- x : number or ndarray Wavelengths in Angstrom. temperature : number Temperature in Kelvin. Returns ------- y : number or ndarray Blackbo...
def _calc_sampleset(w1, w2, step, minimal): """Calculate sampleset for each model.""" if minimal: arr = [w1 - step, w1, w2, w2 + step] else: arr = np.arange(w1 - step, w2 + step + step, step) return arr
def sampleset(self, step=0.01, minimal=False): """Return ``x`` array that samples the feature. Parameters ---------- step : float Distance of first and last points w.r.t. bounding box. minimal : bool Only return the minimal points needed to define the bo...
def evaluate(self, x, *args): """One dimensional constant flux model function. Parameters ---------- x : number or ndarray Wavelengths in Angstrom. Returns ------- y : number or ndarray Flux in PHOTLAM. """ a = (self.ampl...
def _process_neg_flux(self, x, y): """Remove negative flux.""" if self._keep_neg: # Nothing to do return y old_y = None if np.isscalar(y): # pragma: no cover if y < 0: n_neg = 1 old_x = x old_y = y ...
def evaluate(self, inputs): """Evaluate the model. Parameters ---------- inputs : number or ndarray Wavelengths in same unit as ``points``. Returns ------- y : number or ndarray Flux or throughput in same unit as ``lookup_table``. ...
def evaluate(x, amplitude, mean, stddev): """ GaussianAbsorption1D model function. """ return 1.0 - Gaussian1D.evaluate(x, amplitude, mean, stddev)
def fit_deriv(x, amplitude, mean, stddev): """ GaussianAbsorption1D model function derivatives. """ import operator return list(map( operator.neg, Gaussian1D.fit_deriv(x, amplitude, mean, stddev)))
def sampleset(self, factor_step=0.05, **kwargs): """Return ``x`` array that samples the feature. Parameters ---------- factor_step : float Factor for sample step calculation. The step is calculated using ``factor_step * self.fwhm``. kwargs : dict ...
def evaluate(self, x, *args): """Return flux in PHOTLAM. Assume input wavelength is in Angstrom.""" xx = x / self.x_0 y = (self.amplitude * xx ** (-self.alpha)) * self._flux_unit flux = units.convert_flux(x, y, units.PHOTLAM) return flux.value
def sampleset(self): """Return ``x`` array that samples the feature.""" x1, x4 = self.bounding_box dw = self.width * 0.5 x2 = self.x_0 - dw x3 = self.x_0 + dw if self._n_models == 1: w = [x1, x2, x3, x4] else: w = list(zip(x1, x2, x3, x4))...
def get_payment_request(self, cart, request): """ From the given request, add a snippet to the page. """ try: self.charge(cart, request) thank_you_url = OrderModel.objects.get_latest_url() js_expression = 'window.location.href="{}";'.format(thank_you_u...