code stringlengths 1 18.2k |
|---|
vv.compare) ]) # Sort keys based on priority, high priority values first if sort: _compare_vals = sorted( _compare_vals, reverse=True, key=lambda key: (key.priority, key.name)) # Store for future retrieval cls._compare_vals = _compare_vals return cls._compare_vals |
def pretty(self): """Return a 'pretty' string representation of this `Key`. note: do not override the builtin `__str__` or `__repr__` methods! """ retval = ("Key(name={}, type={}, listable={}, compare={}, " "priority={}, kind_preference={}, " "replace_better={})").format( self.name, self.type, self.listable, self.compa... |
def check(self, val): """Make sure given value is consistent with this `Key` specification. NOTE: if `type` is 'None', then `listable` also is *not* checked. """ # If there is no `type` requirement, everything is allowed if self.type is None: return True is_list = isinstance(val, list) # If lists are not allowed, and t... |
False # `is_number` already checks for either list or single value if self.type == KEY_TYPES.NUMERIC and not is_number(val): return False elif (self.type == KEY_TYPES.TIME and not is_number(val) and '-' not in val and '/' not in val): return False elif self.type == KEY_TYPES.STRING: # If its a list, check first element... |
not isinstance(val, basestring): return False elif self.type == KEY_TYPES.BOOL: if is_list and not isinstance(val[0], bool): return False elif not isinstance(val, bool): return False return True |
def get_logger(name=None, stream_fmt=None, file_fmt=None, date_fmt=None, stream_level=None, file_level=None, tofile=None, tostr=True): """Create a standard logger object which logs to file and or stdout stream. If a logger has already been created in this session, it is returned (unless `name` is given). Arguments ----... |
to stream (stdout). If `None`, default settings are used. file_fmt : str or `None`, Format of log messages to file. If `None`, default settings are used. date_fmt : str or `None` Format of time stamps to stream and/or file. If `None`, default settings are used. stream_level : int, Logging level for stream. file_level :... |
Filename to log to (turned off if `None`). tostr : bool, Log to stdout stream. Returns ------- logger : ``logging.Logger`` object, Logger object to use for logging. """ if tofile is None and not tostr: raise ValueError( "Must log to something: `tofile` or `tostr` must be `True`.") logger = logging.getLogger(name) # Add... |
existing # one is being returned if hasattr(logger, '_OSC_LOGGER'): return logger else: logger._OSC_LOGGER = True # Set other custom parameters logger._LOADED = _LOADED_LEVEL # Make sure handlers don't get duplicated (ipython issue) while len(logger.handlers) > 0: logger.handlers.pop() # Prevents duplication or somethi... |
= _STREAM_LEVEL_DEF # Logger object must be at minimum level logger.setLevel(int(np.min([file_level, stream_level]))) if date_fmt is None: date_fmt = '%Y/%m/%d %H:%M:%S' # Log to file # ----------- if tofile is not None: if file_fmt is None: file_fmt = "%(asctime)s %(levelname)8.8s [%(filename)20.20s:" file_fmt += "%(f... |
# Log To stdout # ------------- if tostr: if stream_fmt is None: stream_fmt = "%(indent)s%(message)s" strFormatter = IndentFormatter(stream_fmt, datefmt=date_fmt) strHandler = logging.StreamHandler() strHandler.setFormatter(strFormatter) strHandler.setLevel(stream_level) logger.addHandler(strHandler) return logger |
def log_raise(log, err_str, err_type=RuntimeError): """Log an error message and raise an error. Arguments --------- log : `logging.Logger` object err_str : str Error message to be logged and raised. err_type : `Exception` object Type of error to raise. """ log.error(err_str) # Make sure output is flushed # (happens aut... |
def log_memory(log, pref=None, lvl=logging.DEBUG, raise_flag=True): """Log the current memory usage. """ import os import sys cyc_str = "" KB = 1024.0 if pref is not None: cyc_str += "{}: ".format(pref) # Linux returns units in Bytes; OSX in kilobytes UNIT = KB*KB if sys.platform == 'darwin' else KB good = False # Use ... |
process try: import resource max_self = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss max_child = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss _str = "RSS Max Self: {:7.2f} [MB], Child: {:7.2f} [MB]".format( max_self/UNIT, max_child/UNIT) cyc_str += _str except Exception as err: log.log(lvl, "resource.ge... |
= process.cpu_percent() mem_perc = process.memory_percent() num_thr = process.num_threads() _str = "; RSS: {:7.2f} [MB], {:7.2f}%; Threads: {:3d}, CPU: {:7.2f}%".format( rss/UNIT, mem_perc, num_thr, cpu_perc) cyc_str += _str except Exception as err: log.log(lvl, "psutil.Process failed. '{}'".format(str(err))) if raise_... |
def doblob(morphed, blobdet, img, anno=True): """ img: can be RGB (MxNx3) or gray (MxN) http://docs.opencv.org/master/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html http://docs.opencv.org/trunk/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html """ keypoints = blobdet.detect(mo... |
nkey, kpsize |
def load_args(self, args, clargs): """Parse arguments and return configuration settings. """ # Parse All Arguments args = self.parser.parse_args(args=clargs, namespace=args) # Print the help information if no subcommand is given # subcommand is required for operation if args.subcommand is None: self.parser.print_help()... |
def _setup_argparse(self): """Create `argparse` instance, and setup with appropriate parameters. """ parser = argparse.ArgumentParser( prog='catalog', description='Parent Catalog class for astrocats.') subparsers = parser.add_subparsers( description='valid subcommands', dest='subcommand') # Data Import # ----------- # ... |
def _add_parser_arguments_import(self, subparsers): """Create parser for 'import' subcommand, and associated arguments. """ import_pars = subparsers.add_parser( "import", help="Import data.") import_pars.add_argument( '--update', '-u', dest='update', default=False, action='store_true', help='Only update catalog using l... |
list of tasks to perform.') import_pars.add_argument( '--yes', dest='yes_task_list', nargs='+', default=None, help='space delimited list of tasks to turn on.') import_pars.add_argument( '--no', dest='no_task_list', nargs='+', default=None, help='space delimited list of tasks to turn off.') import_pars.add_argument( '--... |
import_pars |
def _add_parser_arguments_git(self, subparsers): """Create a sub-parsers for git subcommands. """ subparsers.add_parser( "git-clone", help="Clone all defined data repositories if they dont exist.") subparsers.add_parser( "git-push", help="Add all files to data repositories, commit, and push.") subparsers.add_parser( "g... |
all data repositories.") return |
def _add_parser_arguments_analyze(self, subparsers): """Create a parser for the 'analyze' subcommand. """ lyze_pars = subparsers.add_parser( "analyze", help="Perform basic analysis on this catalog.") lyze_pars.add_argument( '--count', '-c', dest='count', default=False, action='store_true', help='Determine counts of ent... |
def compress_gz(fname): """Compress the file with the given name and delete the uncompressed file. The compressed filename is simply the input filename with '.gz' appended. Arguments --------- fname : str Name of the file to compress and delete. Returns ------- comp_fname : str Name of the compressed file produced. Equ... |
with codecs.open(fname, 'rb') as f_in, gzip.open( comp_fname, 'wb') as f_out: shutil.copyfileobj(f_in, f_out) os.remove(fname) return comp_fname |
def draw_flow(img, flow, step=16, dtype=uint8): """ draws flow vectors on image this came from opencv/examples directory another way: http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_drawing_functions/py_drawing_functions.html """ maxval = iinfo(img.dtype).max # scaleFact = 1. #arbitary factor to make flow visib... |
(x+fx), (y+fy)]).T.reshape(-1, 2, 2) lines = int32(lines + 0.5) # create image if img.ndim == 2: # assume gray vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) else: # already RGB vis = img # draw line cv2.polylines(vis, lines, isClosed=False, color=canno, thickness=1, lineType=8) # draw filled green circles for (x1, y1), (... |
def draw_hsv(mag, ang, dtype=uint8, fn=None): """ mag must be uint8, uint16, uint32 and 2-D ang is in radians (float) """ assert mag.shape == ang.shape assert mag.ndim == 2 maxval = iinfo(dtype).max hsv = dstack(((degrees(ang)/2).astype(dtype), # /2 to keep less than 255 ones_like(mag)*maxval, # maxval must be after in... |
' + fn) cv2.imwrite(fn, rgb) return rgb |
def flow2magang(flow, dtype=uint8): """ flow dimensions y,x,2 3-D. flow[...,0] is magnitude, flow[...,1] is angle """ fx, fy = flow[..., 0], flow[..., 1] return hypot(fx, fy).astype(dtype), arctan2(fy, fx) + pi |
def IOC(dir, type, nr, size): """ dir One of IOC_NONE, IOC_WRITE, IOC_READ, or IOC_READ|IOC_WRITE. Direction is from the application's point of view, not kernel's. size (14-bits unsigned integer) Size of the buffer passed to ioctl's "arg" argument. """ assert dir <= _IOC_DIRMASK, dir assert type <= _IOC_TYPEMASK, type ... |
<< _IOC_TYPESHIFT) | (nr << _IOC_NRSHIFT) | (size << _IOC_SIZESHIFT) |
def IOC_TYPECHECK(t): """ Returns the size of given type, and check its suitability for use in an ioctl command number. """ result = ctypes.sizeof(t) assert result <= _IOC_SIZEMASK, result return result |
def IOR(type, nr, size): """ An ioctl with read parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ return IOC(IOC_READ, type, nr, IOC_TYPECHECK(size)) |
def IOW(type, nr, size): """ An ioctl with write parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ return IOC(IOC_WRITE, type, nr, IOC_TYPECHECK(size)) |
def IOWR(type, nr, size): """ An ioctl with both read an writes parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ return IOC(IOC_READ | IOC_WRITE, type, nr, IOC_TYPECHECK(size)) |
def _get_last_dirs(path, num=1): """Get a path including only the trailing `num` directories. Returns ------- last_path : str """ head, tail = os.path.split(path) last_path = str(tail) for ii in range(num): head, tail = os.path.split(head) last_path = os.path.join(tail, last_path) last_path = "..." + last_path return l... |
def analyze(self, args): """Run the analysis routines determined from the given `args`. """ self.log.info("Running catalog analysis") if args.count: self.count() return |
def count(self): """Analyze the counts of ...things. Returns ------- retvals : dict Dictionary of 'property-name: counts' pairs for further processing """ self.log.info("Running 'count'") retvals = {} # Numbers of 'tasks' num_tasks = self._count_tasks() retvals['num_tasks'] = num_tasks # Numbers of 'files' num_files = ... |
def _count_tasks(self): """Count the number of tasks, both in the json and directory. Returns ------- num_tasks : int The total number of all tasks included in the `tasks.json` file. """ self.log.warning("Tasks:") tasks, task_names = self.catalog._load_task_list_from_file() # Total number of all tasks num_tasks = len(t... |
python files in the tasks directory num_task_files = os.path.join(self.catalog.PATHS.tasks_dir, '*.py') num_task_files = len(glob(num_task_files)) tasks_str = "{} ({} default active) with {} task-files.".format( num_tasks, num_tasks_act, num_task_files) self.log.warning(tasks_str) return num_tasks |
def _count_repo_files(self): """Count the number of files in the data repositories. `_COUNT_FILE_TYPES` are used to determine which file types are checked explicitly. `_IGNORE_FILES` determine which files are ignored in (most) counts. Returns ------- repo_files : int Total number of (non-ignored) files in all data repo... |
# Get the last portion of the filepath for this repo last_path = _get_last_dirs(rep, 2) # Get counts for different file types n_all = self._count_files_by_type(rep, '*') n_type = np.zeros(len(self._COUNT_FILE_TYPES), dtype=int) for ii, ftype in enumerate(self._COUNT_FILE_TYPES): n_type[ii] = self._count_files_by_type(r... |
self._file_nums_str(n_all, n_type, n_ign) f_str = "{}: {}".format(last_path, f_str) self.log.warning(f_str) # Update cumulative counts num_files += n_all num_type += n_type num_ign += n_ign f_str = self._file_nums_str(num_files, num_type, num_ign) self.log.warning(f_str) return num_files |
def _file_nums_str(self, n_all, n_type, n_ign): """Construct a string showing the number of different file types. Returns ------- f_str : str """ # 'other' is the difference between all and named n_oth = n_all - np.sum(n_type) f_str = "{} Files".format(n_all) + " (" if len(n_type): f_str += ", ".join("{} {}".format(nam... |
{} ignored)".format(n_oth, n_ign) return f_str |
def _count_files_by_type(self, path, pattern, ignore=True): """Count files in the given path, with the given pattern. If `ignore = True`, skip files in the `_IGNORE_FILES` list. Returns ------- num_files : int """ # Get all files matching the given path and pattern files = glob(os.path.join(path, pattern)) # Count the ... |
num_files = len(files) return num_files |
def bibcode_from_url(cls, url): """Given a URL, try to find the ADS bibcode. Currently: only `ads` URLs will work, e.g. Returns ------- code : str or 'None' The Bibcode if found, otherwise 'None' """ try: code = url.split('/abs/') code = code[1].strip() return code except: return None |
def _get_save_path(self, bury=False): """Return the path that this Entry should be saved to.""" filename = self.get_filename(self[self._KEYS.NAME]) # Put objects that shouldn't belong in this catalog in the boneyard if bury: outdir = self.catalog.get_repo_boneyard() # Get normal repository save directory else: repo_fol... |
repositories found. Cannot save.\n" "Make sure that repo names are correctly configured " "in the `input/repos.json` file, and either manually or " "automatically (using `astrocats CATALOG git-clone`) " "clone the appropriate data repositories.") self.catalog.log.error(err_str) raise RuntimeError(err_str) outdir = repo... |
def _ordered(self, odict): """Convert the object into a plain OrderedDict.""" ndict = OrderedDict() if isinstance(odict, CatDict) or isinstance(odict, Entry): key = odict.sort_func else: key = None nkeys = list(sorted(odict.keys(), key=key)) for key in nkeys: if isinstance(odict[key], OrderedDict): odict[key] = self._o... |
= nlist ndict[key] = odict[key] return ndict |
def get_hash(self, keys=[]): """Return a unique hash associated with the listed keys.""" if not len(keys): keys = list(self.keys()) string_rep = '' oself = self._ordered(deepcopy(self)) for key in keys: string_rep += json.dumps(oself.get(key, ''), sort_keys=True) return hashlib.sha512(string_rep.encode()).hexdigest()[:... |
def _clean_quantity(self, quantity): """Clean quantity value before it is added to entry.""" value = quantity.get(QUANTITY.VALUE, '').strip() error = quantity.get(QUANTITY.E_VALUE, '').strip() unit = quantity.get(QUANTITY.U_VALUE, '').strip() kind = quantity.get(QUANTITY.KIND, '') if isinstance(kind, list) and not isin... |
Decimal(error) if value: quantity[QUANTITY.VALUE] = value if error: quantity[QUANTITY.E_VALUE] = error if unit: quantity[QUANTITY.U_VALUE] = unit if kind: quantity[QUANTITY.KIND] = kind return True |
def _convert_odict_to_classes(self, data, clean=False, merge=True, pop_schema=True, compare_to_existing=True, filter_on={}): """Convert `OrderedDict` into `Entry` or its derivative classes.""" self._log.debug("_convert_odict_to_classes(): {}".format(self.name())) self._log.debug("This should be a temporary fix. Dont be... |
be re-added every execution (done elsewhere) so # just delete the old entry if pop_schema: data.pop(schema_key) else: self[schema_key] = data.pop(schema_key) # Cleanup 'internal' repository stuff if clean: # Add data to `self` in ways accomodating 'internal' formats and # leeway. Removes each added entry from `data` so... |
= self._KEYS.SOURCES if src_key in data: # Remove from `data` sources = data.pop(src_key) self._log.debug("Found {} '{}' entries".format( len(sources), src_key)) self._log.debug("{}: {}".format(src_key, sources)) for src in sources: self.add_source(allow_alias=True, **src) # Handle `photometry` # ------------------- ph... |
fkey in photo and photo[fkey] not in filter_on[fkey]: skip = True if skip: continue self._add_cat_dict( Photometry, self._KEYS.PHOTOMETRY, compare_to_existing=compare_to_existing, **photo) phcount += 1 self._log.debug("Added {} '{}' entries".format( phcount, photo_key)) # Handle `spectra` # --------------- spec_key = s... |
self._log.debug("Found {} '{}' entries".format( len(spectra), spec_key)) for spec in spectra: self._add_cat_dict( Spectrum, self._KEYS.SPECTRA, compare_to_existing=compare_to_existing, **spec) # Handle `error` # -------------- err_key = self._KEYS.ERRORS if err_key in data: errors = data.pop(err_key) self._log.debug("F... |
always want to # require all of the normal spectrum data elements. model = data.pop(model_key) self._log.debug("Found {} '{}' entries".format( len(model), model_key)) for mod in model: self._add_cat_dict( Model, self._KEYS.MODELS, compare_to_existing=compare_to_existing, **mod) # Handle everything else --- should be `Q... |
be in lists of that quantity # E.g. `aliases` is a list of alias quantities if not isinstance(vals, list): vals = [vals] self._log.debug("{}: {}".format(key, vals)) for vv in vals: self._add_cat_dict( Quantity, key, check_for_dupes=merge, compare_to_existing=compare_to_existing, **vv) if merge and self.dupe_of: self.me... |
def _check_cat_dict_source(self, cat_dict_class, key_in_self, **kwargs): """Check that a source exists and that a quantity isn't erroneous.""" # Make sure that a source is given source = kwargs.get(cat_dict_class._KEYS.SOURCE, None) if source is None: raise CatDictError( "{}: `source` must be provided!".format(self[sel... |
" " integers!".format(self[self._KEYS.NAME]), warn=True) # If this source/data is erroneous, skip it if self.is_erroneous(key_in_self, source): self._log.info("This source is erroneous, skipping") return None # If this source/data is private, skip it if (self.catalog.args is not None and not self.catalog.args.private a... |
def _add_cat_dict(self, cat_dict_class, key_in_self, check_for_dupes=True, compare_to_existing=True, **kwargs): """Add a `CatDict` to this `Entry`. CatDict only added if initialization succeeds and it doesn't already exist within the Entry. """ # Make sure that a source is given, and is valid (nor erroneous) if cat_dic... |
str(err))) return False if source is None: return False # Try to create a new instance of this subclass of `CatDict` new_entry = self._init_cat_dict(cat_dict_class, key_in_self, **kwargs) if new_entry is None: return False # Compare this new entry with all previous entries to make sure is new if compare_to_existing and... |
in case we want to use any additional # tags to augment the old entry return new_entry # If this is an alias, add it to the parent catalog's reverse # dictionary linking aliases to names for fast lookup. if key_in_self == self._KEYS.ALIAS: # Check if this adding this alias makes us a dupe, if so mark # ourselves as a d... |
and 'aliases' in dir(self.catalog) and new_entry[QUANTITY.VALUE] in self.catalog.aliases): possible_dupe = self.catalog.aliases[new_entry[QUANTITY.VALUE]] # print(possible_dupe) if (possible_dupe != self[self._KEYS.NAME] and possible_dupe in self.catalog.entries): self.dupe_of.append(possible_dupe) if 'aliases' in dir(... |
def init_from_file(cls, catalog, name=None, path=None, clean=False, merge=True, pop_schema=True, ignore_keys=[], compare_to_existing=True, try_gzip=False, filter_on={}): """Construct a new `Entry` instance from an input file. The input file can be given explicitly by `path`, or a path will be constructed appropriately ... |
e.g. `SN1987A` for a `Supernova` entry. If no `path` is given, a path is constructed by trying to find a file in one of the 'output' repositories with this `name`. note: either `name` or `path` must be provided. path : str or 'None' The absolutely path of the input file. note: either `name` or `path` must be provided. ... |
processing should be done on the input data. This is mostly for input files from the 'internal' repositories. """ if not catalog: from astrocats.catalog.catalog import Catalog log = logging.getLogger() catalog = Catalog(None, log) catalog.log.debug("init_from_file()") if name is None and path is None: err = ("Either en... |
given, use that to load from load_path = '' if path is not None: load_path = path name = '' # If the name is given, try to find a path for it else: repo_paths = catalog.PATHS.get_repo_output_folders() for rep in repo_paths: filename = cls.get_filename(name) newpath = os.path.join(rep, filename + '.json') if os.path.isf... |
FIX: is this warning worthy? return None # Create a new `Entry` instance new_entry = cls(catalog, name) # Check if .gz file if try_gzip and not load_path.endswith('.gz'): try_gzip = False # Fill it with data from json file new_entry._load_data_from_json( load_path, clean=clean, merge=merge, pop_schema=pop_schema, ignor... |
def add_alias(self, alias, source, clean=True): """Add an alias, optionally 'cleaning' the alias string. Calls the parent `catalog` method `clean_entry_name` - to apply the same name-cleaning as is applied to entry names themselves. Returns ------- alias : str The stored version of the alias (cleaned or not). """ if cl... |
def add_error(self, value, **kwargs): """Add an `Error` instance to this entry.""" kwargs.update({ERROR.VALUE: value}) self._add_cat_dict(Error, self._KEYS.ERRORS, **kwargs) return |
def add_photometry(self, compare_to_existing=True, **kwargs): """Add a `Photometry` instance to this entry.""" self._add_cat_dict( Photometry, self._KEYS.PHOTOMETRY, compare_to_existing=compare_to_existing, **kwargs) return |
def merge_dupes(self): """Merge two entries that correspond to the same entry.""" for dupe in self.dupe_of: if dupe in self.catalog.entries: if self.catalog.entries[dupe]._stub: # merge = False to avoid infinite recursion self.catalog.load_entry_from_name( dupe, delete=True, merge=False) self.catalog.copy_entry_to_entr... |
def add_quantity(self, quantities, value, source, check_for_dupes=True, compare_to_existing=True, **kwargs): """Add an `Quantity` instance to this entry.""" success = True for quantity in listify(quantities): kwargs.update({QUANTITY.VALUE: value, QUANTITY.SOURCE: source}) cat_dict = self._add_cat_dict( Quantity, quanti... |
def add_self_source(self): """Add a source that refers to the catalog itself. For now this points to the Open Supernova Catalog by default. """ return self.add_source( bibcode=self.catalog.OSC_BIBCODE, name=self.catalog.OSC_NAME, url=self.catalog.OSC_URL, secondary=True) |
def add_source(self, allow_alias=False, **kwargs): """Add a `Source` instance to this entry.""" if not allow_alias and SOURCE.ALIAS in kwargs: err_str = "`{}` passed in kwargs, this shouldn't happen!".format( SOURCE.ALIAS) self._log.error(err_str) raise RuntimeError(err_str) # Set alias number to be +1 of current numbe... |
for item in self.get(self._KEYS.SOURCES, ''): if source_obj.is_duplicate_of(item): return item[item._KEYS.ALIAS] self.setdefault(self._KEYS.SOURCES, []).append(source_obj) return source_obj[source_obj._KEYS.ALIAS] |
def add_model(self, allow_alias=False, **kwargs): """Add a `Model` instance to this entry.""" if not allow_alias and MODEL.ALIAS in kwargs: err_str = "`{}` passed in kwargs, this shouldn't happen!".format( SOURCE.ALIAS) self._log.error(err_str) raise RuntimeError(err_str) # Set alias number to be +1 of current number o... |
for item in self.get(self._KEYS.MODELS, ''): if model_obj.is_duplicate_of(item): return item[item._KEYS.ALIAS] self.setdefault(self._KEYS.MODELS, []).append(model_obj) return model_obj[model_obj._KEYS.ALIAS] |
def add_spectrum(self, compare_to_existing=True, **kwargs): """Add a `Spectrum` instance to this entry.""" spec_key = self._KEYS.SPECTRA # Make sure that a source is given, and is valid (nor erroneous) source = self._check_cat_dict_source(Spectrum, spec_key, **kwargs) if source is None: return None # Try to create a ne... |
self.get(spec_key, []): # Only the `filename` should be compared for duplicates. If a # duplicate is found, that means the previous `exclude` array # should be saved to the new object, and the old deleted if new_spectrum.is_duplicate_of(item): if SPECTRUM.EXCLUDE in new_spectrum: item[SPECTRUM.EXCLUDE] = new_spectrum[S... |
def check(self): """Check that the entry has the required fields.""" # Make sure there is a schema key in dict if self._KEYS.SCHEMA not in self: self[self._KEYS.SCHEMA] = self.catalog.SCHEMA.URL # Make sure there is a name key in dict if (self._KEYS.NAME not in self or len(self[self._KEYS.NAME]) == 0): raise ValueError... |
def get_aliases(self, includename=True): """Retrieve the aliases of this object as a list of strings. Arguments --------- includename : bool Include the 'name' parameter in the list of aliases. """ # empty list if doesnt exist alias_quanta = self.get(self._KEYS.ALIAS, []) aliases = [aq[QUANTITY.VALUE] for aq in alias_q... |
def get_entry_text(self, fname): """Retrieve the raw text from a file.""" if fname.split('.')[-1] == 'gz': with gz.open(fname, 'rt') as f: filetext = f.read() else: with codecs.open(fname, 'r') as f: filetext = f.read() return filetext |
def get_source_by_alias(self, alias): """Given an alias, find the corresponding source in this entry. If the given alias doesn't exist (e.g. there are no sources), then a `ValueError` is raised. Arguments --------- alias : str The str-integer (e.g. '8') of the target source. Returns ------- source : `astrocats.catalog.... |
== alias: return source raise ValueError("Source '{}': alias '{}' not found!".format(self[ self._KEYS.NAME], alias)) |
def get_stub(self): """Get a new `Entry` which contains the 'stub' of this one. The 'stub' is only the name and aliases. Usage: ----- To convert a normal entry into a stub (for example), overwrite the entry in place, i.e. >>> entries[name] = entries[name].get_stub() Returns ------- stub : `astrocats.catalog.entry.Entry... |
self[self._KEYS.NAME], stub=True) if self._KEYS.ALIAS in self: stub[self._KEYS.ALIAS] = self[self._KEYS.ALIAS] if self._KEYS.DISTINCT_FROM in self: stub[self._KEYS.DISTINCT_FROM] = self[self._KEYS.DISTINCT_FROM] if self._KEYS.RA in self: stub[self._KEYS.RA] = self[self._KEYS.RA] if self._KEYS.DEC in self: stub[self._KE... |
def is_erroneous(self, field, sources): """Check if attribute has been marked as being erroneous.""" if self._KEYS.ERRORS in self: my_errors = self[self._KEYS.ERRORS] for alias in sources.split(','): source = self.get_source_by_alias(alias) bib_err_values = [ err[ERROR.VALUE] for err in my_errors if err[ERROR.KIND] == ... |
== SOURCE.NAME and err[ERROR.EXTRA] == field ] if (SOURCE.NAME in source and source[SOURCE.NAME] in name_err_values): return True return False |
def is_private(self, key, sources): """Check if attribute is private.""" # aliases are always public. if key == ENTRY.ALIAS: return False return all([ SOURCE.PRIVATE in self.get_source_by_alias(x) for x in sources.split(',') ]) |
def sanitize(self): """Sanitize the data (sort it, etc.) before writing it to disk. Template method that can be overridden in each catalog's subclassed `Entry` object. """ name = self[self._KEYS.NAME] aliases = self.get_aliases(includename=False) if name not in aliases: # Assign the first source to alias, if not availa... |
self.add_quantity(self._KEYS.ALIAS, name, source) else: source = self.add_self_source() self.add_quantity(self._KEYS.ALIAS, name, source) if self._KEYS.ALIAS in self: self[self._KEYS.ALIAS].sort( key=lambda key: alias_priority(name, key[QUANTITY.VALUE])) else: self._log.error( 'There should be at least one alias for `{... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.