repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FilesIterator.rename
python
def rename(self, old_key, new_key): assert new_key not in self assert old_key != new_key file_ = self[old_key] old_data = self.filesmap[old_key] # Create a new version with the new name obj = ObjectVersion.create( bucket=self.bucket, key=new_key, _file_id=file_.obj.file_id ) # Delete old key self.filesmap[new_key] = self.file_cls(obj, old_data).dumps() del self[old_key] return obj
Rename a file. :param old_key: Old key that holds the object. :param new_key: New key that will hold the object. :returns: The object that has been renamed.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L195-L218
null
class FilesIterator(object): """Iterator for files.""" def __init__(self, record, bucket=None, file_cls=None): """Initialize iterator.""" self._it = None self.record = record self.model = record.model self.file_cls = file_cls or FileObject self.bucket = bucket self.filesmap = OrderedDict([ (f['key'], f) for f in self.record.get('_files', []) ]) @property def keys(self): """Return file keys.""" return self.filesmap.keys() def __len__(self): """Get number of files.""" return ObjectVersion.get_by_bucket(self.bucket).count() def __iter__(self): """Get iterator.""" self._it = iter(sorted_files_from_bucket(self.bucket, self.keys)) return self def next(self): """Python 2.7 compatibility.""" return self.__next__() # pragma: no cover def __next__(self): """Get next file item.""" obj = next(self._it) return self.file_cls(obj, self.filesmap.get(obj.key, {})) def __contains__(self, key): """Test if file exists.""" return ObjectVersion.get_by_bucket( self.bucket).filter_by(key=key).count() def __getitem__(self, key): """Get a specific file.""" obj = ObjectVersion.get(self.bucket, key) if obj: return self.file_cls(obj, self.filesmap.get(obj.key, {})) raise KeyError(key) def flush(self): """Flush changes to record.""" files = self.dumps() # Do not create `_files` when there has not been `_files` field before # and the record still has no files attached. if files or '_files' in self.record: self.record['_files'] = files @_writable def __setitem__(self, key, stream): """Add file inside a deposit.""" with db.session.begin_nested(): # save the file obj = ObjectVersion.create( bucket=self.bucket, key=key, stream=stream) self.filesmap[key] = self.file_cls(obj, {}).dumps() self.flush() @_writable def __delitem__(self, key): """Delete a file from the deposit.""" obj = ObjectVersion.delete(bucket=self.bucket, key=key) if obj is None: raise KeyError(key) if key in self.filesmap: del self.filesmap[key] self.flush() def sort_by(self, *ids): """Update files order. :param ids: List of ids specifying the final status of the list. """ # Support sorting by file_ids or keys. files = {str(f_.file_id): f_.key for f_ in self} # self.record['_files'] = [{'key': files.get(id_, id_)} for id_ in ids] self.filesmap = OrderedDict([ (files.get(id_, id_), self[files.get(id_, id_)].dumps()) for id_ in ids ]) self.flush() @_writable def dumps(self, bucket=None): """Serialize files from a bucket. :param bucket: Instance of files :class:`invenio_files_rest.models.Bucket`. (Default: ``self.bucket``) :returns: List of serialized files. """ return [ self.file_cls(o, self.filesmap.get(o.key, {})).dumps() for o in sorted_files_from_bucket(bucket or self.bucket, self.keys) ]
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FilesIterator.dumps
python
def dumps(self, bucket=None): return [ self.file_cls(o, self.filesmap.get(o.key, {})).dumps() for o in sorted_files_from_bucket(bucket or self.bucket, self.keys) ]
Serialize files from a bucket. :param bucket: Instance of files :class:`invenio_files_rest.models.Bucket`. (Default: ``self.bucket``) :returns: List of serialized files.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L220-L231
[ "def sorted_files_from_bucket(bucket, keys=None):\n \"\"\"Return files from bucket sorted by given keys.\n\n :param bucket: :class:`~invenio_files_rest.models.Bucket` containing the\n files.\n :param keys: Keys order to be used.\n :returns: Sorted list of bucket items.\n \"\"\"\n keys = keys or []\n total = len(keys)\n sortby = dict(zip(keys, range(total)))\n values = ObjectVersion.get_by_bucket(bucket).all()\n return sorted(values, key=lambda x: sortby.get(x.key, total))\n" ]
class FilesIterator(object): """Iterator for files.""" def __init__(self, record, bucket=None, file_cls=None): """Initialize iterator.""" self._it = None self.record = record self.model = record.model self.file_cls = file_cls or FileObject self.bucket = bucket self.filesmap = OrderedDict([ (f['key'], f) for f in self.record.get('_files', []) ]) @property def keys(self): """Return file keys.""" return self.filesmap.keys() def __len__(self): """Get number of files.""" return ObjectVersion.get_by_bucket(self.bucket).count() def __iter__(self): """Get iterator.""" self._it = iter(sorted_files_from_bucket(self.bucket, self.keys)) return self def next(self): """Python 2.7 compatibility.""" return self.__next__() # pragma: no cover def __next__(self): """Get next file item.""" obj = next(self._it) return self.file_cls(obj, self.filesmap.get(obj.key, {})) def __contains__(self, key): """Test if file exists.""" return ObjectVersion.get_by_bucket( self.bucket).filter_by(key=key).count() def __getitem__(self, key): """Get a specific file.""" obj = ObjectVersion.get(self.bucket, key) if obj: return self.file_cls(obj, self.filesmap.get(obj.key, {})) raise KeyError(key) def flush(self): """Flush changes to record.""" files = self.dumps() # Do not create `_files` when there has not been `_files` field before # and the record still has no files attached. if files or '_files' in self.record: self.record['_files'] = files @_writable def __setitem__(self, key, stream): """Add file inside a deposit.""" with db.session.begin_nested(): # save the file obj = ObjectVersion.create( bucket=self.bucket, key=key, stream=stream) self.filesmap[key] = self.file_cls(obj, {}).dumps() self.flush() @_writable def __delitem__(self, key): """Delete a file from the deposit.""" obj = ObjectVersion.delete(bucket=self.bucket, key=key) if obj is None: raise KeyError(key) if key in self.filesmap: del self.filesmap[key] self.flush() def sort_by(self, *ids): """Update files order. :param ids: List of ids specifying the final status of the list. """ # Support sorting by file_ids or keys. files = {str(f_.file_id): f_.key for f_ in self} # self.record['_files'] = [{'key': files.get(id_, id_)} for id_ in ids] self.filesmap = OrderedDict([ (files.get(id_, id_), self[files.get(id_, id_)].dumps()) for id_ in ids ]) self.flush() @_writable def rename(self, old_key, new_key): """Rename a file. :param old_key: Old key that holds the object. :param new_key: New key that will hold the object. :returns: The object that has been renamed. """ assert new_key not in self assert old_key != new_key file_ = self[old_key] old_data = self.filesmap[old_key] # Create a new version with the new name obj = ObjectVersion.create( bucket=self.bucket, key=new_key, _file_id=file_.obj.file_id ) # Delete old key self.filesmap[new_key] = self.file_cls(obj, old_data).dumps() del self[old_key] return obj
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FilesMixin.files
python
def files(self): if self.model is None: raise MissingModelError() records_buckets = RecordsBuckets.query.filter_by( record_id=self.id).first() if not records_buckets: bucket = self._create_bucket() if not bucket: return None RecordsBuckets.create(record=self.model, bucket=bucket) else: bucket = records_buckets.bucket return self.files_iter_cls(self, bucket=bucket, file_cls=self.file_cls)
Get files iterator. :returns: Files iterator.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L263-L282
null
class FilesMixin(object): """Implement files attribute for Record models. .. note:: Implement ``_create_bucket()`` in subclass to allow files property to automatically create a bucket in case no bucket is present. """ file_cls = FileObject """File class used to generate the instance of files. Default to :class:`~invenio_records_files.api.FileObject` """ files_iter_cls = FilesIterator """Files iterator class used to generate the files iterator. Default to :class:`~invenio_records_files.api.FilesIterator` """ def _create_bucket(self): """Return an instance of ``Bucket`` class. .. note:: Reimplement in children class for custom behavior. :returns: Instance of :class:`invenio_files_rest.models.Bucket`. """ return None @property @files.setter def files(self, data): """Set files from data.""" current_files = self.files if current_files: raise RuntimeError('Can not update existing files.') for key in data: current_files[key] = data[key]
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FilesMixin.files
python
def files(self, data): current_files = self.files if current_files: raise RuntimeError('Can not update existing files.') for key in data: current_files[key] = data[key]
Set files from data.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L285-L291
null
class FilesMixin(object): """Implement files attribute for Record models. .. note:: Implement ``_create_bucket()`` in subclass to allow files property to automatically create a bucket in case no bucket is present. """ file_cls = FileObject """File class used to generate the instance of files. Default to :class:`~invenio_records_files.api.FileObject` """ files_iter_cls = FilesIterator """Files iterator class used to generate the files iterator. Default to :class:`~invenio_records_files.api.FilesIterator` """ def _create_bucket(self): """Return an instance of ``Bucket`` class. .. note:: Reimplement in children class for custom behavior. :returns: Instance of :class:`invenio_files_rest.models.Bucket`. """ return None @property def files(self): """Get files iterator. :returns: Files iterator. """ if self.model is None: raise MissingModelError() records_buckets = RecordsBuckets.query.filter_by( record_id=self.id).first() if not records_buckets: bucket = self._create_bucket() if not bucket: return None RecordsBuckets.create(record=self.model, bucket=bucket) else: bucket = records_buckets.bucket return self.files_iter_cls(self, bucket=bucket, file_cls=self.file_cls) @files.setter
inveniosoftware/invenio-records-files
invenio_records_files/api.py
Record.delete
python
def delete(self, force=False): if force: RecordsBuckets.query.filter_by( record=self.model, bucket=self.files.bucket ).delete() return super(Record, self).delete(force)
Delete a record and also remove the RecordsBuckets if necessary. :param force: True to remove also the :class:`~invenio_records_files.models.RecordsBuckets` object. :returns: Deleted record.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L297-L309
null
class Record(_Record, FilesMixin): """Define API for files manipulation using ``FilesMixin``."""
inveniosoftware/invenio-records-files
invenio_records_files/models.py
RecordsBuckets.create
python
def create(cls, record, bucket): rb = cls(record=record, bucket=bucket) db.session.add(rb) return rb
Create a new RecordsBuckets and adds it to the session. :param record: Record used to relate with the ``Bucket``. :param bucket: Bucket used to relate with the ``Record``. :returns: The :class:`~invenio_records_files.models.RecordsBuckets` object created.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/models.py#L48-L58
null
class RecordsBuckets(db.Model): """Relationship between Records and Buckets.""" __tablename__ = 'records_buckets' record_id = db.Column( UUIDType, db.ForeignKey(RecordMetadata.id), primary_key=True, nullable=False, # NOTE no unique constrain for better future ... ) """Record related with the bucket.""" bucket_id = db.Column( UUIDType, db.ForeignKey(Bucket.id), primary_key=True, nullable=False, ) """Bucket related with the record.""" bucket = db.relationship(Bucket) """Relationship to the bucket.""" record = db.relationship(RecordMetadata) """It is used by SQLAlchemy for optimistic concurrency control.""" @classmethod
inveniosoftware/invenio-records-files
invenio_records_files/utils.py
sorted_files_from_bucket
python
def sorted_files_from_bucket(bucket, keys=None): keys = keys or [] total = len(keys) sortby = dict(zip(keys, range(total))) values = ObjectVersion.get_by_bucket(bucket).all() return sorted(values, key=lambda x: sortby.get(x.key, total))
Return files from bucket sorted by given keys. :param bucket: :class:`~invenio_files_rest.models.Bucket` containing the files. :param keys: Keys order to be used. :returns: Sorted list of bucket items.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/utils.py#L19-L31
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Implementention of various utility functions.""" from __future__ import absolute_import, print_function from flask import abort, request from invenio_files_rest.models import ObjectVersion from invenio_files_rest.views import ObjectResource from invenio_records.errors import MissingModelError def record_file_factory(pid, record, filename): """Get file from a record. :param pid: Not used. It keeps the function signature. :param record: Record which contains the files. :param filename: Name of the file to be returned. :returns: File object or ``None`` if not found. """ try: if not (hasattr(record, 'files') and record.files): return None except MissingModelError: return None try: return record.files[filename] except KeyError: return None def file_download_ui(pid, record, _record_file_factory=None, **kwargs): """File download view for a given record. Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration: .. code-block:: python RECORDS_UI_ENDPOINTS = dict( recid=dict( # ... route='/records/<pid_value/files/<filename>', view_imp='invenio_records_files.utils:file_download_ui', record_class='invenio_records_files.api:Record', ) ) If ``download`` is passed as a querystring argument, the file is sent as an attachment. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` instance. :param record: The record metadata. """ _record_file_factory = _record_file_factory or record_file_factory # Extract file from record. fileobj = _record_file_factory( pid, record, kwargs.get('filename') ) if not fileobj: abort(404) obj = fileobj.obj # Check permissions ObjectResource.check_object_permission(obj) # Send file. return ObjectResource.send_object( obj.bucket, obj, expected_chksum=fileobj.get('checksum'), logger_data={ 'bucket_id': obj.bucket_id, 'pid_type': pid.pid_type, 'pid_value': pid.pid_value, }, as_attachment=('download' in request.args) )
inveniosoftware/invenio-records-files
invenio_records_files/utils.py
record_file_factory
python
def record_file_factory(pid, record, filename): try: if not (hasattr(record, 'files') and record.files): return None except MissingModelError: return None try: return record.files[filename] except KeyError: return None
Get file from a record. :param pid: Not used. It keeps the function signature. :param record: Record which contains the files. :param filename: Name of the file to be returned. :returns: File object or ``None`` if not found.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/utils.py#L34-L51
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Implementention of various utility functions.""" from __future__ import absolute_import, print_function from flask import abort, request from invenio_files_rest.models import ObjectVersion from invenio_files_rest.views import ObjectResource from invenio_records.errors import MissingModelError def sorted_files_from_bucket(bucket, keys=None): """Return files from bucket sorted by given keys. :param bucket: :class:`~invenio_files_rest.models.Bucket` containing the files. :param keys: Keys order to be used. :returns: Sorted list of bucket items. """ keys = keys or [] total = len(keys) sortby = dict(zip(keys, range(total))) values = ObjectVersion.get_by_bucket(bucket).all() return sorted(values, key=lambda x: sortby.get(x.key, total)) def file_download_ui(pid, record, _record_file_factory=None, **kwargs): """File download view for a given record. Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration: .. code-block:: python RECORDS_UI_ENDPOINTS = dict( recid=dict( # ... route='/records/<pid_value/files/<filename>', view_imp='invenio_records_files.utils:file_download_ui', record_class='invenio_records_files.api:Record', ) ) If ``download`` is passed as a querystring argument, the file is sent as an attachment. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` instance. :param record: The record metadata. """ _record_file_factory = _record_file_factory or record_file_factory # Extract file from record. fileobj = _record_file_factory( pid, record, kwargs.get('filename') ) if not fileobj: abort(404) obj = fileobj.obj # Check permissions ObjectResource.check_object_permission(obj) # Send file. return ObjectResource.send_object( obj.bucket, obj, expected_chksum=fileobj.get('checksum'), logger_data={ 'bucket_id': obj.bucket_id, 'pid_type': pid.pid_type, 'pid_value': pid.pid_value, }, as_attachment=('download' in request.args) )
inveniosoftware/invenio-records-files
invenio_records_files/utils.py
file_download_ui
python
def file_download_ui(pid, record, _record_file_factory=None, **kwargs): _record_file_factory = _record_file_factory or record_file_factory # Extract file from record. fileobj = _record_file_factory( pid, record, kwargs.get('filename') ) if not fileobj: abort(404) obj = fileobj.obj # Check permissions ObjectResource.check_object_permission(obj) # Send file. return ObjectResource.send_object( obj.bucket, obj, expected_chksum=fileobj.get('checksum'), logger_data={ 'bucket_id': obj.bucket_id, 'pid_type': pid.pid_type, 'pid_value': pid.pid_value, }, as_attachment=('download' in request.args) )
File download view for a given record. Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration: .. code-block:: python RECORDS_UI_ENDPOINTS = dict( recid=dict( # ... route='/records/<pid_value/files/<filename>', view_imp='invenio_records_files.utils:file_download_ui', record_class='invenio_records_files.api:Record', ) ) If ``download`` is passed as a querystring argument, the file is sent as an attachment. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` instance. :param record: The record metadata.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/utils.py#L54-L101
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Implementention of various utility functions.""" from __future__ import absolute_import, print_function from flask import abort, request from invenio_files_rest.models import ObjectVersion from invenio_files_rest.views import ObjectResource from invenio_records.errors import MissingModelError def sorted_files_from_bucket(bucket, keys=None): """Return files from bucket sorted by given keys. :param bucket: :class:`~invenio_files_rest.models.Bucket` containing the files. :param keys: Keys order to be used. :returns: Sorted list of bucket items. """ keys = keys or [] total = len(keys) sortby = dict(zip(keys, range(total))) values = ObjectVersion.get_by_bucket(bucket).all() return sorted(values, key=lambda x: sortby.get(x.key, total)) def record_file_factory(pid, record, filename): """Get file from a record. :param pid: Not used. It keeps the function signature. :param record: Record which contains the files. :param filename: Name of the file to be returned. :returns: File object or ``None`` if not found. """ try: if not (hasattr(record, 'files') and record.files): return None except MissingModelError: return None try: return record.files[filename] except KeyError: return None
inveniosoftware/invenio-records-files
invenio_records_files/links.py
default_bucket_link_factory
python
def default_bucket_link_factory(pid): try: record = Record.get_record(pid.get_assigned_object()) bucket = record.files.bucket return url_for('invenio_files_rest.bucket_api', bucket_id=bucket.id, _external=True) except AttributeError: return None
Factory for record bucket generation.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/links.py#L16-L25
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Link for file bucket creation.""" from flask import url_for from .api import Record
tmoerman/arboreto
arboreto/core.py
to_tf_matrix
python
def to_tf_matrix(expression_matrix, gene_names, tf_names): tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names] tf_indices = [t[0] for t in tuples] tf_matrix_names = [t[1] for t in tuples] return expression_matrix[:, tf_indices], tf_matrix_names
:param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: a list of transcription factor names. Should be a subset of gene_names. :return: tuple of: 0: A numpy matrix representing the predictor matrix for the regressions. 1: The gene names corresponding to the columns in the predictor matrix.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L85-L102
null
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from dask.dataframe.utils import make_meta logger = logging.getLogger(__name__) DEMON_SEED = 666 ANGEL_SEED = 777 EARLY_STOP_WINDOW_LENGTH = 25 SKLEARN_REGRESSOR_FACTORY = { 'RF': RandomForestRegressor, 'ET': ExtraTreesRegressor, 'GBM': GradientBoostingRegressor } # scikit-learn random forest regressor RF_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn extra-trees regressor ET_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn gradient boosting regressor GBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 500, 'max_features': 0.1 } # scikit-learn stochastic gradient boosting regressor SGBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 5000, # can be arbitrarily large 'max_features': 0.1, 'subsample': 0.9 } def is_sklearn_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API. """ return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys() def is_xgboost_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: boolean indicating whether the regressor type is the xgboost regressor. """ return regressor_type.upper() == 'XGB' def is_oob_heuristic_supported(regressor_type, regressor_kwargs): """ :param regressor_type: on :param regressor_kwargs: :return: whether early stopping heuristic based on out-of-bag improvement is supported. """ return \ regressor_type.upper() == 'GBM' and \ 'subsample' in regressor_kwargs and \ regressor_kwargs['subsample'] < 1.0 def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param tf_matrix: the predictor matrix (transcription factor matrix) as a numpy array. :param target_gene_expression: the target (y) gene expression to predict in function of the tf_matrix (X). :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: a trained regression model. """ regressor_type = regressor_type.upper() assert tf_matrix.shape[0] == len(target_gene_expression) def do_sklearn_regression(): regressor = SKLEARN_REGRESSOR_FACTORY[regressor_type](random_state=seed, **regressor_kwargs) with_early_stopping = is_oob_heuristic_supported(regressor_type, regressor_kwargs) if with_early_stopping: regressor.fit(tf_matrix, target_gene_expression, monitor=EarlyStopMonitor(early_stop_window_length)) else: regressor.fit(tf_matrix, target_gene_expression) return regressor if is_sklearn_regressor(regressor_type): return do_sklearn_regression() # elif is_xgboost_regressor(regressor_type): # raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: {0}'.format(regressor_type)) def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): """ Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used. This enables prioritizing links that were inferred in a regression where lots of :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :return: the feature importances inferred from the trained model. """ if is_oob_heuristic_supported(regressor_type, regressor_kwargs): n_estimators = len(trained_regressor.estimators_) denormalized_importances = trained_regressor.feature_importances_ * n_estimators return denormalized_importances else: return trained_regressor.feature_importances_ def to_meta_df(trained_regressor, target_gene_name): """ :param trained_regressor: the trained model from which to extract the meta information. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame containing side information about the regression. """ n_estimators = len(trained_regressor.estimators_) return pd.DataFrame({'target': [target_gene_name], 'n_estimators': [n_estimators]}) def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :param tf_matrix_gene_names: the list of names corresponding to the columns of the tf_matrix used to train the model. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame['TF', 'target', 'importance'] representing inferred regulatory links and their connection strength. """ def pythonic(): # feature_importances = trained_regressor.feature_importances_ feature_importances = to_feature_importances(regressor_type, regressor_kwargs, trained_regressor) links_df = pd.DataFrame({'TF': tf_matrix_gene_names, 'importance': feature_importances}) links_df['target'] = target_gene_name clean_links_df = links_df[links_df.importance > 0].sort_values(by='importance', ascending=False) return clean_links_df[['TF', 'target', 'importance']] if is_sklearn_regressor(regressor_type): return pythonic() elif is_xgboost_regressor(regressor_type): raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: ' + regressor_type) def clean(tf_matrix, tf_matrix_gene_names, target_gene_name): """ :param tf_matrix: numpy array. The full transcription factor matrix. :param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns. :param target_gene_name: the target gene to remove from the tf_matrix and tf_names. :return: a tuple of (matrix, names) equal to the specified ones minus the target_gene_name if the target happens to be one of the transcription factors. If not, the specified (tf_matrix, tf_names) is returned verbatim. """ if target_gene_name not in tf_matrix_gene_names: clean_tf_matrix = tf_matrix else: clean_tf_matrix = np.delete(tf_matrix, tf_matrix_gene_names.index(target_gene_name), 1) clean_tf_names = [tf for tf in tf_matrix_gene_names if tf != target_gene_name] assert clean_tf_matrix.shape[1] == len(clean_tf_names) # sanity check return clean_tf_matrix, clean_tf_names def retry(fn, max_retries=10, warning_msg=None, fallback_result=None): """ Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn: * https://github.com/scikit-learn/scikit-learn/issues/2755 * https://github.com/scikit-learn/scikit-learn/issues/7346 :param fn: the function to retry. :param max_retries: the maximum number of retries to attempt. :param warning_msg: a warning message to display when an attempt fails. :param fallback_result: result to return when all attempts fail. :return: Returns the result of fn if one attempt succeeds, else return fallback_result. """ nr_retries = 0 result = fallback_result for attempt in range(max_retries): try: result = fn() except Exception as cause: nr_retries += 1 msg_head = '' if warning_msg is None else repr(warning_msg) + ' ' msg_tail = "Retry ({1}/{2}). Failure caused by {0}.".format(repr(cause), nr_retries, max_retries) logger.warning(msg_head + msg_tail) else: break return result def infer_partial_network(regressor_type, regressor_kwargs, tf_matrix, tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ Ties together regressor model training with regulatory links and meta data extraction. :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param tf_matrix: numpy matrix. The feature matrix X to use for the regression. :param tf_matrix_gene_names: list of transcription factor names corresponding to the columns of the tf_matrix used to train the regression model. :param target_gene_name: the name of the target gene to infer the regulatory links for. :param target_gene_expression: the expression profile of the target gene. Numpy array. :param include_meta: whether to also return the meta information DataFrame. :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: if include_meta == True, return links_df, meta_df link_df: a Pandas DataFrame['TF', 'target', 'importance'] containing inferred regulatory links and their connection strength. meta_df: a Pandas DataFrame['target', 'meta', 'value'] containing meta information regarding the trained regression model. """ def fn(): (clean_tf_matrix, clean_tf_matrix_gene_names) = clean(tf_matrix, tf_matrix_gene_names, target_gene_name) try: trained_regressor = fit_model(regressor_type, regressor_kwargs, clean_tf_matrix, target_gene_expression, early_stop_window_length, seed) except ValueError as e: raise ValueError("Regression for target gene {0} failed. Cause {1}.".format(target_gene_name, repr(e))) links_df = to_links_df(regressor_type, regressor_kwargs, trained_regressor, clean_tf_matrix_gene_names, target_gene_name) if include_meta: meta_df = to_meta_df(trained_regressor, target_gene_name) return links_df, meta_df else: return links_df fallback_result = (None, None) if include_meta else None return retry(fn, fallback_result=fallback_result, warning_msg='infer_data failed for target {0}'.format(target_gene_name)) def target_gene_indices(gene_names, target_genes): """ :param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix. """ if isinstance(target_genes, list) and len(target_genes) == 0: return [] if isinstance(target_genes, str) and target_genes.upper() == 'ALL': return list(range(len(gene_names))) elif isinstance(target_genes, int): top_n = target_genes assert top_n > 0 return list(range(min(top_n, len(gene_names)))) elif isinstance(target_genes, list): if not target_genes: # target_genes is empty return target_genes elif all(isinstance(target_gene, str) for target_gene in target_genes): return [index for index, gene in enumerate(gene_names) if gene in target_genes] elif all(isinstance(target_gene, int) for target_gene in target_genes): return target_genes else: raise ValueError("Mixed types in target genes.") else: raise ValueError("Unable to interpret target_genes.") _GRN_SCHEMA = make_meta({'TF': str, 'target': str, 'importance': float}) _META_SCHEMA = make_meta({'target': str, 'n_estimators': int}) def create_graph(expression_matrix, gene_names, tf_names, regressor_type, regressor_kwargs, client, target_genes='all', limit=None, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, repartition_multiplier=1, seed=DEMON_SEED): """ Main API function. Create a Dask computation graph. Note: fixing the GC problems was fixed by 2 changes: [1] and [2] !!! :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: list of transcription factor names. Should have a non-empty intersection with gene_names. :param regressor_type: regressor type. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param client: a dask.distributed client instance. * Used to scatter-broadcast the tf matrix to the workers instead of simply wrapping in a delayed(). :param target_genes: either int, 'all' or a collection that is a subset of gene_names. :param limit: optional number of top regulatory links to return. Default None. :param include_meta: Also return the meta DataFrame. Default False. :param early_stop_window_length: window length of the early stopping monitor. :param repartition_multiplier: multiplier :param seed: (optional) random seed for the regressors. Default 666. :return: if include_meta is False, returns a Dask graph that computes the links DataFrame. If include_meta is True, returns a tuple: the links DataFrame and the meta DataFrame. """ assert expression_matrix.shape[1] == len(gene_names) assert client, "client is required" tf_matrix, tf_matrix_gene_names = to_tf_matrix(expression_matrix, gene_names, tf_names) future_tf_matrix = client.scatter(tf_matrix, broadcast=True) # [1] wrap in a list of 1 -> unsure why but Matt. Rocklin does this often... [future_tf_matrix_gene_names] = client.scatter([tf_matrix_gene_names], broadcast=True) delayed_link_dfs = [] # collection of delayed link DataFrames delayed_meta_dfs = [] # collection of delayed meta DataFrame for target_gene_index in target_gene_indices(gene_names, target_genes): target_gene_name = delayed(gene_names[target_gene_index], pure=True) target_gene_expression = delayed(expression_matrix[:, target_gene_index], pure=True) if include_meta: delayed_link_df, delayed_meta_df = delayed(infer_partial_network, pure=True, nout=2)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) delayed_meta_dfs.append(delayed_meta_df) else: delayed_link_df = delayed(infer_partial_network, pure=True)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) # gather the DataFrames into one distributed DataFrame all_links_df = from_delayed(delayed_link_dfs, meta=_GRN_SCHEMA) all_meta_df = from_delayed(delayed_meta_dfs, meta=_META_SCHEMA) # optionally limit the number of resulting regulatory links, descending by top importance if limit: maybe_limited_links_df = all_links_df.nlargest(limit, columns=['importance']) else: maybe_limited_links_df = all_links_df # [2] repartition to nr of workers -> important to avoid GC problems! # see: http://dask.pydata.org/en/latest/dataframe-performance.html#repartition-to-reduce-overhead n_parts = len(client.ncores()) * repartition_multiplier if include_meta: return maybe_limited_links_df.repartition(npartitions=n_parts), \ all_meta_df.repartition(npartitions=n_parts) else: return maybe_limited_links_df.repartition(npartitions=n_parts) class EarlyStopMonitor: def __init__(self, window_length=EARLY_STOP_WINDOW_LENGTH): """ :param window_length: length of the window over the out-of-bag errors. """ self.window_length = window_length def window_boundaries(self, current_round): """ :param current_round: :return: the low and high boundaries of the estimators window to consider. """ lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi def __call__(self, current_round, regressor, _): """ Implementation of the GradientBoostingRegressor monitor function API. :param current_round: the current boosting round. :param regressor: the regressor. :param _: ignored. :return: True if the regressor should stop early, else False. """ if current_round >= self.window_length - 1: lo, hi = self.window_boundaries(current_round) return np.mean(regressor.oob_improvement_[lo: hi]) < 0 else: return False
tmoerman/arboreto
arboreto/core.py
fit_model
python
def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): regressor_type = regressor_type.upper() assert tf_matrix.shape[0] == len(target_gene_expression) def do_sklearn_regression(): regressor = SKLEARN_REGRESSOR_FACTORY[regressor_type](random_state=seed, **regressor_kwargs) with_early_stopping = is_oob_heuristic_supported(regressor_type, regressor_kwargs) if with_early_stopping: regressor.fit(tf_matrix, target_gene_expression, monitor=EarlyStopMonitor(early_stop_window_length)) else: regressor.fit(tf_matrix, target_gene_expression) return regressor if is_sklearn_regressor(regressor_type): return do_sklearn_regression() # elif is_xgboost_regressor(regressor_type): # raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: {0}'.format(regressor_type))
:param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param tf_matrix: the predictor matrix (transcription factor matrix) as a numpy array. :param target_gene_expression: the target (y) gene expression to predict in function of the tf_matrix (X). :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: a trained regression model.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L105-L141
[ "def is_sklearn_regressor(regressor_type):\n \"\"\"\n :param regressor_type: string. Case insensitive.\n :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API.\n \"\"\"\n return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys()\n", "def do_sklearn_regression():\n regressor = SKLEARN_REGRESSOR_FACTORY[regressor_type](random_state=seed, **regressor_kwargs)\n\n with_early_stopping = is_oob_heuristic_supported(regressor_type, regressor_kwargs)\n\n if with_early_stopping:\n regressor.fit(tf_matrix, target_gene_expression, monitor=EarlyStopMonitor(early_stop_window_length))\n else:\n regressor.fit(tf_matrix, target_gene_expression)\n\n return regressor\n" ]
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from dask.dataframe.utils import make_meta logger = logging.getLogger(__name__) DEMON_SEED = 666 ANGEL_SEED = 777 EARLY_STOP_WINDOW_LENGTH = 25 SKLEARN_REGRESSOR_FACTORY = { 'RF': RandomForestRegressor, 'ET': ExtraTreesRegressor, 'GBM': GradientBoostingRegressor } # scikit-learn random forest regressor RF_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn extra-trees regressor ET_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn gradient boosting regressor GBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 500, 'max_features': 0.1 } # scikit-learn stochastic gradient boosting regressor SGBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 5000, # can be arbitrarily large 'max_features': 0.1, 'subsample': 0.9 } def is_sklearn_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API. """ return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys() def is_xgboost_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: boolean indicating whether the regressor type is the xgboost regressor. """ return regressor_type.upper() == 'XGB' def is_oob_heuristic_supported(regressor_type, regressor_kwargs): """ :param regressor_type: on :param regressor_kwargs: :return: whether early stopping heuristic based on out-of-bag improvement is supported. """ return \ regressor_type.upper() == 'GBM' and \ 'subsample' in regressor_kwargs and \ regressor_kwargs['subsample'] < 1.0 def to_tf_matrix(expression_matrix, gene_names, tf_names): """ :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: a list of transcription factor names. Should be a subset of gene_names. :return: tuple of: 0: A numpy matrix representing the predictor matrix for the regressions. 1: The gene names corresponding to the columns in the predictor matrix. """ tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names] tf_indices = [t[0] for t in tuples] tf_matrix_names = [t[1] for t in tuples] return expression_matrix[:, tf_indices], tf_matrix_names def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): """ Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used. This enables prioritizing links that were inferred in a regression where lots of :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :return: the feature importances inferred from the trained model. """ if is_oob_heuristic_supported(regressor_type, regressor_kwargs): n_estimators = len(trained_regressor.estimators_) denormalized_importances = trained_regressor.feature_importances_ * n_estimators return denormalized_importances else: return trained_regressor.feature_importances_ def to_meta_df(trained_regressor, target_gene_name): """ :param trained_regressor: the trained model from which to extract the meta information. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame containing side information about the regression. """ n_estimators = len(trained_regressor.estimators_) return pd.DataFrame({'target': [target_gene_name], 'n_estimators': [n_estimators]}) def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :param tf_matrix_gene_names: the list of names corresponding to the columns of the tf_matrix used to train the model. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame['TF', 'target', 'importance'] representing inferred regulatory links and their connection strength. """ def pythonic(): # feature_importances = trained_regressor.feature_importances_ feature_importances = to_feature_importances(regressor_type, regressor_kwargs, trained_regressor) links_df = pd.DataFrame({'TF': tf_matrix_gene_names, 'importance': feature_importances}) links_df['target'] = target_gene_name clean_links_df = links_df[links_df.importance > 0].sort_values(by='importance', ascending=False) return clean_links_df[['TF', 'target', 'importance']] if is_sklearn_regressor(regressor_type): return pythonic() elif is_xgboost_regressor(regressor_type): raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: ' + regressor_type) def clean(tf_matrix, tf_matrix_gene_names, target_gene_name): """ :param tf_matrix: numpy array. The full transcription factor matrix. :param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns. :param target_gene_name: the target gene to remove from the tf_matrix and tf_names. :return: a tuple of (matrix, names) equal to the specified ones minus the target_gene_name if the target happens to be one of the transcription factors. If not, the specified (tf_matrix, tf_names) is returned verbatim. """ if target_gene_name not in tf_matrix_gene_names: clean_tf_matrix = tf_matrix else: clean_tf_matrix = np.delete(tf_matrix, tf_matrix_gene_names.index(target_gene_name), 1) clean_tf_names = [tf for tf in tf_matrix_gene_names if tf != target_gene_name] assert clean_tf_matrix.shape[1] == len(clean_tf_names) # sanity check return clean_tf_matrix, clean_tf_names def retry(fn, max_retries=10, warning_msg=None, fallback_result=None): """ Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn: * https://github.com/scikit-learn/scikit-learn/issues/2755 * https://github.com/scikit-learn/scikit-learn/issues/7346 :param fn: the function to retry. :param max_retries: the maximum number of retries to attempt. :param warning_msg: a warning message to display when an attempt fails. :param fallback_result: result to return when all attempts fail. :return: Returns the result of fn if one attempt succeeds, else return fallback_result. """ nr_retries = 0 result = fallback_result for attempt in range(max_retries): try: result = fn() except Exception as cause: nr_retries += 1 msg_head = '' if warning_msg is None else repr(warning_msg) + ' ' msg_tail = "Retry ({1}/{2}). Failure caused by {0}.".format(repr(cause), nr_retries, max_retries) logger.warning(msg_head + msg_tail) else: break return result def infer_partial_network(regressor_type, regressor_kwargs, tf_matrix, tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ Ties together regressor model training with regulatory links and meta data extraction. :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param tf_matrix: numpy matrix. The feature matrix X to use for the regression. :param tf_matrix_gene_names: list of transcription factor names corresponding to the columns of the tf_matrix used to train the regression model. :param target_gene_name: the name of the target gene to infer the regulatory links for. :param target_gene_expression: the expression profile of the target gene. Numpy array. :param include_meta: whether to also return the meta information DataFrame. :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: if include_meta == True, return links_df, meta_df link_df: a Pandas DataFrame['TF', 'target', 'importance'] containing inferred regulatory links and their connection strength. meta_df: a Pandas DataFrame['target', 'meta', 'value'] containing meta information regarding the trained regression model. """ def fn(): (clean_tf_matrix, clean_tf_matrix_gene_names) = clean(tf_matrix, tf_matrix_gene_names, target_gene_name) try: trained_regressor = fit_model(regressor_type, regressor_kwargs, clean_tf_matrix, target_gene_expression, early_stop_window_length, seed) except ValueError as e: raise ValueError("Regression for target gene {0} failed. Cause {1}.".format(target_gene_name, repr(e))) links_df = to_links_df(regressor_type, regressor_kwargs, trained_regressor, clean_tf_matrix_gene_names, target_gene_name) if include_meta: meta_df = to_meta_df(trained_regressor, target_gene_name) return links_df, meta_df else: return links_df fallback_result = (None, None) if include_meta else None return retry(fn, fallback_result=fallback_result, warning_msg='infer_data failed for target {0}'.format(target_gene_name)) def target_gene_indices(gene_names, target_genes): """ :param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix. """ if isinstance(target_genes, list) and len(target_genes) == 0: return [] if isinstance(target_genes, str) and target_genes.upper() == 'ALL': return list(range(len(gene_names))) elif isinstance(target_genes, int): top_n = target_genes assert top_n > 0 return list(range(min(top_n, len(gene_names)))) elif isinstance(target_genes, list): if not target_genes: # target_genes is empty return target_genes elif all(isinstance(target_gene, str) for target_gene in target_genes): return [index for index, gene in enumerate(gene_names) if gene in target_genes] elif all(isinstance(target_gene, int) for target_gene in target_genes): return target_genes else: raise ValueError("Mixed types in target genes.") else: raise ValueError("Unable to interpret target_genes.") _GRN_SCHEMA = make_meta({'TF': str, 'target': str, 'importance': float}) _META_SCHEMA = make_meta({'target': str, 'n_estimators': int}) def create_graph(expression_matrix, gene_names, tf_names, regressor_type, regressor_kwargs, client, target_genes='all', limit=None, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, repartition_multiplier=1, seed=DEMON_SEED): """ Main API function. Create a Dask computation graph. Note: fixing the GC problems was fixed by 2 changes: [1] and [2] !!! :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: list of transcription factor names. Should have a non-empty intersection with gene_names. :param regressor_type: regressor type. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param client: a dask.distributed client instance. * Used to scatter-broadcast the tf matrix to the workers instead of simply wrapping in a delayed(). :param target_genes: either int, 'all' or a collection that is a subset of gene_names. :param limit: optional number of top regulatory links to return. Default None. :param include_meta: Also return the meta DataFrame. Default False. :param early_stop_window_length: window length of the early stopping monitor. :param repartition_multiplier: multiplier :param seed: (optional) random seed for the regressors. Default 666. :return: if include_meta is False, returns a Dask graph that computes the links DataFrame. If include_meta is True, returns a tuple: the links DataFrame and the meta DataFrame. """ assert expression_matrix.shape[1] == len(gene_names) assert client, "client is required" tf_matrix, tf_matrix_gene_names = to_tf_matrix(expression_matrix, gene_names, tf_names) future_tf_matrix = client.scatter(tf_matrix, broadcast=True) # [1] wrap in a list of 1 -> unsure why but Matt. Rocklin does this often... [future_tf_matrix_gene_names] = client.scatter([tf_matrix_gene_names], broadcast=True) delayed_link_dfs = [] # collection of delayed link DataFrames delayed_meta_dfs = [] # collection of delayed meta DataFrame for target_gene_index in target_gene_indices(gene_names, target_genes): target_gene_name = delayed(gene_names[target_gene_index], pure=True) target_gene_expression = delayed(expression_matrix[:, target_gene_index], pure=True) if include_meta: delayed_link_df, delayed_meta_df = delayed(infer_partial_network, pure=True, nout=2)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) delayed_meta_dfs.append(delayed_meta_df) else: delayed_link_df = delayed(infer_partial_network, pure=True)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) # gather the DataFrames into one distributed DataFrame all_links_df = from_delayed(delayed_link_dfs, meta=_GRN_SCHEMA) all_meta_df = from_delayed(delayed_meta_dfs, meta=_META_SCHEMA) # optionally limit the number of resulting regulatory links, descending by top importance if limit: maybe_limited_links_df = all_links_df.nlargest(limit, columns=['importance']) else: maybe_limited_links_df = all_links_df # [2] repartition to nr of workers -> important to avoid GC problems! # see: http://dask.pydata.org/en/latest/dataframe-performance.html#repartition-to-reduce-overhead n_parts = len(client.ncores()) * repartition_multiplier if include_meta: return maybe_limited_links_df.repartition(npartitions=n_parts), \ all_meta_df.repartition(npartitions=n_parts) else: return maybe_limited_links_df.repartition(npartitions=n_parts) class EarlyStopMonitor: def __init__(self, window_length=EARLY_STOP_WINDOW_LENGTH): """ :param window_length: length of the window over the out-of-bag errors. """ self.window_length = window_length def window_boundaries(self, current_round): """ :param current_round: :return: the low and high boundaries of the estimators window to consider. """ lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi def __call__(self, current_round, regressor, _): """ Implementation of the GradientBoostingRegressor monitor function API. :param current_round: the current boosting round. :param regressor: the regressor. :param _: ignored. :return: True if the regressor should stop early, else False. """ if current_round >= self.window_length - 1: lo, hi = self.window_boundaries(current_round) return np.mean(regressor.oob_improvement_[lo: hi]) < 0 else: return False
tmoerman/arboreto
arboreto/core.py
to_feature_importances
python
def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): if is_oob_heuristic_supported(regressor_type, regressor_kwargs): n_estimators = len(trained_regressor.estimators_) denormalized_importances = trained_regressor.feature_importances_ * n_estimators return denormalized_importances else: return trained_regressor.feature_importances_
Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used. This enables prioritizing links that were inferred in a regression where lots of :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :return: the feature importances inferred from the trained model.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L144-L166
[ "def is_oob_heuristic_supported(regressor_type, regressor_kwargs):\n \"\"\"\n :param regressor_type: on\n :param regressor_kwargs:\n :return: whether early stopping heuristic based on out-of-bag improvement is supported.\n\n \"\"\"\n return \\\n regressor_type.upper() == 'GBM' and \\\n 'subsample' in regressor_kwargs and \\\n regressor_kwargs['subsample'] < 1.0\n" ]
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from dask.dataframe.utils import make_meta logger = logging.getLogger(__name__) DEMON_SEED = 666 ANGEL_SEED = 777 EARLY_STOP_WINDOW_LENGTH = 25 SKLEARN_REGRESSOR_FACTORY = { 'RF': RandomForestRegressor, 'ET': ExtraTreesRegressor, 'GBM': GradientBoostingRegressor } # scikit-learn random forest regressor RF_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn extra-trees regressor ET_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn gradient boosting regressor GBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 500, 'max_features': 0.1 } # scikit-learn stochastic gradient boosting regressor SGBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 5000, # can be arbitrarily large 'max_features': 0.1, 'subsample': 0.9 } def is_sklearn_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API. """ return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys() def is_xgboost_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: boolean indicating whether the regressor type is the xgboost regressor. """ return regressor_type.upper() == 'XGB' def is_oob_heuristic_supported(regressor_type, regressor_kwargs): """ :param regressor_type: on :param regressor_kwargs: :return: whether early stopping heuristic based on out-of-bag improvement is supported. """ return \ regressor_type.upper() == 'GBM' and \ 'subsample' in regressor_kwargs and \ regressor_kwargs['subsample'] < 1.0 def to_tf_matrix(expression_matrix, gene_names, tf_names): """ :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: a list of transcription factor names. Should be a subset of gene_names. :return: tuple of: 0: A numpy matrix representing the predictor matrix for the regressions. 1: The gene names corresponding to the columns in the predictor matrix. """ tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names] tf_indices = [t[0] for t in tuples] tf_matrix_names = [t[1] for t in tuples] return expression_matrix[:, tf_indices], tf_matrix_names def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param tf_matrix: the predictor matrix (transcription factor matrix) as a numpy array. :param target_gene_expression: the target (y) gene expression to predict in function of the tf_matrix (X). :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: a trained regression model. """ regressor_type = regressor_type.upper() assert tf_matrix.shape[0] == len(target_gene_expression) def do_sklearn_regression(): regressor = SKLEARN_REGRESSOR_FACTORY[regressor_type](random_state=seed, **regressor_kwargs) with_early_stopping = is_oob_heuristic_supported(regressor_type, regressor_kwargs) if with_early_stopping: regressor.fit(tf_matrix, target_gene_expression, monitor=EarlyStopMonitor(early_stop_window_length)) else: regressor.fit(tf_matrix, target_gene_expression) return regressor if is_sklearn_regressor(regressor_type): return do_sklearn_regression() # elif is_xgboost_regressor(regressor_type): # raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: {0}'.format(regressor_type)) def to_meta_df(trained_regressor, target_gene_name): """ :param trained_regressor: the trained model from which to extract the meta information. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame containing side information about the regression. """ n_estimators = len(trained_regressor.estimators_) return pd.DataFrame({'target': [target_gene_name], 'n_estimators': [n_estimators]}) def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :param tf_matrix_gene_names: the list of names corresponding to the columns of the tf_matrix used to train the model. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame['TF', 'target', 'importance'] representing inferred regulatory links and their connection strength. """ def pythonic(): # feature_importances = trained_regressor.feature_importances_ feature_importances = to_feature_importances(regressor_type, regressor_kwargs, trained_regressor) links_df = pd.DataFrame({'TF': tf_matrix_gene_names, 'importance': feature_importances}) links_df['target'] = target_gene_name clean_links_df = links_df[links_df.importance > 0].sort_values(by='importance', ascending=False) return clean_links_df[['TF', 'target', 'importance']] if is_sklearn_regressor(regressor_type): return pythonic() elif is_xgboost_regressor(regressor_type): raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: ' + regressor_type) def clean(tf_matrix, tf_matrix_gene_names, target_gene_name): """ :param tf_matrix: numpy array. The full transcription factor matrix. :param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns. :param target_gene_name: the target gene to remove from the tf_matrix and tf_names. :return: a tuple of (matrix, names) equal to the specified ones minus the target_gene_name if the target happens to be one of the transcription factors. If not, the specified (tf_matrix, tf_names) is returned verbatim. """ if target_gene_name not in tf_matrix_gene_names: clean_tf_matrix = tf_matrix else: clean_tf_matrix = np.delete(tf_matrix, tf_matrix_gene_names.index(target_gene_name), 1) clean_tf_names = [tf for tf in tf_matrix_gene_names if tf != target_gene_name] assert clean_tf_matrix.shape[1] == len(clean_tf_names) # sanity check return clean_tf_matrix, clean_tf_names def retry(fn, max_retries=10, warning_msg=None, fallback_result=None): """ Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn: * https://github.com/scikit-learn/scikit-learn/issues/2755 * https://github.com/scikit-learn/scikit-learn/issues/7346 :param fn: the function to retry. :param max_retries: the maximum number of retries to attempt. :param warning_msg: a warning message to display when an attempt fails. :param fallback_result: result to return when all attempts fail. :return: Returns the result of fn if one attempt succeeds, else return fallback_result. """ nr_retries = 0 result = fallback_result for attempt in range(max_retries): try: result = fn() except Exception as cause: nr_retries += 1 msg_head = '' if warning_msg is None else repr(warning_msg) + ' ' msg_tail = "Retry ({1}/{2}). Failure caused by {0}.".format(repr(cause), nr_retries, max_retries) logger.warning(msg_head + msg_tail) else: break return result def infer_partial_network(regressor_type, regressor_kwargs, tf_matrix, tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ Ties together regressor model training with regulatory links and meta data extraction. :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param tf_matrix: numpy matrix. The feature matrix X to use for the regression. :param tf_matrix_gene_names: list of transcription factor names corresponding to the columns of the tf_matrix used to train the regression model. :param target_gene_name: the name of the target gene to infer the regulatory links for. :param target_gene_expression: the expression profile of the target gene. Numpy array. :param include_meta: whether to also return the meta information DataFrame. :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: if include_meta == True, return links_df, meta_df link_df: a Pandas DataFrame['TF', 'target', 'importance'] containing inferred regulatory links and their connection strength. meta_df: a Pandas DataFrame['target', 'meta', 'value'] containing meta information regarding the trained regression model. """ def fn(): (clean_tf_matrix, clean_tf_matrix_gene_names) = clean(tf_matrix, tf_matrix_gene_names, target_gene_name) try: trained_regressor = fit_model(regressor_type, regressor_kwargs, clean_tf_matrix, target_gene_expression, early_stop_window_length, seed) except ValueError as e: raise ValueError("Regression for target gene {0} failed. Cause {1}.".format(target_gene_name, repr(e))) links_df = to_links_df(regressor_type, regressor_kwargs, trained_regressor, clean_tf_matrix_gene_names, target_gene_name) if include_meta: meta_df = to_meta_df(trained_regressor, target_gene_name) return links_df, meta_df else: return links_df fallback_result = (None, None) if include_meta else None return retry(fn, fallback_result=fallback_result, warning_msg='infer_data failed for target {0}'.format(target_gene_name)) def target_gene_indices(gene_names, target_genes): """ :param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix. """ if isinstance(target_genes, list) and len(target_genes) == 0: return [] if isinstance(target_genes, str) and target_genes.upper() == 'ALL': return list(range(len(gene_names))) elif isinstance(target_genes, int): top_n = target_genes assert top_n > 0 return list(range(min(top_n, len(gene_names)))) elif isinstance(target_genes, list): if not target_genes: # target_genes is empty return target_genes elif all(isinstance(target_gene, str) for target_gene in target_genes): return [index for index, gene in enumerate(gene_names) if gene in target_genes] elif all(isinstance(target_gene, int) for target_gene in target_genes): return target_genes else: raise ValueError("Mixed types in target genes.") else: raise ValueError("Unable to interpret target_genes.") _GRN_SCHEMA = make_meta({'TF': str, 'target': str, 'importance': float}) _META_SCHEMA = make_meta({'target': str, 'n_estimators': int}) def create_graph(expression_matrix, gene_names, tf_names, regressor_type, regressor_kwargs, client, target_genes='all', limit=None, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, repartition_multiplier=1, seed=DEMON_SEED): """ Main API function. Create a Dask computation graph. Note: fixing the GC problems was fixed by 2 changes: [1] and [2] !!! :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: list of transcription factor names. Should have a non-empty intersection with gene_names. :param regressor_type: regressor type. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param client: a dask.distributed client instance. * Used to scatter-broadcast the tf matrix to the workers instead of simply wrapping in a delayed(). :param target_genes: either int, 'all' or a collection that is a subset of gene_names. :param limit: optional number of top regulatory links to return. Default None. :param include_meta: Also return the meta DataFrame. Default False. :param early_stop_window_length: window length of the early stopping monitor. :param repartition_multiplier: multiplier :param seed: (optional) random seed for the regressors. Default 666. :return: if include_meta is False, returns a Dask graph that computes the links DataFrame. If include_meta is True, returns a tuple: the links DataFrame and the meta DataFrame. """ assert expression_matrix.shape[1] == len(gene_names) assert client, "client is required" tf_matrix, tf_matrix_gene_names = to_tf_matrix(expression_matrix, gene_names, tf_names) future_tf_matrix = client.scatter(tf_matrix, broadcast=True) # [1] wrap in a list of 1 -> unsure why but Matt. Rocklin does this often... [future_tf_matrix_gene_names] = client.scatter([tf_matrix_gene_names], broadcast=True) delayed_link_dfs = [] # collection of delayed link DataFrames delayed_meta_dfs = [] # collection of delayed meta DataFrame for target_gene_index in target_gene_indices(gene_names, target_genes): target_gene_name = delayed(gene_names[target_gene_index], pure=True) target_gene_expression = delayed(expression_matrix[:, target_gene_index], pure=True) if include_meta: delayed_link_df, delayed_meta_df = delayed(infer_partial_network, pure=True, nout=2)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) delayed_meta_dfs.append(delayed_meta_df) else: delayed_link_df = delayed(infer_partial_network, pure=True)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) # gather the DataFrames into one distributed DataFrame all_links_df = from_delayed(delayed_link_dfs, meta=_GRN_SCHEMA) all_meta_df = from_delayed(delayed_meta_dfs, meta=_META_SCHEMA) # optionally limit the number of resulting regulatory links, descending by top importance if limit: maybe_limited_links_df = all_links_df.nlargest(limit, columns=['importance']) else: maybe_limited_links_df = all_links_df # [2] repartition to nr of workers -> important to avoid GC problems! # see: http://dask.pydata.org/en/latest/dataframe-performance.html#repartition-to-reduce-overhead n_parts = len(client.ncores()) * repartition_multiplier if include_meta: return maybe_limited_links_df.repartition(npartitions=n_parts), \ all_meta_df.repartition(npartitions=n_parts) else: return maybe_limited_links_df.repartition(npartitions=n_parts) class EarlyStopMonitor: def __init__(self, window_length=EARLY_STOP_WINDOW_LENGTH): """ :param window_length: length of the window over the out-of-bag errors. """ self.window_length = window_length def window_boundaries(self, current_round): """ :param current_round: :return: the low and high boundaries of the estimators window to consider. """ lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi def __call__(self, current_round, regressor, _): """ Implementation of the GradientBoostingRegressor monitor function API. :param current_round: the current boosting round. :param regressor: the regressor. :param _: ignored. :return: True if the regressor should stop early, else False. """ if current_round >= self.window_length - 1: lo, hi = self.window_boundaries(current_round) return np.mean(regressor.oob_improvement_[lo: hi]) < 0 else: return False
tmoerman/arboreto
arboreto/core.py
to_meta_df
python
def to_meta_df(trained_regressor, target_gene_name): n_estimators = len(trained_regressor.estimators_) return pd.DataFrame({'target': [target_gene_name], 'n_estimators': [n_estimators]})
:param trained_regressor: the trained model from which to extract the meta information. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame containing side information about the regression.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L169-L178
null
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from dask.dataframe.utils import make_meta logger = logging.getLogger(__name__) DEMON_SEED = 666 ANGEL_SEED = 777 EARLY_STOP_WINDOW_LENGTH = 25 SKLEARN_REGRESSOR_FACTORY = { 'RF': RandomForestRegressor, 'ET': ExtraTreesRegressor, 'GBM': GradientBoostingRegressor } # scikit-learn random forest regressor RF_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn extra-trees regressor ET_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn gradient boosting regressor GBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 500, 'max_features': 0.1 } # scikit-learn stochastic gradient boosting regressor SGBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 5000, # can be arbitrarily large 'max_features': 0.1, 'subsample': 0.9 } def is_sklearn_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API. """ return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys() def is_xgboost_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: boolean indicating whether the regressor type is the xgboost regressor. """ return regressor_type.upper() == 'XGB' def is_oob_heuristic_supported(regressor_type, regressor_kwargs): """ :param regressor_type: on :param regressor_kwargs: :return: whether early stopping heuristic based on out-of-bag improvement is supported. """ return \ regressor_type.upper() == 'GBM' and \ 'subsample' in regressor_kwargs and \ regressor_kwargs['subsample'] < 1.0 def to_tf_matrix(expression_matrix, gene_names, tf_names): """ :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: a list of transcription factor names. Should be a subset of gene_names. :return: tuple of: 0: A numpy matrix representing the predictor matrix for the regressions. 1: The gene names corresponding to the columns in the predictor matrix. """ tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names] tf_indices = [t[0] for t in tuples] tf_matrix_names = [t[1] for t in tuples] return expression_matrix[:, tf_indices], tf_matrix_names def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param tf_matrix: the predictor matrix (transcription factor matrix) as a numpy array. :param target_gene_expression: the target (y) gene expression to predict in function of the tf_matrix (X). :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: a trained regression model. """ regressor_type = regressor_type.upper() assert tf_matrix.shape[0] == len(target_gene_expression) def do_sklearn_regression(): regressor = SKLEARN_REGRESSOR_FACTORY[regressor_type](random_state=seed, **regressor_kwargs) with_early_stopping = is_oob_heuristic_supported(regressor_type, regressor_kwargs) if with_early_stopping: regressor.fit(tf_matrix, target_gene_expression, monitor=EarlyStopMonitor(early_stop_window_length)) else: regressor.fit(tf_matrix, target_gene_expression) return regressor if is_sklearn_regressor(regressor_type): return do_sklearn_regression() # elif is_xgboost_regressor(regressor_type): # raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: {0}'.format(regressor_type)) def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): """ Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used. This enables prioritizing links that were inferred in a regression where lots of :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :return: the feature importances inferred from the trained model. """ if is_oob_heuristic_supported(regressor_type, regressor_kwargs): n_estimators = len(trained_regressor.estimators_) denormalized_importances = trained_regressor.feature_importances_ * n_estimators return denormalized_importances else: return trained_regressor.feature_importances_ def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :param tf_matrix_gene_names: the list of names corresponding to the columns of the tf_matrix used to train the model. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame['TF', 'target', 'importance'] representing inferred regulatory links and their connection strength. """ def pythonic(): # feature_importances = trained_regressor.feature_importances_ feature_importances = to_feature_importances(regressor_type, regressor_kwargs, trained_regressor) links_df = pd.DataFrame({'TF': tf_matrix_gene_names, 'importance': feature_importances}) links_df['target'] = target_gene_name clean_links_df = links_df[links_df.importance > 0].sort_values(by='importance', ascending=False) return clean_links_df[['TF', 'target', 'importance']] if is_sklearn_regressor(regressor_type): return pythonic() elif is_xgboost_regressor(regressor_type): raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: ' + regressor_type) def clean(tf_matrix, tf_matrix_gene_names, target_gene_name): """ :param tf_matrix: numpy array. The full transcription factor matrix. :param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns. :param target_gene_name: the target gene to remove from the tf_matrix and tf_names. :return: a tuple of (matrix, names) equal to the specified ones minus the target_gene_name if the target happens to be one of the transcription factors. If not, the specified (tf_matrix, tf_names) is returned verbatim. """ if target_gene_name not in tf_matrix_gene_names: clean_tf_matrix = tf_matrix else: clean_tf_matrix = np.delete(tf_matrix, tf_matrix_gene_names.index(target_gene_name), 1) clean_tf_names = [tf for tf in tf_matrix_gene_names if tf != target_gene_name] assert clean_tf_matrix.shape[1] == len(clean_tf_names) # sanity check return clean_tf_matrix, clean_tf_names def retry(fn, max_retries=10, warning_msg=None, fallback_result=None): """ Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn: * https://github.com/scikit-learn/scikit-learn/issues/2755 * https://github.com/scikit-learn/scikit-learn/issues/7346 :param fn: the function to retry. :param max_retries: the maximum number of retries to attempt. :param warning_msg: a warning message to display when an attempt fails. :param fallback_result: result to return when all attempts fail. :return: Returns the result of fn if one attempt succeeds, else return fallback_result. """ nr_retries = 0 result = fallback_result for attempt in range(max_retries): try: result = fn() except Exception as cause: nr_retries += 1 msg_head = '' if warning_msg is None else repr(warning_msg) + ' ' msg_tail = "Retry ({1}/{2}). Failure caused by {0}.".format(repr(cause), nr_retries, max_retries) logger.warning(msg_head + msg_tail) else: break return result def infer_partial_network(regressor_type, regressor_kwargs, tf_matrix, tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ Ties together regressor model training with regulatory links and meta data extraction. :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param tf_matrix: numpy matrix. The feature matrix X to use for the regression. :param tf_matrix_gene_names: list of transcription factor names corresponding to the columns of the tf_matrix used to train the regression model. :param target_gene_name: the name of the target gene to infer the regulatory links for. :param target_gene_expression: the expression profile of the target gene. Numpy array. :param include_meta: whether to also return the meta information DataFrame. :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: if include_meta == True, return links_df, meta_df link_df: a Pandas DataFrame['TF', 'target', 'importance'] containing inferred regulatory links and their connection strength. meta_df: a Pandas DataFrame['target', 'meta', 'value'] containing meta information regarding the trained regression model. """ def fn(): (clean_tf_matrix, clean_tf_matrix_gene_names) = clean(tf_matrix, tf_matrix_gene_names, target_gene_name) try: trained_regressor = fit_model(regressor_type, regressor_kwargs, clean_tf_matrix, target_gene_expression, early_stop_window_length, seed) except ValueError as e: raise ValueError("Regression for target gene {0} failed. Cause {1}.".format(target_gene_name, repr(e))) links_df = to_links_df(regressor_type, regressor_kwargs, trained_regressor, clean_tf_matrix_gene_names, target_gene_name) if include_meta: meta_df = to_meta_df(trained_regressor, target_gene_name) return links_df, meta_df else: return links_df fallback_result = (None, None) if include_meta else None return retry(fn, fallback_result=fallback_result, warning_msg='infer_data failed for target {0}'.format(target_gene_name)) def target_gene_indices(gene_names, target_genes): """ :param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix. """ if isinstance(target_genes, list) and len(target_genes) == 0: return [] if isinstance(target_genes, str) and target_genes.upper() == 'ALL': return list(range(len(gene_names))) elif isinstance(target_genes, int): top_n = target_genes assert top_n > 0 return list(range(min(top_n, len(gene_names)))) elif isinstance(target_genes, list): if not target_genes: # target_genes is empty return target_genes elif all(isinstance(target_gene, str) for target_gene in target_genes): return [index for index, gene in enumerate(gene_names) if gene in target_genes] elif all(isinstance(target_gene, int) for target_gene in target_genes): return target_genes else: raise ValueError("Mixed types in target genes.") else: raise ValueError("Unable to interpret target_genes.") _GRN_SCHEMA = make_meta({'TF': str, 'target': str, 'importance': float}) _META_SCHEMA = make_meta({'target': str, 'n_estimators': int}) def create_graph(expression_matrix, gene_names, tf_names, regressor_type, regressor_kwargs, client, target_genes='all', limit=None, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, repartition_multiplier=1, seed=DEMON_SEED): """ Main API function. Create a Dask computation graph. Note: fixing the GC problems was fixed by 2 changes: [1] and [2] !!! :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: list of transcription factor names. Should have a non-empty intersection with gene_names. :param regressor_type: regressor type. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param client: a dask.distributed client instance. * Used to scatter-broadcast the tf matrix to the workers instead of simply wrapping in a delayed(). :param target_genes: either int, 'all' or a collection that is a subset of gene_names. :param limit: optional number of top regulatory links to return. Default None. :param include_meta: Also return the meta DataFrame. Default False. :param early_stop_window_length: window length of the early stopping monitor. :param repartition_multiplier: multiplier :param seed: (optional) random seed for the regressors. Default 666. :return: if include_meta is False, returns a Dask graph that computes the links DataFrame. If include_meta is True, returns a tuple: the links DataFrame and the meta DataFrame. """ assert expression_matrix.shape[1] == len(gene_names) assert client, "client is required" tf_matrix, tf_matrix_gene_names = to_tf_matrix(expression_matrix, gene_names, tf_names) future_tf_matrix = client.scatter(tf_matrix, broadcast=True) # [1] wrap in a list of 1 -> unsure why but Matt. Rocklin does this often... [future_tf_matrix_gene_names] = client.scatter([tf_matrix_gene_names], broadcast=True) delayed_link_dfs = [] # collection of delayed link DataFrames delayed_meta_dfs = [] # collection of delayed meta DataFrame for target_gene_index in target_gene_indices(gene_names, target_genes): target_gene_name = delayed(gene_names[target_gene_index], pure=True) target_gene_expression = delayed(expression_matrix[:, target_gene_index], pure=True) if include_meta: delayed_link_df, delayed_meta_df = delayed(infer_partial_network, pure=True, nout=2)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) delayed_meta_dfs.append(delayed_meta_df) else: delayed_link_df = delayed(infer_partial_network, pure=True)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) # gather the DataFrames into one distributed DataFrame all_links_df = from_delayed(delayed_link_dfs, meta=_GRN_SCHEMA) all_meta_df = from_delayed(delayed_meta_dfs, meta=_META_SCHEMA) # optionally limit the number of resulting regulatory links, descending by top importance if limit: maybe_limited_links_df = all_links_df.nlargest(limit, columns=['importance']) else: maybe_limited_links_df = all_links_df # [2] repartition to nr of workers -> important to avoid GC problems! # see: http://dask.pydata.org/en/latest/dataframe-performance.html#repartition-to-reduce-overhead n_parts = len(client.ncores()) * repartition_multiplier if include_meta: return maybe_limited_links_df.repartition(npartitions=n_parts), \ all_meta_df.repartition(npartitions=n_parts) else: return maybe_limited_links_df.repartition(npartitions=n_parts) class EarlyStopMonitor: def __init__(self, window_length=EARLY_STOP_WINDOW_LENGTH): """ :param window_length: length of the window over the out-of-bag errors. """ self.window_length = window_length def window_boundaries(self, current_round): """ :param current_round: :return: the low and high boundaries of the estimators window to consider. """ lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi def __call__(self, current_round, regressor, _): """ Implementation of the GradientBoostingRegressor monitor function API. :param current_round: the current boosting round. :param regressor: the regressor. :param _: ignored. :return: True if the regressor should stop early, else False. """ if current_round >= self.window_length - 1: lo, hi = self.window_boundaries(current_round) return np.mean(regressor.oob_improvement_[lo: hi]) < 0 else: return False
tmoerman/arboreto
arboreto/core.py
to_links_df
python
def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): def pythonic(): # feature_importances = trained_regressor.feature_importances_ feature_importances = to_feature_importances(regressor_type, regressor_kwargs, trained_regressor) links_df = pd.DataFrame({'TF': tf_matrix_gene_names, 'importance': feature_importances}) links_df['target'] = target_gene_name clean_links_df = links_df[links_df.importance > 0].sort_values(by='importance', ascending=False) return clean_links_df[['TF', 'target', 'importance']] if is_sklearn_regressor(regressor_type): return pythonic() elif is_xgboost_regressor(regressor_type): raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: ' + regressor_type)
:param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :param tf_matrix_gene_names: the list of names corresponding to the columns of the tf_matrix used to train the model. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame['TF', 'target', 'importance'] representing inferred regulatory links and their connection strength.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L181-L212
[ "def is_sklearn_regressor(regressor_type):\n \"\"\"\n :param regressor_type: string. Case insensitive.\n :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API.\n \"\"\"\n return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys()\n", "def is_xgboost_regressor(regressor_type):\n \"\"\"\n :param regressor_type: string. Case insensitive.\n :return: boolean indicating whether the regressor type is the xgboost regressor.\n \"\"\"\n return regressor_type.upper() == 'XGB'\n", "def pythonic():\n # feature_importances = trained_regressor.feature_importances_\n feature_importances = to_feature_importances(regressor_type, regressor_kwargs, trained_regressor)\n\n links_df = pd.DataFrame({'TF': tf_matrix_gene_names, 'importance': feature_importances})\n links_df['target'] = target_gene_name\n\n clean_links_df = links_df[links_df.importance > 0].sort_values(by='importance', ascending=False)\n\n return clean_links_df[['TF', 'target', 'importance']]\n" ]
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from dask.dataframe.utils import make_meta logger = logging.getLogger(__name__) DEMON_SEED = 666 ANGEL_SEED = 777 EARLY_STOP_WINDOW_LENGTH = 25 SKLEARN_REGRESSOR_FACTORY = { 'RF': RandomForestRegressor, 'ET': ExtraTreesRegressor, 'GBM': GradientBoostingRegressor } # scikit-learn random forest regressor RF_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn extra-trees regressor ET_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn gradient boosting regressor GBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 500, 'max_features': 0.1 } # scikit-learn stochastic gradient boosting regressor SGBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 5000, # can be arbitrarily large 'max_features': 0.1, 'subsample': 0.9 } def is_sklearn_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API. """ return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys() def is_xgboost_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: boolean indicating whether the regressor type is the xgboost regressor. """ return regressor_type.upper() == 'XGB' def is_oob_heuristic_supported(regressor_type, regressor_kwargs): """ :param regressor_type: on :param regressor_kwargs: :return: whether early stopping heuristic based on out-of-bag improvement is supported. """ return \ regressor_type.upper() == 'GBM' and \ 'subsample' in regressor_kwargs and \ regressor_kwargs['subsample'] < 1.0 def to_tf_matrix(expression_matrix, gene_names, tf_names): """ :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: a list of transcription factor names. Should be a subset of gene_names. :return: tuple of: 0: A numpy matrix representing the predictor matrix for the regressions. 1: The gene names corresponding to the columns in the predictor matrix. """ tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names] tf_indices = [t[0] for t in tuples] tf_matrix_names = [t[1] for t in tuples] return expression_matrix[:, tf_indices], tf_matrix_names def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param tf_matrix: the predictor matrix (transcription factor matrix) as a numpy array. :param target_gene_expression: the target (y) gene expression to predict in function of the tf_matrix (X). :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: a trained regression model. """ regressor_type = regressor_type.upper() assert tf_matrix.shape[0] == len(target_gene_expression) def do_sklearn_regression(): regressor = SKLEARN_REGRESSOR_FACTORY[regressor_type](random_state=seed, **regressor_kwargs) with_early_stopping = is_oob_heuristic_supported(regressor_type, regressor_kwargs) if with_early_stopping: regressor.fit(tf_matrix, target_gene_expression, monitor=EarlyStopMonitor(early_stop_window_length)) else: regressor.fit(tf_matrix, target_gene_expression) return regressor if is_sklearn_regressor(regressor_type): return do_sklearn_regression() # elif is_xgboost_regressor(regressor_type): # raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: {0}'.format(regressor_type)) def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): """ Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used. This enables prioritizing links that were inferred in a regression where lots of :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :return: the feature importances inferred from the trained model. """ if is_oob_heuristic_supported(regressor_type, regressor_kwargs): n_estimators = len(trained_regressor.estimators_) denormalized_importances = trained_regressor.feature_importances_ * n_estimators return denormalized_importances else: return trained_regressor.feature_importances_ def to_meta_df(trained_regressor, target_gene_name): """ :param trained_regressor: the trained model from which to extract the meta information. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame containing side information about the regression. """ n_estimators = len(trained_regressor.estimators_) return pd.DataFrame({'target': [target_gene_name], 'n_estimators': [n_estimators]}) def clean(tf_matrix, tf_matrix_gene_names, target_gene_name): """ :param tf_matrix: numpy array. The full transcription factor matrix. :param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns. :param target_gene_name: the target gene to remove from the tf_matrix and tf_names. :return: a tuple of (matrix, names) equal to the specified ones minus the target_gene_name if the target happens to be one of the transcription factors. If not, the specified (tf_matrix, tf_names) is returned verbatim. """ if target_gene_name not in tf_matrix_gene_names: clean_tf_matrix = tf_matrix else: clean_tf_matrix = np.delete(tf_matrix, tf_matrix_gene_names.index(target_gene_name), 1) clean_tf_names = [tf for tf in tf_matrix_gene_names if tf != target_gene_name] assert clean_tf_matrix.shape[1] == len(clean_tf_names) # sanity check return clean_tf_matrix, clean_tf_names def retry(fn, max_retries=10, warning_msg=None, fallback_result=None): """ Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn: * https://github.com/scikit-learn/scikit-learn/issues/2755 * https://github.com/scikit-learn/scikit-learn/issues/7346 :param fn: the function to retry. :param max_retries: the maximum number of retries to attempt. :param warning_msg: a warning message to display when an attempt fails. :param fallback_result: result to return when all attempts fail. :return: Returns the result of fn if one attempt succeeds, else return fallback_result. """ nr_retries = 0 result = fallback_result for attempt in range(max_retries): try: result = fn() except Exception as cause: nr_retries += 1 msg_head = '' if warning_msg is None else repr(warning_msg) + ' ' msg_tail = "Retry ({1}/{2}). Failure caused by {0}.".format(repr(cause), nr_retries, max_retries) logger.warning(msg_head + msg_tail) else: break return result def infer_partial_network(regressor_type, regressor_kwargs, tf_matrix, tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ Ties together regressor model training with regulatory links and meta data extraction. :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param tf_matrix: numpy matrix. The feature matrix X to use for the regression. :param tf_matrix_gene_names: list of transcription factor names corresponding to the columns of the tf_matrix used to train the regression model. :param target_gene_name: the name of the target gene to infer the regulatory links for. :param target_gene_expression: the expression profile of the target gene. Numpy array. :param include_meta: whether to also return the meta information DataFrame. :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: if include_meta == True, return links_df, meta_df link_df: a Pandas DataFrame['TF', 'target', 'importance'] containing inferred regulatory links and their connection strength. meta_df: a Pandas DataFrame['target', 'meta', 'value'] containing meta information regarding the trained regression model. """ def fn(): (clean_tf_matrix, clean_tf_matrix_gene_names) = clean(tf_matrix, tf_matrix_gene_names, target_gene_name) try: trained_regressor = fit_model(regressor_type, regressor_kwargs, clean_tf_matrix, target_gene_expression, early_stop_window_length, seed) except ValueError as e: raise ValueError("Regression for target gene {0} failed. Cause {1}.".format(target_gene_name, repr(e))) links_df = to_links_df(regressor_type, regressor_kwargs, trained_regressor, clean_tf_matrix_gene_names, target_gene_name) if include_meta: meta_df = to_meta_df(trained_regressor, target_gene_name) return links_df, meta_df else: return links_df fallback_result = (None, None) if include_meta else None return retry(fn, fallback_result=fallback_result, warning_msg='infer_data failed for target {0}'.format(target_gene_name)) def target_gene_indices(gene_names, target_genes): """ :param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix. """ if isinstance(target_genes, list) and len(target_genes) == 0: return [] if isinstance(target_genes, str) and target_genes.upper() == 'ALL': return list(range(len(gene_names))) elif isinstance(target_genes, int): top_n = target_genes assert top_n > 0 return list(range(min(top_n, len(gene_names)))) elif isinstance(target_genes, list): if not target_genes: # target_genes is empty return target_genes elif all(isinstance(target_gene, str) for target_gene in target_genes): return [index for index, gene in enumerate(gene_names) if gene in target_genes] elif all(isinstance(target_gene, int) for target_gene in target_genes): return target_genes else: raise ValueError("Mixed types in target genes.") else: raise ValueError("Unable to interpret target_genes.") _GRN_SCHEMA = make_meta({'TF': str, 'target': str, 'importance': float}) _META_SCHEMA = make_meta({'target': str, 'n_estimators': int}) def create_graph(expression_matrix, gene_names, tf_names, regressor_type, regressor_kwargs, client, target_genes='all', limit=None, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, repartition_multiplier=1, seed=DEMON_SEED): """ Main API function. Create a Dask computation graph. Note: fixing the GC problems was fixed by 2 changes: [1] and [2] !!! :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: list of transcription factor names. Should have a non-empty intersection with gene_names. :param regressor_type: regressor type. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param client: a dask.distributed client instance. * Used to scatter-broadcast the tf matrix to the workers instead of simply wrapping in a delayed(). :param target_genes: either int, 'all' or a collection that is a subset of gene_names. :param limit: optional number of top regulatory links to return. Default None. :param include_meta: Also return the meta DataFrame. Default False. :param early_stop_window_length: window length of the early stopping monitor. :param repartition_multiplier: multiplier :param seed: (optional) random seed for the regressors. Default 666. :return: if include_meta is False, returns a Dask graph that computes the links DataFrame. If include_meta is True, returns a tuple: the links DataFrame and the meta DataFrame. """ assert expression_matrix.shape[1] == len(gene_names) assert client, "client is required" tf_matrix, tf_matrix_gene_names = to_tf_matrix(expression_matrix, gene_names, tf_names) future_tf_matrix = client.scatter(tf_matrix, broadcast=True) # [1] wrap in a list of 1 -> unsure why but Matt. Rocklin does this often... [future_tf_matrix_gene_names] = client.scatter([tf_matrix_gene_names], broadcast=True) delayed_link_dfs = [] # collection of delayed link DataFrames delayed_meta_dfs = [] # collection of delayed meta DataFrame for target_gene_index in target_gene_indices(gene_names, target_genes): target_gene_name = delayed(gene_names[target_gene_index], pure=True) target_gene_expression = delayed(expression_matrix[:, target_gene_index], pure=True) if include_meta: delayed_link_df, delayed_meta_df = delayed(infer_partial_network, pure=True, nout=2)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) delayed_meta_dfs.append(delayed_meta_df) else: delayed_link_df = delayed(infer_partial_network, pure=True)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) # gather the DataFrames into one distributed DataFrame all_links_df = from_delayed(delayed_link_dfs, meta=_GRN_SCHEMA) all_meta_df = from_delayed(delayed_meta_dfs, meta=_META_SCHEMA) # optionally limit the number of resulting regulatory links, descending by top importance if limit: maybe_limited_links_df = all_links_df.nlargest(limit, columns=['importance']) else: maybe_limited_links_df = all_links_df # [2] repartition to nr of workers -> important to avoid GC problems! # see: http://dask.pydata.org/en/latest/dataframe-performance.html#repartition-to-reduce-overhead n_parts = len(client.ncores()) * repartition_multiplier if include_meta: return maybe_limited_links_df.repartition(npartitions=n_parts), \ all_meta_df.repartition(npartitions=n_parts) else: return maybe_limited_links_df.repartition(npartitions=n_parts) class EarlyStopMonitor: def __init__(self, window_length=EARLY_STOP_WINDOW_LENGTH): """ :param window_length: length of the window over the out-of-bag errors. """ self.window_length = window_length def window_boundaries(self, current_round): """ :param current_round: :return: the low and high boundaries of the estimators window to consider. """ lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi def __call__(self, current_round, regressor, _): """ Implementation of the GradientBoostingRegressor monitor function API. :param current_round: the current boosting round. :param regressor: the regressor. :param _: ignored. :return: True if the regressor should stop early, else False. """ if current_round >= self.window_length - 1: lo, hi = self.window_boundaries(current_round) return np.mean(regressor.oob_improvement_[lo: hi]) < 0 else: return False
tmoerman/arboreto
arboreto/core.py
clean
python
def clean(tf_matrix, tf_matrix_gene_names, target_gene_name): if target_gene_name not in tf_matrix_gene_names: clean_tf_matrix = tf_matrix else: clean_tf_matrix = np.delete(tf_matrix, tf_matrix_gene_names.index(target_gene_name), 1) clean_tf_names = [tf for tf in tf_matrix_gene_names if tf != target_gene_name] assert clean_tf_matrix.shape[1] == len(clean_tf_names) # sanity check return clean_tf_matrix, clean_tf_names
:param tf_matrix: numpy array. The full transcription factor matrix. :param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns. :param target_gene_name: the target gene to remove from the tf_matrix and tf_names. :return: a tuple of (matrix, names) equal to the specified ones minus the target_gene_name if the target happens to be one of the transcription factors. If not, the specified (tf_matrix, tf_names) is returned verbatim.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L215-L235
null
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from dask.dataframe.utils import make_meta logger = logging.getLogger(__name__) DEMON_SEED = 666 ANGEL_SEED = 777 EARLY_STOP_WINDOW_LENGTH = 25 SKLEARN_REGRESSOR_FACTORY = { 'RF': RandomForestRegressor, 'ET': ExtraTreesRegressor, 'GBM': GradientBoostingRegressor } # scikit-learn random forest regressor RF_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn extra-trees regressor ET_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn gradient boosting regressor GBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 500, 'max_features': 0.1 } # scikit-learn stochastic gradient boosting regressor SGBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 5000, # can be arbitrarily large 'max_features': 0.1, 'subsample': 0.9 } def is_sklearn_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API. """ return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys() def is_xgboost_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: boolean indicating whether the regressor type is the xgboost regressor. """ return regressor_type.upper() == 'XGB' def is_oob_heuristic_supported(regressor_type, regressor_kwargs): """ :param regressor_type: on :param regressor_kwargs: :return: whether early stopping heuristic based on out-of-bag improvement is supported. """ return \ regressor_type.upper() == 'GBM' and \ 'subsample' in regressor_kwargs and \ regressor_kwargs['subsample'] < 1.0 def to_tf_matrix(expression_matrix, gene_names, tf_names): """ :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: a list of transcription factor names. Should be a subset of gene_names. :return: tuple of: 0: A numpy matrix representing the predictor matrix for the regressions. 1: The gene names corresponding to the columns in the predictor matrix. """ tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names] tf_indices = [t[0] for t in tuples] tf_matrix_names = [t[1] for t in tuples] return expression_matrix[:, tf_indices], tf_matrix_names def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param tf_matrix: the predictor matrix (transcription factor matrix) as a numpy array. :param target_gene_expression: the target (y) gene expression to predict in function of the tf_matrix (X). :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: a trained regression model. """ regressor_type = regressor_type.upper() assert tf_matrix.shape[0] == len(target_gene_expression) def do_sklearn_regression(): regressor = SKLEARN_REGRESSOR_FACTORY[regressor_type](random_state=seed, **regressor_kwargs) with_early_stopping = is_oob_heuristic_supported(regressor_type, regressor_kwargs) if with_early_stopping: regressor.fit(tf_matrix, target_gene_expression, monitor=EarlyStopMonitor(early_stop_window_length)) else: regressor.fit(tf_matrix, target_gene_expression) return regressor if is_sklearn_regressor(regressor_type): return do_sklearn_regression() # elif is_xgboost_regressor(regressor_type): # raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: {0}'.format(regressor_type)) def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): """ Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used. This enables prioritizing links that were inferred in a regression where lots of :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :return: the feature importances inferred from the trained model. """ if is_oob_heuristic_supported(regressor_type, regressor_kwargs): n_estimators = len(trained_regressor.estimators_) denormalized_importances = trained_regressor.feature_importances_ * n_estimators return denormalized_importances else: return trained_regressor.feature_importances_ def to_meta_df(trained_regressor, target_gene_name): """ :param trained_regressor: the trained model from which to extract the meta information. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame containing side information about the regression. """ n_estimators = len(trained_regressor.estimators_) return pd.DataFrame({'target': [target_gene_name], 'n_estimators': [n_estimators]}) def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :param tf_matrix_gene_names: the list of names corresponding to the columns of the tf_matrix used to train the model. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame['TF', 'target', 'importance'] representing inferred regulatory links and their connection strength. """ def pythonic(): # feature_importances = trained_regressor.feature_importances_ feature_importances = to_feature_importances(regressor_type, regressor_kwargs, trained_regressor) links_df = pd.DataFrame({'TF': tf_matrix_gene_names, 'importance': feature_importances}) links_df['target'] = target_gene_name clean_links_df = links_df[links_df.importance > 0].sort_values(by='importance', ascending=False) return clean_links_df[['TF', 'target', 'importance']] if is_sklearn_regressor(regressor_type): return pythonic() elif is_xgboost_regressor(regressor_type): raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: ' + regressor_type) def retry(fn, max_retries=10, warning_msg=None, fallback_result=None): """ Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn: * https://github.com/scikit-learn/scikit-learn/issues/2755 * https://github.com/scikit-learn/scikit-learn/issues/7346 :param fn: the function to retry. :param max_retries: the maximum number of retries to attempt. :param warning_msg: a warning message to display when an attempt fails. :param fallback_result: result to return when all attempts fail. :return: Returns the result of fn if one attempt succeeds, else return fallback_result. """ nr_retries = 0 result = fallback_result for attempt in range(max_retries): try: result = fn() except Exception as cause: nr_retries += 1 msg_head = '' if warning_msg is None else repr(warning_msg) + ' ' msg_tail = "Retry ({1}/{2}). Failure caused by {0}.".format(repr(cause), nr_retries, max_retries) logger.warning(msg_head + msg_tail) else: break return result def infer_partial_network(regressor_type, regressor_kwargs, tf_matrix, tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ Ties together regressor model training with regulatory links and meta data extraction. :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param tf_matrix: numpy matrix. The feature matrix X to use for the regression. :param tf_matrix_gene_names: list of transcription factor names corresponding to the columns of the tf_matrix used to train the regression model. :param target_gene_name: the name of the target gene to infer the regulatory links for. :param target_gene_expression: the expression profile of the target gene. Numpy array. :param include_meta: whether to also return the meta information DataFrame. :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: if include_meta == True, return links_df, meta_df link_df: a Pandas DataFrame['TF', 'target', 'importance'] containing inferred regulatory links and their connection strength. meta_df: a Pandas DataFrame['target', 'meta', 'value'] containing meta information regarding the trained regression model. """ def fn(): (clean_tf_matrix, clean_tf_matrix_gene_names) = clean(tf_matrix, tf_matrix_gene_names, target_gene_name) try: trained_regressor = fit_model(regressor_type, regressor_kwargs, clean_tf_matrix, target_gene_expression, early_stop_window_length, seed) except ValueError as e: raise ValueError("Regression for target gene {0} failed. Cause {1}.".format(target_gene_name, repr(e))) links_df = to_links_df(regressor_type, regressor_kwargs, trained_regressor, clean_tf_matrix_gene_names, target_gene_name) if include_meta: meta_df = to_meta_df(trained_regressor, target_gene_name) return links_df, meta_df else: return links_df fallback_result = (None, None) if include_meta else None return retry(fn, fallback_result=fallback_result, warning_msg='infer_data failed for target {0}'.format(target_gene_name)) def target_gene_indices(gene_names, target_genes): """ :param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix. """ if isinstance(target_genes, list) and len(target_genes) == 0: return [] if isinstance(target_genes, str) and target_genes.upper() == 'ALL': return list(range(len(gene_names))) elif isinstance(target_genes, int): top_n = target_genes assert top_n > 0 return list(range(min(top_n, len(gene_names)))) elif isinstance(target_genes, list): if not target_genes: # target_genes is empty return target_genes elif all(isinstance(target_gene, str) for target_gene in target_genes): return [index for index, gene in enumerate(gene_names) if gene in target_genes] elif all(isinstance(target_gene, int) for target_gene in target_genes): return target_genes else: raise ValueError("Mixed types in target genes.") else: raise ValueError("Unable to interpret target_genes.") _GRN_SCHEMA = make_meta({'TF': str, 'target': str, 'importance': float}) _META_SCHEMA = make_meta({'target': str, 'n_estimators': int}) def create_graph(expression_matrix, gene_names, tf_names, regressor_type, regressor_kwargs, client, target_genes='all', limit=None, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, repartition_multiplier=1, seed=DEMON_SEED): """ Main API function. Create a Dask computation graph. Note: fixing the GC problems was fixed by 2 changes: [1] and [2] !!! :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: list of transcription factor names. Should have a non-empty intersection with gene_names. :param regressor_type: regressor type. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param client: a dask.distributed client instance. * Used to scatter-broadcast the tf matrix to the workers instead of simply wrapping in a delayed(). :param target_genes: either int, 'all' or a collection that is a subset of gene_names. :param limit: optional number of top regulatory links to return. Default None. :param include_meta: Also return the meta DataFrame. Default False. :param early_stop_window_length: window length of the early stopping monitor. :param repartition_multiplier: multiplier :param seed: (optional) random seed for the regressors. Default 666. :return: if include_meta is False, returns a Dask graph that computes the links DataFrame. If include_meta is True, returns a tuple: the links DataFrame and the meta DataFrame. """ assert expression_matrix.shape[1] == len(gene_names) assert client, "client is required" tf_matrix, tf_matrix_gene_names = to_tf_matrix(expression_matrix, gene_names, tf_names) future_tf_matrix = client.scatter(tf_matrix, broadcast=True) # [1] wrap in a list of 1 -> unsure why but Matt. Rocklin does this often... [future_tf_matrix_gene_names] = client.scatter([tf_matrix_gene_names], broadcast=True) delayed_link_dfs = [] # collection of delayed link DataFrames delayed_meta_dfs = [] # collection of delayed meta DataFrame for target_gene_index in target_gene_indices(gene_names, target_genes): target_gene_name = delayed(gene_names[target_gene_index], pure=True) target_gene_expression = delayed(expression_matrix[:, target_gene_index], pure=True) if include_meta: delayed_link_df, delayed_meta_df = delayed(infer_partial_network, pure=True, nout=2)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) delayed_meta_dfs.append(delayed_meta_df) else: delayed_link_df = delayed(infer_partial_network, pure=True)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) # gather the DataFrames into one distributed DataFrame all_links_df = from_delayed(delayed_link_dfs, meta=_GRN_SCHEMA) all_meta_df = from_delayed(delayed_meta_dfs, meta=_META_SCHEMA) # optionally limit the number of resulting regulatory links, descending by top importance if limit: maybe_limited_links_df = all_links_df.nlargest(limit, columns=['importance']) else: maybe_limited_links_df = all_links_df # [2] repartition to nr of workers -> important to avoid GC problems! # see: http://dask.pydata.org/en/latest/dataframe-performance.html#repartition-to-reduce-overhead n_parts = len(client.ncores()) * repartition_multiplier if include_meta: return maybe_limited_links_df.repartition(npartitions=n_parts), \ all_meta_df.repartition(npartitions=n_parts) else: return maybe_limited_links_df.repartition(npartitions=n_parts) class EarlyStopMonitor: def __init__(self, window_length=EARLY_STOP_WINDOW_LENGTH): """ :param window_length: length of the window over the out-of-bag errors. """ self.window_length = window_length def window_boundaries(self, current_round): """ :param current_round: :return: the low and high boundaries of the estimators window to consider. """ lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi def __call__(self, current_round, regressor, _): """ Implementation of the GradientBoostingRegressor monitor function API. :param current_round: the current boosting round. :param regressor: the regressor. :param _: ignored. :return: True if the regressor should stop early, else False. """ if current_round >= self.window_length - 1: lo, hi = self.window_boundaries(current_round) return np.mean(regressor.oob_improvement_[lo: hi]) < 0 else: return False
tmoerman/arboreto
arboreto/core.py
retry
python
def retry(fn, max_retries=10, warning_msg=None, fallback_result=None): nr_retries = 0 result = fallback_result for attempt in range(max_retries): try: result = fn() except Exception as cause: nr_retries += 1 msg_head = '' if warning_msg is None else repr(warning_msg) + ' ' msg_tail = "Retry ({1}/{2}). Failure caused by {0}.".format(repr(cause), nr_retries, max_retries) logger.warning(msg_head + msg_tail) else: break return result
Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn: * https://github.com/scikit-learn/scikit-learn/issues/2755 * https://github.com/scikit-learn/scikit-learn/issues/7346 :param fn: the function to retry. :param max_retries: the maximum number of retries to attempt. :param warning_msg: a warning message to display when an attempt fails. :param fallback_result: result to return when all attempts fail. :return: Returns the result of fn if one attempt succeeds, else return fallback_result.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L238-L267
[ "def blue_skies():\n return 1\n", "def i_will_never_work():\n raise ValueError('never')\n", "def i_procrastinate(self):\n self.attempts += 1\n\n if self.attempts == 3:\n return 1\n else:\n raise ValueError('later')\n", "def fn():\n (clean_tf_matrix, clean_tf_matrix_gene_names) = clean(tf_matrix, tf_matrix_gene_names, target_gene_name)\n\n try:\n trained_regressor = fit_model(regressor_type, regressor_kwargs, clean_tf_matrix, target_gene_expression,\n early_stop_window_length, seed)\n except ValueError as e:\n raise ValueError(\"Regression for target gene {0} failed. Cause {1}.\".format(target_gene_name, repr(e)))\n\n links_df = to_links_df(regressor_type, regressor_kwargs, trained_regressor, clean_tf_matrix_gene_names,\n target_gene_name)\n\n if include_meta:\n meta_df = to_meta_df(trained_regressor, target_gene_name)\n\n return links_df, meta_df\n else:\n return links_df\n" ]
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from dask.dataframe.utils import make_meta logger = logging.getLogger(__name__) DEMON_SEED = 666 ANGEL_SEED = 777 EARLY_STOP_WINDOW_LENGTH = 25 SKLEARN_REGRESSOR_FACTORY = { 'RF': RandomForestRegressor, 'ET': ExtraTreesRegressor, 'GBM': GradientBoostingRegressor } # scikit-learn random forest regressor RF_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn extra-trees regressor ET_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn gradient boosting regressor GBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 500, 'max_features': 0.1 } # scikit-learn stochastic gradient boosting regressor SGBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 5000, # can be arbitrarily large 'max_features': 0.1, 'subsample': 0.9 } def is_sklearn_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API. """ return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys() def is_xgboost_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: boolean indicating whether the regressor type is the xgboost regressor. """ return regressor_type.upper() == 'XGB' def is_oob_heuristic_supported(regressor_type, regressor_kwargs): """ :param regressor_type: on :param regressor_kwargs: :return: whether early stopping heuristic based on out-of-bag improvement is supported. """ return \ regressor_type.upper() == 'GBM' and \ 'subsample' in regressor_kwargs and \ regressor_kwargs['subsample'] < 1.0 def to_tf_matrix(expression_matrix, gene_names, tf_names): """ :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: a list of transcription factor names. Should be a subset of gene_names. :return: tuple of: 0: A numpy matrix representing the predictor matrix for the regressions. 1: The gene names corresponding to the columns in the predictor matrix. """ tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names] tf_indices = [t[0] for t in tuples] tf_matrix_names = [t[1] for t in tuples] return expression_matrix[:, tf_indices], tf_matrix_names def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param tf_matrix: the predictor matrix (transcription factor matrix) as a numpy array. :param target_gene_expression: the target (y) gene expression to predict in function of the tf_matrix (X). :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: a trained regression model. """ regressor_type = regressor_type.upper() assert tf_matrix.shape[0] == len(target_gene_expression) def do_sklearn_regression(): regressor = SKLEARN_REGRESSOR_FACTORY[regressor_type](random_state=seed, **regressor_kwargs) with_early_stopping = is_oob_heuristic_supported(regressor_type, regressor_kwargs) if with_early_stopping: regressor.fit(tf_matrix, target_gene_expression, monitor=EarlyStopMonitor(early_stop_window_length)) else: regressor.fit(tf_matrix, target_gene_expression) return regressor if is_sklearn_regressor(regressor_type): return do_sklearn_regression() # elif is_xgboost_regressor(regressor_type): # raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: {0}'.format(regressor_type)) def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): """ Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used. This enables prioritizing links that were inferred in a regression where lots of :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :return: the feature importances inferred from the trained model. """ if is_oob_heuristic_supported(regressor_type, regressor_kwargs): n_estimators = len(trained_regressor.estimators_) denormalized_importances = trained_regressor.feature_importances_ * n_estimators return denormalized_importances else: return trained_regressor.feature_importances_ def to_meta_df(trained_regressor, target_gene_name): """ :param trained_regressor: the trained model from which to extract the meta information. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame containing side information about the regression. """ n_estimators = len(trained_regressor.estimators_) return pd.DataFrame({'target': [target_gene_name], 'n_estimators': [n_estimators]}) def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :param tf_matrix_gene_names: the list of names corresponding to the columns of the tf_matrix used to train the model. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame['TF', 'target', 'importance'] representing inferred regulatory links and their connection strength. """ def pythonic(): # feature_importances = trained_regressor.feature_importances_ feature_importances = to_feature_importances(regressor_type, regressor_kwargs, trained_regressor) links_df = pd.DataFrame({'TF': tf_matrix_gene_names, 'importance': feature_importances}) links_df['target'] = target_gene_name clean_links_df = links_df[links_df.importance > 0].sort_values(by='importance', ascending=False) return clean_links_df[['TF', 'target', 'importance']] if is_sklearn_regressor(regressor_type): return pythonic() elif is_xgboost_regressor(regressor_type): raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: ' + regressor_type) def clean(tf_matrix, tf_matrix_gene_names, target_gene_name): """ :param tf_matrix: numpy array. The full transcription factor matrix. :param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns. :param target_gene_name: the target gene to remove from the tf_matrix and tf_names. :return: a tuple of (matrix, names) equal to the specified ones minus the target_gene_name if the target happens to be one of the transcription factors. If not, the specified (tf_matrix, tf_names) is returned verbatim. """ if target_gene_name not in tf_matrix_gene_names: clean_tf_matrix = tf_matrix else: clean_tf_matrix = np.delete(tf_matrix, tf_matrix_gene_names.index(target_gene_name), 1) clean_tf_names = [tf for tf in tf_matrix_gene_names if tf != target_gene_name] assert clean_tf_matrix.shape[1] == len(clean_tf_names) # sanity check return clean_tf_matrix, clean_tf_names def infer_partial_network(regressor_type, regressor_kwargs, tf_matrix, tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ Ties together regressor model training with regulatory links and meta data extraction. :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param tf_matrix: numpy matrix. The feature matrix X to use for the regression. :param tf_matrix_gene_names: list of transcription factor names corresponding to the columns of the tf_matrix used to train the regression model. :param target_gene_name: the name of the target gene to infer the regulatory links for. :param target_gene_expression: the expression profile of the target gene. Numpy array. :param include_meta: whether to also return the meta information DataFrame. :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: if include_meta == True, return links_df, meta_df link_df: a Pandas DataFrame['TF', 'target', 'importance'] containing inferred regulatory links and their connection strength. meta_df: a Pandas DataFrame['target', 'meta', 'value'] containing meta information regarding the trained regression model. """ def fn(): (clean_tf_matrix, clean_tf_matrix_gene_names) = clean(tf_matrix, tf_matrix_gene_names, target_gene_name) try: trained_regressor = fit_model(regressor_type, regressor_kwargs, clean_tf_matrix, target_gene_expression, early_stop_window_length, seed) except ValueError as e: raise ValueError("Regression for target gene {0} failed. Cause {1}.".format(target_gene_name, repr(e))) links_df = to_links_df(regressor_type, regressor_kwargs, trained_regressor, clean_tf_matrix_gene_names, target_gene_name) if include_meta: meta_df = to_meta_df(trained_regressor, target_gene_name) return links_df, meta_df else: return links_df fallback_result = (None, None) if include_meta else None return retry(fn, fallback_result=fallback_result, warning_msg='infer_data failed for target {0}'.format(target_gene_name)) def target_gene_indices(gene_names, target_genes): """ :param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix. """ if isinstance(target_genes, list) and len(target_genes) == 0: return [] if isinstance(target_genes, str) and target_genes.upper() == 'ALL': return list(range(len(gene_names))) elif isinstance(target_genes, int): top_n = target_genes assert top_n > 0 return list(range(min(top_n, len(gene_names)))) elif isinstance(target_genes, list): if not target_genes: # target_genes is empty return target_genes elif all(isinstance(target_gene, str) for target_gene in target_genes): return [index for index, gene in enumerate(gene_names) if gene in target_genes] elif all(isinstance(target_gene, int) for target_gene in target_genes): return target_genes else: raise ValueError("Mixed types in target genes.") else: raise ValueError("Unable to interpret target_genes.") _GRN_SCHEMA = make_meta({'TF': str, 'target': str, 'importance': float}) _META_SCHEMA = make_meta({'target': str, 'n_estimators': int}) def create_graph(expression_matrix, gene_names, tf_names, regressor_type, regressor_kwargs, client, target_genes='all', limit=None, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, repartition_multiplier=1, seed=DEMON_SEED): """ Main API function. Create a Dask computation graph. Note: fixing the GC problems was fixed by 2 changes: [1] and [2] !!! :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: list of transcription factor names. Should have a non-empty intersection with gene_names. :param regressor_type: regressor type. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param client: a dask.distributed client instance. * Used to scatter-broadcast the tf matrix to the workers instead of simply wrapping in a delayed(). :param target_genes: either int, 'all' or a collection that is a subset of gene_names. :param limit: optional number of top regulatory links to return. Default None. :param include_meta: Also return the meta DataFrame. Default False. :param early_stop_window_length: window length of the early stopping monitor. :param repartition_multiplier: multiplier :param seed: (optional) random seed for the regressors. Default 666. :return: if include_meta is False, returns a Dask graph that computes the links DataFrame. If include_meta is True, returns a tuple: the links DataFrame and the meta DataFrame. """ assert expression_matrix.shape[1] == len(gene_names) assert client, "client is required" tf_matrix, tf_matrix_gene_names = to_tf_matrix(expression_matrix, gene_names, tf_names) future_tf_matrix = client.scatter(tf_matrix, broadcast=True) # [1] wrap in a list of 1 -> unsure why but Matt. Rocklin does this often... [future_tf_matrix_gene_names] = client.scatter([tf_matrix_gene_names], broadcast=True) delayed_link_dfs = [] # collection of delayed link DataFrames delayed_meta_dfs = [] # collection of delayed meta DataFrame for target_gene_index in target_gene_indices(gene_names, target_genes): target_gene_name = delayed(gene_names[target_gene_index], pure=True) target_gene_expression = delayed(expression_matrix[:, target_gene_index], pure=True) if include_meta: delayed_link_df, delayed_meta_df = delayed(infer_partial_network, pure=True, nout=2)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) delayed_meta_dfs.append(delayed_meta_df) else: delayed_link_df = delayed(infer_partial_network, pure=True)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) # gather the DataFrames into one distributed DataFrame all_links_df = from_delayed(delayed_link_dfs, meta=_GRN_SCHEMA) all_meta_df = from_delayed(delayed_meta_dfs, meta=_META_SCHEMA) # optionally limit the number of resulting regulatory links, descending by top importance if limit: maybe_limited_links_df = all_links_df.nlargest(limit, columns=['importance']) else: maybe_limited_links_df = all_links_df # [2] repartition to nr of workers -> important to avoid GC problems! # see: http://dask.pydata.org/en/latest/dataframe-performance.html#repartition-to-reduce-overhead n_parts = len(client.ncores()) * repartition_multiplier if include_meta: return maybe_limited_links_df.repartition(npartitions=n_parts), \ all_meta_df.repartition(npartitions=n_parts) else: return maybe_limited_links_df.repartition(npartitions=n_parts) class EarlyStopMonitor: def __init__(self, window_length=EARLY_STOP_WINDOW_LENGTH): """ :param window_length: length of the window over the out-of-bag errors. """ self.window_length = window_length def window_boundaries(self, current_round): """ :param current_round: :return: the low and high boundaries of the estimators window to consider. """ lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi def __call__(self, current_round, regressor, _): """ Implementation of the GradientBoostingRegressor monitor function API. :param current_round: the current boosting round. :param regressor: the regressor. :param _: ignored. :return: True if the regressor should stop early, else False. """ if current_round >= self.window_length - 1: lo, hi = self.window_boundaries(current_round) return np.mean(regressor.oob_improvement_[lo: hi]) < 0 else: return False
tmoerman/arboreto
arboreto/core.py
infer_partial_network
python
def infer_partial_network(regressor_type, regressor_kwargs, tf_matrix, tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): def fn(): (clean_tf_matrix, clean_tf_matrix_gene_names) = clean(tf_matrix, tf_matrix_gene_names, target_gene_name) try: trained_regressor = fit_model(regressor_type, regressor_kwargs, clean_tf_matrix, target_gene_expression, early_stop_window_length, seed) except ValueError as e: raise ValueError("Regression for target gene {0} failed. Cause {1}.".format(target_gene_name, repr(e))) links_df = to_links_df(regressor_type, regressor_kwargs, trained_regressor, clean_tf_matrix_gene_names, target_gene_name) if include_meta: meta_df = to_meta_df(trained_regressor, target_gene_name) return links_df, meta_df else: return links_df fallback_result = (None, None) if include_meta else None return retry(fn, fallback_result=fallback_result, warning_msg='infer_data failed for target {0}'.format(target_gene_name))
Ties together regressor model training with regulatory links and meta data extraction. :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param tf_matrix: numpy matrix. The feature matrix X to use for the regression. :param tf_matrix_gene_names: list of transcription factor names corresponding to the columns of the tf_matrix used to train the regression model. :param target_gene_name: the name of the target gene to infer the regulatory links for. :param target_gene_expression: the expression profile of the target gene. Numpy array. :param include_meta: whether to also return the meta information DataFrame. :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: if include_meta == True, return links_df, meta_df link_df: a Pandas DataFrame['TF', 'target', 'importance'] containing inferred regulatory links and their connection strength. meta_df: a Pandas DataFrame['target', 'meta', 'value'] containing meta information regarding the trained regression model.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L270-L323
[ "def retry(fn, max_retries=10, warning_msg=None, fallback_result=None):\n \"\"\"\n Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn:\n * https://github.com/scikit-learn/scikit-learn/issues/2755\n * https://github.com/scikit-learn/scikit-learn/issues/7346\n\n :param fn: the function to retry.\n :param max_retries: the maximum number of retries to attempt.\n :param warning_msg: a warning message to display when an attempt fails.\n :param fallback_result: result to return when all attempts fail.\n :return: Returns the result of fn if one attempt succeeds, else return fallback_result.\n \"\"\"\n nr_retries = 0\n\n result = fallback_result\n\n for attempt in range(max_retries):\n try:\n result = fn()\n except Exception as cause:\n nr_retries += 1\n\n msg_head = '' if warning_msg is None else repr(warning_msg) + ' '\n msg_tail = \"Retry ({1}/{2}). Failure caused by {0}.\".format(repr(cause), nr_retries, max_retries)\n\n logger.warning(msg_head + msg_tail)\n else:\n break\n\n return result\n" ]
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from dask.dataframe.utils import make_meta logger = logging.getLogger(__name__) DEMON_SEED = 666 ANGEL_SEED = 777 EARLY_STOP_WINDOW_LENGTH = 25 SKLEARN_REGRESSOR_FACTORY = { 'RF': RandomForestRegressor, 'ET': ExtraTreesRegressor, 'GBM': GradientBoostingRegressor } # scikit-learn random forest regressor RF_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn extra-trees regressor ET_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn gradient boosting regressor GBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 500, 'max_features': 0.1 } # scikit-learn stochastic gradient boosting regressor SGBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 5000, # can be arbitrarily large 'max_features': 0.1, 'subsample': 0.9 } def is_sklearn_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API. """ return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys() def is_xgboost_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: boolean indicating whether the regressor type is the xgboost regressor. """ return regressor_type.upper() == 'XGB' def is_oob_heuristic_supported(regressor_type, regressor_kwargs): """ :param regressor_type: on :param regressor_kwargs: :return: whether early stopping heuristic based on out-of-bag improvement is supported. """ return \ regressor_type.upper() == 'GBM' and \ 'subsample' in regressor_kwargs and \ regressor_kwargs['subsample'] < 1.0 def to_tf_matrix(expression_matrix, gene_names, tf_names): """ :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: a list of transcription factor names. Should be a subset of gene_names. :return: tuple of: 0: A numpy matrix representing the predictor matrix for the regressions. 1: The gene names corresponding to the columns in the predictor matrix. """ tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names] tf_indices = [t[0] for t in tuples] tf_matrix_names = [t[1] for t in tuples] return expression_matrix[:, tf_indices], tf_matrix_names def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param tf_matrix: the predictor matrix (transcription factor matrix) as a numpy array. :param target_gene_expression: the target (y) gene expression to predict in function of the tf_matrix (X). :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: a trained regression model. """ regressor_type = regressor_type.upper() assert tf_matrix.shape[0] == len(target_gene_expression) def do_sklearn_regression(): regressor = SKLEARN_REGRESSOR_FACTORY[regressor_type](random_state=seed, **regressor_kwargs) with_early_stopping = is_oob_heuristic_supported(regressor_type, regressor_kwargs) if with_early_stopping: regressor.fit(tf_matrix, target_gene_expression, monitor=EarlyStopMonitor(early_stop_window_length)) else: regressor.fit(tf_matrix, target_gene_expression) return regressor if is_sklearn_regressor(regressor_type): return do_sklearn_regression() # elif is_xgboost_regressor(regressor_type): # raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: {0}'.format(regressor_type)) def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): """ Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used. This enables prioritizing links that were inferred in a regression where lots of :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :return: the feature importances inferred from the trained model. """ if is_oob_heuristic_supported(regressor_type, regressor_kwargs): n_estimators = len(trained_regressor.estimators_) denormalized_importances = trained_regressor.feature_importances_ * n_estimators return denormalized_importances else: return trained_regressor.feature_importances_ def to_meta_df(trained_regressor, target_gene_name): """ :param trained_regressor: the trained model from which to extract the meta information. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame containing side information about the regression. """ n_estimators = len(trained_regressor.estimators_) return pd.DataFrame({'target': [target_gene_name], 'n_estimators': [n_estimators]}) def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :param tf_matrix_gene_names: the list of names corresponding to the columns of the tf_matrix used to train the model. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame['TF', 'target', 'importance'] representing inferred regulatory links and their connection strength. """ def pythonic(): # feature_importances = trained_regressor.feature_importances_ feature_importances = to_feature_importances(regressor_type, regressor_kwargs, trained_regressor) links_df = pd.DataFrame({'TF': tf_matrix_gene_names, 'importance': feature_importances}) links_df['target'] = target_gene_name clean_links_df = links_df[links_df.importance > 0].sort_values(by='importance', ascending=False) return clean_links_df[['TF', 'target', 'importance']] if is_sklearn_regressor(regressor_type): return pythonic() elif is_xgboost_regressor(regressor_type): raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: ' + regressor_type) def clean(tf_matrix, tf_matrix_gene_names, target_gene_name): """ :param tf_matrix: numpy array. The full transcription factor matrix. :param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns. :param target_gene_name: the target gene to remove from the tf_matrix and tf_names. :return: a tuple of (matrix, names) equal to the specified ones minus the target_gene_name if the target happens to be one of the transcription factors. If not, the specified (tf_matrix, tf_names) is returned verbatim. """ if target_gene_name not in tf_matrix_gene_names: clean_tf_matrix = tf_matrix else: clean_tf_matrix = np.delete(tf_matrix, tf_matrix_gene_names.index(target_gene_name), 1) clean_tf_names = [tf for tf in tf_matrix_gene_names if tf != target_gene_name] assert clean_tf_matrix.shape[1] == len(clean_tf_names) # sanity check return clean_tf_matrix, clean_tf_names def retry(fn, max_retries=10, warning_msg=None, fallback_result=None): """ Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn: * https://github.com/scikit-learn/scikit-learn/issues/2755 * https://github.com/scikit-learn/scikit-learn/issues/7346 :param fn: the function to retry. :param max_retries: the maximum number of retries to attempt. :param warning_msg: a warning message to display when an attempt fails. :param fallback_result: result to return when all attempts fail. :return: Returns the result of fn if one attempt succeeds, else return fallback_result. """ nr_retries = 0 result = fallback_result for attempt in range(max_retries): try: result = fn() except Exception as cause: nr_retries += 1 msg_head = '' if warning_msg is None else repr(warning_msg) + ' ' msg_tail = "Retry ({1}/{2}). Failure caused by {0}.".format(repr(cause), nr_retries, max_retries) logger.warning(msg_head + msg_tail) else: break return result def target_gene_indices(gene_names, target_genes): """ :param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix. """ if isinstance(target_genes, list) and len(target_genes) == 0: return [] if isinstance(target_genes, str) and target_genes.upper() == 'ALL': return list(range(len(gene_names))) elif isinstance(target_genes, int): top_n = target_genes assert top_n > 0 return list(range(min(top_n, len(gene_names)))) elif isinstance(target_genes, list): if not target_genes: # target_genes is empty return target_genes elif all(isinstance(target_gene, str) for target_gene in target_genes): return [index for index, gene in enumerate(gene_names) if gene in target_genes] elif all(isinstance(target_gene, int) for target_gene in target_genes): return target_genes else: raise ValueError("Mixed types in target genes.") else: raise ValueError("Unable to interpret target_genes.") _GRN_SCHEMA = make_meta({'TF': str, 'target': str, 'importance': float}) _META_SCHEMA = make_meta({'target': str, 'n_estimators': int}) def create_graph(expression_matrix, gene_names, tf_names, regressor_type, regressor_kwargs, client, target_genes='all', limit=None, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, repartition_multiplier=1, seed=DEMON_SEED): """ Main API function. Create a Dask computation graph. Note: fixing the GC problems was fixed by 2 changes: [1] and [2] !!! :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: list of transcription factor names. Should have a non-empty intersection with gene_names. :param regressor_type: regressor type. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param client: a dask.distributed client instance. * Used to scatter-broadcast the tf matrix to the workers instead of simply wrapping in a delayed(). :param target_genes: either int, 'all' or a collection that is a subset of gene_names. :param limit: optional number of top regulatory links to return. Default None. :param include_meta: Also return the meta DataFrame. Default False. :param early_stop_window_length: window length of the early stopping monitor. :param repartition_multiplier: multiplier :param seed: (optional) random seed for the regressors. Default 666. :return: if include_meta is False, returns a Dask graph that computes the links DataFrame. If include_meta is True, returns a tuple: the links DataFrame and the meta DataFrame. """ assert expression_matrix.shape[1] == len(gene_names) assert client, "client is required" tf_matrix, tf_matrix_gene_names = to_tf_matrix(expression_matrix, gene_names, tf_names) future_tf_matrix = client.scatter(tf_matrix, broadcast=True) # [1] wrap in a list of 1 -> unsure why but Matt. Rocklin does this often... [future_tf_matrix_gene_names] = client.scatter([tf_matrix_gene_names], broadcast=True) delayed_link_dfs = [] # collection of delayed link DataFrames delayed_meta_dfs = [] # collection of delayed meta DataFrame for target_gene_index in target_gene_indices(gene_names, target_genes): target_gene_name = delayed(gene_names[target_gene_index], pure=True) target_gene_expression = delayed(expression_matrix[:, target_gene_index], pure=True) if include_meta: delayed_link_df, delayed_meta_df = delayed(infer_partial_network, pure=True, nout=2)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) delayed_meta_dfs.append(delayed_meta_df) else: delayed_link_df = delayed(infer_partial_network, pure=True)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) # gather the DataFrames into one distributed DataFrame all_links_df = from_delayed(delayed_link_dfs, meta=_GRN_SCHEMA) all_meta_df = from_delayed(delayed_meta_dfs, meta=_META_SCHEMA) # optionally limit the number of resulting regulatory links, descending by top importance if limit: maybe_limited_links_df = all_links_df.nlargest(limit, columns=['importance']) else: maybe_limited_links_df = all_links_df # [2] repartition to nr of workers -> important to avoid GC problems! # see: http://dask.pydata.org/en/latest/dataframe-performance.html#repartition-to-reduce-overhead n_parts = len(client.ncores()) * repartition_multiplier if include_meta: return maybe_limited_links_df.repartition(npartitions=n_parts), \ all_meta_df.repartition(npartitions=n_parts) else: return maybe_limited_links_df.repartition(npartitions=n_parts) class EarlyStopMonitor: def __init__(self, window_length=EARLY_STOP_WINDOW_LENGTH): """ :param window_length: length of the window over the out-of-bag errors. """ self.window_length = window_length def window_boundaries(self, current_round): """ :param current_round: :return: the low and high boundaries of the estimators window to consider. """ lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi def __call__(self, current_round, regressor, _): """ Implementation of the GradientBoostingRegressor monitor function API. :param current_round: the current boosting round. :param regressor: the regressor. :param _: ignored. :return: True if the regressor should stop early, else False. """ if current_round >= self.window_length - 1: lo, hi = self.window_boundaries(current_round) return np.mean(regressor.oob_improvement_[lo: hi]) < 0 else: return False
tmoerman/arboreto
arboreto/core.py
target_gene_indices
python
def target_gene_indices(gene_names, target_genes): if isinstance(target_genes, list) and len(target_genes) == 0: return [] if isinstance(target_genes, str) and target_genes.upper() == 'ALL': return list(range(len(gene_names))) elif isinstance(target_genes, int): top_n = target_genes assert top_n > 0 return list(range(min(top_n, len(gene_names)))) elif isinstance(target_genes, list): if not target_genes: # target_genes is empty return target_genes elif all(isinstance(target_gene, str) for target_gene in target_genes): return [index for index, gene in enumerate(gene_names) if gene in target_genes] elif all(isinstance(target_gene, int) for target_gene in target_genes): return target_genes else: raise ValueError("Mixed types in target genes.") else: raise ValueError("Unable to interpret target_genes.")
:param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L326-L357
null
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from dask.dataframe.utils import make_meta logger = logging.getLogger(__name__) DEMON_SEED = 666 ANGEL_SEED = 777 EARLY_STOP_WINDOW_LENGTH = 25 SKLEARN_REGRESSOR_FACTORY = { 'RF': RandomForestRegressor, 'ET': ExtraTreesRegressor, 'GBM': GradientBoostingRegressor } # scikit-learn random forest regressor RF_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn extra-trees regressor ET_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn gradient boosting regressor GBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 500, 'max_features': 0.1 } # scikit-learn stochastic gradient boosting regressor SGBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 5000, # can be arbitrarily large 'max_features': 0.1, 'subsample': 0.9 } def is_sklearn_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API. """ return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys() def is_xgboost_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: boolean indicating whether the regressor type is the xgboost regressor. """ return regressor_type.upper() == 'XGB' def is_oob_heuristic_supported(regressor_type, regressor_kwargs): """ :param regressor_type: on :param regressor_kwargs: :return: whether early stopping heuristic based on out-of-bag improvement is supported. """ return \ regressor_type.upper() == 'GBM' and \ 'subsample' in regressor_kwargs and \ regressor_kwargs['subsample'] < 1.0 def to_tf_matrix(expression_matrix, gene_names, tf_names): """ :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: a list of transcription factor names. Should be a subset of gene_names. :return: tuple of: 0: A numpy matrix representing the predictor matrix for the regressions. 1: The gene names corresponding to the columns in the predictor matrix. """ tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names] tf_indices = [t[0] for t in tuples] tf_matrix_names = [t[1] for t in tuples] return expression_matrix[:, tf_indices], tf_matrix_names def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param tf_matrix: the predictor matrix (transcription factor matrix) as a numpy array. :param target_gene_expression: the target (y) gene expression to predict in function of the tf_matrix (X). :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: a trained regression model. """ regressor_type = regressor_type.upper() assert tf_matrix.shape[0] == len(target_gene_expression) def do_sklearn_regression(): regressor = SKLEARN_REGRESSOR_FACTORY[regressor_type](random_state=seed, **regressor_kwargs) with_early_stopping = is_oob_heuristic_supported(regressor_type, regressor_kwargs) if with_early_stopping: regressor.fit(tf_matrix, target_gene_expression, monitor=EarlyStopMonitor(early_stop_window_length)) else: regressor.fit(tf_matrix, target_gene_expression) return regressor if is_sklearn_regressor(regressor_type): return do_sklearn_regression() # elif is_xgboost_regressor(regressor_type): # raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: {0}'.format(regressor_type)) def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): """ Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used. This enables prioritizing links that were inferred in a regression where lots of :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :return: the feature importances inferred from the trained model. """ if is_oob_heuristic_supported(regressor_type, regressor_kwargs): n_estimators = len(trained_regressor.estimators_) denormalized_importances = trained_regressor.feature_importances_ * n_estimators return denormalized_importances else: return trained_regressor.feature_importances_ def to_meta_df(trained_regressor, target_gene_name): """ :param trained_regressor: the trained model from which to extract the meta information. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame containing side information about the regression. """ n_estimators = len(trained_regressor.estimators_) return pd.DataFrame({'target': [target_gene_name], 'n_estimators': [n_estimators]}) def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :param tf_matrix_gene_names: the list of names corresponding to the columns of the tf_matrix used to train the model. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame['TF', 'target', 'importance'] representing inferred regulatory links and their connection strength. """ def pythonic(): # feature_importances = trained_regressor.feature_importances_ feature_importances = to_feature_importances(regressor_type, regressor_kwargs, trained_regressor) links_df = pd.DataFrame({'TF': tf_matrix_gene_names, 'importance': feature_importances}) links_df['target'] = target_gene_name clean_links_df = links_df[links_df.importance > 0].sort_values(by='importance', ascending=False) return clean_links_df[['TF', 'target', 'importance']] if is_sklearn_regressor(regressor_type): return pythonic() elif is_xgboost_regressor(regressor_type): raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: ' + regressor_type) def clean(tf_matrix, tf_matrix_gene_names, target_gene_name): """ :param tf_matrix: numpy array. The full transcription factor matrix. :param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns. :param target_gene_name: the target gene to remove from the tf_matrix and tf_names. :return: a tuple of (matrix, names) equal to the specified ones minus the target_gene_name if the target happens to be one of the transcription factors. If not, the specified (tf_matrix, tf_names) is returned verbatim. """ if target_gene_name not in tf_matrix_gene_names: clean_tf_matrix = tf_matrix else: clean_tf_matrix = np.delete(tf_matrix, tf_matrix_gene_names.index(target_gene_name), 1) clean_tf_names = [tf for tf in tf_matrix_gene_names if tf != target_gene_name] assert clean_tf_matrix.shape[1] == len(clean_tf_names) # sanity check return clean_tf_matrix, clean_tf_names def retry(fn, max_retries=10, warning_msg=None, fallback_result=None): """ Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn: * https://github.com/scikit-learn/scikit-learn/issues/2755 * https://github.com/scikit-learn/scikit-learn/issues/7346 :param fn: the function to retry. :param max_retries: the maximum number of retries to attempt. :param warning_msg: a warning message to display when an attempt fails. :param fallback_result: result to return when all attempts fail. :return: Returns the result of fn if one attempt succeeds, else return fallback_result. """ nr_retries = 0 result = fallback_result for attempt in range(max_retries): try: result = fn() except Exception as cause: nr_retries += 1 msg_head = '' if warning_msg is None else repr(warning_msg) + ' ' msg_tail = "Retry ({1}/{2}). Failure caused by {0}.".format(repr(cause), nr_retries, max_retries) logger.warning(msg_head + msg_tail) else: break return result def infer_partial_network(regressor_type, regressor_kwargs, tf_matrix, tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ Ties together regressor model training with regulatory links and meta data extraction. :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param tf_matrix: numpy matrix. The feature matrix X to use for the regression. :param tf_matrix_gene_names: list of transcription factor names corresponding to the columns of the tf_matrix used to train the regression model. :param target_gene_name: the name of the target gene to infer the regulatory links for. :param target_gene_expression: the expression profile of the target gene. Numpy array. :param include_meta: whether to also return the meta information DataFrame. :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: if include_meta == True, return links_df, meta_df link_df: a Pandas DataFrame['TF', 'target', 'importance'] containing inferred regulatory links and their connection strength. meta_df: a Pandas DataFrame['target', 'meta', 'value'] containing meta information regarding the trained regression model. """ def fn(): (clean_tf_matrix, clean_tf_matrix_gene_names) = clean(tf_matrix, tf_matrix_gene_names, target_gene_name) try: trained_regressor = fit_model(regressor_type, regressor_kwargs, clean_tf_matrix, target_gene_expression, early_stop_window_length, seed) except ValueError as e: raise ValueError("Regression for target gene {0} failed. Cause {1}.".format(target_gene_name, repr(e))) links_df = to_links_df(regressor_type, regressor_kwargs, trained_regressor, clean_tf_matrix_gene_names, target_gene_name) if include_meta: meta_df = to_meta_df(trained_regressor, target_gene_name) return links_df, meta_df else: return links_df fallback_result = (None, None) if include_meta else None return retry(fn, fallback_result=fallback_result, warning_msg='infer_data failed for target {0}'.format(target_gene_name)) _GRN_SCHEMA = make_meta({'TF': str, 'target': str, 'importance': float}) _META_SCHEMA = make_meta({'target': str, 'n_estimators': int}) def create_graph(expression_matrix, gene_names, tf_names, regressor_type, regressor_kwargs, client, target_genes='all', limit=None, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, repartition_multiplier=1, seed=DEMON_SEED): """ Main API function. Create a Dask computation graph. Note: fixing the GC problems was fixed by 2 changes: [1] and [2] !!! :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: list of transcription factor names. Should have a non-empty intersection with gene_names. :param regressor_type: regressor type. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param client: a dask.distributed client instance. * Used to scatter-broadcast the tf matrix to the workers instead of simply wrapping in a delayed(). :param target_genes: either int, 'all' or a collection that is a subset of gene_names. :param limit: optional number of top regulatory links to return. Default None. :param include_meta: Also return the meta DataFrame. Default False. :param early_stop_window_length: window length of the early stopping monitor. :param repartition_multiplier: multiplier :param seed: (optional) random seed for the regressors. Default 666. :return: if include_meta is False, returns a Dask graph that computes the links DataFrame. If include_meta is True, returns a tuple: the links DataFrame and the meta DataFrame. """ assert expression_matrix.shape[1] == len(gene_names) assert client, "client is required" tf_matrix, tf_matrix_gene_names = to_tf_matrix(expression_matrix, gene_names, tf_names) future_tf_matrix = client.scatter(tf_matrix, broadcast=True) # [1] wrap in a list of 1 -> unsure why but Matt. Rocklin does this often... [future_tf_matrix_gene_names] = client.scatter([tf_matrix_gene_names], broadcast=True) delayed_link_dfs = [] # collection of delayed link DataFrames delayed_meta_dfs = [] # collection of delayed meta DataFrame for target_gene_index in target_gene_indices(gene_names, target_genes): target_gene_name = delayed(gene_names[target_gene_index], pure=True) target_gene_expression = delayed(expression_matrix[:, target_gene_index], pure=True) if include_meta: delayed_link_df, delayed_meta_df = delayed(infer_partial_network, pure=True, nout=2)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) delayed_meta_dfs.append(delayed_meta_df) else: delayed_link_df = delayed(infer_partial_network, pure=True)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) # gather the DataFrames into one distributed DataFrame all_links_df = from_delayed(delayed_link_dfs, meta=_GRN_SCHEMA) all_meta_df = from_delayed(delayed_meta_dfs, meta=_META_SCHEMA) # optionally limit the number of resulting regulatory links, descending by top importance if limit: maybe_limited_links_df = all_links_df.nlargest(limit, columns=['importance']) else: maybe_limited_links_df = all_links_df # [2] repartition to nr of workers -> important to avoid GC problems! # see: http://dask.pydata.org/en/latest/dataframe-performance.html#repartition-to-reduce-overhead n_parts = len(client.ncores()) * repartition_multiplier if include_meta: return maybe_limited_links_df.repartition(npartitions=n_parts), \ all_meta_df.repartition(npartitions=n_parts) else: return maybe_limited_links_df.repartition(npartitions=n_parts) class EarlyStopMonitor: def __init__(self, window_length=EARLY_STOP_WINDOW_LENGTH): """ :param window_length: length of the window over the out-of-bag errors. """ self.window_length = window_length def window_boundaries(self, current_round): """ :param current_round: :return: the low and high boundaries of the estimators window to consider. """ lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi def __call__(self, current_round, regressor, _): """ Implementation of the GradientBoostingRegressor monitor function API. :param current_round: the current boosting round. :param regressor: the regressor. :param _: ignored. :return: True if the regressor should stop early, else False. """ if current_round >= self.window_length - 1: lo, hi = self.window_boundaries(current_round) return np.mean(regressor.oob_improvement_[lo: hi]) < 0 else: return False
tmoerman/arboreto
arboreto/core.py
create_graph
python
def create_graph(expression_matrix, gene_names, tf_names, regressor_type, regressor_kwargs, client, target_genes='all', limit=None, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, repartition_multiplier=1, seed=DEMON_SEED): assert expression_matrix.shape[1] == len(gene_names) assert client, "client is required" tf_matrix, tf_matrix_gene_names = to_tf_matrix(expression_matrix, gene_names, tf_names) future_tf_matrix = client.scatter(tf_matrix, broadcast=True) # [1] wrap in a list of 1 -> unsure why but Matt. Rocklin does this often... [future_tf_matrix_gene_names] = client.scatter([tf_matrix_gene_names], broadcast=True) delayed_link_dfs = [] # collection of delayed link DataFrames delayed_meta_dfs = [] # collection of delayed meta DataFrame for target_gene_index in target_gene_indices(gene_names, target_genes): target_gene_name = delayed(gene_names[target_gene_index], pure=True) target_gene_expression = delayed(expression_matrix[:, target_gene_index], pure=True) if include_meta: delayed_link_df, delayed_meta_df = delayed(infer_partial_network, pure=True, nout=2)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) delayed_meta_dfs.append(delayed_meta_df) else: delayed_link_df = delayed(infer_partial_network, pure=True)( regressor_type, regressor_kwargs, future_tf_matrix, future_tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed) if delayed_link_df is not None: delayed_link_dfs.append(delayed_link_df) # gather the DataFrames into one distributed DataFrame all_links_df = from_delayed(delayed_link_dfs, meta=_GRN_SCHEMA) all_meta_df = from_delayed(delayed_meta_dfs, meta=_META_SCHEMA) # optionally limit the number of resulting regulatory links, descending by top importance if limit: maybe_limited_links_df = all_links_df.nlargest(limit, columns=['importance']) else: maybe_limited_links_df = all_links_df # [2] repartition to nr of workers -> important to avoid GC problems! # see: http://dask.pydata.org/en/latest/dataframe-performance.html#repartition-to-reduce-overhead n_parts = len(client.ncores()) * repartition_multiplier if include_meta: return maybe_limited_links_df.repartition(npartitions=n_parts), \ all_meta_df.repartition(npartitions=n_parts) else: return maybe_limited_links_df.repartition(npartitions=n_parts)
Main API function. Create a Dask computation graph. Note: fixing the GC problems was fixed by 2 changes: [1] and [2] !!! :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: list of transcription factor names. Should have a non-empty intersection with gene_names. :param regressor_type: regressor type. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param client: a dask.distributed client instance. * Used to scatter-broadcast the tf matrix to the workers instead of simply wrapping in a delayed(). :param target_genes: either int, 'all' or a collection that is a subset of gene_names. :param limit: optional number of top regulatory links to return. Default None. :param include_meta: Also return the meta DataFrame. Default False. :param early_stop_window_length: window length of the early stopping monitor. :param repartition_multiplier: multiplier :param seed: (optional) random seed for the regressors. Default 666. :return: if include_meta is False, returns a Dask graph that computes the links DataFrame. If include_meta is True, returns a tuple: the links DataFrame and the meta DataFrame.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L364-L450
[ "def to_tf_matrix(expression_matrix,\n gene_names,\n tf_names):\n \"\"\"\n :param expression_matrix: numpy matrix. Rows are observations and columns are genes.\n :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index.\n :param tf_names: a list of transcription factor names. Should be a subset of gene_names.\n :return: tuple of:\n 0: A numpy matrix representing the predictor matrix for the regressions.\n 1: The gene names corresponding to the columns in the predictor matrix.\n \"\"\"\n\n tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names]\n\n tf_indices = [t[0] for t in tuples]\n tf_matrix_names = [t[1] for t in tuples]\n\n return expression_matrix[:, tf_indices], tf_matrix_names\n", "def target_gene_indices(gene_names,\n target_genes):\n \"\"\"\n :param gene_names: list of gene names.\n :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names).\n :return: the (column) indices of the target genes in the expression_matrix.\n \"\"\"\n\n if isinstance(target_genes, list) and len(target_genes) == 0:\n return []\n\n if isinstance(target_genes, str) and target_genes.upper() == 'ALL':\n return list(range(len(gene_names)))\n\n elif isinstance(target_genes, int):\n top_n = target_genes\n assert top_n > 0\n\n return list(range(min(top_n, len(gene_names))))\n\n elif isinstance(target_genes, list):\n if not target_genes: # target_genes is empty\n return target_genes\n elif all(isinstance(target_gene, str) for target_gene in target_genes):\n return [index for index, gene in enumerate(gene_names) if gene in target_genes]\n elif all(isinstance(target_gene, int) for target_gene in target_genes):\n return target_genes\n else:\n raise ValueError(\"Mixed types in target genes.\")\n\n else:\n raise ValueError(\"Unable to interpret target_genes.\")\n" ]
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from dask.dataframe.utils import make_meta logger = logging.getLogger(__name__) DEMON_SEED = 666 ANGEL_SEED = 777 EARLY_STOP_WINDOW_LENGTH = 25 SKLEARN_REGRESSOR_FACTORY = { 'RF': RandomForestRegressor, 'ET': ExtraTreesRegressor, 'GBM': GradientBoostingRegressor } # scikit-learn random forest regressor RF_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn extra-trees regressor ET_KWARGS = { 'n_jobs': 1, 'n_estimators': 1000, 'max_features': 'sqrt' } # scikit-learn gradient boosting regressor GBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 500, 'max_features': 0.1 } # scikit-learn stochastic gradient boosting regressor SGBM_KWARGS = { 'learning_rate': 0.01, 'n_estimators': 5000, # can be arbitrarily large 'max_features': 0.1, 'subsample': 0.9 } def is_sklearn_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API. """ return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys() def is_xgboost_regressor(regressor_type): """ :param regressor_type: string. Case insensitive. :return: boolean indicating whether the regressor type is the xgboost regressor. """ return regressor_type.upper() == 'XGB' def is_oob_heuristic_supported(regressor_type, regressor_kwargs): """ :param regressor_type: on :param regressor_kwargs: :return: whether early stopping heuristic based on out-of-bag improvement is supported. """ return \ regressor_type.upper() == 'GBM' and \ 'subsample' in regressor_kwargs and \ regressor_kwargs['subsample'] < 1.0 def to_tf_matrix(expression_matrix, gene_names, tf_names): """ :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: a list of transcription factor names. Should be a subset of gene_names. :return: tuple of: 0: A numpy matrix representing the predictor matrix for the regressions. 1: The gene names corresponding to the columns in the predictor matrix. """ tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names] tf_indices = [t[0] for t in tuples] tf_matrix_names = [t[1] for t in tuples] return expression_matrix[:, tf_indices], tf_matrix_names def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param tf_matrix: the predictor matrix (transcription factor matrix) as a numpy array. :param target_gene_expression: the target (y) gene expression to predict in function of the tf_matrix (X). :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: a trained regression model. """ regressor_type = regressor_type.upper() assert tf_matrix.shape[0] == len(target_gene_expression) def do_sklearn_regression(): regressor = SKLEARN_REGRESSOR_FACTORY[regressor_type](random_state=seed, **regressor_kwargs) with_early_stopping = is_oob_heuristic_supported(regressor_type, regressor_kwargs) if with_early_stopping: regressor.fit(tf_matrix, target_gene_expression, monitor=EarlyStopMonitor(early_stop_window_length)) else: regressor.fit(tf_matrix, target_gene_expression) return regressor if is_sklearn_regressor(regressor_type): return do_sklearn_regression() # elif is_xgboost_regressor(regressor_type): # raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: {0}'.format(regressor_type)) def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): """ Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used. This enables prioritizing links that were inferred in a regression where lots of :param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :return: the feature importances inferred from the trained model. """ if is_oob_heuristic_supported(regressor_type, regressor_kwargs): n_estimators = len(trained_regressor.estimators_) denormalized_importances = trained_regressor.feature_importances_ * n_estimators return denormalized_importances else: return trained_regressor.feature_importances_ def to_meta_df(trained_regressor, target_gene_name): """ :param trained_regressor: the trained model from which to extract the meta information. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame containing side information about the regression. """ n_estimators = len(trained_regressor.estimators_) return pd.DataFrame({'target': [target_gene_name], 'n_estimators': [n_estimators]}) def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :param tf_matrix_gene_names: the list of names corresponding to the columns of the tf_matrix used to train the model. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame['TF', 'target', 'importance'] representing inferred regulatory links and their connection strength. """ def pythonic(): # feature_importances = trained_regressor.feature_importances_ feature_importances = to_feature_importances(regressor_type, regressor_kwargs, trained_regressor) links_df = pd.DataFrame({'TF': tf_matrix_gene_names, 'importance': feature_importances}) links_df['target'] = target_gene_name clean_links_df = links_df[links_df.importance > 0].sort_values(by='importance', ascending=False) return clean_links_df[['TF', 'target', 'importance']] if is_sklearn_regressor(regressor_type): return pythonic() elif is_xgboost_regressor(regressor_type): raise ValueError('XGB regressor not yet supported') else: raise ValueError('Unsupported regressor type: ' + regressor_type) def clean(tf_matrix, tf_matrix_gene_names, target_gene_name): """ :param tf_matrix: numpy array. The full transcription factor matrix. :param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns. :param target_gene_name: the target gene to remove from the tf_matrix and tf_names. :return: a tuple of (matrix, names) equal to the specified ones minus the target_gene_name if the target happens to be one of the transcription factors. If not, the specified (tf_matrix, tf_names) is returned verbatim. """ if target_gene_name not in tf_matrix_gene_names: clean_tf_matrix = tf_matrix else: clean_tf_matrix = np.delete(tf_matrix, tf_matrix_gene_names.index(target_gene_name), 1) clean_tf_names = [tf for tf in tf_matrix_gene_names if tf != target_gene_name] assert clean_tf_matrix.shape[1] == len(clean_tf_names) # sanity check return clean_tf_matrix, clean_tf_names def retry(fn, max_retries=10, warning_msg=None, fallback_result=None): """ Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn: * https://github.com/scikit-learn/scikit-learn/issues/2755 * https://github.com/scikit-learn/scikit-learn/issues/7346 :param fn: the function to retry. :param max_retries: the maximum number of retries to attempt. :param warning_msg: a warning message to display when an attempt fails. :param fallback_result: result to return when all attempts fail. :return: Returns the result of fn if one attempt succeeds, else return fallback_result. """ nr_retries = 0 result = fallback_result for attempt in range(max_retries): try: result = fn() except Exception as cause: nr_retries += 1 msg_head = '' if warning_msg is None else repr(warning_msg) + ' ' msg_tail = "Retry ({1}/{2}). Failure caused by {0}.".format(repr(cause), nr_retries, max_retries) logger.warning(msg_head + msg_tail) else: break return result def infer_partial_network(regressor_type, regressor_kwargs, tf_matrix, tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta=False, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ Ties together regressor model training with regulatory links and meta data extraction. :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param tf_matrix: numpy matrix. The feature matrix X to use for the regression. :param tf_matrix_gene_names: list of transcription factor names corresponding to the columns of the tf_matrix used to train the regression model. :param target_gene_name: the name of the target gene to infer the regulatory links for. :param target_gene_expression: the expression profile of the target gene. Numpy array. :param include_meta: whether to also return the meta information DataFrame. :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: if include_meta == True, return links_df, meta_df link_df: a Pandas DataFrame['TF', 'target', 'importance'] containing inferred regulatory links and their connection strength. meta_df: a Pandas DataFrame['target', 'meta', 'value'] containing meta information regarding the trained regression model. """ def fn(): (clean_tf_matrix, clean_tf_matrix_gene_names) = clean(tf_matrix, tf_matrix_gene_names, target_gene_name) try: trained_regressor = fit_model(regressor_type, regressor_kwargs, clean_tf_matrix, target_gene_expression, early_stop_window_length, seed) except ValueError as e: raise ValueError("Regression for target gene {0} failed. Cause {1}.".format(target_gene_name, repr(e))) links_df = to_links_df(regressor_type, regressor_kwargs, trained_regressor, clean_tf_matrix_gene_names, target_gene_name) if include_meta: meta_df = to_meta_df(trained_regressor, target_gene_name) return links_df, meta_df else: return links_df fallback_result = (None, None) if include_meta else None return retry(fn, fallback_result=fallback_result, warning_msg='infer_data failed for target {0}'.format(target_gene_name)) def target_gene_indices(gene_names, target_genes): """ :param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix. """ if isinstance(target_genes, list) and len(target_genes) == 0: return [] if isinstance(target_genes, str) and target_genes.upper() == 'ALL': return list(range(len(gene_names))) elif isinstance(target_genes, int): top_n = target_genes assert top_n > 0 return list(range(min(top_n, len(gene_names)))) elif isinstance(target_genes, list): if not target_genes: # target_genes is empty return target_genes elif all(isinstance(target_gene, str) for target_gene in target_genes): return [index for index, gene in enumerate(gene_names) if gene in target_genes] elif all(isinstance(target_gene, int) for target_gene in target_genes): return target_genes else: raise ValueError("Mixed types in target genes.") else: raise ValueError("Unable to interpret target_genes.") _GRN_SCHEMA = make_meta({'TF': str, 'target': str, 'importance': float}) _META_SCHEMA = make_meta({'target': str, 'n_estimators': int}) class EarlyStopMonitor: def __init__(self, window_length=EARLY_STOP_WINDOW_LENGTH): """ :param window_length: length of the window over the out-of-bag errors. """ self.window_length = window_length def window_boundaries(self, current_round): """ :param current_round: :return: the low and high boundaries of the estimators window to consider. """ lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi def __call__(self, current_round, regressor, _): """ Implementation of the GradientBoostingRegressor monitor function API. :param current_round: the current boosting round. :param regressor: the regressor. :param _: ignored. :return: True if the regressor should stop early, else False. """ if current_round >= self.window_length - 1: lo, hi = self.window_boundaries(current_round) return np.mean(regressor.oob_improvement_[lo: hi]) < 0 else: return False
tmoerman/arboreto
arboreto/core.py
EarlyStopMonitor.window_boundaries
python
def window_boundaries(self, current_round): lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi
:param current_round: :return: the low and high boundaries of the estimators window to consider.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L462-L471
null
class EarlyStopMonitor: def __init__(self, window_length=EARLY_STOP_WINDOW_LENGTH): """ :param window_length: length of the window over the out-of-bag errors. """ self.window_length = window_length def __call__(self, current_round, regressor, _): """ Implementation of the GradientBoostingRegressor monitor function API. :param current_round: the current boosting round. :param regressor: the regressor. :param _: ignored. :return: True if the regressor should stop early, else False. """ if current_round >= self.window_length - 1: lo, hi = self.window_boundaries(current_round) return np.mean(regressor.oob_improvement_[lo: hi]) < 0 else: return False
tmoerman/arboreto
arboreto/algo.py
grnboost2
python
def grnboost2(expression_data, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): return diy(expression_data=expression_data, regressor_type='GBM', regressor_kwargs=SGBM_KWARGS, gene_names=gene_names, tf_names=tf_names, client_or_address=client_or_address, early_stop_window_length=early_stop_window_length, limit=limit, seed=seed, verbose=verbose)
Launch arboreto with [GRNBoost2] profile. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param early_stop_window_length: early stop window length. Default 25. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default None. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/algo.py#L10-L41
[ "def diy(expression_data,\n regressor_type,\n regressor_kwargs,\n gene_names=None,\n tf_names='all',\n client_or_address='local',\n early_stop_window_length=EARLY_STOP_WINDOW_LENGTH,\n limit=None,\n seed=None,\n verbose=False):\n \"\"\"\n :param expression_data: one of:\n * a pandas DataFrame (rows=observations, columns=genes)\n * a dense 2D numpy.ndarray\n * a sparse scipy.sparse.csc_matrix\n :param regressor_type: string. One of: 'RF', 'GBM', 'ET'. Case insensitive.\n :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor.\n :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as\n 'expression_data' instead of a DataFrame.\n :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used.\n :param early_stop_window_length: early stopping window length.\n :param client_or_address: one of:\n * None or 'local': a new Client(LocalCluster()) will be used to perform the computation.\n * string address: a new Client(address) will be used to perform the computation.\n * a Client instance: the specified Client instance will be used to perform the computation.\n :param limit: optional number (int) of top regulatory links to return. Default None.\n :param seed: optional random seed for the regressors. Default 666. Use None for random seed.\n :param verbose: print info.\n :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links.\n \"\"\"\n if verbose:\n print('preparing dask client')\n\n client, shutdown_callback = _prepare_client(client_or_address)\n\n try:\n if verbose:\n print('parsing input')\n\n expression_matrix, gene_names, tf_names = _prepare_input(expression_data, gene_names, tf_names)\n\n if verbose:\n print('creating dask graph')\n\n graph = create_graph(expression_matrix,\n gene_names,\n tf_names,\n client=client,\n regressor_type=regressor_type,\n regressor_kwargs=regressor_kwargs,\n early_stop_window_length=early_stop_window_length,\n limit=limit,\n seed=seed)\n\n if verbose:\n print('{} partitions'.format(graph.npartitions))\n print('computing dask graph')\n\n return client \\\n .compute(graph, sync=True) \\\n .sort_values(by='importance', ascending=False)\n\n finally:\n shutdown_callback(verbose)\n\n if verbose:\n print('finished')\n" ]
""" Top-level functions. """ import pandas as pd from distributed import Client, LocalCluster from arboreto.core import create_graph, SGBM_KWARGS, RF_KWARGS, EARLY_STOP_WINDOW_LENGTH def genie3(expression_data, gene_names=None, tf_names='all', client_or_address='local', limit=None, seed=None, verbose=False): """ Launch arboreto with [GENIE3] profile. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default None. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links. """ return diy(expression_data=expression_data, regressor_type='RF', regressor_kwargs=RF_KWARGS, gene_names=gene_names, tf_names=tf_names, client_or_address=client_or_address, limit=limit, seed=seed, verbose=verbose) def diy(expression_data, regressor_type, regressor_kwargs, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): """ :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param regressor_type: string. One of: 'RF', 'GBM', 'ET'. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param early_stop_window_length: early stopping window length. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default 666. Use None for random seed. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links. """ if verbose: print('preparing dask client') client, shutdown_callback = _prepare_client(client_or_address) try: if verbose: print('parsing input') expression_matrix, gene_names, tf_names = _prepare_input(expression_data, gene_names, tf_names) if verbose: print('creating dask graph') graph = create_graph(expression_matrix, gene_names, tf_names, client=client, regressor_type=regressor_type, regressor_kwargs=regressor_kwargs, early_stop_window_length=early_stop_window_length, limit=limit, seed=seed) if verbose: print('{} partitions'.format(graph.npartitions)) print('computing dask graph') return client \ .compute(graph, sync=True) \ .sort_values(by='importance', ascending=False) finally: shutdown_callback(verbose) if verbose: print('finished') def _prepare_client(client_or_address): """ :param client_or_address: one of: * None * verbatim: 'local' * string address * a Client instance :return: a tuple: (Client instance, shutdown callback function). :raises: ValueError if no valid client input was provided. """ if client_or_address is None or str(client_or_address).lower() == 'local': local_cluster = LocalCluster(diagnostics_port=None) client = Client(local_cluster) def close_client_and_local_cluster(verbose=False): if verbose: print('shutting down client and local cluster') client.close() local_cluster.close() return client, close_client_and_local_cluster elif isinstance(client_or_address, str) and client_or_address.lower() != 'local': client = Client(client_or_address) def close_client(verbose=False): if verbose: print('shutting down client') client.close() return client, close_client elif isinstance(client_or_address, Client): def close_dummy(verbose=False): if verbose: print('not shutting down client, client was created externally') return None return client_or_address, close_dummy else: raise ValueError("Invalid client specified {}".format(str(client_or_address))) def _prepare_input(expression_data, gene_names, tf_names): """ Wrangle the inputs into the correct formats. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :return: a triple of: 1. a np.ndarray or scipy.sparse.csc_matrix 2. a list of gene name strings 3. a list of transcription factor name strings. """ if isinstance(expression_data, pd.DataFrame): expression_matrix = expression_data.as_matrix() gene_names = list(expression_data.columns) else: expression_matrix = expression_data assert expression_matrix.shape[1] == len(gene_names) if tf_names is None: tf_names = gene_names elif tf_names == 'all': tf_names = gene_names else: if len(tf_names) == 0: raise ValueError('Specified tf_names is empty') if not set(gene_names).intersection(set(tf_names)): raise ValueError('Intersection of gene_names and tf_names is empty.') return expression_matrix, gene_names, tf_names
tmoerman/arboreto
arboreto/algo.py
genie3
python
def genie3(expression_data, gene_names=None, tf_names='all', client_or_address='local', limit=None, seed=None, verbose=False): return diy(expression_data=expression_data, regressor_type='RF', regressor_kwargs=RF_KWARGS, gene_names=gene_names, tf_names=tf_names, client_or_address=client_or_address, limit=limit, seed=seed, verbose=verbose)
Launch arboreto with [GENIE3] profile. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default None. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/algo.py#L44-L73
[ "def diy(expression_data,\n regressor_type,\n regressor_kwargs,\n gene_names=None,\n tf_names='all',\n client_or_address='local',\n early_stop_window_length=EARLY_STOP_WINDOW_LENGTH,\n limit=None,\n seed=None,\n verbose=False):\n \"\"\"\n :param expression_data: one of:\n * a pandas DataFrame (rows=observations, columns=genes)\n * a dense 2D numpy.ndarray\n * a sparse scipy.sparse.csc_matrix\n :param regressor_type: string. One of: 'RF', 'GBM', 'ET'. Case insensitive.\n :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor.\n :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as\n 'expression_data' instead of a DataFrame.\n :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used.\n :param early_stop_window_length: early stopping window length.\n :param client_or_address: one of:\n * None or 'local': a new Client(LocalCluster()) will be used to perform the computation.\n * string address: a new Client(address) will be used to perform the computation.\n * a Client instance: the specified Client instance will be used to perform the computation.\n :param limit: optional number (int) of top regulatory links to return. Default None.\n :param seed: optional random seed for the regressors. Default 666. Use None for random seed.\n :param verbose: print info.\n :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links.\n \"\"\"\n if verbose:\n print('preparing dask client')\n\n client, shutdown_callback = _prepare_client(client_or_address)\n\n try:\n if verbose:\n print('parsing input')\n\n expression_matrix, gene_names, tf_names = _prepare_input(expression_data, gene_names, tf_names)\n\n if verbose:\n print('creating dask graph')\n\n graph = create_graph(expression_matrix,\n gene_names,\n tf_names,\n client=client,\n regressor_type=regressor_type,\n regressor_kwargs=regressor_kwargs,\n early_stop_window_length=early_stop_window_length,\n limit=limit,\n seed=seed)\n\n if verbose:\n print('{} partitions'.format(graph.npartitions))\n print('computing dask graph')\n\n return client \\\n .compute(graph, sync=True) \\\n .sort_values(by='importance', ascending=False)\n\n finally:\n shutdown_callback(verbose)\n\n if verbose:\n print('finished')\n" ]
""" Top-level functions. """ import pandas as pd from distributed import Client, LocalCluster from arboreto.core import create_graph, SGBM_KWARGS, RF_KWARGS, EARLY_STOP_WINDOW_LENGTH def grnboost2(expression_data, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): """ Launch arboreto with [GRNBoost2] profile. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param early_stop_window_length: early stop window length. Default 25. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default None. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links. """ return diy(expression_data=expression_data, regressor_type='GBM', regressor_kwargs=SGBM_KWARGS, gene_names=gene_names, tf_names=tf_names, client_or_address=client_or_address, early_stop_window_length=early_stop_window_length, limit=limit, seed=seed, verbose=verbose) def diy(expression_data, regressor_type, regressor_kwargs, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): """ :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param regressor_type: string. One of: 'RF', 'GBM', 'ET'. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param early_stop_window_length: early stopping window length. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default 666. Use None for random seed. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links. """ if verbose: print('preparing dask client') client, shutdown_callback = _prepare_client(client_or_address) try: if verbose: print('parsing input') expression_matrix, gene_names, tf_names = _prepare_input(expression_data, gene_names, tf_names) if verbose: print('creating dask graph') graph = create_graph(expression_matrix, gene_names, tf_names, client=client, regressor_type=regressor_type, regressor_kwargs=regressor_kwargs, early_stop_window_length=early_stop_window_length, limit=limit, seed=seed) if verbose: print('{} partitions'.format(graph.npartitions)) print('computing dask graph') return client \ .compute(graph, sync=True) \ .sort_values(by='importance', ascending=False) finally: shutdown_callback(verbose) if verbose: print('finished') def _prepare_client(client_or_address): """ :param client_or_address: one of: * None * verbatim: 'local' * string address * a Client instance :return: a tuple: (Client instance, shutdown callback function). :raises: ValueError if no valid client input was provided. """ if client_or_address is None or str(client_or_address).lower() == 'local': local_cluster = LocalCluster(diagnostics_port=None) client = Client(local_cluster) def close_client_and_local_cluster(verbose=False): if verbose: print('shutting down client and local cluster') client.close() local_cluster.close() return client, close_client_and_local_cluster elif isinstance(client_or_address, str) and client_or_address.lower() != 'local': client = Client(client_or_address) def close_client(verbose=False): if verbose: print('shutting down client') client.close() return client, close_client elif isinstance(client_or_address, Client): def close_dummy(verbose=False): if verbose: print('not shutting down client, client was created externally') return None return client_or_address, close_dummy else: raise ValueError("Invalid client specified {}".format(str(client_or_address))) def _prepare_input(expression_data, gene_names, tf_names): """ Wrangle the inputs into the correct formats. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :return: a triple of: 1. a np.ndarray or scipy.sparse.csc_matrix 2. a list of gene name strings 3. a list of transcription factor name strings. """ if isinstance(expression_data, pd.DataFrame): expression_matrix = expression_data.as_matrix() gene_names = list(expression_data.columns) else: expression_matrix = expression_data assert expression_matrix.shape[1] == len(gene_names) if tf_names is None: tf_names = gene_names elif tf_names == 'all': tf_names = gene_names else: if len(tf_names) == 0: raise ValueError('Specified tf_names is empty') if not set(gene_names).intersection(set(tf_names)): raise ValueError('Intersection of gene_names and tf_names is empty.') return expression_matrix, gene_names, tf_names
tmoerman/arboreto
arboreto/algo.py
diy
python
def diy(expression_data, regressor_type, regressor_kwargs, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): if verbose: print('preparing dask client') client, shutdown_callback = _prepare_client(client_or_address) try: if verbose: print('parsing input') expression_matrix, gene_names, tf_names = _prepare_input(expression_data, gene_names, tf_names) if verbose: print('creating dask graph') graph = create_graph(expression_matrix, gene_names, tf_names, client=client, regressor_type=regressor_type, regressor_kwargs=regressor_kwargs, early_stop_window_length=early_stop_window_length, limit=limit, seed=seed) if verbose: print('{} partitions'.format(graph.npartitions)) print('computing dask graph') return client \ .compute(graph, sync=True) \ .sort_values(by='importance', ascending=False) finally: shutdown_callback(verbose) if verbose: print('finished')
:param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param regressor_type: string. One of: 'RF', 'GBM', 'ET'. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param early_stop_window_length: early stopping window length. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default 666. Use None for random seed. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/algo.py#L76-L142
[ "def create_graph(expression_matrix,\n gene_names,\n tf_names,\n regressor_type,\n regressor_kwargs,\n client,\n target_genes='all',\n limit=None,\n include_meta=False,\n early_stop_window_length=EARLY_STOP_WINDOW_LENGTH,\n repartition_multiplier=1,\n seed=DEMON_SEED):\n \"\"\"\n Main API function. Create a Dask computation graph.\n\n Note: fixing the GC problems was fixed by 2 changes: [1] and [2] !!!\n\n :param expression_matrix: numpy matrix. Rows are observations and columns are genes.\n :param gene_names: list of gene names. Each entry corresponds to the expression_matrix column with same index.\n :param tf_names: list of transcription factor names. Should have a non-empty intersection with gene_names.\n :param regressor_type: regressor type. Case insensitive.\n :param regressor_kwargs: dict of key-value pairs that configures the regressor.\n :param client: a dask.distributed client instance.\n * Used to scatter-broadcast the tf matrix to the workers instead of simply wrapping in a delayed().\n :param target_genes: either int, 'all' or a collection that is a subset of gene_names.\n :param limit: optional number of top regulatory links to return. Default None.\n :param include_meta: Also return the meta DataFrame. Default False.\n :param early_stop_window_length: window length of the early stopping monitor.\n :param repartition_multiplier: multiplier\n :param seed: (optional) random seed for the regressors. Default 666.\n :return: if include_meta is False, returns a Dask graph that computes the links DataFrame.\n If include_meta is True, returns a tuple: the links DataFrame and the meta DataFrame.\n \"\"\"\n\n assert expression_matrix.shape[1] == len(gene_names)\n assert client, \"client is required\"\n\n tf_matrix, tf_matrix_gene_names = to_tf_matrix(expression_matrix, gene_names, tf_names)\n\n future_tf_matrix = client.scatter(tf_matrix, broadcast=True)\n # [1] wrap in a list of 1 -> unsure why but Matt. Rocklin does this often...\n [future_tf_matrix_gene_names] = client.scatter([tf_matrix_gene_names], broadcast=True)\n\n delayed_link_dfs = [] # collection of delayed link DataFrames\n delayed_meta_dfs = [] # collection of delayed meta DataFrame\n\n for target_gene_index in target_gene_indices(gene_names, target_genes):\n target_gene_name = delayed(gene_names[target_gene_index], pure=True)\n target_gene_expression = delayed(expression_matrix[:, target_gene_index], pure=True)\n\n if include_meta:\n delayed_link_df, delayed_meta_df = delayed(infer_partial_network, pure=True, nout=2)(\n regressor_type, regressor_kwargs,\n future_tf_matrix, future_tf_matrix_gene_names,\n target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed)\n\n if delayed_link_df is not None:\n delayed_link_dfs.append(delayed_link_df)\n delayed_meta_dfs.append(delayed_meta_df)\n else:\n delayed_link_df = delayed(infer_partial_network, pure=True)(\n regressor_type, regressor_kwargs,\n future_tf_matrix, future_tf_matrix_gene_names,\n target_gene_name, target_gene_expression, include_meta, early_stop_window_length, seed)\n\n if delayed_link_df is not None:\n delayed_link_dfs.append(delayed_link_df)\n\n # gather the DataFrames into one distributed DataFrame\n all_links_df = from_delayed(delayed_link_dfs, meta=_GRN_SCHEMA)\n all_meta_df = from_delayed(delayed_meta_dfs, meta=_META_SCHEMA)\n\n # optionally limit the number of resulting regulatory links, descending by top importance\n if limit:\n maybe_limited_links_df = all_links_df.nlargest(limit, columns=['importance'])\n else:\n maybe_limited_links_df = all_links_df\n\n # [2] repartition to nr of workers -> important to avoid GC problems!\n # see: http://dask.pydata.org/en/latest/dataframe-performance.html#repartition-to-reduce-overhead\n n_parts = len(client.ncores()) * repartition_multiplier\n\n if include_meta:\n return maybe_limited_links_df.repartition(npartitions=n_parts), \\\n all_meta_df.repartition(npartitions=n_parts)\n else:\n return maybe_limited_links_df.repartition(npartitions=n_parts)\n", "def _prepare_client(client_or_address):\n \"\"\"\n :param client_or_address: one of:\n * None\n * verbatim: 'local'\n * string address\n * a Client instance\n :return: a tuple: (Client instance, shutdown callback function).\n :raises: ValueError if no valid client input was provided.\n \"\"\"\n\n if client_or_address is None or str(client_or_address).lower() == 'local':\n local_cluster = LocalCluster(diagnostics_port=None)\n client = Client(local_cluster)\n\n def close_client_and_local_cluster(verbose=False):\n if verbose:\n print('shutting down client and local cluster')\n\n client.close()\n local_cluster.close()\n\n return client, close_client_and_local_cluster\n\n elif isinstance(client_or_address, str) and client_or_address.lower() != 'local':\n client = Client(client_or_address)\n\n def close_client(verbose=False):\n if verbose:\n print('shutting down client')\n\n client.close()\n\n return client, close_client\n\n elif isinstance(client_or_address, Client):\n\n def close_dummy(verbose=False):\n if verbose:\n print('not shutting down client, client was created externally')\n\n return None\n\n return client_or_address, close_dummy\n\n else:\n raise ValueError(\"Invalid client specified {}\".format(str(client_or_address)))\n", "def _prepare_input(expression_data,\n gene_names,\n tf_names):\n \"\"\"\n Wrangle the inputs into the correct formats.\n\n :param expression_data: one of:\n * a pandas DataFrame (rows=observations, columns=genes)\n * a dense 2D numpy.ndarray\n * a sparse scipy.sparse.csc_matrix\n :param gene_names: optional list of gene names (strings).\n Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame.\n :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used.\n :return: a triple of:\n 1. a np.ndarray or scipy.sparse.csc_matrix\n 2. a list of gene name strings\n 3. a list of transcription factor name strings.\n \"\"\"\n\n if isinstance(expression_data, pd.DataFrame):\n expression_matrix = expression_data.as_matrix()\n gene_names = list(expression_data.columns)\n else:\n expression_matrix = expression_data\n assert expression_matrix.shape[1] == len(gene_names)\n\n if tf_names is None:\n tf_names = gene_names\n elif tf_names == 'all':\n tf_names = gene_names\n else:\n if len(tf_names) == 0:\n raise ValueError('Specified tf_names is empty')\n\n if not set(gene_names).intersection(set(tf_names)):\n raise ValueError('Intersection of gene_names and tf_names is empty.')\n\n return expression_matrix, gene_names, tf_names\n", "def close_client_and_local_cluster(verbose=False):\n if verbose:\n print('shutting down client and local cluster')\n\n client.close()\n local_cluster.close()\n" ]
""" Top-level functions. """ import pandas as pd from distributed import Client, LocalCluster from arboreto.core import create_graph, SGBM_KWARGS, RF_KWARGS, EARLY_STOP_WINDOW_LENGTH def grnboost2(expression_data, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): """ Launch arboreto with [GRNBoost2] profile. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param early_stop_window_length: early stop window length. Default 25. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default None. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links. """ return diy(expression_data=expression_data, regressor_type='GBM', regressor_kwargs=SGBM_KWARGS, gene_names=gene_names, tf_names=tf_names, client_or_address=client_or_address, early_stop_window_length=early_stop_window_length, limit=limit, seed=seed, verbose=verbose) def genie3(expression_data, gene_names=None, tf_names='all', client_or_address='local', limit=None, seed=None, verbose=False): """ Launch arboreto with [GENIE3] profile. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default None. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links. """ return diy(expression_data=expression_data, regressor_type='RF', regressor_kwargs=RF_KWARGS, gene_names=gene_names, tf_names=tf_names, client_or_address=client_or_address, limit=limit, seed=seed, verbose=verbose) def _prepare_client(client_or_address): """ :param client_or_address: one of: * None * verbatim: 'local' * string address * a Client instance :return: a tuple: (Client instance, shutdown callback function). :raises: ValueError if no valid client input was provided. """ if client_or_address is None or str(client_or_address).lower() == 'local': local_cluster = LocalCluster(diagnostics_port=None) client = Client(local_cluster) def close_client_and_local_cluster(verbose=False): if verbose: print('shutting down client and local cluster') client.close() local_cluster.close() return client, close_client_and_local_cluster elif isinstance(client_or_address, str) and client_or_address.lower() != 'local': client = Client(client_or_address) def close_client(verbose=False): if verbose: print('shutting down client') client.close() return client, close_client elif isinstance(client_or_address, Client): def close_dummy(verbose=False): if verbose: print('not shutting down client, client was created externally') return None return client_or_address, close_dummy else: raise ValueError("Invalid client specified {}".format(str(client_or_address))) def _prepare_input(expression_data, gene_names, tf_names): """ Wrangle the inputs into the correct formats. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :return: a triple of: 1. a np.ndarray or scipy.sparse.csc_matrix 2. a list of gene name strings 3. a list of transcription factor name strings. """ if isinstance(expression_data, pd.DataFrame): expression_matrix = expression_data.as_matrix() gene_names = list(expression_data.columns) else: expression_matrix = expression_data assert expression_matrix.shape[1] == len(gene_names) if tf_names is None: tf_names = gene_names elif tf_names == 'all': tf_names = gene_names else: if len(tf_names) == 0: raise ValueError('Specified tf_names is empty') if not set(gene_names).intersection(set(tf_names)): raise ValueError('Intersection of gene_names and tf_names is empty.') return expression_matrix, gene_names, tf_names
tmoerman/arboreto
arboreto/algo.py
_prepare_client
python
def _prepare_client(client_or_address): if client_or_address is None or str(client_or_address).lower() == 'local': local_cluster = LocalCluster(diagnostics_port=None) client = Client(local_cluster) def close_client_and_local_cluster(verbose=False): if verbose: print('shutting down client and local cluster') client.close() local_cluster.close() return client, close_client_and_local_cluster elif isinstance(client_or_address, str) and client_or_address.lower() != 'local': client = Client(client_or_address) def close_client(verbose=False): if verbose: print('shutting down client') client.close() return client, close_client elif isinstance(client_or_address, Client): def close_dummy(verbose=False): if verbose: print('not shutting down client, client was created externally') return None return client_or_address, close_dummy else: raise ValueError("Invalid client specified {}".format(str(client_or_address)))
:param client_or_address: one of: * None * verbatim: 'local' * string address * a Client instance :return: a tuple: (Client instance, shutdown callback function). :raises: ValueError if no valid client input was provided.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/algo.py#L145-L191
null
""" Top-level functions. """ import pandas as pd from distributed import Client, LocalCluster from arboreto.core import create_graph, SGBM_KWARGS, RF_KWARGS, EARLY_STOP_WINDOW_LENGTH def grnboost2(expression_data, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): """ Launch arboreto with [GRNBoost2] profile. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param early_stop_window_length: early stop window length. Default 25. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default None. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links. """ return diy(expression_data=expression_data, regressor_type='GBM', regressor_kwargs=SGBM_KWARGS, gene_names=gene_names, tf_names=tf_names, client_or_address=client_or_address, early_stop_window_length=early_stop_window_length, limit=limit, seed=seed, verbose=verbose) def genie3(expression_data, gene_names=None, tf_names='all', client_or_address='local', limit=None, seed=None, verbose=False): """ Launch arboreto with [GENIE3] profile. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default None. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links. """ return diy(expression_data=expression_data, regressor_type='RF', regressor_kwargs=RF_KWARGS, gene_names=gene_names, tf_names=tf_names, client_or_address=client_or_address, limit=limit, seed=seed, verbose=verbose) def diy(expression_data, regressor_type, regressor_kwargs, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): """ :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param regressor_type: string. One of: 'RF', 'GBM', 'ET'. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param early_stop_window_length: early stopping window length. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default 666. Use None for random seed. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links. """ if verbose: print('preparing dask client') client, shutdown_callback = _prepare_client(client_or_address) try: if verbose: print('parsing input') expression_matrix, gene_names, tf_names = _prepare_input(expression_data, gene_names, tf_names) if verbose: print('creating dask graph') graph = create_graph(expression_matrix, gene_names, tf_names, client=client, regressor_type=regressor_type, regressor_kwargs=regressor_kwargs, early_stop_window_length=early_stop_window_length, limit=limit, seed=seed) if verbose: print('{} partitions'.format(graph.npartitions)) print('computing dask graph') return client \ .compute(graph, sync=True) \ .sort_values(by='importance', ascending=False) finally: shutdown_callback(verbose) if verbose: print('finished') def _prepare_input(expression_data, gene_names, tf_names): """ Wrangle the inputs into the correct formats. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :return: a triple of: 1. a np.ndarray or scipy.sparse.csc_matrix 2. a list of gene name strings 3. a list of transcription factor name strings. """ if isinstance(expression_data, pd.DataFrame): expression_matrix = expression_data.as_matrix() gene_names = list(expression_data.columns) else: expression_matrix = expression_data assert expression_matrix.shape[1] == len(gene_names) if tf_names is None: tf_names = gene_names elif tf_names == 'all': tf_names = gene_names else: if len(tf_names) == 0: raise ValueError('Specified tf_names is empty') if not set(gene_names).intersection(set(tf_names)): raise ValueError('Intersection of gene_names and tf_names is empty.') return expression_matrix, gene_names, tf_names
tmoerman/arboreto
arboreto/algo.py
_prepare_input
python
def _prepare_input(expression_data, gene_names, tf_names): if isinstance(expression_data, pd.DataFrame): expression_matrix = expression_data.as_matrix() gene_names = list(expression_data.columns) else: expression_matrix = expression_data assert expression_matrix.shape[1] == len(gene_names) if tf_names is None: tf_names = gene_names elif tf_names == 'all': tf_names = gene_names else: if len(tf_names) == 0: raise ValueError('Specified tf_names is empty') if not set(gene_names).intersection(set(tf_names)): raise ValueError('Intersection of gene_names and tf_names is empty.') return expression_matrix, gene_names, tf_names
Wrangle the inputs into the correct formats. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :return: a triple of: 1. a np.ndarray or scipy.sparse.csc_matrix 2. a list of gene name strings 3. a list of transcription factor name strings.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/algo.py#L194-L231
null
""" Top-level functions. """ import pandas as pd from distributed import Client, LocalCluster from arboreto.core import create_graph, SGBM_KWARGS, RF_KWARGS, EARLY_STOP_WINDOW_LENGTH def grnboost2(expression_data, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): """ Launch arboreto with [GRNBoost2] profile. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param early_stop_window_length: early stop window length. Default 25. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default None. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links. """ return diy(expression_data=expression_data, regressor_type='GBM', regressor_kwargs=SGBM_KWARGS, gene_names=gene_names, tf_names=tf_names, client_or_address=client_or_address, early_stop_window_length=early_stop_window_length, limit=limit, seed=seed, verbose=verbose) def genie3(expression_data, gene_names=None, tf_names='all', client_or_address='local', limit=None, seed=None, verbose=False): """ Launch arboreto with [GENIE3] profile. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default None. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links. """ return diy(expression_data=expression_data, regressor_type='RF', regressor_kwargs=RF_KWARGS, gene_names=gene_names, tf_names=tf_names, client_or_address=client_or_address, limit=limit, seed=seed, verbose=verbose) def diy(expression_data, regressor_type, regressor_kwargs, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): """ :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param regressor_type: string. One of: 'RF', 'GBM', 'ET'. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param gene_names: optional list of gene names (strings). Required when a (dense or sparse) matrix is passed as 'expression_data' instead of a DataFrame. :param tf_names: optional list of transcription factors. If None or 'all', the list of gene_names will be used. :param early_stop_window_length: early stopping window length. :param client_or_address: one of: * None or 'local': a new Client(LocalCluster()) will be used to perform the computation. * string address: a new Client(address) will be used to perform the computation. * a Client instance: the specified Client instance will be used to perform the computation. :param limit: optional number (int) of top regulatory links to return. Default None. :param seed: optional random seed for the regressors. Default 666. Use None for random seed. :param verbose: print info. :return: a pandas DataFrame['TF', 'target', 'importance'] representing the inferred gene regulatory links. """ if verbose: print('preparing dask client') client, shutdown_callback = _prepare_client(client_or_address) try: if verbose: print('parsing input') expression_matrix, gene_names, tf_names = _prepare_input(expression_data, gene_names, tf_names) if verbose: print('creating dask graph') graph = create_graph(expression_matrix, gene_names, tf_names, client=client, regressor_type=regressor_type, regressor_kwargs=regressor_kwargs, early_stop_window_length=early_stop_window_length, limit=limit, seed=seed) if verbose: print('{} partitions'.format(graph.npartitions)) print('computing dask graph') return client \ .compute(graph, sync=True) \ .sort_values(by='importance', ascending=False) finally: shutdown_callback(verbose) if verbose: print('finished') def _prepare_client(client_or_address): """ :param client_or_address: one of: * None * verbatim: 'local' * string address * a Client instance :return: a tuple: (Client instance, shutdown callback function). :raises: ValueError if no valid client input was provided. """ if client_or_address is None or str(client_or_address).lower() == 'local': local_cluster = LocalCluster(diagnostics_port=None) client = Client(local_cluster) def close_client_and_local_cluster(verbose=False): if verbose: print('shutting down client and local cluster') client.close() local_cluster.close() return client, close_client_and_local_cluster elif isinstance(client_or_address, str) and client_or_address.lower() != 'local': client = Client(client_or_address) def close_client(verbose=False): if verbose: print('shutting down client') client.close() return client, close_client elif isinstance(client_or_address, Client): def close_dummy(verbose=False): if verbose: print('not shutting down client, client was created externally') return None return client_or_address, close_dummy else: raise ValueError("Invalid client specified {}".format(str(client_or_address)))
tmoerman/arboreto
arboreto/utils.py
load_tf_names
python
def load_tf_names(path): with open(path) as file: tfs_in_file = [line.strip() for line in file.readlines()] return tfs_in_file
:param path: the path of the transcription factor list file. :return: a list of transcription factor names read from the file.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/utils.py#L6-L15
null
""" Utility functions. """
TadLeonard/tfatool
tfatool/sync.py
up_down_by_arrival
python
def up_down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): local_monitor = watch_local_files(*filters, local_dir=local_dir) remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, lfile_set = next(local_monitor) _, rfile_set = next(remote_monitor) _notify_sync_ready(len(lfile_set), local_dir, remote_dir) _notify_sync_ready(len(rfile_set), remote_dir, local_dir) processed = set() for new_local, new_remote in zip(local_monitor, remote_monitor): new_local, local_set = new_local local_arrivals = {f for f in new_local if f.filename not in processed} yield Direction.up, local_arrivals if local_arrivals: new_names.update(f.filename for f in local_arrivals) _notify_sync(Direction.up, local_arrivals) up_by_files(local_arrivals, remote_dir) _notify_sync_ready(len(local_set), local_dir, remote_dir) new_remote, remote_set = new_remote remote_arrivals = {f for f in new_remote if f.filename not in processed} yield Direction.down, remote_arrivals if remote_arrivals: new_names.update(f.filename for f in remote_arrivals) _notify_sync(Direction.down, remote_arrivals) yield Direction.down, remote_arrivals down_by_files(remote_arrivals, local_dir) _notify_sync_ready(len(remote_set), remote_dir, local_dir)
Monitors a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The generator yields before each upload or download actually takes place.
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L83-L115
[ "def watch_local_files(*filters, local_dir=\".\"):\n list_local = partial(list_local_files, *filters, local_dir=local_dir)\n old_files = new_files = set(list_local())\n while True:\n yield new_files - old_files, new_files\n old_files = new_files\n new_files = set(list_local())\n", "def watch_remote_files(*filters, remote_dir=\".\"):\n command.memory_changed() # clear change status to start\n list_remote = partial(command.list_files,\n *filters, remote_dir=remote_dir)\n old_files = new_files = set(list_remote())\n while True:\n yield new_files - old_files, new_files\n old_files = new_files\n if command.memory_changed():\n new_files = set(list_remote())\n", "def _notify_sync_ready(num_old_files, from_dir, to_dir):\n logger.info(\"Ready to sync new files from {} to {} \"\n \"({:d} existing files ignored)\".format(\n from_dir, to_dir, num_old_files))\n", "def _notify_sync(direction, files):\n logger.info(\"{:d} files to {:s}:\\n{}\".format(\n len(files), direction,\n \"\\n\".join(\" \" + f.filename for f in files)))\n", "def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None):\n \"\"\"Sync a given list of local files to `remote_dir` dir\"\"\"\n if remote_files is None:\n remote_files = command.map_files_raw(remote_dir=remote_dir)\n for local_file in to_sync:\n _sync_local_file(local_file, remote_dir, remote_files)\n", "def down_by_files(to_sync, local_dir=\".\"):\n \"\"\"Sync a given list of files from `command.list_files` to `local_dir` dir\"\"\"\n for f in to_sync:\n _sync_remote_file(local_dir, f)\n" ]
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFileInfo logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Python 3.4 compatibility via scandir backport if hasattr(os, "scandir"): scandir = os.scandir else: import scandir scandir = scandir.scandir class Direction(str, Enum): up = "upload" # upload direction down = "download" # download direction ##################################### # Synchronizing newly created files class Monitor: """Synchronizes newly created files TO or FROM FlashAir in separate threads""" def __init__(self, *filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): self._filters = filters self._local_dir = local_dir self._remote_dir = remote_dir self.running = threading.Event() self.thread = None def _run(self, method): assert self.thread is None self.running.set() self.thread = threading.Thread(target=self._run_sync, args=(method,)) self.thread.start() def _run_sync(self, method): files = method(*self._filters, local_dir=self._local_dir, remote_dir=self._remote_dir) while self.running.is_set(): _, new = next(files) if not new: time.sleep(0.3) def sync_both(self): self._run(up_down_by_arrival) def sync_up(self): self._run(up_by_arrival) def sync_down(self): self._run(down_by_arrival) def stop(self): self.running.clear() def join(self): if self.thread: self.thread.join() self.thread = None def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) _, file_set = next(local_monitor) _notify_sync_ready(len(file_set), local_dir, remote_dir) for new_arrivals, file_set in local_monitor: yield Direction.up, new_arrivals # where new_arrivals is possibly empty if new_arrivals: _notify_sync(Direction.up, new_arrivals) up_by_files(new_arrivals, remote_dir) _notify_sync_ready(len(file_set), local_dir, remote_dir) def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place.""" remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, file_set = next(remote_monitor) _notify_sync_ready(len(file_set), remote_dir, local_dir) for new_arrivals, file_set in remote_monitor: if new_arrivals: _notify_sync(Direction.down, new_arrivals) down_by_files(new_arrivals, local_dir) _notify_sync_ready(len(file_set), remote_dir, local_dir) yield Direction.down, new_arrivals ################################################### # Sync ONCE in the DOWN (from FlashAir) direction def down_by_all(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", **_): files = command.list_files(*filters, remote_dir=remote_dir) down_by_files(files, local_dir=local_dir) def down_by_files(to_sync, local_dir="."): """Sync a given list of files from `command.list_files` to `local_dir` dir""" for f in to_sync: _sync_remote_file(local_dir, f) def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync most recent file by date, time attribues""" files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync files whose filename attribute is highest in alphanumeric order""" files = command.list_files(*filters, remote_dir=remote_dir) greatest = sorted(files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def _sync_remote_file(local_dir, remote_file_info): local = Path(local_dir, remote_file_info.filename) local_name = str(local) remote_size = remote_file_info.size if local.exists(): local_size = local.stat().st_size if local.stat().st_size == remote_size: logger.info( "Skipping '{}': already exists locally".format( local_name)) else: logger.warning( "Removing {}: local size {} != remote size {}".format( local_name, local_size, remote_size)) os.remove(local_name) _stream_to_file(local_name, remote_file_info) else: _stream_to_file(local_name, remote_file_info) def _stream_to_file(local_name, fileinfo): logger.info("Copying remote file {} to {}".format( fileinfo.path, local_name)) streaming_file = _get_file(fileinfo) _write_file_safely(local_name, fileinfo, streaming_file) def _get_file(fileinfo): url = urljoin(URL, fileinfo.path) logger.info("Requesting file: {}".format(url)) return requests.get(url, stream=True) def _write_file_safely(local_path, fileinfo, response): """attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error""" try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e def _write_file(local_path, fileinfo, response): start = time.time() pbar_size = fileinfo.size / (5 * 10**5) pbar = tqdm.tqdm(total=int(pbar_size)) if response.status_code == 200: with open(local_path, "wb") as outfile: for chunk in response.iter_content(5*10**5): progress = len(chunk) / (5 * 10**5) _update_pbar(pbar, progress) outfile.write(chunk) else: raise requests.RequestException("Expected status code 200") pbar.close() duration = time.time() - start logger.info("Wrote {} in {:0.2f} s ({:0.2f} MB, {:0.2f} MB/s)".format( fileinfo.filename, duration, fileinfo.size / 10 ** 6, fileinfo.size / (duration * 10 ** 6))) def _update_pbar(pbar, val): update_val = max(int(val), 1) try: pbar.update(update_val) except Exception as e: # oh, c'mon TQDM, progress bars shouldn't crash software logger.debug("TQDM progress bar error: {}({})".format( e.__class__.__name__, e)) ########################################### # Local and remote file watcher-generators def watch_local_files(*filters, local_dir="."): list_local = partial(list_local_files, *filters, local_dir=local_dir) old_files = new_files = set(list_local()) while True: yield new_files - old_files, new_files old_files = new_files new_files = set(list_local()) def watch_remote_files(*filters, remote_dir="."): command.memory_changed() # clear change status to start list_remote = partial(command.list_files, *filters, remote_dir=remote_dir) old_files = new_files = set(list_remote()) while True: yield new_files - old_files, new_files old_files = new_files if command.memory_changed(): new_files = set(list_remote()) ##################################################### # Synchronize ONCE in the UP direction (to FlashAir) def up_by_all(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, **_): files = list_local_files(*filters, local_dir=local_dir) up_by_files(list(files), remote_dir=remote_dir) def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): """Sync a given list of local files to `remote_dir` dir""" if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files) def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync most recent file by date, time attribues""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync files whose filename attribute is highest in alphanumeric order""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def _sync_local_file(local_file_info, remote_dir, remote_files): local_name = local_file_info.filename local_size = local_file_info.size if local_name in remote_files: remote_file_info = remote_files[local_name] remote_size = remote_file_info.size if local_size == remote_size: logger.info( "Skipping '{}' already exists on SD card".format( local_name)) else: logger.warning( "Removing remote file {}: " "local size {} != remote size {}".format( local_name, local_size, remote_size)) upload.delete_file(remote_file_info.path) _stream_from_file(local_file_info, remote_dir) else: _stream_from_file(local_file_info, remote_dir) def _stream_from_file(fileinfo, remote_dir): logger.info("Uploading local file {} to {}".format( fileinfo.path, remote_dir)) _upload_file_safely(fileinfo, remote_dir) def _upload_file_safely(fileinfo, remote_dir): """attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error""" try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fileinfo.path) raise e def list_local_files(*filters, local_dir="."): all_entries = scandir(local_dir) file_entries = (e for e in all_entries if e.is_file()) for entry in file_entries: stat = entry.stat() size = stat.st_size datetime = arrow.get(stat.st_mtime) path = str(Path(local_dir, entry.name)) info = SimpleFileInfo(local_dir, entry.name, path, size, datetime) if all(filt(info) for filt in filters): yield info def list_local_files_raw(*filters, local_dir="."): all_entries = scandir(local_dir) all_files = (e for e in all_entries if e.is_file() and all(filt(e) for filt in filters)) for entry in all_files: path = str(Path(local_dir, entry.name)) yield RawFileInfo(local_dir, entry.name, path, entry.stat().st_size) def _notify_sync(direction, files): logger.info("{:d} files to {:s}:\n{}".format( len(files), direction, "\n".join(" " + f.filename for f in files))) def _notify_sync_ready(num_old_files, from_dir, to_dir): logger.info("Ready to sync new files from {} to {} " "({:d} existing files ignored)".format( from_dir, to_dir, num_old_files))
TadLeonard/tfatool
tfatool/sync.py
up_by_arrival
python
def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): local_monitor = watch_local_files(*filters, local_dir=local_dir) _, file_set = next(local_monitor) _notify_sync_ready(len(file_set), local_dir, remote_dir) for new_arrivals, file_set in local_monitor: yield Direction.up, new_arrivals # where new_arrivals is possibly empty if new_arrivals: _notify_sync(Direction.up, new_arrivals) up_by_files(new_arrivals, remote_dir) _notify_sync_ready(len(file_set), local_dir, remote_dir)
Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L118-L131
[ "def watch_local_files(*filters, local_dir=\".\"):\n list_local = partial(list_local_files, *filters, local_dir=local_dir)\n old_files = new_files = set(list_local())\n while True:\n yield new_files - old_files, new_files\n old_files = new_files\n new_files = set(list_local())\n", "def _notify_sync_ready(num_old_files, from_dir, to_dir):\n logger.info(\"Ready to sync new files from {} to {} \"\n \"({:d} existing files ignored)\".format(\n from_dir, to_dir, num_old_files))\n" ]
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFileInfo logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Python 3.4 compatibility via scandir backport if hasattr(os, "scandir"): scandir = os.scandir else: import scandir scandir = scandir.scandir class Direction(str, Enum): up = "upload" # upload direction down = "download" # download direction ##################################### # Synchronizing newly created files class Monitor: """Synchronizes newly created files TO or FROM FlashAir in separate threads""" def __init__(self, *filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): self._filters = filters self._local_dir = local_dir self._remote_dir = remote_dir self.running = threading.Event() self.thread = None def _run(self, method): assert self.thread is None self.running.set() self.thread = threading.Thread(target=self._run_sync, args=(method,)) self.thread.start() def _run_sync(self, method): files = method(*self._filters, local_dir=self._local_dir, remote_dir=self._remote_dir) while self.running.is_set(): _, new = next(files) if not new: time.sleep(0.3) def sync_both(self): self._run(up_down_by_arrival) def sync_up(self): self._run(up_by_arrival) def sync_down(self): self._run(down_by_arrival) def stop(self): self.running.clear() def join(self): if self.thread: self.thread.join() self.thread = None def up_down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The generator yields before each upload or download actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, lfile_set = next(local_monitor) _, rfile_set = next(remote_monitor) _notify_sync_ready(len(lfile_set), local_dir, remote_dir) _notify_sync_ready(len(rfile_set), remote_dir, local_dir) processed = set() for new_local, new_remote in zip(local_monitor, remote_monitor): new_local, local_set = new_local local_arrivals = {f for f in new_local if f.filename not in processed} yield Direction.up, local_arrivals if local_arrivals: new_names.update(f.filename for f in local_arrivals) _notify_sync(Direction.up, local_arrivals) up_by_files(local_arrivals, remote_dir) _notify_sync_ready(len(local_set), local_dir, remote_dir) new_remote, remote_set = new_remote remote_arrivals = {f for f in new_remote if f.filename not in processed} yield Direction.down, remote_arrivals if remote_arrivals: new_names.update(f.filename for f in remote_arrivals) _notify_sync(Direction.down, remote_arrivals) yield Direction.down, remote_arrivals down_by_files(remote_arrivals, local_dir) _notify_sync_ready(len(remote_set), remote_dir, local_dir) def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place.""" remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, file_set = next(remote_monitor) _notify_sync_ready(len(file_set), remote_dir, local_dir) for new_arrivals, file_set in remote_monitor: if new_arrivals: _notify_sync(Direction.down, new_arrivals) down_by_files(new_arrivals, local_dir) _notify_sync_ready(len(file_set), remote_dir, local_dir) yield Direction.down, new_arrivals ################################################### # Sync ONCE in the DOWN (from FlashAir) direction def down_by_all(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", **_): files = command.list_files(*filters, remote_dir=remote_dir) down_by_files(files, local_dir=local_dir) def down_by_files(to_sync, local_dir="."): """Sync a given list of files from `command.list_files` to `local_dir` dir""" for f in to_sync: _sync_remote_file(local_dir, f) def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync most recent file by date, time attribues""" files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync files whose filename attribute is highest in alphanumeric order""" files = command.list_files(*filters, remote_dir=remote_dir) greatest = sorted(files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def _sync_remote_file(local_dir, remote_file_info): local = Path(local_dir, remote_file_info.filename) local_name = str(local) remote_size = remote_file_info.size if local.exists(): local_size = local.stat().st_size if local.stat().st_size == remote_size: logger.info( "Skipping '{}': already exists locally".format( local_name)) else: logger.warning( "Removing {}: local size {} != remote size {}".format( local_name, local_size, remote_size)) os.remove(local_name) _stream_to_file(local_name, remote_file_info) else: _stream_to_file(local_name, remote_file_info) def _stream_to_file(local_name, fileinfo): logger.info("Copying remote file {} to {}".format( fileinfo.path, local_name)) streaming_file = _get_file(fileinfo) _write_file_safely(local_name, fileinfo, streaming_file) def _get_file(fileinfo): url = urljoin(URL, fileinfo.path) logger.info("Requesting file: {}".format(url)) return requests.get(url, stream=True) def _write_file_safely(local_path, fileinfo, response): """attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error""" try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e def _write_file(local_path, fileinfo, response): start = time.time() pbar_size = fileinfo.size / (5 * 10**5) pbar = tqdm.tqdm(total=int(pbar_size)) if response.status_code == 200: with open(local_path, "wb") as outfile: for chunk in response.iter_content(5*10**5): progress = len(chunk) / (5 * 10**5) _update_pbar(pbar, progress) outfile.write(chunk) else: raise requests.RequestException("Expected status code 200") pbar.close() duration = time.time() - start logger.info("Wrote {} in {:0.2f} s ({:0.2f} MB, {:0.2f} MB/s)".format( fileinfo.filename, duration, fileinfo.size / 10 ** 6, fileinfo.size / (duration * 10 ** 6))) def _update_pbar(pbar, val): update_val = max(int(val), 1) try: pbar.update(update_val) except Exception as e: # oh, c'mon TQDM, progress bars shouldn't crash software logger.debug("TQDM progress bar error: {}({})".format( e.__class__.__name__, e)) ########################################### # Local and remote file watcher-generators def watch_local_files(*filters, local_dir="."): list_local = partial(list_local_files, *filters, local_dir=local_dir) old_files = new_files = set(list_local()) while True: yield new_files - old_files, new_files old_files = new_files new_files = set(list_local()) def watch_remote_files(*filters, remote_dir="."): command.memory_changed() # clear change status to start list_remote = partial(command.list_files, *filters, remote_dir=remote_dir) old_files = new_files = set(list_remote()) while True: yield new_files - old_files, new_files old_files = new_files if command.memory_changed(): new_files = set(list_remote()) ##################################################### # Synchronize ONCE in the UP direction (to FlashAir) def up_by_all(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, **_): files = list_local_files(*filters, local_dir=local_dir) up_by_files(list(files), remote_dir=remote_dir) def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): """Sync a given list of local files to `remote_dir` dir""" if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files) def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync most recent file by date, time attribues""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync files whose filename attribute is highest in alphanumeric order""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def _sync_local_file(local_file_info, remote_dir, remote_files): local_name = local_file_info.filename local_size = local_file_info.size if local_name in remote_files: remote_file_info = remote_files[local_name] remote_size = remote_file_info.size if local_size == remote_size: logger.info( "Skipping '{}' already exists on SD card".format( local_name)) else: logger.warning( "Removing remote file {}: " "local size {} != remote size {}".format( local_name, local_size, remote_size)) upload.delete_file(remote_file_info.path) _stream_from_file(local_file_info, remote_dir) else: _stream_from_file(local_file_info, remote_dir) def _stream_from_file(fileinfo, remote_dir): logger.info("Uploading local file {} to {}".format( fileinfo.path, remote_dir)) _upload_file_safely(fileinfo, remote_dir) def _upload_file_safely(fileinfo, remote_dir): """attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error""" try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fileinfo.path) raise e def list_local_files(*filters, local_dir="."): all_entries = scandir(local_dir) file_entries = (e for e in all_entries if e.is_file()) for entry in file_entries: stat = entry.stat() size = stat.st_size datetime = arrow.get(stat.st_mtime) path = str(Path(local_dir, entry.name)) info = SimpleFileInfo(local_dir, entry.name, path, size, datetime) if all(filt(info) for filt in filters): yield info def list_local_files_raw(*filters, local_dir="."): all_entries = scandir(local_dir) all_files = (e for e in all_entries if e.is_file() and all(filt(e) for filt in filters)) for entry in all_files: path = str(Path(local_dir, entry.name)) yield RawFileInfo(local_dir, entry.name, path, entry.stat().st_size) def _notify_sync(direction, files): logger.info("{:d} files to {:s}:\n{}".format( len(files), direction, "\n".join(" " + f.filename for f in files))) def _notify_sync_ready(num_old_files, from_dir, to_dir): logger.info("Ready to sync new files from {} to {} " "({:d} existing files ignored)".format( from_dir, to_dir, num_old_files))
TadLeonard/tfatool
tfatool/sync.py
down_by_arrival
python
def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, file_set = next(remote_monitor) _notify_sync_ready(len(file_set), remote_dir, local_dir) for new_arrivals, file_set in remote_monitor: if new_arrivals: _notify_sync(Direction.down, new_arrivals) down_by_files(new_arrivals, local_dir) _notify_sync_ready(len(file_set), remote_dir, local_dir) yield Direction.down, new_arrivals
Monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place.
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L134-L147
[ "def watch_remote_files(*filters, remote_dir=\".\"):\n command.memory_changed() # clear change status to start\n list_remote = partial(command.list_files,\n *filters, remote_dir=remote_dir)\n old_files = new_files = set(list_remote())\n while True:\n yield new_files - old_files, new_files\n old_files = new_files\n if command.memory_changed():\n new_files = set(list_remote())\n", "def _notify_sync_ready(num_old_files, from_dir, to_dir):\n logger.info(\"Ready to sync new files from {} to {} \"\n \"({:d} existing files ignored)\".format(\n from_dir, to_dir, num_old_files))\n" ]
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFileInfo logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Python 3.4 compatibility via scandir backport if hasattr(os, "scandir"): scandir = os.scandir else: import scandir scandir = scandir.scandir class Direction(str, Enum): up = "upload" # upload direction down = "download" # download direction ##################################### # Synchronizing newly created files class Monitor: """Synchronizes newly created files TO or FROM FlashAir in separate threads""" def __init__(self, *filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): self._filters = filters self._local_dir = local_dir self._remote_dir = remote_dir self.running = threading.Event() self.thread = None def _run(self, method): assert self.thread is None self.running.set() self.thread = threading.Thread(target=self._run_sync, args=(method,)) self.thread.start() def _run_sync(self, method): files = method(*self._filters, local_dir=self._local_dir, remote_dir=self._remote_dir) while self.running.is_set(): _, new = next(files) if not new: time.sleep(0.3) def sync_both(self): self._run(up_down_by_arrival) def sync_up(self): self._run(up_by_arrival) def sync_down(self): self._run(down_by_arrival) def stop(self): self.running.clear() def join(self): if self.thread: self.thread.join() self.thread = None def up_down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The generator yields before each upload or download actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, lfile_set = next(local_monitor) _, rfile_set = next(remote_monitor) _notify_sync_ready(len(lfile_set), local_dir, remote_dir) _notify_sync_ready(len(rfile_set), remote_dir, local_dir) processed = set() for new_local, new_remote in zip(local_monitor, remote_monitor): new_local, local_set = new_local local_arrivals = {f for f in new_local if f.filename not in processed} yield Direction.up, local_arrivals if local_arrivals: new_names.update(f.filename for f in local_arrivals) _notify_sync(Direction.up, local_arrivals) up_by_files(local_arrivals, remote_dir) _notify_sync_ready(len(local_set), local_dir, remote_dir) new_remote, remote_set = new_remote remote_arrivals = {f for f in new_remote if f.filename not in processed} yield Direction.down, remote_arrivals if remote_arrivals: new_names.update(f.filename for f in remote_arrivals) _notify_sync(Direction.down, remote_arrivals) yield Direction.down, remote_arrivals down_by_files(remote_arrivals, local_dir) _notify_sync_ready(len(remote_set), remote_dir, local_dir) def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) _, file_set = next(local_monitor) _notify_sync_ready(len(file_set), local_dir, remote_dir) for new_arrivals, file_set in local_monitor: yield Direction.up, new_arrivals # where new_arrivals is possibly empty if new_arrivals: _notify_sync(Direction.up, new_arrivals) up_by_files(new_arrivals, remote_dir) _notify_sync_ready(len(file_set), local_dir, remote_dir) ################################################### # Sync ONCE in the DOWN (from FlashAir) direction def down_by_all(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", **_): files = command.list_files(*filters, remote_dir=remote_dir) down_by_files(files, local_dir=local_dir) def down_by_files(to_sync, local_dir="."): """Sync a given list of files from `command.list_files` to `local_dir` dir""" for f in to_sync: _sync_remote_file(local_dir, f) def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync most recent file by date, time attribues""" files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync files whose filename attribute is highest in alphanumeric order""" files = command.list_files(*filters, remote_dir=remote_dir) greatest = sorted(files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def _sync_remote_file(local_dir, remote_file_info): local = Path(local_dir, remote_file_info.filename) local_name = str(local) remote_size = remote_file_info.size if local.exists(): local_size = local.stat().st_size if local.stat().st_size == remote_size: logger.info( "Skipping '{}': already exists locally".format( local_name)) else: logger.warning( "Removing {}: local size {} != remote size {}".format( local_name, local_size, remote_size)) os.remove(local_name) _stream_to_file(local_name, remote_file_info) else: _stream_to_file(local_name, remote_file_info) def _stream_to_file(local_name, fileinfo): logger.info("Copying remote file {} to {}".format( fileinfo.path, local_name)) streaming_file = _get_file(fileinfo) _write_file_safely(local_name, fileinfo, streaming_file) def _get_file(fileinfo): url = urljoin(URL, fileinfo.path) logger.info("Requesting file: {}".format(url)) return requests.get(url, stream=True) def _write_file_safely(local_path, fileinfo, response): """attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error""" try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e def _write_file(local_path, fileinfo, response): start = time.time() pbar_size = fileinfo.size / (5 * 10**5) pbar = tqdm.tqdm(total=int(pbar_size)) if response.status_code == 200: with open(local_path, "wb") as outfile: for chunk in response.iter_content(5*10**5): progress = len(chunk) / (5 * 10**5) _update_pbar(pbar, progress) outfile.write(chunk) else: raise requests.RequestException("Expected status code 200") pbar.close() duration = time.time() - start logger.info("Wrote {} in {:0.2f} s ({:0.2f} MB, {:0.2f} MB/s)".format( fileinfo.filename, duration, fileinfo.size / 10 ** 6, fileinfo.size / (duration * 10 ** 6))) def _update_pbar(pbar, val): update_val = max(int(val), 1) try: pbar.update(update_val) except Exception as e: # oh, c'mon TQDM, progress bars shouldn't crash software logger.debug("TQDM progress bar error: {}({})".format( e.__class__.__name__, e)) ########################################### # Local and remote file watcher-generators def watch_local_files(*filters, local_dir="."): list_local = partial(list_local_files, *filters, local_dir=local_dir) old_files = new_files = set(list_local()) while True: yield new_files - old_files, new_files old_files = new_files new_files = set(list_local()) def watch_remote_files(*filters, remote_dir="."): command.memory_changed() # clear change status to start list_remote = partial(command.list_files, *filters, remote_dir=remote_dir) old_files = new_files = set(list_remote()) while True: yield new_files - old_files, new_files old_files = new_files if command.memory_changed(): new_files = set(list_remote()) ##################################################### # Synchronize ONCE in the UP direction (to FlashAir) def up_by_all(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, **_): files = list_local_files(*filters, local_dir=local_dir) up_by_files(list(files), remote_dir=remote_dir) def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): """Sync a given list of local files to `remote_dir` dir""" if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files) def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync most recent file by date, time attribues""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync files whose filename attribute is highest in alphanumeric order""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def _sync_local_file(local_file_info, remote_dir, remote_files): local_name = local_file_info.filename local_size = local_file_info.size if local_name in remote_files: remote_file_info = remote_files[local_name] remote_size = remote_file_info.size if local_size == remote_size: logger.info( "Skipping '{}' already exists on SD card".format( local_name)) else: logger.warning( "Removing remote file {}: " "local size {} != remote size {}".format( local_name, local_size, remote_size)) upload.delete_file(remote_file_info.path) _stream_from_file(local_file_info, remote_dir) else: _stream_from_file(local_file_info, remote_dir) def _stream_from_file(fileinfo, remote_dir): logger.info("Uploading local file {} to {}".format( fileinfo.path, remote_dir)) _upload_file_safely(fileinfo, remote_dir) def _upload_file_safely(fileinfo, remote_dir): """attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error""" try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fileinfo.path) raise e def list_local_files(*filters, local_dir="."): all_entries = scandir(local_dir) file_entries = (e for e in all_entries if e.is_file()) for entry in file_entries: stat = entry.stat() size = stat.st_size datetime = arrow.get(stat.st_mtime) path = str(Path(local_dir, entry.name)) info = SimpleFileInfo(local_dir, entry.name, path, size, datetime) if all(filt(info) for filt in filters): yield info def list_local_files_raw(*filters, local_dir="."): all_entries = scandir(local_dir) all_files = (e for e in all_entries if e.is_file() and all(filt(e) for filt in filters)) for entry in all_files: path = str(Path(local_dir, entry.name)) yield RawFileInfo(local_dir, entry.name, path, entry.stat().st_size) def _notify_sync(direction, files): logger.info("{:d} files to {:s}:\n{}".format( len(files), direction, "\n".join(" " + f.filename for f in files))) def _notify_sync_ready(num_old_files, from_dir, to_dir): logger.info("Ready to sync new files from {} to {} " "({:d} existing files ignored)".format( from_dir, to_dir, num_old_files))
TadLeonard/tfatool
tfatool/sync.py
down_by_time
python
def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir)
Sync most recent file by date, time attribues
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L164-L170
[ "def _notify_sync(direction, files):\n logger.info(\"{:d} files to {:s}:\\n{}\".format(\n len(files), direction,\n \"\\n\".join(\" \" + f.filename for f in files)))\n", "def down_by_files(to_sync, local_dir=\".\"):\n \"\"\"Sync a given list of files from `command.list_files` to `local_dir` dir\"\"\"\n for f in to_sync:\n _sync_remote_file(local_dir, f)\n" ]
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFileInfo logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Python 3.4 compatibility via scandir backport if hasattr(os, "scandir"): scandir = os.scandir else: import scandir scandir = scandir.scandir class Direction(str, Enum): up = "upload" # upload direction down = "download" # download direction ##################################### # Synchronizing newly created files class Monitor: """Synchronizes newly created files TO or FROM FlashAir in separate threads""" def __init__(self, *filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): self._filters = filters self._local_dir = local_dir self._remote_dir = remote_dir self.running = threading.Event() self.thread = None def _run(self, method): assert self.thread is None self.running.set() self.thread = threading.Thread(target=self._run_sync, args=(method,)) self.thread.start() def _run_sync(self, method): files = method(*self._filters, local_dir=self._local_dir, remote_dir=self._remote_dir) while self.running.is_set(): _, new = next(files) if not new: time.sleep(0.3) def sync_both(self): self._run(up_down_by_arrival) def sync_up(self): self._run(up_by_arrival) def sync_down(self): self._run(down_by_arrival) def stop(self): self.running.clear() def join(self): if self.thread: self.thread.join() self.thread = None def up_down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The generator yields before each upload or download actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, lfile_set = next(local_monitor) _, rfile_set = next(remote_monitor) _notify_sync_ready(len(lfile_set), local_dir, remote_dir) _notify_sync_ready(len(rfile_set), remote_dir, local_dir) processed = set() for new_local, new_remote in zip(local_monitor, remote_monitor): new_local, local_set = new_local local_arrivals = {f for f in new_local if f.filename not in processed} yield Direction.up, local_arrivals if local_arrivals: new_names.update(f.filename for f in local_arrivals) _notify_sync(Direction.up, local_arrivals) up_by_files(local_arrivals, remote_dir) _notify_sync_ready(len(local_set), local_dir, remote_dir) new_remote, remote_set = new_remote remote_arrivals = {f for f in new_remote if f.filename not in processed} yield Direction.down, remote_arrivals if remote_arrivals: new_names.update(f.filename for f in remote_arrivals) _notify_sync(Direction.down, remote_arrivals) yield Direction.down, remote_arrivals down_by_files(remote_arrivals, local_dir) _notify_sync_ready(len(remote_set), remote_dir, local_dir) def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) _, file_set = next(local_monitor) _notify_sync_ready(len(file_set), local_dir, remote_dir) for new_arrivals, file_set in local_monitor: yield Direction.up, new_arrivals # where new_arrivals is possibly empty if new_arrivals: _notify_sync(Direction.up, new_arrivals) up_by_files(new_arrivals, remote_dir) _notify_sync_ready(len(file_set), local_dir, remote_dir) def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place.""" remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, file_set = next(remote_monitor) _notify_sync_ready(len(file_set), remote_dir, local_dir) for new_arrivals, file_set in remote_monitor: if new_arrivals: _notify_sync(Direction.down, new_arrivals) down_by_files(new_arrivals, local_dir) _notify_sync_ready(len(file_set), remote_dir, local_dir) yield Direction.down, new_arrivals ################################################### # Sync ONCE in the DOWN (from FlashAir) direction def down_by_all(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", **_): files = command.list_files(*filters, remote_dir=remote_dir) down_by_files(files, local_dir=local_dir) def down_by_files(to_sync, local_dir="."): """Sync a given list of files from `command.list_files` to `local_dir` dir""" for f in to_sync: _sync_remote_file(local_dir, f) def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync files whose filename attribute is highest in alphanumeric order""" files = command.list_files(*filters, remote_dir=remote_dir) greatest = sorted(files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def _sync_remote_file(local_dir, remote_file_info): local = Path(local_dir, remote_file_info.filename) local_name = str(local) remote_size = remote_file_info.size if local.exists(): local_size = local.stat().st_size if local.stat().st_size == remote_size: logger.info( "Skipping '{}': already exists locally".format( local_name)) else: logger.warning( "Removing {}: local size {} != remote size {}".format( local_name, local_size, remote_size)) os.remove(local_name) _stream_to_file(local_name, remote_file_info) else: _stream_to_file(local_name, remote_file_info) def _stream_to_file(local_name, fileinfo): logger.info("Copying remote file {} to {}".format( fileinfo.path, local_name)) streaming_file = _get_file(fileinfo) _write_file_safely(local_name, fileinfo, streaming_file) def _get_file(fileinfo): url = urljoin(URL, fileinfo.path) logger.info("Requesting file: {}".format(url)) return requests.get(url, stream=True) def _write_file_safely(local_path, fileinfo, response): """attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error""" try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e def _write_file(local_path, fileinfo, response): start = time.time() pbar_size = fileinfo.size / (5 * 10**5) pbar = tqdm.tqdm(total=int(pbar_size)) if response.status_code == 200: with open(local_path, "wb") as outfile: for chunk in response.iter_content(5*10**5): progress = len(chunk) / (5 * 10**5) _update_pbar(pbar, progress) outfile.write(chunk) else: raise requests.RequestException("Expected status code 200") pbar.close() duration = time.time() - start logger.info("Wrote {} in {:0.2f} s ({:0.2f} MB, {:0.2f} MB/s)".format( fileinfo.filename, duration, fileinfo.size / 10 ** 6, fileinfo.size / (duration * 10 ** 6))) def _update_pbar(pbar, val): update_val = max(int(val), 1) try: pbar.update(update_val) except Exception as e: # oh, c'mon TQDM, progress bars shouldn't crash software logger.debug("TQDM progress bar error: {}({})".format( e.__class__.__name__, e)) ########################################### # Local and remote file watcher-generators def watch_local_files(*filters, local_dir="."): list_local = partial(list_local_files, *filters, local_dir=local_dir) old_files = new_files = set(list_local()) while True: yield new_files - old_files, new_files old_files = new_files new_files = set(list_local()) def watch_remote_files(*filters, remote_dir="."): command.memory_changed() # clear change status to start list_remote = partial(command.list_files, *filters, remote_dir=remote_dir) old_files = new_files = set(list_remote()) while True: yield new_files - old_files, new_files old_files = new_files if command.memory_changed(): new_files = set(list_remote()) ##################################################### # Synchronize ONCE in the UP direction (to FlashAir) def up_by_all(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, **_): files = list_local_files(*filters, local_dir=local_dir) up_by_files(list(files), remote_dir=remote_dir) def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): """Sync a given list of local files to `remote_dir` dir""" if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files) def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync most recent file by date, time attribues""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync files whose filename attribute is highest in alphanumeric order""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def _sync_local_file(local_file_info, remote_dir, remote_files): local_name = local_file_info.filename local_size = local_file_info.size if local_name in remote_files: remote_file_info = remote_files[local_name] remote_size = remote_file_info.size if local_size == remote_size: logger.info( "Skipping '{}' already exists on SD card".format( local_name)) else: logger.warning( "Removing remote file {}: " "local size {} != remote size {}".format( local_name, local_size, remote_size)) upload.delete_file(remote_file_info.path) _stream_from_file(local_file_info, remote_dir) else: _stream_from_file(local_file_info, remote_dir) def _stream_from_file(fileinfo, remote_dir): logger.info("Uploading local file {} to {}".format( fileinfo.path, remote_dir)) _upload_file_safely(fileinfo, remote_dir) def _upload_file_safely(fileinfo, remote_dir): """attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error""" try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fileinfo.path) raise e def list_local_files(*filters, local_dir="."): all_entries = scandir(local_dir) file_entries = (e for e in all_entries if e.is_file()) for entry in file_entries: stat = entry.stat() size = stat.st_size datetime = arrow.get(stat.st_mtime) path = str(Path(local_dir, entry.name)) info = SimpleFileInfo(local_dir, entry.name, path, size, datetime) if all(filt(info) for filt in filters): yield info def list_local_files_raw(*filters, local_dir="."): all_entries = scandir(local_dir) all_files = (e for e in all_entries if e.is_file() and all(filt(e) for filt in filters)) for entry in all_files: path = str(Path(local_dir, entry.name)) yield RawFileInfo(local_dir, entry.name, path, entry.stat().st_size) def _notify_sync(direction, files): logger.info("{:d} files to {:s}:\n{}".format( len(files), direction, "\n".join(" " + f.filename for f in files))) def _notify_sync_ready(num_old_files, from_dir, to_dir): logger.info("Ready to sync new files from {} to {} " "({:d} existing files ignored)".format( from_dir, to_dir, num_old_files))
TadLeonard/tfatool
tfatool/sync.py
down_by_name
python
def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): files = command.list_files(*filters, remote_dir=remote_dir) greatest = sorted(files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir)
Sync files whose filename attribute is highest in alphanumeric order
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L173-L179
[ "def _notify_sync(direction, files):\n logger.info(\"{:d} files to {:s}:\\n{}\".format(\n len(files), direction,\n \"\\n\".join(\" \" + f.filename for f in files)))\n", "def down_by_files(to_sync, local_dir=\".\"):\n \"\"\"Sync a given list of files from `command.list_files` to `local_dir` dir\"\"\"\n for f in to_sync:\n _sync_remote_file(local_dir, f)\n" ]
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFileInfo logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Python 3.4 compatibility via scandir backport if hasattr(os, "scandir"): scandir = os.scandir else: import scandir scandir = scandir.scandir class Direction(str, Enum): up = "upload" # upload direction down = "download" # download direction ##################################### # Synchronizing newly created files class Monitor: """Synchronizes newly created files TO or FROM FlashAir in separate threads""" def __init__(self, *filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): self._filters = filters self._local_dir = local_dir self._remote_dir = remote_dir self.running = threading.Event() self.thread = None def _run(self, method): assert self.thread is None self.running.set() self.thread = threading.Thread(target=self._run_sync, args=(method,)) self.thread.start() def _run_sync(self, method): files = method(*self._filters, local_dir=self._local_dir, remote_dir=self._remote_dir) while self.running.is_set(): _, new = next(files) if not new: time.sleep(0.3) def sync_both(self): self._run(up_down_by_arrival) def sync_up(self): self._run(up_by_arrival) def sync_down(self): self._run(down_by_arrival) def stop(self): self.running.clear() def join(self): if self.thread: self.thread.join() self.thread = None def up_down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The generator yields before each upload or download actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, lfile_set = next(local_monitor) _, rfile_set = next(remote_monitor) _notify_sync_ready(len(lfile_set), local_dir, remote_dir) _notify_sync_ready(len(rfile_set), remote_dir, local_dir) processed = set() for new_local, new_remote in zip(local_monitor, remote_monitor): new_local, local_set = new_local local_arrivals = {f for f in new_local if f.filename not in processed} yield Direction.up, local_arrivals if local_arrivals: new_names.update(f.filename for f in local_arrivals) _notify_sync(Direction.up, local_arrivals) up_by_files(local_arrivals, remote_dir) _notify_sync_ready(len(local_set), local_dir, remote_dir) new_remote, remote_set = new_remote remote_arrivals = {f for f in new_remote if f.filename not in processed} yield Direction.down, remote_arrivals if remote_arrivals: new_names.update(f.filename for f in remote_arrivals) _notify_sync(Direction.down, remote_arrivals) yield Direction.down, remote_arrivals down_by_files(remote_arrivals, local_dir) _notify_sync_ready(len(remote_set), remote_dir, local_dir) def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) _, file_set = next(local_monitor) _notify_sync_ready(len(file_set), local_dir, remote_dir) for new_arrivals, file_set in local_monitor: yield Direction.up, new_arrivals # where new_arrivals is possibly empty if new_arrivals: _notify_sync(Direction.up, new_arrivals) up_by_files(new_arrivals, remote_dir) _notify_sync_ready(len(file_set), local_dir, remote_dir) def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place.""" remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, file_set = next(remote_monitor) _notify_sync_ready(len(file_set), remote_dir, local_dir) for new_arrivals, file_set in remote_monitor: if new_arrivals: _notify_sync(Direction.down, new_arrivals) down_by_files(new_arrivals, local_dir) _notify_sync_ready(len(file_set), remote_dir, local_dir) yield Direction.down, new_arrivals ################################################### # Sync ONCE in the DOWN (from FlashAir) direction def down_by_all(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", **_): files = command.list_files(*filters, remote_dir=remote_dir) down_by_files(files, local_dir=local_dir) def down_by_files(to_sync, local_dir="."): """Sync a given list of files from `command.list_files` to `local_dir` dir""" for f in to_sync: _sync_remote_file(local_dir, f) def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync most recent file by date, time attribues""" files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def _sync_remote_file(local_dir, remote_file_info): local = Path(local_dir, remote_file_info.filename) local_name = str(local) remote_size = remote_file_info.size if local.exists(): local_size = local.stat().st_size if local.stat().st_size == remote_size: logger.info( "Skipping '{}': already exists locally".format( local_name)) else: logger.warning( "Removing {}: local size {} != remote size {}".format( local_name, local_size, remote_size)) os.remove(local_name) _stream_to_file(local_name, remote_file_info) else: _stream_to_file(local_name, remote_file_info) def _stream_to_file(local_name, fileinfo): logger.info("Copying remote file {} to {}".format( fileinfo.path, local_name)) streaming_file = _get_file(fileinfo) _write_file_safely(local_name, fileinfo, streaming_file) def _get_file(fileinfo): url = urljoin(URL, fileinfo.path) logger.info("Requesting file: {}".format(url)) return requests.get(url, stream=True) def _write_file_safely(local_path, fileinfo, response): """attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error""" try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e def _write_file(local_path, fileinfo, response): start = time.time() pbar_size = fileinfo.size / (5 * 10**5) pbar = tqdm.tqdm(total=int(pbar_size)) if response.status_code == 200: with open(local_path, "wb") as outfile: for chunk in response.iter_content(5*10**5): progress = len(chunk) / (5 * 10**5) _update_pbar(pbar, progress) outfile.write(chunk) else: raise requests.RequestException("Expected status code 200") pbar.close() duration = time.time() - start logger.info("Wrote {} in {:0.2f} s ({:0.2f} MB, {:0.2f} MB/s)".format( fileinfo.filename, duration, fileinfo.size / 10 ** 6, fileinfo.size / (duration * 10 ** 6))) def _update_pbar(pbar, val): update_val = max(int(val), 1) try: pbar.update(update_val) except Exception as e: # oh, c'mon TQDM, progress bars shouldn't crash software logger.debug("TQDM progress bar error: {}({})".format( e.__class__.__name__, e)) ########################################### # Local and remote file watcher-generators def watch_local_files(*filters, local_dir="."): list_local = partial(list_local_files, *filters, local_dir=local_dir) old_files = new_files = set(list_local()) while True: yield new_files - old_files, new_files old_files = new_files new_files = set(list_local()) def watch_remote_files(*filters, remote_dir="."): command.memory_changed() # clear change status to start list_remote = partial(command.list_files, *filters, remote_dir=remote_dir) old_files = new_files = set(list_remote()) while True: yield new_files - old_files, new_files old_files = new_files if command.memory_changed(): new_files = set(list_remote()) ##################################################### # Synchronize ONCE in the UP direction (to FlashAir) def up_by_all(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, **_): files = list_local_files(*filters, local_dir=local_dir) up_by_files(list(files), remote_dir=remote_dir) def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): """Sync a given list of local files to `remote_dir` dir""" if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files) def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync most recent file by date, time attribues""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync files whose filename attribute is highest in alphanumeric order""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def _sync_local_file(local_file_info, remote_dir, remote_files): local_name = local_file_info.filename local_size = local_file_info.size if local_name in remote_files: remote_file_info = remote_files[local_name] remote_size = remote_file_info.size if local_size == remote_size: logger.info( "Skipping '{}' already exists on SD card".format( local_name)) else: logger.warning( "Removing remote file {}: " "local size {} != remote size {}".format( local_name, local_size, remote_size)) upload.delete_file(remote_file_info.path) _stream_from_file(local_file_info, remote_dir) else: _stream_from_file(local_file_info, remote_dir) def _stream_from_file(fileinfo, remote_dir): logger.info("Uploading local file {} to {}".format( fileinfo.path, remote_dir)) _upload_file_safely(fileinfo, remote_dir) def _upload_file_safely(fileinfo, remote_dir): """attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error""" try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fileinfo.path) raise e def list_local_files(*filters, local_dir="."): all_entries = scandir(local_dir) file_entries = (e for e in all_entries if e.is_file()) for entry in file_entries: stat = entry.stat() size = stat.st_size datetime = arrow.get(stat.st_mtime) path = str(Path(local_dir, entry.name)) info = SimpleFileInfo(local_dir, entry.name, path, size, datetime) if all(filt(info) for filt in filters): yield info def list_local_files_raw(*filters, local_dir="."): all_entries = scandir(local_dir) all_files = (e for e in all_entries if e.is_file() and all(filt(e) for filt in filters)) for entry in all_files: path = str(Path(local_dir, entry.name)) yield RawFileInfo(local_dir, entry.name, path, entry.stat().st_size) def _notify_sync(direction, files): logger.info("{:d} files to {:s}:\n{}".format( len(files), direction, "\n".join(" " + f.filename for f in files))) def _notify_sync_ready(num_old_files, from_dir, to_dir): logger.info("Ready to sync new files from {} to {} " "({:d} existing files ignored)".format( from_dir, to_dir, num_old_files))
TadLeonard/tfatool
tfatool/sync.py
_write_file_safely
python
def _write_file_safely(local_path, fileinfo, response): try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e
attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L215-L225
null
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFileInfo logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Python 3.4 compatibility via scandir backport if hasattr(os, "scandir"): scandir = os.scandir else: import scandir scandir = scandir.scandir class Direction(str, Enum): up = "upload" # upload direction down = "download" # download direction ##################################### # Synchronizing newly created files class Monitor: """Synchronizes newly created files TO or FROM FlashAir in separate threads""" def __init__(self, *filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): self._filters = filters self._local_dir = local_dir self._remote_dir = remote_dir self.running = threading.Event() self.thread = None def _run(self, method): assert self.thread is None self.running.set() self.thread = threading.Thread(target=self._run_sync, args=(method,)) self.thread.start() def _run_sync(self, method): files = method(*self._filters, local_dir=self._local_dir, remote_dir=self._remote_dir) while self.running.is_set(): _, new = next(files) if not new: time.sleep(0.3) def sync_both(self): self._run(up_down_by_arrival) def sync_up(self): self._run(up_by_arrival) def sync_down(self): self._run(down_by_arrival) def stop(self): self.running.clear() def join(self): if self.thread: self.thread.join() self.thread = None def up_down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The generator yields before each upload or download actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, lfile_set = next(local_monitor) _, rfile_set = next(remote_monitor) _notify_sync_ready(len(lfile_set), local_dir, remote_dir) _notify_sync_ready(len(rfile_set), remote_dir, local_dir) processed = set() for new_local, new_remote in zip(local_monitor, remote_monitor): new_local, local_set = new_local local_arrivals = {f for f in new_local if f.filename not in processed} yield Direction.up, local_arrivals if local_arrivals: new_names.update(f.filename for f in local_arrivals) _notify_sync(Direction.up, local_arrivals) up_by_files(local_arrivals, remote_dir) _notify_sync_ready(len(local_set), local_dir, remote_dir) new_remote, remote_set = new_remote remote_arrivals = {f for f in new_remote if f.filename not in processed} yield Direction.down, remote_arrivals if remote_arrivals: new_names.update(f.filename for f in remote_arrivals) _notify_sync(Direction.down, remote_arrivals) yield Direction.down, remote_arrivals down_by_files(remote_arrivals, local_dir) _notify_sync_ready(len(remote_set), remote_dir, local_dir) def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) _, file_set = next(local_monitor) _notify_sync_ready(len(file_set), local_dir, remote_dir) for new_arrivals, file_set in local_monitor: yield Direction.up, new_arrivals # where new_arrivals is possibly empty if new_arrivals: _notify_sync(Direction.up, new_arrivals) up_by_files(new_arrivals, remote_dir) _notify_sync_ready(len(file_set), local_dir, remote_dir) def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place.""" remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, file_set = next(remote_monitor) _notify_sync_ready(len(file_set), remote_dir, local_dir) for new_arrivals, file_set in remote_monitor: if new_arrivals: _notify_sync(Direction.down, new_arrivals) down_by_files(new_arrivals, local_dir) _notify_sync_ready(len(file_set), remote_dir, local_dir) yield Direction.down, new_arrivals ################################################### # Sync ONCE in the DOWN (from FlashAir) direction def down_by_all(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", **_): files = command.list_files(*filters, remote_dir=remote_dir) down_by_files(files, local_dir=local_dir) def down_by_files(to_sync, local_dir="."): """Sync a given list of files from `command.list_files` to `local_dir` dir""" for f in to_sync: _sync_remote_file(local_dir, f) def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync most recent file by date, time attribues""" files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync files whose filename attribute is highest in alphanumeric order""" files = command.list_files(*filters, remote_dir=remote_dir) greatest = sorted(files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def _sync_remote_file(local_dir, remote_file_info): local = Path(local_dir, remote_file_info.filename) local_name = str(local) remote_size = remote_file_info.size if local.exists(): local_size = local.stat().st_size if local.stat().st_size == remote_size: logger.info( "Skipping '{}': already exists locally".format( local_name)) else: logger.warning( "Removing {}: local size {} != remote size {}".format( local_name, local_size, remote_size)) os.remove(local_name) _stream_to_file(local_name, remote_file_info) else: _stream_to_file(local_name, remote_file_info) def _stream_to_file(local_name, fileinfo): logger.info("Copying remote file {} to {}".format( fileinfo.path, local_name)) streaming_file = _get_file(fileinfo) _write_file_safely(local_name, fileinfo, streaming_file) def _get_file(fileinfo): url = urljoin(URL, fileinfo.path) logger.info("Requesting file: {}".format(url)) return requests.get(url, stream=True) def _write_file(local_path, fileinfo, response): start = time.time() pbar_size = fileinfo.size / (5 * 10**5) pbar = tqdm.tqdm(total=int(pbar_size)) if response.status_code == 200: with open(local_path, "wb") as outfile: for chunk in response.iter_content(5*10**5): progress = len(chunk) / (5 * 10**5) _update_pbar(pbar, progress) outfile.write(chunk) else: raise requests.RequestException("Expected status code 200") pbar.close() duration = time.time() - start logger.info("Wrote {} in {:0.2f} s ({:0.2f} MB, {:0.2f} MB/s)".format( fileinfo.filename, duration, fileinfo.size / 10 ** 6, fileinfo.size / (duration * 10 ** 6))) def _update_pbar(pbar, val): update_val = max(int(val), 1) try: pbar.update(update_val) except Exception as e: # oh, c'mon TQDM, progress bars shouldn't crash software logger.debug("TQDM progress bar error: {}({})".format( e.__class__.__name__, e)) ########################################### # Local and remote file watcher-generators def watch_local_files(*filters, local_dir="."): list_local = partial(list_local_files, *filters, local_dir=local_dir) old_files = new_files = set(list_local()) while True: yield new_files - old_files, new_files old_files = new_files new_files = set(list_local()) def watch_remote_files(*filters, remote_dir="."): command.memory_changed() # clear change status to start list_remote = partial(command.list_files, *filters, remote_dir=remote_dir) old_files = new_files = set(list_remote()) while True: yield new_files - old_files, new_files old_files = new_files if command.memory_changed(): new_files = set(list_remote()) ##################################################### # Synchronize ONCE in the UP direction (to FlashAir) def up_by_all(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, **_): files = list_local_files(*filters, local_dir=local_dir) up_by_files(list(files), remote_dir=remote_dir) def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): """Sync a given list of local files to `remote_dir` dir""" if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files) def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync most recent file by date, time attribues""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync files whose filename attribute is highest in alphanumeric order""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def _sync_local_file(local_file_info, remote_dir, remote_files): local_name = local_file_info.filename local_size = local_file_info.size if local_name in remote_files: remote_file_info = remote_files[local_name] remote_size = remote_file_info.size if local_size == remote_size: logger.info( "Skipping '{}' already exists on SD card".format( local_name)) else: logger.warning( "Removing remote file {}: " "local size {} != remote size {}".format( local_name, local_size, remote_size)) upload.delete_file(remote_file_info.path) _stream_from_file(local_file_info, remote_dir) else: _stream_from_file(local_file_info, remote_dir) def _stream_from_file(fileinfo, remote_dir): logger.info("Uploading local file {} to {}".format( fileinfo.path, remote_dir)) _upload_file_safely(fileinfo, remote_dir) def _upload_file_safely(fileinfo, remote_dir): """attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error""" try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fileinfo.path) raise e def list_local_files(*filters, local_dir="."): all_entries = scandir(local_dir) file_entries = (e for e in all_entries if e.is_file()) for entry in file_entries: stat = entry.stat() size = stat.st_size datetime = arrow.get(stat.st_mtime) path = str(Path(local_dir, entry.name)) info = SimpleFileInfo(local_dir, entry.name, path, size, datetime) if all(filt(info) for filt in filters): yield info def list_local_files_raw(*filters, local_dir="."): all_entries = scandir(local_dir) all_files = (e for e in all_entries if e.is_file() and all(filt(e) for filt in filters)) for entry in all_files: path = str(Path(local_dir, entry.name)) yield RawFileInfo(local_dir, entry.name, path, entry.stat().st_size) def _notify_sync(direction, files): logger.info("{:d} files to {:s}:\n{}".format( len(files), direction, "\n".join(" " + f.filename for f in files))) def _notify_sync_ready(num_old_files, from_dir, to_dir): logger.info("Ready to sync new files from {} to {} " "({:d} existing files ignored)".format( from_dir, to_dir, num_old_files))
TadLeonard/tfatool
tfatool/sync.py
up_by_files
python
def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files)
Sync a given list of local files to `remote_dir` dir
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L289-L294
[ "def _sync_local_file(local_file_info, remote_dir, remote_files):\n local_name = local_file_info.filename\n local_size = local_file_info.size\n if local_name in remote_files:\n remote_file_info = remote_files[local_name]\n remote_size = remote_file_info.size\n if local_size == remote_size:\n logger.info(\n \"Skipping '{}' already exists on SD card\".format(\n local_name))\n else:\n logger.warning(\n \"Removing remote file {}: \"\n \"local size {} != remote size {}\".format(\n local_name, local_size, remote_size))\n upload.delete_file(remote_file_info.path)\n _stream_from_file(local_file_info, remote_dir)\n else:\n _stream_from_file(local_file_info, remote_dir)\n" ]
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFileInfo logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Python 3.4 compatibility via scandir backport if hasattr(os, "scandir"): scandir = os.scandir else: import scandir scandir = scandir.scandir class Direction(str, Enum): up = "upload" # upload direction down = "download" # download direction ##################################### # Synchronizing newly created files class Monitor: """Synchronizes newly created files TO or FROM FlashAir in separate threads""" def __init__(self, *filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): self._filters = filters self._local_dir = local_dir self._remote_dir = remote_dir self.running = threading.Event() self.thread = None def _run(self, method): assert self.thread is None self.running.set() self.thread = threading.Thread(target=self._run_sync, args=(method,)) self.thread.start() def _run_sync(self, method): files = method(*self._filters, local_dir=self._local_dir, remote_dir=self._remote_dir) while self.running.is_set(): _, new = next(files) if not new: time.sleep(0.3) def sync_both(self): self._run(up_down_by_arrival) def sync_up(self): self._run(up_by_arrival) def sync_down(self): self._run(down_by_arrival) def stop(self): self.running.clear() def join(self): if self.thread: self.thread.join() self.thread = None def up_down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The generator yields before each upload or download actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, lfile_set = next(local_monitor) _, rfile_set = next(remote_monitor) _notify_sync_ready(len(lfile_set), local_dir, remote_dir) _notify_sync_ready(len(rfile_set), remote_dir, local_dir) processed = set() for new_local, new_remote in zip(local_monitor, remote_monitor): new_local, local_set = new_local local_arrivals = {f for f in new_local if f.filename not in processed} yield Direction.up, local_arrivals if local_arrivals: new_names.update(f.filename for f in local_arrivals) _notify_sync(Direction.up, local_arrivals) up_by_files(local_arrivals, remote_dir) _notify_sync_ready(len(local_set), local_dir, remote_dir) new_remote, remote_set = new_remote remote_arrivals = {f for f in new_remote if f.filename not in processed} yield Direction.down, remote_arrivals if remote_arrivals: new_names.update(f.filename for f in remote_arrivals) _notify_sync(Direction.down, remote_arrivals) yield Direction.down, remote_arrivals down_by_files(remote_arrivals, local_dir) _notify_sync_ready(len(remote_set), remote_dir, local_dir) def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) _, file_set = next(local_monitor) _notify_sync_ready(len(file_set), local_dir, remote_dir) for new_arrivals, file_set in local_monitor: yield Direction.up, new_arrivals # where new_arrivals is possibly empty if new_arrivals: _notify_sync(Direction.up, new_arrivals) up_by_files(new_arrivals, remote_dir) _notify_sync_ready(len(file_set), local_dir, remote_dir) def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place.""" remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, file_set = next(remote_monitor) _notify_sync_ready(len(file_set), remote_dir, local_dir) for new_arrivals, file_set in remote_monitor: if new_arrivals: _notify_sync(Direction.down, new_arrivals) down_by_files(new_arrivals, local_dir) _notify_sync_ready(len(file_set), remote_dir, local_dir) yield Direction.down, new_arrivals ################################################### # Sync ONCE in the DOWN (from FlashAir) direction def down_by_all(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", **_): files = command.list_files(*filters, remote_dir=remote_dir) down_by_files(files, local_dir=local_dir) def down_by_files(to_sync, local_dir="."): """Sync a given list of files from `command.list_files` to `local_dir` dir""" for f in to_sync: _sync_remote_file(local_dir, f) def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync most recent file by date, time attribues""" files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync files whose filename attribute is highest in alphanumeric order""" files = command.list_files(*filters, remote_dir=remote_dir) greatest = sorted(files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def _sync_remote_file(local_dir, remote_file_info): local = Path(local_dir, remote_file_info.filename) local_name = str(local) remote_size = remote_file_info.size if local.exists(): local_size = local.stat().st_size if local.stat().st_size == remote_size: logger.info( "Skipping '{}': already exists locally".format( local_name)) else: logger.warning( "Removing {}: local size {} != remote size {}".format( local_name, local_size, remote_size)) os.remove(local_name) _stream_to_file(local_name, remote_file_info) else: _stream_to_file(local_name, remote_file_info) def _stream_to_file(local_name, fileinfo): logger.info("Copying remote file {} to {}".format( fileinfo.path, local_name)) streaming_file = _get_file(fileinfo) _write_file_safely(local_name, fileinfo, streaming_file) def _get_file(fileinfo): url = urljoin(URL, fileinfo.path) logger.info("Requesting file: {}".format(url)) return requests.get(url, stream=True) def _write_file_safely(local_path, fileinfo, response): """attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error""" try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e def _write_file(local_path, fileinfo, response): start = time.time() pbar_size = fileinfo.size / (5 * 10**5) pbar = tqdm.tqdm(total=int(pbar_size)) if response.status_code == 200: with open(local_path, "wb") as outfile: for chunk in response.iter_content(5*10**5): progress = len(chunk) / (5 * 10**5) _update_pbar(pbar, progress) outfile.write(chunk) else: raise requests.RequestException("Expected status code 200") pbar.close() duration = time.time() - start logger.info("Wrote {} in {:0.2f} s ({:0.2f} MB, {:0.2f} MB/s)".format( fileinfo.filename, duration, fileinfo.size / 10 ** 6, fileinfo.size / (duration * 10 ** 6))) def _update_pbar(pbar, val): update_val = max(int(val), 1) try: pbar.update(update_val) except Exception as e: # oh, c'mon TQDM, progress bars shouldn't crash software logger.debug("TQDM progress bar error: {}({})".format( e.__class__.__name__, e)) ########################################### # Local and remote file watcher-generators def watch_local_files(*filters, local_dir="."): list_local = partial(list_local_files, *filters, local_dir=local_dir) old_files = new_files = set(list_local()) while True: yield new_files - old_files, new_files old_files = new_files new_files = set(list_local()) def watch_remote_files(*filters, remote_dir="."): command.memory_changed() # clear change status to start list_remote = partial(command.list_files, *filters, remote_dir=remote_dir) old_files = new_files = set(list_remote()) while True: yield new_files - old_files, new_files old_files = new_files if command.memory_changed(): new_files = set(list_remote()) ##################################################### # Synchronize ONCE in the UP direction (to FlashAir) def up_by_all(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, **_): files = list_local_files(*filters, local_dir=local_dir) up_by_files(list(files), remote_dir=remote_dir) def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync most recent file by date, time attribues""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync files whose filename attribute is highest in alphanumeric order""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def _sync_local_file(local_file_info, remote_dir, remote_files): local_name = local_file_info.filename local_size = local_file_info.size if local_name in remote_files: remote_file_info = remote_files[local_name] remote_size = remote_file_info.size if local_size == remote_size: logger.info( "Skipping '{}' already exists on SD card".format( local_name)) else: logger.warning( "Removing remote file {}: " "local size {} != remote size {}".format( local_name, local_size, remote_size)) upload.delete_file(remote_file_info.path) _stream_from_file(local_file_info, remote_dir) else: _stream_from_file(local_file_info, remote_dir) def _stream_from_file(fileinfo, remote_dir): logger.info("Uploading local file {} to {}".format( fileinfo.path, remote_dir)) _upload_file_safely(fileinfo, remote_dir) def _upload_file_safely(fileinfo, remote_dir): """attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error""" try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fileinfo.path) raise e def list_local_files(*filters, local_dir="."): all_entries = scandir(local_dir) file_entries = (e for e in all_entries if e.is_file()) for entry in file_entries: stat = entry.stat() size = stat.st_size datetime = arrow.get(stat.st_mtime) path = str(Path(local_dir, entry.name)) info = SimpleFileInfo(local_dir, entry.name, path, size, datetime) if all(filt(info) for filt in filters): yield info def list_local_files_raw(*filters, local_dir="."): all_entries = scandir(local_dir) all_files = (e for e in all_entries if e.is_file() and all(filt(e) for filt in filters)) for entry in all_files: path = str(Path(local_dir, entry.name)) yield RawFileInfo(local_dir, entry.name, path, entry.stat().st_size) def _notify_sync(direction, files): logger.info("{:d} files to {:s}:\n{}".format( len(files), direction, "\n".join(" " + f.filename for f in files))) def _notify_sync_ready(num_old_files, from_dir, to_dir): logger.info("Ready to sync new files from {} to {} " "({:d} existing files ignored)".format( from_dir, to_dir, num_old_files))
TadLeonard/tfatool
tfatool/sync.py
up_by_time
python
def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files)
Sync most recent file by date, time attribues
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L297-L304
[ "def _notify_sync(direction, files):\n logger.info(\"{:d} files to {:s}:\\n{}\".format(\n len(files), direction,\n \"\\n\".join(\" \" + f.filename for f in files)))\n", "def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None):\n \"\"\"Sync a given list of local files to `remote_dir` dir\"\"\"\n if remote_files is None:\n remote_files = command.map_files_raw(remote_dir=remote_dir)\n for local_file in to_sync:\n _sync_local_file(local_file, remote_dir, remote_files)\n", "def list_local_files(*filters, local_dir=\".\"):\n all_entries = scandir(local_dir)\n file_entries = (e for e in all_entries if e.is_file())\n for entry in file_entries:\n stat = entry.stat()\n size = stat.st_size\n datetime = arrow.get(stat.st_mtime)\n path = str(Path(local_dir, entry.name))\n info = SimpleFileInfo(local_dir, entry.name, path, size, datetime)\n if all(filt(info) for filt in filters):\n yield info\n" ]
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFileInfo logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Python 3.4 compatibility via scandir backport if hasattr(os, "scandir"): scandir = os.scandir else: import scandir scandir = scandir.scandir class Direction(str, Enum): up = "upload" # upload direction down = "download" # download direction ##################################### # Synchronizing newly created files class Monitor: """Synchronizes newly created files TO or FROM FlashAir in separate threads""" def __init__(self, *filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): self._filters = filters self._local_dir = local_dir self._remote_dir = remote_dir self.running = threading.Event() self.thread = None def _run(self, method): assert self.thread is None self.running.set() self.thread = threading.Thread(target=self._run_sync, args=(method,)) self.thread.start() def _run_sync(self, method): files = method(*self._filters, local_dir=self._local_dir, remote_dir=self._remote_dir) while self.running.is_set(): _, new = next(files) if not new: time.sleep(0.3) def sync_both(self): self._run(up_down_by_arrival) def sync_up(self): self._run(up_by_arrival) def sync_down(self): self._run(down_by_arrival) def stop(self): self.running.clear() def join(self): if self.thread: self.thread.join() self.thread = None def up_down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The generator yields before each upload or download actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, lfile_set = next(local_monitor) _, rfile_set = next(remote_monitor) _notify_sync_ready(len(lfile_set), local_dir, remote_dir) _notify_sync_ready(len(rfile_set), remote_dir, local_dir) processed = set() for new_local, new_remote in zip(local_monitor, remote_monitor): new_local, local_set = new_local local_arrivals = {f for f in new_local if f.filename not in processed} yield Direction.up, local_arrivals if local_arrivals: new_names.update(f.filename for f in local_arrivals) _notify_sync(Direction.up, local_arrivals) up_by_files(local_arrivals, remote_dir) _notify_sync_ready(len(local_set), local_dir, remote_dir) new_remote, remote_set = new_remote remote_arrivals = {f for f in new_remote if f.filename not in processed} yield Direction.down, remote_arrivals if remote_arrivals: new_names.update(f.filename for f in remote_arrivals) _notify_sync(Direction.down, remote_arrivals) yield Direction.down, remote_arrivals down_by_files(remote_arrivals, local_dir) _notify_sync_ready(len(remote_set), remote_dir, local_dir) def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) _, file_set = next(local_monitor) _notify_sync_ready(len(file_set), local_dir, remote_dir) for new_arrivals, file_set in local_monitor: yield Direction.up, new_arrivals # where new_arrivals is possibly empty if new_arrivals: _notify_sync(Direction.up, new_arrivals) up_by_files(new_arrivals, remote_dir) _notify_sync_ready(len(file_set), local_dir, remote_dir) def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place.""" remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, file_set = next(remote_monitor) _notify_sync_ready(len(file_set), remote_dir, local_dir) for new_arrivals, file_set in remote_monitor: if new_arrivals: _notify_sync(Direction.down, new_arrivals) down_by_files(new_arrivals, local_dir) _notify_sync_ready(len(file_set), remote_dir, local_dir) yield Direction.down, new_arrivals ################################################### # Sync ONCE in the DOWN (from FlashAir) direction def down_by_all(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", **_): files = command.list_files(*filters, remote_dir=remote_dir) down_by_files(files, local_dir=local_dir) def down_by_files(to_sync, local_dir="."): """Sync a given list of files from `command.list_files` to `local_dir` dir""" for f in to_sync: _sync_remote_file(local_dir, f) def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync most recent file by date, time attribues""" files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync files whose filename attribute is highest in alphanumeric order""" files = command.list_files(*filters, remote_dir=remote_dir) greatest = sorted(files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def _sync_remote_file(local_dir, remote_file_info): local = Path(local_dir, remote_file_info.filename) local_name = str(local) remote_size = remote_file_info.size if local.exists(): local_size = local.stat().st_size if local.stat().st_size == remote_size: logger.info( "Skipping '{}': already exists locally".format( local_name)) else: logger.warning( "Removing {}: local size {} != remote size {}".format( local_name, local_size, remote_size)) os.remove(local_name) _stream_to_file(local_name, remote_file_info) else: _stream_to_file(local_name, remote_file_info) def _stream_to_file(local_name, fileinfo): logger.info("Copying remote file {} to {}".format( fileinfo.path, local_name)) streaming_file = _get_file(fileinfo) _write_file_safely(local_name, fileinfo, streaming_file) def _get_file(fileinfo): url = urljoin(URL, fileinfo.path) logger.info("Requesting file: {}".format(url)) return requests.get(url, stream=True) def _write_file_safely(local_path, fileinfo, response): """attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error""" try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e def _write_file(local_path, fileinfo, response): start = time.time() pbar_size = fileinfo.size / (5 * 10**5) pbar = tqdm.tqdm(total=int(pbar_size)) if response.status_code == 200: with open(local_path, "wb") as outfile: for chunk in response.iter_content(5*10**5): progress = len(chunk) / (5 * 10**5) _update_pbar(pbar, progress) outfile.write(chunk) else: raise requests.RequestException("Expected status code 200") pbar.close() duration = time.time() - start logger.info("Wrote {} in {:0.2f} s ({:0.2f} MB, {:0.2f} MB/s)".format( fileinfo.filename, duration, fileinfo.size / 10 ** 6, fileinfo.size / (duration * 10 ** 6))) def _update_pbar(pbar, val): update_val = max(int(val), 1) try: pbar.update(update_val) except Exception as e: # oh, c'mon TQDM, progress bars shouldn't crash software logger.debug("TQDM progress bar error: {}({})".format( e.__class__.__name__, e)) ########################################### # Local and remote file watcher-generators def watch_local_files(*filters, local_dir="."): list_local = partial(list_local_files, *filters, local_dir=local_dir) old_files = new_files = set(list_local()) while True: yield new_files - old_files, new_files old_files = new_files new_files = set(list_local()) def watch_remote_files(*filters, remote_dir="."): command.memory_changed() # clear change status to start list_remote = partial(command.list_files, *filters, remote_dir=remote_dir) old_files = new_files = set(list_remote()) while True: yield new_files - old_files, new_files old_files = new_files if command.memory_changed(): new_files = set(list_remote()) ##################################################### # Synchronize ONCE in the UP direction (to FlashAir) def up_by_all(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, **_): files = list_local_files(*filters, local_dir=local_dir) up_by_files(list(files), remote_dir=remote_dir) def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): """Sync a given list of local files to `remote_dir` dir""" if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files) def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync files whose filename attribute is highest in alphanumeric order""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def _sync_local_file(local_file_info, remote_dir, remote_files): local_name = local_file_info.filename local_size = local_file_info.size if local_name in remote_files: remote_file_info = remote_files[local_name] remote_size = remote_file_info.size if local_size == remote_size: logger.info( "Skipping '{}' already exists on SD card".format( local_name)) else: logger.warning( "Removing remote file {}: " "local size {} != remote size {}".format( local_name, local_size, remote_size)) upload.delete_file(remote_file_info.path) _stream_from_file(local_file_info, remote_dir) else: _stream_from_file(local_file_info, remote_dir) def _stream_from_file(fileinfo, remote_dir): logger.info("Uploading local file {} to {}".format( fileinfo.path, remote_dir)) _upload_file_safely(fileinfo, remote_dir) def _upload_file_safely(fileinfo, remote_dir): """attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error""" try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fileinfo.path) raise e def list_local_files(*filters, local_dir="."): all_entries = scandir(local_dir) file_entries = (e for e in all_entries if e.is_file()) for entry in file_entries: stat = entry.stat() size = stat.st_size datetime = arrow.get(stat.st_mtime) path = str(Path(local_dir, entry.name)) info = SimpleFileInfo(local_dir, entry.name, path, size, datetime) if all(filt(info) for filt in filters): yield info def list_local_files_raw(*filters, local_dir="."): all_entries = scandir(local_dir) all_files = (e for e in all_entries if e.is_file() and all(filt(e) for filt in filters)) for entry in all_files: path = str(Path(local_dir, entry.name)) yield RawFileInfo(local_dir, entry.name, path, entry.stat().st_size) def _notify_sync(direction, files): logger.info("{:d} files to {:s}:\n{}".format( len(files), direction, "\n".join(" " + f.filename for f in files))) def _notify_sync_ready(num_old_files, from_dir, to_dir): logger.info("Ready to sync new files from {} to {} " "({:d} existing files ignored)".format( from_dir, to_dir, num_old_files))
TadLeonard/tfatool
tfatool/sync.py
up_by_name
python
def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files)
Sync files whose filename attribute is highest in alphanumeric order
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L307-L314
[ "def _notify_sync(direction, files):\n logger.info(\"{:d} files to {:s}:\\n{}\".format(\n len(files), direction,\n \"\\n\".join(\" \" + f.filename for f in files)))\n", "def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None):\n \"\"\"Sync a given list of local files to `remote_dir` dir\"\"\"\n if remote_files is None:\n remote_files = command.map_files_raw(remote_dir=remote_dir)\n for local_file in to_sync:\n _sync_local_file(local_file, remote_dir, remote_files)\n", "def list_local_files(*filters, local_dir=\".\"):\n all_entries = scandir(local_dir)\n file_entries = (e for e in all_entries if e.is_file())\n for entry in file_entries:\n stat = entry.stat()\n size = stat.st_size\n datetime = arrow.get(stat.st_mtime)\n path = str(Path(local_dir, entry.name))\n info = SimpleFileInfo(local_dir, entry.name, path, size, datetime)\n if all(filt(info) for filt in filters):\n yield info\n" ]
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFileInfo logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Python 3.4 compatibility via scandir backport if hasattr(os, "scandir"): scandir = os.scandir else: import scandir scandir = scandir.scandir class Direction(str, Enum): up = "upload" # upload direction down = "download" # download direction ##################################### # Synchronizing newly created files class Monitor: """Synchronizes newly created files TO or FROM FlashAir in separate threads""" def __init__(self, *filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): self._filters = filters self._local_dir = local_dir self._remote_dir = remote_dir self.running = threading.Event() self.thread = None def _run(self, method): assert self.thread is None self.running.set() self.thread = threading.Thread(target=self._run_sync, args=(method,)) self.thread.start() def _run_sync(self, method): files = method(*self._filters, local_dir=self._local_dir, remote_dir=self._remote_dir) while self.running.is_set(): _, new = next(files) if not new: time.sleep(0.3) def sync_both(self): self._run(up_down_by_arrival) def sync_up(self): self._run(up_by_arrival) def sync_down(self): self._run(down_by_arrival) def stop(self): self.running.clear() def join(self): if self.thread: self.thread.join() self.thread = None def up_down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The generator yields before each upload or download actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, lfile_set = next(local_monitor) _, rfile_set = next(remote_monitor) _notify_sync_ready(len(lfile_set), local_dir, remote_dir) _notify_sync_ready(len(rfile_set), remote_dir, local_dir) processed = set() for new_local, new_remote in zip(local_monitor, remote_monitor): new_local, local_set = new_local local_arrivals = {f for f in new_local if f.filename not in processed} yield Direction.up, local_arrivals if local_arrivals: new_names.update(f.filename for f in local_arrivals) _notify_sync(Direction.up, local_arrivals) up_by_files(local_arrivals, remote_dir) _notify_sync_ready(len(local_set), local_dir, remote_dir) new_remote, remote_set = new_remote remote_arrivals = {f for f in new_remote if f.filename not in processed} yield Direction.down, remote_arrivals if remote_arrivals: new_names.update(f.filename for f in remote_arrivals) _notify_sync(Direction.down, remote_arrivals) yield Direction.down, remote_arrivals down_by_files(remote_arrivals, local_dir) _notify_sync_ready(len(remote_set), remote_dir, local_dir) def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) _, file_set = next(local_monitor) _notify_sync_ready(len(file_set), local_dir, remote_dir) for new_arrivals, file_set in local_monitor: yield Direction.up, new_arrivals # where new_arrivals is possibly empty if new_arrivals: _notify_sync(Direction.up, new_arrivals) up_by_files(new_arrivals, remote_dir) _notify_sync_ready(len(file_set), local_dir, remote_dir) def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place.""" remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, file_set = next(remote_monitor) _notify_sync_ready(len(file_set), remote_dir, local_dir) for new_arrivals, file_set in remote_monitor: if new_arrivals: _notify_sync(Direction.down, new_arrivals) down_by_files(new_arrivals, local_dir) _notify_sync_ready(len(file_set), remote_dir, local_dir) yield Direction.down, new_arrivals ################################################### # Sync ONCE in the DOWN (from FlashAir) direction def down_by_all(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", **_): files = command.list_files(*filters, remote_dir=remote_dir) down_by_files(files, local_dir=local_dir) def down_by_files(to_sync, local_dir="."): """Sync a given list of files from `command.list_files` to `local_dir` dir""" for f in to_sync: _sync_remote_file(local_dir, f) def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync most recent file by date, time attribues""" files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync files whose filename attribute is highest in alphanumeric order""" files = command.list_files(*filters, remote_dir=remote_dir) greatest = sorted(files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def _sync_remote_file(local_dir, remote_file_info): local = Path(local_dir, remote_file_info.filename) local_name = str(local) remote_size = remote_file_info.size if local.exists(): local_size = local.stat().st_size if local.stat().st_size == remote_size: logger.info( "Skipping '{}': already exists locally".format( local_name)) else: logger.warning( "Removing {}: local size {} != remote size {}".format( local_name, local_size, remote_size)) os.remove(local_name) _stream_to_file(local_name, remote_file_info) else: _stream_to_file(local_name, remote_file_info) def _stream_to_file(local_name, fileinfo): logger.info("Copying remote file {} to {}".format( fileinfo.path, local_name)) streaming_file = _get_file(fileinfo) _write_file_safely(local_name, fileinfo, streaming_file) def _get_file(fileinfo): url = urljoin(URL, fileinfo.path) logger.info("Requesting file: {}".format(url)) return requests.get(url, stream=True) def _write_file_safely(local_path, fileinfo, response): """attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error""" try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e def _write_file(local_path, fileinfo, response): start = time.time() pbar_size = fileinfo.size / (5 * 10**5) pbar = tqdm.tqdm(total=int(pbar_size)) if response.status_code == 200: with open(local_path, "wb") as outfile: for chunk in response.iter_content(5*10**5): progress = len(chunk) / (5 * 10**5) _update_pbar(pbar, progress) outfile.write(chunk) else: raise requests.RequestException("Expected status code 200") pbar.close() duration = time.time() - start logger.info("Wrote {} in {:0.2f} s ({:0.2f} MB, {:0.2f} MB/s)".format( fileinfo.filename, duration, fileinfo.size / 10 ** 6, fileinfo.size / (duration * 10 ** 6))) def _update_pbar(pbar, val): update_val = max(int(val), 1) try: pbar.update(update_val) except Exception as e: # oh, c'mon TQDM, progress bars shouldn't crash software logger.debug("TQDM progress bar error: {}({})".format( e.__class__.__name__, e)) ########################################### # Local and remote file watcher-generators def watch_local_files(*filters, local_dir="."): list_local = partial(list_local_files, *filters, local_dir=local_dir) old_files = new_files = set(list_local()) while True: yield new_files - old_files, new_files old_files = new_files new_files = set(list_local()) def watch_remote_files(*filters, remote_dir="."): command.memory_changed() # clear change status to start list_remote = partial(command.list_files, *filters, remote_dir=remote_dir) old_files = new_files = set(list_remote()) while True: yield new_files - old_files, new_files old_files = new_files if command.memory_changed(): new_files = set(list_remote()) ##################################################### # Synchronize ONCE in the UP direction (to FlashAir) def up_by_all(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, **_): files = list_local_files(*filters, local_dir=local_dir) up_by_files(list(files), remote_dir=remote_dir) def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): """Sync a given list of local files to `remote_dir` dir""" if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files) def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync most recent file by date, time attribues""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def _sync_local_file(local_file_info, remote_dir, remote_files): local_name = local_file_info.filename local_size = local_file_info.size if local_name in remote_files: remote_file_info = remote_files[local_name] remote_size = remote_file_info.size if local_size == remote_size: logger.info( "Skipping '{}' already exists on SD card".format( local_name)) else: logger.warning( "Removing remote file {}: " "local size {} != remote size {}".format( local_name, local_size, remote_size)) upload.delete_file(remote_file_info.path) _stream_from_file(local_file_info, remote_dir) else: _stream_from_file(local_file_info, remote_dir) def _stream_from_file(fileinfo, remote_dir): logger.info("Uploading local file {} to {}".format( fileinfo.path, remote_dir)) _upload_file_safely(fileinfo, remote_dir) def _upload_file_safely(fileinfo, remote_dir): """attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error""" try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fileinfo.path) raise e def list_local_files(*filters, local_dir="."): all_entries = scandir(local_dir) file_entries = (e for e in all_entries if e.is_file()) for entry in file_entries: stat = entry.stat() size = stat.st_size datetime = arrow.get(stat.st_mtime) path = str(Path(local_dir, entry.name)) info = SimpleFileInfo(local_dir, entry.name, path, size, datetime) if all(filt(info) for filt in filters): yield info def list_local_files_raw(*filters, local_dir="."): all_entries = scandir(local_dir) all_files = (e for e in all_entries if e.is_file() and all(filt(e) for filt in filters)) for entry in all_files: path = str(Path(local_dir, entry.name)) yield RawFileInfo(local_dir, entry.name, path, entry.stat().st_size) def _notify_sync(direction, files): logger.info("{:d} files to {:s}:\n{}".format( len(files), direction, "\n".join(" " + f.filename for f in files))) def _notify_sync_ready(num_old_files, from_dir, to_dir): logger.info("Ready to sync new files from {} to {} " "({:d} existing files ignored)".format( from_dir, to_dir, num_old_files))
TadLeonard/tfatool
tfatool/sync.py
_upload_file_safely
python
def _upload_file_safely(fileinfo, remote_dir): try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fileinfo.path) raise e
attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L344-L354
null
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFileInfo logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Python 3.4 compatibility via scandir backport if hasattr(os, "scandir"): scandir = os.scandir else: import scandir scandir = scandir.scandir class Direction(str, Enum): up = "upload" # upload direction down = "download" # download direction ##################################### # Synchronizing newly created files class Monitor: """Synchronizes newly created files TO or FROM FlashAir in separate threads""" def __init__(self, *filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): self._filters = filters self._local_dir = local_dir self._remote_dir = remote_dir self.running = threading.Event() self.thread = None def _run(self, method): assert self.thread is None self.running.set() self.thread = threading.Thread(target=self._run_sync, args=(method,)) self.thread.start() def _run_sync(self, method): files = method(*self._filters, local_dir=self._local_dir, remote_dir=self._remote_dir) while self.running.is_set(): _, new = next(files) if not new: time.sleep(0.3) def sync_both(self): self._run(up_down_by_arrival) def sync_up(self): self._run(up_by_arrival) def sync_down(self): self._run(down_by_arrival) def stop(self): self.running.clear() def join(self): if self.thread: self.thread.join() self.thread = None def up_down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The generator yields before each upload or download actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, lfile_set = next(local_monitor) _, rfile_set = next(remote_monitor) _notify_sync_ready(len(lfile_set), local_dir, remote_dir) _notify_sync_ready(len(rfile_set), remote_dir, local_dir) processed = set() for new_local, new_remote in zip(local_monitor, remote_monitor): new_local, local_set = new_local local_arrivals = {f for f in new_local if f.filename not in processed} yield Direction.up, local_arrivals if local_arrivals: new_names.update(f.filename for f in local_arrivals) _notify_sync(Direction.up, local_arrivals) up_by_files(local_arrivals, remote_dir) _notify_sync_ready(len(local_set), local_dir, remote_dir) new_remote, remote_set = new_remote remote_arrivals = {f for f in new_remote if f.filename not in processed} yield Direction.down, remote_arrivals if remote_arrivals: new_names.update(f.filename for f in remote_arrivals) _notify_sync(Direction.down, remote_arrivals) yield Direction.down, remote_arrivals down_by_files(remote_arrivals, local_dir) _notify_sync_ready(len(remote_set), remote_dir, local_dir) def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.""" local_monitor = watch_local_files(*filters, local_dir=local_dir) _, file_set = next(local_monitor) _notify_sync_ready(len(file_set), local_dir, remote_dir) for new_arrivals, file_set in local_monitor: yield Direction.up, new_arrivals # where new_arrivals is possibly empty if new_arrivals: _notify_sync(Direction.up, new_arrivals) up_by_files(new_arrivals, remote_dir) _notify_sync_ready(len(file_set), local_dir, remote_dir) def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place.""" remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, file_set = next(remote_monitor) _notify_sync_ready(len(file_set), remote_dir, local_dir) for new_arrivals, file_set in remote_monitor: if new_arrivals: _notify_sync(Direction.down, new_arrivals) down_by_files(new_arrivals, local_dir) _notify_sync_ready(len(file_set), remote_dir, local_dir) yield Direction.down, new_arrivals ################################################### # Sync ONCE in the DOWN (from FlashAir) direction def down_by_all(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", **_): files = command.list_files(*filters, remote_dir=remote_dir) down_by_files(files, local_dir=local_dir) def down_by_files(to_sync, local_dir="."): """Sync a given list of files from `command.list_files` to `local_dir` dir""" for f in to_sync: _sync_remote_file(local_dir, f) def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync most recent file by date, time attribues""" files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync files whose filename attribute is highest in alphanumeric order""" files = command.list_files(*filters, remote_dir=remote_dir) greatest = sorted(files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir) def _sync_remote_file(local_dir, remote_file_info): local = Path(local_dir, remote_file_info.filename) local_name = str(local) remote_size = remote_file_info.size if local.exists(): local_size = local.stat().st_size if local.stat().st_size == remote_size: logger.info( "Skipping '{}': already exists locally".format( local_name)) else: logger.warning( "Removing {}: local size {} != remote size {}".format( local_name, local_size, remote_size)) os.remove(local_name) _stream_to_file(local_name, remote_file_info) else: _stream_to_file(local_name, remote_file_info) def _stream_to_file(local_name, fileinfo): logger.info("Copying remote file {} to {}".format( fileinfo.path, local_name)) streaming_file = _get_file(fileinfo) _write_file_safely(local_name, fileinfo, streaming_file) def _get_file(fileinfo): url = urljoin(URL, fileinfo.path) logger.info("Requesting file: {}".format(url)) return requests.get(url, stream=True) def _write_file_safely(local_path, fileinfo, response): """attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error""" try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e def _write_file(local_path, fileinfo, response): start = time.time() pbar_size = fileinfo.size / (5 * 10**5) pbar = tqdm.tqdm(total=int(pbar_size)) if response.status_code == 200: with open(local_path, "wb") as outfile: for chunk in response.iter_content(5*10**5): progress = len(chunk) / (5 * 10**5) _update_pbar(pbar, progress) outfile.write(chunk) else: raise requests.RequestException("Expected status code 200") pbar.close() duration = time.time() - start logger.info("Wrote {} in {:0.2f} s ({:0.2f} MB, {:0.2f} MB/s)".format( fileinfo.filename, duration, fileinfo.size / 10 ** 6, fileinfo.size / (duration * 10 ** 6))) def _update_pbar(pbar, val): update_val = max(int(val), 1) try: pbar.update(update_val) except Exception as e: # oh, c'mon TQDM, progress bars shouldn't crash software logger.debug("TQDM progress bar error: {}({})".format( e.__class__.__name__, e)) ########################################### # Local and remote file watcher-generators def watch_local_files(*filters, local_dir="."): list_local = partial(list_local_files, *filters, local_dir=local_dir) old_files = new_files = set(list_local()) while True: yield new_files - old_files, new_files old_files = new_files new_files = set(list_local()) def watch_remote_files(*filters, remote_dir="."): command.memory_changed() # clear change status to start list_remote = partial(command.list_files, *filters, remote_dir=remote_dir) old_files = new_files = set(list_remote()) while True: yield new_files - old_files, new_files old_files = new_files if command.memory_changed(): new_files = set(list_remote()) ##################################################### # Synchronize ONCE in the UP direction (to FlashAir) def up_by_all(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, **_): files = list_local_files(*filters, local_dir=local_dir) up_by_files(list(files), remote_dir=remote_dir) def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): """Sync a given list of local files to `remote_dir` dir""" if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files) def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync most recent file by date, time attribues""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync files whose filename attribute is highest in alphanumeric order""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_files) def _sync_local_file(local_file_info, remote_dir, remote_files): local_name = local_file_info.filename local_size = local_file_info.size if local_name in remote_files: remote_file_info = remote_files[local_name] remote_size = remote_file_info.size if local_size == remote_size: logger.info( "Skipping '{}' already exists on SD card".format( local_name)) else: logger.warning( "Removing remote file {}: " "local size {} != remote size {}".format( local_name, local_size, remote_size)) upload.delete_file(remote_file_info.path) _stream_from_file(local_file_info, remote_dir) else: _stream_from_file(local_file_info, remote_dir) def _stream_from_file(fileinfo, remote_dir): logger.info("Uploading local file {} to {}".format( fileinfo.path, remote_dir)) _upload_file_safely(fileinfo, remote_dir) def list_local_files(*filters, local_dir="."): all_entries = scandir(local_dir) file_entries = (e for e in all_entries if e.is_file()) for entry in file_entries: stat = entry.stat() size = stat.st_size datetime = arrow.get(stat.st_mtime) path = str(Path(local_dir, entry.name)) info = SimpleFileInfo(local_dir, entry.name, path, size, datetime) if all(filt(info) for filt in filters): yield info def list_local_files_raw(*filters, local_dir="."): all_entries = scandir(local_dir) all_files = (e for e in all_entries if e.is_file() and all(filt(e) for filt in filters)) for entry in all_files: path = str(Path(local_dir, entry.name)) yield RawFileInfo(local_dir, entry.name, path, entry.stat().st_size) def _notify_sync(direction, files): logger.info("{:d} files to {:s}:\n{}".format( len(files), direction, "\n".join(" " + f.filename for f in files))) def _notify_sync_ready(num_old_files, from_dir, to_dir): logger.info("Ready to sync new files from {} to {} " "({:d} existing files ignored)".format( from_dir, to_dir, num_old_files))
TadLeonard/tfatool
tfatool/config.py
config
python
def config(param_map, mastercode=DEFAULT_MASTERCODE): pmap = {Config.mastercode: mastercode} pmap.update(param_map) processed_params = dict(_process_params(pmap)) return processed_params
Takes a dictionary of {Config.key: value} and returns a dictionary of processed keys and values to be used in the construction of a POST request to FlashAir's config.cgi
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/config.py#L8-L15
[ "def _process_params(params):\n for param, value in params.items():\n assert param in Config, \"Invalid param: {}\".format(param)\n yield param.value, value_validators[param](value)\n" ]
import logging from functools import partial from . import cgi from .info import URL, DEFAULT_MASTERCODE from .info import WifiMode, WifiModeOnBoot, ModeValue, DriveMode, Config def _process_params(params): for param, value in params.items(): assert param in Config, "Invalid param: {}".format(param) yield param.value, value_validators[param](value) def post(param_map, url=URL): """Posts a `param_map` created with `config` to the FlashAir config.cgi entrypoint""" prepped_request = _prep_post(url=url, **param_map) return cgi.send(prepped_request) _prep_post = partial(cgi.prep_post, cgi.Entrypoint.config) ###################################################### # Functions for creating config POST parameter values value_validators = {} def _validator(parameter): def wrapper(fn): value_validators[parameter] = fn return fn return wrapper @_validator(Config.wifi_timeout) def _validate_timeout(seconds: float): """Creates an int from 60000 to 4294967294 that represents a valid millisecond wireless LAN timeout""" val = int(seconds * 1000) assert 60000 <= val <= 4294967294, "Bad value: {}".format(val) return val @_validator(Config.app_info) def _validate_app_info(info: str): assert 1 <= len(info) <= 16 return info @_validator(Config.wifi_mode) def _validate_wifi_mode(mode: ModeValue): assert mode in WifiMode or mode in WifiModeOnBoot return int(mode) @_validator(Config.wifi_key) def _validate_wifi_key(network_key: str): assert 0 <= len(network_key) <= 63 return network_key @_validator(Config.wifi_ssid) def _validate_wifi_ssid(network_ssid: str): assert 1 <= len(network_ssid) <= 32 return network_ssid @_validator(Config.passthrough_key) def _validate_passthrough_key(network_key: str): assert 0 <= len(network_key) <= 63 return network_key @_validator(Config.passthrough_ssid) def _validate_passthroughssid(network_ssid: str): assert 1 <= len(network_ssid) <= 32 return network_ssid @_validator(Config.mastercode) def _validate_mastercode(code: str): assert len(code) == 12 code = code.lower() valid_chars = "0123456789abcdef" assert all(c in valid_chars for c in code) return code @_validator(Config.bootscreen_path) def _validate_bootscreen_path(path: str): return path @_validator(Config.clear_mastercode) def _validate_clear_mastercode(_): return 1 @_validator(Config.timezone) def _validate_timezone(hours_offset: int): """Creates an int from -48 to 36 that represents the timezone offset in 15-minute increments as per the FlashAir docs""" param_value = int(hours_offset * 4) assert -48 <= param_value <= 36 return param_value @_validator(Config.drive_mode) def _validate_drive_mode(mode: DriveMode): assert mode in DriveMode return int(mode)
TadLeonard/tfatool
tfatool/config.py
post
python
def post(param_map, url=URL): prepped_request = _prep_post(url=url, **param_map) return cgi.send(prepped_request)
Posts a `param_map` created with `config` to the FlashAir config.cgi entrypoint
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/config.py#L24-L28
null
import logging from functools import partial from . import cgi from .info import URL, DEFAULT_MASTERCODE from .info import WifiMode, WifiModeOnBoot, ModeValue, DriveMode, Config def config(param_map, mastercode=DEFAULT_MASTERCODE): """Takes a dictionary of {Config.key: value} and returns a dictionary of processed keys and values to be used in the construction of a POST request to FlashAir's config.cgi""" pmap = {Config.mastercode: mastercode} pmap.update(param_map) processed_params = dict(_process_params(pmap)) return processed_params def _process_params(params): for param, value in params.items(): assert param in Config, "Invalid param: {}".format(param) yield param.value, value_validators[param](value) _prep_post = partial(cgi.prep_post, cgi.Entrypoint.config) ###################################################### # Functions for creating config POST parameter values value_validators = {} def _validator(parameter): def wrapper(fn): value_validators[parameter] = fn return fn return wrapper @_validator(Config.wifi_timeout) def _validate_timeout(seconds: float): """Creates an int from 60000 to 4294967294 that represents a valid millisecond wireless LAN timeout""" val = int(seconds * 1000) assert 60000 <= val <= 4294967294, "Bad value: {}".format(val) return val @_validator(Config.app_info) def _validate_app_info(info: str): assert 1 <= len(info) <= 16 return info @_validator(Config.wifi_mode) def _validate_wifi_mode(mode: ModeValue): assert mode in WifiMode or mode in WifiModeOnBoot return int(mode) @_validator(Config.wifi_key) def _validate_wifi_key(network_key: str): assert 0 <= len(network_key) <= 63 return network_key @_validator(Config.wifi_ssid) def _validate_wifi_ssid(network_ssid: str): assert 1 <= len(network_ssid) <= 32 return network_ssid @_validator(Config.passthrough_key) def _validate_passthrough_key(network_key: str): assert 0 <= len(network_key) <= 63 return network_key @_validator(Config.passthrough_ssid) def _validate_passthroughssid(network_ssid: str): assert 1 <= len(network_ssid) <= 32 return network_ssid @_validator(Config.mastercode) def _validate_mastercode(code: str): assert len(code) == 12 code = code.lower() valid_chars = "0123456789abcdef" assert all(c in valid_chars for c in code) return code @_validator(Config.bootscreen_path) def _validate_bootscreen_path(path: str): return path @_validator(Config.clear_mastercode) def _validate_clear_mastercode(_): return 1 @_validator(Config.timezone) def _validate_timezone(hours_offset: int): """Creates an int from -48 to 36 that represents the timezone offset in 15-minute increments as per the FlashAir docs""" param_value = int(hours_offset * 4) assert -48 <= param_value <= 36 return param_value @_validator(Config.drive_mode) def _validate_drive_mode(mode: DriveMode): assert mode in DriveMode return int(mode)
TadLeonard/tfatool
tfatool/config.py
_validate_timeout
python
def _validate_timeout(seconds: float): val = int(seconds * 1000) assert 60000 <= val <= 4294967294, "Bad value: {}".format(val) return val
Creates an int from 60000 to 4294967294 that represents a valid millisecond wireless LAN timeout
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/config.py#L48-L53
null
import logging from functools import partial from . import cgi from .info import URL, DEFAULT_MASTERCODE from .info import WifiMode, WifiModeOnBoot, ModeValue, DriveMode, Config def config(param_map, mastercode=DEFAULT_MASTERCODE): """Takes a dictionary of {Config.key: value} and returns a dictionary of processed keys and values to be used in the construction of a POST request to FlashAir's config.cgi""" pmap = {Config.mastercode: mastercode} pmap.update(param_map) processed_params = dict(_process_params(pmap)) return processed_params def _process_params(params): for param, value in params.items(): assert param in Config, "Invalid param: {}".format(param) yield param.value, value_validators[param](value) def post(param_map, url=URL): """Posts a `param_map` created with `config` to the FlashAir config.cgi entrypoint""" prepped_request = _prep_post(url=url, **param_map) return cgi.send(prepped_request) _prep_post = partial(cgi.prep_post, cgi.Entrypoint.config) ###################################################### # Functions for creating config POST parameter values value_validators = {} def _validator(parameter): def wrapper(fn): value_validators[parameter] = fn return fn return wrapper @_validator(Config.wifi_timeout) @_validator(Config.app_info) def _validate_app_info(info: str): assert 1 <= len(info) <= 16 return info @_validator(Config.wifi_mode) def _validate_wifi_mode(mode: ModeValue): assert mode in WifiMode or mode in WifiModeOnBoot return int(mode) @_validator(Config.wifi_key) def _validate_wifi_key(network_key: str): assert 0 <= len(network_key) <= 63 return network_key @_validator(Config.wifi_ssid) def _validate_wifi_ssid(network_ssid: str): assert 1 <= len(network_ssid) <= 32 return network_ssid @_validator(Config.passthrough_key) def _validate_passthrough_key(network_key: str): assert 0 <= len(network_key) <= 63 return network_key @_validator(Config.passthrough_ssid) def _validate_passthroughssid(network_ssid: str): assert 1 <= len(network_ssid) <= 32 return network_ssid @_validator(Config.mastercode) def _validate_mastercode(code: str): assert len(code) == 12 code = code.lower() valid_chars = "0123456789abcdef" assert all(c in valid_chars for c in code) return code @_validator(Config.bootscreen_path) def _validate_bootscreen_path(path: str): return path @_validator(Config.clear_mastercode) def _validate_clear_mastercode(_): return 1 @_validator(Config.timezone) def _validate_timezone(hours_offset: int): """Creates an int from -48 to 36 that represents the timezone offset in 15-minute increments as per the FlashAir docs""" param_value = int(hours_offset * 4) assert -48 <= param_value <= 36 return param_value @_validator(Config.drive_mode) def _validate_drive_mode(mode: DriveMode): assert mode in DriveMode return int(mode)
TadLeonard/tfatool
tfatool/util.py
parse_datetime
python
def parse_datetime(datetime_input): date_els, time_els = _split_datetime(datetime_input) date_vals = _parse_date(date_els) time_vals = _parse_time(time_els) vals = tuple(date_vals) + tuple(time_vals) return arrow.get(*vals)
The arrow library is sadly not good enough to parse certain date strings. It even gives unexpected results for partial date strings such as '2015-01' or just '2015', which I think should be seen as 'the first moment of 2014'. This function should overcome those limitations.
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/util.py#L7-L17
[ "def _split_datetime(datetime_input):\n dt_input = datetime_input.split(\" \")\n if len(dt_input) == 1:\n dt_input.append(\"\")\n date_input, time_input = dt_input\n if \":\" in date_input:\n date_input, time_input = time_input, date_input\n if not date_input:\n date_input = arrow.now().format(\"YYYY-MM-DD\")\n sep = \"-\"\n if not time_input:\n time_input = \"00:00:00\"\n\n if \"/\" in date_input:\n sep = \"/\"\n elif \"-\" in date_input:\n sep = \"-\"\n elif \".\" in date_input:\n sep = \".\"\n elif len(date_input) == 4:\n date_input = \"{}-01-01\".format(date_input) # assume YYYY\n sep = \"-\"\n else:\n raise ValueError(\"Date '{}' can't be understood\".format(date_input))\n if time_input and \":\" not in time_input:\n raise ValueError(\"Time '{}' has no ':'-separators\".format(time_input))\n d, t = date_input.split(sep), time_input.split(\":\")\n return tuple(d), tuple(t)\n", "def _parse_date(date_els):\n if len(date_els) == 2:\n # assumed to be year-month or month-year\n a, b = date_els\n if _is_year(a):\n date_vals = a, b, 1 # 1st of month assumed\n elif _is_year(b):\n date_vals = b, a, 1 # 1st of month assumed\n else:\n date_vals = arrow.now().year, a, b # assumed M/D of this year\n elif len(date_els) == 3:\n # assumed to be year-month-day or month-day-year\n a, b, c = date_els\n if _is_year(a):\n date_vals = a, b, c\n elif _is_year(c):\n date_vals = c, a, b\n else:\n raise ValueError(\"Date '{}' can't be understood\".format(date_els))\n else:\n raise ValueError(\"Date '{}' can't be understood\".format(date_els))\n return map(int, date_vals)\n", "def _parse_time(time_els):\n if len(time_els) == 1:\n time_vals = 0, 0, 0 \n elif len(time_els) == 2:\n time_vals = time_els + (0,) # assumed H:M\n elif len(time_els) == 3:\n time_vals = time_els # H:M:S\n else:\n raise ValueError(\"Time '{}' can't be understood\".format(time_els))\n return map(int, time_vals)\n" ]
import arrow from itertools import groupby from operator import attrgetter, itemgetter def _split_datetime(datetime_input): dt_input = datetime_input.split(" ") if len(dt_input) == 1: dt_input.append("") date_input, time_input = dt_input if ":" in date_input: date_input, time_input = time_input, date_input if not date_input: date_input = arrow.now().format("YYYY-MM-DD") sep = "-" if not time_input: time_input = "00:00:00" if "/" in date_input: sep = "/" elif "-" in date_input: sep = "-" elif "." in date_input: sep = "." elif len(date_input) == 4: date_input = "{}-01-01".format(date_input) # assume YYYY sep = "-" else: raise ValueError("Date '{}' can't be understood".format(date_input)) if time_input and ":" not in time_input: raise ValueError("Time '{}' has no ':'-separators".format(time_input)) d, t = date_input.split(sep), time_input.split(":") return tuple(d), tuple(t) def _parse_date(date_els): if len(date_els) == 2: # assumed to be year-month or month-year a, b = date_els if _is_year(a): date_vals = a, b, 1 # 1st of month assumed elif _is_year(b): date_vals = b, a, 1 # 1st of month assumed else: date_vals = arrow.now().year, a, b # assumed M/D of this year elif len(date_els) == 3: # assumed to be year-month-day or month-day-year a, b, c = date_els if _is_year(a): date_vals = a, b, c elif _is_year(c): date_vals = c, a, b else: raise ValueError("Date '{}' can't be understood".format(date_els)) else: raise ValueError("Date '{}' can't be understood".format(date_els)) return map(int, date_vals) def _parse_time(time_els): if len(time_els) == 1: time_vals = 0, 0, 0 elif len(time_els) == 2: time_vals = time_els + (0,) # assumed H:M elif len(time_els) == 3: time_vals = time_els # H:M:S else: raise ValueError("Time '{}' can't be understood".format(time_els)) return map(int, time_vals) def _is_year(element): return len(element) == 4 def fmt_file_rows(files): files = sorted(files, key=attrgetter("datetime")) for f in files: fname = f.filename fdate = f.datetime.format("YYYY-MM-DD") ftime = f.datetime.format("HH:mm") size = "{:> 3.02f}".format(f.size / 10**6) human = f.datetime.humanize() yield fname, fdate, ftime, size, human def get_size_units(nbytes): if nbytes >= 10**8: units, val = "GB", nbytes / 10**9 elif nbytes >= 10**5: units, val = "MB", nbytes / 10**6 elif nbytes >= 10**2: units, val = "KB", nbytes / 10**3 else: units, val = "B", nbytes return val, units
TadLeonard/tfatool
tfatool/upload.py
_encode_time
python
def _encode_time(mtime: float): dt = arrow.get(mtime) dt = dt.to("local") date_val = ((dt.year - 1980) << 9) | (dt.month << 5) | dt.day secs = dt.second + dt.microsecond / 10**6 time_val = (dt.hour << 11) | (dt.minute << 5) | math.floor(secs / 2) return (date_val << 16) | time_val
Encode a mtime float as a 32-bit FAT time
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/upload.py#L84-L91
null
import math import os import arrow from functools import partial from . import cgi from .info import DEFAULT_REMOTE_DIR, DEFAULT_MASTERCODE, URL from .info import WriteProtectMode, Upload, ResponseCode from requests import RequestException def upload_file(local_path: str, url=URL, remote_dir=DEFAULT_REMOTE_DIR): set_write_protect(WriteProtectMode.on, url=url) set_upload_dir(remote_dir, url=url) set_creation_time(local_path, url=url) post_file(local_path, url=url) set_write_protect(WriteProtectMode.off, url=url) def set_write_protect(mode: WriteProtectMode, url=URL): response = get(url=url, **{Upload.write_protect: mode}) if response.text != ResponseCode.success: raise UploadError("Failed to set write protect", response) return response def set_upload_dir(remote_dir: str, url=URL): response = get(url=url, **{Upload.directory: remote_dir}) if response.text != ResponseCode.success: raise UploadError("Failed to set upload directory", response) return response def set_creation_time(local_path: str, url=URL): mtime = os.stat(local_path).st_mtime fat_time = _encode_time(mtime) encoded_time = _str_encode_time(fat_time) response = get(url=url, **{Upload.creation_time: encoded_time}) if response.text != ResponseCode.success: raise UploadError("Failed to set creation time", response) return response def post_file(local_path: str, url=URL): files = {local_path: open(local_path, "rb")} response = post(url=url, req_kwargs=dict(files=files)) if response.status_code != 200: raise UploadError("Failed to post file", response) return response def delete_file(remote_file: str, url=URL): response = get(url=url, **{Upload.delete: remote_file}) if response.status_code != 200: raise UploadError("Failed to delete file", response) return response def post(url=URL, req_kwargs=None, **params): prepped_request = prep_post(url, req_kwargs, **params) return cgi.send(prepped_request) def get(url=URL, req_kwargs=None, **params): prepped_request = prep_get(url, req_kwargs, **params) return cgi.send(prepped_request) def prep_req(prep_method, url=URL, req_kwargs=None, **params): req_kwargs = req_kwargs or {} params = {key.value: value for key, value in params.items()} return prep_method(url=url, req_kwargs=req_kwargs, **params) prep_get = partial(prep_req, partial(cgi.prep_get, cgi.Entrypoint.upload)) prep_post = partial(prep_req, partial(cgi.prep_post, cgi.Entrypoint.upload)) def _str_encode_time(encoded_time: int): return "{0:#0{1}x}".format(encoded_time, 10) class UploadError(RequestException): def __init__(self, msg, response): self.msg = msg self.response = response def __str__(self): return "{}: {}".format(self.msg, self.response) __repr__ = __str__
TadLeonard/tfatool
tfatool/command.py
memory_changed
python
def memory_changed(url=URL): response = _get(Operation.memory_changed, url) try: return int(response.text) == 1 except ValueError: raise IOError("Likely no FlashAir connection, " "memory changed CGI command failed")
Returns True if memory has been written to, False otherwise
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/command.py#L46-L53
[ "def _get(operation: Operation, url=URL, **params):\n \"\"\"HTTP GET of the FlashAir command.cgi entrypoint\"\"\"\n prepped_request = _prep_get(operation, url=url, **params)\n return cgi.send(prepped_request)\n" ]
import logging import arrow from pathlib import PurePosixPath from collections import namedtuple from . import cgi from .info import URL, DEFAULT_REMOTE_DIR from .info import WifiMode, WifiModeOnBoot, ModeValue, Operation from .info import FileInfo, RawFileInfo logger = logging.getLogger(__name__) ################## # command.cgi API def map_files(*filters, remote_dir=DEFAULT_REMOTE_DIR, url=URL): files = list_files(*filters, remote_dir=remote_dir, url=url) return {f.filename: f for f in files} def list_files(*filters, remote_dir=DEFAULT_REMOTE_DIR, url=URL): response = _get(Operation.list_files, url, DIR=remote_dir) files = _split_file_list(response.text) return (f for f in files if all(filt(f) for filt in filters)) def map_files_raw(*filters, remote_dir=DEFAULT_REMOTE_DIR, url=URL): files = list_files_raw(*filters, remote_dir=remote_dir, url=url) return {f.filename: f for f in files} def list_files_raw(*filters, remote_dir=DEFAULT_REMOTE_DIR, url=URL): response = _get(Operation.list_files, url, DIR=remote_dir) files = _split_file_list_raw(response.text) return (f for f in files if all(filt(f) for filt in filters)) def count_files(remote_dir=DEFAULT_REMOTE_DIR, url=URL): response = _get(Operation.count_files, url, DIR=remote_dir) return int(response.text) def get_ssid(url=URL): return _get(Operation.get_ssid, url).text def get_password(url=URL): return _get(Operation.get_password, url).text def get_mac(url=URL): return _get(Operation.get_mac, url).text def get_browser_lang(url=URL): return _get(Operation.get_browser_lang, url).text def get_fw_version(url=URL): return _get(Operation.get_fw_version, url).text def get_ctrl_image(url=URL): return _get(Operation.get_ctrl_image, url).text def get_wifi_mode(url=URL) -> WifiMode: mode_value = int(_get(Operation.get_wifi_mode, url).text) all_modes = list(WifiMode) + list(WifiModeOnBoot) for mode in all_modes: if mode.value == mode_value: return mode raise ValueError("Uknown mode: {:d}".format(mode_value)) ##################### # API implementation def _split_file_list(text): lines = text.split("\r\n") for line in lines: groups = line.split(",") if len(groups) == 6: directory, filename, *remaining = groups remaining = map(int, remaining) size, attr_val, date_val, time_val = remaining timeinfo = _decode_time(date_val, time_val) attribute = _decode_attribute(attr_val) path = str(PurePosixPath(directory, filename)) yield FileInfo(directory, filename, path, size, attribute, timeinfo) def _split_file_list_raw(text): lines = text.split("\r\n") for line in lines: groups = line.split(",") if len(groups) == 6: directory, filename, size, *_ = groups path = str(PurePosixPath(directory, filename)) yield RawFileInfo(directory, filename, path, int(size)) def _decode_time(date_val: int, time_val: int): year = (date_val >> 9) + 1980 # 0-val is the year 1980 month = (date_val & (0b1111 << 5)) >> 5 day = date_val & 0b11111 hour = time_val >> 11 minute = ((time_val >> 5) & 0b111111) second = (time_val & 0b11111) * 2 try: decoded = arrow.get(year, month, day, hour, minute, second, tzinfo="local") except ValueError: year = max(1980, year) # FAT32 doesn't go higher month = min(max(1, month), 12) day = max(1, day) decoded = arrow.get(year, month, day, hour, minute, second) return decoded AttrInfo = namedtuple( "AttrInfo", "archive directly volume system_file hidden_file read_only") def _decode_attribute(attr_val: int): bit_positions = reversed(range(6)) bit_flags = [bool(attr_val & (1 << bit)) for bit in bit_positions] return AttrInfo(*bit_flags) ######################################## # command.cgi request prepping, sending def _get(operation: Operation, url=URL, **params): """HTTP GET of the FlashAir command.cgi entrypoint""" prepped_request = _prep_get(operation, url=url, **params) return cgi.send(prepped_request) def _prep_get(operation: Operation, url=URL, **params): params.update(op=int(operation)) # op param required return cgi.prep_get(cgi.Entrypoint.command, url=url, **params)
TadLeonard/tfatool
tfatool/command.py
_get
python
def _get(operation: Operation, url=URL, **params): prepped_request = _prep_get(operation, url=url, **params) return cgi.send(prepped_request)
HTTP GET of the FlashAir command.cgi entrypoint
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/command.py#L147-L150
[ "def _prep_get(operation: Operation, url=URL, **params):\n params.update(op=int(operation)) # op param required\n return cgi.prep_get(cgi.Entrypoint.command, url=url, **params)\n" ]
import logging import arrow from pathlib import PurePosixPath from collections import namedtuple from . import cgi from .info import URL, DEFAULT_REMOTE_DIR from .info import WifiMode, WifiModeOnBoot, ModeValue, Operation from .info import FileInfo, RawFileInfo logger = logging.getLogger(__name__) ################## # command.cgi API def map_files(*filters, remote_dir=DEFAULT_REMOTE_DIR, url=URL): files = list_files(*filters, remote_dir=remote_dir, url=url) return {f.filename: f for f in files} def list_files(*filters, remote_dir=DEFAULT_REMOTE_DIR, url=URL): response = _get(Operation.list_files, url, DIR=remote_dir) files = _split_file_list(response.text) return (f for f in files if all(filt(f) for filt in filters)) def map_files_raw(*filters, remote_dir=DEFAULT_REMOTE_DIR, url=URL): files = list_files_raw(*filters, remote_dir=remote_dir, url=url) return {f.filename: f for f in files} def list_files_raw(*filters, remote_dir=DEFAULT_REMOTE_DIR, url=URL): response = _get(Operation.list_files, url, DIR=remote_dir) files = _split_file_list_raw(response.text) return (f for f in files if all(filt(f) for filt in filters)) def count_files(remote_dir=DEFAULT_REMOTE_DIR, url=URL): response = _get(Operation.count_files, url, DIR=remote_dir) return int(response.text) def memory_changed(url=URL): """Returns True if memory has been written to, False otherwise""" response = _get(Operation.memory_changed, url) try: return int(response.text) == 1 except ValueError: raise IOError("Likely no FlashAir connection, " "memory changed CGI command failed") def get_ssid(url=URL): return _get(Operation.get_ssid, url).text def get_password(url=URL): return _get(Operation.get_password, url).text def get_mac(url=URL): return _get(Operation.get_mac, url).text def get_browser_lang(url=URL): return _get(Operation.get_browser_lang, url).text def get_fw_version(url=URL): return _get(Operation.get_fw_version, url).text def get_ctrl_image(url=URL): return _get(Operation.get_ctrl_image, url).text def get_wifi_mode(url=URL) -> WifiMode: mode_value = int(_get(Operation.get_wifi_mode, url).text) all_modes = list(WifiMode) + list(WifiModeOnBoot) for mode in all_modes: if mode.value == mode_value: return mode raise ValueError("Uknown mode: {:d}".format(mode_value)) ##################### # API implementation def _split_file_list(text): lines = text.split("\r\n") for line in lines: groups = line.split(",") if len(groups) == 6: directory, filename, *remaining = groups remaining = map(int, remaining) size, attr_val, date_val, time_val = remaining timeinfo = _decode_time(date_val, time_val) attribute = _decode_attribute(attr_val) path = str(PurePosixPath(directory, filename)) yield FileInfo(directory, filename, path, size, attribute, timeinfo) def _split_file_list_raw(text): lines = text.split("\r\n") for line in lines: groups = line.split(",") if len(groups) == 6: directory, filename, size, *_ = groups path = str(PurePosixPath(directory, filename)) yield RawFileInfo(directory, filename, path, int(size)) def _decode_time(date_val: int, time_val: int): year = (date_val >> 9) + 1980 # 0-val is the year 1980 month = (date_val & (0b1111 << 5)) >> 5 day = date_val & 0b11111 hour = time_val >> 11 minute = ((time_val >> 5) & 0b111111) second = (time_val & 0b11111) * 2 try: decoded = arrow.get(year, month, day, hour, minute, second, tzinfo="local") except ValueError: year = max(1980, year) # FAT32 doesn't go higher month = min(max(1, month), 12) day = max(1, day) decoded = arrow.get(year, month, day, hour, minute, second) return decoded AttrInfo = namedtuple( "AttrInfo", "archive directly volume system_file hidden_file read_only") def _decode_attribute(attr_val: int): bit_positions = reversed(range(6)) bit_flags = [bool(attr_val & (1 << bit)) for bit in bit_positions] return AttrInfo(*bit_flags) ######################################## # command.cgi request prepping, sending def _prep_get(operation: Operation, url=URL, **params): params.update(op=int(operation)) # op param required return cgi.prep_get(cgi.Entrypoint.command, url=url, **params)
python-astrodynamics/spacetrack
shovel/docs.py
watch
python
def watch(): # Start with a clean build sphinx_build['-b', 'html', '-E', 'docs', 'docs/_build/html'] & FG handler = ShellCommandTrick( shell_command='sphinx-build -b html docs docs/_build/html', patterns=['*.rst', '*.py'], ignore_patterns=['_build/*'], ignore_directories=['.tox'], drop_during_process=True) observer = Observer() observe_with(observer, handler, pathnames=['.'], recursive=True)
Renerate documentation when it changes.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/shovel/docs.py#L18-L31
null
# coding: utf-8 from __future__ import absolute_import, division, print_function import os from shutil import rmtree from plumbum import FG from plumbum.cmd import pandoc, sphinx_build from shovel import task from watchdog.observers import Observer from watchdog.tricks import ShellCommandTrick from watchdog.watchmedo import observe_with from _helpers import check_git_unchanged @task @task def gen(skipdirhtml=False): """Generate html and dirhtml output.""" docs_changelog = 'docs/changelog.rst' check_git_unchanged(docs_changelog) pandoc('--from=markdown', '--to=rst', '--output=' + docs_changelog, 'CHANGELOG.md') if not skipdirhtml: sphinx_build['-b', 'dirhtml', '-W', '-E', 'docs', 'docs/_build/dirhtml'] & FG sphinx_build['-b', 'html', '-W', '-E', 'docs', 'docs/_build/html'] & FG @task def clean(): """Clean build directory.""" rmtree('docs/_build') os.mkdir('docs/_build')
python-astrodynamics/spacetrack
shovel/docs.py
gen
python
def gen(skipdirhtml=False): docs_changelog = 'docs/changelog.rst' check_git_unchanged(docs_changelog) pandoc('--from=markdown', '--to=rst', '--output=' + docs_changelog, 'CHANGELOG.md') if not skipdirhtml: sphinx_build['-b', 'dirhtml', '-W', '-E', 'docs', 'docs/_build/dirhtml'] & FG sphinx_build['-b', 'html', '-W', '-E', 'docs', 'docs/_build/html'] & FG
Generate html and dirhtml output.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/shovel/docs.py#L35-L42
null
# coding: utf-8 from __future__ import absolute_import, division, print_function import os from shutil import rmtree from plumbum import FG from plumbum.cmd import pandoc, sphinx_build from shovel import task from watchdog.observers import Observer from watchdog.tricks import ShellCommandTrick from watchdog.watchmedo import observe_with from _helpers import check_git_unchanged @task def watch(): """Renerate documentation when it changes.""" # Start with a clean build sphinx_build['-b', 'html', '-E', 'docs', 'docs/_build/html'] & FG handler = ShellCommandTrick( shell_command='sphinx-build -b html docs docs/_build/html', patterns=['*.rst', '*.py'], ignore_patterns=['_build/*'], ignore_directories=['.tox'], drop_during_process=True) observer = Observer() observe_with(observer, handler, pathnames=['.'], recursive=True) @task @task def clean(): """Clean build directory.""" rmtree('docs/_build') os.mkdir('docs/_build')
python-astrodynamics/spacetrack
shovel/_helpers.py
check_git_unchanged
python
def check_git_unchanged(filename, yes=False): if check_staged(filename): s = 'There are staged changes in {}, overwrite? [y/n] '.format(filename) if yes or input(s) in ('y', 'yes'): return else: raise RuntimeError('There are staged changes in ' '{}, aborting.'.format(filename)) if check_unstaged(filename): s = 'There are unstaged changes in {}, overwrite? [y/n] '.format(filename) if yes or input(s) in ('y', 'yes'): return else: raise RuntimeError('There are unstaged changes in ' '{}, aborting.'.format(filename))
Check git to avoid overwriting user changes.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/shovel/_helpers.py#L7-L22
[ "def check_staged(filename=None):\n \"\"\"Check if there are 'changes to be committed' in the index.\"\"\"\n retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD',\n filename].run(retcode=None)\n if retcode == 1:\n return True\n elif retcode == 0:\n return False\n else:\n raise RuntimeError(stdout)\n", "def check_unstaged(filename):\n \"\"\"Check if there are 'changes not staged for commit' in the working\n directory.\n \"\"\"\n retcode, _, stdout = git['diff-files', '--quiet',\n filename].run(retcode=None)\n if retcode == 1:\n return True\n elif retcode == 0:\n return False\n else:\n raise RuntimeError(stdout)\n" ]
# coding: utf-8 from __future__ import absolute_import, division, print_function from plumbum.cmd import git def check_staged(filename=None): """Check if there are 'changes to be committed' in the index.""" retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD', filename].run(retcode=None) if retcode == 1: return True elif retcode == 0: return False else: raise RuntimeError(stdout) def check_unstaged(filename): """Check if there are 'changes not staged for commit' in the working directory. """ retcode, _, stdout = git['diff-files', '--quiet', filename].run(retcode=None) if retcode == 1: return True elif retcode == 0: return False else: raise RuntimeError(stdout)
python-astrodynamics/spacetrack
shovel/_helpers.py
check_staged
python
def check_staged(filename=None): retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD', filename].run(retcode=None) if retcode == 1: return True elif retcode == 0: return False else: raise RuntimeError(stdout)
Check if there are 'changes to be committed' in the index.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/shovel/_helpers.py#L25-L34
null
# coding: utf-8 from __future__ import absolute_import, division, print_function from plumbum.cmd import git def check_git_unchanged(filename, yes=False): """Check git to avoid overwriting user changes.""" if check_staged(filename): s = 'There are staged changes in {}, overwrite? [y/n] '.format(filename) if yes or input(s) in ('y', 'yes'): return else: raise RuntimeError('There are staged changes in ' '{}, aborting.'.format(filename)) if check_unstaged(filename): s = 'There are unstaged changes in {}, overwrite? [y/n] '.format(filename) if yes or input(s) in ('y', 'yes'): return else: raise RuntimeError('There are unstaged changes in ' '{}, aborting.'.format(filename)) def check_unstaged(filename): """Check if there are 'changes not staged for commit' in the working directory. """ retcode, _, stdout = git['diff-files', '--quiet', filename].run(retcode=None) if retcode == 1: return True elif retcode == 0: return False else: raise RuntimeError(stdout)
python-astrodynamics/spacetrack
spacetrack/aio.py
_raise_for_status
python
async def _raise_for_status(response): try: response.raise_for_status() except aiohttp.ClientResponseError as exc: reason = response.reason spacetrack_error_msg = None try: json = await response.json() if isinstance(json, Mapping): spacetrack_error_msg = json['error'] except (ValueError, KeyError, aiohttp.ClientResponseError): pass if not spacetrack_error_msg: spacetrack_error_msg = await response.text() if spacetrack_error_msg: reason += '\nSpace-Track response:\n' + spacetrack_error_msg payload = dict( code=response.status, message=reason, headers=response.headers, ) # history attribute is only aiohttp >= 2.1 try: payload['history'] = exc.history except AttributeError: pass raise aiohttp.ClientResponseError(**payload)
Raise an appropriate error for a given response. Arguments: response (:py:class:`aiohttp.ClientResponse`): The API response. Raises: :py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate error for the response's status. This function was taken from the aslack project and modified. The original copyright notice: Copyright (c) 2015, Jonathan Sharpe Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/aio.py#L349-L409
null
# coding: utf-8 from __future__ import absolute_import, division, print_function import asyncio import ssl import time from collections.abc import AsyncIterator, Mapping import aiohttp import aiohttp.web_exceptions import requests.certs from aiohttp.helpers import parse_mimetype from .base import AuthenticationError, SpaceTrackClient, logger from .operators import _stringify_predicate_value class AsyncSpaceTrackClient(SpaceTrackClient): """Asynchronous SpaceTrack client class. This class should be considered experimental. It must be closed by calling :meth:`~spacetrack.aio.AsyncSpaceTrackClient.close`. Alternatively, instances of this class can be used as a context manager. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #api-requestClasses .. attribute:: session :class:`aiohttp.ClientSession` instance. """ @staticmethod def _create_session(): # Use requests/certifi CA file ctx = ssl.create_default_context(cafile=requests.certs.where()) connector = aiohttp.TCPConnector(ssl_context=ctx) return aiohttp.ClientSession(connector=connector) async def _ratelimit_callback(self, until): duration = int(round(until - time.time())) logger.info('Rate limit reached. Sleeping for {:d} seconds.', duration) if self.callback is not None: await self.callback(until) async def authenticate(self): if not self._authenticated: login_url = self.base_url + 'ajaxauth/login' data = {'identity': self.identity, 'password': self.password} resp = await self.session.post(login_url, data=data) await _raise_for_status(resp) # If login failed, we get a JSON response with {'Login': 'Failed'} resp_data = await resp.json() if isinstance(resp_data, Mapping): if resp_data.get('Login', None) == 'Failed': raise AuthenticationError() self._authenticated = True async def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): """Generic Space-Track query coroutine. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **st) st.basicspacedata.tle_publish(*args, **st) st.file(*args, **st) st.fileshare.file(*args, **st) st.spephemeris.file(*args, **st) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **st) st.generic_request('tle_publish', *args, controller='basicspacedata', **st) st.generic_request('file', *args, **st) st.generic_request('file', *args, controller='fileshare', **st) st.generic_request('file', *args, controller='spephemeris', **st) Parameters: class_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = AsyncSpaceTrackClient(...) await spacetrack.tle.get_predicates() # or await spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned! """ if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) await self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: predicates = await self.get_predicates(class_) predicate_fields = {p.name for p in predicates} valid_fields = predicate_fields | {p.name for p in self.rest_predicates} else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(url) resp = await self._ratelimited_get(url) await _raise_for_status(resp) if iter_lines: return _AsyncLineIterator(resp, decode_unicode=decode) elif iter_content: return _AsyncChunkIterator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = await resp.text() data = data.replace('\r', '') else: data = await resp.read() return data else: data = await resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates) async def _ratelimited_get(self, *args, **kwargs): async with self._ratelimiter: resp = await self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status == 500: text = await resp.text() # Let's only retry if the error page tells us it's a rate limit # violation.in if 'violated your query rate limit' in text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period asyncio.ensure_future(self._ratelimit_callback(until)) await asyncio.sleep(self._ratelimiter.period) # Now retry async with self._ratelimiter: resp = await self.session.get(*args, **kwargs) return resp async def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ await self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) resp = await self._ratelimited_get(url) await _raise_for_status(resp) resp_json = await resp.json() return resp_json['data'] async def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = await self._download_predicate_data( class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_] def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def close(self): """Close aiohttp session.""" self.session.close() class _AsyncContentIteratorMixin(AsyncIterator): """Asynchronous iterator mixin for Space-Track aiohttp response.""" def __init__(self, response, decode_unicode): self.response = response self.decode_unicode = decode_unicode def get_encoding(self): ctype = self.response.headers.get('content-type', '').lower() mtype, stype, _, params = parse_mimetype(ctype) # Fallback to UTF-8 return params.get('charset', 'UTF-8') async def __anext__(self): raise NotImplementedError class _AsyncLineIterator(_AsyncContentIteratorMixin): """Asynchronous line iterator for Space-Track streamed responses.""" async def __anext__(self): try: data = await self.response.content.__anext__() except StopAsyncIteration: self.response.close() raise if self.decode_unicode: data = data.decode(self.get_encoding()) # Strip newlines data = data.rstrip('\r\n') return data class _AsyncChunkIterator(_AsyncContentIteratorMixin): """Asynchronous chunk iterator for Space-Track streamed responses.""" def __init__(self, *args, chunk_size=100 * 1024, **kwargs): super().__init__(*args, **kwargs) self.chunk_size = chunk_size async def __anext__(self): content = self.response.content try: data = await content.iter_chunked(self.chunk_size).__anext__() except StopAsyncIteration: self.response.close() raise if self.decode_unicode: data = data.decode(self.get_encoding()) # Replace CRLF newlines with LF, Python will handle # platform specific newlines if written to file. data = data.replace('\r\n', '\n') # Chunk could be ['...\r', '\n...'], strip trailing \r data = data.rstrip('\r') return data
python-astrodynamics/spacetrack
spacetrack/aio.py
AsyncSpaceTrackClient.generic_request
python
async def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) await self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: predicates = await self.get_predicates(class_) predicate_fields = {p.name for p in predicates} valid_fields = predicate_fields | {p.name for p in self.rest_predicates} else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(url) resp = await self._ratelimited_get(url) await _raise_for_status(resp) if iter_lines: return _AsyncLineIterator(resp, decode_unicode=decode) elif iter_content: return _AsyncChunkIterator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = await resp.text() data = data.replace('\r', '') else: data = await resp.read() return data else: data = await resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates)
Generic Space-Track query coroutine. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **st) st.basicspacedata.tle_publish(*args, **st) st.file(*args, **st) st.fileshare.file(*args, **st) st.spephemeris.file(*args, **st) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **st) st.generic_request('tle_publish', *args, controller='basicspacedata', **st) st.generic_request('file', *args, **st) st.generic_request('file', *args, controller='fileshare', **st) st.generic_request('file', *args, controller='spephemeris', **st) Parameters: class_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = AsyncSpaceTrackClient(...) await spacetrack.tle.get_predicates() # or await spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned!
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/aio.py#L70-L213
[ "def _stringify_predicate_value(value):\n \"\"\"Convert Python objects to Space-Track compatible strings\n\n - Booleans (``True`` -> ``'true'``)\n - Sequences (``[25544, 34602]`` -> ``'25544,34602'``)\n - dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)\n - ``None`` -> ``'null-val'``\n \"\"\"\n if isinstance(value, bool):\n return str(value).lower()\n elif isinstance(value, Sequence) and not isinstance(value, six.string_types):\n return ','.join(_stringify_predicate_value(x) for x in value)\n elif isinstance(value, datetime.datetime):\n return value.isoformat(sep=' ')\n elif isinstance(value, datetime.date):\n return value.isoformat()\n elif value is None:\n return 'null-val'\n else:\n return str(value)\n", "async def _raise_for_status(response):\n \"\"\"Raise an appropriate error for a given response.\n\n Arguments:\n response (:py:class:`aiohttp.ClientResponse`): The API response.\n\n Raises:\n :py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate\n error for the response's status.\n\n This function was taken from the aslack project and modified. The original\n copyright notice:\n\n Copyright (c) 2015, Jonathan Sharpe\n\n Permission to use, copy, modify, and/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n \"\"\"\n\n try:\n response.raise_for_status()\n except aiohttp.ClientResponseError as exc:\n reason = response.reason\n\n spacetrack_error_msg = None\n\n try:\n json = await response.json()\n if isinstance(json, Mapping):\n spacetrack_error_msg = json['error']\n except (ValueError, KeyError, aiohttp.ClientResponseError):\n pass\n\n if not spacetrack_error_msg:\n spacetrack_error_msg = await response.text()\n\n if spacetrack_error_msg:\n reason += '\\nSpace-Track response:\\n' + spacetrack_error_msg\n\n payload = dict(\n code=response.status,\n message=reason,\n headers=response.headers,\n )\n\n # history attribute is only aiohttp >= 2.1\n try:\n payload['history'] = exc.history\n except AttributeError:\n pass\n\n raise aiohttp.ClientResponseError(**payload)\n", "async def authenticate(self):\n if not self._authenticated:\n login_url = self.base_url + 'ajaxauth/login'\n data = {'identity': self.identity, 'password': self.password}\n resp = await self.session.post(login_url, data=data)\n\n await _raise_for_status(resp)\n\n # If login failed, we get a JSON response with {'Login': 'Failed'}\n resp_data = await resp.json()\n if isinstance(resp_data, Mapping):\n if resp_data.get('Login', None) == 'Failed':\n raise AuthenticationError()\n\n self._authenticated = True\n", "async def _ratelimited_get(self, *args, **kwargs):\n async with self._ratelimiter:\n resp = await self.session.get(*args, **kwargs)\n\n # It's possible that Space-Track will return HTTP status 500 with a\n # query rate limit violation. This can happen if a script is cancelled\n # before it has finished sleeping to satisfy the rate limit and it is\n # started again.\n #\n # Let's catch this specific instance and retry once if it happens.\n if resp.status == 500:\n text = await resp.text()\n\n # Let's only retry if the error page tells us it's a rate limit\n # violation.in\n if 'violated your query rate limit' in text:\n # Mimic the RateLimiter callback behaviour.\n until = time.time() + self._ratelimiter.period\n asyncio.ensure_future(self._ratelimit_callback(until))\n await asyncio.sleep(self._ratelimiter.period)\n\n # Now retry\n async with self._ratelimiter:\n resp = await self.session.get(*args, **kwargs)\n\n return resp\n", "async def get_predicates(self, class_, controller=None):\n \"\"\"Get full predicate information for given request class, and cache\n for subsequent calls.\n \"\"\"\n if class_ not in self._predicates:\n if controller is None:\n controller = self._find_controller(class_)\n else:\n classes = self.request_controllers.get(controller, None)\n if classes is None:\n raise ValueError(\n 'Unknown request controller {!r}'.format(controller))\n if class_ not in classes:\n raise ValueError(\n 'Unknown request class {!r}'.format(class_))\n\n predicates_data = await self._download_predicate_data(\n class_, controller)\n predicate_objects = self._parse_predicates_data(predicates_data)\n self._predicates[class_] = predicate_objects\n\n return self._predicates[class_]\n", "def _find_controller(self, class_):\n \"\"\"Find first controller that matches given request class.\n\n Order is specified by the keys of\n ``SpaceTrackClient.request_controllers``\n (:class:`~collections.OrderedDict`)\n \"\"\"\n for controller, classes in self.request_controllers.items():\n if class_ in classes:\n return controller\n" ]
class AsyncSpaceTrackClient(SpaceTrackClient): """Asynchronous SpaceTrack client class. This class should be considered experimental. It must be closed by calling :meth:`~spacetrack.aio.AsyncSpaceTrackClient.close`. Alternatively, instances of this class can be used as a context manager. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #api-requestClasses .. attribute:: session :class:`aiohttp.ClientSession` instance. """ @staticmethod def _create_session(): # Use requests/certifi CA file ctx = ssl.create_default_context(cafile=requests.certs.where()) connector = aiohttp.TCPConnector(ssl_context=ctx) return aiohttp.ClientSession(connector=connector) async def _ratelimit_callback(self, until): duration = int(round(until - time.time())) logger.info('Rate limit reached. Sleeping for {:d} seconds.', duration) if self.callback is not None: await self.callback(until) async def authenticate(self): if not self._authenticated: login_url = self.base_url + 'ajaxauth/login' data = {'identity': self.identity, 'password': self.password} resp = await self.session.post(login_url, data=data) await _raise_for_status(resp) # If login failed, we get a JSON response with {'Login': 'Failed'} resp_data = await resp.json() if isinstance(resp_data, Mapping): if resp_data.get('Login', None) == 'Failed': raise AuthenticationError() self._authenticated = True async def _ratelimited_get(self, *args, **kwargs): async with self._ratelimiter: resp = await self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status == 500: text = await resp.text() # Let's only retry if the error page tells us it's a rate limit # violation.in if 'violated your query rate limit' in text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period asyncio.ensure_future(self._ratelimit_callback(until)) await asyncio.sleep(self._ratelimiter.period) # Now retry async with self._ratelimiter: resp = await self.session.get(*args, **kwargs) return resp async def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ await self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) resp = await self._ratelimited_get(url) await _raise_for_status(resp) resp_json = await resp.json() return resp_json['data'] async def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = await self._download_predicate_data( class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_] def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def close(self): """Close aiohttp session.""" self.session.close()
python-astrodynamics/spacetrack
spacetrack/aio.py
AsyncSpaceTrackClient._download_predicate_data
python
async def _download_predicate_data(self, class_, controller): await self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) resp = await self._ratelimited_get(url) await _raise_for_status(resp) resp_json = await resp.json() return resp_json['data']
Get raw predicate information for given request class, and cache for subsequent calls.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/aio.py#L242-L256
[ "async def _raise_for_status(response):\n \"\"\"Raise an appropriate error for a given response.\n\n Arguments:\n response (:py:class:`aiohttp.ClientResponse`): The API response.\n\n Raises:\n :py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate\n error for the response's status.\n\n This function was taken from the aslack project and modified. The original\n copyright notice:\n\n Copyright (c) 2015, Jonathan Sharpe\n\n Permission to use, copy, modify, and/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n \"\"\"\n\n try:\n response.raise_for_status()\n except aiohttp.ClientResponseError as exc:\n reason = response.reason\n\n spacetrack_error_msg = None\n\n try:\n json = await response.json()\n if isinstance(json, Mapping):\n spacetrack_error_msg = json['error']\n except (ValueError, KeyError, aiohttp.ClientResponseError):\n pass\n\n if not spacetrack_error_msg:\n spacetrack_error_msg = await response.text()\n\n if spacetrack_error_msg:\n reason += '\\nSpace-Track response:\\n' + spacetrack_error_msg\n\n payload = dict(\n code=response.status,\n message=reason,\n headers=response.headers,\n )\n\n # history attribute is only aiohttp >= 2.1\n try:\n payload['history'] = exc.history\n except AttributeError:\n pass\n\n raise aiohttp.ClientResponseError(**payload)\n", "async def authenticate(self):\n if not self._authenticated:\n login_url = self.base_url + 'ajaxauth/login'\n data = {'identity': self.identity, 'password': self.password}\n resp = await self.session.post(login_url, data=data)\n\n await _raise_for_status(resp)\n\n # If login failed, we get a JSON response with {'Login': 'Failed'}\n resp_data = await resp.json()\n if isinstance(resp_data, Mapping):\n if resp_data.get('Login', None) == 'Failed':\n raise AuthenticationError()\n\n self._authenticated = True\n", "async def _ratelimited_get(self, *args, **kwargs):\n async with self._ratelimiter:\n resp = await self.session.get(*args, **kwargs)\n\n # It's possible that Space-Track will return HTTP status 500 with a\n # query rate limit violation. This can happen if a script is cancelled\n # before it has finished sleeping to satisfy the rate limit and it is\n # started again.\n #\n # Let's catch this specific instance and retry once if it happens.\n if resp.status == 500:\n text = await resp.text()\n\n # Let's only retry if the error page tells us it's a rate limit\n # violation.in\n if 'violated your query rate limit' in text:\n # Mimic the RateLimiter callback behaviour.\n until = time.time() + self._ratelimiter.period\n asyncio.ensure_future(self._ratelimit_callback(until))\n await asyncio.sleep(self._ratelimiter.period)\n\n # Now retry\n async with self._ratelimiter:\n resp = await self.session.get(*args, **kwargs)\n\n return resp\n" ]
class AsyncSpaceTrackClient(SpaceTrackClient): """Asynchronous SpaceTrack client class. This class should be considered experimental. It must be closed by calling :meth:`~spacetrack.aio.AsyncSpaceTrackClient.close`. Alternatively, instances of this class can be used as a context manager. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #api-requestClasses .. attribute:: session :class:`aiohttp.ClientSession` instance. """ @staticmethod def _create_session(): # Use requests/certifi CA file ctx = ssl.create_default_context(cafile=requests.certs.where()) connector = aiohttp.TCPConnector(ssl_context=ctx) return aiohttp.ClientSession(connector=connector) async def _ratelimit_callback(self, until): duration = int(round(until - time.time())) logger.info('Rate limit reached. Sleeping for {:d} seconds.', duration) if self.callback is not None: await self.callback(until) async def authenticate(self): if not self._authenticated: login_url = self.base_url + 'ajaxauth/login' data = {'identity': self.identity, 'password': self.password} resp = await self.session.post(login_url, data=data) await _raise_for_status(resp) # If login failed, we get a JSON response with {'Login': 'Failed'} resp_data = await resp.json() if isinstance(resp_data, Mapping): if resp_data.get('Login', None) == 'Failed': raise AuthenticationError() self._authenticated = True async def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): """Generic Space-Track query coroutine. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **st) st.basicspacedata.tle_publish(*args, **st) st.file(*args, **st) st.fileshare.file(*args, **st) st.spephemeris.file(*args, **st) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **st) st.generic_request('tle_publish', *args, controller='basicspacedata', **st) st.generic_request('file', *args, **st) st.generic_request('file', *args, controller='fileshare', **st) st.generic_request('file', *args, controller='spephemeris', **st) Parameters: class_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = AsyncSpaceTrackClient(...) await spacetrack.tle.get_predicates() # or await spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned! """ if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) await self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: predicates = await self.get_predicates(class_) predicate_fields = {p.name for p in predicates} valid_fields = predicate_fields | {p.name for p in self.rest_predicates} else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(url) resp = await self._ratelimited_get(url) await _raise_for_status(resp) if iter_lines: return _AsyncLineIterator(resp, decode_unicode=decode) elif iter_content: return _AsyncChunkIterator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = await resp.text() data = data.replace('\r', '') else: data = await resp.read() return data else: data = await resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates) async def _ratelimited_get(self, *args, **kwargs): async with self._ratelimiter: resp = await self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status == 500: text = await resp.text() # Let's only retry if the error page tells us it's a rate limit # violation.in if 'violated your query rate limit' in text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period asyncio.ensure_future(self._ratelimit_callback(until)) await asyncio.sleep(self._ratelimiter.period) # Now retry async with self._ratelimiter: resp = await self.session.get(*args, **kwargs) return resp async def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = await self._download_predicate_data( class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_] def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def close(self): """Close aiohttp session.""" self.session.close()
python-astrodynamics/spacetrack
spacetrack/operators.py
_stringify_predicate_value
python
def _stringify_predicate_value(value): if isinstance(value, bool): return str(value).lower() elif isinstance(value, Sequence) and not isinstance(value, six.string_types): return ','.join(_stringify_predicate_value(x) for x in value) elif isinstance(value, datetime.datetime): return value.isoformat(sep=' ') elif isinstance(value, datetime.date): return value.isoformat() elif value is None: return 'null-val' else: return str(value)
Convert Python objects to Space-Track compatible strings - Booleans (``True`` -> ``'true'``) - Sequences (``[25544, 34602]`` -> ``'25544,34602'``) - dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``) - ``None`` -> ``'null-val'``
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/operators.py#L45-L64
null
# coding: utf-8 from __future__ import absolute_import, division, print_function import datetime import six try: from collections.abc import Sequence except ImportError: from collections import Sequence def greater_than(value): """``'>value'``.""" return '>' + _stringify_predicate_value(value) def less_than(value): """``'<value'``.""" return '<' + _stringify_predicate_value(value) def not_equal(value): """``'<>value'``.""" return '<>' + _stringify_predicate_value(value) def inclusive_range(left, right): """``'left--right'``.""" return (_stringify_predicate_value(left) + '--' + _stringify_predicate_value(right)) def like(value): """``'~~value'``.""" return '~~' + _stringify_predicate_value(value) def startswith(value): """``'^value'``.""" return '^' + _stringify_predicate_value(value)
python-astrodynamics/spacetrack
spacetrack/base.py
_iter_content_generator
python
def _iter_content_generator(response, decode_unicode): for chunk in response.iter_content(100 * 1024, decode_unicode=decode_unicode): if decode_unicode: # Replace CRLF newlines with LF, Python will handle # platform specific newlines if written to file. chunk = chunk.replace('\r\n', '\n') # Chunk could be ['...\r', '\n...'], stril trailing \r chunk = chunk.rstrip('\r') yield chunk
Generator used to yield 100 KiB chunks for a given response.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L640-L649
null
# coding: utf-8 from __future__ import absolute_import, division, print_function import datetime as dt import re import threading import time import weakref from collections import OrderedDict from functools import partial import requests from logbook import Logger from ratelimiter import RateLimiter from represent import ReprHelper, ReprHelperMixin from .operators import _stringify_predicate_value try: from collections.abc import Mapping except ImportError: from collections import Mapping logger = Logger('spacetrack') type_re = re.compile(r'(\w+)') enum_re = re.compile(r""" enum\( '(\w+)' # First value (?:, # Subsequent values optional '(\w+)' # Capture string )* \) """, re.VERBOSE) class AuthenticationError(Exception): """Space-Track authentication error.""" class Predicate(ReprHelperMixin, object): """Hold Space-Track predicate information. The current goal of this class is to print the repr for the user. """ def __init__(self, name, type_, nullable=False, default=None, values=None): self.name = name self.type_ = type_ self.nullable = nullable self.default = default # Values can be set e.g. for enum predicates self.values = values def _repr_helper_(self, r): r.keyword_from_attr('name') r.keyword_from_attr('type_') r.keyword_from_attr('nullable') r.keyword_from_attr('default') if self.values is not None: r.keyword_from_attr('values') def parse(self, value): if value is None: return value if self.type_ == 'float': return float(value) elif self.type_ == 'int': return int(value) elif self.type_ == 'datetime': return dt.datetime.strptime(value, '%Y-%m-%d %H:%M:%S') elif self.type_ == 'date': return dt.datetime.strptime(value, '%Y-%m-%d').date() else: return value class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #api-requestClasses .. data:: request_controllers Ordered dictionary of request controllers and their request classes in the following order. - `basicspacedata` - `expandedspacedata` - `fileshare` - `spephemeris` For example, if the ``spacetrack.file`` method is used without specifying which controller, the client will choose the `fileshare` controller (which comes before `spephemeris`). .. note:: If new request classes and/or controllers are added to the Space-Track API but not yet to this library, you can safely subclass :class:`SpaceTrackClient` with a copy of this ordered dictionary to add them. That said, please open an issue on `GitHub`_ for me to add them to the library. .. _`GitHub`: https://github.com/python-astrodynamics/spacetrack """ base_url = 'https://www.space-track.org/' # "request class" methods will be looked up by request controller in this # order request_controllers = OrderedDict.fromkeys([ 'basicspacedata', 'expandedspacedata', 'fileshare', 'spephemeris', ]) request_controllers['basicspacedata'] = { 'tle', 'tle_latest', 'tle_publish', 'omm', 'boxscore', 'satcat', 'launch_site', 'satcat_change', 'satcat_debut', 'decay', 'tip', 'announcement', } request_controllers['expandedspacedata'] = { 'cdm', 'organization', 'maneuver', 'maneuver_history', } request_controllers['fileshare'] = { 'file', 'download', 'upload', 'delete', } request_controllers['spephemeris'] = { 'download', 'file', 'file_history', } # List of (class, controller) tuples for # requests which do not return a modeldef offline_predicates = { ('upload', 'fileshare'): {'folder_id', 'file'}, } # These predicates are available for every request class. rest_predicates = { Predicate('predicates', 'str'), Predicate('metadata', 'enum', values=('true', 'false')), Predicate('limit', 'str'), Predicate('orderby', 'str'), Predicate('distinct', 'enum', values=('true', 'false')), Predicate( 'format', 'enum', values=('json', 'xml', 'html', 'csv', 'tle', '3le', 'kvn', 'stream')), Predicate('emptyresult', 'enum', values=('show',)), Predicate('favorites', 'str'), } def __init__(self, identity, password): #: :class:`requests.Session` instance. It can be mutated to configure #: e.g. proxies. self.session = self._create_session() self.identity = identity self.password = password # If set, this will be called when we sleep for the rate limit. self.callback = None self._authenticated = False self._predicates = dict() self._controller_proxies = dict() # "Space-track throttles API use in order to maintain consistent # performance for all users. To avoid error messages, please limit # your query frequency to less than 20 requests per minute." self._ratelimiter = RateLimiter( max_calls=19, period=60, callback=self._ratelimit_callback) def _ratelimit_callback(self, until): duration = int(round(until - time.time())) logger.info('Rate limit reached. Sleeping for {:d} seconds.', duration) if self.callback is not None: self.callback(until) @staticmethod def _create_session(): """Create session for accessing the web. This method is overridden in :class:`spacetrac.aio.AsyncSpaceTrackClient` to use :mod:`aiohttp` instead of :mod:`requests`. """ return requests.Session() def authenticate(self): """Authenticate with Space-Track. Raises: spacetrack.base.AuthenticationError: Incorrect login details. .. note:: This method is called automatically when required. """ if not self._authenticated: login_url = self.base_url + 'ajaxauth/login' data = {'identity': self.identity, 'password': self.password} resp = self.session.post(login_url, data=data) _raise_for_status(resp) # If login failed, we get a JSON response with {'Login': 'Failed'} resp_data = resp.json() if isinstance(resp_data, Mapping): if resp_data.get('Login', None) == 'Failed': raise AuthenticationError() self._authenticated = True def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) Parameters: class\_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned! """ if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: # Validate keyword argument names by querying valid predicates from # Space-Track predicates = self.get_predicates(class_, controller) predicate_fields = {p.name for p in predicates} valid_fields |= predicate_fields else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) if class_ == 'upload' and key == 'file': continue value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(requests.utils.requote_uri(url)) if class_ == 'upload': if 'file' not in kwargs: raise TypeError("missing keyword argument: 'file'") resp = self.session.post(url, files={'file': kwargs['file']}) else: resp = self._ratelimited_get(url, stream=iter_lines or iter_content) _raise_for_status(resp) if resp.encoding is None: resp.encoding = 'UTF-8' if iter_lines: return _iter_lines_generator(resp, decode_unicode=decode) elif iter_content: return _iter_content_generator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: data = resp.text # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = data.replace('\r\n', '\n') else: data = resp.content return data else: data = resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates) @staticmethod def _parse_types(data, predicates): predicate_map = {p.name: p for p in predicates} for obj in data: for key, value in obj.items(): if key.lower() in predicate_map: obj[key] = predicate_map[key.lower()].parse(value) return data def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status_code == 500: # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp.text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period t = threading.Thread(target=self._ratelimit_callback, args=(until,)) t.daemon = True t.start() time.sleep(self._ratelimiter.period) # Now retry with self._ratelimiter: resp = self.session.get(*args, **kwargs) return resp def __getattr__(self, attr): if attr in self.request_controllers: controller_proxy = self._controller_proxies.get(attr) if controller_proxy is None: controller_proxy = _ControllerProxy(self, attr) self._controller_proxies[attr] = controller_proxy return controller_proxy try: controller = self._find_controller(attr) except ValueError: raise AttributeError( "'{name}' object has no attribute '{attr}'" .format(name=self.__class__.__name__, attr=attr)) # generic_request can resolve the controller itself, but we # pass it because we have to check if the class_ is owned # by a controller here anyway. function = partial( self.generic_request, class_=attr, controller=controller) function.get_predicates = partial( self.get_predicates, class_=attr, controller=controller) return function def __dir__(self): """Include request controllers and request classes.""" attrs = list(self.__dict__) request_classes = { class_ for classes in self.request_controllers.values() for class_ in classes} attrs += list(request_classes) attrs += list(self.request_controllers) return sorted(attrs) def _find_controller(self, class_): """Find first controller that matches given request class. Order is specified by the keys of ``SpaceTrackClient.request_controllers`` (:class:`~collections.OrderedDict`) """ for controller, classes in self.request_controllers.items(): if class_ in classes: return controller else: raise ValueError('Unknown request class {!r}'.format(class_)) def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) logger.debug(requests.utils.requote_uri(url)) resp = self._ratelimited_get(url) _raise_for_status(resp) return resp.json()['data'] def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = self._download_predicate_data(class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_] def _parse_predicates_data(self, predicates_data): predicate_objects = [] for field in predicates_data: full_type = field['Type'] type_match = type_re.match(full_type) if not type_match: raise ValueError( "Couldn't parse field type '{}'".format(full_type)) type_name = type_match.group(1) field_name = field['Field'].lower() nullable = (field['Null'] == 'YES') default = field['Default'] types = { # Strings 'char': 'str', 'varchar': 'str', 'longtext': 'str', # varbinary only used for 'file' request class, for the # 'file_link' predicate. 'varbinary': 'str', # Integers 'bigint': 'int', 'int': 'int', 'tinyint': 'int', 'smallint': 'int', 'mediumint': 'int', # Floats 'decimal': 'float', 'float': 'float', 'double': 'float', # Date/Times 'date': 'date', 'timestamp': 'datetime', 'datetime': 'datetime', # Enum 'enum': 'enum', # Bytes 'longblob': 'bytes', } if type_name not in types: raise ValueError("Unknown predicate type '{}'." .format(type_name)) predicate = Predicate( name=field_name, type_=types[type_name], nullable=nullable, default=default) if type_name == 'enum': enum_match = enum_re.match(full_type) if not enum_match: raise ValueError( "Couldn't parse enum type '{}'".format(full_type)) # match.groups() doesn't work for repeating groups, use findall predicate.values = tuple(re.findall(r"'(\w+)'", full_type)) predicate_objects.append(predicate) return predicate_objects def __repr__(self): r = ReprHelper(self) r.parantheses = ('<', '>') r.keyword_from_attr('identity') return str(r) class _ControllerProxy(object): """Proxies request class methods with a preset request controller.""" def __init__(self, client, controller): # The client will cache _ControllerProxy instances, so only store # a weak reference to it. self.client = weakref.proxy(client) self.controller = controller def __getattr__(self, attr): if attr not in self.client.request_controllers[self.controller]: raise AttributeError( "'{self!r}' object has no attribute '{attr}'" .format(self=self, attr=attr)) function = partial( self.client.generic_request, class_=attr, controller=self.controller) function.get_predicates = partial( self.client.get_predicates, class_=attr, controller=self.controller) return function def __repr__(self): r = ReprHelper(self) r.parantheses = ('<', '>') r.keyword_from_attr('controller') return str(r) def get_predicates(self, class_): """Proxy ``get_predicates`` to client with stored request controller. """ return self.client.get_predicates( class_=class_, controller=self.controller) def _iter_lines_generator(response, decode_unicode): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The function is taken from :meth:`requests.models.Response.iter_lines`, but modified to use our :func:`~spacetrack.base._iter_content_generator`. This is because Space-Track uses CRLF newlines, so :meth:`str.splitlines` can cause us to yield blank lines if one chunk ends with CR and the next one starts with LF. .. note:: This method is not reentrant safe. """ pending = None for chunk in _iter_content_generator(response, decode_unicode=decode_unicode): if pending is not None: chunk = pending + chunk lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None for line in lines: yield line if pending is not None: yield pending def _raise_for_status(response): """Raises stored :class:`HTTPError`, if one occurred. This is the :meth:`requests.models.Response.raise_for_status` method, modified to add the response from Space-Track, if given. """ http_error_msg = '' if 400 <= response.status_code < 500: http_error_msg = '%s Client Error: %s for url: %s' % ( response.status_code, response.reason, response.url) elif 500 <= response.status_code < 600: http_error_msg = '%s Server Error: %s for url: %s' % ( response.status_code, response.reason, response.url) if http_error_msg: spacetrack_error_msg = None try: json = response.json() if isinstance(json, Mapping): spacetrack_error_msg = json['error'] except (ValueError, KeyError): pass if not spacetrack_error_msg: spacetrack_error_msg = response.text if spacetrack_error_msg: http_error_msg += '\nSpace-Track response:\n' + spacetrack_error_msg raise requests.HTTPError(http_error_msg, response=response)
python-astrodynamics/spacetrack
spacetrack/base.py
_iter_lines_generator
python
def _iter_lines_generator(response, decode_unicode): pending = None for chunk in _iter_content_generator(response, decode_unicode=decode_unicode): if pending is not None: chunk = pending + chunk lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None for line in lines: yield line if pending is not None: yield pending
Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The function is taken from :meth:`requests.models.Response.iter_lines`, but modified to use our :func:`~spacetrack.base._iter_content_generator`. This is because Space-Track uses CRLF newlines, so :meth:`str.splitlines` can cause us to yield blank lines if one chunk ends with CR and the next one starts with LF. .. note:: This method is not reentrant safe.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L652-L683
[ "def _iter_content_generator(response, decode_unicode):\n \"\"\"Generator used to yield 100 KiB chunks for a given response.\"\"\"\n for chunk in response.iter_content(100 * 1024, decode_unicode=decode_unicode):\n if decode_unicode:\n # Replace CRLF newlines with LF, Python will handle\n # platform specific newlines if written to file.\n chunk = chunk.replace('\\r\\n', '\\n')\n # Chunk could be ['...\\r', '\\n...'], stril trailing \\r\n chunk = chunk.rstrip('\\r')\n yield chunk\n" ]
# coding: utf-8 from __future__ import absolute_import, division, print_function import datetime as dt import re import threading import time import weakref from collections import OrderedDict from functools import partial import requests from logbook import Logger from ratelimiter import RateLimiter from represent import ReprHelper, ReprHelperMixin from .operators import _stringify_predicate_value try: from collections.abc import Mapping except ImportError: from collections import Mapping logger = Logger('spacetrack') type_re = re.compile(r'(\w+)') enum_re = re.compile(r""" enum\( '(\w+)' # First value (?:, # Subsequent values optional '(\w+)' # Capture string )* \) """, re.VERBOSE) class AuthenticationError(Exception): """Space-Track authentication error.""" class Predicate(ReprHelperMixin, object): """Hold Space-Track predicate information. The current goal of this class is to print the repr for the user. """ def __init__(self, name, type_, nullable=False, default=None, values=None): self.name = name self.type_ = type_ self.nullable = nullable self.default = default # Values can be set e.g. for enum predicates self.values = values def _repr_helper_(self, r): r.keyword_from_attr('name') r.keyword_from_attr('type_') r.keyword_from_attr('nullable') r.keyword_from_attr('default') if self.values is not None: r.keyword_from_attr('values') def parse(self, value): if value is None: return value if self.type_ == 'float': return float(value) elif self.type_ == 'int': return int(value) elif self.type_ == 'datetime': return dt.datetime.strptime(value, '%Y-%m-%d %H:%M:%S') elif self.type_ == 'date': return dt.datetime.strptime(value, '%Y-%m-%d').date() else: return value class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #api-requestClasses .. data:: request_controllers Ordered dictionary of request controllers and their request classes in the following order. - `basicspacedata` - `expandedspacedata` - `fileshare` - `spephemeris` For example, if the ``spacetrack.file`` method is used without specifying which controller, the client will choose the `fileshare` controller (which comes before `spephemeris`). .. note:: If new request classes and/or controllers are added to the Space-Track API but not yet to this library, you can safely subclass :class:`SpaceTrackClient` with a copy of this ordered dictionary to add them. That said, please open an issue on `GitHub`_ for me to add them to the library. .. _`GitHub`: https://github.com/python-astrodynamics/spacetrack """ base_url = 'https://www.space-track.org/' # "request class" methods will be looked up by request controller in this # order request_controllers = OrderedDict.fromkeys([ 'basicspacedata', 'expandedspacedata', 'fileshare', 'spephemeris', ]) request_controllers['basicspacedata'] = { 'tle', 'tle_latest', 'tle_publish', 'omm', 'boxscore', 'satcat', 'launch_site', 'satcat_change', 'satcat_debut', 'decay', 'tip', 'announcement', } request_controllers['expandedspacedata'] = { 'cdm', 'organization', 'maneuver', 'maneuver_history', } request_controllers['fileshare'] = { 'file', 'download', 'upload', 'delete', } request_controllers['spephemeris'] = { 'download', 'file', 'file_history', } # List of (class, controller) tuples for # requests which do not return a modeldef offline_predicates = { ('upload', 'fileshare'): {'folder_id', 'file'}, } # These predicates are available for every request class. rest_predicates = { Predicate('predicates', 'str'), Predicate('metadata', 'enum', values=('true', 'false')), Predicate('limit', 'str'), Predicate('orderby', 'str'), Predicate('distinct', 'enum', values=('true', 'false')), Predicate( 'format', 'enum', values=('json', 'xml', 'html', 'csv', 'tle', '3le', 'kvn', 'stream')), Predicate('emptyresult', 'enum', values=('show',)), Predicate('favorites', 'str'), } def __init__(self, identity, password): #: :class:`requests.Session` instance. It can be mutated to configure #: e.g. proxies. self.session = self._create_session() self.identity = identity self.password = password # If set, this will be called when we sleep for the rate limit. self.callback = None self._authenticated = False self._predicates = dict() self._controller_proxies = dict() # "Space-track throttles API use in order to maintain consistent # performance for all users. To avoid error messages, please limit # your query frequency to less than 20 requests per minute." self._ratelimiter = RateLimiter( max_calls=19, period=60, callback=self._ratelimit_callback) def _ratelimit_callback(self, until): duration = int(round(until - time.time())) logger.info('Rate limit reached. Sleeping for {:d} seconds.', duration) if self.callback is not None: self.callback(until) @staticmethod def _create_session(): """Create session for accessing the web. This method is overridden in :class:`spacetrac.aio.AsyncSpaceTrackClient` to use :mod:`aiohttp` instead of :mod:`requests`. """ return requests.Session() def authenticate(self): """Authenticate with Space-Track. Raises: spacetrack.base.AuthenticationError: Incorrect login details. .. note:: This method is called automatically when required. """ if not self._authenticated: login_url = self.base_url + 'ajaxauth/login' data = {'identity': self.identity, 'password': self.password} resp = self.session.post(login_url, data=data) _raise_for_status(resp) # If login failed, we get a JSON response with {'Login': 'Failed'} resp_data = resp.json() if isinstance(resp_data, Mapping): if resp_data.get('Login', None) == 'Failed': raise AuthenticationError() self._authenticated = True def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) Parameters: class\_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned! """ if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: # Validate keyword argument names by querying valid predicates from # Space-Track predicates = self.get_predicates(class_, controller) predicate_fields = {p.name for p in predicates} valid_fields |= predicate_fields else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) if class_ == 'upload' and key == 'file': continue value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(requests.utils.requote_uri(url)) if class_ == 'upload': if 'file' not in kwargs: raise TypeError("missing keyword argument: 'file'") resp = self.session.post(url, files={'file': kwargs['file']}) else: resp = self._ratelimited_get(url, stream=iter_lines or iter_content) _raise_for_status(resp) if resp.encoding is None: resp.encoding = 'UTF-8' if iter_lines: return _iter_lines_generator(resp, decode_unicode=decode) elif iter_content: return _iter_content_generator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: data = resp.text # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = data.replace('\r\n', '\n') else: data = resp.content return data else: data = resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates) @staticmethod def _parse_types(data, predicates): predicate_map = {p.name: p for p in predicates} for obj in data: for key, value in obj.items(): if key.lower() in predicate_map: obj[key] = predicate_map[key.lower()].parse(value) return data def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status_code == 500: # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp.text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period t = threading.Thread(target=self._ratelimit_callback, args=(until,)) t.daemon = True t.start() time.sleep(self._ratelimiter.period) # Now retry with self._ratelimiter: resp = self.session.get(*args, **kwargs) return resp def __getattr__(self, attr): if attr in self.request_controllers: controller_proxy = self._controller_proxies.get(attr) if controller_proxy is None: controller_proxy = _ControllerProxy(self, attr) self._controller_proxies[attr] = controller_proxy return controller_proxy try: controller = self._find_controller(attr) except ValueError: raise AttributeError( "'{name}' object has no attribute '{attr}'" .format(name=self.__class__.__name__, attr=attr)) # generic_request can resolve the controller itself, but we # pass it because we have to check if the class_ is owned # by a controller here anyway. function = partial( self.generic_request, class_=attr, controller=controller) function.get_predicates = partial( self.get_predicates, class_=attr, controller=controller) return function def __dir__(self): """Include request controllers and request classes.""" attrs = list(self.__dict__) request_classes = { class_ for classes in self.request_controllers.values() for class_ in classes} attrs += list(request_classes) attrs += list(self.request_controllers) return sorted(attrs) def _find_controller(self, class_): """Find first controller that matches given request class. Order is specified by the keys of ``SpaceTrackClient.request_controllers`` (:class:`~collections.OrderedDict`) """ for controller, classes in self.request_controllers.items(): if class_ in classes: return controller else: raise ValueError('Unknown request class {!r}'.format(class_)) def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) logger.debug(requests.utils.requote_uri(url)) resp = self._ratelimited_get(url) _raise_for_status(resp) return resp.json()['data'] def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = self._download_predicate_data(class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_] def _parse_predicates_data(self, predicates_data): predicate_objects = [] for field in predicates_data: full_type = field['Type'] type_match = type_re.match(full_type) if not type_match: raise ValueError( "Couldn't parse field type '{}'".format(full_type)) type_name = type_match.group(1) field_name = field['Field'].lower() nullable = (field['Null'] == 'YES') default = field['Default'] types = { # Strings 'char': 'str', 'varchar': 'str', 'longtext': 'str', # varbinary only used for 'file' request class, for the # 'file_link' predicate. 'varbinary': 'str', # Integers 'bigint': 'int', 'int': 'int', 'tinyint': 'int', 'smallint': 'int', 'mediumint': 'int', # Floats 'decimal': 'float', 'float': 'float', 'double': 'float', # Date/Times 'date': 'date', 'timestamp': 'datetime', 'datetime': 'datetime', # Enum 'enum': 'enum', # Bytes 'longblob': 'bytes', } if type_name not in types: raise ValueError("Unknown predicate type '{}'." .format(type_name)) predicate = Predicate( name=field_name, type_=types[type_name], nullable=nullable, default=default) if type_name == 'enum': enum_match = enum_re.match(full_type) if not enum_match: raise ValueError( "Couldn't parse enum type '{}'".format(full_type)) # match.groups() doesn't work for repeating groups, use findall predicate.values = tuple(re.findall(r"'(\w+)'", full_type)) predicate_objects.append(predicate) return predicate_objects def __repr__(self): r = ReprHelper(self) r.parantheses = ('<', '>') r.keyword_from_attr('identity') return str(r) class _ControllerProxy(object): """Proxies request class methods with a preset request controller.""" def __init__(self, client, controller): # The client will cache _ControllerProxy instances, so only store # a weak reference to it. self.client = weakref.proxy(client) self.controller = controller def __getattr__(self, attr): if attr not in self.client.request_controllers[self.controller]: raise AttributeError( "'{self!r}' object has no attribute '{attr}'" .format(self=self, attr=attr)) function = partial( self.client.generic_request, class_=attr, controller=self.controller) function.get_predicates = partial( self.client.get_predicates, class_=attr, controller=self.controller) return function def __repr__(self): r = ReprHelper(self) r.parantheses = ('<', '>') r.keyword_from_attr('controller') return str(r) def get_predicates(self, class_): """Proxy ``get_predicates`` to client with stored request controller. """ return self.client.get_predicates( class_=class_, controller=self.controller) def _iter_content_generator(response, decode_unicode): """Generator used to yield 100 KiB chunks for a given response.""" for chunk in response.iter_content(100 * 1024, decode_unicode=decode_unicode): if decode_unicode: # Replace CRLF newlines with LF, Python will handle # platform specific newlines if written to file. chunk = chunk.replace('\r\n', '\n') # Chunk could be ['...\r', '\n...'], stril trailing \r chunk = chunk.rstrip('\r') yield chunk def _raise_for_status(response): """Raises stored :class:`HTTPError`, if one occurred. This is the :meth:`requests.models.Response.raise_for_status` method, modified to add the response from Space-Track, if given. """ http_error_msg = '' if 400 <= response.status_code < 500: http_error_msg = '%s Client Error: %s for url: %s' % ( response.status_code, response.reason, response.url) elif 500 <= response.status_code < 600: http_error_msg = '%s Server Error: %s for url: %s' % ( response.status_code, response.reason, response.url) if http_error_msg: spacetrack_error_msg = None try: json = response.json() if isinstance(json, Mapping): spacetrack_error_msg = json['error'] except (ValueError, KeyError): pass if not spacetrack_error_msg: spacetrack_error_msg = response.text if spacetrack_error_msg: http_error_msg += '\nSpace-Track response:\n' + spacetrack_error_msg raise requests.HTTPError(http_error_msg, response=response)
python-astrodynamics/spacetrack
spacetrack/base.py
_raise_for_status
python
def _raise_for_status(response): http_error_msg = '' if 400 <= response.status_code < 500: http_error_msg = '%s Client Error: %s for url: %s' % ( response.status_code, response.reason, response.url) elif 500 <= response.status_code < 600: http_error_msg = '%s Server Error: %s for url: %s' % ( response.status_code, response.reason, response.url) if http_error_msg: spacetrack_error_msg = None try: json = response.json() if isinstance(json, Mapping): spacetrack_error_msg = json['error'] except (ValueError, KeyError): pass if not spacetrack_error_msg: spacetrack_error_msg = response.text if spacetrack_error_msg: http_error_msg += '\nSpace-Track response:\n' + spacetrack_error_msg raise requests.HTTPError(http_error_msg, response=response)
Raises stored :class:`HTTPError`, if one occurred. This is the :meth:`requests.models.Response.raise_for_status` method, modified to add the response from Space-Track, if given.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L686-L719
null
# coding: utf-8 from __future__ import absolute_import, division, print_function import datetime as dt import re import threading import time import weakref from collections import OrderedDict from functools import partial import requests from logbook import Logger from ratelimiter import RateLimiter from represent import ReprHelper, ReprHelperMixin from .operators import _stringify_predicate_value try: from collections.abc import Mapping except ImportError: from collections import Mapping logger = Logger('spacetrack') type_re = re.compile(r'(\w+)') enum_re = re.compile(r""" enum\( '(\w+)' # First value (?:, # Subsequent values optional '(\w+)' # Capture string )* \) """, re.VERBOSE) class AuthenticationError(Exception): """Space-Track authentication error.""" class Predicate(ReprHelperMixin, object): """Hold Space-Track predicate information. The current goal of this class is to print the repr for the user. """ def __init__(self, name, type_, nullable=False, default=None, values=None): self.name = name self.type_ = type_ self.nullable = nullable self.default = default # Values can be set e.g. for enum predicates self.values = values def _repr_helper_(self, r): r.keyword_from_attr('name') r.keyword_from_attr('type_') r.keyword_from_attr('nullable') r.keyword_from_attr('default') if self.values is not None: r.keyword_from_attr('values') def parse(self, value): if value is None: return value if self.type_ == 'float': return float(value) elif self.type_ == 'int': return int(value) elif self.type_ == 'datetime': return dt.datetime.strptime(value, '%Y-%m-%d %H:%M:%S') elif self.type_ == 'date': return dt.datetime.strptime(value, '%Y-%m-%d').date() else: return value class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #api-requestClasses .. data:: request_controllers Ordered dictionary of request controllers and their request classes in the following order. - `basicspacedata` - `expandedspacedata` - `fileshare` - `spephemeris` For example, if the ``spacetrack.file`` method is used without specifying which controller, the client will choose the `fileshare` controller (which comes before `spephemeris`). .. note:: If new request classes and/or controllers are added to the Space-Track API but not yet to this library, you can safely subclass :class:`SpaceTrackClient` with a copy of this ordered dictionary to add them. That said, please open an issue on `GitHub`_ for me to add them to the library. .. _`GitHub`: https://github.com/python-astrodynamics/spacetrack """ base_url = 'https://www.space-track.org/' # "request class" methods will be looked up by request controller in this # order request_controllers = OrderedDict.fromkeys([ 'basicspacedata', 'expandedspacedata', 'fileshare', 'spephemeris', ]) request_controllers['basicspacedata'] = { 'tle', 'tle_latest', 'tle_publish', 'omm', 'boxscore', 'satcat', 'launch_site', 'satcat_change', 'satcat_debut', 'decay', 'tip', 'announcement', } request_controllers['expandedspacedata'] = { 'cdm', 'organization', 'maneuver', 'maneuver_history', } request_controllers['fileshare'] = { 'file', 'download', 'upload', 'delete', } request_controllers['spephemeris'] = { 'download', 'file', 'file_history', } # List of (class, controller) tuples for # requests which do not return a modeldef offline_predicates = { ('upload', 'fileshare'): {'folder_id', 'file'}, } # These predicates are available for every request class. rest_predicates = { Predicate('predicates', 'str'), Predicate('metadata', 'enum', values=('true', 'false')), Predicate('limit', 'str'), Predicate('orderby', 'str'), Predicate('distinct', 'enum', values=('true', 'false')), Predicate( 'format', 'enum', values=('json', 'xml', 'html', 'csv', 'tle', '3le', 'kvn', 'stream')), Predicate('emptyresult', 'enum', values=('show',)), Predicate('favorites', 'str'), } def __init__(self, identity, password): #: :class:`requests.Session` instance. It can be mutated to configure #: e.g. proxies. self.session = self._create_session() self.identity = identity self.password = password # If set, this will be called when we sleep for the rate limit. self.callback = None self._authenticated = False self._predicates = dict() self._controller_proxies = dict() # "Space-track throttles API use in order to maintain consistent # performance for all users. To avoid error messages, please limit # your query frequency to less than 20 requests per minute." self._ratelimiter = RateLimiter( max_calls=19, period=60, callback=self._ratelimit_callback) def _ratelimit_callback(self, until): duration = int(round(until - time.time())) logger.info('Rate limit reached. Sleeping for {:d} seconds.', duration) if self.callback is not None: self.callback(until) @staticmethod def _create_session(): """Create session for accessing the web. This method is overridden in :class:`spacetrac.aio.AsyncSpaceTrackClient` to use :mod:`aiohttp` instead of :mod:`requests`. """ return requests.Session() def authenticate(self): """Authenticate with Space-Track. Raises: spacetrack.base.AuthenticationError: Incorrect login details. .. note:: This method is called automatically when required. """ if not self._authenticated: login_url = self.base_url + 'ajaxauth/login' data = {'identity': self.identity, 'password': self.password} resp = self.session.post(login_url, data=data) _raise_for_status(resp) # If login failed, we get a JSON response with {'Login': 'Failed'} resp_data = resp.json() if isinstance(resp_data, Mapping): if resp_data.get('Login', None) == 'Failed': raise AuthenticationError() self._authenticated = True def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) Parameters: class\_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned! """ if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: # Validate keyword argument names by querying valid predicates from # Space-Track predicates = self.get_predicates(class_, controller) predicate_fields = {p.name for p in predicates} valid_fields |= predicate_fields else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) if class_ == 'upload' and key == 'file': continue value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(requests.utils.requote_uri(url)) if class_ == 'upload': if 'file' not in kwargs: raise TypeError("missing keyword argument: 'file'") resp = self.session.post(url, files={'file': kwargs['file']}) else: resp = self._ratelimited_get(url, stream=iter_lines or iter_content) _raise_for_status(resp) if resp.encoding is None: resp.encoding = 'UTF-8' if iter_lines: return _iter_lines_generator(resp, decode_unicode=decode) elif iter_content: return _iter_content_generator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: data = resp.text # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = data.replace('\r\n', '\n') else: data = resp.content return data else: data = resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates) @staticmethod def _parse_types(data, predicates): predicate_map = {p.name: p for p in predicates} for obj in data: for key, value in obj.items(): if key.lower() in predicate_map: obj[key] = predicate_map[key.lower()].parse(value) return data def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status_code == 500: # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp.text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period t = threading.Thread(target=self._ratelimit_callback, args=(until,)) t.daemon = True t.start() time.sleep(self._ratelimiter.period) # Now retry with self._ratelimiter: resp = self.session.get(*args, **kwargs) return resp def __getattr__(self, attr): if attr in self.request_controllers: controller_proxy = self._controller_proxies.get(attr) if controller_proxy is None: controller_proxy = _ControllerProxy(self, attr) self._controller_proxies[attr] = controller_proxy return controller_proxy try: controller = self._find_controller(attr) except ValueError: raise AttributeError( "'{name}' object has no attribute '{attr}'" .format(name=self.__class__.__name__, attr=attr)) # generic_request can resolve the controller itself, but we # pass it because we have to check if the class_ is owned # by a controller here anyway. function = partial( self.generic_request, class_=attr, controller=controller) function.get_predicates = partial( self.get_predicates, class_=attr, controller=controller) return function def __dir__(self): """Include request controllers and request classes.""" attrs = list(self.__dict__) request_classes = { class_ for classes in self.request_controllers.values() for class_ in classes} attrs += list(request_classes) attrs += list(self.request_controllers) return sorted(attrs) def _find_controller(self, class_): """Find first controller that matches given request class. Order is specified by the keys of ``SpaceTrackClient.request_controllers`` (:class:`~collections.OrderedDict`) """ for controller, classes in self.request_controllers.items(): if class_ in classes: return controller else: raise ValueError('Unknown request class {!r}'.format(class_)) def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) logger.debug(requests.utils.requote_uri(url)) resp = self._ratelimited_get(url) _raise_for_status(resp) return resp.json()['data'] def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = self._download_predicate_data(class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_] def _parse_predicates_data(self, predicates_data): predicate_objects = [] for field in predicates_data: full_type = field['Type'] type_match = type_re.match(full_type) if not type_match: raise ValueError( "Couldn't parse field type '{}'".format(full_type)) type_name = type_match.group(1) field_name = field['Field'].lower() nullable = (field['Null'] == 'YES') default = field['Default'] types = { # Strings 'char': 'str', 'varchar': 'str', 'longtext': 'str', # varbinary only used for 'file' request class, for the # 'file_link' predicate. 'varbinary': 'str', # Integers 'bigint': 'int', 'int': 'int', 'tinyint': 'int', 'smallint': 'int', 'mediumint': 'int', # Floats 'decimal': 'float', 'float': 'float', 'double': 'float', # Date/Times 'date': 'date', 'timestamp': 'datetime', 'datetime': 'datetime', # Enum 'enum': 'enum', # Bytes 'longblob': 'bytes', } if type_name not in types: raise ValueError("Unknown predicate type '{}'." .format(type_name)) predicate = Predicate( name=field_name, type_=types[type_name], nullable=nullable, default=default) if type_name == 'enum': enum_match = enum_re.match(full_type) if not enum_match: raise ValueError( "Couldn't parse enum type '{}'".format(full_type)) # match.groups() doesn't work for repeating groups, use findall predicate.values = tuple(re.findall(r"'(\w+)'", full_type)) predicate_objects.append(predicate) return predicate_objects def __repr__(self): r = ReprHelper(self) r.parantheses = ('<', '>') r.keyword_from_attr('identity') return str(r) class _ControllerProxy(object): """Proxies request class methods with a preset request controller.""" def __init__(self, client, controller): # The client will cache _ControllerProxy instances, so only store # a weak reference to it. self.client = weakref.proxy(client) self.controller = controller def __getattr__(self, attr): if attr not in self.client.request_controllers[self.controller]: raise AttributeError( "'{self!r}' object has no attribute '{attr}'" .format(self=self, attr=attr)) function = partial( self.client.generic_request, class_=attr, controller=self.controller) function.get_predicates = partial( self.client.get_predicates, class_=attr, controller=self.controller) return function def __repr__(self): r = ReprHelper(self) r.parantheses = ('<', '>') r.keyword_from_attr('controller') return str(r) def get_predicates(self, class_): """Proxy ``get_predicates`` to client with stored request controller. """ return self.client.get_predicates( class_=class_, controller=self.controller) def _iter_content_generator(response, decode_unicode): """Generator used to yield 100 KiB chunks for a given response.""" for chunk in response.iter_content(100 * 1024, decode_unicode=decode_unicode): if decode_unicode: # Replace CRLF newlines with LF, Python will handle # platform specific newlines if written to file. chunk = chunk.replace('\r\n', '\n') # Chunk could be ['...\r', '\n...'], stril trailing \r chunk = chunk.rstrip('\r') yield chunk def _iter_lines_generator(response, decode_unicode): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The function is taken from :meth:`requests.models.Response.iter_lines`, but modified to use our :func:`~spacetrack.base._iter_content_generator`. This is because Space-Track uses CRLF newlines, so :meth:`str.splitlines` can cause us to yield blank lines if one chunk ends with CR and the next one starts with LF. .. note:: This method is not reentrant safe. """ pending = None for chunk in _iter_content_generator(response, decode_unicode=decode_unicode): if pending is not None: chunk = pending + chunk lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None for line in lines: yield line if pending is not None: yield pending
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient.generic_request
python
def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) Parameters: class\_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned! """ if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: # Validate keyword argument names by querying valid predicates from # Space-Track predicates = self.get_predicates(class_, controller) predicate_fields = {p.name for p in predicates} valid_fields |= predicate_fields else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) if class_ == 'upload' and key == 'file': continue value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(requests.utils.requote_uri(url)) if class_ == 'upload': if 'file' not in kwargs: raise TypeError("missing keyword argument: 'file'") resp = self.session.post(url, files={'file': kwargs['file']}) else: resp = self._ratelimited_get(url, stream=iter_lines or iter_content) _raise_for_status(resp) if resp.encoding is None: resp.encoding = 'UTF-8' if iter_lines: return _iter_lines_generator(resp, decode_unicode=decode) elif iter_content: return _iter_content_generator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: data = resp.text # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = data.replace('\r\n', '\n') else: data = resp.content return data else: data = resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates)
r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) Parameters: class\_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned!
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L245-L402
[ "def _stringify_predicate_value(value):\n \"\"\"Convert Python objects to Space-Track compatible strings\n\n - Booleans (``True`` -> ``'true'``)\n - Sequences (``[25544, 34602]`` -> ``'25544,34602'``)\n - dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)\n - ``None`` -> ``'null-val'``\n \"\"\"\n if isinstance(value, bool):\n return str(value).lower()\n elif isinstance(value, Sequence) and not isinstance(value, six.string_types):\n return ','.join(_stringify_predicate_value(x) for x in value)\n elif isinstance(value, datetime.datetime):\n return value.isoformat(sep=' ')\n elif isinstance(value, datetime.date):\n return value.isoformat()\n elif value is None:\n return 'null-val'\n else:\n return str(value)\n", "def _raise_for_status(response):\n \"\"\"Raises stored :class:`HTTPError`, if one occurred.\n\n This is the :meth:`requests.models.Response.raise_for_status` method,\n modified to add the response from Space-Track, if given.\n \"\"\"\n\n http_error_msg = ''\n\n if 400 <= response.status_code < 500:\n http_error_msg = '%s Client Error: %s for url: %s' % (\n response.status_code, response.reason, response.url)\n\n elif 500 <= response.status_code < 600:\n http_error_msg = '%s Server Error: %s for url: %s' % (\n response.status_code, response.reason, response.url)\n\n if http_error_msg:\n spacetrack_error_msg = None\n\n try:\n json = response.json()\n if isinstance(json, Mapping):\n spacetrack_error_msg = json['error']\n except (ValueError, KeyError):\n pass\n\n if not spacetrack_error_msg:\n spacetrack_error_msg = response.text\n\n if spacetrack_error_msg:\n http_error_msg += '\\nSpace-Track response:\\n' + spacetrack_error_msg\n\n raise requests.HTTPError(http_error_msg, response=response)\n", "def _iter_lines_generator(response, decode_unicode):\n \"\"\"Iterates over the response data, one line at a time. When\n stream=True is set on the request, this avoids reading the\n content at once into memory for large responses.\n\n The function is taken from :meth:`requests.models.Response.iter_lines`, but\n modified to use our :func:`~spacetrack.base._iter_content_generator`. This\n is because Space-Track uses CRLF newlines, so :meth:`str.splitlines` can\n cause us to yield blank lines if one chunk ends with CR and the next one\n starts with LF.\n\n .. note:: This method is not reentrant safe.\n \"\"\"\n pending = None\n\n for chunk in _iter_content_generator(response, decode_unicode=decode_unicode):\n\n if pending is not None:\n chunk = pending + chunk\n\n lines = chunk.splitlines()\n\n if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n pending = lines.pop()\n else:\n pending = None\n\n for line in lines:\n yield line\n\n if pending is not None:\n yield pending\n", "def _iter_content_generator(response, decode_unicode):\n \"\"\"Generator used to yield 100 KiB chunks for a given response.\"\"\"\n for chunk in response.iter_content(100 * 1024, decode_unicode=decode_unicode):\n if decode_unicode:\n # Replace CRLF newlines with LF, Python will handle\n # platform specific newlines if written to file.\n chunk = chunk.replace('\\r\\n', '\\n')\n # Chunk could be ['...\\r', '\\n...'], stril trailing \\r\n chunk = chunk.rstrip('\\r')\n yield chunk\n", "def authenticate(self):\n \"\"\"Authenticate with Space-Track.\n\n Raises:\n spacetrack.base.AuthenticationError: Incorrect login details.\n\n .. note::\n\n This method is called automatically when required.\n \"\"\"\n if not self._authenticated:\n login_url = self.base_url + 'ajaxauth/login'\n data = {'identity': self.identity, 'password': self.password}\n resp = self.session.post(login_url, data=data)\n\n _raise_for_status(resp)\n\n # If login failed, we get a JSON response with {'Login': 'Failed'}\n resp_data = resp.json()\n if isinstance(resp_data, Mapping):\n if resp_data.get('Login', None) == 'Failed':\n raise AuthenticationError()\n\n self._authenticated = True\n", "def _parse_types(data, predicates):\n predicate_map = {p.name: p for p in predicates}\n\n for obj in data:\n for key, value in obj.items():\n if key.lower() in predicate_map:\n obj[key] = predicate_map[key.lower()].parse(value)\n\n return data\n", "def _ratelimited_get(self, *args, **kwargs):\n \"\"\"Perform get request, handling rate limiting.\"\"\"\n with self._ratelimiter:\n resp = self.session.get(*args, **kwargs)\n\n # It's possible that Space-Track will return HTTP status 500 with a\n # query rate limit violation. This can happen if a script is cancelled\n # before it has finished sleeping to satisfy the rate limit and it is\n # started again.\n #\n # Let's catch this specific instance and retry once if it happens.\n if resp.status_code == 500:\n # Let's only retry if the error page tells us it's a rate limit\n # violation.\n if 'violated your query rate limit' in resp.text:\n # Mimic the RateLimiter callback behaviour.\n until = time.time() + self._ratelimiter.period\n t = threading.Thread(target=self._ratelimit_callback, args=(until,))\n t.daemon = True\n t.start()\n time.sleep(self._ratelimiter.period)\n\n # Now retry\n with self._ratelimiter:\n resp = self.session.get(*args, **kwargs)\n\n return resp\n", "def _find_controller(self, class_):\n \"\"\"Find first controller that matches given request class.\n\n Order is specified by the keys of\n ``SpaceTrackClient.request_controllers``\n (:class:`~collections.OrderedDict`)\n \"\"\"\n for controller, classes in self.request_controllers.items():\n if class_ in classes:\n return controller\n", "def get_predicates(self, class_, controller=None):\n \"\"\"Get full predicate information for given request class, and cache\n for subsequent calls.\n \"\"\"\n if class_ not in self._predicates:\n if controller is None:\n controller = self._find_controller(class_)\n else:\n classes = self.request_controllers.get(controller, None)\n if classes is None:\n raise ValueError(\n 'Unknown request controller {!r}'.format(controller))\n if class_ not in classes:\n raise ValueError(\n 'Unknown request class {!r}'.format(class_))\n\n predicates_data = self._download_predicate_data(class_, controller)\n predicate_objects = self._parse_predicates_data(predicates_data)\n self._predicates[class_] = predicate_objects\n\n return self._predicates[class_]\n" ]
class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #api-requestClasses .. data:: request_controllers Ordered dictionary of request controllers and their request classes in the following order. - `basicspacedata` - `expandedspacedata` - `fileshare` - `spephemeris` For example, if the ``spacetrack.file`` method is used without specifying which controller, the client will choose the `fileshare` controller (which comes before `spephemeris`). .. note:: If new request classes and/or controllers are added to the Space-Track API but not yet to this library, you can safely subclass :class:`SpaceTrackClient` with a copy of this ordered dictionary to add them. That said, please open an issue on `GitHub`_ for me to add them to the library. .. _`GitHub`: https://github.com/python-astrodynamics/spacetrack """ base_url = 'https://www.space-track.org/' # "request class" methods will be looked up by request controller in this # order request_controllers = OrderedDict.fromkeys([ 'basicspacedata', 'expandedspacedata', 'fileshare', 'spephemeris', ]) request_controllers['basicspacedata'] = { 'tle', 'tle_latest', 'tle_publish', 'omm', 'boxscore', 'satcat', 'launch_site', 'satcat_change', 'satcat_debut', 'decay', 'tip', 'announcement', } request_controllers['expandedspacedata'] = { 'cdm', 'organization', 'maneuver', 'maneuver_history', } request_controllers['fileshare'] = { 'file', 'download', 'upload', 'delete', } request_controllers['spephemeris'] = { 'download', 'file', 'file_history', } # List of (class, controller) tuples for # requests which do not return a modeldef offline_predicates = { ('upload', 'fileshare'): {'folder_id', 'file'}, } # These predicates are available for every request class. rest_predicates = { Predicate('predicates', 'str'), Predicate('metadata', 'enum', values=('true', 'false')), Predicate('limit', 'str'), Predicate('orderby', 'str'), Predicate('distinct', 'enum', values=('true', 'false')), Predicate( 'format', 'enum', values=('json', 'xml', 'html', 'csv', 'tle', '3le', 'kvn', 'stream')), Predicate('emptyresult', 'enum', values=('show',)), Predicate('favorites', 'str'), } def __init__(self, identity, password): #: :class:`requests.Session` instance. It can be mutated to configure #: e.g. proxies. self.session = self._create_session() self.identity = identity self.password = password # If set, this will be called when we sleep for the rate limit. self.callback = None self._authenticated = False self._predicates = dict() self._controller_proxies = dict() # "Space-track throttles API use in order to maintain consistent # performance for all users. To avoid error messages, please limit # your query frequency to less than 20 requests per minute." self._ratelimiter = RateLimiter( max_calls=19, period=60, callback=self._ratelimit_callback) def _ratelimit_callback(self, until): duration = int(round(until - time.time())) logger.info('Rate limit reached. Sleeping for {:d} seconds.', duration) if self.callback is not None: self.callback(until) @staticmethod def _create_session(): """Create session for accessing the web. This method is overridden in :class:`spacetrac.aio.AsyncSpaceTrackClient` to use :mod:`aiohttp` instead of :mod:`requests`. """ return requests.Session() def authenticate(self): """Authenticate with Space-Track. Raises: spacetrack.base.AuthenticationError: Incorrect login details. .. note:: This method is called automatically when required. """ if not self._authenticated: login_url = self.base_url + 'ajaxauth/login' data = {'identity': self.identity, 'password': self.password} resp = self.session.post(login_url, data=data) _raise_for_status(resp) # If login failed, we get a JSON response with {'Login': 'Failed'} resp_data = resp.json() if isinstance(resp_data, Mapping): if resp_data.get('Login', None) == 'Failed': raise AuthenticationError() self._authenticated = True @staticmethod def _parse_types(data, predicates): predicate_map = {p.name: p for p in predicates} for obj in data: for key, value in obj.items(): if key.lower() in predicate_map: obj[key] = predicate_map[key.lower()].parse(value) return data def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status_code == 500: # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp.text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period t = threading.Thread(target=self._ratelimit_callback, args=(until,)) t.daemon = True t.start() time.sleep(self._ratelimiter.period) # Now retry with self._ratelimiter: resp = self.session.get(*args, **kwargs) return resp def __getattr__(self, attr): if attr in self.request_controllers: controller_proxy = self._controller_proxies.get(attr) if controller_proxy is None: controller_proxy = _ControllerProxy(self, attr) self._controller_proxies[attr] = controller_proxy return controller_proxy try: controller = self._find_controller(attr) except ValueError: raise AttributeError( "'{name}' object has no attribute '{attr}'" .format(name=self.__class__.__name__, attr=attr)) # generic_request can resolve the controller itself, but we # pass it because we have to check if the class_ is owned # by a controller here anyway. function = partial( self.generic_request, class_=attr, controller=controller) function.get_predicates = partial( self.get_predicates, class_=attr, controller=controller) return function def __dir__(self): """Include request controllers and request classes.""" attrs = list(self.__dict__) request_classes = { class_ for classes in self.request_controllers.values() for class_ in classes} attrs += list(request_classes) attrs += list(self.request_controllers) return sorted(attrs) def _find_controller(self, class_): """Find first controller that matches given request class. Order is specified by the keys of ``SpaceTrackClient.request_controllers`` (:class:`~collections.OrderedDict`) """ for controller, classes in self.request_controllers.items(): if class_ in classes: return controller else: raise ValueError('Unknown request class {!r}'.format(class_)) def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) logger.debug(requests.utils.requote_uri(url)) resp = self._ratelimited_get(url) _raise_for_status(resp) return resp.json()['data'] def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = self._download_predicate_data(class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_] def _parse_predicates_data(self, predicates_data): predicate_objects = [] for field in predicates_data: full_type = field['Type'] type_match = type_re.match(full_type) if not type_match: raise ValueError( "Couldn't parse field type '{}'".format(full_type)) type_name = type_match.group(1) field_name = field['Field'].lower() nullable = (field['Null'] == 'YES') default = field['Default'] types = { # Strings 'char': 'str', 'varchar': 'str', 'longtext': 'str', # varbinary only used for 'file' request class, for the # 'file_link' predicate. 'varbinary': 'str', # Integers 'bigint': 'int', 'int': 'int', 'tinyint': 'int', 'smallint': 'int', 'mediumint': 'int', # Floats 'decimal': 'float', 'float': 'float', 'double': 'float', # Date/Times 'date': 'date', 'timestamp': 'datetime', 'datetime': 'datetime', # Enum 'enum': 'enum', # Bytes 'longblob': 'bytes', } if type_name not in types: raise ValueError("Unknown predicate type '{}'." .format(type_name)) predicate = Predicate( name=field_name, type_=types[type_name], nullable=nullable, default=default) if type_name == 'enum': enum_match = enum_re.match(full_type) if not enum_match: raise ValueError( "Couldn't parse enum type '{}'".format(full_type)) # match.groups() doesn't work for repeating groups, use findall predicate.values = tuple(re.findall(r"'(\w+)'", full_type)) predicate_objects.append(predicate) return predicate_objects def __repr__(self): r = ReprHelper(self) r.parantheses = ('<', '>') r.keyword_from_attr('identity') return str(r)
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient._ratelimited_get
python
def _ratelimited_get(self, *args, **kwargs): with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status_code == 500: # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp.text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period t = threading.Thread(target=self._ratelimit_callback, args=(until,)) t.daemon = True t.start() time.sleep(self._ratelimiter.period) # Now retry with self._ratelimiter: resp = self.session.get(*args, **kwargs) return resp
Perform get request, handling rate limiting.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L415-L441
null
class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #api-requestClasses .. data:: request_controllers Ordered dictionary of request controllers and their request classes in the following order. - `basicspacedata` - `expandedspacedata` - `fileshare` - `spephemeris` For example, if the ``spacetrack.file`` method is used without specifying which controller, the client will choose the `fileshare` controller (which comes before `spephemeris`). .. note:: If new request classes and/or controllers are added to the Space-Track API but not yet to this library, you can safely subclass :class:`SpaceTrackClient` with a copy of this ordered dictionary to add them. That said, please open an issue on `GitHub`_ for me to add them to the library. .. _`GitHub`: https://github.com/python-astrodynamics/spacetrack """ base_url = 'https://www.space-track.org/' # "request class" methods will be looked up by request controller in this # order request_controllers = OrderedDict.fromkeys([ 'basicspacedata', 'expandedspacedata', 'fileshare', 'spephemeris', ]) request_controllers['basicspacedata'] = { 'tle', 'tle_latest', 'tle_publish', 'omm', 'boxscore', 'satcat', 'launch_site', 'satcat_change', 'satcat_debut', 'decay', 'tip', 'announcement', } request_controllers['expandedspacedata'] = { 'cdm', 'organization', 'maneuver', 'maneuver_history', } request_controllers['fileshare'] = { 'file', 'download', 'upload', 'delete', } request_controllers['spephemeris'] = { 'download', 'file', 'file_history', } # List of (class, controller) tuples for # requests which do not return a modeldef offline_predicates = { ('upload', 'fileshare'): {'folder_id', 'file'}, } # These predicates are available for every request class. rest_predicates = { Predicate('predicates', 'str'), Predicate('metadata', 'enum', values=('true', 'false')), Predicate('limit', 'str'), Predicate('orderby', 'str'), Predicate('distinct', 'enum', values=('true', 'false')), Predicate( 'format', 'enum', values=('json', 'xml', 'html', 'csv', 'tle', '3le', 'kvn', 'stream')), Predicate('emptyresult', 'enum', values=('show',)), Predicate('favorites', 'str'), } def __init__(self, identity, password): #: :class:`requests.Session` instance. It can be mutated to configure #: e.g. proxies. self.session = self._create_session() self.identity = identity self.password = password # If set, this will be called when we sleep for the rate limit. self.callback = None self._authenticated = False self._predicates = dict() self._controller_proxies = dict() # "Space-track throttles API use in order to maintain consistent # performance for all users. To avoid error messages, please limit # your query frequency to less than 20 requests per minute." self._ratelimiter = RateLimiter( max_calls=19, period=60, callback=self._ratelimit_callback) def _ratelimit_callback(self, until): duration = int(round(until - time.time())) logger.info('Rate limit reached. Sleeping for {:d} seconds.', duration) if self.callback is not None: self.callback(until) @staticmethod def _create_session(): """Create session for accessing the web. This method is overridden in :class:`spacetrac.aio.AsyncSpaceTrackClient` to use :mod:`aiohttp` instead of :mod:`requests`. """ return requests.Session() def authenticate(self): """Authenticate with Space-Track. Raises: spacetrack.base.AuthenticationError: Incorrect login details. .. note:: This method is called automatically when required. """ if not self._authenticated: login_url = self.base_url + 'ajaxauth/login' data = {'identity': self.identity, 'password': self.password} resp = self.session.post(login_url, data=data) _raise_for_status(resp) # If login failed, we get a JSON response with {'Login': 'Failed'} resp_data = resp.json() if isinstance(resp_data, Mapping): if resp_data.get('Login', None) == 'Failed': raise AuthenticationError() self._authenticated = True def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) Parameters: class\_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned! """ if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: # Validate keyword argument names by querying valid predicates from # Space-Track predicates = self.get_predicates(class_, controller) predicate_fields = {p.name for p in predicates} valid_fields |= predicate_fields else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) if class_ == 'upload' and key == 'file': continue value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(requests.utils.requote_uri(url)) if class_ == 'upload': if 'file' not in kwargs: raise TypeError("missing keyword argument: 'file'") resp = self.session.post(url, files={'file': kwargs['file']}) else: resp = self._ratelimited_get(url, stream=iter_lines or iter_content) _raise_for_status(resp) if resp.encoding is None: resp.encoding = 'UTF-8' if iter_lines: return _iter_lines_generator(resp, decode_unicode=decode) elif iter_content: return _iter_content_generator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: data = resp.text # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = data.replace('\r\n', '\n') else: data = resp.content return data else: data = resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates) @staticmethod def _parse_types(data, predicates): predicate_map = {p.name: p for p in predicates} for obj in data: for key, value in obj.items(): if key.lower() in predicate_map: obj[key] = predicate_map[key.lower()].parse(value) return data def __getattr__(self, attr): if attr in self.request_controllers: controller_proxy = self._controller_proxies.get(attr) if controller_proxy is None: controller_proxy = _ControllerProxy(self, attr) self._controller_proxies[attr] = controller_proxy return controller_proxy try: controller = self._find_controller(attr) except ValueError: raise AttributeError( "'{name}' object has no attribute '{attr}'" .format(name=self.__class__.__name__, attr=attr)) # generic_request can resolve the controller itself, but we # pass it because we have to check if the class_ is owned # by a controller here anyway. function = partial( self.generic_request, class_=attr, controller=controller) function.get_predicates = partial( self.get_predicates, class_=attr, controller=controller) return function def __dir__(self): """Include request controllers and request classes.""" attrs = list(self.__dict__) request_classes = { class_ for classes in self.request_controllers.values() for class_ in classes} attrs += list(request_classes) attrs += list(self.request_controllers) return sorted(attrs) def _find_controller(self, class_): """Find first controller that matches given request class. Order is specified by the keys of ``SpaceTrackClient.request_controllers`` (:class:`~collections.OrderedDict`) """ for controller, classes in self.request_controllers.items(): if class_ in classes: return controller else: raise ValueError('Unknown request class {!r}'.format(class_)) def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) logger.debug(requests.utils.requote_uri(url)) resp = self._ratelimited_get(url) _raise_for_status(resp) return resp.json()['data'] def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = self._download_predicate_data(class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_] def _parse_predicates_data(self, predicates_data): predicate_objects = [] for field in predicates_data: full_type = field['Type'] type_match = type_re.match(full_type) if not type_match: raise ValueError( "Couldn't parse field type '{}'".format(full_type)) type_name = type_match.group(1) field_name = field['Field'].lower() nullable = (field['Null'] == 'YES') default = field['Default'] types = { # Strings 'char': 'str', 'varchar': 'str', 'longtext': 'str', # varbinary only used for 'file' request class, for the # 'file_link' predicate. 'varbinary': 'str', # Integers 'bigint': 'int', 'int': 'int', 'tinyint': 'int', 'smallint': 'int', 'mediumint': 'int', # Floats 'decimal': 'float', 'float': 'float', 'double': 'float', # Date/Times 'date': 'date', 'timestamp': 'datetime', 'datetime': 'datetime', # Enum 'enum': 'enum', # Bytes 'longblob': 'bytes', } if type_name not in types: raise ValueError("Unknown predicate type '{}'." .format(type_name)) predicate = Predicate( name=field_name, type_=types[type_name], nullable=nullable, default=default) if type_name == 'enum': enum_match = enum_re.match(full_type) if not enum_match: raise ValueError( "Couldn't parse enum type '{}'".format(full_type)) # match.groups() doesn't work for repeating groups, use findall predicate.values = tuple(re.findall(r"'(\w+)'", full_type)) predicate_objects.append(predicate) return predicate_objects def __repr__(self): r = ReprHelper(self) r.parantheses = ('<', '>') r.keyword_from_attr('identity') return str(r)
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient._find_controller
python
def _find_controller(self, class_): for controller, classes in self.request_controllers.items(): if class_ in classes: return controller else: raise ValueError('Unknown request class {!r}'.format(class_))
Find first controller that matches given request class. Order is specified by the keys of ``SpaceTrackClient.request_controllers`` (:class:`~collections.OrderedDict`)
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L479-L490
null
class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #api-requestClasses .. data:: request_controllers Ordered dictionary of request controllers and their request classes in the following order. - `basicspacedata` - `expandedspacedata` - `fileshare` - `spephemeris` For example, if the ``spacetrack.file`` method is used without specifying which controller, the client will choose the `fileshare` controller (which comes before `spephemeris`). .. note:: If new request classes and/or controllers are added to the Space-Track API but not yet to this library, you can safely subclass :class:`SpaceTrackClient` with a copy of this ordered dictionary to add them. That said, please open an issue on `GitHub`_ for me to add them to the library. .. _`GitHub`: https://github.com/python-astrodynamics/spacetrack """ base_url = 'https://www.space-track.org/' # "request class" methods will be looked up by request controller in this # order request_controllers = OrderedDict.fromkeys([ 'basicspacedata', 'expandedspacedata', 'fileshare', 'spephemeris', ]) request_controllers['basicspacedata'] = { 'tle', 'tle_latest', 'tle_publish', 'omm', 'boxscore', 'satcat', 'launch_site', 'satcat_change', 'satcat_debut', 'decay', 'tip', 'announcement', } request_controllers['expandedspacedata'] = { 'cdm', 'organization', 'maneuver', 'maneuver_history', } request_controllers['fileshare'] = { 'file', 'download', 'upload', 'delete', } request_controllers['spephemeris'] = { 'download', 'file', 'file_history', } # List of (class, controller) tuples for # requests which do not return a modeldef offline_predicates = { ('upload', 'fileshare'): {'folder_id', 'file'}, } # These predicates are available for every request class. rest_predicates = { Predicate('predicates', 'str'), Predicate('metadata', 'enum', values=('true', 'false')), Predicate('limit', 'str'), Predicate('orderby', 'str'), Predicate('distinct', 'enum', values=('true', 'false')), Predicate( 'format', 'enum', values=('json', 'xml', 'html', 'csv', 'tle', '3le', 'kvn', 'stream')), Predicate('emptyresult', 'enum', values=('show',)), Predicate('favorites', 'str'), } def __init__(self, identity, password): #: :class:`requests.Session` instance. It can be mutated to configure #: e.g. proxies. self.session = self._create_session() self.identity = identity self.password = password # If set, this will be called when we sleep for the rate limit. self.callback = None self._authenticated = False self._predicates = dict() self._controller_proxies = dict() # "Space-track throttles API use in order to maintain consistent # performance for all users. To avoid error messages, please limit # your query frequency to less than 20 requests per minute." self._ratelimiter = RateLimiter( max_calls=19, period=60, callback=self._ratelimit_callback) def _ratelimit_callback(self, until): duration = int(round(until - time.time())) logger.info('Rate limit reached. Sleeping for {:d} seconds.', duration) if self.callback is not None: self.callback(until) @staticmethod def _create_session(): """Create session for accessing the web. This method is overridden in :class:`spacetrac.aio.AsyncSpaceTrackClient` to use :mod:`aiohttp` instead of :mod:`requests`. """ return requests.Session() def authenticate(self): """Authenticate with Space-Track. Raises: spacetrack.base.AuthenticationError: Incorrect login details. .. note:: This method is called automatically when required. """ if not self._authenticated: login_url = self.base_url + 'ajaxauth/login' data = {'identity': self.identity, 'password': self.password} resp = self.session.post(login_url, data=data) _raise_for_status(resp) # If login failed, we get a JSON response with {'Login': 'Failed'} resp_data = resp.json() if isinstance(resp_data, Mapping): if resp_data.get('Login', None) == 'Failed': raise AuthenticationError() self._authenticated = True def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) Parameters: class\_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned! """ if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: # Validate keyword argument names by querying valid predicates from # Space-Track predicates = self.get_predicates(class_, controller) predicate_fields = {p.name for p in predicates} valid_fields |= predicate_fields else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) if class_ == 'upload' and key == 'file': continue value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(requests.utils.requote_uri(url)) if class_ == 'upload': if 'file' not in kwargs: raise TypeError("missing keyword argument: 'file'") resp = self.session.post(url, files={'file': kwargs['file']}) else: resp = self._ratelimited_get(url, stream=iter_lines or iter_content) _raise_for_status(resp) if resp.encoding is None: resp.encoding = 'UTF-8' if iter_lines: return _iter_lines_generator(resp, decode_unicode=decode) elif iter_content: return _iter_content_generator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: data = resp.text # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = data.replace('\r\n', '\n') else: data = resp.content return data else: data = resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates) @staticmethod def _parse_types(data, predicates): predicate_map = {p.name: p for p in predicates} for obj in data: for key, value in obj.items(): if key.lower() in predicate_map: obj[key] = predicate_map[key.lower()].parse(value) return data def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status_code == 500: # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp.text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period t = threading.Thread(target=self._ratelimit_callback, args=(until,)) t.daemon = True t.start() time.sleep(self._ratelimiter.period) # Now retry with self._ratelimiter: resp = self.session.get(*args, **kwargs) return resp def __getattr__(self, attr): if attr in self.request_controllers: controller_proxy = self._controller_proxies.get(attr) if controller_proxy is None: controller_proxy = _ControllerProxy(self, attr) self._controller_proxies[attr] = controller_proxy return controller_proxy try: controller = self._find_controller(attr) except ValueError: raise AttributeError( "'{name}' object has no attribute '{attr}'" .format(name=self.__class__.__name__, attr=attr)) # generic_request can resolve the controller itself, but we # pass it because we have to check if the class_ is owned # by a controller here anyway. function = partial( self.generic_request, class_=attr, controller=controller) function.get_predicates = partial( self.get_predicates, class_=attr, controller=controller) return function def __dir__(self): """Include request controllers and request classes.""" attrs = list(self.__dict__) request_classes = { class_ for classes in self.request_controllers.values() for class_ in classes} attrs += list(request_classes) attrs += list(self.request_controllers) return sorted(attrs) def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) logger.debug(requests.utils.requote_uri(url)) resp = self._ratelimited_get(url) _raise_for_status(resp) return resp.json()['data'] def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = self._download_predicate_data(class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_] def _parse_predicates_data(self, predicates_data): predicate_objects = [] for field in predicates_data: full_type = field['Type'] type_match = type_re.match(full_type) if not type_match: raise ValueError( "Couldn't parse field type '{}'".format(full_type)) type_name = type_match.group(1) field_name = field['Field'].lower() nullable = (field['Null'] == 'YES') default = field['Default'] types = { # Strings 'char': 'str', 'varchar': 'str', 'longtext': 'str', # varbinary only used for 'file' request class, for the # 'file_link' predicate. 'varbinary': 'str', # Integers 'bigint': 'int', 'int': 'int', 'tinyint': 'int', 'smallint': 'int', 'mediumint': 'int', # Floats 'decimal': 'float', 'float': 'float', 'double': 'float', # Date/Times 'date': 'date', 'timestamp': 'datetime', 'datetime': 'datetime', # Enum 'enum': 'enum', # Bytes 'longblob': 'bytes', } if type_name not in types: raise ValueError("Unknown predicate type '{}'." .format(type_name)) predicate = Predicate( name=field_name, type_=types[type_name], nullable=nullable, default=default) if type_name == 'enum': enum_match = enum_re.match(full_type) if not enum_match: raise ValueError( "Couldn't parse enum type '{}'".format(full_type)) # match.groups() doesn't work for repeating groups, use findall predicate.values = tuple(re.findall(r"'(\w+)'", full_type)) predicate_objects.append(predicate) return predicate_objects def __repr__(self): r = ReprHelper(self) r.parantheses = ('<', '>') r.keyword_from_attr('identity') return str(r)
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient._download_predicate_data
python
def _download_predicate_data(self, class_, controller): self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) logger.debug(requests.utils.requote_uri(url)) resp = self._ratelimited_get(url) _raise_for_status(resp) return resp.json()['data']
Get raw predicate information for given request class, and cache for subsequent calls.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L492-L507
[ "def _raise_for_status(response):\n \"\"\"Raises stored :class:`HTTPError`, if one occurred.\n\n This is the :meth:`requests.models.Response.raise_for_status` method,\n modified to add the response from Space-Track, if given.\n \"\"\"\n\n http_error_msg = ''\n\n if 400 <= response.status_code < 500:\n http_error_msg = '%s Client Error: %s for url: %s' % (\n response.status_code, response.reason, response.url)\n\n elif 500 <= response.status_code < 600:\n http_error_msg = '%s Server Error: %s for url: %s' % (\n response.status_code, response.reason, response.url)\n\n if http_error_msg:\n spacetrack_error_msg = None\n\n try:\n json = response.json()\n if isinstance(json, Mapping):\n spacetrack_error_msg = json['error']\n except (ValueError, KeyError):\n pass\n\n if not spacetrack_error_msg:\n spacetrack_error_msg = response.text\n\n if spacetrack_error_msg:\n http_error_msg += '\\nSpace-Track response:\\n' + spacetrack_error_msg\n\n raise requests.HTTPError(http_error_msg, response=response)\n", "def authenticate(self):\n \"\"\"Authenticate with Space-Track.\n\n Raises:\n spacetrack.base.AuthenticationError: Incorrect login details.\n\n .. note::\n\n This method is called automatically when required.\n \"\"\"\n if not self._authenticated:\n login_url = self.base_url + 'ajaxauth/login'\n data = {'identity': self.identity, 'password': self.password}\n resp = self.session.post(login_url, data=data)\n\n _raise_for_status(resp)\n\n # If login failed, we get a JSON response with {'Login': 'Failed'}\n resp_data = resp.json()\n if isinstance(resp_data, Mapping):\n if resp_data.get('Login', None) == 'Failed':\n raise AuthenticationError()\n\n self._authenticated = True\n", "def _ratelimited_get(self, *args, **kwargs):\n \"\"\"Perform get request, handling rate limiting.\"\"\"\n with self._ratelimiter:\n resp = self.session.get(*args, **kwargs)\n\n # It's possible that Space-Track will return HTTP status 500 with a\n # query rate limit violation. This can happen if a script is cancelled\n # before it has finished sleeping to satisfy the rate limit and it is\n # started again.\n #\n # Let's catch this specific instance and retry once if it happens.\n if resp.status_code == 500:\n # Let's only retry if the error page tells us it's a rate limit\n # violation.\n if 'violated your query rate limit' in resp.text:\n # Mimic the RateLimiter callback behaviour.\n until = time.time() + self._ratelimiter.period\n t = threading.Thread(target=self._ratelimit_callback, args=(until,))\n t.daemon = True\n t.start()\n time.sleep(self._ratelimiter.period)\n\n # Now retry\n with self._ratelimiter:\n resp = self.session.get(*args, **kwargs)\n\n return resp\n" ]
class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #api-requestClasses .. data:: request_controllers Ordered dictionary of request controllers and their request classes in the following order. - `basicspacedata` - `expandedspacedata` - `fileshare` - `spephemeris` For example, if the ``spacetrack.file`` method is used without specifying which controller, the client will choose the `fileshare` controller (which comes before `spephemeris`). .. note:: If new request classes and/or controllers are added to the Space-Track API but not yet to this library, you can safely subclass :class:`SpaceTrackClient` with a copy of this ordered dictionary to add them. That said, please open an issue on `GitHub`_ for me to add them to the library. .. _`GitHub`: https://github.com/python-astrodynamics/spacetrack """ base_url = 'https://www.space-track.org/' # "request class" methods will be looked up by request controller in this # order request_controllers = OrderedDict.fromkeys([ 'basicspacedata', 'expandedspacedata', 'fileshare', 'spephemeris', ]) request_controllers['basicspacedata'] = { 'tle', 'tle_latest', 'tle_publish', 'omm', 'boxscore', 'satcat', 'launch_site', 'satcat_change', 'satcat_debut', 'decay', 'tip', 'announcement', } request_controllers['expandedspacedata'] = { 'cdm', 'organization', 'maneuver', 'maneuver_history', } request_controllers['fileshare'] = { 'file', 'download', 'upload', 'delete', } request_controllers['spephemeris'] = { 'download', 'file', 'file_history', } # List of (class, controller) tuples for # requests which do not return a modeldef offline_predicates = { ('upload', 'fileshare'): {'folder_id', 'file'}, } # These predicates are available for every request class. rest_predicates = { Predicate('predicates', 'str'), Predicate('metadata', 'enum', values=('true', 'false')), Predicate('limit', 'str'), Predicate('orderby', 'str'), Predicate('distinct', 'enum', values=('true', 'false')), Predicate( 'format', 'enum', values=('json', 'xml', 'html', 'csv', 'tle', '3le', 'kvn', 'stream')), Predicate('emptyresult', 'enum', values=('show',)), Predicate('favorites', 'str'), } def __init__(self, identity, password): #: :class:`requests.Session` instance. It can be mutated to configure #: e.g. proxies. self.session = self._create_session() self.identity = identity self.password = password # If set, this will be called when we sleep for the rate limit. self.callback = None self._authenticated = False self._predicates = dict() self._controller_proxies = dict() # "Space-track throttles API use in order to maintain consistent # performance for all users. To avoid error messages, please limit # your query frequency to less than 20 requests per minute." self._ratelimiter = RateLimiter( max_calls=19, period=60, callback=self._ratelimit_callback) def _ratelimit_callback(self, until): duration = int(round(until - time.time())) logger.info('Rate limit reached. Sleeping for {:d} seconds.', duration) if self.callback is not None: self.callback(until) @staticmethod def _create_session(): """Create session for accessing the web. This method is overridden in :class:`spacetrac.aio.AsyncSpaceTrackClient` to use :mod:`aiohttp` instead of :mod:`requests`. """ return requests.Session() def authenticate(self): """Authenticate with Space-Track. Raises: spacetrack.base.AuthenticationError: Incorrect login details. .. note:: This method is called automatically when required. """ if not self._authenticated: login_url = self.base_url + 'ajaxauth/login' data = {'identity': self.identity, 'password': self.password} resp = self.session.post(login_url, data=data) _raise_for_status(resp) # If login failed, we get a JSON response with {'Login': 'Failed'} resp_data = resp.json() if isinstance(resp_data, Mapping): if resp_data.get('Login', None) == 'Failed': raise AuthenticationError() self._authenticated = True def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) Parameters: class\_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned! """ if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: # Validate keyword argument names by querying valid predicates from # Space-Track predicates = self.get_predicates(class_, controller) predicate_fields = {p.name for p in predicates} valid_fields |= predicate_fields else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) if class_ == 'upload' and key == 'file': continue value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(requests.utils.requote_uri(url)) if class_ == 'upload': if 'file' not in kwargs: raise TypeError("missing keyword argument: 'file'") resp = self.session.post(url, files={'file': kwargs['file']}) else: resp = self._ratelimited_get(url, stream=iter_lines or iter_content) _raise_for_status(resp) if resp.encoding is None: resp.encoding = 'UTF-8' if iter_lines: return _iter_lines_generator(resp, decode_unicode=decode) elif iter_content: return _iter_content_generator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: data = resp.text # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = data.replace('\r\n', '\n') else: data = resp.content return data else: data = resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates) @staticmethod def _parse_types(data, predicates): predicate_map = {p.name: p for p in predicates} for obj in data: for key, value in obj.items(): if key.lower() in predicate_map: obj[key] = predicate_map[key.lower()].parse(value) return data def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status_code == 500: # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp.text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period t = threading.Thread(target=self._ratelimit_callback, args=(until,)) t.daemon = True t.start() time.sleep(self._ratelimiter.period) # Now retry with self._ratelimiter: resp = self.session.get(*args, **kwargs) return resp def __getattr__(self, attr): if attr in self.request_controllers: controller_proxy = self._controller_proxies.get(attr) if controller_proxy is None: controller_proxy = _ControllerProxy(self, attr) self._controller_proxies[attr] = controller_proxy return controller_proxy try: controller = self._find_controller(attr) except ValueError: raise AttributeError( "'{name}' object has no attribute '{attr}'" .format(name=self.__class__.__name__, attr=attr)) # generic_request can resolve the controller itself, but we # pass it because we have to check if the class_ is owned # by a controller here anyway. function = partial( self.generic_request, class_=attr, controller=controller) function.get_predicates = partial( self.get_predicates, class_=attr, controller=controller) return function def __dir__(self): """Include request controllers and request classes.""" attrs = list(self.__dict__) request_classes = { class_ for classes in self.request_controllers.values() for class_ in classes} attrs += list(request_classes) attrs += list(self.request_controllers) return sorted(attrs) def _find_controller(self, class_): """Find first controller that matches given request class. Order is specified by the keys of ``SpaceTrackClient.request_controllers`` (:class:`~collections.OrderedDict`) """ for controller, classes in self.request_controllers.items(): if class_ in classes: return controller else: raise ValueError('Unknown request class {!r}'.format(class_)) def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = self._download_predicate_data(class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_] def _parse_predicates_data(self, predicates_data): predicate_objects = [] for field in predicates_data: full_type = field['Type'] type_match = type_re.match(full_type) if not type_match: raise ValueError( "Couldn't parse field type '{}'".format(full_type)) type_name = type_match.group(1) field_name = field['Field'].lower() nullable = (field['Null'] == 'YES') default = field['Default'] types = { # Strings 'char': 'str', 'varchar': 'str', 'longtext': 'str', # varbinary only used for 'file' request class, for the # 'file_link' predicate. 'varbinary': 'str', # Integers 'bigint': 'int', 'int': 'int', 'tinyint': 'int', 'smallint': 'int', 'mediumint': 'int', # Floats 'decimal': 'float', 'float': 'float', 'double': 'float', # Date/Times 'date': 'date', 'timestamp': 'datetime', 'datetime': 'datetime', # Enum 'enum': 'enum', # Bytes 'longblob': 'bytes', } if type_name not in types: raise ValueError("Unknown predicate type '{}'." .format(type_name)) predicate = Predicate( name=field_name, type_=types[type_name], nullable=nullable, default=default) if type_name == 'enum': enum_match = enum_re.match(full_type) if not enum_match: raise ValueError( "Couldn't parse enum type '{}'".format(full_type)) # match.groups() doesn't work for repeating groups, use findall predicate.values = tuple(re.findall(r"'(\w+)'", full_type)) predicate_objects.append(predicate) return predicate_objects def __repr__(self): r = ReprHelper(self) r.parantheses = ('<', '>') r.keyword_from_attr('identity') return str(r)
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient.get_predicates
python
def get_predicates(self, class_, controller=None): if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = self._download_predicate_data(class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_]
Get full predicate information for given request class, and cache for subsequent calls.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L509-L529
[ "def _find_controller(self, class_):\n \"\"\"Find first controller that matches given request class.\n\n Order is specified by the keys of\n ``SpaceTrackClient.request_controllers``\n (:class:`~collections.OrderedDict`)\n \"\"\"\n for controller, classes in self.request_controllers.items():\n if class_ in classes:\n return controller\n", "def _download_predicate_data(self, class_, controller):\n \"\"\"Get raw predicate information for given request class, and cache for\n subsequent calls.\n \"\"\"\n self.authenticate()\n\n url = ('{0}{1}/modeldef/class/{2}'\n .format(self.base_url, controller, class_))\n\n logger.debug(requests.utils.requote_uri(url))\n\n resp = self._ratelimited_get(url)\n\n _raise_for_status(resp)\n\n return resp.json()['data']\n", "def _parse_predicates_data(self, predicates_data):\n predicate_objects = []\n for field in predicates_data:\n full_type = field['Type']\n type_match = type_re.match(full_type)\n if not type_match:\n raise ValueError(\n \"Couldn't parse field type '{}'\".format(full_type))\n\n type_name = type_match.group(1)\n field_name = field['Field'].lower()\n nullable = (field['Null'] == 'YES')\n default = field['Default']\n\n types = {\n # Strings\n 'char': 'str',\n 'varchar': 'str',\n 'longtext': 'str',\n # varbinary only used for 'file' request class, for the\n # 'file_link' predicate.\n 'varbinary': 'str',\n # Integers\n 'bigint': 'int',\n 'int': 'int',\n 'tinyint': 'int',\n 'smallint': 'int',\n 'mediumint': 'int',\n # Floats\n 'decimal': 'float',\n 'float': 'float',\n 'double': 'float',\n # Date/Times\n 'date': 'date',\n 'timestamp': 'datetime',\n 'datetime': 'datetime',\n # Enum\n 'enum': 'enum',\n # Bytes\n 'longblob': 'bytes',\n }\n\n if type_name not in types:\n raise ValueError(\"Unknown predicate type '{}'.\"\n .format(type_name))\n\n predicate = Predicate(\n name=field_name,\n type_=types[type_name],\n nullable=nullable,\n default=default)\n\n if type_name == 'enum':\n enum_match = enum_re.match(full_type)\n if not enum_match:\n raise ValueError(\n \"Couldn't parse enum type '{}'\".format(full_type))\n\n # match.groups() doesn't work for repeating groups, use findall\n predicate.values = tuple(re.findall(r\"'(\\w+)'\", full_type))\n\n predicate_objects.append(predicate)\n\n return predicate_objects\n" ]
class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #api-requestClasses .. data:: request_controllers Ordered dictionary of request controllers and their request classes in the following order. - `basicspacedata` - `expandedspacedata` - `fileshare` - `spephemeris` For example, if the ``spacetrack.file`` method is used without specifying which controller, the client will choose the `fileshare` controller (which comes before `spephemeris`). .. note:: If new request classes and/or controllers are added to the Space-Track API but not yet to this library, you can safely subclass :class:`SpaceTrackClient` with a copy of this ordered dictionary to add them. That said, please open an issue on `GitHub`_ for me to add them to the library. .. _`GitHub`: https://github.com/python-astrodynamics/spacetrack """ base_url = 'https://www.space-track.org/' # "request class" methods will be looked up by request controller in this # order request_controllers = OrderedDict.fromkeys([ 'basicspacedata', 'expandedspacedata', 'fileshare', 'spephemeris', ]) request_controllers['basicspacedata'] = { 'tle', 'tle_latest', 'tle_publish', 'omm', 'boxscore', 'satcat', 'launch_site', 'satcat_change', 'satcat_debut', 'decay', 'tip', 'announcement', } request_controllers['expandedspacedata'] = { 'cdm', 'organization', 'maneuver', 'maneuver_history', } request_controllers['fileshare'] = { 'file', 'download', 'upload', 'delete', } request_controllers['spephemeris'] = { 'download', 'file', 'file_history', } # List of (class, controller) tuples for # requests which do not return a modeldef offline_predicates = { ('upload', 'fileshare'): {'folder_id', 'file'}, } # These predicates are available for every request class. rest_predicates = { Predicate('predicates', 'str'), Predicate('metadata', 'enum', values=('true', 'false')), Predicate('limit', 'str'), Predicate('orderby', 'str'), Predicate('distinct', 'enum', values=('true', 'false')), Predicate( 'format', 'enum', values=('json', 'xml', 'html', 'csv', 'tle', '3le', 'kvn', 'stream')), Predicate('emptyresult', 'enum', values=('show',)), Predicate('favorites', 'str'), } def __init__(self, identity, password): #: :class:`requests.Session` instance. It can be mutated to configure #: e.g. proxies. self.session = self._create_session() self.identity = identity self.password = password # If set, this will be called when we sleep for the rate limit. self.callback = None self._authenticated = False self._predicates = dict() self._controller_proxies = dict() # "Space-track throttles API use in order to maintain consistent # performance for all users. To avoid error messages, please limit # your query frequency to less than 20 requests per minute." self._ratelimiter = RateLimiter( max_calls=19, period=60, callback=self._ratelimit_callback) def _ratelimit_callback(self, until): duration = int(round(until - time.time())) logger.info('Rate limit reached. Sleeping for {:d} seconds.', duration) if self.callback is not None: self.callback(until) @staticmethod def _create_session(): """Create session for accessing the web. This method is overridden in :class:`spacetrac.aio.AsyncSpaceTrackClient` to use :mod:`aiohttp` instead of :mod:`requests`. """ return requests.Session() def authenticate(self): """Authenticate with Space-Track. Raises: spacetrack.base.AuthenticationError: Incorrect login details. .. note:: This method is called automatically when required. """ if not self._authenticated: login_url = self.base_url + 'ajaxauth/login' data = {'identity': self.identity, 'password': self.password} resp = self.session.post(login_url, data=data) _raise_for_status(resp) # If login failed, we get a JSON response with {'Login': 'Failed'} resp_data = resp.json() if isinstance(resp_data, Mapping): if resp_data.get('Login', None) == 'Failed': raise AuthenticationError() self._authenticated = True def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) Parameters: class\_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned! """ if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: # Validate keyword argument names by querying valid predicates from # Space-Track predicates = self.get_predicates(class_, controller) predicate_fields = {p.name for p in predicates} valid_fields |= predicate_fields else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) if class_ == 'upload' and key == 'file': continue value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(requests.utils.requote_uri(url)) if class_ == 'upload': if 'file' not in kwargs: raise TypeError("missing keyword argument: 'file'") resp = self.session.post(url, files={'file': kwargs['file']}) else: resp = self._ratelimited_get(url, stream=iter_lines or iter_content) _raise_for_status(resp) if resp.encoding is None: resp.encoding = 'UTF-8' if iter_lines: return _iter_lines_generator(resp, decode_unicode=decode) elif iter_content: return _iter_content_generator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: data = resp.text # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = data.replace('\r\n', '\n') else: data = resp.content return data else: data = resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates) @staticmethod def _parse_types(data, predicates): predicate_map = {p.name: p for p in predicates} for obj in data: for key, value in obj.items(): if key.lower() in predicate_map: obj[key] = predicate_map[key.lower()].parse(value) return data def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status_code == 500: # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp.text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period t = threading.Thread(target=self._ratelimit_callback, args=(until,)) t.daemon = True t.start() time.sleep(self._ratelimiter.period) # Now retry with self._ratelimiter: resp = self.session.get(*args, **kwargs) return resp def __getattr__(self, attr): if attr in self.request_controllers: controller_proxy = self._controller_proxies.get(attr) if controller_proxy is None: controller_proxy = _ControllerProxy(self, attr) self._controller_proxies[attr] = controller_proxy return controller_proxy try: controller = self._find_controller(attr) except ValueError: raise AttributeError( "'{name}' object has no attribute '{attr}'" .format(name=self.__class__.__name__, attr=attr)) # generic_request can resolve the controller itself, but we # pass it because we have to check if the class_ is owned # by a controller here anyway. function = partial( self.generic_request, class_=attr, controller=controller) function.get_predicates = partial( self.get_predicates, class_=attr, controller=controller) return function def __dir__(self): """Include request controllers and request classes.""" attrs = list(self.__dict__) request_classes = { class_ for classes in self.request_controllers.values() for class_ in classes} attrs += list(request_classes) attrs += list(self.request_controllers) return sorted(attrs) def _find_controller(self, class_): """Find first controller that matches given request class. Order is specified by the keys of ``SpaceTrackClient.request_controllers`` (:class:`~collections.OrderedDict`) """ for controller, classes in self.request_controllers.items(): if class_ in classes: return controller else: raise ValueError('Unknown request class {!r}'.format(class_)) def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) logger.debug(requests.utils.requote_uri(url)) resp = self._ratelimited_get(url) _raise_for_status(resp) return resp.json()['data'] def _parse_predicates_data(self, predicates_data): predicate_objects = [] for field in predicates_data: full_type = field['Type'] type_match = type_re.match(full_type) if not type_match: raise ValueError( "Couldn't parse field type '{}'".format(full_type)) type_name = type_match.group(1) field_name = field['Field'].lower() nullable = (field['Null'] == 'YES') default = field['Default'] types = { # Strings 'char': 'str', 'varchar': 'str', 'longtext': 'str', # varbinary only used for 'file' request class, for the # 'file_link' predicate. 'varbinary': 'str', # Integers 'bigint': 'int', 'int': 'int', 'tinyint': 'int', 'smallint': 'int', 'mediumint': 'int', # Floats 'decimal': 'float', 'float': 'float', 'double': 'float', # Date/Times 'date': 'date', 'timestamp': 'datetime', 'datetime': 'datetime', # Enum 'enum': 'enum', # Bytes 'longblob': 'bytes', } if type_name not in types: raise ValueError("Unknown predicate type '{}'." .format(type_name)) predicate = Predicate( name=field_name, type_=types[type_name], nullable=nullable, default=default) if type_name == 'enum': enum_match = enum_re.match(full_type) if not enum_match: raise ValueError( "Couldn't parse enum type '{}'".format(full_type)) # match.groups() doesn't work for repeating groups, use findall predicate.values = tuple(re.findall(r"'(\w+)'", full_type)) predicate_objects.append(predicate) return predicate_objects def __repr__(self): r = ReprHelper(self) r.parantheses = ('<', '>') r.keyword_from_attr('identity') return str(r)
python-astrodynamics/spacetrack
spacetrack/base.py
_ControllerProxy.get_predicates
python
def get_predicates(self, class_): return self.client.get_predicates( class_=class_, controller=self.controller)
Proxy ``get_predicates`` to client with stored request controller.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L632-L637
null
class _ControllerProxy(object): """Proxies request class methods with a preset request controller.""" def __init__(self, client, controller): # The client will cache _ControllerProxy instances, so only store # a weak reference to it. self.client = weakref.proxy(client) self.controller = controller def __getattr__(self, attr): if attr not in self.client.request_controllers[self.controller]: raise AttributeError( "'{self!r}' object has no attribute '{attr}'" .format(self=self, attr=attr)) function = partial( self.client.generic_request, class_=attr, controller=self.controller) function.get_predicates = partial( self.client.get_predicates, class_=attr, controller=self.controller) return function def __repr__(self): r = ReprHelper(self) r.parantheses = ('<', '>') r.keyword_from_attr('controller') return str(r)
howl-anderson/MicroTokenizer
MicroTokenizer/tokenizer_loader.py
TokenizerLoader.create_tokenizer
python
def create_tokenizer(self, name, config=dict()): if name not in self.factories: raise KeyError(Errors.E002.format(name=name)) factory = self.factories[name] return factory(self, **config)
Create a pipeline component from a factory. name (unicode): Factory name to look up in `Language.factories`. config (dict): Configuration parameters to initialise component. RETURNS (callable): Pipeline component.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/tokenizer_loader.py#L44-L54
null
class TokenizerLoader(object): Defaults = BaseDefaults factories = { 'max_match_forward_tokenizer': lambda nlp, **cfg: MaxMatchForwardTokenizer(**cfg), 'max_match_backward_tokenizer': lambda nlp, **cfg: MaxMatchBackwardTokenizer(**cfg), 'max_match_bidirectional_tokenizer': lambda nlp, **cfg: MaxMatchBidirectionalTokenizer(**cfg), 'dag_tokenizer': lambda nlp, **cfg: DAGTokenizer(**cfg), 'hmm_tokenizer': lambda nlp, **cfg: HMMTokenizer(**cfg), 'crf_tokenizer': lambda nlp, **cfg: CRFTokenizer(**cfg) } def __init__(self, meta=None, **kwargs): self.meta = {} if meta is None else meta self.tokenizers = {} def add_tokenizer(self, component, name=None): if issubclass(BaseTokenizer, component.__class__): msg = Errors.E003.format(component=repr(component), name=name) if isinstance(component, basestring_) and component in self.factories: msg += Errors.E004.format(component=component) raise ValueError(msg) if name is None: if hasattr(component, 'name'): name = component.name elif hasattr(component, '__name__'): name = component.__name__ elif (hasattr(component, '__class__') and hasattr(component.__class__, '__name__')): name = component.__class__.__name__ else: name = repr(component) if name in self.tokenizers: raise ValueError(Errors.E007.format(name=name, opts=self.tokenizers.keys())) self.tokenizers[name] = component def from_disk(self, path, disable=tuple()): path = util.ensure_path(path) deserializers = OrderedDict() loader_name_to_tokenizer = defaultdict(list) loader_name_to_class = dict() loader_name_to_instance = dict() for name, tokenizer in self.tokenizers.items(): if name in disable: continue # TODO: why using this in spacy # if not hasattr(tokenizer, 'to_disk'): # continue loader_class = tokenizer.get_loader() loader_name = loader_class.get_name() loader_name_to_tokenizer[loader_name].append(tokenizer) if name not in loader_name_to_class: loader_name_to_class[loader_name] = loader_class for loader_name, loader_class in loader_name_to_class.items(): loader_config = self.meta.get('loader_config', {}).get(loader_name, {}) loader_name_to_instance[loader_name] = loader_class.instance(**loader_config) for loader_name, tokenizer in loader_name_to_tokenizer.items(): loader_instance = loader_name_to_instance[loader_name] # if hasattr(loader_instance, 'skip_load_from_disk'): # continue deserializers[loader_name] = lambda p, loader_instance=loader_instance, tokenizer=tokenizer: loader_instance.from_disk(p, tokenizer), loader_instance.get_model_dir() exclude = {p: False for p in disable} util.from_disk(path, deserializers, exclude) return self def get_tokenizer(self): def assemble_max_match_bidirectional_tokenizer(forward_tokenizer, backward_tokenizer): if forward_tokenizer and backward_tokenizer: max_match_bidirectional_tokenizer = MaxMatchBidirectionalTokenizer() max_match_bidirectional_tokenizer.forward_tokenizer = forward_tokenizer max_match_bidirectional_tokenizer.backward_tokenizer = backward_tokenizer return max_match_bidirectional_tokenizer return None forward_tokenizer = self.tokenizers.get('max_match_forward_tokenizer') backward_tokenizer = self.tokenizers.get('max_match_backward_tokenizer') tokenizer = Tokenizer() tokenizer.max_match_forward_tokenizer = forward_tokenizer tokenizer.max_match_backward_tokenizer = backward_tokenizer tokenizer.max_match_bidirectional_tokenizer = assemble_max_match_bidirectional_tokenizer(forward_tokenizer, backward_tokenizer) tokenizer.hmm_tokenizer = self.tokenizers.get('hmm_tokenizer') tokenizer.dag_tokenizer = self.tokenizers.get('dag_tokenizer') tokenizer.crf_tokenizer = self.tokenizers.get('crf_tokenizer') return tokenizer
howl-anderson/MicroTokenizer
MicroTokenizer/errors.py
add_codes
python
def add_codes(err_cls): class ErrorsWithCodes(object): def __getattribute__(self, code): msg = getattr(err_cls, code) return '[{code}] {msg}'.format(code=code, msg=msg) return ErrorsWithCodes()
Add error codes to string messages via class attribute names.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/errors.py#L9-L15
null
# coding: utf8 from __future__ import unicode_literals import os import warnings import inspect @add_codes class Warnings(object): W001 = ("As of spaCy v2.0, the keyword argument `path=` is deprecated. " "You can now call spacy.load with the path as its first argument, " "and the model's meta.json will be used to determine the language " "to load. For example:\nnlp = spacy.load('{path}')") W002 = ("Tokenizer.from_list is now deprecated. Create a new Doc object " "instead and pass in the strings as the `words` keyword argument, " "for example:\nfrom spacy.tokens import Doc\n" "doc = Doc(nlp.vocab, words=[...])") W003 = ("Positional arguments to Doc.merge are deprecated. Instead, use " "the keyword arguments, for example tag=, lemma= or ent_type=.") W004 = ("No text fixing enabled. Run `pip install ftfy` to enable fixing " "using ftfy.fix_text if necessary.") W005 = ("Doc object not parsed. This means displaCy won't be able to " "generate a dependency visualization for it. Make sure the Doc " "was processed with a model that supports dependency parsing, and " "not just a language class like `English()`. For more info, see " "the docs:\nhttps://spacy.io/usage/models") W006 = ("No entities to visualize found in Doc object. If this is " "surprising to you, make sure the Doc was processed using a model " "that supports named entity recognition, and check the `doc.ents` " "property manually if necessary.") @add_codes class Errors(object): E001 = ("No component '{name}' found in pipeline. Available names: {opts}") E002 = ("Can't find factory for '{name}'. This usually happens when spaCy " "calls `nlp.create_pipe` with a component name that's not built " "in - for example, when constructing the pipeline from a model's " "meta.json. If you're using a custom component, you can write to " "`Language.factories['{name}']` or remove it from the model meta " "and add it via `nlp.add_pipe` instead.") E003 = ("Not a valid pipeline component. Expected callable, but " "got {component} (name: '{name}').") E004 = ("If you meant to add a built-in component, use `create_pipe`: " "`nlp.add_pipe(nlp.create_pipe('{component}'))`") E005 = ("Pipeline component '{name}' returned None. If you're using a " "custom component, maybe you forgot to return the processed Doc?") E006 = ("Invalid constraints. You can only set one of the following: " "before, after, first, last.") E007 = ("'{name}' already exists in pipeline. Existing names: {opts}") E008 = ("Some current components would be lost when restoring previous " "pipeline state. If you added components after calling " "`nlp.disable_pipes()`, you should remove them explicitly with " "`nlp.remove_pipe()` before the pipeline is restored. Names of " "the new components: {names}") E009 = ("The `update` method expects same number of docs and golds, but " "got: {n_docs} docs, {n_golds} golds.") E010 = ("Word vectors set to length 0. This may be because you don't have " "a model installed or loaded, or because your model doesn't " "include word vectors. For more info, see the docs:\n" "https://spacy.io/usage/models") E011 = ("Unknown operator: '{op}'. Options: {opts}") E012 = ("Cannot add pattern for zero tokens to matcher.\nKey: {key}") E013 = ("Error selecting action in matcher") E014 = ("Uknown tag ID: {tag}") E015 = ("Conflicting morphology exception for ({tag}, {orth}). Use " "`force=True` to overwrite.") E016 = ("MultitaskObjective target should be function or one of: dep, " "tag, ent, dep_tag_offset, ent_tag.") E017 = ("Can only add unicode or bytes. Got type: {value_type}") E018 = ("Can't retrieve string for hash '{hash_value}'.") E019 = ("Can't create transition with unknown action ID: {action}. Action " "IDs are enumerated in spacy/syntax/{src}.pyx.") E020 = ("Could not find a gold-standard action to supervise the " "dependency parser. The tree is non-projective (i.e. it has " "crossing arcs - see spacy/syntax/nonproj.pyx for definitions). " "The ArcEager transition system only supports projective trees. " "To learn non-projective representations, transform the data " "before training and after parsing. Either pass " "`make_projective=True` to the GoldParse class, or use " "spacy.syntax.nonproj.preprocess_training_data.") E021 = ("Could not find a gold-standard action to supervise the " "dependency parser. The GoldParse was projective. The transition " "system has {n_actions} actions. State at failure: {state}") E022 = ("Could not find a transition with the name '{name}' in the NER " "model.") E023 = ("Error cleaning up beam: The same state occurred twice at " "memory address {addr} and position {i}.") E024 = ("Could not find an optimal move to supervise the parser. Usually, " "this means the GoldParse was not correct. For example, are all " "labels added to the model?") E025 = ("String is too long: {length} characters. Max is 2**30.") E026 = ("Error accessing token at position {i}: out of bounds in Doc of " "length {length}.") E027 = ("Arguments 'words' and 'spaces' should be sequences of the same " "length, or 'spaces' should be left default at None. spaces " "should be a sequence of booleans, with True meaning that the " "word owns a ' ' character following it.") E028 = ("orths_and_spaces expects either a list of unicode string or a " "list of (unicode, bool) tuples. Got bytes instance: {value}") E029 = ("noun_chunks requires the dependency parse, which requires a " "statistical model to be installed and loaded. For more info, see " "the documentation:\nhttps://spacy.io/usage/models") E030 = ("Sentence boundaries unset. You can add the 'sentencizer' " "component to the pipeline with: " "nlp.add_pipe(nlp.create_pipe('sentencizer')) " "Alternatively, add the dependency parser, or set sentence " "boundaries by setting doc[i].is_sent_start.") E031 = ("Invalid token: empty string ('') at position {i}.") E032 = ("Conflicting attributes specified in doc.from_array(): " "(HEAD, SENT_START). The HEAD attribute currently sets sentence " "boundaries implicitly, based on the tree structure. This means " "the HEAD attribute would potentially override the sentence " "boundaries set by SENT_START.") E033 = ("Cannot load into non-empty Doc of length {length}.") E034 = ("Doc.merge received {n_args} non-keyword arguments. Expected " "either 3 arguments (deprecated), or 0 (use keyword arguments).\n" "Arguments supplied:\n{args}\nKeyword arguments:{kwargs}") E035 = ("Error creating span with start {start} and end {end} for Doc of " "length {length}.") E036 = ("Error calculating span: Can't find a token starting at character " "offset {start}.") E037 = ("Error calculating span: Can't find a token ending at character " "offset {end}.") E038 = ("Error finding sentence for span. Infinite loop detected.") E039 = ("Array bounds exceeded while searching for root word. This likely " "means the parse tree is in an invalid state. Please report this " "issue here: http://github.com/explosion/spaCy/issues") E040 = ("Attempt to access token at {i}, max length {max_length}.") E041 = ("Invalid comparison operator: {op}. Likely a Cython bug?") E042 = ("Error accessing doc[{i}].nbor({j}), for doc of length {length}.") E043 = ("Refusing to write to token.sent_start if its document is parsed, " "because this may cause inconsistent state.") E044 = ("Invalid value for token.sent_start: {value}. Must be one of: " "None, True, False") E045 = ("Possibly infinite loop encountered while looking for {attr}.") E046 = ("Can't retrieve unregistered extension attribute '{name}'. Did " "you forget to call the `set_extension` method?") E047 = ("Can't assign a value to unregistered extension attribute " "'{name}'. Did you forget to call the `set_extension` method?") E048 = ("Can't import language {lang} from spacy.lang.") E049 = ("Can't find spaCy data directory: '{path}'. Check your " "installation and permissions, or use spacy.util.set_data_path " "to customise the location if necessary.") E050 = ("Can't find model '{name}'. It doesn't seem to be a shortcut " "link, a Python package or a valid path to a data directory.") E051 = ("Cant' load '{name}'. If you're using a shortcut link, make sure " "it points to a valid package (not just a data directory).") E052 = ("Can't find model directory: {path}") E053 = ("Could not read meta.json from {path}") E054 = ("No valid '{setting}' setting found in model meta.json.") E055 = ("Invalid ORTH value in exception:\nKey: {key}\nOrths: {orths}") E056 = ("Invalid tokenizer exception: ORTH values combined don't match " "original string.\nKey: {key}\nOrths: {orths}") E057 = ("Stepped slices not supported in Span objects. Try: " "list(tokens)[start:stop:step] instead.") E058 = ("Could not retrieve vector for key {key}.") E059 = ("One (and only one) keyword arg must be set. Got: {kwargs}") E060 = ("Cannot add new key to vectors: the table is full. Current shape: " "({rows}, {cols}).") E061 = ("Bad file name: {filename}. Example of a valid file name: " "'vectors.128.f.bin'") E062 = ("Cannot find empty bit for new lexical flag. All bits between 0 " "and 63 are occupied. You can replace one by specifying the " "`flag_id` explicitly, e.g. " "`nlp.vocab.add_flag(your_func, flag_id=IS_ALPHA`.") E063 = ("Invalid value for flag_id: {value}. Flag IDs must be between 1 " "and 63 (inclusive).") E064 = ("Error fetching a Lexeme from the Vocab. When looking up a " "string, the lexeme returned had an orth ID that did not match " "the query string. This means that the cached lexeme structs are " "mismatched to the string encoding table. The mismatched:\n" "Query string: {string}\nOrth cached: {orth}\nOrth ID: {orth_id}") E065 = ("Only one of the vector table's width and shape can be specified. " "Got width {width} and shape {shape}.") E066 = ("Error creating model helper for extracting columns. Can only " "extract columns by positive integer. Got: {value}.") E067 = ("Invalid BILUO tag sequence: Got a tag starting with 'I' (inside " "an entity) without a preceding 'B' (beginning of an entity). " "Tag sequence:\n{tags}") E068 = ("Invalid BILUO tag: '{tag}'.") E069 = ("Invalid gold-standard parse tree. Found cycle between word " "IDs: {cycle}") E070 = ("Invalid gold-standard data. Number of documents ({n_docs}) " "does not align with number of annotations ({n_annots}).") E071 = ("Error creating lexeme: specified orth ID ({orth}) does not " "match the one in the vocab ({vocab_orth}).") E072 = ("Error serializing lexeme: expected data length {length}, " "got {bad_length}.") E073 = ("Cannot assign vector of length {new_length}. Existing vectors " "are of length {length}. You can use `vocab.reset_vectors` to " "clear the existing vectors and resize the table.") E074 = ("Error interpreting compiled match pattern: patterns are expected " "to end with the attribute {attr}. Got: {bad_attr}.") E075 = ("Error accepting match: length ({length}) > maximum length " "({max_len}).") E076 = ("Error setting tensor on Doc: tensor has {rows} rows, while Doc " "has {words} words.") E077 = ("Error computing {value}: number of Docs ({n_docs}) does not " "equal number of GoldParse objects ({n_golds}) in batch.") E078 = ("Error computing score: number of words in Doc ({words_doc}) does " "not equal number of words in GoldParse ({words_gold}).") E079 = ("Error computing states in beam: number of predicted beams " "({pbeams}) does not equal number of gold beams ({gbeams}).") E080 = ("Duplicate state found in beam: {key}.") E081 = ("Error getting gradient in beam: number of histories ({n_hist}) " "does not equal number of losses ({losses}).") E082 = ("Error deprojectivizing parse: number of heads ({n_heads}), " "projective heads ({n_proj_heads}) and labels ({n_labels}) do not " "match.") E083 = ("Error setting extension: only one of `default`, `method`, or " "`getter` (plus optional `setter`) is allowed. Got: {nr_defined}") E084 = ("Error assigning label ID {label} to span: not in StringStore.") E085 = ("Can't create lexeme for string '{string}'.") E086 = ("Error deserializing lexeme '{string}': orth ID {orth_id} does " "not match hash {hash_id} in StringStore.") E087 = ("Unknown displaCy style: {style}.") E088 = ("Text of length {length} exceeds maximum of {max_length}. The " "v2.x parser and NER models require roughly 1GB of temporary " "memory per 100,000 characters in the input. This means long " "texts may cause memory allocation errors. If you're not using " "the parser or NER, it's probably safe to increase the " "`nlp.max_length` limit. The limit is in number of characters, so " "you can check whether your inputs are too long by checking " "`len(text)`.") E089 = ("Extensions can't have a setter argument without a getter " "argument. Check the keyword arguments on `set_extension`.") E090 = ("Extension '{name}' already exists on {obj}. To overwrite the " "existing extension, set `force=True` on `{obj}.set_extension`.") E091 = ("Invalid extension attribute {name}: expected callable or None, " "but got: {value}") E092 = ("Could not find or assign name for word vectors. Ususally, the " "name is read from the model's meta.json in vector.name. " "Alternatively, it is built from the 'lang' and 'name' keys in " "the meta.json. Vector names are required to avoid issue #1660.") E093 = ("token.ent_iob values make invalid sequence: I without B\n{seq}") E094 = ("Error reading line {line_num} in vectors file {loc}.") E095 = ("Can't write to frozen dictionary. This is likely an internal " "error. Are you writing to a default function argument?") E096 = ("Invalid object passed to displaCy: Can only visualize Doc or " "Span objects, or dicts if set to manual=True.") @add_codes class TempErrors(object): T001 = ("Max length currently 10 for phrase matching") T002 = ("Pattern length ({doc_len}) >= phrase_matcher.max_length " "({max_len}). Length can be set on initialization, up to 10.") T003 = ("Resizing pre-trained Tagger models is not currently supported.") T004 = ("Currently parser depth is hard-coded to 1. Received: {value}.") T005 = ("Currently history size is hard-coded to 0. Received: {value}.") T006 = ("Currently history width is hard-coded to 0. Received: {value}.") T007 = ("Can't yet set {attr} from Span. Vote for this feature on the " "issue tracker: http://github.com/explosion/spaCy/issues") T008 = ("Bad configuration of Tagger. This is probably a bug within " "spaCy. We changed the name of an internal attribute for loading " "pre-trained vectors, and the class has been passed the old name " "(pretrained_dims) but not the new name (pretrained_vectors).") class ModelsWarning(UserWarning): pass WARNINGS = { 'user': UserWarning, 'deprecation': DeprecationWarning, 'models': ModelsWarning, } def _get_warn_types(arg): if arg == '': # don't show any warnings return [] if not arg or arg == 'all': # show all available warnings return WARNINGS.keys() return [w_type.strip() for w_type in arg.split(',') if w_type.strip() in WARNINGS] def _get_warn_excl(arg): if not arg: return [] return [w_id.strip() for w_id in arg.split(',')] SPACY_WARNING_FILTER = os.environ.get('SPACY_WARNING_FILTER') SPACY_WARNING_TYPES = _get_warn_types(os.environ.get('SPACY_WARNING_TYPES')) SPACY_WARNING_IGNORE = _get_warn_excl(os.environ.get('SPACY_WARNING_IGNORE')) def user_warning(message): _warn(message, 'user') def deprecation_warning(message): _warn(message, 'deprecation') def models_warning(message): _warn(message, 'models') def _warn(message, warn_type='user'): """ message (unicode): The message to display. category (Warning): The Warning to show. """ w_id = message.split('[', 1)[1].split(']', 1)[0] # get ID from string if warn_type in SPACY_WARNING_TYPES and w_id not in SPACY_WARNING_IGNORE: category = WARNINGS[warn_type] stack = inspect.stack()[-1] with warnings.catch_warnings(): if SPACY_WARNING_FILTER: warnings.simplefilter(SPACY_WARNING_FILTER, category) warnings.warn_explicit(message, category, stack[1], stack[2])
howl-anderson/MicroTokenizer
MicroTokenizer/errors.py
_warn
python
def _warn(message, warn_type='user'): w_id = message.split('[', 1)[1].split(']', 1)[0] # get ID from string if warn_type in SPACY_WARNING_TYPES and w_id not in SPACY_WARNING_IGNORE: category = WARNINGS[warn_type] stack = inspect.stack()[-1] with warnings.catch_warnings(): if SPACY_WARNING_FILTER: warnings.simplefilter(SPACY_WARNING_FILTER, category) warnings.warn_explicit(message, category, stack[1], stack[2])
message (unicode): The message to display. category (Warning): The Warning to show.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/errors.py#L314-L326
null
# coding: utf8 from __future__ import unicode_literals import os import warnings import inspect def add_codes(err_cls): """Add error codes to string messages via class attribute names.""" class ErrorsWithCodes(object): def __getattribute__(self, code): msg = getattr(err_cls, code) return '[{code}] {msg}'.format(code=code, msg=msg) return ErrorsWithCodes() @add_codes class Warnings(object): W001 = ("As of spaCy v2.0, the keyword argument `path=` is deprecated. " "You can now call spacy.load with the path as its first argument, " "and the model's meta.json will be used to determine the language " "to load. For example:\nnlp = spacy.load('{path}')") W002 = ("Tokenizer.from_list is now deprecated. Create a new Doc object " "instead and pass in the strings as the `words` keyword argument, " "for example:\nfrom spacy.tokens import Doc\n" "doc = Doc(nlp.vocab, words=[...])") W003 = ("Positional arguments to Doc.merge are deprecated. Instead, use " "the keyword arguments, for example tag=, lemma= or ent_type=.") W004 = ("No text fixing enabled. Run `pip install ftfy` to enable fixing " "using ftfy.fix_text if necessary.") W005 = ("Doc object not parsed. This means displaCy won't be able to " "generate a dependency visualization for it. Make sure the Doc " "was processed with a model that supports dependency parsing, and " "not just a language class like `English()`. For more info, see " "the docs:\nhttps://spacy.io/usage/models") W006 = ("No entities to visualize found in Doc object. If this is " "surprising to you, make sure the Doc was processed using a model " "that supports named entity recognition, and check the `doc.ents` " "property manually if necessary.") @add_codes class Errors(object): E001 = ("No component '{name}' found in pipeline. Available names: {opts}") E002 = ("Can't find factory for '{name}'. This usually happens when spaCy " "calls `nlp.create_pipe` with a component name that's not built " "in - for example, when constructing the pipeline from a model's " "meta.json. If you're using a custom component, you can write to " "`Language.factories['{name}']` or remove it from the model meta " "and add it via `nlp.add_pipe` instead.") E003 = ("Not a valid pipeline component. Expected callable, but " "got {component} (name: '{name}').") E004 = ("If you meant to add a built-in component, use `create_pipe`: " "`nlp.add_pipe(nlp.create_pipe('{component}'))`") E005 = ("Pipeline component '{name}' returned None. If you're using a " "custom component, maybe you forgot to return the processed Doc?") E006 = ("Invalid constraints. You can only set one of the following: " "before, after, first, last.") E007 = ("'{name}' already exists in pipeline. Existing names: {opts}") E008 = ("Some current components would be lost when restoring previous " "pipeline state. If you added components after calling " "`nlp.disable_pipes()`, you should remove them explicitly with " "`nlp.remove_pipe()` before the pipeline is restored. Names of " "the new components: {names}") E009 = ("The `update` method expects same number of docs and golds, but " "got: {n_docs} docs, {n_golds} golds.") E010 = ("Word vectors set to length 0. This may be because you don't have " "a model installed or loaded, or because your model doesn't " "include word vectors. For more info, see the docs:\n" "https://spacy.io/usage/models") E011 = ("Unknown operator: '{op}'. Options: {opts}") E012 = ("Cannot add pattern for zero tokens to matcher.\nKey: {key}") E013 = ("Error selecting action in matcher") E014 = ("Uknown tag ID: {tag}") E015 = ("Conflicting morphology exception for ({tag}, {orth}). Use " "`force=True` to overwrite.") E016 = ("MultitaskObjective target should be function or one of: dep, " "tag, ent, dep_tag_offset, ent_tag.") E017 = ("Can only add unicode or bytes. Got type: {value_type}") E018 = ("Can't retrieve string for hash '{hash_value}'.") E019 = ("Can't create transition with unknown action ID: {action}. Action " "IDs are enumerated in spacy/syntax/{src}.pyx.") E020 = ("Could not find a gold-standard action to supervise the " "dependency parser. The tree is non-projective (i.e. it has " "crossing arcs - see spacy/syntax/nonproj.pyx for definitions). " "The ArcEager transition system only supports projective trees. " "To learn non-projective representations, transform the data " "before training and after parsing. Either pass " "`make_projective=True` to the GoldParse class, or use " "spacy.syntax.nonproj.preprocess_training_data.") E021 = ("Could not find a gold-standard action to supervise the " "dependency parser. The GoldParse was projective. The transition " "system has {n_actions} actions. State at failure: {state}") E022 = ("Could not find a transition with the name '{name}' in the NER " "model.") E023 = ("Error cleaning up beam: The same state occurred twice at " "memory address {addr} and position {i}.") E024 = ("Could not find an optimal move to supervise the parser. Usually, " "this means the GoldParse was not correct. For example, are all " "labels added to the model?") E025 = ("String is too long: {length} characters. Max is 2**30.") E026 = ("Error accessing token at position {i}: out of bounds in Doc of " "length {length}.") E027 = ("Arguments 'words' and 'spaces' should be sequences of the same " "length, or 'spaces' should be left default at None. spaces " "should be a sequence of booleans, with True meaning that the " "word owns a ' ' character following it.") E028 = ("orths_and_spaces expects either a list of unicode string or a " "list of (unicode, bool) tuples. Got bytes instance: {value}") E029 = ("noun_chunks requires the dependency parse, which requires a " "statistical model to be installed and loaded. For more info, see " "the documentation:\nhttps://spacy.io/usage/models") E030 = ("Sentence boundaries unset. You can add the 'sentencizer' " "component to the pipeline with: " "nlp.add_pipe(nlp.create_pipe('sentencizer')) " "Alternatively, add the dependency parser, or set sentence " "boundaries by setting doc[i].is_sent_start.") E031 = ("Invalid token: empty string ('') at position {i}.") E032 = ("Conflicting attributes specified in doc.from_array(): " "(HEAD, SENT_START). The HEAD attribute currently sets sentence " "boundaries implicitly, based on the tree structure. This means " "the HEAD attribute would potentially override the sentence " "boundaries set by SENT_START.") E033 = ("Cannot load into non-empty Doc of length {length}.") E034 = ("Doc.merge received {n_args} non-keyword arguments. Expected " "either 3 arguments (deprecated), or 0 (use keyword arguments).\n" "Arguments supplied:\n{args}\nKeyword arguments:{kwargs}") E035 = ("Error creating span with start {start} and end {end} for Doc of " "length {length}.") E036 = ("Error calculating span: Can't find a token starting at character " "offset {start}.") E037 = ("Error calculating span: Can't find a token ending at character " "offset {end}.") E038 = ("Error finding sentence for span. Infinite loop detected.") E039 = ("Array bounds exceeded while searching for root word. This likely " "means the parse tree is in an invalid state. Please report this " "issue here: http://github.com/explosion/spaCy/issues") E040 = ("Attempt to access token at {i}, max length {max_length}.") E041 = ("Invalid comparison operator: {op}. Likely a Cython bug?") E042 = ("Error accessing doc[{i}].nbor({j}), for doc of length {length}.") E043 = ("Refusing to write to token.sent_start if its document is parsed, " "because this may cause inconsistent state.") E044 = ("Invalid value for token.sent_start: {value}. Must be one of: " "None, True, False") E045 = ("Possibly infinite loop encountered while looking for {attr}.") E046 = ("Can't retrieve unregistered extension attribute '{name}'. Did " "you forget to call the `set_extension` method?") E047 = ("Can't assign a value to unregistered extension attribute " "'{name}'. Did you forget to call the `set_extension` method?") E048 = ("Can't import language {lang} from spacy.lang.") E049 = ("Can't find spaCy data directory: '{path}'. Check your " "installation and permissions, or use spacy.util.set_data_path " "to customise the location if necessary.") E050 = ("Can't find model '{name}'. It doesn't seem to be a shortcut " "link, a Python package or a valid path to a data directory.") E051 = ("Cant' load '{name}'. If you're using a shortcut link, make sure " "it points to a valid package (not just a data directory).") E052 = ("Can't find model directory: {path}") E053 = ("Could not read meta.json from {path}") E054 = ("No valid '{setting}' setting found in model meta.json.") E055 = ("Invalid ORTH value in exception:\nKey: {key}\nOrths: {orths}") E056 = ("Invalid tokenizer exception: ORTH values combined don't match " "original string.\nKey: {key}\nOrths: {orths}") E057 = ("Stepped slices not supported in Span objects. Try: " "list(tokens)[start:stop:step] instead.") E058 = ("Could not retrieve vector for key {key}.") E059 = ("One (and only one) keyword arg must be set. Got: {kwargs}") E060 = ("Cannot add new key to vectors: the table is full. Current shape: " "({rows}, {cols}).") E061 = ("Bad file name: {filename}. Example of a valid file name: " "'vectors.128.f.bin'") E062 = ("Cannot find empty bit for new lexical flag. All bits between 0 " "and 63 are occupied. You can replace one by specifying the " "`flag_id` explicitly, e.g. " "`nlp.vocab.add_flag(your_func, flag_id=IS_ALPHA`.") E063 = ("Invalid value for flag_id: {value}. Flag IDs must be between 1 " "and 63 (inclusive).") E064 = ("Error fetching a Lexeme from the Vocab. When looking up a " "string, the lexeme returned had an orth ID that did not match " "the query string. This means that the cached lexeme structs are " "mismatched to the string encoding table. The mismatched:\n" "Query string: {string}\nOrth cached: {orth}\nOrth ID: {orth_id}") E065 = ("Only one of the vector table's width and shape can be specified. " "Got width {width} and shape {shape}.") E066 = ("Error creating model helper for extracting columns. Can only " "extract columns by positive integer. Got: {value}.") E067 = ("Invalid BILUO tag sequence: Got a tag starting with 'I' (inside " "an entity) without a preceding 'B' (beginning of an entity). " "Tag sequence:\n{tags}") E068 = ("Invalid BILUO tag: '{tag}'.") E069 = ("Invalid gold-standard parse tree. Found cycle between word " "IDs: {cycle}") E070 = ("Invalid gold-standard data. Number of documents ({n_docs}) " "does not align with number of annotations ({n_annots}).") E071 = ("Error creating lexeme: specified orth ID ({orth}) does not " "match the one in the vocab ({vocab_orth}).") E072 = ("Error serializing lexeme: expected data length {length}, " "got {bad_length}.") E073 = ("Cannot assign vector of length {new_length}. Existing vectors " "are of length {length}. You can use `vocab.reset_vectors` to " "clear the existing vectors and resize the table.") E074 = ("Error interpreting compiled match pattern: patterns are expected " "to end with the attribute {attr}. Got: {bad_attr}.") E075 = ("Error accepting match: length ({length}) > maximum length " "({max_len}).") E076 = ("Error setting tensor on Doc: tensor has {rows} rows, while Doc " "has {words} words.") E077 = ("Error computing {value}: number of Docs ({n_docs}) does not " "equal number of GoldParse objects ({n_golds}) in batch.") E078 = ("Error computing score: number of words in Doc ({words_doc}) does " "not equal number of words in GoldParse ({words_gold}).") E079 = ("Error computing states in beam: number of predicted beams " "({pbeams}) does not equal number of gold beams ({gbeams}).") E080 = ("Duplicate state found in beam: {key}.") E081 = ("Error getting gradient in beam: number of histories ({n_hist}) " "does not equal number of losses ({losses}).") E082 = ("Error deprojectivizing parse: number of heads ({n_heads}), " "projective heads ({n_proj_heads}) and labels ({n_labels}) do not " "match.") E083 = ("Error setting extension: only one of `default`, `method`, or " "`getter` (plus optional `setter`) is allowed. Got: {nr_defined}") E084 = ("Error assigning label ID {label} to span: not in StringStore.") E085 = ("Can't create lexeme for string '{string}'.") E086 = ("Error deserializing lexeme '{string}': orth ID {orth_id} does " "not match hash {hash_id} in StringStore.") E087 = ("Unknown displaCy style: {style}.") E088 = ("Text of length {length} exceeds maximum of {max_length}. The " "v2.x parser and NER models require roughly 1GB of temporary " "memory per 100,000 characters in the input. This means long " "texts may cause memory allocation errors. If you're not using " "the parser or NER, it's probably safe to increase the " "`nlp.max_length` limit. The limit is in number of characters, so " "you can check whether your inputs are too long by checking " "`len(text)`.") E089 = ("Extensions can't have a setter argument without a getter " "argument. Check the keyword arguments on `set_extension`.") E090 = ("Extension '{name}' already exists on {obj}. To overwrite the " "existing extension, set `force=True` on `{obj}.set_extension`.") E091 = ("Invalid extension attribute {name}: expected callable or None, " "but got: {value}") E092 = ("Could not find or assign name for word vectors. Ususally, the " "name is read from the model's meta.json in vector.name. " "Alternatively, it is built from the 'lang' and 'name' keys in " "the meta.json. Vector names are required to avoid issue #1660.") E093 = ("token.ent_iob values make invalid sequence: I without B\n{seq}") E094 = ("Error reading line {line_num} in vectors file {loc}.") E095 = ("Can't write to frozen dictionary. This is likely an internal " "error. Are you writing to a default function argument?") E096 = ("Invalid object passed to displaCy: Can only visualize Doc or " "Span objects, or dicts if set to manual=True.") @add_codes class TempErrors(object): T001 = ("Max length currently 10 for phrase matching") T002 = ("Pattern length ({doc_len}) >= phrase_matcher.max_length " "({max_len}). Length can be set on initialization, up to 10.") T003 = ("Resizing pre-trained Tagger models is not currently supported.") T004 = ("Currently parser depth is hard-coded to 1. Received: {value}.") T005 = ("Currently history size is hard-coded to 0. Received: {value}.") T006 = ("Currently history width is hard-coded to 0. Received: {value}.") T007 = ("Can't yet set {attr} from Span. Vote for this feature on the " "issue tracker: http://github.com/explosion/spaCy/issues") T008 = ("Bad configuration of Tagger. This is probably a bug within " "spaCy. We changed the name of an internal attribute for loading " "pre-trained vectors, and the class has been passed the old name " "(pretrained_dims) but not the new name (pretrained_vectors).") class ModelsWarning(UserWarning): pass WARNINGS = { 'user': UserWarning, 'deprecation': DeprecationWarning, 'models': ModelsWarning, } def _get_warn_types(arg): if arg == '': # don't show any warnings return [] if not arg or arg == 'all': # show all available warnings return WARNINGS.keys() return [w_type.strip() for w_type in arg.split(',') if w_type.strip() in WARNINGS] def _get_warn_excl(arg): if not arg: return [] return [w_id.strip() for w_id in arg.split(',')] SPACY_WARNING_FILTER = os.environ.get('SPACY_WARNING_FILTER') SPACY_WARNING_TYPES = _get_warn_types(os.environ.get('SPACY_WARNING_TYPES')) SPACY_WARNING_IGNORE = _get_warn_excl(os.environ.get('SPACY_WARNING_IGNORE')) def user_warning(message): _warn(message, 'user') def deprecation_warning(message): _warn(message, 'deprecation') def models_warning(message): _warn(message, 'models')
howl-anderson/MicroTokenizer
MicroTokenizer/cli_command/download.py
download
python
def download(model=None, direct=False, *pip_args): if model is None: model = about.__default_corpus__ if direct: dl = download_model('{m}/{m}.tar.gz#egg={m}'.format(m=model), pip_args) else: shortcuts = get_json(about.__shortcuts__, "available shortcuts") model_name = shortcuts.get(model, model) compatibility = get_compatibility() version = get_version(model_name, compatibility) dl = download_model('{m}-{v}/{m}-{v}.tar.gz#egg={m}=={v}' .format(m=model_name, v=version), pip_args) if dl != 0: # if download subprocess doesn't return 0, exit sys.exit(dl) try: # Get package path here because link uses # pip.get_installed_distributions() to check if model is a # package, which fails if model was just installed via # subprocess package_path = get_package_path(model_name) link(model_name, model, force=True, model_path=package_path) except: # Dirty, but since spacy.download and the auto-linking is # mostly a convenience wrapper, it's best to show a success # message and loading instructions, even if linking fails. prints(Messages.M001.format(name=model_name), title=Messages.M002)
Download compatible model from default download path using pip. Model can be shortcut, model name or, if --direct flag is set, full model name with version.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/cli_command/download.py#L22-L53
[ "def get_version(model, comp):\n model = model.rsplit('.dev', 1)[0]\n if model not in comp:\n prints(Messages.M007.format(name=model, version=about.__version__),\n title=Messages.M005, exits=1)\n return comp[model][0]\n", "def prints(*texts, **kwargs):\n \"\"\"Print formatted message (manual ANSI escape sequences to avoid\n dependency)\n\n *texts (unicode): Texts to print. Each argument is rendered as paragraph.\n **kwargs: 'title' becomes coloured headline. exits=True performs sys exit.\n \"\"\"\n exits = kwargs.get('exits', None)\n title = kwargs.get('title', None)\n title = '\\033[93m{}\\033[0m\\n'.format(_wrap(title)) if title else ''\n message = '\\n\\n'.join([_wrap(text) for text in texts])\n print('\\n{}{}\\n'.format(title, message))\n if exits is not None:\n sys.exit(exits)\n", "def get_package_path(name):\n \"\"\"Get the path to an installed package.\n\n name (unicode): Package name.\n RETURNS (Path): Path to installed package.\n \"\"\"\n name = name.lower() # use lowercase version to be safe\n # Here we're importing the module just to find it. This is worryingly\n # indirect, but it's otherwise very difficult to find the package.\n pkg = importlib.import_module(name)\n return Path(pkg.__file__).parent\n", "def download_model(filename, user_pip_args=None):\n download_url = about.__download_url__ + '/' + filename\n pip_args = ['--no-cache-dir', '--no-deps']\n if user_pip_args:\n pip_args.extend(user_pip_args)\n cmd = [sys.executable, '-m', 'pip', 'install'] + pip_args + [download_url]\n return subprocess.call(cmd, env=os.environ.copy())\n", "def get_json(url, desc):\n r = requests.get(url)\n if r.status_code != 200:\n prints(Messages.M004.format(desc=desc, version=about.__version__),\n title=Messages.M003.format(code=r.status_code), exits=1)\n return r.json()\n", "def get_compatibility():\n version = about.__version__\n version = version.rsplit('.dev', 1)[0]\n comp_table = get_json(about.__compatibility__, \"compatibility table\")\n comp = comp_table['MicroTokenizer']\n if version not in comp:\n prints(Messages.M006.format(version=version), title=Messages.M005,\n exits=1)\n return comp[version]\n" ]
# coding: utf8 from __future__ import unicode_literals import plac import requests import os import subprocess import sys from MicroTokenizer.cli_command._messages import Messages from MicroTokenizer.cli_command.link import link from MicroTokenizer.util import prints, get_package_path from MicroTokenizer import about @plac.annotations( model=("model to download, shortcut or name)", "positional", None, str), direct=("force direct download. Needs model name with version and won't " "perform compatibility check", "flag", "d", bool), pip_args=("additional arguments to be passed to `pip install` when " "installing the model")) def get_json(url, desc): r = requests.get(url) if r.status_code != 200: prints(Messages.M004.format(desc=desc, version=about.__version__), title=Messages.M003.format(code=r.status_code), exits=1) return r.json() def get_compatibility(): version = about.__version__ version = version.rsplit('.dev', 1)[0] comp_table = get_json(about.__compatibility__, "compatibility table") comp = comp_table['MicroTokenizer'] if version not in comp: prints(Messages.M006.format(version=version), title=Messages.M005, exits=1) return comp[version] def get_version(model, comp): model = model.rsplit('.dev', 1)[0] if model not in comp: prints(Messages.M007.format(name=model, version=about.__version__), title=Messages.M005, exits=1) return comp[model][0] def download_model(filename, user_pip_args=None): download_url = about.__download_url__ + '/' + filename pip_args = ['--no-cache-dir', '--no-deps'] if user_pip_args: pip_args.extend(user_pip_args) cmd = [sys.executable, '-m', 'pip', 'install'] + pip_args + [download_url] return subprocess.call(cmd, env=os.environ.copy())
howl-anderson/MicroTokenizer
MicroTokenizer/cli_command/link.py
link
python
def link(origin, link_name, force=False, model_path=None): if util.is_package(origin): model_path = util.get_package_path(origin) else: model_path = Path(origin) if model_path is None else Path(model_path) if not model_path.exists(): prints(Messages.M009.format(path=path2str(model_path)), title=Messages.M008, exits=1) data_path = util.get_data_path() if not data_path or not data_path.exists(): spacy_loc = Path(__file__).parent.parent prints(Messages.M011, spacy_loc, title=Messages.M010, exits=1) link_path = util.get_data_path() / link_name if link_path.is_symlink() and not force: prints(Messages.M013, title=Messages.M012.format(name=link_name), exits=1) elif link_path.is_symlink(): # does a symlink exist? # NB: It's important to check for is_symlink here and not for exists, # because invalid/outdated symlinks would return False otherwise. link_path.unlink() elif link_path.exists(): # does it exist otherwise? # NB: Check this last because valid symlinks also "exist". prints(Messages.M015, link_path, title=Messages.M014.format(name=link_name), exits=1) msg = "%s --> %s" % (path2str(model_path), path2str(link_path)) try: symlink_to(link_path, model_path) except: # This is quite dirty, but just making sure other errors are caught. prints(Messages.M017, msg, title=Messages.M016.format(name=link_name)) raise prints(msg, Messages.M019.format(name=link_name), title=Messages.M018)
Create a symlink for models within the spacy/data directory. Accepts either the name of a pip package, or the local path to the model data directory. Linking models allows loading them via spacy.load(link_name).
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/cli_command/link.py#L17-L53
[ "def is_package(name):\n \"\"\"Check if string maps to a package installed via pip.\n\n name (unicode): Name of package.\n RETURNS (bool): True if installed package, False if not.\n \"\"\"\n name = name.lower() # compare package name against lowercase name\n packages = pkg_resources.working_set.by_key.keys()\n for package in packages:\n if package.lower().replace('-', '_') == name:\n return True\n return False\n", "path2str = lambda path: str(path)\n", "def symlink_to(orig, dest):\n if is_python2 and is_windows:\n import subprocess\n subprocess.call(['mklink', '/d', path2str(orig), path2str(dest)], shell=True)\n else:\n orig.symlink_to(dest)\n", "def prints(*texts, **kwargs):\n \"\"\"Print formatted message (manual ANSI escape sequences to avoid\n dependency)\n\n *texts (unicode): Texts to print. Each argument is rendered as paragraph.\n **kwargs: 'title' becomes coloured headline. exits=True performs sys exit.\n \"\"\"\n exits = kwargs.get('exits', None)\n title = kwargs.get('title', None)\n title = '\\033[93m{}\\033[0m\\n'.format(_wrap(title)) if title else ''\n message = '\\n\\n'.join([_wrap(text) for text in texts])\n print('\\n{}{}\\n'.format(title, message))\n if exits is not None:\n sys.exit(exits)\n" ]
# coding: utf8 from __future__ import unicode_literals import plac from pathlib import Path from ._messages import Messages from ..compat import symlink_to, path2str from ..util import prints from .. import util @plac.annotations( origin=("package name or local path to model", "positional", None, str), link_name=("name of shortuct link to create", "positional", None, str), force=("force overwriting of existing link", "flag", "f", bool))
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
load_model_from_path
python
def load_model_from_path(model_path, meta=False, **overrides): from .tokenizer_loader import TokenizerLoader if not meta: meta = get_model_meta(model_path) tokenizer_loader = TokenizerLoader(meta=meta, **overrides) tokenizers = meta.get('tokenizers', []) disable = overrides.get('disable', []) if tokenizers is True: tokenizers = TokenizerLoader.Defaults.tokenizers elif tokenizers in (False, None): tokenizers = [] for tokenizer_name in tokenizers: if tokenizer_name not in disable: config = meta.get('tokenizer_args', {}).get(tokenizer_name, {}) component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config) tokenizer_loader.add_tokenizer(component, name=tokenizer_name) return tokenizer_loader.from_disk(model_path)
Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L101-L120
[ "def get_model_meta(path):\n \"\"\"Get model meta.json from a directory path and validate its contents.\n\n path (unicode or Path): Path to model directory.\n RETURNS (dict): The model's meta data.\n \"\"\"\n model_path = ensure_path(path)\n if not model_path.exists():\n raise IOError(Errors.E052.format(path=path2str(model_path)))\n meta_path = model_path / 'meta.json'\n if not meta_path.is_file():\n raise IOError(Errors.E053.format(path=meta_path))\n meta = read_json(meta_path)\n for setting in ['name', 'version']:\n if setting not in meta or not meta[setting]:\n raise ValueError(Errors.E054.format(setting=setting))\n return meta\n", "def create_tokenizer(self, name, config=dict()):\n \"\"\"Create a pipeline component from a factory.\n\n name (unicode): Factory name to look up in `Language.factories`.\n config (dict): Configuration parameters to initialise component.\n RETURNS (callable): Pipeline component.\n \"\"\"\n if name not in self.factories:\n raise KeyError(Errors.E002.format(name=name))\n factory = self.factories[name]\n return factory(self, **config)\n", "def add_tokenizer(self, component, name=None):\n if issubclass(BaseTokenizer, component.__class__):\n msg = Errors.E003.format(component=repr(component), name=name)\n if isinstance(component, basestring_) and component in self.factories:\n msg += Errors.E004.format(component=component)\n raise ValueError(msg)\n if name is None:\n if hasattr(component, 'name'):\n name = component.name\n elif hasattr(component, '__name__'):\n name = component.__name__\n elif (hasattr(component, '__class__') and\n hasattr(component.__class__, '__name__')):\n name = component.__class__.__name__\n else:\n name = repr(component)\n if name in self.tokenizers:\n raise ValueError(Errors.E007.format(name=name, opts=self.tokenizers.keys()))\n\n self.tokenizers[name] = component\n", "def from_disk(self, path, disable=tuple()):\n path = util.ensure_path(path)\n deserializers = OrderedDict()\n loader_name_to_tokenizer = defaultdict(list)\n loader_name_to_class = dict()\n loader_name_to_instance = dict()\n for name, tokenizer in self.tokenizers.items():\n if name in disable:\n continue\n\n # TODO: why using this in spacy\n # if not hasattr(tokenizer, 'to_disk'):\n # continue\n\n loader_class = tokenizer.get_loader()\n loader_name = loader_class.get_name()\n loader_name_to_tokenizer[loader_name].append(tokenizer)\n\n if name not in loader_name_to_class:\n loader_name_to_class[loader_name] = loader_class\n\n for loader_name, loader_class in loader_name_to_class.items():\n loader_config = self.meta.get('loader_config', {}).get(loader_name, {})\n loader_name_to_instance[loader_name] = loader_class.instance(**loader_config)\n\n for loader_name, tokenizer in loader_name_to_tokenizer.items():\n loader_instance = loader_name_to_instance[loader_name]\n\n # if hasattr(loader_instance, 'skip_load_from_disk'):\n # continue\n\n deserializers[loader_name] = lambda p, loader_instance=loader_instance, tokenizer=tokenizer: loader_instance.from_disk(p, tokenizer), loader_instance.get_model_dir()\n\n exclude = {p: False for p in disable}\n util.from_disk(path, deserializers, exclude)\n return self\n" ]
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_, input_, unicode_ from .errors import Errors LANGUAGES = {} _data_path = Path(__file__).parent / 'data' _PRINT_ENV = False def set_env_log(value): global _PRINT_ENV _PRINT_ENV = value def get_data_path(require_exists=True): """Get path to spaCy data directory. require_exists (bool): Only return path if it exists, otherwise None. RETURNS (Path or None): Data path or None. """ if not require_exists: return _data_path else: return _data_path if _data_path.exists() else None def set_data_path(path): """Set path to spaCy data directory. path (unicode or Path): Path to new data directory. """ global _data_path _data_path = ensure_path(path) def ensure_path(path): """Ensure string is converted to a Path. path: Anything. If string, it's converted to Path. RETURNS: Path or original argument. """ if isinstance(path, basestring_): return Path(path) else: return path def load_model(name, **overrides): """Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model. """ data_path = get_data_path() if not data_path or not data_path.exists(): raise IOError(Errors.E049.format(path=path2str(data_path))) if isinstance(name, basestring_): # in data dir / shortcut if name in set([d.name for d in data_path.iterdir()]): return load_model_from_link(name, **overrides) if is_package(name): # installed as package return load_model_from_package(name, **overrides) if Path(name).exists(): # path to model data directory return load_model_from_path(Path(name), **overrides) elif hasattr(name, 'exists'): # Path or Path-like to model data return load_model_from_path(name, **overrides) raise IOError(Errors.E050.format(name=name)) def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / '__init__.py' try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(**overrides) def load_model_from_package(name, **overrides): """Load a model from an installed package.""" cls = importlib.import_module(name) return cls.load(**overrides) def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = '%s-%s' % (meta['name'], meta['version']) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides) def get_model_meta(path): """Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data. """ model_path = ensure_path(path) if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(model_path))) meta_path = model_path / 'meta.json' if not meta_path.is_file(): raise IOError(Errors.E053.format(path=meta_path)) meta = read_json(meta_path) for setting in ['name', 'version']: if setting not in meta or not meta[setting]: raise ValueError(Errors.E054.format(setting=setting)) return meta def is_package(name): """Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not. """ name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it's otherwise very difficult to find the package. pkg = importlib.import_module(name) return Path(pkg.__file__).parent def read_regex(path): path = ensure_path(path) with path.open() as file_: entries = file_.read().split('\n') expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) def compile_prefix_regex(entries): if '(' in entries: # Handle deprecated data expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) else: expression = '|'.join(['^' + piece for piece in entries if piece.strip()]) return re.compile(expression) def compile_suffix_regex(entries): expression = '|'.join([piece + '$' for piece in entries if piece.strip()]) return re.compile(expression) def compile_infix_regex(entries): expression = '|'.join([piece for piece in entries if piece.strip()]) return re.compile(expression) def add_lookups(default_func, *lookups): """Extend an attribute function with special cases. If a word is in the lookups, the value is returned. Otherwise the previous function is used. default_func (callable): The default function to execute. *lookups (dict): Lookup dictionary mapping string to attribute value. RETURNS (callable): Lexical attribute getter. """ # This is implemented as functools.partial instead of a closure, to allow # pickle to work. return functools.partial(_get_attr_unless_lookup, default_func, lookups) def _get_attr_unless_lookup(default_func, lookups, string): for lookup in lookups: if string in lookup: return lookup[string] return default_func(string) def normalize_slice(length, start, stop, step=None): if not (step is None or step == 1): raise ValueError(Errors.E057) if start is None: start = 0 elif start < 0: start += length start = min(length, max(0, start)) if stop is None: stop = length elif stop < 0: stop += length stop = min(length, max(start, stop)) return start, stop def compounding(start, stop, compound): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert next(sizes) == 1.5 * 1.5 """ def clip(value): return max(value, stop) if (start > stop) else min(value, stop) curr = float(start) while True: yield clip(curr) curr *= compound def decaying(start, stop, decay): """Yield an infinite series of linearly decaying values.""" def clip(value): return max(value, stop) if (start > stop) else min(value, stop) nr_upd = 1. while True: yield clip(start * 1./(1. + decay * nr_upd)) nr_upd += 1 def itershuffle(iterable, bufsize=1000): """Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 iterable (iterable): Iterator to shuffle. bufsize (int): Items to hold back. YIELDS (iterable): The shuffled iterator. """ iterable = iter(iterable) buf = [] try: while True: for i in range(random.randint(1, bufsize-len(buf))): buf.append(iterable.next()) random.shuffle(buf) for i in range(random.randint(1, bufsize)): if buf: yield buf.pop() else: break except StopIteration: random.shuffle(buf) while buf: yield buf.pop() raise StopIteration def read_json(location): """Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content. """ location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f) def get_raw_input(description, default=False): """Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input. """ additional = ' (default: %s)' % default if default else '' prompt = ' %s%s: ' % (description, additional) user_input = input_(prompt) return user_input def to_disk(path, writers, exclude): path = ensure_path(path) if not path.exists(): path.mkdir() for key, writer in writers.items(): if key not in exclude: writer(path / key) return path def from_disk(path, readers, exclude): path = ensure_path(path) for key, args in readers.items(): reader, model_dir = args model_dir = model_dir if model_dir else key if key not in exclude: reader(path / model_dir) return path def print_table(data, title=None): """Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above. """ if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table)) def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ def excl_value(value): # contains path, i.e. personal info return isinstance(value, basestring_) and Path(value).exists() if isinstance(data, dict): data = list(data.items()) markdown = ["* **{}:** {}".format(l, unicode_(v)) for l, v in data if not excl_value(v)] if title: print("\n## {}".format(title)) print('\n{}\n'.format('\n'.join(markdown))) def prints(*texts, **kwargs): """Print formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit. """ exits = kwargs.get('exits', None) title = kwargs.get('title', None) title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else '' message = '\n\n'.join([_wrap(text) for text in texts]) print('\n{}{}\n'.format(title, message)) if exits is not None: sys.exit(exits) def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text. """ indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False) def minify_html(html): """Perform a template-specific, rudimentary HTML minification for displaCy. Disclaimer: NOT a general-purpose solution, only removes indentation and newlines. html (unicode): Markup to minify. RETURNS (unicode): "Minified" HTML. """ return html.strip().replace(' ', '').replace('\n', '') def escape_html(text): """Replace <, >, &, " with their HTML encoded representation. Intended to prevent HTML errors in rendered displaCy markup. text (unicode): The original text. RETURNS (unicode): Equivalent text to be safely used within HTML. """ text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text def fix_random_seed(seed=0): random.seed(seed) numpy.random.seed(seed) class SimpleFrozenDict(dict): """Simplified implementation of a frozen dict, mainly used as default function or method argument (for arguments that should default to empty dictionary). Will raise an error if user or spaCy attempts to add to dict. """ def __setitem__(self, key, value): raise NotImplementedError(Errors.E095) def pop(self, key, default=None): raise NotImplementedError(Errors.E095) def update(self, other): raise NotImplementedError(Errors.E095)
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
is_package
python
def is_package(name): name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False
Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L159-L170
null
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_, input_, unicode_ from .errors import Errors LANGUAGES = {} _data_path = Path(__file__).parent / 'data' _PRINT_ENV = False def set_env_log(value): global _PRINT_ENV _PRINT_ENV = value def get_data_path(require_exists=True): """Get path to spaCy data directory. require_exists (bool): Only return path if it exists, otherwise None. RETURNS (Path or None): Data path or None. """ if not require_exists: return _data_path else: return _data_path if _data_path.exists() else None def set_data_path(path): """Set path to spaCy data directory. path (unicode or Path): Path to new data directory. """ global _data_path _data_path = ensure_path(path) def ensure_path(path): """Ensure string is converted to a Path. path: Anything. If string, it's converted to Path. RETURNS: Path or original argument. """ if isinstance(path, basestring_): return Path(path) else: return path def load_model(name, **overrides): """Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model. """ data_path = get_data_path() if not data_path or not data_path.exists(): raise IOError(Errors.E049.format(path=path2str(data_path))) if isinstance(name, basestring_): # in data dir / shortcut if name in set([d.name for d in data_path.iterdir()]): return load_model_from_link(name, **overrides) if is_package(name): # installed as package return load_model_from_package(name, **overrides) if Path(name).exists(): # path to model data directory return load_model_from_path(Path(name), **overrides) elif hasattr(name, 'exists'): # Path or Path-like to model data return load_model_from_path(name, **overrides) raise IOError(Errors.E050.format(name=name)) def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / '__init__.py' try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(**overrides) def load_model_from_package(name, **overrides): """Load a model from an installed package.""" cls = importlib.import_module(name) return cls.load(**overrides) def load_model_from_path(model_path, meta=False, **overrides): """Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.""" from .tokenizer_loader import TokenizerLoader if not meta: meta = get_model_meta(model_path) tokenizer_loader = TokenizerLoader(meta=meta, **overrides) tokenizers = meta.get('tokenizers', []) disable = overrides.get('disable', []) if tokenizers is True: tokenizers = TokenizerLoader.Defaults.tokenizers elif tokenizers in (False, None): tokenizers = [] for tokenizer_name in tokenizers: if tokenizer_name not in disable: config = meta.get('tokenizer_args', {}).get(tokenizer_name, {}) component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config) tokenizer_loader.add_tokenizer(component, name=tokenizer_name) return tokenizer_loader.from_disk(model_path) def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = '%s-%s' % (meta['name'], meta['version']) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides) def get_model_meta(path): """Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data. """ model_path = ensure_path(path) if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(model_path))) meta_path = model_path / 'meta.json' if not meta_path.is_file(): raise IOError(Errors.E053.format(path=meta_path)) meta = read_json(meta_path) for setting in ['name', 'version']: if setting not in meta or not meta[setting]: raise ValueError(Errors.E054.format(setting=setting)) return meta def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it's otherwise very difficult to find the package. pkg = importlib.import_module(name) return Path(pkg.__file__).parent def read_regex(path): path = ensure_path(path) with path.open() as file_: entries = file_.read().split('\n') expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) def compile_prefix_regex(entries): if '(' in entries: # Handle deprecated data expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) else: expression = '|'.join(['^' + piece for piece in entries if piece.strip()]) return re.compile(expression) def compile_suffix_regex(entries): expression = '|'.join([piece + '$' for piece in entries if piece.strip()]) return re.compile(expression) def compile_infix_regex(entries): expression = '|'.join([piece for piece in entries if piece.strip()]) return re.compile(expression) def add_lookups(default_func, *lookups): """Extend an attribute function with special cases. If a word is in the lookups, the value is returned. Otherwise the previous function is used. default_func (callable): The default function to execute. *lookups (dict): Lookup dictionary mapping string to attribute value. RETURNS (callable): Lexical attribute getter. """ # This is implemented as functools.partial instead of a closure, to allow # pickle to work. return functools.partial(_get_attr_unless_lookup, default_func, lookups) def _get_attr_unless_lookup(default_func, lookups, string): for lookup in lookups: if string in lookup: return lookup[string] return default_func(string) def normalize_slice(length, start, stop, step=None): if not (step is None or step == 1): raise ValueError(Errors.E057) if start is None: start = 0 elif start < 0: start += length start = min(length, max(0, start)) if stop is None: stop = length elif stop < 0: stop += length stop = min(length, max(start, stop)) return start, stop def compounding(start, stop, compound): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert next(sizes) == 1.5 * 1.5 """ def clip(value): return max(value, stop) if (start > stop) else min(value, stop) curr = float(start) while True: yield clip(curr) curr *= compound def decaying(start, stop, decay): """Yield an infinite series of linearly decaying values.""" def clip(value): return max(value, stop) if (start > stop) else min(value, stop) nr_upd = 1. while True: yield clip(start * 1./(1. + decay * nr_upd)) nr_upd += 1 def itershuffle(iterable, bufsize=1000): """Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 iterable (iterable): Iterator to shuffle. bufsize (int): Items to hold back. YIELDS (iterable): The shuffled iterator. """ iterable = iter(iterable) buf = [] try: while True: for i in range(random.randint(1, bufsize-len(buf))): buf.append(iterable.next()) random.shuffle(buf) for i in range(random.randint(1, bufsize)): if buf: yield buf.pop() else: break except StopIteration: random.shuffle(buf) while buf: yield buf.pop() raise StopIteration def read_json(location): """Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content. """ location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f) def get_raw_input(description, default=False): """Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input. """ additional = ' (default: %s)' % default if default else '' prompt = ' %s%s: ' % (description, additional) user_input = input_(prompt) return user_input def to_disk(path, writers, exclude): path = ensure_path(path) if not path.exists(): path.mkdir() for key, writer in writers.items(): if key not in exclude: writer(path / key) return path def from_disk(path, readers, exclude): path = ensure_path(path) for key, args in readers.items(): reader, model_dir = args model_dir = model_dir if model_dir else key if key not in exclude: reader(path / model_dir) return path def print_table(data, title=None): """Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above. """ if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table)) def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ def excl_value(value): # contains path, i.e. personal info return isinstance(value, basestring_) and Path(value).exists() if isinstance(data, dict): data = list(data.items()) markdown = ["* **{}:** {}".format(l, unicode_(v)) for l, v in data if not excl_value(v)] if title: print("\n## {}".format(title)) print('\n{}\n'.format('\n'.join(markdown))) def prints(*texts, **kwargs): """Print formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit. """ exits = kwargs.get('exits', None) title = kwargs.get('title', None) title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else '' message = '\n\n'.join([_wrap(text) for text in texts]) print('\n{}{}\n'.format(title, message)) if exits is not None: sys.exit(exits) def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text. """ indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False) def minify_html(html): """Perform a template-specific, rudimentary HTML minification for displaCy. Disclaimer: NOT a general-purpose solution, only removes indentation and newlines. html (unicode): Markup to minify. RETURNS (unicode): "Minified" HTML. """ return html.strip().replace(' ', '').replace('\n', '') def escape_html(text): """Replace <, >, &, " with their HTML encoded representation. Intended to prevent HTML errors in rendered displaCy markup. text (unicode): The original text. RETURNS (unicode): Equivalent text to be safely used within HTML. """ text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text def fix_random_seed(seed=0): random.seed(seed) numpy.random.seed(seed) class SimpleFrozenDict(dict): """Simplified implementation of a frozen dict, mainly used as default function or method argument (for arguments that should default to empty dictionary). Will raise an error if user or spaCy attempts to add to dict. """ def __setitem__(self, key, value): raise NotImplementedError(Errors.E095) def pop(self, key, default=None): raise NotImplementedError(Errors.E095) def update(self, other): raise NotImplementedError(Errors.E095)
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
decaying
python
def decaying(start, stop, decay): def clip(value): return max(value, stop) if (start > stop) else min(value, stop) nr_upd = 1. while True: yield clip(start * 1./(1. + decay * nr_upd)) nr_upd += 1
Yield an infinite series of linearly decaying values.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L272-L279
[ "def clip(value):\n return max(value, stop) if (start > stop) else min(value, stop)\n" ]
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_, input_, unicode_ from .errors import Errors LANGUAGES = {} _data_path = Path(__file__).parent / 'data' _PRINT_ENV = False def set_env_log(value): global _PRINT_ENV _PRINT_ENV = value def get_data_path(require_exists=True): """Get path to spaCy data directory. require_exists (bool): Only return path if it exists, otherwise None. RETURNS (Path or None): Data path or None. """ if not require_exists: return _data_path else: return _data_path if _data_path.exists() else None def set_data_path(path): """Set path to spaCy data directory. path (unicode or Path): Path to new data directory. """ global _data_path _data_path = ensure_path(path) def ensure_path(path): """Ensure string is converted to a Path. path: Anything. If string, it's converted to Path. RETURNS: Path or original argument. """ if isinstance(path, basestring_): return Path(path) else: return path def load_model(name, **overrides): """Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model. """ data_path = get_data_path() if not data_path or not data_path.exists(): raise IOError(Errors.E049.format(path=path2str(data_path))) if isinstance(name, basestring_): # in data dir / shortcut if name in set([d.name for d in data_path.iterdir()]): return load_model_from_link(name, **overrides) if is_package(name): # installed as package return load_model_from_package(name, **overrides) if Path(name).exists(): # path to model data directory return load_model_from_path(Path(name), **overrides) elif hasattr(name, 'exists'): # Path or Path-like to model data return load_model_from_path(name, **overrides) raise IOError(Errors.E050.format(name=name)) def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / '__init__.py' try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(**overrides) def load_model_from_package(name, **overrides): """Load a model from an installed package.""" cls = importlib.import_module(name) return cls.load(**overrides) def load_model_from_path(model_path, meta=False, **overrides): """Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.""" from .tokenizer_loader import TokenizerLoader if not meta: meta = get_model_meta(model_path) tokenizer_loader = TokenizerLoader(meta=meta, **overrides) tokenizers = meta.get('tokenizers', []) disable = overrides.get('disable', []) if tokenizers is True: tokenizers = TokenizerLoader.Defaults.tokenizers elif tokenizers in (False, None): tokenizers = [] for tokenizer_name in tokenizers: if tokenizer_name not in disable: config = meta.get('tokenizer_args', {}).get(tokenizer_name, {}) component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config) tokenizer_loader.add_tokenizer(component, name=tokenizer_name) return tokenizer_loader.from_disk(model_path) def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = '%s-%s' % (meta['name'], meta['version']) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides) def get_model_meta(path): """Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data. """ model_path = ensure_path(path) if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(model_path))) meta_path = model_path / 'meta.json' if not meta_path.is_file(): raise IOError(Errors.E053.format(path=meta_path)) meta = read_json(meta_path) for setting in ['name', 'version']: if setting not in meta or not meta[setting]: raise ValueError(Errors.E054.format(setting=setting)) return meta def is_package(name): """Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not. """ name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it's otherwise very difficult to find the package. pkg = importlib.import_module(name) return Path(pkg.__file__).parent def read_regex(path): path = ensure_path(path) with path.open() as file_: entries = file_.read().split('\n') expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) def compile_prefix_regex(entries): if '(' in entries: # Handle deprecated data expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) else: expression = '|'.join(['^' + piece for piece in entries if piece.strip()]) return re.compile(expression) def compile_suffix_regex(entries): expression = '|'.join([piece + '$' for piece in entries if piece.strip()]) return re.compile(expression) def compile_infix_regex(entries): expression = '|'.join([piece for piece in entries if piece.strip()]) return re.compile(expression) def add_lookups(default_func, *lookups): """Extend an attribute function with special cases. If a word is in the lookups, the value is returned. Otherwise the previous function is used. default_func (callable): The default function to execute. *lookups (dict): Lookup dictionary mapping string to attribute value. RETURNS (callable): Lexical attribute getter. """ # This is implemented as functools.partial instead of a closure, to allow # pickle to work. return functools.partial(_get_attr_unless_lookup, default_func, lookups) def _get_attr_unless_lookup(default_func, lookups, string): for lookup in lookups: if string in lookup: return lookup[string] return default_func(string) def normalize_slice(length, start, stop, step=None): if not (step is None or step == 1): raise ValueError(Errors.E057) if start is None: start = 0 elif start < 0: start += length start = min(length, max(0, start)) if stop is None: stop = length elif stop < 0: stop += length stop = min(length, max(start, stop)) return start, stop def compounding(start, stop, compound): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert next(sizes) == 1.5 * 1.5 """ def clip(value): return max(value, stop) if (start > stop) else min(value, stop) curr = float(start) while True: yield clip(curr) curr *= compound def itershuffle(iterable, bufsize=1000): """Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 iterable (iterable): Iterator to shuffle. bufsize (int): Items to hold back. YIELDS (iterable): The shuffled iterator. """ iterable = iter(iterable) buf = [] try: while True: for i in range(random.randint(1, bufsize-len(buf))): buf.append(iterable.next()) random.shuffle(buf) for i in range(random.randint(1, bufsize)): if buf: yield buf.pop() else: break except StopIteration: random.shuffle(buf) while buf: yield buf.pop() raise StopIteration def read_json(location): """Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content. """ location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f) def get_raw_input(description, default=False): """Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input. """ additional = ' (default: %s)' % default if default else '' prompt = ' %s%s: ' % (description, additional) user_input = input_(prompt) return user_input def to_disk(path, writers, exclude): path = ensure_path(path) if not path.exists(): path.mkdir() for key, writer in writers.items(): if key not in exclude: writer(path / key) return path def from_disk(path, readers, exclude): path = ensure_path(path) for key, args in readers.items(): reader, model_dir = args model_dir = model_dir if model_dir else key if key not in exclude: reader(path / model_dir) return path def print_table(data, title=None): """Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above. """ if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table)) def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ def excl_value(value): # contains path, i.e. personal info return isinstance(value, basestring_) and Path(value).exists() if isinstance(data, dict): data = list(data.items()) markdown = ["* **{}:** {}".format(l, unicode_(v)) for l, v in data if not excl_value(v)] if title: print("\n## {}".format(title)) print('\n{}\n'.format('\n'.join(markdown))) def prints(*texts, **kwargs): """Print formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit. """ exits = kwargs.get('exits', None) title = kwargs.get('title', None) title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else '' message = '\n\n'.join([_wrap(text) for text in texts]) print('\n{}{}\n'.format(title, message)) if exits is not None: sys.exit(exits) def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text. """ indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False) def minify_html(html): """Perform a template-specific, rudimentary HTML minification for displaCy. Disclaimer: NOT a general-purpose solution, only removes indentation and newlines. html (unicode): Markup to minify. RETURNS (unicode): "Minified" HTML. """ return html.strip().replace(' ', '').replace('\n', '') def escape_html(text): """Replace <, >, &, " with their HTML encoded representation. Intended to prevent HTML errors in rendered displaCy markup. text (unicode): The original text. RETURNS (unicode): Equivalent text to be safely used within HTML. """ text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text def fix_random_seed(seed=0): random.seed(seed) numpy.random.seed(seed) class SimpleFrozenDict(dict): """Simplified implementation of a frozen dict, mainly used as default function or method argument (for arguments that should default to empty dictionary). Will raise an error if user or spaCy attempts to add to dict. """ def __setitem__(self, key, value): raise NotImplementedError(Errors.E095) def pop(self, key, default=None): raise NotImplementedError(Errors.E095) def update(self, other): raise NotImplementedError(Errors.E095)
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
read_json
python
def read_json(location): location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f)
Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L311-L319
[ "def ensure_path(path):\n \"\"\"Ensure string is converted to a Path.\n\n path: Anything. If string, it's converted to Path.\n RETURNS: Path or original argument.\n \"\"\"\n if isinstance(path, basestring_):\n return Path(path)\n else:\n return path\n" ]
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_, input_, unicode_ from .errors import Errors LANGUAGES = {} _data_path = Path(__file__).parent / 'data' _PRINT_ENV = False def set_env_log(value): global _PRINT_ENV _PRINT_ENV = value def get_data_path(require_exists=True): """Get path to spaCy data directory. require_exists (bool): Only return path if it exists, otherwise None. RETURNS (Path or None): Data path or None. """ if not require_exists: return _data_path else: return _data_path if _data_path.exists() else None def set_data_path(path): """Set path to spaCy data directory. path (unicode or Path): Path to new data directory. """ global _data_path _data_path = ensure_path(path) def ensure_path(path): """Ensure string is converted to a Path. path: Anything. If string, it's converted to Path. RETURNS: Path or original argument. """ if isinstance(path, basestring_): return Path(path) else: return path def load_model(name, **overrides): """Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model. """ data_path = get_data_path() if not data_path or not data_path.exists(): raise IOError(Errors.E049.format(path=path2str(data_path))) if isinstance(name, basestring_): # in data dir / shortcut if name in set([d.name for d in data_path.iterdir()]): return load_model_from_link(name, **overrides) if is_package(name): # installed as package return load_model_from_package(name, **overrides) if Path(name).exists(): # path to model data directory return load_model_from_path(Path(name), **overrides) elif hasattr(name, 'exists'): # Path or Path-like to model data return load_model_from_path(name, **overrides) raise IOError(Errors.E050.format(name=name)) def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / '__init__.py' try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(**overrides) def load_model_from_package(name, **overrides): """Load a model from an installed package.""" cls = importlib.import_module(name) return cls.load(**overrides) def load_model_from_path(model_path, meta=False, **overrides): """Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.""" from .tokenizer_loader import TokenizerLoader if not meta: meta = get_model_meta(model_path) tokenizer_loader = TokenizerLoader(meta=meta, **overrides) tokenizers = meta.get('tokenizers', []) disable = overrides.get('disable', []) if tokenizers is True: tokenizers = TokenizerLoader.Defaults.tokenizers elif tokenizers in (False, None): tokenizers = [] for tokenizer_name in tokenizers: if tokenizer_name not in disable: config = meta.get('tokenizer_args', {}).get(tokenizer_name, {}) component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config) tokenizer_loader.add_tokenizer(component, name=tokenizer_name) return tokenizer_loader.from_disk(model_path) def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = '%s-%s' % (meta['name'], meta['version']) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides) def get_model_meta(path): """Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data. """ model_path = ensure_path(path) if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(model_path))) meta_path = model_path / 'meta.json' if not meta_path.is_file(): raise IOError(Errors.E053.format(path=meta_path)) meta = read_json(meta_path) for setting in ['name', 'version']: if setting not in meta or not meta[setting]: raise ValueError(Errors.E054.format(setting=setting)) return meta def is_package(name): """Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not. """ name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it's otherwise very difficult to find the package. pkg = importlib.import_module(name) return Path(pkg.__file__).parent def read_regex(path): path = ensure_path(path) with path.open() as file_: entries = file_.read().split('\n') expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) def compile_prefix_regex(entries): if '(' in entries: # Handle deprecated data expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) else: expression = '|'.join(['^' + piece for piece in entries if piece.strip()]) return re.compile(expression) def compile_suffix_regex(entries): expression = '|'.join([piece + '$' for piece in entries if piece.strip()]) return re.compile(expression) def compile_infix_regex(entries): expression = '|'.join([piece for piece in entries if piece.strip()]) return re.compile(expression) def add_lookups(default_func, *lookups): """Extend an attribute function with special cases. If a word is in the lookups, the value is returned. Otherwise the previous function is used. default_func (callable): The default function to execute. *lookups (dict): Lookup dictionary mapping string to attribute value. RETURNS (callable): Lexical attribute getter. """ # This is implemented as functools.partial instead of a closure, to allow # pickle to work. return functools.partial(_get_attr_unless_lookup, default_func, lookups) def _get_attr_unless_lookup(default_func, lookups, string): for lookup in lookups: if string in lookup: return lookup[string] return default_func(string) def normalize_slice(length, start, stop, step=None): if not (step is None or step == 1): raise ValueError(Errors.E057) if start is None: start = 0 elif start < 0: start += length start = min(length, max(0, start)) if stop is None: stop = length elif stop < 0: stop += length stop = min(length, max(start, stop)) return start, stop def compounding(start, stop, compound): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert next(sizes) == 1.5 * 1.5 """ def clip(value): return max(value, stop) if (start > stop) else min(value, stop) curr = float(start) while True: yield clip(curr) curr *= compound def decaying(start, stop, decay): """Yield an infinite series of linearly decaying values.""" def clip(value): return max(value, stop) if (start > stop) else min(value, stop) nr_upd = 1. while True: yield clip(start * 1./(1. + decay * nr_upd)) nr_upd += 1 def itershuffle(iterable, bufsize=1000): """Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 iterable (iterable): Iterator to shuffle. bufsize (int): Items to hold back. YIELDS (iterable): The shuffled iterator. """ iterable = iter(iterable) buf = [] try: while True: for i in range(random.randint(1, bufsize-len(buf))): buf.append(iterable.next()) random.shuffle(buf) for i in range(random.randint(1, bufsize)): if buf: yield buf.pop() else: break except StopIteration: random.shuffle(buf) while buf: yield buf.pop() raise StopIteration def get_raw_input(description, default=False): """Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input. """ additional = ' (default: %s)' % default if default else '' prompt = ' %s%s: ' % (description, additional) user_input = input_(prompt) return user_input def to_disk(path, writers, exclude): path = ensure_path(path) if not path.exists(): path.mkdir() for key, writer in writers.items(): if key not in exclude: writer(path / key) return path def from_disk(path, readers, exclude): path = ensure_path(path) for key, args in readers.items(): reader, model_dir = args model_dir = model_dir if model_dir else key if key not in exclude: reader(path / model_dir) return path def print_table(data, title=None): """Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above. """ if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table)) def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ def excl_value(value): # contains path, i.e. personal info return isinstance(value, basestring_) and Path(value).exists() if isinstance(data, dict): data = list(data.items()) markdown = ["* **{}:** {}".format(l, unicode_(v)) for l, v in data if not excl_value(v)] if title: print("\n## {}".format(title)) print('\n{}\n'.format('\n'.join(markdown))) def prints(*texts, **kwargs): """Print formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit. """ exits = kwargs.get('exits', None) title = kwargs.get('title', None) title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else '' message = '\n\n'.join([_wrap(text) for text in texts]) print('\n{}{}\n'.format(title, message)) if exits is not None: sys.exit(exits) def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text. """ indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False) def minify_html(html): """Perform a template-specific, rudimentary HTML minification for displaCy. Disclaimer: NOT a general-purpose solution, only removes indentation and newlines. html (unicode): Markup to minify. RETURNS (unicode): "Minified" HTML. """ return html.strip().replace(' ', '').replace('\n', '') def escape_html(text): """Replace <, >, &, " with their HTML encoded representation. Intended to prevent HTML errors in rendered displaCy markup. text (unicode): The original text. RETURNS (unicode): Equivalent text to be safely used within HTML. """ text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text def fix_random_seed(seed=0): random.seed(seed) numpy.random.seed(seed) class SimpleFrozenDict(dict): """Simplified implementation of a frozen dict, mainly used as default function or method argument (for arguments that should default to empty dictionary). Will raise an error if user or spaCy attempts to add to dict. """ def __setitem__(self, key, value): raise NotImplementedError(Errors.E095) def pop(self, key, default=None): raise NotImplementedError(Errors.E095) def update(self, other): raise NotImplementedError(Errors.E095)
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
get_raw_input
python
def get_raw_input(description, default=False): additional = ' (default: %s)' % default if default else '' prompt = ' %s%s: ' % (description, additional) user_input = input_(prompt) return user_input
Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L322-L332
null
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_, input_, unicode_ from .errors import Errors LANGUAGES = {} _data_path = Path(__file__).parent / 'data' _PRINT_ENV = False def set_env_log(value): global _PRINT_ENV _PRINT_ENV = value def get_data_path(require_exists=True): """Get path to spaCy data directory. require_exists (bool): Only return path if it exists, otherwise None. RETURNS (Path or None): Data path or None. """ if not require_exists: return _data_path else: return _data_path if _data_path.exists() else None def set_data_path(path): """Set path to spaCy data directory. path (unicode or Path): Path to new data directory. """ global _data_path _data_path = ensure_path(path) def ensure_path(path): """Ensure string is converted to a Path. path: Anything. If string, it's converted to Path. RETURNS: Path or original argument. """ if isinstance(path, basestring_): return Path(path) else: return path def load_model(name, **overrides): """Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model. """ data_path = get_data_path() if not data_path or not data_path.exists(): raise IOError(Errors.E049.format(path=path2str(data_path))) if isinstance(name, basestring_): # in data dir / shortcut if name in set([d.name for d in data_path.iterdir()]): return load_model_from_link(name, **overrides) if is_package(name): # installed as package return load_model_from_package(name, **overrides) if Path(name).exists(): # path to model data directory return load_model_from_path(Path(name), **overrides) elif hasattr(name, 'exists'): # Path or Path-like to model data return load_model_from_path(name, **overrides) raise IOError(Errors.E050.format(name=name)) def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / '__init__.py' try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(**overrides) def load_model_from_package(name, **overrides): """Load a model from an installed package.""" cls = importlib.import_module(name) return cls.load(**overrides) def load_model_from_path(model_path, meta=False, **overrides): """Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.""" from .tokenizer_loader import TokenizerLoader if not meta: meta = get_model_meta(model_path) tokenizer_loader = TokenizerLoader(meta=meta, **overrides) tokenizers = meta.get('tokenizers', []) disable = overrides.get('disable', []) if tokenizers is True: tokenizers = TokenizerLoader.Defaults.tokenizers elif tokenizers in (False, None): tokenizers = [] for tokenizer_name in tokenizers: if tokenizer_name not in disable: config = meta.get('tokenizer_args', {}).get(tokenizer_name, {}) component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config) tokenizer_loader.add_tokenizer(component, name=tokenizer_name) return tokenizer_loader.from_disk(model_path) def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = '%s-%s' % (meta['name'], meta['version']) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides) def get_model_meta(path): """Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data. """ model_path = ensure_path(path) if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(model_path))) meta_path = model_path / 'meta.json' if not meta_path.is_file(): raise IOError(Errors.E053.format(path=meta_path)) meta = read_json(meta_path) for setting in ['name', 'version']: if setting not in meta or not meta[setting]: raise ValueError(Errors.E054.format(setting=setting)) return meta def is_package(name): """Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not. """ name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it's otherwise very difficult to find the package. pkg = importlib.import_module(name) return Path(pkg.__file__).parent def read_regex(path): path = ensure_path(path) with path.open() as file_: entries = file_.read().split('\n') expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) def compile_prefix_regex(entries): if '(' in entries: # Handle deprecated data expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) else: expression = '|'.join(['^' + piece for piece in entries if piece.strip()]) return re.compile(expression) def compile_suffix_regex(entries): expression = '|'.join([piece + '$' for piece in entries if piece.strip()]) return re.compile(expression) def compile_infix_regex(entries): expression = '|'.join([piece for piece in entries if piece.strip()]) return re.compile(expression) def add_lookups(default_func, *lookups): """Extend an attribute function with special cases. If a word is in the lookups, the value is returned. Otherwise the previous function is used. default_func (callable): The default function to execute. *lookups (dict): Lookup dictionary mapping string to attribute value. RETURNS (callable): Lexical attribute getter. """ # This is implemented as functools.partial instead of a closure, to allow # pickle to work. return functools.partial(_get_attr_unless_lookup, default_func, lookups) def _get_attr_unless_lookup(default_func, lookups, string): for lookup in lookups: if string in lookup: return lookup[string] return default_func(string) def normalize_slice(length, start, stop, step=None): if not (step is None or step == 1): raise ValueError(Errors.E057) if start is None: start = 0 elif start < 0: start += length start = min(length, max(0, start)) if stop is None: stop = length elif stop < 0: stop += length stop = min(length, max(start, stop)) return start, stop def compounding(start, stop, compound): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert next(sizes) == 1.5 * 1.5 """ def clip(value): return max(value, stop) if (start > stop) else min(value, stop) curr = float(start) while True: yield clip(curr) curr *= compound def decaying(start, stop, decay): """Yield an infinite series of linearly decaying values.""" def clip(value): return max(value, stop) if (start > stop) else min(value, stop) nr_upd = 1. while True: yield clip(start * 1./(1. + decay * nr_upd)) nr_upd += 1 def itershuffle(iterable, bufsize=1000): """Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 iterable (iterable): Iterator to shuffle. bufsize (int): Items to hold back. YIELDS (iterable): The shuffled iterator. """ iterable = iter(iterable) buf = [] try: while True: for i in range(random.randint(1, bufsize-len(buf))): buf.append(iterable.next()) random.shuffle(buf) for i in range(random.randint(1, bufsize)): if buf: yield buf.pop() else: break except StopIteration: random.shuffle(buf) while buf: yield buf.pop() raise StopIteration def read_json(location): """Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content. """ location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f) def to_disk(path, writers, exclude): path = ensure_path(path) if not path.exists(): path.mkdir() for key, writer in writers.items(): if key not in exclude: writer(path / key) return path def from_disk(path, readers, exclude): path = ensure_path(path) for key, args in readers.items(): reader, model_dir = args model_dir = model_dir if model_dir else key if key not in exclude: reader(path / model_dir) return path def print_table(data, title=None): """Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above. """ if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table)) def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ def excl_value(value): # contains path, i.e. personal info return isinstance(value, basestring_) and Path(value).exists() if isinstance(data, dict): data = list(data.items()) markdown = ["* **{}:** {}".format(l, unicode_(v)) for l, v in data if not excl_value(v)] if title: print("\n## {}".format(title)) print('\n{}\n'.format('\n'.join(markdown))) def prints(*texts, **kwargs): """Print formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit. """ exits = kwargs.get('exits', None) title = kwargs.get('title', None) title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else '' message = '\n\n'.join([_wrap(text) for text in texts]) print('\n{}{}\n'.format(title, message)) if exits is not None: sys.exit(exits) def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text. """ indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False) def minify_html(html): """Perform a template-specific, rudimentary HTML minification for displaCy. Disclaimer: NOT a general-purpose solution, only removes indentation and newlines. html (unicode): Markup to minify. RETURNS (unicode): "Minified" HTML. """ return html.strip().replace(' ', '').replace('\n', '') def escape_html(text): """Replace <, >, &, " with their HTML encoded representation. Intended to prevent HTML errors in rendered displaCy markup. text (unicode): The original text. RETURNS (unicode): Equivalent text to be safely used within HTML. """ text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text def fix_random_seed(seed=0): random.seed(seed) numpy.random.seed(seed) class SimpleFrozenDict(dict): """Simplified implementation of a frozen dict, mainly used as default function or method argument (for arguments that should default to empty dictionary). Will raise an error if user or spaCy attempts to add to dict. """ def __setitem__(self, key, value): raise NotImplementedError(Errors.E095) def pop(self, key, default=None): raise NotImplementedError(Errors.E095) def update(self, other): raise NotImplementedError(Errors.E095)
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
print_table
python
def print_table(data, title=None): if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table))
Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L355-L367
null
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_, input_, unicode_ from .errors import Errors LANGUAGES = {} _data_path = Path(__file__).parent / 'data' _PRINT_ENV = False def set_env_log(value): global _PRINT_ENV _PRINT_ENV = value def get_data_path(require_exists=True): """Get path to spaCy data directory. require_exists (bool): Only return path if it exists, otherwise None. RETURNS (Path or None): Data path or None. """ if not require_exists: return _data_path else: return _data_path if _data_path.exists() else None def set_data_path(path): """Set path to spaCy data directory. path (unicode or Path): Path to new data directory. """ global _data_path _data_path = ensure_path(path) def ensure_path(path): """Ensure string is converted to a Path. path: Anything. If string, it's converted to Path. RETURNS: Path or original argument. """ if isinstance(path, basestring_): return Path(path) else: return path def load_model(name, **overrides): """Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model. """ data_path = get_data_path() if not data_path or not data_path.exists(): raise IOError(Errors.E049.format(path=path2str(data_path))) if isinstance(name, basestring_): # in data dir / shortcut if name in set([d.name for d in data_path.iterdir()]): return load_model_from_link(name, **overrides) if is_package(name): # installed as package return load_model_from_package(name, **overrides) if Path(name).exists(): # path to model data directory return load_model_from_path(Path(name), **overrides) elif hasattr(name, 'exists'): # Path or Path-like to model data return load_model_from_path(name, **overrides) raise IOError(Errors.E050.format(name=name)) def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / '__init__.py' try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(**overrides) def load_model_from_package(name, **overrides): """Load a model from an installed package.""" cls = importlib.import_module(name) return cls.load(**overrides) def load_model_from_path(model_path, meta=False, **overrides): """Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.""" from .tokenizer_loader import TokenizerLoader if not meta: meta = get_model_meta(model_path) tokenizer_loader = TokenizerLoader(meta=meta, **overrides) tokenizers = meta.get('tokenizers', []) disable = overrides.get('disable', []) if tokenizers is True: tokenizers = TokenizerLoader.Defaults.tokenizers elif tokenizers in (False, None): tokenizers = [] for tokenizer_name in tokenizers: if tokenizer_name not in disable: config = meta.get('tokenizer_args', {}).get(tokenizer_name, {}) component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config) tokenizer_loader.add_tokenizer(component, name=tokenizer_name) return tokenizer_loader.from_disk(model_path) def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = '%s-%s' % (meta['name'], meta['version']) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides) def get_model_meta(path): """Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data. """ model_path = ensure_path(path) if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(model_path))) meta_path = model_path / 'meta.json' if not meta_path.is_file(): raise IOError(Errors.E053.format(path=meta_path)) meta = read_json(meta_path) for setting in ['name', 'version']: if setting not in meta or not meta[setting]: raise ValueError(Errors.E054.format(setting=setting)) return meta def is_package(name): """Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not. """ name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it's otherwise very difficult to find the package. pkg = importlib.import_module(name) return Path(pkg.__file__).parent def read_regex(path): path = ensure_path(path) with path.open() as file_: entries = file_.read().split('\n') expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) def compile_prefix_regex(entries): if '(' in entries: # Handle deprecated data expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) else: expression = '|'.join(['^' + piece for piece in entries if piece.strip()]) return re.compile(expression) def compile_suffix_regex(entries): expression = '|'.join([piece + '$' for piece in entries if piece.strip()]) return re.compile(expression) def compile_infix_regex(entries): expression = '|'.join([piece for piece in entries if piece.strip()]) return re.compile(expression) def add_lookups(default_func, *lookups): """Extend an attribute function with special cases. If a word is in the lookups, the value is returned. Otherwise the previous function is used. default_func (callable): The default function to execute. *lookups (dict): Lookup dictionary mapping string to attribute value. RETURNS (callable): Lexical attribute getter. """ # This is implemented as functools.partial instead of a closure, to allow # pickle to work. return functools.partial(_get_attr_unless_lookup, default_func, lookups) def _get_attr_unless_lookup(default_func, lookups, string): for lookup in lookups: if string in lookup: return lookup[string] return default_func(string) def normalize_slice(length, start, stop, step=None): if not (step is None or step == 1): raise ValueError(Errors.E057) if start is None: start = 0 elif start < 0: start += length start = min(length, max(0, start)) if stop is None: stop = length elif stop < 0: stop += length stop = min(length, max(start, stop)) return start, stop def compounding(start, stop, compound): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert next(sizes) == 1.5 * 1.5 """ def clip(value): return max(value, stop) if (start > stop) else min(value, stop) curr = float(start) while True: yield clip(curr) curr *= compound def decaying(start, stop, decay): """Yield an infinite series of linearly decaying values.""" def clip(value): return max(value, stop) if (start > stop) else min(value, stop) nr_upd = 1. while True: yield clip(start * 1./(1. + decay * nr_upd)) nr_upd += 1 def itershuffle(iterable, bufsize=1000): """Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 iterable (iterable): Iterator to shuffle. bufsize (int): Items to hold back. YIELDS (iterable): The shuffled iterator. """ iterable = iter(iterable) buf = [] try: while True: for i in range(random.randint(1, bufsize-len(buf))): buf.append(iterable.next()) random.shuffle(buf) for i in range(random.randint(1, bufsize)): if buf: yield buf.pop() else: break except StopIteration: random.shuffle(buf) while buf: yield buf.pop() raise StopIteration def read_json(location): """Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content. """ location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f) def get_raw_input(description, default=False): """Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input. """ additional = ' (default: %s)' % default if default else '' prompt = ' %s%s: ' % (description, additional) user_input = input_(prompt) return user_input def to_disk(path, writers, exclude): path = ensure_path(path) if not path.exists(): path.mkdir() for key, writer in writers.items(): if key not in exclude: writer(path / key) return path def from_disk(path, readers, exclude): path = ensure_path(path) for key, args in readers.items(): reader, model_dir = args model_dir = model_dir if model_dir else key if key not in exclude: reader(path / model_dir) return path def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ def excl_value(value): # contains path, i.e. personal info return isinstance(value, basestring_) and Path(value).exists() if isinstance(data, dict): data = list(data.items()) markdown = ["* **{}:** {}".format(l, unicode_(v)) for l, v in data if not excl_value(v)] if title: print("\n## {}".format(title)) print('\n{}\n'.format('\n'.join(markdown))) def prints(*texts, **kwargs): """Print formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit. """ exits = kwargs.get('exits', None) title = kwargs.get('title', None) title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else '' message = '\n\n'.join([_wrap(text) for text in texts]) print('\n{}{}\n'.format(title, message)) if exits is not None: sys.exit(exits) def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text. """ indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False) def minify_html(html): """Perform a template-specific, rudimentary HTML minification for displaCy. Disclaimer: NOT a general-purpose solution, only removes indentation and newlines. html (unicode): Markup to minify. RETURNS (unicode): "Minified" HTML. """ return html.strip().replace(' ', '').replace('\n', '') def escape_html(text): """Replace <, >, &, " with their HTML encoded representation. Intended to prevent HTML errors in rendered displaCy markup. text (unicode): The original text. RETURNS (unicode): Equivalent text to be safely used within HTML. """ text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text def fix_random_seed(seed=0): random.seed(seed) numpy.random.seed(seed) class SimpleFrozenDict(dict): """Simplified implementation of a frozen dict, mainly used as default function or method argument (for arguments that should default to empty dictionary). Will raise an error if user or spaCy attempts to add to dict. """ def __setitem__(self, key, value): raise NotImplementedError(Errors.E095) def pop(self, key, default=None): raise NotImplementedError(Errors.E095) def update(self, other): raise NotImplementedError(Errors.E095)
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
print_markdown
python
def print_markdown(data, title=None): def excl_value(value): # contains path, i.e. personal info return isinstance(value, basestring_) and Path(value).exists() if isinstance(data, dict): data = list(data.items()) markdown = ["* **{}:** {}".format(l, unicode_(v)) for l, v in data if not excl_value(v)] if title: print("\n## {}".format(title)) print('\n{}\n'.format('\n'.join(markdown)))
Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L370-L386
null
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_, input_, unicode_ from .errors import Errors LANGUAGES = {} _data_path = Path(__file__).parent / 'data' _PRINT_ENV = False def set_env_log(value): global _PRINT_ENV _PRINT_ENV = value def get_data_path(require_exists=True): """Get path to spaCy data directory. require_exists (bool): Only return path if it exists, otherwise None. RETURNS (Path or None): Data path or None. """ if not require_exists: return _data_path else: return _data_path if _data_path.exists() else None def set_data_path(path): """Set path to spaCy data directory. path (unicode or Path): Path to new data directory. """ global _data_path _data_path = ensure_path(path) def ensure_path(path): """Ensure string is converted to a Path. path: Anything. If string, it's converted to Path. RETURNS: Path or original argument. """ if isinstance(path, basestring_): return Path(path) else: return path def load_model(name, **overrides): """Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model. """ data_path = get_data_path() if not data_path or not data_path.exists(): raise IOError(Errors.E049.format(path=path2str(data_path))) if isinstance(name, basestring_): # in data dir / shortcut if name in set([d.name for d in data_path.iterdir()]): return load_model_from_link(name, **overrides) if is_package(name): # installed as package return load_model_from_package(name, **overrides) if Path(name).exists(): # path to model data directory return load_model_from_path(Path(name), **overrides) elif hasattr(name, 'exists'): # Path or Path-like to model data return load_model_from_path(name, **overrides) raise IOError(Errors.E050.format(name=name)) def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / '__init__.py' try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(**overrides) def load_model_from_package(name, **overrides): """Load a model from an installed package.""" cls = importlib.import_module(name) return cls.load(**overrides) def load_model_from_path(model_path, meta=False, **overrides): """Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.""" from .tokenizer_loader import TokenizerLoader if not meta: meta = get_model_meta(model_path) tokenizer_loader = TokenizerLoader(meta=meta, **overrides) tokenizers = meta.get('tokenizers', []) disable = overrides.get('disable', []) if tokenizers is True: tokenizers = TokenizerLoader.Defaults.tokenizers elif tokenizers in (False, None): tokenizers = [] for tokenizer_name in tokenizers: if tokenizer_name not in disable: config = meta.get('tokenizer_args', {}).get(tokenizer_name, {}) component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config) tokenizer_loader.add_tokenizer(component, name=tokenizer_name) return tokenizer_loader.from_disk(model_path) def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = '%s-%s' % (meta['name'], meta['version']) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides) def get_model_meta(path): """Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data. """ model_path = ensure_path(path) if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(model_path))) meta_path = model_path / 'meta.json' if not meta_path.is_file(): raise IOError(Errors.E053.format(path=meta_path)) meta = read_json(meta_path) for setting in ['name', 'version']: if setting not in meta or not meta[setting]: raise ValueError(Errors.E054.format(setting=setting)) return meta def is_package(name): """Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not. """ name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it's otherwise very difficult to find the package. pkg = importlib.import_module(name) return Path(pkg.__file__).parent def read_regex(path): path = ensure_path(path) with path.open() as file_: entries = file_.read().split('\n') expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) def compile_prefix_regex(entries): if '(' in entries: # Handle deprecated data expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) else: expression = '|'.join(['^' + piece for piece in entries if piece.strip()]) return re.compile(expression) def compile_suffix_regex(entries): expression = '|'.join([piece + '$' for piece in entries if piece.strip()]) return re.compile(expression) def compile_infix_regex(entries): expression = '|'.join([piece for piece in entries if piece.strip()]) return re.compile(expression) def add_lookups(default_func, *lookups): """Extend an attribute function with special cases. If a word is in the lookups, the value is returned. Otherwise the previous function is used. default_func (callable): The default function to execute. *lookups (dict): Lookup dictionary mapping string to attribute value. RETURNS (callable): Lexical attribute getter. """ # This is implemented as functools.partial instead of a closure, to allow # pickle to work. return functools.partial(_get_attr_unless_lookup, default_func, lookups) def _get_attr_unless_lookup(default_func, lookups, string): for lookup in lookups: if string in lookup: return lookup[string] return default_func(string) def normalize_slice(length, start, stop, step=None): if not (step is None or step == 1): raise ValueError(Errors.E057) if start is None: start = 0 elif start < 0: start += length start = min(length, max(0, start)) if stop is None: stop = length elif stop < 0: stop += length stop = min(length, max(start, stop)) return start, stop def compounding(start, stop, compound): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert next(sizes) == 1.5 * 1.5 """ def clip(value): return max(value, stop) if (start > stop) else min(value, stop) curr = float(start) while True: yield clip(curr) curr *= compound def decaying(start, stop, decay): """Yield an infinite series of linearly decaying values.""" def clip(value): return max(value, stop) if (start > stop) else min(value, stop) nr_upd = 1. while True: yield clip(start * 1./(1. + decay * nr_upd)) nr_upd += 1 def itershuffle(iterable, bufsize=1000): """Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 iterable (iterable): Iterator to shuffle. bufsize (int): Items to hold back. YIELDS (iterable): The shuffled iterator. """ iterable = iter(iterable) buf = [] try: while True: for i in range(random.randint(1, bufsize-len(buf))): buf.append(iterable.next()) random.shuffle(buf) for i in range(random.randint(1, bufsize)): if buf: yield buf.pop() else: break except StopIteration: random.shuffle(buf) while buf: yield buf.pop() raise StopIteration def read_json(location): """Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content. """ location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f) def get_raw_input(description, default=False): """Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input. """ additional = ' (default: %s)' % default if default else '' prompt = ' %s%s: ' % (description, additional) user_input = input_(prompt) return user_input def to_disk(path, writers, exclude): path = ensure_path(path) if not path.exists(): path.mkdir() for key, writer in writers.items(): if key not in exclude: writer(path / key) return path def from_disk(path, readers, exclude): path = ensure_path(path) for key, args in readers.items(): reader, model_dir = args model_dir = model_dir if model_dir else key if key not in exclude: reader(path / model_dir) return path def print_table(data, title=None): """Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above. """ if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table)) def prints(*texts, **kwargs): """Print formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit. """ exits = kwargs.get('exits', None) title = kwargs.get('title', None) title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else '' message = '\n\n'.join([_wrap(text) for text in texts]) print('\n{}{}\n'.format(title, message)) if exits is not None: sys.exit(exits) def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text. """ indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False) def minify_html(html): """Perform a template-specific, rudimentary HTML minification for displaCy. Disclaimer: NOT a general-purpose solution, only removes indentation and newlines. html (unicode): Markup to minify. RETURNS (unicode): "Minified" HTML. """ return html.strip().replace(' ', '').replace('\n', '') def escape_html(text): """Replace <, >, &, " with their HTML encoded representation. Intended to prevent HTML errors in rendered displaCy markup. text (unicode): The original text. RETURNS (unicode): Equivalent text to be safely used within HTML. """ text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text def fix_random_seed(seed=0): random.seed(seed) numpy.random.seed(seed) class SimpleFrozenDict(dict): """Simplified implementation of a frozen dict, mainly used as default function or method argument (for arguments that should default to empty dictionary). Will raise an error if user or spaCy attempts to add to dict. """ def __setitem__(self, key, value): raise NotImplementedError(Errors.E095) def pop(self, key, default=None): raise NotImplementedError(Errors.E095) def update(self, other): raise NotImplementedError(Errors.E095)
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
prints
python
def prints(*texts, **kwargs): exits = kwargs.get('exits', None) title = kwargs.get('title', None) title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else '' message = '\n\n'.join([_wrap(text) for text in texts]) print('\n{}{}\n'.format(title, message)) if exits is not None: sys.exit(exits)
Print formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L389-L402
[ "def _wrap(text, wrap_max=80, indent=4):\n \"\"\"Wrap text at given width using textwrap module.\n\n text (unicode): Text to wrap. If it's a Path, it's converted to string.\n wrap_max (int): Maximum line length (indent is deducted).\n indent (int): Number of spaces for indentation.\n RETURNS (unicode): Wrapped text.\n \"\"\"\n indent = indent * ' '\n wrap_width = wrap_max - len(indent)\n if isinstance(text, Path):\n text = path2str(text)\n return textwrap.fill(text, width=wrap_width, initial_indent=indent,\n subsequent_indent=indent, break_long_words=False,\n break_on_hyphens=False)\n" ]
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_, input_, unicode_ from .errors import Errors LANGUAGES = {} _data_path = Path(__file__).parent / 'data' _PRINT_ENV = False def set_env_log(value): global _PRINT_ENV _PRINT_ENV = value def get_data_path(require_exists=True): """Get path to spaCy data directory. require_exists (bool): Only return path if it exists, otherwise None. RETURNS (Path or None): Data path or None. """ if not require_exists: return _data_path else: return _data_path if _data_path.exists() else None def set_data_path(path): """Set path to spaCy data directory. path (unicode or Path): Path to new data directory. """ global _data_path _data_path = ensure_path(path) def ensure_path(path): """Ensure string is converted to a Path. path: Anything. If string, it's converted to Path. RETURNS: Path or original argument. """ if isinstance(path, basestring_): return Path(path) else: return path def load_model(name, **overrides): """Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model. """ data_path = get_data_path() if not data_path or not data_path.exists(): raise IOError(Errors.E049.format(path=path2str(data_path))) if isinstance(name, basestring_): # in data dir / shortcut if name in set([d.name for d in data_path.iterdir()]): return load_model_from_link(name, **overrides) if is_package(name): # installed as package return load_model_from_package(name, **overrides) if Path(name).exists(): # path to model data directory return load_model_from_path(Path(name), **overrides) elif hasattr(name, 'exists'): # Path or Path-like to model data return load_model_from_path(name, **overrides) raise IOError(Errors.E050.format(name=name)) def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / '__init__.py' try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(**overrides) def load_model_from_package(name, **overrides): """Load a model from an installed package.""" cls = importlib.import_module(name) return cls.load(**overrides) def load_model_from_path(model_path, meta=False, **overrides): """Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.""" from .tokenizer_loader import TokenizerLoader if not meta: meta = get_model_meta(model_path) tokenizer_loader = TokenizerLoader(meta=meta, **overrides) tokenizers = meta.get('tokenizers', []) disable = overrides.get('disable', []) if tokenizers is True: tokenizers = TokenizerLoader.Defaults.tokenizers elif tokenizers in (False, None): tokenizers = [] for tokenizer_name in tokenizers: if tokenizer_name not in disable: config = meta.get('tokenizer_args', {}).get(tokenizer_name, {}) component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config) tokenizer_loader.add_tokenizer(component, name=tokenizer_name) return tokenizer_loader.from_disk(model_path) def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = '%s-%s' % (meta['name'], meta['version']) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides) def get_model_meta(path): """Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data. """ model_path = ensure_path(path) if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(model_path))) meta_path = model_path / 'meta.json' if not meta_path.is_file(): raise IOError(Errors.E053.format(path=meta_path)) meta = read_json(meta_path) for setting in ['name', 'version']: if setting not in meta or not meta[setting]: raise ValueError(Errors.E054.format(setting=setting)) return meta def is_package(name): """Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not. """ name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it's otherwise very difficult to find the package. pkg = importlib.import_module(name) return Path(pkg.__file__).parent def read_regex(path): path = ensure_path(path) with path.open() as file_: entries = file_.read().split('\n') expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) def compile_prefix_regex(entries): if '(' in entries: # Handle deprecated data expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) else: expression = '|'.join(['^' + piece for piece in entries if piece.strip()]) return re.compile(expression) def compile_suffix_regex(entries): expression = '|'.join([piece + '$' for piece in entries if piece.strip()]) return re.compile(expression) def compile_infix_regex(entries): expression = '|'.join([piece for piece in entries if piece.strip()]) return re.compile(expression) def add_lookups(default_func, *lookups): """Extend an attribute function with special cases. If a word is in the lookups, the value is returned. Otherwise the previous function is used. default_func (callable): The default function to execute. *lookups (dict): Lookup dictionary mapping string to attribute value. RETURNS (callable): Lexical attribute getter. """ # This is implemented as functools.partial instead of a closure, to allow # pickle to work. return functools.partial(_get_attr_unless_lookup, default_func, lookups) def _get_attr_unless_lookup(default_func, lookups, string): for lookup in lookups: if string in lookup: return lookup[string] return default_func(string) def normalize_slice(length, start, stop, step=None): if not (step is None or step == 1): raise ValueError(Errors.E057) if start is None: start = 0 elif start < 0: start += length start = min(length, max(0, start)) if stop is None: stop = length elif stop < 0: stop += length stop = min(length, max(start, stop)) return start, stop def compounding(start, stop, compound): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert next(sizes) == 1.5 * 1.5 """ def clip(value): return max(value, stop) if (start > stop) else min(value, stop) curr = float(start) while True: yield clip(curr) curr *= compound def decaying(start, stop, decay): """Yield an infinite series of linearly decaying values.""" def clip(value): return max(value, stop) if (start > stop) else min(value, stop) nr_upd = 1. while True: yield clip(start * 1./(1. + decay * nr_upd)) nr_upd += 1 def itershuffle(iterable, bufsize=1000): """Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 iterable (iterable): Iterator to shuffle. bufsize (int): Items to hold back. YIELDS (iterable): The shuffled iterator. """ iterable = iter(iterable) buf = [] try: while True: for i in range(random.randint(1, bufsize-len(buf))): buf.append(iterable.next()) random.shuffle(buf) for i in range(random.randint(1, bufsize)): if buf: yield buf.pop() else: break except StopIteration: random.shuffle(buf) while buf: yield buf.pop() raise StopIteration def read_json(location): """Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content. """ location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f) def get_raw_input(description, default=False): """Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input. """ additional = ' (default: %s)' % default if default else '' prompt = ' %s%s: ' % (description, additional) user_input = input_(prompt) return user_input def to_disk(path, writers, exclude): path = ensure_path(path) if not path.exists(): path.mkdir() for key, writer in writers.items(): if key not in exclude: writer(path / key) return path def from_disk(path, readers, exclude): path = ensure_path(path) for key, args in readers.items(): reader, model_dir = args model_dir = model_dir if model_dir else key if key not in exclude: reader(path / model_dir) return path def print_table(data, title=None): """Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above. """ if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table)) def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ def excl_value(value): # contains path, i.e. personal info return isinstance(value, basestring_) and Path(value).exists() if isinstance(data, dict): data = list(data.items()) markdown = ["* **{}:** {}".format(l, unicode_(v)) for l, v in data if not excl_value(v)] if title: print("\n## {}".format(title)) print('\n{}\n'.format('\n'.join(markdown))) def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text. """ indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False) def minify_html(html): """Perform a template-specific, rudimentary HTML minification for displaCy. Disclaimer: NOT a general-purpose solution, only removes indentation and newlines. html (unicode): Markup to minify. RETURNS (unicode): "Minified" HTML. """ return html.strip().replace(' ', '').replace('\n', '') def escape_html(text): """Replace <, >, &, " with their HTML encoded representation. Intended to prevent HTML errors in rendered displaCy markup. text (unicode): The original text. RETURNS (unicode): Equivalent text to be safely used within HTML. """ text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text def fix_random_seed(seed=0): random.seed(seed) numpy.random.seed(seed) class SimpleFrozenDict(dict): """Simplified implementation of a frozen dict, mainly used as default function or method argument (for arguments that should default to empty dictionary). Will raise an error if user or spaCy attempts to add to dict. """ def __setitem__(self, key, value): raise NotImplementedError(Errors.E095) def pop(self, key, default=None): raise NotImplementedError(Errors.E095) def update(self, other): raise NotImplementedError(Errors.E095)
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
_wrap
python
def _wrap(text, wrap_max=80, indent=4): indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False)
Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L405-L419
[ "path2str = lambda path: str(path)\n" ]
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_, input_, unicode_ from .errors import Errors LANGUAGES = {} _data_path = Path(__file__).parent / 'data' _PRINT_ENV = False def set_env_log(value): global _PRINT_ENV _PRINT_ENV = value def get_data_path(require_exists=True): """Get path to spaCy data directory. require_exists (bool): Only return path if it exists, otherwise None. RETURNS (Path or None): Data path or None. """ if not require_exists: return _data_path else: return _data_path if _data_path.exists() else None def set_data_path(path): """Set path to spaCy data directory. path (unicode or Path): Path to new data directory. """ global _data_path _data_path = ensure_path(path) def ensure_path(path): """Ensure string is converted to a Path. path: Anything. If string, it's converted to Path. RETURNS: Path or original argument. """ if isinstance(path, basestring_): return Path(path) else: return path def load_model(name, **overrides): """Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model. """ data_path = get_data_path() if not data_path or not data_path.exists(): raise IOError(Errors.E049.format(path=path2str(data_path))) if isinstance(name, basestring_): # in data dir / shortcut if name in set([d.name for d in data_path.iterdir()]): return load_model_from_link(name, **overrides) if is_package(name): # installed as package return load_model_from_package(name, **overrides) if Path(name).exists(): # path to model data directory return load_model_from_path(Path(name), **overrides) elif hasattr(name, 'exists'): # Path or Path-like to model data return load_model_from_path(name, **overrides) raise IOError(Errors.E050.format(name=name)) def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / '__init__.py' try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(**overrides) def load_model_from_package(name, **overrides): """Load a model from an installed package.""" cls = importlib.import_module(name) return cls.load(**overrides) def load_model_from_path(model_path, meta=False, **overrides): """Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.""" from .tokenizer_loader import TokenizerLoader if not meta: meta = get_model_meta(model_path) tokenizer_loader = TokenizerLoader(meta=meta, **overrides) tokenizers = meta.get('tokenizers', []) disable = overrides.get('disable', []) if tokenizers is True: tokenizers = TokenizerLoader.Defaults.tokenizers elif tokenizers in (False, None): tokenizers = [] for tokenizer_name in tokenizers: if tokenizer_name not in disable: config = meta.get('tokenizer_args', {}).get(tokenizer_name, {}) component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config) tokenizer_loader.add_tokenizer(component, name=tokenizer_name) return tokenizer_loader.from_disk(model_path) def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = '%s-%s' % (meta['name'], meta['version']) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides) def get_model_meta(path): """Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data. """ model_path = ensure_path(path) if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(model_path))) meta_path = model_path / 'meta.json' if not meta_path.is_file(): raise IOError(Errors.E053.format(path=meta_path)) meta = read_json(meta_path) for setting in ['name', 'version']: if setting not in meta or not meta[setting]: raise ValueError(Errors.E054.format(setting=setting)) return meta def is_package(name): """Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not. """ name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it's otherwise very difficult to find the package. pkg = importlib.import_module(name) return Path(pkg.__file__).parent def read_regex(path): path = ensure_path(path) with path.open() as file_: entries = file_.read().split('\n') expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) def compile_prefix_regex(entries): if '(' in entries: # Handle deprecated data expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) else: expression = '|'.join(['^' + piece for piece in entries if piece.strip()]) return re.compile(expression) def compile_suffix_regex(entries): expression = '|'.join([piece + '$' for piece in entries if piece.strip()]) return re.compile(expression) def compile_infix_regex(entries): expression = '|'.join([piece for piece in entries if piece.strip()]) return re.compile(expression) def add_lookups(default_func, *lookups): """Extend an attribute function with special cases. If a word is in the lookups, the value is returned. Otherwise the previous function is used. default_func (callable): The default function to execute. *lookups (dict): Lookup dictionary mapping string to attribute value. RETURNS (callable): Lexical attribute getter. """ # This is implemented as functools.partial instead of a closure, to allow # pickle to work. return functools.partial(_get_attr_unless_lookup, default_func, lookups) def _get_attr_unless_lookup(default_func, lookups, string): for lookup in lookups: if string in lookup: return lookup[string] return default_func(string) def normalize_slice(length, start, stop, step=None): if not (step is None or step == 1): raise ValueError(Errors.E057) if start is None: start = 0 elif start < 0: start += length start = min(length, max(0, start)) if stop is None: stop = length elif stop < 0: stop += length stop = min(length, max(start, stop)) return start, stop def compounding(start, stop, compound): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert next(sizes) == 1.5 * 1.5 """ def clip(value): return max(value, stop) if (start > stop) else min(value, stop) curr = float(start) while True: yield clip(curr) curr *= compound def decaying(start, stop, decay): """Yield an infinite series of linearly decaying values.""" def clip(value): return max(value, stop) if (start > stop) else min(value, stop) nr_upd = 1. while True: yield clip(start * 1./(1. + decay * nr_upd)) nr_upd += 1 def itershuffle(iterable, bufsize=1000): """Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 iterable (iterable): Iterator to shuffle. bufsize (int): Items to hold back. YIELDS (iterable): The shuffled iterator. """ iterable = iter(iterable) buf = [] try: while True: for i in range(random.randint(1, bufsize-len(buf))): buf.append(iterable.next()) random.shuffle(buf) for i in range(random.randint(1, bufsize)): if buf: yield buf.pop() else: break except StopIteration: random.shuffle(buf) while buf: yield buf.pop() raise StopIteration def read_json(location): """Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content. """ location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f) def get_raw_input(description, default=False): """Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input. """ additional = ' (default: %s)' % default if default else '' prompt = ' %s%s: ' % (description, additional) user_input = input_(prompt) return user_input def to_disk(path, writers, exclude): path = ensure_path(path) if not path.exists(): path.mkdir() for key, writer in writers.items(): if key not in exclude: writer(path / key) return path def from_disk(path, readers, exclude): path = ensure_path(path) for key, args in readers.items(): reader, model_dir = args model_dir = model_dir if model_dir else key if key not in exclude: reader(path / model_dir) return path def print_table(data, title=None): """Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above. """ if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table)) def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ def excl_value(value): # contains path, i.e. personal info return isinstance(value, basestring_) and Path(value).exists() if isinstance(data, dict): data = list(data.items()) markdown = ["* **{}:** {}".format(l, unicode_(v)) for l, v in data if not excl_value(v)] if title: print("\n## {}".format(title)) print('\n{}\n'.format('\n'.join(markdown))) def prints(*texts, **kwargs): """Print formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit. """ exits = kwargs.get('exits', None) title = kwargs.get('title', None) title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else '' message = '\n\n'.join([_wrap(text) for text in texts]) print('\n{}{}\n'.format(title, message)) if exits is not None: sys.exit(exits) def minify_html(html): """Perform a template-specific, rudimentary HTML minification for displaCy. Disclaimer: NOT a general-purpose solution, only removes indentation and newlines. html (unicode): Markup to minify. RETURNS (unicode): "Minified" HTML. """ return html.strip().replace(' ', '').replace('\n', '') def escape_html(text): """Replace <, >, &, " with their HTML encoded representation. Intended to prevent HTML errors in rendered displaCy markup. text (unicode): The original text. RETURNS (unicode): Equivalent text to be safely used within HTML. """ text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text def fix_random_seed(seed=0): random.seed(seed) numpy.random.seed(seed) class SimpleFrozenDict(dict): """Simplified implementation of a frozen dict, mainly used as default function or method argument (for arguments that should default to empty dictionary). Will raise an error if user or spaCy attempts to add to dict. """ def __setitem__(self, key, value): raise NotImplementedError(Errors.E095) def pop(self, key, default=None): raise NotImplementedError(Errors.E095) def update(self, other): raise NotImplementedError(Errors.E095)
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
escape_html
python
def escape_html(text): text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text
Replace <, >, &, " with their HTML encoded representation. Intended to prevent HTML errors in rendered displaCy markup. text (unicode): The original text. RETURNS (unicode): Equivalent text to be safely used within HTML.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L433-L444
null
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_, input_, unicode_ from .errors import Errors LANGUAGES = {} _data_path = Path(__file__).parent / 'data' _PRINT_ENV = False def set_env_log(value): global _PRINT_ENV _PRINT_ENV = value def get_data_path(require_exists=True): """Get path to spaCy data directory. require_exists (bool): Only return path if it exists, otherwise None. RETURNS (Path or None): Data path or None. """ if not require_exists: return _data_path else: return _data_path if _data_path.exists() else None def set_data_path(path): """Set path to spaCy data directory. path (unicode or Path): Path to new data directory. """ global _data_path _data_path = ensure_path(path) def ensure_path(path): """Ensure string is converted to a Path. path: Anything. If string, it's converted to Path. RETURNS: Path or original argument. """ if isinstance(path, basestring_): return Path(path) else: return path def load_model(name, **overrides): """Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model. """ data_path = get_data_path() if not data_path or not data_path.exists(): raise IOError(Errors.E049.format(path=path2str(data_path))) if isinstance(name, basestring_): # in data dir / shortcut if name in set([d.name for d in data_path.iterdir()]): return load_model_from_link(name, **overrides) if is_package(name): # installed as package return load_model_from_package(name, **overrides) if Path(name).exists(): # path to model data directory return load_model_from_path(Path(name), **overrides) elif hasattr(name, 'exists'): # Path or Path-like to model data return load_model_from_path(name, **overrides) raise IOError(Errors.E050.format(name=name)) def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / '__init__.py' try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(**overrides) def load_model_from_package(name, **overrides): """Load a model from an installed package.""" cls = importlib.import_module(name) return cls.load(**overrides) def load_model_from_path(model_path, meta=False, **overrides): """Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.""" from .tokenizer_loader import TokenizerLoader if not meta: meta = get_model_meta(model_path) tokenizer_loader = TokenizerLoader(meta=meta, **overrides) tokenizers = meta.get('tokenizers', []) disable = overrides.get('disable', []) if tokenizers is True: tokenizers = TokenizerLoader.Defaults.tokenizers elif tokenizers in (False, None): tokenizers = [] for tokenizer_name in tokenizers: if tokenizer_name not in disable: config = meta.get('tokenizer_args', {}).get(tokenizer_name, {}) component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config) tokenizer_loader.add_tokenizer(component, name=tokenizer_name) return tokenizer_loader.from_disk(model_path) def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = '%s-%s' % (meta['name'], meta['version']) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides) def get_model_meta(path): """Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data. """ model_path = ensure_path(path) if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(model_path))) meta_path = model_path / 'meta.json' if not meta_path.is_file(): raise IOError(Errors.E053.format(path=meta_path)) meta = read_json(meta_path) for setting in ['name', 'version']: if setting not in meta or not meta[setting]: raise ValueError(Errors.E054.format(setting=setting)) return meta def is_package(name): """Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not. """ name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it's otherwise very difficult to find the package. pkg = importlib.import_module(name) return Path(pkg.__file__).parent def read_regex(path): path = ensure_path(path) with path.open() as file_: entries = file_.read().split('\n') expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) def compile_prefix_regex(entries): if '(' in entries: # Handle deprecated data expression = '|'.join(['^' + re.escape(piece) for piece in entries if piece.strip()]) return re.compile(expression) else: expression = '|'.join(['^' + piece for piece in entries if piece.strip()]) return re.compile(expression) def compile_suffix_regex(entries): expression = '|'.join([piece + '$' for piece in entries if piece.strip()]) return re.compile(expression) def compile_infix_regex(entries): expression = '|'.join([piece for piece in entries if piece.strip()]) return re.compile(expression) def add_lookups(default_func, *lookups): """Extend an attribute function with special cases. If a word is in the lookups, the value is returned. Otherwise the previous function is used. default_func (callable): The default function to execute. *lookups (dict): Lookup dictionary mapping string to attribute value. RETURNS (callable): Lexical attribute getter. """ # This is implemented as functools.partial instead of a closure, to allow # pickle to work. return functools.partial(_get_attr_unless_lookup, default_func, lookups) def _get_attr_unless_lookup(default_func, lookups, string): for lookup in lookups: if string in lookup: return lookup[string] return default_func(string) def normalize_slice(length, start, stop, step=None): if not (step is None or step == 1): raise ValueError(Errors.E057) if start is None: start = 0 elif start < 0: start += length start = min(length, max(0, start)) if stop is None: stop = length elif stop < 0: stop += length stop = min(length, max(start, stop)) return start, stop def compounding(start, stop, compound): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert next(sizes) == 1.5 * 1.5 """ def clip(value): return max(value, stop) if (start > stop) else min(value, stop) curr = float(start) while True: yield clip(curr) curr *= compound def decaying(start, stop, decay): """Yield an infinite series of linearly decaying values.""" def clip(value): return max(value, stop) if (start > stop) else min(value, stop) nr_upd = 1. while True: yield clip(start * 1./(1. + decay * nr_upd)) nr_upd += 1 def itershuffle(iterable, bufsize=1000): """Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 iterable (iterable): Iterator to shuffle. bufsize (int): Items to hold back. YIELDS (iterable): The shuffled iterator. """ iterable = iter(iterable) buf = [] try: while True: for i in range(random.randint(1, bufsize-len(buf))): buf.append(iterable.next()) random.shuffle(buf) for i in range(random.randint(1, bufsize)): if buf: yield buf.pop() else: break except StopIteration: random.shuffle(buf) while buf: yield buf.pop() raise StopIteration def read_json(location): """Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content. """ location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f) def get_raw_input(description, default=False): """Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input. """ additional = ' (default: %s)' % default if default else '' prompt = ' %s%s: ' % (description, additional) user_input = input_(prompt) return user_input def to_disk(path, writers, exclude): path = ensure_path(path) if not path.exists(): path.mkdir() for key, writer in writers.items(): if key not in exclude: writer(path / key) return path def from_disk(path, readers, exclude): path = ensure_path(path) for key, args in readers.items(): reader, model_dir = args model_dir = model_dir if model_dir else key if key not in exclude: reader(path / model_dir) return path def print_table(data, title=None): """Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above. """ if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table)) def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ def excl_value(value): # contains path, i.e. personal info return isinstance(value, basestring_) and Path(value).exists() if isinstance(data, dict): data = list(data.items()) markdown = ["* **{}:** {}".format(l, unicode_(v)) for l, v in data if not excl_value(v)] if title: print("\n## {}".format(title)) print('\n{}\n'.format('\n'.join(markdown))) def prints(*texts, **kwargs): """Print formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit. """ exits = kwargs.get('exits', None) title = kwargs.get('title', None) title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else '' message = '\n\n'.join([_wrap(text) for text in texts]) print('\n{}{}\n'.format(title, message)) if exits is not None: sys.exit(exits) def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text. """ indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False) def minify_html(html): """Perform a template-specific, rudimentary HTML minification for displaCy. Disclaimer: NOT a general-purpose solution, only removes indentation and newlines. html (unicode): Markup to minify. RETURNS (unicode): "Minified" HTML. """ return html.strip().replace(' ', '').replace('\n', '') def fix_random_seed(seed=0): random.seed(seed) numpy.random.seed(seed) class SimpleFrozenDict(dict): """Simplified implementation of a frozen dict, mainly used as default function or method argument (for arguments that should default to empty dictionary). Will raise an error if user or spaCy attempts to add to dict. """ def __setitem__(self, key, value): raise NotImplementedError(Errors.E095) def pop(self, key, default=None): raise NotImplementedError(Errors.E095) def update(self, other): raise NotImplementedError(Errors.E095)
howl-anderson/MicroTokenizer
MicroTokenizer/compat.py
normalize_string_keys
python
def normalize_string_keys(old): new = {} for key, value in old.items(): if isinstance(key, bytes_): new[key.decode('utf8')] = value else: new[key] = value return new
Given a dictionary, make sure keys are unicode strings, not bytes.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/compat.py#L78-L86
null
# coding: utf8 from __future__ import unicode_literals import sys import ujson import itertools import locale try: import cPickle as pickle except ImportError: import pickle try: import copy_reg except ImportError: import copyreg as copy_reg pickle = pickle copy_reg = copy_reg izip = getattr(itertools, 'izip', zip) is_windows = sys.platform.startswith('win') is_linux = sys.platform.startswith('linux') is_osx = sys.platform == 'darwin' # See: https://github.com/benjaminp/six/blob/master/six.py is_python2 = sys.version_info[0] == 2 is_python3 = sys.version_info[0] == 3 is_python_pre_3_5 = is_python2 or (is_python3 and sys.version_info[1] < 5) if is_python2: bytes_ = str unicode_ = unicode # noqa: F821 basestring_ = basestring # noqa: F821 input_ = raw_input # noqa: F821 json_dumps = lambda data: ujson.dumps(data, indent=2, escape_forward_slashes=False).decode('utf8') path2str = lambda path: str(path).decode('utf8') elif is_python3: bytes_ = bytes unicode_ = str basestring_ = str input_ = input json_dumps = lambda data: ujson.dumps(data, indent=2, escape_forward_slashes=False) path2str = lambda path: str(path) def b_to_str(b_str): if is_python2: return b_str # important: if no encoding is set, string becomes "b'...'" return str(b_str, encoding='utf8') def getattr_(obj, name, *default): if is_python3 and isinstance(name, bytes): name = name.decode('utf8') return getattr(obj, name, *default) def symlink_to(orig, dest): if is_python2 and is_windows: import subprocess subprocess.call(['mklink', '/d', path2str(orig), path2str(dest)], shell=True) else: orig.symlink_to(dest) def is_config(python2=None, python3=None, windows=None, linux=None, osx=None): return (python2 in (None, is_python2) and python3 in (None, is_python3) and windows in (None, is_windows) and linux in (None, is_linux) and osx in (None, is_osx)) def import_file(name, loc): loc = str(loc) if is_python_pre_3_5: import imp return imp.load_source(name, loc) else: import importlib.util spec = importlib.util.spec_from_file_location(name, str(loc)) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def locale_escape(string, errors='replace'): ''' Mangle non-supported characters, for savages with ascii terminals. ''' encoding = locale.getpreferredencoding() string = string.encode(encoding, errors).decode('utf8') return string
howl-anderson/MicroTokenizer
MicroTokenizer/compat.py
locale_escape
python
def locale_escape(string, errors='replace'): ''' Mangle non-supported characters, for savages with ascii terminals. ''' encoding = locale.getpreferredencoding() string = string.encode(encoding, errors).decode('utf8') return string
Mangle non-supported characters, for savages with ascii terminals.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/compat.py#L102-L108
null
# coding: utf8 from __future__ import unicode_literals import sys import ujson import itertools import locale try: import cPickle as pickle except ImportError: import pickle try: import copy_reg except ImportError: import copyreg as copy_reg pickle = pickle copy_reg = copy_reg izip = getattr(itertools, 'izip', zip) is_windows = sys.platform.startswith('win') is_linux = sys.platform.startswith('linux') is_osx = sys.platform == 'darwin' # See: https://github.com/benjaminp/six/blob/master/six.py is_python2 = sys.version_info[0] == 2 is_python3 = sys.version_info[0] == 3 is_python_pre_3_5 = is_python2 or (is_python3 and sys.version_info[1] < 5) if is_python2: bytes_ = str unicode_ = unicode # noqa: F821 basestring_ = basestring # noqa: F821 input_ = raw_input # noqa: F821 json_dumps = lambda data: ujson.dumps(data, indent=2, escape_forward_slashes=False).decode('utf8') path2str = lambda path: str(path).decode('utf8') elif is_python3: bytes_ = bytes unicode_ = str basestring_ = str input_ = input json_dumps = lambda data: ujson.dumps(data, indent=2, escape_forward_slashes=False) path2str = lambda path: str(path) def b_to_str(b_str): if is_python2: return b_str # important: if no encoding is set, string becomes "b'...'" return str(b_str, encoding='utf8') def getattr_(obj, name, *default): if is_python3 and isinstance(name, bytes): name = name.decode('utf8') return getattr(obj, name, *default) def symlink_to(orig, dest): if is_python2 and is_windows: import subprocess subprocess.call(['mklink', '/d', path2str(orig), path2str(dest)], shell=True) else: orig.symlink_to(dest) def is_config(python2=None, python3=None, windows=None, linux=None, osx=None): return (python2 in (None, is_python2) and python3 in (None, is_python3) and windows in (None, is_windows) and linux in (None, is_linux) and osx in (None, is_osx)) def normalize_string_keys(old): """Given a dictionary, make sure keys are unicode strings, not bytes.""" new = {} for key, value in old.items(): if isinstance(key, bytes_): new[key.decode('utf8')] = value else: new[key] = value return new def import_file(name, loc): loc = str(loc) if is_python_pre_3_5: import imp return imp.load_source(name, loc) else: import importlib.util spec = importlib.util.spec_from_file_location(name, str(loc)) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
jmvrbanac/Specter
specter/reporting/dots.py
DotsReporter.print_error
python
def print_error(self, wrapper): level = 0 parent = wrapper.parent while parent: print_test_msg(parent.name, level, TestStatus.FAIL, self.use_color) level += 1 parent = parent.parent print_test_msg(wrapper.name, level, TestStatus.FAIL, self.use_color) print_test_args(wrapper.execute_kwargs, level, TestStatus.FAIL, self.use_color) if wrapper.error: for line in wrapper.error: print_test_msg( line, level + 2, TestStatus.FAIL, self.use_color ) print_expects(wrapper, level, use_color=self.use_color)
A crude way of output the errors for now. This needs to be cleaned up into something better.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/reporting/dots.py#L29-L53
[ "def print_expects(test_case, level, use_color=True, use_unicode=True):\n # Print expects\n for expect in test_case.expects:\n mark = u'\\u2718'\n if not use_unicode:\n mark = 'x'\n\n status = TestStatus.FAIL\n if expect.success:\n status = TestStatus.PASS\n mark = u'\\u2714'\n if not use_unicode:\n mark = ' '\n\n # Turn off the status if we're not using color\n if not use_color:\n status = None\n\n expect_msg = u'{mark} {msg}'.format(mark=mark, msg=expect)\n\n print_test_msg(expect_msg, level + 1, status=status)\n\n def hardcoded(param):\n result = re.match('^(\\'|\"|\\d)', str(param)) is not None\n return result\n\n def print_param(value, param, indent, prefix=None):\n if not expect.success and not hardcoded(param):\n msg_list = str(value).splitlines() or ['']\n prefix = _('{0}: {1}').format(param or prefix, msg_list[0])\n print_indent_msg(prefix, indent)\n if len(msg_list) > 1:\n print_msg_list(msg_list[1:], indent)\n\n if expect.custom_msg:\n print_test_msg(expect.custom_msg, level + 3, status=status)\n\n # Print the target parameter\n try:\n print_param(expect.target, expect.target_src_param,\n level + 3, 'Target')\n except:\n print_param('ERROR - Couldn\\'t evaluate target value',\n expect.target_src_param, level + 3, 'Target')\n\n # Print the expected parameter\n try:\n print_param(expect.expected, expect.expected_src_param,\n level + 3, 'Expected')\n except:\n print_param('ERROR - Couldn\\'t evaluate expected value',\n expect.expected_src_param, level + 3, 'Expected')\n\n for var_name, var_value in expect.custom_report_vars.items():\n print_param(var_value, var_name, level + 3)\n", "def print_test_args(kwargs, level, status=TestStatus.PASS, use_color=True):\n if kwargs and (status == TestStatus.ERROR or\n status == TestStatus.FAIL):\n msg = u''.join([\n u' Parameters: ',\n pretty_print_args(kwargs)\n ])\n print_test_msg(msg, level, status, use_color)\n", "def print_test_msg(msg, level, status=None, use_color=True):\n color = get_color_from_status(status) if use_color else None\n print_indent_msg(msg=msg, level=level, color=color)\n" ]
class DotsReporter(AbstractConsoleReporter, AbstractParallelReporter): def __init__(self): super(DotsReporter, self).__init__() self.total = 0 self.failed_tests = [] self.use_color = True def get_name(self): return _('Dots Reporter') def subscribe_to_spec(self, spec): spec.add_listener(TestEvent.COMPLETE, self.test_event) def process_arguments(self, args): if args.no_color: self.use_color = False def test_event(self, evt): self.total += 1 if evt.payload.success: char = '.' else: char = 'x' self.failed_tests.append(evt.payload) stdout.write(char) stdout.flush() def print_summary(self): print(_('\n{0} Test(s) Executed!'.format(self.total))) if len(self.failed_tests) > 0: print(_('\nFailed test information:')) for wrapper in self.failed_tests: self.print_error(wrapper)
jmvrbanac/Specter
specter/runner.py
SpecterRunner.combine_coverage_reports
python
def combine_coverage_reports(self, omit, parallel): tmp_cov = coverage.coverage(omit=omit, data_suffix=parallel) tmp_cov.load() tmp_cov.combine() tmp_cov.save()
Method to force the combination of parallel coverage reports.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/runner.py#L120-L125
null
class SpecterRunner(object): DESCRIPTION = _('Specter is a spec-based testing library to help ' 'facilitate BDD in Python.') def __init__(self): super(SpecterRunner, self).__init__() self.coverage = None self.suite_scanner = None self.arg_parser = ArgumentParser(description=self.DESCRIPTION) self.setup_argparse() self.suites = [] self.reporter_manager = None self.parallel_manager = None def setup_argparse(self): self.arg_parser.add_argument( '--coverage', dest='coverage', action='store_true', help=_('Activates coverage.py integration') ) self.arg_parser.add_argument( '--search', type=str, dest='search', metavar='', help=_('The spec suite folder path.') ) self.arg_parser.add_argument( '--no-art', dest='no_art', action='store_true', help=_('Disables ASCII art') ) self.arg_parser.add_argument( '--select-module', dest='select_module', metavar='', help=_('Selects a module path to run. Ex: sample.TestClass'), default=None ) self.arg_parser.add_argument( '--select-tests', dest='select_tests', metavar='', help=_('Selects tests by name (comma delimited list).'), type=lambda s: [item.strip() for item in s.split(',')], default=None ) self.arg_parser.add_argument( '--select-by-metadata', dest='select_meta', metavar='', help=_('Selects tests to run by specifying a list of ' 'key=value pairs you wish to run'), default=[], nargs='*' ) self.arg_parser.add_argument( '--no-color', dest='no_color', action='store_true', help=_('Disables all ASCII color codes.') ) self.arg_parser.add_argument( '--parallel', dest='parallel', action='store_true', help=_('Activate parallel testing mode') ) self.arg_parser.add_argument( '--num-processes', dest='num_processes', type=int, default=6, metavar='', help=_('Specifies the number of processes to use under ' 'parallel mode (default: 6)') ) def generate_ascii_art(self): tag_line = _('Keeping the Bogeyman away from your code!') ascii_art = """ ___ _/ @@\\ ~- ( \\ O/__ Specter ~- \\ \\__) ~~~~~~~~~~ ~- / \\ {tag} ~- / _\\ ~~~~~~~~~ """.format(tag=tag_line) return ascii_art def get_coverage_omit_list(self): omit_list = ['*/pyevents/event.py', '*/pyevents/manager.py', '*/specter/spec.py', '*/specter/expect.py', '*/specter/parallel.py', '*/specter/scanner.py', '*/specter/runner.py', '*/specter/util.py', '*/specter/reporting/__init__.py', '*/specter/reporting/console.py', '*/specter/reporting/dots.py', '*/specter/reporting/xunit.py', '*/specter/__init__.py'] return omit_list def run(self, args): select_meta = None self.reporter_manager = ReporterPluginManager() self.reporter_manager.add_to_arguments(self.arg_parser) self.arguments = self.arg_parser.parse_args(args) # Let each reporter parse cli arguments self.reporter_manager.process_arguments(self.arguments) if self.arguments.parallel: coverage.process_startup() self.parallel_manager = ParallelManager( num_processes=self.arguments.num_processes, track_coverage=self.arguments.coverage, coverage_omit=self.get_coverage_omit_list()) if self.arguments.select_meta: metas = [meta.split('=') for meta in self.arguments.select_meta] select_meta = {meta[0]: meta[1].strip('"\'') for meta in metas} if not self.arguments.no_art: print(self.generate_ascii_art()) if self.arguments.coverage: print(_(' - Running with coverage enabled - ')) self.coverage = coverage.coverage( omit=self.get_coverage_omit_list(), data_suffix=self.arguments.parallel) self.coverage._warn_no_data = False self.coverage.start() self.suite_scanner = SuiteScanner(self.arguments.search or 'spec') self.suite_types = self.suite_scanner.scan( self.arguments.select_module) # Serial: Add and Execute | Parallel: Collect all with the add process for suite_type in self.suite_types: suite = suite_type() self.suites.append(suite) self.reporter_manager.subscribe_all_to_spec(suite) suite.execute(select_metadata=select_meta, parallel_manager=self.parallel_manager, select_tests=self.arguments.select_tests) # Actually execute the tests for parallel now if self.arguments.parallel: self.parallel_manager.execute_all() # Save coverage data if enabled if self.coverage: self.coverage.stop() self.coverage.save() if self.arguments.parallel: self.combine_coverage_reports( self.get_coverage_omit_list(), self.arguments.parallel) # Print all console summaries for reporter in self.reporter_manager.get_console_reporters(): reporter.print_summary() self.reporter_manager.finish_all() self.suite_scanner.destroy()
jmvrbanac/Specter
specter/spec.py
CaseWrapper.serialize
python
def serialize(self): expects = [exp.serialize() for exp in self.expects] converted_dict = { 'id': self.id, 'name': self.pretty_name, 'raw_name': self.name, 'doc': self.doc, 'error': self.error, 'skipped': self.skipped, 'skip_reason': self.skip_reason, 'execute_kwargs': self.safe_execute_kwargs, 'metadata': self.metadata, 'start': self.start_time, 'end': self.end_time, 'expects': expects, 'success': self.success } return remove_empty_entries_from_dict(converted_dict)
Serializes the CaseWrapper object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/spec.py#L53-L76
[ "def remove_empty_entries_from_dict(input_dict):\n return {k: v for k, v in six.iteritems(input_dict) if v is not None}\n" ]
class CaseWrapper(TimedObject): def __init__(self, case_func, parent, execute_kwargs=None, metadata={}): super(CaseWrapper, self).__init__() self.id = str(uuid.uuid4()) self.case_func = case_func self.expects = [] self.parent = parent self.failed = None self.error = None self.skipped = False self.incomplete = False self.skip_reason = None self.execute_kwargs = execute_kwargs self.metadata = metadata def execute(self, context=None): kwargs = {} if self.execute_kwargs: kwargs.update(self.execute_kwargs) self.start() try: types.MethodType(self.case_func, context or self)(**kwargs) except TestIncompleteException as e: self.incomplete = True # If thrown during decorators if e.real_func: self.case_func = e.real_func except TestSkippedException as e: self.skipped = True self.skip_reason = e.reason if type(e.reason) is str else '' # If thrown during decorators if e.real_func: self.case_func = e.real_func except FailedRequireException: pass except Exception as e: self.error = get_real_last_traceback(e) self.stop() @property def name(self): return convert_camelcase(self.case_func.__name__) @property def pretty_name(self): return self.case_func.__name__.replace('_', ' ') @property def doc(self): return self.case_func.__doc__ @property def success(self): return (self.complete and not self.failed and not self.error and len([exp for exp in self.expects if not exp.success]) == 0) @property def complete(self): return self.end_time > 0.0 @property def safe_execute_kwargs(self): safe_kwargs = copy.deepcopy(self.execute_kwargs) if not safe_kwargs: return for k, v in six.iteritems(safe_kwargs): if type(v) not in [str, int, list, bool, dict]: safe_kwargs[k] = str(v) return safe_kwargs def __getstate__(self): altered = dict(self.__dict__) if 'case_func' in altered: altered['case_func'] = self.id if 'parent' in altered: altered['parent'] = self.parent.id return altered def __eq__(self, other): if isinstance(other, CaseWrapper): return self.id == other.id return False def __ne__(self, other): return not self == other
jmvrbanac/Specter
specter/spec.py
Describe.serialize
python
def serialize(self): cases = [case.serialize() for key, case in six.iteritems(self.cases)] specs = [spec.serialize() for spec in self.describes] converted_dict = { 'id': self.id, 'name': self.name, 'class_path': self.real_class_path, 'doc': self.doc, 'cases': cases, 'specs': specs } return converted_dict
Serializes the Spec/Describe object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/spec.py#L280-L299
null
class Describe(EventDispatcher): __FIXTURE__ = False #: List of methods to be called after every test hooks = () def __init__(self, parent=None): super(Describe, self).__init__() self.id = str(uuid.uuid4()) wrappers = self.__wrappers__ self.parent = parent self.cases = wrappers self.describes = [desc_type(parent=self) for desc_type in self.describe_types] self._num_completed_cases = 0 self._state = self.__create_state_obj__() @property def name(self): return convert_camelcase(self.__class__.__name__) @property def complete(self): cases_completed = self._num_completed_cases == len(self.cases) descs_not_completed = [desc for desc in self.describes if not desc.complete] return cases_completed and len(descs_not_completed) == 0 @property def real_class_path(self): ancestors = [self.__class__.__name__] parent = self.parent while parent: ancestors.insert(0, parent.__class__.__name__) parent = parent.parent real_path = '.'.join(ancestors) return '{base}.{path}'.format(base=self.__module__, path=real_path) @property def doc(self): return type(self).__doc__ @property def total_time(self): total = 0.0 for key, case in six.iteritems(self.cases): total += case.elapsed_time for describe in self.describes: total += describe.total_time return total @property def success(self): ok = True case_successes = [case.success for key, case in six.iteritems(self.cases)] spec_successes = [spec.success for spec in self.describes] if case_successes and False in case_successes: ok = False if spec_successes and False in spec_successes: ok = False return ok @property def __wrappers__(self): wrappers = {} for case_func in self.case_funcs: case_func, metadata = extract_metadata(case_func) wrapper = CaseWrapper(case_func, parent=self, metadata=metadata) wrappers[wrapper.id] = wrapper return wrappers @classmethod def __cls_members__(cls): all_members = {} classes = list(cls.__bases__) + [cls] for klass in classes: pairs = dict((key, val) for key, val in vars(klass).items()) all_members.update(pairs) return all_members @classmethod def __get_all_child_describes__(cls): members = cls.__cls_members__() child_describes = [val for key, val in members.items() if Describe.plugin_filter(val)] all_children = child_describes + [cls] for child in child_describes: all_children.extend(child.__get_all_child_describes__()) return set(all_children) @property def __members__(self): return type(self).__cls_members__() @property def describe_types(self): return [val for key, val in self.__members__.items() if Describe.plugin_filter(val)] @property def case_funcs(self): return [val for key, val in self.__members__.items() if Describe.case_filter(val)] @property def top_parent(self): parent_above = last_parent = self.parent or self while parent_above is not None: last_parent = parent_above parent_above = parent_above.parent return last_parent @classmethod def is_fixture(cls): return vars(cls).get('__FIXTURE__') is True def _run_hooks(self): """Calls any registered hooks providing the current state.""" for hook in self.hooks: getattr(self, hook)(self._state) def __create_state_obj__(self): """ Generates the clean state object magic. Here be dragons! """ stops = [Describe, Spec, DataDescribe, EventDispatcher] mros = [mro for mro in inspect.getmro(type(self)) if mro not in stops] mros.reverse() # Create generic object class GenericStateObj(object): def before_all(self): pass def after_all(self): pass def before_each(self): pass def after_each(self): pass # Duplicate inheritance chain chain = [GenericStateObj] for mro in mros: cls_name = '{0}StateObj'.format(mro.__name__) cls = type(cls_name, (chain[-1:][0],), dict(mro.__dict__)) cls.__spec__ = self chain.append(cls) # Removing fallback chain.pop(0) state_cls = chain[-1:][0] return state_cls() def _sort_cases(self, cases): sorted_cases = sorted( cases.items(), key=lambda case: case[1].case_func.__name__) return collections.OrderedDict(sorted_cases) def parallel_execution(self, manager, select_metadata=None, select_tests=None): self.top_parent.dispatch(DescribeEvent(DescribeEvent.START, self)) self._state.before_all() for key, case in six.iteritems(self.cases): manager.add_to_queue(case) for describe in self.describes: describe.execute(select_metadata, select_tests, manager) def standard_execution(self, select_metadata=None, select_tests=None): self.top_parent.dispatch(DescribeEvent(DescribeEvent.START, self)) self._state.before_all() # Execute Cases for key, case in six.iteritems(self.cases): self._state.before_each() case.execute(context=self._state) self._state.after_each() self._run_hooks() self._num_completed_cases += 1 self.top_parent.dispatch(TestEvent(case)) # Execute Suites for describe in self.describes: describe.execute( select_metadata=select_metadata, select_tests=select_tests ) self._state.after_all() self.top_parent.dispatch(DescribeEvent(DescribeEvent.COMPLETE, self)) def execute(self, select_metadata=None, select_tests=None, parallel_manager=None): if select_metadata: self.cases = find_by_metadata(select_metadata, self.cases) self.describes = children_with_tests_with_metadata( select_metadata, self) if select_tests: self.cases = find_by_names(select_tests, self.cases) self.describes = children_with_tests_named(select_tests, self) # If it doesn't have tests or describes don't run it if len(self.cases) <= 0 and len(self.describes) <= 0: return # Sort suite case funcs to ensure stable order of execution self.cases = self._sort_cases(self.cases) if parallel_manager: self.parallel_execution( parallel_manager, select_metadata, select_tests ) else: self.standard_execution(select_metadata, select_tests) @classmethod def plugin_filter(cls, other): if not isinstance(other, type): return False if hasattr(other, 'is_fixture') and other.is_fixture(): return False return (issubclass(other, Describe) and other is not cls and other is not Spec and other is not DataSpec and other is not DataDescribe) @classmethod def case_filter(cls, obj): if not isinstance(obj, types.FunctionType): return False reserved = [ 'execute', 'standard_execution', 'parallel_execution', 'serialize', 'before_each', 'after_each', 'before_all', 'after_all' ] func_name = obj.__name__ return (not func_name.startswith('_') and func_name not in reserved)
jmvrbanac/Specter
specter/spec.py
Describe._run_hooks
python
def _run_hooks(self): for hook in self.hooks: getattr(self, hook)(self._state)
Calls any registered hooks providing the current state.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/spec.py#L301-L304
null
class Describe(EventDispatcher): __FIXTURE__ = False #: List of methods to be called after every test hooks = () def __init__(self, parent=None): super(Describe, self).__init__() self.id = str(uuid.uuid4()) wrappers = self.__wrappers__ self.parent = parent self.cases = wrappers self.describes = [desc_type(parent=self) for desc_type in self.describe_types] self._num_completed_cases = 0 self._state = self.__create_state_obj__() @property def name(self): return convert_camelcase(self.__class__.__name__) @property def complete(self): cases_completed = self._num_completed_cases == len(self.cases) descs_not_completed = [desc for desc in self.describes if not desc.complete] return cases_completed and len(descs_not_completed) == 0 @property def real_class_path(self): ancestors = [self.__class__.__name__] parent = self.parent while parent: ancestors.insert(0, parent.__class__.__name__) parent = parent.parent real_path = '.'.join(ancestors) return '{base}.{path}'.format(base=self.__module__, path=real_path) @property def doc(self): return type(self).__doc__ @property def total_time(self): total = 0.0 for key, case in six.iteritems(self.cases): total += case.elapsed_time for describe in self.describes: total += describe.total_time return total @property def success(self): ok = True case_successes = [case.success for key, case in six.iteritems(self.cases)] spec_successes = [spec.success for spec in self.describes] if case_successes and False in case_successes: ok = False if spec_successes and False in spec_successes: ok = False return ok @property def __wrappers__(self): wrappers = {} for case_func in self.case_funcs: case_func, metadata = extract_metadata(case_func) wrapper = CaseWrapper(case_func, parent=self, metadata=metadata) wrappers[wrapper.id] = wrapper return wrappers @classmethod def __cls_members__(cls): all_members = {} classes = list(cls.__bases__) + [cls] for klass in classes: pairs = dict((key, val) for key, val in vars(klass).items()) all_members.update(pairs) return all_members @classmethod def __get_all_child_describes__(cls): members = cls.__cls_members__() child_describes = [val for key, val in members.items() if Describe.plugin_filter(val)] all_children = child_describes + [cls] for child in child_describes: all_children.extend(child.__get_all_child_describes__()) return set(all_children) @property def __members__(self): return type(self).__cls_members__() @property def describe_types(self): return [val for key, val in self.__members__.items() if Describe.plugin_filter(val)] @property def case_funcs(self): return [val for key, val in self.__members__.items() if Describe.case_filter(val)] @property def top_parent(self): parent_above = last_parent = self.parent or self while parent_above is not None: last_parent = parent_above parent_above = parent_above.parent return last_parent @classmethod def is_fixture(cls): return vars(cls).get('__FIXTURE__') is True def serialize(self): """ Serializes the Spec/Describe object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed. """ cases = [case.serialize() for key, case in six.iteritems(self.cases)] specs = [spec.serialize() for spec in self.describes] converted_dict = { 'id': self.id, 'name': self.name, 'class_path': self.real_class_path, 'doc': self.doc, 'cases': cases, 'specs': specs } return converted_dict def __create_state_obj__(self): """ Generates the clean state object magic. Here be dragons! """ stops = [Describe, Spec, DataDescribe, EventDispatcher] mros = [mro for mro in inspect.getmro(type(self)) if mro not in stops] mros.reverse() # Create generic object class GenericStateObj(object): def before_all(self): pass def after_all(self): pass def before_each(self): pass def after_each(self): pass # Duplicate inheritance chain chain = [GenericStateObj] for mro in mros: cls_name = '{0}StateObj'.format(mro.__name__) cls = type(cls_name, (chain[-1:][0],), dict(mro.__dict__)) cls.__spec__ = self chain.append(cls) # Removing fallback chain.pop(0) state_cls = chain[-1:][0] return state_cls() def _sort_cases(self, cases): sorted_cases = sorted( cases.items(), key=lambda case: case[1].case_func.__name__) return collections.OrderedDict(sorted_cases) def parallel_execution(self, manager, select_metadata=None, select_tests=None): self.top_parent.dispatch(DescribeEvent(DescribeEvent.START, self)) self._state.before_all() for key, case in six.iteritems(self.cases): manager.add_to_queue(case) for describe in self.describes: describe.execute(select_metadata, select_tests, manager) def standard_execution(self, select_metadata=None, select_tests=None): self.top_parent.dispatch(DescribeEvent(DescribeEvent.START, self)) self._state.before_all() # Execute Cases for key, case in six.iteritems(self.cases): self._state.before_each() case.execute(context=self._state) self._state.after_each() self._run_hooks() self._num_completed_cases += 1 self.top_parent.dispatch(TestEvent(case)) # Execute Suites for describe in self.describes: describe.execute( select_metadata=select_metadata, select_tests=select_tests ) self._state.after_all() self.top_parent.dispatch(DescribeEvent(DescribeEvent.COMPLETE, self)) def execute(self, select_metadata=None, select_tests=None, parallel_manager=None): if select_metadata: self.cases = find_by_metadata(select_metadata, self.cases) self.describes = children_with_tests_with_metadata( select_metadata, self) if select_tests: self.cases = find_by_names(select_tests, self.cases) self.describes = children_with_tests_named(select_tests, self) # If it doesn't have tests or describes don't run it if len(self.cases) <= 0 and len(self.describes) <= 0: return # Sort suite case funcs to ensure stable order of execution self.cases = self._sort_cases(self.cases) if parallel_manager: self.parallel_execution( parallel_manager, select_metadata, select_tests ) else: self.standard_execution(select_metadata, select_tests) @classmethod def plugin_filter(cls, other): if not isinstance(other, type): return False if hasattr(other, 'is_fixture') and other.is_fixture(): return False return (issubclass(other, Describe) and other is not cls and other is not Spec and other is not DataSpec and other is not DataDescribe) @classmethod def case_filter(cls, obj): if not isinstance(obj, types.FunctionType): return False reserved = [ 'execute', 'standard_execution', 'parallel_execution', 'serialize', 'before_each', 'after_each', 'before_all', 'after_all' ] func_name = obj.__name__ return (not func_name.startswith('_') and func_name not in reserved)
jmvrbanac/Specter
specter/reporting/__init__.py
ReporterPluginManager.subscribe_all_to_spec
python
def subscribe_all_to_spec(self, spec): for reporter in self.reporters: if self.can_use_reporter(reporter, self.parallel): reporter.subscribe_to_spec(spec)
Will automatically not subscribe reporters that are not parallel or serial depending on the current mode.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/reporting/__init__.py#L77-L83
[ "def can_use_reporter(self, reporter, parallel):\n can_use = False\n if parallel:\n if isinstance(reporter, AbstractParallelReporter):\n can_use = True\n else:\n if isinstance(reporter, AbstractSerialReporter):\n can_use = True\n return can_use\n" ]
class ReporterPluginManager(object): def __init__(self, parallel=False): self.reporters = [] self.load_reporters() self.parallel = parallel def get_console_reporters(self): return [reporter for reporter in self.reporters if issubclass(type(reporter), AbstractConsoleReporter) and self.can_use_reporter(reporter, self.parallel)] def add_to_arguments(self, argparser): [reporter.add_arguments(argparser) for reporter in self.reporters] def process_arguments(self, args): self.parallel = args.parallel [reporter.process_arguments(args) for reporter in self.reporters] def can_use_reporter(self, reporter, parallel): can_use = False if parallel: if isinstance(reporter, AbstractParallelReporter): can_use = True else: if isinstance(reporter, AbstractSerialReporter): can_use = True return can_use def finish_all(self): [reporter.finished() for reporter in self.reporters] def reporter_filter(self, class_type): abstracts = [AbstractReporterPlugin, AbstractParallelReporter, AbstractSerialReporter, AbstractConsoleReporter] return (issubclass(class_type, AbstractReporterPlugin) and class_type not in abstracts) def get_reporters_classes(self): module = py.get_module_by_name('specter.reporting') return py.get_all_classes(module, self.reporter_filter) def load_reporters(self, force_reload=False): if force_reload: self.reporters = [] if not self.reporters: classes = self.get_reporters_classes() for klass in classes: self.reporters.append(klass()) return self.reporters
jmvrbanac/Specter
specter/reporting/console.py
ConsoleReporter.output
python
def output(self, msg, indent, status=None): color = None if self.use_color: color = get_color_from_status(status) print_indent_msg(msg, indent, color)
Alias for print_indent_msg with color determined by status.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/reporting/console.py#L139-L144
[ "def get_color_from_status(status):\n color = None\n if status == TestStatus.PASS:\n color = ConsoleColors.GREEN\n elif status == TestStatus.SKIP:\n color = ConsoleColors.YELLOW\n elif status == TestStatus.INCOMPLETE:\n color = ConsoleColors.MAGENTA\n elif status is not None:\n color = ConsoleColors.RED\n\n return color\n", "def print_indent_msg(msg, level=0, color=None):\n indent = u' ' * 2\n msg = u'{0}{1}'.format(str(indent * level), msg)\n print_to_screen(msg=msg, color=color)\n" ]
class ConsoleReporter(AbstractConsoleReporter, AbstractSerialReporter): """ Simple BDD Style console reporter. """ def __init__(self, output_docstrings=False, use_color=True): super(ConsoleReporter, self).__init__() self.use_color = use_color self.use_unicode = True self.test_total = 0 self.test_expects = 0 self.passed_tests = 0 self.skipped_tests = 0 self.errored_tests = 0 self.failed_tests = 0 self.incomplete_tests = 0 self.output_docstrings = output_docstrings self.show_all = False self.separator = UNICODE_SEP def get_name(self): return 'Simple BDD Serial console reporter' def add_arguments(self, argparser): argparser.add_argument( '--show-all-expects', dest='show_all_expects', action='store_true', help=_('Displays all expectations for test cases')) argparser.add_argument( '--ascii-only', dest='ascii_only', action='store_true', help=_('Disables color and uses only ascii characters ' '(useful for CI systems)')) def process_arguments(self, args): if args.no_color: self.use_color = False if args.show_all_expects: self.show_all = True if args.ascii_only: self.use_color = False self.use_unicode = False self.separator = ASCII_SEP def get_test_case_status(self, test_case, name): status = TestStatus.FAIL if (test_case.success and not test_case.skipped and not test_case.incomplete): status = TestStatus.PASS elif test_case.incomplete: status = TestStatus.INCOMPLETE name = u'{name} (incomplete)'.format(name=name) elif test_case.skipped: status = TestStatus.SKIP name = u'{name} (skipped): {reason}'.format( name=name, reason=test_case.skip_reason) elif test_case.error: status = TestStatus.ERROR return status, name def add_to_totals(self, test_case): self.test_total += 1 if (test_case.success and not test_case.skipped and not test_case.incomplete): self.passed_tests += 1 elif test_case.skipped: self.skipped_tests += 1 elif test_case.incomplete: self.incomplete_tests += 1 elif test_case.error: self.errored_tests += 1 else: self.failed_tests += 1 self.test_expects += len(test_case.expects) def output_test_case_result(self, test_case, level): name = test_case.pretty_name if level > 0: name = u'{0} {1}'.format(self.separator, name) status, name = self.get_test_case_status(test_case, name) self.output(name, level, status) print_test_args(test_case.execute_kwargs, level, status, self.use_color) if test_case.doc and self.output_docstrings: print_indent_msg(test_case.doc, level + 1, status) # Print error if it exists if test_case.error: for line in test_case.error: self.output(line, level + 2, TestStatus.FAIL) if status == TestStatus.FAIL or self.show_all: print_expects( test_case, level, self.use_color, self.use_unicode ) def subscribe_to_spec(self, spec): spec.add_listener(TestEvent.COMPLETE, self.test_complete) spec.add_listener(DescribeEvent.START, self.start_spec) def test_complete(self, evt): test_case = evt.payload level = get_item_level(test_case) self.output_test_case_result(test_case, level) self.add_to_totals(test_case) def start_spec(self, evt): level = get_item_level(evt.payload) name = evt.payload.name if level > 0: name = u'{0} {1}'.format(self.separator, name) # Output Spec name color = ConsoleColors.GREEN if self.use_color else None print_indent_msg(name, level, color=color) # Output Docstrings if enabled if evt.payload.doc and self.output_docstrings: print_indent_msg(evt.payload.doc, level + 1) def print_summary(self): msg = """------- Summary -------- Pass | {passed} Skip | {skipped} Fail | {failed} Error | {errored} Incomplete | {incomplete} Test Total | {total} - Expectations | {expects} """.format( total=self.test_total, passed=self.passed_tests, failed=self.failed_tests, expects=self.test_expects, skipped=self.skipped_tests, incomplete=self.incomplete_tests, errored=self.errored_tests) status = TestStatus.FAIL if self.failed_tests == 0 and self.errored_tests == 0: status = TestStatus.PASS print_to_screen('\n') self.output('-' * 24, 0, status) self.output(msg, 0, status) self.output('-' * 24, 0, status)
jmvrbanac/Specter
specter/util.py
get_real_last_traceback
python
def get_real_last_traceback(exception): traceback_blocks = [] _n, _n, exc_traceback = sys.exc_info() tb_list = get_all_tracebacks(exc_traceback)[1:] # Remove already captured tracebacks # TODO(jmv): This must be a better way of doing this. Need to revisit. tb_list = [tb for tb in tb_list if tb not in CAPTURED_TRACEBACKS] CAPTURED_TRACEBACKS.extend(tb_list) for traceback in tb_list: lines, path, line_num = get_source_from_frame(traceback.tb_frame) traceback_lines = get_numbered_source(lines, traceback.tb_lineno, line_num) traceback_lines.insert(0, ' - {0}'.format(path)) traceback_lines.insert(1, ' ------------------') traceback_lines.append(' ------------------') traceback_blocks.append(traceback_lines) traced_lines = ['Error Traceback:'] traced_lines.extend(itertools.chain.from_iterable(traceback_blocks)) traced_lines.append(' - Error | {0}: {1}'.format( type(exception).__name__, exception)) return traced_lines
An unfortunate evil... All because Python's traceback cannot determine where my executed code is coming from...
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/util.py#L155-L183
[ "def get_numbered_source(lines, line_num, starting_line=0):\n try:\n center = (line_num - starting_line) - 1\n start = center - 2 if center - 2 > 0 else 0\n end = center + 2 if center + 2 <= len(lines) else len(lines)\n\n orig_src_lines = [line.rstrip('\\n') for line in lines[start:end]]\n line_range = range(start + 1 + starting_line, end + 1 + starting_line)\n nums_and_source = zip(line_range, orig_src_lines)\n\n traceback_lines = []\n for num, line in nums_and_source:\n prefix = '--> ' if num == line_num else ' '\n traceback_lines.append('{0}{1}: {2}'.format(prefix, num, line))\n\n return traceback_lines\n except Exception as e:\n return ['Error finding traceback!', e]\n", "def get_source_from_frame(frame):\n self = frame.f_locals.get('self', None)\n cls = frame.f_locals.get('cls', None)\n\n # for old style classes, getmodule(type(self)) returns __builtin__, and\n # inspect.getfile(__builtin__) throws an exception\n insp_obj = inspect.getmodule(type(self) if self else cls) or frame.f_code\n if insp_obj == __builtin__:\n insp_obj = frame.f_code\n\n line_num_modifier = 0\n if inspect.iscode(insp_obj):\n line_num_modifier -= 1\n\n module_path = inspect.getfile(insp_obj)\n source_lines = inspect.getsourcelines(insp_obj)\n return source_lines[0], module_path, source_lines[1] + line_num_modifier\n", "def get_all_tracebacks(tb, tb_list=[]):\n tb_list.append(tb)\n next_tb = getattr(tb, 'tb_next')\n if next_tb:\n tb_list = get_all_tracebacks(next_tb, tb_list)\n return tb_list\n" ]
import ast import inspect import re import itertools import sys import six from specter.vendor.ast_decompiler import decompile try: import __builtin__ except ImportError: import builtins as __builtin__ CAPTURED_TRACEBACKS = [] class ExpectParams(object): types_with_args = [ 'equal', 'almost_equal', 'be_greater_than', 'be_less_than', 'be_almost_equal', 'be_a', 'be_an_instance_of', 'be_in', 'contain', 'raise_a' ] def __init__(self, line, module): def distance(node): return abs(node.lineno - line) tree = ast.parse(inspect.getsource(module)) # Walk the tree until we get the expression we need expect_exp = None closest_exp = None for node in ast.walk(tree): if isinstance(node, ast.Expr): if node.lineno == line: expect_exp = node break if (closest_exp is None or distance(node) < distance(closest_exp)): closest_exp = node self.expect_exp = expect_exp or closest_exp @property def cmp_call(self): if self.expect_exp: return self.expect_exp.value @property def expect_call(self): if self.cmp_call: return self.cmp_call.func.value.value @property def cmp_type(self): if self.cmp_call: return self.cmp_call.func.attr @property def cmp_arg(self): arg = None if self.cmp_type in self.types_with_args: arg = decompile(self.cmp_call.args[0]) return arg @property def expect_type(self): return self.expect_call.func.id @property def expect_arg(self): if self.expect_call: return decompile(self.expect_call.args[0]) def convert_camelcase(input_str): if input_str is None: return '' camelcase_tags = '((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))' return re.sub(camelcase_tags, r' \1', input_str) def get_module_and_line(use_child_attr=None): last_frame = inspect.currentframe() steps = 2 for i in range(steps): last_frame = last_frame.f_back self = module = last_frame.f_locals['self'] # Use an attr instead of self if use_child_attr: module = getattr(self, use_child_attr, self) return last_frame.f_lineno, inspect.getmodule(type(module)) def get_source_from_frame(frame): self = frame.f_locals.get('self', None) cls = frame.f_locals.get('cls', None) # for old style classes, getmodule(type(self)) returns __builtin__, and # inspect.getfile(__builtin__) throws an exception insp_obj = inspect.getmodule(type(self) if self else cls) or frame.f_code if insp_obj == __builtin__: insp_obj = frame.f_code line_num_modifier = 0 if inspect.iscode(insp_obj): line_num_modifier -= 1 module_path = inspect.getfile(insp_obj) source_lines = inspect.getsourcelines(insp_obj) return source_lines[0], module_path, source_lines[1] + line_num_modifier def get_all_tracebacks(tb, tb_list=[]): tb_list.append(tb) next_tb = getattr(tb, 'tb_next') if next_tb: tb_list = get_all_tracebacks(next_tb, tb_list) return tb_list def get_numbered_source(lines, line_num, starting_line=0): try: center = (line_num - starting_line) - 1 start = center - 2 if center - 2 > 0 else 0 end = center + 2 if center + 2 <= len(lines) else len(lines) orig_src_lines = [line.rstrip('\n') for line in lines[start:end]] line_range = range(start + 1 + starting_line, end + 1 + starting_line) nums_and_source = zip(line_range, orig_src_lines) traceback_lines = [] for num, line in nums_and_source: prefix = '--> ' if num == line_num else ' ' traceback_lines.append('{0}{1}: {2}'.format(prefix, num, line)) return traceback_lines except Exception as e: return ['Error finding traceback!', e] def find_by_names(names, cases): selected_cases = {} for case_id, case in six.iteritems(cases): if case.name in names or case.pretty_name in names: selected_cases[case_id] = case return selected_cases def children_with_tests_named(names, describe): children = [] for child in describe.describes: found = find_by_names(names, child.cases) if len(found) > 0: children.append(child) children.extend(children_with_tests_named(names, child)) return children def find_by_metadata(meta, cases): selected_cases = {} for case_id, case in six.iteritems(cases): matched_keys = set(meta.keys()) & set(case.metadata.keys()) for key in matched_keys: if meta.get(key) == case.metadata.get(key): selected_cases[case_id] = case return selected_cases def children_with_tests_with_metadata(meta, describe): children = [] for child in describe.describes: found = find_by_metadata(meta, child.cases) if len(found) > 0: children.append(child) children.extend(children_with_tests_with_metadata(meta, child)) return children def extract_metadata(case_func): # Handle metadata decorator metadata = {} if 'DECORATOR_ONCALL' in case_func.__name__: try: decorator_data = case_func() case_func = decorator_data[0] metadata = decorator_data[1] except Exception as e: # Doing this old school to avoid dependancy conflicts handled = ['TestIncompleteException', 'TestSkippedException'] if type(e).__name__ in handled: case_func = e.func metadata = e.other_data.get('metadata') else: raise e return case_func, metadata def remove_empty_entries_from_dict(input_dict): return {k: v for k, v in six.iteritems(input_dict) if v is not None}
jmvrbanac/Specter
specter/vendor/ast_decompiler.py
decompile
python
def decompile(ast, indentation=4, line_length=100, starting_indentation=0): decompiler = Decompiler( indentation=indentation, line_length=line_length, starting_indentation=starting_indentation, ) return decompiler.run(ast)
Decompiles an AST into Python code. Arguments: - ast: code to decompile, using AST objects as generated by the standard library ast module - indentation: indentation level of lines - line_length: if lines become longer than this length, ast_decompiler will try to break them up (but it will not necessarily succeed in all cases) - starting_indentation: indentation level at which to start producing code
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/vendor/ast_decompiler.py#L94-L110
[ "def run(self, ast):\n self.visit(ast)\n if self.current_line:\n self.lines.append(''.join(self.current_line))\n self.current_line = []\n return ''.join(self.lines)\n" ]
""" Vendored Project: AST Decompiler Package: ast-decompiler Version: 0.2 Author: Jelle Zijlstra License: Apache v2 Project: https://github.com/JelleZijlstra/ast_decompiler """ import ast from contextlib import contextmanager import sys try: _basestring = basestring _long = long PY3 = False except NameError: # py3 _basestring = str _long = int PY3 = True _OP_TO_STR = { ast.Add: '+', ast.Sub: '-', ast.Mult: '*', ast.Div: '/', ast.Mod: '%', ast.Pow: '**', ast.LShift: '<<', ast.RShift: '>>', ast.BitOr: '|', ast.BitXor: '^', ast.BitAnd: '&', ast.FloorDiv: '//', ast.Invert: '~', ast.Not: 'not ', ast.UAdd: '+', ast.USub: '-', ast.Eq: '==', ast.NotEq: '!=', ast.Lt: '<', ast.LtE: '<=', ast.Gt: '>', ast.GtE: '>=', ast.Is: 'is', ast.IsNot: 'is not', ast.In: 'in', ast.NotIn: 'not in', ast.And: 'and', ast.Or: 'or', } class _CallArgs(object): """Used as an entry in the precedence table. Needed to convey the high precedence of the callee but low precedence of the arguments. """ _PRECEDENCE = { _CallArgs: -1, ast.Or: 0, ast.And: 1, ast.Not: 2, ast.Compare: 3, ast.BitOr: 4, ast.BitXor: 5, ast.BitAnd: 6, ast.LShift: 7, ast.RShift: 7, ast.Add: 8, ast.Sub: 8, ast.Mult: 9, ast.Div: 9, ast.FloorDiv: 9, ast.Mod: 9, ast.UAdd: 10, ast.USub: 10, ast.Invert: 10, ast.Pow: 11, ast.Subscript: 12, ast.Call: 12, ast.Attribute: 12, } if hasattr(ast, 'MatMult'): _OP_TO_STR[ast.MatMult] = '@' _PRECEDENCE[ast.MatMult] = 9 # same as multiplication class Decompiler(ast.NodeVisitor): def __init__(self, indentation, line_length, starting_indentation): self.lines = [] self.current_line = [] self.current_indentation = starting_indentation self.node_stack = [] self.indentation = indentation self.max_line_length = line_length self.has_unicode_literals = False def run(self, ast): self.visit(ast) if self.current_line: self.lines.append(''.join(self.current_line)) self.current_line = [] return ''.join(self.lines) def visit(self, node): self.node_stack.append(node) try: return super(Decompiler, self).visit(node) finally: if self.node_stack: self.node_stack.pop() def precedence_of_node(self, node): if isinstance(node, (ast.BinOp, ast.UnaryOp, ast.BoolOp)): return _PRECEDENCE[type(node.op)] return _PRECEDENCE.get(type(node), -1) def get_parent_node(self): try: return self.node_stack[-2] except IndexError: return None def write(self, code): assert isinstance(code, _basestring), 'invalid code %r' % code self.current_line.append(code) def write_indentation(self): self.write(' ' * self.current_indentation) def write_newline(self): line = ''.join(self.current_line) + '\n' self.lines.append(line) self.current_line = [] def current_line_length(self): return sum(map(len, self.current_line)) def write_expression_list(self, nodes, separator=', ', allow_newlines=True, need_parens=True, final_separator_if_multiline=True): """Writes a list of nodes, separated by separator. If allow_newlines, will write the expression over multiple lines if necessary to say within max_line_length. If need_parens, will surround the expression with parentheses in this case. If final_separator_if_multiline, will write a separator at the end of the list if it is divided over multiple lines. """ first = True last_line = len(self.lines) current_line = list(self.current_line) for node in nodes: if first: first = False else: self.write(separator) self.visit(node) if allow_newlines and (self.current_line_length() > self.max_line_length or last_line != len(self.lines)): break else: return # stayed within the limit # reset state del self.lines[last_line:] self.current_line = current_line separator = separator.rstrip() if need_parens: self.write('(') self.write_newline() with self.add_indentation(): num_nodes = len(nodes) for i, node in enumerate(nodes): self.write_indentation() self.visit(node) if final_separator_if_multiline or i < num_nodes - 1: self.write(separator) self.write_newline() self.write_indentation() if need_parens: self.write(')') def write_suite(self, nodes): with self.add_indentation(): for line in nodes: self.visit(line) @contextmanager def add_indentation(self): self.current_indentation += self.indentation try: yield finally: self.current_indentation -= self.indentation @contextmanager def parenthesize_if(self, condition): if condition: self.write('(') yield self.write(')') else: yield def generic_visit(self, node): raise NotImplementedError('missing visit method for %r' % node) def visit_Module(self, node): for line in node.body: self.visit(line) visit_Interactive = visit_Module def visit_Expression(self, node): self.visit(node.body) # Multi-line statements def visit_FunctionDef(self, node): self.write_function_def(node) def visit_AsyncFunctionDef(self, node): self.write_function_def(node, is_async=True) def write_function_def(self, node, is_async=False): self.write_newline() for decorator in node.decorator_list: self.write_indentation() self.write('@') self.visit(decorator) self.write_newline() self.write_indentation() if is_async: self.write('async ') self.write('def %s(' % node.name) self.visit(node.args) self.write(')') if getattr(node, 'returns', None): self.write(' -> ') self.visit(node.returns) self.write(':') self.write_newline() self.write_suite(node.body) def visit_ClassDef(self, node): self.write_newline() self.write_newline() for decorator in node.decorator_list: self.write_indentation() self.write('@') self.visit(decorator) self.write_newline() self.write_indentation() self.write('class %s(' % node.name) exprs = node.bases + getattr(node, 'keywords', []) self.write_expression_list(exprs, need_parens=False) self.write('):') self.write_newline() self.write_suite(node.body) def visit_For(self, node): self.write_for(node) def visit_AsyncFor(self, node): self.write_for(node, is_async=True) def write_for(self, node, is_async=False): self.write_indentation() if is_async: self.write('async ') self.write('for ') self.visit(node.target) self.write(' in ') self.visit(node.iter) self.write(':') self.write_newline() self.write_suite(node.body) self.write_else(node.orelse) def visit_While(self, node): self.write_indentation() self.write('while ') self.visit(node.test) self.write(':') self.write_newline() self.write_suite(node.body) self.write_else(node.orelse) def visit_If(self, node): self.write_indentation() self.write('if ') self.visit(node.test) self.write(':') self.write_newline() self.write_suite(node.body) while node.orelse and len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If): node = node.orelse[0] self.write_indentation() self.write('elif ') self.visit(node.test) self.write(':') self.write_newline() self.write_suite(node.body) self.write_else(node.orelse) def write_else(self, orelse): if orelse: self.write_indentation() self.write('else:') self.write_newline() self.write_suite(orelse) def visit_With(self, node): if hasattr(node, 'items'): self.write_py3_with(node) return self.write_indentation() self.write('with ') nodes = [node] body = node.body is_first = True while len(body) == 1 and isinstance(body[0], ast.With): nodes.append(body[0]) body = body[0].body for context_node in nodes: if is_first: is_first = False else: self.write(', ') self.visit(context_node.context_expr) if context_node.optional_vars: self.write(' as ') self.visit(context_node.optional_vars) self.write(':') self.write_newline() self.write_suite(body) def visit_AsyncWith(self, node): self.write_py3_with(node, is_async=True) def write_py3_with(self, node, is_async=False): self.write_indentation() if is_async: self.write('async ') self.write('with ') self.write_expression_list(node.items, allow_newlines=False) self.write(':') self.write_newline() self.write_suite(node.body) def visit_withitem(self, node): self.visit(node.context_expr) if node.optional_vars: self.write(' as ') self.visit(node.optional_vars) def visit_Try(self, node): # py3 only self.visit_TryExcept(node) if node.finalbody: self.write_finalbody(node.finalbody) def visit_TryExcept(self, node): self.write_indentation() self.write('try:') self.write_newline() self.write_suite(node.body) for handler in node.handlers: self.visit(handler) self.write_else(node.orelse) def visit_TryFinally(self, node): if len(node.body) == 1 and isinstance(node.body[0], ast.TryExcept): self.visit(node.body[0]) else: self.write_indentation() self.write('try:') self.write_newline() self.write_suite(node.body) self.write_finalbody(node.finalbody) def write_finalbody(self, body): self.write_indentation() self.write('finally:') self.write_newline() self.write_suite(body) # One-line statements def visit_Return(self, node): self.write_indentation() self.write('return') if node.value: self.write(' ') self.visit(node.value) self.write_newline() def visit_Delete(self, node): self.write_indentation() self.write('del ') self.write_expression_list(node.targets, allow_newlines=False) self.write_newline() def visit_Assign(self, node): self.write_indentation() self.write_expression_list(node.targets, separator=' = ', allow_newlines=False) self.write(' = ') self.visit(node.value) self.write_newline() def visit_AugAssign(self, node): self.write_indentation() self.visit(node.target) self.write(' ') self.visit(node.op) self.write('= ') self.visit(node.value) self.write_newline() def visit_AnnAssign(self, node): self.write_indentation() if not node.simple: self.write('(') self.visit(node.target) if not node.simple: self.write(')') self.write(': ') self.visit(node.annotation) if node.value is not None: self.write(' = ') self.visit(node.value) self.write_newline() def visit_Print(self, node): self.write_indentation() self.write('print') if node.dest: self.write(' >>') self.visit(node.dest) if node.values: self.write(',') if node.values: self.write(' ') self.write_expression_list(node.values, allow_newlines=False) if not node.nl: self.write(',') self.write_newline() def visit_Raise(self, node): self.write_indentation() self.write('raise') if hasattr(node, 'exc'): # py3 if node.exc is not None: self.write(' ') self.visit(node.exc) if node.cause is not None: self.write(' from ') self.visit(node.cause) else: expressions = [child for child in (node.type, node.inst, node.tback) if child] if expressions: self.write(' ') self.write_expression_list(expressions, allow_newlines=False) self.write_newline() def visit_Assert(self, node): self.write_indentation() self.write('assert ') self.visit(node.test) if node.msg: self.write(', ') self.visit(node.msg) self.write_newline() def visit_Import(self, node): self.write_indentation() self.write('import ') self.write_expression_list(node.names, allow_newlines=False) self.write_newline() def visit_ImportFrom(self, node): if ( node.module == '__future__' and any(alias.name == 'unicode_literals' for alias in node.names) ): self.has_unicode_literals = True self.write_indentation() self.write('from %s' % ('.' * (node.level or 0))) if node.module: self.write(node.module) self.write(' import ') self.write_expression_list(node.names) self.write_newline() def visit_Exec(self, node): self.write_indentation() self.write('exec ') self.visit(node.body) if node.globals: self.write(' in ') self.visit(node.globals) if node.locals: self.write(', ') self.visit(node.locals) self.write_newline() def visit_Global(self, node): self.write_indentation() self.write('global %s' % ', '.join(node.names)) self.write_newline() def visit_Nonlocal(self, node): self.write_indentation() self.write('nonlocal %s' % ', '.join(node.names)) self.write_newline() def visit_Expr(self, node): self.write_indentation() self.visit(node.value) self.write_newline() def visit_Pass(self, node): self.write_indentation() self.write('pass') self.write_newline() def visit_Break(self, node): self.write_indentation() self.write('break') self.write_newline() def visit_Continue(self, node): self.write_indentation() self.write('continue') self.write_newline() # Expressions def visit_BoolOp(self, node): my_prec = self.precedence_of_node(node) parent_prec = self.precedence_of_node(self.get_parent_node()) with self.parenthesize_if(my_prec <= parent_prec): op = 'and' if isinstance(node.op, ast.And) else 'or' self.write_expression_list( node.values, separator=' %s ' % op, final_separator_if_multiline=False, ) def visit_BinOp(self, node): parent_node = self.get_parent_node() my_prec = self.precedence_of_node(node) parent_prec = self.precedence_of_node(parent_node) if my_prec < parent_prec: should_parenthesize = True elif my_prec == parent_prec: if isinstance(node.op, ast.Pow): should_parenthesize = node == parent_node.left else: should_parenthesize = node == parent_node.right else: should_parenthesize = False with self.parenthesize_if(should_parenthesize): self.visit(node.left) self.write(' ') self.visit(node.op) self.write(' ') self.visit(node.right) def visit_UnaryOp(self, node): my_prec = self.precedence_of_node(node) parent_prec = self.precedence_of_node(self.get_parent_node()) with self.parenthesize_if(my_prec < parent_prec): self.visit(node.op) self.visit(node.operand) def visit_Lambda(self, node): should_parenthesize = isinstance( self.get_parent_node(), (ast.BinOp, ast.UnaryOp, ast.Compare, ast.IfExp, ast.Attribute, ast.Subscript, ast.Call, ast.BoolOp) ) with self.parenthesize_if(should_parenthesize): self.write('lambda') if node.args.args or node.args.vararg or node.args.kwarg: self.write(' ') self.visit(node.args) self.write(': ') self.visit(node.body) def visit_IfExp(self, node): parent_node = self.get_parent_node() if isinstance(parent_node, (ast.BinOp, ast.UnaryOp, ast.Compare, ast.Attribute, ast.Subscript, ast.Call, ast.BoolOp, ast.comprehension)): should_parenthesize = True elif isinstance(parent_node, ast.IfExp) and \ (node is parent_node.test or node is parent_node.body): should_parenthesize = True else: should_parenthesize = False with self.parenthesize_if(should_parenthesize): self.visit(node.body) self.write(' if ') self.visit(node.test) self.write(' else ') self.visit(node.orelse) def visit_Dict(self, node): self.write('{') items = [KeyValuePair(key, value) for key, value in zip(node.keys, node.values)] self.write_expression_list(items, need_parens=False) self.write('}') def visit_KeyValuePair(self, node): self.visit(node.key) self.write(': ') self.visit(node.value) def visit_Set(self, node): self.write('{') self.write_expression_list(node.elts, need_parens=False) self.write('}') def visit_ListComp(self, node): self.visit_comp(node, '[', ']') def visit_SetComp(self, node): self.visit_comp(node, '{', '}') def visit_DictComp(self, node): self.write('{') elts = [KeyValuePair(node.key, node.value)] + node.generators self.write_expression_list(elts, separator=' ', need_parens=False) self.write('}') def visit_GeneratorExp(self, node): self.visit_comp(node, '(', ')') def visit_comp(self, node, start, end): self.write(start) self.write_expression_list([node.elt] + node.generators, separator=' ', need_parens=False) self.write(end) def visit_Await(self, node): with self.parenthesize_if( not isinstance(self.get_parent_node(), (ast.Expr, ast.Assign, ast.AugAssign))): self.write('await ') self.visit(node.value) def visit_Yield(self, node): with self.parenthesize_if( not isinstance(self.get_parent_node(), (ast.Expr, ast.Assign, ast.AugAssign))): self.write('yield') if node.value: self.write(' ') self.visit(node.value) def visit_YieldFrom(self, node): with self.parenthesize_if( not isinstance(self.get_parent_node(), (ast.Expr, ast.Assign, ast.AugAssign))): self.write('yield from ') self.visit(node.value) def visit_Compare(self, node): my_prec = self.precedence_of_node(node) parent_prec = self.precedence_of_node(self.get_parent_node()) with self.parenthesize_if(my_prec <= parent_prec): self.visit(node.left) for op, expr in zip(node.ops, node.comparators): self.write(' ') self.visit(op) self.write(' ') self.visit(expr) def visit_Call(self, node): self.visit(node.func) self.write('(') self.node_stack.append(_CallArgs()) try: args = node.args + node.keywords if hasattr(node, 'starargs') and node.starargs: args.append(StarArg(node.starargs)) if hasattr(node, 'kwargs') and node.kwargs: args.append(DoubleStarArg(node.kwargs)) if args: self.write_expression_list( args, need_parens=False, final_separator_if_multiline=False # it's illegal after *args and **kwargs ) self.write(')') finally: self.node_stack.pop() def visit_StarArg(self, node): self.write('*') self.visit(node.arg) def visit_DoubleStarArg(self, node): self.write('**') self.visit(node.arg) def visit_KeywordArg(self, node): self.visit(node.arg) self.write('=') self.visit(node.value) def visit_Repr(self, node): self.write('`') self.visit(node.value) self.write('`') def visit_Num(self, node): should_parenthesize = isinstance(node.n, int) and node.n >= 0 and \ isinstance(self.get_parent_node(), ast.Attribute) should_parenthesize = should_parenthesize or (isinstance(node.n, complex) and node.n.real == 0.0 and (node.n.imag < 0 or node.n.imag == -0.0)) if not should_parenthesize: parent_node = self.get_parent_node() should_parenthesize = isinstance(parent_node, ast.UnaryOp) and \ isinstance(parent_node.op, ast.USub) and \ hasattr(parent_node, 'lineno') with self.parenthesize_if(should_parenthesize): if isinstance(node.n, float) and abs(node.n) > sys.float_info.max: # otherwise we write inf, which won't be parsed back right # I don't know of any way to write nan with a literal self.write('1e1000' if node.n > 0 else '-1e1000') elif isinstance(node.n, (int, _long, float)) and node.n < 0: # needed for precedence to work correctly me = self.node_stack.pop() if isinstance(node.n, int): val = str(-node.n) else: val = repr(type(node.n)(-node.n)) # - of long may be int self.visit(ast.UnaryOp(op=ast.USub(), operand=ast.Name(id=val))) self.node_stack.append(me) else: self.write(repr(node.n)) def visit_Str(self, node): if self.has_unicode_literals and isinstance(node.s, str): self.write('b') self.write(repr(node.s)) def visit_FormattedValue(self, node): has_parent = isinstance(self.get_parent_node(), ast.JoinedStr) if not has_parent: self.write('f"') self.write('{') self.visit(node.value) if node.conversion != -1: self.write('!%s' % chr(node.conversion)) if node.format_spec is not None: self.write(':') if not isinstance(node.format_spec, ast.Str): raise TypeError('format spec must be a string') self.write(node.format_spec.s) self.write('}') if not has_parent: self.write('"') def visit_JoinedStr(self, node): self.write("f'") for value in node.values: if isinstance(value, ast.Str): self.write(value.s) else: self.visit(value) self.write("'") def visit_Bytes(self, node): self.write(repr(node.s)) def visit_NameConstant(self, node): self.write(repr(node.value)) def visit_Constant(self, node): # TODO what is this raise NotImplementedError(ast.dump(node)) def visit_Attribute(self, node): self.visit(node.value) self.write('.%s' % node.attr) def visit_Subscript(self, node): self.visit(node.value) self.write('[') self.visit(node.slice) self.write(']') def visit_Starred(self, node): # TODO precedence self.write('*') self.visit(node.value) def visit_Name(self, node): if isinstance(node.id, _basestring): self.write(node.id) else: self.visit(node.id) def visit_List(self, node): self.write('[') self.write_expression_list(node.elts, need_parens=False) self.write(']') def visit_Tuple(self, node): if not node.elts: self.write('()') else: should_parenthesize = not isinstance( self.get_parent_node(), (ast.Expr, ast.Assign, ast.AugAssign, ast.Return, ast.Yield) ) with self.parenthesize_if(should_parenthesize): if len(node.elts) == 1: self.visit(node.elts[0]) self.write(',') else: self.write_expression_list(node.elts, need_parens=not should_parenthesize) # slice def visit_Ellipsis(self, node): if PY3: self.write('...') elif isinstance(self.get_parent_node(), (ast.Subscript, ast.ExtSlice)): # self[...] gets parsed into Ellipsis without an intervening Index node self.write('...') else: self.write('Ellipsis') def visit_Slice(self, node): if node.lower: self.visit(node.lower) self.write(':') if node.upper: self.visit(node.upper) if node.step: self.write(':') self.visit(node.step) def visit_ExtSlice(self, node): if len(node.dims) == 1: self.visit(node.dims[0]) self.write(',') else: self.write_expression_list(node.dims, need_parens=False) def visit_Index(self, node): self.visit(node.value) # operators for op, string in _OP_TO_STR.items(): exec('def visit_%s(self, node): self.write(%r)' % (op.__name__, string)) # Other types visit_Load = visit_Store = visit_Del = visit_AugLoad = visit_AugStore = visit_Param = \ lambda self, node: None def visit_comprehension(self, node): self.write('for ') self.visit(node.target) self.write(' in ') self.visit(node.iter) for expr in node.ifs: self.write(' if ') self.visit(expr) def visit_ExceptHandler(self, node): self.write_indentation() self.write('except') if node.type: self.write(' ') self.visit(node.type) if node.name: self.write(' as ') # node.name is a string in py3 but an expr in py2 if isinstance(node.name, _basestring): self.write(node.name) else: self.visit(node.name) self.write(':') self.write_newline() self.write_suite(node.body) def visit_arguments(self, node): num_defaults = len(node.defaults) if num_defaults: args = node.args[:-num_defaults] default_args = zip(node.args[-num_defaults:], node.defaults) else: args = list(node.args) default_args = [] for name, value in default_args: args.append(KeywordArg(name, value)) if node.vararg: args.append(StarArg(ast.Name(id=node.vararg))) # TODO write a * if there are kwonly args but no vararg if hasattr(node, 'kw_defaults'): if node.kwonlyargs and not node.vararg: args.append(StarArg(ast.Name(id=''))) num_kwarg_defaults = len(node.kw_defaults) if num_kwarg_defaults: args += node.kwonlyargs[:-num_kwarg_defaults] default_kwargs = zip(node.kwonlyargs[-num_kwarg_defaults:], node.kw_defaults) else: args += node.kwonlyargs default_kwargs = [] for name, value in default_kwargs: args.append(KeywordArg(name, value)) if node.kwarg: args.append(DoubleStarArg(ast.Name(id=node.kwarg))) if args: # lambdas can't have a multiline arglist allow_newlines = not isinstance(self.get_parent_node(), ast.Lambda) self.write_expression_list( args, allow_newlines=allow_newlines, need_parens=False, final_separator_if_multiline=False # illegal after **kwargs ) def visit_arg(self, node): self.write(node.arg) if node.annotation: self.write(': ') # TODO precedence self.visit(node.annotation) def visit_keyword(self, node): if node.arg is None: # in py3, **kwargs is a keyword whose arg is None self.write('**') else: self.write(node.arg + '=') self.visit(node.value) def visit_alias(self, node): self.write(node.name) if node.asname is not None: self.write(' as %s' % node.asname) # helper ast nodes to make decompilation easier class KeyValuePair(object): """A key-value pair as used in a dictionary display.""" _fields = ['key', 'value'] def __init__(self, key, value): self.key = key self.value = value class StarArg(object): """A * argument.""" _fields = ['arg'] def __init__(self, arg): self.arg = arg class DoubleStarArg(object): """A ** argument.""" _fields = ['arg'] def __init__(self, arg): self.arg = arg class KeywordArg(object): """A x=3 keyword argument in a function definition.""" _fields = ['arg', 'value'] def __init__(self, arg, value): self.arg = arg self.value = value
jmvrbanac/Specter
specter/vendor/ast_decompiler.py
Decompiler.write_expression_list
python
def write_expression_list(self, nodes, separator=', ', allow_newlines=True, need_parens=True, final_separator_if_multiline=True): first = True last_line = len(self.lines) current_line = list(self.current_line) for node in nodes: if first: first = False else: self.write(separator) self.visit(node) if allow_newlines and (self.current_line_length() > self.max_line_length or last_line != len(self.lines)): break else: return # stayed within the limit # reset state del self.lines[last_line:] self.current_line = current_line separator = separator.rstrip() if need_parens: self.write('(') self.write_newline() with self.add_indentation(): num_nodes = len(nodes) for i, node in enumerate(nodes): self.write_indentation() self.visit(node) if final_separator_if_multiline or i < num_nodes - 1: self.write(separator) self.write_newline() self.write_indentation() if need_parens: self.write(')')
Writes a list of nodes, separated by separator. If allow_newlines, will write the expression over multiple lines if necessary to say within max_line_length. If need_parens, will surround the expression with parentheses in this case. If final_separator_if_multiline, will write a separator at the end of the list if it is divided over multiple lines.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/vendor/ast_decompiler.py#L164-L208
[ "def visit(self, node):\n self.node_stack.append(node)\n try:\n return super(Decompiler, self).visit(node)\n finally:\n if self.node_stack:\n self.node_stack.pop()\n", "def write(self, code):\n assert isinstance(code, _basestring), 'invalid code %r' % code\n self.current_line.append(code)\n", "def write_indentation(self):\n self.write(' ' * self.current_indentation)\n", "def write_newline(self):\n line = ''.join(self.current_line) + '\\n'\n self.lines.append(line)\n self.current_line = []\n", "def current_line_length(self):\n return sum(map(len, self.current_line))\n" ]
class Decompiler(ast.NodeVisitor): def __init__(self, indentation, line_length, starting_indentation): self.lines = [] self.current_line = [] self.current_indentation = starting_indentation self.node_stack = [] self.indentation = indentation self.max_line_length = line_length self.has_unicode_literals = False def run(self, ast): self.visit(ast) if self.current_line: self.lines.append(''.join(self.current_line)) self.current_line = [] return ''.join(self.lines) def visit(self, node): self.node_stack.append(node) try: return super(Decompiler, self).visit(node) finally: if self.node_stack: self.node_stack.pop() def precedence_of_node(self, node): if isinstance(node, (ast.BinOp, ast.UnaryOp, ast.BoolOp)): return _PRECEDENCE[type(node.op)] return _PRECEDENCE.get(type(node), -1) def get_parent_node(self): try: return self.node_stack[-2] except IndexError: return None def write(self, code): assert isinstance(code, _basestring), 'invalid code %r' % code self.current_line.append(code) def write_indentation(self): self.write(' ' * self.current_indentation) def write_newline(self): line = ''.join(self.current_line) + '\n' self.lines.append(line) self.current_line = [] def current_line_length(self): return sum(map(len, self.current_line)) def write_suite(self, nodes): with self.add_indentation(): for line in nodes: self.visit(line) @contextmanager def add_indentation(self): self.current_indentation += self.indentation try: yield finally: self.current_indentation -= self.indentation @contextmanager def parenthesize_if(self, condition): if condition: self.write('(') yield self.write(')') else: yield def generic_visit(self, node): raise NotImplementedError('missing visit method for %r' % node) def visit_Module(self, node): for line in node.body: self.visit(line) visit_Interactive = visit_Module def visit_Expression(self, node): self.visit(node.body) # Multi-line statements def visit_FunctionDef(self, node): self.write_function_def(node) def visit_AsyncFunctionDef(self, node): self.write_function_def(node, is_async=True) def write_function_def(self, node, is_async=False): self.write_newline() for decorator in node.decorator_list: self.write_indentation() self.write('@') self.visit(decorator) self.write_newline() self.write_indentation() if is_async: self.write('async ') self.write('def %s(' % node.name) self.visit(node.args) self.write(')') if getattr(node, 'returns', None): self.write(' -> ') self.visit(node.returns) self.write(':') self.write_newline() self.write_suite(node.body) def visit_ClassDef(self, node): self.write_newline() self.write_newline() for decorator in node.decorator_list: self.write_indentation() self.write('@') self.visit(decorator) self.write_newline() self.write_indentation() self.write('class %s(' % node.name) exprs = node.bases + getattr(node, 'keywords', []) self.write_expression_list(exprs, need_parens=False) self.write('):') self.write_newline() self.write_suite(node.body) def visit_For(self, node): self.write_for(node) def visit_AsyncFor(self, node): self.write_for(node, is_async=True) def write_for(self, node, is_async=False): self.write_indentation() if is_async: self.write('async ') self.write('for ') self.visit(node.target) self.write(' in ') self.visit(node.iter) self.write(':') self.write_newline() self.write_suite(node.body) self.write_else(node.orelse) def visit_While(self, node): self.write_indentation() self.write('while ') self.visit(node.test) self.write(':') self.write_newline() self.write_suite(node.body) self.write_else(node.orelse) def visit_If(self, node): self.write_indentation() self.write('if ') self.visit(node.test) self.write(':') self.write_newline() self.write_suite(node.body) while node.orelse and len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If): node = node.orelse[0] self.write_indentation() self.write('elif ') self.visit(node.test) self.write(':') self.write_newline() self.write_suite(node.body) self.write_else(node.orelse) def write_else(self, orelse): if orelse: self.write_indentation() self.write('else:') self.write_newline() self.write_suite(orelse) def visit_With(self, node): if hasattr(node, 'items'): self.write_py3_with(node) return self.write_indentation() self.write('with ') nodes = [node] body = node.body is_first = True while len(body) == 1 and isinstance(body[0], ast.With): nodes.append(body[0]) body = body[0].body for context_node in nodes: if is_first: is_first = False else: self.write(', ') self.visit(context_node.context_expr) if context_node.optional_vars: self.write(' as ') self.visit(context_node.optional_vars) self.write(':') self.write_newline() self.write_suite(body) def visit_AsyncWith(self, node): self.write_py3_with(node, is_async=True) def write_py3_with(self, node, is_async=False): self.write_indentation() if is_async: self.write('async ') self.write('with ') self.write_expression_list(node.items, allow_newlines=False) self.write(':') self.write_newline() self.write_suite(node.body) def visit_withitem(self, node): self.visit(node.context_expr) if node.optional_vars: self.write(' as ') self.visit(node.optional_vars) def visit_Try(self, node): # py3 only self.visit_TryExcept(node) if node.finalbody: self.write_finalbody(node.finalbody) def visit_TryExcept(self, node): self.write_indentation() self.write('try:') self.write_newline() self.write_suite(node.body) for handler in node.handlers: self.visit(handler) self.write_else(node.orelse) def visit_TryFinally(self, node): if len(node.body) == 1 and isinstance(node.body[0], ast.TryExcept): self.visit(node.body[0]) else: self.write_indentation() self.write('try:') self.write_newline() self.write_suite(node.body) self.write_finalbody(node.finalbody) def write_finalbody(self, body): self.write_indentation() self.write('finally:') self.write_newline() self.write_suite(body) # One-line statements def visit_Return(self, node): self.write_indentation() self.write('return') if node.value: self.write(' ') self.visit(node.value) self.write_newline() def visit_Delete(self, node): self.write_indentation() self.write('del ') self.write_expression_list(node.targets, allow_newlines=False) self.write_newline() def visit_Assign(self, node): self.write_indentation() self.write_expression_list(node.targets, separator=' = ', allow_newlines=False) self.write(' = ') self.visit(node.value) self.write_newline() def visit_AugAssign(self, node): self.write_indentation() self.visit(node.target) self.write(' ') self.visit(node.op) self.write('= ') self.visit(node.value) self.write_newline() def visit_AnnAssign(self, node): self.write_indentation() if not node.simple: self.write('(') self.visit(node.target) if not node.simple: self.write(')') self.write(': ') self.visit(node.annotation) if node.value is not None: self.write(' = ') self.visit(node.value) self.write_newline() def visit_Print(self, node): self.write_indentation() self.write('print') if node.dest: self.write(' >>') self.visit(node.dest) if node.values: self.write(',') if node.values: self.write(' ') self.write_expression_list(node.values, allow_newlines=False) if not node.nl: self.write(',') self.write_newline() def visit_Raise(self, node): self.write_indentation() self.write('raise') if hasattr(node, 'exc'): # py3 if node.exc is not None: self.write(' ') self.visit(node.exc) if node.cause is not None: self.write(' from ') self.visit(node.cause) else: expressions = [child for child in (node.type, node.inst, node.tback) if child] if expressions: self.write(' ') self.write_expression_list(expressions, allow_newlines=False) self.write_newline() def visit_Assert(self, node): self.write_indentation() self.write('assert ') self.visit(node.test) if node.msg: self.write(', ') self.visit(node.msg) self.write_newline() def visit_Import(self, node): self.write_indentation() self.write('import ') self.write_expression_list(node.names, allow_newlines=False) self.write_newline() def visit_ImportFrom(self, node): if ( node.module == '__future__' and any(alias.name == 'unicode_literals' for alias in node.names) ): self.has_unicode_literals = True self.write_indentation() self.write('from %s' % ('.' * (node.level or 0))) if node.module: self.write(node.module) self.write(' import ') self.write_expression_list(node.names) self.write_newline() def visit_Exec(self, node): self.write_indentation() self.write('exec ') self.visit(node.body) if node.globals: self.write(' in ') self.visit(node.globals) if node.locals: self.write(', ') self.visit(node.locals) self.write_newline() def visit_Global(self, node): self.write_indentation() self.write('global %s' % ', '.join(node.names)) self.write_newline() def visit_Nonlocal(self, node): self.write_indentation() self.write('nonlocal %s' % ', '.join(node.names)) self.write_newline() def visit_Expr(self, node): self.write_indentation() self.visit(node.value) self.write_newline() def visit_Pass(self, node): self.write_indentation() self.write('pass') self.write_newline() def visit_Break(self, node): self.write_indentation() self.write('break') self.write_newline() def visit_Continue(self, node): self.write_indentation() self.write('continue') self.write_newline() # Expressions def visit_BoolOp(self, node): my_prec = self.precedence_of_node(node) parent_prec = self.precedence_of_node(self.get_parent_node()) with self.parenthesize_if(my_prec <= parent_prec): op = 'and' if isinstance(node.op, ast.And) else 'or' self.write_expression_list( node.values, separator=' %s ' % op, final_separator_if_multiline=False, ) def visit_BinOp(self, node): parent_node = self.get_parent_node() my_prec = self.precedence_of_node(node) parent_prec = self.precedence_of_node(parent_node) if my_prec < parent_prec: should_parenthesize = True elif my_prec == parent_prec: if isinstance(node.op, ast.Pow): should_parenthesize = node == parent_node.left else: should_parenthesize = node == parent_node.right else: should_parenthesize = False with self.parenthesize_if(should_parenthesize): self.visit(node.left) self.write(' ') self.visit(node.op) self.write(' ') self.visit(node.right) def visit_UnaryOp(self, node): my_prec = self.precedence_of_node(node) parent_prec = self.precedence_of_node(self.get_parent_node()) with self.parenthesize_if(my_prec < parent_prec): self.visit(node.op) self.visit(node.operand) def visit_Lambda(self, node): should_parenthesize = isinstance( self.get_parent_node(), (ast.BinOp, ast.UnaryOp, ast.Compare, ast.IfExp, ast.Attribute, ast.Subscript, ast.Call, ast.BoolOp) ) with self.parenthesize_if(should_parenthesize): self.write('lambda') if node.args.args or node.args.vararg or node.args.kwarg: self.write(' ') self.visit(node.args) self.write(': ') self.visit(node.body) def visit_IfExp(self, node): parent_node = self.get_parent_node() if isinstance(parent_node, (ast.BinOp, ast.UnaryOp, ast.Compare, ast.Attribute, ast.Subscript, ast.Call, ast.BoolOp, ast.comprehension)): should_parenthesize = True elif isinstance(parent_node, ast.IfExp) and \ (node is parent_node.test or node is parent_node.body): should_parenthesize = True else: should_parenthesize = False with self.parenthesize_if(should_parenthesize): self.visit(node.body) self.write(' if ') self.visit(node.test) self.write(' else ') self.visit(node.orelse) def visit_Dict(self, node): self.write('{') items = [KeyValuePair(key, value) for key, value in zip(node.keys, node.values)] self.write_expression_list(items, need_parens=False) self.write('}') def visit_KeyValuePair(self, node): self.visit(node.key) self.write(': ') self.visit(node.value) def visit_Set(self, node): self.write('{') self.write_expression_list(node.elts, need_parens=False) self.write('}') def visit_ListComp(self, node): self.visit_comp(node, '[', ']') def visit_SetComp(self, node): self.visit_comp(node, '{', '}') def visit_DictComp(self, node): self.write('{') elts = [KeyValuePair(node.key, node.value)] + node.generators self.write_expression_list(elts, separator=' ', need_parens=False) self.write('}') def visit_GeneratorExp(self, node): self.visit_comp(node, '(', ')') def visit_comp(self, node, start, end): self.write(start) self.write_expression_list([node.elt] + node.generators, separator=' ', need_parens=False) self.write(end) def visit_Await(self, node): with self.parenthesize_if( not isinstance(self.get_parent_node(), (ast.Expr, ast.Assign, ast.AugAssign))): self.write('await ') self.visit(node.value) def visit_Yield(self, node): with self.parenthesize_if( not isinstance(self.get_parent_node(), (ast.Expr, ast.Assign, ast.AugAssign))): self.write('yield') if node.value: self.write(' ') self.visit(node.value) def visit_YieldFrom(self, node): with self.parenthesize_if( not isinstance(self.get_parent_node(), (ast.Expr, ast.Assign, ast.AugAssign))): self.write('yield from ') self.visit(node.value) def visit_Compare(self, node): my_prec = self.precedence_of_node(node) parent_prec = self.precedence_of_node(self.get_parent_node()) with self.parenthesize_if(my_prec <= parent_prec): self.visit(node.left) for op, expr in zip(node.ops, node.comparators): self.write(' ') self.visit(op) self.write(' ') self.visit(expr) def visit_Call(self, node): self.visit(node.func) self.write('(') self.node_stack.append(_CallArgs()) try: args = node.args + node.keywords if hasattr(node, 'starargs') and node.starargs: args.append(StarArg(node.starargs)) if hasattr(node, 'kwargs') and node.kwargs: args.append(DoubleStarArg(node.kwargs)) if args: self.write_expression_list( args, need_parens=False, final_separator_if_multiline=False # it's illegal after *args and **kwargs ) self.write(')') finally: self.node_stack.pop() def visit_StarArg(self, node): self.write('*') self.visit(node.arg) def visit_DoubleStarArg(self, node): self.write('**') self.visit(node.arg) def visit_KeywordArg(self, node): self.visit(node.arg) self.write('=') self.visit(node.value) def visit_Repr(self, node): self.write('`') self.visit(node.value) self.write('`') def visit_Num(self, node): should_parenthesize = isinstance(node.n, int) and node.n >= 0 and \ isinstance(self.get_parent_node(), ast.Attribute) should_parenthesize = should_parenthesize or (isinstance(node.n, complex) and node.n.real == 0.0 and (node.n.imag < 0 or node.n.imag == -0.0)) if not should_parenthesize: parent_node = self.get_parent_node() should_parenthesize = isinstance(parent_node, ast.UnaryOp) and \ isinstance(parent_node.op, ast.USub) and \ hasattr(parent_node, 'lineno') with self.parenthesize_if(should_parenthesize): if isinstance(node.n, float) and abs(node.n) > sys.float_info.max: # otherwise we write inf, which won't be parsed back right # I don't know of any way to write nan with a literal self.write('1e1000' if node.n > 0 else '-1e1000') elif isinstance(node.n, (int, _long, float)) and node.n < 0: # needed for precedence to work correctly me = self.node_stack.pop() if isinstance(node.n, int): val = str(-node.n) else: val = repr(type(node.n)(-node.n)) # - of long may be int self.visit(ast.UnaryOp(op=ast.USub(), operand=ast.Name(id=val))) self.node_stack.append(me) else: self.write(repr(node.n)) def visit_Str(self, node): if self.has_unicode_literals and isinstance(node.s, str): self.write('b') self.write(repr(node.s)) def visit_FormattedValue(self, node): has_parent = isinstance(self.get_parent_node(), ast.JoinedStr) if not has_parent: self.write('f"') self.write('{') self.visit(node.value) if node.conversion != -1: self.write('!%s' % chr(node.conversion)) if node.format_spec is not None: self.write(':') if not isinstance(node.format_spec, ast.Str): raise TypeError('format spec must be a string') self.write(node.format_spec.s) self.write('}') if not has_parent: self.write('"') def visit_JoinedStr(self, node): self.write("f'") for value in node.values: if isinstance(value, ast.Str): self.write(value.s) else: self.visit(value) self.write("'") def visit_Bytes(self, node): self.write(repr(node.s)) def visit_NameConstant(self, node): self.write(repr(node.value)) def visit_Constant(self, node): # TODO what is this raise NotImplementedError(ast.dump(node)) def visit_Attribute(self, node): self.visit(node.value) self.write('.%s' % node.attr) def visit_Subscript(self, node): self.visit(node.value) self.write('[') self.visit(node.slice) self.write(']') def visit_Starred(self, node): # TODO precedence self.write('*') self.visit(node.value) def visit_Name(self, node): if isinstance(node.id, _basestring): self.write(node.id) else: self.visit(node.id) def visit_List(self, node): self.write('[') self.write_expression_list(node.elts, need_parens=False) self.write(']') def visit_Tuple(self, node): if not node.elts: self.write('()') else: should_parenthesize = not isinstance( self.get_parent_node(), (ast.Expr, ast.Assign, ast.AugAssign, ast.Return, ast.Yield) ) with self.parenthesize_if(should_parenthesize): if len(node.elts) == 1: self.visit(node.elts[0]) self.write(',') else: self.write_expression_list(node.elts, need_parens=not should_parenthesize) # slice def visit_Ellipsis(self, node): if PY3: self.write('...') elif isinstance(self.get_parent_node(), (ast.Subscript, ast.ExtSlice)): # self[...] gets parsed into Ellipsis without an intervening Index node self.write('...') else: self.write('Ellipsis') def visit_Slice(self, node): if node.lower: self.visit(node.lower) self.write(':') if node.upper: self.visit(node.upper) if node.step: self.write(':') self.visit(node.step) def visit_ExtSlice(self, node): if len(node.dims) == 1: self.visit(node.dims[0]) self.write(',') else: self.write_expression_list(node.dims, need_parens=False) def visit_Index(self, node): self.visit(node.value) # operators for op, string in _OP_TO_STR.items(): exec('def visit_%s(self, node): self.write(%r)' % (op.__name__, string)) # Other types visit_Load = visit_Store = visit_Del = visit_AugLoad = visit_AugStore = visit_Param = \ lambda self, node: None def visit_comprehension(self, node): self.write('for ') self.visit(node.target) self.write(' in ') self.visit(node.iter) for expr in node.ifs: self.write(' if ') self.visit(expr) def visit_ExceptHandler(self, node): self.write_indentation() self.write('except') if node.type: self.write(' ') self.visit(node.type) if node.name: self.write(' as ') # node.name is a string in py3 but an expr in py2 if isinstance(node.name, _basestring): self.write(node.name) else: self.visit(node.name) self.write(':') self.write_newline() self.write_suite(node.body) def visit_arguments(self, node): num_defaults = len(node.defaults) if num_defaults: args = node.args[:-num_defaults] default_args = zip(node.args[-num_defaults:], node.defaults) else: args = list(node.args) default_args = [] for name, value in default_args: args.append(KeywordArg(name, value)) if node.vararg: args.append(StarArg(ast.Name(id=node.vararg))) # TODO write a * if there are kwonly args but no vararg if hasattr(node, 'kw_defaults'): if node.kwonlyargs and not node.vararg: args.append(StarArg(ast.Name(id=''))) num_kwarg_defaults = len(node.kw_defaults) if num_kwarg_defaults: args += node.kwonlyargs[:-num_kwarg_defaults] default_kwargs = zip(node.kwonlyargs[-num_kwarg_defaults:], node.kw_defaults) else: args += node.kwonlyargs default_kwargs = [] for name, value in default_kwargs: args.append(KeywordArg(name, value)) if node.kwarg: args.append(DoubleStarArg(ast.Name(id=node.kwarg))) if args: # lambdas can't have a multiline arglist allow_newlines = not isinstance(self.get_parent_node(), ast.Lambda) self.write_expression_list( args, allow_newlines=allow_newlines, need_parens=False, final_separator_if_multiline=False # illegal after **kwargs ) def visit_arg(self, node): self.write(node.arg) if node.annotation: self.write(': ') # TODO precedence self.visit(node.annotation) def visit_keyword(self, node): if node.arg is None: # in py3, **kwargs is a keyword whose arg is None self.write('**') else: self.write(node.arg + '=') self.visit(node.value) def visit_alias(self, node): self.write(node.name) if node.asname is not None: self.write(' as %s' % node.asname)
jmvrbanac/Specter
specter/expect.py
expect
python
def expect(obj, caller_args=[]): line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) expect_obj = ExpectAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(expect_obj) return expect_obj
Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L202-L217
[ "def get_module_and_line(use_child_attr=None):\n last_frame = inspect.currentframe()\n\n steps = 2\n for i in range(steps):\n last_frame = last_frame.f_back\n\n self = module = last_frame.f_locals['self']\n # Use an attr instead of self\n if use_child_attr:\n module = getattr(self, use_child_attr, self)\n\n return last_frame.f_lineno, inspect.getmodule(type(module))\n", "def _add_expect_to_wrapper(obj_to_add):\n try:\n for frame in inspect.stack():\n if frame[3] == 'execute':\n wrapper = frame[0].f_locals.get('self')\n if type(wrapper) is CaseWrapper:\n wrapper.expects.append(obj_to_add)\n except Exception as error:\n raise Exception(_('Error attempting to add expect to parent '\n 'wrapper: {err}').format(err=error))\n" ]
import functools import inspect # Making sure we support 2.7 and 3+ try: from types import ClassType as ClassObjType except ImportError: from types import ModuleType as ClassObjType from specter import _ from specter.spec import (CaseWrapper, FailedRequireException, TestSkippedException, TestIncompleteException) from specter.util import ExpectParams, get_module_and_line class ExpectAssert(object): def __init__(self, target, required=False, src_params=None, caller_args=[]): super(ExpectAssert, self).__init__() self.prefix = _('expect') self.target = target self.src_params = src_params self.actions = [target] self.success = False self.used_negative = False self.required = required self.caller_args = caller_args self.custom_msg = None self.custom_report_vars = {} @property def target_src_param(self): if self.src_params and self.src_params.expect_arg: return self.src_params.expect_arg @property def expected_src_param(self): if self.src_params and self.src_params.cmp_arg: return self.src_params.cmp_arg def serialize(self): """Serializes the ExpectAssert object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed. """ converted_dict = { 'success': self.success, 'assertion': str(self), 'required': self.required } return converted_dict def _verify_condition(self, condition): self.success = condition if not self.used_negative else not condition if self.required and not self.success: raise FailedRequireException() return self.success @property def not_to(self): self.actions.append(_('not')) self.used_negative = not self.used_negative return self.to @property def to(self): self.actions.append(_('to')) return self def _compare(self, action_name, expected, condition): self.expected = expected self.actions.extend([action_name, expected]) self._verify_condition(condition=condition) def equal(self, expected): self._compare(action_name=_('equal'), expected=expected, condition=self.target == expected) def almost_equal(self, expected, places=7): if not isinstance(places, int): raise TypeError('Places must be an integer') self._compare( action_name=_('almost equal'), expected=expected, condition=round(abs(self.target - expected), places) == 0 ) def be_greater_than(self, expected): self._compare(action_name=_('be greater than'), expected=expected, condition=self.target > expected) def be_less_than(self, expected): self._compare(action_name=_('be less than'), expected=expected, condition=self.target < expected) def be_none(self): self._compare(action_name=_('be'), expected=None, condition=self.target is None) def be_true(self): self._compare(action_name=_('be'), expected=True, condition=self.target) def be_false(self): self._compare(action_name=_('be'), expected=False, condition=not self.target) def contain(self, expected): self._compare(action_name=_('contain'), expected=expected, condition=expected in self.target) def be_in(self, expected): self._compare(action_name=_('be in'), expected=expected, condition=self.target in expected) def be_a(self, expected): self._compare(action_name=_('be a'), expected=expected, condition=type(self.target) is expected) def be_an_instance_of(self, expected): self._compare(action_name=_('be an instance of'), expected=expected, condition=isinstance(self.target, expected)) def raise_a(self, exception): self.expected = exception self.actions.extend(['raise', exception]) condition = False raised_exc = 'nothing' try: self.target(*self.caller_args) except Exception as e: condition = type(e) == exception raised_exc = e # We didn't raise anything if self.used_negative and not isinstance(raised_exc, Exception): self.success = True # Raised, but it didn't match elif self.used_negative and type(raised_exc) != exception: self.success = False elif self.used_negative: self.success = not condition else: self.success = condition if not self.success: was = 'wasn\'t' if self.used_negative else 'was' # Make sure we have a name to use if hasattr(self.expected, '__name__'): name = self.expected.__name__ else: name = type(self.expected).__name__ msg = _('function {func_name} {was} expected to raise "{exc}".') self.custom_msg = msg.format( func_name=self.target_src_param, exc=name, was=was ) self.custom_report_vars['Raised Exception'] = ( type(raised_exc).__name__ ) def __str__(self): action_list = [] action_list.extend(self.actions) action_list[0] = self.target_src_param or str(self.target) action_list[-1] = self.expected_src_param or str(self.expected) return ' '.join([str(action) for action in action_list]) class RequireAssert(ExpectAssert): def __init__(self, target, src_params=None, caller_args=[]): super(RequireAssert, self).__init__(target=target, required=True, src_params=src_params, caller_args=caller_args) self.prefix = _('require') def _add_expect_to_wrapper(obj_to_add): try: for frame in inspect.stack(): if frame[3] == 'execute': wrapper = frame[0].f_locals.get('self') if type(wrapper) is CaseWrapper: wrapper.expects.append(obj_to_add) except Exception as error: raise Exception(_('Error attempting to add expect to parent ' 'wrapper: {err}').format(err=error)) def require(obj, caller_args=[]): """Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception """ line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) require_obj = RequireAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(require_obj) return require_obj def skip(reason): """The skip decorator allows for you to always bypass a test. :param reason: Expects a string """ def decorator(test_func): if not isinstance(test_func, (type, ClassObjType)): func_data = None if test_func.__name__ == 'DECORATOR_ONCALL': # Call down and save the results func_data = test_func() @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): other_data = { 'real_func': func_data[0] if func_data else test_func, 'metadata': func_data[1] if func_data else None } raise TestSkippedException(test_func, reason, other_data) test_func = skip_wrapper return test_func return decorator def skip_if(condition, reason=None): """The skip_if decorator allows for you to bypass a test on conditions :param condition: Expects a boolean :param reason: Expects a string """ if condition: return skip(reason) def wrapper(func): return func return wrapper def incomplete(test_func): """The incomplete decorator behaves much like a normal skip; however, tests that are marked as incomplete get tracked under a different metric. This allows for you to create a skeleton around all of your features and specifications, and track what tests have been written and what tests are left outstanding. .. code-block:: python # Example of using the incomplete decorator @incomplete def it_should_do_something(self): pass """ if not isinstance(test_func, (type, ClassObjType)): @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): raise TestIncompleteException(test_func, _('Test is incomplete')) return skip_wrapper def metadata(**key_value_pairs): """The metadata decorator allows for you to tag specific tests with key/value data for run-time processing or reporting. The common use case is to use metadata to tag a test as a positive or negative test type. .. code-block:: python # Example of using the metadata decorator @metadata(type='negative') def it_shouldnt_do_something(self): pass """ def onTestFunc(func): def DECORATOR_ONCALL(*args, **kwargs): return (func, key_value_pairs) return DECORATOR_ONCALL return onTestFunc
jmvrbanac/Specter
specter/expect.py
require
python
def require(obj, caller_args=[]): line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) require_obj = RequireAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(require_obj) return require_obj
Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L220-L235
[ "def get_module_and_line(use_child_attr=None):\n last_frame = inspect.currentframe()\n\n steps = 2\n for i in range(steps):\n last_frame = last_frame.f_back\n\n self = module = last_frame.f_locals['self']\n # Use an attr instead of self\n if use_child_attr:\n module = getattr(self, use_child_attr, self)\n\n return last_frame.f_lineno, inspect.getmodule(type(module))\n", "def _add_expect_to_wrapper(obj_to_add):\n try:\n for frame in inspect.stack():\n if frame[3] == 'execute':\n wrapper = frame[0].f_locals.get('self')\n if type(wrapper) is CaseWrapper:\n wrapper.expects.append(obj_to_add)\n except Exception as error:\n raise Exception(_('Error attempting to add expect to parent '\n 'wrapper: {err}').format(err=error))\n" ]
import functools import inspect # Making sure we support 2.7 and 3+ try: from types import ClassType as ClassObjType except ImportError: from types import ModuleType as ClassObjType from specter import _ from specter.spec import (CaseWrapper, FailedRequireException, TestSkippedException, TestIncompleteException) from specter.util import ExpectParams, get_module_and_line class ExpectAssert(object): def __init__(self, target, required=False, src_params=None, caller_args=[]): super(ExpectAssert, self).__init__() self.prefix = _('expect') self.target = target self.src_params = src_params self.actions = [target] self.success = False self.used_negative = False self.required = required self.caller_args = caller_args self.custom_msg = None self.custom_report_vars = {} @property def target_src_param(self): if self.src_params and self.src_params.expect_arg: return self.src_params.expect_arg @property def expected_src_param(self): if self.src_params and self.src_params.cmp_arg: return self.src_params.cmp_arg def serialize(self): """Serializes the ExpectAssert object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed. """ converted_dict = { 'success': self.success, 'assertion': str(self), 'required': self.required } return converted_dict def _verify_condition(self, condition): self.success = condition if not self.used_negative else not condition if self.required and not self.success: raise FailedRequireException() return self.success @property def not_to(self): self.actions.append(_('not')) self.used_negative = not self.used_negative return self.to @property def to(self): self.actions.append(_('to')) return self def _compare(self, action_name, expected, condition): self.expected = expected self.actions.extend([action_name, expected]) self._verify_condition(condition=condition) def equal(self, expected): self._compare(action_name=_('equal'), expected=expected, condition=self.target == expected) def almost_equal(self, expected, places=7): if not isinstance(places, int): raise TypeError('Places must be an integer') self._compare( action_name=_('almost equal'), expected=expected, condition=round(abs(self.target - expected), places) == 0 ) def be_greater_than(self, expected): self._compare(action_name=_('be greater than'), expected=expected, condition=self.target > expected) def be_less_than(self, expected): self._compare(action_name=_('be less than'), expected=expected, condition=self.target < expected) def be_none(self): self._compare(action_name=_('be'), expected=None, condition=self.target is None) def be_true(self): self._compare(action_name=_('be'), expected=True, condition=self.target) def be_false(self): self._compare(action_name=_('be'), expected=False, condition=not self.target) def contain(self, expected): self._compare(action_name=_('contain'), expected=expected, condition=expected in self.target) def be_in(self, expected): self._compare(action_name=_('be in'), expected=expected, condition=self.target in expected) def be_a(self, expected): self._compare(action_name=_('be a'), expected=expected, condition=type(self.target) is expected) def be_an_instance_of(self, expected): self._compare(action_name=_('be an instance of'), expected=expected, condition=isinstance(self.target, expected)) def raise_a(self, exception): self.expected = exception self.actions.extend(['raise', exception]) condition = False raised_exc = 'nothing' try: self.target(*self.caller_args) except Exception as e: condition = type(e) == exception raised_exc = e # We didn't raise anything if self.used_negative and not isinstance(raised_exc, Exception): self.success = True # Raised, but it didn't match elif self.used_negative and type(raised_exc) != exception: self.success = False elif self.used_negative: self.success = not condition else: self.success = condition if not self.success: was = 'wasn\'t' if self.used_negative else 'was' # Make sure we have a name to use if hasattr(self.expected, '__name__'): name = self.expected.__name__ else: name = type(self.expected).__name__ msg = _('function {func_name} {was} expected to raise "{exc}".') self.custom_msg = msg.format( func_name=self.target_src_param, exc=name, was=was ) self.custom_report_vars['Raised Exception'] = ( type(raised_exc).__name__ ) def __str__(self): action_list = [] action_list.extend(self.actions) action_list[0] = self.target_src_param or str(self.target) action_list[-1] = self.expected_src_param or str(self.expected) return ' '.join([str(action) for action in action_list]) class RequireAssert(ExpectAssert): def __init__(self, target, src_params=None, caller_args=[]): super(RequireAssert, self).__init__(target=target, required=True, src_params=src_params, caller_args=caller_args) self.prefix = _('require') def _add_expect_to_wrapper(obj_to_add): try: for frame in inspect.stack(): if frame[3] == 'execute': wrapper = frame[0].f_locals.get('self') if type(wrapper) is CaseWrapper: wrapper.expects.append(obj_to_add) except Exception as error: raise Exception(_('Error attempting to add expect to parent ' 'wrapper: {err}').format(err=error)) def expect(obj, caller_args=[]): """Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception """ line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) expect_obj = ExpectAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(expect_obj) return expect_obj def skip(reason): """The skip decorator allows for you to always bypass a test. :param reason: Expects a string """ def decorator(test_func): if not isinstance(test_func, (type, ClassObjType)): func_data = None if test_func.__name__ == 'DECORATOR_ONCALL': # Call down and save the results func_data = test_func() @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): other_data = { 'real_func': func_data[0] if func_data else test_func, 'metadata': func_data[1] if func_data else None } raise TestSkippedException(test_func, reason, other_data) test_func = skip_wrapper return test_func return decorator def skip_if(condition, reason=None): """The skip_if decorator allows for you to bypass a test on conditions :param condition: Expects a boolean :param reason: Expects a string """ if condition: return skip(reason) def wrapper(func): return func return wrapper def incomplete(test_func): """The incomplete decorator behaves much like a normal skip; however, tests that are marked as incomplete get tracked under a different metric. This allows for you to create a skeleton around all of your features and specifications, and track what tests have been written and what tests are left outstanding. .. code-block:: python # Example of using the incomplete decorator @incomplete def it_should_do_something(self): pass """ if not isinstance(test_func, (type, ClassObjType)): @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): raise TestIncompleteException(test_func, _('Test is incomplete')) return skip_wrapper def metadata(**key_value_pairs): """The metadata decorator allows for you to tag specific tests with key/value data for run-time processing or reporting. The common use case is to use metadata to tag a test as a positive or negative test type. .. code-block:: python # Example of using the metadata decorator @metadata(type='negative') def it_shouldnt_do_something(self): pass """ def onTestFunc(func): def DECORATOR_ONCALL(*args, **kwargs): return (func, key_value_pairs) return DECORATOR_ONCALL return onTestFunc
jmvrbanac/Specter
specter/expect.py
skip
python
def skip(reason): def decorator(test_func): if not isinstance(test_func, (type, ClassObjType)): func_data = None if test_func.__name__ == 'DECORATOR_ONCALL': # Call down and save the results func_data = test_func() @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): other_data = { 'real_func': func_data[0] if func_data else test_func, 'metadata': func_data[1] if func_data else None } raise TestSkippedException(test_func, reason, other_data) test_func = skip_wrapper return test_func return decorator
The skip decorator allows for you to always bypass a test. :param reason: Expects a string
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L238-L259
null
import functools import inspect # Making sure we support 2.7 and 3+ try: from types import ClassType as ClassObjType except ImportError: from types import ModuleType as ClassObjType from specter import _ from specter.spec import (CaseWrapper, FailedRequireException, TestSkippedException, TestIncompleteException) from specter.util import ExpectParams, get_module_and_line class ExpectAssert(object): def __init__(self, target, required=False, src_params=None, caller_args=[]): super(ExpectAssert, self).__init__() self.prefix = _('expect') self.target = target self.src_params = src_params self.actions = [target] self.success = False self.used_negative = False self.required = required self.caller_args = caller_args self.custom_msg = None self.custom_report_vars = {} @property def target_src_param(self): if self.src_params and self.src_params.expect_arg: return self.src_params.expect_arg @property def expected_src_param(self): if self.src_params and self.src_params.cmp_arg: return self.src_params.cmp_arg def serialize(self): """Serializes the ExpectAssert object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed. """ converted_dict = { 'success': self.success, 'assertion': str(self), 'required': self.required } return converted_dict def _verify_condition(self, condition): self.success = condition if not self.used_negative else not condition if self.required and not self.success: raise FailedRequireException() return self.success @property def not_to(self): self.actions.append(_('not')) self.used_negative = not self.used_negative return self.to @property def to(self): self.actions.append(_('to')) return self def _compare(self, action_name, expected, condition): self.expected = expected self.actions.extend([action_name, expected]) self._verify_condition(condition=condition) def equal(self, expected): self._compare(action_name=_('equal'), expected=expected, condition=self.target == expected) def almost_equal(self, expected, places=7): if not isinstance(places, int): raise TypeError('Places must be an integer') self._compare( action_name=_('almost equal'), expected=expected, condition=round(abs(self.target - expected), places) == 0 ) def be_greater_than(self, expected): self._compare(action_name=_('be greater than'), expected=expected, condition=self.target > expected) def be_less_than(self, expected): self._compare(action_name=_('be less than'), expected=expected, condition=self.target < expected) def be_none(self): self._compare(action_name=_('be'), expected=None, condition=self.target is None) def be_true(self): self._compare(action_name=_('be'), expected=True, condition=self.target) def be_false(self): self._compare(action_name=_('be'), expected=False, condition=not self.target) def contain(self, expected): self._compare(action_name=_('contain'), expected=expected, condition=expected in self.target) def be_in(self, expected): self._compare(action_name=_('be in'), expected=expected, condition=self.target in expected) def be_a(self, expected): self._compare(action_name=_('be a'), expected=expected, condition=type(self.target) is expected) def be_an_instance_of(self, expected): self._compare(action_name=_('be an instance of'), expected=expected, condition=isinstance(self.target, expected)) def raise_a(self, exception): self.expected = exception self.actions.extend(['raise', exception]) condition = False raised_exc = 'nothing' try: self.target(*self.caller_args) except Exception as e: condition = type(e) == exception raised_exc = e # We didn't raise anything if self.used_negative and not isinstance(raised_exc, Exception): self.success = True # Raised, but it didn't match elif self.used_negative and type(raised_exc) != exception: self.success = False elif self.used_negative: self.success = not condition else: self.success = condition if not self.success: was = 'wasn\'t' if self.used_negative else 'was' # Make sure we have a name to use if hasattr(self.expected, '__name__'): name = self.expected.__name__ else: name = type(self.expected).__name__ msg = _('function {func_name} {was} expected to raise "{exc}".') self.custom_msg = msg.format( func_name=self.target_src_param, exc=name, was=was ) self.custom_report_vars['Raised Exception'] = ( type(raised_exc).__name__ ) def __str__(self): action_list = [] action_list.extend(self.actions) action_list[0] = self.target_src_param or str(self.target) action_list[-1] = self.expected_src_param or str(self.expected) return ' '.join([str(action) for action in action_list]) class RequireAssert(ExpectAssert): def __init__(self, target, src_params=None, caller_args=[]): super(RequireAssert, self).__init__(target=target, required=True, src_params=src_params, caller_args=caller_args) self.prefix = _('require') def _add_expect_to_wrapper(obj_to_add): try: for frame in inspect.stack(): if frame[3] == 'execute': wrapper = frame[0].f_locals.get('self') if type(wrapper) is CaseWrapper: wrapper.expects.append(obj_to_add) except Exception as error: raise Exception(_('Error attempting to add expect to parent ' 'wrapper: {err}').format(err=error)) def expect(obj, caller_args=[]): """Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception """ line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) expect_obj = ExpectAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(expect_obj) return expect_obj def require(obj, caller_args=[]): """Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception """ line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) require_obj = RequireAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(require_obj) return require_obj def skip_if(condition, reason=None): """The skip_if decorator allows for you to bypass a test on conditions :param condition: Expects a boolean :param reason: Expects a string """ if condition: return skip(reason) def wrapper(func): return func return wrapper def incomplete(test_func): """The incomplete decorator behaves much like a normal skip; however, tests that are marked as incomplete get tracked under a different metric. This allows for you to create a skeleton around all of your features and specifications, and track what tests have been written and what tests are left outstanding. .. code-block:: python # Example of using the incomplete decorator @incomplete def it_should_do_something(self): pass """ if not isinstance(test_func, (type, ClassObjType)): @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): raise TestIncompleteException(test_func, _('Test is incomplete')) return skip_wrapper def metadata(**key_value_pairs): """The metadata decorator allows for you to tag specific tests with key/value data for run-time processing or reporting. The common use case is to use metadata to tag a test as a positive or negative test type. .. code-block:: python # Example of using the metadata decorator @metadata(type='negative') def it_shouldnt_do_something(self): pass """ def onTestFunc(func): def DECORATOR_ONCALL(*args, **kwargs): return (func, key_value_pairs) return DECORATOR_ONCALL return onTestFunc
jmvrbanac/Specter
specter/expect.py
skip_if
python
def skip_if(condition, reason=None): if condition: return skip(reason) def wrapper(func): return func return wrapper
The skip_if decorator allows for you to bypass a test on conditions :param condition: Expects a boolean :param reason: Expects a string
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L262-L273
[ "def skip(reason):\n \"\"\"The skip decorator allows for you to always bypass a test.\n\n :param reason: Expects a string\n \"\"\"\n def decorator(test_func):\n if not isinstance(test_func, (type, ClassObjType)):\n func_data = None\n if test_func.__name__ == 'DECORATOR_ONCALL':\n # Call down and save the results\n func_data = test_func()\n\n @functools.wraps(test_func)\n def skip_wrapper(*args, **kwargs):\n other_data = {\n 'real_func': func_data[0] if func_data else test_func,\n 'metadata': func_data[1] if func_data else None\n }\n raise TestSkippedException(test_func, reason, other_data)\n test_func = skip_wrapper\n return test_func\n return decorator\n" ]
import functools import inspect # Making sure we support 2.7 and 3+ try: from types import ClassType as ClassObjType except ImportError: from types import ModuleType as ClassObjType from specter import _ from specter.spec import (CaseWrapper, FailedRequireException, TestSkippedException, TestIncompleteException) from specter.util import ExpectParams, get_module_and_line class ExpectAssert(object): def __init__(self, target, required=False, src_params=None, caller_args=[]): super(ExpectAssert, self).__init__() self.prefix = _('expect') self.target = target self.src_params = src_params self.actions = [target] self.success = False self.used_negative = False self.required = required self.caller_args = caller_args self.custom_msg = None self.custom_report_vars = {} @property def target_src_param(self): if self.src_params and self.src_params.expect_arg: return self.src_params.expect_arg @property def expected_src_param(self): if self.src_params and self.src_params.cmp_arg: return self.src_params.cmp_arg def serialize(self): """Serializes the ExpectAssert object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed. """ converted_dict = { 'success': self.success, 'assertion': str(self), 'required': self.required } return converted_dict def _verify_condition(self, condition): self.success = condition if not self.used_negative else not condition if self.required and not self.success: raise FailedRequireException() return self.success @property def not_to(self): self.actions.append(_('not')) self.used_negative = not self.used_negative return self.to @property def to(self): self.actions.append(_('to')) return self def _compare(self, action_name, expected, condition): self.expected = expected self.actions.extend([action_name, expected]) self._verify_condition(condition=condition) def equal(self, expected): self._compare(action_name=_('equal'), expected=expected, condition=self.target == expected) def almost_equal(self, expected, places=7): if not isinstance(places, int): raise TypeError('Places must be an integer') self._compare( action_name=_('almost equal'), expected=expected, condition=round(abs(self.target - expected), places) == 0 ) def be_greater_than(self, expected): self._compare(action_name=_('be greater than'), expected=expected, condition=self.target > expected) def be_less_than(self, expected): self._compare(action_name=_('be less than'), expected=expected, condition=self.target < expected) def be_none(self): self._compare(action_name=_('be'), expected=None, condition=self.target is None) def be_true(self): self._compare(action_name=_('be'), expected=True, condition=self.target) def be_false(self): self._compare(action_name=_('be'), expected=False, condition=not self.target) def contain(self, expected): self._compare(action_name=_('contain'), expected=expected, condition=expected in self.target) def be_in(self, expected): self._compare(action_name=_('be in'), expected=expected, condition=self.target in expected) def be_a(self, expected): self._compare(action_name=_('be a'), expected=expected, condition=type(self.target) is expected) def be_an_instance_of(self, expected): self._compare(action_name=_('be an instance of'), expected=expected, condition=isinstance(self.target, expected)) def raise_a(self, exception): self.expected = exception self.actions.extend(['raise', exception]) condition = False raised_exc = 'nothing' try: self.target(*self.caller_args) except Exception as e: condition = type(e) == exception raised_exc = e # We didn't raise anything if self.used_negative and not isinstance(raised_exc, Exception): self.success = True # Raised, but it didn't match elif self.used_negative and type(raised_exc) != exception: self.success = False elif self.used_negative: self.success = not condition else: self.success = condition if not self.success: was = 'wasn\'t' if self.used_negative else 'was' # Make sure we have a name to use if hasattr(self.expected, '__name__'): name = self.expected.__name__ else: name = type(self.expected).__name__ msg = _('function {func_name} {was} expected to raise "{exc}".') self.custom_msg = msg.format( func_name=self.target_src_param, exc=name, was=was ) self.custom_report_vars['Raised Exception'] = ( type(raised_exc).__name__ ) def __str__(self): action_list = [] action_list.extend(self.actions) action_list[0] = self.target_src_param or str(self.target) action_list[-1] = self.expected_src_param or str(self.expected) return ' '.join([str(action) for action in action_list]) class RequireAssert(ExpectAssert): def __init__(self, target, src_params=None, caller_args=[]): super(RequireAssert, self).__init__(target=target, required=True, src_params=src_params, caller_args=caller_args) self.prefix = _('require') def _add_expect_to_wrapper(obj_to_add): try: for frame in inspect.stack(): if frame[3] == 'execute': wrapper = frame[0].f_locals.get('self') if type(wrapper) is CaseWrapper: wrapper.expects.append(obj_to_add) except Exception as error: raise Exception(_('Error attempting to add expect to parent ' 'wrapper: {err}').format(err=error)) def expect(obj, caller_args=[]): """Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception """ line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) expect_obj = ExpectAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(expect_obj) return expect_obj def require(obj, caller_args=[]): """Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception """ line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) require_obj = RequireAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(require_obj) return require_obj def skip(reason): """The skip decorator allows for you to always bypass a test. :param reason: Expects a string """ def decorator(test_func): if not isinstance(test_func, (type, ClassObjType)): func_data = None if test_func.__name__ == 'DECORATOR_ONCALL': # Call down and save the results func_data = test_func() @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): other_data = { 'real_func': func_data[0] if func_data else test_func, 'metadata': func_data[1] if func_data else None } raise TestSkippedException(test_func, reason, other_data) test_func = skip_wrapper return test_func return decorator def incomplete(test_func): """The incomplete decorator behaves much like a normal skip; however, tests that are marked as incomplete get tracked under a different metric. This allows for you to create a skeleton around all of your features and specifications, and track what tests have been written and what tests are left outstanding. .. code-block:: python # Example of using the incomplete decorator @incomplete def it_should_do_something(self): pass """ if not isinstance(test_func, (type, ClassObjType)): @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): raise TestIncompleteException(test_func, _('Test is incomplete')) return skip_wrapper def metadata(**key_value_pairs): """The metadata decorator allows for you to tag specific tests with key/value data for run-time processing or reporting. The common use case is to use metadata to tag a test as a positive or negative test type. .. code-block:: python # Example of using the metadata decorator @metadata(type='negative') def it_shouldnt_do_something(self): pass """ def onTestFunc(func): def DECORATOR_ONCALL(*args, **kwargs): return (func, key_value_pairs) return DECORATOR_ONCALL return onTestFunc
jmvrbanac/Specter
specter/expect.py
incomplete
python
def incomplete(test_func): if not isinstance(test_func, (type, ClassObjType)): @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): raise TestIncompleteException(test_func, _('Test is incomplete')) return skip_wrapper
The incomplete decorator behaves much like a normal skip; however, tests that are marked as incomplete get tracked under a different metric. This allows for you to create a skeleton around all of your features and specifications, and track what tests have been written and what tests are left outstanding. .. code-block:: python # Example of using the incomplete decorator @incomplete def it_should_do_something(self): pass
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L276-L294
null
import functools import inspect # Making sure we support 2.7 and 3+ try: from types import ClassType as ClassObjType except ImportError: from types import ModuleType as ClassObjType from specter import _ from specter.spec import (CaseWrapper, FailedRequireException, TestSkippedException, TestIncompleteException) from specter.util import ExpectParams, get_module_and_line class ExpectAssert(object): def __init__(self, target, required=False, src_params=None, caller_args=[]): super(ExpectAssert, self).__init__() self.prefix = _('expect') self.target = target self.src_params = src_params self.actions = [target] self.success = False self.used_negative = False self.required = required self.caller_args = caller_args self.custom_msg = None self.custom_report_vars = {} @property def target_src_param(self): if self.src_params and self.src_params.expect_arg: return self.src_params.expect_arg @property def expected_src_param(self): if self.src_params and self.src_params.cmp_arg: return self.src_params.cmp_arg def serialize(self): """Serializes the ExpectAssert object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed. """ converted_dict = { 'success': self.success, 'assertion': str(self), 'required': self.required } return converted_dict def _verify_condition(self, condition): self.success = condition if not self.used_negative else not condition if self.required and not self.success: raise FailedRequireException() return self.success @property def not_to(self): self.actions.append(_('not')) self.used_negative = not self.used_negative return self.to @property def to(self): self.actions.append(_('to')) return self def _compare(self, action_name, expected, condition): self.expected = expected self.actions.extend([action_name, expected]) self._verify_condition(condition=condition) def equal(self, expected): self._compare(action_name=_('equal'), expected=expected, condition=self.target == expected) def almost_equal(self, expected, places=7): if not isinstance(places, int): raise TypeError('Places must be an integer') self._compare( action_name=_('almost equal'), expected=expected, condition=round(abs(self.target - expected), places) == 0 ) def be_greater_than(self, expected): self._compare(action_name=_('be greater than'), expected=expected, condition=self.target > expected) def be_less_than(self, expected): self._compare(action_name=_('be less than'), expected=expected, condition=self.target < expected) def be_none(self): self._compare(action_name=_('be'), expected=None, condition=self.target is None) def be_true(self): self._compare(action_name=_('be'), expected=True, condition=self.target) def be_false(self): self._compare(action_name=_('be'), expected=False, condition=not self.target) def contain(self, expected): self._compare(action_name=_('contain'), expected=expected, condition=expected in self.target) def be_in(self, expected): self._compare(action_name=_('be in'), expected=expected, condition=self.target in expected) def be_a(self, expected): self._compare(action_name=_('be a'), expected=expected, condition=type(self.target) is expected) def be_an_instance_of(self, expected): self._compare(action_name=_('be an instance of'), expected=expected, condition=isinstance(self.target, expected)) def raise_a(self, exception): self.expected = exception self.actions.extend(['raise', exception]) condition = False raised_exc = 'nothing' try: self.target(*self.caller_args) except Exception as e: condition = type(e) == exception raised_exc = e # We didn't raise anything if self.used_negative and not isinstance(raised_exc, Exception): self.success = True # Raised, but it didn't match elif self.used_negative and type(raised_exc) != exception: self.success = False elif self.used_negative: self.success = not condition else: self.success = condition if not self.success: was = 'wasn\'t' if self.used_negative else 'was' # Make sure we have a name to use if hasattr(self.expected, '__name__'): name = self.expected.__name__ else: name = type(self.expected).__name__ msg = _('function {func_name} {was} expected to raise "{exc}".') self.custom_msg = msg.format( func_name=self.target_src_param, exc=name, was=was ) self.custom_report_vars['Raised Exception'] = ( type(raised_exc).__name__ ) def __str__(self): action_list = [] action_list.extend(self.actions) action_list[0] = self.target_src_param or str(self.target) action_list[-1] = self.expected_src_param or str(self.expected) return ' '.join([str(action) for action in action_list]) class RequireAssert(ExpectAssert): def __init__(self, target, src_params=None, caller_args=[]): super(RequireAssert, self).__init__(target=target, required=True, src_params=src_params, caller_args=caller_args) self.prefix = _('require') def _add_expect_to_wrapper(obj_to_add): try: for frame in inspect.stack(): if frame[3] == 'execute': wrapper = frame[0].f_locals.get('self') if type(wrapper) is CaseWrapper: wrapper.expects.append(obj_to_add) except Exception as error: raise Exception(_('Error attempting to add expect to parent ' 'wrapper: {err}').format(err=error)) def expect(obj, caller_args=[]): """Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception """ line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) expect_obj = ExpectAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(expect_obj) return expect_obj def require(obj, caller_args=[]): """Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception """ line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) require_obj = RequireAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(require_obj) return require_obj def skip(reason): """The skip decorator allows for you to always bypass a test. :param reason: Expects a string """ def decorator(test_func): if not isinstance(test_func, (type, ClassObjType)): func_data = None if test_func.__name__ == 'DECORATOR_ONCALL': # Call down and save the results func_data = test_func() @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): other_data = { 'real_func': func_data[0] if func_data else test_func, 'metadata': func_data[1] if func_data else None } raise TestSkippedException(test_func, reason, other_data) test_func = skip_wrapper return test_func return decorator def skip_if(condition, reason=None): """The skip_if decorator allows for you to bypass a test on conditions :param condition: Expects a boolean :param reason: Expects a string """ if condition: return skip(reason) def wrapper(func): return func return wrapper def metadata(**key_value_pairs): """The metadata decorator allows for you to tag specific tests with key/value data for run-time processing or reporting. The common use case is to use metadata to tag a test as a positive or negative test type. .. code-block:: python # Example of using the metadata decorator @metadata(type='negative') def it_shouldnt_do_something(self): pass """ def onTestFunc(func): def DECORATOR_ONCALL(*args, **kwargs): return (func, key_value_pairs) return DECORATOR_ONCALL return onTestFunc
jmvrbanac/Specter
specter/expect.py
metadata
python
def metadata(**key_value_pairs): def onTestFunc(func): def DECORATOR_ONCALL(*args, **kwargs): return (func, key_value_pairs) return DECORATOR_ONCALL return onTestFunc
The metadata decorator allows for you to tag specific tests with key/value data for run-time processing or reporting. The common use case is to use metadata to tag a test as a positive or negative test type. .. code-block:: python # Example of using the metadata decorator @metadata(type='negative') def it_shouldnt_do_something(self): pass
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L297-L313
null
import functools import inspect # Making sure we support 2.7 and 3+ try: from types import ClassType as ClassObjType except ImportError: from types import ModuleType as ClassObjType from specter import _ from specter.spec import (CaseWrapper, FailedRequireException, TestSkippedException, TestIncompleteException) from specter.util import ExpectParams, get_module_and_line class ExpectAssert(object): def __init__(self, target, required=False, src_params=None, caller_args=[]): super(ExpectAssert, self).__init__() self.prefix = _('expect') self.target = target self.src_params = src_params self.actions = [target] self.success = False self.used_negative = False self.required = required self.caller_args = caller_args self.custom_msg = None self.custom_report_vars = {} @property def target_src_param(self): if self.src_params and self.src_params.expect_arg: return self.src_params.expect_arg @property def expected_src_param(self): if self.src_params and self.src_params.cmp_arg: return self.src_params.cmp_arg def serialize(self): """Serializes the ExpectAssert object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed. """ converted_dict = { 'success': self.success, 'assertion': str(self), 'required': self.required } return converted_dict def _verify_condition(self, condition): self.success = condition if not self.used_negative else not condition if self.required and not self.success: raise FailedRequireException() return self.success @property def not_to(self): self.actions.append(_('not')) self.used_negative = not self.used_negative return self.to @property def to(self): self.actions.append(_('to')) return self def _compare(self, action_name, expected, condition): self.expected = expected self.actions.extend([action_name, expected]) self._verify_condition(condition=condition) def equal(self, expected): self._compare(action_name=_('equal'), expected=expected, condition=self.target == expected) def almost_equal(self, expected, places=7): if not isinstance(places, int): raise TypeError('Places must be an integer') self._compare( action_name=_('almost equal'), expected=expected, condition=round(abs(self.target - expected), places) == 0 ) def be_greater_than(self, expected): self._compare(action_name=_('be greater than'), expected=expected, condition=self.target > expected) def be_less_than(self, expected): self._compare(action_name=_('be less than'), expected=expected, condition=self.target < expected) def be_none(self): self._compare(action_name=_('be'), expected=None, condition=self.target is None) def be_true(self): self._compare(action_name=_('be'), expected=True, condition=self.target) def be_false(self): self._compare(action_name=_('be'), expected=False, condition=not self.target) def contain(self, expected): self._compare(action_name=_('contain'), expected=expected, condition=expected in self.target) def be_in(self, expected): self._compare(action_name=_('be in'), expected=expected, condition=self.target in expected) def be_a(self, expected): self._compare(action_name=_('be a'), expected=expected, condition=type(self.target) is expected) def be_an_instance_of(self, expected): self._compare(action_name=_('be an instance of'), expected=expected, condition=isinstance(self.target, expected)) def raise_a(self, exception): self.expected = exception self.actions.extend(['raise', exception]) condition = False raised_exc = 'nothing' try: self.target(*self.caller_args) except Exception as e: condition = type(e) == exception raised_exc = e # We didn't raise anything if self.used_negative and not isinstance(raised_exc, Exception): self.success = True # Raised, but it didn't match elif self.used_negative and type(raised_exc) != exception: self.success = False elif self.used_negative: self.success = not condition else: self.success = condition if not self.success: was = 'wasn\'t' if self.used_negative else 'was' # Make sure we have a name to use if hasattr(self.expected, '__name__'): name = self.expected.__name__ else: name = type(self.expected).__name__ msg = _('function {func_name} {was} expected to raise "{exc}".') self.custom_msg = msg.format( func_name=self.target_src_param, exc=name, was=was ) self.custom_report_vars['Raised Exception'] = ( type(raised_exc).__name__ ) def __str__(self): action_list = [] action_list.extend(self.actions) action_list[0] = self.target_src_param or str(self.target) action_list[-1] = self.expected_src_param or str(self.expected) return ' '.join([str(action) for action in action_list]) class RequireAssert(ExpectAssert): def __init__(self, target, src_params=None, caller_args=[]): super(RequireAssert, self).__init__(target=target, required=True, src_params=src_params, caller_args=caller_args) self.prefix = _('require') def _add_expect_to_wrapper(obj_to_add): try: for frame in inspect.stack(): if frame[3] == 'execute': wrapper = frame[0].f_locals.get('self') if type(wrapper) is CaseWrapper: wrapper.expects.append(obj_to_add) except Exception as error: raise Exception(_('Error attempting to add expect to parent ' 'wrapper: {err}').format(err=error)) def expect(obj, caller_args=[]): """Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception """ line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) expect_obj = ExpectAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(expect_obj) return expect_obj def require(obj, caller_args=[]): """Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception """ line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) require_obj = RequireAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(require_obj) return require_obj def skip(reason): """The skip decorator allows for you to always bypass a test. :param reason: Expects a string """ def decorator(test_func): if not isinstance(test_func, (type, ClassObjType)): func_data = None if test_func.__name__ == 'DECORATOR_ONCALL': # Call down and save the results func_data = test_func() @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): other_data = { 'real_func': func_data[0] if func_data else test_func, 'metadata': func_data[1] if func_data else None } raise TestSkippedException(test_func, reason, other_data) test_func = skip_wrapper return test_func return decorator def skip_if(condition, reason=None): """The skip_if decorator allows for you to bypass a test on conditions :param condition: Expects a boolean :param reason: Expects a string """ if condition: return skip(reason) def wrapper(func): return func return wrapper def incomplete(test_func): """The incomplete decorator behaves much like a normal skip; however, tests that are marked as incomplete get tracked under a different metric. This allows for you to create a skeleton around all of your features and specifications, and track what tests have been written and what tests are left outstanding. .. code-block:: python # Example of using the incomplete decorator @incomplete def it_should_do_something(self): pass """ if not isinstance(test_func, (type, ClassObjType)): @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): raise TestIncompleteException(test_func, _('Test is incomplete')) return skip_wrapper
jmvrbanac/Specter
specter/expect.py
ExpectAssert.serialize
python
def serialize(self): converted_dict = { 'success': self.success, 'assertion': str(self), 'required': self.required } return converted_dict
Serializes the ExpectAssert object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L41-L53
null
class ExpectAssert(object): def __init__(self, target, required=False, src_params=None, caller_args=[]): super(ExpectAssert, self).__init__() self.prefix = _('expect') self.target = target self.src_params = src_params self.actions = [target] self.success = False self.used_negative = False self.required = required self.caller_args = caller_args self.custom_msg = None self.custom_report_vars = {} @property def target_src_param(self): if self.src_params and self.src_params.expect_arg: return self.src_params.expect_arg @property def expected_src_param(self): if self.src_params and self.src_params.cmp_arg: return self.src_params.cmp_arg def _verify_condition(self, condition): self.success = condition if not self.used_negative else not condition if self.required and not self.success: raise FailedRequireException() return self.success @property def not_to(self): self.actions.append(_('not')) self.used_negative = not self.used_negative return self.to @property def to(self): self.actions.append(_('to')) return self def _compare(self, action_name, expected, condition): self.expected = expected self.actions.extend([action_name, expected]) self._verify_condition(condition=condition) def equal(self, expected): self._compare(action_name=_('equal'), expected=expected, condition=self.target == expected) def almost_equal(self, expected, places=7): if not isinstance(places, int): raise TypeError('Places must be an integer') self._compare( action_name=_('almost equal'), expected=expected, condition=round(abs(self.target - expected), places) == 0 ) def be_greater_than(self, expected): self._compare(action_name=_('be greater than'), expected=expected, condition=self.target > expected) def be_less_than(self, expected): self._compare(action_name=_('be less than'), expected=expected, condition=self.target < expected) def be_none(self): self._compare(action_name=_('be'), expected=None, condition=self.target is None) def be_true(self): self._compare(action_name=_('be'), expected=True, condition=self.target) def be_false(self): self._compare(action_name=_('be'), expected=False, condition=not self.target) def contain(self, expected): self._compare(action_name=_('contain'), expected=expected, condition=expected in self.target) def be_in(self, expected): self._compare(action_name=_('be in'), expected=expected, condition=self.target in expected) def be_a(self, expected): self._compare(action_name=_('be a'), expected=expected, condition=type(self.target) is expected) def be_an_instance_of(self, expected): self._compare(action_name=_('be an instance of'), expected=expected, condition=isinstance(self.target, expected)) def raise_a(self, exception): self.expected = exception self.actions.extend(['raise', exception]) condition = False raised_exc = 'nothing' try: self.target(*self.caller_args) except Exception as e: condition = type(e) == exception raised_exc = e # We didn't raise anything if self.used_negative and not isinstance(raised_exc, Exception): self.success = True # Raised, but it didn't match elif self.used_negative and type(raised_exc) != exception: self.success = False elif self.used_negative: self.success = not condition else: self.success = condition if not self.success: was = 'wasn\'t' if self.used_negative else 'was' # Make sure we have a name to use if hasattr(self.expected, '__name__'): name = self.expected.__name__ else: name = type(self.expected).__name__ msg = _('function {func_name} {was} expected to raise "{exc}".') self.custom_msg = msg.format( func_name=self.target_src_param, exc=name, was=was ) self.custom_report_vars['Raised Exception'] = ( type(raised_exc).__name__ ) def __str__(self): action_list = [] action_list.extend(self.actions) action_list[0] = self.target_src_param or str(self.target) action_list[-1] = self.expected_src_param or str(self.expected) return ' '.join([str(action) for action in action_list])
beregond/super_state_machine
super_state_machine/utils.py
is_
python
def is_(self, state): translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state
Check if machine is in given state.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L9-L13
null
"""Utilities for core.""" from enum import Enum, unique from functools import wraps from .errors import TransitionError def can_be_(self, state): """Check if machine can transit to given state.""" translator = self._meta['translator'] state = translator.translate(state) if self._meta['complete']: return True if self.actual_state is None: return True transitions = self._meta['transitions'][self.actual_state] return state in transitions def force_set(self, state): """Set new state without checking if transition is allowed.""" translator = self._meta['translator'] state = translator.translate(state) attr = self._meta['state_attribute_name'] setattr(self, attr, state) def set_(self, state): """Set new state for machine.""" if not self.can_be_(state): state = self._meta['translator'].translate(state) raise TransitionError( "Cannot transit from '{actual_value}' to '{value}'." .format(actual_value=self.actual_state.value, value=state.value) ) self.force_set(state) def state_getter(self): """Get actual state as value.""" try: return self.actual_state.value except AttributeError: return None def state_setter(self, value): """Set new state for machine.""" self.set_(value) def generate_getter(value): """Generate getter for given value.""" @property @wraps(is_) def getter(self): return self.is_(value) return getter def generate_checker(value): """Generate state checker for given value.""" @property @wraps(can_be_) def checker(self): return self.can_be_(value) return checker def generate_setter(value): """Generate setter for given value.""" @wraps(set_) def setter(self): self.set_(value) return setter state_property = property(state_getter, state_setter) @property def actual_state(self): """Actual state as `None` or `enum` instance.""" attr = self._meta['state_attribute_name'] return getattr(self, attr) @property def as_enum(self): """Return actual state as enum.""" return self.actual_state class EnumValueTranslator(object): """Helps to find enum element by its value.""" def __init__(self, base_enum): """Init. :param enum base_enum: Enum, to which elements values are translated. """ base_enum = unique(base_enum) self.base_enum = base_enum self.generate_search_table() def generate_search_table(self): self.search_table = dict( (item.value, item) for item in list(self.base_enum) ) def translate(self, value): """Translate value to enum instance. If value is already enum instance, check if this value belongs to base enum. """ if self._check_if_already_proper(value): return value try: return self.search_table[value] except KeyError: raise ValueError("Value {value} doesn't match any state.".format( value=value )) def _check_if_already_proper(self, value): if isinstance(value, Enum): if value in self.base_enum: return True raise ValueError( "Given value ('{value}') doesn't belong to states enum." .format(value=value) ) return False
beregond/super_state_machine
super_state_machine/utils.py
can_be_
python
def can_be_(self, state): translator = self._meta['translator'] state = translator.translate(state) if self._meta['complete']: return True if self.actual_state is None: return True transitions = self._meta['transitions'][self.actual_state] return state in transitions
Check if machine can transit to given state.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L16-L28
null
"""Utilities for core.""" from enum import Enum, unique from functools import wraps from .errors import TransitionError def is_(self, state): """Check if machine is in given state.""" translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state def force_set(self, state): """Set new state without checking if transition is allowed.""" translator = self._meta['translator'] state = translator.translate(state) attr = self._meta['state_attribute_name'] setattr(self, attr, state) def set_(self, state): """Set new state for machine.""" if not self.can_be_(state): state = self._meta['translator'].translate(state) raise TransitionError( "Cannot transit from '{actual_value}' to '{value}'." .format(actual_value=self.actual_state.value, value=state.value) ) self.force_set(state) def state_getter(self): """Get actual state as value.""" try: return self.actual_state.value except AttributeError: return None def state_setter(self, value): """Set new state for machine.""" self.set_(value) def generate_getter(value): """Generate getter for given value.""" @property @wraps(is_) def getter(self): return self.is_(value) return getter def generate_checker(value): """Generate state checker for given value.""" @property @wraps(can_be_) def checker(self): return self.can_be_(value) return checker def generate_setter(value): """Generate setter for given value.""" @wraps(set_) def setter(self): self.set_(value) return setter state_property = property(state_getter, state_setter) @property def actual_state(self): """Actual state as `None` or `enum` instance.""" attr = self._meta['state_attribute_name'] return getattr(self, attr) @property def as_enum(self): """Return actual state as enum.""" return self.actual_state class EnumValueTranslator(object): """Helps to find enum element by its value.""" def __init__(self, base_enum): """Init. :param enum base_enum: Enum, to which elements values are translated. """ base_enum = unique(base_enum) self.base_enum = base_enum self.generate_search_table() def generate_search_table(self): self.search_table = dict( (item.value, item) for item in list(self.base_enum) ) def translate(self, value): """Translate value to enum instance. If value is already enum instance, check if this value belongs to base enum. """ if self._check_if_already_proper(value): return value try: return self.search_table[value] except KeyError: raise ValueError("Value {value} doesn't match any state.".format( value=value )) def _check_if_already_proper(self, value): if isinstance(value, Enum): if value in self.base_enum: return True raise ValueError( "Given value ('{value}') doesn't belong to states enum." .format(value=value) ) return False
beregond/super_state_machine
super_state_machine/utils.py
force_set
python
def force_set(self, state): translator = self._meta['translator'] state = translator.translate(state) attr = self._meta['state_attribute_name'] setattr(self, attr, state)
Set new state without checking if transition is allowed.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L31-L36
null
"""Utilities for core.""" from enum import Enum, unique from functools import wraps from .errors import TransitionError def is_(self, state): """Check if machine is in given state.""" translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state def can_be_(self, state): """Check if machine can transit to given state.""" translator = self._meta['translator'] state = translator.translate(state) if self._meta['complete']: return True if self.actual_state is None: return True transitions = self._meta['transitions'][self.actual_state] return state in transitions def set_(self, state): """Set new state for machine.""" if not self.can_be_(state): state = self._meta['translator'].translate(state) raise TransitionError( "Cannot transit from '{actual_value}' to '{value}'." .format(actual_value=self.actual_state.value, value=state.value) ) self.force_set(state) def state_getter(self): """Get actual state as value.""" try: return self.actual_state.value except AttributeError: return None def state_setter(self, value): """Set new state for machine.""" self.set_(value) def generate_getter(value): """Generate getter for given value.""" @property @wraps(is_) def getter(self): return self.is_(value) return getter def generate_checker(value): """Generate state checker for given value.""" @property @wraps(can_be_) def checker(self): return self.can_be_(value) return checker def generate_setter(value): """Generate setter for given value.""" @wraps(set_) def setter(self): self.set_(value) return setter state_property = property(state_getter, state_setter) @property def actual_state(self): """Actual state as `None` or `enum` instance.""" attr = self._meta['state_attribute_name'] return getattr(self, attr) @property def as_enum(self): """Return actual state as enum.""" return self.actual_state class EnumValueTranslator(object): """Helps to find enum element by its value.""" def __init__(self, base_enum): """Init. :param enum base_enum: Enum, to which elements values are translated. """ base_enum = unique(base_enum) self.base_enum = base_enum self.generate_search_table() def generate_search_table(self): self.search_table = dict( (item.value, item) for item in list(self.base_enum) ) def translate(self, value): """Translate value to enum instance. If value is already enum instance, check if this value belongs to base enum. """ if self._check_if_already_proper(value): return value try: return self.search_table[value] except KeyError: raise ValueError("Value {value} doesn't match any state.".format( value=value )) def _check_if_already_proper(self, value): if isinstance(value, Enum): if value in self.base_enum: return True raise ValueError( "Given value ('{value}') doesn't belong to states enum." .format(value=value) ) return False
beregond/super_state_machine
super_state_machine/utils.py
set_
python
def set_(self, state): if not self.can_be_(state): state = self._meta['translator'].translate(state) raise TransitionError( "Cannot transit from '{actual_value}' to '{value}'." .format(actual_value=self.actual_state.value, value=state.value) ) self.force_set(state)
Set new state for machine.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L39-L48
null
"""Utilities for core.""" from enum import Enum, unique from functools import wraps from .errors import TransitionError def is_(self, state): """Check if machine is in given state.""" translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state def can_be_(self, state): """Check if machine can transit to given state.""" translator = self._meta['translator'] state = translator.translate(state) if self._meta['complete']: return True if self.actual_state is None: return True transitions = self._meta['transitions'][self.actual_state] return state in transitions def force_set(self, state): """Set new state without checking if transition is allowed.""" translator = self._meta['translator'] state = translator.translate(state) attr = self._meta['state_attribute_name'] setattr(self, attr, state) def state_getter(self): """Get actual state as value.""" try: return self.actual_state.value except AttributeError: return None def state_setter(self, value): """Set new state for machine.""" self.set_(value) def generate_getter(value): """Generate getter for given value.""" @property @wraps(is_) def getter(self): return self.is_(value) return getter def generate_checker(value): """Generate state checker for given value.""" @property @wraps(can_be_) def checker(self): return self.can_be_(value) return checker def generate_setter(value): """Generate setter for given value.""" @wraps(set_) def setter(self): self.set_(value) return setter state_property = property(state_getter, state_setter) @property def actual_state(self): """Actual state as `None` or `enum` instance.""" attr = self._meta['state_attribute_name'] return getattr(self, attr) @property def as_enum(self): """Return actual state as enum.""" return self.actual_state class EnumValueTranslator(object): """Helps to find enum element by its value.""" def __init__(self, base_enum): """Init. :param enum base_enum: Enum, to which elements values are translated. """ base_enum = unique(base_enum) self.base_enum = base_enum self.generate_search_table() def generate_search_table(self): self.search_table = dict( (item.value, item) for item in list(self.base_enum) ) def translate(self, value): """Translate value to enum instance. If value is already enum instance, check if this value belongs to base enum. """ if self._check_if_already_proper(value): return value try: return self.search_table[value] except KeyError: raise ValueError("Value {value} doesn't match any state.".format( value=value )) def _check_if_already_proper(self, value): if isinstance(value, Enum): if value in self.base_enum: return True raise ValueError( "Given value ('{value}') doesn't belong to states enum." .format(value=value) ) return False
beregond/super_state_machine
super_state_machine/utils.py
generate_getter
python
def generate_getter(value): @property @wraps(is_) def getter(self): return self.is_(value) return getter
Generate getter for given value.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L64-L71
null
"""Utilities for core.""" from enum import Enum, unique from functools import wraps from .errors import TransitionError def is_(self, state): """Check if machine is in given state.""" translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state def can_be_(self, state): """Check if machine can transit to given state.""" translator = self._meta['translator'] state = translator.translate(state) if self._meta['complete']: return True if self.actual_state is None: return True transitions = self._meta['transitions'][self.actual_state] return state in transitions def force_set(self, state): """Set new state without checking if transition is allowed.""" translator = self._meta['translator'] state = translator.translate(state) attr = self._meta['state_attribute_name'] setattr(self, attr, state) def set_(self, state): """Set new state for machine.""" if not self.can_be_(state): state = self._meta['translator'].translate(state) raise TransitionError( "Cannot transit from '{actual_value}' to '{value}'." .format(actual_value=self.actual_state.value, value=state.value) ) self.force_set(state) def state_getter(self): """Get actual state as value.""" try: return self.actual_state.value except AttributeError: return None def state_setter(self, value): """Set new state for machine.""" self.set_(value) def generate_checker(value): """Generate state checker for given value.""" @property @wraps(can_be_) def checker(self): return self.can_be_(value) return checker def generate_setter(value): """Generate setter for given value.""" @wraps(set_) def setter(self): self.set_(value) return setter state_property = property(state_getter, state_setter) @property def actual_state(self): """Actual state as `None` or `enum` instance.""" attr = self._meta['state_attribute_name'] return getattr(self, attr) @property def as_enum(self): """Return actual state as enum.""" return self.actual_state class EnumValueTranslator(object): """Helps to find enum element by its value.""" def __init__(self, base_enum): """Init. :param enum base_enum: Enum, to which elements values are translated. """ base_enum = unique(base_enum) self.base_enum = base_enum self.generate_search_table() def generate_search_table(self): self.search_table = dict( (item.value, item) for item in list(self.base_enum) ) def translate(self, value): """Translate value to enum instance. If value is already enum instance, check if this value belongs to base enum. """ if self._check_if_already_proper(value): return value try: return self.search_table[value] except KeyError: raise ValueError("Value {value} doesn't match any state.".format( value=value )) def _check_if_already_proper(self, value): if isinstance(value, Enum): if value in self.base_enum: return True raise ValueError( "Given value ('{value}') doesn't belong to states enum." .format(value=value) ) return False