_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
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 ensembl formated genes
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: ensembl_gene(dict): A dictionary with the relevant information """ header = [] LOG.debug("Parsing ensembl exons...") for index, line in enumerate(lines): # File allways start with a header line if index == 0: header = line.rstrip().split('\t') continue exon_info = parse_ensembl_line(line, header) chrom = exon_info['chrom'] start = exon_info['exon_start'] end = exon_info['exon_end'] transcript = exon_info['ensembl_transcript_id'] gene = exon_info['ensembl_gene_id'] rank = exon_info['exon_rank'] strand = exon_info['strand'] # Recalculate start and stop (taking UTR regions into account for end exons) if strand == 1: # highest position: start of exon or end of 5' UTR # If no 5' UTR make sure exon_start is allways choosen start = max(start, exon_info.get('utr_5_end') or -1) # lowest
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', '5_utr_start', '5_utr_end', '3_utr_start', '3_utr_end', 'strand', 'rank' ] # for res in result.itertuples(): for res in zip(result['Chromosome/scaffold name'], result['Gene stable ID'], result['Transcript stable ID'], result['Exon stable ID'], result['Exon region start (bp)'], result['Exon region end (bp)'], result["5' UTR start"], result["5' UTR end"], result["3' UTR start"], result["3' UTR end"], result["Strand"], result["Exon rank in transcript"]): ensembl_info = dict(zip(keys, res)) # Recalculate start and stop (taking UTR regions into account for end exons)
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 = '[%(asctime)s] %(levelname)-8s: %(name)-25s: %(message)s' formatter = logging.Formatter(template) if loglevel: logger.setLevel(getattr(logging, loglevel)) # We will always print warnings and higher to stderr console = logging.StreamHandler() console.setLevel('WARNING') console.setFormatter(formatter) if filename: file_handler = logging.FileHandler(filename, encoding='utf-8') if loglevel:
python
{ "resource": "" }
q273504
parse_omim_line
test
def parse_omim_line(line, header): """docstring for parse_omim_2_line"""
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:
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 dictionaries with phenotype information as values. { 'description': str, # Description of the phenotype 'hgnc_symbols': set(), # Associated hgnc symbols 'inheritance': set(), # Associated phenotypes 'mim_number': int, # mim number of phenotype } """ # Set with all omim numbers that are phenotypes # Parsed
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 print("Morbid file: %s" % morbid) print("Genemap file: %s" % genemap) print("mim2gene file: %s" % mim2gene) print("MimTitles file: %s" % mim_titles) if morbid: morbid_handle = get_file_handle(morbid) if genemap: genemap_handle = get_file_handle(genemap) if mim2gene: mim2gene_handle = get_file_handle(mim2gene) if mim_titles: mimtitles_handle = get_file_handle(mim_titles) mim_genes = get_mim_genes(genemap_handle, mim2gene_handle) for entry in mim_genes: if entry == 'C10orf11': pp(mim_genes[entry]) context.abort() if phenotypes: if not genemap: click.echo("Please provide the genemap file") context.abort() phenotypes = get_mim_phenotypes(genemap_handle) for i,mim_term in enumerate(phenotypes):
python
{ "resource": "" }
q273508
convert_number
test
def convert_number(string): """Convert a string to number If int convert to int otherwise float If not
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'] = [] for week in self.monthdays2calendar(theyear, themonth): week_row = [] for day, weekday in week: week_row.append(self.formatday(day, weekday)) context['week_rows'].append(week_row)
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.cssclasses[weekday]) ) if URLS_NAMESPACE: url_name = '%s:day_list' % (URLS_NAMESPACE) else:
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:
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> ' + display_month + ' ' + str(self.day) + ', ' + self.event.l_start_date.strftime( LEGACY_CALENDAR_TIME_FORMAT).lstrip('0') + ' - ' + self.event.l_end_date.strftime(LEGACY_CALENDAR_TIME_FORMAT).lstrip('0') + '</p>') if self.event.location.exists(): # where self.where = '<p><b>Where:</b> ' for l in self.event.location.all(): self.where += l.name self.where += '</p>' else: self.where = '' # description
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 header. Args: panel_lines(iterable(str)) Returns: panel_info(dict): Dictionary with panel information """ panel_info = { 'panel_id': panel_id, 'institute': institute, 'version': version, 'date': date, 'display_name': display_name, }
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': str, 'disease_associated_transcripts': list(str), 'inheritance_models': list(str), 'mosaicism': bool, 'reduced_penetrance': bool, 'database_entry_version': str, } """ gene = {} # This is either hgnc id or hgnc symbol identifier = None hgnc_id = None try: if 'hgnc_id' in gene_info: hgnc_id = int(gene_info['hgnc_id']) elif 'hgnc_idnumber' in gene_info: hgnc_id = int(gene_info['hgnc_idnumber']) elif 'hgncid' in gene_info: hgnc_id = int(gene_info['hgncid']) except ValueError as e: raise SyntaxError("Invalid hgnc id: {0}".format(hgnc_id)) gene['hgnc_id'] = hgnc_id identifier = hgnc_id hgnc_symbol = None if 'hgnc_symbol' in gene_info: hgnc_symbol = gene_info['hgnc_symbol'] elif 'hgncsymbol' in gene_info: hgnc_symbol = gene_info['hgncsymbol'] elif 'symbol' in gene_info: hgnc_symbol = gene_info['symbol'] gene['hgnc_symbol'] = hgnc_symbol if not identifier: if hgnc_symbol: identifier = hgnc_symbol else: raise SyntaxError("No gene identifier could be found") gene['identifier'] = identifier # Disease associated transcripts is a ','-separated list of # manually curated transcripts transcripts = "" if 'disease_associated_transcripts' in gene_info: transcripts = gene_info['disease_associated_transcripts'] elif 'disease_associated_transcript' in gene_info: transcripts = gene_info['disease_associated_transcript']
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' # This can be '\t' or ';' delimiters = ['\t', ' ', ';'] # There are files that have '#' to indicate headers # There are some files that start with a header line without # any special symbol for i,line in enumerate(gene_lines): line = line.rstrip() if not len(line) > 0: continue if line.startswith('#'): if not line.startswith('##'): # We need to try delimiters # We prefer ';' or '\t' byt should accept ' ' line_length = 0 delimiter = None for alt in delimiters: head_line = line.split(alt) if len(head_line) > line_length: line_length = len(head_line) delimiter = alt header = [word.lower() for word in line[1:].split(delimiter)] else: # If no header symbol(#) assume first line is header if i == 0: line_length = 0 for alt in delimiters: head_line = line.split(alt) if len(head_line) > line_length: line_length = len(head_line) delimiter = alt if ('hgnc' in line or 'HGNC' in line): header = [word.lower() for word in line.split(delimiter)] continue
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 of institute that owns the panel panel_id(str): Panel id date(datetime.datetime): Date of creation version(float) full_name(str): Option to have a long name Returns: gene_panel(dict) """ LOG.info("Parsing gene panel %s", panel_id) gene_panel = {} gene_panel['path'] = path
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.echo("Disease")
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")
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 in user_obj.get('institutes')] else: user_obj['institutes'] = []
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( variant, 'dbNSFP_GERP___RS' ) conservations['phast'] = parse_conservation( variant,
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)
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) """ general = {} # Potentially sensitive slice queries are assumed allowed if we have got this far name_query = slice_query cases = adapter.cases(owner=institute_id, name_query=name_query) phenotype_cases = 0 causative_cases = 0 pinned_cases = 0 cohort_cases = 0 pedigree = { 1: { 'title': 'Single', 'count': 0 }, 2: { 'title': 'Duo', 'count': 0 }, 3: { 'title': 'Trio', 'count': 0 }, 'many': { 'title': 'Many', 'count': 0 }, } case_ids = set() total_cases = 0 for total_cases,case in enumerate(cases,1): # If only looking at one institute we need to save the case ids if institute_id:
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: cases(dict): """ # Create a group with all cases in the database cases = [{'status': 'all', 'count': total_cases, 'percent': 1}] # Group the cases based on their status pipeline = [] group = {'$group' : {'_id': '$status', 'count': {'$sum': 1}}} subquery = {} if institute_id and slice_query: subquery = adapter.cases(owner=institute_id, name_query=slice_query, yield_query=True) elif institute_id:
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
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 month = now.month + net month_orig = None if 'cal_ignore=true' not in qs: if 'year' and 'month' in self.kwargs: # try kwargs year, month_orig = map( int, (self.kwargs['year'], self.kwargs['month']) ) month = month_orig + net else: try: # try querystring year = int(self.request.GET['cal_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:
python
{ "resource": "" }
q273527
HpoHandler.hpo_term
test
def hpo_term(self, hpo_id): """Fetch a hpo term Args: hpo_id(str) Returns:
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 specific hpo term limit(int): the number of desired results Returns: result(pymongo.Cursor): A cursor with hpo terms """ query_dict = {} search_term = None if query: query_dict = {'$or': [ {'hpo_id': {'$regex': query, '$options':'i'}}, {'description': {'$regex': query, '$options':'i'}}, ] } search_term = query elif text: new_string = '' for i,word in enumerate(text.split(' ')): if i == 0:
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:
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 = {}
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'])
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)) """ genes = {}
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("Warning: this function will be deprecated in the future. Please use Waterfall to open HDF5 files.") # raise DeprecationWarning('Please use Waterfall to open HDF5 files.') self.header = {} self.filename = filename self.h5 = h5py.File(filename) for key, val in self.h5[b'data'].attrs.items(): if six.PY3: key = bytes(key, 'ascii') if key == b'src_raj': self.header[key] = Angle(val, unit='hr') elif key == b'src_dej': self.header[key] = Angle(val, unit='deg') else: self.header[key] = val self.n_ints_in_file = self.h5[b"data"].shape[0] i_start, i_stop, chan_start_idx, chan_stop_idx = self._setup_freqs(f_start=f_start,
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) if f_stop: i_stop = int((f_stop - f0) / f_delt) #calculate closest true index value chan_start_idx = np.int(i_start) chan_stop_idx = np.int(i_stop) #create freq array if i_start < i_stop: i_vals = np.arange(chan_start_idx, chan_stop_idx)
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_stop - ii_start ## Setup time axis t0
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. """ if filename is None: filename = self.filename else: self.filename = filename self.header = read_header(filename) #convert input frequencies into what their corresponding index would be i_start, i_stop, chan_start_idx, chan_stop_idx = self._setup_freqs(f_start=f_start, f_stop=f_stop) n_bits = self.header[b'nbits'] n_bytes = int(self.header[b'nbits'] / 8) n_chans = self.header[b'nchans'] n_chans_selected = self.freqs.shape[0] n_ifs = self.header[b'nifs'] # Load binary data self.idx_data = len_header(filename) f = open(filename, 'rb') f.seek(self.idx_data) filesize = os.path.getsize(self.filename) n_bytes_data = filesize - self.idx_data # Finally add some other info to the class as objects self.n_ints_in_file = calc_n_ints_in_file(self.filename) self.file_size_bytes = filesize ## Setup time axis ii_start, ii_stop, n_ints = self._setup_time_axis(t_start=t_start, t_stop=t_stop) # Seek to first integration f.seek(int(ii_start * n_bits * n_ifs * n_chans / 8), 1) # Set up indexes used in file read (taken out of loop for speed) i0 = np.min((chan_start_idx, chan_stop_idx)) i1 = np.max((chan_start_idx, chan_stop_idx)) #Set up the data type (taken out of loop for speed) if n_bits == 2: dd_type = b'uint8' n_chans_selected = int(n_chans_selected/4) elif n_bytes == 4: dd_type = b'float32' elif n_bytes == 2: dd_type = b'uint16' elif n_bytes == 1: dd_type = b'uint8' if load_data: if n_ints * n_ifs * n_chans_selected > MAX_DATA_ARRAY_SIZE: print("[Filterbank] Error: data array is too large to load. Either select fewer points or manually increase MAX_DATA_ARRAY_SIZE. Large files are
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 supported") if HAS_SLALIB: # dut1 = (0.2 /3600.0) * np.pi/12.0 dut1 = 0.0 mjd = self.header[b'tstart'] tellong
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 % int(n_coarse_chan) == 0: logger.warning('Selection does not contain an interger number of coarse channels, unable to blank DC bin.') return None n_coarse_chan = int(n_coarse_chan) n_chan = self.data.shape[-1]
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': val *= u.second if key in ('foff', 'fch1'): val *= u.MHz if key == b'tstart': print("%16s : %32s" % ("tstart (ISOT)", Time(val, format='mjd').isot))
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.timestamps[0]) if MJD_time:
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 units (True), cb (bool): for plotting the colorbar kwargs: keyword args to be passed to matplotlib imshow() """ plot_f, plot_data = self.grab_data(f_start, f_stop, if_id) #Using accending frequency for all plots. if self.header[b'foff'] < 0: plot_data = plot_data[..., ::-1] # Reverse data plot_f = plot_f[::-1] if logged: plot_data = db(plot_data) # Make sure waterfall plot is under 4k*4k dec_fac_x, dec_fac_y = 1, 1 if plot_data.shape[0] > MAX_IMSHOW_POINTS[0]: dec_fac_x = int(plot_data.shape[0] / MAX_IMSHOW_POINTS[0]) if plot_data.shape[1] > MAX_IMSHOW_POINTS[1]: dec_fac_y = int(plot_data.shape[1] / MAX_IMSHOW_POINTS[1]) plot_data = rebin(plot_data, dec_fac_x, dec_fac_y) try: plt.title(self.header[b'source_name'])
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 (False) or dB units (True), kwargs: keyword args to be passed to matplotlib imshow() """ ax = plt.gca() plot_f, plot_data = self.grab_data(f_start, f_stop, if_id) if logged and self.header[b'nbits'] >= 8: plot_data = db(plot_data) #Since the data has been squeezed, the axis for time goes away if only one bin, causing a bug
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[b'nbits'] / 8) with open(filename_out, "wb") as fileh: fileh.write(generate_sigproc_header(self)) j = self.data if n_bytes == 4:
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
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
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 ax0 = I.shape[0] ax1 = I.shape[1] nchans = I.shape[2] ncoarse = nchans/chan_per_coarse #Reshape data arrays to separate coarse channels I = np.reshape(I,(ax0,ax1,ncoarse,chan_per_coarse)) Q = np.reshape(Q,(ax0,ax1,ncoarse,chan_per_coarse)) U = np.reshape(U,(ax0,ax1,ncoarse,chan_per_coarse)) V = np.reshape(V,(ax0,ax1,ncoarse,chan_per_coarse)) #Swap axes 2 and 3 to in order for broadcasting to work correctly I = np.swapaxes(I,2,3) Q = np.swapaxes(Q,2,3) U = np.swapaxes(U,2,3) V = np.swapaxes(V,2,3) #Apply top left corner of electronics chain inverse Mueller matrix a = 1/(1-gain_offsets**2) if feedtype=='l': Icorr = a*(I-gain_offsets*Q) Qcorr = a*(-1*gain_offsets*I+Q) I = None Q = None if feedtype=='c': Icorr = a*(I-gain_offsets*V) Vcorr = a*(-1*gain_offsets*I+V) I = None V = None #Apply bottom right corner
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 filterbank file (rawspec output) for observation to be calibrated diode_cross : string Path to cross polarization filterbank file of noise diode measurement ON the target obsI : string Path to Stokes I filterbank file of main observation (only needed if onefile=False) onefile : boolean True writes all calibrated Stokes parameters to a single filterbank file, False writes four separate files feedtype : 'l' or 'c' Basis of antenna dipoles. 'c' for circular, 'l' for linear ''' #Obtain time sample length, frequencies, and noise diode data obs = Waterfall(diode_cross,max_load=150) cross_dat = obs.data tsamp = obs.header['tsamp'] #Calculate number of coarse channels in the noise diode measurement (usually 8) dio_ncoarse = obs.calc_n_coarse_chan() dio_nchans = obs.header['nchans'] dio_chan_per_coarse = dio_nchans/dio_ncoarse obs = None Idat,Qdat,Udat,Vdat = get_stokes(cross_dat,feedtype) cross_dat = None #Calculate differential gain and phase from noise diode measurements print('Calculating Mueller Matrix variables') gams = gain_offsets(Idat,Qdat,Udat,Vdat,tsamp,dio_chan_per_coarse,feedtype,**kwargs) psis = phase_offsets(Idat,Qdat,Udat,Vdat,tsamp,dio_chan_per_coarse,feedtype,**kwargs) #Clear data arrays to save memory Idat = None Qdat = None Udat = None Vdat = None #Get corrected Stokes parameters print('Opening '+cross_pols) cross_obs = Waterfall(cross_pols,max_load=150) obs_ncoarse = cross_obs.calc_n_coarse_chan() obs_nchans = cross_obs.header['nchans'] obs_chan_per_coarse = obs_nchans/obs_ncoarse print('Grabbing Stokes parameters') I,Q,U,V = get_stokes(cross_obs.data,feedtype) print('Applying Mueller Matrix') I,Q,U,V = apply_Mueller(I,Q,U,V,gams,psis,obs_chan_per_coarse,feedtype) #Use onefile (default) to produce one filterbank file containing all Stokes information
python
{ "resource": "" }
q273548
fracpols
test
def fracpols(str, **kwargs): '''Output fractional linear and circular polarizations for a rawspec cross polarization
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
python
{ "resource": "" }
q273550
closest
test
def closest(xarr, val): """ Return the index of the closest in xarr to value val """ 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 n_y is None: n_y = 1 if n_x is None: n_x = 1 d = d[:int(d.shape[0] // n_x) * n_x, :int(d.shape[1] // n_y) * n_y] d = d.reshape((d.shape[0]
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, np.int8): raise TypeError("unpack: dtype must be 8-bit") if nbit ==
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'] data = obs.data obs = None I,Q,U,V = get_stokes(data,feedtype) #Fold noise diode data I_OFF,I_ON
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,Qdiff,Udiff,Vdiff,freqs = get_diff(dio_cross,feedtype,**kwargs) else: obs = Waterfall(dio_cross,max_load=150) freqs = obs.populate_freqs() tsamp = obs.header['tsamp'] data = obs.data I,Q,U,V = get_stokes(data,feedtype) I_OFF,I_ON = foldcal(I,tsamp,**kwargs) Q_OFF,Q_ON = foldcal(Q,tsamp,**kwargs) U_OFF,U_ON = foldcal(U,tsamp,**kwargs) V_OFF,V_ON = foldcal(V,tsamp,**kwargs) #Plot spectra if diff==True: plt.plot(freqs,Idiff,'k-',label='I') plt.plot(freqs,Qdiff,'r-',label='Q') plt.plot(freqs,Udiff,'g-',label='U')
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 = Waterfall(dio_cross,max_load=150) freqs = obs.populate_freqs() tsamp = obs.header['tsamp'] data = obs.data obs = None I,Q,U,V = get_stokes(data,feedtype) data = None #Calculate Mueller Matrix variables for each coarse channel psis = phase_offsets(I,Q,U,V,tsamp,chan_per_coarse,feedtype,**kwargs)
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_diff(dio_cross,feedtype,**kwargs) obs = Waterfall(dio_cross,max_load=150) tsamp = obs.header['tsamp'] data = obs.data obs = None I,Q,U,V = get_stokes(data,feedtype) #Get phase offsets and convert to degrees coarse_G = gain_offsets(I,Q,U,V,tsamp,dio_chan_per_coarse,feedtype,**kwargs) coarse_freqs = convert_to_coarse(freqs,dio_chan_per_coarse) #Get X and Y spectra for the noise diode ON and OFF #If using circular feeds these correspond to LL and RR XX_OFF,XX_ON = foldcal(np.expand_dims(data[:,0,:],axis=1),tsamp,**kwargs) YY_OFF,YY_ON = foldcal(np.expand_dims(data[:,1,:],axis=1),tsamp,**kwargs) if ax1==None: plt.subplot(211) else: axG = plt.axes(ax1)
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 ================== ================================================== h5, hdf5 HDF5 format fil fil format *other* Will raise NotImplementedError ================== ================================================== """ if not os.path.isfile(filename): type(filename) print(filename) raise IOError("No such file or directory: " + filename) filename = os.path.expandvars(os.path.expanduser(filename)) # Get file extension to determine type ext = filename.split(".")[-1].strip().lower()
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 is True: if t_start is None: t_start = self.t_begin if t_stop is None: t_stop = self.t_end if f_start is None: f_start = self.f_begin if f_stop is None: f_stop = self.f_end else: if f_start is None: f_start = self.f_start if f_stop is None: f_stop = self.f_stop if t_start is None: t_start = self.t_start if t_stop is None: t_stop = self.t_stop # By now, all values start/stop are populated. if t_stop >= 0 and t_start >= 0 and t_stop < t_start: t_stop, t_start = t_start,t_stop logger.warning('Given t_stop < t_start,
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
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
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.header[b'foff'])
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 if self.t_stop: ii_stop = self.t_stop ## Setup time axis t0 = self.header[b'tstart'] t_delt
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
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. """ nchans = int(self.header[b'nchans']) # Do we have a file with enough channels that it has coarse channelization? if chan_bw is not None: bandwidth = abs(self.f_stop - self.f_start) n_coarse_chan = int(bandwidth / chan_bw) return n_coarse_chan elif nchans >= 2**20: # Does the common FFT length of 2^20 divide through without a remainder? # This should work for most GBT and all Parkes hires data if nchans % 2**20 == 0: n_coarse_chan = nchans // 2**20 return n_coarse_chan # Early GBT data has non-2^N FFT length, check if it is GBT data elif self.header[b'telescope_id'] == 6: coarse_chan_bw =
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. """
python
{ "resource": "" }
q273567
Reader.isheavy
test
def isheavy(self): """ Check if the current selection is too large. """ selection_size_bytes = self._calc_selection_size()
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 size of %.2f GB, exceeding our size limit %.2f GB. Instance created, " "header loaded, but data not loaded, please try another (t,v) selection." % (self._calc_selection_size() / (1024. ** 3), self.MAX_DATA_ARRAY_SIZE / (1024. ** 3))) self.data = np.array([0],dtype=self._d_type) return None #Convert input frequencies into what their corresponding channel number would be. self._setup_chans() #Update frequencies ranges from channel number. self._setup_freqs() n_chans = self.header[b'nchans'] n_chans_selected = self.selection_shape[self.freq_axis] n_ifs = self.header[b'nifs'] # Load binary data f = open(self.filename, 'rb') f.seek(int(self.idx_data)) # now check to see how many integrations requested n_ints = self.t_stop - self.t_start # Seek to first integration
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 #
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.datastart+self.channels*rownumber*(int(self.nbits/8)))) # read data
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. """
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'fch1'] = self.container.f_start #Updating
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 = val.to_string(unit=u.deg, sep=':') print("%16s : %32s" % (key, val)) print("\n%16s : %32s" % ("Num ints in file",
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
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
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' h5.attrs[b'VERSION'] = b'1.0' if HAS_BITSHUFFLE: bs_compression = bitshuffle.h5.H5FILTER bs_compression_opts = (block_size, bitshuffle.h5.H5_COMPRESS_LZ4) else: bs_compression = None bs_compression_opts = None logger.warning("Warning: bitshuffle not found. No compression applied.") dset = h5.create_dataset('data', data=self.data, # compression='lzf') compression=bs_compression, compression_opts=bs_compression_opts) dset_mask = h5.create_dataset('mask',
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.selection_shape[self.freq_axis] > chunk_dim[self.freq_axis]*MAX_BLOB_MB: freq_axis_size = self.selection_shape[self.freq_axis] # while freq_axis_size > chunk_dim[self.freq_axis]*MAX_BLOB_MB: # freq_axis_size /= 2 time_axis_size = 1
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) #1048576 is the number of channels in a coarse channel. return chunk_dim #Usually '.0001.' is in self.filename elif np.abs(self.header[b'tsamp']) < 1e-3: logger.info('Detecting high time resolution data.') chunk_dim = (2048,1,512) #512 is the total number of channels per single band (ie. blc00) return chunk_dim #Usually '.0002.' is in self.filename
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 multiple IFs in file) Returns: (freqs, data) (np.arrays): frequency axis in MHz and data subset """ self.freqs = self.populate_freqs() self.timestamps = self.populate_timestamps() if f_start is None: f_start = self.freqs[0] if f_stop is None:
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 read') parser.add_argument('-o', dest='outdir', type=str, default='./', help='output directory for PNG files') args = parser.parse_args() r = GuppiRaw(args.filename)
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 """
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_idx0) block_size = int(header0['BLOCSIZE']) n_bits = int(header0['NBITS']) self.file_obj.seek(int(header0['BLOCSIZE']), 1) n_blocks = 1 end_found = False while not end_found: try:
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())
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')
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 elif telescope_str in ('PKS', 'PARKES'): fb_head["telescop_id"] = 7 else: fb_head["telescop_id"] = 0 # Using .get() method allows us to fill in default values if not present fb_head["source_name"] = gp_head.get("SRC_NAME", "unknown") fb_head["az_start"] = gp_head.get("AZ", 0) fb_head["za_start"] = gp_head.get("ZA", 0) fb_head["src_raj"] = Angle(str(gp_head.get("RA", 0.0)) + "hr") fb_head["src_dej"] = Angle(str(gp_head.get("DEC", 0.0)) + "deg") fb_head["rawdatafile"] = self.filename
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')
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 = OptionParser() p.set_usage('matchfils <FIL_FILE1> <FIL_FILE2>') opts, args = p.parse_args(sys.argv[1:]) file1 = args[0] file2 = args[1] #------------------------------------ #Create batch script make_batch_script() #------------------------------------ #First checksum headersize1 = find_header_size(file1) file_size1 = os.path.getsize(file1) #Strip header from file, and calculate the md5sum of the rest. #command=['tail','-c',str(file_size1-headersize1),file1,'|','md5sum'] command=['./tail_sum.sh',file1,str(file_size1-headersize1)] print('[matchfils] '+' '.join(command)) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = proc.communicate() check_sum1 = out.split()[0] print('[matchfils] Checksum is:', check_sum1) if err: raise Error('There is an error.') #--- out,err = reset_outs() command=[header_loc,file1] print('[matchfils] Header information:') proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = proc.communicate() header1 = out print(header1) #------------------------------------ #Second checksum out,err = reset_outs() headersize2 = find_header_size(file2) file_size2 = os.path.getsize(file2) #Strip header from file, and calculate the md5sum of the rest. command=['./tail_sum.sh',file2,str(file_size2-headersize2)]
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="Command line utility for creating HDF5 Raw files.") parser.add_argument('filename', type=str, help='Name of filename to read') args = parser.parse_args() fileroot = args.filename.split('.0000.raw')[0] filelist = glob.glob(fileroot + '*.raw') filelist = sorted(filelist) # Read first file r = GuppiRaw(filelist[0]) header, data = r.read_next_data_block() dshape = data.shape #r.read_next_data_block_shape() print(dshape) n_blocks_total = 0 for filename in filelist: print(filename) r = GuppiRaw(filename) n_blocks_total += r.n_blocks print(n_blocks_total) full_dshape = np.concatenate(((n_blocks_total,), dshape)) # Create h5py file h5 = h5py.File(fileroot + '.h5', 'w') h5.attrs['CLASS'] = 'GUPPIRAW' block_size = 0 # This is chunk block size dset = h5.create_dataset('data', shape=full_dshape, #compression=bitshuffle.h5.H5FILTER, #compression_opts=(block_size, bitshuffle.h5.H5_COMPRESS_LZ4), dtype=data.dtype) h5_idx = 0
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 Stokes parameter) with flickering noise diode. tsamp : float Sampling time of data in seconds diode_p : float Period of the flickering noise diode in seconds numsamps : int Number of samples over which to average noise diode ON and OFF switch : boolean Use switch=True if the noise diode "skips" turning from OFF to ON once or vice versa inds : boolean Use inds=True to also return the indexes of the time series where the ND is ON and OFF ''' halfper = diode_p/2.0 foldt = halfper/tsamp #number of time samples per diode switch onesec = 1/tsamp #number of time samples in the first second #Find diode switches in units of time samples and round down to the nearest int ints = np.arange(0,numsamps) t_switch = (onesec+ints*foldt) t_switch = t_switch.astype('int') ONints = np.array(np.reshape(t_switch[:],(numsamps/2,2))) ONints[:,0] = ONints[:,0]+1 #Find index ranges of ON time samples OFFints = np.array(np.reshape(t_switch[1:-1],(numsamps/2-1,2))) OFFints[:,0] = OFFints[:,0]+1 #Find index ranges of OFF time samples av_ON = [] av_OFF = [] #Average ON and OFF spectra separately with respect to time for i in ONints: if i[1]!=i[0]:
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 fullstokes : boolean Use fullstokes=True if data is in IQUV format or just Stokes I, use fullstokes=False if it is in cross_pols format ''' #Load data obs = Waterfall(name,max_load=150) data = obs.data #If the data has cross_pols format calculate Stokes I if fullstokes==False and data.shape[1]>1: data = data[:,0,:]+data[:,1,:] data = np.expand_dims(data,axis=1) #If the data has IQUV format get Stokes I if fullstokes==True: data = data[:,0,:]
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 : float Frequency where calibrator source has flux calflux (see above) spec_in : float
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 '''
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 Path to filterbank file (any format) for observation OFF the calibrator source '''
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 Parameters ---------- calON_obs : str (see f_ratios() above) calOFF_obs : str (see f_ratios() above) calflux : float Known flux of calibrator source at a particular frequency calfreq : float Frequency where calibrator source has flux calflux (see above) spec_in : float Known power-law spectral index of calibrator source. Use convention flux(frequency) = constant * frequency^(spec_in) average : boolean Use average=True to return noise diode and Tsys spectra averaged over frequencies ''' #Load frequencies and calculate number of channels per coarse channel obs = Waterfall(calON_obs,max_load=150) freqs = obs.populate_freqs()
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 ----------
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 Path to filterbank file containing final data to be calibrated dio_name : str Path to filterbank file for observation on the target source with flickering noise diode dspec : 1D Array (float) or float Coarse channel spectrum (or average) of the noise diode in Jy (obtained from diode_spec()) Tsys : 1D Array (float) or float Coarse channel spectrum (or average) of the system temperature in Jy fullstokes: boolean Use fullstokes=True if data is in IQUV format or just Stokes I, use fullstokes=False if it is in cross_pols format ''' #Find folded spectra of the target source with the noise diode ON and OFF main_obs = Waterfall(main_obs_name,max_load=150) ncoarse = main_obs.calc_n_coarse_chan() dio_obs = Waterfall(dio_name,max_load=150) dio_chan_per_coarse = dio_obs.header['nchans']/ncoarse dOFF,dON = integrate_calib(dio_name,dio_chan_per_coarse,fullstokes,**kwargs) #Find Jy/count for each coarse channel using the
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 eoh_found: header_sub = f.read(512) header_sub_count += 1 if b'HEADER_END' in header_sub:
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)
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 value to write. Notes: This will overwrite the current value of the blimpy with a desired 'fixed' version. Note that this has limited support for patching string-type values - if the length of the string changes, all hell will break loose. """ # Read header data and return indexes of data offsets in file hd = read_header(filename) hi = read_header(filename, return_idxs=True) idx = hi[keyword] # Find out the datatype for the given keyword dtype = header_keyword_types[keyword] dtype_to_type = {b'<l' : np.int32, b'str' : bytes, b'<d' : np.float64, b'angle' : to_sigproc_angle} value_dtype = dtype_to_type[dtype]
python
{ "resource": "" }