INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Read the next block of data and its header
def read_next_data_block_int8(self): """ Read the next block of data and its header Returns: (header, data) header (dict): dictionary of header metadata data (np.array): Numpy array of data, converted into to complex64. """ header, data_idx = self.read_header() ...
Read the next block of data and its header
def read_next_data_block_int8_2x(self): """ Read the next block of data and its header Returns: (header, data) header (dict): dictionary of header metadata data (np.array): Numpy array of data, converted into to complex64. """ header, data_idx = self.read_header(...
Read the next block of data and its header
def read_next_data_block(self): """ Read the next block of data and its header Returns: (header, data) header (dict): dictionary of header metadata data (np.array): Numpy array of data, converted into to complex64. """ header, data_idx = self.read_header() ...
Seek through the file to find how many data blocks there are in the file
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...
Compute some basic stats on the next block of data
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...
Plot a histogram of data values
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...
Do a ( slow ) numpy FFT and take power of data
def plot_spectrum(self, filename=None, plot_db=True): """ Do a (slow) numpy FFT and take power of data """ header, data = self.read_next_data_block() print("Computing FFT...") d_xx_fft = np.abs(np.fft.fft(data[..., 0])) d_xx_fft = d_xx_fft.flatten() # Rebin to max numbe...
Generate a blimpy header dictionary
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 ...
Script to find the header size of a filterbank file
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...
Command line tool to make a md5sum comparison of two. fil files.
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...
Converts file to HDF5 (. h5 ) format. Default saves output in current dir.
def make_h5_file(filename,out_dir='./', new_filename = None, max_load = None): ''' Converts file to HDF5 (.h5) format. Default saves output in current dir. ''' fil_file = Waterfall(filename, max_load = max_load) if not new_filename: new_filename = out_dir+filename.replace('.fil','.h5').split('/...
Command line tool for converting guppi raw into HDF5 versions of guppi raw
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...
Returns time - averaged spectra of the ON and OFF measurements in a calibrator measurement with flickering noise diode
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...
Integrates over each core channel of a given spectrum. Important for calibrating data with frequency/ time resolution different from noise diode data
def integrate_chans(spec,freqs,chan_per_coarse): ''' Integrates over each core channel of a given spectrum. Important for calibrating data with frequency/time resolution different from noise diode data Parameters ---------- spec : 1D Array (float) Spectrum (any Stokes parameter) to be i...
Folds Stokes I noise diode data and integrates along coarse channels
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 ...
Given properties of the calibrator source calculate fluxes of the source in a particular frequency range
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...
Returns central frequency of each coarse channel
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 ...
Calculate f_ON and f_OFF as defined in van Straten et al. 2012 equations 2 and 3
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 ...
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
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...
Returns frequency dependent system temperature given observations on and off a calibrator source
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...
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
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 ...
Return the length of the blimpy header in bytes
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...
Open file and confirm if it is a filterbank file or not.
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 ...
Read blimpy header and return a Python dictionary of key: value pairs
def read_header(filename, 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 for value...
Apply a quick patch - up to a Filterbank header by overwriting a header value
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...
Reads a little - endian double in ddmmss. s ( or hhmmss. s ) format and then converts to Float degrees ( or hours ). This is primarily used to read src_raj and src_dej header values.
def fil_double_to_angle(angle): """ Reads a little-endian double in ddmmss.s (or hhmmss.s) format and then converts to Float degrees (or hours). This is primarily used to read src_raj and src_dej header values. """ negative = (angle < 0.0) angle = np.abs(angle) dd = np.floor((angl...
Generate a serialized string for a sigproc keyword: value pair
def to_sigproc_keyword(keyword, value=None): """ Generate a serialized string for a sigproc keyword:value pair If value=None, just the keyword will be written with no payload. Data type is inferred by keyword name (via a lookup table) Args: keyword (str): Keyword to write value (None, ...
Generate a serialzed sigproc header which can be written to disk.
def generate_sigproc_header(f): """ Generate a serialzed sigproc header which can be written to disk. Args: f (Filterbank object): Filterbank object for which to generate header Returns: header_str (str): Serialized string corresponding to header """ header_string = b'' header...
Convert an astropy. Angle to the ridiculous sigproc angle format string.
def to_sigproc_angle(angle_val): """ Convert an astropy.Angle to the ridiculous sigproc angle format string. """ x = str(angle_val) if '.' in x: if 'h' in x: d, m, s, ss = int(x[0:x.index('h')]), int(x[x.index('h')+1:x.index('m')]), \ int(x[x.index('m')+1:x.index('.'...
Calculate number of integrations in a given file
def calc_n_ints_in_file(filename): """ Calculate number of integrations in a given file """ # Load binary data h = read_header(filename) n_bytes = int(h[b'nbits'] / 8) n_chans = h[b'nchans'] n_ifs = h[b'nifs'] idx_data = len_header(filename) f = open(filename, 'rb') f.seek(idx_da...
Converts file to Sigproc filterbank (. fil ) format. Default saves output in current dir.
def make_fil_file(filename,out_dir='./', new_filename=None, max_load = None): ''' Converts file to Sigproc filterbank (.fil) format. Default saves output in current dir. ''' fil_file = Waterfall(filename, max_load = max_load) if not new_filename: new_filename = out_dir+filename.replace('.h5','...
Convert a Traceback into a dictionary representation
def to_dict(self): """Convert a Traceback into a dictionary representation""" if self.tb_next is None: tb_next = None else: tb_next = self.tb_next.to_dict() code = { 'co_filename': self.tb_frame.f_code.co_filename, 'co_name': self.tb_frame...
Make a subparser for a given type of DNS record
def make_rr_subparser(subparsers, rec_type, args_and_types): """ Make a subparser for a given type of DNS record """ sp = subparsers.add_parser(rec_type) sp.add_argument("name", type=str) sp.add_argument("ttl", type=int, nargs='?') sp.add_argument(rec_type, type=str) for my_spec in arg...
Make an ArgumentParser that accepts DNS RRs
def make_parser(): """ Make an ArgumentParser that accepts DNS RRs """ line_parser = ZonefileLineParser() subparsers = line_parser.add_subparsers() # parse $ORIGIN sp = subparsers.add_parser("$ORIGIN") sp.add_argument("$ORIGIN", type=str) # parse $TTL sp = subparsers.add_parser...
Tokenize a line: * split tokens on whitespace * treat quoted strings as a single token * drop comments * handle escaped spaces and comment delimiters
def tokenize_line(line): """ Tokenize a line: * split tokens on whitespace * treat quoted strings as a single token * drop comments * handle escaped spaces and comment delimiters """ ret = [] escape = False quote = False tokbuf = "" ll = list(line) while len(ll) > 0: ...
Serialize tokens: * quote whitespace - containing tokens * escape semicolons
def serialize(tokens): """ Serialize tokens: * quote whitespace-containing tokens * escape semicolons """ ret = [] for tok in tokens: if " " in tok: tok = '"%s"' % tok if ";" in tok: tok = tok.replace(";", "\;") ret.append(tok) return " ...
Remove comments from a zonefile
def remove_comments(text): """ Remove comments from a zonefile """ ret = [] lines = text.split("\n") for line in lines: if len(line) == 0: continue line = serialize(tokenize_line(line)) ret.append(line) return "\n".join(ret)
Flatten the text: * make sure each record is on one line. * remove parenthesis
def flatten(text): """ Flatten the text: * make sure each record is on one line. * remove parenthesis """ lines = text.split("\n") # tokens: sequence of non-whitespace separated by '' where a newline was tokens = [] for l in lines: if len(l) == 0: continue ...
Remove the CLASS from each DNS record if present. The only class that gets used today ( for all intents and purposes ) is IN.
def remove_class(text): """ Remove the CLASS from each DNS record, if present. The only class that gets used today (for all intents and purposes) is 'IN'. """ # see RFC 1035 for list of classes lines = text.split("\n") ret = [] for line in lines: tokens = tokenize_line(line)...
Go through each line of the text and ensure that a name is defined. Use
def add_default_name(text): """ Go through each line of the text and ensure that a name is defined. Use '@' if there is none. """ global SUPPORTED_RECORDS lines = text.split("\n") ret = [] for line in lines: tokens = tokenize_line(line) if len(tokens) == 0: ...
Given the parser capitalized list of a line s tokens and the current set of records parsed so far parse it into a dictionary.
def parse_line(parser, record_token, parsed_records): """ Given the parser, capitalized list of a line's tokens, and the current set of records parsed so far, parse it into a dictionary. Return the new set of parsed records. Raise an exception on error. """ global SUPPORTED_RECORDS l...
Parse a zonefile into a dict.
def parse_lines(text, ignore_invalid=False): """ Parse a zonefile into a dict. @text must be flattened--each record must be on one line. Also, all comments must be removed. """ json_zone_file = defaultdict(list) record_lines = text.split("\n") parser = make_parser() for record_line ...
Parse a zonefile into a dict
def parse_zone_file(text, ignore_invalid=False): """ Parse a zonefile into a dict """ text = remove_comments(text) text = flatten(text) text = remove_class(text) text = add_default_name(text) json_zone_file = parse_lines(text, ignore_invalid=ignore_invalid) return json_zone_file
Generate the DNS zonefile given a json - encoded description of the zone file ( @json_zone_file ) and the template to fill in ( @template )
def make_zone_file(json_zone_file_input, origin=None, ttl=None, template=None): """ Generate the DNS zonefile, given a json-encoded description of the zone file (@json_zone_file) and the template to fill in (@template) json_zone_file = { "$origin": origin server, "$ttl": default time...
Replace { $origin } in template with a serialized $ORIGIN record
def process_origin(data, template): """ Replace {$origin} in template with a serialized $ORIGIN record """ record = "" if data is not None: record += "$ORIGIN %s" % data return template.replace("{$origin}", record)
Replace { $ttl } in template with a serialized $TTL record
def process_ttl(data, template): """ Replace {$ttl} in template with a serialized $TTL record """ record = "" if data is not None: record += "$TTL %s" % data return template.replace("{$ttl}", record)
Replace { SOA } in template with a set of serialized SOA records
def process_soa(data, template): """ Replace {SOA} in template with a set of serialized SOA records """ record = template[:] if data is not None: assert len(data) == 1, "Only support one SOA RR at this time" data = data[0] soadat = [] domain_fields = ['mname', ...
Quote a field in a list of DNS records. Return the new data records.
def quote_field(data, field): """ Quote a field in a list of DNS records. Return the new data records. """ if data is None: return None data_dup = copy.deepcopy(data) for i in xrange(0, len(data_dup)): data_dup[i][field] = '"%s"' % data_dup[i][field] data_dup[i][fie...
Meta method: Replace $field in template with the serialized $record_type records using
def process_rr(data, record_type, record_keys, field, template): """ Meta method: Replace $field in template with the serialized $record_type records, using @record_key from each datum. """ if data is None: return template.replace(field, "") if type(record_keys) == list: pas...
Replace { txt } in template with the serialized TXT records
def process_txt(data, template): """ Replace {txt} in template with the serialized TXT records """ if data is None: to_process = None else: # quote txt to_process = copy.deepcopy(data) for datum in to_process: if isinstance(datum["txt"], list): ...
Load and return a PySchema class from an avsc string
def parse_schema_string(schema_string): """ Load and return a PySchema class from an avsc string """ if isinstance(schema_string, str): schema_string = schema_string.decode("utf8") schema_struct = json.loads(schema_string) return AvroSchemaParser().parse_schema_struct(schema_struct)
This function can be used to build a python package representation of pyschema classes. One module is created per namespace in a package matching the namespace hierarchy.
def to_python_package(classes, target_folder, parent_package=None, indent=DEFAULT_INDENT): ''' This function can be used to build a python package representation of pyschema classes. One module is created per namespace in a package matching the namespace hierarchy. Args: classes: A collection o...
Generate Python source code for one specific class
def _class_source(schema, indent): """Generate Python source code for one specific class Doesn't include or take into account any dependencies between record types """ def_pattern = ( "class {class_name}(pyschema.Record):\n" "{indent}# WARNING: This class was generated by pyschema.to_p...
Temporarily disable automatic registration of records in the auto_store
def no_auto_store(): """ Temporarily disable automatic registration of records in the auto_store Decorator factory. This is _NOT_ thread safe >>> @no_auto_store() ... class BarRecord(Record): ... pass >>> BarRecord in auto_store False """ original_auto_register_value = PySchem...
Dump record in json - encodable object format
def to_json_compatible(record): "Dump record in json-encodable object format" d = {} for fname, f in record._fields.iteritems(): val = getattr(record, fname) if val is not None: d[fname] = f.dump(val) return d
Load from json - encodable
def from_json_compatible(schema, dct): "Load from json-encodable" kwargs = {} for key in dct: field_type = schema._fields.get(key) if field_type is None: raise ParseError("Unexpected field encountered in line for record %s: %s" % (schema.__name__, key)) kwargs[key] = fie...
Create a Record instance from a json - compatible dictionary
def load_json_dct( dct, record_store=None, schema=None, loader=from_json_compatible ): """ Create a Record instance from a json-compatible dictionary The dictionary values should have types that are json compatible, as if just loaded from a json serialized record string. ...
Create a Record instance from a json serialized dictionary
def loads( s, record_store=None, schema=None, loader=from_json_compatible, record_class=None # deprecated in favor of schema ): """ Create a Record instance from a json serialized dictionary :param s: String with a json-serialized dictionary :param record_s...
Add record class to record store for retrieval at record load time.
def add_record(self, schema, _bump_stack_level=False): """ Add record class to record store for retrieval at record load time. Can be used as a class decorator """ full_name = get_full_name(schema) has_namespace = '.' in full_name self._force_add(full_name, schema, _...
Will return a matching record or raise KeyError is no record is found.
def get(self, record_name): """ Will return a matching record or raise KeyError is no record is found. If the record name is a full name we will first check for a record matching the full name. If no such record is found any record matching the last part of the full name (without the na...
Return a dictionary the field definition
def repr_vars(self): """Return a dictionary the field definition Should contain all fields that are required for the definition of this field in a pyschema class""" d = OrderedDict() d["nullable"] = repr(self.nullable) d["default"] = repr(self.default) if self.descriptio...
Decorator for mixing in additional functionality into field type
def mixin(cls, mixin_cls): """Decorator for mixing in additional functionality into field type Example: >>> @Integer.mixin ... class IntegerPostgresExtensions: ... postgres_type = 'INT' ... ... def postgres_dump(self, obj): ... self.dump(...
Create proper PySchema class from cls
def from_class(metacls, cls, auto_store=True): """Create proper PySchema class from cls Any methods and attributes will be transferred to the new object """ if auto_store: def wrap(cls): return cls else: wrap = no_auto_store() ...
Return a python dict representing the jsonschema of a record
def get_schema_dict(record, state=None): """Return a python dict representing the jsonschema of a record Any references to sub-schemas will be URI fragments that won't be resolvable without a root schema, available from get_root_schema_dict. """ state = state or SchemaGeneratorState() schema = ...
Return a root jsonschema for a given record
def get_root_schema_dict(record): """Return a root jsonschema for a given record A root schema includes the $schema attribute and all sub-record schemas and definitions. """ state = SchemaGeneratorState() schema = get_schema_dict(record, state) del state.record_schemas[record._schema_name] ...
Load from json - encodable
def from_json_compatible(schema, dct): "Load from json-encodable" kwargs = {} for key in dct: field_type = schema._fields.get(key) if field_type is None: warnings.warn("Unexpected field encountered in line for record %s: %r" % (schema.__name__, key)) continue ...
Converts a file object with json serialised pyschema records to a stream of pyschema objects
def mr_reader(job, input_stream, loads=core.loads): """ Converts a file object with json serialised pyschema records to a stream of pyschema objects Can be used as job.reader in luigi.hadoop.JobTask """ for line in input_stream: yield loads(line),
Writes a stream of json serialised pyschema Records to a file object
def mr_writer(job, outputs, output_stream, stderr=sys.stderr, dumps=core.dumps): """ Writes a stream of json serialised pyschema Records to a file object Can be used as job.writer in luigi.hadoop.JobTask """ for output in outputs: try: print >> output_stream, dumps(out...
Set a value at the front of an OrderedDict
def ordereddict_push_front(dct, key, value): """Set a value at the front of an OrderedDict The original dict isn't modified, instead a copy is returned """ d = OrderedDict() d[key] = value d.update(dct) return d
Generates a single filter expression for filter [].
def gen_filter(name, op, value, is_or=False): """Generates a single filter expression for ``filter[]``.""" if op not in OPERATORS: raise ValueError('Unknown operator {}'.format(op)) result = u'{} {} {}'.format(name, op, escape_filter(value)) if is_or: result = u'or ' + result return ...
Creates a query ( AND and = ) from a dictionary.
def from_dict(cls, d): """Creates a query (AND and =) from a dictionary.""" if not d: raise ValueError('Empty dictionary!') items = list(d.items()) key, value = items.pop(0) q = cls(key, u'=', value) for key, value in items: q = q & cls(key, u'=', ...
Specify query string to use with the collection.
def query_string(self, **params): """Specify query string to use with the collection. Returns: :py:class:`SearchResult` """ return SearchResult(self, self._api.get(self._href, **params))
Sends all filters to the API.
def raw_filter(self, filters): """Sends all filters to the API. No fancy, just a wrapper. Any advanced functionality shall be implemented as another method. Args: filters: List of filters (strings) Returns: :py:class:`SearchResult` """ return SearchResult(s...
Returns all entities present in the collection with attributes included.
def all_include_attributes(self, attributes): """Returns all entities present in the collection with ``attributes`` included.""" self.reload(expand=True, attributes=attributes) entities = [Entity(self, r, attributes=attributes) for r in self._resources] self.reload() return entit...
Returns entity in correct collection.
def _get_entity_from_href(self, result): """Returns entity in correct collection. If the "href" value in result doesn't match the current collection, try to find the collection that the "href" refers to. """ href_result = result['href'] if self.collection._href.startswi...
When you pass a quote character returns you an another one if possible
def give_another_quote(q): """When you pass a quote character, returns you an another one if possible""" for qc in QUOTES: if qc != q: return qc else: raise ValueError(u'Could not find a different quote for {}'.format(q))
Tries to escape the values that are passed to filter as correctly as possible.
def escape_filter(o): """Tries to escape the values that are passed to filter as correctly as possible. No standard way is followed, but at least it is simple. """ if o is None: return u'NULL' if isinstance(o, int): return str(o) if not isinstance(o, six.string_types): r...
Make the plot with parallax performance predictions.
def makePlot(args): """ Make the plot with parallax performance predictions. :argument args: command line arguments """ gmag=np.linspace(5.7,20.0,101) vminiB1V=vminiFromSpt('B1V') vminiG2V=vminiFromSpt('G2V') vminiM6V=vminiFromSpt('M6V') vmagB1V=gmag-gminvFromVmini(vminiB1V) vmagG2V=gmag-gminvF...
Plot the bright limit of Gaia in V as a function of ( V - I ).
def plotBrightLimitInV(gBright, pdf=False, png=False): """ Plot the bright limit of Gaia in V as a function of (V-I). Parameters ---------- gBright - The bright limit of Gaia in G """ vmini=np.linspace(0.0,6.0,1001) gminv=gminvFromVmini(vmini) vBright=gBright-gminv fig=plt.figure(figsize=(10,6.5)...
Convert spherical to Cartesian coordinates. The input can be scalars or 1 - dimensional numpy arrays. Note that the angle coordinates follow the astronomical convention of using elevation ( declination latitude ) rather than its complement ( pi/ 2 - elevation ) where the latter is commonly used in the mathematical trea...
def sphericalToCartesian(r, phi, theta): """ Convert spherical to Cartesian coordinates. The input can be scalars or 1-dimensional numpy arrays. Note that the angle coordinates follow the astronomical convention of using elevation (declination, latitude) rather than its complement (pi/2-elevation), where the la...
Convert Cartesian to spherical coordinates. The input can be scalars or 1 - dimensional numpy arrays. Note that the angle coordinates follow the astronomical convention of using elevation ( declination latitude ) rather than its complement ( pi/ 2 - elevation ) which is commonly used in the mathematical treatment of sp...
def cartesianToSpherical(x, y, z): """ Convert Cartesian to spherical coordinates. The input can be scalars or 1-dimensional numpy arrays. Note that the angle coordinates follow the astronomical convention of using elevation (declination, latitude) rather than its complement (pi/2-elevation), which is commonly ...
Calculate the so - called normal triad [ p q r ] which is associated with a spherical coordinate system. The three vectors are:
def normalTriad(phi, theta): """ Calculate the so-called normal triad [p, q, r] which is associated with a spherical coordinate system . The three vectors are: p - The unit tangent vector in the direction of increasing longitudinal angle phi. q - The unit tangent vector in the direction of increasing latitud...
Construct an elementary rotation matrix describing a rotation around the x y or z - axis.
def elementaryRotationMatrix(axis, rotationAngle): """ Construct an elementary rotation matrix describing a rotation around the x, y, or z-axis. Parameters ---------- axis - Axis around which to rotate ("x", "y", or "z") rotationAngle - the rotation angle in radians Returns ------- The ro...
From the given phase space coordinates calculate the astrometric observables including the radial velocity which here is seen as the sixth astrometric parameter. The phase space coordinates are assumed to represent barycentric ( i. e. centred on the Sun ) positions and velocities.
def phaseSpaceToAstrometry(x, y, z, vx, vy, vz): """ From the given phase space coordinates calculate the astrometric observables, including the radial velocity, which here is seen as the sixth astrometric parameter. The phase space coordinates are assumed to represent barycentric (i.e. centred on the Sun) posi...
From the input astrometric parameters calculate the phase space coordinates. The output phase space coordinates represent barycentric ( i. e. centred on the Sun ) positions and velocities.
def astrometryToPhaseSpace(phi, theta, parallax, muphistar, mutheta, vrad): """ From the input astrometric parameters calculate the phase space coordinates. The output phase space coordinates represent barycentric (i.e. centred on the Sun) positions and velocities. This function has no mechanism to deal with u...
Make the plot with proper motion performance predictions. The predictions are for the TOTAL proper motion under the assumption of equal components mu_alpha * and mu_delta.
def makePlot(args): """ Make the plot with proper motion performance predictions. The predictions are for the TOTAL proper motion under the assumption of equal components mu_alpha* and mu_delta. :argument args: command line arguments """ gmag=np.linspace(5.7,20.0,101) vminiB1V=vminiFromSpt('B1V') vmin...
Set up command line parsing.
def parseCommandLineArguments(): """ Set up command line parsing. """ parser = argparse.ArgumentParser(description="Plot predicted Gaia sky averaged proper motion errors as a function of V") parser.add_argument("-p", action="store_true", dest="pdfOutput", help="Make PDF plot") parser.add_argument("-b", acti...
Create a new enumeration type. Code is copyright ( c ) Gabriel Genellina 2010 MIT License.
def enum(typename, field_names): """ Create a new enumeration type. Code is copyright (c) Gabriel Genellina, 2010, MIT License. Parameters ---------- typename - Name of the enumerated type field_names - Names of the fields of the enumerated type """ if isinstance(field_names, s...
Take the astrometric parameter standard uncertainties and the uncertainty correlations as quoted in the Gaia catalogue and construct the covariance matrix.
def construct_covariance_matrix(cvec, parallax, radial_velocity, radial_velocity_error): """ Take the astrometric parameter standard uncertainties and the uncertainty correlations as quoted in the Gaia catalogue and construct the covariance matrix. Parameters ---------- cvec : array_like ...
Make a plot of a Mv vs ( V - I ) colour magnitude diagram containing lines of constant distance for stars at G = 20. This will give an idea of the reach of Gaia.
def makePlot(gmag, pdf=False, png=False, rvs=False): """ Make a plot of a Mv vs (V-I) colour magnitude diagram containing lines of constant distance for stars at G=20. This will give an idea of the reach of Gaia. Parameters ---------- args - command line arguments """ vmini = np.linspace(-0.5,4.0,100)...
Calculate radial velocity error from V and the spectral type. The value of the error is an average over the sky.
def vradErrorSkyAvg(vmag, spt): """ Calculate radial velocity error from V and the spectral type. The value of the error is an average over the sky. Parameters ---------- vmag - Value of V-band magnitude. spt - String representing the spectral type of the star. Returns ------- The radial veloci...
This code takes care of ordering the points ( x y ) calculated for a sky map parallel or merdian such that the drawing code can start at one end of the curve and end at the other ( so no artifacts due to connecting the disjoint ends occur ).
def _orderGridlinePoints(x, y): """ This code takes care of ordering the points (x,y), calculated for a sky map parallel or merdian, such that the drawing code can start at one end of the curve and end at the other (so no artifacts due to connecting the disjoint ends occur). Parameters ---------- x - Se...
Produce a sky - plot in a given coordinate system with the meridians and paralles for another coordinate system overlayed. The coordinate systems are specified through the pygaia. coordinates. Transformations enum. For example for Transformations. GAL2ECL the sky plot will be in Ecliptic coordinates with the Galactic c...
def plotCoordinateTransformationOnSky(transformation, outfile=None, myProjection='hammer', noTitle=False, noLabels=False, returnPlotObject=False): """ Produce a sky-plot in a given coordinate system with the meridians and paralles for another coordinate system overlayed. The coordinate systems are speci...
Calculate the parallax error for the given input source magnitude and colour.
def calcParallaxError(args): """ Calculate the parallax error for the given input source magnitude and colour. :argument args: command line arguments """ gmag=float(args['gmag']) vmini=float(args['vmini']) sigmaPar=parallaxErrorSkyAvg(gmag, vmini) gminv=gminvFromVmini(vmini) print("G = {0}".format(gm...
Set up command line parsing.
def parseCommandLineArguments(): """ Set up command line parsing. """ parser = argparse.ArgumentParser(description="Calculate parallax error for given G and (V-I)") parser.add_argument("gmag", help="G-band magnitude of source", type=float) parser.add_argument("vmini", help="(V-I) colour of source", type=flo...
Calculate the single - field - of - view - transit photometric standard error in the G band as a function of G. A 20% margin is included.
def gMagnitudeError(G): """ Calculate the single-field-of-view-transit photometric standard error in the G band as a function of G. A 20% margin is included. Parameters ---------- G - Value(s) of G-band magnitude. Returns ------- The G band photometric standard error in units of magnitude. "...
Calculate the end of mission photometric standard error in the G band as a function of G. A 20% margin is included.
def gMagnitudeErrorEoM(G, nobs=70): """ Calculate the end of mission photometric standard error in the G band as a function of G. A 20% margin is included. Parameters ---------- G - Value(s) of G-band magnitude. Keywords -------- nobs - Number of observations collected (default 70). Return...
Calculate the single - field - of - view - transit photometric standard error in the BP band as a function of G and ( V - I ). Note: this refers to the integrated flux from the BP spectrophotometer. A margin of 20% is included.
def bpMagnitudeError(G, vmini): """ Calculate the single-field-of-view-transit photometric standard error in the BP band as a function of G and (V-I). Note: this refers to the integrated flux from the BP spectrophotometer. A margin of 20% is included. Parameters ---------- G - Value(s) of G-band mag...
Calculate the end - of - mission photometric standard error in the BP band as a function of G and ( V - I ). Note: this refers to the integrated flux from the BP spectrophotometer. A margin of 20% is included.
def bpMagnitudeErrorEoM(G, vmini, nobs=70): """ Calculate the end-of-mission photometric standard error in the BP band as a function of G and (V-I). Note: this refers to the integrated flux from the BP spectrophotometer. A margin of 20% is included. Parameters ---------- G - Value(s) of G-band magnitu...
Calculate the end - of - mission photometric standard error in the RP band as a function of G and ( V - I ). Note: this refers to the integrated flux from the RP spectrophotometer. A margin of 20% is included.
def rpMagnitudeErrorEoM(G, vmini, nobs=70): """ Calculate the end-of-mission photometric standard error in the RP band as a function of G and (V-I). Note: this refers to the integrated flux from the RP spectrophotometer. A margin of 20% is included. Parameters ---------- G - Value(s) of G-band magnitu...