_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q273500 | parse_ensembl_genes | test | def parse_ensembl_genes(lines):
"""Parse lines with ensembl formated genes
This is designed to take a biomart dump with genes from ensembl.
Mandatory columns are:
'Gene ID' 'Chromosome' 'Gene Start' 'Gene End' 'HGNC symbol
Args:
lines(iterable(str)): An iterable with en... | python | {
"resource": ""
} |
q273501 | parse_ensembl_exons | test | def parse_ensembl_exons(lines):
"""Parse lines with ensembl formated exons
This is designed to take a biomart dump with exons from ensembl.
Check documentation for spec for download
Args:
lines(iterable(str)): An iterable with ensembl formated exons
Yields:
... | python | {
"resource": ""
} |
q273502 | parse_ensembl_exon_request | test | def parse_ensembl_exon_request(result):
"""Parse a dataframe with ensembl exon information
Args:
res(pandas.DataFrame)
Yields:
gene_info(dict)
"""
keys = [
'chrom',
'gene',
'transcript',
'exon_id',
'exon_chrom_start',
'exon_chrom_end'... | python | {
"resource": ""
} |
q273503 | init_log | test | def init_log(logger, filename=None, loglevel=None):
"""
Initializes the log file in the proper format.
Arguments:
filename (str): Path to a file. Or None if logging is to
be disabled.
loglevel (str): Determines the level of the log output.
"""
template = '[... | python | {
"resource": ""
} |
q273504 | parse_omim_line | test | def parse_omim_line(line, header):
"""docstring for parse_omim_2_line"""
omim_info = dict(zip(header, line.split('\t')))
return omim_info | python | {
"resource": ""
} |
q273505 | parse_omim_morbid | test | def parse_omim_morbid(lines):
"""docstring for parse_omim_morbid"""
header = []
for i,line in enumerate(lines):
line = line.rstrip()
if line.startswith('#'):
if i < 10:
if line.startswith('# Phenotype'):
header = line[2:].split('\t')
el... | python | {
"resource": ""
} |
q273506 | get_mim_phenotypes | test | def get_mim_phenotypes(genemap_lines):
"""Get a dictionary with phenotypes
Use the mim numbers for phenotypes as keys and phenotype information as
values.
Args:
genemap_lines(iterable(str))
Returns:
phenotypes_found(dict): A dictionary with mim_numbers as keys and
... | python | {
"resource": ""
} |
q273507 | cli | test | def cli(context, morbid, genemap, mim2gene, mim_titles, phenotypes):
"""Parse the omim files"""
# if not (morbid and genemap and mim2gene, mim_titles):
# print("Please provide all files")
# context.abort()
from scout.utils.handle import get_file_handle
from pprint import pprint as pp
... | python | {
"resource": ""
} |
q273508 | convert_number | test | def convert_number(string):
"""Convert a string to number
If int convert to int otherwise float
If not possible return None
"""
res = None
if isint(string):
res = int(string)
elif isfloat(string):
res = float(string)
return res | python | {
"resource": ""
} |
q273509 | GenericCalendar.formatmonth | test | def formatmonth(self, theyear, themonth, withyear=True, net=None, qs=None, template='happenings/partials/calendar/month_table.html'):
"""Return a formatted month as a table."""
context = self.get_context()
context['month_start_date'] = date(self.yr, self.mo, 1)
context['week_rows'] = []
... | python | {
"resource": ""
} |
q273510 | LegacyGenericCalendar.formatday | test | def formatday(self, day, weekday):
"""Set some commonly used variables."""
self.wkday_not_today = '<td class="%s"><div class="td-inner">' % (
self.cssclasses[weekday])
self.wkday_today = (
'<td class="%s calendar-today"><div class="td-inner">' % (
self.cs... | python | {
"resource": ""
} |
q273511 | LegacyGenericCalendar.formatmonthname | test | def formatmonthname(self, theyear, themonth, withyear=True):
"""
Change colspan to "5", add "today" button, and return a month
name as a table row.
"""
display_month = month_name[themonth]
if isinstance(display_month, six.binary_type) and self.encoding:
displ... | python | {
"resource": ""
} |
q273512 | LegacyEventCalendar.popover_helper | test | def popover_helper(self):
"""Populate variables used to build popovers."""
# when
display_month = month_name[self.mo]
if isinstance(display_month, six.binary_type) and self.encoding:
display_month = display_month.decode('utf-8')
self.when = ('<p><b>When:</b> ' + dis... | python | {
"resource": ""
} |
q273513 | get_panel_info | test | def get_panel_info(panel_lines=None, panel_id=None, institute=None, version=None, date=None,
display_name=None):
"""Parse metadata for a gene panel
For historical reasons it is possible to include all information about a gene panel in the
header of a panel file. This function parses the ... | python | {
"resource": ""
} |
q273514 | parse_gene | test | def parse_gene(gene_info):
"""Parse a gene line with information from a panel file
Args:
gene_info(dict): dictionary with gene info
Returns:
gene(dict): A dictionary with the gene information
{
'hgnc_id': int,
'hgnc_symbol': s... | python | {
"resource": ""
} |
q273515 | parse_genes | test | def parse_genes(gene_lines):
"""Parse a file with genes and return the hgnc ids
Args:
gene_lines(iterable(str)): Stream with genes
Returns:
genes(list(dict)): Dictionaries with relevant gene info
"""
genes = []
header = []
hgnc_identifiers = set()
delimiter = '\t'
#... | python | {
"resource": ""
} |
q273516 | parse_gene_panel | test | def parse_gene_panel(path, institute='cust000', panel_id='test', panel_type='clinical', date=datetime.now(),
version=1.0, display_name=None, genes = None):
"""Parse the panel info and return a gene panel
Args:
path(str): Path to panel file
institute(str): Name ... | python | {
"resource": ""
} |
q273517 | diseases | test | def diseases(context):
"""Show all diseases in the database"""
LOG.info("Running scout view diseases")
adapter = context.obj['adapter']
disease_objs = adapter.disease_terms()
nr_diseases = disease_objs.count()
if nr_diseases == 0:
click.echo("No diseases found")
else:
click... | python | {
"resource": ""
} |
q273518 | hpo | test | def hpo(context):
"""
Update the hpo terms in the database. Fetch the latest release and update terms.
"""
LOG.info("Running scout update hpo")
adapter = context.obj['adapter']
LOG.info("Dropping HPO terms")
adapter.hpo_term_collection.drop()
LOG.debug("HPO terms dropped")
load_hpo... | python | {
"resource": ""
} |
q273519 | users | test | def users(store):
"""Display a list of all users and which institutes they belong to."""
user_objs = list(store.users())
total_events = store.user_events().count()
for user_obj in user_objs:
if user_obj.get('institutes'):
user_obj['institutes'] = [store.institute(inst_id) for inst_id... | python | {
"resource": ""
} |
q273520 | parse_conservations | test | def parse_conservations(variant):
"""Parse the conservation predictors
Args:
variant(dict): A variant dictionary
Returns:
conservations(dict): A dictionary with the conservations
"""
conservations = {}
conservations['gerp'] = parse_conservation(
... | python | {
"resource": ""
} |
q273521 | parse_conservation | test | def parse_conservation(variant, info_key):
"""Get the conservation prediction
Args:
variant(dict): A variant dictionary
info_key(str)
Returns:
conservations(list): List of censervation terms
"""
raw_score = variant.INFO.get(info_key)
conservations = ... | python | {
"resource": ""
} |
q273522 | get_general_case_info | test | def get_general_case_info(adapter, institute_id=None, slice_query=None):
"""Return general information about cases
Args:
adapter(adapter.MongoAdapter)
institute_id(str)
slice_query(str): Query to filter cases to obtain statistics for.
Returns:
general(dict)
"""
g... | python | {
"resource": ""
} |
q273523 | get_case_groups | test | def get_case_groups(adapter, total_cases, institute_id=None, slice_query=None):
"""Return the information about case groups
Args:
store(adapter.MongoAdapter)
total_cases(int): Total number of cases
slice_query(str): Query to filter cases to obtain statistics for.
Returns:
c... | python | {
"resource": ""
} |
q273524 | JSONResponseMixin.render_to_json_response | test | def render_to_json_response(self, context, **kwargs):
"""
Returns a JSON response, transforming 'context' to make the payload.
"""
return HttpResponse(
self.convert_context_to_json(context),
content_type='application/json',
**kwargs
) | python | {
"resource": ""
} |
q273525 | EventMonthView.get_year_and_month | test | def get_year_and_month(self, net, qs, **kwargs):
"""
Get the year and month. First tries from kwargs, then from
querystrings. If none, or if cal_ignore qs is specified,
sets year and month to this year and this month.
"""
now = c.get_now()
year = now.year
... | python | {
"resource": ""
} |
q273526 | EventDayView.check_for_cancelled_events | test | def check_for_cancelled_events(self, d):
"""Check if any events are cancelled on the given date 'd'."""
for event in self.events:
for cn in event.cancellations.all():
if cn.date == d:
event.title += ' (CANCELLED)' | python | {
"resource": ""
} |
q273527 | HpoHandler.hpo_term | test | def hpo_term(self, hpo_id):
"""Fetch a hpo term
Args:
hpo_id(str)
Returns:
hpo_obj(dict)
"""
LOG.debug("Fetching hpo term %s", hpo_id)
return self.hpo_term_collection.find_one({'_id': hpo_id}) | python | {
"resource": ""
} |
q273528 | HpoHandler.hpo_terms | test | def hpo_terms(self, query=None, hpo_term=None, text=None, limit=None):
"""Return all HPO terms
If a query is sent hpo_terms will try to match with regex on term or
description.
Args:
query(str): Part of a hpoterm or description
hpo_term(str): Search for a specif... | python | {
"resource": ""
} |
q273529 | HpoHandler.disease_term | test | def disease_term(self, disease_identifier):
"""Return a disease term
Checks if the identifier is a disease number or a id
Args:
disease_identifier(str)
Returns:
disease_obj(dict)
"""
query = {}
try:
disease_identifier = int(d... | python | {
"resource": ""
} |
q273530 | HpoHandler.disease_terms | test | def disease_terms(self, hgnc_id=None):
"""Return all disease terms that overlaps a gene
If no gene, return all disease terms
Args:
hgnc_id(int)
Returns:
iterable(dict): A list with all disease terms that match
"""
query = {}
if hgnc_... | python | {
"resource": ""
} |
q273531 | HpoHandler.load_disease_term | test | def load_disease_term(self, disease_obj):
"""Load a disease term into the database
Args:
disease_obj(dict)
"""
LOG.debug("Loading disease term %s into database", disease_obj['_id'])
try:
self.disease_term_collection.insert_one(disease_obj)
except ... | python | {
"resource": ""
} |
q273532 | HpoHandler.generate_hpo_gene_list | test | def generate_hpo_gene_list(self, *hpo_terms):
"""Generate a sorted list with namedtuples of hpogenes
Each namedtuple of the list looks like (hgnc_id, count)
Args:
hpo_terms(iterable(str))
Returns:
hpo_genes(list(HpoGene))
"""
... | python | {
"resource": ""
} |
q273533 | Filterbank.read_hdf5 | test | def read_hdf5(self, filename, f_start=None, f_stop=None,
t_start=None, t_stop=None, load_data=True):
""" Populate Filterbank instance with data from HDF5 file
Note:
This is to be deprecated in future, please use Waterfall() to open files.
"""
print("W... | python | {
"resource": ""
} |
q273534 | Filterbank._setup_freqs | test | def _setup_freqs(self, f_start=None, f_stop=None):
""" Setup frequency axis """
## Setup frequency axis
f0 = self.header[b'fch1']
f_delt = self.header[b'foff']
i_start, i_stop = 0, self.header[b'nchans']
if f_start:
i_start = int((f_start - f0) / f_delt)
... | python | {
"resource": ""
} |
q273535 | Filterbank._setup_time_axis | test | def _setup_time_axis(self, t_start=None, t_stop=None):
""" Setup time axis. """
# now check to see how many integrations requested
ii_start, ii_stop = 0, self.n_ints_in_file
if t_start:
ii_start = t_start
if t_stop:
ii_stop = t_stop
n_ints = ii_s... | python | {
"resource": ""
} |
q273536 | Filterbank.read_filterbank | test | def read_filterbank(self, filename=None, f_start=None, f_stop=None,
t_start=None, t_stop=None, load_data=True):
""" Populate Filterbank instance with data from Filterbank file
Note:
This is to be deprecated in future, please use Waterfall() to open files.
"""... | python | {
"resource": ""
} |
q273537 | Filterbank.compute_lst | test | def compute_lst(self):
""" Compute LST for observation """
if self.header[b'telescope_id'] == 6:
self.coords = gbt_coords
elif self.header[b'telescope_id'] == 4:
self.coords = parkes_coords
else:
raise RuntimeError("Currently only Parkes and GBT suppor... | python | {
"resource": ""
} |
q273538 | Filterbank.blank_dc | test | def blank_dc(self, n_coarse_chan):
""" Blank DC bins in coarse channels.
Note: currently only works if entire file is read
"""
if n_coarse_chan < 1:
logger.warning('Coarse channel number < 1, unable to blank DC bin.')
return None
if not n_coarse_chan % ... | python | {
"resource": ""
} |
q273539 | Filterbank.info | test | def info(self):
""" Print header information """
for key, val in self.header.items():
if key == b'src_raj':
val = val.to_string(unit=u.hour, sep=':')
if key == b'src_dej':
val = val.to_string(unit=u.deg, sep=':')
if key == b'tsamp':
... | python | {
"resource": ""
} |
q273540 | Filterbank._calc_extent | test | def _calc_extent(self,plot_f=None,plot_t=None,MJD_time=False):
""" Setup ploting edges.
"""
plot_f_begin = plot_f[0]
plot_f_end = plot_f[-1] + (plot_f[1]-plot_f[0])
plot_t_begin = self.timestamps[0]
plot_t_end = self.timestamps[-1] + (self.timestamps[1] - self.timestam... | python | {
"resource": ""
} |
q273541 | Filterbank.plot_waterfall | test | def plot_waterfall(self, f_start=None, f_stop=None, if_id=0, logged=True, cb=True, MJD_time=False, **kwargs):
""" Plot waterfall of data
Args:
f_start (float): start frequency, in MHz
f_stop (float): stop frequency, in MHz
logged (bool): Plot in linear (False) or dB ... | python | {
"resource": ""
} |
q273542 | Filterbank.plot_time_series | test | def plot_time_series(self, f_start=None, f_stop=None, if_id=0, logged=True, orientation='h', MJD_time=False, **kwargs):
""" Plot the time series.
Args:
f_start (float): start frequency, in MHz
f_stop (float): stop frequency, in MHz
logged (bool): Plot in linear (Fal... | python | {
"resource": ""
} |
q273543 | Filterbank.write_to_filterbank | test | def write_to_filterbank(self, filename_out):
""" Write data to blimpy file.
Args:
filename_out (str): Name of output file
"""
print("[Filterbank] Warning: Non-standard function to write in filterbank (.fil) format. Please use Waterfall.")
n_bytes = int(self.header... | python | {
"resource": ""
} |
q273544 | Filterbank.calibrate_band_pass_N1 | test | def calibrate_band_pass_N1(self):
""" One way to calibrate the band pass is to take the median value
for every frequency fine channel, and divide by it.
"""
band_pass = np.median(self.data.squeeze(),axis=0)
self.data = self.data/band_pass | python | {
"resource": ""
} |
q273545 | convert_to_coarse | test | def convert_to_coarse(data,chan_per_coarse):
'''
Converts a data array with length n_chans to an array of length n_coarse_chans
by averaging over the coarse channels
'''
#find number of coarse channels and reshape array
num_coarse = data.size/chan_per_coarse
data_shaped = np.array(np.reshape... | python | {
"resource": ""
} |
q273546 | apply_Mueller | test | def apply_Mueller(I,Q,U,V, gain_offsets, phase_offsets, chan_per_coarse, feedtype='l'):
'''
Returns calibrated Stokes parameters for an observation given an array
of differential gains and phase differences.
'''
#Find shape of data arrays and calculate number of coarse channels
shape = I.shape
... | python | {
"resource": ""
} |
q273547 | calibrate_pols | test | def calibrate_pols(cross_pols,diode_cross,obsI=None,onefile=True,feedtype='l',**kwargs):
'''
Write Stokes-calibrated filterbank file for a given observation
with a calibrator noise diode measurement on the source
Parameters
----------
cross_pols : string
Path to cross polarization filte... | python | {
"resource": ""
} |
q273548 | fracpols | test | def fracpols(str, **kwargs):
'''Output fractional linear and circular polarizations for a
rawspec cross polarization .fil file. NOT STANDARD USE'''
I,Q,U,V,L=get_stokes(str, **kwargs)
return L/I,V/I | python | {
"resource": ""
} |
q273549 | write_polfils | test | def write_polfils(str, str_I, **kwargs):
'''Writes two new filterbank files containing fractional linear and
circular polarization data'''
lin,circ=fracpols(str, **kwargs)
obs = Waterfall(str_I, max_load=150)
obs.data = lin
obs.write_to_fil(str[:-15]+'.linpol.fil') #assuming file is named *.... | python | {
"resource": ""
} |
q273550 | closest | test | def closest(xarr, val):
""" Return the index of the closest in xarr to value val """
idx_closest = np.argmin(np.abs(np.array(xarr) - val))
return idx_closest | python | {
"resource": ""
} |
q273551 | rebin | test | def rebin(d, n_x, n_y=None):
""" Rebin data by averaging bins together
Args:
d (np.array): data
n_x (int): number of bins in x dir to rebin into one
n_y (int): number of bins in y dir to rebin into one
Returns:
d: rebinned data with shape (n_x, n_y)
"""
if d.ndim == 2:
if ... | python | {
"resource": ""
} |
q273552 | unpack | test | def unpack(data, nbit):
"""upgrade data from nbits to 8bits
Notes: Pretty sure this function is a little broken!
"""
if nbit > 8:
raise ValueError("unpack: nbit must be <= 8")
if 8 % nbit != 0:
raise ValueError("unpack: nbit must divide into 8")
if data.dtype not in (np.uint8, n... | python | {
"resource": ""
} |
q273553 | get_diff | test | def get_diff(dio_cross,feedtype,**kwargs):
'''
Returns ON-OFF for all Stokes parameters given a cross_pols noise diode measurement
'''
#Get Stokes parameters, frequencies, and time sample length
obs = Waterfall(dio_cross,max_load=150)
freqs = obs.populate_freqs()
tsamp = obs.header['tsamp']
... | python | {
"resource": ""
} |
q273554 | plot_Stokes_diode | test | def plot_Stokes_diode(dio_cross,diff=True,feedtype='l',**kwargs):
'''
Plots the uncalibrated full stokes spectrum of the noise diode.
Use diff=False to plot both ON and OFF, or diff=True for ON-OFF
'''
#If diff=True, get ON-OFF. If not get ON and OFF separately
if diff==True:
Idiff,Qdif... | python | {
"resource": ""
} |
q273555 | plot_calibrated_diode | test | def plot_calibrated_diode(dio_cross,chan_per_coarse=8,feedtype='l',**kwargs):
'''
Plots the corrected noise diode spectrum for a given noise diode measurement
after application of the inverse Mueller matrix for the electronics chain.
'''
#Get full stokes data for the ND observation
obs = Waterfa... | python | {
"resource": ""
} |
q273556 | plot_gain_offsets | test | def plot_gain_offsets(dio_cross,dio_chan_per_coarse=8,feedtype='l',ax1=None,ax2=None,legend=True,**kwargs):
'''
Plots the calculated gain offsets of each coarse channel along with
the time averaged power spectra of the X and Y feeds
'''
#Get ON-OFF ND spectra
Idiff,Qdiff,Udiff,Vdiff,freqs = get_... | python | {
"resource": ""
} |
q273557 | open_file | test | def open_file(filename, f_start=None, f_stop=None,t_start=None, t_stop=None,load_data=True,max_load=1.):
"""Open a HDF5 or filterbank file
Returns instance of a Reader to read data from file.
================== ==================================================
Filename extension File type
=======... | python | {
"resource": ""
} |
q273558 | Reader._setup_selection_range | test | def _setup_selection_range(self, f_start=None, f_stop=None, t_start=None, t_stop=None, init=False):
"""Making sure the selection if time and frequency are within the file limits.
Args:
init (bool): If call during __init__
"""
# This avoids resetting values
if init i... | python | {
"resource": ""
} |
q273559 | Reader._calc_selection_size | test | def _calc_selection_size(self):
"""Calculate size of data of interest.
"""
#Check to see how many integrations requested
n_ints = self.t_stop - self.t_start
#Check to see how many frequency channels requested
n_chan = (self.f_stop - self.f_start) / abs(self.header[b'foff... | python | {
"resource": ""
} |
q273560 | Reader._calc_selection_shape | test | def _calc_selection_shape(self):
"""Calculate shape of data of interest.
"""
#Check how many integrations requested
n_ints = int(self.t_stop - self.t_start)
#Check how many frequency channels requested
n_chan = int(np.round((self.f_stop - self.f_start) / abs(self.header[... | python | {
"resource": ""
} |
q273561 | Reader._setup_chans | test | def _setup_chans(self):
"""Setup channel borders
"""
if self.header[b'foff'] < 0:
f0 = self.f_end
else:
f0 = self.f_begin
i_start, i_stop = 0, self.n_channels_in_file
if self.f_start:
i_start = np.round((self.f_start - f0) / self.head... | python | {
"resource": ""
} |
q273562 | Reader._setup_freqs | test | def _setup_freqs(self):
"""Updating frequency borders from channel values
"""
if self.header[b'foff'] > 0:
self.f_start = self.f_begin + self.chan_start_idx*abs(self.header[b'foff'])
self.f_stop = self.f_begin + self.chan_stop_idx*abs(self.header[b'foff'])
else:
... | python | {
"resource": ""
} |
q273563 | Reader.populate_timestamps | test | def populate_timestamps(self,update_header=False):
""" Populate time axis.
IF update_header then only return tstart
"""
#Check to see how many integrations requested
ii_start, ii_stop = 0, self.n_ints_in_file
if self.t_start:
ii_start = self.t_start
... | python | {
"resource": ""
} |
q273564 | Reader.populate_freqs | test | def populate_freqs(self):
"""
Populate frequency axis
"""
if self.header[b'foff'] < 0:
f0 = self.f_end
else:
f0 = self.f_begin
self._setup_chans()
#create freq array
i_vals = np.arange(self.chan_start_idx, self.chan_stop_idx)
... | python | {
"resource": ""
} |
q273565 | Reader.calc_n_coarse_chan | test | def calc_n_coarse_chan(self, chan_bw=None):
""" This makes an attempt to calculate the number of coarse channels in a given file.
Note:
This is unlikely to work on non-Breakthrough Listen data, as a-priori knowledge of
the digitizer system is required.
"""
... | python | {
"resource": ""
} |
q273566 | Reader.calc_n_blobs | test | def calc_n_blobs(self, blob_dim):
""" Given the blob dimensions, calculate how many fit in the data selection.
"""
n_blobs = int(np.ceil(1.0 * np.prod(self.selection_shape) / np.prod(blob_dim)))
return n_blobs | python | {
"resource": ""
} |
q273567 | Reader.isheavy | test | def isheavy(self):
""" Check if the current selection is too large.
"""
selection_size_bytes = self._calc_selection_size()
if selection_size_bytes > self.MAX_DATA_ARRAY_SIZE:
return True
else:
return False | python | {
"resource": ""
} |
q273568 | FilReader.read_data | test | def read_data(self, f_start=None, f_stop=None,t_start=None, t_stop=None):
""" Read data.
"""
self._setup_selection_range(f_start=f_start, f_stop=f_stop, t_start=t_start, t_stop=t_stop)
#check if selection is small enough.
if self.isheavy():
logger.warning("Selection... | python | {
"resource": ""
} |
q273569 | FilReader.read_all | test | def read_all(self,reverse=True):
""" read all the data.
If reverse=True the x axis is flipped.
"""
raise NotImplementedError('To be implemented')
# go to start of the data
self.filfile.seek(int(self.datastart))
# read data into 2-D numpy array
# data=n... | python | {
"resource": ""
} |
q273570 | FilReader.read_row | test | def read_row(self,rownumber,reverse=True):
""" Read a block of data. The number of samples per row is set in self.channels
If reverse=True the x axis is flipped.
"""
raise NotImplementedError('To be implemented')
# go to start of the row
self.filfile.seek(int(self.da... | python | {
"resource": ""
} |
q273571 | Waterfall.read_data | test | def read_data(self, f_start=None, f_stop=None,t_start=None, t_stop=None):
""" Reads data selection if small enough.
"""
self.container.read_data(f_start=f_start, f_stop=f_stop,t_start=t_start, t_stop=t_stop)
self.__load_data() | python | {
"resource": ""
} |
q273572 | Waterfall.__update_header | test | def __update_header(self):
""" Updates the header information from the original file to the selection.
"""
#Updating frequency of first channel from selection
if self.header[b'foff'] < 0:
self.header[b'fch1'] = self.container.f_stop
else:
self.header[b'fc... | python | {
"resource": ""
} |
q273573 | Waterfall.info | test | def info(self):
""" Print header information and other derived information. """
print("\n--- File Info ---")
for key, val in self.file_header.items():
if key == 'src_raj':
val = val.to_string(unit=u.hour, sep=':')
if key == 'src_dej':
val... | python | {
"resource": ""
} |
q273574 | Waterfall.write_to_fil | test | def write_to_fil(self, filename_out, *args, **kwargs):
""" Write data to .fil file.
It check the file size then decides how to write the file.
Args:
filename_out (str): Name of output file
"""
#For timing how long it takes to write a file.
t0 = time.time... | python | {
"resource": ""
} |
q273575 | Waterfall.write_to_hdf5 | test | def write_to_hdf5(self, filename_out, *args, **kwargs):
""" Write data to HDF5 file.
It check the file size then decides how to write the file.
Args:
filename_out (str): Name of output file
"""
#For timing how long it takes to write a file.
t0 = time.tim... | python | {
"resource": ""
} |
q273576 | Waterfall.__write_to_hdf5_light | test | def __write_to_hdf5_light(self, filename_out, *args, **kwargs):
""" Write data to HDF5 file in one go.
Args:
filename_out (str): Name of output file
"""
block_size = 0
with h5py.File(filename_out, 'w') as h5:
h5.attrs[b'CLASS'] = b'FILTERBANK'
... | python | {
"resource": ""
} |
q273577 | Waterfall.__get_blob_dimensions | test | def __get_blob_dimensions(self, chunk_dim):
""" Sets the blob dimmentions, trying to read around 1024 MiB at a time.
This is assuming a chunk is about 1 MiB.
"""
#Taking the size into consideration, but avoiding having multiple blobs within a single time bin.
if self.selecti... | python | {
"resource": ""
} |
q273578 | Waterfall.__get_chunk_dimensions | test | def __get_chunk_dimensions(self):
""" Sets the chunking dimmentions depending on the file type.
"""
#Usually '.0000.' is in self.filename
if np.abs(self.header[b'foff']) < 1e-5:
logger.info('Detecting high frequency resolution data.')
chunk_dim = (1,1,1048576) #1... | python | {
"resource": ""
} |
q273579 | Waterfall.grab_data | test | def grab_data(self, f_start=None, f_stop=None,t_start=None, t_stop=None, if_id=0):
""" Extract a portion of data by frequency range.
Args:
f_start (float): start frequency in MHz
f_stop (float): stop frequency in MHz
if_id (int): IF input identification (req. when mu... | python | {
"resource": ""
} |
q273580 | cmd_tool | test | def cmd_tool(args=None):
""" Command line tool for plotting and viewing info on guppi raw files """
from argparse import ArgumentParser
parser = ArgumentParser(description="Command line utility for creating spectra from GuppiRaw files.")
parser.add_argument('filename', type=str, help='Name of file to... | python | {
"resource": ""
} |
q273581 | GuppiRaw.read_first_header | test | def read_first_header(self):
""" Read first header in file
Returns:
header (dict): keyword:value pairs of header metadata
"""
self.file_obj.seek(0)
header_dict, pos = self.read_header()
self.file_obj.seek(0)
return header_dict | python | {
"resource": ""
} |
q273582 | GuppiRaw.find_n_data_blocks | test | def find_n_data_blocks(self):
""" Seek through the file to find how many data blocks there are in the file
Returns:
n_blocks (int): number of data blocks in the file
"""
self.file_obj.seek(0)
header0, data_idx0 = self.read_header()
self.file_obj.seek(data_id... | python | {
"resource": ""
} |
q273583 | GuppiRaw.print_stats | test | def print_stats(self):
""" Compute some basic stats on the next block of data """
header, data = self.read_next_data_block()
data = data.view('float32')
print("AVG: %2.3f" % data.mean())
print("STD: %2.3f" % data.std())
print("MAX: %2.3f" % data.max())
print("MI... | python | {
"resource": ""
} |
q273584 | GuppiRaw.plot_histogram | test | def plot_histogram(self, filename=None):
""" Plot a histogram of data values """
header, data = self.read_next_data_block()
data = data.view('float32')
plt.figure("Histogram")
plt.hist(data.flatten(), 65, facecolor='#cc0000')
if filename:
plt.savefig(filename... | python | {
"resource": ""
} |
q273585 | GuppiRaw.generate_filterbank_header | test | def generate_filterbank_header(self, nchans=1, ):
""" Generate a blimpy header dictionary """
gp_head = self.read_first_header()
fb_head = {}
telescope_str = gp_head.get("TELESCOP", "unknown")
if telescope_str in ('GBT', 'GREENBANK'):
fb_head["telescope_id"] = 6
... | python | {
"resource": ""
} |
q273586 | find_header_size | test | def find_header_size(filename):
''' Script to find the header size of a filterbank file'''
# open datafile
filfile=open(filename,'rb')
# go to the start of the file
filfile.seek(0)
#read some region larger than the header.
round1 = filfile.read(1000)
headersize = round1.find('HEADER_END... | python | {
"resource": ""
} |
q273587 | cmd_tool | test | def cmd_tool(args=None):
""" Command line tool to make a md5sum comparison of two .fil files. """
if 'bl' in local_host:
header_loc = '/usr/local/sigproc/bin/header' #Current location of header command in GBT.
else:
raise IOError('Script only able to run in BL systems.')
p = OptionPars... | python | {
"resource": ""
} |
q273588 | cmd_tool | test | def cmd_tool(args=None):
""" Command line tool for converting guppi raw into HDF5 versions of guppi raw """
from argparse import ArgumentParser
if not HAS_BITSHUFFLE:
print("Error: the bitshuffle library is required to run this script.")
exit()
parser = ArgumentParser(description="Comm... | python | {
"resource": ""
} |
q273589 | foldcal | test | def foldcal(data,tsamp, diode_p=0.04,numsamps=1000,switch=False,inds=False):
'''
Returns time-averaged spectra of the ON and OFF measurements in a
calibrator measurement with flickering noise diode
Parameters
----------
data : 2D Array object (float)
2D dynamic spectrum for data (any St... | python | {
"resource": ""
} |
q273590 | integrate_calib | test | def integrate_calib(name,chan_per_coarse,fullstokes=False,**kwargs):
'''
Folds Stokes I noise diode data and integrates along coarse channels
Parameters
----------
name : str
Path to noise diode filterbank file
chan_per_coarse : int
Number of frequency bins per coarse channel
... | python | {
"resource": ""
} |
q273591 | get_calfluxes | test | def get_calfluxes(calflux,calfreq,spec_in,centerfreqs,oneflux):
'''
Given properties of the calibrator source, calculate fluxes of the source
in a particular frequency range
Parameters
----------
calflux : float
Known flux of calibrator source at a particular frequency
calfreq : flo... | python | {
"resource": ""
} |
q273592 | get_centerfreqs | test | def get_centerfreqs(freqs,chan_per_coarse):
'''
Returns central frequency of each coarse channel
Parameters
----------
freqs : 1D Array (float)
Frequency values for each bin of the spectrum
chan_per_coarse: int
Number of frequency bins per coarse channel
'''
num_coarse ... | python | {
"resource": ""
} |
q273593 | f_ratios | test | def f_ratios(calON_obs,calOFF_obs,chan_per_coarse,**kwargs):
'''
Calculate f_ON, and f_OFF as defined in van Straten et al. 2012 equations 2 and 3
Parameters
----------
calON_obs : str
Path to filterbank file (any format) for observation ON the calibrator source
calOFF_obs : str
... | python | {
"resource": ""
} |
q273594 | diode_spec | test | def diode_spec(calON_obs,calOFF_obs,calflux,calfreq,spec_in,average=True,oneflux=False,**kwargs):
'''
Calculate the coarse channel spectrum and system temperature of the noise diode in Jy given two noise diode
measurements ON and OFF the calibrator source with the same frequency and time resolution
Par... | python | {
"resource": ""
} |
q273595 | get_Tsys | test | def get_Tsys(calON_obs,calOFF_obs,calflux,calfreq,spec_in,oneflux=False,**kwargs):
'''
Returns frequency dependent system temperature given observations on and off a calibrator source
Parameters
----------
(See diode_spec())
'''
return diode_spec(calON_obs,calOFF_obs,calflux,calfreq,spec_in... | python | {
"resource": ""
} |
q273596 | calibrate_fluxes | test | def calibrate_fluxes(main_obs_name,dio_name,dspec,Tsys,fullstokes=False,**kwargs):
'''
Produce calibrated Stokes I for an observation given a noise diode
measurement on the source and a diode spectrum with the same number of
coarse channels
Parameters
----------
main_obs_name : str
... | python | {
"resource": ""
} |
q273597 | len_header | test | def len_header(filename):
""" Return the length of the blimpy header, in bytes
Args:
filename (str): name of file to open
Returns:
idx_end (int): length of header, in bytes
"""
with open(filename, 'rb') as f:
header_sub_count = 0
eoh_found = False
while not... | python | {
"resource": ""
} |
q273598 | is_filterbank | test | def is_filterbank(filename):
""" Open file and confirm if it is a filterbank file or not. """
with open(filename, 'rb') as fh:
is_fil = True
# Check this is a blimpy file
try:
keyword, value, idx = read_next_header_keyword(fh)
try:
assert keyword ... | python | {
"resource": ""
} |
q273599 | fix_header | test | def fix_header(filename, keyword, new_value):
""" Apply a quick patch-up to a Filterbank header by overwriting a header value
Args:
filename (str): name of file to open and fix. WILL BE MODIFIED.
keyword (stt): header keyword to update
new_value (long, double, angle or string): New va... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.