code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
d = pickle.load(open(mergepkl))
ndist, imstd, flagfrac = plotnoisedist(noisepkl, plot_width=plot_width/2, plot_height=plot_height)
fluxscale = calcfluxscale(d, imstd, flagfrac)
logger.info('Median image noise is {0:.3} Jy.'.format(fluxscale*imstd))
ncum, imnoise = plotnoisecum(noisepkl, fluxsc... | def plotnoise(noisepkl, mergepkl, plot_width=950, plot_height=400) | Make two panel plot to summary noise analysis with estimated flux scale | 5.572264 | 5.220536 | 1.067374 |
# noise histogram
noises = read_noise(noisepkl)
imnoise = np.sort(fluxscale*noises[4])
frac = [float(count)/len(imnoise) for count in reversed(range(1, len(imnoise)+1))]
noiseplot = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="above",
x_axis_l... | def plotnoisecum(noisepkl, fluxscale=1, plot_width=450, plot_height=400) | Merged noise pkl converted to interactive cumulative histogram
noisepkl is standard noise pickle file.
fluxscale is scaling applied by gain calibrator. telcal solutions have fluxscale=1.
also returns corrected imnoise values if non-unity fluxscale provided | 4.387436 | 4.07978 | 1.07541 |
# useful functions and VLA parameters
sensitivity = lambda sefd, dt, bw, eta, nbl, npol: sefd/(eta*np.sqrt(nbl*2 * dt * bw * npol))
nbl = lambda nant: nant*(nant-1)/2
eta = {'L': 0.92, 'S': 0.92, 'C': 0.8, 'X': 0.8} # correlator efficiency
sefd = {'L': 420, 'S': 370, 'C': 310, 'X': 250} #... | def calcfluxscale(d, imstd_med, flagfrac_med) | Given state dict and noise properties, estimate flux scale at the VLA
imstd and flagfrac are expected to be median (typical) values from sample in merged noise pkl. | 4.364346 | 4.291529 | 1.016968 |
# get cands from pkl
if mergepkl:
logger.info('Reading {0}'.format(mergepkl))
loc, prop, d = read_candidates(mergepkl, returnstate=True)
elif d and cands:
logger.info('Using provided d/cands')
loc, prop = cands
# define columns to extract
if 'snr2' in d['featur... | def readdata(mergepkl=None, d=None, cands=None, sizerange=(2,70)) | Converts candidate data to dictionary for bokeh
Can take merged pkl file or d/cands as read separately.
cands is an optional (loc, prop) tuple of numpy arrays. | 3.108964 | 3.026103 | 1.027382 |
time = np.sort(data['time'])
ww = np.ones(len(time), dtype=bool) # initialize pass filter
if ignoret:
for (t0, t1) in ignoret:
ww = ww & np.where( (time < t0) | (time > t1), True, False )
bins = np.round(time[ww]).astype('int')
counts = np.bincount(bins)
high = np.wh... | def findhight(data, ignoret=None, threshold=20) | Find bad time ranges from distribution of candidates.
ignoret is list of tuples [(t0, t1), (t2, t3)] defining ranges to ignore.
threshold is made above std of candidate distribution in time.
Returns the time (in seconds) and counts for bins above threshold. | 3.917964 | 3.227544 | 1.213915 |
inds = []
for i in range(len(data['time'])):
snr = data['snrs'][i]
time = data['time'][i]
if (threshold >= 0 and snr > threshold):
if ignoret:
incl = [t0 for (t0, t1) in ignoret if np.round(time).astype(int) in range(t0,t1)]
logger.debug(... | def calcinds(data, threshold, ignoret=None) | Find indexes for data above (or below) given threshold. | 1.970018 | 1.987299 | 0.991305 |
if not inds:
inds = range(len(data['time']))
logger.info('No indices provided. Assuming all are valid.')
scans = set([data['scan'][i] for i in inds])
total = 0.
for scan in scans:
time = [data['time'][i] for i in inds if data['scan'][i] == scan]
total += max(time) ... | def calcontime(data, inds=None) | Given indices of good times, calculate total time per scan with indices. | 2.873187 | 2.538959 | 1.13164 |
if not inds: inds = range(len(snrs))
# define norm quantile functions
Z = lambda quan: np.sqrt(2)*erfinv( 2*quan - 1)
quan = lambda ntrials, i: (ntrials + 1/2. - i)/ntrials
# calc number of trials
npix = d['npixx']*d['npixy']
if d.has_key('goodintcount'):
nints = d['goodintc... | def normprob(d, snrs, inds=None, version=2) | Uses observed SNR distribution to calculate normal probability SNR
Uses state dict to calculate number of trials.
snrs is list of all snrs in distribution.
version used to toggle for tests. version 2 is fastest and returns zeros for filtered snr values.
Returns list of expected snr given each input val... | 2.629966 | 2.602763 | 1.010452 |
if inds:
smax = max([abs(values[i]) for i in inds])
smin = min([abs(values[i]) for i in inds])
else:
smax = max([abs(val) for val in values])
smin = min([abs(val) for val in values])
return [sizerange[0] + sizerange[1] * ((abs(val) - smin)/(smax - smin))**plaw for val i... | def calcsize(values, sizerange=(2,70), inds=None, plaw=3) | Use set of values to calculate symbol size.
values is a list of floats for candidate significance.
inds is an optional list of indexes to use to calculate symbol size.
Scaling of symbol size min max set by sizerange tuple (min, max).
plaw is powerlaw scaling of symbol size from values | 2.062937 | 1.87412 | 1.10075 |
lm = np.zeros(len(l), dtype='complex')
lm.real = l
lm.imag = m
red = 0.5*(1+np.cos(np.angle(lm)))
green = 0.5*(1+np.cos(np.angle(lm) + 2*3.14/3))
blue = 0.5*(1+np.cos(np.angle(lm) - 2*3.14/3))
amp = 256*np.abs(lm)/np.abs(lm).max()
return ["#%02x%02x%02x" % (np.floor(amp[i]*red[i]),... | def colorsat(l,m) | Returns color for given l,m
Designed to look like a color wheel that is more saturated in middle. | 2.22634 | 2.202479 | 1.010834 |
logger.info('Ignoring times from ignorestr {0}'.format(ignorestr))
ignoret = parseignoret(ignorestr)
thresh0 = d['sigma_image1']
thresh1 = d['sigma_plot']
plinds['cir'] = calcinds(data, thresh0, ignoret=ignoret) # positive cands
plinds['cro'] = calcinds(data, -1*thresh0, ignoret=ignoret)... | def filterdata(data, plinds, d, threshold, ignorestr) | Iteratively filter bad times and set indices for later plotting | 5.482558 | 5.447159 | 1.006499 |
plotdict = {'dmt': plotdmt, 'norm': plotnorm,
'loc': plotloc, 'stat': plotstat,
'all': plotall}
sizedict = {'dmt': [900,500], 'norm': [700, 700], 'loc': [700,700],
'stat': [700,700]}
sortinds = sorted(set(plinds['cir'] + plinds['cro'] + plinds['edg']))
... | def displayplot(data, plinds, plottype, scaling, fileroot, url_path='http://www.aoc.nrao.edu/~claw/plots') | Generate interactive plot | 3.568146 | 3.59432 | 0.992718 |
try:
ag = activegit.ActiveGit(agdir)
if version:
ag.set_version(version)
clf = ag.classifier
score = clf.predict_proba((np.nan_to_num(prop[:,statfeats])))[:,1] # take real score
return score
except:
logger.info('Failure when parsing activegit r... | def addclassifications(agdir, prop, version=None, statfeats = [0,4,5,6,7,8]) | Calculates real score probability of prop from an activegit repo.
version is string name of activegit tag.
Default agdir initialization will have latest tag, so version is optional.
statfeats set to work with alnotebook naming. | 6.871043 | 5.359008 | 1.282148 |
return lambda n, f: f.future_datetime(
end_date=end, tzinfo=get_timezone(),
) | def future_datetime(end='+30d') | Returns a ``datetime`` object in the future (that is, 1 second from now) up
to the specified ``end``. ``end`` can be a string, anotther datetime, or a
timedelta. If it's a string, it must start with `+`, followed by and integer
and a unit, Eg: ``'+30d'``. Defaults to `'+30d'`
Valid units are:
* ``'... | 11.247871 | 22.048294 | 0.510147 |
return lambda n, f: f.future_date(
end_date=end, tzinfo=get_timezone(),
) | def future_date(end='+30d') | Returns a ``date`` object in the future (that is, 1 day from now) up to
the specified ``end``. ``end`` can be a string, another date, or a
timedelta. If it's a string, it must start with `+`, followed by and integer
and a unit, Eg: ``'+30d'``. Defaults to `'+30d'`
Valid units are:
* ``'years'``, ``... | 11.309199 | 22.274424 | 0.507721 |
return lambda n, f: f.past_datetime(
start_date=start, tzinfo=get_timezone(),
) | def past_datetime(start='-30d') | Returns a ``datetime`` object in the past between 1 second ago and the
specified ``start``. ``start`` can be a string, another datetime, or a
timedelta. If it's a string, it must start with `-`, followed by and integer
and a unit, Eg: ``'-30d'``. Defaults to `'-30d'`
Valid units are:
* ``'years'``,... | 11.294714 | 20.69585 | 0.545748 |
return lambda n, f: f.past_date(
start_date=start, tzinfo=get_timezone(),
) | def past_date(start='-30d') | Returns a ``date`` object in the past between 1 day ago and the
specified ``start``. ``start`` can be a string, another date, or a
timedelta. If it's a string, it must start with `-`, followed by and integer
and a unit, Eg: ``'-30d'``. Defaults to `'-30d'`
Valid units are:
* ``'years'``, ``'y'``
... | 11.347692 | 20.095999 | 0.564674 |
emoticons_tuple = []
for emoticons, image in emoticons_list:
if isinstance(emoticons, basestring):
emoticons = [emoticons]
else:
emoticons = list(emoticons)
emoticons_tuple.append((emoticons, image))
return emoticons_tuple | def cast_to_list(emoticons_list) | Fix list of emoticons with a single name
to a list for easier future iterations,
and cast iterables to list. | 2.071569 | 2.047924 | 1.011546 |
emoticons_compiled = []
for emoticons, image in emoticons_list:
for emoticon in emoticons:
context = {
'name': emoticon,
'image': os.path.join(EMOTICONS_DIRECTORY, image),
'code': binascii.hexlify(emoticon.encode('utf-8'))}
emo... | def compile_emoticons(emoticons_list) | Compile a new list of emoticon tuples.
Each tuple contains a compiled regular expression
of the emoticon, and the html version of the emoticon. | 2.72488 | 2.843463 | 0.958296 |
'''Refetch instance data from the API.
'''
# There's no GET endpoint for steps, so get the parent guide and loop
# through its steps until we find the right one.
response = requests.get('%s/guides/%s' % (API_BASE_URL, self.guideid))
attributes = response.json()
for step ... | def refresh(self) | Refetch instance data from the API. | 5.11575 | 4.645338 | 1.101265 |
'''Update the step using the blob of json-parsed data directly from the
API.
'''
self.orderby = data['orderby']
self.revision = data['revisionid']
self.title = data['title']
self.lines = [Line(self.guideid, self.stepid, line['lineid'], data=line)
for line in... | def _update(self, data) | Update the step using the blob of json-parsed data directly from the
API. | 7.439952 | 4.488994 | 1.657376 |
filename = os.path.abspath(filename)
scans = ps.read_scans(filename, bdfdir=bdfdir)
logger.info('Scans, Target names:')
logger.info('%s' % str([(ss, scans[ss]['source']) for ss in scans]))
logger.info('Example pipeline:')
state = rt.set_pipeline(filename, scan, paramfile=paramfile, logfil... | def read(filename, paramfile, bdfdir, scan) | Simple parse and return metadata for pipeline for first scan | 8.097102 | 7.46217 | 1.085087 |
filename = os.path.abspath(filename)
scans = ps.read_scans(filename, bdfdir=bdfdir)
if scan != 0:
d = rt.set_pipeline(filename, scan, paramfile=paramfile,
fileroot=os.path.basename(filename), logfile=logfile)
rt.pipeline(d, range(d['nsegments']))
#... | def searchone(filename, scan, paramfile, logfile, bdfdir) | Searches one scan of filename
filename is name of local sdm ('filename.GN' expected locally).
scan is scan number to search. if none provided, script prints all.
assumes filename is an sdm. | 4.940528 | 4.995285 | 0.989038 |
filename = os.path.abspath(filename)
bignumber = 500
if os.path.exists(filename):
scans = ps.read_scans(filename, bdfdir=bdfdir)
scanlist = sorted(scans.keys())
else:
logger.warn('Could not find file {0}. Estimating scans from available files.'.format(filename))
fi... | def mergeall(filename, snrmin, snrmax, bdfdir) | Merge cands/noise files over all scans
Tries to find scans from filename, but will fall back to finding relevant files if it does not exist. | 3.559876 | 3.42309 | 1.03996 |
filename = os.path.abspath(filename)
pc.nbcompile(os.path.dirname(filename), os.path.basename(filename), html=html, basenb=basenb, agdir=agdir) | def nbcompile(filename, html, basenb, agdir) | Compile the baseinteract.ipynb notebook into an analysis notebook for filename | 3.090263 | 3.074122 | 1.005251 |
reproduce.refine_cand(candsfile, candnum=candnum, threshold=threshold) | def refine_cand(candsfile, candnum, threshold) | Run refinement search for candnum in list_cands with abs(snr) > threshold | 5.135688 | 4.716738 | 1.088822 |
'''Refetch instance data from the API.
'''
response = requests.get('%s/categories/%s' % (API_BASE_URL, self.name))
attributes = response.json()
self.ancestors = [Category(name) for name in attributes['ancestors']]
self.contents = WikiText(attributes['contents_raw'],
... | def refresh(self) | Refetch instance data from the API. | 5.15818 | 4.870561 | 1.059052 |
self.logger.info("Start_all_linking for device %s type %s group %s",
self.device_id, link_type, group_id)
self.hub.direct_command(self.device_id, '02', '64' + link_type + group_id) | def start_all_linking(self, link_type, group_id) | Start all linking | 4.471168 | 4.116863 | 1.086062 |
self.logger.info("Cancel_all_linking for device %s", self.device_id)
self.hub.direct_command(self.device_id, '02', '65') | def cancel_all_linking(self) | Cancel all linking | 7.270279 | 6.435034 | 1.129797 |
status = self.hub.get_device_status(self.device_id, return_led)
self.logger.info("Dimmer %s status: %s", self.device_id,
pprint.pformat(status))
return status | def status(self, return_led=0) | Get status from device | 4.096478 | 3.88261 | 1.055083 |
if not extra_context:
extra_context = {}
extra_context['is_popup'] = request.REQUEST.get('_popup', 0)
return super(EnhancedAdminMixin, self).delete_view(request, object_id, extra_context) | def delete_view(self, request, object_id, extra_context=None) | Sets is_popup context variable to hide admin header. | 2.937216 | 2.473933 | 1.187266 |
# NOTE: this MUST use coverage itself, and not pytest-cov, because the
# latter is apparently unable to prevent pytest plugins from being loaded
# before pytest-cov itself is able to start up coverage.py! The result is
# that coverage _always_ skips over all module level code, i.e. constants,
#... | def coverage(c, html=True) | Run coverage with coverage.py. | 12.264249 | 11.397831 | 1.076016 |
with fields.FieldLock(self.related_field):
related_pks = self()
for pk in related_pks:
# get the real related field
related_instance = self.related_field._model(pk)
related_field = getattr(related_instance, self.related_field.name... | def remove_instance(self) | Remove the instance from the related fields (delete the field if it's
a simple one, or remove the instance from the field if it's a set/list/
sorted_set) | 5.280148 | 4.140461 | 1.275256 |
for related_collection_name in self.related_collections:
related_collection = getattr(self, related_collection_name)
related_collection.remove_instance()
return super(RelatedModel, self).delete() | def delete(self) | When the instance is deleted, we propagate the deletion to the related
collections, which will remove it from the related fields. | 4.071029 | 2.771788 | 1.468737 |
original_database = getattr(cls, 'database', None)
impacted_models = super(RelatedModel, cls).use_database(database)
# no relation on the current database, so nothing nore to transfer
if not original_database or not getattr(original_database, '_relations', {}):
retu... | def use_database(cls, database) | Move model and its submodels to the new database, as the original
use_database method. And manage relations too (done here instead of
the database because the database class is not aware of relations) | 4.357579 | 4.115514 | 1.058818 |
super(RelatedFieldMixin, self)._attach_to_model(model)
if model.abstract:
# do not manage the relation if it's an abstract model
return
# now, check related_name and save the relation in the database
# get related parameters to identify the relation
... | def _attach_to_model(self, model) | When we have a model, save the relation in the database, to later create
RelatedCollection objects in the related model | 4.733377 | 4.382849 | 1.079977 |
relations = self.database._relations[self.related_to]
existing = [r for r in relations if r[2] == self.related_name]
if existing:
error = ("The related name defined for the field '%s.%s', named '%s', already exists "
"on the model '%s' (tied to the field... | def _assert_relation_does_not_exists(self) | Check if a relation with the current related_name doesn't already exists
for the related model | 4.809163 | 4.330123 | 1.110629 |
if isinstance(self.related_to, type) and issubclass(self.related_to, RelatedModel):
model_name = self.related_to._name
elif isinstance(self.related_to, str):
if self.related_to == 'self':
model_name = self._model._name
elif ':' not in self.re... | def _get_related_model_name(self) | Return the name of the related model, as used to store all models in the
database object, in the following format: "%(namespace)s:%(class_name)"
The result is computed from the "to" argument of the RelatedField
constructor, stored in the "related_to" attribute, based on theses rules :
- ... | 3.25792 | 2.871217 | 1.134683 |
related_name = self.related_name or '%(model)s_set'
related_name = related_name % {
'namespace': re_identifier.sub('_', self._model.namespace),
'model': self._model.__name__
}
if re_identifier.sub('', related_name) != related_name:
raise Imple... | def _get_related_name(self) | Return the related name to use to access this related field.
If the related_name argument is not defined in its declaration,
a new one will be computed following this format: '%s_set' with %s the
name of the model owning the related.field.
If the related_name argument exists, it can be t... | 3.64748 | 3.17604 | 1.148437 |
if isinstance(value, model.RedisModel):
value = value._pk
elif isinstance(value, SimpleValueRelatedFieldMixin):
value = value.proxy_get()
return value | def from_python(self, value) | Provide the ability to pass a RedisModel instances or a FK field as
value instead of passing the PK. The value will then be translated in
the real PK. | 11.409073 | 7.285598 | 1.565976 |
def func(self, *args, **kwargs):
if many:
args = self.from_python_many(*args)
else:
if 'value' in kwargs:
kwargs['value'] = self.from_python(kwargs['value'])
else:
args = list(args)
... | def _make_command_method(cls, command_name, many=False) | Return a function which will convert objects to their pk, then call the
super method for the given name.
The "many" attribute indicates that the command accept one or many
values as arguments (in *args) | 3.306112 | 3.109524 | 1.063221 |
model = self.database._models[self.related_to]
meth = model.lazy_connect if skip_exist_test else model
return meth(self.proxy_get()) | def instance(self, skip_exist_test=False) | Returns the instance of the related object linked by the field. | 21.268419 | 14.709794 | 1.445868 |
if 'values_callback' not in kwargs:
kwargs['values_callback'] = self.from_python_many
pieces = fields.SortedSetField.coerce_zadd_args(*args, **kwargs)
return super(M2MSortedSetField, self).zadd(*pieces) | def zadd(self, *args, **kwargs) | Parse args and kwargs to check values to pass them through the
from_python method.
We pass the parsed args/kwargs as args in the super call, to avoid
doing the same calculation on kwargs one more time. | 8.740143 | 6.938268 | 1.259701 |
'''Refetch instance data from the API.
'''
response = requests.get('%s/media/images/%s' % (API_BASE_URL, self.id))
attributes = response.json()
#self.exif = attributes['exif']
self.height = attributes['height']
self.width = attributes['width']
#self.ratio = attribu... | def refresh(self) | Refetch instance data from the API. | 6.228541 | 5.759381 | 1.08146 |
return _Pipeline(self, transaction=transaction, share_in_threads=share_in_threads) | def pipeline(self, transaction=True, share_in_threads=False) | A replacement to the default redis pipeline method which manage saving
and restoring of the connection.
ALL calls to redis for the current database will pass via the pipeline.
So if you don't use watches, all getters will not return any value, but
results will be available via the pipe.e... | 3.375273 | 3.937406 | 0.857233 |
with self.pipeline(True, share_in_threads=kwargs.get('share_in_threads', False)) as pipe:
while 1:
try:
if watches:
pipe.watch(*watches)
func(pipe)
return pipe.execute()
excep... | def transaction(self, func, *watches, **kwargs) | Convenience method for executing the callable `func` as a transaction
while watching all keys specified in `watches`. The 'func' callable
should expect a single arguement which is a Pipeline object. | 4.340163 | 4.219759 | 1.028533 |
if self._pipelined_connection is not None:
if self._pipelined_connection.share_in_threads or \
threading.current_thread().ident == self._pipelined_connection.current_thread_id:
return self._pipelined_connection
return self._direct_connection | def _connection(self) | If we have a pipeline, shared in thread, or in the good thread, return it
else use the direct connection | 5.048567 | 3.100502 | 1.628307 |
if isinstance(value, _Pipeline):
self._pipelined_connection = value
else:
self._direct_connection = value
self._pipelined_connection = None | def _connection(self, value) | If the value is a pipeline, save it as the connection to use for pipelines if to be shared
in threads or goot thread. Do not remove the direct connection.
If it is not a pipeline, clear it, and set the direct connection again. | 4.210462 | 2.750218 | 1.530955 |
watches = []
for watch in names:
if isinstance(watch, RedisField):
watch = watch.key
watches.append(watch)
return super(_Pipeline, self).watch(*watches) | def watch(self, *names) | Override the default watch method to allow the user to pass RedisField
objects as names, which will be translated to their real keys and passed
to the default watch method | 4.796933 | 3.041443 | 1.57719 |
return get_relationship(relationship).distance_between(obj1, obj2, limit) | def get_connection_distance(relationship, obj1, obj2, limit=2) | Calculates the distance between the two given objects for the given
relationship. See `connections.models.Relationship` for more info.
{% get_connection_distance 'relationship_name' obj1 obj2 as distance %}
{% get_connection_distance 'relationship_name' obj1 obj2 limit=3 as distance %} | 5.498558 | 7.158011 | 0.768168 |
# read in pickle file of candidates
assert os.path.exists(candsfile)
try:
with open(candsfile, 'rb') as pkl:
d = pickle.load(pkl)
cands = pickle.load(pkl)
except IOError:
logger.error('Trouble parsing candsfile')
loc = np.array([])
prop = np... | def read_candidates(candsfile, snrmin=0, snrmax=999, returnstate=False) | Reads candidate file and returns data as python object.
candsfile is pkl file (for now) with (1) state dict and (2) cands object.
cands object can either be a dictionary or tuple of two numpy arrays.
Return tuple of two numpy arrays (location, properties).
returned values can be filtered by snrmin... | 2.811741 | 2.635786 | 1.066756 |
noises = pickle.load(open(noisefile, 'r'))
scan = []; seg = []; noiseperbl = []; flagfrac = []; imnoise = []
if len(noises[0]) == 4:
for noise in noises:
seg.append(noise[0]); noiseperbl.append(noise[1])
flagfrac.append(noise[2]); imnoise.append(noise[3])
retur... | def read_noise(noisefile) | Function to read a noise file and parse columns.
Works with both per-scan and merged noise files. | 2.455584 | 2.348184 | 1.045737 |
os.chdir(workdir)
# merge cands/noise files per scan
for scan in scans:
merge_segments(fileroot, scan, cleanup=True, sizelimit=2.) | def cleanup(workdir, fileroot, scans=[]) | Cleanup up noise and cands files.
Finds all segments in each scan and merges them into single cand/noise file per scan. | 12.044779 | 6.059369 | 1.987794 |
assert isinstance(pkllist, list), "pkllist must be list of file names"
if not outroot:
outroot = '_'.join(pkllist[0].split('_')[1:-1])
workdir = os.path.dirname(pkllist[0])
mergepkl = os.path.join(workdir, 'noise_' + outroot + '_merge.pkl')
pkllist = [pkllist[i] for i in range(len(pk... | def merge_noises(pkllist, outroot='') | Merge noise files from multiple segments.
Output noise file has scan number at start of each entry. | 3.03934 | 2.936423 | 1.035048 |
assert isinstance(pkllist, list), "pkllist must be list of file names"
if not outroot:
outroot = '_'.join(pkllist[0].split('_')[1:-1])
workdir = os.path.dirname(pkllist[0])
mergepkl = os.path.join(workdir, 'cands_' + outroot + '_merge.pkl')
pkllist = [pkllist[i] for i in range(len(pk... | def merge_cands(pkllist, outroot='', remove=[], snrmin=0, snrmax=999) | Takes cands pkls from list and filteres to write new single "merge" pkl.
Ignores segment cand files.
remove is a list [t0,t1,t2,t3], where t0-t1, t2-t3 define the time ranges in seconds.
snrmin, snrmax define how to filter cands read and written by abs(snr) | 3.40934 | 3.329572 | 1.023957 |
pkllist = [ff for ff in
[os.path.join(workdir, 'cands_{0}_sc{1}.pkl'.format(fileroot, scan))
for scan in scans] if os.path.exists(ff)]
merge_cands(pkllist, outroot=fileroot, snrmin=snrmin, snrmax=snrmax)
pkllist = [ff for ff in
[os.path.join(workdir, 'no... | def merge_scans(workdir, fileroot, scans, snrmin=0, snrmax=999) | Merge cands/noise files over all scans | 2.485632 | 2.230132 | 1.114567 |
with open(candsfile, 'rb') as pkl:
d = pickle.load(pkl)
cands = pickle.load(pkl)
features = d['features']
d1 = d.copy()
d2 = d.copy()
d1['features'] = [features[i] for i in featind1]
d2['features'] = [features[i] for i in featind2]
cands1 = {}
cands2 = {}
for ... | def split_candidates(candsfile, featind1, featind2, candsfile1, candsfile2) | Split features from one candsfile into two new candsfiles
featind1/2 is list of indices to take from d['features'].
New features and updated state dict go to candsfile1/2. | 1.596913 | 1.498322 | 1.065801 |
from shutil import copy
from rtpipe import get_notebook
from subprocess import call
os.environ['fileroot'] = fileroot
if agdir:
os.environ['agdir'] = agdir
if not basenb:
basenb = get_notebook('baseinteract.ipynb')
logger.info('Moving to {0} and building notebook for... | def nbcompile(workdir, fileroot, html=True, basenb='', agdir='') | Run analysis pipeline from jupyter base notebook and save as notebook and html.
html will also compile static html version
basenb can be provided, else will get distributed version.
agdir is the activegit repo (optional) | 2.885033 | 2.846404 | 1.013571 |
# read metadata and define columns of interest
loc, prop, d = read_candidates(candsfile, returnstate=True)
try:
scancol = d['featureind'].index('scan')
except ValueError:
scancol = -1
if 'snr2' in d['features']:
snrcol = d['features'].index('snr2')
elif 'snr1' in d[... | def thresholdcands(candsfile, threshold, numberperscan=1) | Returns list of significant candidate loc in candsfile.
Can define threshold and maximum number of locs per scan.
Works on merge or per-scan cands pkls. | 3.018981 | 2.945692 | 1.02488 |
# needs to take merge pkl dict
if len(loc):
intcol = d['featureind'].index('int')
segmentcol = d['featureind'].index('segment')
if d.has_key('segmenttimesdict'): # using merged pkl
scancol = d['featureind'].index('scan')
t0 = np.array([d['segmenttimesdict'... | def int2mjd(d, loc) | Function to convert segment+integration into mjd seconds. | 5.152885 | 4.633825 | 1.112015 |
loc, prop, d = read_candidates(candsfile, returnstate=True)
npixx, npixy = prop[0][4].shape
nints, nchan, npol = prop[0][5].shape
bin = 10
plt.figure(1)
for i in cands:
if mode == 'spec':
rr = np.array([np.abs(prop[i][5][:,i0:i0+bin,0].mean(axis=1)) for i0 in range(0,n... | def plot_full(candsfile, cands, mode='im') | Plot 'full' features, such as cutout image and spectrum. | 3.191275 | 3.086818 | 1.03384 |
# get metadata
state = pickle.load(open(pkllist[0], 'r')) # assume single state for all scans
if 'image2' in state['searchtype']:
immaxcol = state['features'].index('immax2')
logger.info('Using immax2 for flux.')
elif 'image1' in state['searchtype']:
try:
immax... | def make_psrrates(pkllist, nbins=60, period=0.156) | Visualize cands in set of pkl files from pulsar observations.
Input pkl list assumed to start with on-axis pulsar scan, followed by off-axis scans.
nbins for output histogram. period is pulsar period in seconds (used to find single peak for cluster of detections). | 2.634848 | 2.612865 | 1.008413 |
if not outname:
outname = 'tmp.png'
labels = {0: 'Flux at 0\'', 1: 'Flux at 7\'', 2: 'Flux at 15\'', 3: 'Flux at 25\''}
labelsr = {1: 'Flux Ratio 7\' to 0\'', 2: 'Flux Ratio 15\' to 0\'', 3: 'Flux Ratio 25\' to 0\''}
colors = {0: 'b.', 1: 'r.', 2: 'g.', 3: 'y.'}
rates = make_psrrates... | def plot_psrrates(pkllist, outname='') | Plot cumulative rate histograms. List of pkl files in order, as for make_psrrates. | 2.246624 | 2.22954 | 1.007662 |
loc, prop = read_candidates(candsfile)
loc2, prop2 = read_candidates(mockcandsfile)
dmselect = np.where(loc[:,2] == dmbin)[0]
mocki = [i for i in loc2[:,1].astype(int)] # known transients
rat = []; newloc = []; newprop = []
for i in mocki:
try:
detind = list(loc[dmsel... | def mock_fluxratio(candsfile, mockcandsfile, dmbin=0) | Associates mock cands with detections in candsfile by integration.
Returns ratio of detected to expected flux for all associations. | 3.859411 | 3.633724 | 1.062109 |
absdev = np.abs(data - np.median(data))
return np.median(absdev) | def flag_calcmad(data) | Calculate median absolute deviation of data array | 4.335038 | 3.066664 | 1.413601 |
level_int = int(level)
new_int = int((level_int * 255)/100)
new_level = format(new_int, '02X')
self.logger.debug("brightness_to_hex: %s to %s", level, str(new_level))
return str(new_level) | def brightness_to_hex(self, level) | Convert numeric brightness percentage into hex for insteon | 3.013485 | 2.89759 | 1.039997 |
self.logger.info("post_direct_command: %s", command_url)
req = requests.post(command_url, timeout=self.timeout,
auth=requests.auth.HTTPBasicAuth(self.username,
self.password))
self.http_code = req.s... | def post_direct_command(self, command_url) | Send raw command via post | 2.420169 | 2.308582 | 1.048336 |
self.logger.info("get_direct_command: %s", command_url)
req = requests.get(command_url, timeout=self.timeout,
auth=requests.auth.HTTPBasicAuth(self.username,
self.password))
self.http_code = req.statu... | def get_direct_command(self, command_url) | Send raw command via get | 2.489091 | 2.335797 | 1.065628 |
extended_payload = extended_payload or ''
if not extended_payload:
msg_type = '0'
msg_type_desc = 'Standard'
else:
msg_type = '1'
msg_type_desc = 'Extended'
extended_payload = extended_payload.ljust(26, '0')
### D... | def direct_command(self, device_id, command, command2, extended_payload=None) | Wrapper to send posted direct command and get response. Level is 0-100.
extended_payload is 14 bytes/28 chars..but last 2 chars is a generated checksum so leave off | 3.46865 | 3.423601 | 1.013158 |
self.logger.info("direct_command_hub: Command %s", command)
command_url = (self.hub_url + '/3?' + command + "=I=3")
return self.post_direct_command(command_url) | def direct_command_hub(self, command) | Send direct hub command | 8.332931 | 7.31962 | 1.138438 |
self.logger.info("direct_command_short: Command %s", command)
command_url = (self.hub_url + '/3?' + command + "=I=0")
return self.post_direct_command(command_url) | def direct_command_short(self, command) | Wrapper for short-form commands (doesn't need device id or flags byte) | 8.072041 | 7.313322 | 1.103745 |
if cat in self.device_categories:
return self.device_categories[cat]
else:
return False | def get_device_category(self, cat) | Return the device category and name given the category id | 2.976857 | 2.771743 | 1.074002 |
if cat + ':' + sub_cat in self.device_models:
return self.device_models[cat + ':' + sub_cat]
else:
for i_key, i_val in self.device_models.items():
if 'key' in i_val:
if i_val['key'] == key:
return i_val
... | def get_device_model(self, cat, sub_cat, key='') | Return the model name given cat/subcat or product key | 2.331558 | 2.308549 | 1.009967 |
self.logger.info("\nid_request for device %s", device_id)
device_id = device_id.upper()
self.direct_command(device_id, '10', '00')
sleep(2)
status = self.get_buffer_status(device_id)
if not status:
sleep(1)
status = self.get_buffer_stat... | def id_request(self, device_id) | Get the device for the ID. ID request can return device type (cat/subcat),
firmware ver, etc. Cat is status['is_high'], sub cat is status['id_mid'] | 3.872812 | 3.739237 | 1.035723 |
# status['responseCmd2'] is lighting level
# responseCmd1 contains All-Link Database delta
# if returnLED = 0. returns light level in responseCmd2
# if returnLED = 1, returns LED Bit Flags in responseCmd1
self.logger.info("\nget_device_status for device %s", device_id)
... | def get_device_status(self, device_id, return_led=0, level=None) | Do a separate query to get device status. This can tell if device
is on/off, lighting level, etc. | 3.792946 | 3.718605 | 1.019992 |
key = self.create_key_from_command(command, command2)
command_cache = self.get_cache_from_file(device_id)
if device_id not in command_cache:
command_cache[device_id] = {}
return False
elif key not in command_cache[device_id]:
return False
... | def get_command_response_from_cache(self, device_id, command, command2) | Gets response | 2.706967 | 2.738977 | 0.988313 |
if not device_id:
return False
key = self.create_key_from_command(command, command2)
ttl = int(time()) + CACHE_TTL
command_cache = self.get_cache_from_file(device_id)
if device_id not in command_cache:
command_cache[device_id] = {}
com... | def set_command_response_from_cache(self, response, device_id, command, command2) | Sets response | 2.696097 | 2.741739 | 0.983353 |
device_id = device_id.upper()
self.logger.info('check_success: for device %s cmd1 %s cmd2 %s',
device_id, sent_cmd1, sent_cmd2)
sleep(2)
status = self.get_buffer_status(device_id)
check_id = status.get('id_from', '')
cmd1 = status.get('... | def check_success(self, device_id, sent_cmd1, sent_cmd2) | Check if last command succeeded by checking buffer | 2.524285 | 2.451449 | 1.029711 |
command_url = self.hub_url + '/1?XB=M=1'
response = self.post_direct_command(command_url)
self.logger.info("clear_buffer: %s", response)
return response | def clear_buffer(self) | Clear the hub buffer | 9.931074 | 8.460404 | 1.17383 |
self.logger.info("start_all_linking for type %s group %s",
link_type, group_id)
self.direct_command_hub('0264' + link_type + group_id) | def start_all_linking(self, link_type, group_id) | Begin all linking | 6.351109 | 5.814642 | 1.092261 |
# compute a unique key for this settings, for caching. Work on the whole
# dict without directly using known keys to allow the use of unix socket
# connection or any other (future ?) way to connect to redis
if not settings:
settings = self.connection_settings
... | def connect(self, **settings) | Connect to redis and cache the new connection | 6.902124 | 6.20914 | 1.111607 |
name = model._name
existing = self._models.get(name, None)
if not existing:
self._models[name] = model
elif model.__name__ != existing.__name__ or model._creation_source != existing._creation_source:
raise ImplementationError(
'A model wit... | def _add_model(self, model) | Save this model as one existing on this database, to deny many models
with same namespace and name.
If the model already exists, check if it is the same. It can happen if the
module is imported twice in different ways.
If it's a new model or an existing and valid one, return the model in... | 3.991429 | 3.363694 | 1.186621 |
original_database = getattr(model, 'database', None)
def get_models(model):
model_database = getattr(model, 'database', None)
if model_database == self:
return []
models = [model]
for submodel in model.__subclasses__(... | def _use_for_model(self, model) | Update the given model to use the current database. Do it also for all
of its subclasses if they share the same database. (so it's easy to
call use_database on an abstract model to use the new database for all
subclasses) | 3.684643 | 3.444618 | 1.069681 |
if not hasattr(self, '_redis_version'):
self._redis_version = tuple(
map(int, self.connection.info().get('redis_version').split('.')[:3])
)
return self._redis_version | def redis_version(self) | Return the redis version as a tuple | 2.691828 | 2.360278 | 1.140471 |
if not hasattr(self, '_support_scripting'):
try:
self._support_scripting = self.redis_version >= (2, 5) \
and hasattr(self.connection, 'register_script')
except:
self._support_scripting = False
return self._support_scri... | def support_scripting(self) | Returns True if scripting is available. Checks are done in the client
library (redis-py) AND the redis server. Result is cached, so done only
one time. | 3.012911 | 2.438418 | 1.235601 |
if not hasattr(self, '_support_zrangebylex'):
try:
self._support_zrangebylex = self.redis_version >= (2, 8, 9) \
and hasattr(self.connection, 'zrangebylex')
except:
self._support_zrangebylex = False
return self._support... | def support_zrangebylex(self) | Returns True if zrangebylex is available. Checks are done in the client
library (redis-py) AND the redis server. Result is cached, so done only
one time. | 2.148834 | 1.903429 | 1.128928 |
if keys is None:
keys = []
if args is None:
args = []
if 'script_object' not in script_dict:
script_dict['script_object'] = self.connection.register_script(script_dict['lua'])
return script_dict['script_object'](keys=keys, args=args, client=se... | def call_script(self, script_dict, keys=None, args=None) | Call a redis script with keys and args
The first time we call a script, we register it to speed up later calls.
We expect a dict with a ``lua`` key having the script, and the dict will be
updated with a ``script_object`` key, with the content returned by the
the redis-py ``register_scri... | 2.682949 | 2.118538 | 1.266415 |
cursor = 0
while True:
cursor, keys = self.connection.scan(cursor, match=match, count=count)
for key in keys:
yield key
if not cursor or cursor == '0': # string for redis.py < 2.10
break | def scan_keys(self, match=None, count=None) | Take a pattern expected by the redis `scan` command and iter on all matching keys
Parameters
----------
match: str
The pattern of keys to look for
count: int, default to None (redis uses 10)
Hint for redis about the number of expected result
Yields
... | 4.165429 | 4.894862 | 0.85098 |
'''Update the line using the blob of json-parsed data directly from the
API.
'''
self.bullet = data['bullet']
self.level = data['level']
self.text = WikiText(data['text_raw'],
data['text_rendered']) | def _update(self, data) | Update the line using the blob of json-parsed data directly from the
API. | 14.925845 | 4.962104 | 3.007967 |
logger = logging.getLogger(__name__)
domain = (validDomain[1] - validDomain[0])[0]
bins = -1 + 2* n.array([ (freqs[i]-validDomain[0,i])/domain for i in range(len(freqs))])
ncoeffs = len(coeffs[0])/2
rr = n.array([n.polynomial.chebyshev.chebval(bins[i], coeffs[i,:ncoeffs]) for i in range(len(c... | def calcChebyshev(coeffs, validDomain, freqs) | Given a set of coefficients,
this method evaluates a Chebyshev approximation.
Used for CASA bandpass reading.
input coeffs and freqs are numpy arrays | 2.7623 | 2.739762 | 1.008226 |
# bandpass. taking liberally from Corder et al's analysisutilities
([polyMode, polyType, nPolyAmp, nPolyPhase, scaleFactor, nRows, nSpws, nUniqueTimesBP, uniqueTimesBP,
nPolarizations, frequencyLimits, increments, frequenciesGHz, polynomialPhase,
polynomialAmplitude, timesB... | def parsebp(self, bpfile, debug=False) | Takes bp CASA cal table and places values in numpy arrays.
Assumes two or fewer spw. :\
Assumes one bp solution per file. | 3.894492 | 3.793321 | 1.026671 |
self.spwind = spwind
if calname:
self.logger.warn('calname option not used for casa_sol. Applied based on radec.')
# define pol index
if 'X' in ''.join(pols) or 'Y' in ''.join(pols):
polord = ['XX', 'YY']
elif 'R' in ''.join(pols) or 'L' in ''.j... | def set_selection(self, time, freqs, blarr, calname='', radec=(), dist=1, spwind=[], pols=['XX','YY']) | Set select parameter that defines time, spw, and pol solutions to apply.
time defines the time to find solutions near in mjd.
freqs defines frequencies to select bandpass solution
blarr is array of size 2xnbl that gives pairs of antennas in each baseline (a la tpipe.blarr).
radec (radian... | 3.563957 | 3.428079 | 1.039637 |
if len(self.gain.shape) == 4:
gamp = n.abs(self.gain).mean(axis=0) # mean gain amp for each ant over time
elif len(self.gain.shape) == 3:
gamp = n.abs(self.gain) # gain amp for selected time
# badgain = n.where(gamp < gamp.mean() - sig*gamp.std())
b... | def calc_flag(self, sig=3.0) | Calculates antennas to flag, based on bad gain and bp solutions. | 4.118109 | 3.818147 | 1.078562 |
# flag bad ants
if self.flagants:
badants = self.calc_flag()
else:
badants = n.array([[]])
# apply gain correction
if hasattr(self, 'bandpass'):
corr = n.ones_like(data)
flag = n.ones_like(data.real).astype('int')
... | def apply(self, data) | Applies calibration solution to data array. Assumes structure of (nint, nbl, nch, npol). | 3.490406 | 3.317828 | 1.052015 |
import pylab as p
p.clf()
fig = p.figure(1)
nspw = len(self.gain[0])
ext = n.ceil(n.sqrt(nspw)) # find best squre plot (simplest)
for spw in range(len(self.gain[0])):
ax = fig.add_subplot(ext, ext, spw+1)
for pol in [0,1]:
... | def plot(self) | Quick visualization of calibration solution. | 5.003081 | 4.845968 | 1.032421 |
# identify very low gain amps not already flagged
badsols = n.where( (n.median(self.amp)/self.amp > threshold) & (self.flagged == False))[0]
if len(badsols):
self.logger.info('Solutions %s flagged (times %s, ants %s, freqs %s) for low gain amplitude.' % (str(badsols), self.... | def flagants(self, threshold=50) | Flags solutions with amplitude more than threshold larger than median. | 5.52165 | 5.176247 | 1.066728 |
skip = 3 # skip first three header lines
MJD = 0; UTC = 1; LSTD = 2; LSTS = 3; IFID = 4; SKYFREQ = 5; ANT = 6; AMP = 7; PHASE = 8
RESIDUAL = 9; DELAY = 10; FLAGGED = 11; ZEROED = 12; HA = 13; AZ = 14; EL = 15
SOURCE = 16
#FLAGREASON = 17
mjd = []; utc = []; l... | def parseGN(self, telcalfile, onlycomplete=True) | Takes .GN telcal file and places values in numpy arrays.
onlycomplete defines whether to toss times with less than full set of solutions (one per spw, pol, ant). | 2.442115 | 2.403121 | 1.016226 |
select = self.select[n.where( (self.skyfreq[self.select] == skyfreq) & (self.polarization[self.select] == pol) )[0]]
if len(select): # for when telcal solutions don't exist
ind1 = n.where(ant1 == self.antnum[select])
ind2 = n.where(ant2 == self.antnum[select])
... | def calcgain(self, ant1, ant2, skyfreq, pol) | Calculates the complex gain product (g1*g2) for a pair of antennas. | 2.887969 | 2.824959 | 1.022305 |
select = self.select[n.where( (self.skyfreq[self.select] == skyfreq) & (self.polarization[self.select] == pol) )[0]]
ind1 = n.where(ant1 == self.antnum[select])
ind2 = n.where(ant2 == self.antnum[select])
d1 = self.delay[select][ind1]
d2 = self.delay[select][ind2]
... | def calcdelay(self, ant1, ant2, skyfreq, pol) | Calculates the relative delay (d1-d2) for a pair of antennas in ns. | 2.563309 | 2.508448 | 1.021871 |
# find best skyfreq for each channel
skyfreqs = n.unique(self.skyfreq[self.select]) # one per spw
nch_tot = len(self.freqs)
chan_bandnum = [range(nch_tot*i/len(skyfreqs), nch_tot*(i+1)/len(skyfreqs)) for i in range(len(skyfreqs))] # divide chans by number of spw in solution... | def apply(self, data) | Applies calibration solution to data array. Assumes structure of (nint, nbl, nch, npol). | 4.56357 | 4.342867 | 1.05082 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.