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/web/web/initiate/populate_ossuary.py
main
def main(): """ Update the ossuary Postgres db with images observed for OSSOS. iq: Go through and check all ossuary's images for new existence of IQs/zeropoints. comment: Go through all ossuary and Then updates ossuary with new images that are at any stage of processing. Constructs full image entries, including header and info in the vtags, and inserts to ossuary. TODO: a CLUSTER after data is inserted - maybe once a week, depending how much there is CLUSTER images; need to sqlalchemy this one """ parser = argparse.ArgumentParser() parser.add_argument("-iq", "--iq", action="store_true", help="Check existing images in ossuary that do not yet have " "IQ/zeropoint information; update where possible.") parser.add_argument("-comment", action="store_true", help="Add comments on images provided by S. Gwyn to database.") parser.add_argument("-snr", action="store_true", help="Update existing images in ossuary for SNR info where that exists in a vtag.") args = parser.parse_args() images = web.field_obs.queries.ImagesQuery() processed_images, iqs = retrieve_processed_images(images) # straight list of primary keys commdict = parse_sgwn_comments() if args.iq: unmeasured_iqs = iq_unmeasured_images(images) sys.stdout.write('%d images in ossuary; updating %d with new IQ/zeropoint information.\n' % (len(processed_images), len(unmeasured_iqs))) for n, image in enumerate(unmeasured_iqs): # it's in the db, so has already passed the other checks update_values(images, image) sys.stdout.write('%s %d/%d...ossuary updated.\n' % (image, n + 1, len(unmeasured_iqs))) if args.snr: unmeasured = snr_unmeasured_images(images) sys.stdout.write('%d images in ossuary; updating %d with new SNR information.\n' % (len(processed_images), len(unmeasured))) for n, image in enumerate(unmeasured): # it's in the db, so has already passed the other checks update_values(images, image, iq_zeropt=False, snr=True) sys.stdout.write('%s %d/%d...ossuary updated.\n' % (image, n + 1, len(unmeasured))) if args.comment: sys.stdout.write('%d images in ossuary; updating with new comment information.\n' % len(processed_images)) for image in commdict.keys(): if int(image) in processed_images: update_values(images, image, iq_zeropt=False, comment=True, commdict=commdict) sys.stdout.write('%s has comment...\n' % image) unprocessed_images = parse_unprocessed_images(storage.list_dbimages(), processed_images) sys.stdout.write('%d images in ossuary; updating with %d new in VOspace.\n' % (len(processed_images), len(unprocessed_images))) for n, image in enumerate(unprocessed_images): sys.stdout.write('%s %d/%d ' % (image, n + 1, len(unprocessed_images))) try: subheader, fullheader = get_header(image) if subheader is not None: sys.stdout.write('Header obtained. ') verify_ossos_image(fullheader) header = get_iq_and_zeropoint(image, subheader) header = get_snr(image, header) if image in commdict.keys(): header['comment'] = commdict[image] put_image_in_database(header, images) sys.stdout.write('...added to ossuary...\n') # generate_MegaCam_previews(image) # sys.stdout.write(' .gif preview saved.\n') else: sys.stdout.write('Header is not available: skipping.\n') except Exception, e: sys.stdout.write('... %s\n' % e)
python
def main(): """ Update the ossuary Postgres db with images observed for OSSOS. iq: Go through and check all ossuary's images for new existence of IQs/zeropoints. comment: Go through all ossuary and Then updates ossuary with new images that are at any stage of processing. Constructs full image entries, including header and info in the vtags, and inserts to ossuary. TODO: a CLUSTER after data is inserted - maybe once a week, depending how much there is CLUSTER images; need to sqlalchemy this one """ parser = argparse.ArgumentParser() parser.add_argument("-iq", "--iq", action="store_true", help="Check existing images in ossuary that do not yet have " "IQ/zeropoint information; update where possible.") parser.add_argument("-comment", action="store_true", help="Add comments on images provided by S. Gwyn to database.") parser.add_argument("-snr", action="store_true", help="Update existing images in ossuary for SNR info where that exists in a vtag.") args = parser.parse_args() images = web.field_obs.queries.ImagesQuery() processed_images, iqs = retrieve_processed_images(images) # straight list of primary keys commdict = parse_sgwn_comments() if args.iq: unmeasured_iqs = iq_unmeasured_images(images) sys.stdout.write('%d images in ossuary; updating %d with new IQ/zeropoint information.\n' % (len(processed_images), len(unmeasured_iqs))) for n, image in enumerate(unmeasured_iqs): # it's in the db, so has already passed the other checks update_values(images, image) sys.stdout.write('%s %d/%d...ossuary updated.\n' % (image, n + 1, len(unmeasured_iqs))) if args.snr: unmeasured = snr_unmeasured_images(images) sys.stdout.write('%d images in ossuary; updating %d with new SNR information.\n' % (len(processed_images), len(unmeasured))) for n, image in enumerate(unmeasured): # it's in the db, so has already passed the other checks update_values(images, image, iq_zeropt=False, snr=True) sys.stdout.write('%s %d/%d...ossuary updated.\n' % (image, n + 1, len(unmeasured))) if args.comment: sys.stdout.write('%d images in ossuary; updating with new comment information.\n' % len(processed_images)) for image in commdict.keys(): if int(image) in processed_images: update_values(images, image, iq_zeropt=False, comment=True, commdict=commdict) sys.stdout.write('%s has comment...\n' % image) unprocessed_images = parse_unprocessed_images(storage.list_dbimages(), processed_images) sys.stdout.write('%d images in ossuary; updating with %d new in VOspace.\n' % (len(processed_images), len(unprocessed_images))) for n, image in enumerate(unprocessed_images): sys.stdout.write('%s %d/%d ' % (image, n + 1, len(unprocessed_images))) try: subheader, fullheader = get_header(image) if subheader is not None: sys.stdout.write('Header obtained. ') verify_ossos_image(fullheader) header = get_iq_and_zeropoint(image, subheader) header = get_snr(image, header) if image in commdict.keys(): header['comment'] = commdict[image] put_image_in_database(header, images) sys.stdout.write('...added to ossuary...\n') # generate_MegaCam_previews(image) # sys.stdout.write(' .gif preview saved.\n') else: sys.stdout.write('Header is not available: skipping.\n') except Exception, e: sys.stdout.write('... %s\n' % e)
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"-iq\"", ",", "\"--iq\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Check existing images in ossuary that do not yet ha...
Update the ossuary Postgres db with images observed for OSSOS. iq: Go through and check all ossuary's images for new existence of IQs/zeropoints. comment: Go through all ossuary and Then updates ossuary with new images that are at any stage of processing. Constructs full image entries, including header and info in the vtags, and inserts to ossuary. TODO: a CLUSTER after data is inserted - maybe once a week, depending how much there is CLUSTER images; need to sqlalchemy this one
[ "Update", "the", "ossuary", "Postgres", "db", "with", "images", "observed", "for", "OSSOS", ".", "iq", ":", "Go", "through", "and", "check", "all", "ossuary", "s", "images", "for", "new", "existence", "of", "IQs", "/", "zeropoints", ".", "comment", ":", ...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/web/web/initiate/populate_ossuary.py#L298-L370
JohnVinyard/zounds
zounds/spectral/frequencyadaptive.py
FrequencyAdaptive.square
def square(self, n_coeffs, do_overlap_add=False): """ Compute a "square" view of the frequency adaptive transform, by resampling each frequency band such that they all contain the same number of samples, and performing an overlap-add procedure in the case where the sample frequency and duration differ :param n_coeffs: The common size to which each frequency band should be resampled """ resampled_bands = [ self._resample(band, n_coeffs) for band in self.iter_bands()] stacked = np.vstack(resampled_bands).T fdim = FrequencyDimension(self.scale) # TODO: This feels like it could be wrapped up nicely elsewhere chunk_frequency = Picoseconds(int(np.round( self.time_dimension.duration / Picoseconds(1) / n_coeffs))) td = TimeDimension(frequency=chunk_frequency) arr = ConstantRateTimeSeries(ArrayWithUnits( stacked.reshape(-1, n_coeffs, self.n_bands), dimensions=[self.time_dimension, td, fdim])) if not do_overlap_add: return arr # Begin the overlap add procedure overlap_ratio = self.time_dimension.overlap_ratio if overlap_ratio == 0: # no overlap add is necessary return ArrayWithUnits(stacked, [td, fdim]) step_size_samples = int(n_coeffs * overlap_ratio) first_dim = int(np.round( (stacked.shape[0] * overlap_ratio) + (n_coeffs * overlap_ratio))) output = ArrayWithUnits( np.zeros((first_dim, self.n_bands)), dimensions=[td, fdim]) for i, chunk in enumerate(arr): start = step_size_samples * i stop = start + n_coeffs output[start: stop] += chunk.reshape((-1, self.n_bands)) return output
python
def square(self, n_coeffs, do_overlap_add=False): """ Compute a "square" view of the frequency adaptive transform, by resampling each frequency band such that they all contain the same number of samples, and performing an overlap-add procedure in the case where the sample frequency and duration differ :param n_coeffs: The common size to which each frequency band should be resampled """ resampled_bands = [ self._resample(band, n_coeffs) for band in self.iter_bands()] stacked = np.vstack(resampled_bands).T fdim = FrequencyDimension(self.scale) # TODO: This feels like it could be wrapped up nicely elsewhere chunk_frequency = Picoseconds(int(np.round( self.time_dimension.duration / Picoseconds(1) / n_coeffs))) td = TimeDimension(frequency=chunk_frequency) arr = ConstantRateTimeSeries(ArrayWithUnits( stacked.reshape(-1, n_coeffs, self.n_bands), dimensions=[self.time_dimension, td, fdim])) if not do_overlap_add: return arr # Begin the overlap add procedure overlap_ratio = self.time_dimension.overlap_ratio if overlap_ratio == 0: # no overlap add is necessary return ArrayWithUnits(stacked, [td, fdim]) step_size_samples = int(n_coeffs * overlap_ratio) first_dim = int(np.round( (stacked.shape[0] * overlap_ratio) + (n_coeffs * overlap_ratio))) output = ArrayWithUnits( np.zeros((first_dim, self.n_bands)), dimensions=[td, fdim]) for i, chunk in enumerate(arr): start = step_size_samples * i stop = start + n_coeffs output[start: stop] += chunk.reshape((-1, self.n_bands)) return output
[ "def", "square", "(", "self", ",", "n_coeffs", ",", "do_overlap_add", "=", "False", ")", ":", "resampled_bands", "=", "[", "self", ".", "_resample", "(", "band", ",", "n_coeffs", ")", "for", "band", "in", "self", ".", "iter_bands", "(", ")", "]", "stac...
Compute a "square" view of the frequency adaptive transform, by resampling each frequency band such that they all contain the same number of samples, and performing an overlap-add procedure in the case where the sample frequency and duration differ :param n_coeffs: The common size to which each frequency band should be resampled
[ "Compute", "a", "square", "view", "of", "the", "frequency", "adaptive", "transform", "by", "resampling", "each", "frequency", "band", "such", "that", "they", "all", "contain", "the", "same", "number", "of", "samples", "and", "performing", "an", "overlap", "-",...
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/frequencyadaptive.py#L94-L145
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/calculator.py
CoordinateConverter.convert
def convert(self, point): """ Convert a point from one coordinate system to another. Args: point: tuple(int x, int y) The point in the original coordinate system. Returns: converted_point: tuple(int x, int y) The point in the new coordinate system. Example: convert coordinate from original image into a pixel location within a cutout image. @rtype: list(float,float) """ x, y = point (x1, y1) = x - self.x_offset, y - self.y_offset logger.debug("converted {} {} ==> {} {}".format(x, y, x1, y1)) return x1, y1
python
def convert(self, point): """ Convert a point from one coordinate system to another. Args: point: tuple(int x, int y) The point in the original coordinate system. Returns: converted_point: tuple(int x, int y) The point in the new coordinate system. Example: convert coordinate from original image into a pixel location within a cutout image. @rtype: list(float,float) """ x, y = point (x1, y1) = x - self.x_offset, y - self.y_offset logger.debug("converted {} {} ==> {} {}".format(x, y, x1, y1)) return x1, y1
[ "def", "convert", "(", "self", ",", "point", ")", ":", "x", ",", "y", "=", "point", "(", "x1", ",", "y1", ")", "=", "x", "-", "self", ".", "x_offset", ",", "y", "-", "self", ".", "y_offset", "logger", ".", "debug", "(", "\"converted {} {} ==> {} {}...
Convert a point from one coordinate system to another. Args: point: tuple(int x, int y) The point in the original coordinate system. Returns: converted_point: tuple(int x, int y) The point in the new coordinate system. Example: convert coordinate from original image into a pixel location within a cutout image. @rtype: list(float,float)
[ "Convert", "a", "point", "from", "one", "coordinate", "system", "to", "another", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/calculator.py#L36-L56
JohnVinyard/zounds
zounds/learn/util.py
simple_settings
def simple_settings(cls): """ Create sane default persistence settings for learning pipelines :param cls: The class to decorate """ class Settings(ff.PersistenceSettings): _id = cls.__name__ id_provider = ff.StaticIdProvider(_id) key_builder = ff.StringDelimitedKeyBuilder() database = ff.FileSystemDatabase( path=_id, key_builder=key_builder, createdirs=True) class Model(cls, Settings): pass Model.__name__ = cls.__name__ Model.__module__ = cls.__module__ return Model
python
def simple_settings(cls): """ Create sane default persistence settings for learning pipelines :param cls: The class to decorate """ class Settings(ff.PersistenceSettings): _id = cls.__name__ id_provider = ff.StaticIdProvider(_id) key_builder = ff.StringDelimitedKeyBuilder() database = ff.FileSystemDatabase( path=_id, key_builder=key_builder, createdirs=True) class Model(cls, Settings): pass Model.__name__ = cls.__name__ Model.__module__ = cls.__module__ return Model
[ "def", "simple_settings", "(", "cls", ")", ":", "class", "Settings", "(", "ff", ".", "PersistenceSettings", ")", ":", "_id", "=", "cls", ".", "__name__", "id_provider", "=", "ff", ".", "StaticIdProvider", "(", "_id", ")", "key_builder", "=", "ff", ".", "...
Create sane default persistence settings for learning pipelines :param cls: The class to decorate
[ "Create", "sane", "default", "persistence", "settings", "for", "learning", "pipelines", ":", "param", "cls", ":", "The", "class", "to", "decorate" ]
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/learn/util.py#L11-L29
JohnVinyard/zounds
zounds/learn/util.py
apply_network
def apply_network(network, x, chunksize=None): """ Apply a pytorch network, potentially in chunks """ network_is_cuda = next(network.parameters()).is_cuda x = torch.from_numpy(x) with torch.no_grad(): if network_is_cuda: x = x.cuda() if chunksize is None: return from_var(network(x)) return np.concatenate( [from_var(network(x[i: i + chunksize])) for i in range(0, len(x), chunksize)])
python
def apply_network(network, x, chunksize=None): """ Apply a pytorch network, potentially in chunks """ network_is_cuda = next(network.parameters()).is_cuda x = torch.from_numpy(x) with torch.no_grad(): if network_is_cuda: x = x.cuda() if chunksize is None: return from_var(network(x)) return np.concatenate( [from_var(network(x[i: i + chunksize])) for i in range(0, len(x), chunksize)])
[ "def", "apply_network", "(", "network", ",", "x", ",", "chunksize", "=", "None", ")", ":", "network_is_cuda", "=", "next", "(", "network", ".", "parameters", "(", ")", ")", ".", "is_cuda", "x", "=", "torch", ".", "from_numpy", "(", "x", ")", "with", ...
Apply a pytorch network, potentially in chunks
[ "Apply", "a", "pytorch", "network", "potentially", "in", "chunks" ]
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/learn/util.py#L92-L109
JohnVinyard/zounds
zounds/learn/util.py
sample_norm
def sample_norm(x): """ pixel norm as described in section 4.2 here: https://arxiv.org/pdf/1710.10196.pdf """ original = x # square x = x ** 2 # feature-map-wise sum x = torch.sum(x, dim=1) # scale by number of feature maps x *= 1.0 / original.shape[1] x += 10e-8 x = torch.sqrt(x) return original / x.view(-1, 1, x.shape[-1])
python
def sample_norm(x): """ pixel norm as described in section 4.2 here: https://arxiv.org/pdf/1710.10196.pdf """ original = x # square x = x ** 2 # feature-map-wise sum x = torch.sum(x, dim=1) # scale by number of feature maps x *= 1.0 / original.shape[1] x += 10e-8 x = torch.sqrt(x) return original / x.view(-1, 1, x.shape[-1])
[ "def", "sample_norm", "(", "x", ")", ":", "original", "=", "x", "# square", "x", "=", "x", "**", "2", "# feature-map-wise sum", "x", "=", "torch", ".", "sum", "(", "x", ",", "dim", "=", "1", ")", "# scale by number of feature maps", "x", "*=", "1.0", "...
pixel norm as described in section 4.2 here: https://arxiv.org/pdf/1710.10196.pdf
[ "pixel", "norm", "as", "described", "in", "section", "4", ".", "2", "here", ":", "https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1710", ".", "10196", ".", "pdf" ]
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/learn/util.py#L112-L126
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.reset_coord
def reset_coord(self): """ Reset the source location based on the init_skycoord values @return: """ (x, y, idx) = self.world2pix(self.init_skycoord.ra, self.init_skycoord.dec, usepv=True) self.update_pixel_location((x, y), idx)
python
def reset_coord(self): """ Reset the source location based on the init_skycoord values @return: """ (x, y, idx) = self.world2pix(self.init_skycoord.ra, self.init_skycoord.dec, usepv=True) self.update_pixel_location((x, y), idx)
[ "def", "reset_coord", "(", "self", ")", ":", "(", "x", ",", "y", ",", "idx", ")", "=", "self", ".", "world2pix", "(", "self", ".", "init_skycoord", ".", "ra", ",", "self", ".", "init_skycoord", ".", "dec", ",", "usepv", "=", "True", ")", "self", ...
Reset the source location based on the init_skycoord values @return:
[ "Reset", "the", "source", "location", "based", "on", "the", "init_skycoord", "values" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L63-L71
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.pixel_coord
def pixel_coord(self): """ Return the coordinates of the source in the cutout reference frame. @return: """ return self.get_pixel_coordinates(self.reading.pix_coord, self.reading.get_ccd_num())
python
def pixel_coord(self): """ Return the coordinates of the source in the cutout reference frame. @return: """ return self.get_pixel_coordinates(self.reading.pix_coord, self.reading.get_ccd_num())
[ "def", "pixel_coord", "(", "self", ")", ":", "return", "self", ".", "get_pixel_coordinates", "(", "self", ".", "reading", ".", "pix_coord", ",", "self", ".", "reading", ".", "get_ccd_num", "(", ")", ")" ]
Return the coordinates of the source in the cutout reference frame. @return:
[ "Return", "the", "coordinates", "of", "the", "source", "in", "the", "cutout", "reference", "frame", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L74-L79
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.get_hdulist_idx
def get_hdulist_idx(self, ccdnum): """ The SourceCutout is a list of HDUs, this method returns the index of the HDU that corresponds to the given ccd number. CCDs are numbers from 0, but the first CCD (CCDNUM=0) is often in extension 1 of an MEF. @param ccdnum: the number of the CCD in the MEF that is being referenced. @return: the index of in self.hdulist that corresponds to the given CCD number. """ for (extno, hdu) in enumerate(self.hdulist): if ccdnum == int(hdu.header.get('EXTVER', -1)) or str(ccdnum) in hdu.header.get('AMPNAME', ''): return extno raise ValueError("Failed to find requested CCD Number {} in cutout {}".format(ccdnum, self))
python
def get_hdulist_idx(self, ccdnum): """ The SourceCutout is a list of HDUs, this method returns the index of the HDU that corresponds to the given ccd number. CCDs are numbers from 0, but the first CCD (CCDNUM=0) is often in extension 1 of an MEF. @param ccdnum: the number of the CCD in the MEF that is being referenced. @return: the index of in self.hdulist that corresponds to the given CCD number. """ for (extno, hdu) in enumerate(self.hdulist): if ccdnum == int(hdu.header.get('EXTVER', -1)) or str(ccdnum) in hdu.header.get('AMPNAME', ''): return extno raise ValueError("Failed to find requested CCD Number {} in cutout {}".format(ccdnum, self))
[ "def", "get_hdulist_idx", "(", "self", ",", "ccdnum", ")", ":", "for", "(", "extno", ",", "hdu", ")", "in", "enumerate", "(", "self", ".", "hdulist", ")", ":", "if", "ccdnum", "==", "int", "(", "hdu", ".", "header", ".", "get", "(", "'EXTVER'", ","...
The SourceCutout is a list of HDUs, this method returns the index of the HDU that corresponds to the given ccd number. CCDs are numbers from 0, but the first CCD (CCDNUM=0) is often in extension 1 of an MEF. @param ccdnum: the number of the CCD in the MEF that is being referenced. @return: the index of in self.hdulist that corresponds to the given CCD number.
[ "The", "SourceCutout", "is", "a", "list", "of", "HDUs", "this", "method", "returns", "the", "index", "of", "the", "HDU", "that", "corresponds", "to", "the", "given", "ccd", "number", ".", "CCDs", "are", "numbers", "from", "0", "but", "the", "first", "CCD...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L118-L129
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.flip_flip
def flip_flip(self, point): """ Sometimes we 'flipped' the X/Y coordinates of the image during processing. This function takes an (x,y) location from the processing pipeline and returns the x/y location relative to the original reference frame. (Correctly checks if the coordinate is flipped to begin with.) This is only for use on the original X/Y coordinates as provided by an input reading. @param point: an x/y location on the image. @type point: [x, y] @return: the x/y location on the un-fliped frame """ x, y = point if self.reading.compute_inverted(): naxis1 = self.reading.obs.header.get(self.reading.obs.HEADER_IMG_SIZE_X, self.reading.obs.header.get('NAXIS1', 256)) naxis2 = self.reading.obs.header.get(self.reading.obs.HEADER_IMG_SIZE_Y, self.reading.obs.header.get('NAXIS2', 256)) logger.debug("Got that image has size {}, {}".format(naxis1, naxis2)) x1 = x y1 = y x = int(naxis1) - x + 1 y = int(naxis2) - y + 1 logger.debug("Inverted source location from {},{} to {},{}".format(x1, y1, x, y)) return x, y
python
def flip_flip(self, point): """ Sometimes we 'flipped' the X/Y coordinates of the image during processing. This function takes an (x,y) location from the processing pipeline and returns the x/y location relative to the original reference frame. (Correctly checks if the coordinate is flipped to begin with.) This is only for use on the original X/Y coordinates as provided by an input reading. @param point: an x/y location on the image. @type point: [x, y] @return: the x/y location on the un-fliped frame """ x, y = point if self.reading.compute_inverted(): naxis1 = self.reading.obs.header.get(self.reading.obs.HEADER_IMG_SIZE_X, self.reading.obs.header.get('NAXIS1', 256)) naxis2 = self.reading.obs.header.get(self.reading.obs.HEADER_IMG_SIZE_Y, self.reading.obs.header.get('NAXIS2', 256)) logger.debug("Got that image has size {}, {}".format(naxis1, naxis2)) x1 = x y1 = y x = int(naxis1) - x + 1 y = int(naxis2) - y + 1 logger.debug("Inverted source location from {},{} to {},{}".format(x1, y1, x, y)) return x, y
[ "def", "flip_flip", "(", "self", ",", "point", ")", ":", "x", ",", "y", "=", "point", "if", "self", ".", "reading", ".", "compute_inverted", "(", ")", ":", "naxis1", "=", "self", ".", "reading", ".", "obs", ".", "header", ".", "get", "(", "self", ...
Sometimes we 'flipped' the X/Y coordinates of the image during processing. This function takes an (x,y) location from the processing pipeline and returns the x/y location relative to the original reference frame. (Correctly checks if the coordinate is flipped to begin with.) This is only for use on the original X/Y coordinates as provided by an input reading. @param point: an x/y location on the image. @type point: [x, y] @return: the x/y location on the un-fliped frame
[ "Sometimes", "we", "flipped", "the", "X", "/", "Y", "coordinates", "of", "the", "image", "during", "processing", ".", "This", "function", "takes", "an", "(", "x", "y", ")", "location", "from", "the", "processing", "pipeline", "and", "returns", "the", "x", ...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L131-L157
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.update_pixel_location
def update_pixel_location(self, new_pixel_location, hdu_index): """ Update the x/y location of the associated reading by using new_pixel_location and transforming from cutout reference frame to observation refrence frame. @param new_pixel_location: (x, y) location of the source in cutout pixel reference frame @param hdu_index: index of the associate hdu in the hdulist for this cutout """ self.reading.pix_coord = self.get_observation_coordinates(new_pixel_location[0], new_pixel_location[1], hdu_index) new_ccd = self.get_ccdnum(hdu_index) if new_ccd != self.reading.get_ccd_num(): self._apcor = None self._zmag = None self.reading.obs.ccdnum = self.get_ccdnum(hdu_index) self.reading.sky_coord = self.pix2world(new_pixel_location[0], new_pixel_location[1], hdu_index)
python
def update_pixel_location(self, new_pixel_location, hdu_index): """ Update the x/y location of the associated reading by using new_pixel_location and transforming from cutout reference frame to observation refrence frame. @param new_pixel_location: (x, y) location of the source in cutout pixel reference frame @param hdu_index: index of the associate hdu in the hdulist for this cutout """ self.reading.pix_coord = self.get_observation_coordinates(new_pixel_location[0], new_pixel_location[1], hdu_index) new_ccd = self.get_ccdnum(hdu_index) if new_ccd != self.reading.get_ccd_num(): self._apcor = None self._zmag = None self.reading.obs.ccdnum = self.get_ccdnum(hdu_index) self.reading.sky_coord = self.pix2world(new_pixel_location[0], new_pixel_location[1], hdu_index)
[ "def", "update_pixel_location", "(", "self", ",", "new_pixel_location", ",", "hdu_index", ")", ":", "self", ".", "reading", ".", "pix_coord", "=", "self", ".", "get_observation_coordinates", "(", "new_pixel_location", "[", "0", "]", ",", "new_pixel_location", "[",...
Update the x/y location of the associated reading by using new_pixel_location and transforming from cutout reference frame to observation refrence frame. @param new_pixel_location: (x, y) location of the source in cutout pixel reference frame @param hdu_index: index of the associate hdu in the hdulist for this cutout
[ "Update", "the", "x", "/", "y", "location", "of", "the", "associated", "reading", "by", "using", "new_pixel_location", "and", "transforming", "from", "cutout", "reference", "frame", "to", "observation", "refrence", "frame", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L175-L192
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.get_pixel_coordinates
def get_pixel_coordinates(self, point, ccdnum): """ Retrieves the pixel location of a point within the current HDUList given the location in the original FITS image. This takes into account that the image may be a cutout of a larger original. Args: point: tuple(float, float) (x, y) in original. Returns: (x, y) pixel in this image. @param extno: the extno from the original Mosaic that the x/y coordinates are from. """ hdulist_index = self.get_hdulist_idx(ccdnum) if isinstance(point[0], Quantity) and isinstance(point[1], Quantity): pix_point = point[0].value, point[1].value else: pix_point = point if self.reading.inverted: pix_point = self.reading.obs.naxis1 - pix_point[0] +1 , self.reading.obs.naxis2 - pix_point[1] + 1 (x, y) = self.hdulist[hdulist_index].converter.convert(pix_point) return x, y, hdulist_index
python
def get_pixel_coordinates(self, point, ccdnum): """ Retrieves the pixel location of a point within the current HDUList given the location in the original FITS image. This takes into account that the image may be a cutout of a larger original. Args: point: tuple(float, float) (x, y) in original. Returns: (x, y) pixel in this image. @param extno: the extno from the original Mosaic that the x/y coordinates are from. """ hdulist_index = self.get_hdulist_idx(ccdnum) if isinstance(point[0], Quantity) and isinstance(point[1], Quantity): pix_point = point[0].value, point[1].value else: pix_point = point if self.reading.inverted: pix_point = self.reading.obs.naxis1 - pix_point[0] +1 , self.reading.obs.naxis2 - pix_point[1] + 1 (x, y) = self.hdulist[hdulist_index].converter.convert(pix_point) return x, y, hdulist_index
[ "def", "get_pixel_coordinates", "(", "self", ",", "point", ",", "ccdnum", ")", ":", "hdulist_index", "=", "self", ".", "get_hdulist_idx", "(", "ccdnum", ")", "if", "isinstance", "(", "point", "[", "0", "]", ",", "Quantity", ")", "and", "isinstance", "(", ...
Retrieves the pixel location of a point within the current HDUList given the location in the original FITS image. This takes into account that the image may be a cutout of a larger original. Args: point: tuple(float, float) (x, y) in original. Returns: (x, y) pixel in this image. @param extno: the extno from the original Mosaic that the x/y coordinates are from.
[ "Retrieves", "the", "pixel", "location", "of", "a", "point", "within", "the", "current", "HDUList", "given", "the", "location", "in", "the", "original", "FITS", "image", ".", "This", "takes", "into", "account", "that", "the", "image", "may", "be", "a", "cu...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L209-L232
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.get_observation_coordinates
def get_observation_coordinates(self, x, y, hdulist_index): """ Retrieves the location of a point using the coordinate system of the original observation, i.e. the original image before any cutouts were done. Returns: (x, y) in the original image coordinate system. @param x: x-pixel location in the cutout frame of reference @param y: y-pixel location in the cutout frame of reference @param idx: index of hdu in hdulist that the given x/y corresponds to. """ return self.hdulist[hdulist_index].converter.get_inverse_converter().convert((x, y))
python
def get_observation_coordinates(self, x, y, hdulist_index): """ Retrieves the location of a point using the coordinate system of the original observation, i.e. the original image before any cutouts were done. Returns: (x, y) in the original image coordinate system. @param x: x-pixel location in the cutout frame of reference @param y: y-pixel location in the cutout frame of reference @param idx: index of hdu in hdulist that the given x/y corresponds to. """ return self.hdulist[hdulist_index].converter.get_inverse_converter().convert((x, y))
[ "def", "get_observation_coordinates", "(", "self", ",", "x", ",", "y", ",", "hdulist_index", ")", ":", "return", "self", ".", "hdulist", "[", "hdulist_index", "]", ".", "converter", ".", "get_inverse_converter", "(", ")", ".", "convert", "(", "(", "x", ","...
Retrieves the location of a point using the coordinate system of the original observation, i.e. the original image before any cutouts were done. Returns: (x, y) in the original image coordinate system. @param x: x-pixel location in the cutout frame of reference @param y: y-pixel location in the cutout frame of reference @param idx: index of hdu in hdulist that the given x/y corresponds to.
[ "Retrieves", "the", "location", "of", "a", "point", "using", "the", "coordinate", "system", "of", "the", "original", "observation", "i", ".", "e", ".", "the", "original", "image", "before", "any", "cutouts", "were", "done", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L234-L246
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.world2pix
def world2pix(self, ra, dec, usepv=True): """ Convert a given RA/DEC position to the X/Y/HDULIST_INDEX in the cutout frame. Here we loop over the hdulist to find the extension is RA/DEC are from and then return the appropriate X/Y :param ra: The Right Ascension of the point :type ra: Quantity :param dec: The Declination of the point :type dec: Quantity :return: X, Y, Extension position of source in cutout reference frame :rtype: (float, float, int) @param usepv: Should the non-linear part of the WCS be using to compute the transformation? (default: True) """ x, y, idx = (0, 0, 0) for idx in range(1, len(self.hdulist)): hdu = self.hdulist[idx] x, y = hdu.wcs.sky2xy(ra, dec, usepv=usepv) if 0 < x < hdu.header['NAXIS1'] and 0 < y < hdu.header['NAXIS2']: # print "Inside the frame." return x, y, idx return x, y, idx
python
def world2pix(self, ra, dec, usepv=True): """ Convert a given RA/DEC position to the X/Y/HDULIST_INDEX in the cutout frame. Here we loop over the hdulist to find the extension is RA/DEC are from and then return the appropriate X/Y :param ra: The Right Ascension of the point :type ra: Quantity :param dec: The Declination of the point :type dec: Quantity :return: X, Y, Extension position of source in cutout reference frame :rtype: (float, float, int) @param usepv: Should the non-linear part of the WCS be using to compute the transformation? (default: True) """ x, y, idx = (0, 0, 0) for idx in range(1, len(self.hdulist)): hdu = self.hdulist[idx] x, y = hdu.wcs.sky2xy(ra, dec, usepv=usepv) if 0 < x < hdu.header['NAXIS1'] and 0 < y < hdu.header['NAXIS2']: # print "Inside the frame." return x, y, idx return x, y, idx
[ "def", "world2pix", "(", "self", ",", "ra", ",", "dec", ",", "usepv", "=", "True", ")", ":", "x", ",", "y", ",", "idx", "=", "(", "0", ",", "0", ",", "0", ")", "for", "idx", "in", "range", "(", "1", ",", "len", "(", "self", ".", "hdulist", ...
Convert a given RA/DEC position to the X/Y/HDULIST_INDEX in the cutout frame. Here we loop over the hdulist to find the extension is RA/DEC are from and then return the appropriate X/Y :param ra: The Right Ascension of the point :type ra: Quantity :param dec: The Declination of the point :type dec: Quantity :return: X, Y, Extension position of source in cutout reference frame :rtype: (float, float, int) @param usepv: Should the non-linear part of the WCS be using to compute the transformation? (default: True)
[ "Convert", "a", "given", "RA", "/", "DEC", "position", "to", "the", "X", "/", "Y", "/", "HDULIST_INDEX", "in", "the", "cutout", "frame", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L252-L272
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.zmag
def zmag(self,): """ Return the photometric zeropoint of the CCD associated with the reading. @return: float """ if self._zmag is None: hdulist_index = self.get_hdulist_idx(self.reading.get_ccd_num()) self._zmag = self.hdulist[hdulist_index].header.get('PHOTZP', 0.0) return self._zmag
python
def zmag(self,): """ Return the photometric zeropoint of the CCD associated with the reading. @return: float """ if self._zmag is None: hdulist_index = self.get_hdulist_idx(self.reading.get_ccd_num()) self._zmag = self.hdulist[hdulist_index].header.get('PHOTZP', 0.0) return self._zmag
[ "def", "zmag", "(", "self", ",", ")", ":", "if", "self", ".", "_zmag", "is", "None", ":", "hdulist_index", "=", "self", ".", "get_hdulist_idx", "(", "self", ".", "reading", ".", "get_ccd_num", "(", ")", ")", "self", ".", "_zmag", "=", "self", ".", ...
Return the photometric zeropoint of the CCD associated with the reading. @return: float
[ "Return", "the", "photometric", "zeropoint", "of", "the", "CCD", "associated", "with", "the", "reading", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L275-L283
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.apcor
def apcor(self): """ return the aperture correction of for the CCD assocated with the reading. @return: Apcor """ if self._apcor is None: try: self._apcor = Downloader().download_apcor(self.reading.get_apcor_uri()) except: self._apcor = ApcorData.from_string("5 15 99.99 99.99") return self._apcor
python
def apcor(self): """ return the aperture correction of for the CCD assocated with the reading. @return: Apcor """ if self._apcor is None: try: self._apcor = Downloader().download_apcor(self.reading.get_apcor_uri()) except: self._apcor = ApcorData.from_string("5 15 99.99 99.99") return self._apcor
[ "def", "apcor", "(", "self", ")", ":", "if", "self", ".", "_apcor", "is", "None", ":", "try", ":", "self", ".", "_apcor", "=", "Downloader", "(", ")", ".", "download_apcor", "(", "self", ".", "reading", ".", "get_apcor_uri", "(", ")", ")", "except", ...
return the aperture correction of for the CCD assocated with the reading. @return: Apcor
[ "return", "the", "aperture", "correction", "of", "for", "the", "CCD", "assocated", "with", "the", "reading", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L286-L296
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.get_observed_magnitude
def get_observed_magnitude(self, centroid=True): # NOTE: this import is only here so that we don't load up IRAF # unnecessarily (ex: for candidates processing). """ Get the magnitude at the current pixel x/y location. :return: Table """ max_count = float(self.astrom_header.get("MAXCOUNT", 30000)) (x, y, hdulist_index) = self.pixel_coord tmp_file = self._hdu_on_disk(hdulist_index) try: from ossos import daophot phot = daophot.phot_mag(tmp_file, x, y, aperture=self.apcor.aperture, sky=self.apcor.sky, swidth=self.apcor.swidth, apcor=self.apcor.apcor, zmag=self.zmag, maxcount=max_count, extno=1, centroid=centroid) if not self.apcor.valid: phot['PIER'][0] = 1 return phot except Exception as ex: print ex raise ex finally: self.close()
python
def get_observed_magnitude(self, centroid=True): # NOTE: this import is only here so that we don't load up IRAF # unnecessarily (ex: for candidates processing). """ Get the magnitude at the current pixel x/y location. :return: Table """ max_count = float(self.astrom_header.get("MAXCOUNT", 30000)) (x, y, hdulist_index) = self.pixel_coord tmp_file = self._hdu_on_disk(hdulist_index) try: from ossos import daophot phot = daophot.phot_mag(tmp_file, x, y, aperture=self.apcor.aperture, sky=self.apcor.sky, swidth=self.apcor.swidth, apcor=self.apcor.apcor, zmag=self.zmag, maxcount=max_count, extno=1, centroid=centroid) if not self.apcor.valid: phot['PIER'][0] = 1 return phot except Exception as ex: print ex raise ex finally: self.close()
[ "def", "get_observed_magnitude", "(", "self", ",", "centroid", "=", "True", ")", ":", "# NOTE: this import is only here so that we don't load up IRAF", "# unnecessarily (ex: for candidates processing).", "max_count", "=", "float", "(", "self", ".", "astrom_header", ".", "get"...
Get the magnitude at the current pixel x/y location. :return: Table
[ "Get", "the", "magnitude", "at", "the", "current", "pixel", "x", "/", "y", "location", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L298-L328
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout._hdu_on_disk
def _hdu_on_disk(self, hdulist_index): """ IRAF routines such as daophot need input on disk. Returns: filename: str The name of the file containing the FITS data. """ if self._tempfile is None: self._tempfile = tempfile.NamedTemporaryFile( mode="r+b", suffix=".fits") self.hdulist[hdulist_index].writeto(self._tempfile.name) return self._tempfile.name
python
def _hdu_on_disk(self, hdulist_index): """ IRAF routines such as daophot need input on disk. Returns: filename: str The name of the file containing the FITS data. """ if self._tempfile is None: self._tempfile = tempfile.NamedTemporaryFile( mode="r+b", suffix=".fits") self.hdulist[hdulist_index].writeto(self._tempfile.name) return self._tempfile.name
[ "def", "_hdu_on_disk", "(", "self", ",", "hdulist_index", ")", ":", "if", "self", ".", "_tempfile", "is", "None", ":", "self", ".", "_tempfile", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "\"r+b\"", ",", "suffix", "=", "\".fits\"", ")", ...
IRAF routines such as daophot need input on disk. Returns: filename: str The name of the file containing the FITS data.
[ "IRAF", "routines", "such", "as", "daophot", "need", "input", "on", "disk", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L330-L342
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.comparison_image_list
def comparison_image_list(self): """ returns a list of possible comparison images for the current cutout. Will query CADC to create the list when first called. @rtype: Table """ if self._comparison_image_list is not None: return self._comparison_image_list ref_ra = self.reading.ra * units.degree ref_dec = self.reading.dec * units.degree radius = self.radius is not None and self.radius or config.read('CUTOUTS.SINGLETS.RADIUS') * units.arcminute print("Querying CADC for list of possible comparison images at RA: {}, DEC: {}, raidus: {}".format(ref_ra, ref_dec, radius)) query_result = storage.cone_search(ref_ra, ref_dec, radius, radius) # returns an astropy.table.table.Table print("Got {} possible images".format(len(query_result))) ans = raw_input("Do you want to lookup IQ? (y/n)") print("Building table for presentation and selection") if ans == "y": print("Including getting fwhm which is a bit slow.") comparison_image_list = [] if len(query_result['collectionID']) > 0: # are there any comparison images even available on that sky? index = -1 for row in query_result: expnum = row['collectionID'] if expnum in self._bad_comparison_images: continue date = Time(row['mjdate'], format='mjd').mpc if Time(row['mjdate'], format='mjd') < Time('2013-01-01 00:00:00', format='iso'): continue exptime = row['exptime'] if float(exptime) < 250: continue filter_name = row['filter'] if 'U' in filter_name: continue if filter_name.lower() in self.hdulist[-1].header['FILTER'].lower(): filter_name = "* {:8s}".format(filter_name) fwhm = -1.0 if ans == 'y': try: fwhm = "{:5.2f}".format(float(storage.get_fwhm_tag(expnum, 22))) except: pass index += 1 comparison_image_list.append([index, expnum, date, exptime, filter_name, fwhm, None]) self._comparison_image_list = Table(data=numpy.array(comparison_image_list), names=["ID", "EXPNUM", "DATE-OBS", "EXPTIME", "FILTER", "FWHM", "REFERENCE"]) return self._comparison_image_list
python
def comparison_image_list(self): """ returns a list of possible comparison images for the current cutout. Will query CADC to create the list when first called. @rtype: Table """ if self._comparison_image_list is not None: return self._comparison_image_list ref_ra = self.reading.ra * units.degree ref_dec = self.reading.dec * units.degree radius = self.radius is not None and self.radius or config.read('CUTOUTS.SINGLETS.RADIUS') * units.arcminute print("Querying CADC for list of possible comparison images at RA: {}, DEC: {}, raidus: {}".format(ref_ra, ref_dec, radius)) query_result = storage.cone_search(ref_ra, ref_dec, radius, radius) # returns an astropy.table.table.Table print("Got {} possible images".format(len(query_result))) ans = raw_input("Do you want to lookup IQ? (y/n)") print("Building table for presentation and selection") if ans == "y": print("Including getting fwhm which is a bit slow.") comparison_image_list = [] if len(query_result['collectionID']) > 0: # are there any comparison images even available on that sky? index = -1 for row in query_result: expnum = row['collectionID'] if expnum in self._bad_comparison_images: continue date = Time(row['mjdate'], format='mjd').mpc if Time(row['mjdate'], format='mjd') < Time('2013-01-01 00:00:00', format='iso'): continue exptime = row['exptime'] if float(exptime) < 250: continue filter_name = row['filter'] if 'U' in filter_name: continue if filter_name.lower() in self.hdulist[-1].header['FILTER'].lower(): filter_name = "* {:8s}".format(filter_name) fwhm = -1.0 if ans == 'y': try: fwhm = "{:5.2f}".format(float(storage.get_fwhm_tag(expnum, 22))) except: pass index += 1 comparison_image_list.append([index, expnum, date, exptime, filter_name, fwhm, None]) self._comparison_image_list = Table(data=numpy.array(comparison_image_list), names=["ID", "EXPNUM", "DATE-OBS", "EXPTIME", "FILTER", "FWHM", "REFERENCE"]) return self._comparison_image_list
[ "def", "comparison_image_list", "(", "self", ")", ":", "if", "self", ".", "_comparison_image_list", "is", "not", "None", ":", "return", "self", ".", "_comparison_image_list", "ref_ra", "=", "self", ".", "reading", ".", "ra", "*", "units", ".", "degree", "ref...
returns a list of possible comparison images for the current cutout. Will query CADC to create the list when first called. @rtype: Table
[ "returns", "a", "list", "of", "possible", "comparison", "images", "for", "the", "current", "cutout", ".", "Will", "query", "CADC", "to", "create", "the", "list", "when", "first", "called", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L372-L422
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/source.py
SourceCutout.retrieve_comparison_image
def retrieve_comparison_image(self): """ Search the DB for a comparison image for this cutout. """ # selecting comparator when on a comparator should load a new one. collectionID = self.comparison_image_list[self.comparison_image_index]['EXPNUM'] ref_ra = self.reading.ra * units.degree ref_dec = self.reading.dec * units.degree radius = self.radius is not None and self.radius or config.read('CUTOUTS.SINGLETS.RADIUS') * units.arcminute try: comparison = collectionID hdu_list = storage.ra_dec_cutout(storage.dbimages_uri(comparison), SkyCoord(ref_ra, ref_dec), radius) ccd = int(hdu_list[-1].header.get('EXTVER', 0)) obs = Observation(str(comparison), 'p', ccdnum=ccd) x = hdu_list[-1].header.get('NAXIS1', 0) // 2.0 y = hdu_list[-1].header.get('NAXIS2', 0) // 2.0 ref_ra = self.reading.ra * units.degree ref_dec = self.reading.dec * units.degree reading = SourceReading(x, y, self.reading.x, self.reading.y, ref_ra, ref_dec, self.reading.x, self.reading.y, obs) self.comparison_image_list[self.comparison_image_index]["REFERENCE"] = SourceCutout(reading, hdu_list) except Exception as ex: print traceback.format_exc() print ex print "Failed to load comparison image;" self.comparison_image_index = None logger.error("{} {}".format(type(ex), str(ex))) logger.error(traceback.format_exc())
python
def retrieve_comparison_image(self): """ Search the DB for a comparison image for this cutout. """ # selecting comparator when on a comparator should load a new one. collectionID = self.comparison_image_list[self.comparison_image_index]['EXPNUM'] ref_ra = self.reading.ra * units.degree ref_dec = self.reading.dec * units.degree radius = self.radius is not None and self.radius or config.read('CUTOUTS.SINGLETS.RADIUS') * units.arcminute try: comparison = collectionID hdu_list = storage.ra_dec_cutout(storage.dbimages_uri(comparison), SkyCoord(ref_ra, ref_dec), radius) ccd = int(hdu_list[-1].header.get('EXTVER', 0)) obs = Observation(str(comparison), 'p', ccdnum=ccd) x = hdu_list[-1].header.get('NAXIS1', 0) // 2.0 y = hdu_list[-1].header.get('NAXIS2', 0) // 2.0 ref_ra = self.reading.ra * units.degree ref_dec = self.reading.dec * units.degree reading = SourceReading(x, y, self.reading.x, self.reading.y, ref_ra, ref_dec, self.reading.x, self.reading.y, obs) self.comparison_image_list[self.comparison_image_index]["REFERENCE"] = SourceCutout(reading, hdu_list) except Exception as ex: print traceback.format_exc() print ex print "Failed to load comparison image;" self.comparison_image_index = None logger.error("{} {}".format(type(ex), str(ex))) logger.error(traceback.format_exc())
[ "def", "retrieve_comparison_image", "(", "self", ")", ":", "# selecting comparator when on a comparator should load a new one.", "collectionID", "=", "self", ".", "comparison_image_list", "[", "self", ".", "comparison_image_index", "]", "[", "'EXPNUM'", "]", "ref_ra", "=", ...
Search the DB for a comparison image for this cutout.
[ "Search", "the", "DB", "for", "a", "comparison", "image", "for", "this", "cutout", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L425-L454
OSSOS/MOP
src/ossos/web/web/auth/model.py
User.check_password
def check_password(self, passwd, group): # This provides authentication via CADC. """check that the passwd provided matches the required password.""" return gms.isMember(self.login, passwd, group)
python
def check_password(self, passwd, group): # This provides authentication via CADC. """check that the passwd provided matches the required password.""" return gms.isMember(self.login, passwd, group)
[ "def", "check_password", "(", "self", ",", "passwd", ",", "group", ")", ":", "# This provides authentication via CADC.", "return", "gms", ".", "isMember", "(", "self", ".", "login", ",", "passwd", ",", "group", ")" ]
check that the passwd provided matches the required password.
[ "check", "that", "the", "passwd", "provided", "matches", "the", "required", "password", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/web/web/auth/model.py#L22-L25
JohnVinyard/zounds
zounds/timeseries/timeseries.py
TimeDimension.integer_based_slice
def integer_based_slice(self, ts): """ Transform a :class:`TimeSlice` into integer indices that numpy can work with Args: ts (slice, TimeSlice): the time slice to translate into integer indices """ if isinstance(ts, slice): try: start = Seconds(0) if ts.start is None else ts.start if start < Seconds(0): start = self.end + start stop = self.end if ts.stop is None else ts.stop if stop < Seconds(0): stop = self.end + stop duration = stop - start ts = TimeSlice(start=start, duration=duration) except (ValueError, TypeError): pass if not isinstance(ts, TimeSlice): return ts diff = self.duration - self.frequency start_index = \ max(0, np.floor((ts.start - diff) / self.frequency)) end = self.end if ts.duration is None else ts.end # KLUDGE: This is basically arbitrary, but the motivation is that we'd # like to differentiate between cases where the slice # actually/intentionally overlaps a particular sample, and cases where # the slice overlaps the sample by a tiny amount, due to rounding or # lack of precision (e.g. Seconds(1) / SR44100().frequency). ratio = np.round(end / self.frequency, 2) stop_index = np.ceil(ratio) return slice(int(start_index), int(stop_index))
python
def integer_based_slice(self, ts): """ Transform a :class:`TimeSlice` into integer indices that numpy can work with Args: ts (slice, TimeSlice): the time slice to translate into integer indices """ if isinstance(ts, slice): try: start = Seconds(0) if ts.start is None else ts.start if start < Seconds(0): start = self.end + start stop = self.end if ts.stop is None else ts.stop if stop < Seconds(0): stop = self.end + stop duration = stop - start ts = TimeSlice(start=start, duration=duration) except (ValueError, TypeError): pass if not isinstance(ts, TimeSlice): return ts diff = self.duration - self.frequency start_index = \ max(0, np.floor((ts.start - diff) / self.frequency)) end = self.end if ts.duration is None else ts.end # KLUDGE: This is basically arbitrary, but the motivation is that we'd # like to differentiate between cases where the slice # actually/intentionally overlaps a particular sample, and cases where # the slice overlaps the sample by a tiny amount, due to rounding or # lack of precision (e.g. Seconds(1) / SR44100().frequency). ratio = np.round(end / self.frequency, 2) stop_index = np.ceil(ratio) return slice(int(start_index), int(stop_index))
[ "def", "integer_based_slice", "(", "self", ",", "ts", ")", ":", "if", "isinstance", "(", "ts", ",", "slice", ")", ":", "try", ":", "start", "=", "Seconds", "(", "0", ")", "if", "ts", ".", "start", "is", "None", "else", "ts", ".", "start", "if", "...
Transform a :class:`TimeSlice` into integer indices that numpy can work with Args: ts (slice, TimeSlice): the time slice to translate into integer indices
[ "Transform", "a", ":", "class", ":", "TimeSlice", "into", "integer", "indices", "that", "numpy", "can", "work", "with" ]
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/timeseries/timeseries.py#L234-L275
OSSOS/MOP
src/ossos/core/ossos/pipeline/build_astrometry_report.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. @param path: the directory where filenames are. @type path str @param filenames: list of files in path. @type filenames list @rtype None """ for filename in filenames: if re.search(regex, filename) is None: logging.error("Skipping {}".format(filename)) continue obs = mpc.MPCReader().read(os.path.join(path, filename)) for ob in obs: if "568" not in ob.observatory_code: continue if not isinstance(ob.comment, mpc.OSSOSComment): continue if ob.date < Time("2013-01-01 00:00:00"): continue if rename: new_provisional_name = os.path.basename(filename) new_provisional_name = new_provisional_name[0:new_provisional_name.find(".")] rename_map[ob.provisional_name] = new_provisional_name try: key1 = ob.comment.frame.split('p')[0] except Exception as ex: logger.warning(str(ex)) logger.warning(ob.to_string()) continue 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(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. @param path: the directory where filenames are. @type path str @param filenames: list of files in path. @type filenames list @rtype None """ for filename in filenames: if re.search(regex, filename) is None: logging.error("Skipping {}".format(filename)) continue obs = mpc.MPCReader().read(os.path.join(path, filename)) for ob in obs: if "568" not in ob.observatory_code: continue if not isinstance(ob.comment, mpc.OSSOSComment): continue if ob.date < Time("2013-01-01 00:00:00"): continue if rename: new_provisional_name = os.path.basename(filename) new_provisional_name = new_provisional_name[0:new_provisional_name.find(".")] rename_map[ob.provisional_name] = new_provisional_name try: key1 = ob.comment.frame.split('p')[0] except Exception as ex: logger.warning(str(ex)) logger.warning(ob.to_string()) continue 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(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. @param path: the directory where filenames are. @type path str @param filenames: list of files in path. @type filenames list @rtype None
[ "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/core/ossos/pipeline/build_astrometry_report.py#L18-L62
OSSOS/MOP
src/ossos/core/scripts/plant.py
plant_kbos
def plant_kbos(filename, psf, kbos, shifts, prefix): """ Add KBOs to an image :param filename: name of the image to add KBOs to :param psf: the Point Spread Function in IRAF/DAOPHOT format to be used by ADDSTAR :param kbos: list of KBOs to add, has format as returned by KBOGenerator :param shifts: dictionary with shifts to transfer to coordinates to reference frame. :param prefix: an estimate FWHM of the image, used to determine trailing. :return: None """ iraf.set(uparm="./") iraf.digiphot() iraf.apphot() iraf.daophot(_doprint=0) iraf.images() if shifts['nmag'] < 4: logging.warning("Mag shift based on fewer than 4 common stars.") fd = open("plant.WARNING", 'a') fd.write("Mag shift based on fewer than 4 common stars.") fd.close() if shifts['emag'] > 0.05: logging.warning("Mag shift has large uncertainty.") fd = open("plant.WARNING", 'a') fd.write("Mag shift hsa large uncertainty.") fd.close() addstar = tempfile.NamedTemporaryFile(suffix=".add") # transform KBO locations to this frame using the shifts provided. w = get_wcs(shifts) header = fits.open(filename)[0].header # set the rate of motion in units of pixels/hour instead of ''/hour scale = header['PIXSCAL1'] rate = kbos['sky_rate']/scale # compute the location of the KBOs in the current frame. # offset magnitudes from the reference frame to the current one. mag = kbos['mag'] - shifts['dmag'] angle = radians(kbos['angle']) # Move the x/y locations to account for the sky motion of the source. x = kbos['x'] - rate*24.0*shifts['dmjd']*cos(angle) y = kbos['y'] - rate*24.0*shifts['dmjd']*sin(angle) x, y = w.wcs_world2pix(x, y, 1) # Each source will be added as a series of PSFs so that a new PSF is added for each pixel the source moves. itime = float(header['EXPTIME'])/3600.0 npsf = fabs(rint(rate * itime)) + 1 mag += 2.5*log10(npsf) dt_per_psf = itime/npsf # Build an addstar file to be used in the planting of source. idx = 0 for record in transpose([x, y, mag, npsf, dt_per_psf, rate, angle]): x = record[0] y = record[1] mag = record[2] npsf = record[3] dt = record[4] rate = record[5] angle = record[6] for i in range(int(npsf)): idx += 1 x += dt*rate*math.cos(angle) y += dt*rate*math.sin(angle) addstar.write("{} {} {} {}\n".format(x, y, mag, idx)) addstar.flush() fk_image = prefix+filename try: os.unlink(fk_image) except OSError as err: if err.errno == errno.ENOENT: pass else: raise # add the sources to the image. iraf.daophot.addstar(filename, addstar.name, psf, fk_image, simple=True, verify=False, verbose=False) # convert the image to short integers. iraf.images.chpix(fk_image, fk_image, 'ushort')
python
def plant_kbos(filename, psf, kbos, shifts, prefix): """ Add KBOs to an image :param filename: name of the image to add KBOs to :param psf: the Point Spread Function in IRAF/DAOPHOT format to be used by ADDSTAR :param kbos: list of KBOs to add, has format as returned by KBOGenerator :param shifts: dictionary with shifts to transfer to coordinates to reference frame. :param prefix: an estimate FWHM of the image, used to determine trailing. :return: None """ iraf.set(uparm="./") iraf.digiphot() iraf.apphot() iraf.daophot(_doprint=0) iraf.images() if shifts['nmag'] < 4: logging.warning("Mag shift based on fewer than 4 common stars.") fd = open("plant.WARNING", 'a') fd.write("Mag shift based on fewer than 4 common stars.") fd.close() if shifts['emag'] > 0.05: logging.warning("Mag shift has large uncertainty.") fd = open("plant.WARNING", 'a') fd.write("Mag shift hsa large uncertainty.") fd.close() addstar = tempfile.NamedTemporaryFile(suffix=".add") # transform KBO locations to this frame using the shifts provided. w = get_wcs(shifts) header = fits.open(filename)[0].header # set the rate of motion in units of pixels/hour instead of ''/hour scale = header['PIXSCAL1'] rate = kbos['sky_rate']/scale # compute the location of the KBOs in the current frame. # offset magnitudes from the reference frame to the current one. mag = kbos['mag'] - shifts['dmag'] angle = radians(kbos['angle']) # Move the x/y locations to account for the sky motion of the source. x = kbos['x'] - rate*24.0*shifts['dmjd']*cos(angle) y = kbos['y'] - rate*24.0*shifts['dmjd']*sin(angle) x, y = w.wcs_world2pix(x, y, 1) # Each source will be added as a series of PSFs so that a new PSF is added for each pixel the source moves. itime = float(header['EXPTIME'])/3600.0 npsf = fabs(rint(rate * itime)) + 1 mag += 2.5*log10(npsf) dt_per_psf = itime/npsf # Build an addstar file to be used in the planting of source. idx = 0 for record in transpose([x, y, mag, npsf, dt_per_psf, rate, angle]): x = record[0] y = record[1] mag = record[2] npsf = record[3] dt = record[4] rate = record[5] angle = record[6] for i in range(int(npsf)): idx += 1 x += dt*rate*math.cos(angle) y += dt*rate*math.sin(angle) addstar.write("{} {} {} {}\n".format(x, y, mag, idx)) addstar.flush() fk_image = prefix+filename try: os.unlink(fk_image) except OSError as err: if err.errno == errno.ENOENT: pass else: raise # add the sources to the image. iraf.daophot.addstar(filename, addstar.name, psf, fk_image, simple=True, verify=False, verbose=False) # convert the image to short integers. iraf.images.chpix(fk_image, fk_image, 'ushort')
[ "def", "plant_kbos", "(", "filename", ",", "psf", ",", "kbos", ",", "shifts", ",", "prefix", ")", ":", "iraf", ".", "set", "(", "uparm", "=", "\"./\"", ")", "iraf", ".", "digiphot", "(", ")", "iraf", ".", "apphot", "(", ")", "iraf", ".", "daophot",...
Add KBOs to an image :param filename: name of the image to add KBOs to :param psf: the Point Spread Function in IRAF/DAOPHOT format to be used by ADDSTAR :param kbos: list of KBOs to add, has format as returned by KBOGenerator :param shifts: dictionary with shifts to transfer to coordinates to reference frame. :param prefix: an estimate FWHM of the image, used to determine trailing. :return: None
[ "Add", "KBOs", "to", "an", "image", ":", "param", "filename", ":", "name", "of", "the", "image", "to", "add", "KBOs", "to", ":", "param", "psf", ":", "the", "Point", "Spread", "Function", "in", "IRAF", "/", "DAOPHOT", "format", "to", "be", "used", "b...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/scripts/plant.py#L45-L132
OSSOS/MOP
src/ossos/core/scripts/plant.py
plant
def plant(expnums, ccd, rmin, rmax, ang, width, number=10, mmin=21.0, mmax=25.5, version='s', dry_run=False): """Plant artificial sources into the list of images provided. :param expnums: list of MegaPrime exposure numbers to add artificial KBOs to :param ccd: which ccd to work on. :param rmin: The minimum rate of motion to add sources at (''/hour) :param rmax: The maximum rate of motion to add sources at (''/hour) :param ang: The mean angle of motion to add sources :param width: The +/- range of angles of motion :param version: Add sources to the 'o', 'p' or 's' images :param dry_run: don't push results to VOSpace. """ # Construct a list of artificial KBOs with positions in the image # and rates of motion within the bounds given by the caller. filename = storage.get_image(expnums[0], ccd=ccd, version=version) header = fits.open(filename)[0].header bounds = util.get_pixel_bounds_from_datasec_keyword(header.get('DATASEC', '[33:2080,1:4612]')) # generate a set of artificial KBOs to add to the image. kbos = KBOGenerator.get_kbos(n=number, rate=(rmin, rmax), angle=(ang - width, ang + width), mag=(mmin, mmax), x=(bounds[0][0], bounds[0][1]), y=(bounds[1][0], bounds[1][1]), filename='Object.planted') for expnum in expnums: filename = storage.get_image(expnum, ccd, version) psf = storage.get_file(expnum, ccd, version, ext='psf.fits') plant_kbos(filename, psf, kbos, get_shifts(expnum, ccd, version), "fk") if dry_run: return uri = storage.get_uri('Object', ext='planted', version='', subdir=str( expnums[0]) + "/ccd%s" % (str(ccd).zfill(2))) storage.copy('Object.planted', uri) for expnum in expnums: uri = storage.get_uri(expnum, ccd=ccd, version=version, ext='fits', prefix='fk') filename = os.path.basename(uri) storage.copy(filename, uri) return
python
def plant(expnums, ccd, rmin, rmax, ang, width, number=10, mmin=21.0, mmax=25.5, version='s', dry_run=False): """Plant artificial sources into the list of images provided. :param expnums: list of MegaPrime exposure numbers to add artificial KBOs to :param ccd: which ccd to work on. :param rmin: The minimum rate of motion to add sources at (''/hour) :param rmax: The maximum rate of motion to add sources at (''/hour) :param ang: The mean angle of motion to add sources :param width: The +/- range of angles of motion :param version: Add sources to the 'o', 'p' or 's' images :param dry_run: don't push results to VOSpace. """ # Construct a list of artificial KBOs with positions in the image # and rates of motion within the bounds given by the caller. filename = storage.get_image(expnums[0], ccd=ccd, version=version) header = fits.open(filename)[0].header bounds = util.get_pixel_bounds_from_datasec_keyword(header.get('DATASEC', '[33:2080,1:4612]')) # generate a set of artificial KBOs to add to the image. kbos = KBOGenerator.get_kbos(n=number, rate=(rmin, rmax), angle=(ang - width, ang + width), mag=(mmin, mmax), x=(bounds[0][0], bounds[0][1]), y=(bounds[1][0], bounds[1][1]), filename='Object.planted') for expnum in expnums: filename = storage.get_image(expnum, ccd, version) psf = storage.get_file(expnum, ccd, version, ext='psf.fits') plant_kbos(filename, psf, kbos, get_shifts(expnum, ccd, version), "fk") if dry_run: return uri = storage.get_uri('Object', ext='planted', version='', subdir=str( expnums[0]) + "/ccd%s" % (str(ccd).zfill(2))) storage.copy('Object.planted', uri) for expnum in expnums: uri = storage.get_uri(expnum, ccd=ccd, version=version, ext='fits', prefix='fk') filename = os.path.basename(uri) storage.copy(filename, uri) return
[ "def", "plant", "(", "expnums", ",", "ccd", ",", "rmin", ",", "rmax", ",", "ang", ",", "width", ",", "number", "=", "10", ",", "mmin", "=", "21.0", ",", "mmax", "=", "25.5", ",", "version", "=", "'s'", ",", "dry_run", "=", "False", ")", ":", "#...
Plant artificial sources into the list of images provided. :param expnums: list of MegaPrime exposure numbers to add artificial KBOs to :param ccd: which ccd to work on. :param rmin: The minimum rate of motion to add sources at (''/hour) :param rmax: The maximum rate of motion to add sources at (''/hour) :param ang: The mean angle of motion to add sources :param width: The +/- range of angles of motion :param version: Add sources to the 'o', 'p' or 's' images :param dry_run: don't push results to VOSpace.
[ "Plant", "artificial", "sources", "into", "the", "list", "of", "images", "provided", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/scripts/plant.py#L141-L192
OSSOS/MOP
src/ossos/core/ossos/kbo.py
Orbfit._fit_radec
def _fit_radec(self): """ call fit_radec of BK passing in the observations. """ # call fitradec with mpcfile, abgfile, resfile self.orbfit.fitradec.restype = ctypes.c_int self.orbfit.fitradec.argtypes = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p ] mpc_file = tempfile.NamedTemporaryFile(suffix='.mpc') for observation in self.observations: mpc_file.write("{}\n".format(str(observation))) mpc_file.seek(0) abg_file = tempfile.NamedTemporaryFile() res_file = tempfile.NamedTemporaryFile() self.orbfit.fitradec(ctypes.c_char_p(mpc_file.name), ctypes.c_char_p(abg_file.name), ctypes.c_char_p(res_file.name)) self.abg = abg_file self.abg.seek(0) self.residuals = res_file self.residuals.seek(0)
python
def _fit_radec(self): """ call fit_radec of BK passing in the observations. """ # call fitradec with mpcfile, abgfile, resfile self.orbfit.fitradec.restype = ctypes.c_int self.orbfit.fitradec.argtypes = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p ] mpc_file = tempfile.NamedTemporaryFile(suffix='.mpc') for observation in self.observations: mpc_file.write("{}\n".format(str(observation))) mpc_file.seek(0) abg_file = tempfile.NamedTemporaryFile() res_file = tempfile.NamedTemporaryFile() self.orbfit.fitradec(ctypes.c_char_p(mpc_file.name), ctypes.c_char_p(abg_file.name), ctypes.c_char_p(res_file.name)) self.abg = abg_file self.abg.seek(0) self.residuals = res_file self.residuals.seek(0)
[ "def", "_fit_radec", "(", "self", ")", ":", "# call fitradec with mpcfile, abgfile, resfile", "self", ".", "orbfit", ".", "fitradec", ".", "restype", "=", "ctypes", ".", "c_int", "self", ".", "orbfit", ".", "fitradec", ".", "argtypes", "=", "[", "ctypes", ".",...
call fit_radec of BK passing in the observations.
[ "call", "fit_radec", "of", "BK", "passing", "in", "the", "observations", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/kbo.py#L21-L46
OSSOS/MOP
src/ossos/core/ossos/kbo.py
Orbfit.predict
def predict(self, date, obs_code=568): """ use the bk predict method to compute the location of the source on the given date. """ time = Time(date, scale='utc', precision=6) jd = ctypes.c_double(time.jd) # call predict with agbfile, jdate, obscode self.orbfit.predict.restype = ctypes.POINTER(ctypes.c_double * 5) self.orbfit.predict.argtypes = [ ctypes.c_char_p, ctypes.c_double, ctypes.c_int ] predict = self.orbfit.predict(ctypes.c_char_p(self.abg.name), jd, ctypes.c_int(obs_code)) self.coordinate = coordinates.SkyCoord(predict.contents[0], predict.contents[1], unit=(units.degree, units.degree)) self.dra = predict.contents[2] self.ddec = predict.contents[3] self.pa = predict.contents[4] self.date = str(time)
python
def predict(self, date, obs_code=568): """ use the bk predict method to compute the location of the source on the given date. """ time = Time(date, scale='utc', precision=6) jd = ctypes.c_double(time.jd) # call predict with agbfile, jdate, obscode self.orbfit.predict.restype = ctypes.POINTER(ctypes.c_double * 5) self.orbfit.predict.argtypes = [ ctypes.c_char_p, ctypes.c_double, ctypes.c_int ] predict = self.orbfit.predict(ctypes.c_char_p(self.abg.name), jd, ctypes.c_int(obs_code)) self.coordinate = coordinates.SkyCoord(predict.contents[0], predict.contents[1], unit=(units.degree, units.degree)) self.dra = predict.contents[2] self.ddec = predict.contents[3] self.pa = predict.contents[4] self.date = str(time)
[ "def", "predict", "(", "self", ",", "date", ",", "obs_code", "=", "568", ")", ":", "time", "=", "Time", "(", "date", ",", "scale", "=", "'utc'", ",", "precision", "=", "6", ")", "jd", "=", "ctypes", ".", "c_double", "(", "time", ".", "jd", ")", ...
use the bk predict method to compute the location of the source on the given date.
[ "use", "the", "bk", "predict", "method", "to", "compute", "the", "location", "of", "the", "source", "on", "the", "given", "date", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/kbo.py#L48-L66
OSSOS/MOP
src/ossos/core/ossos/gui/views/appview.py
guithread
def guithread(function): """ Decorator to make sure the function is called from wx's main GUI thread. This is needed when trying to trigger UI updates from a thread other than the main GUI thread (such as some asynchronous data loading thread). I learned about doing this from: wxPython 2.8 Application Development Cookbook, Chapter 11 """ def new_guithread_function(*args, **kwargs): if wx.Thread_IsMain(): return function(*args, **kwargs) else: wx.CallAfter(function, *args, **kwargs) return new_guithread_function
python
def guithread(function): """ Decorator to make sure the function is called from wx's main GUI thread. This is needed when trying to trigger UI updates from a thread other than the main GUI thread (such as some asynchronous data loading thread). I learned about doing this from: wxPython 2.8 Application Development Cookbook, Chapter 11 """ def new_guithread_function(*args, **kwargs): if wx.Thread_IsMain(): return function(*args, **kwargs) else: wx.CallAfter(function, *args, **kwargs) return new_guithread_function
[ "def", "guithread", "(", "function", ")", ":", "def", "new_guithread_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "wx", ".", "Thread_IsMain", "(", ")", ":", "return", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")"...
Decorator to make sure the function is called from wx's main GUI thread. This is needed when trying to trigger UI updates from a thread other than the main GUI thread (such as some asynchronous data loading thread). I learned about doing this from: wxPython 2.8 Application Development Cookbook, Chapter 11
[ "Decorator", "to", "make", "sure", "the", "function", "is", "called", "from", "wx", "s", "main", "GUI", "thread", ".", "This", "is", "needed", "when", "trying", "to", "trigger", "UI", "updates", "from", "a", "thread", "other", "than", "the", "main", "GUI...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/views/appview.py#L17-L34
OSSOS/MOP
src/jjk/preproc/MOPfiles.py
write
def write(file,hdu,order=None,format=None): """Write a file in the crazy MOP format given an mop data hdu.""" if order or format: warnings.warn('Use of <order> and <format> depricated',DeprecationWarning) ## if the order of the columns isn't constrained just use the keys in what ever order data='data' if not order: if not hdu.has_key('order'): hdu['order']=hdu[data].keys() else: hdu['order']=order if not format: if not hdu.has_key('format'): hdu['format']={} for o in hdu['order']: if not hdu['format'].has_key(o): hdu['format'][o]='%10s' else: hdu['format']=format f=open(file,'w') kline='## ' vline='# ' header='header' num=0 for keyword in hdu[header]: kline+='%10s ' % (keyword, ) vline+='%10s ' % str(hdu[header][keyword]) num+=1 if not ( num % 6 ) : num=0 f.write(kline+'\n') f.write(vline+'\n') kline='## ' vline='# ' if num > 0: f.write(kline+'\n') f.write(vline+'\n') f.write('## ') for column in hdu['order']: f.write(' %10s' % (column)) f.write('\n') dlen=len(hdu[data][hdu['order'][0]]) for i in range(dlen): f.write(' ') for column in hdu['order']: f.write(hdu['format'][column] % (hdu[data][column][i])) f.write(' ') f.write('\n') f.close() return
python
def write(file,hdu,order=None,format=None): """Write a file in the crazy MOP format given an mop data hdu.""" if order or format: warnings.warn('Use of <order> and <format> depricated',DeprecationWarning) ## if the order of the columns isn't constrained just use the keys in what ever order data='data' if not order: if not hdu.has_key('order'): hdu['order']=hdu[data].keys() else: hdu['order']=order if not format: if not hdu.has_key('format'): hdu['format']={} for o in hdu['order']: if not hdu['format'].has_key(o): hdu['format'][o]='%10s' else: hdu['format']=format f=open(file,'w') kline='## ' vline='# ' header='header' num=0 for keyword in hdu[header]: kline+='%10s ' % (keyword, ) vline+='%10s ' % str(hdu[header][keyword]) num+=1 if not ( num % 6 ) : num=0 f.write(kline+'\n') f.write(vline+'\n') kline='## ' vline='# ' if num > 0: f.write(kline+'\n') f.write(vline+'\n') f.write('## ') for column in hdu['order']: f.write(' %10s' % (column)) f.write('\n') dlen=len(hdu[data][hdu['order'][0]]) for i in range(dlen): f.write(' ') for column in hdu['order']: f.write(hdu['format'][column] % (hdu[data][column][i])) f.write(' ') f.write('\n') f.close() return
[ "def", "write", "(", "file", ",", "hdu", ",", "order", "=", "None", ",", "format", "=", "None", ")", ":", "if", "order", "or", "format", ":", "warnings", ".", "warn", "(", "'Use of <order> and <format> depricated'", ",", "DeprecationWarning", ")", "## if the...
Write a file in the crazy MOP format given an mop data hdu.
[ "Write", "a", "file", "in", "the", "crazy", "MOP", "format", "given", "an", "mop", "data", "hdu", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfiles.py#L57-L112
OSSOS/MOP
src/jjk/preproc/MOPfiles.py
store
def store(hdu,dbase='cfeps',duser='cfhls',dtype='MYSQL',table='source'): """Write the contents of a MOP data structure to a SQL table""" import MOPdbaccess db=MOPdbaccess.connect(dbase,duser,dbSystem=dtype) dbc=db.cursor() ### INSERT THE 'HEADER' in the meta-data table file_id=hdu['header']['image'] for key in hdu['header'].keys(): if key == 'image': continue value=hdu['header'][key] ### require that the file_id+keyword is unique sql="DELETE FROM metadata WHERE file_id='%s' and keyword='%s' " % ( file_id, key) dbc.execute(sql) sql="INSERT INTO metadata (file_id, keyword, value) values ('%s','%s','%s' ) "% ( file_id, key, value) dbc.execute(sql) db.commit() sql="DELETE FROM source WHERE file_id LIKE '%s' " % ( file_id ) dbc.execute(sql) sql="INSERT INTO %s ( " % ( table) sep=" " values="(" cols=hdu['hdu2sql'].keys() for col in cols: sql+=sep+hdu['hdu2sql'][col] values+=sep+" %s " sep=', ' values+=", '%s', %d, %d )" % ( file_id, int(hdu['header']['EXPNUM']), int(hdu['header']['CHIP'] )-1 ) sql+=", file_id, expnum, ccd ) VALUES "+values #print sql #sys.exit() #values=[] for row in range(len(hdu['data'][cols[0]])): value=[] for col in cols: value.append(hdu['data'][col][row]) dbc.execute(sql,value) sql="""insert into source_idx ( sourceID, x, y, z ) SELECT sourceID, (360.0*COS(RADIANS(raDeg))*COS(RADIANS(decDeg))), (360.0*SIN(RADIANS(raDeg))*COS(RADIANS(decDeg))), (360.0*SIN(RADIANS(decDeg))) FROM source WHERE file_id='%s'""" % (file_id) dbc.execute(sql) db.commit() return
python
def store(hdu,dbase='cfeps',duser='cfhls',dtype='MYSQL',table='source'): """Write the contents of a MOP data structure to a SQL table""" import MOPdbaccess db=MOPdbaccess.connect(dbase,duser,dbSystem=dtype) dbc=db.cursor() ### INSERT THE 'HEADER' in the meta-data table file_id=hdu['header']['image'] for key in hdu['header'].keys(): if key == 'image': continue value=hdu['header'][key] ### require that the file_id+keyword is unique sql="DELETE FROM metadata WHERE file_id='%s' and keyword='%s' " % ( file_id, key) dbc.execute(sql) sql="INSERT INTO metadata (file_id, keyword, value) values ('%s','%s','%s' ) "% ( file_id, key, value) dbc.execute(sql) db.commit() sql="DELETE FROM source WHERE file_id LIKE '%s' " % ( file_id ) dbc.execute(sql) sql="INSERT INTO %s ( " % ( table) sep=" " values="(" cols=hdu['hdu2sql'].keys() for col in cols: sql+=sep+hdu['hdu2sql'][col] values+=sep+" %s " sep=', ' values+=", '%s', %d, %d )" % ( file_id, int(hdu['header']['EXPNUM']), int(hdu['header']['CHIP'] )-1 ) sql+=", file_id, expnum, ccd ) VALUES "+values #print sql #sys.exit() #values=[] for row in range(len(hdu['data'][cols[0]])): value=[] for col in cols: value.append(hdu['data'][col][row]) dbc.execute(sql,value) sql="""insert into source_idx ( sourceID, x, y, z ) SELECT sourceID, (360.0*COS(RADIANS(raDeg))*COS(RADIANS(decDeg))), (360.0*SIN(RADIANS(raDeg))*COS(RADIANS(decDeg))), (360.0*SIN(RADIANS(decDeg))) FROM source WHERE file_id='%s'""" % (file_id) dbc.execute(sql) db.commit() return
[ "def", "store", "(", "hdu", ",", "dbase", "=", "'cfeps'", ",", "duser", "=", "'cfhls'", ",", "dtype", "=", "'MYSQL'", ",", "table", "=", "'source'", ")", ":", "import", "MOPdbaccess", "db", "=", "MOPdbaccess", ".", "connect", "(", "dbase", ",", "duser"...
Write the contents of a MOP data structure to a SQL table
[ "Write", "the", "contents", "of", "a", "MOP", "data", "structure", "to", "a", "SQL", "table" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfiles.py#L114-L164
OSSOS/MOP
src/jjk/preproc/MOPfiles.py
read
def read(file): """Read in a file and create a data strucuture that is a hash with members 'header' and 'data'. The 'header' is a hash of header keywords, the data is a hash of columns. To get to the nth element of column NAME use hdu[data][NAME][n]. To get the header information use hdu[header][KEYWORD]. """ f = open(file,'r') lines=f.readlines() f.close() import re, string keywords=[] values=[] formats={} header={} cdata={} for line in lines: if ( re.match(r'^##',line)): ## header line m=string.split(string.lstrip(line[2:])) if not m: sys.stderr.write( "Ill formed header line in %s \ n " % ( file, )) sys.stderr.write( line) continue keywords=m add_id=False continue if ( re.match(r'^# ',line)): ## this is a keyword value line, must match the previous keyword line m=string.split(string.lstrip(line[1:])) values=m if len(values)!= len(keywords): sys.stderr.write( "Ill formed header, keyword/value missmatach\n") for index in range(len(values)): header[keywords[index]]=values[index] ## blank the arrays, we've already stuck this into the header keywords=[] values=[] continue if ( re.match(r'^#F',line)): ## this is a format line for the columns needs to be a keyword line first if not keywords: sys.stderr.write("Cann't have formats without column names...\n") continue f=string.split(string.lstrip(line)) if add_id: f.append('%8d') for col in keywords: formats[col]=f.pop(0) ### must be the actual data ### expect a previous header line to define column headers if not keywords: sys.stderr.write( "No keywords for data columns, assuming x,y,mag,msky\n") keywords=('X','Y','MAG','MSKY') values = string.split(string.lstrip(line)) ### add the id value to the values array if needed if not 'ID' in keywords: keywords.append('ID') add_id=True if not cdata: for keyword in keywords: cdata[keyword]=[] if add_id: values.append(len(cdata[keywords[0]])+1) if len(values)!=len(keywords): sys.stderr.write("Keyword and value index have different length?\n") continue for index in range(len(values)): cdata[keywords[index]].append(values[index]) hdu={'data': cdata, 'header': header, 'format': formats, 'order': keywords} ### the hdu is a dictionary with the header and data return hdu
python
def read(file): """Read in a file and create a data strucuture that is a hash with members 'header' and 'data'. The 'header' is a hash of header keywords, the data is a hash of columns. To get to the nth element of column NAME use hdu[data][NAME][n]. To get the header information use hdu[header][KEYWORD]. """ f = open(file,'r') lines=f.readlines() f.close() import re, string keywords=[] values=[] formats={} header={} cdata={} for line in lines: if ( re.match(r'^##',line)): ## header line m=string.split(string.lstrip(line[2:])) if not m: sys.stderr.write( "Ill formed header line in %s \ n " % ( file, )) sys.stderr.write( line) continue keywords=m add_id=False continue if ( re.match(r'^# ',line)): ## this is a keyword value line, must match the previous keyword line m=string.split(string.lstrip(line[1:])) values=m if len(values)!= len(keywords): sys.stderr.write( "Ill formed header, keyword/value missmatach\n") for index in range(len(values)): header[keywords[index]]=values[index] ## blank the arrays, we've already stuck this into the header keywords=[] values=[] continue if ( re.match(r'^#F',line)): ## this is a format line for the columns needs to be a keyword line first if not keywords: sys.stderr.write("Cann't have formats without column names...\n") continue f=string.split(string.lstrip(line)) if add_id: f.append('%8d') for col in keywords: formats[col]=f.pop(0) ### must be the actual data ### expect a previous header line to define column headers if not keywords: sys.stderr.write( "No keywords for data columns, assuming x,y,mag,msky\n") keywords=('X','Y','MAG','MSKY') values = string.split(string.lstrip(line)) ### add the id value to the values array if needed if not 'ID' in keywords: keywords.append('ID') add_id=True if not cdata: for keyword in keywords: cdata[keyword]=[] if add_id: values.append(len(cdata[keywords[0]])+1) if len(values)!=len(keywords): sys.stderr.write("Keyword and value index have different length?\n") continue for index in range(len(values)): cdata[keywords[index]].append(values[index]) hdu={'data': cdata, 'header': header, 'format': formats, 'order': keywords} ### the hdu is a dictionary with the header and data return hdu
[ "def", "read", "(", "file", ")", ":", "f", "=", "open", "(", "file", ",", "'r'", ")", "lines", "=", "f", ".", "readlines", "(", ")", "f", ".", "close", "(", ")", "import", "re", ",", "string", "keywords", "=", "[", "]", "values", "=", "[", "]...
Read in a file and create a data strucuture that is a hash with members 'header' and 'data'. The 'header' is a hash of header keywords, the data is a hash of columns. To get to the nth element of column NAME use hdu[data][NAME][n]. To get the header information use hdu[header][KEYWORD].
[ "Read", "in", "a", "file", "and", "create", "a", "data", "strucuture", "that", "is", "a", "hash", "with", "members", "header", "and", "data", ".", "The", "header", "is", "a", "hash", "of", "header", "keywords", "the", "data", "is", "a", "hash", "of", ...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfiles.py#L168-L242
OSSOS/MOP
src/jjk/preproc/MOPfiles.py
xymatch
def xymatch(outfile, filenames, tol=2): """Given a list of MOPfiles merge them based on x/y coordinates matching..""" import math import sys output={} files=[] for filename in filenames: this_file=read(filename) ## match files based on the 'X' and 'Y' column. ## if those don't exist then skip this file if not this_file['data'].has_key('X') or not this_file['data'].has_key('Y'): continue if not output.has_key('data'): output=this_file continue delete_list=[] for keyword in this_file['header']: if not keyword in output['header']: output['header'][keyword]=this_file['header'][keyword] for col in this_file['data'].keys(): if not output['data'].has_key(col): output['order'].append(col) output['data'][col]=[] output['order'].append(col) if this_file['format'].has_key(col): output['format'][col]=this_file['format'][col] else: output['format'][col]='%10s' ### pad previously values with empties.. for i in range(len(output['data']['X'])): output['data'][col].append(None) for i in xrange(len(output['data']['X'])): x1=float(output['data']['X'][i]) y1=float(output['data']['Y'][i]) matched=False for j in xrange(len(this_file['data']['X'])): x2=float(this_file['data']['X'][j]) y2=float(this_file['data']['Y'][j]) if ( ((x1-x2)**2+(y1-y2)**2) < tol**2): for col in this_file['data'].keys(): if output['data'][col][i] is None: output['data'][col][i]=this_file['data'][col][j] matched=True break if not matched: delete_list.append(i) delete_list.sort() delete_list.reverse() for i in delete_list: for col in output['data'].keys(): del output['data'][col][i] write(outfile,output)
python
def xymatch(outfile, filenames, tol=2): """Given a list of MOPfiles merge them based on x/y coordinates matching..""" import math import sys output={} files=[] for filename in filenames: this_file=read(filename) ## match files based on the 'X' and 'Y' column. ## if those don't exist then skip this file if not this_file['data'].has_key('X') or not this_file['data'].has_key('Y'): continue if not output.has_key('data'): output=this_file continue delete_list=[] for keyword in this_file['header']: if not keyword in output['header']: output['header'][keyword]=this_file['header'][keyword] for col in this_file['data'].keys(): if not output['data'].has_key(col): output['order'].append(col) output['data'][col]=[] output['order'].append(col) if this_file['format'].has_key(col): output['format'][col]=this_file['format'][col] else: output['format'][col]='%10s' ### pad previously values with empties.. for i in range(len(output['data']['X'])): output['data'][col].append(None) for i in xrange(len(output['data']['X'])): x1=float(output['data']['X'][i]) y1=float(output['data']['Y'][i]) matched=False for j in xrange(len(this_file['data']['X'])): x2=float(this_file['data']['X'][j]) y2=float(this_file['data']['Y'][j]) if ( ((x1-x2)**2+(y1-y2)**2) < tol**2): for col in this_file['data'].keys(): if output['data'][col][i] is None: output['data'][col][i]=this_file['data'][col][j] matched=True break if not matched: delete_list.append(i) delete_list.sort() delete_list.reverse() for i in delete_list: for col in output['data'].keys(): del output['data'][col][i] write(outfile,output)
[ "def", "xymatch", "(", "outfile", ",", "filenames", ",", "tol", "=", "2", ")", ":", "import", "math", "import", "sys", "output", "=", "{", "}", "files", "=", "[", "]", "for", "filename", "in", "filenames", ":", "this_file", "=", "read", "(", "filenam...
Given a list of MOPfiles merge them based on x/y coordinates matching..
[ "Given", "a", "list", "of", "MOPfiles", "merge", "them", "based", "on", "x", "/", "y", "coordinates", "matching", ".." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfiles.py#L245-L299
playpauseandstop/rororo
rororo/logger.py
default_logging_dict
def default_logging_dict(*loggers: str, **kwargs: Any) -> DictStrAny: r"""Prepare logging dict suitable with ``logging.config.dictConfig``. **Usage**:: from logging.config import dictConfig dictConfig(default_logging_dict('yourlogger')) :param \*loggers: Enable logging for each logger in sequence. :param \*\*kwargs: Setup additional logger params via keyword arguments. """ kwargs.setdefault('level', 'INFO') return { 'version': 1, 'disable_existing_loggers': True, 'filters': { 'ignore_errors': { '()': IgnoreErrorsFilter, }, }, 'formatters': { 'default': { 'format': '%(asctime)s [%(levelname)s:%(name)s] %(message)s', }, 'naked': { 'format': u'%(message)s', }, }, 'handlers': { 'stdout': { 'class': 'logging.StreamHandler', 'filters': ['ignore_errors'], 'formatter': 'default', 'level': 'DEBUG', 'stream': sys.stdout, }, 'stderr': { 'class': 'logging.StreamHandler', 'formatter': 'default', 'level': 'WARNING', 'stream': sys.stderr, }, }, 'loggers': { logger: dict(handlers=['stdout', 'stderr'], **kwargs) for logger in loggers }, }
python
def default_logging_dict(*loggers: str, **kwargs: Any) -> DictStrAny: r"""Prepare logging dict suitable with ``logging.config.dictConfig``. **Usage**:: from logging.config import dictConfig dictConfig(default_logging_dict('yourlogger')) :param \*loggers: Enable logging for each logger in sequence. :param \*\*kwargs: Setup additional logger params via keyword arguments. """ kwargs.setdefault('level', 'INFO') return { 'version': 1, 'disable_existing_loggers': True, 'filters': { 'ignore_errors': { '()': IgnoreErrorsFilter, }, }, 'formatters': { 'default': { 'format': '%(asctime)s [%(levelname)s:%(name)s] %(message)s', }, 'naked': { 'format': u'%(message)s', }, }, 'handlers': { 'stdout': { 'class': 'logging.StreamHandler', 'filters': ['ignore_errors'], 'formatter': 'default', 'level': 'DEBUG', 'stream': sys.stdout, }, 'stderr': { 'class': 'logging.StreamHandler', 'formatter': 'default', 'level': 'WARNING', 'stream': sys.stderr, }, }, 'loggers': { logger: dict(handlers=['stdout', 'stderr'], **kwargs) for logger in loggers }, }
[ "def", "default_logging_dict", "(", "*", "loggers", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "DictStrAny", ":", "kwargs", ".", "setdefault", "(", "'level'", ",", "'INFO'", ")", "return", "{", "'version'", ":", "1", ",", "'disable_exist...
r"""Prepare logging dict suitable with ``logging.config.dictConfig``. **Usage**:: from logging.config import dictConfig dictConfig(default_logging_dict('yourlogger')) :param \*loggers: Enable logging for each logger in sequence. :param \*\*kwargs: Setup additional logger params via keyword arguments.
[ "r", "Prepare", "logging", "dict", "suitable", "with", "logging", ".", "config", ".", "dictConfig", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/logger.py#L28-L75
playpauseandstop/rororo
rororo/logger.py
update_sentry_logging
def update_sentry_logging(logging_dict: DictStrAny, sentry_dsn: Optional[str], *loggers: str, level: Union[str, int] = None, **kwargs: Any) -> None: r"""Enable Sentry logging if Sentry DSN passed. .. note:: Sentry logging requires `raven <http://pypi.python.org/pypi/raven>`_ library to be installed. **Usage**:: from logging.config import dictConfig LOGGING = default_logging_dict() SENTRY_DSN = '...' update_sentry_logging(LOGGING, SENTRY_DSN) dictConfig(LOGGING) **Using AioHttpTransport for SentryHandler** This will allow to use ``aiohttp.client`` for pushing data to Sentry in your ``aiohttp.web`` app, which means elimination of sync calls to Sentry. :: from raven_aiohttp import AioHttpTransport update_sentry_logging(LOGGING, SENTRY_DSN, transport=AioHttpTransport) :param logging_dict: Logging dict. :param sentry_dsn: Sentry DSN value. If ``None`` do not update logging dict at all. :param \*loggers: Use Sentry logging for each logger in the sequence. If the sequence is empty use Sentry logging to each available logger. :param \*\*kwargs: Additional kwargs to be passed to ``SentryHandler``. """ # No Sentry DSN, nothing to do if not sentry_dsn: return # Add Sentry handler kwargs['class'] = 'raven.handlers.logging.SentryHandler' kwargs['dsn'] = sentry_dsn logging_dict['handlers']['sentry'] = dict( level=level or 'WARNING', **kwargs) loggers = tuple(logging_dict['loggers']) if not loggers else loggers for logger in loggers: # Ignore missing loggers logger_dict = logging_dict['loggers'].get(logger) if not logger_dict: continue # Ignore logger from logger config if logger_dict.pop('ignore_sentry', False): continue # Handlers list should exist handlers = list(logger_dict.setdefault('handlers', [])) handlers.append('sentry') logger_dict['handlers'] = tuple(handlers)
python
def update_sentry_logging(logging_dict: DictStrAny, sentry_dsn: Optional[str], *loggers: str, level: Union[str, int] = None, **kwargs: Any) -> None: r"""Enable Sentry logging if Sentry DSN passed. .. note:: Sentry logging requires `raven <http://pypi.python.org/pypi/raven>`_ library to be installed. **Usage**:: from logging.config import dictConfig LOGGING = default_logging_dict() SENTRY_DSN = '...' update_sentry_logging(LOGGING, SENTRY_DSN) dictConfig(LOGGING) **Using AioHttpTransport for SentryHandler** This will allow to use ``aiohttp.client`` for pushing data to Sentry in your ``aiohttp.web`` app, which means elimination of sync calls to Sentry. :: from raven_aiohttp import AioHttpTransport update_sentry_logging(LOGGING, SENTRY_DSN, transport=AioHttpTransport) :param logging_dict: Logging dict. :param sentry_dsn: Sentry DSN value. If ``None`` do not update logging dict at all. :param \*loggers: Use Sentry logging for each logger in the sequence. If the sequence is empty use Sentry logging to each available logger. :param \*\*kwargs: Additional kwargs to be passed to ``SentryHandler``. """ # No Sentry DSN, nothing to do if not sentry_dsn: return # Add Sentry handler kwargs['class'] = 'raven.handlers.logging.SentryHandler' kwargs['dsn'] = sentry_dsn logging_dict['handlers']['sentry'] = dict( level=level or 'WARNING', **kwargs) loggers = tuple(logging_dict['loggers']) if not loggers else loggers for logger in loggers: # Ignore missing loggers logger_dict = logging_dict['loggers'].get(logger) if not logger_dict: continue # Ignore logger from logger config if logger_dict.pop('ignore_sentry', False): continue # Handlers list should exist handlers = list(logger_dict.setdefault('handlers', [])) handlers.append('sentry') logger_dict['handlers'] = tuple(handlers)
[ "def", "update_sentry_logging", "(", "logging_dict", ":", "DictStrAny", ",", "sentry_dsn", ":", "Optional", "[", "str", "]", ",", "*", "loggers", ":", "str", ",", "level", ":", "Union", "[", "str", ",", "int", "]", "=", "None", ",", "*", "*", "kwargs",...
r"""Enable Sentry logging if Sentry DSN passed. .. note:: Sentry logging requires `raven <http://pypi.python.org/pypi/raven>`_ library to be installed. **Usage**:: from logging.config import dictConfig LOGGING = default_logging_dict() SENTRY_DSN = '...' update_sentry_logging(LOGGING, SENTRY_DSN) dictConfig(LOGGING) **Using AioHttpTransport for SentryHandler** This will allow to use ``aiohttp.client`` for pushing data to Sentry in your ``aiohttp.web`` app, which means elimination of sync calls to Sentry. :: from raven_aiohttp import AioHttpTransport update_sentry_logging(LOGGING, SENTRY_DSN, transport=AioHttpTransport) :param logging_dict: Logging dict. :param sentry_dsn: Sentry DSN value. If ``None`` do not update logging dict at all. :param \*loggers: Use Sentry logging for each logger in the sequence. If the sequence is empty use Sentry logging to each available logger. :param \*\*kwargs: Additional kwargs to be passed to ``SentryHandler``.
[ "r", "Enable", "Sentry", "logging", "if", "Sentry", "DSN", "passed", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/logger.py#L78-L142
OSSOS/MOP
src/ossos/core/scripts/preproc.py
trim
def trim(hdu, datasec='DATASEC'): """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]) logger.info("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, datasec='DATASEC'): """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]) logger.info("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", "=", "'DATASEC'", ")", ":", "datasec", "=", "re", ".", "findall", "(", "r'(\\d+)'", ",", "hdu", ".", "header", ".", "get", "(", "datasec", ")", ")", "l", "=", "int", "(", "datasec", "[", "0", "]", ")", ...
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/ossos/core/scripts/preproc.py#L77-L93
OSSOS/MOP
src/ossos/core/ossos/parsers.py
ossos_release_parser
def ossos_release_parser(table=False, data_release=parameters.RELEASE_VERSION): """ extra fun as this is space-separated so using CSV parsers is not an option """ names = ['cl', 'p', 'j', 'k', 'sh', 'object', 'mag', 'e_mag', 'Filt', 'Hsur', 'dist', 'e_dist', 'Nobs', 'time', 'av_xres', 'av_yres', 'max_x', 'max_y', 'a', 'e_a', 'e', 'e_e', 'i', 'e_i', 'Omega', 'e_Omega', 'omega', 'e_omega', 'tperi', 'e_tperi', 'RAdeg', 'DEdeg', 'JD', 'rate']#, 'eff', 'm_lim'] if table: retval = Table.read(parameters.RELEASE_DETECTIONS[data_release], format='ascii', guess=False, delimiter=' ', data_start=0, comment='#', names=names, header_start=None) else: retval = [] with open(data_release, 'r') as detectionsfile: for line in detectionsfile.readlines()[1:]: # first line is column definitions obj = TNO.from_string(line, version=parameters.RELEASE_DETECTIONS[data_release]) retval.append(obj) return retval
python
def ossos_release_parser(table=False, data_release=parameters.RELEASE_VERSION): """ extra fun as this is space-separated so using CSV parsers is not an option """ names = ['cl', 'p', 'j', 'k', 'sh', 'object', 'mag', 'e_mag', 'Filt', 'Hsur', 'dist', 'e_dist', 'Nobs', 'time', 'av_xres', 'av_yres', 'max_x', 'max_y', 'a', 'e_a', 'e', 'e_e', 'i', 'e_i', 'Omega', 'e_Omega', 'omega', 'e_omega', 'tperi', 'e_tperi', 'RAdeg', 'DEdeg', 'JD', 'rate']#, 'eff', 'm_lim'] if table: retval = Table.read(parameters.RELEASE_DETECTIONS[data_release], format='ascii', guess=False, delimiter=' ', data_start=0, comment='#', names=names, header_start=None) else: retval = [] with open(data_release, 'r') as detectionsfile: for line in detectionsfile.readlines()[1:]: # first line is column definitions obj = TNO.from_string(line, version=parameters.RELEASE_DETECTIONS[data_release]) retval.append(obj) return retval
[ "def", "ossos_release_parser", "(", "table", "=", "False", ",", "data_release", "=", "parameters", ".", "RELEASE_VERSION", ")", ":", "names", "=", "[", "'cl'", ",", "'p'", ",", "'j'", ",", "'k'", ",", "'sh'", ",", "'object'", ",", "'mag'", ",", "'e_mag'"...
extra fun as this is space-separated so using CSV parsers is not an option
[ "extra", "fun", "as", "this", "is", "space", "-", "separated", "so", "using", "CSV", "parsers", "is", "not", "an", "option" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/parsers.py#L23-L41
OSSOS/MOP
src/ossos/core/ossos/parsers.py
ossos_discoveries
def ossos_discoveries(directory=parameters.REAL_KBO_AST_DIR, suffix='ast', no_nt_and_u=False, single_object=None, all_objects=True, data_release=None, ): """ Returns a list of objects holding orbfit.Orbfit objects with the observations in the Orbfit.observations field. Default is to return only the objects corresponding to the current Data Release. """ retval = [] # working_context = context.get_context(directory) # files = working_context.get_listing(suffix) files = [f for f in os.listdir(directory) if (f.endswith('mpc') or f.endswith('ast') or f.endswith('DONE'))] if single_object is not None: files = filter(lambda name: name.startswith(single_object), files) elif all_objects and data_release is not None: # only return the objects corresponding to a particular Data Release data_release = ossos_release_parser(table=True, data_release=data_release) objects = data_release['object'] files = filter(lambda name: name.partition(suffix)[0].rstrip('.') in objects, files) for filename in files: # keep out the not-tracked and uncharacteried. if no_nt_and_u and (filename.__contains__('nt') or filename.startswith('u')): continue # observations = mpc.MPCReader(directory + filename) mpc_filename = directory + filename abg_filename = os.path.abspath(directory + '/../abg/') + "/" + os.path.splitext(filename)[0] + ".abg" obj = TNO(None, ast_filename=mpc_filename, abg_filename=abg_filename) retval.append(obj) return retval
python
def ossos_discoveries(directory=parameters.REAL_KBO_AST_DIR, suffix='ast', no_nt_and_u=False, single_object=None, all_objects=True, data_release=None, ): """ Returns a list of objects holding orbfit.Orbfit objects with the observations in the Orbfit.observations field. Default is to return only the objects corresponding to the current Data Release. """ retval = [] # working_context = context.get_context(directory) # files = working_context.get_listing(suffix) files = [f for f in os.listdir(directory) if (f.endswith('mpc') or f.endswith('ast') or f.endswith('DONE'))] if single_object is not None: files = filter(lambda name: name.startswith(single_object), files) elif all_objects and data_release is not None: # only return the objects corresponding to a particular Data Release data_release = ossos_release_parser(table=True, data_release=data_release) objects = data_release['object'] files = filter(lambda name: name.partition(suffix)[0].rstrip('.') in objects, files) for filename in files: # keep out the not-tracked and uncharacteried. if no_nt_and_u and (filename.__contains__('nt') or filename.startswith('u')): continue # observations = mpc.MPCReader(directory + filename) mpc_filename = directory + filename abg_filename = os.path.abspath(directory + '/../abg/') + "/" + os.path.splitext(filename)[0] + ".abg" obj = TNO(None, ast_filename=mpc_filename, abg_filename=abg_filename) retval.append(obj) return retval
[ "def", "ossos_discoveries", "(", "directory", "=", "parameters", ".", "REAL_KBO_AST_DIR", ",", "suffix", "=", "'ast'", ",", "no_nt_and_u", "=", "False", ",", "single_object", "=", "None", ",", "all_objects", "=", "True", ",", "data_release", "=", "None", ",", ...
Returns a list of objects holding orbfit.Orbfit objects with the observations in the Orbfit.observations field. Default is to return only the objects corresponding to the current Data Release.
[ "Returns", "a", "list", "of", "objects", "holding", "orbfit", ".", "Orbfit", "objects", "with", "the", "observations", "in", "the", "Orbfit", ".", "observations", "field", ".", "Default", "is", "to", "return", "only", "the", "objects", "corresponding", "to", ...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/parsers.py#L83-L117
OSSOS/MOP
src/ossos/core/ossos/parsers.py
ossos_release_with_metadata
def ossos_release_with_metadata(): """ Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines """ # discoveries = ossos_release_parser() discoveries = [] observations = ossos_discoveries() for obj in observations: discov = [n for n in obj[0].mpc_observations if n.discovery.is_discovery][0] tno = parameters.tno() tno.dist = obj[1].distance tno.ra_discov = discov.coordinate.ra.degrees tno.mag = discov.mag tno.name = discov.provisional_name discoveries.append(tno) # for obj in discoveries: # observation = [n for n in observations if n.observations[-1].provisional_name == obj.name][0] # for obs in observation.observations: # if obs.discovery.is_discovery: # if obj.mag is not None: # H = obj.mag + 2.5 * math.log10(1. / ((obj.dist ** 2) * ((obj.dist - 1.) ** 2))) # else: # H = None # obj.H = H # obj.T = observation.T # obj.discovery_date = obs.date # obj.observations = observation return discoveries
python
def ossos_release_with_metadata(): """ Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines """ # discoveries = ossos_release_parser() discoveries = [] observations = ossos_discoveries() for obj in observations: discov = [n for n in obj[0].mpc_observations if n.discovery.is_discovery][0] tno = parameters.tno() tno.dist = obj[1].distance tno.ra_discov = discov.coordinate.ra.degrees tno.mag = discov.mag tno.name = discov.provisional_name discoveries.append(tno) # for obj in discoveries: # observation = [n for n in observations if n.observations[-1].provisional_name == obj.name][0] # for obs in observation.observations: # if obs.discovery.is_discovery: # if obj.mag is not None: # H = obj.mag + 2.5 * math.log10(1. / ((obj.dist ** 2) * ((obj.dist - 1.) ** 2))) # else: # H = None # obj.H = H # obj.T = observation.T # obj.discovery_date = obs.date # obj.observations = observation return discoveries
[ "def", "ossos_release_with_metadata", "(", ")", ":", "# discoveries = ossos_release_parser()", "discoveries", "=", "[", "]", "observations", "=", "ossos_discoveries", "(", ")", "for", "obj", "in", "observations", ":", "discov", "=", "[", "n", "for", "n", "in", "...
Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines
[ "Wrap", "the", "objects", "from", "the", "Version", "Releases", "together", "with", "the", "objects", "instantiated", "from", "fitting", "their", "mpc", "lines" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/parsers.py#L120-L149
OSSOS/MOP
src/ossos/core/ossos/parsers.py
_kbos_from_survey_sym_model_input_file
def _kbos_from_survey_sym_model_input_file(model_file): """ Load a Survey Simulator model file as an array of ephem EllipticalBody objects. @param model_file: @return: """ lines = storage.open_vos_or_local(model_file).read().split('\n') kbos = [] for line in lines: if len(line) == 0 or line[0] == '#': # skip initial column descriptors and the final blank line continue kbo = ephem.EllipticalBody() values = line.split() kbo.name = values[8] kbo.j = values[9] kbo.k = values[10] kbo._a = float(values[0]) kbo._e = float(values[1]) kbo._inc = float(values[2]) kbo._Om = float(values[3]) kbo._om = float(values[4]) kbo._M = float(values[5]) kbo._H = float(values[6]) epoch = ephem.date(2453157.50000 - ephem.julian_date(0)) kbo._epoch_M = epoch kbo._epoch = epoch kbos.append(kbo) return kbos
python
def _kbos_from_survey_sym_model_input_file(model_file): """ Load a Survey Simulator model file as an array of ephem EllipticalBody objects. @param model_file: @return: """ lines = storage.open_vos_or_local(model_file).read().split('\n') kbos = [] for line in lines: if len(line) == 0 or line[0] == '#': # skip initial column descriptors and the final blank line continue kbo = ephem.EllipticalBody() values = line.split() kbo.name = values[8] kbo.j = values[9] kbo.k = values[10] kbo._a = float(values[0]) kbo._e = float(values[1]) kbo._inc = float(values[2]) kbo._Om = float(values[3]) kbo._om = float(values[4]) kbo._M = float(values[5]) kbo._H = float(values[6]) epoch = ephem.date(2453157.50000 - ephem.julian_date(0)) kbo._epoch_M = epoch kbo._epoch = epoch kbos.append(kbo) return kbos
[ "def", "_kbos_from_survey_sym_model_input_file", "(", "model_file", ")", ":", "lines", "=", "storage", ".", "open_vos_or_local", "(", "model_file", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "kbos", "=", "[", "]", "for", "line", "in", "li...
Load a Survey Simulator model file as an array of ephem EllipticalBody objects. @param model_file: @return:
[ "Load", "a", "Survey", "Simulator", "model", "file", "as", "an", "array", "of", "ephem", "EllipticalBody", "objects", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/parsers.py#L152-L179
OSSOS/MOP
src/ossos/core/ossos/parsers.py
round_sig_error
def round_sig_error(num, uncert, pm=False): """ Return a string of the number and its uncertainty to the right sig figs via uncertainty's print methods. The uncertainty determines the sig fig rounding of the number. https://pythonhosted.org/uncertainties/user_guide.html """ u = ufloat(num, uncert) if pm: return '{:.1uL}'.format(u) else: return '{:.1uLS}'.format(u)
python
def round_sig_error(num, uncert, pm=False): """ Return a string of the number and its uncertainty to the right sig figs via uncertainty's print methods. The uncertainty determines the sig fig rounding of the number. https://pythonhosted.org/uncertainties/user_guide.html """ u = ufloat(num, uncert) if pm: return '{:.1uL}'.format(u) else: return '{:.1uLS}'.format(u)
[ "def", "round_sig_error", "(", "num", ",", "uncert", ",", "pm", "=", "False", ")", ":", "u", "=", "ufloat", "(", "num", ",", "uncert", ")", "if", "pm", ":", "return", "'{:.1uL}'", ".", "format", "(", "u", ")", "else", ":", "return", "'{:.1uLS}'", "...
Return a string of the number and its uncertainty to the right sig figs via uncertainty's print methods. The uncertainty determines the sig fig rounding of the number. https://pythonhosted.org/uncertainties/user_guide.html
[ "Return", "a", "string", "of", "the", "number", "and", "its", "uncertainty", "to", "the", "right", "sig", "figs", "via", "uncertainty", "s", "print", "methods", ".", "The", "uncertainty", "determines", "the", "sig", "fig", "rounding", "of", "the", "number", ...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/parsers.py#L251-L261
openstack/python-scciclient
scciclient/irmc/elcm.py
_parse_elcm_response_body_as_json
def _parse_elcm_response_body_as_json(response): """parse eLCM response body as json data eLCM response should be in form of: _ Key1: value1 <-- optional --> Key2: value2 <-- optional --> KeyN: valueN <-- optional --> - CRLF - JSON string - :param response: eLCM response :return: json object if success :raise ELCMInvalidResponse: if the response does not contain valid json data. """ try: body = response.text body_parts = body.split('\r\n') if len(body_parts) > 0: return jsonutils.loads(body_parts[-1]) else: return None except (TypeError, ValueError): raise ELCMInvalidResponse('eLCM response does not contain valid json ' 'data. Response is "%s".' % body)
python
def _parse_elcm_response_body_as_json(response): """parse eLCM response body as json data eLCM response should be in form of: _ Key1: value1 <-- optional --> Key2: value2 <-- optional --> KeyN: valueN <-- optional --> - CRLF - JSON string - :param response: eLCM response :return: json object if success :raise ELCMInvalidResponse: if the response does not contain valid json data. """ try: body = response.text body_parts = body.split('\r\n') if len(body_parts) > 0: return jsonutils.loads(body_parts[-1]) else: return None except (TypeError, ValueError): raise ELCMInvalidResponse('eLCM response does not contain valid json ' 'data. Response is "%s".' % body)
[ "def", "_parse_elcm_response_body_as_json", "(", "response", ")", ":", "try", ":", "body", "=", "response", ".", "text", "body_parts", "=", "body", ".", "split", "(", "'\\r\\n'", ")", "if", "len", "(", "body_parts", ")", ">", "0", ":", "return", "jsonutils...
parse eLCM response body as json data eLCM response should be in form of: _ Key1: value1 <-- optional --> Key2: value2 <-- optional --> KeyN: valueN <-- optional --> - CRLF - JSON string - :param response: eLCM response :return: json object if success :raise ELCMInvalidResponse: if the response does not contain valid json data.
[ "parse", "eLCM", "response", "body", "as", "json", "data" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L149-L177
openstack/python-scciclient
scciclient/irmc/elcm.py
elcm_request
def elcm_request(irmc_info, method, path, **kwargs): """send an eLCM request to the server :param irmc_info: dict of iRMC params to access the server node { 'irmc_address': host, 'irmc_username': user_id, 'irmc_password': password, 'irmc_port': 80 or 443, default is 443, 'irmc_auth_method': 'basic' or 'digest', default is 'basic', 'irmc_client_timeout': timeout, default is 60, ... } :param method: request method such as 'GET', 'POST' :param path: url path for eLCM request :returns: requests.Response from SCCI server :raises SCCIInvalidInputError: if port and/or auth_method params are invalid :raises SCCIClientError: if SCCI failed """ host = irmc_info['irmc_address'] port = irmc_info.get('irmc_port', 443) auth_method = irmc_info.get('irmc_auth_method', 'basic') userid = irmc_info['irmc_username'] password = irmc_info['irmc_password'] client_timeout = irmc_info.get('irmc_client_timeout', 60) # Request headers, params, and data headers = kwargs.get('headers', {'Accept': 'application/json'}) params = kwargs.get('params') data = kwargs.get('data') auth_obj = None try: protocol = {80: 'http', 443: 'https'}[port] auth_obj = { 'basic': requests.auth.HTTPBasicAuth(userid, password), 'digest': requests.auth.HTTPDigestAuth(userid, password) }[auth_method.lower()] except KeyError: raise scci.SCCIInvalidInputError( ("Invalid port %(port)d or " + "auth_method for method %(auth_method)s") % {'port': port, 'auth_method': auth_method}) try: r = requests.request(method, protocol + '://' + host + path, headers=headers, params=params, data=data, verify=False, timeout=client_timeout, allow_redirects=False, auth=auth_obj) except requests.exceptions.RequestException as requests_exception: raise scci.SCCIClientError(requests_exception) # Process status_code 401 if r.status_code == 401: raise scci.SCCIClientError('UNAUTHORIZED') return r
python
def elcm_request(irmc_info, method, path, **kwargs): """send an eLCM request to the server :param irmc_info: dict of iRMC params to access the server node { 'irmc_address': host, 'irmc_username': user_id, 'irmc_password': password, 'irmc_port': 80 or 443, default is 443, 'irmc_auth_method': 'basic' or 'digest', default is 'basic', 'irmc_client_timeout': timeout, default is 60, ... } :param method: request method such as 'GET', 'POST' :param path: url path for eLCM request :returns: requests.Response from SCCI server :raises SCCIInvalidInputError: if port and/or auth_method params are invalid :raises SCCIClientError: if SCCI failed """ host = irmc_info['irmc_address'] port = irmc_info.get('irmc_port', 443) auth_method = irmc_info.get('irmc_auth_method', 'basic') userid = irmc_info['irmc_username'] password = irmc_info['irmc_password'] client_timeout = irmc_info.get('irmc_client_timeout', 60) # Request headers, params, and data headers = kwargs.get('headers', {'Accept': 'application/json'}) params = kwargs.get('params') data = kwargs.get('data') auth_obj = None try: protocol = {80: 'http', 443: 'https'}[port] auth_obj = { 'basic': requests.auth.HTTPBasicAuth(userid, password), 'digest': requests.auth.HTTPDigestAuth(userid, password) }[auth_method.lower()] except KeyError: raise scci.SCCIInvalidInputError( ("Invalid port %(port)d or " + "auth_method for method %(auth_method)s") % {'port': port, 'auth_method': auth_method}) try: r = requests.request(method, protocol + '://' + host + path, headers=headers, params=params, data=data, verify=False, timeout=client_timeout, allow_redirects=False, auth=auth_obj) except requests.exceptions.RequestException as requests_exception: raise scci.SCCIClientError(requests_exception) # Process status_code 401 if r.status_code == 401: raise scci.SCCIClientError('UNAUTHORIZED') return r
[ "def", "elcm_request", "(", "irmc_info", ",", "method", ",", "path", ",", "*", "*", "kwargs", ")", ":", "host", "=", "irmc_info", "[", "'irmc_address'", "]", "port", "=", "irmc_info", ".", "get", "(", "'irmc_port'", ",", "443", ")", "auth_method", "=", ...
send an eLCM request to the server :param irmc_info: dict of iRMC params to access the server node { 'irmc_address': host, 'irmc_username': user_id, 'irmc_password': password, 'irmc_port': 80 or 443, default is 443, 'irmc_auth_method': 'basic' or 'digest', default is 'basic', 'irmc_client_timeout': timeout, default is 60, ... } :param method: request method such as 'GET', 'POST' :param path: url path for eLCM request :returns: requests.Response from SCCI server :raises SCCIInvalidInputError: if port and/or auth_method params are invalid :raises SCCIClientError: if SCCI failed
[ "send", "an", "eLCM", "request", "to", "the", "server" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L180-L243
openstack/python-scciclient
scciclient/irmc/elcm.py
elcm_profile_get_versions
def elcm_profile_get_versions(irmc_info): """send an eLCM request to get profile versions :param irmc_info: node info :returns: dict object of profiles if succeed { "Server":{ "@Version": "1.01", "AdapterConfigIrmc":{ "@Version": "1.00" }, "HWConfigurationIrmc":{ "@Version": "1.00" }, "SystemConfig":{ "IrmcConfig":{ "@Version": "1.02" }, "BiosConfig":{ "@Version": "1.02" } } } } :raises: SCCIClientError if SCCI failed """ # Send GET request to the server resp = elcm_request(irmc_info, method='GET', path=URL_PATH_PROFILE_MGMT + 'version') if resp.status_code == 200: return _parse_elcm_response_body_as_json(resp) else: raise scci.SCCIClientError(('Failed to get profile versions with ' 'error code %s' % resp.status_code))
python
def elcm_profile_get_versions(irmc_info): """send an eLCM request to get profile versions :param irmc_info: node info :returns: dict object of profiles if succeed { "Server":{ "@Version": "1.01", "AdapterConfigIrmc":{ "@Version": "1.00" }, "HWConfigurationIrmc":{ "@Version": "1.00" }, "SystemConfig":{ "IrmcConfig":{ "@Version": "1.02" }, "BiosConfig":{ "@Version": "1.02" } } } } :raises: SCCIClientError if SCCI failed """ # Send GET request to the server resp = elcm_request(irmc_info, method='GET', path=URL_PATH_PROFILE_MGMT + 'version') if resp.status_code == 200: return _parse_elcm_response_body_as_json(resp) else: raise scci.SCCIClientError(('Failed to get profile versions with ' 'error code %s' % resp.status_code))
[ "def", "elcm_profile_get_versions", "(", "irmc_info", ")", ":", "# Send GET request to the server", "resp", "=", "elcm_request", "(", "irmc_info", ",", "method", "=", "'GET'", ",", "path", "=", "URL_PATH_PROFILE_MGMT", "+", "'version'", ")", "if", "resp", ".", "st...
send an eLCM request to get profile versions :param irmc_info: node info :returns: dict object of profiles if succeed { "Server":{ "@Version": "1.01", "AdapterConfigIrmc":{ "@Version": "1.00" }, "HWConfigurationIrmc":{ "@Version": "1.00" }, "SystemConfig":{ "IrmcConfig":{ "@Version": "1.02" }, "BiosConfig":{ "@Version": "1.02" } } } } :raises: SCCIClientError if SCCI failed
[ "send", "an", "eLCM", "request", "to", "get", "profile", "versions" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L246-L281
openstack/python-scciclient
scciclient/irmc/elcm.py
elcm_profile_get
def elcm_profile_get(irmc_info, profile_name): """send an eLCM request to get profile data :param irmc_info: node info :param profile_name: name of profile :returns: dict object of profile data if succeed :raises: ELCMProfileNotFound if profile does not exist :raises: SCCIClientError if SCCI failed """ # Send GET request to the server resp = elcm_request(irmc_info, method='GET', path=URL_PATH_PROFILE_MGMT + profile_name) if resp.status_code == 200: return _parse_elcm_response_body_as_json(resp) elif resp.status_code == 404: raise ELCMProfileNotFound('Profile "%s" not found ' 'in the profile store.' % profile_name) else: raise scci.SCCIClientError(('Failed to get profile "%(profile)s" with ' 'error code %(error)s' % {'profile': profile_name, 'error': resp.status_code}))
python
def elcm_profile_get(irmc_info, profile_name): """send an eLCM request to get profile data :param irmc_info: node info :param profile_name: name of profile :returns: dict object of profile data if succeed :raises: ELCMProfileNotFound if profile does not exist :raises: SCCIClientError if SCCI failed """ # Send GET request to the server resp = elcm_request(irmc_info, method='GET', path=URL_PATH_PROFILE_MGMT + profile_name) if resp.status_code == 200: return _parse_elcm_response_body_as_json(resp) elif resp.status_code == 404: raise ELCMProfileNotFound('Profile "%s" not found ' 'in the profile store.' % profile_name) else: raise scci.SCCIClientError(('Failed to get profile "%(profile)s" with ' 'error code %(error)s' % {'profile': profile_name, 'error': resp.status_code}))
[ "def", "elcm_profile_get", "(", "irmc_info", ",", "profile_name", ")", ":", "# Send GET request to the server", "resp", "=", "elcm_request", "(", "irmc_info", ",", "method", "=", "'GET'", ",", "path", "=", "URL_PATH_PROFILE_MGMT", "+", "profile_name", ")", "if", "...
send an eLCM request to get profile data :param irmc_info: node info :param profile_name: name of profile :returns: dict object of profile data if succeed :raises: ELCMProfileNotFound if profile does not exist :raises: SCCIClientError if SCCI failed
[ "send", "an", "eLCM", "request", "to", "get", "profile", "data" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L314-L337
openstack/python-scciclient
scciclient/irmc/elcm.py
elcm_profile_create
def elcm_profile_create(irmc_info, param_path): """send an eLCM request to create profile To create a profile, a new session is spawned with status 'running'. When profile is created completely, the session ends. :param irmc_info: node info :param param_path: path of profile :returns: dict object of session info if succeed { 'Session': { 'Id': id 'Status': 'activated' ... } } :raises: SCCIClientError if SCCI failed """ # Send POST request to the server # NOTE: This task may take time, so set a timeout _irmc_info = dict(irmc_info) _irmc_info['irmc_client_timeout'] = PROFILE_CREATE_TIMEOUT resp = elcm_request(_irmc_info, method='POST', path=URL_PATH_PROFILE_MGMT + 'get', params={'PARAM_PATH': param_path}) if resp.status_code == 202: return _parse_elcm_response_body_as_json(resp) else: raise scci.SCCIClientError(('Failed to create profile for path ' '"%(param_path)s" with error code ' '%(error)s' % {'param_path': param_path, 'error': resp.status_code}))
python
def elcm_profile_create(irmc_info, param_path): """send an eLCM request to create profile To create a profile, a new session is spawned with status 'running'. When profile is created completely, the session ends. :param irmc_info: node info :param param_path: path of profile :returns: dict object of session info if succeed { 'Session': { 'Id': id 'Status': 'activated' ... } } :raises: SCCIClientError if SCCI failed """ # Send POST request to the server # NOTE: This task may take time, so set a timeout _irmc_info = dict(irmc_info) _irmc_info['irmc_client_timeout'] = PROFILE_CREATE_TIMEOUT resp = elcm_request(_irmc_info, method='POST', path=URL_PATH_PROFILE_MGMT + 'get', params={'PARAM_PATH': param_path}) if resp.status_code == 202: return _parse_elcm_response_body_as_json(resp) else: raise scci.SCCIClientError(('Failed to create profile for path ' '"%(param_path)s" with error code ' '%(error)s' % {'param_path': param_path, 'error': resp.status_code}))
[ "def", "elcm_profile_create", "(", "irmc_info", ",", "param_path", ")", ":", "# Send POST request to the server", "# NOTE: This task may take time, so set a timeout", "_irmc_info", "=", "dict", "(", "irmc_info", ")", "_irmc_info", "[", "'irmc_client_timeout'", "]", "=", "PR...
send an eLCM request to create profile To create a profile, a new session is spawned with status 'running'. When profile is created completely, the session ends. :param irmc_info: node info :param param_path: path of profile :returns: dict object of session info if succeed { 'Session': { 'Id': id 'Status': 'activated' ... } } :raises: SCCIClientError if SCCI failed
[ "send", "an", "eLCM", "request", "to", "create", "profile" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L340-L376
openstack/python-scciclient
scciclient/irmc/elcm.py
elcm_profile_set
def elcm_profile_set(irmc_info, input_data): """send an eLCM request to set param values To apply param values, a new session is spawned with status 'running'. When values are applied or error, the session ends. :param irmc_info: node info :param input_data: param values to apply, eg. { 'Server': { 'SystemConfig': { 'BiosConfig': { '@Processing': 'execute', -- config data -- } } } } :returns: dict object of session info if succeed { 'Session': { 'Id': id 'Status': 'activated' ... } } :raises: SCCIClientError if SCCI failed """ # Prepare the data to apply if isinstance(input_data, dict): data = jsonutils.dumps(input_data) else: data = input_data # Send POST request to the server # NOTE: This task may take time, so set a timeout _irmc_info = dict(irmc_info) _irmc_info['irmc_client_timeout'] = PROFILE_SET_TIMEOUT content_type = 'application/x-www-form-urlencoded' if input_data['Server'].get('HWConfigurationIrmc'): content_type = 'application/json' resp = elcm_request(_irmc_info, method='POST', path=URL_PATH_PROFILE_MGMT + 'set', headers={'Content-type': content_type}, data=data) if resp.status_code == 202: return _parse_elcm_response_body_as_json(resp) else: raise scci.SCCIClientError(('Failed to apply param values with ' 'error code %(error)s' % {'error': resp.status_code}))
python
def elcm_profile_set(irmc_info, input_data): """send an eLCM request to set param values To apply param values, a new session is spawned with status 'running'. When values are applied or error, the session ends. :param irmc_info: node info :param input_data: param values to apply, eg. { 'Server': { 'SystemConfig': { 'BiosConfig': { '@Processing': 'execute', -- config data -- } } } } :returns: dict object of session info if succeed { 'Session': { 'Id': id 'Status': 'activated' ... } } :raises: SCCIClientError if SCCI failed """ # Prepare the data to apply if isinstance(input_data, dict): data = jsonutils.dumps(input_data) else: data = input_data # Send POST request to the server # NOTE: This task may take time, so set a timeout _irmc_info = dict(irmc_info) _irmc_info['irmc_client_timeout'] = PROFILE_SET_TIMEOUT content_type = 'application/x-www-form-urlencoded' if input_data['Server'].get('HWConfigurationIrmc'): content_type = 'application/json' resp = elcm_request(_irmc_info, method='POST', path=URL_PATH_PROFILE_MGMT + 'set', headers={'Content-type': content_type}, data=data) if resp.status_code == 202: return _parse_elcm_response_body_as_json(resp) else: raise scci.SCCIClientError(('Failed to apply param values with ' 'error code %(error)s' % {'error': resp.status_code}))
[ "def", "elcm_profile_set", "(", "irmc_info", ",", "input_data", ")", ":", "# Prepare the data to apply", "if", "isinstance", "(", "input_data", ",", "dict", ")", ":", "data", "=", "jsonutils", ".", "dumps", "(", "input_data", ")", "else", ":", "data", "=", "...
send an eLCM request to set param values To apply param values, a new session is spawned with status 'running'. When values are applied or error, the session ends. :param irmc_info: node info :param input_data: param values to apply, eg. { 'Server': { 'SystemConfig': { 'BiosConfig': { '@Processing': 'execute', -- config data -- } } } } :returns: dict object of session info if succeed { 'Session': { 'Id': id 'Status': 'activated' ... } } :raises: SCCIClientError if SCCI failed
[ "send", "an", "eLCM", "request", "to", "set", "param", "values" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L379-L436
openstack/python-scciclient
scciclient/irmc/elcm.py
elcm_profile_delete
def elcm_profile_delete(irmc_info, profile_name): """send an eLCM request to delete a profile :param irmc_info: node info :param profile_name: name of profile :raises: ELCMProfileNotFound if the profile does not exist :raises: SCCIClientError if SCCI failed """ # Send DELETE request to the server resp = elcm_request(irmc_info, method='DELETE', path=URL_PATH_PROFILE_MGMT + profile_name) if resp.status_code == 200: # Profile deleted return elif resp.status_code == 404: # Profile not found raise ELCMProfileNotFound('Profile "%s" not found ' 'in the profile store.' % profile_name) else: raise scci.SCCIClientError(('Failed to delete profile "%(profile)s" ' 'with error code %(error)s' % {'profile': profile_name, 'error': resp.status_code}))
python
def elcm_profile_delete(irmc_info, profile_name): """send an eLCM request to delete a profile :param irmc_info: node info :param profile_name: name of profile :raises: ELCMProfileNotFound if the profile does not exist :raises: SCCIClientError if SCCI failed """ # Send DELETE request to the server resp = elcm_request(irmc_info, method='DELETE', path=URL_PATH_PROFILE_MGMT + profile_name) if resp.status_code == 200: # Profile deleted return elif resp.status_code == 404: # Profile not found raise ELCMProfileNotFound('Profile "%s" not found ' 'in the profile store.' % profile_name) else: raise scci.SCCIClientError(('Failed to delete profile "%(profile)s" ' 'with error code %(error)s' % {'profile': profile_name, 'error': resp.status_code}))
[ "def", "elcm_profile_delete", "(", "irmc_info", ",", "profile_name", ")", ":", "# Send DELETE request to the server", "resp", "=", "elcm_request", "(", "irmc_info", ",", "method", "=", "'DELETE'", ",", "path", "=", "URL_PATH_PROFILE_MGMT", "+", "profile_name", ")", ...
send an eLCM request to delete a profile :param irmc_info: node info :param profile_name: name of profile :raises: ELCMProfileNotFound if the profile does not exist :raises: SCCIClientError if SCCI failed
[ "send", "an", "eLCM", "request", "to", "delete", "a", "profile" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L439-L463
openstack/python-scciclient
scciclient/irmc/elcm.py
elcm_session_list
def elcm_session_list(irmc_info): """send an eLCM request to list all sessions :param irmc_info: node info :returns: dict object of sessions if succeed { 'SessionList': { 'Contains': [ { 'Id': id1, 'Name': name1 }, { 'Id': id2, 'Name': name2 }, { 'Id': idN, 'Name': nameN }, ] } } :raises: SCCIClientError if SCCI failed """ # Send GET request to the server resp = elcm_request(irmc_info, method='GET', path='/sessionInformation/') if resp.status_code == 200: return _parse_elcm_response_body_as_json(resp) else: raise scci.SCCIClientError(('Failed to list sessions with ' 'error code %s' % resp.status_code))
python
def elcm_session_list(irmc_info): """send an eLCM request to list all sessions :param irmc_info: node info :returns: dict object of sessions if succeed { 'SessionList': { 'Contains': [ { 'Id': id1, 'Name': name1 }, { 'Id': id2, 'Name': name2 }, { 'Id': idN, 'Name': nameN }, ] } } :raises: SCCIClientError if SCCI failed """ # Send GET request to the server resp = elcm_request(irmc_info, method='GET', path='/sessionInformation/') if resp.status_code == 200: return _parse_elcm_response_body_as_json(resp) else: raise scci.SCCIClientError(('Failed to list sessions with ' 'error code %s' % resp.status_code))
[ "def", "elcm_session_list", "(", "irmc_info", ")", ":", "# Send GET request to the server", "resp", "=", "elcm_request", "(", "irmc_info", ",", "method", "=", "'GET'", ",", "path", "=", "'/sessionInformation/'", ")", "if", "resp", ".", "status_code", "==", "200", ...
send an eLCM request to list all sessions :param irmc_info: node info :returns: dict object of sessions if succeed { 'SessionList': { 'Contains': [ { 'Id': id1, 'Name': name1 }, { 'Id': id2, 'Name': name2 }, { 'Id': idN, 'Name': nameN }, ] } } :raises: SCCIClientError if SCCI failed
[ "send", "an", "eLCM", "request", "to", "list", "all", "sessions" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L466-L493
openstack/python-scciclient
scciclient/irmc/elcm.py
elcm_session_get_status
def elcm_session_get_status(irmc_info, session_id): """send an eLCM request to get session status :param irmc_info: node info :param session_id: session id :returns: dict object of session info if succeed { 'Session': { 'Id': id 'Status': status ... } } :raises: ELCMSessionNotFound if the session does not exist :raises: SCCIClientError if SCCI failed """ # Send GET request to the server resp = elcm_request(irmc_info, method='GET', path='/sessionInformation/%s/status' % session_id) if resp.status_code == 200: return _parse_elcm_response_body_as_json(resp) elif resp.status_code == 404: raise ELCMSessionNotFound('Session "%s" does not exist' % session_id) else: raise scci.SCCIClientError(('Failed to get status of session ' '"%(session)s" with error code %(error)s' % {'session': session_id, 'error': resp.status_code}))
python
def elcm_session_get_status(irmc_info, session_id): """send an eLCM request to get session status :param irmc_info: node info :param session_id: session id :returns: dict object of session info if succeed { 'Session': { 'Id': id 'Status': status ... } } :raises: ELCMSessionNotFound if the session does not exist :raises: SCCIClientError if SCCI failed """ # Send GET request to the server resp = elcm_request(irmc_info, method='GET', path='/sessionInformation/%s/status' % session_id) if resp.status_code == 200: return _parse_elcm_response_body_as_json(resp) elif resp.status_code == 404: raise ELCMSessionNotFound('Session "%s" does not exist' % session_id) else: raise scci.SCCIClientError(('Failed to get status of session ' '"%(session)s" with error code %(error)s' % {'session': session_id, 'error': resp.status_code}))
[ "def", "elcm_session_get_status", "(", "irmc_info", ",", "session_id", ")", ":", "# Send GET request to the server", "resp", "=", "elcm_request", "(", "irmc_info", ",", "method", "=", "'GET'", ",", "path", "=", "'/sessionInformation/%s/status'", "%", "session_id", ")"...
send an eLCM request to get session status :param irmc_info: node info :param session_id: session id :returns: dict object of session info if succeed { 'Session': { 'Id': id 'Status': status ... } } :raises: ELCMSessionNotFound if the session does not exist :raises: SCCIClientError if SCCI failed
[ "send", "an", "eLCM", "request", "to", "get", "session", "status" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L496-L526
openstack/python-scciclient
scciclient/irmc/elcm.py
elcm_session_terminate
def elcm_session_terminate(irmc_info, session_id): """send an eLCM request to terminate a session :param irmc_info: node info :param session_id: session id :raises: ELCMSessionNotFound if the session does not exist :raises: SCCIClientError if SCCI failed """ # Send DELETE request to the server resp = elcm_request(irmc_info, method='DELETE', path='/sessionInformation/%s/terminate' % session_id) if resp.status_code == 200: return elif resp.status_code == 404: raise ELCMSessionNotFound('Session "%s" does not exist' % session_id) else: raise scci.SCCIClientError(('Failed to terminate session ' '"%(session)s" with error code %(error)s' % {'session': session_id, 'error': resp.status_code}))
python
def elcm_session_terminate(irmc_info, session_id): """send an eLCM request to terminate a session :param irmc_info: node info :param session_id: session id :raises: ELCMSessionNotFound if the session does not exist :raises: SCCIClientError if SCCI failed """ # Send DELETE request to the server resp = elcm_request(irmc_info, method='DELETE', path='/sessionInformation/%s/terminate' % session_id) if resp.status_code == 200: return elif resp.status_code == 404: raise ELCMSessionNotFound('Session "%s" does not exist' % session_id) else: raise scci.SCCIClientError(('Failed to terminate session ' '"%(session)s" with error code %(error)s' % {'session': session_id, 'error': resp.status_code}))
[ "def", "elcm_session_terminate", "(", "irmc_info", ",", "session_id", ")", ":", "# Send DELETE request to the server", "resp", "=", "elcm_request", "(", "irmc_info", ",", "method", "=", "'DELETE'", ",", "path", "=", "'/sessionInformation/%s/terminate'", "%", "session_id...
send an eLCM request to terminate a session :param irmc_info: node info :param session_id: session id :raises: ELCMSessionNotFound if the session does not exist :raises: SCCIClientError if SCCI failed
[ "send", "an", "eLCM", "request", "to", "terminate", "a", "session" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L561-L582
openstack/python-scciclient
scciclient/irmc/elcm.py
elcm_session_delete
def elcm_session_delete(irmc_info, session_id, terminate=False): """send an eLCM request to remove a session from the session list :param irmc_info: node info :param session_id: session id :param terminate: a running session must be terminated before removing :raises: ELCMSessionNotFound if the session does not exist :raises: SCCIClientError if SCCI failed """ # Terminate the session first if needs to if terminate: # Get session status to check session = elcm_session_get_status(irmc_info, session_id) status = session['Session']['Status'] # Terminate session if it is activated or running if status == 'running' or status == 'activated': elcm_session_terminate(irmc_info, session_id) # Send DELETE request to the server resp = elcm_request(irmc_info, method='DELETE', path='/sessionInformation/%s/remove' % session_id) if resp.status_code == 200: return elif resp.status_code == 404: raise ELCMSessionNotFound('Session "%s" does not exist' % session_id) else: raise scci.SCCIClientError(('Failed to remove session ' '"%(session)s" with error code %(error)s' % {'session': session_id, 'error': resp.status_code}))
python
def elcm_session_delete(irmc_info, session_id, terminate=False): """send an eLCM request to remove a session from the session list :param irmc_info: node info :param session_id: session id :param terminate: a running session must be terminated before removing :raises: ELCMSessionNotFound if the session does not exist :raises: SCCIClientError if SCCI failed """ # Terminate the session first if needs to if terminate: # Get session status to check session = elcm_session_get_status(irmc_info, session_id) status = session['Session']['Status'] # Terminate session if it is activated or running if status == 'running' or status == 'activated': elcm_session_terminate(irmc_info, session_id) # Send DELETE request to the server resp = elcm_request(irmc_info, method='DELETE', path='/sessionInformation/%s/remove' % session_id) if resp.status_code == 200: return elif resp.status_code == 404: raise ELCMSessionNotFound('Session "%s" does not exist' % session_id) else: raise scci.SCCIClientError(('Failed to remove session ' '"%(session)s" with error code %(error)s' % {'session': session_id, 'error': resp.status_code}))
[ "def", "elcm_session_delete", "(", "irmc_info", ",", "session_id", ",", "terminate", "=", "False", ")", ":", "# Terminate the session first if needs to", "if", "terminate", ":", "# Get session status to check", "session", "=", "elcm_session_get_status", "(", "irmc_info", ...
send an eLCM request to remove a session from the session list :param irmc_info: node info :param session_id: session id :param terminate: a running session must be terminated before removing :raises: ELCMSessionNotFound if the session does not exist :raises: SCCIClientError if SCCI failed
[ "send", "an", "eLCM", "request", "to", "remove", "a", "session", "from", "the", "session", "list" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L585-L617
openstack/python-scciclient
scciclient/irmc/elcm.py
_process_session_data
def _process_session_data(irmc_info, operation, session_id, session_timeout=BIOS_CONFIG_SESSION_TIMEOUT): """process session for Bios config backup/restore or RAID config operation :param irmc_info: node info :param operation: one of 'BACKUP_BIOS', 'RESTORE_BIOS' or 'CONFIG_RAID' :param session_id: session id :param session_timeout: session timeout :return: a dict with following values: { 'bios_config': <data in case of BACKUP/RESTORE_BIOS operation>, 'warning': <warning message if there is> } or { 'raid_config': <data of raid adapter profile>, 'warning': <warning message if there is> } """ session_expiration = time.time() + session_timeout while time.time() < session_expiration: # Get session status to check session = elcm_session_get_status(irmc_info=irmc_info, session_id=session_id) status = session['Session']['Status'] if status == 'running' or status == 'activated': # Sleep a bit time.sleep(5) elif status == 'terminated regularly': result = {} if operation == 'BACKUP_BIOS': # Bios profile is created, get the data now result['bios_config'] = elcm_profile_get( irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) elif operation == 'RESTORE_BIOS': # Bios config applied successfully pass elif operation == 'CONFIG_RAID': # Getting raid config result['raid_config'] = elcm_profile_get(irmc_info, PROFILE_RAID_CONFIG) # Cleanup operation by deleting related session and profile. # In case of error, report it as warning instead of error. try: elcm_session_delete(irmc_info=irmc_info, session_id=session_id, terminate=True) if operation == 'CONFIG_RAID': return result elcm_profile_delete(irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) except scci.SCCIError as e: result['warning'] = e return result else: # Error occurred, get session log to see what happened session_log = elcm_session_get_log(irmc_info=irmc_info, session_id=session_id) raise scci.SCCIClientError( ('Failed to %(operation)s config. ' 'Session log is "%(session_log)s".' % {'operation': operation, 'session_log': jsonutils.dumps(session_log)})) else: raise ELCMSessionTimeout( ('Failed to %(operation)s config. ' 'Session %(session_id)s log is timeout.' % {'operation': operation, 'session_id': session_id}))
python
def _process_session_data(irmc_info, operation, session_id, session_timeout=BIOS_CONFIG_SESSION_TIMEOUT): """process session for Bios config backup/restore or RAID config operation :param irmc_info: node info :param operation: one of 'BACKUP_BIOS', 'RESTORE_BIOS' or 'CONFIG_RAID' :param session_id: session id :param session_timeout: session timeout :return: a dict with following values: { 'bios_config': <data in case of BACKUP/RESTORE_BIOS operation>, 'warning': <warning message if there is> } or { 'raid_config': <data of raid adapter profile>, 'warning': <warning message if there is> } """ session_expiration = time.time() + session_timeout while time.time() < session_expiration: # Get session status to check session = elcm_session_get_status(irmc_info=irmc_info, session_id=session_id) status = session['Session']['Status'] if status == 'running' or status == 'activated': # Sleep a bit time.sleep(5) elif status == 'terminated regularly': result = {} if operation == 'BACKUP_BIOS': # Bios profile is created, get the data now result['bios_config'] = elcm_profile_get( irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) elif operation == 'RESTORE_BIOS': # Bios config applied successfully pass elif operation == 'CONFIG_RAID': # Getting raid config result['raid_config'] = elcm_profile_get(irmc_info, PROFILE_RAID_CONFIG) # Cleanup operation by deleting related session and profile. # In case of error, report it as warning instead of error. try: elcm_session_delete(irmc_info=irmc_info, session_id=session_id, terminate=True) if operation == 'CONFIG_RAID': return result elcm_profile_delete(irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) except scci.SCCIError as e: result['warning'] = e return result else: # Error occurred, get session log to see what happened session_log = elcm_session_get_log(irmc_info=irmc_info, session_id=session_id) raise scci.SCCIClientError( ('Failed to %(operation)s config. ' 'Session log is "%(session_log)s".' % {'operation': operation, 'session_log': jsonutils.dumps(session_log)})) else: raise ELCMSessionTimeout( ('Failed to %(operation)s config. ' 'Session %(session_id)s log is timeout.' % {'operation': operation, 'session_id': session_id}))
[ "def", "_process_session_data", "(", "irmc_info", ",", "operation", ",", "session_id", ",", "session_timeout", "=", "BIOS_CONFIG_SESSION_TIMEOUT", ")", ":", "session_expiration", "=", "time", ".", "time", "(", ")", "+", "session_timeout", "while", "time", ".", "ti...
process session for Bios config backup/restore or RAID config operation :param irmc_info: node info :param operation: one of 'BACKUP_BIOS', 'RESTORE_BIOS' or 'CONFIG_RAID' :param session_id: session id :param session_timeout: session timeout :return: a dict with following values: { 'bios_config': <data in case of BACKUP/RESTORE_BIOS operation>, 'warning': <warning message if there is> } or { 'raid_config': <data of raid adapter profile>, 'warning': <warning message if there is> }
[ "process", "session", "for", "Bios", "config", "backup", "/", "restore", "or", "RAID", "config", "operation" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L620-L698
openstack/python-scciclient
scciclient/irmc/elcm.py
backup_bios_config
def backup_bios_config(irmc_info): """backup current bios configuration This function sends a BACKUP BIOS request to the server. Then when the bios config data are ready for retrieving, it will return the data to the caller. Note that this operation may take time. :param irmc_info: node info :return: a dict with following values: { 'bios_config': <bios config data>, 'warning': <warning message if there is> } """ # 1. Make sure there is no BiosConfig profile in the store try: # Get the profile first, if not found, then an exception # will be raised. elcm_profile_get(irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) # Profile found, delete it elcm_profile_delete(irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) except ELCMProfileNotFound: # Ignore this error as it's not an error in this case pass # 2. Send request to create a new profile for BiosConfig session = elcm_profile_create(irmc_info=irmc_info, param_path=PARAM_PATH_BIOS_CONFIG) # 3. Profile creation is in progress, we monitor the session session_timeout = irmc_info.get('irmc_bios_session_timeout', BIOS_CONFIG_SESSION_TIMEOUT) return _process_session_data( irmc_info=irmc_info, operation='BACKUP_BIOS', session_id=session['Session']['Id'], session_timeout=session_timeout)
python
def backup_bios_config(irmc_info): """backup current bios configuration This function sends a BACKUP BIOS request to the server. Then when the bios config data are ready for retrieving, it will return the data to the caller. Note that this operation may take time. :param irmc_info: node info :return: a dict with following values: { 'bios_config': <bios config data>, 'warning': <warning message if there is> } """ # 1. Make sure there is no BiosConfig profile in the store try: # Get the profile first, if not found, then an exception # will be raised. elcm_profile_get(irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) # Profile found, delete it elcm_profile_delete(irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) except ELCMProfileNotFound: # Ignore this error as it's not an error in this case pass # 2. Send request to create a new profile for BiosConfig session = elcm_profile_create(irmc_info=irmc_info, param_path=PARAM_PATH_BIOS_CONFIG) # 3. Profile creation is in progress, we monitor the session session_timeout = irmc_info.get('irmc_bios_session_timeout', BIOS_CONFIG_SESSION_TIMEOUT) return _process_session_data( irmc_info=irmc_info, operation='BACKUP_BIOS', session_id=session['Session']['Id'], session_timeout=session_timeout)
[ "def", "backup_bios_config", "(", "irmc_info", ")", ":", "# 1. Make sure there is no BiosConfig profile in the store", "try", ":", "# Get the profile first, if not found, then an exception", "# will be raised.", "elcm_profile_get", "(", "irmc_info", "=", "irmc_info", ",", "profile_...
backup current bios configuration This function sends a BACKUP BIOS request to the server. Then when the bios config data are ready for retrieving, it will return the data to the caller. Note that this operation may take time. :param irmc_info: node info :return: a dict with following values: { 'bios_config': <bios config data>, 'warning': <warning message if there is> }
[ "backup", "current", "bios", "configuration" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L701-L739
openstack/python-scciclient
scciclient/irmc/elcm.py
restore_bios_config
def restore_bios_config(irmc_info, bios_config): """restore bios configuration This function sends a RESTORE BIOS request to the server. Then when the bios is ready for restoring, it will apply the provided settings and return. Note that this operation may take time. :param irmc_info: node info :param bios_config: bios config """ def _process_bios_config(): try: if isinstance(bios_config, dict): input_data = bios_config else: input_data = jsonutils.loads(bios_config) # The input data must contain flag "@Processing":"execute" in the # equivalent section. bios_cfg = input_data['Server']['SystemConfig']['BiosConfig'] bios_cfg['@Processing'] = 'execute' return input_data except (TypeError, ValueError, KeyError): raise scci.SCCIInvalidInputError( ('Invalid input bios config "%s".' % bios_config)) # 1. Parse the bios config and create the input data input_data = _process_bios_config() # 2. Make sure there is no BiosConfig profile in the store try: # Get the profile first, if not found, then an exception # will be raised. elcm_profile_get(irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) # Profile found, delete it elcm_profile_delete(irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) except ELCMProfileNotFound: # Ignore this error as it's not an error in this case pass # 3. Send a request to apply the param values session = elcm_profile_set(irmc_info=irmc_info, input_data=input_data) # 4. Param values applying is in progress, we monitor the session session_timeout = irmc_info.get('irmc_bios_session_timeout', BIOS_CONFIG_SESSION_TIMEOUT) _process_session_data(irmc_info=irmc_info, operation='RESTORE_BIOS', session_id=session['Session']['Id'], session_timeout=session_timeout)
python
def restore_bios_config(irmc_info, bios_config): """restore bios configuration This function sends a RESTORE BIOS request to the server. Then when the bios is ready for restoring, it will apply the provided settings and return. Note that this operation may take time. :param irmc_info: node info :param bios_config: bios config """ def _process_bios_config(): try: if isinstance(bios_config, dict): input_data = bios_config else: input_data = jsonutils.loads(bios_config) # The input data must contain flag "@Processing":"execute" in the # equivalent section. bios_cfg = input_data['Server']['SystemConfig']['BiosConfig'] bios_cfg['@Processing'] = 'execute' return input_data except (TypeError, ValueError, KeyError): raise scci.SCCIInvalidInputError( ('Invalid input bios config "%s".' % bios_config)) # 1. Parse the bios config and create the input data input_data = _process_bios_config() # 2. Make sure there is no BiosConfig profile in the store try: # Get the profile first, if not found, then an exception # will be raised. elcm_profile_get(irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) # Profile found, delete it elcm_profile_delete(irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) except ELCMProfileNotFound: # Ignore this error as it's not an error in this case pass # 3. Send a request to apply the param values session = elcm_profile_set(irmc_info=irmc_info, input_data=input_data) # 4. Param values applying is in progress, we monitor the session session_timeout = irmc_info.get('irmc_bios_session_timeout', BIOS_CONFIG_SESSION_TIMEOUT) _process_session_data(irmc_info=irmc_info, operation='RESTORE_BIOS', session_id=session['Session']['Id'], session_timeout=session_timeout)
[ "def", "restore_bios_config", "(", "irmc_info", ",", "bios_config", ")", ":", "def", "_process_bios_config", "(", ")", ":", "try", ":", "if", "isinstance", "(", "bios_config", ",", "dict", ")", ":", "input_data", "=", "bios_config", "else", ":", "input_data", ...
restore bios configuration This function sends a RESTORE BIOS request to the server. Then when the bios is ready for restoring, it will apply the provided settings and return. Note that this operation may take time. :param irmc_info: node info :param bios_config: bios config
[ "restore", "bios", "configuration" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L742-L797
openstack/python-scciclient
scciclient/irmc/elcm.py
get_secure_boot_mode
def get_secure_boot_mode(irmc_info): """Get the status if secure boot is enabled or not. :param irmc_info: node info. :raises: SecureBootConfigNotFound, if there is no configuration for secure boot mode in the bios. :return: True if secure boot mode is enabled on the node, False otherwise. """ result = backup_bios_config(irmc_info=irmc_info) try: bioscfg = result['bios_config']['Server']['SystemConfig']['BiosConfig'] return bioscfg['SecurityConfig']['SecureBootControlEnabled'] except KeyError: msg = ("Failed to get secure boot mode from server %s. Upgrading iRMC " "firmware may resolve this issue." % irmc_info['irmc_address']) raise SecureBootConfigNotFound(msg)
python
def get_secure_boot_mode(irmc_info): """Get the status if secure boot is enabled or not. :param irmc_info: node info. :raises: SecureBootConfigNotFound, if there is no configuration for secure boot mode in the bios. :return: True if secure boot mode is enabled on the node, False otherwise. """ result = backup_bios_config(irmc_info=irmc_info) try: bioscfg = result['bios_config']['Server']['SystemConfig']['BiosConfig'] return bioscfg['SecurityConfig']['SecureBootControlEnabled'] except KeyError: msg = ("Failed to get secure boot mode from server %s. Upgrading iRMC " "firmware may resolve this issue." % irmc_info['irmc_address']) raise SecureBootConfigNotFound(msg)
[ "def", "get_secure_boot_mode", "(", "irmc_info", ")", ":", "result", "=", "backup_bios_config", "(", "irmc_info", "=", "irmc_info", ")", "try", ":", "bioscfg", "=", "result", "[", "'bios_config'", "]", "[", "'Server'", "]", "[", "'SystemConfig'", "]", "[", "...
Get the status if secure boot is enabled or not. :param irmc_info: node info. :raises: SecureBootConfigNotFound, if there is no configuration for secure boot mode in the bios. :return: True if secure boot mode is enabled on the node, False otherwise.
[ "Get", "the", "status", "if", "secure", "boot", "is", "enabled", "or", "not", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L800-L818
openstack/python-scciclient
scciclient/irmc/elcm.py
set_secure_boot_mode
def set_secure_boot_mode(irmc_info, enable): """Enable/Disable secure boot on the server. :param irmc_info: node info :param enable: True, if secure boot needs to be enabled for next boot, else False. """ bios_config_data = { 'Server': { '@Version': '1.01', 'SystemConfig': { 'BiosConfig': { '@Version': '1.01', 'SecurityConfig': { 'SecureBootControlEnabled': enable } } } } } restore_bios_config(irmc_info=irmc_info, bios_config=bios_config_data)
python
def set_secure_boot_mode(irmc_info, enable): """Enable/Disable secure boot on the server. :param irmc_info: node info :param enable: True, if secure boot needs to be enabled for next boot, else False. """ bios_config_data = { 'Server': { '@Version': '1.01', 'SystemConfig': { 'BiosConfig': { '@Version': '1.01', 'SecurityConfig': { 'SecureBootControlEnabled': enable } } } } } restore_bios_config(irmc_info=irmc_info, bios_config=bios_config_data)
[ "def", "set_secure_boot_mode", "(", "irmc_info", ",", "enable", ")", ":", "bios_config_data", "=", "{", "'Server'", ":", "{", "'@Version'", ":", "'1.01'", ",", "'SystemConfig'", ":", "{", "'BiosConfig'", ":", "{", "'@Version'", ":", "'1.01'", ",", "'SecurityCo...
Enable/Disable secure boot on the server. :param irmc_info: node info :param enable: True, if secure boot needs to be enabled for next boot, else False.
[ "Enable", "/", "Disable", "secure", "boot", "on", "the", "server", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L821-L842
openstack/python-scciclient
scciclient/irmc/elcm.py
_update_raid_input_data
def _update_raid_input_data(target_raid_config, raid_input): """Process raid input data. :param target_raid_config: node raid info :param raid_input: raid information for creating via eLCM :raises ELCMValueError: raise msg if wrong input :return: raid_input: raid input data which create raid configuration { "Server":{ "HWConfigurationIrmc":{ "@Processing":"execute", "Adapters":{ "RAIDAdapter":[ { "@AdapterId":"RAIDAdapter0", "@ConfigurationType":"Addressing", "LogicalDrives":{ "LogicalDrive":[ { "@Number":0, "@Action":"Create", "RaidLevel":"1" } ] } } ] }, "@Version":"1.00" }, "@Version":"1.01" } } """ logical_disk_list = target_raid_config['logical_disks'] raid_input['Server']['HWConfigurationIrmc'].update({'@Processing': 'execute'}) array_info = raid_input['Server']['HWConfigurationIrmc']['Adapters'][ 'RAIDAdapter'][0] array_info['LogicalDrives'] = {'LogicalDrive': []} array_info['Arrays'] = {'Array': []} for i, logical_disk in enumerate(logical_disk_list): physical_disks = logical_disk.get('physical_disks') # Auto create logical drive along with random physical disks. # Allow auto create along with raid 10 and raid 50 # with specific physical drive. if not physical_disks or logical_disk['raid_level'] \ in ('10', '50'): array_info['LogicalDrives']['LogicalDrive'].append( {'@Action': 'Create', 'RaidLevel': logical_disk['raid_level'], 'InitMode': 'slow'}) array_info['LogicalDrives']['LogicalDrive'][i].update({ "@Number": i}) else: # Create array disks with specific physical servers arrays = { "@Number": i, "@ConfigurationType": "Setting", "PhysicalDiskRefs": { "PhysicalDiskRef": [] } } lo_drive = { "@Number": i, "@Action": "Create", "RaidLevel": "", "ArrayRefs": { "ArrayRef": [ ] }, "InitMode": "slow" } array_info['Arrays']['Array'].append(arrays) array_info['LogicalDrives']['LogicalDrive'].append(lo_drive) lo_drive.update({'RaidLevel': logical_disk['raid_level']}) lo_drive['ArrayRefs']['ArrayRef'].append({"@Number": i}) for element in logical_disk['physical_disks']: arrays['PhysicalDiskRefs']['PhysicalDiskRef'].append({ '@Number': element}) if logical_disk['size_gb'] != "MAX": # Ensure correctly order these items in dict size = collections.OrderedDict() size['@Unit'] = 'GB' size['#text'] = logical_disk['size_gb'] array_info['LogicalDrives']['LogicalDrive'][i]['Size'] = size return raid_input
python
def _update_raid_input_data(target_raid_config, raid_input): """Process raid input data. :param target_raid_config: node raid info :param raid_input: raid information for creating via eLCM :raises ELCMValueError: raise msg if wrong input :return: raid_input: raid input data which create raid configuration { "Server":{ "HWConfigurationIrmc":{ "@Processing":"execute", "Adapters":{ "RAIDAdapter":[ { "@AdapterId":"RAIDAdapter0", "@ConfigurationType":"Addressing", "LogicalDrives":{ "LogicalDrive":[ { "@Number":0, "@Action":"Create", "RaidLevel":"1" } ] } } ] }, "@Version":"1.00" }, "@Version":"1.01" } } """ logical_disk_list = target_raid_config['logical_disks'] raid_input['Server']['HWConfigurationIrmc'].update({'@Processing': 'execute'}) array_info = raid_input['Server']['HWConfigurationIrmc']['Adapters'][ 'RAIDAdapter'][0] array_info['LogicalDrives'] = {'LogicalDrive': []} array_info['Arrays'] = {'Array': []} for i, logical_disk in enumerate(logical_disk_list): physical_disks = logical_disk.get('physical_disks') # Auto create logical drive along with random physical disks. # Allow auto create along with raid 10 and raid 50 # with specific physical drive. if not physical_disks or logical_disk['raid_level'] \ in ('10', '50'): array_info['LogicalDrives']['LogicalDrive'].append( {'@Action': 'Create', 'RaidLevel': logical_disk['raid_level'], 'InitMode': 'slow'}) array_info['LogicalDrives']['LogicalDrive'][i].update({ "@Number": i}) else: # Create array disks with specific physical servers arrays = { "@Number": i, "@ConfigurationType": "Setting", "PhysicalDiskRefs": { "PhysicalDiskRef": [] } } lo_drive = { "@Number": i, "@Action": "Create", "RaidLevel": "", "ArrayRefs": { "ArrayRef": [ ] }, "InitMode": "slow" } array_info['Arrays']['Array'].append(arrays) array_info['LogicalDrives']['LogicalDrive'].append(lo_drive) lo_drive.update({'RaidLevel': logical_disk['raid_level']}) lo_drive['ArrayRefs']['ArrayRef'].append({"@Number": i}) for element in logical_disk['physical_disks']: arrays['PhysicalDiskRefs']['PhysicalDiskRef'].append({ '@Number': element}) if logical_disk['size_gb'] != "MAX": # Ensure correctly order these items in dict size = collections.OrderedDict() size['@Unit'] = 'GB' size['#text'] = logical_disk['size_gb'] array_info['LogicalDrives']['LogicalDrive'][i]['Size'] = size return raid_input
[ "def", "_update_raid_input_data", "(", "target_raid_config", ",", "raid_input", ")", ":", "logical_disk_list", "=", "target_raid_config", "[", "'logical_disks'", "]", "raid_input", "[", "'Server'", "]", "[", "'HWConfigurationIrmc'", "]", ".", "update", "(", "{", "'@...
Process raid input data. :param target_raid_config: node raid info :param raid_input: raid information for creating via eLCM :raises ELCMValueError: raise msg if wrong input :return: raid_input: raid input data which create raid configuration { "Server":{ "HWConfigurationIrmc":{ "@Processing":"execute", "Adapters":{ "RAIDAdapter":[ { "@AdapterId":"RAIDAdapter0", "@ConfigurationType":"Addressing", "LogicalDrives":{ "LogicalDrive":[ { "@Number":0, "@Action":"Create", "RaidLevel":"1" } ] } } ] }, "@Version":"1.00" }, "@Version":"1.01" } }
[ "Process", "raid", "input", "data", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L845-L941
openstack/python-scciclient
scciclient/irmc/elcm.py
_get_existing_logical_drives
def _get_existing_logical_drives(raid_adapter): """Collect existing logical drives on the server. :param raid_adapter: raid adapter info :returns: existing_logical_drives: get logical drive on server """ existing_logical_drives = [] logical_drives = raid_adapter['Server']['HWConfigurationIrmc'][ 'Adapters']['RAIDAdapter'][0].get('LogicalDrives') if logical_drives is not None: for drive in logical_drives['LogicalDrive']: existing_logical_drives.append(drive['@Number']) return existing_logical_drives
python
def _get_existing_logical_drives(raid_adapter): """Collect existing logical drives on the server. :param raid_adapter: raid adapter info :returns: existing_logical_drives: get logical drive on server """ existing_logical_drives = [] logical_drives = raid_adapter['Server']['HWConfigurationIrmc'][ 'Adapters']['RAIDAdapter'][0].get('LogicalDrives') if logical_drives is not None: for drive in logical_drives['LogicalDrive']: existing_logical_drives.append(drive['@Number']) return existing_logical_drives
[ "def", "_get_existing_logical_drives", "(", "raid_adapter", ")", ":", "existing_logical_drives", "=", "[", "]", "logical_drives", "=", "raid_adapter", "[", "'Server'", "]", "[", "'HWConfigurationIrmc'", "]", "[", "'Adapters'", "]", "[", "'RAIDAdapter'", "]", "[", ...
Collect existing logical drives on the server. :param raid_adapter: raid adapter info :returns: existing_logical_drives: get logical drive on server
[ "Collect", "existing", "logical", "drives", "on", "the", "server", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L958-L971
openstack/python-scciclient
scciclient/irmc/elcm.py
_create_raid_adapter_profile
def _create_raid_adapter_profile(irmc_info): """Attempt delete exist adapter then create new raid adapter on the server. :param irmc_info: node info :returns: result: a dict with following values: { 'raid_config': <data of raid adapter profile>, 'warning': <warning message if there is> } """ try: # Attempt erase exist adapter on BM Server elcm_profile_delete(irmc_info, PROFILE_RAID_CONFIG) except ELCMProfileNotFound: # Ignore this error as it's not an error in this case pass session = elcm_profile_create(irmc_info, PARAM_PATH_RAID_CONFIG) # Monitoring currently session until done. session_timeout = irmc_info.get('irmc_raid_session_timeout', RAID_CONFIG_SESSION_TIMEOUT) return _process_session_data(irmc_info, 'CONFIG_RAID', session['Session']['Id'], session_timeout)
python
def _create_raid_adapter_profile(irmc_info): """Attempt delete exist adapter then create new raid adapter on the server. :param irmc_info: node info :returns: result: a dict with following values: { 'raid_config': <data of raid adapter profile>, 'warning': <warning message if there is> } """ try: # Attempt erase exist adapter on BM Server elcm_profile_delete(irmc_info, PROFILE_RAID_CONFIG) except ELCMProfileNotFound: # Ignore this error as it's not an error in this case pass session = elcm_profile_create(irmc_info, PARAM_PATH_RAID_CONFIG) # Monitoring currently session until done. session_timeout = irmc_info.get('irmc_raid_session_timeout', RAID_CONFIG_SESSION_TIMEOUT) return _process_session_data(irmc_info, 'CONFIG_RAID', session['Session']['Id'], session_timeout)
[ "def", "_create_raid_adapter_profile", "(", "irmc_info", ")", ":", "try", ":", "# Attempt erase exist adapter on BM Server", "elcm_profile_delete", "(", "irmc_info", ",", "PROFILE_RAID_CONFIG", ")", "except", "ELCMProfileNotFound", ":", "# Ignore this error as it's not an error i...
Attempt delete exist adapter then create new raid adapter on the server. :param irmc_info: node info :returns: result: a dict with following values: { 'raid_config': <data of raid adapter profile>, 'warning': <warning message if there is> }
[ "Attempt", "delete", "exist", "adapter", "then", "create", "new", "raid", "adapter", "on", "the", "server", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L974-L1000
openstack/python-scciclient
scciclient/irmc/elcm.py
create_raid_configuration
def create_raid_configuration(irmc_info, target_raid_config): """Process raid_input then perform raid configuration into server. :param irmc_info: node info :param target_raid_config: node raid information """ if len(target_raid_config['logical_disks']) < 1: raise ELCMValueError(message="logical_disks must not be empty") # Check RAID config in the new RAID adapter. Must be erased before # create new RAID config. raid_adapter = get_raid_adapter(irmc_info) logical_drives = raid_adapter['Server']['HWConfigurationIrmc'][ 'Adapters']['RAIDAdapter'][0].get('LogicalDrives') session_timeout = irmc_info.get('irmc_raid_session_timeout', RAID_CONFIG_SESSION_TIMEOUT) if logical_drives is not None: # Delete exist logical drives in server. # NOTE(trungnv): Wait session complete and raise error if # delete raid config during FGI(Foreground Initialization) in-progress # in previous mechanism. delete_raid_configuration(irmc_info) # Updating raid adapter profile after deleted profile. raid_adapter = get_raid_adapter(irmc_info) # Create raid configuration based on target_raid_config of node raid_input = _update_raid_input_data(target_raid_config, raid_adapter) session = elcm_profile_set(irmc_info, raid_input) # Monitoring raid creation session until done. _process_session_data(irmc_info, 'CONFIG_RAID', session['Session']['Id'], session_timeout)
python
def create_raid_configuration(irmc_info, target_raid_config): """Process raid_input then perform raid configuration into server. :param irmc_info: node info :param target_raid_config: node raid information """ if len(target_raid_config['logical_disks']) < 1: raise ELCMValueError(message="logical_disks must not be empty") # Check RAID config in the new RAID adapter. Must be erased before # create new RAID config. raid_adapter = get_raid_adapter(irmc_info) logical_drives = raid_adapter['Server']['HWConfigurationIrmc'][ 'Adapters']['RAIDAdapter'][0].get('LogicalDrives') session_timeout = irmc_info.get('irmc_raid_session_timeout', RAID_CONFIG_SESSION_TIMEOUT) if logical_drives is not None: # Delete exist logical drives in server. # NOTE(trungnv): Wait session complete and raise error if # delete raid config during FGI(Foreground Initialization) in-progress # in previous mechanism. delete_raid_configuration(irmc_info) # Updating raid adapter profile after deleted profile. raid_adapter = get_raid_adapter(irmc_info) # Create raid configuration based on target_raid_config of node raid_input = _update_raid_input_data(target_raid_config, raid_adapter) session = elcm_profile_set(irmc_info, raid_input) # Monitoring raid creation session until done. _process_session_data(irmc_info, 'CONFIG_RAID', session['Session']['Id'], session_timeout)
[ "def", "create_raid_configuration", "(", "irmc_info", ",", "target_raid_config", ")", ":", "if", "len", "(", "target_raid_config", "[", "'logical_disks'", "]", ")", "<", "1", ":", "raise", "ELCMValueError", "(", "message", "=", "\"logical_disks must not be empty\"", ...
Process raid_input then perform raid configuration into server. :param irmc_info: node info :param target_raid_config: node raid information
[ "Process", "raid_input", "then", "perform", "raid", "configuration", "into", "server", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L1003-L1035
openstack/python-scciclient
scciclient/irmc/elcm.py
delete_raid_configuration
def delete_raid_configuration(irmc_info): """Delete whole raid configuration or one of logical drive on the server. :param irmc_info: node info """ # Attempt to get raid configuration on BM Server raid_adapter = get_raid_adapter(irmc_info) existing_logical_drives = _get_existing_logical_drives(raid_adapter) # Ironic requires delete_configuration first. Will pass if blank raid # configuration in server. if not existing_logical_drives: return raid_adapter['Server']['HWConfigurationIrmc'].update({ '@Processing': 'execute'}) logical_drive = raid_adapter['Server']['HWConfigurationIrmc'][ 'Adapters']['RAIDAdapter'][0]['LogicalDrives']['LogicalDrive'] for drive in logical_drive: drive['@Action'] = 'Delete' # Attempt to delete logical drive in the raid config session = elcm_profile_set(irmc_info, raid_adapter) # Monitoring raid config delete session until done. session_timeout = irmc_info.get('irmc_raid_session_timeout', RAID_CONFIG_SESSION_TIMEOUT) _process_session_data(irmc_info, 'CONFIG_RAID', session['Session']['Id'], session_timeout) # Attempt to delete raid adapter elcm_profile_delete(irmc_info, PROFILE_RAID_CONFIG)
python
def delete_raid_configuration(irmc_info): """Delete whole raid configuration or one of logical drive on the server. :param irmc_info: node info """ # Attempt to get raid configuration on BM Server raid_adapter = get_raid_adapter(irmc_info) existing_logical_drives = _get_existing_logical_drives(raid_adapter) # Ironic requires delete_configuration first. Will pass if blank raid # configuration in server. if not existing_logical_drives: return raid_adapter['Server']['HWConfigurationIrmc'].update({ '@Processing': 'execute'}) logical_drive = raid_adapter['Server']['HWConfigurationIrmc'][ 'Adapters']['RAIDAdapter'][0]['LogicalDrives']['LogicalDrive'] for drive in logical_drive: drive['@Action'] = 'Delete' # Attempt to delete logical drive in the raid config session = elcm_profile_set(irmc_info, raid_adapter) # Monitoring raid config delete session until done. session_timeout = irmc_info.get('irmc_raid_session_timeout', RAID_CONFIG_SESSION_TIMEOUT) _process_session_data(irmc_info, 'CONFIG_RAID', session['Session']['Id'], session_timeout) # Attempt to delete raid adapter elcm_profile_delete(irmc_info, PROFILE_RAID_CONFIG)
[ "def", "delete_raid_configuration", "(", "irmc_info", ")", ":", "# Attempt to get raid configuration on BM Server", "raid_adapter", "=", "get_raid_adapter", "(", "irmc_info", ")", "existing_logical_drives", "=", "_get_existing_logical_drives", "(", "raid_adapter", ")", "# Ironi...
Delete whole raid configuration or one of logical drive on the server. :param irmc_info: node info
[ "Delete", "whole", "raid", "configuration", "or", "one", "of", "logical", "drive", "on", "the", "server", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L1038-L1067
openstack/python-scciclient
scciclient/irmc/elcm.py
set_bios_configuration
def set_bios_configuration(irmc_info, settings): """Set BIOS configurations on the server. :param irmc_info: node info :param settings: Dictionary containing the BIOS configuration. :raise: BiosConfigNotFound, if there is wrong settings for bios configuration. """ bios_config_data = { 'Server': { 'SystemConfig': { 'BiosConfig': {} } } } versions = elcm_profile_get_versions(irmc_info) server_version = versions['Server'].get('@Version') bios_version = \ versions['Server']['SystemConfig']['BiosConfig'].get('@Version') if server_version: bios_config_data['Server']['@Version'] = server_version if bios_version: bios_config_data['Server']['SystemConfig']['BiosConfig']['@Version'] = \ bios_version configs = {} for setting_param in settings: setting_name = setting_param.get("name") setting_value = setting_param.get("value") # Revert-conversion from a string of True/False to boolean. # It will be raise failed if put "True" or "False" string value. if isinstance(setting_value, six.string_types): if setting_value.lower() == "true": setting_value = True elif setting_value.lower() == "false": setting_value = False try: type_config, config = BIOS_CONFIGURATION_DICTIONARY[ setting_name].split("_") if type_config in configs.keys(): configs[type_config][config] = setting_value else: configs.update({type_config: {config: setting_value}}) except KeyError: raise BiosConfigNotFound("Invalid BIOS setting: %s" % setting_param) bios_config_data['Server']['SystemConfig']['BiosConfig'].update(configs) restore_bios_config(irmc_info, bios_config_data)
python
def set_bios_configuration(irmc_info, settings): """Set BIOS configurations on the server. :param irmc_info: node info :param settings: Dictionary containing the BIOS configuration. :raise: BiosConfigNotFound, if there is wrong settings for bios configuration. """ bios_config_data = { 'Server': { 'SystemConfig': { 'BiosConfig': {} } } } versions = elcm_profile_get_versions(irmc_info) server_version = versions['Server'].get('@Version') bios_version = \ versions['Server']['SystemConfig']['BiosConfig'].get('@Version') if server_version: bios_config_data['Server']['@Version'] = server_version if bios_version: bios_config_data['Server']['SystemConfig']['BiosConfig']['@Version'] = \ bios_version configs = {} for setting_param in settings: setting_name = setting_param.get("name") setting_value = setting_param.get("value") # Revert-conversion from a string of True/False to boolean. # It will be raise failed if put "True" or "False" string value. if isinstance(setting_value, six.string_types): if setting_value.lower() == "true": setting_value = True elif setting_value.lower() == "false": setting_value = False try: type_config, config = BIOS_CONFIGURATION_DICTIONARY[ setting_name].split("_") if type_config in configs.keys(): configs[type_config][config] = setting_value else: configs.update({type_config: {config: setting_value}}) except KeyError: raise BiosConfigNotFound("Invalid BIOS setting: %s" % setting_param) bios_config_data['Server']['SystemConfig']['BiosConfig'].update(configs) restore_bios_config(irmc_info, bios_config_data)
[ "def", "set_bios_configuration", "(", "irmc_info", ",", "settings", ")", ":", "bios_config_data", "=", "{", "'Server'", ":", "{", "'SystemConfig'", ":", "{", "'BiosConfig'", ":", "{", "}", "}", "}", "}", "versions", "=", "elcm_profile_get_versions", "(", "irmc...
Set BIOS configurations on the server. :param irmc_info: node info :param settings: Dictionary containing the BIOS configuration. :raise: BiosConfigNotFound, if there is wrong settings for bios configuration.
[ "Set", "BIOS", "configurations", "on", "the", "server", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L1070-L1120
openstack/python-scciclient
scciclient/irmc/elcm.py
get_bios_settings
def get_bios_settings(irmc_info): """Get the current BIOS settings on the server :param irmc_info: node info. :returns: a list of dictionary BIOS settings """ bios_config = backup_bios_config(irmc_info)['bios_config'] bios_config_data = bios_config['Server']['SystemConfig']['BiosConfig'] settings = [] # TODO(trungnv): Allow working with multi levels of BIOS dictionary. for setting_param in BIOS_CONFIGURATION_DICTIONARY: type_config, config = BIOS_CONFIGURATION_DICTIONARY[ setting_param].split("_") if config in bios_config_data.get(type_config, {}): value = six.text_type(bios_config_data[type_config][config]) settings.append({'name': setting_param, 'value': value}) return settings
python
def get_bios_settings(irmc_info): """Get the current BIOS settings on the server :param irmc_info: node info. :returns: a list of dictionary BIOS settings """ bios_config = backup_bios_config(irmc_info)['bios_config'] bios_config_data = bios_config['Server']['SystemConfig']['BiosConfig'] settings = [] # TODO(trungnv): Allow working with multi levels of BIOS dictionary. for setting_param in BIOS_CONFIGURATION_DICTIONARY: type_config, config = BIOS_CONFIGURATION_DICTIONARY[ setting_param].split("_") if config in bios_config_data.get(type_config, {}): value = six.text_type(bios_config_data[type_config][config]) settings.append({'name': setting_param, 'value': value}) return settings
[ "def", "get_bios_settings", "(", "irmc_info", ")", ":", "bios_config", "=", "backup_bios_config", "(", "irmc_info", ")", "[", "'bios_config'", "]", "bios_config_data", "=", "bios_config", "[", "'Server'", "]", "[", "'SystemConfig'", "]", "[", "'BiosConfig'", "]", ...
Get the current BIOS settings on the server :param irmc_info: node info. :returns: a list of dictionary BIOS settings
[ "Get", "the", "current", "BIOS", "settings", "on", "the", "server" ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L1123-L1141
playpauseandstop/rororo
rororo/aio.py
add_resource_context
def add_resource_context(router: web.AbstractRouter, url_prefix: str = None, name_prefix: str = None) -> Iterator[Any]: """Context manager for adding resources for given router. Main goal of context manager to easify process of adding resources with routes to the router. This also allow to reduce amount of repeats, when supplying new resources by reusing URL & name prefixes for all routes inside context manager. Behind the scene, context manager returns a function which calls:: resource = router.add_resource(url, name) resource.add_route(method, handler) **Usage**:: with add_resource_context(app.router, '/api', 'api') as add_resource: add_resource('/', get=views.index) add_resource('/news', get=views.list_news, post=views.create_news) :param router: Route to add resources to. :param url_prefix: If supplied prepend this prefix to each resource URL. :param name_prefix: If supplied prepend this prefix to each resource name. """ def add_resource(url: str, get: View = None, *, name: str = None, **kwargs: Any) -> web.Resource: """Inner function to create resource and add necessary routes to it. Support adding routes of all methods, supported by aiohttp, as GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS/*, e.g., :: with add_resource_context(app.router) as add_resource: add_resource('/', get=views.get, post=views.post) add_resource('/wildcard', **{'*': views.wildcard}) :param url: Resource URL. If ``url_prefix`` setup in context it will be prepended to URL with ``/``. :param get: GET handler. Only handler to be setup without explicit call. :param name: Resource name. :type name: str :rtype: aiohttp.web.Resource """ kwargs['get'] = get if url_prefix: url = '/'.join((url_prefix.rstrip('/'), url.lstrip('/'))) if not name and get: name = get.__name__ if name_prefix and name: name = '.'.join((name_prefix.rstrip('.'), name.lstrip('.'))) resource = router.add_resource(url, name=name) for method, handler in kwargs.items(): if handler is None: continue resource.add_route(method.upper(), handler) return resource yield add_resource
python
def add_resource_context(router: web.AbstractRouter, url_prefix: str = None, name_prefix: str = None) -> Iterator[Any]: """Context manager for adding resources for given router. Main goal of context manager to easify process of adding resources with routes to the router. This also allow to reduce amount of repeats, when supplying new resources by reusing URL & name prefixes for all routes inside context manager. Behind the scene, context manager returns a function which calls:: resource = router.add_resource(url, name) resource.add_route(method, handler) **Usage**:: with add_resource_context(app.router, '/api', 'api') as add_resource: add_resource('/', get=views.index) add_resource('/news', get=views.list_news, post=views.create_news) :param router: Route to add resources to. :param url_prefix: If supplied prepend this prefix to each resource URL. :param name_prefix: If supplied prepend this prefix to each resource name. """ def add_resource(url: str, get: View = None, *, name: str = None, **kwargs: Any) -> web.Resource: """Inner function to create resource and add necessary routes to it. Support adding routes of all methods, supported by aiohttp, as GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS/*, e.g., :: with add_resource_context(app.router) as add_resource: add_resource('/', get=views.get, post=views.post) add_resource('/wildcard', **{'*': views.wildcard}) :param url: Resource URL. If ``url_prefix`` setup in context it will be prepended to URL with ``/``. :param get: GET handler. Only handler to be setup without explicit call. :param name: Resource name. :type name: str :rtype: aiohttp.web.Resource """ kwargs['get'] = get if url_prefix: url = '/'.join((url_prefix.rstrip('/'), url.lstrip('/'))) if not name and get: name = get.__name__ if name_prefix and name: name = '.'.join((name_prefix.rstrip('.'), name.lstrip('.'))) resource = router.add_resource(url, name=name) for method, handler in kwargs.items(): if handler is None: continue resource.add_route(method.upper(), handler) return resource yield add_resource
[ "def", "add_resource_context", "(", "router", ":", "web", ".", "AbstractRouter", ",", "url_prefix", ":", "str", "=", "None", ",", "name_prefix", ":", "str", "=", "None", ")", "->", "Iterator", "[", "Any", "]", ":", "def", "add_resource", "(", "url", ":",...
Context manager for adding resources for given router. Main goal of context manager to easify process of adding resources with routes to the router. This also allow to reduce amount of repeats, when supplying new resources by reusing URL & name prefixes for all routes inside context manager. Behind the scene, context manager returns a function which calls:: resource = router.add_resource(url, name) resource.add_route(method, handler) **Usage**:: with add_resource_context(app.router, '/api', 'api') as add_resource: add_resource('/', get=views.index) add_resource('/news', get=views.list_news, post=views.create_news) :param router: Route to add resources to. :param url_prefix: If supplied prepend this prefix to each resource URL. :param name_prefix: If supplied prepend this prefix to each resource name.
[ "Context", "manager", "for", "adding", "resources", "for", "given", "router", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/aio.py#L42-L110
playpauseandstop/rororo
rororo/aio.py
parse_aioredis_url
def parse_aioredis_url(url: str) -> DictStrAny: """ Convert Redis URL string to dict suitable to pass to ``aioredis.create_redis(...)`` call. **Usage**:: async def connect_redis(url=None): url = url or 'redis://localhost:6379/0' return await create_redis(**get_aioredis_parts(url)) :param url: URL to access Redis instance, started with ``redis://``. """ parts = urlparse(url) db = parts.path[1:] or None # type: Optional[Union[str, int]] if db: db = int(db) return { 'address': (parts.hostname, parts.port or 6379), 'db': db, 'password': parts.password}
python
def parse_aioredis_url(url: str) -> DictStrAny: """ Convert Redis URL string to dict suitable to pass to ``aioredis.create_redis(...)`` call. **Usage**:: async def connect_redis(url=None): url = url or 'redis://localhost:6379/0' return await create_redis(**get_aioredis_parts(url)) :param url: URL to access Redis instance, started with ``redis://``. """ parts = urlparse(url) db = parts.path[1:] or None # type: Optional[Union[str, int]] if db: db = int(db) return { 'address': (parts.hostname, parts.port or 6379), 'db': db, 'password': parts.password}
[ "def", "parse_aioredis_url", "(", "url", ":", "str", ")", "->", "DictStrAny", ":", "parts", "=", "urlparse", "(", "url", ")", "db", "=", "parts", ".", "path", "[", "1", ":", "]", "or", "None", "# type: Optional[Union[str, int]]", "if", "db", ":", "db", ...
Convert Redis URL string to dict suitable to pass to ``aioredis.create_redis(...)`` call. **Usage**:: async def connect_redis(url=None): url = url or 'redis://localhost:6379/0' return await create_redis(**get_aioredis_parts(url)) :param url: URL to access Redis instance, started with ``redis://``.
[ "Convert", "Redis", "URL", "string", "to", "dict", "suitable", "to", "pass", "to", "aioredis", ".", "create_redis", "(", "...", ")", "call", "." ]
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/aio.py#L124-L146
OSSOS/MOP
src/ossos/core/ossos/mpc_time.py
TimeMPC.str_kwargs
def str_kwargs(self): """ Generator that yields a dict of values corresponding to the calendar date and time for the internal JD values. Here we provide the additional 'fracday' element needed by 'mpc' format """ iys, ims, ids, ihmsfs = sofa_time.jd_dtf(self.scale.upper() .encode('utf8'), 6, self.jd1, self.jd2) # Get the str_fmt element of the first allowed output subformat _, _, str_fmt = self._select_subfmts(self.out_subfmt)[0] yday = None has_yday = '{yday:' in str_fmt or False for iy, im, iday, ihmsf in itertools.izip(iys, ims, ids, ihmsfs): ihr, imin, isec, ifracsec = ihmsf if has_yday: yday = datetime(iy, im, iday).timetuple().tm_yday # MPC uses day fraction as time part of datetime fracday = (((((ifracsec / 1000000.0 + isec) / 60.0 + imin) / 60.0) + ihr) / 24.0) * (10 ** 6) fracday = '{0:06g}'.format(fracday)[0:self.precision] #format_str = '{{0:g}}'.format(self.precision) #fracday = int(format_str.format(fracday)) yield dict(year=int(iy), mon=int(im), day=int(iday), hour=int(ihr), min=int(imin), sec=int(isec), fracsec=int(ifracsec), yday=yday, fracday=fracday)
python
def str_kwargs(self): """ Generator that yields a dict of values corresponding to the calendar date and time for the internal JD values. Here we provide the additional 'fracday' element needed by 'mpc' format """ iys, ims, ids, ihmsfs = sofa_time.jd_dtf(self.scale.upper() .encode('utf8'), 6, self.jd1, self.jd2) # Get the str_fmt element of the first allowed output subformat _, _, str_fmt = self._select_subfmts(self.out_subfmt)[0] yday = None has_yday = '{yday:' in str_fmt or False for iy, im, iday, ihmsf in itertools.izip(iys, ims, ids, ihmsfs): ihr, imin, isec, ifracsec = ihmsf if has_yday: yday = datetime(iy, im, iday).timetuple().tm_yday # MPC uses day fraction as time part of datetime fracday = (((((ifracsec / 1000000.0 + isec) / 60.0 + imin) / 60.0) + ihr) / 24.0) * (10 ** 6) fracday = '{0:06g}'.format(fracday)[0:self.precision] #format_str = '{{0:g}}'.format(self.precision) #fracday = int(format_str.format(fracday)) yield dict(year=int(iy), mon=int(im), day=int(iday), hour=int(ihr), min=int(imin), sec=int(isec), fracsec=int(ifracsec), yday=yday, fracday=fracday)
[ "def", "str_kwargs", "(", "self", ")", ":", "iys", ",", "ims", ",", "ids", ",", "ihmsfs", "=", "sofa_time", ".", "jd_dtf", "(", "self", ".", "scale", ".", "upper", "(", ")", ".", "encode", "(", "'utf8'", ")", ",", "6", ",", "self", ".", "jd1", ...
Generator that yields a dict of values corresponding to the calendar date and time for the internal JD values. Here we provide the additional 'fracday' element needed by 'mpc' format
[ "Generator", "that", "yields", "a", "dict", "of", "values", "corresponding", "to", "the", "calendar", "date", "and", "time", "for", "the", "internal", "JD", "values", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mpc_time.py#L82-L111
JohnVinyard/zounds
zounds/spectral/sliding_window.py
oggvorbis
def oggvorbis(s): """ This is taken from the ogg vorbis spec (http://xiph.org/vorbis/doc/Vorbis_I_spec.html) :param s: the total length of the window, in samples """ try: s = np.arange(s) except TypeError: s = np.arange(s[0]) i = np.sin((s + .5) / len(s) * np.pi) ** 2 f = np.sin(.5 * np.pi * i) return f * (1. / f.max())
python
def oggvorbis(s): """ This is taken from the ogg vorbis spec (http://xiph.org/vorbis/doc/Vorbis_I_spec.html) :param s: the total length of the window, in samples """ try: s = np.arange(s) except TypeError: s = np.arange(s[0]) i = np.sin((s + .5) / len(s) * np.pi) ** 2 f = np.sin(.5 * np.pi * i) return f * (1. / f.max())
[ "def", "oggvorbis", "(", "s", ")", ":", "try", ":", "s", "=", "np", ".", "arange", "(", "s", ")", "except", "TypeError", ":", "s", "=", "np", ".", "arange", "(", "s", "[", "0", "]", ")", "i", "=", "np", ".", "sin", "(", "(", "s", "+", ".5...
This is taken from the ogg vorbis spec (http://xiph.org/vorbis/doc/Vorbis_I_spec.html) :param s: the total length of the window, in samples
[ "This", "is", "taken", "from", "the", "ogg", "vorbis", "spec", "(", "http", ":", "//", "xiph", ".", "org", "/", "vorbis", "/", "doc", "/", "Vorbis_I_spec", ".", "html", ")" ]
train
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/sliding_window.py#L7-L21
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/focus.py
FocusCalculator.convert_source_location
def convert_source_location(self, source_reading, reference_reading): """ Converts the source (x, y) location from reading into the coordinate system of reference_reading. """ offset_x, offset_y = reference_reading.get_coordinate_offset(source_reading) focus = source_reading.x + offset_x, source_reading.y + offset_y return focus
python
def convert_source_location(self, source_reading, reference_reading): """ Converts the source (x, y) location from reading into the coordinate system of reference_reading. """ offset_x, offset_y = reference_reading.get_coordinate_offset(source_reading) focus = source_reading.x + offset_x, source_reading.y + offset_y return focus
[ "def", "convert_source_location", "(", "self", ",", "source_reading", ",", "reference_reading", ")", ":", "offset_x", ",", "offset_y", "=", "reference_reading", ".", "get_coordinate_offset", "(", "source_reading", ")", "focus", "=", "source_reading", ".", "x", "+", ...
Converts the source (x, y) location from reading into the coordinate system of reference_reading.
[ "Converts", "the", "source", "(", "x", "y", ")", "location", "from", "reading", "into", "the", "coordinate", "system", "of", "reference_reading", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/focus.py#L5-L12
OSSOS/MOP
src/ossos/core/ossos/downloads/cutouts/focus.py
SingletFocusCalculator.calculate_focus
def calculate_focus(self, reading): """ Determines what the focal point of the downloaded image should be. Returns: focal_point: (x, y) The location of the source in the middle observation, in the coordinate system of the current source reading. """ middle_index = len(self.source.get_readings()) // 2 middle_reading = self.source.get_reading(middle_index) return self.convert_source_location(middle_reading, reading)
python
def calculate_focus(self, reading): """ Determines what the focal point of the downloaded image should be. Returns: focal_point: (x, y) The location of the source in the middle observation, in the coordinate system of the current source reading. """ middle_index = len(self.source.get_readings()) // 2 middle_reading = self.source.get_reading(middle_index) return self.convert_source_location(middle_reading, reading)
[ "def", "calculate_focus", "(", "self", ",", "reading", ")", ":", "middle_index", "=", "len", "(", "self", ".", "source", ".", "get_readings", "(", ")", ")", "//", "2", "middle_reading", "=", "self", ".", "source", ".", "get_reading", "(", "middle_index", ...
Determines what the focal point of the downloaded image should be. Returns: focal_point: (x, y) The location of the source in the middle observation, in the coordinate system of the current source reading.
[ "Determines", "what", "the", "focal", "point", "of", "the", "downloaded", "image", "should", "be", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/focus.py#L24-L35
OSSOS/MOP
src/ossos/plotting/scripts/rose_topdown.py
top_down_SolarSystem
def top_down_SolarSystem(discoveries, inner_limit=6, # truncate at 8 AU to show that we don't have sensitivity in close extent=83, # extend to 83 AU as indicative only, sensitivity is to ~300 AU plot_discoveries=None, plot_colossos=False, plot_blocks=None, plot_galaxy=False, feature_blocks=None, plot_Ijiraq=False, # detected Ijiraq at 9.80 AU in the 13AE block label_blocks=True, savefilename=None): """ Plot the OSSOS discoveries on a top-down Solar System showing the position of Neptune and model TNOs. Discoveries are plotted each at their time of discovery according to the value in the Version Release. Coordinates should be polar to account for RA hours, radial axis is in AU. :return: a saved plot This is not a 'projection' of the particles into any common plane. Each wedge is a different latitude above the plane, but inside each wedge it is heliocentric distance vs RA. That is fine. It's just important to know that if someone asks we know this is NOT (for example) a projection of each object down into the ecliptic. A very minor future long-term improvement is that the galactic plane wedge is not (I don't think) symmetric around 18h and 6h. I think that lines of constant (say 15 degree galactic lat) are centered a little off (I think the wedge would 'twist' a little bit counter-clockwise). I am not absolutely sure along the ecliptic where the b= +/- 15 degree lines are but I don't think they are symmetric? """ fig = plt.figure(figsize=(6, 6)) rect = [0.01, 0.01, 0.95, .95] # the plot occupies not all the figspace ax1 = fig.add_axes(rect, polar=True, frameon=False) # theta (RA) is zero at E, increases anticlockwise ax1.set_aspect('equal') ax1.set_rlim(0, extent) ax1.set_rgrids([20, 40, 60, 80], labels=["", "", '20 au', '40 au', '60 au', '80 au'], angle=190, alpha=0.45) # angle = 308 ax1.yaxis.set_major_locator(MultipleLocator(20)) ax1.xaxis.set_major_locator(MultipleLocator(math.radians(15))) # every 2 hours ax1.grid(axis='x', color='k', linestyle='--', alpha=0.2) ax1.set_xticklabels(['', '0h', "", '2h', "", '4h', "", '6h', "", '8h', "", '10h', "", '12h', "", '14h', "", '16h', "", '18h', "", '20h', "", '22h', "", ], # ""]) # str(r)+'h' for r in range(-1,24)], # ['', '0h', '2h', '4h', '6h', '8h', '10h', '12h', '14h', '16h', '18h', '20h', '22h'], color='b', alpha=0.6) # otherwise they get in the way if plot_galaxy: # plot exclusion zones due to Galactic plane: RAs indicate where bar starts, rather than its centre angle width = math.radians(3 * 15) plt.bar(math.radians(4.5 * 15), extent, width=width, color=plot_fanciness.ALMOST_BLACK, linewidth=0, alpha=0.2) plt.bar(math.radians(16.5 * 15), extent, width=width, color=plot_fanciness.ALMOST_BLACK, linewidth=0, alpha=0.2) ax1.annotate('galactic plane', (math.radians(6.9 * 15), extent - 15), size=10, color='k', alpha=0.45) ax1.annotate(' galactic plane\navoidance zone', (math.radians(16.9 * 15), extent - 12), size=10, color='k', alpha=0.45) # again RAs indicate where bar starts, so subtract half the block width from the block centrepoints # and approximate blocks as math.radians(7) degrees wide. for blockname, block in parameters.BLOCKS.items(): if plot_blocks: if blockname in plot_blocks: if feature_blocks is not None and blockname in feature_blocks: colour = 'm' #'#E47833' alpha = 0.25 else: colour = 'b' alpha = 0.1 # if blockname.startswith('13') or blockname.startswith('14'): width = math.radians(7) # the 3 x 7 field layout # else: # width = math.radians(5) # the 4 x 5 field layout # cmap = plt.get_cmap('Blues') # if blockname.endswith('AO'): # colour = '#E47833' # alpha = 0.17 # cmap = plt.get_cmap('Oranges') # colorbrewer.sequential.Oranges_3.mpl_colors ax1.bar(ephem.hours(block["RA"]) - math.radians(3.5), extent, linewidth=0.1, width=width, bottom=inner_limit, zorder=0, color=colour, alpha=alpha) if label_blocks: ax1.annotate(blockname[3], (ephem.hours(block["RA"]) + math.radians(0.36), extent - 3.), size=15, color='b') # No optional on these just yet plot_planets_plus_Pluto(ax1) ra, dist, hlat, Hmag = parsers.synthetic_model_kbos(kbotype='resonant', arrays=True, maglimit=24.7) # can't plot Hmag as marker size in current setup. ax1.scatter(ra, dist, marker='o', s=2, facecolor=plot_fanciness.ALMOST_BLACK, edgecolor=plot_fanciness.ALMOST_BLACK, linewidth=0.1, alpha=0.12, zorder=1) if plot_discoveries is not None: plot_ossos_discoveries(ax1, discoveries, plot_discoveries, plot_colossos=plot_colossos) # special detection in 13AE: Saturn's moon Ijiraq at 2013-04-09 shows inner limit of sensitivity. if plot_Ijiraq: # Position from Horizons as it's excluded from the list of detections ax1.scatter(ephem.hours('14 29 46.57'), 9.805, marker='o', s=4, facecolor='b', edgecolor=plot_fanciness.ALMOST_BLACK, linewidth=0.15, alpha=0.8) plt.draw() if savefilename is not None: outfile = '{}.pdf'.format(savefilename) else: outfile = 'topdown_RA_d_OSSOS_v{}.pdf'.format(parameters.RELEASE_VERSION) plt.savefig(outfile, transparent=True, bbox_inches='tight') return
python
def top_down_SolarSystem(discoveries, inner_limit=6, # truncate at 8 AU to show that we don't have sensitivity in close extent=83, # extend to 83 AU as indicative only, sensitivity is to ~300 AU plot_discoveries=None, plot_colossos=False, plot_blocks=None, plot_galaxy=False, feature_blocks=None, plot_Ijiraq=False, # detected Ijiraq at 9.80 AU in the 13AE block label_blocks=True, savefilename=None): """ Plot the OSSOS discoveries on a top-down Solar System showing the position of Neptune and model TNOs. Discoveries are plotted each at their time of discovery according to the value in the Version Release. Coordinates should be polar to account for RA hours, radial axis is in AU. :return: a saved plot This is not a 'projection' of the particles into any common plane. Each wedge is a different latitude above the plane, but inside each wedge it is heliocentric distance vs RA. That is fine. It's just important to know that if someone asks we know this is NOT (for example) a projection of each object down into the ecliptic. A very minor future long-term improvement is that the galactic plane wedge is not (I don't think) symmetric around 18h and 6h. I think that lines of constant (say 15 degree galactic lat) are centered a little off (I think the wedge would 'twist' a little bit counter-clockwise). I am not absolutely sure along the ecliptic where the b= +/- 15 degree lines are but I don't think they are symmetric? """ fig = plt.figure(figsize=(6, 6)) rect = [0.01, 0.01, 0.95, .95] # the plot occupies not all the figspace ax1 = fig.add_axes(rect, polar=True, frameon=False) # theta (RA) is zero at E, increases anticlockwise ax1.set_aspect('equal') ax1.set_rlim(0, extent) ax1.set_rgrids([20, 40, 60, 80], labels=["", "", '20 au', '40 au', '60 au', '80 au'], angle=190, alpha=0.45) # angle = 308 ax1.yaxis.set_major_locator(MultipleLocator(20)) ax1.xaxis.set_major_locator(MultipleLocator(math.radians(15))) # every 2 hours ax1.grid(axis='x', color='k', linestyle='--', alpha=0.2) ax1.set_xticklabels(['', '0h', "", '2h', "", '4h', "", '6h', "", '8h', "", '10h', "", '12h', "", '14h', "", '16h', "", '18h', "", '20h', "", '22h', "", ], # ""]) # str(r)+'h' for r in range(-1,24)], # ['', '0h', '2h', '4h', '6h', '8h', '10h', '12h', '14h', '16h', '18h', '20h', '22h'], color='b', alpha=0.6) # otherwise they get in the way if plot_galaxy: # plot exclusion zones due to Galactic plane: RAs indicate where bar starts, rather than its centre angle width = math.radians(3 * 15) plt.bar(math.radians(4.5 * 15), extent, width=width, color=plot_fanciness.ALMOST_BLACK, linewidth=0, alpha=0.2) plt.bar(math.radians(16.5 * 15), extent, width=width, color=plot_fanciness.ALMOST_BLACK, linewidth=0, alpha=0.2) ax1.annotate('galactic plane', (math.radians(6.9 * 15), extent - 15), size=10, color='k', alpha=0.45) ax1.annotate(' galactic plane\navoidance zone', (math.radians(16.9 * 15), extent - 12), size=10, color='k', alpha=0.45) # again RAs indicate where bar starts, so subtract half the block width from the block centrepoints # and approximate blocks as math.radians(7) degrees wide. for blockname, block in parameters.BLOCKS.items(): if plot_blocks: if blockname in plot_blocks: if feature_blocks is not None and blockname in feature_blocks: colour = 'm' #'#E47833' alpha = 0.25 else: colour = 'b' alpha = 0.1 # if blockname.startswith('13') or blockname.startswith('14'): width = math.radians(7) # the 3 x 7 field layout # else: # width = math.radians(5) # the 4 x 5 field layout # cmap = plt.get_cmap('Blues') # if blockname.endswith('AO'): # colour = '#E47833' # alpha = 0.17 # cmap = plt.get_cmap('Oranges') # colorbrewer.sequential.Oranges_3.mpl_colors ax1.bar(ephem.hours(block["RA"]) - math.radians(3.5), extent, linewidth=0.1, width=width, bottom=inner_limit, zorder=0, color=colour, alpha=alpha) if label_blocks: ax1.annotate(blockname[3], (ephem.hours(block["RA"]) + math.radians(0.36), extent - 3.), size=15, color='b') # No optional on these just yet plot_planets_plus_Pluto(ax1) ra, dist, hlat, Hmag = parsers.synthetic_model_kbos(kbotype='resonant', arrays=True, maglimit=24.7) # can't plot Hmag as marker size in current setup. ax1.scatter(ra, dist, marker='o', s=2, facecolor=plot_fanciness.ALMOST_BLACK, edgecolor=plot_fanciness.ALMOST_BLACK, linewidth=0.1, alpha=0.12, zorder=1) if plot_discoveries is not None: plot_ossos_discoveries(ax1, discoveries, plot_discoveries, plot_colossos=plot_colossos) # special detection in 13AE: Saturn's moon Ijiraq at 2013-04-09 shows inner limit of sensitivity. if plot_Ijiraq: # Position from Horizons as it's excluded from the list of detections ax1.scatter(ephem.hours('14 29 46.57'), 9.805, marker='o', s=4, facecolor='b', edgecolor=plot_fanciness.ALMOST_BLACK, linewidth=0.15, alpha=0.8) plt.draw() if savefilename is not None: outfile = '{}.pdf'.format(savefilename) else: outfile = 'topdown_RA_d_OSSOS_v{}.pdf'.format(parameters.RELEASE_VERSION) plt.savefig(outfile, transparent=True, bbox_inches='tight') return
[ "def", "top_down_SolarSystem", "(", "discoveries", ",", "inner_limit", "=", "6", ",", "# truncate at 8 AU to show that we don't have sensitivity in close", "extent", "=", "83", ",", "# extend to 83 AU as indicative only, sensitivity is to ~300 AU", "plot_discoveries", "=", "None", ...
Plot the OSSOS discoveries on a top-down Solar System showing the position of Neptune and model TNOs. Discoveries are plotted each at their time of discovery according to the value in the Version Release. Coordinates should be polar to account for RA hours, radial axis is in AU. :return: a saved plot This is not a 'projection' of the particles into any common plane. Each wedge is a different latitude above the plane, but inside each wedge it is heliocentric distance vs RA. That is fine. It's just important to know that if someone asks we know this is NOT (for example) a projection of each object down into the ecliptic. A very minor future long-term improvement is that the galactic plane wedge is not (I don't think) symmetric around 18h and 6h. I think that lines of constant (say 15 degree galactic lat) are centered a little off (I think the wedge would 'twist' a little bit counter-clockwise). I am not absolutely sure along the ecliptic where the b= +/- 15 degree lines are but I don't think they are symmetric?
[ "Plot", "the", "OSSOS", "discoveries", "on", "a", "top", "-", "down", "Solar", "System", "showing", "the", "position", "of", "Neptune", "and", "model", "TNOs", ".", "Discoveries", "are", "plotted", "each", "at", "their", "time", "of", "discovery", "according...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/plotting/scripts/rose_topdown.py#L22-L129
OSSOS/MOP
src/ossos/plotting/scripts/rose_topdown.py
plot_ossos_discoveries
def plot_ossos_discoveries(ax, discoveries, plot_discoveries, plot_colossos=False, split_plutinos=False): """ plotted at their discovery locations, provided by the Version Releases in decimal degrees. """ fc = ['b', '#E47833', 'k'] alpha = [0.85, 0.6, 1.] marker = ['o', 'd'] size = [7, 25] plottable = [] # Which blocks' discoveries to include? for d in discoveries: for n in plot_discoveries: if d['object'].startswith(n): # can for sure be better, but this hack works. Need to get where going plottable.append(d) # Hack to get in the O15BD objects # directory_name = '/Users/bannisterm/Dropbox/OSSOS/measure3/ossin/D_tmp/' # kbos = parsers.ossos_discoveries(directory_name, all_objects=False, data_release=None) # for kbo in kbos: # plottable_kbo = {'RAdeg': kbo.discovery.coordinate.ra.to_string(unit=units.degree, sep=':'), # 'dist': kbo.orbit.distance.value} # plottable.append(plottable_kbo) if plot_colossos: fainter = [] colossos = [] for n in plottable: if n['object'] in parameters.COLOSSOS: colossos.append(n) else: fainter.append(n) plot_ossos_points(fainter, ax, marker[0], size[0], fc[0], alpha[1], 1) plot_ossos_points(colossos, ax, marker[1], size[1], fc[2], alpha[2], 2) elif split_plutinos: # plutino_index = np.where((plottable['cl'] == 'res') & (plottable['j'] == 3) & (plottable['k'] == 2)) raise NotImplementedError else: plot_ossos_points(plottable, ax, marker[0], size[0], fc[0], alpha[0], 2) return
python
def plot_ossos_discoveries(ax, discoveries, plot_discoveries, plot_colossos=False, split_plutinos=False): """ plotted at their discovery locations, provided by the Version Releases in decimal degrees. """ fc = ['b', '#E47833', 'k'] alpha = [0.85, 0.6, 1.] marker = ['o', 'd'] size = [7, 25] plottable = [] # Which blocks' discoveries to include? for d in discoveries: for n in plot_discoveries: if d['object'].startswith(n): # can for sure be better, but this hack works. Need to get where going plottable.append(d) # Hack to get in the O15BD objects # directory_name = '/Users/bannisterm/Dropbox/OSSOS/measure3/ossin/D_tmp/' # kbos = parsers.ossos_discoveries(directory_name, all_objects=False, data_release=None) # for kbo in kbos: # plottable_kbo = {'RAdeg': kbo.discovery.coordinate.ra.to_string(unit=units.degree, sep=':'), # 'dist': kbo.orbit.distance.value} # plottable.append(plottable_kbo) if plot_colossos: fainter = [] colossos = [] for n in plottable: if n['object'] in parameters.COLOSSOS: colossos.append(n) else: fainter.append(n) plot_ossos_points(fainter, ax, marker[0], size[0], fc[0], alpha[1], 1) plot_ossos_points(colossos, ax, marker[1], size[1], fc[2], alpha[2], 2) elif split_plutinos: # plutino_index = np.where((plottable['cl'] == 'res') & (plottable['j'] == 3) & (plottable['k'] == 2)) raise NotImplementedError else: plot_ossos_points(plottable, ax, marker[0], size[0], fc[0], alpha[0], 2) return
[ "def", "plot_ossos_discoveries", "(", "ax", ",", "discoveries", ",", "plot_discoveries", ",", "plot_colossos", "=", "False", ",", "split_plutinos", "=", "False", ")", ":", "fc", "=", "[", "'b'", ",", "'#E47833'", ",", "'k'", "]", "alpha", "=", "[", "0.85",...
plotted at their discovery locations, provided by the Version Releases in decimal degrees.
[ "plotted", "at", "their", "discovery", "locations", "provided", "by", "the", "Version", "Releases", "in", "decimal", "degrees", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/plotting/scripts/rose_topdown.py#L165-L205
OSSOS/MOP
src/ossos/plotting/scripts/rose_topdown.py
orbit_fit_residuals
def orbit_fit_residuals(discoveries, blockID='O13AE'): """Brett: What are relevant and stunning are the actual orbit fit residuals for orbits with d(a)/a<1%. I would be happy with a simple histogram of all those numbers, although the 'tail' (probably blended and not yet completely flagged) should perhaps be excluded. There will be a pretty clear gaussian I would think, peaking near 0.07". """ ra_residuals = [] dec_residuals = [] ressum = [] for i, orbit in enumerate(discoveries): if (orbit.da / orbit.a) < 0.01: print i, len(discoveries), orbit.observations[0].provisional_name, orbit.da / orbit.a res = orbit.residuals.split('\n') for r in res: rr = r.split(' ') if (len(rr) > 1) and not (rr[0].startswith('!')): ra_residuals.append(float(r.split(' ')[4])) dec_residuals.append(float(r.split(' ')[5])) ressum.append(1000 * (float(r.split(' ')[4]) ** 2 + float(r.split(' ')[5]) ** 2)) plt.figure(figsize=(6, 6)) bins = [r for r in range(-25, 150, 25)] n, bins, patches = plt.hist(ressum, histtype='step', color='b', bins=bins, label='$dra^{2}+ddec^{2}$') # midpoints = [r/1000. for r in range(-350,350,50)] # popt, pcov = curve_fit(gaussian, midpoints, n) # print 'a', popt[0], 'mu', popt[1], 'sigma', popt[2] # xm = np.linspace(-.375, .375, 100) # 100 evenly spaced points # plt.plot(xm, gaussian(xm, popt[0], popt[1], popt[2]), ls='--', color='#E47833', linewidth=2) # sigma = r'$\sigma = %.2f \pm %.2f$' % (popt[2], np.sqrt(pcov[2, 2])) # plt.annotate(sigma, (0.12, 50), color='#E47833') plt.xlim((-25, 150)) # sufficient for 13AE data plt.ylabel('observations of orbits with d(a)/a < 1% (i.e 3-5 month arcs)') plt.xlabel('orbit fit residuals (milliarcsec)') plt.legend() # clean_legend() plt.draw() outfile = 'orbit_fit_residuals_13AE_corrected' plt.savefig('/ossos_sequence/'+ outfile + '.pdf', transparent=True) return
python
def orbit_fit_residuals(discoveries, blockID='O13AE'): """Brett: What are relevant and stunning are the actual orbit fit residuals for orbits with d(a)/a<1%. I would be happy with a simple histogram of all those numbers, although the 'tail' (probably blended and not yet completely flagged) should perhaps be excluded. There will be a pretty clear gaussian I would think, peaking near 0.07". """ ra_residuals = [] dec_residuals = [] ressum = [] for i, orbit in enumerate(discoveries): if (orbit.da / orbit.a) < 0.01: print i, len(discoveries), orbit.observations[0].provisional_name, orbit.da / orbit.a res = orbit.residuals.split('\n') for r in res: rr = r.split(' ') if (len(rr) > 1) and not (rr[0].startswith('!')): ra_residuals.append(float(r.split(' ')[4])) dec_residuals.append(float(r.split(' ')[5])) ressum.append(1000 * (float(r.split(' ')[4]) ** 2 + float(r.split(' ')[5]) ** 2)) plt.figure(figsize=(6, 6)) bins = [r for r in range(-25, 150, 25)] n, bins, patches = plt.hist(ressum, histtype='step', color='b', bins=bins, label='$dra^{2}+ddec^{2}$') # midpoints = [r/1000. for r in range(-350,350,50)] # popt, pcov = curve_fit(gaussian, midpoints, n) # print 'a', popt[0], 'mu', popt[1], 'sigma', popt[2] # xm = np.linspace(-.375, .375, 100) # 100 evenly spaced points # plt.plot(xm, gaussian(xm, popt[0], popt[1], popt[2]), ls='--', color='#E47833', linewidth=2) # sigma = r'$\sigma = %.2f \pm %.2f$' % (popt[2], np.sqrt(pcov[2, 2])) # plt.annotate(sigma, (0.12, 50), color='#E47833') plt.xlim((-25, 150)) # sufficient for 13AE data plt.ylabel('observations of orbits with d(a)/a < 1% (i.e 3-5 month arcs)') plt.xlabel('orbit fit residuals (milliarcsec)') plt.legend() # clean_legend() plt.draw() outfile = 'orbit_fit_residuals_13AE_corrected' plt.savefig('/ossos_sequence/'+ outfile + '.pdf', transparent=True) return
[ "def", "orbit_fit_residuals", "(", "discoveries", ",", "blockID", "=", "'O13AE'", ")", ":", "ra_residuals", "=", "[", "]", "dec_residuals", "=", "[", "]", "ressum", "=", "[", "]", "for", "i", ",", "orbit", "in", "enumerate", "(", "discoveries", ")", ":",...
Brett: What are relevant and stunning are the actual orbit fit residuals for orbits with d(a)/a<1%. I would be happy with a simple histogram of all those numbers, although the 'tail' (probably blended and not yet completely flagged) should perhaps be excluded. There will be a pretty clear gaussian I would think, peaking near 0.07".
[ "Brett", ":", "What", "are", "relevant", "and", "stunning", "are", "the", "actual", "orbit", "fit", "residuals", "for", "orbits", "with", "d", "(", "a", ")", "/", "a<1%", ".", "I", "would", "be", "happy", "with", "a", "simple", "histogram", "of", "all"...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/plotting/scripts/rose_topdown.py#L247-L286
openstack/python-scciclient
scciclient/irmc/snmp.py
get_irmc_firmware_version
def get_irmc_firmware_version(snmp_client): """Get irmc firmware version of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of bmc name and irmc firmware version. """ try: bmc_name = snmp_client.get(BMC_NAME_OID) irmc_firm_ver = snmp_client.get(IRMC_FW_VERSION_OID) return ('%(bmc)s%(sep)s%(firm_ver)s' % {'bmc': bmc_name if bmc_name else '', 'firm_ver': irmc_firm_ver if irmc_firm_ver else '', 'sep': '-' if bmc_name and irmc_firm_ver else ''}) except SNMPFailure as e: raise SNMPIRMCFirmwareFailure( SNMP_FAILURE_MSG % ("GET IRMC FIRMWARE VERSION", e))
python
def get_irmc_firmware_version(snmp_client): """Get irmc firmware version of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of bmc name and irmc firmware version. """ try: bmc_name = snmp_client.get(BMC_NAME_OID) irmc_firm_ver = snmp_client.get(IRMC_FW_VERSION_OID) return ('%(bmc)s%(sep)s%(firm_ver)s' % {'bmc': bmc_name if bmc_name else '', 'firm_ver': irmc_firm_ver if irmc_firm_ver else '', 'sep': '-' if bmc_name and irmc_firm_ver else ''}) except SNMPFailure as e: raise SNMPIRMCFirmwareFailure( SNMP_FAILURE_MSG % ("GET IRMC FIRMWARE VERSION", e))
[ "def", "get_irmc_firmware_version", "(", "snmp_client", ")", ":", "try", ":", "bmc_name", "=", "snmp_client", ".", "get", "(", "BMC_NAME_OID", ")", "irmc_firm_ver", "=", "snmp_client", ".", "get", "(", "IRMC_FW_VERSION_OID", ")", "return", "(", "'%(bmc)s%(sep)s%(f...
Get irmc firmware version of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of bmc name and irmc firmware version.
[ "Get", "irmc", "firmware", "version", "of", "the", "node", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L69-L86
openstack/python-scciclient
scciclient/irmc/snmp.py
get_bios_firmware_version
def get_bios_firmware_version(snmp_client): """Get bios firmware version of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of bios firmware version. """ try: bios_firmware_version = snmp_client.get(BIOS_FW_VERSION_OID) return six.text_type(bios_firmware_version) except SNMPFailure as e: raise SNMPBIOSFirmwareFailure( SNMP_FAILURE_MSG % ("GET BIOS FIRMWARE VERSION", e))
python
def get_bios_firmware_version(snmp_client): """Get bios firmware version of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of bios firmware version. """ try: bios_firmware_version = snmp_client.get(BIOS_FW_VERSION_OID) return six.text_type(bios_firmware_version) except SNMPFailure as e: raise SNMPBIOSFirmwareFailure( SNMP_FAILURE_MSG % ("GET BIOS FIRMWARE VERSION", e))
[ "def", "get_bios_firmware_version", "(", "snmp_client", ")", ":", "try", ":", "bios_firmware_version", "=", "snmp_client", ".", "get", "(", "BIOS_FW_VERSION_OID", ")", "return", "six", ".", "text_type", "(", "bios_firmware_version", ")", "except", "SNMPFailure", "as...
Get bios firmware version of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of bios firmware version.
[ "Get", "bios", "firmware", "version", "of", "the", "node", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L89-L102
openstack/python-scciclient
scciclient/irmc/snmp.py
get_server_model
def get_server_model(snmp_client): """Get server model of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of server model. """ try: server_model = snmp_client.get(SERVER_MODEL_OID) return six.text_type(server_model) except SNMPFailure as e: raise SNMPServerModelFailure( SNMP_FAILURE_MSG % ("GET SERVER MODEL", e))
python
def get_server_model(snmp_client): """Get server model of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of server model. """ try: server_model = snmp_client.get(SERVER_MODEL_OID) return six.text_type(server_model) except SNMPFailure as e: raise SNMPServerModelFailure( SNMP_FAILURE_MSG % ("GET SERVER MODEL", e))
[ "def", "get_server_model", "(", "snmp_client", ")", ":", "try", ":", "server_model", "=", "snmp_client", ".", "get", "(", "SERVER_MODEL_OID", ")", "return", "six", ".", "text_type", "(", "server_model", ")", "except", "SNMPFailure", "as", "e", ":", "raise", ...
Get server model of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of server model.
[ "Get", "server", "model", "of", "the", "node", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L105-L118
openstack/python-scciclient
scciclient/irmc/snmp.py
SNMPClient._get_auth
def _get_auth(self): """Return the authorization data for an SNMP request. :returns: A :class:`pysnmp.entity.rfc3413.oneliner.cmdgen.CommunityData` object. """ if self.version == SNMP_V3: # Handling auth/encryption credentials is not (yet) supported. # This version supports a security name analogous to community. return cmdgen.UsmUserData(self.security) else: mp_model = 1 if self.version == SNMP_V2C else 0 return cmdgen.CommunityData(self.community, mpModel=mp_model)
python
def _get_auth(self): """Return the authorization data for an SNMP request. :returns: A :class:`pysnmp.entity.rfc3413.oneliner.cmdgen.CommunityData` object. """ if self.version == SNMP_V3: # Handling auth/encryption credentials is not (yet) supported. # This version supports a security name analogous to community. return cmdgen.UsmUserData(self.security) else: mp_model = 1 if self.version == SNMP_V2C else 0 return cmdgen.CommunityData(self.community, mpModel=mp_model)
[ "def", "_get_auth", "(", "self", ")", ":", "if", "self", ".", "version", "==", "SNMP_V3", ":", "# Handling auth/encryption credentials is not (yet) supported.", "# This version supports a security name analogous to community.", "return", "cmdgen", ".", "UsmUserData", "(", "se...
Return the authorization data for an SNMP request. :returns: A :class:`pysnmp.entity.rfc3413.oneliner.cmdgen.CommunityData` object.
[ "Return", "the", "authorization", "data", "for", "an", "SNMP", "request", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L138-L151
openstack/python-scciclient
scciclient/irmc/snmp.py
SNMPClient.get
def get(self, oid): """Use PySNMP to perform an SNMP GET operation on a single object. :param oid: The OID of the object to get. :raises: SNMPFailure if an SNMP request fails. :returns: The value of the requested object. """ try: results = self.cmd_gen.getCmd(self._get_auth(), self._get_transport(), oid) except snmp_error.PySnmpError as e: raise SNMPFailure(SNMP_FAILURE_MSG % ("GET", e)) error_indication, error_status, error_index, var_binds = results if error_indication: # SNMP engine-level error. raise SNMPFailure(SNMP_FAILURE_MSG % ("GET", error_indication)) if error_status: # SNMP PDU error. raise SNMPFailure( "SNMP operation '%(operation)s' failed: %(error)s at" " %(index)s" % {'operation': "GET", 'error': error_status.prettyPrint(), 'index': error_index and var_binds[int(error_index) - 1] or '?'}) # We only expect a single value back name, val = var_binds[0] return val
python
def get(self, oid): """Use PySNMP to perform an SNMP GET operation on a single object. :param oid: The OID of the object to get. :raises: SNMPFailure if an SNMP request fails. :returns: The value of the requested object. """ try: results = self.cmd_gen.getCmd(self._get_auth(), self._get_transport(), oid) except snmp_error.PySnmpError as e: raise SNMPFailure(SNMP_FAILURE_MSG % ("GET", e)) error_indication, error_status, error_index, var_binds = results if error_indication: # SNMP engine-level error. raise SNMPFailure(SNMP_FAILURE_MSG % ("GET", error_indication)) if error_status: # SNMP PDU error. raise SNMPFailure( "SNMP operation '%(operation)s' failed: %(error)s at" " %(index)s" % {'operation': "GET", 'error': error_status.prettyPrint(), 'index': error_index and var_binds[int(error_index) - 1] or '?'}) # We only expect a single value back name, val = var_binds[0] return val
[ "def", "get", "(", "self", ",", "oid", ")", ":", "try", ":", "results", "=", "self", ".", "cmd_gen", ".", "getCmd", "(", "self", ".", "_get_auth", "(", ")", ",", "self", ".", "_get_transport", "(", ")", ",", "oid", ")", "except", "snmp_error", ".",...
Use PySNMP to perform an SNMP GET operation on a single object. :param oid: The OID of the object to get. :raises: SNMPFailure if an SNMP request fails. :returns: The value of the requested object.
[ "Use", "PySNMP", "to", "perform", "an", "SNMP", "GET", "operation", "on", "a", "single", "object", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L165-L197
openstack/python-scciclient
scciclient/irmc/snmp.py
SNMPClient.get_next
def get_next(self, oid): """Use PySNMP to perform an SNMP GET NEXT operation on a table object. :param oid: The OID of the object to get. :raises: SNMPFailure if an SNMP request fails. :returns: A list of values of the requested table object. """ try: results = self.cmd_gen.nextCmd(self._get_auth(), self._get_transport(), oid) except snmp_error.PySnmpError as e: raise SNMPFailure(SNMP_FAILURE_MSG % ("GET_NEXT", e)) error_indication, error_status, error_index, var_binds = results if error_indication: # SNMP engine-level error. raise SNMPFailure( SNMP_FAILURE_MSG % ("GET_NEXT", error_indication)) if error_status: # SNMP PDU error. raise SNMPFailure( "SNMP operation '%(operation)s' failed: %(error)s at" " %(index)s" % {'operation': "GET_NEXT", 'error': error_status.prettyPrint(), 'index': error_index and var_binds[int(error_index) - 1] or '?'}) return [val for row in var_binds for name, val in row]
python
def get_next(self, oid): """Use PySNMP to perform an SNMP GET NEXT operation on a table object. :param oid: The OID of the object to get. :raises: SNMPFailure if an SNMP request fails. :returns: A list of values of the requested table object. """ try: results = self.cmd_gen.nextCmd(self._get_auth(), self._get_transport(), oid) except snmp_error.PySnmpError as e: raise SNMPFailure(SNMP_FAILURE_MSG % ("GET_NEXT", e)) error_indication, error_status, error_index, var_binds = results if error_indication: # SNMP engine-level error. raise SNMPFailure( SNMP_FAILURE_MSG % ("GET_NEXT", error_indication)) if error_status: # SNMP PDU error. raise SNMPFailure( "SNMP operation '%(operation)s' failed: %(error)s at" " %(index)s" % {'operation': "GET_NEXT", 'error': error_status.prettyPrint(), 'index': error_index and var_binds[int(error_index) - 1] or '?'}) return [val for row in var_binds for name, val in row]
[ "def", "get_next", "(", "self", ",", "oid", ")", ":", "try", ":", "results", "=", "self", ".", "cmd_gen", ".", "nextCmd", "(", "self", ".", "_get_auth", "(", ")", ",", "self", ".", "_get_transport", "(", ")", ",", "oid", ")", "except", "snmp_error", ...
Use PySNMP to perform an SNMP GET NEXT operation on a table object. :param oid: The OID of the object to get. :raises: SNMPFailure if an SNMP request fails. :returns: A list of values of the requested table object.
[ "Use", "PySNMP", "to", "perform", "an", "SNMP", "GET", "NEXT", "operation", "on", "a", "table", "object", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L199-L230
openstack/python-scciclient
scciclient/irmc/snmp.py
SNMPClient.set
def set(self, oid, value): """Use PySNMP to perform an SNMP SET operation on a single object. :param oid: The OID of the object to set. :param value: The value of the object to set. :raises: SNMPFailure if an SNMP request fails. """ try: results = self.cmd_gen.setCmd(self._get_auth(), self._get_transport(), (oid, value)) except snmp_error.PySnmpError as e: raise SNMPFailure(SNMP_FAILURE_MSG % ("SET", e)) error_indication, error_status, error_index, var_binds = results if error_indication: # SNMP engine-level error. raise SNMPFailure(SNMP_FAILURE_MSG % ("SET", error_indication)) if error_status: # SNMP PDU error. raise SNMPFailure( "SNMP operation '%(operation)s' failed: %(error)s at" " %(index)s" % {'operation': "SET", 'error': error_status.prettyPrint(), 'index': error_index and var_binds[int(error_index) - 1] or '?'})
python
def set(self, oid, value): """Use PySNMP to perform an SNMP SET operation on a single object. :param oid: The OID of the object to set. :param value: The value of the object to set. :raises: SNMPFailure if an SNMP request fails. """ try: results = self.cmd_gen.setCmd(self._get_auth(), self._get_transport(), (oid, value)) except snmp_error.PySnmpError as e: raise SNMPFailure(SNMP_FAILURE_MSG % ("SET", e)) error_indication, error_status, error_index, var_binds = results if error_indication: # SNMP engine-level error. raise SNMPFailure(SNMP_FAILURE_MSG % ("SET", error_indication)) if error_status: # SNMP PDU error. raise SNMPFailure( "SNMP operation '%(operation)s' failed: %(error)s at" " %(index)s" % {'operation': "SET", 'error': error_status.prettyPrint(), 'index': error_index and var_binds[int(error_index) - 1] or '?'})
[ "def", "set", "(", "self", ",", "oid", ",", "value", ")", ":", "try", ":", "results", "=", "self", ".", "cmd_gen", ".", "setCmd", "(", "self", ".", "_get_auth", "(", ")", ",", "self", ".", "_get_transport", "(", ")", ",", "(", "oid", ",", "value"...
Use PySNMP to perform an SNMP SET operation on a single object. :param oid: The OID of the object to set. :param value: The value of the object to set. :raises: SNMPFailure if an SNMP request fails.
[ "Use", "PySNMP", "to", "perform", "an", "SNMP", "SET", "operation", "on", "a", "single", "object", "." ]
train
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L232-L260
OSSOS/MOP
src/ossos/core/ossos/mop_file.py
MOPFile.filename
def filename(self): """ Name if the MOP formatted file to parse. @rtype: basestring @return: filename """ if self._filename is None: self._filename = storage.get_file(self.basename, self.ccd, ext=self.extension, version=self.type, prefix=self.prefix) return self._filename
python
def filename(self): """ Name if the MOP formatted file to parse. @rtype: basestring @return: filename """ if self._filename is None: self._filename = storage.get_file(self.basename, self.ccd, ext=self.extension, version=self.type, prefix=self.prefix) return self._filename
[ "def", "filename", "(", "self", ")", ":", "if", "self", ".", "_filename", "is", "None", ":", "self", ".", "_filename", "=", "storage", ".", "get_file", "(", "self", ".", "basename", ",", "self", ".", "ccd", ",", "ext", "=", "self", ".", "extension", ...
Name if the MOP formatted file to parse. @rtype: basestring @return: filename
[ "Name", "if", "the", "MOP", "formatted", "file", "to", "parse", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mop_file.py#L28-L40
OSSOS/MOP
src/ossos/core/ossos/mop_file.py
MOPFile._parse
def _parse(self): """read in a file and return a MOPFile object.""" with open(self.filename, 'r') as fobj: lines = fobj.read().split('\n') # Create a header object with content at start of file self.header = MOPHeader(self.subfmt).parser(lines) # Create a data attribute to hold an astropy.table.Table object self.data = MOPDataParser(self.header).parse(lines)
python
def _parse(self): """read in a file and return a MOPFile object.""" with open(self.filename, 'r') as fobj: lines = fobj.read().split('\n') # Create a header object with content at start of file self.header = MOPHeader(self.subfmt).parser(lines) # Create a data attribute to hold an astropy.table.Table object self.data = MOPDataParser(self.header).parse(lines)
[ "def", "_parse", "(", "self", ")", ":", "with", "open", "(", "self", ".", "filename", ",", "'r'", ")", "as", "fobj", ":", "lines", "=", "fobj", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "# Create a header object with content at start of file"...
read in a file and return a MOPFile object.
[ "read", "in", "a", "file", "and", "return", "a", "MOPFile", "object", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mop_file.py#L56-L65
OSSOS/MOP
src/ossos/core/ossos/mop_file.py
MOPDataParser.table
def table(self): """ The astropy.table.Table object that will contain the data result @rtype: Table @return: data table """ if self._table is None: column_names = [] for fileid in self.header.file_ids: for column_name in self.header.column_names: column_names.append("{}_{}".format(column_name, fileid)) column_names.append("ZP_{}".format(fileid)) if len(column_names) > 0: self._table = Table(names=column_names) else: self._table = Table() return self._table
python
def table(self): """ The astropy.table.Table object that will contain the data result @rtype: Table @return: data table """ if self._table is None: column_names = [] for fileid in self.header.file_ids: for column_name in self.header.column_names: column_names.append("{}_{}".format(column_name, fileid)) column_names.append("ZP_{}".format(fileid)) if len(column_names) > 0: self._table = Table(names=column_names) else: self._table = Table() return self._table
[ "def", "table", "(", "self", ")", ":", "if", "self", ".", "_table", "is", "None", ":", "column_names", "=", "[", "]", "for", "fileid", "in", "self", ".", "header", ".", "file_ids", ":", "for", "column_name", "in", "self", ".", "header", ".", "column_...
The astropy.table.Table object that will contain the data result @rtype: Table @return: data table
[ "The", "astropy", ".", "table", ".", "Table", "object", "that", "will", "contain", "the", "data", "result" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mop_file.py#L80-L96
OSSOS/MOP
src/ossos/core/ossos/mop_file.py
MOPHeader.parser
def parser(self, lines): """Given a set of lines parse the into a MOP Header""" while len(lines) > 0: if lines[0].startswith('##') and lines[1].startswith('# '): # A two-line keyword/value line starts here. self._header_append(lines.pop(0), lines.pop(0)) elif lines[0].startswith('# '): # Lines with single comments are exposure numbers unless preceeded by double comment line self._append_file_id(lines.pop(0)) elif lines[0].startswith('##'): # Double comment lines without a single comment following are column headers for dataset. self._set_column_names(lines.pop(0)[2:]) else: # Last line of the header reached. return self raise IOError("Failed trying to read header")
python
def parser(self, lines): """Given a set of lines parse the into a MOP Header""" while len(lines) > 0: if lines[0].startswith('##') and lines[1].startswith('# '): # A two-line keyword/value line starts here. self._header_append(lines.pop(0), lines.pop(0)) elif lines[0].startswith('# '): # Lines with single comments are exposure numbers unless preceeded by double comment line self._append_file_id(lines.pop(0)) elif lines[0].startswith('##'): # Double comment lines without a single comment following are column headers for dataset. self._set_column_names(lines.pop(0)[2:]) else: # Last line of the header reached. return self raise IOError("Failed trying to read header")
[ "def", "parser", "(", "self", ",", "lines", ")", ":", "while", "len", "(", "lines", ")", ">", "0", ":", "if", "lines", "[", "0", "]", ".", "startswith", "(", "'##'", ")", "and", "lines", "[", "1", "]", ".", "startswith", "(", "'# '", ")", ":", ...
Given a set of lines parse the into a MOP Header
[ "Given", "a", "set", "of", "lines", "parse", "the", "into", "a", "MOP", "Header" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mop_file.py#L147-L162
OSSOS/MOP
src/ossos/core/ossos/mop_file.py
MOPHeader._compute_mjd
def _compute_mjd(self, kw, val): """ Sometimes that MJD-OBS-CENTER keyword maps to a three component string, instead of a single value. @param kw: a list of keywords @param val: a list of matching values @return: the MJD-OBS-CENTER as a julian date. """ try: idx = kw.index('MJD-OBS-CENTER') except ValueError: return if len(val) == len(kw): return if len(val) - 2 != len(kw): raise ValueError("convert: keyword/value lengths don't match: {}/{}".format(kw, val)) val.insert(idx, Time("{} {} {}".format(val.pop(idx), val.pop(idx), val.pop(idx)), format='mpc', scale='utc').mjd) logging.debug("Computed MJD: {}".format(val[idx]))
python
def _compute_mjd(self, kw, val): """ Sometimes that MJD-OBS-CENTER keyword maps to a three component string, instead of a single value. @param kw: a list of keywords @param val: a list of matching values @return: the MJD-OBS-CENTER as a julian date. """ try: idx = kw.index('MJD-OBS-CENTER') except ValueError: return if len(val) == len(kw): return if len(val) - 2 != len(kw): raise ValueError("convert: keyword/value lengths don't match: {}/{}".format(kw, val)) val.insert(idx, Time("{} {} {}".format(val.pop(idx), val.pop(idx), val.pop(idx)), format='mpc', scale='utc').mjd) logging.debug("Computed MJD: {}".format(val[idx]))
[ "def", "_compute_mjd", "(", "self", ",", "kw", ",", "val", ")", ":", "try", ":", "idx", "=", "kw", ".", "index", "(", "'MJD-OBS-CENTER'", ")", "except", "ValueError", ":", "return", "if", "len", "(", "val", ")", "==", "len", "(", "kw", ")", ":", ...
Sometimes that MJD-OBS-CENTER keyword maps to a three component string, instead of a single value. @param kw: a list of keywords @param val: a list of matching values @return: the MJD-OBS-CENTER as a julian date.
[ "Sometimes", "that", "MJD", "-", "OBS", "-", "CENTER", "keyword", "maps", "to", "a", "three", "component", "string", "instead", "of", "a", "single", "value", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mop_file.py#L164-L182
OSSOS/MOP
src/jjk/preproc/findTriplets.py
getExpInfo
def getExpInfo(expnum): """Return a dictionary of information about a particular exposure""" col_names=['object', 'e.expnum', 'mjdate', 'uttime', 'filter', 'elongation', 'obs_iq_refccd', 'triple', 'qso_status'] sql="SELECT " sep=" " for col_name in col_names: sql=sql+sep+col_name sep="," sql=sql+" FROM bucket.exposure e " sql=sql+" JOIN bucket.circumstance c ON e.expnum=c.expnum " sql=sql+" LEFT JOIN triple_members t ON e.expnum=t.expnum " sql=sql+" WHERE e.expnum=%d " % ( expnum ) #sys.stderr.write(sql); cfeps.execute(sql) rows=cfeps.fetchall() #print rows result={} #import datetime for idx in range(len(rows[0])): result[col_names[idx]]=rows[0][idx] return(result)
python
def getExpInfo(expnum): """Return a dictionary of information about a particular exposure""" col_names=['object', 'e.expnum', 'mjdate', 'uttime', 'filter', 'elongation', 'obs_iq_refccd', 'triple', 'qso_status'] sql="SELECT " sep=" " for col_name in col_names: sql=sql+sep+col_name sep="," sql=sql+" FROM bucket.exposure e " sql=sql+" JOIN bucket.circumstance c ON e.expnum=c.expnum " sql=sql+" LEFT JOIN triple_members t ON e.expnum=t.expnum " sql=sql+" WHERE e.expnum=%d " % ( expnum ) #sys.stderr.write(sql); cfeps.execute(sql) rows=cfeps.fetchall() #print rows result={} #import datetime for idx in range(len(rows[0])): result[col_names[idx]]=rows[0][idx] return(result)
[ "def", "getExpInfo", "(", "expnum", ")", ":", "col_names", "=", "[", "'object'", ",", "'e.expnum'", ",", "'mjdate'", ",", "'uttime'", ",", "'filter'", ",", "'elongation'", ",", "'obs_iq_refccd'", ",", "'triple'", ",", "'qso_status'", "]", "sql", "=", "\"SELE...
Return a dictionary of information about a particular exposure
[ "Return", "a", "dictionary", "of", "information", "about", "a", "particular", "exposure" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/findTriplets.py#L79-L109
OSSOS/MOP
src/jjk/preproc/findTriplets.py
getTripInfo
def getTripInfo(triple): """Return a dictionary of information about a particular triple""" col_names=['mjdate', 'filter', 'elongation', 'discovery','checkup', 'recovery', 'iq','block' ] sql="SELECT mjdate md," sql=sql+" filter, avg(elongation), d.id, checkup.checkup, recovery.recovery , avg(obs_iq_refccd), b.qname " sql=sql+"FROM triple_members t JOIN bucket.exposure e ON t.expnum=e.expnum " sql=sql+"JOIN bucket.blocks b ON b.expnum=e.expnum " sql=sql+"JOIN bucket.circumstance c on e.expnum=c.expnum " sql=sql+"LEFT JOIN discovery d ON t.triple=d.triple " sql=sql+"LEFT JOIN checkup ON t.triple=checkup.triple " sql=sql+"LEFT JOIN recovery ON t.triple=recovery.triple " sql=sql+"WHERE t.triple=%s " sql=sql+"GROUP BY t.triple ORDER BY t.triple " cfeps.execute(sql,(triple, ) ) rows=cfeps.fetchall() result={} #import datetime for idx in range(len(rows[0])): result[col_names[idx]]=rows[0][idx] return result
python
def getTripInfo(triple): """Return a dictionary of information about a particular triple""" col_names=['mjdate', 'filter', 'elongation', 'discovery','checkup', 'recovery', 'iq','block' ] sql="SELECT mjdate md," sql=sql+" filter, avg(elongation), d.id, checkup.checkup, recovery.recovery , avg(obs_iq_refccd), b.qname " sql=sql+"FROM triple_members t JOIN bucket.exposure e ON t.expnum=e.expnum " sql=sql+"JOIN bucket.blocks b ON b.expnum=e.expnum " sql=sql+"JOIN bucket.circumstance c on e.expnum=c.expnum " sql=sql+"LEFT JOIN discovery d ON t.triple=d.triple " sql=sql+"LEFT JOIN checkup ON t.triple=checkup.triple " sql=sql+"LEFT JOIN recovery ON t.triple=recovery.triple " sql=sql+"WHERE t.triple=%s " sql=sql+"GROUP BY t.triple ORDER BY t.triple " cfeps.execute(sql,(triple, ) ) rows=cfeps.fetchall() result={} #import datetime for idx in range(len(rows[0])): result[col_names[idx]]=rows[0][idx] return result
[ "def", "getTripInfo", "(", "triple", ")", ":", "col_names", "=", "[", "'mjdate'", ",", "'filter'", ",", "'elongation'", ",", "'discovery'", ",", "'checkup'", ",", "'recovery'", ",", "'iq'", ",", "'block'", "]", "sql", "=", "\"SELECT mjdate md,\"", "sql", "="...
Return a dictionary of information about a particular triple
[ "Return", "a", "dictionary", "of", "information", "about", "a", "particular", "triple" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/findTriplets.py#L111-L132
OSSOS/MOP
src/jjk/preproc/findTriplets.py
getExpnums
def getExpnums(pointing,night=None): """Get all exposures of specified pointing ID. Default is to return a list of all exposure numbers""" if night: night=" floor(e.mjdate-0.0833)=%d " % ( night ) else: night='' sql="SELECT e.expnum " sql=sql+"FROM bucket.exposure e " sql=sql+"JOIN bucket.association a on e.expnum=a.expnum " sql=sql+"WHERE a.pointing="+str(pointing)+" AND "+night sql=sql+" ORDER BY mjdate, uttime DESC " cfeps.execute(sql) return(cfeps.fetchall())
python
def getExpnums(pointing,night=None): """Get all exposures of specified pointing ID. Default is to return a list of all exposure numbers""" if night: night=" floor(e.mjdate-0.0833)=%d " % ( night ) else: night='' sql="SELECT e.expnum " sql=sql+"FROM bucket.exposure e " sql=sql+"JOIN bucket.association a on e.expnum=a.expnum " sql=sql+"WHERE a.pointing="+str(pointing)+" AND "+night sql=sql+" ORDER BY mjdate, uttime DESC " cfeps.execute(sql) return(cfeps.fetchall())
[ "def", "getExpnums", "(", "pointing", ",", "night", "=", "None", ")", ":", "if", "night", ":", "night", "=", "\" floor(e.mjdate-0.0833)=%d \"", "%", "(", "night", ")", "else", ":", "night", "=", "''", "sql", "=", "\"SELECT e.expnum \"", "sql", "=", "sql", ...
Get all exposures of specified pointing ID. Default is to return a list of all exposure numbers
[ "Get", "all", "exposures", "of", "specified", "pointing", "ID", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/findTriplets.py#L134-L151
OSSOS/MOP
src/jjk/preproc/findTriplets.py
getTriples
def getTriples(pointing): """Get all triples of a specified pointing ID. Defaults is to return a complete list triples.""" sql="SELECT id FROM triples t join triple_members m ON t.id=m.triple" sql+=" join bucket.exposure e on e.expnum=m.expnum " sql+=" WHERE pointing=%s group by id order by e.expnum " cfeps.execute(sql, ( pointing, ) ) return(cfeps.fetchall())
python
def getTriples(pointing): """Get all triples of a specified pointing ID. Defaults is to return a complete list triples.""" sql="SELECT id FROM triples t join triple_members m ON t.id=m.triple" sql+=" join bucket.exposure e on e.expnum=m.expnum " sql+=" WHERE pointing=%s group by id order by e.expnum " cfeps.execute(sql, ( pointing, ) ) return(cfeps.fetchall())
[ "def", "getTriples", "(", "pointing", ")", ":", "sql", "=", "\"SELECT id FROM triples t join triple_members m ON t.id=m.triple\"", "sql", "+=", "\" join bucket.exposure e on e.expnum=m.expnum \"", "sql", "+=", "\" WHERE pointing=%s group by id order by e.expnum \"", "cfeps", ".", ...
Get all triples of a specified pointing ID. Defaults is to return a complete list triples.
[ "Get", "all", "triples", "of", "a", "specified", "pointing", "ID", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/findTriplets.py#L153-L162
OSSOS/MOP
src/jjk/preproc/findTriplets.py
createNewTriples
def createNewTriples(Win): """Add entries to the triples tables based on new images in the db""" win.help("Building list of exposures to look for triples") cols=('e.expnum', 'object', 'mjdate', 'uttime', 'elongation', 'filter', 'obs_iq_refccd','qso_status' ) header='%6s %-10s%-12s%10s%10s%10s%8s%10s' % cols pointings=getNewTriples() num_p=len(pointings) for pointing in pointings: pid=pointing[0] mjd=pointing[1] expnums=getExpnums(pointing=pid,night=mjd) num_p=num_p-1 while (1): ### Loop over this pointing until keystroke gets us out win.help("Select (space) members of triplets - %d remaining" % num_p ) ## start with an empty list explist=[] choices=[] current_date='' for expnum in expnums: info=getExpInfo(expnum[0]) row=() if not str(info['triple'])=='None' : continue if str(info['obs_iq_refccd'])=='None': info['obs_iq_refccd']=-1.0 choices.append('%6d %10s %15s %10s %8.2f %10s %8.2f %10s' % ( int(info['e.expnum']), str(info['object']), str(info['mjdate']), str(info['uttime']), float(str(info['elongation'])), str(info['filter']), float(str(info['obs_iq_refccd'])), str(info['qso_status']) )) explist.append(expnum[0]) if len(choices)<3: ### we need to provide at least 3 choices, ### otherwise this isn't a triple (is it) break ### win.list returns the user's choices as a list. choice_list=win.list(header,choices) ### zero length list implies were done. if choice_list==None: break ### is this actually a triple? if len(choice_list)!=3: win.help("Must have 3 members to make a tripple") continue ### Create a new line in the triple table sql = "INSERT INTO triples (id, pointing ) VALUES ( NULL, %s ) " cfeps.execute(sql, ( pid, ) ) sql = "SELECT id FROM triples WHERE pointing=%s order by id desc" cfeps.execute(sql, ( pid, ) ) ttt=cfeps.fetchall() triple= ttt[0][0] win.help(str(triple)) ### record the members of this new triple. sql = "INSERT INTO triple_members (triple, expnum) VALUES ( %s, %s)"; win.help(sql) for exp in choice_list: cfeps.execute(sql,(triple,explist[exp])) return(0)
python
def createNewTriples(Win): """Add entries to the triples tables based on new images in the db""" win.help("Building list of exposures to look for triples") cols=('e.expnum', 'object', 'mjdate', 'uttime', 'elongation', 'filter', 'obs_iq_refccd','qso_status' ) header='%6s %-10s%-12s%10s%10s%10s%8s%10s' % cols pointings=getNewTriples() num_p=len(pointings) for pointing in pointings: pid=pointing[0] mjd=pointing[1] expnums=getExpnums(pointing=pid,night=mjd) num_p=num_p-1 while (1): ### Loop over this pointing until keystroke gets us out win.help("Select (space) members of triplets - %d remaining" % num_p ) ## start with an empty list explist=[] choices=[] current_date='' for expnum in expnums: info=getExpInfo(expnum[0]) row=() if not str(info['triple'])=='None' : continue if str(info['obs_iq_refccd'])=='None': info['obs_iq_refccd']=-1.0 choices.append('%6d %10s %15s %10s %8.2f %10s %8.2f %10s' % ( int(info['e.expnum']), str(info['object']), str(info['mjdate']), str(info['uttime']), float(str(info['elongation'])), str(info['filter']), float(str(info['obs_iq_refccd'])), str(info['qso_status']) )) explist.append(expnum[0]) if len(choices)<3: ### we need to provide at least 3 choices, ### otherwise this isn't a triple (is it) break ### win.list returns the user's choices as a list. choice_list=win.list(header,choices) ### zero length list implies were done. if choice_list==None: break ### is this actually a triple? if len(choice_list)!=3: win.help("Must have 3 members to make a tripple") continue ### Create a new line in the triple table sql = "INSERT INTO triples (id, pointing ) VALUES ( NULL, %s ) " cfeps.execute(sql, ( pid, ) ) sql = "SELECT id FROM triples WHERE pointing=%s order by id desc" cfeps.execute(sql, ( pid, ) ) ttt=cfeps.fetchall() triple= ttt[0][0] win.help(str(triple)) ### record the members of this new triple. sql = "INSERT INTO triple_members (triple, expnum) VALUES ( %s, %s)"; win.help(sql) for exp in choice_list: cfeps.execute(sql,(triple,explist[exp])) return(0)
[ "def", "createNewTriples", "(", "Win", ")", ":", "win", ".", "help", "(", "\"Building list of exposures to look for triples\"", ")", "cols", "=", "(", "'e.expnum'", ",", "'object'", ",", "'mjdate'", ",", "'uttime'", ",", "'elongation'", ",", "'filter'", ",", "'o...
Add entries to the triples tables based on new images in the db
[ "Add", "entries", "to", "the", "triples", "tables", "based", "on", "new", "images", "in", "the", "db" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/findTriplets.py#L170-L255
OSSOS/MOP
src/jjk/preproc/findTriplets.py
setDiscoveryTriples
def setDiscoveryTriples(win,table="discovery"): """Provide user with a list of triples that could be discovery triples""" win.help("Getting a list of pointings with triples from the CFEPS db") pointings=getPointingsWithTriples() win.help("Select the "+table+" triple form the list...") import time for pointing in pointings: header="%10s %10s %8s %10s %8s" % (pointing[1],'mjdate','Elongation','Filter', 'IQ') triples=getTriples(pointing=pointing[0]) choices=[] triplist=[] no_type=0 previous_list=[] for triple in triples: #win.help(str(triple)) tripinfo=getTripInfo(triple[0]) if not tripinfo[table]==None: previous_list.append(triple[0]) #if not abs(180-tripinfo['elongation'])< 20: # continue triplist.append(triple) if str(tripinfo['iq'])=='None': tripinfo['iq']=-1.0 obs_type=' ' if tripinfo['discovery']: obs_type='D' elif tripinfo['checkup']: obs_type='C' elif tripinfo['recovery']: obs_type='R' if obs_type==' ': no_type+=1 line=(obs_type,tripinfo['mjdate'], tripinfo['elongation'], tripinfo['filter'], tripinfo['iq'], tripinfo['block'] ) choices.append('%10s %10s %8.2f %10s %8.2f %8s' % line) if len(choices)==0 or no_type==0: continue #if len(previous_list)==1: # continue win.help("Choose a "+table+" triple (space) [no choice means skip] then press enter\n (q) to exit") choice=win.list(header,choices) if choice==None: win.help("Loading next triple") break ### Record which triplet is a discovery triplet if len(choice)!=1: win.help("Loading next triple\n") continue discovery_triple=triplist[choice[0]] for triple in previous_list: sql="DELETE FROM "+table+" WHERE triple=%s " cfeps.execute(sql,triple) sql="INSERT INTO "+table+" ( triple ) VALUES ( %s ) " cfeps.execute(sql,discovery_triple)
python
def setDiscoveryTriples(win,table="discovery"): """Provide user with a list of triples that could be discovery triples""" win.help("Getting a list of pointings with triples from the CFEPS db") pointings=getPointingsWithTriples() win.help("Select the "+table+" triple form the list...") import time for pointing in pointings: header="%10s %10s %8s %10s %8s" % (pointing[1],'mjdate','Elongation','Filter', 'IQ') triples=getTriples(pointing=pointing[0]) choices=[] triplist=[] no_type=0 previous_list=[] for triple in triples: #win.help(str(triple)) tripinfo=getTripInfo(triple[0]) if not tripinfo[table]==None: previous_list.append(triple[0]) #if not abs(180-tripinfo['elongation'])< 20: # continue triplist.append(triple) if str(tripinfo['iq'])=='None': tripinfo['iq']=-1.0 obs_type=' ' if tripinfo['discovery']: obs_type='D' elif tripinfo['checkup']: obs_type='C' elif tripinfo['recovery']: obs_type='R' if obs_type==' ': no_type+=1 line=(obs_type,tripinfo['mjdate'], tripinfo['elongation'], tripinfo['filter'], tripinfo['iq'], tripinfo['block'] ) choices.append('%10s %10s %8.2f %10s %8.2f %8s' % line) if len(choices)==0 or no_type==0: continue #if len(previous_list)==1: # continue win.help("Choose a "+table+" triple (space) [no choice means skip] then press enter\n (q) to exit") choice=win.list(header,choices) if choice==None: win.help("Loading next triple") break ### Record which triplet is a discovery triplet if len(choice)!=1: win.help("Loading next triple\n") continue discovery_triple=triplist[choice[0]] for triple in previous_list: sql="DELETE FROM "+table+" WHERE triple=%s " cfeps.execute(sql,triple) sql="INSERT INTO "+table+" ( triple ) VALUES ( %s ) " cfeps.execute(sql,discovery_triple)
[ "def", "setDiscoveryTriples", "(", "win", ",", "table", "=", "\"discovery\"", ")", ":", "win", ".", "help", "(", "\"Getting a list of pointings with triples from the CFEPS db\"", ")", "pointings", "=", "getPointingsWithTriples", "(", ")", "win", ".", "help", "(", "\...
Provide user with a list of triples that could be discovery triples
[ "Provide", "user", "with", "a", "list", "of", "triples", "that", "could", "be", "discovery", "triples" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/findTriplets.py#L257-L312
OSSOS/MOP
src/ossos/core/ossos/pipeline/step1.py
run
def run(expnum, ccd, prefix='', version='p', sex_thresh=_SEX_THRESHOLD, wave_thresh=_WAVE_THRESHOLD, maxcount=_MAX_COUNT, dry_run=False, force=True): """run the actual step1jmp/matt codes. expnum: the CFHT expousre to process ccd: which ccd in the mosaic to process fwhm: the image quality, FWHM, of the image. In pixels. sex_thresh: the detection threhold to run sExtractor at wave_thresh: the detection threshold for wavelet maxcount: saturation level """ message = storage.SUCCESS if storage.get_status(task, prefix, expnum, version, ccd) and not force: logging.info("{} completed successfully for {} {} {} {}".format(task, prefix, expnum, version, ccd)) return with storage.LoggingManager(task, prefix, expnum, ccd, version, dry_run): try: if not storage.get_status(dependency, prefix, expnum, version, ccd): raise IOError(35, "Cannot start {} as {} not yet completed for {}{}{}{:02d}".format( task, dependency, prefix, expnum, version, ccd)) logging.info("Retrieving imaging and input parameters from VOSpace") storage.get_file(expnum, ccd, prefix=prefix, version=version, ext='mopheader') filename = storage.get_image(expnum, ccd, version=version, prefix=prefix) fwhm = storage.get_fwhm(expnum, ccd, prefix=prefix, version=version) basename = os.path.splitext(filename)[0] _get_weight_map(filename, ccd) logging.info("Launching step1jmp") logging.info(util.exec_prog(['step1jmp', '-f', basename, '-t', str(wave_thresh), '-w', str(fwhm), '-m', str(maxcount)])) logging.info(util.exec_prog(['step1matt', '-f', basename, '-t', str(sex_thresh), '-w', str(fwhm), '-m', str(maxcount)])) if os.access('weight.fits', os.R_OK): os.unlink('weight.fits') if not dry_run: for ext in ['obj.jmp', 'obj.matt']: obj_uri = storage.get_uri(expnum, ccd, version=version, ext=ext, prefix=prefix) obj_filename = basename + "." + ext count = 0 with open(obj_filename, 'r'): while True: try: count += 1 logging.info("Attempt {} to copy {} -> {}".format(count, obj_filename, obj_uri)) storage.copy(obj_filename, obj_uri) break except Exception as ex: if count > 10: raise ex logging.info(message) except Exception as ex: message = str(ex) logging.error(message) if not dry_run: storage.set_status(task, prefix, expnum, version, ccd, status=message)
python
def run(expnum, ccd, prefix='', version='p', sex_thresh=_SEX_THRESHOLD, wave_thresh=_WAVE_THRESHOLD, maxcount=_MAX_COUNT, dry_run=False, force=True): """run the actual step1jmp/matt codes. expnum: the CFHT expousre to process ccd: which ccd in the mosaic to process fwhm: the image quality, FWHM, of the image. In pixels. sex_thresh: the detection threhold to run sExtractor at wave_thresh: the detection threshold for wavelet maxcount: saturation level """ message = storage.SUCCESS if storage.get_status(task, prefix, expnum, version, ccd) and not force: logging.info("{} completed successfully for {} {} {} {}".format(task, prefix, expnum, version, ccd)) return with storage.LoggingManager(task, prefix, expnum, ccd, version, dry_run): try: if not storage.get_status(dependency, prefix, expnum, version, ccd): raise IOError(35, "Cannot start {} as {} not yet completed for {}{}{}{:02d}".format( task, dependency, prefix, expnum, version, ccd)) logging.info("Retrieving imaging and input parameters from VOSpace") storage.get_file(expnum, ccd, prefix=prefix, version=version, ext='mopheader') filename = storage.get_image(expnum, ccd, version=version, prefix=prefix) fwhm = storage.get_fwhm(expnum, ccd, prefix=prefix, version=version) basename = os.path.splitext(filename)[0] _get_weight_map(filename, ccd) logging.info("Launching step1jmp") logging.info(util.exec_prog(['step1jmp', '-f', basename, '-t', str(wave_thresh), '-w', str(fwhm), '-m', str(maxcount)])) logging.info(util.exec_prog(['step1matt', '-f', basename, '-t', str(sex_thresh), '-w', str(fwhm), '-m', str(maxcount)])) if os.access('weight.fits', os.R_OK): os.unlink('weight.fits') if not dry_run: for ext in ['obj.jmp', 'obj.matt']: obj_uri = storage.get_uri(expnum, ccd, version=version, ext=ext, prefix=prefix) obj_filename = basename + "." + ext count = 0 with open(obj_filename, 'r'): while True: try: count += 1 logging.info("Attempt {} to copy {} -> {}".format(count, obj_filename, obj_uri)) storage.copy(obj_filename, obj_uri) break except Exception as ex: if count > 10: raise ex logging.info(message) except Exception as ex: message = str(ex) logging.error(message) if not dry_run: storage.set_status(task, prefix, expnum, version, ccd, status=message)
[ "def", "run", "(", "expnum", ",", "ccd", ",", "prefix", "=", "''", ",", "version", "=", "'p'", ",", "sex_thresh", "=", "_SEX_THRESHOLD", ",", "wave_thresh", "=", "_WAVE_THRESHOLD", ",", "maxcount", "=", "_MAX_COUNT", ",", "dry_run", "=", "False", ",", "f...
run the actual step1jmp/matt codes. expnum: the CFHT expousre to process ccd: which ccd in the mosaic to process fwhm: the image quality, FWHM, of the image. In pixels. sex_thresh: the detection threhold to run sExtractor at wave_thresh: the detection threshold for wavelet maxcount: saturation level
[ "run", "the", "actual", "step1jmp", "/", "matt", "codes", "." ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/pipeline/step1.py#L73-L149
OSSOS/MOP
src/ossos/utils/2MASS_Vizier.py
query
def query(ra ,dec, rad=0.1, query=None): """Query the CADC TAP service to determine the list of images for the NewHorizons Search. Things to determine: a- Images to have the reference subtracted from. b- Image to use as the 'REFERENCE' image. c- Images to be used for input into the reference image Logic: Given a particular Image/CCD find all the CCDs of the same field that overlap that CCD but are taken more than 7 days later or earlier than that image. """ if query is None: query=( """ SELECT """ """ "II/246/out".raj2000 as ra, "II/246/out".dej2000 as dec, "II/246/out".jmag as jmag """ """ FROM "II/246/out" """ """ WHERE """ """ CONTAINS(POINT('ICRS', raj2000, dej2000), CIRCLE('ICRS', {}, {}, {})) = 1 """.format(ra,dec,rad) ) tapURL = "http://TAPVizieR.u-strasbg.fr/TAPVizieR/tap/sync" ## Some default parameters for that TAP service queries. tapParams={'REQUEST': 'doQuery', 'LANG': 'ADQL', 'FORMAT': 'votable', 'QUERY': query} response = requests.get(tapURL, params=tapParams) data = StringIO(response.text) data.seek(0) data.seek(0) T = votable.parse_single_table(data).to_table() return T
python
def query(ra ,dec, rad=0.1, query=None): """Query the CADC TAP service to determine the list of images for the NewHorizons Search. Things to determine: a- Images to have the reference subtracted from. b- Image to use as the 'REFERENCE' image. c- Images to be used for input into the reference image Logic: Given a particular Image/CCD find all the CCDs of the same field that overlap that CCD but are taken more than 7 days later or earlier than that image. """ if query is None: query=( """ SELECT """ """ "II/246/out".raj2000 as ra, "II/246/out".dej2000 as dec, "II/246/out".jmag as jmag """ """ FROM "II/246/out" """ """ WHERE """ """ CONTAINS(POINT('ICRS', raj2000, dej2000), CIRCLE('ICRS', {}, {}, {})) = 1 """.format(ra,dec,rad) ) tapURL = "http://TAPVizieR.u-strasbg.fr/TAPVizieR/tap/sync" ## Some default parameters for that TAP service queries. tapParams={'REQUEST': 'doQuery', 'LANG': 'ADQL', 'FORMAT': 'votable', 'QUERY': query} response = requests.get(tapURL, params=tapParams) data = StringIO(response.text) data.seek(0) data.seek(0) T = votable.parse_single_table(data).to_table() return T
[ "def", "query", "(", "ra", ",", "dec", ",", "rad", "=", "0.1", ",", "query", "=", "None", ")", ":", "if", "query", "is", "None", ":", "query", "=", "(", "\"\"\" SELECT \"\"\"", "\"\"\" \"II/246/out\".raj2000 as ra, \"II/246/out\".dej2000 as dec, \"II/246/out\".jmag ...
Query the CADC TAP service to determine the list of images for the NewHorizons Search. Things to determine: a- Images to have the reference subtracted from. b- Image to use as the 'REFERENCE' image. c- Images to be used for input into the reference image Logic: Given a particular Image/CCD find all the CCDs of the same field that overlap that CCD but are taken more than 7 days later or earlier than that image.
[ "Query", "the", "CADC", "TAP", "service", "to", "determine", "the", "list", "of", "images", "for", "the", "NewHorizons", "Search", ".", "Things", "to", "determine", ":" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/2MASS_Vizier.py#L6-L42
OSSOS/MOP
src/jjk/preproc/objIngest.py
objIngest
def objIngest(obj_file): import sys,os,math,re import pyfits import MOPfiles obj=MOPfiles.read(obj_file) """ The SQL description of the source table +-------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------+------+-----+---------+----------------+ | sourceID | int(11) | | PRI | NULL | auto_increment | | x_pix | float | YES | MUL | NULL | | | y_pix | float | YES | | NULL | | | iso_flux | float | YES | | NULL | | | iso_err | float | YES | | NULL | | | aper_flux | float | YES | | NULL | | | aper_err | float | YES | | NULL | | | iso_area | float | YES | | NULL | | | kron_radius | float | YES | MUL | NULL | | | elongation | float | YES | | NULL | | | cxx | float | YES | | NULL | | | cyy | float | YES | | NULL | | | cxy | float | YES | | NULL | | | max_flux | float | YES | | NULL | | | max_int | float | YES | | NULL | | | mag_dao | float | YES | MUL | NULL | | | merr_dao | float | YES | | NULL | | | sky_cts | float | YES | | NULL | | | chi2 | float | YES | | NULL | | | npix | float | YES | | NULL | | | sharp | float | YES | | NULL | | | ra_deg | float | YES | MUL | NULL | | | dec_deg | float | YES | | NULL | | +-------------+---------+------+-----+---------+----------------+ """ """ Columns in the SOURCE table... ## X Y FLUX_ISO FLUXERR_ISO FLUX_APER FLUXERR_APER ISOAREA_IMAGE KRON_RADIUS ELONGATION CXX_IMAGE CYY_IMAGE CXY_IMAGE FLUX_MAX ID MAX_INT FLUX MERR SKY ELON X^2 N_PIX MAG SHARP SIZE """ ### The mapping obj['hdu2sql']={'MAX_INT': 'peak', 'FLUX': 'flux', 'MAG': 'mag', 'MERR': 'merr', 'SKY': 'sky', 'ELON': 'elongation', 'X^2': 'chi2', 'N_PIX': 'npix', 'SHARP': 'sharpness', 'Y': 'yPix', 'X': 'xPix', 'SIZE': 'size', 'RA': 'raDeg', 'DEC': 'decDeg', } MOPfiles.store(obj) return
python
def objIngest(obj_file): import sys,os,math,re import pyfits import MOPfiles obj=MOPfiles.read(obj_file) """ The SQL description of the source table +-------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------+------+-----+---------+----------------+ | sourceID | int(11) | | PRI | NULL | auto_increment | | x_pix | float | YES | MUL | NULL | | | y_pix | float | YES | | NULL | | | iso_flux | float | YES | | NULL | | | iso_err | float | YES | | NULL | | | aper_flux | float | YES | | NULL | | | aper_err | float | YES | | NULL | | | iso_area | float | YES | | NULL | | | kron_radius | float | YES | MUL | NULL | | | elongation | float | YES | | NULL | | | cxx | float | YES | | NULL | | | cyy | float | YES | | NULL | | | cxy | float | YES | | NULL | | | max_flux | float | YES | | NULL | | | max_int | float | YES | | NULL | | | mag_dao | float | YES | MUL | NULL | | | merr_dao | float | YES | | NULL | | | sky_cts | float | YES | | NULL | | | chi2 | float | YES | | NULL | | | npix | float | YES | | NULL | | | sharp | float | YES | | NULL | | | ra_deg | float | YES | MUL | NULL | | | dec_deg | float | YES | | NULL | | +-------------+---------+------+-----+---------+----------------+ """ """ Columns in the SOURCE table... ## X Y FLUX_ISO FLUXERR_ISO FLUX_APER FLUXERR_APER ISOAREA_IMAGE KRON_RADIUS ELONGATION CXX_IMAGE CYY_IMAGE CXY_IMAGE FLUX_MAX ID MAX_INT FLUX MERR SKY ELON X^2 N_PIX MAG SHARP SIZE """ ### The mapping obj['hdu2sql']={'MAX_INT': 'peak', 'FLUX': 'flux', 'MAG': 'mag', 'MERR': 'merr', 'SKY': 'sky', 'ELON': 'elongation', 'X^2': 'chi2', 'N_PIX': 'npix', 'SHARP': 'sharpness', 'Y': 'yPix', 'X': 'xPix', 'SIZE': 'size', 'RA': 'raDeg', 'DEC': 'decDeg', } MOPfiles.store(obj) return
[ "def", "objIngest", "(", "obj_file", ")", ":", "import", "sys", ",", "os", ",", "math", ",", "re", "import", "pyfits", "import", "MOPfiles", "obj", "=", "MOPfiles", ".", "read", "(", "obj_file", ")", "\"\"\"\n Columns in the SOURCE table...\n ## X ...
The SQL description of the source table +-------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------+------+-----+---------+----------------+ | sourceID | int(11) | | PRI | NULL | auto_increment | | x_pix | float | YES | MUL | NULL | | | y_pix | float | YES | | NULL | | | iso_flux | float | YES | | NULL | | | iso_err | float | YES | | NULL | | | aper_flux | float | YES | | NULL | | | aper_err | float | YES | | NULL | | | iso_area | float | YES | | NULL | | | kron_radius | float | YES | MUL | NULL | | | elongation | float | YES | | NULL | | | cxx | float | YES | | NULL | | | cyy | float | YES | | NULL | | | cxy | float | YES | | NULL | | | max_flux | float | YES | | NULL | | | max_int | float | YES | | NULL | | | mag_dao | float | YES | MUL | NULL | | | merr_dao | float | YES | | NULL | | | sky_cts | float | YES | | NULL | | | chi2 | float | YES | | NULL | | | npix | float | YES | | NULL | | | sharp | float | YES | | NULL | | | ra_deg | float | YES | MUL | NULL | | | dec_deg | float | YES | | NULL | | +-------------+---------+------+-----+---------+----------------+
[ "The", "SQL", "description", "of", "the", "source", "table", "+", "-------------", "+", "---------", "+", "------", "+", "-----", "+", "---------", "+", "----------------", "+", "|", "Field", "|", "Type", "|", "Null", "|", "Key", "|", "Default", "|", "Ex...
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/objIngest.py#L7-L74
OSSOS/MOP
src/jjk/preproc/MOPplot.py
load_edbfile
def load_edbfile(file=None): """Load the targets from a file""" import ephem,string,math if file is None: import tkFileDialog try: file=tkFileDialog.askopenfilename() except: return if file is None or file == '': return f=open(file) lines=f.readlines() f.close() for line in lines: p=line.split(',') name=p[0].strip().upper() mpc_objs[name]=ephem.readdb(line) mpc_objs[name].compute() objInfoDict[name]="%6s %6s %6s\n" % ( string.center("a",6), string.center("e",6), string.center("i",6) ) objInfoDict[name]+="%6.2f %6.3f %6.2f\n" % (mpc_objs[name]._a,mpc_objs[name]._e,math.degrees(mpc_objs[name]._inc)) objInfoDict[name]+="%7.2f %7.2f\n" % ( mpc_objs[name].earth_distance, mpc_objs[name].mag) doplot(mpc_objs)
python
def load_edbfile(file=None): """Load the targets from a file""" import ephem,string,math if file is None: import tkFileDialog try: file=tkFileDialog.askopenfilename() except: return if file is None or file == '': return f=open(file) lines=f.readlines() f.close() for line in lines: p=line.split(',') name=p[0].strip().upper() mpc_objs[name]=ephem.readdb(line) mpc_objs[name].compute() objInfoDict[name]="%6s %6s %6s\n" % ( string.center("a",6), string.center("e",6), string.center("i",6) ) objInfoDict[name]+="%6.2f %6.3f %6.2f\n" % (mpc_objs[name]._a,mpc_objs[name]._e,math.degrees(mpc_objs[name]._inc)) objInfoDict[name]+="%7.2f %7.2f\n" % ( mpc_objs[name].earth_distance, mpc_objs[name].mag) doplot(mpc_objs)
[ "def", "load_edbfile", "(", "file", "=", "None", ")", ":", "import", "ephem", ",", "string", ",", "math", "if", "file", "is", "None", ":", "import", "tkFileDialog", "try", ":", "file", "=", "tkFileDialog", ".", "askopenfilename", "(", ")", "except", ":",...
Load the targets from a file
[ "Load", "the", "targets", "from", "a", "file" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L14-L38
OSSOS/MOP
src/jjk/preproc/MOPplot.py
load_abgfiles
def load_abgfiles(dir=None): """Load the targets from a file""" import ephem,string if dir is None: import tkFileDialog try: dir=tkFileDialog.askdirectory() except: return if dir is None: return None from glob import glob files=glob(dir+"/*.abg") import os for f in files: (name,ext)=os.path.splitext(os.path.basename(f)) NAME=name.strip().upper() kbos[name]=f #print name aei=file(dir+"/"+name+".aei") lines=aei.readlines() aei.close() objInfoDict[name]="%6s %6s %6s\n" % ( string.center("a",6), string.center("e",6), string.center("i",6) ) try: (a,e,i,N,w,T) = lines[4].split() except: print lines[4] (a,e,i,N,w,T) = (0,0,0,0,0,0) objInfoDict[name]+="%6.2f %6.3f %6.2f\n" % (float(a),float(e),float(i)) s=lines[5][0:2] (a,e,i,N,w,T) = lines[5][2:-1].split() objInfoDict[name]+=" %6.3f %6.3f %6.3f\n" % (float(a),float(e),float(i)) abg = file(dir+"/"+name+".abg") lines = abg.readlines() abg.close() for line in lines: if not line[0:5] == "# Bar": continue objInfoDict[name]+=line[2:-1]+"\n" break res=file(dir+"/"+name+".res") lines=res.readlines() res.close() line=lines.pop() values=line.split() s = "[nobs: "+values[0]+" dt: "+values[1]+"]\n" objInfoDict[name]+=s mpc = file(dir+"/../mpc/"+name+".mpc") lines=mpc.readlines() mpc.close() last_date=0 for line in lines: if len(line)==0: continue if line[0]=="#": continue this_year=int(line[15:19]) this_month=int(line[20:22]) this_day = int(line[23:25]) this_date = this_year+this_month/12.0 +this_day/365.25 if last_date < this_date: last_date=this_date year=this_year day = this_day month=this_month mag={} for line in lines: try: mags=line[65:69].strip() if len(mags)==0: continue filter=line[70] if filter not in mag: mag[filter]=[] mag[filter].append(float(mags)) except: continue mags='' for filter in mag: magv=0 for m in mag[filter]: magv = magv+m/len(mag[filter]) mags = mags+ "%4.1f-%s " % ( magv , filter) if len(mags)==0: mags= "N/A" objInfoDict[name]+="MAG: "+mags+"\n" objInfoDict[name]+="Last obs: %s %s %s \n" % (year,month, day) doplot(kbos)
python
def load_abgfiles(dir=None): """Load the targets from a file""" import ephem,string if dir is None: import tkFileDialog try: dir=tkFileDialog.askdirectory() except: return if dir is None: return None from glob import glob files=glob(dir+"/*.abg") import os for f in files: (name,ext)=os.path.splitext(os.path.basename(f)) NAME=name.strip().upper() kbos[name]=f #print name aei=file(dir+"/"+name+".aei") lines=aei.readlines() aei.close() objInfoDict[name]="%6s %6s %6s\n" % ( string.center("a",6), string.center("e",6), string.center("i",6) ) try: (a,e,i,N,w,T) = lines[4].split() except: print lines[4] (a,e,i,N,w,T) = (0,0,0,0,0,0) objInfoDict[name]+="%6.2f %6.3f %6.2f\n" % (float(a),float(e),float(i)) s=lines[5][0:2] (a,e,i,N,w,T) = lines[5][2:-1].split() objInfoDict[name]+=" %6.3f %6.3f %6.3f\n" % (float(a),float(e),float(i)) abg = file(dir+"/"+name+".abg") lines = abg.readlines() abg.close() for line in lines: if not line[0:5] == "# Bar": continue objInfoDict[name]+=line[2:-1]+"\n" break res=file(dir+"/"+name+".res") lines=res.readlines() res.close() line=lines.pop() values=line.split() s = "[nobs: "+values[0]+" dt: "+values[1]+"]\n" objInfoDict[name]+=s mpc = file(dir+"/../mpc/"+name+".mpc") lines=mpc.readlines() mpc.close() last_date=0 for line in lines: if len(line)==0: continue if line[0]=="#": continue this_year=int(line[15:19]) this_month=int(line[20:22]) this_day = int(line[23:25]) this_date = this_year+this_month/12.0 +this_day/365.25 if last_date < this_date: last_date=this_date year=this_year day = this_day month=this_month mag={} for line in lines: try: mags=line[65:69].strip() if len(mags)==0: continue filter=line[70] if filter not in mag: mag[filter]=[] mag[filter].append(float(mags)) except: continue mags='' for filter in mag: magv=0 for m in mag[filter]: magv = magv+m/len(mag[filter]) mags = mags+ "%4.1f-%s " % ( magv , filter) if len(mags)==0: mags= "N/A" objInfoDict[name]+="MAG: "+mags+"\n" objInfoDict[name]+="Last obs: %s %s %s \n" % (year,month, day) doplot(kbos)
[ "def", "load_abgfiles", "(", "dir", "=", "None", ")", ":", "import", "ephem", ",", "string", "if", "dir", "is", "None", ":", "import", "tkFileDialog", "try", ":", "dir", "=", "tkFileDialog", ".", "askdirectory", "(", ")", "except", ":", "return", "if", ...
Load the targets from a file
[ "Load", "the", "targets", "from", "a", "file" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L43-L133
OSSOS/MOP
src/jjk/preproc/MOPplot.py
fits_list
def fits_list(filter,root,fnames): """Get a list of files matching filter in directory root""" import re, pyfits, wcsutil for file in fnames: if re.match(filter,file): fh=pyfits.open(file) for ext in fh: obj=ext.header.get('OBJECT',file) dx=ext.header.get('NAXIS1',None) dy=ext.header.get('NAXIS2',None) wcs=wcsutil.WCSObject(ext) (x1,y1)=wcs.xy2rd((1,1,)) (x2,y2)=wcs.xy2rd((dx,dy)) ccds=[x1,y1,x2,y2] pointing={'label': obj, 'camera': ccds} return files
python
def fits_list(filter,root,fnames): """Get a list of files matching filter in directory root""" import re, pyfits, wcsutil for file in fnames: if re.match(filter,file): fh=pyfits.open(file) for ext in fh: obj=ext.header.get('OBJECT',file) dx=ext.header.get('NAXIS1',None) dy=ext.header.get('NAXIS2',None) wcs=wcsutil.WCSObject(ext) (x1,y1)=wcs.xy2rd((1,1,)) (x2,y2)=wcs.xy2rd((dx,dy)) ccds=[x1,y1,x2,y2] pointing={'label': obj, 'camera': ccds} return files
[ "def", "fits_list", "(", "filter", ",", "root", ",", "fnames", ")", ":", "import", "re", ",", "pyfits", ",", "wcsutil", "for", "file", "in", "fnames", ":", "if", "re", ".", "match", "(", "filter", ",", "file", ")", ":", "fh", "=", "pyfits", ".", ...
Get a list of files matching filter in directory root
[ "Get", "a", "list", "of", "files", "matching", "filter", "in", "directory", "root" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L137-L152
OSSOS/MOP
src/jjk/preproc/MOPplot.py
load_fis
def load_fis(dir=None): """Load fits images in a directory""" if dir is None: import tkFileDialog try: dir=tkFileDialog.askdirectory() except: return if dir is None: return None from os.path import walk walk(dir,fits_list,"*.fits")
python
def load_fis(dir=None): """Load fits images in a directory""" if dir is None: import tkFileDialog try: dir=tkFileDialog.askdirectory() except: return if dir is None: return None from os.path import walk walk(dir,fits_list,"*.fits")
[ "def", "load_fis", "(", "dir", "=", "None", ")", ":", "if", "dir", "is", "None", ":", "import", "tkFileDialog", "try", ":", "dir", "=", "tkFileDialog", ".", "askdirectory", "(", ")", "except", ":", "return", "if", "dir", "is", "None", ":", "return", ...
Load fits images in a directory
[ "Load", "fits", "images", "in", "a", "directory" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L155-L166
OSSOS/MOP
src/jjk/preproc/MOPplot.py
do_objs
def do_objs(kbos): """Draw the actual plot""" import orbfit, ephem, math import re re_string=w.FilterVar.get() vlist=[] for name in kbos: if not re.search(re_string,name): continue vlist.append(name) if type(kbos[name])==type(ephem.EllipticalBody()): kbos[name].compute(w.date.get()) ra=kbos[name].ra dec=kbos[name].dec a=math.radians(10.0/3600.0) b=a ang=0.0 color='blue' yoffset=+10 xoffset=+10 else: yoffset=-10 xoffset=-10 file=kbos[name] jdate=ephem.julian_date(w.date.get()) obs=568 try: position=orbfit.predict(file,jdate,obs) except: continue ra=math.radians(position[0]) dec=math.radians(position[1]) a=math.radians(position[2]/3600.0) b=math.radians(position[3]/3600.0) ang=math.radians(position[4]) if ( a> math.radians(1.0) ): color='green' else: color='black' if w.show_ellipse.get()==1 : if ( a < math.radians(5.0) ): w.create_ellipse(ra,dec,a,b,ang) if ( a < math.radians(1.0) ): w.create_point(ra,dec,size=2,color=color) if w.show_labels.get()==1: w.label(ra,dec,name,offset=[xoffset,yoffset]) vlist.sort() for v in vlist: w.objList.insert(END,v) w.plot_pointings()
python
def do_objs(kbos): """Draw the actual plot""" import orbfit, ephem, math import re re_string=w.FilterVar.get() vlist=[] for name in kbos: if not re.search(re_string,name): continue vlist.append(name) if type(kbos[name])==type(ephem.EllipticalBody()): kbos[name].compute(w.date.get()) ra=kbos[name].ra dec=kbos[name].dec a=math.radians(10.0/3600.0) b=a ang=0.0 color='blue' yoffset=+10 xoffset=+10 else: yoffset=-10 xoffset=-10 file=kbos[name] jdate=ephem.julian_date(w.date.get()) obs=568 try: position=orbfit.predict(file,jdate,obs) except: continue ra=math.radians(position[0]) dec=math.radians(position[1]) a=math.radians(position[2]/3600.0) b=math.radians(position[3]/3600.0) ang=math.radians(position[4]) if ( a> math.radians(1.0) ): color='green' else: color='black' if w.show_ellipse.get()==1 : if ( a < math.radians(5.0) ): w.create_ellipse(ra,dec,a,b,ang) if ( a < math.radians(1.0) ): w.create_point(ra,dec,size=2,color=color) if w.show_labels.get()==1: w.label(ra,dec,name,offset=[xoffset,yoffset]) vlist.sort() for v in vlist: w.objList.insert(END,v) w.plot_pointings()
[ "def", "do_objs", "(", "kbos", ")", ":", "import", "orbfit", ",", "ephem", ",", "math", "import", "re", "re_string", "=", "w", ".", "FilterVar", ".", "get", "(", ")", "vlist", "=", "[", "]", "for", "name", "in", "kbos", ":", "if", "not", "re", "....
Draw the actual plot
[ "Draw", "the", "actual", "plot" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L1201-L1251
OSSOS/MOP
src/jjk/preproc/MOPplot.py
plot.eps
def eps(self): """Print the canvas to a postscript file""" import tkFileDialog,tkMessageBox filename=tkFileDialog.asksaveasfilename(message="save postscript to file",filetypes=['eps','ps']) if filename is None: return self.postscript(file=filename)
python
def eps(self): """Print the canvas to a postscript file""" import tkFileDialog,tkMessageBox filename=tkFileDialog.asksaveasfilename(message="save postscript to file",filetypes=['eps','ps']) if filename is None: return self.postscript(file=filename)
[ "def", "eps", "(", "self", ")", ":", "import", "tkFileDialog", ",", "tkMessageBox", "filename", "=", "tkFileDialog", ".", "asksaveasfilename", "(", "message", "=", "\"save postscript to file\"", ",", "filetypes", "=", "[", "'eps'", ",", "'ps'", "]", ")", "if",...
Print the canvas to a postscript file
[ "Print", "the", "canvas", "to", "a", "postscript", "file" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L208-L216
OSSOS/MOP
src/jjk/preproc/MOPplot.py
plot.c2s
def c2s(self,p=[0,0]): """Convert from canvas to screen coordinates""" return((p[0]-self.canvasx(self.cx1),p[1]-self.canvasy(self.cy1)))
python
def c2s(self,p=[0,0]): """Convert from canvas to screen coordinates""" return((p[0]-self.canvasx(self.cx1),p[1]-self.canvasy(self.cy1)))
[ "def", "c2s", "(", "self", ",", "p", "=", "[", "0", ",", "0", "]", ")", ":", "return", "(", "(", "p", "[", "0", "]", "-", "self", ".", "canvasx", "(", "self", ".", "cx1", ")", ",", "p", "[", "1", "]", "-", "self", ".", "canvasy", "(", "...
Convert from canvas to screen coordinates
[ "Convert", "from", "canvas", "to", "screen", "coordinates" ]
train
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L250-L253