text stringlengths 18 773k |
|---|
def synthesize(self, duration):
"""
Synthesize white noise
Args:
duration (numpy.timedelta64): The duration of the synthesized sound
"""
sr = self.samplerate.samples_per_second
seconds = duration / Seconds(1)
samples = np.random.uniform(low=-1., high=... |
def query_ssos(self):
"""
Use the MPC file that has been built up in processing this work
unit to generate another workunit.
"""
self._ssos_queried = True
mpc_filename = self.save()
return self.builder.build_workunit(mpc_filename) |
def save(self):
"""
Update the SouceReading information for the currently recorded observations and then flush those to a file.
@return: mpc_filename of the resulting save.
"""
self.get_writer().flush()
mpc_filename = self.get_writer().get_filename()
self.get_writ... |
def get_writer(self):
"""
Get a writer.
This method also makes the output filename be the same as the .track file but with .mpc.
(Currently only works on local filesystem)
:rtype MPCWriter
"""
if self._writer is None:
suffix = tasks.get_suffix(tasks.T... |
def _filter(self, filename):
"""
return 'true' if filename doesn't match name_filter regex and should be filtered out of the list.
@param filename:
@return:
"""
return self.name_filter is not None and re.search(self.name_filter, filename) is None |
def get_workunit(self, ignore_list=None):
"""
Gets a new unit of work.
Args:
ignore_list: list(str)
A list of filenames which should be ignored. Defaults to None.
Returns:
new_workunit: WorkUnit
A new unit of work that has not yet been proce... |
def get_potential_files(self, ignore_list):
"""
Get a listing of files for the appropriate task which may or may
not be locked and/or done.
"""
exclude_prefix = self.taskid == tasks.suffixes.get(tasks.REALS_TASK, '') and 'fk' or None
filenames = [filename for filename in
... |
def move_discovery_to_front(self, data):
"""
Moves the discovery triplet to the front of the reading list.
Leaves everything else in the same order.
"""
readings = self.get_readings(data)
discovery_index = self.get_discovery_index(data)
reordered_readings = (read... |
def TAPQuery(RAdeg=180.0, DECdeg=0.0, width=1, height=1):
"""Do a query of the CADC Megacam table. Get all observations insize the box. Returns a file-like object"""
QUERY =( """ SELECT """
""" COORD1(CENTROID(Plane.position_bounds)) AS "RAJ2000", COORD2(CENTROID(Plane.position_bounds)) AS "DEJ... |
def check_tags(my_expnum, ops_set, my_ccds, dry_run=True):
"""
check the tags for the given expnum/ccd set.
@param ops:
@param my_expnum:
@return:
"""
tags = storage.get_tags(my_expnum)
count = 0
outcount = 0
fails = []
for ccd in my_ccds:
success = True
count += ... |
def get_flipped_ext(file_id,ccd):
"""Given a list of exposure numbers and CCD, get them from the DB"""
import MOPfits
import os, shutil
filename=MOPfits.adGet(file_id,extno=int(ccd))
if int(ccd)<18:
tfname=filename+"F"
shutil.move(filename, tfname)
os.system("imcopy %s[-*,... |
def get_file_ids(object):
"""Get the exposure for a particular line in the meausre table"""
import MOPdbaccess
mysql = MOPdbaccess.connect('cfeps','cfhls',dbSystem='MYSQL')
cfeps=mysql.cursor()
sql="SELECT file_id FROM measure WHERE provisional LIKE %s"
cfeps.execute(sql,(object, ))
file_ids... |
def main():
"""Do the script."""
parser = argparse.ArgumentParser(
description='replace image header')
parser.add_argument('--extname',
help='name of extension to in header')
parser.add_argument('expnum', type=str,
help='exposure to update')
pa... |
def _deriv(UK, deriv):
"""Real deriv is to :math:`t`, complex deriv is to :math:`\ln t`"""
if deriv == 0:
return UK
if isinstance(deriv, complex):
def UKderiv(z):
return (-z) ** deriv.imag * UK(z)
return UKderiv
def UKderiv(z):
poly = arange(deriv) + 1
... |
def convert(lat, lon):
"""convert lat/lon from the ecliptic to the invariable plane."""
x = numpy.cos(lon) * numpy.cos(lat)
y = numpy.sin(lon) * numpy.cos(lat)
z = numpy.sin(lat)
# Invariable plane: values in arcseconds.
epsilon = 5713.86
omega = 387390.8
coseps = numpy.cos(epsilon * ... |
def searchTriples(expnums,ccd):
"""Given a list of exposure numbers, find all the KBOs in that set of exposures"""
import MOPfits,os
import MOPdbaccess
if len(expnums)!=3:
return(-1)
mysql=MOPdbaccess.connect('bucket','cfhls','MYSQL')
bucket=mysql.cursor()
### Some pro... |
def handle_error(self, error, download_request):
"""
Checks what error occured and looks for an appropriate solution.
Args:
error: Exception
The error that has occured.
download_request:
The request which resulted in the error.
"""
if ... |
def get_current_observation_date(self):
"""
Get the date of the current observation by looking in the header
of the observation for the DATE and EXPTIME keywords.
The 'DATE AT MIDDLE OF OBSERVATION' of the observation is returned
@return: Time
"""
# All HDU eleme... |
def square(m, eff_max,c,m0,sigma,m1=21):
"""
eff_max: Maximum of the efficiency function (peak efficiency)
c: shape of the drop-off in the efficiency at bright end
m0: transition to tappering at faint magnitudes
sigma: width of the transition in efficeincy
m1: magnitude at which peak efficeincy... |
def parse_square_param(line):
"""
Parse the line from the .eff file that contains the efficiency function
parameters for a 'square' function
line : the line containt the parameters, must start with 'square_param'
"""
if not line.startswith("square_param="):
raise ValueError("Not a valid ... |
def parse_eff(filename):
"""
Parse through Jean-Marcs OSSSO .eff files.
The efficiency files comes in 'chunks' meant to be used at different 'rates' of motion.
"""
blocks = []
block = {}
with open(filename) as efile:
for line in efile.readlines():
if line.lstrip().... |
def read(keypath, configfile=None):
"""
Reads a value from the configuration file.
Args:
keypath: str
Specifies the key for which the value is desired. It can be a
hierarchical path. Example: "section1.subsection.key1"
configfile: str
Path to the config file to read. ... |
def _cdata_header(self, colsep="|"):
"""
Create a header for the CDATA section, as a visual guide.
"""
fields = self.fields
header_lines = []
line = ""
for fieldName in self.field_names:
width = int(fields[fieldName]['attr']['width'])
line ... |
def _append_cdata(self, coordinate):
"""
Append an target location to the ephemeris listing.
"""
fields = self.fields
sra = coordinate.ra.to_string(units.hour, sep=':', precision=2, pad=True)
sdec = coordinate.dec.to_string(units.degree, sep=':', precision=1, alwayssign=T... |
def gemini_writer(self, f_handle):
"""
Write out a GEMINI formated OT ephemeris. This is just a hack of SSD Horizons output.
"""
f_handle.write(GEMINI_HEADER)
# Date__(UT)__HR:MN Date_________JDUT R.A.___(ICRF/J2000.0)___DEC dRA*cosD d(DEC)/dt
# 1 2 ... |
def mkpsf_failures():
"""A simple script to loop over the standard tags for the mkpsf and
step1 processing steps. If exposure/ccd combo isn't marked as
'success' then report the failure.
This example uses the vos client directly.
"""
for expnum in storage.list_dbimages():
for ccd i... |
def searchTriples(expnums,ccd,plant=False):
"""Given a list of exposure numbers, find all the KBOs in that set of exposures"""
import MOPfits,os
import MOPdbaccess
if len(expnums)!=3:
raise TaskError, "got %d exposures"%(len(expnums))
### Some program Constants
proc_these_files=[... |
def get_nailing(expnum,ccd):
"""Get the 'nailing' images associated with expnum"""
sql="""
SELECT e.expnum, (e.mjdate - f.mjdate) dt
FROM bucket.exposure e
JOIN bucket.exposure f
JOIN bucket.association b ON b.expnum=f.expnum
JOIN bucket.association a ON a.pointing=b.pointing AND a.expnum=e.... |
def intersect(self, other):
"""
Return the intersection between this frequency band and another.
Args:
other (FrequencyBand): the instance to intersect with
Examples::
>>> import zounds
>>> b1 = zounds.FrequencyBand(500, 1000)
>>> b2 = zo... |
def bands(self):
"""
An iterable of all bands in this scale
"""
if self._bands is None:
self._bands = self._compute_bands()
return self._bands |
def ensure_overlap_ratio(self, required_ratio=0.5):
"""
Ensure that every adjacent pair of frequency bands meets the overlap
ratio criteria. This can be helpful in scenarios where a scale is
being used in an invertible transform, and something like the `constant
overlap add cons... |
def Q(self):
"""
The quality factor of the scale, or, the ratio of center frequencies
to bandwidths
"""
return np.array(list(self.center_frequencies)) \
/ np.array(list(self.bandwidths)) |
def get_slice(self, frequency_band):
"""
Given a frequency band, and a frequency dimension comprised of
n_samples, return a slice using integer indices that may be used to
extract only the frequency samples that intersect with the frequency
band
"""
index = freque... |
def from_sample_rate(sample_rate, n_bands, always_even=False):
"""
Return a :class:`~zounds.spectral.LinearScale` instance whose upper
frequency bound is informed by the nyquist frequency of the sample rate.
Args:
sample_rate (SamplingRate): the sample rate whose nyquist fre... |
def _hz_to_semitones(self, hz):
"""
Convert hertz into a number of semitones above or below some reference
value, in this case, A440
"""
return np.log(hz / self._a440) / np.log(self._a) |
def resolve(object):
"""Look up the name of a source using a resolver"""
import re
sesame_cmd = 'curl -s http://cdsweb.u-strasbg.fr/viz-bin/nph-sesame/-oI?'+string.replace(object,' ','')
f = os.popen(sesame_cmd)
lines = f.readlines()
f.close()
for line in lines:
if re.searc... |
def remove_border(axes=None, keep=('left', 'bottom'), remove=('right', 'top'), labelcol=ALMOST_BLACK):
"""
Minimize chart junk by stripping out unnecessary plot borders and axis ticks.
The top/right/left/bottom keywords toggle whether the corresponding plot border is drawn
"""
ax = axes or plt.gca()... |
def handle_exit_code(d, code):
"""Sample function showing how to interpret the dialog exit codes.
This function is not used after every call to dialog in this demo
for two reasons:
1. For some boxes, unfortunately, dialog returns the code for
ERROR when the user presses ESC (instead of th... |
def main():
"""This demo shows the main features of the pythondialog Dialog class.
"""
try:
demo()
except dialog.error, exc_instance:
sys.stderr.write("Error:\n\n%s\n" % exc_instance.complete_message())
sys.exit(1)
sys.exit(0) |
def searchTriples(expnums,ccd):
"""Given a list of exposure numbers, find all the KBOs in that set of exposures"""
import MOPfits,os
import MOPdbaccess
if len(expnums)!=3:
return(-1)
### Some program Constants
proc_file = open("proc-these-files","w")
proc_file.write("# Files... |
def discands(record):
"""Display the candidates contained in a candidate record list"""
import pyfits
pyraf.iraf.images()
pyraf.iraf.images.tv()
display = pyraf.iraf.images.tv.display
width=128
cands = record['cands']
exps= record['fileId']
comments= record['comments']
... |
def is_up(coordinate, current_time):
"""
Given the position and time determin if the given target is up.
@param coordinate: the J2000 location of the source
@param current_time: The time of the observations
@return: True/False
"""
cfht.date = current_time.iso.replace('-', '/')
cfht.hori... |
def TAPQuery(query):
"""The __main__ part of the script"""
tapURL = "http://cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/sync"
## Some default parameters for that TAP service queries.
tapParams={'REQUEST': 'doQuery',
'LANG': 'ADQL',
'FORMAT': 'votable',
'QUERY... |
def step1(expnum,
ccd,
prefix='',
version='p',
sex_thresh=_SEX_THRESHOLD,
wave_thresh=_WAVE_THRESHOLD,
maxcount=_MAX_COUNT,
dry_run=False):
"""run the actual step1jmp/matt codes.
expnum: the CFHT expousre to process
ccd: which ccd in the... |
def get_json(self):
"""Create JSON data for AdapterConfig.
:returns: JSON data as follows:
{
"VIOMManage":{
},
"InitBoot":{
},
"UseVirtualAddresses":{
},
"BootMenuEnable":{
... |
def get_json(self):
"""Create JSON data for slot.
:returns: JSON data for slot as follows:
{
"@SlotIdx":0,
"OnboardControllers":{
"OnboardController": [
]
},
"AddOnCards":{
... |
def get_json(self):
"""Create JSON data for LANPort.
:returns: JSON data as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"BootProtocol":{
},
"VirtualAddr... |
def get_json(self):
"""Create FC port.
:returns: JSON for FC port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"VirtualAddress":{
"WWNN":{
... |
def get_json(self):
"""Create JSON for CNA port.
:returns: JSON for CNA port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"Functions":{
}
}
"""
port = self.get_basic_json()
p... |
def get_json(self):
"""Create JSON for FCBootEnvironment.
:returns: JSON for FCBootEnvironment as follows:
{
"FCBootEnvironment":{
"FCTargets":{
"FCTarget":[
]
},
"FC... |
def get_json(self):
"""Create JSON data for iSCSI initiator.
:returns: JSON data for iSCSI initiator as follows:
{
"DHCPUsage":{
},
"Name":{
},
"IPv4Address":{
},
"SubnetMask":{
... |
def get_json(self):
"""Create JSON data for iSCSI target.
:returns: JSON data for iSCSI target as follows:
{
"DHCPUsage":{
},
"Name":{
},
"IPv4Address":{
},
"PortNumber":{
... |
def zscale(data,contrast,min=100,max=60000):
"""Scale the data cube into the range 0-255"""
## pic 100 random elements along each dimension
## use zscale (see the IRAF display man page or
## http://iraf.net/article.php/20051205162333315
import random
x=[]
for i in random.sample(xrange(data.shape[0]),50):
... |
def update_values(ims, image_id, iq_zeropt=True, comment=False, snr=False, commdict=None):
"""
Update a row in ossuary with
:param ims: an ImageQuery, contains image table and a connector
:param image_id: the primary key of the row to be updated
:param iq_zeropt: Keyword set if iq and zeropoint are ... |
def main():
"""
Update the ossuary Postgres db with images observed for OSSOS.
iq: Go through and check all ossuary's images for new existence of IQs/zeropoints.
comment: Go through all ossuary and
Then updates ossuary with new images that are at any stage of processing.
Constructs full image en... |
def square(self, n_coeffs, do_overlap_add=False):
"""
Compute a "square" view of the frequency adaptive transform, by
resampling each frequency band such that they all contain the same
number of samples, and performing an overlap-add procedure in the
case where the sample frequen... |
def convert(self, point):
"""
Convert a point from one coordinate system to another.
Args:
point: tuple(int x, int y)
The point in the original coordinate system.
Returns:
converted_point: tuple(int x, int y)
The point in the new coordinate s... |
def simple_settings(cls):
"""
Create sane default persistence settings for learning pipelines
:param cls: The class to decorate
"""
class Settings(ff.PersistenceSettings):
_id = cls.__name__
id_provider = ff.StaticIdProvider(_id)
key_builder = ff.StringDelimitedKeyBuilder()
... |
def apply_network(network, x, chunksize=None):
"""
Apply a pytorch network, potentially in chunks
"""
network_is_cuda = next(network.parameters()).is_cuda
x = torch.from_numpy(x)
with torch.no_grad():
if network_is_cuda:
x = x.cuda()
if chunksize is None:
... |
def sample_norm(x):
"""
pixel norm as described in section 4.2 here:
https://arxiv.org/pdf/1710.10196.pdf
"""
original = x
# square
x = x ** 2
# feature-map-wise sum
x = torch.sum(x, dim=1)
# scale by number of feature maps
x *= 1.0 / original.shape[1]
x += 10e-8
x = ... |
def reset_coord(self):
"""
Reset the source location based on the init_skycoord values
@return:
"""
(x, y, idx) = self.world2pix(self.init_skycoord.ra,
self.init_skycoord.dec,
usepv=True)
self.updat... |
def pixel_coord(self):
"""
Return the coordinates of the source in the cutout reference frame.
@return:
"""
return self.get_pixel_coordinates(self.reading.pix_coord, self.reading.get_ccd_num()) |
def get_hdulist_idx(self, ccdnum):
"""
The SourceCutout is a list of HDUs, this method returns the index of the HDU that corresponds to the given
ccd number. CCDs are numbers from 0, but the first CCD (CCDNUM=0) is often in extension 1 of an MEF.
@param ccdnum: the number of the CCD in ... |
def flip_flip(self, point):
"""
Sometimes we 'flipped' the X/Y coordinates of the image during processing. This function takes an
(x,y) location from the processing pipeline and returns the x/y location relative to the original
reference frame. (Correctly checks if the coordinate is f... |
def update_pixel_location(self, new_pixel_location, hdu_index):
"""
Update the x/y location of the associated reading by using new_pixel_location and transforming from cutout
reference frame to observation refrence frame.
@param new_pixel_location: (x, y) location of the source in cutout... |
def get_pixel_coordinates(self, point, ccdnum):
"""
Retrieves the pixel location of a point within the current HDUList given the
location in the original FITS image. This takes into account that
the image may be a cutout of a larger original.
Args:
point: tuple(float,... |
def get_observation_coordinates(self, x, y, hdulist_index):
"""
Retrieves the location of a point using the coordinate system of
the original observation, i.e. the original image before any
cutouts were done.
Returns:
(x, y) in the original image coordinate system.
... |
def world2pix(self, ra, dec, usepv=True):
"""
Convert a given RA/DEC position to the X/Y/HDULIST_INDEX in the cutout frame.
Here we loop over the hdulist to find the extension is RA/DEC are from and then return the appropriate X/Y
:param ra: The Right Ascension of the point
:t... |
def zmag(self,):
"""
Return the photometric zeropoint of the CCD associated with the reading.
@return: float
"""
if self._zmag is None:
hdulist_index = self.get_hdulist_idx(self.reading.get_ccd_num())
self._zmag = self.hdulist[hdulist_index].header.get('PH... |
def apcor(self):
"""
return the aperture correction of for the CCD assocated with the reading.
@return: Apcor
"""
if self._apcor is None:
try:
self._apcor = Downloader().download_apcor(self.reading.get_apcor_uri())
except:
s... |
def get_observed_magnitude(self, centroid=True):
# NOTE: this import is only here so that we don't load up IRAF
# unnecessarily (ex: for candidates processing).
"""
Get the magnitude at the current pixel x/y location.
:return: Table
"""
max_count = float(self.as... |
def _hdu_on_disk(self, hdulist_index):
"""
IRAF routines such as daophot need input on disk.
Returns:
filename: str
The name of the file containing the FITS data.
"""
if self._tempfile is None:
self._tempfile = tempfile.NamedTemporaryFile(
... |
def comparison_image_list(self):
"""
returns a list of possible comparison images for the current cutout. Will query CADC to create the list when
first called.
@rtype: Table
"""
if self._comparison_image_list is not None:
return self._comparison_image_list
... |
def retrieve_comparison_image(self):
"""
Search the DB for a comparison image for this cutout.
"""
# selecting comparator when on a comparator should load a new one.
collectionID = self.comparison_image_list[self.comparison_image_index]['EXPNUM']
ref_ra = self.reading.ra ... |
def check_password(self, passwd, group):
# This provides authentication via CADC.
"""check that the passwd provided matches the required password."""
return gms.isMember(self.login, passwd, group) |
def integer_based_slice(self, ts):
"""
Transform a :class:`TimeSlice` into integer indices that numpy can work
with
Args:
ts (slice, TimeSlice): the time slice to translate into integer
indices
"""
if isinstance(ts, slice):
try:
... |
def load_observations((observations, regex, rename), path, filenames):
"""
Returns a provisional name based dictionary of observations of the object.
Each observations is keyed on the date. ie. a dictionary of dictionaries.
@param path: the directory where filenames are.
@type path str
@param f... |
def plant_kbos(filename, psf, kbos, shifts, prefix):
"""
Add KBOs to an image
:param filename: name of the image to add KBOs to
:param psf: the Point Spread Function in IRAF/DAOPHOT format to be used by ADDSTAR
:param kbos: list of KBOs to add, has format as returned by KBOGenerator
:param shift... |
def plant(expnums, ccd, rmin, rmax, ang, width, number=10, mmin=21.0, mmax=25.5, version='s', dry_run=False):
"""Plant artificial sources into the list of images provided.
:param expnums: list of MegaPrime exposure numbers to add artificial KBOs to
:param ccd: which ccd to work on.
:param rmin: The min... |
def _fit_radec(self):
"""
call fit_radec of BK passing in the observations.
"""
# call fitradec with mpcfile, abgfile, resfile
self.orbfit.fitradec.restype = ctypes.c_int
self.orbfit.fitradec.argtypes = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p ]
mpc_... |
def predict(self, date, obs_code=568):
"""
use the bk predict method to compute the location of the source on the given date.
"""
time = Time(date, scale='utc', precision=6)
jd = ctypes.c_double(time.jd)
# call predict with agbfile, jdate, obscode
self.orbfit.pred... |
def guithread(function):
"""
Decorator to make sure the function is called from wx's main GUI
thread. This is needed when trying to trigger UI updates from a thread
other than the main GUI thread (such as some asynchronous data loading
thread).
I learned about doing this from:
wxPython 2.8... |
def write(file,hdu,order=None,format=None):
"""Write a file in the crazy MOP format given an mop data hdu."""
if order or format:
warnings.warn('Use of <order> and <format> depricated',DeprecationWarning)
## if the order of the columns isn't constrained just use the keys in what ever order
da... |
def store(hdu,dbase='cfeps',duser='cfhls',dtype='MYSQL',table='source'):
"""Write the contents of a MOP data structure to a SQL table"""
import MOPdbaccess
db=MOPdbaccess.connect(dbase,duser,dbSystem=dtype)
dbc=db.cursor()
### INSERT THE 'HEADER' in the meta-data table
file_id=hdu['header']['i... |
def read(file):
"""Read in a file and create a data strucuture that is a hash with members 'header'
and 'data'. The 'header' is a hash of header keywords, the data is a hash of columns.
To get to the nth element of column NAME use hdu[data][NAME][n]. To get the header
information use hdu[header][KEYW... |
def xymatch(outfile, filenames, tol=2):
"""Given a list of MOPfiles merge them based on x/y coordinates matching.."""
import math
import sys
output={}
files=[]
for filename in filenames:
this_file=read(filename)
## match files based on the 'X' and 'Y' column.
## if those ... |
def default_logging_dict(*loggers: str, **kwargs: Any) -> DictStrAny:
r"""Prepare logging dict suitable with ``logging.config.dictConfig``.
**Usage**::
from logging.config import dictConfig
dictConfig(default_logging_dict('yourlogger'))
:param \*loggers: Enable logging for each logger in ... |
def update_sentry_logging(logging_dict: DictStrAny,
sentry_dsn: Optional[str],
*loggers: str,
level: Union[str, int] = None,
**kwargs: Any) -> None:
r"""Enable Sentry logging if Sentry DSN passed.
.. note::
... |
def trim(hdu, datasec='DATASEC'):
"""TRIM a CFHT MEGAPRIME frame using the DATASEC keyword"""
datasec = re.findall(r'(\d+)',
hdu.header.get(datasec))
l = int(datasec[0]) - 1
r = int(datasec[1])
b = int(datasec[2]) - 1
t = int(datasec[3])
logger.info("Trimming [%d:%d... |
def ossos_release_parser(table=False, data_release=parameters.RELEASE_VERSION):
"""
extra fun as this is space-separated so using CSV parsers is not an option
"""
names = ['cl', 'p', 'j', 'k', 'sh', 'object', 'mag', 'e_mag', 'Filt', 'Hsur', 'dist', 'e_dist', 'Nobs',
'time', 'av_xres', 'av_y... |
def ossos_discoveries(directory=parameters.REAL_KBO_AST_DIR,
suffix='ast',
no_nt_and_u=False,
single_object=None,
all_objects=True,
data_release=None,
):
"""
Returns a list of obje... |
def ossos_release_with_metadata():
"""
Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines
"""
# discoveries = ossos_release_parser()
discoveries = []
observations = ossos_discoveries()
for obj in observations:
discov = [n fo... |
def _kbos_from_survey_sym_model_input_file(model_file):
"""
Load a Survey Simulator model file as an array of ephem EllipticalBody objects.
@param model_file:
@return:
"""
lines = storage.open_vos_or_local(model_file).read().split('\n')
kbos = []
for line in lines:
if len(line) =... |
def round_sig_error(num, uncert, pm=False):
"""
Return a string of the number and its uncertainty to the right sig figs via uncertainty's print methods.
The uncertainty determines the sig fig rounding of the number.
https://pythonhosted.org/uncertainties/user_guide.html
"""
u = ufloat(num, uncer... |
def _parse_elcm_response_body_as_json(response):
"""parse eLCM response body as json data
eLCM response should be in form of:
_
Key1: value1 <-- optional -->
Key2: value2 <-- optional -->
KeyN: valueN <-- optional -->
- CRLF -
JSON string
-
:param response: eLCM response
... |
def elcm_request(irmc_info, method, path, **kwargs):
"""send an eLCM request to the server
:param irmc_info: dict of iRMC params to access the server node
{
'irmc_address': host,
'irmc_username': user_id,
'irmc_password': password,
'irmc_port': 80 or 443, default... |
def elcm_profile_get_versions(irmc_info):
"""send an eLCM request to get profile versions
:param irmc_info: node info
:returns: dict object of profiles if succeed
{
"Server":{
"@Version": "1.01",
"AdapterConfigIrmc":{
"@Version": "1.00... |
def elcm_profile_get(irmc_info, profile_name):
"""send an eLCM request to get profile data
:param irmc_info: node info
:param profile_name: name of profile
:returns: dict object of profile data if succeed
:raises: ELCMProfileNotFound if profile does not exist
:raises: SCCIClientError if SCCI fa... |
def elcm_profile_create(irmc_info, param_path):
"""send an eLCM request to create profile
To create a profile, a new session is spawned with status 'running'.
When profile is created completely, the session ends.
:param irmc_info: node info
:param param_path: path of profile
:returns: dict obj... |
def elcm_profile_set(irmc_info, input_data):
"""send an eLCM request to set param values
To apply param values, a new session is spawned with status 'running'.
When values are applied or error, the session ends.
:param irmc_info: node info
:param input_data: param values to apply, eg.
{
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.