text stringlengths 18 773k |
|---|
def write_source(self, source, comment=None, reject=False):
"""
Writes out data for a single source.
"""
if not self._header_written:
observations = [reading.get_observation() for reading in source.get_readings()]
self.write_headers(observations, self.sys_header)
... |
def mjd2gmst(mjd):
"""Convert Modfied Juian Date (JD = 2400000.5) to GMST
Taken from P.T. Walace routines.
"""
tu = (mjd - MJD0) / (100*DPY)
st = math.fmod(mjd, 1.0) * D2PI + (24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * tu) * tu) * tu) * DS2R
w = math.fmod(st, D2PI)
if w >=... |
def _gradient_penalty(self, real_samples, fake_samples, kwargs):
"""
Compute the norm of the gradients for each sample in a batch, and
penalize anything on either side of unit norm
"""
import torch
from torch.autograd import Variable, grad
real_samples = real_sam... |
def remeasure(mpc_in, reset_pixel_coordinates=True):
"""
Compute the RA/DEC of the line based on the X/Y in the comment and the WCS of the associated image.
Comment of supplied astrometric line (mpc_in) must be in OSSOSComment format.
@param mpc_in: An line of astrometric measurement to recompute the ... |
def _connection_error_wrapper(func, *args, **kwargs):
"""
Wrap a call to func in a try/except that repeats on ConnectionError
@param func:
@param args:
@param kwargs:
@return:
"""
counter = 0
while counter < 5:
try:
result = func(*args, **kwargs)
retu... |
def recompute_mag(mpc_in, skip_centroids=False):
"""
Get the mag of the object given the mp_ephem.ephem.Observation
"""
# TODO this really shouldn't need to build a 'reading' to get the cutout...
from ossos.downloads.cutouts import downloader
dlm = downloader.ImageCutoutDownloader()
mpc_ob... |
def compare_orbits(original_obs, modified_obs, cor_file):
"""Compare the orbit fit given the oringal and modified astrometry."""
origin = orbfit.Orbfit(original_obs)
modified = orbfit.Orbfit(modified_obs)
orbpt = file(cor_file+".orb", 'w')
# Dump summaries of the orbits
orbpt.write("#"*80+"\n... |
def mono(self):
"""
Return this instance summed to mono. If the instance is already mono,
this is a no-op.
"""
if self.channels == 1:
return self
x = self.sum(axis=1) * 0.5
y = x * 0.5
return AudioSamples(y, self.samplerate) |
def encode(self, flo=None, fmt='WAV', subtype='PCM_16'):
"""
Return audio samples encoded as bytes given a particular audio format
Args:
flo (file-like): A file-like object to write the bytes to. If flo
is not supplied, a new :class:`io.BytesIO` instance will be
... |
def extend_with_default(validator_class: Any) -> Any:
"""Append defaults from schema to instance need to be validated.
:param validator_class: Apply the change for given validator class.
"""
validate_properties = validator_class.VALIDATORS['properties']
def set_defaults(validator: Any,
... |
def weights(self, other):
"""
Compute weights, given a scale or time-frequency representation
:param other: A time-frequency representation, or a scale
:return: a numpy array of weights
"""
try:
return self._wdata(other)
except AttributeError:
... |
def rates_angles(fk_candidate_observations):
"""
:param fk_candidate_observations: name of the fk*reals.astrom file to check against Object.planted
"""
detections = fk_candidate_observations.get_sources()
for detection in detections:
measures = detection.get_readings()
for measure i... |
def download_hdulist(self, uri, **kwargs):
"""
Downloads a FITS image as a HDUList.
Args:
uri: The URI of the FITS image to download.
kwargs: optional arguments to pass to the vos client.
For example, passing view="cutout" and cutout=[1] will result
i... |
def download_apcor(self, uri):
"""
Downloads apcor data.
Args:
uri: The URI of the apcor data file.
Returns:
apcor: ossos.downloads.core.ApcorData
"""
local_file = os.path.basename(uri)
if os.access(local_file, os.F_OK):
fobj = o... |
def from_string(cls, rawstr):
"""
Creates an ApcorData record from the raw string format.
Expected string format:
ap_in ap_out ap_cor apcor_err
"""
try:
args = map(float, rawstr.split())
except Exception as ex:
import sys
lo... |
def run(expnum, ccd, version, dry_run=False, prefix="", force=False):
"""Run the OSSOS jmpmakepsf script.
"""
message = storage.SUCCESS
if storage.get_status(task, prefix, expnum, version=version, ccd=ccd) and not force:
logging.info("{} completed successfully for {} {} {} {}".format(task, pre... |
def run(expnum, ccd, version, dry_run=False, prefix="", force=False, ignore_dependency=False):
"""Run the OSSOS mopheader script.
"""
message = storage.SUCCESS
logging.info("Attempting to get status on header for {} {}".format(expnum, ccd))
if storage.get_status(task, prefix, expnum, version, ccd) ... |
def htmIndex(ra,dec,htm_level=3):
"""Compute htm index of htm_level at position ra,dec"""
import re
if os.uname()[0] == "Linux": javabin = '/opt/java2/bin/java '
htm_level = htm_level
verc_htm_cmd = javabin+'-classpath /usr/cadc/misc/htm/htmIndex.jar edu.jhu.htm.app.lookup %s %s %s' % (htm_level, ra... |
def circTOcutout(wcs,ra,dec,rad):
"""Convert an RA/DEC/RADIUS to an imcopy cutout"""
(x1,y1)=wcs.rd2xy((ra+rad/2.0,dec-rad/2.0))
(x2,y2)=wcs.rd2xy((ra-rad/2.0,dec+rad/2.0))
xl=min(x1,x2)
xr=max(x1,x2)
yl=min(y1,y2)
yu=max(y1,y2)
### constrain the cutout to be inside the image
x1... |
def predict(abg,date,obs=568):
"""Run GB's predict using an ABG file as input."""
import orbfit
import RO.StringUtil
(ra,dec,a,b,ang) = orbfit.predict(abg,date,obs)
obj['RA']=ra
obj['DEC']=dec
obj['dRA']=a
obj['dDEC']=b
obj['dANG']=ang
return obj |
def config_logging(level):
"""
Configure the logging given the level desired
"""
logger = logging.getLogger('')
logger.setLevel(level)
if level < logging.DEBUG:
log_format = "%(asctime)s %(message)s"
else:
log_format = "%(asctime)s %(module)s : %(lineno)d %(message)s"
s... |
def exec_prog(args):
"""Run a subprocess, check for .OK and raise error if does not exist.
args: list of arguments, for value is the command to execute.
"""
program_name = args[0]
logging.info(" ".join(args))
output = subprocess.check_output(args, stderr=subprocess.STDOUT)
if not os.acces... |
def get_pixel_bounds_from_datasec_keyword(datasec):
"""
Return the x/y pixel boundaries of the data section.
:param datasec: str e.g. '[33:2080,1:4612]'
:return: ((xmin,xmax),(ymin,ymax))
"""
datasec = re.findall(r'(\d+)', datasec)
x1 = min(int(datasec[0]), int(datasec[1]))
x2 = max(int(... |
def match_lists(pos1, pos2, tolerance=MATCH_TOLERANCE, spherical=False):
"""
Given two sets of x/y positions match the lists, uniquely.
:rtype : numpy.ma, numpy.ma
:param pos1: list of x/y positions.
:param pos2: list of x/y positions.
:param tolerance: float distance, in pixels, to consider a ... |
def stream(self):
"""
the stream to write the log content too.
@return:
"""
if self._stream is None:
self._stream = tempfile.NamedTemporaryFile(delete=False)
try:
self._stream.write(self.client.open(self.filename, view='data').read())
... |
def client(self):
"""
Send back the client we were sent, or construct a default one.
@rtype vospace.client
"""
if self._client is not None:
return self._client
self._client = vospace.client
return self._client |
def close(self):
"""
Closes the stream.
"""
self.flush()
try:
if self.stream is not None:
self.stream.flush()
_name = self.stream.name
self.stream.close()
self.client.copy(_name, self.filename)
ex... |
def parse_string(self, timestr, subfmts):
"""Read time from a single string, using a set of possible formats."""
# Datetime components required for conversion to JD by ERFA, along
# with the default values.
components = ('year', 'mon', 'mday')
defaults = (None, 1, 1, 0)
#... |
def str_kwargs(self):
"""
Generator that yields a dict of values corresponding to the
calendar date and time for the internal JD values.
"""
iys, ims, ids, ihmsfs = d2dtf(self.scale.upper()
.encode('utf8'),
... |
def _get_db_options(args):
"""Parse through a command line of arguments to over-ride the values
in the users .dbrc file.
If no user name is given then the environment variable $USERNAME is
used. If $USERNAME is not defined then prompt for input.
"""
import optik, getpass,sys
from optik impo... |
def _get_db_password(dbSystem,db,user):
"""Read through the users .dbrc file to get password for the db/user
combination suplied. If no password is found then prompt for one
"""
import string, getpass, os
dbrc = os.environ['HOME']+"/.dbrc"
password={}
if os.access(dbrc,os.R_OK):
fd=... |
def _get_db_connect(dbSystem,db,user,password):
"""Create a connection to the database specified on the command line
"""
if dbSystem=='SYBASE':
import Sybase
try:
dbh = Sybase.connect(dbSystem,
user,
password,
... |
def caom2(mpc_filename, search_date="2014 07 24.0"):
"""
builds a TSV file in the format of SSOIS by querying for possilbe observations in CADC/CAOM2.
This is a fall back program, should only be useful when SSOIS is behind.
"""
columns = ('Image',
'Ext',
'X',
... |
def download_cutout(self, reading, focus=None, needs_apcor=False):
"""
Downloads a cutout of the FITS image for a given source reading.
Args:
reading: ossos.astrom.SourceReading
The reading which will be the focus of the downloaded image.
focus: tuple(int, int)
... |
def load_objects(self, directory_name=None):
"""Load the targets from a file.
"""
# for name in Neptune:
# self.kbos[name] = Neptune[name]
if directory_name is not None:
# defaults to looking at .ast files only
if directory_name == parameters.REAL_KB... |
def p2c(self, p=None):
"""convert from plot to canvas coordinates.
See also c2p."""
if p is None:
p = [0, 0]
x = (p[0] - self.x1) * self.xscale + self.cx1
y = (p[1] - self.y1) * self.yscale + self.cy1
# logging.debug("p2c: ({},{}) -> ({},{})".format(p[0],p[1]... |
def p2s(self, p=None):
"""Convert from plot to screen coordinates"""
if not p: p = [0, 0]
s = self.p2c(p)
return self.c2s(s) |
def c2s(self, p=None):
"""Convert from canvas to screen coordinates"""
if not p:
p = [0, 0]
return p[0] - self.canvasx(self.cx1), p[1] - self.canvasy(self.cy2) |
def centre(self):
"""Return the RA/DEC of the center of the visible Canvas."""
return self.p2s(self.canvasx(self.width / 2.0)), self.p2s(self.canvasy(self.height / 2.0)) |
def coord_grid(self):
"""Draw a grid of RA/DEC on Canvas."""
ra2 = math.pi * 2
ra1 = 0
dec1 = -1 * math.pi / 2.0
dec2 = math.pi / 2.0
dra = math.fabs((self.x2 - self.x1) / 4.0)
ddec = math.fabs((self.y2 - self.y1) / 4.0)
logging.debug("Drawing the grid."... |
def tickmark(self, x, y, size=10, orientation=90):
"""Draw a line of size and orientation at x,y"""
(x1, y1) = self.p2c([x, y])
x2 = x1 + size * math.cos(math.radians(orientation))
y2 = y1 - size * math.sin(math.radians(orientation))
self.create_line(x1, y1, x2, y2) |
def limits(self, x1, x2, y1, y2):
"""Set the coordinate boundaries of plot"""
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.xscale = (self.cx2 - self.cx1) / (self.x2 - self.x1)
self.yscale = (self.cy2 - self.cy1) / (self.y2 - self.y1)
# Determ... |
def reset(self):
"""Expand to the full scale"""
sun = ephem.Sun()
this_time = Time(self.date.get(), scale='utc')
sun.compute(this_time.iso)
self.sun = Coord((sun.ra, sun.dec))
self.doplot()
self.plot_pointings() |
def updateObj(self, event):
"""Put this object in the search box"""
name = self.objList.get("active")
self.SearchVar.set(name)
self.object_info.set(str(self.kbos.get(name, '')))
return |
def relocate(self):
"""Move to the position of self.SearchVar"""
name = self.SearchVar.get()
if self.kbos.has_key(name):
kbo = self.kbos[name]
assert isinstance(kbo, orbfit.Orbfit)
this_time = Time(self.date.get(), scale='utc')
try:
... |
def zoom(self, event=None, scale=2.0):
"""Zoom in"""
# compute the x,y of the center of the screen
sx1 = (self.cx1 + self.cx2) / 2.0
sy1 = (self.cy1 + self.cy2) / 2.0
if not event is None:
logging.debug("EVENT: {},{}".format(event.x, event.y))
sx1 = even... |
def create_point(self, xcen, ycen, size=10, color='red', fill=None):
"""Plot a circle of size at this x,y location"""
if fill is None:
fill = color
(x, y) = self.p2c((xcen, ycen))
x1 = x - size
x2 = x + size
y1 = y - size
y2 = y + size
self.c... |
def current_pointing(self, index):
"""set the color of the currently selected pointing to 'blue'"""
if self.current is not None:
for item in self.pointings[self.current]['items']:
self.itemconfigure(item, outline="black")
self.current = index
for item in self.... |
def delete_pointing(self, event):
"""Delete the currently active pointing"""
if self.current is None:
return
for item in self.pointings[self.current]['items']:
self.delete(item)
self.delete(self.pointings[self.current]['label']['id'])
del (self.pointings[... |
def load_pointings(self, filename=None):
"""Load some pointings"""
filename = ( filename is None and tkFileDialog.askopenfilename() or filename)
if filename is None:
return
f = storage.open_vos_or_local(filename)
lines = f.readlines()
f.close()
poin... |
def create_pointing(self, event, label_text=None):
"""Plot the sky coverage of pointing at event.x,event.y on the canvas.
"""
x = self.canvasx(event.x)
y = self.canvasy(event.y)
(ra, dec) = self.c2p((x, y))
this_camera = Camera(ra=float(ra) * units.radian, dec=float(dec)... |
def plot_pointings(self, pointings=None):
"""Plot pointings on canavs"""
if pointings is None:
pointings = self.pointings
i = 0
for pointing in pointings:
items = []
i = i + 1
label = {}
label['text'] = pointing['label']['text... |
def set_pointing_label(self):
"""Let the label of the current pointing to the value in the plabel box"""
current = self.current
pointing = self.pointings[current]
self.delete_pointing(None)
pointing["label"]['text'] = self.plabel.get()
self.pointings.append(pointing)
... |
def move_pointing(self, event):
"""Grab nearest pointing to event.x,event.y and with cursor"""
(ra, dec) = self.c2p((self.canvasx(event.x),
self.canvasy(event.y)))
closest = None
this_pointing = None
this_index = -1
index = -1
for po... |
def ossos_pointings(self):
"""
plot an OSSOS observation on the OSSOS plot.
"""
match = re.match('(\d+)\D(\d+)', self.expnum.get())
if match is not None:
expnum = int(match.group(1))
ccd = int(match.group(2))
x = 2112 / 2.0
y = 4644... |
def get_pointings(self):
"""
Retrieve the MEGACAM pointings that overlap with the current FOV and plot.
@return: None
"""
self.camera.set("MEGACAM_40")
(ra1, dec1) = self.c2p((self.canvasx(1), self.canvasy(1)))
(ra2, dec2) = self.c2p((self.canvasx(480 * 2), self.... |
def save_pointings(self):
"""Print the currently defined FOVs"""
i = 0
if self.pointing_format.get() in ['GEMINI ET', 'CFHT ET', 'CFHT API']:
logging.info('Beginning table pointing save.')
for pointing in self.pointings:
name = pointing["label"]["text"]
... |
def doplot(self):
"""
Clear the plot and then redraw it.
"""
w = self
w.delete(ALL)
w.coord_grid()
w.objList.delete(0, END)
self._plot() |
def _plot(self):
"""Draw the actual plot.
"""
w = self
kbos = self.kbos
re_string = w.FilterVar.get()
vlist = []
for name in kbos:
if not re.search(re_string, name):
continue
vlist.append(name)
fill = None
... |
def planted(fk_candidate_observations, planted_objects, tolerance=10):
"""
Using the fk_candidate_observations as input get the Object.planted file from VOSpace and match
planted sources with found sources.
The Object.planted list is pulled from VOSpace based on the standard file-layout and name of the... |
def mjd2gmst(mjd):
"""Convert Modfied Juian Date (JD = 2400000.5) to GMST
Take from P.T. Walace routines"""
D2PI= 6.2831853071795864769252867665590057683943387987502
DS2R= 7.2722052166430399038487115353692196393452995355905e-5
tu = (mjd-51544.5)/36525.0;
st = fmod(mjd,1.0) * ... |
def ec2eq(self):
"""Convert ecliptic coordinates to equatorial coordinates"""
import math
#from numpy.matlib import sin, cos, arcsin, arctan2
from math import sin, cos
from math import asin as arcsin
from math import atan2 as arctan2
from math import acos as arcc... |
def plot_line(axes, fname, ltype):
"""plot the ecliptic plane line on the given axes."""
x = np.genfromtxt(fname, unpack=True)
axes.plot(x[0], x[1], ltype) |
def apmag_at_absmag(H, d, phi=1):
"""
Calculate the apparent magnitude of a TNO given its absolute magnitude H, for a given distance.
:param H: TNO absolute magnitude (unitless)
:param d: barycentric distance (AU)
:param phi: phase angle (0-1, always v close to 1 for TNOs)
:return: apparent mag... |
def from_summary_line(cls, summaryLine, version=4, existing_object=None):
''' Summary format:
object mag stdev dist ..E nobs time av_xres av_yres max_x max_y
a ..E e ..E i ..E node ..E argperi ..E M ..E ra_dis dec_dis
'''
if not summaryLi... |
def from_class_line(cls, classLine, version=4, existing_object=None):
'''
Class format:
class wrt n m security object mag stdev F H_sur dist ..E nobs time av_xres av_yres max_x max_y
a ..E e ..E i ..E node ..E argperi ..E time_peri .... |
def scci_cmd(host, userid, password, cmd, port=443, auth_method='basic',
client_timeout=60, do_async=True, **kwargs):
"""execute SCCI command
This function calls SCCI server modules
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param ... |
def get_client(host, userid, password, port=443, auth_method='basic',
client_timeout=60, **kwargs):
"""get SCCI command partial function
This function returns SCCI command partial function
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
... |
def get_virtual_cd_set_params_cmd(remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_deploy_iso,
... |
def get_virtual_fd_set_params_cmd(remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_floppy_fat,
... |
def get_report(host, userid, password,
port=443, auth_method='basic', client_timeout=60):
"""get iRMC report
This function returns iRMC report in XML format
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for ... |
def get_essential_properties(report, prop_keys):
"""get essential properties
This function returns a dictionary which contains keys as in
prop_keys and its values from the report.
:param report: SCCI report element
:param prop_keys: a list of keys for essential properties
:returns: a dictionar... |
def get_capabilities_properties(d_info,
capa_keys,
gpu_ids,
fpga_ids=None,
**kwargs):
"""get capabilities properties
This function returns a dictionary which contains keys
and the... |
def process_session_status(irmc_info, session_timeout, upgrade_type):
"""process session for Bios config backup/restore or RAID config operation
:param irmc_info: node info
:param session_timeout: session timeout
:param upgrade_type: flag to check upgrade with bios or irmc
:return: a dict with foll... |
def get_raid_fgi_status(report):
"""Gather fgi(foreground initialization) information of raid configuration
This function returns a fgi status which contains activity status
and its values from the report.
:param report: SCCI report information
:returns: dict of fgi status of logical_drives, such ... |
def get_firmware_upgrade_status(irmc_info, upgrade_type):
"""get firmware upgrade status of bios or irmc
: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 o... |
def median(ma):
""" do it row by row, to save memory...."""
_median = 0*ma[0].filled(fill_value=0)
for i in range(ma.shape[-1]):
t=xmedian(ma[:,:,i])
_median[:,i]=t
t=None
return _median |
def xmedian(ma):
""" Given a masked numpy array (build using numpy.ma class) return
the median value of the array."""
import numpy
_medianIndex = numpy.floor(ma.count(axis=0)/2.0)
_sortIndex = ma.argsort(kind='heapsort',axis=0)
_median = ma[0].filled(fill_value=0)*0
for idx in range(len(_sor... |
def _generate_provisional_name(q, astrom_header, fits_header):
"""
Generates a name for an object given the information in its astrom
observation header and FITS header.
:param q: a queue of provisional names to return.
:type q: Queue
:param astrom_header:
:param fits_header:
"""
whi... |
def on_toggle_autoplay_key(self):
"""
The user has pressed the keybind for toggling autoplay.
"""
if self.autoplay_manager.is_running():
self.autoplay_manager.stop_autoplay()
self.view.set_autoplay(False)
else:
self.autoplay_manager.start_autop... |
def on_accept(self, auto=False):
"""
Initiates acceptance procedure, gathering required data.
@param auto: Set on_accept to automatic measure of source?
"""
if self.model.is_current_source_named():
provisional_name = self.model.get_current_source_name()
else:... |
def on_do_accept(self,
minor_planet_number,
provisional_name,
note1,
note2,
date_of_obs,
ra,
dec,
obs_mag,
obs_mag_err,
... |
def on_do_accept(self, comment):
"""
WARNING WARNING: THIS IS ACUTALLY on_do_accept BUT HACKED.
TODO: Make it so that we have a short 'vetting' accept dialogue. Current accept dialogue too heavy for
this part of process, thus the hack.
Process the rejection of a vetting cand... |
def on_load_comparison(self, research=False):
"""
Display the comparison image
@param research: find a new comparison image even if one already known?
"""
cutout = self.model.get_current_cutout()
if research:
cutout.comparison_image_index = None
compa... |
def compute_trans(expnums, ccd, version, prefix=None, default="WCS"):
"""
Pull the astrometric header for each image, compute an x/y transform and compare to trans.jmp
this one overides trans.jmp if they are very different.
@param expnums:
@param ccd:
@param version:
@param prefix:
@ret... |
def step2(expnums, ccd, version, prefix=None, dry_run=False, default="WCS"):
"""run the actual step2 on the given exp/ccd combo"""
jmp_trans = ['step2ajmp']
jmp_args = ['step2bjmp']
matt_args = ['step2matt_jmp']
idx = 0
for expnum in expnums:
jmp_args.append(
storage.get_f... |
def parse_nate_sims(path):
'''
parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly
for every particle in the simulation at t=0.
The second (parts3999.dat) contains the same info at t=3.999 Gyrs for these particles.
:return:
'''
... |
def _convert_netmask(mask):
"""Convert netmask from CIDR format(integer) to doted decimal string."""
if mask not in range(0, 33):
raise scci.SCCIInvalidInputError(
'Netmask value is invalid.')
return socket.inet_ntoa(struct.pack(
'!L', int('1' * mask + '0' * (32 - mask), 2))) |
def apply(self, reboot=False):
"""Apply the configuration to iRMC."""
self.root.use_virtual_addresses = True
self.root.manage.manage = True
self.root.mode = 'new'
self.root.init_boot = reboot
self.client.set_profile(self.root.get_json()) |
def terminate(self, reboot=False):
"""Delete VIOM configuration from iRMC."""
self.root.manage.manage = False
self.root.mode = 'delete'
self.root.init_boot = reboot
self.client.set_profile(self.root.get_json()) |
def set_lan_port(self, port_id, mac=None):
"""Set LAN port information to configuration.
:param port_id: Physical port ID.
:param mac: virtual MAC address if virtualization is necessary.
"""
port_handler = _parse_physical_port_id(port_id)
port = self._find_port(port_hand... |
def set_iscsi_volume(self, port_id,
initiator_iqn, initiator_dhcp=False,
initiator_ip=None, initiator_netmask=None,
target_dhcp=False, target_iqn=None, target_ip=None,
target_port=3260, target_lun=0, boot_prio=1,
... |
def set_fc_volume(self, port_id,
target_wwn, target_lun=0, boot_prio=1,
initiator_wwnn=None, initiator_wwpn=None):
"""Set FibreChannel volume information to configuration.
:param port_id: Physical port ID.
:param target_wwn: WWN of target.
:pa... |
def _pad_former_ports(self, port_handler):
"""Create ports with former port index.
:param port_handler: Port information to be registered.
Depending on slot type and card type, it is necessary to register
LAN ports with former index to VIOM table.
"""
if not port_handle... |
def chunk_size_samples(sf, buf):
"""
Black magic to account for the fact that libsndfile's behavior varies
depending on file format when using the virtual io api.
If you ask for more samples from an ogg or flac file than are available
at that moment, libsndfile will give you no more samples ever, e... |
def encode(number, alphabet):
"""
Converts an integer to a base n string where n is the length of the
provided alphabet.
Modified from http://en.wikipedia.org/wiki/Base_36
"""
if not isinstance(number, (int, long)):
raise TypeError("Number must be an integer.")
base_n = ""
sign... |
def categorical(x, mu=255, normalize=True):
"""
Mu-law compress a block of audio samples, and convert them into a
categorical distribution
"""
if normalize:
# normalize the signal
mx = x.max()
x = np.divide(x, mx, where=mx != 0)
# mu law compression
x = mu_law(x)
... |
def inverse_categorical(x, mu=255):
"""
Invert categorical samples
"""
flat = x.reshape((-1, x.shape[-1]))
indices = np.argmax(flat, axis=1).astype(np.float32)
indices = (indices / mu) - 0.5
inverted = inverse_mu_law(indices, mu=mu).reshape(x.shape[:-1])
return ArrayWithUnits(inverted, x... |
def synthesize(self, duration, freqs_in_hz=[440.]):
"""
Synthesize one or more sine waves
Args:
duration (numpy.timdelta64): The duration of the sound to be
synthesized
freqs_in_hz (list of float): Numbers representing the frequencies
in h... |
def synthesize(self, duration, tick_frequency):
"""
Synthesize periodic "ticks", generated from white noise and an envelope
Args:
duration (numpy.timedelta64): The total duration of the sound to be
synthesized
tick_frequency (numpy.timedelta64): The frequ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.