code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
def func(params, vec): vec[0] = -13 + params[0] + ((5 - params[1]) * params[1] - 2) * params[1] vec[1] = -29 + params[0] + ((1 + params[1]) * params[1] - 14) * params[1] def jac(params, jac): jac[0] = 1 jac[1,0] = params[1] * (10 - 3 * params[1]) - 2 jac[1,1] = par...
def _lmder1_freudenstein_roth()
Freudenstein and Roth function (lmder1 test #7)
3.367754
3.351339
1.004898
y1 = np.asfarray([0.14, 0.18, 0.22, 0.25, 0.29, 0.32, 0.35, 0.39, 0.37, 0.58, 0.73, 0.96, 1.34, 2.10, 4.39]) def func(params, vec): for i in range(15): tmp2 = 15 - i if i > 7: tmp3 = tmp2 else: ...
def _lmder1_bard()
Bard function (lmder1 test #8)
3.368493
3.363454
1.001498
v = np.asfarray([4, 2, 1, 0.5, 0.25, 0.167, 0.125, 0.1, 0.0833, 0.0714, 0.0625]) y2 = np.asfarray([0.1957, 0.1947, 0.1735, 0.16, 0.0844, 0.0627, 0.0456, 0.0342, 0.0323, 0.0235, 0.0246]) def func(params, vec): tmp1 = v * (v + params[1]) tmp2 = v * (v + params[2]) +...
def _lmder1_kowalik_osborne()
Kowalik & Osborne function (lmder1 test #9)
3.611172
3.568206
1.012042
y3 = np.asarray([3.478e4, 2.861e4, 2.365e4, 1.963e4, 1.637e4, 1.372e4, 1.154e4, 9.744e3, 8.261e3, 7.03e3, 6.005e3, 5.147e3, 4.427e3, 3.82e3, 3.307e3, 2.872e3]) def func(params, vec): temp = 5 * (np.arange(16) + 1) + 45 + params[2] tmp1 = params[1]...
def _lmder1_meyer()
Meyer function (lmder1 test #10)
3.538605
3.509908
1.008176
dsideval = _dside_names.get(sidedness) if dsideval is None: raise ValueError('unrecognized sidedness "%s"' % sidedness) p = self._pinfob p[idx] = (p[idx] & ~PI_M_SIDE) | dsideval return self
def p_side(self, idx, sidedness)
Acceptable values for *sidedness* are "auto", "pos", "neg", and "two".
6.274982
6.073805
1.033122
return (isinstance (value, type) and issubclass (value, klass) and value is not klass)
def is_strict_subclass (value, klass)
Check that `value` is a subclass of `klass` but that it is not actually `klass`. Unlike issubclass(), does not raise an exception if `value` is not a type.
3.750209
3.957448
0.947633
import sys from .. import cli cli.propagate_sigint () cli.unicode_stdio () cli.backtrace_on_usr1 () if tool_class is None: for value in itervalues (namespace): if is_strict_subclass (value, Multitool): if tool_class is not None: raise...
def invoke_tool (namespace, tool_class=None)
Invoke a tool and exit. `namespace` is a namespace-type dict from which the tool is initialized. It should contain exactly one value that is a `Multitool` subclass, and this subclass will be instantiated and populated (see `Multitool.populate()`) using the other items in the namespace. Instances an...
5.881067
4.464292
1.317357
argv0 = kwargs['argv0'] usage = self._usage (argv0) argv = [argv0] + args uina = 'long' if self.help_if_no_args else False check_usage (usage, argv, usageifnoargs=uina) try: return self.invoke (args, **kwargs) except UsageError as e: ...
def invoke_with_usage (self, args, **kwargs)
Invoke the command with standardized usage-help processing. Same calling convention as `Command.invoke()`.
6.68813
6.623445
1.009766
import argparse ap = argparse.ArgumentParser ( prog = kwargs['argv0'], description = self.summary, ) return ap
def get_arg_parser (self, **kwargs)
Return an instance of `argparse.ArgumentParser` used to process this tool's command-line arguments.
7.990372
6.676708
1.196753
ap = self.get_arg_parser (**kwargs) args = ap.parse_args (args) return self.invoke (args, **kwargs)
def invoke_with_usage (self, args, **kwargs)
Invoke the command with standardized usage-help processing. Same calling convention as `Command.invoke()`, except here *args* is an un-parsed list of strings.
3.694997
3.392842
1.089057
if cmd.name is None: raise ValueError ('no name set for Command object %r' % cmd) if cmd.name in self.commands: raise ValueError ('a command named "%s" has already been ' 'registered' % cmd.name) self.commands[cmd.name] = cmd ...
def register (self, cmd)
Register a new command with the tool. 'cmd' is expected to be an instance of `Command`, although here only the `cmd.name` attribute is investigated. Multiple commands with the same name are not allowed to be registered. Returns 'self'.
3.296315
2.880142
1.144497
for value in values: if isinstance (value, Command): self.register (value) elif is_strict_subclass (value, Command) and getattr (value, 'name') is not None: self.register (value ()) return self
def populate (self, values)
Register multiple new commands by investigating the iterable `values`. For each item in `values`, instances of `Command` are registered, and subclasses of `Command` are instantiated (with no arguments passed to the constructor) and registered. Other kinds of values are ignored. Returns '...
5.479741
4.101694
1.33597
new_kwargs = kwargs.copy () new_kwargs['argv0'] = kwargs['argv0'] + ' ' + cmd.name new_kwargs['parent'] = self new_kwargs['parent_kwargs'] = kwargs return cmd.invoke_with_usage (args, **new_kwargs)
def invoke_command (self, cmd, args, **kwargs)
This function mainly exists to be overridden by subclasses.
4.273569
3.988263
1.071536
self.invoke_with_usage (argv[1:], tool=self, argv0=self.cli_name)
def commandline (self, argv)
Run as if invoked from the command line. 'argv' is a Unix-style list of arguments, where the zeroth item is the program name (which is ignored here). Usage help is printed if deemed appropriate (e.g., no arguments are given). This function always terminates with an exception, with the ex...
19.149734
16.268328
1.177118
cited = set() for line in stream: if not line.startswith(r'\citation{'): continue line = line.rstrip() if line[-1] != '}': continue # should issue a warning or something entries = line[10:-1] for name in entries.split(','): nam...
def cited_names_from_aux_file(stream)
Parse a LaTeX ".aux" file and generate a list of names cited according to LaTeX ``\\citation`` commands. Repeated names are generated only once. The argument should be a opened I/O stream.
3.483327
3.391527
1.027067
allrecords = {} for ed in extradicts: allrecords.update(ed) allrecords.update(maindict) missing = [] from collections import OrderedDict records = OrderedDict() from itertools import chain wantednames = sorted(chain(citednames, six.viewkeys(maindict))) for name in wa...
def merge_bibtex_collections(citednames, maindict, extradicts, allow_missing=False)
There must be a way to be efficient and stream output instead of loading everything into memory at once, but, meh. Note that we augment `citednames` with all of the names in `maindict`. The intention is that if we've gone to the effort of getting good data for some record, we don't want to trash it if ...
4.677638
4.678062
0.999909
from bibtexparser.bwriter import BibTexWriter writer = BibTexWriter() writer.indent = ' ' writer.entry_separator = '' first = True for rec in entries: if first: first = False else: stream.write(b'\n') stream.write(writer._entry_to_bibtex(re...
def write_bibtex_dict(stream, entries)
bibtexparser.write converts the entire database to one big string and writes it out in one go. I'm sure it will always all fit in RAM but some things just will not stand.
2.690255
2.609768
1.030841
auxpath = Path(auxpath) mainpath = Path(mainpath) extradir = Path(extradir) with auxpath.open('rt') as aux: citednames = sorted(cited_names_from_aux_file(aux)) main = mainpath.try_open(mode='rt') if main is None: maindict = {} else: maindict = parse(main) ...
def merge_bibtex_with_aux(auxpath, mainpath, extradir, parse=get_bibtex_dict, allow_missing=False)
Merge multiple BibTeX files into a single homogeneously-formatted output, using a LaTeX .aux file to know which records are worth paying attention to. The file identified by `mainpath` will be overwritten with the new .bib contents. This function is intended to be used in a version-control context....
4.179678
4.479774
0.933011
extradir = Path('.bibtex') extradir.ensure_dir(parents=True) bib_export(bib_style, aux, extradir / 'ZZ_bibtools.bib', no_tool_ok=True, quiet=True, ignore_missing=True) merge_bibtex_with_aux(aux, bib, extradir)
def just_smart_bibtools(bib_style, aux, bib)
Tectonic has taken over most of the features that this tool used to provide, but here's a hack to keep my smart .bib file generation working.
10.990637
10.81203
1.016519
if asdm is None: raise ValueError ('asdm') if ms is None: raise ValueError ('ms') helper.casans.importasdm ( asdm = asdm, vis = ms, asis = 'Antenna Station Receiver Source CalAtmosphere CalWVR CorrelatorMode SBSummary', bdfflags = True, lazy = Fa...
def in_casapy (helper, asdm=None, ms=None)
This function is run inside the weirdo casapy IPython environment! A strange set of modules is available, and the `pwkit.environments.casa.scripting` system sets up a very particular environment to allow encapsulated scripting.
20.793741
21.31407
0.975588
ap1, ap2 = bp if ap1 < 0: raise ValueError ('first antpol %d is negative' % ap1) if ap2 < 0: raise ValueError ('second antpol %d is negative' % ap2) pol = _fpol_to_pol[((ap1 & 0x7) << 4) + (ap2 & 0x7)] if pol == 0xFF: raise ValueError ('no CASA polarization code for pa...
def bp_to_aap (bp)
Converts a basepol into a tuple of (ant1, ant2, pol).
4.105412
3.507065
1.170612
if ant1 < 0: raise ValueError ('first antenna is below 0: %s' % ant1) if ant2 < ant1: raise ValueError ('second antenna is below first: %s' % ant2) if pol < 1 or pol > 12: raise ValueError ('illegal polarization code %s' % pol) fps = _pol_to_fpol[pol] ap1 = (ant1 << 3)...
def aap_to_bp (ant1, ant2, pol)
Create a basepol from antenna numbers and a CASA polarization code.
2.764287
2.666084
1.036834
n, mean, scat = stats_result mean *= 180 / np.pi # rad => deg scat /= n # variance-of-samples => variance-of-mean scat **= 0.5 # variance => stddev scat *= 180 / np.pi # rad => deg return mean, scat
def postproc (stats_result)
Simple helper to postprocess angular outputs from StatsCollectors in the way we want.
5.070447
4.595794
1.10328
n, mean, scat = stats_result ok = np.isfinite (mean) n = n[ok] mean = mean[ok] scat = scat[ok] mean *= 180 / np.pi # rad => deg scat /= n # variance-of-samples => variance-of-mean scat **= 0.5 # variance => stddev scat *= 180 / np.pi # rad => deg return ok, mean, scat
def postproc_mask (stats_result)
Simple helper to postprocess angular outputs from StatsCollectors in the way we want.
3.977344
3.829502
1.038606
seen_ants = set () seen_pols = set () for ant1, ant2, pol in (bp_to_aap (bp) for bp in bps): seen_ants.add (ant1) seen_ants.add (ant2) seen_pols.add (pol) if len (seen_pols) != 2: raise Exception ('can only work with 2 polarizations') pol1, pol2 = sorted (seen_...
def grid_bp_data (bps, items, mask=True)
Given a bunch of scalars associated with intensity-type basepols, place them onto a grid. There should be only two polarizations represented (e.g. RR, LL); baselines for one of them will be put into the upper triangle of the grid, while baselines for the other will be put into the lower triangle. `bps`...
2.265357
2.127378
1.064859
n_us = len (self._keymap) # By definition (for now), wt >= 1 everywhere, so we don't need to # worry about div-by-zero. wt_us = self._m0[:n_us] mean_us = self._m1[:n_us] / wt_us var_us = self._m2[:n_us] / wt_us - mean_us**2 n_them = len (keyset) ...
def finish (self, keyset, mask=True)
Returns (weights, means, variances), where: weights ndarray of number of samples per key means computed mean value for each key variances computed variance for each key
2.614015
2.615641
0.999378
n1_us = len (self._key1map) n2_us = len (self._key2map) wt_us = self._m0[:n1_us,:n2_us] badwt = (wt_us == 0) | ~np.isfinite (wt_us) wt_us[badwt] = 1 mean_us = self._m1[:n1_us,:n2_us] / wt_us var_us = self._m2[:n1_us,:n2_us] / wt_us - mean_us**2 wt...
def finish (self, key1set, key2set, mask=True)
Returns (weights, means, variances), where: weights ndarray of number of samples per key; shape (n1, n2), where n1 is the size of key1set and n2 is the size of key2set. means computed mean value for each key variances computed variance for each key
2.165895
2.151756
1.006571
for fpol, aps in self.ap_by_fpol.items (): aps = sorted (aps) nap = len (aps) for i1, ap1 in enumerate (aps): for i2 in range (i1, nap): ap2 = aps[i2] bp1 = (ap1, ap2) info = self.data_by_bp...
def _finish_timeslot (self)
We have loaded in all of the visibilities in one timeslot. We can now compute the phase closure triples. XXX: we should only process independent triples. Are we???
3.07156
2.857611
1.07487
# Frequency-resolved: np.divide (triple, np.abs (triple), triple) phase = np.angle (triple) self.ap_spec_stats_by_ddid[self.cur_ddid].accum (ap1, phase, tflags + 0.) self.ap_spec_stats_by_ddid[self.cur_ddid].accum (ap2, phase, tflags + 0.) self.ap_spec_stats_by_...
def _process_sample (self, ap1, ap2, ap3, triple, tflags)
We have computed one independent phase closure triple in one timeslot.
1.938228
1.912223
1.013599
check_usage(dftphotom_doc, argv, usageifnoargs=True) cfg = Config().parse(argv[1:]) util.logger(cfg.loglevel) dftphotom(cfg)
def dftphotom_cli(argv)
Command-line access to the :func:`dftphotom` algorithm. This function implements the behavior of the command-line ``casatask dftphotom`` tool, wrapped up into a single callable function. The argument *argv* is a list of command-line arguments, in Unix style where the zeroth item is the name of the comm...
7.350591
10.742248
0.684269
links = self.links if not path.exists(dir_path): makedirs(dir_path) for i, url in enumerate(links): if 'start' in self.cseargs: i += int(self.cseargs['start']) ext = self.cseargs['fileType'] ext = '.html' if ext == '' else '.' + ext file_name = self.cseargs['q'].re...
def download_links(self, dir_path)
Download web pages or images from search result links. Args: dir_path (str): Path of directory to save downloads of :class:`api.results`.links
2.318554
2.36004
0.982421
metadata = self.metadata values = [] if metadata != None: if k in metadata: for metav in metadata[k]: if v in metav: values.append(metav[v]) return values
def get_values(self, k, v)
Get a list of values from the key value metadata attribute. Args: k (str): Key in :class:`api.results`.metadata v (str): Values from each item in the key of :class:`api.results`.metadata Returns: A list containing all the ``v`` values in the ``k`` key for the :class:...
4.494161
4.797808
0.936711
if 'searchType' in self.cseargs: searchType = self.cseargs['searchType'] else: searchType = None items = self.metadata[k] # (cse_print) Print results for i, kv in enumerate(items[:n]): if 'start' in self.cseargs: i += int(self.cseargs['start']) # (print...
def preview(self, n=10, k='items', kheader='displayLink', klink='link', kdescription='snippet')
Print a preview of the search results. Args: n (int): Maximum number of search results to preview k (str): Key in :class:`api.results`.metadata to preview kheader (str): Key in :class:`api.results`.metadata[``k``] to use as the header klink (str): Key in ...
3.545722
3.509828
1.010227
data = '\n'.join(self.links) with open(file_path, 'w') as out_file: out_file.write(data)
def save_links(self, file_path)
Saves a text file of the search result links. Saves a text file of the search result links, where each link is saved in a new line. An example is provided below:: http://www.google.ca http://www.gmail.com Args: file_path (str): Path to the text file to save links ...
2.946634
3.266424
0.902098
data = self.metadata with open(file_path, 'w') as out_file: json.dump(data, out_file)
def save_metadata(self, file_path)
Saves a json file of the search result metadata. Saves a json file of the search result metadata from :class:`api.results`.metadata. Args: file_path (str): Path to the json file to save metadata to.
3.759181
4.467425
0.841465
try: ang, lflam = np.loadtxt(path, usecols=(0,1)).T except ValueError: # In some files, the numbers in the first columns fill up the # whole 12-character column width, and are given in exponential # notation with a 'D' character, so we must be more careful: with open...
def load_spectrum(path, smoothing=181, DF=-8.)
Load a Phoenix model atmosphere spectrum. path : string The file path to load. smoothing : integer Smoothing to apply. If None, do not smooth. If an integer, smooth with a Hamming window. Otherwise, the variable is assumed to be a different smoothing window, and the data will be convolv...
4.522457
3.998437
1.131056
return np.where ((spt >= 0) & (spt <= 10), 1.53 + 0.148 * spt - 0.0105 * spt**2, np.nan)
def bcj_from_spt (spt)
Calculate a bolometric correction constant for a J band magnitude based on a spectral type, using the fit of Wilking+ (1999AJ....117..469W). spt - Numerical spectral type. M0=0, M9=9, L0=10, ... Returns: the correction `bcj` such that `m_bol = j_abs + bcj`, or NaN if `spt` is out of range. Valid ...
4.567321
4.236449
1.078101
# NOTE: the way np.piecewise() is implemented, the last 'true' value in # the condition list is the one that takes precedence. This motivates the # construction of our condition list. # # XXX: I've restructured the implementation; this needs testing! spt = np.asfarray (spt) # we crash wit...
def bck_from_spt (spt)
Calculate a bolometric correction constant for a J band magnitude based on a spectral type, using the fits of Wilking+ (1999AJ....117..469W), Dahn+ (2002AJ....124.1170D), and Nakajima+ (2004ApJ...607..499N). spt - Numerical spectral type. M0=0, M9=9, L0=10, ... Returns: the correction `bck` such that ...
5.928074
4.748199
1.248489
bcj = bcj_from_spt (sptnum) bck = bck_from_spt (sptnum) n = np.zeros (sptnum.shape, dtype=np.int) app_mbol = np.zeros (sptnum.shape) w = np.isfinite (bcj) & np.isfinite (jmag) app_mbol[w] += jmag[w] + bcj[w] n[w] += 1 w = np.isfinite (bck) & np.isfinite (kmag) app_mbol[w] += ...
def lbol_from_spt_dist_mag (sptnum, dist_pc, jmag, kmag, format='cgs')
Estimate a UCD's bolometric luminosity given some basic parameters. sptnum: the spectral type as a number; 8 -> M8; 10 -> L0 ; 20 -> T0 Valid values range between 0 and 30, ie M0 to Y0. dist_pc: distance to the object in parsecs jmag: object's J-band magnitude or NaN (*not* None) if unavailable k...
2.548094
2.645882
0.963041
j_abs = np.asfarray (j_abs) return np.piecewise (j_abs, [j_abs > 11, j_abs <= 11, j_abs < 5.5], [0.1 * cgs.msun, _delfosse_mass_from_j_helper, np.nan])
def mass_from_j (j_abs)
Estimate mass in cgs from absolute J magnitude, using the relationship of Delfosse+ (2000A&A...364..217D). j_abs - The absolute J magnitude. Returns: the estimated mass in grams. If j_abs > 11, a fixed result of 0.1 Msun is returned. Values of j_abs < 5.5 are illegal and get NaN. There is a disco...
5.598752
3.609679
1.551039
mdata, rdata = [], [] for line in tablelines: a = line.strip ().split () thismetallicity = float (a[0]) if thismetallicity != metallicity: continue thisheliumfrac = float (a[1]) if thisheliumfrac != heliumfrac: continue thisage = f...
def load_bcah98_mass_radius (tablelines, metallicity=0, heliumfrac=0.275, age_gyr=5., age_tol=0.05)
Load mass and radius from the main data table for the famous models of Baraffe+ (1998A&A...337..403B). tablelines An iterable yielding lines from the table data file. I've named the file '1998A&A...337..403B_tbl1-3.dat' in some repositories (it's about 150K, not too bad). metallicity ...
3.316305
3.391474
0.977836
from scipy.interpolate import UnivariateSpline m, r = load_bcah98_mass_radius (*args, **kwargs) spl = UnivariateSpline (m, r, s=1) # This allows us to do range-checking with either scalars or vectors with # minimal gymnastics. @numutil.broadcastize (1) def interp (mass_g): if n...
def mk_radius_from_mass_bcah98 (*args, **kwargs)
Create a function that maps (sub)stellar mass to radius, based on the famous models of Baraffe+ (1998A&A...337..403B). tablelines An iterable yielding lines from the table data file. I've named the file '1998A&A...337..403B_tbl1-3.dat' in some repositories (it's about 150K, not too bad). ...
5.221108
4.848923
1.076756
m = mass_g / cgs.msun return np.piecewise (m, [m < 1.3, m < 0.82, m < 0.65, m < 0.1], [lambda x: 61.7 - 44.7 * x, 25., lambda x...
def tauc_from_mass (mass_g)
Estimate the convective turnover time from mass, using the method described in Cook+ (2014ApJ...785...10C). mass_g - UCD mass in grams. Returns: the convective turnover timescale in seconds. Masses larger than 1.3 Msun are out of range and yield NaN. If the mass is <0.1 Msun, the turnover time is...
4.898816
4.682639
1.046166
return [func(i, fixed_arg, x) for i, x in enumerate(var_arg_iter)]
def serial_ppmap(func, fixed_arg, var_arg_iter)
A serial implementation of the "partially-pickling map" function returned by the :meth:`ParallelHelper.get_ppmap` interface. Its arguments are: *func* A callable taking three arguments and returning a Pickle-able value. *fixed_arg* Any value, even one that is not pickle-able. *var_arg_iter*...
4.003262
2.690958
1.487672
while True: i, var_arg = in_queue.get() if i is None: break out_queue.put((i, func(i, fixed_arg, var_arg)))
def multiprocessing_ppmap_worker(in_queue, out_queue, func, fixed_arg)
Worker for the :mod:`multiprocessing` ppmap implementation. Strongly derived from code posted on StackExchange by "klaus se": `<http://stackoverflow.com/a/16071616/3760486>`_.
2.709494
3.209875
0.844112
if parallel_arg is True: # note: (True == 1) is True return MultiprocessingPoolHelper(**kwargs) if parallel_arg is False or parallel_arg == 1: return SerialHelper(**kwargs) if parallel_arg > 0 and parallel_arg < 1: from multiprocessing import cpu_count n = int(round(pa...
def make_parallel_helper(parallel_arg, **kwargs)
Return a :class:`ParallelHelper` object that can be used for easy parallelization of computations. *parallel_arg* is an object that lets the caller easily specify the kind of parallelization they are interested in. Allowed values are: False Serial processing only. True Parallel processi...
2.754309
2.673399
1.030265
# The key magic is that we must call r.get() with a timeout, because a # Condition.wait() without a timeout swallows KeyboardInterrupts. r = self.map_async(func, iterable, chunksize) while True: try: return r.get(self.wait_timeout) except...
def map(self, func, iterable, chunksize=None)
Equivalent of `map` built-in, without swallowing KeyboardInterrupt. func The function to apply to the items. iterable An iterable of items that will have `func` applied to them.
6.162252
7.009767
0.879095
n_procs = self.pool_kwargs.get('processes') if n_procs is None: # Logic copied from multiprocessing.pool.Pool.__init__() try: from multiprocessing import cpu_count n_procs = cpu_count() except NotImplementedError: ...
def _ppmap(self, func, fixed_arg, var_arg_iter)
The multiprocessing implementation of the partially-Pickling "ppmap" function. This doesn't use a Pool like map() does, because the whole problem is that Pool chokes on un-Pickle-able values. Strongly derived from code posted on StackExchange by "klaus se": `<http://stackoverflow.com/a/1...
2.174127
2.111204
1.029804
tol = 1e-6 origN = N try: N = int (N) assert N == origN except Exception: raise ValueError ('N must be an integer') CL = float (CL) if CL <= 0. or CL >= 1.: raise ValueError ('CL must be between 0 and 1, noninclusive') B = float (B) if B < 0: ...
def kbn_conf (N, B, CL)
Given a (integer) number of observed Poisson events `N` and a (real) expected number of background events `B` and a confidence limit `CL` (between 0 and 1), return the confidence interval on the source event rate. Returns: (Smin, Smax) This interval is calculated using the Bayesian formalism of Kr...
4.848662
4.483034
1.081558
times = np.asarray (times) tstarts = np.asarray (tstarts) tstops = np.asarray (tstops) nevents = times.size if nevents < 1: raise ValueError ('must be given at least 1 event') info = tt_bblock (tstarts, tstops, times, p0) # Now bootstrap resample to assess uncertainties on th...
def bs_tt_bblock (times, tstarts, tstops, p0=0.05, nbootstrap=512)
Bayesian Blocks for time-tagged events with bootstrapping uncertainty assessment. THE UNCERTAINTIES ARE NOT VERY GOOD! Arguments: tstarts - Array of input bin start times. tstops - Array of input bin stop times. times - Array of event arrival times. p0=0.05 - Probabil...
3.49498
3.323804
1.0515
return _fmtsexagesimal (radians * R2H, norm, 24, seps, precision=precision)
def fmthours (radians, norm='wrap', precision=3, seps='::')
Format an angle as sexagesimal hours in a string. Arguments are: radians The angle, in radians. norm (default "wrap") The normalization mode, used for angles outside of the standard range of 0 to 2π. If "none", the value is formatted ignoring any potential problems. If "wrap", it i...
10.728703
36.339359
0.295236
return _fmtsexagesimal (radians * R2D, norm, 360, seps, precision=precision)
def fmtdeglon (radians, norm='wrap', precision=2, seps='::')
Format a longitudinal angle as sexagesimal degrees in a string. Arguments are: radians The angle, in radians. norm (default "wrap") The normalization mode, used for angles outside of the standard range of 0 to 2π. If "none", the value is formatted ignoring any potential problems. I...
8.521813
28.035955
0.30396
if norm == 'none': pass elif norm == 'raise': if radians > halfpi or radians < -halfpi: raise ValueError ('illegal latitude of %f radians' % radians) elif norm == 'wrap': radians = angcen (radians) if radians > halfpi: radians = pi - radians ...
def fmtdeglat (radians, norm='raise', precision=2, seps='::')
Format a latitudinal angle as sexagesimal degrees in a string. Arguments are: radians The angle, in radians. norm (default "raise") The normalization mode, used for angles outside of the standard range of -π/2 to π/2. If "none", the value is formatted ignoring any potential problem...
2.857816
2.752572
1.038235
return (fmthours (rarad, precision=precision + 1, seps=raseps) + text_type (intersep) + fmtdeglat (decrad, precision=precision, seps=decseps))
def fmtradec (rarad, decrad, precision=2, raseps='::', decseps='::', intersep=' ')
Format equatorial coordinates in a single sexagesimal string. Returns a string of the RA/lon coordinate, formatted as sexagesimal hours, then *intersep*, then the Dec/lat coordinate, formatted as degrees. This yields something like "12:34:56.78 -01:23:45.6". Arguments are: rarad The right ascens...
6.553731
12.026397
0.544946
hr = _parsesexagesimal (hrstr, 'hours', False) if hr >= 24: raise ValueError ('illegal hour specification: ' + hrstr) return hr * H2R
def parsehours (hrstr)
Parse a string formatted as sexagesimal hours into an angle. This function converts a textual representation of an angle, measured in hours, into a floating point value measured in radians. The format of *hrstr* is very limited: it may not have leading or trailing whitespace, and the components of the ...
7.466056
8.598543
0.868293
deg = _parsesexagesimal (latstr, 'latitude', True) if abs (deg) > 90: raise ValueError ('illegal latitude specification: ' + latstr) return deg * D2R
def parsedeglat (latstr)
Parse a latitude formatted as sexagesimal degrees into an angle. This function converts a textual representation of a latitude, measured in degrees, into a floating point value measured in radians. The format of *latstr* is very limited: it may not have leading or trailing whitespace, and the component...
5.945386
6.516129
0.912411
cd = np.cos (lon2 - lon1) sd = np.sin (lon2 - lon1) c2 = np.cos (lat2) c1 = np.cos (lat1) s2 = np.sin (lat2) s1 = np.sin (lat1) a = np.sqrt ((c2 * sd)**2 + (c1 * s2 - s1 * c2 * cd)**2) b = s1 * s2 + c1 * c2 * cd return np.arctan2 (a, b)
def sphdist (lat1, lon1, lat2, lon2)
Calculate the distance between two locations on a sphere. lat1 The latitude of the first location. lon1 The longitude of the first location. lat2 The latitude of the second location. lon2 The longitude of the second location. Returns the separation in radians. All arguments...
1.838113
1.867982
0.98401
# cross product on outer axis: ocross = lambda a, b: np.cross (a, b, axisa=0, axisb=0, axisc=0) # if args have shape S, this has shape (3, S) v1 = np.asarray ([np.cos (lat1) * np.cos (lon1), np.cos (lat1) * np.sin (lon1), np.sin (lat1)]) v2 = np.asa...
def sphbear (lat1, lon1, lat2, lon2, tol=1e-15)
Calculate the bearing between two locations on a sphere. lat1 The latitude of the first location. lon1 The longitude of the first location. lat2 The latitude of the second location. lon2 The longitude of the second location. tol Tolerance for checking proximity to pole...
3.0072
3.136669
0.958724
if rmax is not None and np.abs (r) > rmax: raise ValueError ('sphofs radius value %f is too big for ' 'our approximation' % r) lat2 = lat1 + r * np.cos (pa) lon2 = lon1 + r * np.sin (pa) / np.cos (lat2) if tol is not None: s = sphdist (lat1, lon1, lat2, l...
def sphofs (lat1, lon1, r, pa, tol=1e-2, rmax=None)
Offset from one location on the sphere to another. This function is given a start location, expressed as a latitude and longitude, a distance to offset, and a direction to offset (expressed as a bearing, AKA position angle). It uses these to compute a final location. This function mirrors :func:`sphdis...
2.92696
3.080451
0.950173
return -np.arctan2 (-np.sin (hourangle), np.cos (declination) * np.tan (latitude) - np.sin (declination) * np.cos (hourangle))
def parang (hourangle, declination, latitude)
Calculate the parallactic angle of a sky position. This computes the parallactic angle of a sky position expressed in terms of an hour angle and declination. Arguments: hourangle The hour angle of the location on the sky. declination The declination of the location on the sky. latitude...
2.597759
3.700527
0.701997
c1 = np.cos (pa1) s1 = np.sin (pa1) c2 = np.cos (pa2) s2 = np.sin (pa2) a = (maj1*c1)**2 + (min1*s1)**2 + (maj2*c2)**2 + (min2*s2)**2 b = (maj1*s1)**2 + (min1*c1)**2 + (maj2*s2)**2 + (min2*c2)**2 g = 2 * ((min1**2 - maj1**2) * s1 * c1 + (min2**2 - maj2**2) * s2 * c2) s = a + b ...
def gaussian_convolve (maj1, min1, pa1, maj2, min2, pa2)
Convolve two Gaussians analytically. Given the shapes of two 2-dimensional Gaussians, this function returns the shape of their convolution. Arguments: maj1 Major axis of input Gaussian 1. min1 Minor axis of input Gaussian 1. pa1 Orientation angle of input Gaussian 1, in radi...
2.297995
2.271063
1.011859
# I've added extra code to ensure ``smaj >= bmaj``, ``smin >= bmin``, and # increased the coefficient in front of "limit" from 0.1 to 0.5. Feel a # little wary about that first change. from numpy import cos, sin, sqrt, min, abs, arctan2 if smaj < bmaj: smaj = bmaj if smin < bmin: ...
def gaussian_deconvolve (smaj, smin, spa, bmaj, bmin, bpa)
Deconvolve two Gaussians analytically. Given the shapes of 2-dimensional “source” and “beam” Gaussians, this returns a deconvolved “result” Gaussian such that the convolution of “beam” and “result” is “source”. Arguments: smaj Major axis of source Gaussian. smin Minor axis of sour...
3.100894
2.851139
1.087598
import os.path from astropy.config import paths from skyfield.api import Loader cache_dir = os.path.join(paths.get_cache_dir(), 'pwkit') loader = Loader(cache_dir) planets = loader('de421.bsp') ts = loader.timescale() return planets, ts
def load_skyfield_data()
Load data files used in Skyfield. This will download files from the internet if they haven't been downloaded before. Skyfield downloads files to the current directory by default, which is not ideal. Here we abuse astropy and use its cache directory to cache the data files per-user. If we start download...
3.522446
2.968994
1.186411
import codecs try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen postdata = b'''-mime=csv -source=2MASS -out=_q,JD -c=%.6f %.6f -c.eq=J2000''' % (tmra * R2D, tmdec * R2D) jd = None for line in codecs.getreader('utf-8')(urlopen (_vizurl,...
def get_2mass_epoch (tmra, tmdec, debug=False)
Given a 2MASS position, look up the epoch when it was observed. This function uses the CDS Vizier web service to look up information in the 2MASS point source database. Arguments are: tmra The source's J2000 right ascension, in radians. tmdec The source's J2000 declination, in radians. ...
5.722379
4.985487
1.147808
import codecs try: from urllib.parse import quote except ImportError: from urllib import quote try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen s = '\\n'.join ('%s %%%s' % (i, i) for i in items) s = '''output consol...
def get_simbad_astrometry_info (ident, items=_simbaditems, debug=False)
Fetch astrometric information from the Simbad web service. Given the name of a source as known to the CDS Simbad service, this function looks up its positional information and returns it in a dictionary. In most cases you should use an :class:`AstrometryInfo` object and its :meth:`~AstrometryInfo.fill_...
4.154039
4.371269
0.950305
import sys if self.ra is None: raise ValueError ('AstrometryInfo missing "ra"') if self.dec is None: raise ValueError ('AstrometryInfo missing "dec"') if self._partial_info (self.promo_ra, self.promo_dec): raise ValueError ('partial proper-m...
def verify (self, complain=True)
Validate that the attributes are self-consistent. This function does some basic checks of the object attributes to ensure that astrometric calculations can legally be performed. If the *complain* keyword is true, messages may be printed to :data:`sys.stderr` if non-fatal issues are enco...
2.38188
2.33008
1.022231
import sys self.verify(complain=complain) planets, ts = load_skyfield_data() # might download stuff from the internet earth = planets['earth'] t = ts.tdb(jd = mjd + 2400000.5) # "Best" position. The implementation here is a bit weird to keep # parallel...
def predict_without_uncertainties(self, mjd, complain=True)
Predict the object position at a given MJD. The return value is a tuple ``(ra, dec)``, in radians, giving the predicted position of the object at *mjd*. Unlike :meth:`predict`, the astrometric uncertainties are ignored. This function is therefore deterministic but potentially misleading...
4.802573
4.61676
1.040247
from . import ellipses bestra, bestdec, maj, min, pa = ptup f = ellipses.sigmascale (1) maj *= R2A min *= R2A pa *= R2D print_ ('position =', fmtradec (bestra, bestdec, precision=precision)) print_ ('err(1σ) = %.*f" × %.*f" @ %.0f°' % (precisio...
def print_prediction (self, ptup, precision=2)
Print a summary of a predicted position. The argument *ptup* is a tuple returned by :meth:`predict`. It is printed to :data:`sys.stdout` in a reasonable format that uses Unicode characters.
10.966995
11.026648
0.99459
info = get_simbad_astrometry_info (ident, debug=debug) posref = 'unknown' for k, v in six.iteritems (info): if '~' in v: continue # no info if k == 'COO(d;A)': self.ra = float (v) * D2R elif k == 'COO(d;D)': ...
def fill_from_simbad (self, ident, debug=False)
Fill in astrometric information using the Simbad web service. This uses the CDS Simbad web service to look up astrometric information for the source name *ident* and fills in attributes appropriately. Values from Simbad are not always reliable. Returns *self*.
2.922219
2.959308
0.987467
from astroquery.vizier import Vizier import numpy.ma.core as ma_core # We should match exactly one table and one row within that table, but # for robustness we ignore additional results if they happen to # appear. Strangely, querying for an invalid identifier yields a t...
def fill_from_allwise (self, ident, catalog_ident='II/328/allwise')
Fill in astrometric information from the AllWISE catalog using Astroquery. This uses the :mod:`astroquery` module to query the AllWISE (2013wise.rept....1C) source catalog through the Vizier (2000A&AS..143...23O) web service. It then fills in the instance with the relevant information. ...
3.178209
2.85853
1.111833
if six.PY3: return enc = sys.stdin.encoding or 'utf-8' sys.stdin = codecs.getreader (enc) (sys.stdin) enc = sys.stdout.encoding or enc sys.stdout = codecs.getwriter (enc) (sys.stdout) enc = sys.stderr.encoding or enc sys.stderr = codecs.getwriter (enc) (sys.stderr)
def unicode_stdio ()
Make sure that the standard I/O streams accept Unicode. In Python 2, the standard I/O streams accept bytes, not Unicode characters. This means that in principle every Unicode string that we want to output should be encoded to utf-8 before print()ing. But Python 2.X has a hack where, if the output is a ...
2.025075
2.214183
0.914592
import signal try: signal.signal (signal.SIGUSR1, _print_backtrace_signal_handler) except Exception as e: warn ('failed to set up Python backtraces on SIGUSR1: %s', e)
def backtrace_on_usr1 ()
Install a signal handler such that this program prints a Python traceback upon receipt of SIGUSR1. This could be useful for checking that long-running programs are behaving properly, or for discovering where an infinite loop is occurring. Note, however, that the Python interpreter does not invoke Pytho...
5.751861
5.016479
1.146593
if not len (args): raise SystemExit ('error: ' + text_type (fmt)) raise SystemExit ('error: ' + (fmt % args))
def die (fmt, *args)
Raise a :exc:`SystemExit` exception with a formatted error message. :arg str fmt: a format string :arg args: arguments to the format string If *args* is empty, a :exc:`SystemExit` exception is raised with the argument ``'error: ' + str (fmt)``. Otherwise, the string component is ``fmt % args``. If...
5.046959
5.58272
0.904032
import os, struct from .. import Holder payload = struct.Struct ('L') info = Holder () readfd, writefd = os.pipe () pid1 = os.fork () if pid1 > 0: info.whoami = 'original' info.pipe = os.fdopen (readfd, 'rb') os.close (writefd) retcode = os.waitpid (pi...
def fork_detached_process ()
Fork this process, creating a subprocess detached from the current context. Returns a :class:`pwkit.Holder` instance with information about what happened. Its fields are: whoami A string, either "original" or "forked" depending on which process we are. pipe An open binary file descriptor. ...
3.822689
2.977947
1.283666
if argv is None: from sys import argv if len (ident) == 1: ident = '-' + ident else: ident = '--' + ident found = ident in argv if found: argv.remove (ident) return found
def pop_option (ident, argv=None)
A lame routine for grabbing command-line arguments. Returns a boolean indicating whether the option was present. If it was, it's removed from the argument string. Because of the lame behavior, options can't be combined, and non-boolean options aren't supported. Operates on sys.argv by default. Note...
3.384403
3.261364
1.037726
if stream is None: from sys import stdout as stream if not short: print ('Usage:', docstring.strip (), file=stream) else: intext = False for l in docstring.splitlines (): if intext: if not len (l): break pr...
def show_usage (docstring, short, stream, exitcode)
Print program usage information and exit. :arg str docstring: the program help text This function just prints *docstring* and exits. In most cases, the function :func:`check_usage` should be used: it automatically checks :data:`sys.argv` for a sole "-h" or "--help" argument and invokes this functi...
4.055137
4.621793
0.877395
if argv is None: from sys import argv if len (argv) == 1 and usageifnoargs: show_usage (docstring, (usageifnoargs != 'long'), None, 0) if len (argv) == 2 and argv[1] in ('-h', '--help'): show_usage (docstring, False, None, 0)
def check_usage (docstring, argv=None, usageifnoargs=False)
Check if the program has been run with a --help argument; if so, print usage information and exit. :arg str docstring: the program help text :arg argv: the program arguments; taken as :data:`sys.argv` if given as :const:`None` (the default). (Note that this implies ``argv[0]`` should be the...
3.1806
3.433079
0.926457
intext = False if len (rest) == 0: detail = 'invalid command-line arguments' elif len (rest) == 1: detail = rest[0] else: detail = rest[0] % tuple (rest[1:]) print ('error:', detail, '\n', file=sys.stderr) # extra NL show_usage (docstring, True, sys.stderr, 1)
def wrong_usage (docstring, *rest)
Print a message indicating invalid command-line arguments and exit with an error code. :arg str docstring: the program help text :arg rest: an optional specific error message This function is intended for small programs launched from the command line. The intention is for the program help informat...
5.599674
4.628396
1.209852
self.inner_excepthook (etype, evalue, etb) if issubclass (etype, KeyboardInterrupt): # Don't try this at home, kids. On some systems os.kill (0, ...) # signals our entire progress group, which is not what we want, # so we use os.getpid (). signal...
def excepthook (self, etype, evalue, etb)
Handle an uncaught exception. We always forward the exception on to whatever `sys.excepthook` was present upon setup. However, if the exception is a KeyboardInterrupt, we additionally kill ourselves with an uncaught SIGINT, so that invoking programs know what happened.
5.772751
5.56314
1.037678
return cgs.e * b / (2 * cgs.pi * cgs.me * cgs.c)
def calc_nu_b(b)
Calculate the cyclotron frequency in Hz given a magnetic field strength in Gauss. This is in cycles per second not radians per second; i.e. there is a 2π in the denominator: ν_B = e B / (2π m_e c)
6.793592
6.5016
1.044911
omega = (width / dist)**2 depth = width * elongation tau = depth * kappa sourcefn = eta / kappa return 2 * omega * sourcefn * (1 - np.exp(-tau))
def calc_snu(eta, kappa, width, elongation, dist)
Calculate the flux density S_ν given a simple physical configuration. This is basic radiative transfer as per Dulk (1985) equations 5, 6, and 11. eta The emissivity, in units of ``erg s^-1 Hz^-1 cm^-3 sr^-1``. kappa The absorption coefficient, in units of ``cm^-1``. width The charact...
7.405569
6.623497
1.118075
return 9.78e-3 * ne**2 * hz**-2 * t**-1.5 * (24.5 + np.log(t) - np.log(hz))
def calc_freefree_kappa(ne, t, hz)
Dulk (1985) eq 20, assuming pure hydrogen.
5.617217
5.386309
1.04287
kappa = calc_freefree_kappa(ne, t, hz) return kappa * cgs.k * t * hz**2 / cgs.c**2
def calc_freefree_eta(ne, t, hz)
Dulk (1985) equations 7 and 20, assuming pure hydrogen.
4.52763
4.605893
0.983008
hz = ghz * 1e9 eta = calc_freefree_eta(ne, t, hz) kappa = calc_freefree_kappa(ne, t, hz) snu = calc_snu(eta, kappa, width, elongation, dist) ujy = snu * cgs.jypercgs * 1e6 return ujy
def calc_freefree_snu_ujy(ne, t, width, elongation, dist, ghz)
Calculate a flux density from pure free-free emission.
3.427132
3.4811
0.984497
s = nu / calc_nu_b(b) return (b * ne * 3.3e-24 * 10**(-0.52 * delta) * sinth**(-0.43 + 0.65 * delta) * s**(1.22 - 0.90 * delta))
def calc_gs_eta(b, ne, delta, sinth, nu)
Calculate the gyrosynchrotron emission coefficient η_ν. This is Dulk (1985) equation 35, which is a fitting function assuming a power-law electron population. Arguments are: b Magnetic field strength in Gauss ne The density of electrons per cubic centimeter with energies greater than 10 ke...
7.50943
6.83049
1.099398
s = nu / calc_nu_b(b) return (ne / b * 1.4e-9 * 10**(-0.22 * delta) * sinth**(-0.09 + 0.72 * delta) * s**(-1.30 - 0.98 * delta))
def calc_gs_kappa(b, ne, delta, sinth, nu)
Calculate the gyrosynchrotron absorption coefficient κ_ν. This is Dulk (1985) equation 36, which is a fitting function assuming a power-law electron population. Arguments are: b Magnetic field strength in Gauss ne The density of electrons per cubic centimeter with energies greater than 10 ...
6.941616
6.80795
1.019634
coldens = ne * depth return (2.72e3 * 10**(0.27 * delta) * sinth**(0.41 + 0.03 * delta) * coldens**(0.32 - 0.03 * delta) * b**(0.68 + 0.03 * delta))
def calc_gs_nu_pk(b, ne, delta, sinth, depth)
Calculate the frequency of peak synchrotron emission, ν_pk. This is Dulk (1985) equation 39, which is a fitting function assuming a power-law electron population. Arguments are: b Magnetic field strength in Gauss ne The density of electrons per cubic centimeter with energies greater than 1...
5.362511
6.268718
0.85544
hz = ghz * 1e9 eta = calc_gs_eta(b, ne, delta, sinth, hz) kappa = calc_gs_kappa(b, ne, delta, sinth, hz) snu = calc_snu(eta, kappa, width, elongation, dist) ujy = snu * cgs.jypercgs * 1e6 return ujy
def calc_gs_snu_ujy(b, ne, delta, sinth, width, elongation, dist, ghz)
Calculate a flux density from pure gyrosynchrotron emission. This combines Dulk (1985) equations 35 and 36, which are fitting functions assuming a power-law electron population, with standard radiative transfer through a uniform medium. Arguments are: b Magnetic field strength in Gauss ne ...
3.167661
3.717157
0.852173
s = nu / calc_nu_b(b) return (b * ne * 8.6e-24 * (delta - 1) * sinth * (0.175 * s / (E0**2 * sinth))**(0.5 * (1 - delta)))
def calc_synch_eta(b, ne, delta, sinth, nu, E0=1.)
Calculate the relativistic synchrotron emission coefficient η_ν. This is Dulk (1985) equation 40, which is an approximation assuming a power-law electron population. Arguments are: b Magnetic field strength in Gauss ne The density of electrons per cubic centimeter with energies greater tha...
9.436106
9.524309
0.990739
coldens = ne * depth return (3.2e7 * sinth * E0**((2 * delta - 2) / (delta + 4)) * (8.7e-12 * (delta - 1) * coldens / sinth)**(2./(delta + 4)) * b**((delta + 2) / (delta + 4)))
def calc_synch_nu_pk(b, ne, delta, sinth, depth, E0=1.)
Calculate the frequency of peak synchrotron emission, ν_pk. This is Dulk (1985) equation 43, which is a fitting function assuming a power-law electron population. Arguments are: b Magnetic field strength in Gauss ne The density of electrons per cubic centimeter with energies greater than 1...
6.144576
6.723138
0.913945
hz = ghz * 1e9 eta = calc_synch_eta(b, ne, delta, sinth, hz, E0=E0) kappa = calc_synch_kappa(b, ne, delta, sinth, hz, E0=E0) snu = calc_snu(eta, kappa, width, elongation, dist) ujy = snu * cgs.jypercgs * 1e6 return ujy
def calc_synch_snu_ujy(b, ne, delta, sinth, width, elongation, dist, ghz, E0=1.)
Calculate a flux density from pure gyrosynchrotron emission. This combines Dulk (1985) equations 40 and 41, which are fitting functions assuming a power-law electron population, with standard radiative transfer through a uniform medium. Arguments are: b Magnetic field strength in Gauss ne ...
2.836403
3.319932
0.854356
doc_args = dict( bulk = '\n'.join(l for l in doc.splitlines() if not l.startswith ('casatask ')), taskname = taskname ) return _kwcli_cfg_class_doc_template % doc_args
def makecfgdoc(taskname, doc)
In Python 2.x you can't alter the __doc__ of a class after you define it, so we need to provide a function that does the munging when we define each class. This is that function.
10.337546
11.371531
0.909072
tb = util.tools.table() cb = util.tools.calibrater() # cb.open() will create the tables if they're not present, so # if that's the case, we don't actually need to run initcalset() tb.open(b(vis), nomodify=False) colnames = tb.colnames() needinit = ('MODEL_DATA' in colnames) or('CORREC...
def clearcal(vis, weightonly=False)
Fill the imaging and calibration columns (``MODEL_DATA``, ``CORRECTED_DATA``, ``IMAGING_WEIGHT``) of each measurement set with default values, creating the columns if necessary. vis (string) Path to the input measurement set weightonly (boolean) If true, just create the ``IMAGING_WEIGHT`` c...
7.415844
6.565861
1.129455
tb = util.tools.table() ms = util.tools.ms() if os.path.exists(outvis): raise RuntimeError('output "%s" already exists' % outvis) for invis in invises: if not os.path.isdir(invis): raise RuntimeError('input "%s" does not exist' % invis) tb.open(b(invises[0])) ...
def concat(invises, outvis, timesort=False)
Concatenate visibility measurement sets. invises (list of str) Paths to the input measurement sets outvis (str) Path to the output measurement set. timesort (boolean) If true, sort the output in time after concatenation. Example:: from pwkit.environments.casa import tasks ...
4.195786
4.319218
0.971423
wantremove = 'MODEL_DATA CORRECTED_DATA'.split() tb = util.tools.table() tb.open(b(mspath), nomodify=False) cols = frozenset(tb.colnames()) toremove = [b(c) for c in wantremove if c in cols] if len(toremove): tb.removecols(toremove) tb.close() # We want to return a `str` ty...
def delcal(mspath)
Delete the ``MODEL_DATA`` and ``CORRECTED_DATA`` columns from a measurement set. mspath (str) The path to the MS to modify Example:: from pwkit.environments.casa import tasks tasks.delcal('dataset.ms')
5.579673
5.107043
1.092545
check_usage(delmod_doc, argv, usageifnoargs=True) if alter_logger: util.logger() cb = util.tools.calibrater() for mspath in argv[1:]: cb.open(b(mspath), addcorr=False, addmodel=False) cb.delmod(otf=True, scr=False) cb.close()
def delmod_cli(argv, alter_logger=True)
Command-line access to ``delmod`` functionality. The ``delmod`` task deletes "on-the-fly" model information from a Measurement Set. It is so easy to implement that a standalone function is essentially unnecessary. Just write:: from pwkit.environments.casa import util cb = util.tools.calibrater...
11.577978
4.64001
2.495248
tb = util.tools.table() tb.open(b(os.path.join(calpath, 'ANTENNA'))) antnames = tb.getcol(b'NAME') tb.close() tb.open(b(calpath)) try: t = tb.getkeyword(b'VisCal') except RuntimeError: raise PKError('no "VisCal" keyword in %s; it doesn\'t seem to be a ' ...
def extractbpflags(calpath, deststream)
Make a flags file out of a bandpass calibration table calpath (str) The path to the bandpass calibration table deststream (stream-like object, e.g. an opened file) Where to write the flags data Below is documentation written for the command-line interface to this functionality:
4.364546
4.420551
0.987331
check_usage(flagmanager_doc, argv, usageifnoargs=True) if len(argv) < 3: wrong_usage(flagmanager_doc, 'expect at least a mode and an MS name') mode = argv[1] ms = argv[2] if alter_logger: if mode == 'list': util.logger('info') elif mode == 'delete': ...
def flagmanager_cli(argv, alter_logger=True)
Command-line access to ``flagmanager`` functionality. The ``flagmanager`` task manages tables of flags associated with measurement sets. Its features are easy to implement that a standalone library function is essentially unnecessary. See the source code to this function for the tool calls that impleme...
3.797708
3.902574
0.973129
ia = util.tools.image() ia.open(b(mspath)) ia.tofits(outfile=b(fitspath), velocity=velocity, optical=optical, bitpix=bitpix, minpix=minpix, maxpix=maxpix, overwrite=overwrite, dropstokes=dropstokes, stokeslast=stokeslast, history=history, **kwargs) ia.close()
def image2fits(mspath, fitspath, velocity=False, optical=False, bitpix=-32, minpix=0, maxpix=-1, overwrite=False, dropstokes=False, stokeslast=True, history=True, **kwargs)
Convert an image in MS format to FITS format. mspath (str) The path to the input MS. fitspath (str) The path to the output FITS file. velocity (boolean) (To be documented.) optical (boolean) (To be documented.) bitpix (integer) (To be documented.) minpix (integer) ...
2.598765
2.738043
0.949132
from .scripting import CasapyScript script = os.path.join(os.path.dirname(__file__), 'cscript_importalma.py') with CasapyScript(script, asdm=asdm, ms=ms) as cs: pass
def importalma(asdm, ms)
Convert an ALMA low-level ASDM dataset to Measurement Set format. asdm (str) The path to the input ASDM dataset. ms (str) The path to the output MS dataset. This implementation automatically infers the value of the "tbuff" parameter. Example:: from pwkit.environments.casa impor...
4.893788
5.577858
0.87736