repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
OSSOS/MOP
src/ossos/core/ossos/storage.py
reset_datasec
def reset_datasec(cutout, datasec, naxis1, naxis2): """ reset the datasec to account for a possible cutout. @param cutout: @param datasec: @param naxis1: size of the original image in the 'x' direction @param naxis2: size of the oringal image in the 'y' direction @return: """ if cutout is None or cutout == "[*,*]": return datasec try: datasec = datasec_to_list(datasec) except: return datasec # check for '-*' in the cutout string and replace is naxis:1 cutout = cutout.replace(" ", "") cutout = cutout.replace("[-*,", "{}:1,".format(naxis1)) cutout = cutout.replace(",-*]", ",{}:1]".format(naxis2)) cutout = cutout.replace("[*,", "[1:{},".format(naxis1)) cutout = cutout.replace(",*]", ",1:{}]".format(naxis1)) try: cutout = [int(x) for x in re.findall(r"([-+]?[*\d]+?)[:,\]]+", cutout)] except: logger.debug("Failed to processes the cutout pattern: {}".format(cutout)) return datasec if len(cutout) == 5: # cutout likely starts with extension, remove cutout = cutout[1:] # -ve integer offsets indicate offset from the end of array. for idx in [0, 1]: if cutout[idx] < 0: cutout[idx] = naxis1 - cutout[idx] + 1 for idx in [2, 3]: if cutout[idx] < 0: cutout[idx] = naxis2 - cutout[idx] + 1 flip = cutout[0] > cutout[1] flop = cutout[2] > cutout[3] logger.debug("Working with cutout: {}".format(cutout)) if flip: cutout = [naxis1 - cutout[0] + 1, naxis1 - cutout[1] + 1, cutout[2], cutout[3]] datasec = [naxis1 - datasec[1] + 1, naxis1 - datasec[0] + 1, datasec[2], datasec[3]] if flop: cutout = [cutout[0], cutout[1], naxis2 - cutout[2] + 1, naxis2 - cutout[3] + 1] datasec = [datasec[0], datasec[1], naxis2 - datasec[3] + 1, naxis2 - datasec[2] + 1] datasec = [max(datasec[0] - cutout[0] + 1, 1), min(datasec[1] - cutout[0] + 1, naxis1), max(datasec[2] - cutout[2] + 1, 1), min(datasec[3] - cutout[2] + 1, naxis2)] return "[{}:{},{}:{}]".format(datasec[0], datasec[1], datasec[2], datasec[3])
python
def reset_datasec(cutout, datasec, naxis1, naxis2): """ reset the datasec to account for a possible cutout. @param cutout: @param datasec: @param naxis1: size of the original image in the 'x' direction @param naxis2: size of the oringal image in the 'y' direction @return: """ if cutout is None or cutout == "[*,*]": return datasec try: datasec = datasec_to_list(datasec) except: return datasec # check for '-*' in the cutout string and replace is naxis:1 cutout = cutout.replace(" ", "") cutout = cutout.replace("[-*,", "{}:1,".format(naxis1)) cutout = cutout.replace(",-*]", ",{}:1]".format(naxis2)) cutout = cutout.replace("[*,", "[1:{},".format(naxis1)) cutout = cutout.replace(",*]", ",1:{}]".format(naxis1)) try: cutout = [int(x) for x in re.findall(r"([-+]?[*\d]+?)[:,\]]+", cutout)] except: logger.debug("Failed to processes the cutout pattern: {}".format(cutout)) return datasec if len(cutout) == 5: # cutout likely starts with extension, remove cutout = cutout[1:] # -ve integer offsets indicate offset from the end of array. for idx in [0, 1]: if cutout[idx] < 0: cutout[idx] = naxis1 - cutout[idx] + 1 for idx in [2, 3]: if cutout[idx] < 0: cutout[idx] = naxis2 - cutout[idx] + 1 flip = cutout[0] > cutout[1] flop = cutout[2] > cutout[3] logger.debug("Working with cutout: {}".format(cutout)) if flip: cutout = [naxis1 - cutout[0] + 1, naxis1 - cutout[1] + 1, cutout[2], cutout[3]] datasec = [naxis1 - datasec[1] + 1, naxis1 - datasec[0] + 1, datasec[2], datasec[3]] if flop: cutout = [cutout[0], cutout[1], naxis2 - cutout[2] + 1, naxis2 - cutout[3] + 1] datasec = [datasec[0], datasec[1], naxis2 - datasec[3] + 1, naxis2 - datasec[2] + 1] datasec = [max(datasec[0] - cutout[0] + 1, 1), min(datasec[1] - cutout[0] + 1, naxis1), max(datasec[2] - cutout[2] + 1, 1), min(datasec[3] - cutout[2] + 1, naxis2)] return "[{}:{},{}:{}]".format(datasec[0], datasec[1], datasec[2], datasec[3])
[ "def", "reset_datasec", "(", "cutout", ",", "datasec", ",", "naxis1", ",", "naxis2", ")", ":", "if", "cutout", "is", "None", "or", "cutout", "==", "\"[*,*]\"", ":", "return", "datasec", "try", ":", "datasec", "=", "datasec_to_list", "(", "datasec", ")", ...
reset the datasec to account for a possible cutout. @param cutout: @param datasec: @param naxis1: size of the original image in the 'x' direction @param naxis2: size of the oringal image in the 'y' direction @return:
[ "reset", "the", "datasec", "to", "account", "for", "a", "possible", "cutout", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L956-L1017
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_hdu
def get_hdu(uri, cutout=None): """Get a at the given uri from VOSpace, possibly doing a cutout. If the cutout is flips the image then we also must flip the datasec keywords. Also, we must offset the datasec to reflect the cutout area being used. @param uri: The URI in VOSpace of the image to HDU to retrieve. @param cutout: A CADC data service CUTOUT paramter to be used when retrieving the observation. @return: fits.HDU """ try: # the filename is based on the Simple FITS images file. filename = os.path.basename(uri) if os.access(filename, os.F_OK) and cutout is None: logger.debug("File already on disk: {}".format(filename)) hdu_list = fits.open(filename, scale_back=True) hdu_list.verify('silentfix+ignore') else: logger.debug("Pulling: {}{} from VOSpace".format(uri, cutout)) fpt = tempfile.NamedTemporaryFile(suffix='.fits') cutout = cutout is not None and cutout or "" copy(uri+cutout, fpt.name) fpt.seek(0, 2) fpt.seek(0) logger.debug("Read from vospace completed. Building fits object.") hdu_list = fits.open(fpt, scale_back=False) hdu_list.verify('silentfix+ignore') logger.debug("Got image from vospace") try: hdu_list[0].header['DATASEC'] = reset_datasec(cutout, hdu_list[0].header['DATASEC'], hdu_list[0].header['NAXIS1'], hdu_list[0].header['NAXIS2']) except Exception as e: logging.debug("error converting datasec: {}".format(str(e))) for hdu in hdu_list: logging.debug("Adding converter to {}".format(hdu)) hdu.converter = CoordinateConverter(0, 0) try: hdu.wcs = WCS(hdu.header) except Exception as ex: logger.error("Failed trying to initialize the WCS: {}".format(ex)) except Exception as ex: raise ex return hdu_list
python
def get_hdu(uri, cutout=None): """Get a at the given uri from VOSpace, possibly doing a cutout. If the cutout is flips the image then we also must flip the datasec keywords. Also, we must offset the datasec to reflect the cutout area being used. @param uri: The URI in VOSpace of the image to HDU to retrieve. @param cutout: A CADC data service CUTOUT paramter to be used when retrieving the observation. @return: fits.HDU """ try: # the filename is based on the Simple FITS images file. filename = os.path.basename(uri) if os.access(filename, os.F_OK) and cutout is None: logger.debug("File already on disk: {}".format(filename)) hdu_list = fits.open(filename, scale_back=True) hdu_list.verify('silentfix+ignore') else: logger.debug("Pulling: {}{} from VOSpace".format(uri, cutout)) fpt = tempfile.NamedTemporaryFile(suffix='.fits') cutout = cutout is not None and cutout or "" copy(uri+cutout, fpt.name) fpt.seek(0, 2) fpt.seek(0) logger.debug("Read from vospace completed. Building fits object.") hdu_list = fits.open(fpt, scale_back=False) hdu_list.verify('silentfix+ignore') logger.debug("Got image from vospace") try: hdu_list[0].header['DATASEC'] = reset_datasec(cutout, hdu_list[0].header['DATASEC'], hdu_list[0].header['NAXIS1'], hdu_list[0].header['NAXIS2']) except Exception as e: logging.debug("error converting datasec: {}".format(str(e))) for hdu in hdu_list: logging.debug("Adding converter to {}".format(hdu)) hdu.converter = CoordinateConverter(0, 0) try: hdu.wcs = WCS(hdu.header) except Exception as ex: logger.error("Failed trying to initialize the WCS: {}".format(ex)) except Exception as ex: raise ex return hdu_list
[ "def", "get_hdu", "(", "uri", ",", "cutout", "=", "None", ")", ":", "try", ":", "# the filename is based on the Simple FITS images file.", "filename", "=", "os", ".", "path", ".", "basename", "(", "uri", ")", "if", "os", ".", "access", "(", "filename", ",", ...
Get a at the given uri from VOSpace, possibly doing a cutout. If the cutout is flips the image then we also must flip the datasec keywords. Also, we must offset the datasec to reflect the cutout area being used. @param uri: The URI in VOSpace of the image to HDU to retrieve. @param cutout: A CADC data service CUTOUT paramter to be used when retrieving the observation. @return: fits.HDU
[ "Get", "a", "at", "the", "given", "uri", "from", "VOSpace", "possibly", "doing", "a", "cutout", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1020-L1066
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_fwhm_tag
def get_fwhm_tag(expnum, ccd, prefix=None, version='p'): """ Get the FWHM from the VOSpace annotation. @param expnum: @param ccd: @param prefix: @param version: @return: """ uri = get_uri(expnum, ccd, version, ext='fwhm', prefix=prefix) if uri not in fwhm: key = "fwhm_{:1s}{:02d}".format(version, int(ccd)) fwhm[uri] = get_tag(expnum, key) return fwhm[uri]
python
def get_fwhm_tag(expnum, ccd, prefix=None, version='p'): """ Get the FWHM from the VOSpace annotation. @param expnum: @param ccd: @param prefix: @param version: @return: """ uri = get_uri(expnum, ccd, version, ext='fwhm', prefix=prefix) if uri not in fwhm: key = "fwhm_{:1s}{:02d}".format(version, int(ccd)) fwhm[uri] = get_tag(expnum, key) return fwhm[uri]
[ "def", "get_fwhm_tag", "(", "expnum", ",", "ccd", ",", "prefix", "=", "None", ",", "version", "=", "'p'", ")", ":", "uri", "=", "get_uri", "(", "expnum", ",", "ccd", ",", "version", ",", "ext", "=", "'fwhm'", ",", "prefix", "=", "prefix", ")", "if"...
Get the FWHM from the VOSpace annotation. @param expnum: @param ccd: @param prefix: @param version: @return:
[ "Get", "the", "FWHM", "from", "the", "VOSpace", "annotation", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1093-L1107
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_fwhm
def get_fwhm(expnum, ccd, prefix=None, version='p'): """Get the FWHM computed for the given expnum/ccd combo. @param expnum: @param ccd: @param prefix: @param version: @return: """ uri = get_uri(expnum, ccd, version, ext='fwhm', prefix=prefix) filename = os.path.basename(uri) try: return fwhm[uri] except: pass try: fwhm[uri] = float(open(filename, 'r').read()) return fwhm[uri] except: pass try: fwhm[uri] = float(open_vos_or_local(uri).read()) return fwhm[uri] except Exception as ex: logger.error(str(ex)) fwhm[uri] = 4.0 return fwhm[uri]
python
def get_fwhm(expnum, ccd, prefix=None, version='p'): """Get the FWHM computed for the given expnum/ccd combo. @param expnum: @param ccd: @param prefix: @param version: @return: """ uri = get_uri(expnum, ccd, version, ext='fwhm', prefix=prefix) filename = os.path.basename(uri) try: return fwhm[uri] except: pass try: fwhm[uri] = float(open(filename, 'r').read()) return fwhm[uri] except: pass try: fwhm[uri] = float(open_vos_or_local(uri).read()) return fwhm[uri] except Exception as ex: logger.error(str(ex)) fwhm[uri] = 4.0 return fwhm[uri]
[ "def", "get_fwhm", "(", "expnum", ",", "ccd", ",", "prefix", "=", "None", ",", "version", "=", "'p'", ")", ":", "uri", "=", "get_uri", "(", "expnum", ",", "ccd", ",", "version", ",", "ext", "=", "'fwhm'", ",", "prefix", "=", "prefix", ")", "filenam...
Get the FWHM computed for the given expnum/ccd combo. @param expnum: @param ccd: @param prefix: @param version: @return:
[ "Get", "the", "FWHM", "computed", "for", "the", "given", "expnum", "/", "ccd", "combo", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1110-L1140
OSSOS/MOP
src/ossos/core/ossos/storage.py
_get_zeropoint
def _get_zeropoint(expnum, ccd, prefix=None, version='p'): """ Retrieve the zeropoint stored in the tags associated with this image. @param expnum: Exposure number @param ccd: ccd of the exposure @param prefix: possible prefix (such as 'fk') @param version: which version: p, s, or o ? @return: zeropoint """ if prefix is not None: DeprecationWarning("Prefix is no longer used here as the 'fk' and 's' have the same zeropoint.") key = "zeropoint_{:1s}{:02d}".format(version, int(ccd)) return get_tag(expnum, key)
python
def _get_zeropoint(expnum, ccd, prefix=None, version='p'): """ Retrieve the zeropoint stored in the tags associated with this image. @param expnum: Exposure number @param ccd: ccd of the exposure @param prefix: possible prefix (such as 'fk') @param version: which version: p, s, or o ? @return: zeropoint """ if prefix is not None: DeprecationWarning("Prefix is no longer used here as the 'fk' and 's' have the same zeropoint.") key = "zeropoint_{:1s}{:02d}".format(version, int(ccd)) return get_tag(expnum, key)
[ "def", "_get_zeropoint", "(", "expnum", ",", "ccd", ",", "prefix", "=", "None", ",", "version", "=", "'p'", ")", ":", "if", "prefix", "is", "not", "None", ":", "DeprecationWarning", "(", "\"Prefix is no longer used here as the 'fk' and 's' have the same zeropoint.\"",...
Retrieve the zeropoint stored in the tags associated with this image. @param expnum: Exposure number @param ccd: ccd of the exposure @param prefix: possible prefix (such as 'fk') @param version: which version: p, s, or o ? @return: zeropoint
[ "Retrieve", "the", "zeropoint", "stored", "in", "the", "tags", "associated", "with", "this", "image", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1143-L1156
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_zeropoint
def get_zeropoint(expnum, ccd, prefix=None, version='p'): """Get the zeropoint for this exposure using the zeropoint.used file created during source planting.. This command expects that there is a file called #######p##.zeropoint.used which contains the zeropoint. @param expnum: exposure to get zeropoint of @param ccd: which ccd (extension - 1) to get zp @param prefix: possible string prefixed to expsoure number. @param version: one of [spo] as in #######p## @return: zeropoint """ uri = get_uri(expnum, ccd, version, ext='zeropoint.used', prefix=prefix) try: return zmag[uri] except: pass try: zmag[uri] = float(open_vos_or_local(uri).read()) return zmag[uri] except: pass zmag[uri] = 0.0 return zmag[uri]
python
def get_zeropoint(expnum, ccd, prefix=None, version='p'): """Get the zeropoint for this exposure using the zeropoint.used file created during source planting.. This command expects that there is a file called #######p##.zeropoint.used which contains the zeropoint. @param expnum: exposure to get zeropoint of @param ccd: which ccd (extension - 1) to get zp @param prefix: possible string prefixed to expsoure number. @param version: one of [spo] as in #######p## @return: zeropoint """ uri = get_uri(expnum, ccd, version, ext='zeropoint.used', prefix=prefix) try: return zmag[uri] except: pass try: zmag[uri] = float(open_vos_or_local(uri).read()) return zmag[uri] except: pass zmag[uri] = 0.0 return zmag[uri]
[ "def", "get_zeropoint", "(", "expnum", ",", "ccd", ",", "prefix", "=", "None", ",", "version", "=", "'p'", ")", ":", "uri", "=", "get_uri", "(", "expnum", ",", "ccd", ",", "version", ",", "ext", "=", "'zeropoint.used'", ",", "prefix", "=", "prefix", ...
Get the zeropoint for this exposure using the zeropoint.used file created during source planting.. This command expects that there is a file called #######p##.zeropoint.used which contains the zeropoint. @param expnum: exposure to get zeropoint of @param ccd: which ccd (extension - 1) to get zp @param prefix: possible string prefixed to expsoure number. @param version: one of [spo] as in #######p## @return: zeropoint
[ "Get", "the", "zeropoint", "for", "this", "exposure", "using", "the", "zeropoint", ".", "used", "file", "created", "during", "source", "planting", ".." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1159-L1183
OSSOS/MOP
src/ossos/core/ossos/storage.py
mkdir
def mkdir(dirname): """make directory tree in vospace. @param dirname: name of the directory to make """ dir_list = [] while not client.isdir(dirname): dir_list.append(dirname) dirname = os.path.dirname(dirname) while len(dir_list) > 0: logging.info("Creating directory: %s" % (dir_list[-1])) try: client.mkdir(dir_list.pop()) except IOError as e: if e.errno == errno.EEXIST: pass else: raise e
python
def mkdir(dirname): """make directory tree in vospace. @param dirname: name of the directory to make """ dir_list = [] while not client.isdir(dirname): dir_list.append(dirname) dirname = os.path.dirname(dirname) while len(dir_list) > 0: logging.info("Creating directory: %s" % (dir_list[-1])) try: client.mkdir(dir_list.pop()) except IOError as e: if e.errno == errno.EEXIST: pass else: raise e
[ "def", "mkdir", "(", "dirname", ")", ":", "dir_list", "=", "[", "]", "while", "not", "client", ".", "isdir", "(", "dirname", ")", ":", "dir_list", ".", "append", "(", "dirname", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "dirname", ...
make directory tree in vospace. @param dirname: name of the directory to make
[ "make", "directory", "tree", "in", "vospace", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1186-L1204
OSSOS/MOP
src/ossos/core/ossos/storage.py
vofile
def vofile(filename, **kwargs): """ Open and return a handle on a VOSpace data connection @param filename: @param kwargs: @return: """ basename = os.path.basename(filename) if os.access(basename, os.R_OK): return open(basename, 'r') kwargs['view'] = kwargs.get('view', 'data') return client.open(filename, **kwargs)
python
def vofile(filename, **kwargs): """ Open and return a handle on a VOSpace data connection @param filename: @param kwargs: @return: """ basename = os.path.basename(filename) if os.access(basename, os.R_OK): return open(basename, 'r') kwargs['view'] = kwargs.get('view', 'data') return client.open(filename, **kwargs)
[ "def", "vofile", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "if", "os", ".", "access", "(", "basename", ",", "os", ".", "R_OK", ")", ":", "return", "open", "(", "...
Open and return a handle on a VOSpace data connection @param filename: @param kwargs: @return:
[ "Open", "and", "return", "a", "handle", "on", "a", "VOSpace", "data", "connection" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1207-L1218
OSSOS/MOP
src/ossos/core/ossos/storage.py
open_vos_or_local
def open_vos_or_local(path, mode="rb"): """ Opens a file which can either be in VOSpace or the local filesystem. @param path: @param mode: @return: """ filename = os.path.basename(path) if os.access(filename, os.F_OK): return open(filename, mode) if path.startswith("vos:"): primary_mode = mode[0] if primary_mode == "r": vofile_mode = os.O_RDONLY elif primary_mode == "w": vofile_mode = os.O_WRONLY elif primary_mode == "a": vofile_mode = os.O_APPEND else: raise ValueError("Can't open with mode %s" % mode) return vofile(path, mode=vofile_mode) else: return open(path, mode)
python
def open_vos_or_local(path, mode="rb"): """ Opens a file which can either be in VOSpace or the local filesystem. @param path: @param mode: @return: """ filename = os.path.basename(path) if os.access(filename, os.F_OK): return open(filename, mode) if path.startswith("vos:"): primary_mode = mode[0] if primary_mode == "r": vofile_mode = os.O_RDONLY elif primary_mode == "w": vofile_mode = os.O_WRONLY elif primary_mode == "a": vofile_mode = os.O_APPEND else: raise ValueError("Can't open with mode %s" % mode) return vofile(path, mode=vofile_mode) else: return open(path, mode)
[ "def", "open_vos_or_local", "(", "path", ",", "mode", "=", "\"rb\"", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "os", ".", "access", "(", "filename", ",", "os", ".", "F_OK", ")", ":", "return", "open", "(...
Opens a file which can either be in VOSpace or the local filesystem. @param path: @param mode: @return:
[ "Opens", "a", "file", "which", "can", "either", "be", "in", "VOSpace", "or", "the", "local", "filesystem", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1221-L1245
OSSOS/MOP
src/ossos/core/ossos/storage.py
copy
def copy(source, dest): """ use the vospace service to get a file. @param source: @param dest: @return: """ logger.info("copying {} -> {}".format(source, dest)) return client.copy(source, dest)
python
def copy(source, dest): """ use the vospace service to get a file. @param source: @param dest: @return: """ logger.info("copying {} -> {}".format(source, dest)) return client.copy(source, dest)
[ "def", "copy", "(", "source", ",", "dest", ")", ":", "logger", ".", "info", "(", "\"copying {} -> {}\"", ".", "format", "(", "source", ",", "dest", ")", ")", "return", "client", ".", "copy", "(", "source", ",", "dest", ")" ]
use the vospace service to get a file. @param source: @param dest: @return:
[ "use", "the", "vospace", "service", "to", "get", "a", "file", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1248-L1258
OSSOS/MOP
src/ossos/core/ossos/storage.py
vlink
def vlink(s_expnum, s_ccd, s_version, s_ext, l_expnum, l_ccd, l_version, l_ext, s_prefix=None, l_prefix=None): """make a link between two version of a file. @param s_expnum: @param s_ccd: @param s_version: @param s_ext: @param l_expnum: @param l_ccd: @param l_version: @param l_ext: @param s_prefix: @param l_prefix: @return: """ source_uri = get_uri(s_expnum, ccd=s_ccd, version=s_version, ext=s_ext, prefix=s_prefix) link_uri = get_uri(l_expnum, ccd=l_ccd, version=l_version, ext=l_ext, prefix=l_prefix) return client.link(source_uri, link_uri)
python
def vlink(s_expnum, s_ccd, s_version, s_ext, l_expnum, l_ccd, l_version, l_ext, s_prefix=None, l_prefix=None): """make a link between two version of a file. @param s_expnum: @param s_ccd: @param s_version: @param s_ext: @param l_expnum: @param l_ccd: @param l_version: @param l_ext: @param s_prefix: @param l_prefix: @return: """ source_uri = get_uri(s_expnum, ccd=s_ccd, version=s_version, ext=s_ext, prefix=s_prefix) link_uri = get_uri(l_expnum, ccd=l_ccd, version=l_version, ext=l_ext, prefix=l_prefix) return client.link(source_uri, link_uri)
[ "def", "vlink", "(", "s_expnum", ",", "s_ccd", ",", "s_version", ",", "s_ext", ",", "l_expnum", ",", "l_ccd", ",", "l_version", ",", "l_ext", ",", "s_prefix", "=", "None", ",", "l_prefix", "=", "None", ")", ":", "source_uri", "=", "get_uri", "(", "s_ex...
make a link between two version of a file. @param s_expnum: @param s_ccd: @param s_version: @param s_ext: @param l_expnum: @param l_ccd: @param l_version: @param l_ext: @param s_prefix: @param l_prefix: @return:
[ "make", "a", "link", "between", "two", "version", "of", "a", "file", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1261-L1280
OSSOS/MOP
src/ossos/core/ossos/storage.py
delete
def delete(expnum, ccd, version, ext, prefix=None): """ delete a file, no error on does not exist @param expnum: @param ccd: @param version: @param ext: @param prefix: @return: """ uri = get_uri(expnum, ccd=ccd, version=version, ext=ext, prefix=prefix) remove(uri)
python
def delete(expnum, ccd, version, ext, prefix=None): """ delete a file, no error on does not exist @param expnum: @param ccd: @param version: @param ext: @param prefix: @return: """ uri = get_uri(expnum, ccd=ccd, version=version, ext=ext, prefix=prefix) remove(uri)
[ "def", "delete", "(", "expnum", ",", "ccd", ",", "version", ",", "ext", ",", "prefix", "=", "None", ")", ":", "uri", "=", "get_uri", "(", "expnum", ",", "ccd", "=", "ccd", ",", "version", "=", "version", ",", "ext", "=", "ext", ",", "prefix", "="...
delete a file, no error on does not exist @param expnum: @param ccd: @param version: @param ext: @param prefix: @return:
[ "delete", "a", "file", "no", "error", "on", "does", "not", "exist" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1290-L1302
OSSOS/MOP
src/ossos/core/ossos/storage.py
my_glob
def my_glob(pattern): """ get a listing matching pattern @param pattern: @return: """ result = [] if pattern[0:4] == 'vos:': dirname = os.path.dirname(pattern) flist = listdir(dirname) for fname in flist: fname = '/'.join([dirname, fname]) if fnmatch.fnmatch(fname, pattern): result.append(fname) else: result = glob(pattern) return result
python
def my_glob(pattern): """ get a listing matching pattern @param pattern: @return: """ result = [] if pattern[0:4] == 'vos:': dirname = os.path.dirname(pattern) flist = listdir(dirname) for fname in flist: fname = '/'.join([dirname, fname]) if fnmatch.fnmatch(fname, pattern): result.append(fname) else: result = glob(pattern) return result
[ "def", "my_glob", "(", "pattern", ")", ":", "result", "=", "[", "]", "if", "pattern", "[", "0", ":", "4", "]", "==", "'vos:'", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "pattern", ")", "flist", "=", "listdir", "(", "dirname", "...
get a listing matching pattern @param pattern: @return:
[ "get", "a", "listing", "matching", "pattern" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1305-L1322
OSSOS/MOP
src/ossos/core/ossos/storage.py
has_property
def has_property(node_uri, property_name, ossos_base=True): """ Checks if a node in VOSpace has the specified property. @param node_uri: @param property_name: @param ossos_base: @return: """ if get_property(node_uri, property_name, ossos_base) is None: return False else: return True
python
def has_property(node_uri, property_name, ossos_base=True): """ Checks if a node in VOSpace has the specified property. @param node_uri: @param property_name: @param ossos_base: @return: """ if get_property(node_uri, property_name, ossos_base) is None: return False else: return True
[ "def", "has_property", "(", "node_uri", ",", "property_name", ",", "ossos_base", "=", "True", ")", ":", "if", "get_property", "(", "node_uri", ",", "property_name", ",", "ossos_base", ")", "is", "None", ":", "return", "False", "else", ":", "return", "True" ]
Checks if a node in VOSpace has the specified property. @param node_uri: @param property_name: @param ossos_base: @return:
[ "Checks", "if", "a", "node", "in", "VOSpace", "has", "the", "specified", "property", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1351-L1363
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_property
def get_property(node_uri, property_name, ossos_base=True): """ Retrieves the value associated with a property on a node in VOSpace. @param node_uri: @param property_name: @param ossos_base: @return: """ # Must use force or we could have a cached copy of the node from before # properties of interest were set/updated. node = client.get_node(node_uri, force=True) property_uri = tag_uri(property_name) if ossos_base else property_name if property_uri not in node.props: return None return node.props[property_uri]
python
def get_property(node_uri, property_name, ossos_base=True): """ Retrieves the value associated with a property on a node in VOSpace. @param node_uri: @param property_name: @param ossos_base: @return: """ # Must use force or we could have a cached copy of the node from before # properties of interest were set/updated. node = client.get_node(node_uri, force=True) property_uri = tag_uri(property_name) if ossos_base else property_name if property_uri not in node.props: return None return node.props[property_uri]
[ "def", "get_property", "(", "node_uri", ",", "property_name", ",", "ossos_base", "=", "True", ")", ":", "# Must use force or we could have a cached copy of the node from before", "# properties of interest were set/updated.", "node", "=", "client", ".", "get_node", "(", "node_...
Retrieves the value associated with a property on a node in VOSpace. @param node_uri: @param property_name: @param ossos_base: @return:
[ "Retrieves", "the", "value", "associated", "with", "a", "property", "on", "a", "node", "in", "VOSpace", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1366-L1383
OSSOS/MOP
src/ossos/core/ossos/storage.py
set_property
def set_property(node_uri, property_name, property_value, ossos_base=True): """ Sets the value of a property on a node in VOSpace. If the property already has a value then it is first cleared and then set. @param node_uri: @param property_name: @param property_value: @param ossos_base: @return: """ node = client.get_node(node_uri) property_uri = tag_uri(property_name) if ossos_base else property_name # If there is an existing value, clear it first if property_uri in node.props: node.props[property_uri] = None client.add_props(node) node.props[property_uri] = property_value client.add_props(node)
python
def set_property(node_uri, property_name, property_value, ossos_base=True): """ Sets the value of a property on a node in VOSpace. If the property already has a value then it is first cleared and then set. @param node_uri: @param property_name: @param property_value: @param ossos_base: @return: """ node = client.get_node(node_uri) property_uri = tag_uri(property_name) if ossos_base else property_name # If there is an existing value, clear it first if property_uri in node.props: node.props[property_uri] = None client.add_props(node) node.props[property_uri] = property_value client.add_props(node)
[ "def", "set_property", "(", "node_uri", ",", "property_name", ",", "property_value", ",", "ossos_base", "=", "True", ")", ":", "node", "=", "client", ".", "get_node", "(", "node_uri", ")", "property_uri", "=", "tag_uri", "(", "property_name", ")", "if", "oss...
Sets the value of a property on a node in VOSpace. If the property already has a value then it is first cleared and then set. @param node_uri: @param property_name: @param property_value: @param ossos_base: @return:
[ "Sets", "the", "value", "of", "a", "property", "on", "a", "node", "in", "VOSpace", ".", "If", "the", "property", "already", "has", "a", "value", "then", "it", "is", "first", "cleared", "and", "then", "set", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1386-L1406
OSSOS/MOP
src/ossos/core/ossos/storage.py
build_counter_tag
def build_counter_tag(epoch_field, dry_run=False): """ Builds the tag for the counter of a given epoch/field, without the OSSOS base. @param epoch_field: @param dry_run: @return: """ logger.info("Epoch Field: {}, OBJECT_COUNT {}".format(str(epoch_field), str(OBJECT_COUNT))) tag = epoch_field[1] + "-" + OBJECT_COUNT if dry_run: tag += "-DRYRUN" return tag
python
def build_counter_tag(epoch_field, dry_run=False): """ Builds the tag for the counter of a given epoch/field, without the OSSOS base. @param epoch_field: @param dry_run: @return: """ logger.info("Epoch Field: {}, OBJECT_COUNT {}".format(str(epoch_field), str(OBJECT_COUNT))) tag = epoch_field[1] + "-" + OBJECT_COUNT if dry_run: tag += "-DRYRUN" return tag
[ "def", "build_counter_tag", "(", "epoch_field", ",", "dry_run", "=", "False", ")", ":", "logger", ".", "info", "(", "\"Epoch Field: {}, OBJECT_COUNT {}\"", ".", "format", "(", "str", "(", "epoch_field", ")", ",", "str", "(", "OBJECT_COUNT", ")", ")", ")", "t...
Builds the tag for the counter of a given epoch/field, without the OSSOS base. @param epoch_field: @param dry_run: @return:
[ "Builds", "the", "tag", "for", "the", "counter", "of", "a", "given", "epoch", "/", "field", "without", "the", "OSSOS", "base", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1409-L1423
OSSOS/MOP
src/ossos/core/ossos/storage.py
read_object_counter
def read_object_counter(node_uri, epoch_field, dry_run=False): """ Reads the object counter for the given epoch/field on the specified node. @param node_uri: @param epoch_field: @param dry_run: @return: the current object count. """ return get_property(node_uri, build_counter_tag(epoch_field, dry_run), ossos_base=True)
python
def read_object_counter(node_uri, epoch_field, dry_run=False): """ Reads the object counter for the given epoch/field on the specified node. @param node_uri: @param epoch_field: @param dry_run: @return: the current object count. """ return get_property(node_uri, build_counter_tag(epoch_field, dry_run), ossos_base=True)
[ "def", "read_object_counter", "(", "node_uri", ",", "epoch_field", ",", "dry_run", "=", "False", ")", ":", "return", "get_property", "(", "node_uri", ",", "build_counter_tag", "(", "epoch_field", ",", "dry_run", ")", ",", "ossos_base", "=", "True", ")" ]
Reads the object counter for the given epoch/field on the specified node. @param node_uri: @param epoch_field: @param dry_run: @return: the current object count.
[ "Reads", "the", "object", "counter", "for", "the", "given", "epoch", "/", "field", "on", "the", "specified", "node", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1426-L1436
OSSOS/MOP
src/ossos/core/ossos/storage.py
increment_object_counter
def increment_object_counter(node_uri, epoch_field, dry_run=False): """ Increment the object counter used to create unique object identifiers. @param node_uri: @param epoch_field: @param dry_run: @return: The object count AFTER incrementing. """ current_count = read_object_counter(node_uri, epoch_field, dry_run=dry_run) if current_count is None: new_count = "01" else: new_count = coding.base36encode(coding.base36decode(current_count) + 1, pad_length=2) set_property(node_uri, build_counter_tag(epoch_field, dry_run=dry_run), new_count, ossos_base=True) return new_count
python
def increment_object_counter(node_uri, epoch_field, dry_run=False): """ Increment the object counter used to create unique object identifiers. @param node_uri: @param epoch_field: @param dry_run: @return: The object count AFTER incrementing. """ current_count = read_object_counter(node_uri, epoch_field, dry_run=dry_run) if current_count is None: new_count = "01" else: new_count = coding.base36encode(coding.base36decode(current_count) + 1, pad_length=2) set_property(node_uri, build_counter_tag(epoch_field, dry_run=dry_run), new_count, ossos_base=True) return new_count
[ "def", "increment_object_counter", "(", "node_uri", ",", "epoch_field", ",", "dry_run", "=", "False", ")", ":", "current_count", "=", "read_object_counter", "(", "node_uri", ",", "epoch_field", ",", "dry_run", "=", "dry_run", ")", "if", "current_count", "is", "N...
Increment the object counter used to create unique object identifiers. @param node_uri: @param epoch_field: @param dry_run: @return: The object count AFTER incrementing.
[ "Increment", "the", "object", "counter", "used", "to", "create", "unique", "object", "identifiers", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1439-L1462
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_mopheader
def get_mopheader(expnum, ccd, version='p', prefix=None): """ Retrieve the mopheader, either from cache or from vospace @param expnum: @param ccd: @param version: @param prefix: @return: Header """ prefix = prefix is None and "" or prefix mopheader_uri = dbimages_uri(expnum=expnum, ccd=ccd, version=version, prefix=prefix, ext='.mopheader') if mopheader_uri in mopheaders: return mopheaders[mopheader_uri] filename = os.path.basename(mopheader_uri) if os.access(filename, os.F_OK): logger.debug("File already on disk: {}".format(filename)) mopheader_fpt = StringIO(open(filename, 'r').read()) else: mopheader_fpt = StringIO(open_vos_or_local(mopheader_uri).read()) with warnings.catch_warnings(): warnings.simplefilter('ignore', AstropyUserWarning) mopheader = fits.open(mopheader_fpt) # add some values to the mopheader so it can be an astrom header too. header = mopheader[0].header try: header['FWHM'] = get_fwhm(expnum, ccd) except IOError: header['FWHM'] = 10 header['SCALE'] = mopheader[0].header['PIXSCALE'] header['NAX1'] = header['NAXIS1'] header['NAX2'] = header['NAXIS2'] header['MOPversion'] = header['MOP_VER'] header['MJD_OBS_CENTER'] = str(Time(header['MJD-OBSC'], format='mjd', scale='utc', precision=5).replicate(format='mpc')) header['MAXCOUNT'] = MAXCOUNT mopheaders[mopheader_uri] = header mopheader.close() return mopheaders[mopheader_uri]
python
def get_mopheader(expnum, ccd, version='p', prefix=None): """ Retrieve the mopheader, either from cache or from vospace @param expnum: @param ccd: @param version: @param prefix: @return: Header """ prefix = prefix is None and "" or prefix mopheader_uri = dbimages_uri(expnum=expnum, ccd=ccd, version=version, prefix=prefix, ext='.mopheader') if mopheader_uri in mopheaders: return mopheaders[mopheader_uri] filename = os.path.basename(mopheader_uri) if os.access(filename, os.F_OK): logger.debug("File already on disk: {}".format(filename)) mopheader_fpt = StringIO(open(filename, 'r').read()) else: mopheader_fpt = StringIO(open_vos_or_local(mopheader_uri).read()) with warnings.catch_warnings(): warnings.simplefilter('ignore', AstropyUserWarning) mopheader = fits.open(mopheader_fpt) # add some values to the mopheader so it can be an astrom header too. header = mopheader[0].header try: header['FWHM'] = get_fwhm(expnum, ccd) except IOError: header['FWHM'] = 10 header['SCALE'] = mopheader[0].header['PIXSCALE'] header['NAX1'] = header['NAXIS1'] header['NAX2'] = header['NAXIS2'] header['MOPversion'] = header['MOP_VER'] header['MJD_OBS_CENTER'] = str(Time(header['MJD-OBSC'], format='mjd', scale='utc', precision=5).replicate(format='mpc')) header['MAXCOUNT'] = MAXCOUNT mopheaders[mopheader_uri] = header mopheader.close() return mopheaders[mopheader_uri]
[ "def", "get_mopheader", "(", "expnum", ",", "ccd", ",", "version", "=", "'p'", ",", "prefix", "=", "None", ")", ":", "prefix", "=", "prefix", "is", "None", "and", "\"\"", "or", "prefix", "mopheader_uri", "=", "dbimages_uri", "(", "expnum", "=", "expnum",...
Retrieve the mopheader, either from cache or from vospace @param expnum: @param ccd: @param version: @param prefix: @return: Header
[ "Retrieve", "the", "mopheader", "either", "from", "cache", "or", "from", "vospace" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1465-L1512
OSSOS/MOP
src/ossos/core/ossos/storage.py
_get_sghead
def _get_sghead(expnum): """ Use the data web service to retrieve the stephen's astrometric header. :param expnum: CFHT exposure number you want the header for :rtype : list of astropy.io.fits.Header objects. """ version = 'p' key = "{}{}".format(expnum, version) if key in sgheaders: return sgheaders[key] url = "http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub/CFHTSG/{}{}.head".format(expnum, version) logging.getLogger("requests").setLevel(logging.ERROR) logging.debug("Attempting to retrieve {}".format(url)) resp = requests.get(url) if resp.status_code != 200: raise IOError(errno.ENOENT, "Could not get {}".format(url)) header_str_list = re.split('END \n', resp.content) # # make the first entry in the list a Null headers = [None] for header_str in header_str_list: headers.append(fits.Header.fromstring(header_str, sep='\n')) logging.debug(headers[-1].get('EXTVER', -1)) sgheaders[key] = headers return sgheaders[key]
python
def _get_sghead(expnum): """ Use the data web service to retrieve the stephen's astrometric header. :param expnum: CFHT exposure number you want the header for :rtype : list of astropy.io.fits.Header objects. """ version = 'p' key = "{}{}".format(expnum, version) if key in sgheaders: return sgheaders[key] url = "http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub/CFHTSG/{}{}.head".format(expnum, version) logging.getLogger("requests").setLevel(logging.ERROR) logging.debug("Attempting to retrieve {}".format(url)) resp = requests.get(url) if resp.status_code != 200: raise IOError(errno.ENOENT, "Could not get {}".format(url)) header_str_list = re.split('END \n', resp.content) # # make the first entry in the list a Null headers = [None] for header_str in header_str_list: headers.append(fits.Header.fromstring(header_str, sep='\n')) logging.debug(headers[-1].get('EXTVER', -1)) sgheaders[key] = headers return sgheaders[key]
[ "def", "_get_sghead", "(", "expnum", ")", ":", "version", "=", "'p'", "key", "=", "\"{}{}\"", ".", "format", "(", "expnum", ",", "version", ")", "if", "key", "in", "sgheaders", ":", "return", "sgheaders", "[", "key", "]", "url", "=", "\"http://www.cadc-c...
Use the data web service to retrieve the stephen's astrometric header. :param expnum: CFHT exposure number you want the header for :rtype : list of astropy.io.fits.Header objects.
[ "Use", "the", "data", "web", "service", "to", "retrieve", "the", "stephen", "s", "astrometric", "header", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1515-L1543
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_header
def get_header(uri): """ Pull a FITS header from observation at the given URI @param uri: The URI of the image in VOSpace. """ if uri not in astheaders: astheaders[uri] = get_hdu(uri, cutout="[1:1,1:1]")[0].header return astheaders[uri]
python
def get_header(uri): """ Pull a FITS header from observation at the given URI @param uri: The URI of the image in VOSpace. """ if uri not in astheaders: astheaders[uri] = get_hdu(uri, cutout="[1:1,1:1]")[0].header return astheaders[uri]
[ "def", "get_header", "(", "uri", ")", ":", "if", "uri", "not", "in", "astheaders", ":", "astheaders", "[", "uri", "]", "=", "get_hdu", "(", "uri", ",", "cutout", "=", "\"[1:1,1:1]\"", ")", "[", "0", "]", ".", "header", "return", "astheaders", "[", "u...
Pull a FITS header from observation at the given URI @param uri: The URI of the image in VOSpace.
[ "Pull", "a", "FITS", "header", "from", "observation", "at", "the", "given", "URI" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1546-L1554
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_astheader
def get_astheader(expnum, ccd, version='p', prefix=None): """ Retrieve the header for a given dbimages file. @param expnum: CFHT odometer number @param ccd: which ccd based extension (0..35) @param version: 'o','p', or 's' @param prefix: @return: """ logger.debug("Getting ast header for {}".format(expnum)) if version == 'p': try: # Get the SG header if possible. sg_key = "{}{}".format(expnum, version) if sg_key not in sgheaders: _get_sghead(expnum) if sg_key in sgheaders: for header in sgheaders[sg_key]: if header.get('EXTVER', -1) == int(ccd): return header except: pass try: ast_uri = dbimages_uri(expnum, ccd, version=version, ext='.fits') if ast_uri not in astheaders: hdulist = get_image(expnum, ccd=ccd, version=version, prefix=prefix, cutout="[1:1,1:1]", return_file=False, ext='.fits') assert isinstance(hdulist, fits.HDUList) astheaders[ast_uri] = hdulist[0].header except: ast_uri = dbimages_uri(expnum, ccd, version=version, ext='.fits.fz') if ast_uri not in astheaders: hdulist = get_image(expnum, ccd=ccd, version=version, prefix=prefix, cutout="[1:1,1:1]", return_file=False, ext='.fits.fz') assert isinstance(hdulist, fits.HDUList) astheaders[ast_uri] = hdulist[0].header return astheaders[ast_uri]
python
def get_astheader(expnum, ccd, version='p', prefix=None): """ Retrieve the header for a given dbimages file. @param expnum: CFHT odometer number @param ccd: which ccd based extension (0..35) @param version: 'o','p', or 's' @param prefix: @return: """ logger.debug("Getting ast header for {}".format(expnum)) if version == 'p': try: # Get the SG header if possible. sg_key = "{}{}".format(expnum, version) if sg_key not in sgheaders: _get_sghead(expnum) if sg_key in sgheaders: for header in sgheaders[sg_key]: if header.get('EXTVER', -1) == int(ccd): return header except: pass try: ast_uri = dbimages_uri(expnum, ccd, version=version, ext='.fits') if ast_uri not in astheaders: hdulist = get_image(expnum, ccd=ccd, version=version, prefix=prefix, cutout="[1:1,1:1]", return_file=False, ext='.fits') assert isinstance(hdulist, fits.HDUList) astheaders[ast_uri] = hdulist[0].header except: ast_uri = dbimages_uri(expnum, ccd, version=version, ext='.fits.fz') if ast_uri not in astheaders: hdulist = get_image(expnum, ccd=ccd, version=version, prefix=prefix, cutout="[1:1,1:1]", return_file=False, ext='.fits.fz') assert isinstance(hdulist, fits.HDUList) astheaders[ast_uri] = hdulist[0].header return astheaders[ast_uri]
[ "def", "get_astheader", "(", "expnum", ",", "ccd", ",", "version", "=", "'p'", ",", "prefix", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"Getting ast header for {}\"", ".", "format", "(", "expnum", ")", ")", "if", "version", "==", "'p'", ":", ...
Retrieve the header for a given dbimages file. @param expnum: CFHT odometer number @param ccd: which ccd based extension (0..35) @param version: 'o','p', or 's' @param prefix: @return:
[ "Retrieve", "the", "header", "for", "a", "given", "dbimages", "file", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1557-L1595
OSSOS/MOP
src/ossos/core/ossos/storage.py
Task.tag
def tag(self): """ Get the string representation of the tag used to annotate the status in VOSpace. @return: str """ return "{}{}_{}{:02d}".format(self.target.prefix, self, self.target.version, self.target.ccd)
python
def tag(self): """ Get the string representation of the tag used to annotate the status in VOSpace. @return: str """ return "{}{}_{}{:02d}".format(self.target.prefix, self, self.target.version, self.target.ccd)
[ "def", "tag", "(", "self", ")", ":", "return", "\"{}{}_{}{:02d}\"", ".", "format", "(", "self", ".", "target", ".", "prefix", ",", "self", ",", "self", ".", "target", ".", "version", ",", "self", ".", "target", ".", "ccd", ")" ]
Get the string representation of the tag used to annotate the status in VOSpace. @return: str
[ "Get", "the", "string", "representation", "of", "the", "tag", "used", "to", "annotate", "the", "status", "in", "VOSpace", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L468-L476
OSSOS/MOP
src/ossos/core/scripts/scramble.py
scramble
def scramble(expnums, ccd, version='p', dry_run=False): """run the plant script on this combination of exposures""" mjds = [] fobjs = [] for expnum in expnums: filename = storage.get_image(expnum, ccd=ccd, version=version) fobjs.append(fits.open(filename)) # Pull out values to replace in headers.. must pull them # as otherwise we get pointers... mjds.append(fobjs[-1][0].header['MJD-OBS']) order = [0, 2, 1] for idx in range(len(fobjs)): logging.info("Flipping %d to %d" % (fobjs[idx][0].header['EXPNUM'], expnums[order[idx]])) fobjs[idx][0].header['EXPNUM'] = expnums[order[idx]] fobjs[idx][0].header['MJD-OBS'] = mjds[order[idx]] uri = storage.get_uri(expnums[order[idx]], ccd=ccd, version='s', ext='fits') fname = os.path.basename(uri) if os.access(fname, os.F_OK): os.unlink(fname) fobjs[idx].writeto(fname) if dry_run: continue storage.copy(fname, uri) return
python
def scramble(expnums, ccd, version='p', dry_run=False): """run the plant script on this combination of exposures""" mjds = [] fobjs = [] for expnum in expnums: filename = storage.get_image(expnum, ccd=ccd, version=version) fobjs.append(fits.open(filename)) # Pull out values to replace in headers.. must pull them # as otherwise we get pointers... mjds.append(fobjs[-1][0].header['MJD-OBS']) order = [0, 2, 1] for idx in range(len(fobjs)): logging.info("Flipping %d to %d" % (fobjs[idx][0].header['EXPNUM'], expnums[order[idx]])) fobjs[idx][0].header['EXPNUM'] = expnums[order[idx]] fobjs[idx][0].header['MJD-OBS'] = mjds[order[idx]] uri = storage.get_uri(expnums[order[idx]], ccd=ccd, version='s', ext='fits') fname = os.path.basename(uri) if os.access(fname, os.F_OK): os.unlink(fname) fobjs[idx].writeto(fname) if dry_run: continue storage.copy(fname, uri) return
[ "def", "scramble", "(", "expnums", ",", "ccd", ",", "version", "=", "'p'", ",", "dry_run", "=", "False", ")", ":", "mjds", "=", "[", "]", "fobjs", "=", "[", "]", "for", "expnum", "in", "expnums", ":", "filename", "=", "storage", ".", "get_image", "...
run the plant script on this combination of exposures
[ "run", "the", "plant", "script", "on", "this", "combination", "of", "exposures" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/scripts/scramble.py#L37-L67
OSSOS/MOP
src/ossos/core/scripts/scramble.py
main
def main(): """Run the script.""" parser = argparse.ArgumentParser() parser.add_argument('--ccd', action='store', type=int, default=None, help='which ccd to process') parser.add_argument("--dbimages", action="store", default="vos:OSSOS/dbimages", help='vospace dbimages containerNode') parser.add_argument("expnums", type=int, nargs=3, help="expnums to scramble") parser.add_argument("--nosort", action='store_true', default=False, help="do not sort before processing") parser.add_argument("--type", action='store', default='p', choices=['p', 'o'], help='which type of image') parser.add_argument("--verbose", "-v", action="store_true") parser.add_argument("--debug", '-d', action='store_true') parser.add_argument("--dry-run", action="store_true", help="Do not copy back to VOSpace, implies --force") parser.add_argument("--force", action='store_true') args = parser.parse_args() prefix = "" task = util.task() dependency = "update_header" storage.DBIMAGES = args.dbimages ## setup logging level = logging.CRITICAL if args.debug: level = logging.DEBUG elif args.verbose: level = logging.INFO logging.basicConfig(level=level, format="%(message)s") logging.getLogger('vos').setLevel(level) logging.getLogger('vos').addHandler(logging.StreamHandler()) if not args.nosort: args.expnums.sort() ccds = [args.ccd] exit_status = 0 if args.ccd is None: ccds = range(0, 36) for ccd in ccds: storage.set_logger(task, prefix, args.expnums[0], ccd, args.type, args.dry_run) expnums = args.expnums if not (args.force or args.dry_run) and storage.get_status(task, prefix, expnums[0], version='s', ccd=ccd): continue message = storage.SUCCESS try: scramble(expnums=expnums, ccd=ccd, version='p', dry_run=args.dry_run) except Exception as e: logging.error(e) message = str(e) exit_status = message if not args.dry_run: storage.set_status(task, prefix, expnums[0], version='s', ccd=ccd, status=message) return exit_status
python
def main(): """Run the script.""" parser = argparse.ArgumentParser() parser.add_argument('--ccd', action='store', type=int, default=None, help='which ccd to process') parser.add_argument("--dbimages", action="store", default="vos:OSSOS/dbimages", help='vospace dbimages containerNode') parser.add_argument("expnums", type=int, nargs=3, help="expnums to scramble") parser.add_argument("--nosort", action='store_true', default=False, help="do not sort before processing") parser.add_argument("--type", action='store', default='p', choices=['p', 'o'], help='which type of image') parser.add_argument("--verbose", "-v", action="store_true") parser.add_argument("--debug", '-d', action='store_true') parser.add_argument("--dry-run", action="store_true", help="Do not copy back to VOSpace, implies --force") parser.add_argument("--force", action='store_true') args = parser.parse_args() prefix = "" task = util.task() dependency = "update_header" storage.DBIMAGES = args.dbimages ## setup logging level = logging.CRITICAL if args.debug: level = logging.DEBUG elif args.verbose: level = logging.INFO logging.basicConfig(level=level, format="%(message)s") logging.getLogger('vos').setLevel(level) logging.getLogger('vos').addHandler(logging.StreamHandler()) if not args.nosort: args.expnums.sort() ccds = [args.ccd] exit_status = 0 if args.ccd is None: ccds = range(0, 36) for ccd in ccds: storage.set_logger(task, prefix, args.expnums[0], ccd, args.type, args.dry_run) expnums = args.expnums if not (args.force or args.dry_run) and storage.get_status(task, prefix, expnums[0], version='s', ccd=ccd): continue message = storage.SUCCESS try: scramble(expnums=expnums, ccd=ccd, version='p', dry_run=args.dry_run) except Exception as e: logging.error(e) message = str(e) exit_status = message if not args.dry_run: storage.set_status(task, prefix, expnums[0], version='s', ccd=ccd, status=message) return exit_status
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'--ccd'", ",", "action", "=", "'store'", ",", "type", "=", "int", ",", "default", "=", "None", ",", "help", "=", "'which ccd ...
Run the script.
[ "Run", "the", "script", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/scripts/scramble.py#L70-L143
OSSOS/MOP
src/ossos/core/scripts/mk_mopheader.py
mk_mopheader
def mk_mopheader(expnum, ccd, version, dry_run=False, prefix=""): """Run the OSSOS mopheader script. """ ## confirm destination directory exists. destdir = os.path.dirname( storage.dbimages_uri(expnum, ccd, prefix=prefix, version=version, ext='fits')) if not dry_run: storage.mkdir(destdir) ## get image from the vospace storage area filename = storage.get_image(expnum, ccd, version=version, prefix=prefix) logging.info("Running mopheader on %s %d" % (expnum, ccd)) ## launch the mopheader script ## launch the makepsf script expname = os.path.basename(filename).strip('.fits') logging.info(util.exec_prog(['stepZjmp', '-f', expname])) mopheader_filename = expname+".mopheader" # mopheader_filename = mopheader.main(filename) if dry_run: return destination = storage.dbimages_uri(expnum, ccd, prefix=prefix, version=version, ext='mopheader') source = mopheader_filename storage.copy(source, destination) return
python
def mk_mopheader(expnum, ccd, version, dry_run=False, prefix=""): """Run the OSSOS mopheader script. """ ## confirm destination directory exists. destdir = os.path.dirname( storage.dbimages_uri(expnum, ccd, prefix=prefix, version=version, ext='fits')) if not dry_run: storage.mkdir(destdir) ## get image from the vospace storage area filename = storage.get_image(expnum, ccd, version=version, prefix=prefix) logging.info("Running mopheader on %s %d" % (expnum, ccd)) ## launch the mopheader script ## launch the makepsf script expname = os.path.basename(filename).strip('.fits') logging.info(util.exec_prog(['stepZjmp', '-f', expname])) mopheader_filename = expname+".mopheader" # mopheader_filename = mopheader.main(filename) if dry_run: return destination = storage.dbimages_uri(expnum, ccd, prefix=prefix, version=version, ext='mopheader') source = mopheader_filename storage.copy(source, destination) return
[ "def", "mk_mopheader", "(", "expnum", ",", "ccd", ",", "version", ",", "dry_run", "=", "False", ",", "prefix", "=", "\"\"", ")", ":", "## confirm destination directory exists.", "destdir", "=", "os", ".", "path", ".", "dirname", "(", "storage", ".", "dbimage...
Run the OSSOS mopheader script.
[ "Run", "the", "OSSOS", "mopheader", "script", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/scripts/mk_mopheader.py#L36-L67
OSSOS/MOP
src/jjk/preproc/t.py
read_cands
def read_cands(filename): """Read in the contents of a cands comb file""" import sre lines=file(filename).readlines() exps=[] cands=[] coo=[] for line in lines: if ( line[0:2]=="##" ) : break exps.append(line[2:].strip()) for line in lines: if ( line[0]=="#" ) : continue if len(line.strip())==0: if len(coo)!=0: cands.append(coo) coo=[] continue vals=line.split() cols=['x','y','x_0','y_0','flux','size','max_int','elon'] values={} for j in range(len(cols)): col=cols.pop().strip() val=vals.pop().strip() values[col]=float(val) coo.append(values) cands.append(coo) return {'fileId': exps, 'cands': cands}
python
def read_cands(filename): """Read in the contents of a cands comb file""" import sre lines=file(filename).readlines() exps=[] cands=[] coo=[] for line in lines: if ( line[0:2]=="##" ) : break exps.append(line[2:].strip()) for line in lines: if ( line[0]=="#" ) : continue if len(line.strip())==0: if len(coo)!=0: cands.append(coo) coo=[] continue vals=line.split() cols=['x','y','x_0','y_0','flux','size','max_int','elon'] values={} for j in range(len(cols)): col=cols.pop().strip() val=vals.pop().strip() values[col]=float(val) coo.append(values) cands.append(coo) return {'fileId': exps, 'cands': cands}
[ "def", "read_cands", "(", "filename", ")", ":", "import", "sre", "lines", "=", "file", "(", "filename", ")", ".", "readlines", "(", ")", "exps", "=", "[", "]", "cands", "=", "[", "]", "coo", "=", "[", "]", "for", "line", "in", "lines", ":", "if",...
Read in the contents of a cands comb file
[ "Read", "in", "the", "contents", "of", "a", "cands", "comb", "file" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/t.py#L4-L34
OSSOS/MOP
src/jjk/preproc/t.py
discands
def discands(record): """Display the candidates contained in a candidate record list""" import pyraf, pyfits pyraf.iraf.tv() display = pyraf.iraf.tv.display width=128 cands = record['cands'] exps= record['fileId'] ### load some header info from the mophead file headers={} for exp in exps: f = pyfits.open(exp+".fits") headers[exp]={} for key in ['MJDATE', 'NAXIS1', 'NAXIS2', 'EXPTIME', 'FILTER']: headers[exp][key]=f[0].header[key] headers[exp]['MJD-OBSC']=headers[exp]['MJDATE']+headers[exp]['EXPTIME']/2.0/3600.0/24.0 f.close() import math,os for cand in cands: for i in range(len(exps)): x2=[] y2=[] y1=[] x1=[] fileId=exps[i] x2.append(int(min(math.floor(cand[i]['x'])+width,headers[fileId]['NAXIS1']))) y2.append(int(min(math.floor(cand[i]['y'])+width,headers[fileId]['NAXIS2']))) x1.append(int(max(math.floor(cand[i]['x'])-width,1))) y1.append(int(max(math.floor(cand[i]['y'])-width,1))) x_1 = min(x1) y_1 = min(y1) x_2 = max(x2) y_2 = max(y2) for i in range(len(exps)): tvmark=open('tv.coo','w') xshift=cand[i]['x']-cand[i]['x_0'] yshift=cand[i]['y']-cand[i]['y_0'] tvmark.write('%f %f\n' % ( cand[i]['x'], cand[i]['y'])) x1=x_1 + xshift y1=y_1 + yshift x2=x_2 + xshift y2=y_2 + yshift cutout = "[%d:%d,%d:%d]" % (x1,x2,y1,y2) fileId=exps[i] display(fileId+cutout,i+1) tvmark.close() pyraf.iraf.tv.tvmark(i+1,'tv.coo',mark='circle',radii=15) os.unlink('tv.coo')
python
def discands(record): """Display the candidates contained in a candidate record list""" import pyraf, pyfits pyraf.iraf.tv() display = pyraf.iraf.tv.display width=128 cands = record['cands'] exps= record['fileId'] ### load some header info from the mophead file headers={} for exp in exps: f = pyfits.open(exp+".fits") headers[exp]={} for key in ['MJDATE', 'NAXIS1', 'NAXIS2', 'EXPTIME', 'FILTER']: headers[exp][key]=f[0].header[key] headers[exp]['MJD-OBSC']=headers[exp]['MJDATE']+headers[exp]['EXPTIME']/2.0/3600.0/24.0 f.close() import math,os for cand in cands: for i in range(len(exps)): x2=[] y2=[] y1=[] x1=[] fileId=exps[i] x2.append(int(min(math.floor(cand[i]['x'])+width,headers[fileId]['NAXIS1']))) y2.append(int(min(math.floor(cand[i]['y'])+width,headers[fileId]['NAXIS2']))) x1.append(int(max(math.floor(cand[i]['x'])-width,1))) y1.append(int(max(math.floor(cand[i]['y'])-width,1))) x_1 = min(x1) y_1 = min(y1) x_2 = max(x2) y_2 = max(y2) for i in range(len(exps)): tvmark=open('tv.coo','w') xshift=cand[i]['x']-cand[i]['x_0'] yshift=cand[i]['y']-cand[i]['y_0'] tvmark.write('%f %f\n' % ( cand[i]['x'], cand[i]['y'])) x1=x_1 + xshift y1=y_1 + yshift x2=x_2 + xshift y2=y_2 + yshift cutout = "[%d:%d,%d:%d]" % (x1,x2,y1,y2) fileId=exps[i] display(fileId+cutout,i+1) tvmark.close() pyraf.iraf.tv.tvmark(i+1,'tv.coo',mark='circle',radii=15) os.unlink('tv.coo')
[ "def", "discands", "(", "record", ")", ":", "import", "pyraf", ",", "pyfits", "pyraf", ".", "iraf", ".", "tv", "(", ")", "display", "=", "pyraf", ".", "iraf", ".", "tv", ".", "display", "width", "=", "128", "cands", "=", "record", "[", "'cands'", "...
Display the candidates contained in a candidate record list
[ "Display", "the", "candidates", "contained", "in", "a", "candidate", "record", "list" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/t.py#L36-L88
OSSOS/MOP
src/ossos/core/ossos/planning/ObsStatus.py
query_for_observations
def query_for_observations(mjd, observable, runid_list): """Do a QUERY on the TAP service for all observations that are part of runid, where taken after mjd and have calibration 'observable'. Schema is at: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/tables mjd : float observable: str ( 2 or 1 ) runid: tuple eg. ('13AP05', '13AP06') """ data = {"QUERY": ("SELECT Observation.target_name as TargetName, " "COORD1(CENTROID(Plane.position_bounds)) AS RA," "COORD2(CENTROID(Plane.position_bounds)) AS DEC, " "Plane.time_bounds_lower AS StartDate, " "Plane.time_exposure AS ExposureTime, " "Observation.instrument_name AS Instrument, " "Plane.energy_bandpassName AS Filter, " "Observation.observationID AS dataset_name, " "Observation.proposal_id AS ProposalID, " "Observation.proposal_pi AS PI " "FROM caom2.Observation AS Observation " "JOIN caom2.Plane AS Plane ON " "Observation.obsID = Plane.obsID " "WHERE ( Observation.collection = 'CFHT' ) " "AND Plane.time_bounds_lower > %d " "AND Plane.calibrationLevel=%s " "AND Observation.proposal_id IN %s ") % (mjd, observable, str(runid_list)), "REQUEST": "doQuery", "LANG": "ADQL", "FORMAT": "votable"} result = requests.get(storage.TAP_WEB_SERVICE, params=data, verify=False) assert isinstance(result, requests.Response) logging.debug("Doing TAP Query using url: %s" % (str(result.url))) temp_file = tempfile.NamedTemporaryFile() with open(temp_file.name, 'w') as outfile: outfile.write(result.text) try: vot = parse(temp_file.name).get_first_table() except Exception as ex: logging.error(str(ex)) logging.error(result.text) raise ex vot.array.sort(order='StartDate') t = vot.array temp_file.close() logging.debug("Got {} lines from tap query".format(len(t))) return t
python
def query_for_observations(mjd, observable, runid_list): """Do a QUERY on the TAP service for all observations that are part of runid, where taken after mjd and have calibration 'observable'. Schema is at: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/tables mjd : float observable: str ( 2 or 1 ) runid: tuple eg. ('13AP05', '13AP06') """ data = {"QUERY": ("SELECT Observation.target_name as TargetName, " "COORD1(CENTROID(Plane.position_bounds)) AS RA," "COORD2(CENTROID(Plane.position_bounds)) AS DEC, " "Plane.time_bounds_lower AS StartDate, " "Plane.time_exposure AS ExposureTime, " "Observation.instrument_name AS Instrument, " "Plane.energy_bandpassName AS Filter, " "Observation.observationID AS dataset_name, " "Observation.proposal_id AS ProposalID, " "Observation.proposal_pi AS PI " "FROM caom2.Observation AS Observation " "JOIN caom2.Plane AS Plane ON " "Observation.obsID = Plane.obsID " "WHERE ( Observation.collection = 'CFHT' ) " "AND Plane.time_bounds_lower > %d " "AND Plane.calibrationLevel=%s " "AND Observation.proposal_id IN %s ") % (mjd, observable, str(runid_list)), "REQUEST": "doQuery", "LANG": "ADQL", "FORMAT": "votable"} result = requests.get(storage.TAP_WEB_SERVICE, params=data, verify=False) assert isinstance(result, requests.Response) logging.debug("Doing TAP Query using url: %s" % (str(result.url))) temp_file = tempfile.NamedTemporaryFile() with open(temp_file.name, 'w') as outfile: outfile.write(result.text) try: vot = parse(temp_file.name).get_first_table() except Exception as ex: logging.error(str(ex)) logging.error(result.text) raise ex vot.array.sort(order='StartDate') t = vot.array temp_file.close() logging.debug("Got {} lines from tap query".format(len(t))) return t
[ "def", "query_for_observations", "(", "mjd", ",", "observable", ",", "runid_list", ")", ":", "data", "=", "{", "\"QUERY\"", ":", "(", "\"SELECT Observation.target_name as TargetName, \"", "\"COORD1(CENTROID(Plane.position_bounds)) AS RA,\"", "\"COORD2(CENTROID(Plane.position_boun...
Do a QUERY on the TAP service for all observations that are part of runid, where taken after mjd and have calibration 'observable'. Schema is at: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/tables mjd : float observable: str ( 2 or 1 ) runid: tuple eg. ('13AP05', '13AP06')
[ "Do", "a", "QUERY", "on", "the", "TAP", "service", "for", "all", "observations", "that", "are", "part", "of", "runid", "where", "taken", "after", "mjd", "and", "have", "calibration", "observable", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/ObsStatus.py#L22-L74
OSSOS/MOP
src/ossos/core/ossos/planning/ObsStatus.py
create_ascii_table
def create_ascii_table(observation_table, outfile): """Given a table of observations create an ascii log file for easy parsing. Store the result in outfile (could/should be a vospace dataNode) observation_table: astropy.votable.array object outfile: str (name of the vospace dataNode to store the result to) """ logging.info("writing text log to %s" % outfile) stamp = "#\n# Last Updated: " + time.asctime() + "\n#\n" header = "| %20s | %20s | %20s | %20s | %20s | %20s | %20s |\n" % ( "EXPNUM", "OBS-DATE", "FIELD", "EXPTIME(s)", "RA", "DEC", "RUNID") bar = "=" * (len(header) - 1) + "\n" if outfile[0:4] == "vos:": temp_file = tempfile.NamedTemporaryFile(suffix='.txt') fout = temp_file else: fout = open(outfile, 'w') t2 = None fout.write(bar + stamp + bar + header) populated = storage.list_dbimages() for i in range(len(observation_table) - 1, -1, -1): row = observation_table.data[i] if row['dataset_name'] not in populated: storage.populate(row['dataset_name']) str_date = str(ephem.date(row.StartDate + 2400000.5 - ephem.julian_date(ephem.date(0))))[:20] t1 = time.strptime(str_date, "%Y/%m/%d %H:%M:%S") if t2 is None or math.fabs(time.mktime(t2) - time.mktime(t1)) > 3 * 3600.0: fout.write(bar) t2 = t1 ra = str(ephem.hours(math.radians(row.RA))) dec = str(ephem.degrees(math.radians(row.DEC))) line = "| %20s | %20s | %20s | %20.1f | %20s | %20s | %20s |\n" % ( str(row.dataset_name), str(ephem.date(row.StartDate + 2400000.5 - ephem.julian_date(ephem.date(0))))[:20], row.TargetName[:20], row.ExposureTime, ra[:20], dec[:20], row.ProposalID[:20]) fout.write(line) fout.write(bar) if outfile[0:4] == "vos:": fout.flush() storage.copy(fout.name, outfile) fout.close() return
python
def create_ascii_table(observation_table, outfile): """Given a table of observations create an ascii log file for easy parsing. Store the result in outfile (could/should be a vospace dataNode) observation_table: astropy.votable.array object outfile: str (name of the vospace dataNode to store the result to) """ logging.info("writing text log to %s" % outfile) stamp = "#\n# Last Updated: " + time.asctime() + "\n#\n" header = "| %20s | %20s | %20s | %20s | %20s | %20s | %20s |\n" % ( "EXPNUM", "OBS-DATE", "FIELD", "EXPTIME(s)", "RA", "DEC", "RUNID") bar = "=" * (len(header) - 1) + "\n" if outfile[0:4] == "vos:": temp_file = tempfile.NamedTemporaryFile(suffix='.txt') fout = temp_file else: fout = open(outfile, 'w') t2 = None fout.write(bar + stamp + bar + header) populated = storage.list_dbimages() for i in range(len(observation_table) - 1, -1, -1): row = observation_table.data[i] if row['dataset_name'] not in populated: storage.populate(row['dataset_name']) str_date = str(ephem.date(row.StartDate + 2400000.5 - ephem.julian_date(ephem.date(0))))[:20] t1 = time.strptime(str_date, "%Y/%m/%d %H:%M:%S") if t2 is None or math.fabs(time.mktime(t2) - time.mktime(t1)) > 3 * 3600.0: fout.write(bar) t2 = t1 ra = str(ephem.hours(math.radians(row.RA))) dec = str(ephem.degrees(math.radians(row.DEC))) line = "| %20s | %20s | %20s | %20.1f | %20s | %20s | %20s |\n" % ( str(row.dataset_name), str(ephem.date(row.StartDate + 2400000.5 - ephem.julian_date(ephem.date(0))))[:20], row.TargetName[:20], row.ExposureTime, ra[:20], dec[:20], row.ProposalID[:20]) fout.write(line) fout.write(bar) if outfile[0:4] == "vos:": fout.flush() storage.copy(fout.name, outfile) fout.close() return
[ "def", "create_ascii_table", "(", "observation_table", ",", "outfile", ")", ":", "logging", ".", "info", "(", "\"writing text log to %s\"", "%", "outfile", ")", "stamp", "=", "\"#\\n# Last Updated: \"", "+", "time", ".", "asctime", "(", ")", "+", "\"\\n#\\n\"", ...
Given a table of observations create an ascii log file for easy parsing. Store the result in outfile (could/should be a vospace dataNode) observation_table: astropy.votable.array object outfile: str (name of the vospace dataNode to store the result to)
[ "Given", "a", "table", "of", "observations", "create", "an", "ascii", "log", "file", "for", "easy", "parsing", ".", "Store", "the", "result", "in", "outfile", "(", "could", "/", "should", "be", "a", "vospace", "dataNode", ")" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/ObsStatus.py#L77-L131
OSSOS/MOP
src/ossos/core/ossos/planning/ObsStatus.py
create_sky_plot
def create_sky_plot(observation_table, outfile): """Given a VOTable that describes the observation coverage provide a PDF of the skycoverge. observation_table: vostable.arrary outfile: name of file to write results to. """ # camera dimensions width = 0.98 height = 0.98 ax = None if outfile[0:4] == 'vos:': temp_file = tempfile.NamedTemporaryFile(suffix='.pdf') pdf = PdfPages(temp_file.name) else: pdf = PdfPages(outfile) saturn = ephem.Saturn() uranus = ephem.Uranus() t2 = None fig = None proposal_id = None limits = {'13A': (245, 200, -20, 0), '13B': (0, 45, 0, 20)} for row in reversed(observation_table.data): date = ephem.date(row.StartDate + 2400000.5 - ephem.julian_date(ephem.date(0))) str_date = str(date) # Saturn only a problem in 2013A fields saturn.compute(date) sra = math.degrees(saturn.ra) sdec = math.degrees(saturn.dec) uranus.compute(date) ura = math.degrees(uranus.ra) udec = math.degrees(uranus.dec) t1 = time.strptime(str_date, "%Y/%m/%d %H:%M:%S") if t2 is None or (math.fabs(time.mktime(t2) - time.mktime( t1)) > 3 * 3600.0 and opt.stack) or proposal_id is None or proposal_id != row.ProposalID: if fig is not None: pdf.savefig() close() proposal_id = row.ProposalID fig = figure(figsize=(7, 2)) ax = fig.add_subplot(111, aspect='equal') ax.set_title("Data taken on %s-%s-%s" % (t1.tm_year, t1.tm_mon, t1.tm_mday), fontdict={'fontsize': 8}) ax.axis(limits.get(row.ProposalID[0:3], (0, 20, 0, 20))) # appropriate only for 2013A fields ax.grid() ax.set_xlabel("RA (deg)", fontdict={'fontsize': 8}) ax.set_ylabel("DEC (deg)", fontdict={'fontsize': 8}) t2 = t1 ra = row.RA - width / 2.0 dec = row.DEC - height / 2.0 color = 'b' if 'W' in row['TargetName']: color = 'g' ax.add_artist(Rectangle(xy=(ra, dec), height=height, width=width, edgecolor=color, facecolor=color, lw=0.5, fill='g', alpha=0.33)) ax.add_artist(Rectangle(xy=(sra, sdec), height=0.3, width=0.3, edgecolor='r', facecolor='r', lw=0.5, fill='k', alpha=0.33)) ax.add_artist(Rectangle(xy=(ura, udec), height=0.3, width=0.3, edgecolor='b', facecolor='b', lw=0.5, fill='b', alpha=0.33)) if ax is not None: ax.axis((270, 215, -20, 0)) pdf.savefig() close() pdf.close() if outfile[0:4] == "vos:": storage.copy(pdf.name, outfile) pdf.close() return
python
def create_sky_plot(observation_table, outfile): """Given a VOTable that describes the observation coverage provide a PDF of the skycoverge. observation_table: vostable.arrary outfile: name of file to write results to. """ # camera dimensions width = 0.98 height = 0.98 ax = None if outfile[0:4] == 'vos:': temp_file = tempfile.NamedTemporaryFile(suffix='.pdf') pdf = PdfPages(temp_file.name) else: pdf = PdfPages(outfile) saturn = ephem.Saturn() uranus = ephem.Uranus() t2 = None fig = None proposal_id = None limits = {'13A': (245, 200, -20, 0), '13B': (0, 45, 0, 20)} for row in reversed(observation_table.data): date = ephem.date(row.StartDate + 2400000.5 - ephem.julian_date(ephem.date(0))) str_date = str(date) # Saturn only a problem in 2013A fields saturn.compute(date) sra = math.degrees(saturn.ra) sdec = math.degrees(saturn.dec) uranus.compute(date) ura = math.degrees(uranus.ra) udec = math.degrees(uranus.dec) t1 = time.strptime(str_date, "%Y/%m/%d %H:%M:%S") if t2 is None or (math.fabs(time.mktime(t2) - time.mktime( t1)) > 3 * 3600.0 and opt.stack) or proposal_id is None or proposal_id != row.ProposalID: if fig is not None: pdf.savefig() close() proposal_id = row.ProposalID fig = figure(figsize=(7, 2)) ax = fig.add_subplot(111, aspect='equal') ax.set_title("Data taken on %s-%s-%s" % (t1.tm_year, t1.tm_mon, t1.tm_mday), fontdict={'fontsize': 8}) ax.axis(limits.get(row.ProposalID[0:3], (0, 20, 0, 20))) # appropriate only for 2013A fields ax.grid() ax.set_xlabel("RA (deg)", fontdict={'fontsize': 8}) ax.set_ylabel("DEC (deg)", fontdict={'fontsize': 8}) t2 = t1 ra = row.RA - width / 2.0 dec = row.DEC - height / 2.0 color = 'b' if 'W' in row['TargetName']: color = 'g' ax.add_artist(Rectangle(xy=(ra, dec), height=height, width=width, edgecolor=color, facecolor=color, lw=0.5, fill='g', alpha=0.33)) ax.add_artist(Rectangle(xy=(sra, sdec), height=0.3, width=0.3, edgecolor='r', facecolor='r', lw=0.5, fill='k', alpha=0.33)) ax.add_artist(Rectangle(xy=(ura, udec), height=0.3, width=0.3, edgecolor='b', facecolor='b', lw=0.5, fill='b', alpha=0.33)) if ax is not None: ax.axis((270, 215, -20, 0)) pdf.savefig() close() pdf.close() if outfile[0:4] == "vos:": storage.copy(pdf.name, outfile) pdf.close() return
[ "def", "create_sky_plot", "(", "observation_table", ",", "outfile", ")", ":", "# camera dimensions", "width", "=", "0.98", "height", "=", "0.98", "ax", "=", "None", "if", "outfile", "[", "0", ":", "4", "]", "==", "'vos:'", ":", "temp_file", "=", "tempfile"...
Given a VOTable that describes the observation coverage provide a PDF of the skycoverge. observation_table: vostable.arrary outfile: name of file to write results to.
[ "Given", "a", "VOTable", "that", "describes", "the", "observation", "coverage", "provide", "a", "PDF", "of", "the", "skycoverge", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/ObsStatus.py#L134-L211
OSSOS/MOP
src/ossos/utils/update_astrometry_files.py
load_observations
def load_observations((observations, regex, rename), path, filenames): """ Returns a provisional name based dictionary of observations of the object. Each observations is keyed on the date. ie. a dictionary of dictionaries. :rtype : None :param observations: dictionary to store observtions into :param path: the directory where filenames are. :param filenames: list of files in path. """ for filename in filenames: if re.search(regex, filename) is None: logging.warning("Skipping {}".format(filename)) continue print os.path.join(path,filename) obs = mpc.MPCReader().read(os.path.join(path,filename)) for ob in obs: if rename: new_provisional_name = os.path.basename(filename) new_provisional_name = new_provisional_name[0:new_provisional_name.find(".")] ob.provisional_name = new_provisional_name # ob.comment.name = new_provisional_name key1 = "{:.5f}".format(ob.date.mjd) key2 = ob.provisional_name if key1 not in observations: observations[key1] = {} if key2 in observations[key1]: if observations[key1][key2]: continue if not observation.null_observation: logger.error(filename) logger.error(line) logger.error(str(observations[key1][key2])) raise ValueError("conflicting observations for {} in {}".format(key2, key1)) observations[key1][key2] = ob
python
def load_observations((observations, regex, rename), path, filenames): """ Returns a provisional name based dictionary of observations of the object. Each observations is keyed on the date. ie. a dictionary of dictionaries. :rtype : None :param observations: dictionary to store observtions into :param path: the directory where filenames are. :param filenames: list of files in path. """ for filename in filenames: if re.search(regex, filename) is None: logging.warning("Skipping {}".format(filename)) continue print os.path.join(path,filename) obs = mpc.MPCReader().read(os.path.join(path,filename)) for ob in obs: if rename: new_provisional_name = os.path.basename(filename) new_provisional_name = new_provisional_name[0:new_provisional_name.find(".")] ob.provisional_name = new_provisional_name # ob.comment.name = new_provisional_name key1 = "{:.5f}".format(ob.date.mjd) key2 = ob.provisional_name if key1 not in observations: observations[key1] = {} if key2 in observations[key1]: if observations[key1][key2]: continue if not observation.null_observation: logger.error(filename) logger.error(line) logger.error(str(observations[key1][key2])) raise ValueError("conflicting observations for {} in {}".format(key2, key1)) observations[key1][key2] = ob
[ "def", "load_observations", "(", "(", "observations", ",", "regex", ",", "rename", ")", ",", "path", ",", "filenames", ")", ":", "for", "filename", "in", "filenames", ":", "if", "re", ".", "search", "(", "regex", ",", "filename", ")", "is", "None", ":"...
Returns a provisional name based dictionary of observations of the object. Each observations is keyed on the date. ie. a dictionary of dictionaries. :rtype : None :param observations: dictionary to store observtions into :param path: the directory where filenames are. :param filenames: list of files in path.
[ "Returns", "a", "provisional", "name", "based", "dictionary", "of", "observations", "of", "the", "object", ".", "Each", "observations", "is", "keyed", "on", "the", "date", ".", "ie", ".", "a", "dictionary", "of", "dictionaries", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/update_astrometry_files.py#L14-L49
OSSOS/MOP
src/ossos/core/ossos/mopheader.py
MOPHeader.writeto
def writeto(self, filename, **kwargs): """ Write the header to a fits file. :param filename: :return: """ fits.PrimaryHDU(header=self).writeto(filename, output_verify='ignore', **kwargs)
python
def writeto(self, filename, **kwargs): """ Write the header to a fits file. :param filename: :return: """ fits.PrimaryHDU(header=self).writeto(filename, output_verify='ignore', **kwargs)
[ "def", "writeto", "(", "self", ",", "filename", ",", "*", "*", "kwargs", ")", ":", "fits", ".", "PrimaryHDU", "(", "header", "=", "self", ")", ".", "writeto", "(", "filename", ",", "output_verify", "=", "'ignore'", ",", "*", "*", "kwargs", ")" ]
Write the header to a fits file. :param filename: :return:
[ "Write", "the", "header", "to", "a", "fits", "file", ".", ":", "param", "filename", ":", ":", "return", ":" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mopheader.py#L74-L80
OSSOS/MOP
src/ossos/core/ossos/mopheader.py
MOPHeader.crpix
def crpix(self): """ The location of the reference coordinate in the pixel frame. First simple respond with the header values, if they don't exist try usnig the DETSEC values @rtype: float, float """ try: return self.wcs.crpix1, self.wcs.crpix2 except Exception as ex: logging.debug("Couldn't get CRPIX from WCS: {}".format(ex)) logging.debug("Switching to use DATASEC for CRPIX value computation.") try: (x1, x2), (y1, y2) = util.get_pixel_bounds_from_datasec_keyword(self['DETSEC']) dx = float(self['NAXIS1']) dy = float(self['NAXIS2']) except KeyError as ke: raise KeyError("Header missing keyword: {}, required for CRPIX[12] computation".format(ke.args[0])) crpix1 = self._DET_X_CEN - (x1 + x2) / 2. + dx / 2. crpix2 = self._DET_Y_CEN - (y1 + y2) / 2. + dy / 2. return crpix1, crpix2
python
def crpix(self): """ The location of the reference coordinate in the pixel frame. First simple respond with the header values, if they don't exist try usnig the DETSEC values @rtype: float, float """ try: return self.wcs.crpix1, self.wcs.crpix2 except Exception as ex: logging.debug("Couldn't get CRPIX from WCS: {}".format(ex)) logging.debug("Switching to use DATASEC for CRPIX value computation.") try: (x1, x2), (y1, y2) = util.get_pixel_bounds_from_datasec_keyword(self['DETSEC']) dx = float(self['NAXIS1']) dy = float(self['NAXIS2']) except KeyError as ke: raise KeyError("Header missing keyword: {}, required for CRPIX[12] computation".format(ke.args[0])) crpix1 = self._DET_X_CEN - (x1 + x2) / 2. + dx / 2. crpix2 = self._DET_Y_CEN - (y1 + y2) / 2. + dy / 2. return crpix1, crpix2
[ "def", "crpix", "(", "self", ")", ":", "try", ":", "return", "self", ".", "wcs", ".", "crpix1", ",", "self", ".", "wcs", ".", "crpix2", "except", "Exception", "as", "ex", ":", "logging", ".", "debug", "(", "\"Couldn't get CRPIX from WCS: {}\"", ".", "for...
The location of the reference coordinate in the pixel frame. First simple respond with the header values, if they don't exist try usnig the DETSEC values @rtype: float, float
[ "The", "location", "of", "the", "reference", "coordinate", "in", "the", "pixel", "frame", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mopheader.py#L99-L122
OSSOS/MOP
src/ossos/core/ossos/mopheader.py
MOPHeader.mjd_obsc
def mjd_obsc(self): """Given a CFHT Megaprime image header compute the center of exposure. This routine uses the calibration provide by Richard Wainscoat: From: Richard Wainscoat <[email protected]> Subject: Fwd: timing for MegaCam Date: April 24, 2015 at 7:23:09 PM EDT To: David Tholen <[email protected]> Looks like the midpoint of the exposure is now UTCEND - 0.73 sec - (exposure time / 2 ) Wobble on the 0.73 sec is +/- 0.15 sec. @rtype : float """ # TODO Check if this exposure was taken afer or before correction needed. try: utc_end = self['UTCEND'] exposure_time = float(self['EXPTIME']) date_obs = self['DATE-OBS'] except KeyError as ke: raise KeyError("Header missing keyword: {}, required for MJD-OBSC computation".format(ke.args[0])) utc_end = Time(date_obs + "T" + utc_end) utc_cen = utc_end - TimeDelta(0.73, format='sec') - TimeDelta(exposure_time / 2.0, format='sec') return round(utc_cen.mjd, 7)
python
def mjd_obsc(self): """Given a CFHT Megaprime image header compute the center of exposure. This routine uses the calibration provide by Richard Wainscoat: From: Richard Wainscoat <[email protected]> Subject: Fwd: timing for MegaCam Date: April 24, 2015 at 7:23:09 PM EDT To: David Tholen <[email protected]> Looks like the midpoint of the exposure is now UTCEND - 0.73 sec - (exposure time / 2 ) Wobble on the 0.73 sec is +/- 0.15 sec. @rtype : float """ # TODO Check if this exposure was taken afer or before correction needed. try: utc_end = self['UTCEND'] exposure_time = float(self['EXPTIME']) date_obs = self['DATE-OBS'] except KeyError as ke: raise KeyError("Header missing keyword: {}, required for MJD-OBSC computation".format(ke.args[0])) utc_end = Time(date_obs + "T" + utc_end) utc_cen = utc_end - TimeDelta(0.73, format='sec') - TimeDelta(exposure_time / 2.0, format='sec') return round(utc_cen.mjd, 7)
[ "def", "mjd_obsc", "(", "self", ")", ":", "# TODO Check if this exposure was taken afer or before correction needed.", "try", ":", "utc_end", "=", "self", "[", "'UTCEND'", "]", "exposure_time", "=", "float", "(", "self", "[", "'EXPTIME'", "]", ")", "date_obs", "=", ...
Given a CFHT Megaprime image header compute the center of exposure. This routine uses the calibration provide by Richard Wainscoat: From: Richard Wainscoat <[email protected]> Subject: Fwd: timing for MegaCam Date: April 24, 2015 at 7:23:09 PM EDT To: David Tholen <[email protected]> Looks like the midpoint of the exposure is now UTCEND - 0.73 sec - (exposure time / 2 ) Wobble on the 0.73 sec is +/- 0.15 sec. @rtype : float
[ "Given", "a", "CFHT", "Megaprime", "image", "header", "compute", "the", "center", "of", "exposure", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mopheader.py#L125-L151
OSSOS/MOP
src/ossos/core/ossos/mopheader.py
MOPHeader.crval
def crval(self): """ Get the world coordinate of the reference pixel. @rtype: float, float """ try: return self.wcs.crval1, self.wcs.crval2 except Exception as ex: logging.debug("Couldn't get CRVAL from WCS: {}".format(ex)) logging.debug("Trying RA/DEC values") try: return (float(self['RA-DEG']), float(self['DEC-DEG'])) except KeyError as ke: KeyError("Can't build CRVAL1/2 missing keyword: {}".format(ke.args[0]))
python
def crval(self): """ Get the world coordinate of the reference pixel. @rtype: float, float """ try: return self.wcs.crval1, self.wcs.crval2 except Exception as ex: logging.debug("Couldn't get CRVAL from WCS: {}".format(ex)) logging.debug("Trying RA/DEC values") try: return (float(self['RA-DEG']), float(self['DEC-DEG'])) except KeyError as ke: KeyError("Can't build CRVAL1/2 missing keyword: {}".format(ke.args[0]))
[ "def", "crval", "(", "self", ")", ":", "try", ":", "return", "self", ".", "wcs", ".", "crval1", ",", "self", ".", "wcs", ".", "crval2", "except", "Exception", "as", "ex", ":", "logging", ".", "debug", "(", "\"Couldn't get CRVAL from WCS: {}\"", ".", "for...
Get the world coordinate of the reference pixel. @rtype: float, float
[ "Get", "the", "world", "coordinate", "of", "the", "reference", "pixel", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mopheader.py#L154-L170
OSSOS/MOP
src/ossos/core/ossos/mopheader.py
MOPHeader.pixscale
def pixscale(self): """Return the pixel scale of the detector, in arcseconds. This routine first attempts to compute the size of a pixel using the WCS. Then looks for PIXSCAL in header. @return: pixscal @rtype: float """ try: (x, y) = self['NAXIS1'] / 2.0, self['NAXIS2'] / 2.0 p1 = SkyCoord(*self.wcs.xy2sky(x, y) * units.degree) p2 = SkyCoord(*self.wcs.xy2sky(x + 1, y + 1) * units.degree) return round(p1.separation(p2).to(units.arcsecond).value / math.sqrt(2), 3) except Exception as ex: logging.debug("Failed to compute PIXSCALE using WCS: {}".format(ex)) return float(self['PIXSCAL'])
python
def pixscale(self): """Return the pixel scale of the detector, in arcseconds. This routine first attempts to compute the size of a pixel using the WCS. Then looks for PIXSCAL in header. @return: pixscal @rtype: float """ try: (x, y) = self['NAXIS1'] / 2.0, self['NAXIS2'] / 2.0 p1 = SkyCoord(*self.wcs.xy2sky(x, y) * units.degree) p2 = SkyCoord(*self.wcs.xy2sky(x + 1, y + 1) * units.degree) return round(p1.separation(p2).to(units.arcsecond).value / math.sqrt(2), 3) except Exception as ex: logging.debug("Failed to compute PIXSCALE using WCS: {}".format(ex)) return float(self['PIXSCAL'])
[ "def", "pixscale", "(", "self", ")", ":", "try", ":", "(", "x", ",", "y", ")", "=", "self", "[", "'NAXIS1'", "]", "/", "2.0", ",", "self", "[", "'NAXIS2'", "]", "/", "2.0", "p1", "=", "SkyCoord", "(", "*", "self", ".", "wcs", ".", "xy2sky", "...
Return the pixel scale of the detector, in arcseconds. This routine first attempts to compute the size of a pixel using the WCS. Then looks for PIXSCAL in header. @return: pixscal @rtype: float
[ "Return", "the", "pixel", "scale", "of", "the", "detector", "in", "arcseconds", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mopheader.py#L173-L189
OSSOS/MOP
src/jjk/preproc/MOPphot.py
iraf_phot
def iraf_phot(f,x,y,zmag=26.5,apin=10,skyin=15,skywidth=10): """Compute the magnitude of the star at location x/y""" import pyfits import re infits=pyfits.open(f,'update') f=re.sub(r'.fits$','',f) ### Get my python routines from pyraf import iraf from pyraf.irafpar import IrafParList ### keep all the parameters locally cached. iraf.set(uparm="./") iraf.set(imtype="fits") ### Load the required IRAF packages iraf.digiphot() iraf.apphot() iraf.daophot() ### temp file name hash. tfile={} iraf.datapars.datamax=60000 iraf.datapars.datamin=-1000 iraf.datapars.airmass='AIRMASS' iraf.datapars.filter='FILTER' iraf.datapars.obstime='TIME-OBS' iraf.datapars.exposure='EXPTIME' iraf.datapars.gain='GAIN' iraf.datapars.ccdread='RDNOISE' iraf.datapars.fwhmpsf=5.0 iraf.centerpars.calgorithm='centroid' iraf.photpars.zmag=zmag iraf.photpars.apertures=apin iraf.fitskypars.annulus=skyin iraf.fitskypars.dannulus=skywidth iraf.daophot.verbose=iraf.no iraf.daophot.verify=iraf.no iraf.daophot.update=iraf.no iraf.psf.interactive=iraf.no iraf.pstselect.interactive=iraf.no iraf.datapars.saveParList() iraf.fitskypars.saveParList() iraf.centerpars.saveParList() iraf.findpars.saveParList() iraf.photpars.saveParList() tfiles = ['coo','mag'] for file in tfiles: extname=f tfile[file]=extname+"."+file if ( os.access(tfile[file],os.F_OK) ): os.unlink(tfile[file]) this_image=f fd = open(tfile['coo'],'w') fd.write('%f %f\n' % ( x, y) ) fd.close() print "Measuring photometry psf star in "+tfile['coo'] iraf.daophot.phot(image=this_image, coords=tfile['coo'], output=tfile['mag']) import string a=iraf.txdump(tfile['mag'],"MAG,XCEN,YCEN",iraf.yes,Stdout=1) (mag,x,y)=string.split(a[0]) inhdu=infits[0].header inhdu.update("PSFMAG",float(mag),comment="PSF Magnitude") inhdu.update("PSF_X",float(x),comment="PSF Magnitude") inhdu.update("PSF_Y",float(y),comment="PSF Magnitude") inhdu.update("ZMAG",zmag,comment="ZMAG of PSF ") ## now measure using a smaller aperture to get aper correction iraf.photpars.apertures=apin*3.0 os.unlink(tfile['mag']) iraf.daophot.phot(image=this_image, coords=tfile['coo'], output=tfile['mag']) a=iraf.txdump(tfile['mag'],"MAG,XCEN,YCEN",iraf.yes,Stdout=1) (magout,x,y)=string.split(a[0]) inhdu.update("APCOR",float(magout)-float(mag),comment="AP_OUT - AP_IN") inhdu.update("AP_IN",apin*3.0,comment="Small aperature") inhdu.update("AP_OUT",apin,comment="Large aperture") # ### append this psf to the output images.... infits.close() ### remove the temp file we used for this computation. #for tf in tfile.keys(): # if os.access(tfile[tf],os.F_OK): # os.unlink(tfile[tf]) return 0
python
def iraf_phot(f,x,y,zmag=26.5,apin=10,skyin=15,skywidth=10): """Compute the magnitude of the star at location x/y""" import pyfits import re infits=pyfits.open(f,'update') f=re.sub(r'.fits$','',f) ### Get my python routines from pyraf import iraf from pyraf.irafpar import IrafParList ### keep all the parameters locally cached. iraf.set(uparm="./") iraf.set(imtype="fits") ### Load the required IRAF packages iraf.digiphot() iraf.apphot() iraf.daophot() ### temp file name hash. tfile={} iraf.datapars.datamax=60000 iraf.datapars.datamin=-1000 iraf.datapars.airmass='AIRMASS' iraf.datapars.filter='FILTER' iraf.datapars.obstime='TIME-OBS' iraf.datapars.exposure='EXPTIME' iraf.datapars.gain='GAIN' iraf.datapars.ccdread='RDNOISE' iraf.datapars.fwhmpsf=5.0 iraf.centerpars.calgorithm='centroid' iraf.photpars.zmag=zmag iraf.photpars.apertures=apin iraf.fitskypars.annulus=skyin iraf.fitskypars.dannulus=skywidth iraf.daophot.verbose=iraf.no iraf.daophot.verify=iraf.no iraf.daophot.update=iraf.no iraf.psf.interactive=iraf.no iraf.pstselect.interactive=iraf.no iraf.datapars.saveParList() iraf.fitskypars.saveParList() iraf.centerpars.saveParList() iraf.findpars.saveParList() iraf.photpars.saveParList() tfiles = ['coo','mag'] for file in tfiles: extname=f tfile[file]=extname+"."+file if ( os.access(tfile[file],os.F_OK) ): os.unlink(tfile[file]) this_image=f fd = open(tfile['coo'],'w') fd.write('%f %f\n' % ( x, y) ) fd.close() print "Measuring photometry psf star in "+tfile['coo'] iraf.daophot.phot(image=this_image, coords=tfile['coo'], output=tfile['mag']) import string a=iraf.txdump(tfile['mag'],"MAG,XCEN,YCEN",iraf.yes,Stdout=1) (mag,x,y)=string.split(a[0]) inhdu=infits[0].header inhdu.update("PSFMAG",float(mag),comment="PSF Magnitude") inhdu.update("PSF_X",float(x),comment="PSF Magnitude") inhdu.update("PSF_Y",float(y),comment="PSF Magnitude") inhdu.update("ZMAG",zmag,comment="ZMAG of PSF ") ## now measure using a smaller aperture to get aper correction iraf.photpars.apertures=apin*3.0 os.unlink(tfile['mag']) iraf.daophot.phot(image=this_image, coords=tfile['coo'], output=tfile['mag']) a=iraf.txdump(tfile['mag'],"MAG,XCEN,YCEN",iraf.yes,Stdout=1) (magout,x,y)=string.split(a[0]) inhdu.update("APCOR",float(magout)-float(mag),comment="AP_OUT - AP_IN") inhdu.update("AP_IN",apin*3.0,comment="Small aperature") inhdu.update("AP_OUT",apin,comment="Large aperture") # ### append this psf to the output images.... infits.close() ### remove the temp file we used for this computation. #for tf in tfile.keys(): # if os.access(tfile[tf],os.F_OK): # os.unlink(tfile[tf]) return 0
[ "def", "iraf_phot", "(", "f", ",", "x", ",", "y", ",", "zmag", "=", "26.5", ",", "apin", "=", "10", ",", "skyin", "=", "15", ",", "skywidth", "=", "10", ")", ":", "import", "pyfits", "import", "re", "infits", "=", "pyfits", ".", "open", "(", "f...
Compute the magnitude of the star at location x/y
[ "Compute", "the", "magnitude", "of", "the", "star", "at", "location", "x", "/", "y" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPphot.py#L59-L164
OSSOS/MOP
src/jjk/preproc/rate.py
get_rates
def get_rates(file,au_min=25,au_max=150): """ Use the rates program to determine the minimum and maximum bounds for planting""" import os, string rate_command='rate.pl --file %s %d ' % ( file, au_min) rate=os.popen(rate_command) line=rate.readline() print line rate.close() (min_rate, min_ang, min_aw, min_rmin, min_rmax)=string.split(line) rate_command='rate.pl --file %s %d ' % ( file, au_min) rate=os.popen(rate_command) line=rate.readline() rate.close() (max_rate, max_ang, max_aw, max_rmin, max_rmax)=string.split(line) rmin=float(min(max_rmin, min_rmin)) rmax=float(max(max_rmax, min_rmax)) aw=float(max(max_aw,min_aw)) angle=(float(max_ang)+float(min_ang))/2.0 rates={'rmin': rmin, 'rmax': rmax, 'angle': angle, 'aw': aw} return rates
python
def get_rates(file,au_min=25,au_max=150): """ Use the rates program to determine the minimum and maximum bounds for planting""" import os, string rate_command='rate.pl --file %s %d ' % ( file, au_min) rate=os.popen(rate_command) line=rate.readline() print line rate.close() (min_rate, min_ang, min_aw, min_rmin, min_rmax)=string.split(line) rate_command='rate.pl --file %s %d ' % ( file, au_min) rate=os.popen(rate_command) line=rate.readline() rate.close() (max_rate, max_ang, max_aw, max_rmin, max_rmax)=string.split(line) rmin=float(min(max_rmin, min_rmin)) rmax=float(max(max_rmax, min_rmax)) aw=float(max(max_aw,min_aw)) angle=(float(max_ang)+float(min_ang))/2.0 rates={'rmin': rmin, 'rmax': rmax, 'angle': angle, 'aw': aw} return rates
[ "def", "get_rates", "(", "file", ",", "au_min", "=", "25", ",", "au_max", "=", "150", ")", ":", "import", "os", ",", "string", "rate_command", "=", "'rate.pl --file %s %d '", "%", "(", "file", ",", "au_min", ")", "rate", "=", "os", ".", "popen", "(", ...
Use the rates program to determine the minimum and maximum bounds for planting
[ "Use", "the", "rates", "program", "to", "determine", "the", "minimum", "and", "maximum", "bounds", "for", "planting" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/rate.py#L7-L27
OSSOS/MOP
src/jjk/preproc/rate.py
kbo_gen
def kbo_gen(file,outfile='objects.list',mmin=22.5,mmax=24.5): """Generate a file with object moving at a range of rates and angles""" header=get_rates(file) print header import pyfits hdulist=pyfits.open(file) header['xmin']=1 header['xmax']=hdulist[0].header.get('NAXIS1',2048) header['ymin']=1 header['aw']=round(header['aw'],2) header['angle']=round(header['angle'],2) header['ymax']=hdulist[0].header.get('NAXIS2',4096) header['pixscale']=hdulist[0].header.get('PIXSCALE',0.185) header['rmax']=round(float(header['rmax'])/float(header['pixscale']),2) header['rmin']=round(float(header['rmin'])/float(header['pixscale']),2) header['mmin']=mmin header['mmax']=mmax header['expnum']=hdulist[0].header.get('EXPNUM',1000000) header['chipnum']=hdulist[0].header.get('CHIPNUM') import random number = 250 cdata={'x': [], 'y': [], 'mag': [], 'pix_rate': [], 'angle': [], 'id':[]} order=['x','y','mag','pix_rate','angle','arc_rate','id'] for i in range(number): cdata['x'].append( random.uniform(header['xmin'],header['xmax'])) cdata['y'].append( random.uniform(header['ymin'],header['ymax'])) cdata['pix_rate'].append( random.uniform(header['rmin'],header['rmax'])) cdata['angle'].append(random.uniform(header['angle']-header['aw'], header['angle']+header['aw'])) cdata['mag'].append(random.uniform(header['mmin'],header['mmax'])) cdata['id'].append(i) hdu={'data': cdata, 'header': header} return hdu
python
def kbo_gen(file,outfile='objects.list',mmin=22.5,mmax=24.5): """Generate a file with object moving at a range of rates and angles""" header=get_rates(file) print header import pyfits hdulist=pyfits.open(file) header['xmin']=1 header['xmax']=hdulist[0].header.get('NAXIS1',2048) header['ymin']=1 header['aw']=round(header['aw'],2) header['angle']=round(header['angle'],2) header['ymax']=hdulist[0].header.get('NAXIS2',4096) header['pixscale']=hdulist[0].header.get('PIXSCALE',0.185) header['rmax']=round(float(header['rmax'])/float(header['pixscale']),2) header['rmin']=round(float(header['rmin'])/float(header['pixscale']),2) header['mmin']=mmin header['mmax']=mmax header['expnum']=hdulist[0].header.get('EXPNUM',1000000) header['chipnum']=hdulist[0].header.get('CHIPNUM') import random number = 250 cdata={'x': [], 'y': [], 'mag': [], 'pix_rate': [], 'angle': [], 'id':[]} order=['x','y','mag','pix_rate','angle','arc_rate','id'] for i in range(number): cdata['x'].append( random.uniform(header['xmin'],header['xmax'])) cdata['y'].append( random.uniform(header['ymin'],header['ymax'])) cdata['pix_rate'].append( random.uniform(header['rmin'],header['rmax'])) cdata['angle'].append(random.uniform(header['angle']-header['aw'], header['angle']+header['aw'])) cdata['mag'].append(random.uniform(header['mmin'],header['mmax'])) cdata['id'].append(i) hdu={'data': cdata, 'header': header} return hdu
[ "def", "kbo_gen", "(", "file", ",", "outfile", "=", "'objects.list'", ",", "mmin", "=", "22.5", ",", "mmax", "=", "24.5", ")", ":", "header", "=", "get_rates", "(", "file", ")", "print", "header", "import", "pyfits", "hdulist", "=", "pyfits", ".", "ope...
Generate a file with object moving at a range of rates and angles
[ "Generate", "a", "file", "with", "object", "moving", "at", "a", "range", "of", "rates", "and", "angles" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/rate.py#L29-L64
OSSOS/MOP
src/ossos/utils/get_image_lists.py
main
def main(): """ Input asteroid family, filter type, and image type to query SSOIS """ parser = argparse.ArgumentParser(description='Run SSOIS and return the available images in a particular filter.') parser.add_argument("--filter", action="store", default='r', dest="filter", choices=['r', 'u'], help="Passband: default is r.") parser.add_argument("--family", '-f', action="store", default=None, help='List of objects to query.') parser.add_argument("--member", '-m', action="store", default=None, help='Member object of family to query.') args = parser.parse_args() if args.family != None and args.member == None: get_family_info(str(args.family), args.filter) elif args.family == None and args.member != None: get_member_info(str(args.member), args.filter) else: print "Please input either a family or single member name"
python
def main(): """ Input asteroid family, filter type, and image type to query SSOIS """ parser = argparse.ArgumentParser(description='Run SSOIS and return the available images in a particular filter.') parser.add_argument("--filter", action="store", default='r', dest="filter", choices=['r', 'u'], help="Passband: default is r.") parser.add_argument("--family", '-f', action="store", default=None, help='List of objects to query.') parser.add_argument("--member", '-m', action="store", default=None, help='Member object of family to query.') args = parser.parse_args() if args.family != None and args.member == None: get_family_info(str(args.family), args.filter) elif args.family == None and args.member != None: get_member_info(str(args.member), args.filter) else: print "Please input either a family or single member name"
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Run SSOIS and return the available images in a particular filter.'", ")", "parser", ".", "add_argument", "(", "\"--filter\"", ",", "action", "=", "\"store\"", ",...
Input asteroid family, filter type, and image type to query SSOIS
[ "Input", "asteroid", "family", "filter", "type", "and", "image", "type", "to", "query", "SSOIS" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/get_image_lists.py#L17-L46
OSSOS/MOP
src/ossos/utils/get_image_lists.py
get_family_info
def get_family_info(familyname, filtertype='r', imagetype='p'): """ Query the ssois table for images of objects in a given family. Then parse through for desired image type, filter, exposure time, and telescope instrument """ # establish input family_list = '{}/{}_family.txt'.format(_FAMILY_LISTS, familyname) if os.path.exists(family_list): with open(family_list) as infile: filestr = infile.read() object_list = filestr.split('\n') # array of objects to query elif familyname == 'all': object_list = find_family.get_all_families_list() else: object_list = find_family.find_family_members(familyname) for obj in object_list[0:len(object_list) - 1]: # skip header lines get_member_info(obj, filtertype)
python
def get_family_info(familyname, filtertype='r', imagetype='p'): """ Query the ssois table for images of objects in a given family. Then parse through for desired image type, filter, exposure time, and telescope instrument """ # establish input family_list = '{}/{}_family.txt'.format(_FAMILY_LISTS, familyname) if os.path.exists(family_list): with open(family_list) as infile: filestr = infile.read() object_list = filestr.split('\n') # array of objects to query elif familyname == 'all': object_list = find_family.get_all_families_list() else: object_list = find_family.find_family_members(familyname) for obj in object_list[0:len(object_list) - 1]: # skip header lines get_member_info(obj, filtertype)
[ "def", "get_family_info", "(", "familyname", ",", "filtertype", "=", "'r'", ",", "imagetype", "=", "'p'", ")", ":", "# establish input", "family_list", "=", "'{}/{}_family.txt'", ".", "format", "(", "_FAMILY_LISTS", ",", "familyname", ")", "if", "os", ".", "pa...
Query the ssois table for images of objects in a given family. Then parse through for desired image type, filter, exposure time, and telescope instrument
[ "Query", "the", "ssois", "table", "for", "images", "of", "objects", "in", "a", "given", "family", ".", "Then", "parse", "through", "for", "desired", "image", "type", "filter", "exposure", "time", "and", "telescope", "instrument" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/get_image_lists.py#L49-L68
OSSOS/MOP
src/ossos/utils/get_image_lists.py
get_member_info
def get_member_info(object_name, filtertype='r', imagetype='p'): """ Query the ssois table for images of a given object. Then parse through for desired image type, filter, exposure time, and telescope instrument """ # From the given input, identify the desired filter and rename appropriately Replace this? if filtertype.lower().__contains__('r'): filtertype = 'r.MP9601' # this is the old (standard) r filter for MegaCam if filtertype.lower().__contains__('u'): filtertype = 'u.MP9301' # Define time period of image search, basically while MegaCam in operation search_start_date = Time('2013-01-01', scale='utc') # epoch1=2013+01+01 search_end_date = Time('2017-01-01', scale='utc') # epoch2=2017+1+1 print("----- Searching for images of object {}".format(object_name)) image_list = [] expnum_list = [] ra_list = [] dec_list = [] query = Query(object_name, search_start_date=search_start_date, search_end_date=search_end_date) result = query.get() print(result) try: objects = parse_ssois_return(query.get(), object_name, imagetype, camera_filter=filtertype) except IOError: print("Sleeping 30 seconds") time.sleep(30) objects = parse_ssois_return(query.get(), object_name, imagetype, camera_filter=filtertype) print(objects) # Setup output, label columns if len(objects)>0: output = '{}/{}_object_images.txt'.format(_OUTPUT_DIR, object_name) with open(output, 'w') as outfile: outfile.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( "Object", "Image", "Exp_time", "RA (deg)", "Dec (deg)", "time", "filter", "RA rate (\"/hr)", "Dec rate (\"/hr)")) for line in objects: with open(output, 'a') as outfile: image_list.append(object_name) expnum_list.append(line['Exptime']) t_start = Time(line['MJD'], format='mjd', scale='utc') - 1.0 * units.minute t_stop = t_start + 2 * units.minute hq = horizons.Query(object_name) hq.start_time = t_start hq.stop_time = t_stop hq.step_size = 1 * units.minute p_ra = hq.table[1]['R.A._(ICRF/J2000.0'] p_dec = hq.table[1]['DEC_(ICRF/J2000.0'] ra_dot = hq.table[1]['dRA*cosD'] dec_dot = hq.table[1]['dDEC/dt'] try: outfile.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( object_name, line['Image'], line['Exptime'], p_ra, p_dec, Time(line['MJD'], format='mjd', scale='utc'), line['Filter'], ra_dot, dec_dot)) except Exception as e: print("Error writing to outfile: {}".format(e)) return image_list, expnum_list, ra_list, dec_list
python
def get_member_info(object_name, filtertype='r', imagetype='p'): """ Query the ssois table for images of a given object. Then parse through for desired image type, filter, exposure time, and telescope instrument """ # From the given input, identify the desired filter and rename appropriately Replace this? if filtertype.lower().__contains__('r'): filtertype = 'r.MP9601' # this is the old (standard) r filter for MegaCam if filtertype.lower().__contains__('u'): filtertype = 'u.MP9301' # Define time period of image search, basically while MegaCam in operation search_start_date = Time('2013-01-01', scale='utc') # epoch1=2013+01+01 search_end_date = Time('2017-01-01', scale='utc') # epoch2=2017+1+1 print("----- Searching for images of object {}".format(object_name)) image_list = [] expnum_list = [] ra_list = [] dec_list = [] query = Query(object_name, search_start_date=search_start_date, search_end_date=search_end_date) result = query.get() print(result) try: objects = parse_ssois_return(query.get(), object_name, imagetype, camera_filter=filtertype) except IOError: print("Sleeping 30 seconds") time.sleep(30) objects = parse_ssois_return(query.get(), object_name, imagetype, camera_filter=filtertype) print(objects) # Setup output, label columns if len(objects)>0: output = '{}/{}_object_images.txt'.format(_OUTPUT_DIR, object_name) with open(output, 'w') as outfile: outfile.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( "Object", "Image", "Exp_time", "RA (deg)", "Dec (deg)", "time", "filter", "RA rate (\"/hr)", "Dec rate (\"/hr)")) for line in objects: with open(output, 'a') as outfile: image_list.append(object_name) expnum_list.append(line['Exptime']) t_start = Time(line['MJD'], format='mjd', scale='utc') - 1.0 * units.minute t_stop = t_start + 2 * units.minute hq = horizons.Query(object_name) hq.start_time = t_start hq.stop_time = t_stop hq.step_size = 1 * units.minute p_ra = hq.table[1]['R.A._(ICRF/J2000.0'] p_dec = hq.table[1]['DEC_(ICRF/J2000.0'] ra_dot = hq.table[1]['dRA*cosD'] dec_dot = hq.table[1]['dDEC/dt'] try: outfile.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( object_name, line['Image'], line['Exptime'], p_ra, p_dec, Time(line['MJD'], format='mjd', scale='utc'), line['Filter'], ra_dot, dec_dot)) except Exception as e: print("Error writing to outfile: {}".format(e)) return image_list, expnum_list, ra_list, dec_list
[ "def", "get_member_info", "(", "object_name", ",", "filtertype", "=", "'r'", ",", "imagetype", "=", "'p'", ")", ":", "# From the given input, identify the desired filter and rename appropriately Replace this?", "if", "filtertype", ".", "lower", "(", ")", ...
Query the ssois table for images of a given object. Then parse through for desired image type, filter, exposure time, and telescope instrument
[ "Query", "the", "ssois", "table", "for", "images", "of", "a", "given", "object", ".", "Then", "parse", "through", "for", "desired", "image", "type", "filter", "exposure", "time", "and", "telescope", "instrument" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/get_image_lists.py#L71-L133
OSSOS/MOP
src/ossos/utils/get_image_lists.py
parse_ssois_return
def parse_ssois_return(ssois_return, object_name, imagetype, camera_filter='r.MP9601', telescope_instrument='CFHT/MegaCam'): """ Parse through objects in ssois query and filter out images of desired filter, type, exposure time, and instrument """ assert camera_filter in ['r.MP9601', 'u.MP9301'] ret_table = [] good_table = 0 table_reader = ascii.get_reader(Reader=ascii.Basic) table_reader.inconsistent_handler = _skip_missing_data table_reader.header.splitter.delimiter = '\t' table_reader.data.splitter.delimiter = '\t' table = table_reader.read(ssois_return) for row in table: # Excludes the OSSOS wallpaper. # note: 'Telescope_Insturment' is a typo in SSOIS's return format if not 'MegaCam' in row['Telescope_Insturment']: continue # Check if image of object exists in OSSOS observations if not storage.exists(storage.get_uri(row['Image'][:-1])): continue if not str(row['Image_target']).startswith('WP'): good_table += 1 ret_table.append(row) if good_table > 0: print(" %d images found" % good_table) return ret_table
python
def parse_ssois_return(ssois_return, object_name, imagetype, camera_filter='r.MP9601', telescope_instrument='CFHT/MegaCam'): """ Parse through objects in ssois query and filter out images of desired filter, type, exposure time, and instrument """ assert camera_filter in ['r.MP9601', 'u.MP9301'] ret_table = [] good_table = 0 table_reader = ascii.get_reader(Reader=ascii.Basic) table_reader.inconsistent_handler = _skip_missing_data table_reader.header.splitter.delimiter = '\t' table_reader.data.splitter.delimiter = '\t' table = table_reader.read(ssois_return) for row in table: # Excludes the OSSOS wallpaper. # note: 'Telescope_Insturment' is a typo in SSOIS's return format if not 'MegaCam' in row['Telescope_Insturment']: continue # Check if image of object exists in OSSOS observations if not storage.exists(storage.get_uri(row['Image'][:-1])): continue if not str(row['Image_target']).startswith('WP'): good_table += 1 ret_table.append(row) if good_table > 0: print(" %d images found" % good_table) return ret_table
[ "def", "parse_ssois_return", "(", "ssois_return", ",", "object_name", ",", "imagetype", ",", "camera_filter", "=", "'r.MP9601'", ",", "telescope_instrument", "=", "'CFHT/MegaCam'", ")", ":", "assert", "camera_filter", "in", "[", "'r.MP9601'", ",", "'u.MP9301'", "]",...
Parse through objects in ssois query and filter out images of desired filter, type, exposure time, and instrument
[ "Parse", "through", "objects", "in", "ssois", "query", "and", "filter", "out", "images", "of", "desired", "filter", "type", "exposure", "time", "and", "instrument" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/get_image_lists.py#L136-L168
OSSOS/MOP
src/ossos/core/ossos/match.py
match_mopfiles
def match_mopfiles(mopfile1, mopfile2): """ Given an input list of 'real' detections and candidate detections provide a result file that contains the measured values from candidate detections with a flag indicating if they are real or false. @rtype MOPFile @return mopfile2 with a new column containing index of matching entry in mopfile1 """ pos1 = pos2 = numpy.array([]) if len(mopfile1.data) > 0: X_COL = "X_{}".format(mopfile1.header.file_ids[0]) Y_COL = "Y_{}".format(mopfile1.header.file_ids[0]) pos1 = numpy.array([mopfile1.data[X_COL].data, mopfile1.data[Y_COL].data]).transpose() if len(mopfile2.data) > 0: X_COL = "X_{}".format(mopfile2.header.file_ids[0]) Y_COL = "Y_{}".format(mopfile2.header.file_ids[0]) pos2 = numpy.array([mopfile2.data[X_COL].data, mopfile2.data[Y_COL].data]).transpose() # match_idx is an order list. The list is in the order of the first list of positions and each entry # is the index of the matching position from the second list. match_idx1, match_idx2 = util.match_lists(pos1, pos2) mopfile1.data.add_column(Column(data=match_idx1.filled(-1), name="real", length=len(mopfile1.data))) idx = 0 for file_id in mopfile1.header.file_ids: idx += 1 mopfile1.data.add_column(Column(data=[file_id]*len(mopfile1.data), name="ID_{}".format(idx))) return mopfile1
python
def match_mopfiles(mopfile1, mopfile2): """ Given an input list of 'real' detections and candidate detections provide a result file that contains the measured values from candidate detections with a flag indicating if they are real or false. @rtype MOPFile @return mopfile2 with a new column containing index of matching entry in mopfile1 """ pos1 = pos2 = numpy.array([]) if len(mopfile1.data) > 0: X_COL = "X_{}".format(mopfile1.header.file_ids[0]) Y_COL = "Y_{}".format(mopfile1.header.file_ids[0]) pos1 = numpy.array([mopfile1.data[X_COL].data, mopfile1.data[Y_COL].data]).transpose() if len(mopfile2.data) > 0: X_COL = "X_{}".format(mopfile2.header.file_ids[0]) Y_COL = "Y_{}".format(mopfile2.header.file_ids[0]) pos2 = numpy.array([mopfile2.data[X_COL].data, mopfile2.data[Y_COL].data]).transpose() # match_idx is an order list. The list is in the order of the first list of positions and each entry # is the index of the matching position from the second list. match_idx1, match_idx2 = util.match_lists(pos1, pos2) mopfile1.data.add_column(Column(data=match_idx1.filled(-1), name="real", length=len(mopfile1.data))) idx = 0 for file_id in mopfile1.header.file_ids: idx += 1 mopfile1.data.add_column(Column(data=[file_id]*len(mopfile1.data), name="ID_{}".format(idx))) return mopfile1
[ "def", "match_mopfiles", "(", "mopfile1", ",", "mopfile2", ")", ":", "pos1", "=", "pos2", "=", "numpy", ".", "array", "(", "[", "]", ")", "if", "len", "(", "mopfile1", ".", "data", ")", ">", "0", ":", "X_COL", "=", "\"X_{}\"", ".", "format", "(", ...
Given an input list of 'real' detections and candidate detections provide a result file that contains the measured values from candidate detections with a flag indicating if they are real or false. @rtype MOPFile @return mopfile2 with a new column containing index of matching entry in mopfile1
[ "Given", "an", "input", "list", "of", "real", "detections", "and", "candidate", "detections", "provide", "a", "result", "file", "that", "contains", "the", "measured", "values", "from", "candidate", "detections", "with", "a", "flag", "indicating", "if", "they", ...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/match.py#L18-L45
OSSOS/MOP
src/ossos/core/ossos/match.py
measure_mags
def measure_mags(measures): """ Given a list of readings compute the magnitudes for all sources in each reading. @param measures: list of readings @return: None """ import daophot image_downloader = ImageDownloader() observations = {} for measure in measures: for reading in measure: if reading.obs not in observations: observations[reading.obs] = {'x': [], 'y': [], 'source': image_downloader.download(reading, needs_apcor=True)} assert isinstance(reading.obs, Observation) observations[reading.obs]['x'].append(reading.x) observations[reading.obs]['y'].append(reading.y) for observation in observations: source = observations[observation]['source'] assert isinstance(source, SourceCutout) source.update_pixel_location(observations[observation]['x'], observations[observation]['y']) hdulist_index = source.get_hdulist_idx(observation.ccdnum) observations[observation]['mags'] = daophot.phot(source._hdu_on_disk(hdulist_index), observations[observation]['x'], observations[observation]['y'], aperture=source.apcor.aperture, sky=source.apcor.sky, swidth=source.apcor.swidth, apcor=source.apcor.apcor, zmag=source.zmag, maxcount=30000, extno=0) return observations
python
def measure_mags(measures): """ Given a list of readings compute the magnitudes for all sources in each reading. @param measures: list of readings @return: None """ import daophot image_downloader = ImageDownloader() observations = {} for measure in measures: for reading in measure: if reading.obs not in observations: observations[reading.obs] = {'x': [], 'y': [], 'source': image_downloader.download(reading, needs_apcor=True)} assert isinstance(reading.obs, Observation) observations[reading.obs]['x'].append(reading.x) observations[reading.obs]['y'].append(reading.y) for observation in observations: source = observations[observation]['source'] assert isinstance(source, SourceCutout) source.update_pixel_location(observations[observation]['x'], observations[observation]['y']) hdulist_index = source.get_hdulist_idx(observation.ccdnum) observations[observation]['mags'] = daophot.phot(source._hdu_on_disk(hdulist_index), observations[observation]['x'], observations[observation]['y'], aperture=source.apcor.aperture, sky=source.apcor.sky, swidth=source.apcor.swidth, apcor=source.apcor.apcor, zmag=source.zmag, maxcount=30000, extno=0) return observations
[ "def", "measure_mags", "(", "measures", ")", ":", "import", "daophot", "image_downloader", "=", "ImageDownloader", "(", ")", "observations", "=", "{", "}", "for", "measure", "in", "measures", ":", "for", "reading", "in", "measure", ":", "if", "reading", ".",...
Given a list of readings compute the magnitudes for all sources in each reading. @param measures: list of readings @return: None
[ "Given", "a", "list", "of", "readings", "compute", "the", "magnitudes", "for", "all", "sources", "in", "each", "reading", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/match.py#L48-L87
OSSOS/MOP
src/ossos/core/ossos/match.py
match_planted
def match_planted(fk_candidate_observations, match_filename, bright_limit=BRIGHT_LIMIT, object_planted=OBJECT_PLANTED, minimum_bright_detections=MINIMUM_BRIGHT_DETECTIONS, bright_fraction=MINIMUM_BRIGHT_FRACTION): """ Using the fk_candidate_observations as input get the Object.planted file from VOSpace and match planted sources with found sources. The Object.planted list is pulled from VOSpace based on the standard file-layout and name of the first exposure as read from the .astrom file. :param fk_candidate_observations: name of the fk*reals.astrom file to check against Object.planted :param match_filename: a file that will contain a list of all planted sources and the matched found source @param minimum_bright_detections: if there are too few bright detections we raise an error. """ found_pos = [] detections = fk_candidate_observations.get_sources() for detection in detections: reading = detection.get_reading(0) # create a list of positions, to be used later by match_lists found_pos.append([reading.x, reading.y]) # Now get the Object.planted file, either from the local FS or from VOSpace. objects_planted_uri = object_planted if not os.access(objects_planted_uri, os.F_OK): objects_planted_uri = fk_candidate_observations.observations[0].get_object_planted_uri() lines = open(objects_planted_uri).read() # we are changing the format of the Object.planted header to be compatible with astropy.io.ascii but # there are some old Object.planted files out there so we do these string/replace calls to reset those. new_lines = lines.replace("pix rate", "pix_rate") new_lines = new_lines.replace("""''/h rate""", "sky_rate") planted_objects_table = ascii.read(new_lines, header_start=-1, data_start=0) planted_objects_table.meta = None # The match_list method expects a list that contains a position, not an x and a y vector, so we transpose. planted_pos = numpy.transpose([planted_objects_table['x'].data, planted_objects_table['y'].data]) # match_idx is an order list. The list is in the order of the first list of positions and each entry # is the index of the matching position from the second list. (match_idx, match_fnd) = util.match_lists(numpy.array(planted_pos), numpy.array(found_pos)) assert isinstance(match_idx, numpy.ma.MaskedArray) assert isinstance(match_fnd, numpy.ma.MaskedArray) false_positives_table = Table() # Once we've matched the two lists we'll need some new columns to store the information in. # these are masked columns so that object.planted entries that have no detected match are left 'blank'. new_columns = [MaskedColumn(name="measure_x", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_y", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_rate", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_angle", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_mag1", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_merr1", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_mag2", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_merr2", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_mag3", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_merr3", length=len(planted_objects_table), mask=True)] planted_objects_table.add_columns(new_columns) tlength = 0 new_columns = [MaskedColumn(name="measure_x", length=tlength, mask=True), MaskedColumn(name="measure_y", length=tlength, mask=True), MaskedColumn(name="measure_rate", length=0, mask=True), MaskedColumn(name="measure_angle", length=0, mask=True), MaskedColumn(name="measure_mag1", length=0, mask=True), MaskedColumn(name="measure_merr1", length=0, mask=True), MaskedColumn(name="measure_mag2", length=0, mask=True), MaskedColumn(name="measure_merr2", length=0, mask=True), MaskedColumn(name="measure_mag3", length=tlength, mask=True), MaskedColumn(name="measure_merr3", length=tlength, mask=True)] false_positives_table.add_columns(new_columns) # We do some 'checks' on the Object.planted match to diagnose pipeline issues. Those checks are made using just # those planted sources we should have detected. bright = planted_objects_table['mag'] < bright_limit n_bright_planted = numpy.count_nonzero(planted_objects_table['mag'][bright]) measures = [] idxs = [] for idx in range(len(match_idx)): # The match_idx value is False if nothing was found. if not match_idx.mask[idx]: # Each 'source' has multiple 'readings' measures.append(detections[match_idx[idx]].get_readings()) idxs.append(idx) observations = measure_mags(measures) for oidx in range(len(measures)): idx = idxs[oidx] readings = measures[oidx] start_jd = util.Time(readings[0].obs.header['MJD_OBS_CENTER'], format='mpc', scale='utc').jd end_jd = util.Time(readings[-1].obs.header['MJD_OBS_CENTER'], format='mpc', scale='utc').jd rate = math.sqrt((readings[-1].x - readings[0].x) ** 2 + (readings[-1].y - readings[0].y) ** 2) / ( 24 * (end_jd - start_jd)) rate = int(rate * 100) / 100.0 angle = math.degrees(math.atan2(readings[-1].y - readings[0].y, readings[-1].x - readings[0].x)) angle = int(angle * 100) / 100.0 planted_objects_table[idx]['measure_rate'] = rate planted_objects_table[idx]['measure_angle'] = angle planted_objects_table[idx]['measure_x'] = observations[readings[0].obs]['mags']["XCENTER"][oidx] planted_objects_table[idx]['measure_y'] = observations[readings[0].obs]['mags']["YCENTER"][oidx] for ridx in range(len(readings)): reading = readings[ridx] mags = observations[reading.obs]['mags'] planted_objects_table[idx]['measure_mag{}'.format(ridx+1)] = mags["MAG"][oidx] planted_objects_table[idx]['measure_merr{}'.format(ridx+1)] = mags["MERR"][oidx] # for idx in range(len(match_fnd)): # if match_fnd.mask[idx]: # measures = detections[idx].get_readings() # false_positives_table.add_row() # false_positives_table[-1] = measure_mags(measures, false_positives_table[-1]) # Count an object as detected if it has a measured magnitude in the first frame of the triplet. n_bright_found = numpy.count_nonzero(planted_objects_table['measure_mag1'][bright]) # Also compute the offset and standard deviation of the measured magnitude from that planted ones. offset = numpy.mean(planted_objects_table['mag'][bright] - planted_objects_table['measure_mag1'][bright]) try: offset = "{:5.2f}".format(offset) except: offset = "indef" std = numpy.std(planted_objects_table['mag'][bright] - planted_objects_table['measure_mag1'][bright]) try: std = "{:5.2f}".format(std) except: std = "indef" if os.access(match_filename, os.R_OK): fout = open(match_filename, 'a') else: fout = open(match_filename, 'w') fout.write("#K {:10s} {:10s}\n".format("EXPNUM", "FWHM")) for measure in detections[0].get_readings(): fout.write('#V {:10s} {:10s}\n'.format(measure.obs.header['EXPNUM'], measure.obs.header['FWHM'])) fout.write("#K ") for keyword in ["RMIN", "RMAX", "ANGLE", "AWIDTH"]: fout.write("{:10s} ".format(keyword)) fout.write("\n") fout.write("#V ") for keyword in ["RMIN", "RMAX", "ANGLE", "AWIDTH"]: fout.write("{:10s} ".format(fk_candidate_observations.sys_header[keyword])) fout.write("\n") fout.write("#K ") for keyword in ["NBRIGHT", "NFOUND", "OFFSET", "STDEV"]: fout.write("{:10s} ".format(keyword)) fout.write("\n") fout.write("#V {:<10} {:<10} {:<10} {:<10}\n".format(n_bright_planted, n_bright_found, offset, std)) try: writer = ascii.FixedWidth # add a hash to the start of line that will have header columns: for JMP fout.write("#") fout.flush() ascii.write(planted_objects_table, output=fout, Writer=writer, delimiter=None) if len(false_positives_table) > 0: with open(match_filename+".fp", 'a') as fpout: fpout.write("#") ascii.write(false_positives_table, output=fpout, Writer=writer, delimiter=None) except Exception as e: logging.error(str(e)) raise e finally: fout.close() # Some simple checks to report a failure how we're doing. if n_bright_planted < minimum_bright_detections: raise RuntimeError(1, "Too few bright objects planted.") if n_bright_found / float(n_bright_planted) < bright_fraction: raise RuntimeError(2, "Too few bright objects found.") return "{} {} {} {}".format(n_bright_planted, n_bright_found, offset, std)
python
def match_planted(fk_candidate_observations, match_filename, bright_limit=BRIGHT_LIMIT, object_planted=OBJECT_PLANTED, minimum_bright_detections=MINIMUM_BRIGHT_DETECTIONS, bright_fraction=MINIMUM_BRIGHT_FRACTION): """ Using the fk_candidate_observations as input get the Object.planted file from VOSpace and match planted sources with found sources. The Object.planted list is pulled from VOSpace based on the standard file-layout and name of the first exposure as read from the .astrom file. :param fk_candidate_observations: name of the fk*reals.astrom file to check against Object.planted :param match_filename: a file that will contain a list of all planted sources and the matched found source @param minimum_bright_detections: if there are too few bright detections we raise an error. """ found_pos = [] detections = fk_candidate_observations.get_sources() for detection in detections: reading = detection.get_reading(0) # create a list of positions, to be used later by match_lists found_pos.append([reading.x, reading.y]) # Now get the Object.planted file, either from the local FS or from VOSpace. objects_planted_uri = object_planted if not os.access(objects_planted_uri, os.F_OK): objects_planted_uri = fk_candidate_observations.observations[0].get_object_planted_uri() lines = open(objects_planted_uri).read() # we are changing the format of the Object.planted header to be compatible with astropy.io.ascii but # there are some old Object.planted files out there so we do these string/replace calls to reset those. new_lines = lines.replace("pix rate", "pix_rate") new_lines = new_lines.replace("""''/h rate""", "sky_rate") planted_objects_table = ascii.read(new_lines, header_start=-1, data_start=0) planted_objects_table.meta = None # The match_list method expects a list that contains a position, not an x and a y vector, so we transpose. planted_pos = numpy.transpose([planted_objects_table['x'].data, planted_objects_table['y'].data]) # match_idx is an order list. The list is in the order of the first list of positions and each entry # is the index of the matching position from the second list. (match_idx, match_fnd) = util.match_lists(numpy.array(planted_pos), numpy.array(found_pos)) assert isinstance(match_idx, numpy.ma.MaskedArray) assert isinstance(match_fnd, numpy.ma.MaskedArray) false_positives_table = Table() # Once we've matched the two lists we'll need some new columns to store the information in. # these are masked columns so that object.planted entries that have no detected match are left 'blank'. new_columns = [MaskedColumn(name="measure_x", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_y", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_rate", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_angle", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_mag1", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_merr1", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_mag2", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_merr2", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_mag3", length=len(planted_objects_table), mask=True), MaskedColumn(name="measure_merr3", length=len(planted_objects_table), mask=True)] planted_objects_table.add_columns(new_columns) tlength = 0 new_columns = [MaskedColumn(name="measure_x", length=tlength, mask=True), MaskedColumn(name="measure_y", length=tlength, mask=True), MaskedColumn(name="measure_rate", length=0, mask=True), MaskedColumn(name="measure_angle", length=0, mask=True), MaskedColumn(name="measure_mag1", length=0, mask=True), MaskedColumn(name="measure_merr1", length=0, mask=True), MaskedColumn(name="measure_mag2", length=0, mask=True), MaskedColumn(name="measure_merr2", length=0, mask=True), MaskedColumn(name="measure_mag3", length=tlength, mask=True), MaskedColumn(name="measure_merr3", length=tlength, mask=True)] false_positives_table.add_columns(new_columns) # We do some 'checks' on the Object.planted match to diagnose pipeline issues. Those checks are made using just # those planted sources we should have detected. bright = planted_objects_table['mag'] < bright_limit n_bright_planted = numpy.count_nonzero(planted_objects_table['mag'][bright]) measures = [] idxs = [] for idx in range(len(match_idx)): # The match_idx value is False if nothing was found. if not match_idx.mask[idx]: # Each 'source' has multiple 'readings' measures.append(detections[match_idx[idx]].get_readings()) idxs.append(idx) observations = measure_mags(measures) for oidx in range(len(measures)): idx = idxs[oidx] readings = measures[oidx] start_jd = util.Time(readings[0].obs.header['MJD_OBS_CENTER'], format='mpc', scale='utc').jd end_jd = util.Time(readings[-1].obs.header['MJD_OBS_CENTER'], format='mpc', scale='utc').jd rate = math.sqrt((readings[-1].x - readings[0].x) ** 2 + (readings[-1].y - readings[0].y) ** 2) / ( 24 * (end_jd - start_jd)) rate = int(rate * 100) / 100.0 angle = math.degrees(math.atan2(readings[-1].y - readings[0].y, readings[-1].x - readings[0].x)) angle = int(angle * 100) / 100.0 planted_objects_table[idx]['measure_rate'] = rate planted_objects_table[idx]['measure_angle'] = angle planted_objects_table[idx]['measure_x'] = observations[readings[0].obs]['mags']["XCENTER"][oidx] planted_objects_table[idx]['measure_y'] = observations[readings[0].obs]['mags']["YCENTER"][oidx] for ridx in range(len(readings)): reading = readings[ridx] mags = observations[reading.obs]['mags'] planted_objects_table[idx]['measure_mag{}'.format(ridx+1)] = mags["MAG"][oidx] planted_objects_table[idx]['measure_merr{}'.format(ridx+1)] = mags["MERR"][oidx] # for idx in range(len(match_fnd)): # if match_fnd.mask[idx]: # measures = detections[idx].get_readings() # false_positives_table.add_row() # false_positives_table[-1] = measure_mags(measures, false_positives_table[-1]) # Count an object as detected if it has a measured magnitude in the first frame of the triplet. n_bright_found = numpy.count_nonzero(planted_objects_table['measure_mag1'][bright]) # Also compute the offset and standard deviation of the measured magnitude from that planted ones. offset = numpy.mean(planted_objects_table['mag'][bright] - planted_objects_table['measure_mag1'][bright]) try: offset = "{:5.2f}".format(offset) except: offset = "indef" std = numpy.std(planted_objects_table['mag'][bright] - planted_objects_table['measure_mag1'][bright]) try: std = "{:5.2f}".format(std) except: std = "indef" if os.access(match_filename, os.R_OK): fout = open(match_filename, 'a') else: fout = open(match_filename, 'w') fout.write("#K {:10s} {:10s}\n".format("EXPNUM", "FWHM")) for measure in detections[0].get_readings(): fout.write('#V {:10s} {:10s}\n'.format(measure.obs.header['EXPNUM'], measure.obs.header['FWHM'])) fout.write("#K ") for keyword in ["RMIN", "RMAX", "ANGLE", "AWIDTH"]: fout.write("{:10s} ".format(keyword)) fout.write("\n") fout.write("#V ") for keyword in ["RMIN", "RMAX", "ANGLE", "AWIDTH"]: fout.write("{:10s} ".format(fk_candidate_observations.sys_header[keyword])) fout.write("\n") fout.write("#K ") for keyword in ["NBRIGHT", "NFOUND", "OFFSET", "STDEV"]: fout.write("{:10s} ".format(keyword)) fout.write("\n") fout.write("#V {:<10} {:<10} {:<10} {:<10}\n".format(n_bright_planted, n_bright_found, offset, std)) try: writer = ascii.FixedWidth # add a hash to the start of line that will have header columns: for JMP fout.write("#") fout.flush() ascii.write(planted_objects_table, output=fout, Writer=writer, delimiter=None) if len(false_positives_table) > 0: with open(match_filename+".fp", 'a') as fpout: fpout.write("#") ascii.write(false_positives_table, output=fpout, Writer=writer, delimiter=None) except Exception as e: logging.error(str(e)) raise e finally: fout.close() # Some simple checks to report a failure how we're doing. if n_bright_planted < minimum_bright_detections: raise RuntimeError(1, "Too few bright objects planted.") if n_bright_found / float(n_bright_planted) < bright_fraction: raise RuntimeError(2, "Too few bright objects found.") return "{} {} {} {}".format(n_bright_planted, n_bright_found, offset, std)
[ "def", "match_planted", "(", "fk_candidate_observations", ",", "match_filename", ",", "bright_limit", "=", "BRIGHT_LIMIT", ",", "object_planted", "=", "OBJECT_PLANTED", ",", "minimum_bright_detections", "=", "MINIMUM_BRIGHT_DETECTIONS", ",", "bright_fraction", "=", "MINIMUM...
Using the fk_candidate_observations as input get the Object.planted file from VOSpace and match planted sources with found sources. The Object.planted list is pulled from VOSpace based on the standard file-layout and name of the first exposure as read from the .astrom file. :param fk_candidate_observations: name of the fk*reals.astrom file to check against Object.planted :param match_filename: a file that will contain a list of all planted sources and the matched found source @param minimum_bright_detections: if there are too few bright detections we raise an error.
[ "Using", "the", "fk_candidate_observations", "as", "input", "get", "the", "Object", ".", "planted", "file", "from", "VOSpace", "and", "match", "planted", "sources", "with", "found", "sources", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/match.py#L90-L266
OSSOS/MOP
src/ossos/core/ossos/gui/models/collections.py
StatefulCollection.append
def append(self, item): """Adds a new item to the end of the collection.""" if len(self) == 0: # Special case, we make this the current item self.index = 0 self.items.append(item)
python
def append(self, item): """Adds a new item to the end of the collection.""" if len(self) == 0: # Special case, we make this the current item self.index = 0 self.items.append(item)
[ "def", "append", "(", "self", ",", "item", ")", ":", "if", "len", "(", "self", ")", "==", "0", ":", "# Special case, we make this the current item", "self", ".", "index", "=", "0", "self", ".", "items", ".", "append", "(", "item", ")" ]
Adds a new item to the end of the collection.
[ "Adds", "a", "new", "item", "to", "the", "end", "of", "the", "collection", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/models/collections.py#L27-L33
OSSOS/MOP
src/ossos/utils/vtag_cleanup.py
fix_tags_on_cands_missing_reals
def fix_tags_on_cands_missing_reals(user_id, vos_dir, property): "At the moment this just checks for a single user's missing reals. Easy to generalise it to all users." con = context.get_context(vos_dir) user_progress = [] listing = con.get_listing(tasks.get_suffix('reals')) mpc_listing = con.get_listing('mpc') for filename in listing: if not filename.startswith('fk'): user = storage.get_property(con.get_full_path(filename), property) if (user is not None): # and (user == user_id): # modify 'and' to generalise to all users with work in this directory #realsfile = filename.replace('cands', 'reals') #if not con.exists(realsfile): # print filename, 'no reals file', realsfile # go through the listing of .mpc files and see if any match this reals.astrom is_present = False for mpcfile in [f for f in mpc_listing if not f.startswith('fk')]: if mpcfile.startswith(filename): print filename, user, 'exists!', mpcfile is_present = True if not is_present: user_progress.append(filename) print filename, user, 'no mpc file' storage.set_property(con.get_full_path(filename), property, None) print 'Fixed files:', len(user_progress) return
python
def fix_tags_on_cands_missing_reals(user_id, vos_dir, property): "At the moment this just checks for a single user's missing reals. Easy to generalise it to all users." con = context.get_context(vos_dir) user_progress = [] listing = con.get_listing(tasks.get_suffix('reals')) mpc_listing = con.get_listing('mpc') for filename in listing: if not filename.startswith('fk'): user = storage.get_property(con.get_full_path(filename), property) if (user is not None): # and (user == user_id): # modify 'and' to generalise to all users with work in this directory #realsfile = filename.replace('cands', 'reals') #if not con.exists(realsfile): # print filename, 'no reals file', realsfile # go through the listing of .mpc files and see if any match this reals.astrom is_present = False for mpcfile in [f for f in mpc_listing if not f.startswith('fk')]: if mpcfile.startswith(filename): print filename, user, 'exists!', mpcfile is_present = True if not is_present: user_progress.append(filename) print filename, user, 'no mpc file' storage.set_property(con.get_full_path(filename), property, None) print 'Fixed files:', len(user_progress) return
[ "def", "fix_tags_on_cands_missing_reals", "(", "user_id", ",", "vos_dir", ",", "property", ")", ":", "con", "=", "context", ".", "get_context", "(", "vos_dir", ")", "user_progress", "=", "[", "]", "listing", "=", "con", ".", "get_listing", "(", "tasks", ".",...
At the moment this just checks for a single user's missing reals. Easy to generalise it to all users.
[ "At", "the", "moment", "this", "just", "checks", "for", "a", "single", "user", "s", "missing", "reals", ".", "Easy", "to", "generalise", "it", "to", "all", "users", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/vtag_cleanup.py#L64-L93
playpauseandstop/rororo
rororo/schemas/schema.py
Schema.make_error
def make_error(self, message: str, *, error: Exception = None, # ``error_class: Type[Exception]=None`` doesn't work on # Python 3.5.2, but that is exact version ran by Read the # Docs :( More info: http://stackoverflow.com/q/42942867 error_class: Any = None) -> Exception: """Return error instantiated from given message. :param message: Message to wrap. :param error: Validation error. :param error_class: Special class to wrap error message into. When omitted ``self.error_class`` will be used. """ if error_class is None: error_class = self.error_class if self.error_class else Error return error_class(message)
python
def make_error(self, message: str, *, error: Exception = None, # ``error_class: Type[Exception]=None`` doesn't work on # Python 3.5.2, but that is exact version ran by Read the # Docs :( More info: http://stackoverflow.com/q/42942867 error_class: Any = None) -> Exception: """Return error instantiated from given message. :param message: Message to wrap. :param error: Validation error. :param error_class: Special class to wrap error message into. When omitted ``self.error_class`` will be used. """ if error_class is None: error_class = self.error_class if self.error_class else Error return error_class(message)
[ "def", "make_error", "(", "self", ",", "message", ":", "str", ",", "*", ",", "error", ":", "Exception", "=", "None", ",", "# ``error_class: Type[Exception]=None`` doesn't work on", "# Python 3.5.2, but that is exact version ran by Read the", "# Docs :( More info: http://stackov...
Return error instantiated from given message. :param message: Message to wrap. :param error: Validation error. :param error_class: Special class to wrap error message into. When omitted ``self.error_class`` will be used.
[ "Return", "error", "instantiated", "from", "given", "message", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/schema.py#L74-L92
playpauseandstop/rororo
rororo/schemas/schema.py
Schema.make_response
def make_response(self, data: Any = None, **kwargs: Any) -> Any: r"""Validate response data and wrap it inside response factory. :param data: Response data. Could be ommited. :param \*\*kwargs: Keyword arguments to be passed to response factory. """ if not self._valid_request: logger.error('Request not validated, cannot make response') raise self.make_error('Request not validated before, cannot make ' 'response') if data is None and self.response_factory is None: logger.error('Response data omit, but no response factory is used') raise self.make_error('Response data could be omitted only when ' 'response factory is used') response_schema = getattr(self.module, 'response', None) if response_schema is not None: self._validate(data, response_schema) if self.response_factory is not None: return self.response_factory( *([data] if data is not None else []), **kwargs) return data
python
def make_response(self, data: Any = None, **kwargs: Any) -> Any: r"""Validate response data and wrap it inside response factory. :param data: Response data. Could be ommited. :param \*\*kwargs: Keyword arguments to be passed to response factory. """ if not self._valid_request: logger.error('Request not validated, cannot make response') raise self.make_error('Request not validated before, cannot make ' 'response') if data is None and self.response_factory is None: logger.error('Response data omit, but no response factory is used') raise self.make_error('Response data could be omitted only when ' 'response factory is used') response_schema = getattr(self.module, 'response', None) if response_schema is not None: self._validate(data, response_schema) if self.response_factory is not None: return self.response_factory( *([data] if data is not None else []), **kwargs) return data
[ "def", "make_response", "(", "self", ",", "data", ":", "Any", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Any", ":", "if", "not", "self", ".", "_valid_request", ":", "logger", ".", "error", "(", "'Request not validated, cannot make respon...
r"""Validate response data and wrap it inside response factory. :param data: Response data. Could be ommited. :param \*\*kwargs: Keyword arguments to be passed to response factory.
[ "r", "Validate", "response", "data", "and", "wrap", "it", "inside", "response", "factory", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/schema.py#L94-L120
playpauseandstop/rororo
rororo/schemas/schema.py
Schema.validate_request
def validate_request(self, data: Any, *additional: AnyMapping, merged_class: Type[dict] = dict) -> Any: r"""Validate request data against request schema from module. :param data: Request data. :param \*additional: Additional data dicts to be merged with base request data. :param merged_class: When additional data dicts supplied method by default will return merged **dict** with all data, but you can customize things to use read-only dict or any other additional class or callable. """ request_schema = getattr(self.module, 'request', None) if request_schema is None: logger.error( 'Request schema should be defined', extra={'schema_module': self.module, 'schema_module_attrs': dir(self.module)}) raise self.make_error('Request schema should be defined') # Merge base and additional data dicts, but only if additional data # dicts have been supplied if isinstance(data, dict) and additional: data = merged_class(self._merge_data(data, *additional)) try: self._validate(data, request_schema) finally: self._valid_request = False self._valid_request = True processor = getattr(self.module, 'request_processor', None) return processor(data) if processor else data
python
def validate_request(self, data: Any, *additional: AnyMapping, merged_class: Type[dict] = dict) -> Any: r"""Validate request data against request schema from module. :param data: Request data. :param \*additional: Additional data dicts to be merged with base request data. :param merged_class: When additional data dicts supplied method by default will return merged **dict** with all data, but you can customize things to use read-only dict or any other additional class or callable. """ request_schema = getattr(self.module, 'request', None) if request_schema is None: logger.error( 'Request schema should be defined', extra={'schema_module': self.module, 'schema_module_attrs': dir(self.module)}) raise self.make_error('Request schema should be defined') # Merge base and additional data dicts, but only if additional data # dicts have been supplied if isinstance(data, dict) and additional: data = merged_class(self._merge_data(data, *additional)) try: self._validate(data, request_schema) finally: self._valid_request = False self._valid_request = True processor = getattr(self.module, 'request_processor', None) return processor(data) if processor else data
[ "def", "validate_request", "(", "self", ",", "data", ":", "Any", ",", "*", "additional", ":", "AnyMapping", ",", "merged_class", ":", "Type", "[", "dict", "]", "=", "dict", ")", "->", "Any", ":", "request_schema", "=", "getattr", "(", "self", ".", "mod...
r"""Validate request data against request schema from module. :param data: Request data. :param \*additional: Additional data dicts to be merged with base request data. :param merged_class: When additional data dicts supplied method by default will return merged **dict** with all data, but you can customize things to use read-only dict or any other additional class or callable.
[ "r", "Validate", "request", "data", "against", "request", "schema", "from", "module", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/schema.py#L122-L157
playpauseandstop/rororo
rororo/schemas/schema.py
Schema._merge_data
def _merge_data(self, data: AnyMapping, *additional: AnyMapping) -> dict: r"""Merge base data and additional dicts. :param data: Base data. :param \*additional: Additional data dicts to be merged into base dict. """ return defaults( dict(data) if not isinstance(data, dict) else data, *(dict(item) for item in additional))
python
def _merge_data(self, data: AnyMapping, *additional: AnyMapping) -> dict: r"""Merge base data and additional dicts. :param data: Base data. :param \*additional: Additional data dicts to be merged into base dict. """ return defaults( dict(data) if not isinstance(data, dict) else data, *(dict(item) for item in additional))
[ "def", "_merge_data", "(", "self", ",", "data", ":", "AnyMapping", ",", "*", "additional", ":", "AnyMapping", ")", "->", "dict", ":", "return", "defaults", "(", "dict", "(", "data", ")", "if", "not", "isinstance", "(", "data", ",", "dict", ")", "else",...
r"""Merge base data and additional dicts. :param data: Base data. :param \*additional: Additional data dicts to be merged into base dict.
[ "r", "Merge", "base", "data", "and", "additional", "dicts", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/schema.py#L159-L167
playpauseandstop/rororo
rororo/schemas/schema.py
Schema._pure_data
def _pure_data(self, data: Any) -> Any: """ If data is dict-like object, convert it to pure dict instance, so it will be possible to pass to default ``jsonschema.validate`` func. :param data: Request or response data. """ if not isinstance(data, dict) and not isinstance(data, list): try: return dict(data) except TypeError: ... return data
python
def _pure_data(self, data: Any) -> Any: """ If data is dict-like object, convert it to pure dict instance, so it will be possible to pass to default ``jsonschema.validate`` func. :param data: Request or response data. """ if not isinstance(data, dict) and not isinstance(data, list): try: return dict(data) except TypeError: ... return data
[ "def", "_pure_data", "(", "self", ",", "data", ":", "Any", ")", "->", "Any", ":", "if", "not", "isinstance", "(", "data", ",", "dict", ")", "and", "not", "isinstance", "(", "data", ",", "list", ")", ":", "try", ":", "return", "dict", "(", "data", ...
If data is dict-like object, convert it to pure dict instance, so it will be possible to pass to default ``jsonschema.validate`` func. :param data: Request or response data.
[ "If", "data", "is", "dict", "-", "like", "object", "convert", "it", "to", "pure", "dict", "instance", "so", "it", "will", "be", "possible", "to", "pass", "to", "default", "jsonschema", ".", "validate", "func", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/schema.py#L169-L181
playpauseandstop/rororo
rororo/schemas/schema.py
Schema._validate
def _validate(self, data: Any, schema: AnyMapping) -> Any: """Validate data against given schema. :param data: Data to validate. :param schema: Schema to use for validation. """ try: return self.validate_func(schema, self._pure_data(data)) except self.validation_error_class as err: logger.error( 'Schema validation error', exc_info=True, extra={'schema': schema, 'schema_module': self.module}) if self.error_class is None: raise raise self.make_error('Validation Error', error=err) from err
python
def _validate(self, data: Any, schema: AnyMapping) -> Any: """Validate data against given schema. :param data: Data to validate. :param schema: Schema to use for validation. """ try: return self.validate_func(schema, self._pure_data(data)) except self.validation_error_class as err: logger.error( 'Schema validation error', exc_info=True, extra={'schema': schema, 'schema_module': self.module}) if self.error_class is None: raise raise self.make_error('Validation Error', error=err) from err
[ "def", "_validate", "(", "self", ",", "data", ":", "Any", ",", "schema", ":", "AnyMapping", ")", "->", "Any", ":", "try", ":", "return", "self", ".", "validate_func", "(", "schema", ",", "self", ".", "_pure_data", "(", "data", ")", ")", "except", "se...
Validate data against given schema. :param data: Data to validate. :param schema: Schema to use for validation.
[ "Validate", "data", "against", "given", "schema", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/schema.py#L183-L198
OSSOS/MOP
src/ossos/canfar/cadc_certificates.py
getCert
def getCert(certHost=vos.vos.SERVER, certfile=None, certQuery="/cred/proxyCert?daysValid=",daysValid=2): """Access the cadc certificate server""" if certfile is None: certfile = os.path.join(os.getenv("HOME","/tmp"),".ssl/cadcproxy.pem") dirname = os.path.dirname(certfile) try: os.makedirs(dirname) except OSError as e: if os.path.isdir(dirname): pass elif e.errno == 20 or e.errno == 17: sys.stderr.write(str(e)+": %s \n" % dirname) sys.stderr.write("Expected %s to be a directory.\n" % ( dirname)) sys.exit(e.errno) else: raise e # Example taken from voidspace.org.uk # create a password manager password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() (username, passwd) = getUserPassword(host=certHost) # Add the username and password. # If we knew the realm, we could use it instead of ``None``. top_level_url = "http://"+certHost password_mgr.add_password(None, top_level_url, username, passwd) handler = urllib2.HTTPBasicAuthHandler(password_mgr) # create "opener" (OpenerDirector instance) opener = urllib2.build_opener(handler) # Install the opener. urllib2.install_opener(opener) # Now all calls to urllib2.urlopen use our opener. url="http://"+certHost+certQuery+str(daysValid) r= urllib2.urlopen(url) w= file(certfile,'w') while True: buf=r.read() if not buf: break w.write(buf) w.close() r.close() return
python
def getCert(certHost=vos.vos.SERVER, certfile=None, certQuery="/cred/proxyCert?daysValid=",daysValid=2): """Access the cadc certificate server""" if certfile is None: certfile = os.path.join(os.getenv("HOME","/tmp"),".ssl/cadcproxy.pem") dirname = os.path.dirname(certfile) try: os.makedirs(dirname) except OSError as e: if os.path.isdir(dirname): pass elif e.errno == 20 or e.errno == 17: sys.stderr.write(str(e)+": %s \n" % dirname) sys.stderr.write("Expected %s to be a directory.\n" % ( dirname)) sys.exit(e.errno) else: raise e # Example taken from voidspace.org.uk # create a password manager password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() (username, passwd) = getUserPassword(host=certHost) # Add the username and password. # If we knew the realm, we could use it instead of ``None``. top_level_url = "http://"+certHost password_mgr.add_password(None, top_level_url, username, passwd) handler = urllib2.HTTPBasicAuthHandler(password_mgr) # create "opener" (OpenerDirector instance) opener = urllib2.build_opener(handler) # Install the opener. urllib2.install_opener(opener) # Now all calls to urllib2.urlopen use our opener. url="http://"+certHost+certQuery+str(daysValid) r= urllib2.urlopen(url) w= file(certfile,'w') while True: buf=r.read() if not buf: break w.write(buf) w.close() r.close() return
[ "def", "getCert", "(", "certHost", "=", "vos", ".", "vos", ".", "SERVER", ",", "certfile", "=", "None", ",", "certQuery", "=", "\"/cred/proxyCert?daysValid=\"", ",", "daysValid", "=", "2", ")", ":", "if", "certfile", "is", "None", ":", "certfile", "=", "...
Access the cadc certificate server
[ "Access", "the", "cadc", "certificate", "server" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/canfar/cadc_certificates.py#L10-L60
OSSOS/MOP
src/ossos/canfar/cadc_certificates.py
getUserPassword
def getUserPassword(host='www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca'): """"Getting the username/password for host from .netrc filie """ if os.access(os.path.join(os.environ.get('HOME','/'),".netrc"),os.R_OK): auth=netrc.netrc().authenticators(host) else: auth=False if not auth: sys.stdout.write("CADC Username: ") username=sys.stdin.readline().strip('\n') password=getpass.getpass().strip('\n') else: username=auth[0] password=auth[2] return (username,password)
python
def getUserPassword(host='www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca'): """"Getting the username/password for host from .netrc filie """ if os.access(os.path.join(os.environ.get('HOME','/'),".netrc"),os.R_OK): auth=netrc.netrc().authenticators(host) else: auth=False if not auth: sys.stdout.write("CADC Username: ") username=sys.stdin.readline().strip('\n') password=getpass.getpass().strip('\n') else: username=auth[0] password=auth[2] return (username,password)
[ "def", "getUserPassword", "(", "host", "=", "'www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca'", ")", ":", "if", "os", ".", "access", "(", "os", ".", "path", ".", "join", "(", "os", ".", "environ", ".", "get", "(", "'HOME'", ",", "'/'", ")", ",", "\".netrc\"", ")",...
Getting the username/password for host from .netrc filie
[ "Getting", "the", "username", "/", "password", "for", "host", "from", ".", "netrc", "filie" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/canfar/cadc_certificates.py#L62-L75
OSSOS/MOP
src/ossos/utils/reset_processing_tags.py
clear_tags
def clear_tags(my_expnum, ops_set, my_ccds, dry_run=True): """ Clear the tags for the given expnum/ccd set. @param ops: @param my_expnum: @return: """ for ops in ops_set: for fake in ops[0]: for my_program in ops[1]: for version in ops[2]: props = {} for ccd in my_ccds: # print my_expnum, fake, my_program, version, ccd key = storage.get_process_tag(fake + my_program, ccd, version) props[key] = None if not dry_run: storage.set_tags(my_expnum, props) else: sys.stdout.write(" ".join(props)+"\n")
python
def clear_tags(my_expnum, ops_set, my_ccds, dry_run=True): """ Clear the tags for the given expnum/ccd set. @param ops: @param my_expnum: @return: """ for ops in ops_set: for fake in ops[0]: for my_program in ops[1]: for version in ops[2]: props = {} for ccd in my_ccds: # print my_expnum, fake, my_program, version, ccd key = storage.get_process_tag(fake + my_program, ccd, version) props[key] = None if not dry_run: storage.set_tags(my_expnum, props) else: sys.stdout.write(" ".join(props)+"\n")
[ "def", "clear_tags", "(", "my_expnum", ",", "ops_set", ",", "my_ccds", ",", "dry_run", "=", "True", ")", ":", "for", "ops", "in", "ops_set", ":", "for", "fake", "in", "ops", "[", "0", "]", ":", "for", "my_program", "in", "ops", "[", "1", "]", ":", ...
Clear the tags for the given expnum/ccd set. @param ops: @param my_expnum: @return:
[ "Clear", "the", "tags", "for", "the", "given", "expnum", "/", "ccd", "set", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/reset_processing_tags.py#L33-L53
playpauseandstop/rororo
rororo/utils.py
to_bool
def to_bool(value: Any) -> bool: """Convert string or other Python object to boolean. **Rationalle** Passing flags is one of the most common cases of using environment vars and as values are strings we need to have an easy way to convert them to boolean Python value. Without this function int or float string values can be converted as false positives, e.g. ``bool('0') => True``, but using this function ensure that digit flag be properly converted to boolean value. :param value: String or other value. """ return bool(strtobool(value) if isinstance(value, str) else value)
python
def to_bool(value: Any) -> bool: """Convert string or other Python object to boolean. **Rationalle** Passing flags is one of the most common cases of using environment vars and as values are strings we need to have an easy way to convert them to boolean Python value. Without this function int or float string values can be converted as false positives, e.g. ``bool('0') => True``, but using this function ensure that digit flag be properly converted to boolean value. :param value: String or other value. """ return bool(strtobool(value) if isinstance(value, str) else value)
[ "def", "to_bool", "(", "value", ":", "Any", ")", "->", "bool", ":", "return", "bool", "(", "strtobool", "(", "value", ")", "if", "isinstance", "(", "value", ",", "str", ")", "else", "value", ")" ]
Convert string or other Python object to boolean. **Rationalle** Passing flags is one of the most common cases of using environment vars and as values are strings we need to have an easy way to convert them to boolean Python value. Without this function int or float string values can be converted as false positives, e.g. ``bool('0') => True``, but using this function ensure that digit flag be properly converted to boolean value. :param value: String or other value.
[ "Convert", "string", "or", "other", "Python", "object", "to", "boolean", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/utils.py#L17-L32
playpauseandstop/rororo
rororo/utils.py
to_int
def to_int(value: str, default: T = None) -> Union[int, Optional[T]]: """Convert given value to int. If conversion failed, return default value without raising Exception. :param value: Value to convert to int. :param default: Default value to use in case of failed conversion. """ try: return int(value) except (TypeError, ValueError): return default
python
def to_int(value: str, default: T = None) -> Union[int, Optional[T]]: """Convert given value to int. If conversion failed, return default value without raising Exception. :param value: Value to convert to int. :param default: Default value to use in case of failed conversion. """ try: return int(value) except (TypeError, ValueError): return default
[ "def", "to_int", "(", "value", ":", "str", ",", "default", ":", "T", "=", "None", ")", "->", "Union", "[", "int", ",", "Optional", "[", "T", "]", "]", ":", "try", ":", "return", "int", "(", "value", ")", "except", "(", "TypeError", ",", "ValueErr...
Convert given value to int. If conversion failed, return default value without raising Exception. :param value: Value to convert to int. :param default: Default value to use in case of failed conversion.
[ "Convert", "given", "value", "to", "int", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/utils.py#L35-L46
OSSOS/MOP
src/jjk/preproc/cfeps_object.py
mk_dict
def mk_dict(results,description): """Given a result list and descrition sequence, return a list of dictionaries""" rows=[] for row in results: row_dict={} for idx in range(len(row)): col=description[idx][0] row_dict[col]=row[idx] rows.append(row_dict) return rows
python
def mk_dict(results,description): """Given a result list and descrition sequence, return a list of dictionaries""" rows=[] for row in results: row_dict={} for idx in range(len(row)): col=description[idx][0] row_dict[col]=row[idx] rows.append(row_dict) return rows
[ "def", "mk_dict", "(", "results", ",", "description", ")", ":", "rows", "=", "[", "]", "for", "row", "in", "results", ":", "row_dict", "=", "{", "}", "for", "idx", "in", "range", "(", "len", "(", "row", ")", ")", ":", "col", "=", "description", "...
Given a result list and descrition sequence, return a list of dictionaries
[ "Given", "a", "result", "list", "and", "descrition", "sequence", "return", "a", "list", "of", "dictionaries" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/cfeps_object.py#L16-L27
OSSOS/MOP
src/jjk/preproc/cfeps_object.py
get_orbits
def get_orbits(official='%'): """Query the orbit table for the object whose official desingation matches parameter official. By default all entries are returned """ sql= "SELECT * FROM orbits WHERE official LIKE '%s' " % (official, ) cfeps.execute(sql) return mk_dict(cfeps.fetchall(),cfeps.description)
python
def get_orbits(official='%'): """Query the orbit table for the object whose official desingation matches parameter official. By default all entries are returned """ sql= "SELECT * FROM orbits WHERE official LIKE '%s' " % (official, ) cfeps.execute(sql) return mk_dict(cfeps.fetchall(),cfeps.description)
[ "def", "get_orbits", "(", "official", "=", "'%'", ")", ":", "sql", "=", "\"SELECT * FROM orbits WHERE official LIKE '%s' \"", "%", "(", "official", ",", ")", "cfeps", ".", "execute", "(", "sql", ")", "return", "mk_dict", "(", "cfeps", ".", "fetchall", "(", "...
Query the orbit table for the object whose official desingation matches parameter official. By default all entries are returned
[ "Query", "the", "orbit", "table", "for", "the", "object", "whose", "official", "desingation", "matches", "parameter", "official", ".", "By", "default", "all", "entries", "are", "returned" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/cfeps_object.py#L30-L37
OSSOS/MOP
src/jjk/preproc/cfeps_object.py
get_astrom
def get_astrom(official='%',provisional='%'): """Query the measure table for all measurements of a particular object. Default is to return all the astrometry in the measure table, sorted by mjdate""" sql= "SELECT m.* FROM measure m " sql+="LEFT JOIN object o ON m.provisional LIKE o.provisional " if not official: sql+="WHERE o.official IS NULL" else: sql+="WHERE o.official LIKE '%s' " % ( official, ) sql+=" AND m.provisional LIKE '%s' " % ( provisional, ) cfeps.execute(sql) return mk_dict(cfeps.fetchall(), cfeps.description)
python
def get_astrom(official='%',provisional='%'): """Query the measure table for all measurements of a particular object. Default is to return all the astrometry in the measure table, sorted by mjdate""" sql= "SELECT m.* FROM measure m " sql+="LEFT JOIN object o ON m.provisional LIKE o.provisional " if not official: sql+="WHERE o.official IS NULL" else: sql+="WHERE o.official LIKE '%s' " % ( official, ) sql+=" AND m.provisional LIKE '%s' " % ( provisional, ) cfeps.execute(sql) return mk_dict(cfeps.fetchall(), cfeps.description)
[ "def", "get_astrom", "(", "official", "=", "'%'", ",", "provisional", "=", "'%'", ")", ":", "sql", "=", "\"SELECT m.* FROM measure m \"", "sql", "+=", "\"LEFT JOIN object o ON m.provisional LIKE o.provisional \"", "if", "not", "official", ":", "sql", "+=", "\"WHERE o...
Query the measure table for all measurements of a particular object. Default is to return all the astrometry in the measure table, sorted by mjdate
[ "Query", "the", "measure", "table", "for", "all", "measurements", "of", "a", "particular", "object", ".", "Default", "is", "to", "return", "all", "the", "astrometry", "in", "the", "measure", "table", "sorted", "by", "mjdate" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/cfeps_object.py#L40-L54
OSSOS/MOP
src/jjk/preproc/cfeps_object.py
getData
def getData(file_id,ra,dec): """Create a link that connects to a getData URL""" DATA="www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca" BASE="http://"+DATA+"/authProxy/getData" archive="CFHT" wcs="corrected" import re groups=re.match('^(?P<file_id>\d{6}).*',file_id) if not groups: return None file_id=groups.group('file_id') file_id+="p" #### THIS IS NOT WORKING YET.... URL=BASE+"?dataset_name="+file_id+"&cutout=circle("+str(ra*57.3)+"," URL+=str(dec*57.3)+","+str(5.0/60.0)+")" return URL
python
def getData(file_id,ra,dec): """Create a link that connects to a getData URL""" DATA="www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca" BASE="http://"+DATA+"/authProxy/getData" archive="CFHT" wcs="corrected" import re groups=re.match('^(?P<file_id>\d{6}).*',file_id) if not groups: return None file_id=groups.group('file_id') file_id+="p" #### THIS IS NOT WORKING YET.... URL=BASE+"?dataset_name="+file_id+"&cutout=circle("+str(ra*57.3)+"," URL+=str(dec*57.3)+","+str(5.0/60.0)+")" return URL
[ "def", "getData", "(", "file_id", ",", "ra", ",", "dec", ")", ":", "DATA", "=", "\"www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca\"", "BASE", "=", "\"http://\"", "+", "DATA", "+", "\"/authProxy/getData\"", "archive", "=", "\"CFHT\"", "wcs", "=", "\"corrected\"", "import", ...
Create a link that connects to a getData URL
[ "Create", "a", "link", "that", "connects", "to", "a", "getData", "URL" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/cfeps_object.py#L57-L75
etesync/pyetesync
example_crud.py
EtesyncCRUD.create_event
def create_event(self, event): """Create event Parameters ---------- event : iCalendar file as a string (calendar containing one event to be added) """ ev = api.Event.create(self.journal.collection, event) ev.save()
python
def create_event(self, event): """Create event Parameters ---------- event : iCalendar file as a string (calendar containing one event to be added) """ ev = api.Event.create(self.journal.collection, event) ev.save()
[ "def", "create_event", "(", "self", ",", "event", ")", ":", "ev", "=", "api", ".", "Event", ".", "create", "(", "self", ".", "journal", ".", "collection", ",", "event", ")", "ev", ".", "save", "(", ")" ]
Create event Parameters ---------- event : iCalendar file as a string (calendar containing one event to be added)
[ "Create", "event" ]
train
https://github.com/etesync/pyetesync/blob/6b185925b1489912c971e99d6a115583021873bd/example_crud.py#L53-L62
etesync/pyetesync
example_crud.py
EtesyncCRUD.update_event
def update_event(self, event, uid): """Edit event Parameters ---------- event : iCalendar file as a string (calendar containing one event to be updated) uid : uid of event to be updated """ ev_for_change = self.calendar.get(uid) ev_for_change.content = event ev_for_change.save()
python
def update_event(self, event, uid): """Edit event Parameters ---------- event : iCalendar file as a string (calendar containing one event to be updated) uid : uid of event to be updated """ ev_for_change = self.calendar.get(uid) ev_for_change.content = event ev_for_change.save()
[ "def", "update_event", "(", "self", ",", "event", ",", "uid", ")", ":", "ev_for_change", "=", "self", ".", "calendar", ".", "get", "(", "uid", ")", "ev_for_change", ".", "content", "=", "event", "ev_for_change", ".", "save", "(", ")" ]
Edit event Parameters ---------- event : iCalendar file as a string (calendar containing one event to be updated) uid : uid of event to be updated
[ "Edit", "event" ]
train
https://github.com/etesync/pyetesync/blob/6b185925b1489912c971e99d6a115583021873bd/example_crud.py#L64-L75
etesync/pyetesync
example_crud.py
EtesyncCRUD.delete_event
def delete_event(self, uid): """Delete event and sync calendar Parameters ---------- uid : uid of event to be deleted """ ev_for_deletion = self.calendar.get(uid) ev_for_deletion.delete()
python
def delete_event(self, uid): """Delete event and sync calendar Parameters ---------- uid : uid of event to be deleted """ ev_for_deletion = self.calendar.get(uid) ev_for_deletion.delete()
[ "def", "delete_event", "(", "self", ",", "uid", ")", ":", "ev_for_deletion", "=", "self", ".", "calendar", ".", "get", "(", "uid", ")", "ev_for_deletion", ".", "delete", "(", ")" ]
Delete event and sync calendar Parameters ---------- uid : uid of event to be deleted
[ "Delete", "event", "and", "sync", "calendar" ]
train
https://github.com/etesync/pyetesync/blob/6b185925b1489912c971e99d6a115583021873bd/example_crud.py#L100-L108
JohnVinyard/zounds
zounds/util/persistence.py
simple_lmdb_settings
def simple_lmdb_settings(path, map_size=1e9, user_supplied_id=False): """ Creates a decorator that can be used to configure sane default LMDB persistence settings for a model Args: path (str): The path where the LMDB database files will be created map_size (int): The amount of space to allot for the database """ def decorator(cls): provider = \ ff.UserSpecifiedIdProvider(key='_id') \ if user_supplied_id else ff.UuidProvider() class Settings(ff.PersistenceSettings): id_provider = provider key_builder = ff.StringDelimitedKeyBuilder('|') database = ff.LmdbDatabase( path, key_builder=key_builder, map_size=map_size) class Model(cls, Settings): pass Model.__name__ = cls.__name__ Model.__module__ = cls.__module__ return Model return decorator
python
def simple_lmdb_settings(path, map_size=1e9, user_supplied_id=False): """ Creates a decorator that can be used to configure sane default LMDB persistence settings for a model Args: path (str): The path where the LMDB database files will be created map_size (int): The amount of space to allot for the database """ def decorator(cls): provider = \ ff.UserSpecifiedIdProvider(key='_id') \ if user_supplied_id else ff.UuidProvider() class Settings(ff.PersistenceSettings): id_provider = provider key_builder = ff.StringDelimitedKeyBuilder('|') database = ff.LmdbDatabase( path, key_builder=key_builder, map_size=map_size) class Model(cls, Settings): pass Model.__name__ = cls.__name__ Model.__module__ = cls.__module__ return Model return decorator
[ "def", "simple_lmdb_settings", "(", "path", ",", "map_size", "=", "1e9", ",", "user_supplied_id", "=", "False", ")", ":", "def", "decorator", "(", "cls", ")", ":", "provider", "=", "ff", ".", "UserSpecifiedIdProvider", "(", "key", "=", "'_id'", ")", "if", ...
Creates a decorator that can be used to configure sane default LMDB persistence settings for a model Args: path (str): The path where the LMDB database files will be created map_size (int): The amount of space to allot for the database
[ "Creates", "a", "decorator", "that", "can", "be", "used", "to", "configure", "sane", "default", "LMDB", "persistence", "settings", "for", "a", "model" ]
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/util/persistence.py#L4-L32
JohnVinyard/zounds
zounds/util/persistence.py
simple_in_memory_settings
def simple_in_memory_settings(cls): """ Decorator that returns a class that "persists" data in-memory. Mostly useful for testing :param cls: the class whose features should be persisted in-memory :return: A new class that will persist features in memory """ class Settings(ff.PersistenceSettings): id_provider = ff.UuidProvider() key_builder = ff.StringDelimitedKeyBuilder() database = ff.InMemoryDatabase(key_builder=key_builder) class Model(cls, Settings): pass Model.__name__ = cls.__name__ Model.__module__ = cls.__module__ return Model
python
def simple_in_memory_settings(cls): """ Decorator that returns a class that "persists" data in-memory. Mostly useful for testing :param cls: the class whose features should be persisted in-memory :return: A new class that will persist features in memory """ class Settings(ff.PersistenceSettings): id_provider = ff.UuidProvider() key_builder = ff.StringDelimitedKeyBuilder() database = ff.InMemoryDatabase(key_builder=key_builder) class Model(cls, Settings): pass Model.__name__ = cls.__name__ Model.__module__ = cls.__module__ return Model
[ "def", "simple_in_memory_settings", "(", "cls", ")", ":", "class", "Settings", "(", "ff", ".", "PersistenceSettings", ")", ":", "id_provider", "=", "ff", ".", "UuidProvider", "(", ")", "key_builder", "=", "ff", ".", "StringDelimitedKeyBuilder", "(", ")", "data...
Decorator that returns a class that "persists" data in-memory. Mostly useful for testing :param cls: the class whose features should be persisted in-memory :return: A new class that will persist features in memory
[ "Decorator", "that", "returns", "a", "class", "that", "persists", "data", "in", "-", "memory", ".", "Mostly", "useful", "for", "testing", ":", "param", "cls", ":", "the", "class", "whose", "features", "should", "be", "persisted", "in", "-", "memory", ":", ...
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/util/persistence.py#L53-L71
OSSOS/MOP
src/ossos/core/ossos/cameras.py
Camera.offset
def offset(self, index=0): """Offset the camera pointing to be centred on a particular CCD.""" eta = self._geometry[self.camera][index]["ra"] xi = self._geometry[self.camera][index]["dec"] ra = self.origin.ra - (eta/math.cos(self.dec.radian))*units.degree dec = self.origin.dec - xi * units.degree + 45 * units.arcsec self._coordinate = SkyCoord(ra, dec)
python
def offset(self, index=0): """Offset the camera pointing to be centred on a particular CCD.""" eta = self._geometry[self.camera][index]["ra"] xi = self._geometry[self.camera][index]["dec"] ra = self.origin.ra - (eta/math.cos(self.dec.radian))*units.degree dec = self.origin.dec - xi * units.degree + 45 * units.arcsec self._coordinate = SkyCoord(ra, dec)
[ "def", "offset", "(", "self", ",", "index", "=", "0", ")", ":", "eta", "=", "self", ".", "_geometry", "[", "self", ".", "camera", "]", "[", "index", "]", "[", "\"ra\"", "]", "xi", "=", "self", ".", "_geometry", "[", "self", ".", "camera", "]", ...
Offset the camera pointing to be centred on a particular CCD.
[ "Offset", "the", "camera", "pointing", "to", "be", "centred", "on", "a", "particular", "CCD", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/cameras.py#L213-L219
OSSOS/MOP
src/ossos/core/ossos/cameras.py
Camera.coord
def coord(self): """The center of the camera pointing in sky coordinates""" if self._coordinate is None: self._coordinate = SkyCoord(self.origin.ra, self.origin.dec + 45 * units.arcsec) return self._coordinate
python
def coord(self): """The center of the camera pointing in sky coordinates""" if self._coordinate is None: self._coordinate = SkyCoord(self.origin.ra, self.origin.dec + 45 * units.arcsec) return self._coordinate
[ "def", "coord", "(", "self", ")", ":", "if", "self", ".", "_coordinate", "is", "None", ":", "self", ".", "_coordinate", "=", "SkyCoord", "(", "self", ".", "origin", ".", "ra", ",", "self", ".", "origin", ".", "dec", "+", "45", "*", "units", ".", ...
The center of the camera pointing in sky coordinates
[ "The", "center", "of", "the", "camera", "pointing", "in", "sky", "coordinates" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/cameras.py#L226-L230
OSSOS/MOP
src/ossos/core/ossos/cameras.py
Camera.geometry
def geometry(self): """Return an array of rectangles that represent the 'ra,dec' corners of the FOV @rtype: list """ if self.coord is None: return None ra = self.coord.ra.degree dec = self.coord.dec.degree ccds = [] for geo in self._geometry[self.camera]: ycen = geo["dec"] + dec xcen = geo["ra"] / math.cos(math.radians(ycen)) + ra try: dy = geo["ddec"] dx = geo["dra"] / math.cos(math.radians(ycen)) ccds.append([xcen - dx / 2.0, ycen - dy / 2.0, xcen + dx / 2.0, ycen + dy / 2.0]) except: rad = geo["rad"] ccds.append([xcen, ycen, rad]) return ccds
python
def geometry(self): """Return an array of rectangles that represent the 'ra,dec' corners of the FOV @rtype: list """ if self.coord is None: return None ra = self.coord.ra.degree dec = self.coord.dec.degree ccds = [] for geo in self._geometry[self.camera]: ycen = geo["dec"] + dec xcen = geo["ra"] / math.cos(math.radians(ycen)) + ra try: dy = geo["ddec"] dx = geo["dra"] / math.cos(math.radians(ycen)) ccds.append([xcen - dx / 2.0, ycen - dy / 2.0, xcen + dx / 2.0, ycen + dy / 2.0]) except: rad = geo["rad"] ccds.append([xcen, ycen, rad]) return ccds
[ "def", "geometry", "(", "self", ")", ":", "if", "self", ".", "coord", "is", "None", ":", "return", "None", "ra", "=", "self", ".", "coord", ".", "ra", ".", "degree", "dec", "=", "self", ".", "coord", ".", "dec", ".", "degree", "ccds", "=", "[", ...
Return an array of rectangles that represent the 'ra,dec' corners of the FOV @rtype: list
[ "Return", "an", "array", "of", "rectangles", "that", "represent", "the", "ra", "dec", "corners", "of", "the", "FOV", "@rtype", ":", "list" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/cameras.py#L283-L305
OSSOS/MOP
src/ossos/core/ossos/cameras.py
Camera.separation
def separation(self, ra, dec): """Compute the separation between self and (ra,dec)""" if self.coord is None: return None return self.coord.separation(SkyCoord(ra, dec, unit=('degree', 'degree')))
python
def separation(self, ra, dec): """Compute the separation between self and (ra,dec)""" if self.coord is None: return None return self.coord.separation(SkyCoord(ra, dec, unit=('degree', 'degree')))
[ "def", "separation", "(", "self", ",", "ra", ",", "dec", ")", ":", "if", "self", ".", "coord", "is", "None", ":", "return", "None", "return", "self", ".", "coord", ".", "separation", "(", "SkyCoord", "(", "ra", ",", "dec", ",", "unit", "=", "(", ...
Compute the separation between self and (ra,dec)
[ "Compute", "the", "separation", "between", "self", "and", "(", "ra", "dec", ")" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/cameras.py#L307-L311
OSSOS/MOP
src/jjk/preproc/preproc.py
trim
def trim(hdu): """TRIM a CFHT MEGAPRIME frame using the DATASEC keyword""" datasec = re.findall(r'(\d+)', hdu.header.get('DATASEC')) l=int(datasec[0])-1 r=int(datasec[1]) b=int(datasec[2])-1 t=int(datasec[3]) if opt.verbose: print "Trimming [%d:%d,%d:%d]" % ( l,r,b,t) hdu.data = hdu.data[b:t,l:r] hdu.header.update('DATASEC',"[%d:%d,%d:%d]" % (1,r-l+1,1,t-b+1), comment="Image was trimmed") hdu.header.update('ODATASEC',"[%d:%d,%d:%d]" % (l+1,r,b+1,t), comment="previous DATASEC") return
python
def trim(hdu): """TRIM a CFHT MEGAPRIME frame using the DATASEC keyword""" datasec = re.findall(r'(\d+)', hdu.header.get('DATASEC')) l=int(datasec[0])-1 r=int(datasec[1]) b=int(datasec[2])-1 t=int(datasec[3]) if opt.verbose: print "Trimming [%d:%d,%d:%d]" % ( l,r,b,t) hdu.data = hdu.data[b:t,l:r] hdu.header.update('DATASEC',"[%d:%d,%d:%d]" % (1,r-l+1,1,t-b+1), comment="Image was trimmed") hdu.header.update('ODATASEC',"[%d:%d,%d:%d]" % (l+1,r,b+1,t), comment="previous DATASEC") return
[ "def", "trim", "(", "hdu", ")", ":", "datasec", "=", "re", ".", "findall", "(", "r'(\\d+)'", ",", "hdu", ".", "header", ".", "get", "(", "'DATASEC'", ")", ")", "l", "=", "int", "(", "datasec", "[", "0", "]", ")", "-", "1", "r", "=", "int", "(...
TRIM a CFHT MEGAPRIME frame using the DATASEC keyword
[ "TRIM", "a", "CFHT", "MEGAPRIME", "frame", "using", "the", "DATASEC", "keyword" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/preproc.py#L55-L68
OSSOS/MOP
src/jjk/preproc/preproc.py
overscan
def overscan(hdu): """Overscan subtract a CFHT MEGAPRIME frame. oversan(hdu) --> status The BIAS section keywords are expected to be BSEC[A|B] (for amps A and B) and the AMP sectoin is ASEC[A|B]. """ for amp in (['A','B']): AMPKW= 'ASEC'+amp BIASKW= 'BSEC'+amp dsec=re.findall(r'(\d+)', hdu.header.get(AMPKW)) bias=re.findall(r'(\d+)', hdu.header.get(BIASKW)) ## the X-boundaries set the amp section off from the bias section ## (ie. this is a column orriented device) al=int(dsec[0])-1 ah=int(dsec[1]) bl=int(bias[0])-1 bh=int(bias[1]) ### the Y directions must match or the array math fails ## b == Bottom ## t == Top b=max(int(bias[2]),int(dsec[2]))-1 t=min(int(bias[3]),int(dsec[3])) bias = np.add.reduce(hdu.data[b:t,bl:bh],axis=1)/float(len(hdu.data[b:t,bl:bh][0])) mean = bias.mean() hdu.data[b:t,al:ah] -= bias[:,np.newaxis] hdu.data = hdu.data.astype('int16') hdu.header.update("BIAS",mean,comment="Mean bias level") del(bias) ### send back the mean bias level subtracted return mean
python
def overscan(hdu): """Overscan subtract a CFHT MEGAPRIME frame. oversan(hdu) --> status The BIAS section keywords are expected to be BSEC[A|B] (for amps A and B) and the AMP sectoin is ASEC[A|B]. """ for amp in (['A','B']): AMPKW= 'ASEC'+amp BIASKW= 'BSEC'+amp dsec=re.findall(r'(\d+)', hdu.header.get(AMPKW)) bias=re.findall(r'(\d+)', hdu.header.get(BIASKW)) ## the X-boundaries set the amp section off from the bias section ## (ie. this is a column orriented device) al=int(dsec[0])-1 ah=int(dsec[1]) bl=int(bias[0])-1 bh=int(bias[1]) ### the Y directions must match or the array math fails ## b == Bottom ## t == Top b=max(int(bias[2]),int(dsec[2]))-1 t=min(int(bias[3]),int(dsec[3])) bias = np.add.reduce(hdu.data[b:t,bl:bh],axis=1)/float(len(hdu.data[b:t,bl:bh][0])) mean = bias.mean() hdu.data[b:t,al:ah] -= bias[:,np.newaxis] hdu.data = hdu.data.astype('int16') hdu.header.update("BIAS",mean,comment="Mean bias level") del(bias) ### send back the mean bias level subtracted return mean
[ "def", "overscan", "(", "hdu", ")", ":", "for", "amp", "in", "(", "[", "'A'", ",", "'B'", "]", ")", ":", "AMPKW", "=", "'ASEC'", "+", "amp", "BIASKW", "=", "'BSEC'", "+", "amp", "dsec", "=", "re", ".", "findall", "(", "r'(\\d+)'", ",", "hdu", "...
Overscan subtract a CFHT MEGAPRIME frame. oversan(hdu) --> status The BIAS section keywords are expected to be BSEC[A|B] (for amps A and B) and the AMP sectoin is ASEC[A|B].
[ "Overscan", "subtract", "a", "CFHT", "MEGAPRIME", "frame", ".", "oversan", "(", "hdu", ")", "--", ">", "status" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/preproc.py#L70-L106
OSSOS/MOP
src/ossos/core/ossos/gui/progress.py
requires_lock
def requires_lock(function): """ Decorator to check if the user owns the required lock. The first argument must be the filename. """ def new_lock_requiring_function(self, filename, *args, **kwargs): if self.owns_lock(filename): return function(self, filename, *args, **kwargs) else: raise RequiresLockException() return new_lock_requiring_function
python
def requires_lock(function): """ Decorator to check if the user owns the required lock. The first argument must be the filename. """ def new_lock_requiring_function(self, filename, *args, **kwargs): if self.owns_lock(filename): return function(self, filename, *args, **kwargs) else: raise RequiresLockException() return new_lock_requiring_function
[ "def", "requires_lock", "(", "function", ")", ":", "def", "new_lock_requiring_function", "(", "self", ",", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "owns_lock", "(", "filename", ")", ":", "return", "function", "...
Decorator to check if the user owns the required lock. The first argument must be the filename.
[ "Decorator", "to", "check", "if", "the", "user", "owns", "the", "required", "lock", ".", "The", "first", "argument", "must", "be", "the", "filename", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/progress.py#L29-L41
OSSOS/MOP
src/ossos/core/ossos/gui/progress.py
LocalProgressManager.clean
def clean(self, suffixes=None): """ Remove all persistence-related files from the directory. """ if suffixes is None: suffixes = [DONE_SUFFIX, LOCK_SUFFIX, PART_SUFFIX] for suffix in suffixes: listing = self.working_context.get_listing(suffix) for filename in listing: self.working_context.remove(filename)
python
def clean(self, suffixes=None): """ Remove all persistence-related files from the directory. """ if suffixes is None: suffixes = [DONE_SUFFIX, LOCK_SUFFIX, PART_SUFFIX] for suffix in suffixes: listing = self.working_context.get_listing(suffix) for filename in listing: self.working_context.remove(filename)
[ "def", "clean", "(", "self", ",", "suffixes", "=", "None", ")", ":", "if", "suffixes", "is", "None", ":", "suffixes", "=", "[", "DONE_SUFFIX", ",", "LOCK_SUFFIX", ",", "PART_SUFFIX", "]", "for", "suffix", "in", "suffixes", ":", "listing", "=", "self", ...
Remove all persistence-related files from the directory.
[ "Remove", "all", "persistence", "-", "related", "files", "from", "the", "directory", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/progress.py#L359-L369
OSSOS/MOP
src/ossos/core/ossos/figures.py
setFigForm
def setFigForm(): """set the rcparams to EmulateApJ columnwidth=245.26 pts """ 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, 'text.fontsize': 12, 'legend.fontsize': 7, 'xtick.labelsize': 11, 'ytick.labelsize': 11, 'text.usetex': True, 'font.family': 'serif', 'font.serif': 'Times', 'image.aspect': 'auto', 'figure.subplot.left': 0.1, 'figure.subplot.bottom': 0.1, 'figure.subplot.hspace': 0.25, 'figure.figsize': fig_size} rcParams.update(params)
python
def setFigForm(): """set the rcparams to EmulateApJ columnwidth=245.26 pts """ 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, 'text.fontsize': 12, 'legend.fontsize': 7, 'xtick.labelsize': 11, 'ytick.labelsize': 11, 'text.usetex': True, 'font.family': 'serif', 'font.serif': 'Times', 'image.aspect': 'auto', 'figure.subplot.left': 0.1, 'figure.subplot.bottom': 0.1, 'figure.subplot.hspace': 0.25, 'figure.figsize': fig_size} rcParams.update(params)
[ "def", "setFigForm", "(", ")", ":", "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", "*", ...
set the rcparams to EmulateApJ columnwidth=245.26 pts
[ "set", "the", "rcparams", "to", "EmulateApJ", "columnwidth", "=", "245", ".", "26", "pts" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/figures.py#L5-L30
OSSOS/MOP
src/ossos/web/web/auth/gms.py
getCert
def getCert(username, password, certHost=_SERVER, certfile=None, certQuery=_PROXY): """Access the cadc certificate server.""" 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) password_mgr.add_password(None, top_level_url, username, password) handler = urllib2.HTTPBasicAuthHandler(password_mgr) logging.debug(str(handler)) # create "opener" (OpenerDirector instance) opener = urllib2.build_opener(handler) # Install the opener. urllib2.install_opener(opener) # buuld the url that with 'GET' a certificat using user_id/password info url = "http://" + certHost + certQuery logging.debug(url) r = None try: r = opener.open(url) except urllib2.HTTPError as e: logging.debug(url) logging.debug(str(e)) return False logging.debug(str(r)) if r is not None: while True: buf = r.read() logging.debug(buf) if not buf: break certfile.write(buf) r.close() return certfile
python
def getCert(username, password, certHost=_SERVER, certfile=None, certQuery=_PROXY): """Access the cadc certificate server.""" 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) password_mgr.add_password(None, top_level_url, username, password) handler = urllib2.HTTPBasicAuthHandler(password_mgr) logging.debug(str(handler)) # create "opener" (OpenerDirector instance) opener = urllib2.build_opener(handler) # Install the opener. urllib2.install_opener(opener) # buuld the url that with 'GET' a certificat using user_id/password info url = "http://" + certHost + certQuery logging.debug(url) r = None try: r = opener.open(url) except urllib2.HTTPError as e: logging.debug(url) logging.debug(str(e)) return False logging.debug(str(r)) if r is not None: while True: buf = r.read() logging.debug(buf) if not buf: break certfile.write(buf) r.close() return certfile
[ "def", "getCert", "(", "username", ",", "password", ",", "certHost", "=", "_SERVER", ",", "certfile", "=", "None", ",", "certQuery", "=", "_PROXY", ")", ":", "if", "certfile", "is", "None", ":", "certfile", "=", "tempfile", ".", "NamedTemporaryFile", "(", ...
Access the cadc certificate server.
[ "Access", "the", "cadc", "certificate", "server", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/web/web/auth/gms.py#L51-L97
OSSOS/MOP
src/ossos/web/web/auth/gms.py
getGroupsURL
def getGroupsURL(certfile, group): """given a certfile load a list of groups that user is a member of""" 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.append(i[0]) dn = i[0] + "=" + i[1] + sep + dn sep = "," return GMS + "/" + group + "/" + urllib.quote(dn)
python
def getGroupsURL(certfile, group): """given a certfile load a list of groups that user is a member of""" 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.append(i[0]) dn = i[0] + "=" + i[1] + sep + dn sep = "," return GMS + "/" + group + "/" + urllib.quote(dn)
[ "def", "getGroupsURL", "(", "certfile", ",", "group", ")", ":", "GMS", "=", "\"https://\"", "+", "_SERVER", "+", "_GMS", "certfile", ".", "seek", "(", "0", ")", "buf", "=", "certfile", ".", "read", "(", ")", "x509", "=", "crypto", ".", "load_certificat...
given a certfile load a list of groups that user is a member of
[ "given", "a", "certfile", "load", "a", "list", "of", "groups", "that", "user", "is", "a", "member", "of" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/web/web/auth/gms.py#L100-L120
OSSOS/MOP
src/ossos/web/web/auth/gms.py
isMember
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) """ 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, cert_file=certfile.name, timeout=600) con.connect() con.request("GET", group_url) resp = con.getresponse() if resp.status == 200: return True except Exception as e: logging.error(str(e)) #logging.debug(str(resp.status)) return False
python
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) """ 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, cert_file=certfile.name, timeout=600) con.connect() con.request("GET", group_url) resp = con.getresponse() if resp.status == 200: return True except Exception as e: logging.error(str(e)) #logging.debug(str(resp.status)) return False
[ "def", "isMember", "(", "userid", ",", "password", ",", "group", ")", ":", "try", ":", "certfile", "=", "getCert", "(", "userid", ",", "password", ")", "group_url", "=", "getGroupsURL", "(", "certfile", ",", "group", ")", "logging", ".", "debug", "(", ...
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)
[ "Test", "to", "see", "if", "the", "given", "userid", "/", "password", "combo", "is", "an", "authenticated", "member", "of", "group", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/web/web/auth/gms.py#L123-L153
OSSOS/MOP
src/ossos/web/web/auth/gms.py
stub
def stub(): """Just some left over code""" form = cgi.FieldStorage() userid = form['userid'].value password = form['passwd'].value group = form['group'].value
python
def stub(): """Just some left over code""" form = cgi.FieldStorage() userid = form['userid'].value password = form['passwd'].value group = form['group'].value
[ "def", "stub", "(", ")", ":", "form", "=", "cgi", ".", "FieldStorage", "(", ")", "userid", "=", "form", "[", "'userid'", "]", ".", "value", "password", "=", "form", "[", "'passwd'", "]", ".", "value", "group", "=", "form", "[", "'group'", "]", ".",...
Just some left over code
[ "Just", "some", "left", "over", "code" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/web/web/auth/gms.py#L156-L161
OSSOS/MOP
src/ossos/core/ossos/wcs.py
sky2xypv
def sky2xypv(ra, dec, crpix1, crpix2, crval1, crval2, dc, pv, nord, maxiter=300): """ Transforms from celestial coordinates to pixel coordinates to taking non-linear distortion into account with the World Coordinate System FITS keywords as used in MegaPipe. For the inverse operation see xy2sky. Reference material: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/megapipe/docs/CD_PV_keywords.pdf Args: ra: float Right ascension dec: float Declination crpix1: float Tangent point x, pixels crpix2: float Tangent point y, pixels crval1: float Tangent point RA, degrees crval2: Tangent point Dec, degrees dc: 2d array Expresses the scale, the rotation and any possible skew of the image with respect to the sky. It is the inverse of the cd matrix in xy2sky. pv: 2d array nord: int order of the fit Returns: x, y: float Pixel coordinates """ if math.fabs(ra - crval1) > 100: if crval1 < 180: ra -= 360 else: ra += 360 ra /= PI180 dec /= PI180 tdec = math.tan(dec) ra0 = crval1 / PI180 dec0 = crval2 / PI180 ctan = math.tan(dec0) ccos = math.cos(dec0) traoff = math.tan(ra - ra0) craoff = math.cos(ra - ra0) etar = (1 - ctan * craoff / tdec) / (ctan + craoff / tdec) xir = traoff * ccos * (1 - etar * ctan) xi = xir * PI180 eta = etar * PI180 if nord < 0: # The simple solution x = xi y = eta else: # Reverse by Newton's method tolerance = 0.001 / 3600 # Initial guess x = xi y = eta iteration = 0 converged = False while not converged: assert nord >= 0 # Estimates f = pv[0][0] g = pv[1][0] # Derivatives fx = 0 fy = 0 gx = 0 gy = 0 if nord >= 1: r = math.sqrt(x ** 2 + y ** 2) f += pv[0][1] * x + pv[0][2] * y + pv[0][3] * r g += pv[1][1] * y + pv[1][2] * x + pv[1][3] * r fx += pv[0][1] + pv[0][3] * x / r fy += pv[0][2] + pv[0][3] * y / r gx += pv[1][2] + pv[1][3] * x / r gy += pv[1][1] + pv[1][3] * y / r if nord >= 2: x2 = x ** 2 xy = x * y y2 = y ** 2 f += pv[0][4] * x2 + pv[0][5] * xy + pv[0][6] * y2 g += pv[1][4] * y2 + pv[1][5] * xy + pv[1][6] * x2 fx += pv[0][4] * 2 * x + pv[0][5] * y fy += pv[0][5] * x + pv[0][6] * 2 * y gx += pv[1][5] * y + pv[1][6] * 2 * x gy += pv[1][4] * 2 * y + pv[1][5] * x if nord >= 3: x3 = x ** 3 x2y = x2 * y xy2 = x * y2 y3 = y ** 3 f += pv[0][7] * x3 + pv[0][8] * x2y + pv[0][9] * xy2 + pv[0][10] * y3 g += pv[1][7] * y3 + pv[1][8] * xy2 + pv[1][9] * x2y + pv[1][10] * x3 fx += pv[0][7] * 3 * x2 + pv[0][8] * 2 * xy + pv[0][9] * y2 fy += pv[0][8] * x2 + pv[0][9] * 2 * xy + pv[0][10] * 3 * y2 gx += pv[0][8] * y2 + pv[1][9] * 2 * xy + pv[1][10] * 3 * x2 gy += pv[1][7] * 3 * y2 + pv[0][8] * 2 * xy + pv[1][9] * x2 f -= xi g -= eta dx = (-f * gy + g * fy) / (fx * gy - fy * gx) dy = (-g * fx + f * gx) / (fx * gy - fy * gx) x += dx y += dy if math.fabs(dx) < tolerance and math.fabs(dy) < tolerance: converged = True iteration += 1 if iteration > maxiter: break xp = dc[0][0] * x + dc[0][1] * y yp = dc[1][0] * x + dc[1][1] * y x = xp + crpix1 y = yp + crpix2 return x, y
python
def sky2xypv(ra, dec, crpix1, crpix2, crval1, crval2, dc, pv, nord, maxiter=300): """ Transforms from celestial coordinates to pixel coordinates to taking non-linear distortion into account with the World Coordinate System FITS keywords as used in MegaPipe. For the inverse operation see xy2sky. Reference material: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/megapipe/docs/CD_PV_keywords.pdf Args: ra: float Right ascension dec: float Declination crpix1: float Tangent point x, pixels crpix2: float Tangent point y, pixels crval1: float Tangent point RA, degrees crval2: Tangent point Dec, degrees dc: 2d array Expresses the scale, the rotation and any possible skew of the image with respect to the sky. It is the inverse of the cd matrix in xy2sky. pv: 2d array nord: int order of the fit Returns: x, y: float Pixel coordinates """ if math.fabs(ra - crval1) > 100: if crval1 < 180: ra -= 360 else: ra += 360 ra /= PI180 dec /= PI180 tdec = math.tan(dec) ra0 = crval1 / PI180 dec0 = crval2 / PI180 ctan = math.tan(dec0) ccos = math.cos(dec0) traoff = math.tan(ra - ra0) craoff = math.cos(ra - ra0) etar = (1 - ctan * craoff / tdec) / (ctan + craoff / tdec) xir = traoff * ccos * (1 - etar * ctan) xi = xir * PI180 eta = etar * PI180 if nord < 0: # The simple solution x = xi y = eta else: # Reverse by Newton's method tolerance = 0.001 / 3600 # Initial guess x = xi y = eta iteration = 0 converged = False while not converged: assert nord >= 0 # Estimates f = pv[0][0] g = pv[1][0] # Derivatives fx = 0 fy = 0 gx = 0 gy = 0 if nord >= 1: r = math.sqrt(x ** 2 + y ** 2) f += pv[0][1] * x + pv[0][2] * y + pv[0][3] * r g += pv[1][1] * y + pv[1][2] * x + pv[1][3] * r fx += pv[0][1] + pv[0][3] * x / r fy += pv[0][2] + pv[0][3] * y / r gx += pv[1][2] + pv[1][3] * x / r gy += pv[1][1] + pv[1][3] * y / r if nord >= 2: x2 = x ** 2 xy = x * y y2 = y ** 2 f += pv[0][4] * x2 + pv[0][5] * xy + pv[0][6] * y2 g += pv[1][4] * y2 + pv[1][5] * xy + pv[1][6] * x2 fx += pv[0][4] * 2 * x + pv[0][5] * y fy += pv[0][5] * x + pv[0][6] * 2 * y gx += pv[1][5] * y + pv[1][6] * 2 * x gy += pv[1][4] * 2 * y + pv[1][5] * x if nord >= 3: x3 = x ** 3 x2y = x2 * y xy2 = x * y2 y3 = y ** 3 f += pv[0][7] * x3 + pv[0][8] * x2y + pv[0][9] * xy2 + pv[0][10] * y3 g += pv[1][7] * y3 + pv[1][8] * xy2 + pv[1][9] * x2y + pv[1][10] * x3 fx += pv[0][7] * 3 * x2 + pv[0][8] * 2 * xy + pv[0][9] * y2 fy += pv[0][8] * x2 + pv[0][9] * 2 * xy + pv[0][10] * 3 * y2 gx += pv[0][8] * y2 + pv[1][9] * 2 * xy + pv[1][10] * 3 * x2 gy += pv[1][7] * 3 * y2 + pv[0][8] * 2 * xy + pv[1][9] * x2 f -= xi g -= eta dx = (-f * gy + g * fy) / (fx * gy - fy * gx) dy = (-g * fx + f * gx) / (fx * gy - fy * gx) x += dx y += dy if math.fabs(dx) < tolerance and math.fabs(dy) < tolerance: converged = True iteration += 1 if iteration > maxiter: break xp = dc[0][0] * x + dc[0][1] * y yp = dc[1][0] * x + dc[1][1] * y x = xp + crpix1 y = yp + crpix2 return x, y
[ "def", "sky2xypv", "(", "ra", ",", "dec", ",", "crpix1", ",", "crpix2", ",", "crval1", ",", "crval2", ",", "dc", ",", "pv", ",", "nord", ",", "maxiter", "=", "300", ")", ":", "if", "math", ".", "fabs", "(", "ra", "-", "crval1", ")", ">", "100",...
Transforms from celestial coordinates to pixel coordinates to taking non-linear distortion into account with the World Coordinate System FITS keywords as used in MegaPipe. For the inverse operation see xy2sky. Reference material: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/megapipe/docs/CD_PV_keywords.pdf Args: ra: float Right ascension dec: float Declination crpix1: float Tangent point x, pixels crpix2: float Tangent point y, pixels crval1: float Tangent point RA, degrees crval2: Tangent point Dec, degrees dc: 2d array Expresses the scale, the rotation and any possible skew of the image with respect to the sky. It is the inverse of the cd matrix in xy2sky. pv: 2d array nord: int order of the fit Returns: x, y: float Pixel coordinates
[ "Transforms", "from", "celestial", "coordinates", "to", "pixel", "coordinates", "to", "taking", "non", "-", "linear", "distortion", "into", "account", "with", "the", "World", "Coordinate", "System", "FITS", "keywords", "as", "used", "in", "MegaPipe", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/wcs.py#L132-L271
OSSOS/MOP
src/ossos/core/ossos/wcs.py
xy2skypv
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.pdf Args: x, y: float Input pixel coordinate crpix1: float Tangent point x, pixels crpix2: float Tangent point y, pixels crval1: float Tangent point RA, degrees crval2: Tangent point Dec, degrees cd: 2d array Expresses the scale, the rotation and any possible skew of the image with respect to the sky. pv: 2d array nord: int order of the fit Returns: ra: float Right ascension dec: float Declination """ 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: xi = pv[0][0] eta = pv[1][0] if nord >= 1: r = numpy.sqrt(x_deg ** 2 + y_deg ** 2) xi += pv[0][1] * x_deg + pv[0][2] * y_deg + pv[0][3] * r eta += pv[1][1] * y_deg + pv[1][2] * x_deg + pv[1][3] * r if nord >= 2: x2 = x_deg ** 2 xy = x_deg * y_deg y2 = y_deg ** 2 xi += pv[0][4] * x2 + pv[0][5] * xy + pv[0][6] * y2 eta += pv[1][4] * y2 + pv[1][5] * xy + pv[1][6] * x2 if nord >= 3: x3 = x_deg ** 3 x2y = x2 * y_deg xy2 = x_deg * y2 y3 = y_deg ** 3 xi += pv[0][7] * x3 + pv[0][8] * x2y + pv[0][9] * xy2 + pv[0][10] * y3 eta += pv[1][7] * y3 + pv[1][8] * xy2 + pv[1][9] * x2y + pv[1][10] * x3 xir = xi / PI180 etar = eta / PI180 ra0 = crval1 / PI180 dec0 = crval2 / PI180 ctan = numpy.tan(dec0) ccos = numpy.cos(dec0) raoff = numpy.arctan2(xir / ccos, 1 - etar * ctan) ra = raoff + ra0 dec = numpy.arctan(numpy.cos(raoff) / ((1 - (etar * ctan)) / (etar + ctan))) ra *= PI180 ra = numpy.where(ra < 0 , ra + 360, ra) ra = numpy.where(ra > 360, ra - 360, ra) # f = numpy.int(ra < 0) + 360 # print f # if ra < 0: # ra += 360 # if ra >= 360: # ra -= 360 dec *= PI180 return ra * units.degree, dec * units.degree
python
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.pdf Args: x, y: float Input pixel coordinate crpix1: float Tangent point x, pixels crpix2: float Tangent point y, pixels crval1: float Tangent point RA, degrees crval2: Tangent point Dec, degrees cd: 2d array Expresses the scale, the rotation and any possible skew of the image with respect to the sky. pv: 2d array nord: int order of the fit Returns: ra: float Right ascension dec: float Declination """ 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: xi = pv[0][0] eta = pv[1][0] if nord >= 1: r = numpy.sqrt(x_deg ** 2 + y_deg ** 2) xi += pv[0][1] * x_deg + pv[0][2] * y_deg + pv[0][3] * r eta += pv[1][1] * y_deg + pv[1][2] * x_deg + pv[1][3] * r if nord >= 2: x2 = x_deg ** 2 xy = x_deg * y_deg y2 = y_deg ** 2 xi += pv[0][4] * x2 + pv[0][5] * xy + pv[0][6] * y2 eta += pv[1][4] * y2 + pv[1][5] * xy + pv[1][6] * x2 if nord >= 3: x3 = x_deg ** 3 x2y = x2 * y_deg xy2 = x_deg * y2 y3 = y_deg ** 3 xi += pv[0][7] * x3 + pv[0][8] * x2y + pv[0][9] * xy2 + pv[0][10] * y3 eta += pv[1][7] * y3 + pv[1][8] * xy2 + pv[1][9] * x2y + pv[1][10] * x3 xir = xi / PI180 etar = eta / PI180 ra0 = crval1 / PI180 dec0 = crval2 / PI180 ctan = numpy.tan(dec0) ccos = numpy.cos(dec0) raoff = numpy.arctan2(xir / ccos, 1 - etar * ctan) ra = raoff + ra0 dec = numpy.arctan(numpy.cos(raoff) / ((1 - (etar * ctan)) / (etar + ctan))) ra *= PI180 ra = numpy.where(ra < 0 , ra + 360, ra) ra = numpy.where(ra > 360, ra - 360, ra) # f = numpy.int(ra < 0) + 360 # print f # if ra < 0: # ra += 360 # if ra >= 360: # ra -= 360 dec *= PI180 return ra * units.degree, dec * units.degree
[ "def", "xy2skypv", "(", "x", ",", "y", ",", "crpix1", ",", "crpix2", ",", "crval1", ",", "crval2", ",", "cd", ",", "pv", ",", "nord", ")", ":", "xp", "=", "x", "-", "crpix1", "yp", "=", "y", "-", "crpix2", "# IMPORTANT NOTE: 0-based indexing in Python ...
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.pdf Args: x, y: float Input pixel coordinate crpix1: float Tangent point x, pixels crpix2: float Tangent point y, pixels crval1: float Tangent point RA, degrees crval2: Tangent point Dec, degrees cd: 2d array Expresses the scale, the rotation and any possible skew of the image with respect to the sky. pv: 2d array nord: int order of the fit Returns: ra: float Right ascension dec: float Declination
[ "Transforms", "from", "pixel", "coordinates", "to", "celestial", "coordinates", "taking", "non", "-", "linear", "distortion", "into", "account", "with", "the", "World", "Coordinate", "System", "FITS", "keywords", "as", "used", "in", "MegaPipe", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/wcs.py#L274-L370
OSSOS/MOP
src/ossos/core/ossos/wcs.py
parse_pv
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. For example, an order 3 fit goes up to PV?_10. """ 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: parse_range(1, 3) if order_fit >= 2: parse_range(4, 6) if order_fit >= 3: parse_range(7, 10) return pvi_x return [parse_with_base(1), parse_with_base(2)]
python
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. For example, an order 3 fit goes up to PV?_10. """ 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: parse_range(1, 3) if order_fit >= 2: parse_range(4, 6) if order_fit >= 3: parse_range(7, 10) return pvi_x return [parse_with_base(1), parse_with_base(2)]
[ "def", "parse_pv", "(", "header", ")", ":", "order_fit", "=", "parse_order_fit", "(", "header", ")", "def", "parse_with_base", "(", "i", ")", ":", "key_base", "=", "\"PV%d_\"", "%", "i", "pvi_x", "=", "[", "header", "[", "key_base", "+", "\"0\"", "]", ...
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. For example, an order 3 fit goes up to PV?_10.
[ "Parses", "the", "PV", "array", "from", "an", "astropy", "FITS", "header", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/wcs.py#L389-L425
JohnVinyard/zounds
zounds/nputil/npx.py
safe_unit_norm
def safe_unit_norm(a): """ Ensure that the vector or vectors have unit norm """ 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 be dividing # a vector of zeros by the number, and 0 / N always equals 0. norm[norm == 0] = -1e12 return a / norm[:, np.newaxis]
python
def safe_unit_norm(a): """ Ensure that the vector or vectors have unit norm """ 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 be dividing # a vector of zeros by the number, and 0 / N always equals 0. norm[norm == 0] = -1e12 return a / norm[:, np.newaxis]
[ "def", "safe_unit_norm", "(", "a", ")", ":", "if", "1", "==", "len", "(", "a", ".", "shape", ")", ":", "n", "=", "np", ".", "linalg", ".", "norm", "(", "a", ")", "if", "n", ":", "return", "a", "/", "n", "return", "a", "norm", "=", "np", "."...
Ensure that the vector or vectors have unit norm
[ "Ensure", "that", "the", "vector", "or", "vectors", "have", "unit", "norm" ]
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/nputil/npx.py#L47-L63
JohnVinyard/zounds
zounds/nputil/npx.py
pad
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 """ 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
python
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 """ 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", ")", ":", "if", "len", "(", "a", ")", ">=", "desiredlength", ":", "return", "a", "islist", "=", "isinstance", "(", "a", ",", "list", ")", "a", "=", "np", ".", "array", "(", "a", ")", "diff", "=", "d...
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
[ "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", ...
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/nputil/npx.py#L66-L83
JohnVinyard/zounds
zounds/nputil/npx.py
_wpad
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 """ 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
python
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 """ 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", ")", ":", "if", "l", "<=", "windowsize", ":", "return", "windowsize", "nsteps", "=", "(", "(", "l", "//", "stepsize", ")", "*", "stepsize", ")", "overlap", "=", "(", "windowsize", "-", "st...
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
[ "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" ]
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/nputil/npx.py#L86-L106
JohnVinyard/zounds
zounds/nputil/npx.py
_wcut
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 """ end = l - windowsize if l <= windowsize: return 0, 0 elif end % stepsize: l = windowsize + ((end // stepsize) * stepsize) return l, l - (windowsize - stepsize)
python
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 """ 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", ")", ":", "end", "=", "l", "-", "windowsize", "if", "l", "<=", "windowsize", ":", "return", "0", ",", "0", "elif", "end", "%", "stepsize", ":", "l", "=", "windowsize", "+", "(", "(", "...
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
[ "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" ]
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/nputil/npx.py#L109-L125
JohnVinyard/zounds
zounds/nputil/npx.py
windowed
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 (default), leftover samples are returned seperately. If true, the input array is padded with zeros so that all samples are used. """ 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() if windowsize == 1 and stepsize == 1: # A windowsize and stepsize of one mean that no windowing is necessary. # Return the array unchanged. return np.zeros((0,) + a.shape[1:], dtype=a.dtype), a if windowsize == 1 and stepsize > 1: return np.zeros(0, dtype=a.dtype), a[::stepsize] # the original length of the input array l = a.shape[0] if dopad: p = _wpad(l, windowsize, stepsize) # pad the array with enough zeros so that there are no leftover samples a = pad(a, p) # no leftovers; an empty array leftover = np.zeros((0,) + a.shape[1:], dtype=a.dtype) else: # cut the array so that any leftover samples are returned seperately c, lc = _wcut(l, windowsize, stepsize) leftover = a[lc:] a = a[:c] if 0 == a.shape[0]: return leftover, np.zeros(a.shape, dtype=a.dtype) n = 1 + (a.shape[0] - windowsize) // (stepsize) s = a.strides[0] newshape = (n, windowsize) + a.shape[1:] newstrides = (stepsize * s, s) + a.strides[1:] out = np.ndarray.__new__( \ np.ndarray, strides=newstrides, shape=newshape, buffer=a, dtype=a.dtype) return leftover, out
python
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 (default), leftover samples are returned seperately. If true, the input array is padded with zeros so that all samples are used. """ 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() if windowsize == 1 and stepsize == 1: # A windowsize and stepsize of one mean that no windowing is necessary. # Return the array unchanged. return np.zeros((0,) + a.shape[1:], dtype=a.dtype), a if windowsize == 1 and stepsize > 1: return np.zeros(0, dtype=a.dtype), a[::stepsize] # the original length of the input array l = a.shape[0] if dopad: p = _wpad(l, windowsize, stepsize) # pad the array with enough zeros so that there are no leftover samples a = pad(a, p) # no leftovers; an empty array leftover = np.zeros((0,) + a.shape[1:], dtype=a.dtype) else: # cut the array so that any leftover samples are returned seperately c, lc = _wcut(l, windowsize, stepsize) leftover = a[lc:] a = a[:c] if 0 == a.shape[0]: return leftover, np.zeros(a.shape, dtype=a.dtype) n = 1 + (a.shape[0] - windowsize) // (stepsize) s = a.strides[0] newshape = (n, windowsize) + a.shape[1:] newstrides = (stepsize * s, s) + a.strides[1:] out = np.ndarray.__new__( \ np.ndarray, strides=newstrides, shape=newshape, buffer=a, dtype=a.dtype) return leftover, out
[ "def", "windowed", "(", "a", ",", "windowsize", ",", "stepsize", "=", "None", ",", "dopad", "=", "False", ")", ":", "if", "windowsize", "<", "1", ":", "raise", "ValueError", "(", "'windowsize must be greater than or equal to one'", ")", "if", "stepsize", "is",...
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 (default), leftover samples are returned seperately. If true, the input array is padded with zeros so that all samples are used.
[ "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", "windo...
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/nputil/npx.py#L128-L190
JohnVinyard/zounds
zounds/nputil/npx.py
Growable.append
def append(self, item): """ append a single item to the array, growing the wrapped numpy array if necessary """ try: self._data[self._position] = item except IndexError: self._grow() self._data[self._position] = item self._position += 1 return self
python
def append(self, item): """ append a single item to the array, growing the wrapped numpy array if necessary """ try: self._data[self._position] = item except IndexError: self._grow() self._data[self._position] = item self._position += 1 return self
[ "def", "append", "(", "self", ",", "item", ")", ":", "try", ":", "self", ".", "_data", "[", "self", ".", "_position", "]", "=", "item", "except", "IndexError", ":", "self", ".", "_grow", "(", ")", "self", ".", "_data", "[", "self", ".", "_position"...
append a single item to the array, growing the wrapped numpy array if necessary
[ "append", "a", "single", "item", "to", "the", "array", "growing", "the", "wrapped", "numpy", "array", "if", "necessary" ]
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/nputil/npx.py#L332-L343
JohnVinyard/zounds
zounds/nputil/npx.py
Growable.extend
def extend(self, items): """ extend the numpy array with multiple items, growing the wrapped array if necessary """ 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 memory by the prescribed amount still won't # make enough room. Allocate exactly as much memory as is needed # to accommodate items amt = pos - self.physical_size # actually grow the array self._grow(amt=amt) stop = self._position + items.shape[0] self._data[self._position: stop] = items self._position += items.shape[0] return self
python
def extend(self, items): """ extend the numpy array with multiple items, growing the wrapped array if necessary """ 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 memory by the prescribed amount still won't # make enough room. Allocate exactly as much memory as is needed # to accommodate items amt = pos - self.physical_size # actually grow the array self._grow(amt=amt) stop = self._position + items.shape[0] self._data[self._position: stop] = items self._position += items.shape[0] return self
[ "def", "extend", "(", "self", ",", "items", ")", ":", "items", "=", "np", ".", "array", "(", "items", ")", "pos", "=", "items", ".", "shape", "[", "0", "]", "+", "self", ".", "logical_size", "if", "pos", ">", "self", ".", "physical_size", ":", "#...
extend the numpy array with multiple items, growing the wrapped array if necessary
[ "extend", "the", "numpy", "array", "with", "multiple", "items", "growing", "the", "wrapped", "array", "if", "necessary" ]
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/nputil/npx.py#L345-L367
OSSOS/MOP
src/ossos/core/ossos/fitsviewer/baseviewer.py
WxMPLFitsViewer.display
def display(self, cutout, use_pixel_coords=False): """ :param cutout: source cutout object to be display :type cutout: source.SourceCutout """ 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[cutout] else: displayable = self._create_displayable(cutout) self._displayables_by_cutout[cutout] = displayable self._detach_handlers(self.current_displayable) self.current_cutout = cutout self.current_displayable = displayable self._attach_handlers(self.current_displayable) self._do_render(self.current_displayable) self.mark_apertures(cutout, pixel=use_pixel_coords) self.draw_uncertainty_ellipse(cutout)
python
def display(self, cutout, use_pixel_coords=False): """ :param cutout: source cutout object to be display :type cutout: source.SourceCutout """ 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[cutout] else: displayable = self._create_displayable(cutout) self._displayables_by_cutout[cutout] = displayable self._detach_handlers(self.current_displayable) self.current_cutout = cutout self.current_displayable = displayable self._attach_handlers(self.current_displayable) self._do_render(self.current_displayable) self.mark_apertures(cutout, pixel=use_pixel_coords) self.draw_uncertainty_ellipse(cutout)
[ "def", "display", "(", "self", ",", "cutout", ",", "use_pixel_coords", "=", "False", ")", ":", "logging", ".", "debug", "(", "\"Current display list contains: {}\"", ".", "format", "(", "self", ".", "_displayables_by_cutout", ".", "keys", "(", ")", ")", ")", ...
:param cutout: source cutout object to be display :type cutout: source.SourceCutout
[ ":", "param", "cutout", ":", "source", "cutout", "object", "to", "be", "display", ":", "type", "cutout", ":", "source", ".", "SourceCutout" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/fitsviewer/baseviewer.py#L34-L53
OSSOS/MOP
src/ossos/core/ossos/fitsviewer/baseviewer.py
WxMPLFitsViewer.draw_uncertainty_ellipse
def draw_uncertainty_ellipse(self, cutout): """ Draws an ErrEllipse with the spcified dimensions. Only one ErrEllipse can be drawn and only once (not movable). """ 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.sky_coord # RA/DEC value of observation / prediction goes to X/Y using PV keywords predict_ra = sky_coord.ra.to(units.degree) predict_dec = sky_coord.dec.to(units.degree) x, y, extno = cutout.world2pix(predict_ra, predict_dec, usepv=True) # The X/Y pixel values are then converted to RA/DEC without PV for use with DS9. ra, dec = cutout.pix2world(x, y, extno, usepv=False) uncertainty_ellipse = cutout.reading.uncertainty_ellipse self.current_displayable.place_ellipse((ra, dec), uncertainty_ellipse, colour=colour, dash=dash) # Also mark on the image where source is localted, not just the ellipse. try: measured_ra = cutout.reading.mpc_observation.coordinate.ra.to(units.degree) measured_dec = cutout.reading.mpc_observation.coordinate.dec.to(units.degree) try: print "{:5.2f} {:5.2f} || {:5.2f} {:5.2f} # {}".format((predict_ra - measured_ra).to('arcsec'), (predict_dec - measured_dec).to('arcsec'), cutout.reading.uncertainty_ellipse.a, cutout.reading.uncertainty_ellipse.b, cutout.reading.mpc_observation.to_string()) except Exception as ex: print "Failed trying to write out the prevoiusly recorded measurement: {}".format(ex) pass # x, y, extno = cutout.world2pix(measured_ra, measured_dec, usepv=True) # ra, dec = cutout.pix2world(x, y, extno, usepv=False) except Exception as ex: # print "We had an error :{}".format(ex) logging.debug(str(ex)) logging.debug("Failed to get x/y from previous observation, using prediction.") hdulist_index = cutout.get_hdulist_idx(cutout.reading.get_ccd_num()) measured_ra, measured_dec = cutout.pix2world(cutout.pixel_x, cutout.pixel_y, hdulist_index, usepv=True) colour = 'm' self.current_displayable.place_marker(measured_ra, measured_dec, radius=8, colour=colour) except Exception as ex: print "EXCEPTION while drawing the uncertainty ellipse, skipping.: {}".format(ex) logger.debug(type(ex)) logger.debug(str(ex))
python
def draw_uncertainty_ellipse(self, cutout): """ Draws an ErrEllipse with the spcified dimensions. Only one ErrEllipse can be drawn and only once (not movable). """ 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.sky_coord # RA/DEC value of observation / prediction goes to X/Y using PV keywords predict_ra = sky_coord.ra.to(units.degree) predict_dec = sky_coord.dec.to(units.degree) x, y, extno = cutout.world2pix(predict_ra, predict_dec, usepv=True) # The X/Y pixel values are then converted to RA/DEC without PV for use with DS9. ra, dec = cutout.pix2world(x, y, extno, usepv=False) uncertainty_ellipse = cutout.reading.uncertainty_ellipse self.current_displayable.place_ellipse((ra, dec), uncertainty_ellipse, colour=colour, dash=dash) # Also mark on the image where source is localted, not just the ellipse. try: measured_ra = cutout.reading.mpc_observation.coordinate.ra.to(units.degree) measured_dec = cutout.reading.mpc_observation.coordinate.dec.to(units.degree) try: print "{:5.2f} {:5.2f} || {:5.2f} {:5.2f} # {}".format((predict_ra - measured_ra).to('arcsec'), (predict_dec - measured_dec).to('arcsec'), cutout.reading.uncertainty_ellipse.a, cutout.reading.uncertainty_ellipse.b, cutout.reading.mpc_observation.to_string()) except Exception as ex: print "Failed trying to write out the prevoiusly recorded measurement: {}".format(ex) pass # x, y, extno = cutout.world2pix(measured_ra, measured_dec, usepv=True) # ra, dec = cutout.pix2world(x, y, extno, usepv=False) except Exception as ex: # print "We had an error :{}".format(ex) logging.debug(str(ex)) logging.debug("Failed to get x/y from previous observation, using prediction.") hdulist_index = cutout.get_hdulist_idx(cutout.reading.get_ccd_num()) measured_ra, measured_dec = cutout.pix2world(cutout.pixel_x, cutout.pixel_y, hdulist_index, usepv=True) colour = 'm' self.current_displayable.place_marker(measured_ra, measured_dec, radius=8, colour=colour) except Exception as ex: print "EXCEPTION while drawing the uncertainty ellipse, skipping.: {}".format(ex) logger.debug(type(ex)) logger.debug(str(ex))
[ "def", "draw_uncertainty_ellipse", "(", "self", ",", "cutout", ")", ":", "if", "not", "self", ".", "mark_prediction", ":", "return", "try", ":", "colour", "=", "cutout", ".", "reading", ".", "from_input_file", "and", "'b'", "or", "'g'", "colour", "=", "cut...
Draws an ErrEllipse with the spcified dimensions. Only one ErrEllipse can be drawn and only once (not movable).
[ "Draws", "an", "ErrEllipse", "with", "the", "spcified", "dimensions", ".", "Only", "one", "ErrEllipse", "can", "be", "drawn", "and", "only", "once", "(", "not", "movable", ")", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/fitsviewer/baseviewer.py#L58-L112
OSSOS/MOP
src/ossos/core/ossos/fitsviewer/baseviewer.py
WxMPLFitsViewer.align
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 @return: """ 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_calculator, source)) #focus = cutout.flip_flip(focus_calculator.calculate_focus(reading)) #focus = cutout.get_pixel_coordinates(focus) #focus = cutout.pix2world(focus[0], focus[1], usepv=False) #focus_sky_coord = SkyCoord(focus[0], focus[1]) self.current_displayable.pan_to(focus_sky_coord)
python
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 @return: """ 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_calculator, source)) #focus = cutout.flip_flip(focus_calculator.calculate_focus(reading)) #focus = cutout.get_pixel_coordinates(focus) #focus = cutout.pix2world(focus[0], focus[1], usepv=False) #focus_sky_coord = SkyCoord(focus[0], focus[1]) self.current_displayable.pan_to(focus_sky_coord)
[ "def", "align", "(", "self", ",", "cutout", ",", "reading", ",", "source", ")", ":", "if", "not", "self", ".", "current_displayable", ":", "return", "if", "not", "self", ".", "current_displayable", ".", "aligned", ":", "focus_sky_coord", "=", "reading", "....
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 @return:
[ "Set", "the", "display", "center", "to", "the", "reference", "point", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/fitsviewer/baseviewer.py#L141-L163
OSSOS/MOP
src/ossos/core/ossos/daophot.py
phot
def phot(fits_filename, x_in, y_in, aperture=15, sky=20, swidth=10, apcor=0.3, maxcount=30000.0, exptime=1.0, zmag=None, extno=0, centroid=True): """ Compute the centroids and magnitudes of a bunch sources on fits image. :rtype : astropy.table.Table :param fits_filename: Name of fits image to measure source photometry on. :type fits_filename: str :param x_in: x location of source to measure :type x_in: float, numpy.array :param y_in: y location of source to measure :type y_in: float, numpy.array :param aperture: radius of circular aperture to use. :type aperture: float :param sky: radius of inner sky annulus :type sky: float :param swidth: width of the sky annulus :type swidth: float :param apcor: Aperture correction to take aperture flux to full flux. :type apcor: float :param maxcount: maximum linearity in the image. :type maxcount: float :param exptime: exposure time, relative to zmag supplied :type exptime: float :param zmag: zeropoint magnitude :param extno: extension of fits_filename the x/y location refers to. """ if not hasattr(x_in, '__iter__'): x_in = [x_in, ] if not hasattr(y_in, '__iter__'): y_in = [y_in, ] if (not os.path.exists(fits_filename) and not fits_filename.endswith(".fits")): # For convenience, see if we just forgot to provide the extension fits_filename += ".fits" try: input_hdulist = fits.open(fits_filename) except Exception as err: logger.debug(str(err)) raise TaskError("Failed to open input image: %s" % err.message) # get the filter for this image filter_name = input_hdulist[extno].header.get('FILTER', 'DEFAULT') # Some nominal CFHT zeropoints that might be useful zeropoints = {"I": 25.77, "R": 26.07, "V": 26.07, "B": 25.92, "DEFAULT": 26.0, "g.MP9401": 32.0, 'r.MP9601': 31.9, 'gri.MP9603': 33.520} if zmag is None: logger.warning("No zmag supplied to daophot, looking for header or default values.") zmag = input_hdulist[extno].header.get('PHOTZP', zeropoints[filter_name]) logger.warning("Setting zmag to: {}".format(zmag)) # check for magic 'zeropoint.used' files for zpu_file in ["{}.zeropoint.used".format(os.path.splitext(fits_filename)[0]), "zeropoint.used"]: if os.access(zpu_file, os.R_OK): with open(zpu_file) as zpu_fh: zmag = float(zpu_fh.read()) logger.warning("Using file {} to set zmag to: {}".format(zpu_file, zmag)) break photzp = input_hdulist[extno].header.get('PHOTZP', zeropoints.get(filter_name, zeropoints["DEFAULT"])) if zmag != photzp: logger.warning(("zmag sent to daophot: ({}) " "doesn't match PHOTZP value in image header: ({})".format(zmag, photzp))) # setup IRAF to do the magnitude/centroid measurements iraf.set(uparm="./") iraf.digiphot() iraf.apphot() iraf.daophot(_doprint=0) iraf.photpars.apertures = aperture iraf.photpars.zmag = zmag iraf.datapars.datamin = 0 iraf.datapars.datamax = maxcount iraf.datapars.exposur = "" iraf.datapars.itime = exptime iraf.fitskypars.annulus = sky iraf.fitskypars.dannulus = swidth iraf.fitskypars.salgorithm = "mode" iraf.fitskypars.sloclip = 5.0 iraf.fitskypars.shiclip = 5.0 if centroid: iraf.centerpars.calgori = "centroid" iraf.centerpars.cbox = 5. iraf.centerpars.cthreshold = 0. iraf.centerpars.maxshift = 2. iraf.centerpars.clean = 'no' else: iraf.centerpars.calgori = "none" iraf.phot.update = 'no' iraf.phot.verbose = 'no' iraf.phot.verify = 'no' iraf.phot.interactive = 'no' # Used for passing the input coordinates coofile = tempfile.NamedTemporaryFile(suffix=".coo", delete=False) for i in range(len(x_in)): coofile.write("%f %f \n" % (x_in[i], y_in[i])) coofile.flush() # Used for receiving the results of the task # mag_fd, mag_path = tempfile.mkstemp(suffix=".mag") magfile = tempfile.NamedTemporaryFile(suffix=".mag", delete=False) # Close the temp files before sending to IRAF due to docstring: # "Whether the name can be used to open the file a second time, while # the named temporary file is still open, varies across platforms" coofile.close() magfile.close() os.remove(magfile.name) iraf.phot(fits_filename+"[{}]".format(extno), coofile.name, magfile.name) pdump_out = ascii.read(magfile.name, format='daophot') logging.debug("PHOT FILE:\n"+str(pdump_out)) if not len(pdump_out) > 0: mag_content = open(magfile.name).read() raise TaskError("photometry failed. {}".format(mag_content)) # apply the aperture correction pdump_out['MAG'] -= apcor # if pdump_out['PIER'][0] != 0 or pdump_out['SIER'][0] != 0 or pdump_out['CIER'][0] != 0: # raise ValueError("Photometry failed:\n {}".format(pdump_out)) # Clean up temporary files generated by IRAF os.remove(coofile.name) os.remove(magfile.name) logger.debug("Computed aperture photometry on {} objects in {}".format(len(pdump_out), fits_filename)) del input_hdulist return pdump_out
python
def phot(fits_filename, x_in, y_in, aperture=15, sky=20, swidth=10, apcor=0.3, maxcount=30000.0, exptime=1.0, zmag=None, extno=0, centroid=True): """ Compute the centroids and magnitudes of a bunch sources on fits image. :rtype : astropy.table.Table :param fits_filename: Name of fits image to measure source photometry on. :type fits_filename: str :param x_in: x location of source to measure :type x_in: float, numpy.array :param y_in: y location of source to measure :type y_in: float, numpy.array :param aperture: radius of circular aperture to use. :type aperture: float :param sky: radius of inner sky annulus :type sky: float :param swidth: width of the sky annulus :type swidth: float :param apcor: Aperture correction to take aperture flux to full flux. :type apcor: float :param maxcount: maximum linearity in the image. :type maxcount: float :param exptime: exposure time, relative to zmag supplied :type exptime: float :param zmag: zeropoint magnitude :param extno: extension of fits_filename the x/y location refers to. """ if not hasattr(x_in, '__iter__'): x_in = [x_in, ] if not hasattr(y_in, '__iter__'): y_in = [y_in, ] if (not os.path.exists(fits_filename) and not fits_filename.endswith(".fits")): # For convenience, see if we just forgot to provide the extension fits_filename += ".fits" try: input_hdulist = fits.open(fits_filename) except Exception as err: logger.debug(str(err)) raise TaskError("Failed to open input image: %s" % err.message) # get the filter for this image filter_name = input_hdulist[extno].header.get('FILTER', 'DEFAULT') # Some nominal CFHT zeropoints that might be useful zeropoints = {"I": 25.77, "R": 26.07, "V": 26.07, "B": 25.92, "DEFAULT": 26.0, "g.MP9401": 32.0, 'r.MP9601': 31.9, 'gri.MP9603': 33.520} if zmag is None: logger.warning("No zmag supplied to daophot, looking for header or default values.") zmag = input_hdulist[extno].header.get('PHOTZP', zeropoints[filter_name]) logger.warning("Setting zmag to: {}".format(zmag)) # check for magic 'zeropoint.used' files for zpu_file in ["{}.zeropoint.used".format(os.path.splitext(fits_filename)[0]), "zeropoint.used"]: if os.access(zpu_file, os.R_OK): with open(zpu_file) as zpu_fh: zmag = float(zpu_fh.read()) logger.warning("Using file {} to set zmag to: {}".format(zpu_file, zmag)) break photzp = input_hdulist[extno].header.get('PHOTZP', zeropoints.get(filter_name, zeropoints["DEFAULT"])) if zmag != photzp: logger.warning(("zmag sent to daophot: ({}) " "doesn't match PHOTZP value in image header: ({})".format(zmag, photzp))) # setup IRAF to do the magnitude/centroid measurements iraf.set(uparm="./") iraf.digiphot() iraf.apphot() iraf.daophot(_doprint=0) iraf.photpars.apertures = aperture iraf.photpars.zmag = zmag iraf.datapars.datamin = 0 iraf.datapars.datamax = maxcount iraf.datapars.exposur = "" iraf.datapars.itime = exptime iraf.fitskypars.annulus = sky iraf.fitskypars.dannulus = swidth iraf.fitskypars.salgorithm = "mode" iraf.fitskypars.sloclip = 5.0 iraf.fitskypars.shiclip = 5.0 if centroid: iraf.centerpars.calgori = "centroid" iraf.centerpars.cbox = 5. iraf.centerpars.cthreshold = 0. iraf.centerpars.maxshift = 2. iraf.centerpars.clean = 'no' else: iraf.centerpars.calgori = "none" iraf.phot.update = 'no' iraf.phot.verbose = 'no' iraf.phot.verify = 'no' iraf.phot.interactive = 'no' # Used for passing the input coordinates coofile = tempfile.NamedTemporaryFile(suffix=".coo", delete=False) for i in range(len(x_in)): coofile.write("%f %f \n" % (x_in[i], y_in[i])) coofile.flush() # Used for receiving the results of the task # mag_fd, mag_path = tempfile.mkstemp(suffix=".mag") magfile = tempfile.NamedTemporaryFile(suffix=".mag", delete=False) # Close the temp files before sending to IRAF due to docstring: # "Whether the name can be used to open the file a second time, while # the named temporary file is still open, varies across platforms" coofile.close() magfile.close() os.remove(magfile.name) iraf.phot(fits_filename+"[{}]".format(extno), coofile.name, magfile.name) pdump_out = ascii.read(magfile.name, format='daophot') logging.debug("PHOT FILE:\n"+str(pdump_out)) if not len(pdump_out) > 0: mag_content = open(magfile.name).read() raise TaskError("photometry failed. {}".format(mag_content)) # apply the aperture correction pdump_out['MAG'] -= apcor # if pdump_out['PIER'][0] != 0 or pdump_out['SIER'][0] != 0 or pdump_out['CIER'][0] != 0: # raise ValueError("Photometry failed:\n {}".format(pdump_out)) # Clean up temporary files generated by IRAF os.remove(coofile.name) os.remove(magfile.name) logger.debug("Computed aperture photometry on {} objects in {}".format(len(pdump_out), fits_filename)) del input_hdulist return pdump_out
[ "def", "phot", "(", "fits_filename", ",", "x_in", ",", "y_in", ",", "aperture", "=", "15", ",", "sky", "=", "20", ",", "swidth", "=", "10", ",", "apcor", "=", "0.3", ",", "maxcount", "=", "30000.0", ",", "exptime", "=", "1.0", ",", "zmag", "=", "...
Compute the centroids and magnitudes of a bunch sources on fits image. :rtype : astropy.table.Table :param fits_filename: Name of fits image to measure source photometry on. :type fits_filename: str :param x_in: x location of source to measure :type x_in: float, numpy.array :param y_in: y location of source to measure :type y_in: float, numpy.array :param aperture: radius of circular aperture to use. :type aperture: float :param sky: radius of inner sky annulus :type sky: float :param swidth: width of the sky annulus :type swidth: float :param apcor: Aperture correction to take aperture flux to full flux. :type apcor: float :param maxcount: maximum linearity in the image. :type maxcount: float :param exptime: exposure time, relative to zmag supplied :type exptime: float :param zmag: zeropoint magnitude :param extno: extension of fits_filename the x/y location refers to.
[ "Compute", "the", "centroids", "and", "magnitudes", "of", "a", "bunch", "sources", "on", "fits", "image", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/daophot.py#L19-L158
OSSOS/MOP
src/ossos/core/ossos/daophot.py
phot_mag
def phot_mag(*args, **kwargs): """Wrapper around phot which only returns the computed magnitude directly.""" try: return phot(*args, **kwargs) except IndexError: raise TaskError("No photometric records returned for {0}".format(kwargs))
python
def phot_mag(*args, **kwargs): """Wrapper around phot which only returns the computed magnitude directly.""" try: return phot(*args, **kwargs) except IndexError: raise TaskError("No photometric records returned for {0}".format(kwargs))
[ "def", "phot_mag", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "phot", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "IndexError", ":", "raise", "TaskError", "(", "\"No photometric records returned for {0}\"", "."...
Wrapper around phot which only returns the computed magnitude directly.
[ "Wrapper", "around", "phot", "which", "only", "returns", "the", "computed", "magnitude", "directly", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/daophot.py#L161-L166
OSSOS/MOP
src/ossos/web/web/block/queries.py
BlockQuery.all_blocks
def all_blocks(self): 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', '-', '-'] status['15AP'] = ['discovery running', '-', '-'] status['15AM'] = ['discovery running', '-', '-'] '''Overview tal table is expecting: ID observations processing status discoveries m_r 40% ''' bks = [] for block in status.iterkeys(): bk = [block, self.num_block_images(block)] # if set in the .fromkeys(), doesn't give a unique list if status[block] is not None: bk = bk + status[block] else: bk = bk + ['awaiting triplets', '-', '-'] bks.append(bk) retval = {'blocks': bks, 'status': status} return retval
python
def all_blocks(self): 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', '-', '-'] status['15AP'] = ['discovery running', '-', '-'] status['15AM'] = ['discovery running', '-', '-'] '''Overview tal table is expecting: ID observations processing status discoveries m_r 40% ''' bks = [] for block in status.iterkeys(): bk = [block, self.num_block_images(block)] # if set in the .fromkeys(), doesn't give a unique list if status[block] is not None: bk = bk + status[block] else: bk = bk + ['awaiting triplets', '-', '-'] bks.append(bk) retval = {'blocks': bks, 'status': status} return retval
[ "def", "all_blocks", "(", "self", ")", ":", "status", "=", "OrderedDict", ".", "fromkeys", "(", "parameters", ".", "BLOCKS", ".", "keys", "(", ")", ")", "status", "[", "'13AE'", "]", "=", "[", "'discovery complete'", ",", "'50'", ",", "'24.05'", "]", "...
Overview tal table is expecting: ID observations processing status discoveries m_r 40%
[ "Overview", "tal", "table", "is", "expecting", ":", "ID", "observations", "processing", "status", "discoveries", "m_r", "40%" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/web/web/block/queries.py#L21-L45
playpauseandstop/rororo
rororo/settings.py
from_env
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`` """ return os.getenv(key, default)
python
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`` """ return os.getenv(key, default)
[ "def", "from_env", "(", "key", ":", "str", ",", "default", ":", "T", "=", "None", ")", "->", "Union", "[", "str", ",", "Optional", "[", "T", "]", "]", ":", "return", "os", ".", "getenv", "(", "key", ",", "default", ")" ]
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``
[ "Shortcut", "for", "safely", "reading", "environment", "variable", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/settings.py#L26-L34