INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns the next occurrence of a given event relative to now. The event arg should be an iterable containing one element namely the event we d like to find the occurrence of. The reason for this is b/ c the get_count () function of CountHandler which this func makes use of expects an iterable. CHANGED: The now arg must... | def get_next_event(event, now):
"""
Returns the next occurrence of a given event, relative to 'now'.
The 'event' arg should be an iterable containing one element,
namely the event we'd like to find the occurrence of.
The reason for this is b/c the get_count() function of CountHandler,
which this... |
Returns cases with phenotype | def get_dashboard_info(adapter, institute_id=None, slice_query=None):
"""Returns cases with phenotype
If phenotypes are provided search for only those
Args:
adapter(adapter.MongoAdapter)
institute_id(str): an institute _id
slice_query(str): query to filter cases to obtain stat... |
Return general information about cases | 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... |
Return the information about case groups | 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... |
Return information about analysis types. Group cases based on analysis type for the individuals. Args: adapter ( adapter. MongoAdapter ) total_cases ( int ): Total number of cases institute_id ( str ) slice_query ( str ): Query to filter cases to obtain statistics for. Returns: analysis_types array of hashes with name:... | def get_analysis_types(adapter, total_cases, institute_id=None, slice_query=None):
""" Return information about analysis types.
Group cases based on analysis type for the individuals.
Args:
adapter(adapter.MongoAdapter)
total_cases(int): Total number of cases
institute_id(str)
... |
Returns a JSON response transforming context to make the payload. | 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
) |
Get what we want out of the context dict and convert that to a JSON object. Note that this does no object serialization b/ c we re not sending any objects. | def convert_context_to_json(self, context):
"""
Get what we want out of the context dict and convert that to a JSON
object. Note that this does no object serialization b/c we're
not sending any objects.
"""
if 'month/shift' in self.request.path: # month calendar
... |
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. | 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
... |
Check if any events are cancelled on the given date d. | 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)' |
Add a hpo object | def load_hpo_term(self, hpo_obj):
"""Add a hpo object
Arguments:
hpo_obj(dict)
"""
LOG.debug("Loading hpo term %s into database", hpo_obj['_id'])
try:
self.hpo_term_collection.insert_one(hpo_obj)
except DuplicateKeyError as err:
raise... |
Add a hpo object | def load_hpo_bulk(self, hpo_bulk):
"""Add a hpo object
Arguments:
hpo_bulk(list(scout.models.HpoTerm))
Returns:
result: pymongo bulkwrite result
"""
LOG.debug("Loading hpo bulk")
try:
result = self.hpo_term_collection.insert_many(hp... |
Fetch a hpo term | 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}) |
Return all HPO terms | 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... |
Return a disease term | 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... |
Return all disease terms that overlaps a gene | 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_... |
Load a disease term into the database | 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 ... |
Generate a sorted list with namedtuples of hpogenes | 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))
"""
... |
Command line tool for plotting and viewing info on filterbank files | def cmd_tool(args=None):
""" Command line tool for plotting and viewing info on filterbank files """
from argparse import ArgumentParser
parser = ArgumentParser(description="Command line utility for reading and plotting filterbank files.")
parser.add_argument('-p', action='store', default='ank', des... |
Populate Filterbank instance with data from HDF5 file | 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... |
Setup frequency axis | 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)
... |
Setup time axis. | 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... |
Populate Filterbank instance with data from Filterbank file | 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.
"""... |
Compute LST for observation | 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... |
Computes the LSR in km/ s | def compute_lsrk(self):
""" Computes the LSR in km/s
uses the MJD, RA and DEC of observation to compute
along with the telescope location. Requires pyslalib
"""
ra = Angle(self.header[b'src_raj'], unit='hourangle')
dec = Angle(self.header[b'src_dej'], unit='degree')
... |
Blank DC bins in coarse channels. | 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 % ... |
Print header information | 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':
... |
returns frequency array [ f_start... f_stop ] | def generate_freqs(self, f_start, f_stop):
"""
returns frequency array [f_start...f_stop]
"""
fch1 = self.header[b'fch1']
foff = self.header[b'foff']
#convert input frequencies into what their corresponding index would be
i_start = int((f_start - fch1) / foff)
... |
Setup ploting edges. | 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... |
Plot frequency spectrum of a given file | def plot_spectrum(self, t=0, f_start=None, f_stop=None, logged=False, if_id=0, c=None, **kwargs):
""" Plot frequency spectrum of a given file
Args:
t (int): integration number to plot (0 -> len(data))
logged (bool): Plot in linear (False) or dB units (True)
if_id (in... |
Plot frequency spectrum of a given file | def plot_spectrum_min_max(self, t=0, f_start=None, f_stop=None, logged=False, if_id=0, c=None, **kwargs):
""" Plot frequency spectrum of a given file
Args:
logged (bool): Plot in linear (False) or dB units (True)
if_id (int): IF identification (if multiple IF signals in file)
... |
Plot waterfall of data | 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 ... |
Plot the time series. | 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... |
Plot kurtosis | def plot_kurtosis(self, f_start=None, f_stop=None, if_id=0, **kwargs):
""" Plot kurtosis
Args:
f_start (float): start frequency, in MHz
f_stop (float): stop frequency, in MHz
kwargs: keyword args to be passed to matplotlib imshow()
"""
ax = plt.gca()... |
Plot waterfall of data as well as spectrum ; also placeholder to make even more complicated plots in the future. | def plot_all(self, t=0, f_start=None, f_stop=None, logged=False, if_id=0, kurtosis=True, **kwargs):
""" Plot waterfall of data as well as spectrum; also, placeholder to make even more complicated plots in the future.
Args:
f_start (float): start frequency, in MHz
f_stop (float):... |
Write data to blimpy file. | 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... |
Write data to HDF5 file. | def write_to_hdf5(self, filename_out, *args, **kwargs):
""" Write data to HDF5 file.
Args:
filename_out (str): Name of output file
"""
print("[Filterbank] Warning: Non-standard function to write in HDF5 (.h5) format. Please use Waterfall.")
if not HAS_HDF5:
... |
One way to calibrate the band pass is to take the median value for every frequency fine channel and divide by it. | 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 |
Output stokes parameters ( I Q U V ) for a rawspec cross polarization filterbank file | def get_stokes(cross_dat, feedtype='l'):
'''Output stokes parameters (I,Q,U,V) for a rawspec
cross polarization filterbank file'''
#Compute Stokes Parameters
if feedtype=='l':
#I = XX+YY
I = cross_dat[:,0,:]+cross_dat[:,1,:]
#Q = XX-YY
Q = cross_dat[:,0,:]-cross_dat[:,1,... |
Converts a data array with length n_chans to an array of length n_coarse_chans by averaging over the coarse channels | 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... |
Calculates phase difference between X and Y feeds given U and V ( U and Q for circular basis ) data from a noise diode measurement on the target | def phase_offsets(Idat,Qdat,Udat,Vdat,tsamp,chan_per_coarse,feedtype='l',**kwargs):
'''
Calculates phase difference between X and Y feeds given U and V (U and Q for circular basis)
data from a noise diode measurement on the target
'''
#Fold noise diode data and calculate ON OFF diferences for U and ... |
Determines relative gain error in the X and Y feeds for an observation given I and Q ( I and V for circular basis ) noise diode data. | def gain_offsets(Idat,Qdat,Udat,Vdat,tsamp,chan_per_coarse,feedtype='l',**kwargs):
'''
Determines relative gain error in the X and Y feeds for an
observation given I and Q (I and V for circular basis) noise diode data.
'''
if feedtype=='l':
#Fold noise diode data and calculate ON OFF differe... |
Returns calibrated Stokes parameters for an observation given an array of differential gains and phase differences. | 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
... |
Write Stokes - calibrated filterbank file for a given observation with a calibrator noise diode measurement on the source | 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... |
Output fractional linear and circular polarizations for a rawspec cross polarization. fil file. NOT STANDARD USE | 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 |
Writes up to 5 new filterbank files corresponding to each Stokes parameter ( and total linear polarization L ) for a given cross polarization. fil file | def write_stokefils(str, str_I, Ifil=False, Qfil=False, Ufil=False, Vfil=False, Lfil=False, **kwargs):
'''Writes up to 5 new filterbank files corresponding to each Stokes
parameter (and total linear polarization L) for a given cross polarization .fil file'''
I,Q,U,V,L=get_stokes(str, **kwargs)
obs = Wa... |
Writes two new filterbank files containing fractional linear and circular polarization data | 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 *.... |
Return the index of the closest in xarr to value val | 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 |
Rebin data by averaging bins together | 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 ... |
upgrade data from nbits to 8bits | 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... |
Promote 2 - bit unisgned data into 8 - bit unsigned data. | def unpack_2to8(data):
""" Promote 2-bit unisgned data into 8-bit unsigned data.
Args:
data: Numpy array with dtype == uint8
Notes:
DATA MUST BE LOADED as np.array() with dtype='uint8'.
This works with some clever shifting and AND / OR operations.
Data is LOADED as 8-bit, ... |
Promote 2 - bit unisgned data into 8 - bit unsigned data. | def unpack_4to8(data):
""" Promote 2-bit unisgned data into 8-bit unsigned data.
Args:
data: Numpy array with dtype == uint8
Notes:
# The process is this:
# ABCDEFGH [Bits of one 4+4-bit value]
# 00000000ABCDEFGH [astype(uint16)]
# 0000ABCDEFGH0000 [<< 4]
# ... |
Returns ON - OFF for all Stokes parameters given a cross_pols noise diode measurement | 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']
... |
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 | 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... |
Plots the corrected noise diode spectrum for a given noise diode measurement after application of the inverse Mueller matrix for the electronics chain. | 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... |
Plots the calculated phase offsets of each coarse channel along with the UV ( or QU ) noise diode spectrum for comparison | def plot_phase_offsets(dio_cross,chan_per_coarse=8,feedtype='l',ax1=None,ax2=None,legend=True,**kwargs):
'''
Plots the calculated phase offsets of each coarse channel along with
the UV (or QU) noise diode spectrum for comparison
'''
#Get ON-OFF ND spectra
Idiff,Qdiff,Udiff,Vdiff,freqs = get_diff... |
Plots the calculated gain offsets of each coarse channel along with the time averaged power spectra of the X and Y feeds | 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_... |
Plots the calculated average power and time sampling of ON ( red ) and OFF ( blue ) for a noise diode measurement over the observation time series | def plot_diode_fold(dio_cross,bothfeeds=True,feedtype='l',min_samp=-500,max_samp=7000,legend=True,**kwargs):
'''
Plots the calculated average power and time sampling of ON (red) and
OFF (blue) for a noise diode measurement over the observation time series
'''
#Get full stokes data of ND measurement
... |
Generates and shows five plots: Uncalibrated diode calibrated diode fold information phase offsets and gain offsets for a noise diode measurement. Most useful diagnostic plot to make sure calibration proceeds correctly. | def plot_fullcalib(dio_cross,feedtype='l',**kwargs):
'''
Generates and shows five plots: Uncalibrated diode, calibrated diode, fold information,
phase offsets, and gain offsets for a noise diode measurement. Most useful diagnostic plot to
make sure calibration proceeds correctly.
'''
plt.figure... |
Plots the full - band Stokes I spectrum of the noise diode ( ON - OFF ) | def plot_diodespec(ON_obs,OFF_obs,calflux,calfreq,spec_in,units='mJy',**kwargs):
'''
Plots the full-band Stokes I spectrum of the noise diode (ON-OFF)
'''
dspec = diode_spec(ON_obs,OFF_obs,calflux,calfreq,spec_in,**kwargs)
obs = Waterfall(ON_obs,max_load=150)
freqs = obs.populate_freqs()
ch... |
Read input and output frequency and output file name | def cmd_tool():
'''Read input and output frequency, and output file name
'''
parser = argparse.ArgumentParser(description='Dices hdf5 or fil files and writes to hdf5 or fil.')
parser.add_argument('-f', '--input_filename', action='store', default=None, dest='in_fname', type=str, help='Name of file ... |
Command line utility for creating HDF5 blimpy files. | def cmd_tool(args=None):
""" Command line utility for creating HDF5 blimpy files. """
from argparse import ArgumentParser
parser = ArgumentParser(description="Command line utility for creating HDF5 Filterbank files.")
parser.add_argument('dirname', type=str, help='Name of directory to read')
args = ... |
Open a HDF5 or filterbank file | 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
=======... |
Making sure the selection if time and frequency are within the file limits. | 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... |
Calculating dtype | def _setup_dtype(self):
"""Calculating dtype
"""
#Set up the data type
if self._n_bytes == 4:
return b'float32'
elif self._n_bytes == 2:
return b'uint16'
elif self._n_bytes == 1:
return b'uint8'
else:
logger.warn... |
Calculate size of data of interest. | 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... |
Calculate shape of data of interest. | 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[... |
Setup channel borders | 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... |
Updating frequency borders from channel values | 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:
... |
Populate time axis. IF update_header then only return tstart | 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
... |
Populate frequency axis | 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)
... |
This makes an attempt to calculate the number of coarse channels in a given file. | 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.
"""
... |
Given the blob dimensions calculate how many fit in the data selection. | 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 |
Check if the current selection is too large. | 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 |
Read header and return a Python dictionary of key: value pairs | def read_header(self):
""" Read header and return a Python dictionary of key:value pairs
"""
self.header = {}
for key, val in self.h5['data'].attrs.items():
if six.PY3:
key = bytes(key, 'ascii')
if key == b'src_raj':
self.header[k... |
Find first blob from selection. | def _find_blob_start(self, blob_dim, n_blob):
"""Find first blob from selection.
"""
#Convert input frequencies into what their corresponding channel number would be.
self._setup_chans()
#Check which is the blob time offset
blob_time_start = self.t_start + blob_dim[self... |
Read data | 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 ... |
Read blob from a selection. | def read_blob(self,blob_dim,n_blob=0):
"""Read blob from a selection.
"""
n_blobs = self.calc_n_blobs(blob_dim)
if n_blob > n_blobs or n_blob < 0:
raise ValueError('Please provide correct n_blob value. Given %i, but max values is %i'%(n_blob,n_blobs))
#This prevents... |
Read blimpy header and return a Python dictionary of key: value pairs | def read_header(self, return_idxs=False):
""" Read blimpy header and return a Python dictionary of key:value pairs
Args:
filename (str): name of file to open
Optional args:
return_idxs (bool): Default False. If true, returns the file offset indexes
... |
Read data. | 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... |
Find first blob from selection. | def _find_blob_start(self):
"""Find first blob from selection.
"""
# Convert input frequencies into what their corresponding channel number would be.
self._setup_chans()
# Check which is the blob time offset
blob_time_start = self.t_start
# Check which is the b... |
Read blob from a selection. | def read_blob(self,blob_dim,n_blob=0):
"""Read blob from a selection.
"""
n_blobs = self.calc_n_blobs(blob_dim)
if n_blob > n_blobs or n_blob < 0:
raise ValueError('Please provide correct n_blob value. Given %i, but max values is %i'%(n_blob,n_blobs))
# This prevent... |
read all the data. If reverse = True the x axis is flipped. | 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... |
Read a block of data. The number of samples per row is set in self. channels If reverse = True the x axis is flipped. | 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... |
Command line tool for plotting and viewing info on blimpy files | def cmd_tool(args=None):
""" Command line tool for plotting and viewing info on blimpy files """
from argparse import ArgumentParser
parser = ArgumentParser(description="Command line utility for reading and plotting blimpy files.")
parser.add_argument('filename', type=str,
hel... |
Reads data selection if small enough. | 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() |
Updates the header information from the original file to the selection. | 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... |
Print header information and other derived information. | 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... |
Write data to. fil file. It check the file size then decides how to write the file. | 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... |
Write data to. fil file. | def __write_to_fil_heavy(self, filename_out, *args, **kwargs):
""" Write data to .fil file.
Args:
filename_out (str): Name of output file
"""
#Note that a chunk is not a blob!!
chunk_dim = self.__get_chunk_dimensions()
blob_dim = self.__get_blob_dimensions(c... |
Write data to. fil file. | def __write_to_fil_light(self, filename_out, *args, **kwargs):
""" Write data to .fil file.
Args:
filename_out (str): Name of output file
"""
n_bytes = self.header[b'nbits'] / 8
with open(filename_out, "wb") as fileh:
fileh.write(generate_sigproc_header... |
Write data to HDF5 file. It check the file size then decides how to write the file. | 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... |
Write data to HDF5 file. | def __write_to_hdf5_heavy(self, filename_out, *args, **kwargs):
""" Write data to HDF5 file.
Args:
filename_out (str): Name of output file
"""
block_size = 0
#Note that a chunk is not a blob!!
chunk_dim = self.__get_chunk_dimensions()
blob_dim = sel... |
Write data to HDF5 file in one go. | 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'
... |
Sets the blob dimmentions trying to read around 1024 MiB at a time. This is assuming a chunk is about 1 MiB. | 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... |
Sets the chunking dimmentions depending on the file type. | 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... |
Extract a portion of data by frequency range. | 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... |
Command line tool for plotting and viewing info on guppi raw files | 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... |
Read next header ( multiple headers in file ) | def read_header(self):
""" Read next header (multiple headers in file)
Returns:
(header, data_idx) - a dictionary of keyword:value header data and
also the byte index of where the corresponding data block resides.
"""
start_idx = self.file_obj.tell()
key,... |
Read first header in file | 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 |
returns a generator object that reads data a block at a time ; the generator prints File depleted and returns nothing when all data in the file has been read.: return: | def get_data(self):
"""
returns a generator object that reads data a block at a time;
the generator prints "File depleted" and returns nothing when all data in the file has been read.
:return:
"""
with self as gr:
while True:
try:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.