code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
fig_width_pt = 245.26*2
inches_per_pt = 1.0/72.27
golden_mean = (math.sqrt(5.)-1.0)/2.0
fig_width = fig_width_pt*inches_per_pt
fig_height = fig_width*golden_mean
fig_size = [1.5*fig_width, fig_height]
params = {'backend': 'ps',
'axes.labelsize': 12,
'te... | def setFigForm() | set the rcparams to EmulateApJ columnwidth=245.26 pts | 1.771284 | 1.67985 | 1.05443 |
if certfile is None:
certfile = tempfile.NamedTemporaryFile()
# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://" + certHost
logging.debug(top_level_url)
... | def getCert(username, password,
certHost=_SERVER,
certfile=None,
certQuery=_PROXY) | Access the cadc certificate server. | 2.859684 | 2.870253 | 0.996318 |
GMS = "https://" + _SERVER + _GMS
certfile.seek(0)
buf = certfile.read()
x509 = crypto.load_certificate(crypto.FILETYPE_PEM, buf)
sep = ""
dn = ""
parts = []
for i in x509.get_issuer().get_components():
#print i
if i[0] in parts:
continue
parts... | def getGroupsURL(certfile, group) | given a certfile load a list of groups that user is a member of | 3.451244 | 3.60758 | 0.956665 |
try:
certfile = getCert(userid, password)
group_url = getGroupsURL(certfile, group)
logging.debug("group url: %s" % ( group_url))
con = httplib.HTTPSConnection(_SERVER,
443,
key_file=certfile.name,
... | def isMember(userid, password, group) | Test to see if the given userid/password combo is an authenticated member of group.
userid: CADC Username (str)
password: CADC Password (str)
group: CADC GMS group (str) | 3.261219 | 3.37511 | 0.966256 |
form = cgi.FieldStorage()
userid = form['userid'].value
password = form['passwd'].value
group = form['group'].value | def stub() | Just some left over code | 5.031736 | 4.933087 | 1.019997 |
xp = x - crpix1
yp = y - crpix2
# IMPORTANT NOTE: 0-based indexing in Python means indexing for values
# in cd and pv will be shifted from in the paper.
x_deg = cd[0][0] * xp + cd[0][1] * yp
y_deg = cd[1][0] * xp + cd[1][1] * yp
if nord < 0:
xi = x
eta = y
else:
... | def xy2skypv(x, y, crpix1, crpix2, crval1, crval2, cd, pv, nord) | Transforms from pixel coordinates to celestial coordinates taking
non-linear distortion into account with the World Coordinate System
FITS keywords as used in MegaPipe.
For the inverse operation see sky2xy
Reference material:
http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/megapipe/docs/CD_PV_keywords... | 2.256462 | 2.306707 | 0.978218 |
order_fit = parse_order_fit(header)
def parse_with_base(i):
key_base = "PV%d_" % i
pvi_x = [header[key_base + "0"]]
def parse_range(lower, upper):
for j in range(lower, upper + 1):
pvi_x.append(header[key_base + str(j)])
if order_fit >= 1:
... | def parse_pv(header) | Parses the PV array from an astropy FITS header.
Args:
header: astropy.io.fits.header.Header
The header containing the PV values.
Returns:
cd: 2d array (list(list(float))
[[PV1_0, PV1_1, ... PV1_N], [PV2_0, PV2_1, ... PV2_N]]
Note that N depends on the order of the fit. Fo... | 3.205175 | 3.018721 | 1.061766 |
if 1 == len(a.shape):
n = np.linalg.norm(a)
if n:
return a / n
return a
norm = np.sum(np.abs(a) ** 2, axis=-1) ** (1. / 2)
# Dividing by a norm of zero will cause a warning to be issued. Set those
# values to another number. It doesn't matter what, since we'll ... | def safe_unit_norm(a) | Ensure that the vector or vectors have unit norm | 4.937833 | 4.732138 | 1.043468 |
if len(a) >= desiredlength:
return a
islist = isinstance(a, list)
a = np.array(a)
diff = desiredlength - len(a)
shape = list(a.shape)
shape[0] = diff
padded = np.concatenate([a, np.zeros(shape, dtype=a.dtype)])
return padded.tolist() if islist else padded | def pad(a, desiredlength) | Pad an n-dimensional numpy array with zeros along the zero-th dimension
so that it is the desired length. Return it unchanged if it is greater
than or equal to the desired length | 2.620714 | 2.701405 | 0.97013 |
if l <= windowsize:
return windowsize
nsteps = ((l // stepsize) * stepsize)
overlap = (windowsize - stepsize)
if overlap:
return nsteps + overlap
diff = (l - nsteps)
left = max(0, windowsize - diff)
return l + left if diff else l | def _wpad(l, windowsize, stepsize) | Parameters
l - The length of the input array
windowsize - the size of each window of samples
stepsize - the number of samples to move the window each step
Returns
The length the input array should be so that no samples are leftover | 5.145355 | 5.588516 | 0.920701 |
end = l - windowsize
if l <= windowsize:
return 0, 0
elif end % stepsize:
l = windowsize + ((end // stepsize) * stepsize)
return l, l - (windowsize - stepsize) | def _wcut(l, windowsize, stepsize) | Parameters
l - The length of the input array
windowsize - the size of each window of samples
stepsize - the number of samples to move the window each step
Returns
The length the input array should be so that leftover samples are ignored | 4.846793 | 5.284553 | 0.917162 |
if windowsize < 1:
raise ValueError('windowsize must be greater than or equal to one')
if stepsize is None:
stepsize = windowsize
if stepsize < 1:
raise ValueError('stepsize must be greater than or equal to one')
if not a.flags['C_CONTIGUOUS']:
a = a.copy()
... | def windowed(a, windowsize, stepsize=None, dopad=False) | Parameters
a - the input array to restructure into overlapping windows
windowsize - the size of each window of samples
stepsize - the number of samples to shift the window each step. If not
specified, this defaults to windowsize
dopad - If false (defa... | 2.748293 | 2.600307 | 1.056911 |
try:
self._data[self._position] = item
except IndexError:
self._grow()
self._data[self._position] = item
self._position += 1
return self | def append(self, item) | append a single item to the array, growing the wrapped numpy array
if necessary | 2.649861 | 2.545726 | 1.040906 |
items = np.array(items)
pos = items.shape[0] + self.logical_size
if pos > self.physical_size:
# more physical memory is needed than has been allocated so far
amt = self._tmp_size()
if self.physical_size + amt < pos:
# growing the memor... | def extend(self, items) | extend the numpy array with multiple items, growing the wrapped array
if necessary | 6.201235 | 5.757143 | 1.077138 |
logging.debug("Current display list contains: {}".format(self._displayables_by_cutout.keys()))
logging.debug("Looking for {}".format(cutout))
assert isinstance(cutout, SourceCutout)
if cutout in self._displayables_by_cutout:
displayable = self._displayables_by_cutout... | def display(self, cutout, use_pixel_coords=False) | :param cutout: source cutout object to be display
:type cutout: source.SourceCutout | 2.938857 | 2.846571 | 1.03242 |
if not self.mark_prediction:
return
try:
colour = cutout.reading.from_input_file and 'b' or 'g'
colour = cutout.reading.null_observation and 'c' or colour
dash = cutout.reading.null_observation and 1 or 0
sky_coord = cutout.reading.sk... | def draw_uncertainty_ellipse(self, cutout) | Draws an ErrEllipse with the spcified dimensions. Only one ErrEllipse can be drawn and
only once (not movable). | 4.425064 | 4.465473 | 0.990951 |
if not self.current_displayable:
return
if not self.current_displayable.aligned:
focus_sky_coord = reading.reference_sky_coord
#focus_calculator = SingletFocusCalculator(source)
#logger.debug("Got focus calculator {} for source {}".format(focus_ca... | def align(self, cutout, reading, source) | Set the display center to the reference point.
@param cutout: The cutout to align on
@type cutout: SourceCutout
@param reading: The reading this cutout is from
@type reading: SourceReading
@param source: The source the reading is from
@type source: Source
@retu... | 5.072553 | 5.03148 | 1.008163 |
try:
return phot(*args, **kwargs)
except IndexError:
raise TaskError("No photometric records returned for {0}".format(kwargs)) | def phot_mag(*args, **kwargs) | Wrapper around phot which only returns the computed magnitude directly. | 8.185946 | 7.753753 | 1.05574 |
status = OrderedDict.fromkeys(parameters.BLOCKS.keys())
status['13AE'] = ['discovery complete', '50', '24.05']
status['13AO'] = ['discovery complete', '36', '24.40']
status['13BL'] = ['discovery complete', '79', '24.48']
status['14BH'] = ['discovery running', '-', '-']
s... | def all_blocks(self) | Overview tal table is expecting:
ID observations processing status discoveries m_r 40% | 8.784551 | 5.312879 | 1.653444 |
return os.getenv(key, default) | def from_env(key: str, default: T = None) -> Union[str, Optional[T]] | Shortcut for safely reading environment variable.
:param key: Environment var key.
:param default:
Return default value if environment var not found by given key. By
default: ``None`` | 6.746267 | 26.713514 | 0.252541 |
r
settings = {key: value for key, value in iter_settings(defaults)}
for key, value in iter_settings(optionals):
settings[key] = value
return types.MappingProxyType(settings) | def immutable_settings(defaults: Settings,
**optionals: Any) -> types.MappingProxyType | r"""Initialize and return immutable Settings dictionary.
Settings dictionary allows you to setup settings values from multiple
sources and make sure that values cannot be changed, updated by anyone else
after initialization. This helps keep things clear and not worry about
hidden settings change somewh... | 3.228006 | 4.994503 | 0.646312 |
if isinstance(mixed, str):
try:
mixed = import_module(mixed)
except Exception:
if fail_silently:
return
raise
for key, value in iter_settings(mixed):
context[key] = value | def inject_settings(mixed: Union[str, Settings],
context: MutableMapping[str, Any],
fail_silently: bool = False) -> None | Inject settings values to given context.
:param mixed:
Settings can be a string (that it will be read from Python path),
Python module or dict-like instance.
:param context:
Context to assign settings key values. It should support dict-like item
assingment.
:param fail_silen... | 2.953188 | 2.830225 | 1.043446 |
if isinstance(mixed, types.ModuleType):
for attr in dir(mixed):
if not is_setting_key(attr):
continue
yield (attr, getattr(mixed, attr))
else:
yield from filter(lambda item: is_setting_key(item[0]), mixed.items()) | def iter_settings(mixed: Settings) -> Iterator[Tuple[str, Any]] | Iterate over settings values from settings module or dict-like instance.
:param mixed: Settings instance to iterate. | 2.617458 | 2.815324 | 0.929718 |
if first_weekday is not None:
calendar.setfirstweekday(first_weekday)
locale.setlocale(locale.LC_COLLATE, lc_collate or lc_all)
locale.setlocale(locale.LC_CTYPE, lc_ctype or lc_all)
locale.setlocale(locale.LC_MESSAGES, lc_messages or lc_all)
locale.setlocale(locale.LC_MONETARY, lc_mone... | def setup_locale(lc_all: str,
first_weekday: int = None,
*,
lc_collate: str = None,
lc_ctype: str = None,
lc_messages: str = None,
lc_monetary: str = None,
lc_numeric: str = None,
lc_t... | Shortcut helper to setup locale for backend application.
:param lc_all: Locale to use.
:param first_weekday:
Weekday for start week. 0 for Monday, 6 for Sunday. By default: None
:param lc_collate: Collate locale to use. By default: ``<lc_all>``
:param lc_ctype: Ctype locale to use. By default: ... | 1.426334 | 1.430529 | 0.997067 |
if timezone and hasattr(time, 'tzset'):
tz_root = '/usr/share/zoneinfo'
tz_filename = os.path.join(tz_root, *(timezone.split('/')))
if os.path.exists(tz_root) and not os.path.exists(tz_filename):
raise ValueError('Incorrect timezone value: {0}'.format(timezone))
os... | def setup_timezone(timezone: str) -> None | Shortcut helper to configure timezone for backend application.
:param timezone: Timezone to use, e.g. "UTC", "Europe/Kiev". | 3.182957 | 3.492703 | 0.911316 |
import string, re
inputs=[]
for h in header.ascardlist():
if h.key=="HISTORY":
g=h.value
result=re.search('imcombred: (\d{6}[bfopd])\d{2} .*',g)
if not result:
continue
file_id=result.group(1)
import os
sta... | def inputs(header) | Read through the HISTORY cards in an image header looking for detrend
input lines.
Detrend inputs are given on lines like:
HISTORY imcombred: file_id
We require that the value in file_id be store in the CADC archive before
adding to the inputs list. | 4.592716 | 3.855384 | 1.191248 |
import re, pyfits
parts_RE=re.compile(r'([^\.\s]+)')
dataset_name = parts_RE.findall(elixir_filename)
### check that this was a valid elixir_filename
if not dataset_name or len(dataset_name)<5 :
raise ValueError('String %s does not parse as elixir filename'
... | def elixir_decode(elixir_filename) | Takes an elixir style file name and decodes it's content.
Values returned as a dictionary. Elixir filenames have the format
RUNID.TYPE.FILTER/EXPTIME.CHIPID.VERSION.fits | 5.422211 | 5.257896 | 1.031251 |
import pyfits, time
if not filename:
### here I know what filename is to start with.
import tempfile
filename=tempfile.mktemp(suffix='.fits')
else:
import string, re
### filenames gotta be a string and no lead/trailing space
filename=string.strip(str(fil... | def create_mef(filename=None) | Create a file an MEF fits file called filename. Generate a random
filename if None given | 5.927927 | 5.971622 | 0.992683 |
l = hdu.header.ascardlist()
d = []
for index in range(len(l)):
if l[index].key in __comment_keys and str(l[index])==__cfht_padding:
d.append(index)
d.reverse()
for index in d:
del l[index]
return(0) | def strip_pad(hdu) | Remove the padding lines that CFHT adds to headers | 6.140047 | 4.792501 | 1.281178 |
import os, sys, string, tempfile, shutil
import pyfits, re, time
### if there is a pre-existing MEF file for output then append to it
### otherwise we need to create a PrimaryHDU
if os.access(outfile,os.R_OK)!=1:
if verbose:
print "Creating new MEF file: ",outfile
outf... | def stack(outfile,infiles,verbose=0) | Stick infiles into outfiles as FITS extensions.
outfile willl contain an MEF format file of the single extension FITS
files named in the infiles array | 3.237628 | 3.212666 | 1.00777 |
import os, string, re,urllib
#proxy="http://www1.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData"
proxy="http://test.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData"
if file_id is None:
return(-1)
if extno is None:
filename=file_id+".fits"
else:
filen... | def adGet(file_id, archive="CFHT", extno=None, cutout=None ) | Use get a fits image from the CADC. | 3.814325 | 3.785989 | 1.007485 |
import pyfits
try:
infits=pyfits.open(file,mode)
hdu=infits
except (ValueError,pyfits.VerifyError,pyfits.FITS_SevereError):
import sys
#### I really only know how to deal with one error right now.
#if str(sys.exc_info()[1])=='mandatory keywords are not fixed ... | def _open(file,mode='copyonwrite') | Opens a FITS format file and calls _open_fix if header doesn't
verify correctly. | 8.37726 | 8.039668 | 1.041991 |
import string, re
for h in header.ascardlist():
if h.key=="HISTORY":
g=h.value
if ( string.find(g,'FLIPS 1.0 -:') ):
result=re.search('imred: FLIPS 1.0 - \S{3} (.*) - ([\s\d]\d:\d\d:\d\d)\s*$',g)
if result:
date=result.grou... | def find_proc_date(header) | Search the HISTORY fields of a header looking for the FLIPS
processing date. | 6.76032 | 5.434381 | 1.243991 |
import re, string
value='NULL'
#print type
for h in header:
g = str(h)
if ( string.find(g,'.'+type+'.')!= -1 ):
result=re.search('[^\s]*\.'+type+'\.[^\s]*\.\d\d\.\d\d',g)
if result:
return result.group(0) | def find_detrend_keyword(header, type) | Search through header and find
the elixir formated string(s) that match the the
input 'type'.
header is a FITS HDU.
Elixir formated strings are crunid.type.filter/exptime.chipid.version. | 5.828703 | 6.161731 | 0.945952 |
# we observe ~ a week either side of new moon
# but we don't know when in the dark run the discovery happened
# so be generous with the search boundaries, add extra 2 weeks
# current date just has to be the night of the triplet,
from mp_ephem import horizons
sea... | def query_ssos(self, target_name, lunation_count=None) | Send a query to the SSOS web service, looking for available observations using the given track.
:param target_name: name of target to query against SSOIS db
:param lunation_count: ignored
:rtype: SSOSData | 5.543787 | 5.383458 | 1.029782 |
logger.debug("Building source reading for expnum:{} ccd:{} ftype:{}".format(expnum, ccd, ftype))
return astrom.Observation(expnum=str(expnum),
ftype=ftype,
ccdnum=ccd) | def build_source_reading(expnum, ccd=None, ftype='p') | Build an astrom.Observation object for a SourceReading
:param expnum: (str) Name or CFHT Exposure number of the observation.
:param ccd: (str) CCD is this observation associated with. (can be None)
:param ftype: (str) exposure time (specific to CFHT imaging)
:return: An astrom.Observat... | 4.583101 | 3.529007 | 1.298694 |
assert isinstance(search_end_date, Time)
self._search_end_date = search_end_date.replicate(format='iso')
self._search_end_date.out_subfmt = 'date' | def search_end_date(self, search_end_date) | :type search_end_date: astropy.io.Time
:param search_end_date: search for frames take after the given date. | 5.395158 | 4.049169 | 1.332411 |
params = dict(format=RESPONSE_FORMAT,
verbose=self.verbose,
epoch1=str(self.search_start_date),
epoch2=str(self.search_end_date),
search=self.orbit_method,
eunits=self.error_units,
... | def params(self) | :return: A dictionary of SSOS query parameters.
:rtype: dict | 6.381133 | 6.526855 | 0.977673 |
params = self.param_dict_builder.params
logger.debug(pprint.pformat(format(params)))
response = requests.post(SSOS_URL,
data=params,
headers=self.headers)
logger.debug(response.url)
assert isinstance(respo... | def get(self) | :return: A string containing the TSV result from SSOS
:rtype: str
:raise: AssertionError | 8.756529 | 7.843053 | 1.116469 |
if self._focus is not None:
self._focus.SetFocus()
else:
# fall back on the default behaviour
super(_FocusablePanel, self).SetFocus() | def SetFocus(self, **kwargs) | Over-rides normal behaviour of shifting focus to any child. Prefers
the one set explicityly by use_as_focus.
:param **kwargs: | 5.40379 | 5.030806 | 1.07414 |
jmp_args = ['step3jmp']
matt_args = ['step3jjk']
idx = 0
cmd_args = []
for expnum in expnums:
idx += 1
for ext in ['unid.jmp', 'unid.matt']:
storage.get_file(expnum, ccd=ccd, version=version, ext=ext, prefix=prefix)
image = os.path.splitext(os.path.basename... | def step3(expnums, ccd, version, rate_min,
rate_max, angle, width, field=None, prefix=None, dry_run=False,
maximum_flux_ratio=3, minimum_area=5, minimum_median_flux=1000.0) | run the actual step3 on the given exp/ccd combo | 3.191319 | 3.301978 | 0.966487 |
cls = instance.__class__
args = [x for x in inspect.getargspec(cls.__init__).args if x != 'self']
return [instance.__dict__[key] for key in args] | def extract_init_args(instance) | Given an instance, and under the assumption that member variables have the
same name as the __init__ arguments, extract the arguments so they can
be used to reconstruct the instance when deserializing | 2.640898 | 2.763988 | 0.955467 |
"Display list of choices. As many as we can get in a page."
if not self.__list_window:
(y,x)=self.__main.getmaxyx()
self.__list_window = self.__main.subwin(35,x,0,0)
_lw=self.__list_window
_lw.keypad(1)
(y_max,x_max)=_lw.getmaxyx()
... | def list(self,header,choices) | Display list of choices. As many as we can get in a page. | 2.965422 | 2.847778 | 1.041311 |
if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0:
print 'WCS.recenter() only supported for TAN projections.'
raise TypeError
# Check to see if WCS is already centered...
if self.crpix1 == self.naxis1/2. and self.crpix2 == self.naxis2/2.:
... | def recenter(self) | Reset the reference position values to correspond to the center
of the reference frame.
Algorithm used here developed by Colin Cox - 27-Jan-2004. | 2.886446 | 2.842924 | 1.015309 |
if len(prepend+key) <= 8: _new_key = prepend+key
else: _new_key = str(prepend+key)[:8]
return _new_key | def _buildNewKeyname(self,key,prepend) | Builds a new keyword based on original keyword name and
a prepend string. | 4.850147 | 4.788245 | 1.012928 |
if deep:
return copy.deepcopy(self)
else:
return copy.copy(self) | def copy(self,deep=yes) | Makes a (deep)copy of this object for use by other objects. | 2.316327 | 2.133429 | 1.08573 |
import pyfits, MOPfits
mjd=[]
fid=[]
fs=[]
filenames=[]
for expnum in expnums:
if int(ccd)<18:
cutout="[-*,-*]"
else:
cutout="[*,*]"
filenames.append(MOPfits.adGet(str(expnum)+opt.raw,extno=int(ccd),cutout=cutout))
fs.append(pyfits.open(filen... | def scrambleTriples(expnums,ccd) | Pull the three images and then scramble the MJD-OBS keywords | 3.833101 | 3.776789 | 1.01491 |
import pyfits, MOPfits
filenames=[]
for expnum in expnums:
if int(ccd)<18:
cutout="[-*,-*]"
else:
cutout="[*,*]"
filenames.append(MOPfits.adGet(str(expnum)+opt.raw,extno=int(ccd),cutout=cutout))
for filename in filenames:
if not os.access(fil... | def getTriples(expnums,ccd) | Pull the three images and then scramble the MJD-OBS keywords | 5.738053 | 5.706152 | 1.005591 |
import pyfits
f=pyfits.open(filename,mode='update')
f[0].scale('int16','',bzero=32768)
f.flush()
f.close() | def ushort(filename) | Ushort a the pixels | 3.651415 | 4.173923 | 0.874816 |
filehandle = storage.open_vos_or_local(filename, "rb")
assert filehandle is not None, "Failed to open file {} ".format(filename)
filestr = filehandle.read()
filehandle.close()
assert filestr is not None, "File contents are None"
observations = self._parse_obser... | def parse(self, filename) | Parses a file into an AstromData structure.
Args:
filename: str
The name of the file whose contents will be parsed.
Returns:
data: AstromData
The file contents extracted into a data structure for programmatic
access. | 4.94241 | 4.624398 | 1.068768 |
for observation in observations:
header = observation.header
def get_header_vals(header_list):
header_vals = []
for key in header_list:
val = header[key]
if key == MJD_OBS_CENTER:
h... | def _write_observation_headers(self, observations) | See src/pipematt/step1matt-c | 3.466626 | 3.471429 | 0.998617 |
header_vals = [sys_header[RMIN], sys_header[RMAX], sys_header[ANGLE],
sys_header[AWIDTH]]
self._write_line("## RMIN RMAX ANGLE AWIDTH")
self._write_line("# %8.1f%8.1f%8.1f%8.1f" % tuple(map(float, header_vals))) | def _write_sys_header(self, sys_header) | See src/pipematt/step3matt-c | 4.372211 | 4.335081 | 1.008565 |
for i, source in enumerate(sources):
self._write_source(source) | def _write_source_data(self, sources) | See src/jjk/measure3 | 4.644517 | 4.711811 | 0.985718 |
if self._header_written:
raise AstromFormatError("Astrom file already has headers.")
self._write_observation_list(observations)
self._write_observation_headers(observations)
self._write_sys_header(sys_header)
self._write_source_header()
self._header... | def write_headers(self, observations, sys_header) | Writes the header part of the astrom file so that only the source
data has to be filled in. | 3.741057 | 2.95928 | 1.264178 |
if not self._header_written:
observations = [reading.get_observation() for reading in source.get_readings()]
self.write_headers(observations, self.sys_header)
self._write_source(source) | def write_source(self, source) | Writes out data for a single source. | 6.928951 | 6.796337 | 1.019513 |
self.write_headers(astrom_data.observations, astrom_data.sys_header)
self._write_source_data(astrom_data.sources) | def write_astrom_data(self, astrom_data) | Writes a full AstromData structure at once. | 6.053327 | 5.235388 | 1.156233 |
if self._inverted:
return self.obs.naxis1 - x, self.obs.naxis2 - y
return x, y | def _original_frame(self, x, y) | Return x/y in the original frame, based on a guess as much as anything.
:param x: x pixel coordinate
:type x: float
:param y: y pixel coordinate
:type y: float
:return: x,y
:rtype: float, float | 7.097671 | 6.351153 | 1.11754 |
try:
pix_coord = list(pix_coord)
except:
pass
if not isinstance(pix_coord, list) or len(pix_coord) != 2:
raise ValueError("pix_coord needs to be set with an (x,y) coordinate pair, got {}".format(pix_coord))
x, y = pix_coord
if not isin... | def pix_coord(self, pix_coord) | :type pix_coord: list
:param pix_coord: an x,y pixel coordinate, origin = 1 | 2.402463 | 2.512949 | 0.956033 |
xref = isinstance(self.xref, Quantity) and self.xref.value or self.xref
yref = isinstance(self.yref, Quantity) and self.yref.value or self.yref
return xref + self.x_ref_offset, yref + self.y_ref_offset | def reference_source_point(self) | The location of the source in the reference image, in terms of the
current image coordinates. | 2.877066 | 2.776765 | 1.036121 |
my_x, my_y = self.reference_source_point
other_x, other_y = other_reading.reference_source_point
return my_x - other_x, my_y - other_y | def get_coordinate_offset(self, other_reading) | Calculates the offsets between readings' coordinate systems.
Args:
other_reading: ossos.astrom.SourceReading
The reading to compare coordinate systems with.
Returns:
(offset_x, offset_y):
The x and y offsets between this reading and the other reading's
... | 2.871952 | 3.029704 | 0.947932 |
# astheader = storage.get_astheader(self.obs.expnum, self.obs.ccdnum, version=self.obs.ftype)
# pvwcs = wcs.WCS(astheader)
# (x, y) = pvwcs.sky2xy(self.ra, self.dec)
# logger.debug("is_inverted: X,Y {},{} -> wcs X,Y {},{}".format(self.x, self.y, x, y))
# dr2 = ((x-self.... | def compute_inverted(self) | Returns:
inverted: bool
True if the stored image is inverted. | 6.292509 | 6.165373 | 1.020621 |
image_uri = storage.dbimages_uri(expnum=expnum,
ccd=None,
version='p',
ext='.fits',
subdir=None)
logger.debug('Trying to access {}... | def from_source_reference(expnum, ccd, x, y) | Given the location of a source in the image, create an Observation. | 5.250153 | 5.243628 | 1.001244 |
if not self._header_written:
observations = [reading.get_observation() for reading in source.get_readings()]
self.write_headers(observations, self.sys_header)
self._write_source(source, comment=comment, reject=reject) | def write_source(self, source, comment=None, reject=False) | Writes out data for a single source. | 5.524664 | 5.427337 | 1.017933 |
tu = (mjd - MJD0) / (100*DPY)
st = math.fmod(mjd, 1.0) * D2PI + (24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * tu) * tu) * tu) * DS2R
w = math.fmod(st, D2PI)
if w >= 0.0:
return w
else:
return w + D2PI | def mjd2gmst(mjd) | Convert Modfied Juian Date (JD = 2400000.5) to GMST
Taken from P.T. Walace routines. | 3.859442 | 3.796849 | 1.016486 |
import torch
from torch.autograd import Variable, grad
real_samples = real_samples.view(fake_samples.shape)
subset_size = real_samples.shape[0]
real_samples = real_samples[:subset_size]
fake_samples = fake_samples[:subset_size]
alpha = torch.rand(subs... | def _gradient_penalty(self, real_samples, fake_samples, kwargs) | Compute the norm of the gradients for each sample in a batch, and
penalize anything on either side of unit norm | 1.835403 | 1.822055 | 1.007326 |
counter = 0
while counter < 5:
try:
result = func(*args, **kwargs)
return result
except Exception as ex:
time.sleep(5)
counter += 1
logging.warning(str(ex)) | def _connection_error_wrapper(func, *args, **kwargs) | Wrap a call to func in a try/except that repeats on ConnectionError
@param func:
@param args:
@param kwargs:
@return: | 2.815321 | 2.770923 | 1.016023 |
if self.channels == 1:
return self
x = self.sum(axis=1) * 0.5
y = x * 0.5
return AudioSamples(y, self.samplerate) | def mono(self) | Return this instance summed to mono. If the instance is already mono,
this is a no-op. | 5.942676 | 4.472351 | 1.328759 |
flo = flo or BytesIO()
with SoundFile(
flo,
mode='w',
channels=self.channels,
format=fmt,
subtype=subtype,
samplerate=self.samples_per_second) as f:
if fmt == 'OGG':
# KL... | def encode(self, flo=None, fmt='WAV', subtype='PCM_16') | Return audio samples encoded as bytes given a particular audio format
Args:
flo (file-like): A file-like object to write the bytes to. If flo
is not supplied, a new :class:`io.BytesIO` instance will be
created and returned
fmt (str): A libsndfile-friendl... | 4.399992 | 4.927277 | 0.892987 |
validate_properties = validator_class.VALIDATORS['properties']
def set_defaults(validator: Any,
properties: dict,
instance: dict,
schema: dict) -> Iterator[ValidationError]:
for prop, subschema in properties.items():
if 'de... | def extend_with_default(validator_class: Any) -> Any | Append defaults from schema to instance need to be validated.
:param validator_class: Apply the change for given validator class. | 2.365314 | 2.876216 | 0.82237 |
try:
return self._wdata(other)
except AttributeError:
frequency_dim = other.dimensions[-1]
return self._wdata(frequency_dim.scale) | def weights(self, other) | Compute weights, given a scale or time-frequency representation
:param other: A time-frequency representation, or a scale
:return: a numpy array of weights | 10.484541 | 8.111642 | 1.29253 |
detections = fk_candidate_observations.get_sources()
for detection in detections:
measures = detection.get_readings()
for measure in measures:
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--astrom-filename', default=None, help="Give the astrom f... | def rates_angles(fk_candidate_observations) | :param fk_candidate_observations: name of the fk*reals.astrom file to check against Object.planted | 4.499839 | 4.313819 | 1.043122 |
logger.debug(str(kwargs))
hdulist = None
try:
vobj = storage.vofile(uri, **kwargs)
try:
fobj = cStringIO.StringIO(vobj.read())
fobj.seek(0)
hdulist = fits.open(fobj)
except Exception as e:
... | def download_hdulist(self, uri, **kwargs) | Downloads a FITS image as a HDUList.
Args:
uri: The URI of the FITS image to download.
kwargs: optional arguments to pass to the vos client.
For example, passing view="cutout" and cutout=[1] will result
in a cutout of extension 1 from the FITS image specified by the
... | 5.432004 | 5.474387 | 0.992258 |
local_file = os.path.basename(uri)
if os.access(local_file, os.F_OK):
fobj = open(local_file)
else:
fobj = storage.vofile(uri, view='data')
fobj.seek(0)
str = fobj.read()
fobj.close()
apcor_str = str
return ApcorData.f... | def download_apcor(self, uri) | Downloads apcor data.
Args:
uri: The URI of the apcor data file.
Returns:
apcor: ossos.downloads.core.ApcorData | 4.381541 | 4.236184 | 1.034313 |
try:
args = map(float, rawstr.split())
except Exception as ex:
import sys
logger.error("Failed to convert aperture correction: {}".format(ex))
raise ex
return cls(*args) | def from_string(cls, rawstr) | Creates an ApcorData record from the raw string format.
Expected string format:
ap_in ap_out ap_cor apcor_err | 5.966861 | 5.675459 | 1.051344 |
message = storage.SUCCESS
if storage.get_status(task, prefix, expnum, version=version, ccd=ccd) and not force:
logging.info("{} completed successfully for {} {} {} {}".format(task, prefix, expnum, version, ccd))
return
with storage.LoggingManager(task, prefix, expnum, ccd, version, dr... | def run(expnum, ccd, version, dry_run=False, prefix="", force=False) | Run the OSSOS jmpmakepsf script. | 3.94068 | 3.795342 | 1.038294 |
message = storage.SUCCESS
logging.info("Attempting to get status on header for {} {}".format(expnum, ccd))
if storage.get_status(task, prefix, expnum, version, ccd) and not force:
logging.info("{} completed successfully for {} {} {} {}".format(task, prefix, expnum, version, ccd))
return... | def run(expnum, ccd, version, dry_run=False, prefix="", force=False, ignore_dependency=False) | Run the OSSOS mopheader script. | 4.337593 | 4.170262 | 1.040125 |
import re
if os.uname()[0] == "Linux": javabin = '/opt/java2/bin/java '
htm_level = htm_level
verc_htm_cmd = javabin+'-classpath /usr/cadc/misc/htm/htmIndex.jar edu.jhu.htm.app.lookup %s %s %s' % (htm_level, ra, dec)
for result in os.popen( verc_htm_cmd ).readlines():
result = result[:... | def htmIndex(ra,dec,htm_level=3) | Compute htm index of htm_level at position ra,dec | 8.277551 | 8.229964 | 1.005782 |
(x1,y1)=wcs.rd2xy((ra+rad/2.0,dec-rad/2.0))
(x2,y2)=wcs.rd2xy((ra-rad/2.0,dec+rad/2.0))
xl=min(x1,x2)
xr=max(x1,x2)
yl=min(y1,y2)
yu=max(y1,y2)
### constrain the cutout to be inside the image
x1=max(xl,1)
x1=int(min(x1,wcs.naxis1))
x2=max(xr,x1,1)
x2=int(min(x2... | def circTOcutout(wcs,ra,dec,rad) | Convert an RA/DEC/RADIUS to an imcopy cutout | 2.154697 | 2.162176 | 0.996541 |
import orbfit
import RO.StringUtil
(ra,dec,a,b,ang) = orbfit.predict(abg,date,obs)
obj['RA']=ra
obj['DEC']=dec
obj['dRA']=a
obj['dDEC']=b
obj['dANG']=ang
return obj | def predict(abg,date,obs=568) | Run GB's predict using an ABG file as input. | 5.433656 | 5.15326 | 1.054411 |
logger = logging.getLogger('')
logger.setLevel(level)
if level < logging.DEBUG:
log_format = "%(asctime)s %(message)s"
else:
log_format = "%(asctime)s %(module)s : %(lineno)d %(message)s"
sh = logging.StreamHandler()
sh.formatter = logging.Formatter(fmt=log_format)
log... | def config_logging(level) | Configure the logging given the level desired | 2.449981 | 2.385312 | 1.027111 |
program_name = args[0]
logging.info(" ".join(args))
output = subprocess.check_output(args, stderr=subprocess.STDOUT)
if not os.access(program_name+".OK", os.F_OK):
logging.error("No {}.OK file?".format(program_name))
raise subprocess.CalledProcessError(-1, ' '.join(args), output)
... | def exec_prog(args) | Run a subprocess, check for .OK and raise error if does not exist.
args: list of arguments, for value is the command to execute. | 2.801204 | 2.569084 | 1.090351 |
datasec = re.findall(r'(\d+)', datasec)
x1 = min(int(datasec[0]), int(datasec[1]))
x2 = max(int(datasec[0]), int(datasec[1]))
y1 = min(int(datasec[2]), int(datasec[3]))
y2 = max(int(datasec[2]), int(datasec[3]))
return (x1, x2), (y1, y2) | def get_pixel_bounds_from_datasec_keyword(datasec) | Return the x/y pixel boundaries of the data section.
:param datasec: str e.g. '[33:2080,1:4612]'
:return: ((xmin,xmax),(ymin,ymax)) | 1.607262 | 1.778345 | 0.903797 |
assert isinstance(pos1, numpy.ndarray)
assert isinstance(pos2, numpy.ndarray)
# build some arrays to hold the index of things that matched between lists.
npts2 = npts1 = 0
if len(pos1) > 0:
npts1 = len(pos1[:, 0])
pos1_idx_array = numpy.arange(npts1, dtype=numpy.int16)
if l... | def match_lists(pos1, pos2, tolerance=MATCH_TOLERANCE, spherical=False) | Given two sets of x/y positions match the lists, uniquely.
:rtype : numpy.ma, numpy.ma
:param pos1: list of x/y positions.
:param pos2: list of x/y positions.
:param tolerance: float distance, in pixels, to consider a match
Algorithm:
- Find all the members of pos2 that are within toleranc... | 2.929032 | 2.780027 | 1.053598 |
if self._stream is None:
self._stream = tempfile.NamedTemporaryFile(delete=False)
try:
self._stream.write(self.client.open(self.filename, view='data').read())
except:
pass
return self._stream | def stream(self) | the stream to write the log content too.
@return: | 5.022582 | 5.559828 | 0.90337 |
if self._client is not None:
return self._client
self._client = vospace.client
return self._client | def client(self) | Send back the client we were sent, or construct a default one.
@rtype vospace.client | 5.952257 | 4.046921 | 1.470811 |
self.flush()
try:
if self.stream is not None:
self.stream.flush()
_name = self.stream.name
self.stream.close()
self.client.copy(_name, self.filename)
except Exception as ex:
print str(ex)
... | def close(self) | Closes the stream. | 4.323962 | 3.905099 | 1.107261 |
# Datetime components required for conversion to JD by ERFA, along
# with the default values.
components = ('year', 'mon', 'mday')
defaults = (None, 1, 1, 0)
# Assume that anything following "." on the right side is a
# floating fraction of a second.
try:... | def parse_string(self, timestr, subfmts) | Read time from a single string, using a set of possible formats. | 3.067478 | 3.110739 | 0.986093 |
iys, ims, ids, ihmsfs = d2dtf(self.scale.upper()
.encode('utf8'),
6,
self.jd1, self.jd2)
# Get the str_fmt element of the first allowed output subformat
_, _, str_fmt = sel... | def str_kwargs(self) | Generator that yields a dict of values corresponding to the
calendar date and time for the internal JD values. | 4.43094 | 3.94249 | 1.123894 |
import optik, getpass,sys
from optik import OptionParser
parser=OptionParser()
parser.add_option("-d","--database",
action="store", type="string", dest="database",
default="cfht",
help="Name of the SYBASE database containing TABLE",
... | def _get_db_options(args) | Parse through a command line of arguments to over-ride the values
in the users .dbrc file.
If no user name is given then the environment variable $USERNAME is
used. If $USERNAME is not defined then prompt for input. | 3.961734 | 3.698092 | 1.071291 |
import string, getpass, os
dbrc = os.environ['HOME']+"/.dbrc"
password={}
if os.access(dbrc,os.R_OK):
fd=open(dbrc)
lines=fd.readlines()
for line in lines:
entry=line.split()
if entry[0]==dbSystem and entry[1]==db and entry[2]==user:
r... | def _get_db_password(dbSystem,db,user) | Read through the users .dbrc file to get password for the db/user
combination suplied. If no password is found then prompt for one | 2.98089 | 2.57042 | 1.15969 |
if dbSystem=='SYBASE':
import Sybase
try:
dbh = Sybase.connect(dbSystem,
user,
password,
database=db )
except:
dbh=None
elif dbSystem=='MYSQL':
impo... | def _get_db_connect(dbSystem,db,user,password) | Create a connection to the database specified on the command line | 3.310832 | 3.471553 | 0.953703 |
columns = ('Image',
'Ext',
'X',
'Y',
'MJD',
'Filter',
'Exptime',
'Object_RA',
'Object_Dec',
'Image_target',
'Telescope/Instrument',
'Meta... | def caom2(mpc_filename, search_date="2014 07 24.0") | builds a TSV file in the format of SSOIS by querying for possilbe observations in CADC/CAOM2.
This is a fall back program, should only be useful when SSOIS is behind. | 3.481369 | 3.458464 | 1.006623 |
logger.debug("Doing download_cutout with inputs: reading:{} focus:{} needs_apcor:{}".format(reading,
focus,
... | def download_cutout(self, reading, focus=None, needs_apcor=False) | Downloads a cutout of the FITS image for a given source reading.
Args:
reading: ossos.astrom.SourceReading
The reading which will be the focus of the downloaded image.
focus: tuple(int, int)
The x, y coordinates that should be the focus of the downloaded
... | 5.601864 | 5.696484 | 0.98339 |
# for name in Neptune:
# self.kbos[name] = Neptune[name]
if directory_name is not None:
# defaults to looking at .ast files only
if directory_name == parameters.REAL_KBO_AST_DIR:
kbos = parsers.ossos_discoveries(all_objects=True, data_release... | def load_objects(self, directory_name=None) | Load the targets from a file. | 8.224574 | 8.090284 | 1.016599 |
if p is None:
p = [0, 0]
x = (p[0] - self.x1) * self.xscale + self.cx1
y = (p[1] - self.y1) * self.yscale + self.cy1
# logging.debug("p2c: ({},{}) -> ({},{})".format(p[0],p[1], x, y))
return (x, y) | def p2c(self, p=None) | convert from plot to canvas coordinates.
See also c2p. | 2.458962 | 2.486299 | 0.989005 |
if not p: p = [0, 0]
s = self.p2c(p)
return self.c2s(s) | def p2s(self, p=None) | Convert from plot to screen coordinates | 4.520781 | 4.116852 | 1.098116 |
if not p:
p = [0, 0]
return p[0] - self.canvasx(self.cx1), p[1] - self.canvasy(self.cy2) | def c2s(self, p=None) | Convert from canvas to screen coordinates | 4.642374 | 3.692988 | 1.257078 |
return self.p2s(self.canvasx(self.width / 2.0)), self.p2s(self.canvasy(self.height / 2.0)) | def centre(self) | Return the RA/DEC of the center of the visible Canvas. | 4.34235 | 3.454201 | 1.257122 |
ra2 = math.pi * 2
ra1 = 0
dec1 = -1 * math.pi / 2.0
dec2 = math.pi / 2.0
dra = math.fabs((self.x2 - self.x1) / 4.0)
ddec = math.fabs((self.y2 - self.y1) / 4.0)
logging.debug("Drawing the grid.")
label = True
ra = ra1
while ra <= ... | def coord_grid(self) | Draw a grid of RA/DEC on Canvas. | 3.063593 | 2.933631 | 1.044301 |
(x1, y1) = self.p2c([x, y])
x2 = x1 + size * math.cos(math.radians(orientation))
y2 = y1 - size * math.sin(math.radians(orientation))
self.create_line(x1, y1, x2, y2) | def tickmark(self, x, y, size=10, orientation=90) | Draw a line of size and orientation at x,y | 2.216599 | 2.208228 | 1.003791 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.