hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
1c2beb17305d8936ca8116de0afa4ec98fd39c51
127
py
Python
language/_experimental/peace/_coherent.py
jedhsu/language
3772a4a0ff287e1fc5ebefc716b8d91928d04c72
[ "MIT" ]
null
null
null
language/_experimental/peace/_coherent.py
jedhsu/language
3772a4a0ff287e1fc5ebefc716b8d91928d04c72
[ "MIT" ]
null
null
null
language/_experimental/peace/_coherent.py
jedhsu/language
3772a4a0ff287e1fc5ebefc716b8d91928d04c72
[ "MIT" ]
null
null
null
""" *Coherent* """ from abc import ABCMeta __all__ = [ "Coherent", ] class Coherent: __metaclass__ = ABCMeta
7.9375
27
0.598425
from abc import ABCMeta __all__ = [ "Coherent", ] class Coherent: __metaclass__ = ABCMeta
true
true
1c2becd673e4d1caa9ff0dcb3a8856e5946e4172
1,185
py
Python
zerver/migrations/0232_make_archive_transaction_field_not_nullable.py
kaustubh-nair/zulip
fb96407607c1f42b350980ad13af20b884750606
[ "Apache-2.0" ]
6
2019-05-09T20:43:20.000Z
2022-03-29T05:53:50.000Z
zerver/migrations/0232_make_archive_transaction_field_not_nullable.py
kaustubh-nair/zulip
fb96407607c1f42b350980ad13af20b884750606
[ "Apache-2.0" ]
2
2016-10-18T04:01:56.000Z
2016-10-20T18:19:09.000Z
zerver/migrations/0232_make_archive_transaction_field_not_nullable.py
kaustubh-nair/zulip
fb96407607c1f42b350980ad13af20b884750606
[ "Apache-2.0" ]
7
2016-08-10T02:24:32.000Z
2022-03-28T15:14:18.000Z
import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): """ Tables cannot have data deleted from them and be altered in a single transaction, but we need the DELETEs to be atomic together. So we set atomic=False for the migration in general, and run the DELETEs in one transaction, and AlterField in another. """ atomic = False dependencies = [ ('zerver', '0231_add_archive_transaction_model'), ] operations = [ migrations.RunSQL(""" BEGIN; DELETE FROM zerver_archivedusermessage; DELETE FROM zerver_archivedreaction; DELETE FROM zerver_archivedsubmessage; DELETE FROM zerver_archivedattachment_messages; DELETE FROM zerver_archivedattachment; DELETE FROM zerver_archivedmessage; DELETE FROM zerver_archivetransaction; COMMIT; """, elidable=True), migrations.AlterField( model_name='archivedmessage', name='archive_transaction', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'), ), ]
33.857143
113
0.683544
import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): atomic = False dependencies = [ ('zerver', '0231_add_archive_transaction_model'), ] operations = [ migrations.RunSQL(""" BEGIN; DELETE FROM zerver_archivedusermessage; DELETE FROM zerver_archivedreaction; DELETE FROM zerver_archivedsubmessage; DELETE FROM zerver_archivedattachment_messages; DELETE FROM zerver_archivedattachment; DELETE FROM zerver_archivedmessage; DELETE FROM zerver_archivetransaction; COMMIT; """, elidable=True), migrations.AlterField( model_name='archivedmessage', name='archive_transaction', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'), ), ]
true
true
1c2bed449e2331f0a0e96bda18a70f2e92511a9b
36,224
py
Python
pydantic/schema.py
xzycn/pydantic
36c0af787fee01fe566a38c9a3d19940cb3e93c8
[ "MIT" ]
1
2020-03-03T22:12:12.000Z
2020-03-03T22:12:12.000Z
pydantic/schema.py
xzycn/pydantic
36c0af787fee01fe566a38c9a3d19940cb3e93c8
[ "MIT" ]
5
2021-06-02T03:55:08.000Z
2022-03-12T00:54:02.000Z
pydantic/schema.py
xzycn/pydantic
36c0af787fee01fe566a38c9a3d19940cb3e93c8
[ "MIT" ]
1
2021-10-05T16:57:32.000Z
2021-10-05T16:57:32.000Z
import re import warnings from datetime import date, datetime, time, timedelta from decimal import Decimal from enum import Enum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path from typing import ( TYPE_CHECKING, Any, Callable, Dict, FrozenSet, Iterable, List, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, cast, ) from uuid import UUID from .class_validators import ROOT_KEY from .fields import ( SHAPE_FROZENSET, SHAPE_ITERABLE, SHAPE_LIST, SHAPE_MAPPING, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, FieldInfo, ModelField, ) from .json import pydantic_encoder from .networks import AnyUrl, EmailStr from .types import ( ConstrainedDecimal, ConstrainedFloat, ConstrainedInt, ConstrainedList, ConstrainedSet, ConstrainedStr, conbytes, condecimal, confloat, conint, conlist, conset, constr, ) from .typing import ForwardRef, Literal, is_callable_type, is_literal_type, literal_values from .utils import get_model, lenient_issubclass, sequence_like if TYPE_CHECKING: from .main import BaseModel # noqa: F401 from .dataclasses import DataclassType # noqa: F401 default_prefix = '#/definitions/' TypeModelOrEnum = Union[Type['BaseModel'], Type[Enum]] TypeModelSet = Set[TypeModelOrEnum] def schema( models: Sequence[Union[Type['BaseModel'], Type['DataclassType']]], *, by_alias: bool = True, title: Optional[str] = None, description: Optional[str] = None, ref_prefix: Optional[str] = None, ) -> Dict[str, Any]: """ Process a list of models and generate a single JSON Schema with all of them defined in the ``definitions`` top-level JSON key, including their sub-models. :param models: a list of models to include in the generated JSON Schema :param by_alias: generate the schemas using the aliases defined, if any :param title: title for the generated schema that includes the definitions :param description: description for the generated schema :param ref_prefix: the JSON Pointer prefix for schema references with ``$ref``, if None, will be set to the default of ``#/definitions/``. Update it if you want the schemas to reference the definitions somewhere else, e.g. for OpenAPI use ``#/components/schemas/``. The resulting generated schemas will still be at the top-level key ``definitions``, so you can extract them from there. But all the references will have the set prefix. :return: dict with the JSON Schema with a ``definitions`` top-level key including the schema definitions for the models and sub-models passed in ``models``. """ clean_models = [get_model(model) for model in models] ref_prefix = ref_prefix or default_prefix flat_models = get_flat_models_from_models(clean_models) model_name_map = get_model_name_map(flat_models) definitions = {} output_schema: Dict[str, Any] = {} if title: output_schema['title'] = title if description: output_schema['description'] = description for model in clean_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema if definitions: output_schema['definitions'] = definitions return output_schema def model_schema( model: Union[Type['BaseModel'], Type['DataclassType']], by_alias: bool = True, ref_prefix: Optional[str] = None ) -> Dict[str, Any]: """ Generate a JSON Schema for one model. With all the sub-models defined in the ``definitions`` top-level JSON key. :param model: a Pydantic model (a class that inherits from BaseModel) :param by_alias: generate the schemas using the aliases defined, if any :param ref_prefix: the JSON Pointer prefix for schema references with ``$ref``, if None, will be set to the default of ``#/definitions/``. Update it if you want the schemas to reference the definitions somewhere else, e.g. for OpenAPI use ``#/components/schemas/``. The resulting generated schemas will still be at the top-level key ``definitions``, so you can extract them from there. But all the references will have the set prefix. :return: dict with the JSON Schema for the passed ``model`` """ model = get_model(model) ref_prefix = ref_prefix or default_prefix flat_models = get_flat_models_from_model(model) model_name_map = get_model_name_map(flat_models) model_name = model_name_map[model] m_schema, m_definitions, nested_models = model_process_schema( model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix ) if model_name in nested_models: # model_name is in Nested models, it has circular references m_definitions[model_name] = m_schema m_schema = {'$ref': ref_prefix + model_name} if m_definitions: m_schema.update({'definitions': m_definitions}) return m_schema def field_schema( field: ModelField, *, by_alias: bool = True, model_name_map: Dict[TypeModelOrEnum, str], ref_prefix: Optional[str] = None, known_models: TypeModelSet = None, ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: """ Process a Pydantic field and return a tuple with a JSON Schema for it as the first item. Also return a dictionary of definitions with models as keys and their schemas as values. If the passed field is a model and has sub-models, and those sub-models don't have overrides (as ``title``, ``default``, etc), they will be included in the definitions and referenced in the schema instead of included recursively. :param field: a Pydantic ``ModelField`` :param by_alias: use the defined alias (if any) in the returned schema :param model_name_map: used to generate the JSON Schema references to other models included in the definitions :param ref_prefix: the JSON Pointer prefix to use for references to other schemas, if None, the default of #/definitions/ will be used :param known_models: used to solve circular references :return: tuple of the schema for this field and additional definitions """ ref_prefix = ref_prefix or default_prefix schema_overrides = False s = dict(title=field.field_info.title or field.alias.title().replace('_', ' ')) if field.field_info.title: schema_overrides = True if field.field_info.description: s['description'] = field.field_info.description schema_overrides = True if not field.required and not field.field_info.const and field.default is not None: s['default'] = encode_default(field.default) schema_overrides = True validation_schema = get_field_schema_validations(field) if validation_schema: s.update(validation_schema) schema_overrides = True f_schema, f_definitions, f_nested_models = field_type_schema( field, by_alias=by_alias, model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, known_models=known_models or set(), ) # $ref will only be returned when there are no schema_overrides if '$ref' in f_schema: return f_schema, f_definitions, f_nested_models else: s.update(f_schema) return s, f_definitions, f_nested_models numeric_types = (int, float, Decimal) _str_types_attrs: Tuple[Tuple[str, Union[type, Tuple[type, ...]], str], ...] = ( ('max_length', numeric_types, 'maxLength'), ('min_length', numeric_types, 'minLength'), ('regex', str, 'pattern'), ) _numeric_types_attrs: Tuple[Tuple[str, Union[type, Tuple[type, ...]], str], ...] = ( ('gt', numeric_types, 'exclusiveMinimum'), ('lt', numeric_types, 'exclusiveMaximum'), ('ge', numeric_types, 'minimum'), ('le', numeric_types, 'maximum'), ('multiple_of', numeric_types, 'multipleOf'), ) def get_field_schema_validations(field: ModelField) -> Dict[str, Any]: """ Get the JSON Schema validation keywords for a ``field`` with an annotation of a Pydantic ``FieldInfo`` with validation arguments. """ f_schema: Dict[str, Any] = {} if lenient_issubclass(field.type_, (str, bytes)): for attr_name, t, keyword in _str_types_attrs: attr = getattr(field.field_info, attr_name, None) if isinstance(attr, t): f_schema[keyword] = attr if lenient_issubclass(field.type_, numeric_types) and not issubclass(field.type_, bool): for attr_name, t, keyword in _numeric_types_attrs: attr = getattr(field.field_info, attr_name, None) if isinstance(attr, t): f_schema[keyword] = attr if field.field_info is not None and field.field_info.const: f_schema['const'] = field.default if field.field_info.extra: f_schema.update(field.field_info.extra) modify_schema = getattr(field.outer_type_, '__modify_schema__', None) if modify_schema: modify_schema(f_schema) return f_schema def get_model_name_map(unique_models: TypeModelSet) -> Dict[TypeModelOrEnum, str]: """ Process a set of models and generate unique names for them to be used as keys in the JSON Schema definitions. By default the names are the same as the class name. But if two models in different Python modules have the same name (e.g. "users.Model" and "items.Model"), the generated names will be based on the Python module path for those conflicting models to prevent name collisions. :param unique_models: a Python set of models :return: dict mapping models to names """ name_model_map = {} conflicting_names: Set[str] = set() for model in unique_models: model_name = normalize_name(model.__name__) if model_name in conflicting_names: model_name = get_long_model_name(model) name_model_map[model_name] = model elif model_name in name_model_map: conflicting_names.add(model_name) conflicting_model = name_model_map.pop(model_name) name_model_map[get_long_model_name(conflicting_model)] = conflicting_model name_model_map[get_long_model_name(model)] = model else: name_model_map[model_name] = model return {v: k for k, v in name_model_map.items()} def get_flat_models_from_model(model: Type['BaseModel'], known_models: TypeModelSet = None) -> TypeModelSet: """ Take a single ``model`` and generate a set with itself and all the sub-models in the tree. I.e. if you pass model ``Foo`` (subclass of Pydantic ``BaseModel``) as ``model``, and it has a field of type ``Bar`` (also subclass of ``BaseModel``) and that model ``Bar`` has a field of type ``Baz`` (also subclass of ``BaseModel``), the return value will be ``set([Foo, Bar, Baz])``. :param model: a Pydantic ``BaseModel`` subclass :param known_models: used to solve circular references :return: a set with the initial model and all its sub-models """ known_models = known_models or set() flat_models: TypeModelSet = set() flat_models.add(model) known_models |= flat_models fields = cast(Sequence[ModelField], model.__fields__.values()) flat_models |= get_flat_models_from_fields(fields, known_models=known_models) return flat_models def get_flat_models_from_field(field: ModelField, known_models: TypeModelSet) -> TypeModelSet: """ Take a single Pydantic ``ModelField`` (from a model) that could have been declared as a sublcass of BaseModel (so, it could be a submodel), and generate a set with its model and all the sub-models in the tree. I.e. if you pass a field that was declared to be of type ``Foo`` (subclass of BaseModel) as ``field``, and that model ``Foo`` has a field of type ``Bar`` (also subclass of ``BaseModel``) and that model ``Bar`` has a field of type ``Baz`` (also subclass of ``BaseModel``), the return value will be ``set([Foo, Bar, Baz])``. :param field: a Pydantic ``ModelField`` :param known_models: used to solve circular references :return: a set with the model used in the declaration for this field, if any, and all its sub-models """ from .main import BaseModel # noqa: F811 flat_models: TypeModelSet = set() # Handle dataclass-based models field_type = field.type_ if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), BaseModel): field_type = field_type.__pydantic_model__ if field.sub_fields: flat_models |= get_flat_models_from_fields(field.sub_fields, known_models=known_models) elif lenient_issubclass(field_type, BaseModel) and field_type not in known_models: flat_models |= get_flat_models_from_model(field_type, known_models=known_models) elif lenient_issubclass(field_type, Enum): flat_models.add(field_type) return flat_models def get_flat_models_from_fields(fields: Sequence[ModelField], known_models: TypeModelSet) -> TypeModelSet: """ Take a list of Pydantic ``ModelField``s (from a model) that could have been declared as sublcasses of ``BaseModel`` (so, any of them could be a submodel), and generate a set with their models and all the sub-models in the tree. I.e. if you pass a the fields of a model ``Foo`` (subclass of ``BaseModel``) as ``fields``, and on of them has a field of type ``Bar`` (also subclass of ``BaseModel``) and that model ``Bar`` has a field of type ``Baz`` (also subclass of ``BaseModel``), the return value will be ``set([Foo, Bar, Baz])``. :param fields: a list of Pydantic ``ModelField``s :param known_models: used to solve circular references :return: a set with any model declared in the fields, and all their sub-models """ flat_models: TypeModelSet = set() for field in fields: flat_models |= get_flat_models_from_field(field, known_models=known_models) return flat_models def get_flat_models_from_models(models: Sequence[Type['BaseModel']]) -> TypeModelSet: """ Take a list of ``models`` and generate a set with them and all their sub-models in their trees. I.e. if you pass a list of two models, ``Foo`` and ``Bar``, both subclasses of Pydantic ``BaseModel`` as models, and ``Bar`` has a field of type ``Baz`` (also subclass of ``BaseModel``), the return value will be ``set([Foo, Bar, Baz])``. """ flat_models: TypeModelSet = set() for model in models: flat_models |= get_flat_models_from_model(model) return flat_models def get_long_model_name(model: TypeModelOrEnum) -> str: return f'{model.__module__}__{model.__name__}'.replace('.', '__') def field_type_schema( field: ModelField, *, by_alias: bool, model_name_map: Dict[TypeModelOrEnum, str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, known_models: TypeModelSet, ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: """ Used by ``field_schema()``, you probably should be using that function. Take a single ``field`` and generate the schema for its type only, not including additional information as title, etc. Also return additional schema definitions, from sub-models. """ definitions = {} nested_models: Set[str] = set() f_schema: Dict[str, Any] ref_prefix = ref_prefix or default_prefix if field.shape in {SHAPE_LIST, SHAPE_TUPLE_ELLIPSIS, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_FROZENSET, SHAPE_ITERABLE}: items_schema, f_definitions, f_nested_models = field_singleton_schema( field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) definitions.update(f_definitions) nested_models.update(f_nested_models) f_schema = {'type': 'array', 'items': items_schema} if field.shape in {SHAPE_SET, SHAPE_FROZENSET}: f_schema['uniqueItems'] = True elif field.shape == SHAPE_MAPPING: f_schema = {'type': 'object'} key_field = cast(ModelField, field.key_field) regex = getattr(key_field.type_, 'regex', None) items_schema, f_definitions, f_nested_models = field_singleton_schema( field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) definitions.update(f_definitions) nested_models.update(f_nested_models) if regex: # Dict keys have a regex pattern # items_schema might be a schema or empty dict, add it either way f_schema['patternProperties'] = {regex.pattern: items_schema} elif items_schema: # The dict values are not simply Any, so they need a schema f_schema['additionalProperties'] = items_schema elif field.shape == SHAPE_TUPLE: sub_schema = [] sub_fields = cast(List[ModelField], field.sub_fields) for sf in sub_fields: sf_schema, sf_definitions, sf_nested_models = field_type_schema( sf, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) definitions.update(sf_definitions) nested_models.update(sf_nested_models) sub_schema.append(sf_schema) if len(sub_schema) == 1: sub_schema = sub_schema[0] # type: ignore f_schema = {'type': 'array', 'items': sub_schema} else: assert field.shape == SHAPE_SINGLETON, field.shape f_schema, f_definitions, f_nested_models = field_singleton_schema( field, by_alias=by_alias, model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, known_models=known_models, ) definitions.update(f_definitions) nested_models.update(f_nested_models) # check field type to avoid repeated calls to the same __modify_schema__ method if field.type_ != field.outer_type_: modify_schema = getattr(field.outer_type_, '__modify_schema__', None) if modify_schema: modify_schema(f_schema) return f_schema, definitions, nested_models def model_process_schema( model: TypeModelOrEnum, *, by_alias: bool = True, model_name_map: Dict[TypeModelOrEnum, str], ref_prefix: Optional[str] = None, known_models: TypeModelSet = None, ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: """ Used by ``model_schema()``, you probably should be using that function. Take a single ``model`` and generate its schema. Also return additional schema definitions, from sub-models. The sub-models of the returned schema will be referenced, but their definitions will not be included in the schema. All the definitions are returned as the second value. """ from inspect import getdoc, signature ref_prefix = ref_prefix or default_prefix known_models = known_models or set() if lenient_issubclass(model, Enum): model = cast(Type[Enum], model) s = enum_process_schema(model) return s, {}, set() model = cast(Type['BaseModel'], model) s = {'title': model.__config__.title or model.__name__} doc = getdoc(model) if doc: s['description'] = doc known_models.add(model) m_schema, m_definitions, nested_models = model_type_schema( model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) s.update(m_schema) schema_extra = model.__config__.schema_extra if callable(schema_extra): if len(signature(schema_extra).parameters) == 1: schema_extra(s) else: schema_extra(s, model) else: s.update(schema_extra) return s, m_definitions, nested_models def model_type_schema( model: Type['BaseModel'], *, by_alias: bool, model_name_map: Dict[TypeModelOrEnum, str], ref_prefix: Optional[str] = None, known_models: TypeModelSet, ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: """ You probably should be using ``model_schema()``, this function is indirectly used by that function. Take a single ``model`` and generate the schema for its type only, not including additional information as title, etc. Also return additional schema definitions, from sub-models. """ ref_prefix = ref_prefix or default_prefix properties = {} required = [] definitions: Dict[str, Any] = {} nested_models: Set[str] = set() for k, f in model.__fields__.items(): try: f_schema, f_definitions, f_nested_models = field_schema( f, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) except SkipField as skip: warnings.warn(skip.message, UserWarning) continue definitions.update(f_definitions) nested_models.update(f_nested_models) if by_alias: properties[f.alias] = f_schema if f.required: required.append(f.alias) else: properties[k] = f_schema if f.required: required.append(k) if ROOT_KEY in properties: out_schema = properties[ROOT_KEY] out_schema['title'] = model.__config__.title or model.__name__ else: out_schema = {'type': 'object', 'properties': properties} if required: out_schema['required'] = required if model.__config__.extra == 'forbid': out_schema['additionalProperties'] = False return out_schema, definitions, nested_models def enum_process_schema(enum: Type[Enum]) -> Dict[str, Any]: """ Take a single `enum` and generate its schema. This is similar to the `model_process_schema` function, but applies to ``Enum`` objects. """ from inspect import getdoc schema: Dict[str, Any] = { 'title': enum.__name__, # Python assigns all enums a default docstring value of 'An enumeration', so # all enums will have a description field even if not explicitly provided. 'description': getdoc(enum), # Add enum values and the enum field type to the schema. 'enum': [item.value for item in cast(Iterable[Enum], enum)], } add_field_type_to_schema(enum, schema) modify_schema = getattr(enum, '__modify_schema__', None) if modify_schema: modify_schema(schema) return schema def field_singleton_sub_fields_schema( sub_fields: Sequence[ModelField], *, by_alias: bool, model_name_map: Dict[TypeModelOrEnum, str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, known_models: TypeModelSet, ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: """ This function is indirectly used by ``field_schema()``, you probably should be using that function. Take a list of Pydantic ``ModelField`` from the declaration of a type with parameters, and generate their schema. I.e., fields used as "type parameters", like ``str`` and ``int`` in ``Tuple[str, int]``. """ ref_prefix = ref_prefix or default_prefix definitions = {} nested_models: Set[str] = set() sub_fields = [sf for sf in sub_fields if sf.include_in_schema()] if len(sub_fields) == 1: return field_type_schema( sub_fields[0], by_alias=by_alias, model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, known_models=known_models, ) else: sub_field_schemas = [] for sf in sub_fields: sub_schema, sub_definitions, sub_nested_models = field_type_schema( sf, by_alias=by_alias, model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, known_models=known_models, ) definitions.update(sub_definitions) if schema_overrides and 'allOf' in sub_schema: # if the sub_field is a referenced schema we only need the referenced # object. Otherwise we will end up with several allOf inside anyOf. # See https://github.com/samuelcolvin/pydantic/issues/1209 sub_schema = sub_schema['allOf'][0] sub_field_schemas.append(sub_schema) nested_models.update(sub_nested_models) return {'anyOf': sub_field_schemas}, definitions, nested_models # Order is important, e.g. subclasses of str must go before str # this is used only for standard library types, custom types should use __modify_schema__ instead field_class_to_schema: Tuple[Tuple[Any, Dict[str, Any]], ...] = ( (Path, {'type': 'string', 'format': 'path'}), (datetime, {'type': 'string', 'format': 'date-time'}), (date, {'type': 'string', 'format': 'date'}), (time, {'type': 'string', 'format': 'time'}), (timedelta, {'type': 'number', 'format': 'time-delta'}), (IPv4Network, {'type': 'string', 'format': 'ipv4network'}), (IPv6Network, {'type': 'string', 'format': 'ipv6network'}), (IPv4Interface, {'type': 'string', 'format': 'ipv4interface'}), (IPv6Interface, {'type': 'string', 'format': 'ipv6interface'}), (IPv4Address, {'type': 'string', 'format': 'ipv4'}), (IPv6Address, {'type': 'string', 'format': 'ipv6'}), (str, {'type': 'string'}), (bytes, {'type': 'string', 'format': 'binary'}), (bool, {'type': 'boolean'}), (int, {'type': 'integer'}), (float, {'type': 'number'}), (Decimal, {'type': 'number'}), (UUID, {'type': 'string', 'format': 'uuid'}), (dict, {'type': 'object'}), (list, {'type': 'array', 'items': {}}), (tuple, {'type': 'array', 'items': {}}), (set, {'type': 'array', 'items': {}, 'uniqueItems': True}), (frozenset, {'type': 'array', 'items': {}, 'uniqueItems': True}), ) json_scheme = {'type': 'string', 'format': 'json-string'} def add_field_type_to_schema(field_type: Any, schema: Dict[str, Any]) -> None: """ Update the given `schema` with the type-specific metadata for the given `field_type`. This function looks through `field_class_to_schema` for a class that matches the given `field_type`, and then modifies the given `schema` with the information from that type. """ for type_, t_schema in field_class_to_schema: if issubclass(field_type, type_): schema.update(t_schema) break def field_singleton_schema( # noqa: C901 (ignore complexity) field: ModelField, *, by_alias: bool, model_name_map: Dict[TypeModelOrEnum, str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, known_models: TypeModelSet, ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: """ This function is indirectly used by ``field_schema()``, you should probably be using that function. Take a single Pydantic ``ModelField``, and return its schema and any additional definitions from sub-models. """ from .main import BaseModel # noqa: F811 ref_prefix = ref_prefix or default_prefix definitions: Dict[str, Any] = {} nested_models: Set[str] = set() if field.sub_fields: return field_singleton_sub_fields_schema( field.sub_fields, by_alias=by_alias, model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, known_models=known_models, ) if field.type_ is Any or field.type_.__class__ == TypeVar: return {}, definitions, nested_models # no restrictions if is_callable_type(field.type_): raise SkipField(f'Callable {field.name} was excluded from schema since JSON schema has no equivalent type.') f_schema: Dict[str, Any] = {} if field.field_info is not None and field.field_info.const: f_schema['const'] = field.default field_type = field.type_ if is_literal_type(field_type): values = literal_values(field_type) if len(values) > 1: return field_schema( multivalue_literal_field_for_schema(values, field), by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models, ) literal_value = values[0] field_type = literal_value.__class__ f_schema['const'] = literal_value if lenient_issubclass(field_type, Enum): enum_name = normalize_name(field_type.__name__) f_schema = {'$ref': ref_prefix + enum_name} definitions[enum_name] = enum_process_schema(field_type) else: add_field_type_to_schema(field_type, f_schema) modify_schema = getattr(field_type, '__modify_schema__', None) if modify_schema: modify_schema(f_schema) if f_schema: return f_schema, definitions, nested_models # Handle dataclass-based models if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), BaseModel): field_type = field_type.__pydantic_model__ if issubclass(field_type, BaseModel): model_name = model_name_map[field_type] if field_type not in known_models: sub_schema, sub_definitions, sub_nested_models = model_process_schema( field_type, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models, ) definitions.update(sub_definitions) definitions[model_name] = sub_schema nested_models.update(sub_nested_models) else: nested_models.add(model_name) schema_ref = {'$ref': ref_prefix + model_name} if not schema_overrides: return schema_ref, definitions, nested_models else: return {'allOf': [schema_ref]}, definitions, nested_models raise ValueError(f'Value not declarable with JSON Schema, field: {field}') def multivalue_literal_field_for_schema(values: Tuple[Any, ...], field: ModelField) -> ModelField: return ModelField( name=field.name, type_=Union[tuple(Literal[value] for value in values)], # type: ignore class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, field_info=field.field_info, ) def encode_default(dft: Any) -> Any: if isinstance(dft, (int, float, str)): return dft elif sequence_like(dft): t = dft.__class__ return t(encode_default(v) for v in dft) elif isinstance(dft, dict): return {encode_default(k): encode_default(v) for k, v in dft.items()} elif dft is None: return None else: return pydantic_encoder(dft) _map_types_constraint: Dict[Any, Callable[..., type]] = {int: conint, float: confloat, Decimal: condecimal} _field_constraints = { 'min_length', 'max_length', 'regex', 'gt', 'lt', 'ge', 'le', 'multiple_of', 'min_items', 'max_items', } def get_annotation_from_field_info(annotation: Any, field_info: FieldInfo, field_name: str) -> Type[Any]: # noqa: C901 """ Get an annotation with validation implemented for numbers and strings based on the field_info. :param annotation: an annotation from a field specification, as ``str``, ``ConstrainedStr`` :param field_info: an instance of FieldInfo, possibly with declarations for validations and JSON Schema :param field_name: name of the field for use in error messages :return: the same ``annotation`` if unmodified or a new annotation with validation in place """ constraints = {f for f in _field_constraints if getattr(field_info, f) is not None} if not constraints: return annotation used_constraints: Set[str] = set() def go(type_: Any) -> Type[Any]: if ( is_literal_type(annotation) or isinstance(type_, ForwardRef) or lenient_issubclass(type_, (ConstrainedList, ConstrainedSet)) ): return type_ origin = getattr(type_, '__origin__', None) if origin is not None: args: Tuple[Any, ...] = type_.__args__ if any(isinstance(a, ForwardRef) for a in args): # forward refs cause infinite recursion below return type_ if origin is Union: return Union[tuple(go(a) for a in args)] # type: ignore if issubclass(origin, List) and (field_info.min_items is not None or field_info.max_items is not None): used_constraints.update({'min_items', 'max_items'}) return conlist(go(args[0]), min_items=field_info.min_items, max_items=field_info.max_items) if issubclass(origin, Set) and (field_info.min_items is not None or field_info.max_items is not None): used_constraints.update({'min_items', 'max_items'}) return conset(go(args[0]), min_items=field_info.min_items, max_items=field_info.max_items) for t in (Tuple, List, Set, FrozenSet, Sequence): if issubclass(origin, t): # type: ignore return t[tuple(go(a) for a in args)] # type: ignore if issubclass(origin, Dict): return Dict[args[0], go(args[1])] # type: ignore attrs: Optional[Tuple[str, ...]] = None constraint_func: Optional[Callable[..., type]] = None if isinstance(type_, type): if issubclass(type_, str) and not issubclass(type_, (EmailStr, AnyUrl, ConstrainedStr)): attrs = ('max_length', 'min_length', 'regex') constraint_func = constr elif issubclass(type_, bytes): attrs = ('max_length', 'min_length', 'regex') constraint_func = conbytes elif issubclass(type_, numeric_types) and not issubclass( type_, (ConstrainedInt, ConstrainedFloat, ConstrainedDecimal, ConstrainedList, ConstrainedSet, bool) ): # Is numeric type attrs = ('gt', 'lt', 'ge', 'le', 'multiple_of') numeric_type = next(t for t in numeric_types if issubclass(type_, t)) # pragma: no branch constraint_func = _map_types_constraint[numeric_type] if attrs: used_constraints.update(set(attrs)) kwargs = { attr_name: attr for attr_name, attr in ((attr_name, getattr(field_info, attr_name)) for attr_name in attrs) if attr is not None } if kwargs: constraint_func = cast(Callable[..., type], constraint_func) return constraint_func(**kwargs) return type_ ans = go(annotation) unused_constraints = constraints - used_constraints if unused_constraints: raise ValueError( f'On field "{field_name}" the following field constraints are set but not enforced: ' f'{", ".join(unused_constraints)}. ' f'\nFor more details see https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints' ) return ans def normalize_name(name: str) -> str: """ Normalizes the given name. This can be applied to either a model *or* enum. """ return re.sub(r'[^a-zA-Z0-9.\-_]', '_', name) class SkipField(Exception): """ Utility exception used to exclude fields from schema. """ def __init__(self, message: str) -> None: self.message = message
40.838782
120
0.665443
import re import warnings from datetime import date, datetime, time, timedelta from decimal import Decimal from enum import Enum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path from typing import ( TYPE_CHECKING, Any, Callable, Dict, FrozenSet, Iterable, List, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, cast, ) from uuid import UUID from .class_validators import ROOT_KEY from .fields import ( SHAPE_FROZENSET, SHAPE_ITERABLE, SHAPE_LIST, SHAPE_MAPPING, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, FieldInfo, ModelField, ) from .json import pydantic_encoder from .networks import AnyUrl, EmailStr from .types import ( ConstrainedDecimal, ConstrainedFloat, ConstrainedInt, ConstrainedList, ConstrainedSet, ConstrainedStr, conbytes, condecimal, confloat, conint, conlist, conset, constr, ) from .typing import ForwardRef, Literal, is_callable_type, is_literal_type, literal_values from .utils import get_model, lenient_issubclass, sequence_like if TYPE_CHECKING: from .main import BaseModel from .dataclasses import DataclassType default_prefix = '#/definitions/' TypeModelOrEnum = Union[Type['BaseModel'], Type[Enum]] TypeModelSet = Set[TypeModelOrEnum] def schema( models: Sequence[Union[Type['BaseModel'], Type['DataclassType']]], *, by_alias: bool = True, title: Optional[str] = None, description: Optional[str] = None, ref_prefix: Optional[str] = None, ) -> Dict[str, Any]: clean_models = [get_model(model) for model in models] ref_prefix = ref_prefix or default_prefix flat_models = get_flat_models_from_models(clean_models) model_name_map = get_model_name_map(flat_models) definitions = {} output_schema: Dict[str, Any] = {} if title: output_schema['title'] = title if description: output_schema['description'] = description for model in clean_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema if definitions: output_schema['definitions'] = definitions return output_schema def model_schema( model: Union[Type['BaseModel'], Type['DataclassType']], by_alias: bool = True, ref_prefix: Optional[str] = None ) -> Dict[str, Any]: model = get_model(model) ref_prefix = ref_prefix or default_prefix flat_models = get_flat_models_from_model(model) model_name_map = get_model_name_map(flat_models) model_name = model_name_map[model] m_schema, m_definitions, nested_models = model_process_schema( model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix ) if model_name in nested_models: m_definitions[model_name] = m_schema m_schema = {'$ref': ref_prefix + model_name} if m_definitions: m_schema.update({'definitions': m_definitions}) return m_schema def field_schema( field: ModelField, *, by_alias: bool = True, model_name_map: Dict[TypeModelOrEnum, str], ref_prefix: Optional[str] = None, known_models: TypeModelSet = None, ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: ref_prefix = ref_prefix or default_prefix schema_overrides = False s = dict(title=field.field_info.title or field.alias.title().replace('_', ' ')) if field.field_info.title: schema_overrides = True if field.field_info.description: s['description'] = field.field_info.description schema_overrides = True if not field.required and not field.field_info.const and field.default is not None: s['default'] = encode_default(field.default) schema_overrides = True validation_schema = get_field_schema_validations(field) if validation_schema: s.update(validation_schema) schema_overrides = True f_schema, f_definitions, f_nested_models = field_type_schema( field, by_alias=by_alias, model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, known_models=known_models or set(), ) if '$ref' in f_schema: return f_schema, f_definitions, f_nested_models else: s.update(f_schema) return s, f_definitions, f_nested_models numeric_types = (int, float, Decimal) _str_types_attrs: Tuple[Tuple[str, Union[type, Tuple[type, ...]], str], ...] = ( ('max_length', numeric_types, 'maxLength'), ('min_length', numeric_types, 'minLength'), ('regex', str, 'pattern'), ) _numeric_types_attrs: Tuple[Tuple[str, Union[type, Tuple[type, ...]], str], ...] = ( ('gt', numeric_types, 'exclusiveMinimum'), ('lt', numeric_types, 'exclusiveMaximum'), ('ge', numeric_types, 'minimum'), ('le', numeric_types, 'maximum'), ('multiple_of', numeric_types, 'multipleOf'), ) def get_field_schema_validations(field: ModelField) -> Dict[str, Any]: f_schema: Dict[str, Any] = {} if lenient_issubclass(field.type_, (str, bytes)): for attr_name, t, keyword in _str_types_attrs: attr = getattr(field.field_info, attr_name, None) if isinstance(attr, t): f_schema[keyword] = attr if lenient_issubclass(field.type_, numeric_types) and not issubclass(field.type_, bool): for attr_name, t, keyword in _numeric_types_attrs: attr = getattr(field.field_info, attr_name, None) if isinstance(attr, t): f_schema[keyword] = attr if field.field_info is not None and field.field_info.const: f_schema['const'] = field.default if field.field_info.extra: f_schema.update(field.field_info.extra) modify_schema = getattr(field.outer_type_, '__modify_schema__', None) if modify_schema: modify_schema(f_schema) return f_schema def get_model_name_map(unique_models: TypeModelSet) -> Dict[TypeModelOrEnum, str]: name_model_map = {} conflicting_names: Set[str] = set() for model in unique_models: model_name = normalize_name(model.__name__) if model_name in conflicting_names: model_name = get_long_model_name(model) name_model_map[model_name] = model elif model_name in name_model_map: conflicting_names.add(model_name) conflicting_model = name_model_map.pop(model_name) name_model_map[get_long_model_name(conflicting_model)] = conflicting_model name_model_map[get_long_model_name(model)] = model else: name_model_map[model_name] = model return {v: k for k, v in name_model_map.items()} def get_flat_models_from_model(model: Type['BaseModel'], known_models: TypeModelSet = None) -> TypeModelSet: known_models = known_models or set() flat_models: TypeModelSet = set() flat_models.add(model) known_models |= flat_models fields = cast(Sequence[ModelField], model.__fields__.values()) flat_models |= get_flat_models_from_fields(fields, known_models=known_models) return flat_models def get_flat_models_from_field(field: ModelField, known_models: TypeModelSet) -> TypeModelSet: from .main import BaseModel flat_models: TypeModelSet = set() field_type = field.type_ if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), BaseModel): field_type = field_type.__pydantic_model__ if field.sub_fields: flat_models |= get_flat_models_from_fields(field.sub_fields, known_models=known_models) elif lenient_issubclass(field_type, BaseModel) and field_type not in known_models: flat_models |= get_flat_models_from_model(field_type, known_models=known_models) elif lenient_issubclass(field_type, Enum): flat_models.add(field_type) return flat_models def get_flat_models_from_fields(fields: Sequence[ModelField], known_models: TypeModelSet) -> TypeModelSet: flat_models: TypeModelSet = set() for field in fields: flat_models |= get_flat_models_from_field(field, known_models=known_models) return flat_models def get_flat_models_from_models(models: Sequence[Type['BaseModel']]) -> TypeModelSet: flat_models: TypeModelSet = set() for model in models: flat_models |= get_flat_models_from_model(model) return flat_models def get_long_model_name(model: TypeModelOrEnum) -> str: return f'{model.__module__}__{model.__name__}'.replace('.', '__') def field_type_schema( field: ModelField, *, by_alias: bool, model_name_map: Dict[TypeModelOrEnum, str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, known_models: TypeModelSet, ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: definitions = {} nested_models: Set[str] = set() f_schema: Dict[str, Any] ref_prefix = ref_prefix or default_prefix if field.shape in {SHAPE_LIST, SHAPE_TUPLE_ELLIPSIS, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_FROZENSET, SHAPE_ITERABLE}: items_schema, f_definitions, f_nested_models = field_singleton_schema( field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) definitions.update(f_definitions) nested_models.update(f_nested_models) f_schema = {'type': 'array', 'items': items_schema} if field.shape in {SHAPE_SET, SHAPE_FROZENSET}: f_schema['uniqueItems'] = True elif field.shape == SHAPE_MAPPING: f_schema = {'type': 'object'} key_field = cast(ModelField, field.key_field) regex = getattr(key_field.type_, 'regex', None) items_schema, f_definitions, f_nested_models = field_singleton_schema( field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) definitions.update(f_definitions) nested_models.update(f_nested_models) if regex: f_schema['patternProperties'] = {regex.pattern: items_schema} elif items_schema: f_schema['additionalProperties'] = items_schema elif field.shape == SHAPE_TUPLE: sub_schema = [] sub_fields = cast(List[ModelField], field.sub_fields) for sf in sub_fields: sf_schema, sf_definitions, sf_nested_models = field_type_schema( sf, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) definitions.update(sf_definitions) nested_models.update(sf_nested_models) sub_schema.append(sf_schema) if len(sub_schema) == 1: sub_schema = sub_schema[0] f_schema = {'type': 'array', 'items': sub_schema} else: assert field.shape == SHAPE_SINGLETON, field.shape f_schema, f_definitions, f_nested_models = field_singleton_schema( field, by_alias=by_alias, model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, known_models=known_models, ) definitions.update(f_definitions) nested_models.update(f_nested_models) if field.type_ != field.outer_type_: modify_schema = getattr(field.outer_type_, '__modify_schema__', None) if modify_schema: modify_schema(f_schema) return f_schema, definitions, nested_models def model_process_schema( model: TypeModelOrEnum, *, by_alias: bool = True, model_name_map: Dict[TypeModelOrEnum, str], ref_prefix: Optional[str] = None, known_models: TypeModelSet = None, ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: from inspect import getdoc, signature ref_prefix = ref_prefix or default_prefix known_models = known_models or set() if lenient_issubclass(model, Enum): model = cast(Type[Enum], model) s = enum_process_schema(model) return s, {}, set() model = cast(Type['BaseModel'], model) s = {'title': model.__config__.title or model.__name__} doc = getdoc(model) if doc: s['description'] = doc known_models.add(model) m_schema, m_definitions, nested_models = model_type_schema( model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) s.update(m_schema) schema_extra = model.__config__.schema_extra if callable(schema_extra): if len(signature(schema_extra).parameters) == 1: schema_extra(s) else: schema_extra(s, model) else: s.update(schema_extra) return s, m_definitions, nested_models def model_type_schema( model: Type['BaseModel'], *, by_alias: bool, model_name_map: Dict[TypeModelOrEnum, str], ref_prefix: Optional[str] = None, known_models: TypeModelSet, ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: ref_prefix = ref_prefix or default_prefix properties = {} required = [] definitions: Dict[str, Any] = {} nested_models: Set[str] = set() for k, f in model.__fields__.items(): try: f_schema, f_definitions, f_nested_models = field_schema( f, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) except SkipField as skip: warnings.warn(skip.message, UserWarning) continue definitions.update(f_definitions) nested_models.update(f_nested_models) if by_alias: properties[f.alias] = f_schema if f.required: required.append(f.alias) else: properties[k] = f_schema if f.required: required.append(k) if ROOT_KEY in properties: out_schema = properties[ROOT_KEY] out_schema['title'] = model.__config__.title or model.__name__ else: out_schema = {'type': 'object', 'properties': properties} if required: out_schema['required'] = required if model.__config__.extra == 'forbid': out_schema['additionalProperties'] = False return out_schema, definitions, nested_models def enum_process_schema(enum: Type[Enum]) -> Dict[str, Any]: from inspect import getdoc schema: Dict[str, Any] = { 'title': enum.__name__, 'description': getdoc(enum), 'enum': [item.value for item in cast(Iterable[Enum], enum)], } add_field_type_to_schema(enum, schema) modify_schema = getattr(enum, '__modify_schema__', None) if modify_schema: modify_schema(schema) return schema def field_singleton_sub_fields_schema( sub_fields: Sequence[ModelField], *, by_alias: bool, model_name_map: Dict[TypeModelOrEnum, str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, known_models: TypeModelSet, ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: ref_prefix = ref_prefix or default_prefix definitions = {} nested_models: Set[str] = set() sub_fields = [sf for sf in sub_fields if sf.include_in_schema()] if len(sub_fields) == 1: return field_type_schema( sub_fields[0], by_alias=by_alias, model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, known_models=known_models, ) else: sub_field_schemas = [] for sf in sub_fields: sub_schema, sub_definitions, sub_nested_models = field_type_schema( sf, by_alias=by_alias, model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, known_models=known_models, ) definitions.update(sub_definitions) if schema_overrides and 'allOf' in sub_schema: sub_schema = sub_schema['allOf'][0] sub_field_schemas.append(sub_schema) nested_models.update(sub_nested_models) return {'anyOf': sub_field_schemas}, definitions, nested_models field_class_to_schema: Tuple[Tuple[Any, Dict[str, Any]], ...] = ( (Path, {'type': 'string', 'format': 'path'}), (datetime, {'type': 'string', 'format': 'date-time'}), (date, {'type': 'string', 'format': 'date'}), (time, {'type': 'string', 'format': 'time'}), (timedelta, {'type': 'number', 'format': 'time-delta'}), (IPv4Network, {'type': 'string', 'format': 'ipv4network'}), (IPv6Network, {'type': 'string', 'format': 'ipv6network'}), (IPv4Interface, {'type': 'string', 'format': 'ipv4interface'}), (IPv6Interface, {'type': 'string', 'format': 'ipv6interface'}), (IPv4Address, {'type': 'string', 'format': 'ipv4'}), (IPv6Address, {'type': 'string', 'format': 'ipv6'}), (str, {'type': 'string'}), (bytes, {'type': 'string', 'format': 'binary'}), (bool, {'type': 'boolean'}), (int, {'type': 'integer'}), (float, {'type': 'number'}), (Decimal, {'type': 'number'}), (UUID, {'type': 'string', 'format': 'uuid'}), (dict, {'type': 'object'}), (list, {'type': 'array', 'items': {}}), (tuple, {'type': 'array', 'items': {}}), (set, {'type': 'array', 'items': {}, 'uniqueItems': True}), (frozenset, {'type': 'array', 'items': {}, 'uniqueItems': True}), ) json_scheme = {'type': 'string', 'format': 'json-string'} def add_field_type_to_schema(field_type: Any, schema: Dict[str, Any]) -> None: for type_, t_schema in field_class_to_schema: if issubclass(field_type, type_): schema.update(t_schema) break def field_singleton_schema( field: ModelField, *, by_alias: bool, model_name_map: Dict[TypeModelOrEnum, str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, known_models: TypeModelSet, ) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: from .main import BaseModel ref_prefix = ref_prefix or default_prefix definitions: Dict[str, Any] = {} nested_models: Set[str] = set() if field.sub_fields: return field_singleton_sub_fields_schema( field.sub_fields, by_alias=by_alias, model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, known_models=known_models, ) if field.type_ is Any or field.type_.__class__ == TypeVar: return {}, definitions, nested_models if is_callable_type(field.type_): raise SkipField(f'Callable {field.name} was excluded from schema since JSON schema has no equivalent type.') f_schema: Dict[str, Any] = {} if field.field_info is not None and field.field_info.const: f_schema['const'] = field.default field_type = field.type_ if is_literal_type(field_type): values = literal_values(field_type) if len(values) > 1: return field_schema( multivalue_literal_field_for_schema(values, field), by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models, ) literal_value = values[0] field_type = literal_value.__class__ f_schema['const'] = literal_value if lenient_issubclass(field_type, Enum): enum_name = normalize_name(field_type.__name__) f_schema = {'$ref': ref_prefix + enum_name} definitions[enum_name] = enum_process_schema(field_type) else: add_field_type_to_schema(field_type, f_schema) modify_schema = getattr(field_type, '__modify_schema__', None) if modify_schema: modify_schema(f_schema) if f_schema: return f_schema, definitions, nested_models if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), BaseModel): field_type = field_type.__pydantic_model__ if issubclass(field_type, BaseModel): model_name = model_name_map[field_type] if field_type not in known_models: sub_schema, sub_definitions, sub_nested_models = model_process_schema( field_type, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models, ) definitions.update(sub_definitions) definitions[model_name] = sub_schema nested_models.update(sub_nested_models) else: nested_models.add(model_name) schema_ref = {'$ref': ref_prefix + model_name} if not schema_overrides: return schema_ref, definitions, nested_models else: return {'allOf': [schema_ref]}, definitions, nested_models raise ValueError(f'Value not declarable with JSON Schema, field: {field}') def multivalue_literal_field_for_schema(values: Tuple[Any, ...], field: ModelField) -> ModelField: return ModelField( name=field.name, type_=Union[tuple(Literal[value] for value in values)], class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, field_info=field.field_info, ) def encode_default(dft: Any) -> Any: if isinstance(dft, (int, float, str)): return dft elif sequence_like(dft): t = dft.__class__ return t(encode_default(v) for v in dft) elif isinstance(dft, dict): return {encode_default(k): encode_default(v) for k, v in dft.items()} elif dft is None: return None else: return pydantic_encoder(dft) _map_types_constraint: Dict[Any, Callable[..., type]] = {int: conint, float: confloat, Decimal: condecimal} _field_constraints = { 'min_length', 'max_length', 'regex', 'gt', 'lt', 'ge', 'le', 'multiple_of', 'min_items', 'max_items', } def get_annotation_from_field_info(annotation: Any, field_info: FieldInfo, field_name: str) -> Type[Any]: constraints = {f for f in _field_constraints if getattr(field_info, f) is not None} if not constraints: return annotation used_constraints: Set[str] = set() def go(type_: Any) -> Type[Any]: if ( is_literal_type(annotation) or isinstance(type_, ForwardRef) or lenient_issubclass(type_, (ConstrainedList, ConstrainedSet)) ): return type_ origin = getattr(type_, '__origin__', None) if origin is not None: args: Tuple[Any, ...] = type_.__args__ if any(isinstance(a, ForwardRef) for a in args): return type_ if origin is Union: return Union[tuple(go(a) for a in args)] if issubclass(origin, List) and (field_info.min_items is not None or field_info.max_items is not None): used_constraints.update({'min_items', 'max_items'}) return conlist(go(args[0]), min_items=field_info.min_items, max_items=field_info.max_items) if issubclass(origin, Set) and (field_info.min_items is not None or field_info.max_items is not None): used_constraints.update({'min_items', 'max_items'}) return conset(go(args[0]), min_items=field_info.min_items, max_items=field_info.max_items) for t in (Tuple, List, Set, FrozenSet, Sequence): if issubclass(origin, t): return t[tuple(go(a) for a in args)] if issubclass(origin, Dict): return Dict[args[0], go(args[1])] attrs: Optional[Tuple[str, ...]] = None constraint_func: Optional[Callable[..., type]] = None if isinstance(type_, type): if issubclass(type_, str) and not issubclass(type_, (EmailStr, AnyUrl, ConstrainedStr)): attrs = ('max_length', 'min_length', 'regex') constraint_func = constr elif issubclass(type_, bytes): attrs = ('max_length', 'min_length', 'regex') constraint_func = conbytes elif issubclass(type_, numeric_types) and not issubclass( type_, (ConstrainedInt, ConstrainedFloat, ConstrainedDecimal, ConstrainedList, ConstrainedSet, bool) ): attrs = ('gt', 'lt', 'ge', 'le', 'multiple_of') numeric_type = next(t for t in numeric_types if issubclass(type_, t)) constraint_func = _map_types_constraint[numeric_type] if attrs: used_constraints.update(set(attrs)) kwargs = { attr_name: attr for attr_name, attr in ((attr_name, getattr(field_info, attr_name)) for attr_name in attrs) if attr is not None } if kwargs: constraint_func = cast(Callable[..., type], constraint_func) return constraint_func(**kwargs) return type_ ans = go(annotation) unused_constraints = constraints - used_constraints if unused_constraints: raise ValueError( f'On field "{field_name}" the following field constraints are set but not enforced: ' f'{", ".join(unused_constraints)}. ' f'\nFor more details see https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints' ) return ans def normalize_name(name: str) -> str: return re.sub(r'[^a-zA-Z0-9.\-_]', '_', name) class SkipField(Exception): def __init__(self, message: str) -> None: self.message = message
true
true
1c2bed8c36105c3c4609fb84bceed7998b51d8e0
2,945
py
Python
cinder/tests/api/contrib/test_availability_zones.py
cloudbau/cinder
3179f2f42ae940a08b910e326a809556689864d8
[ "Apache-2.0" ]
1
2015-11-25T10:18:28.000Z
2015-11-25T10:18:28.000Z
cinder/tests/api/contrib/test_availability_zones.py
NeCTAR-RC/cinder
e01da23febc530de218ed8eed6737add150c1587
[ "Apache-2.0" ]
null
null
null
cinder/tests/api/contrib/test_availability_zones.py
NeCTAR-RC/cinder
e01da23febc530de218ed8eed6737add150c1587
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import datetime from lxml import etree import cinder.api.contrib.availability_zones import cinder.context from cinder.openstack.common import timeutils import cinder.test import cinder.volume.api created_time = datetime.datetime(2012, 11, 14, 1, 20, 41, 95099) current_time = timeutils.utcnow() def list_availability_zones(self): return ( {'name': 'ping', 'available': True}, {'name': 'pong', 'available': False}, ) class FakeRequest(object): environ = {'cinder.context': cinder.context.get_admin_context()} GET = {} class ControllerTestCase(cinder.test.TestCase): def setUp(self): super(ControllerTestCase, self).setUp() self.controller = cinder.api.contrib.availability_zones.Controller() self.req = FakeRequest() self.stubs.Set(cinder.volume.api.API, 'list_availability_zones', list_availability_zones) def test_list_hosts(self): """Verify that the volume hosts are returned.""" actual = self.controller.index(self.req) expected = { 'availabilityZoneInfo': [ {'zoneName': 'ping', 'zoneState': {'available': True}}, {'zoneName': 'pong', 'zoneState': {'available': False}}, ], } self.assertEqual(expected, actual) class XMLSerializerTest(cinder.test.TestCase): def test_index_xml(self): fixture = { 'availabilityZoneInfo': [ {'zoneName': 'ping', 'zoneState': {'available': True}}, {'zoneName': 'pong', 'zoneState': {'available': False}}, ], } serializer = cinder.api.contrib.availability_zones.ListTemplate() text = serializer.serialize(fixture) tree = etree.fromstring(text) self.assertEqual('availabilityZones', tree.tag) self.assertEqual(2, len(tree)) self.assertEqual('availabilityZone', tree[0].tag) self.assertEqual('ping', tree[0].get('name')) self.assertEqual('zoneState', tree[0][0].tag) self.assertEqual('True', tree[0][0].get('available')) self.assertEqual('pong', tree[1].get('name')) self.assertEqual('zoneState', tree[1][0].tag) self.assertEqual('False', tree[1][0].get('available'))
32.362637
78
0.639728
import datetime from lxml import etree import cinder.api.contrib.availability_zones import cinder.context from cinder.openstack.common import timeutils import cinder.test import cinder.volume.api created_time = datetime.datetime(2012, 11, 14, 1, 20, 41, 95099) current_time = timeutils.utcnow() def list_availability_zones(self): return ( {'name': 'ping', 'available': True}, {'name': 'pong', 'available': False}, ) class FakeRequest(object): environ = {'cinder.context': cinder.context.get_admin_context()} GET = {} class ControllerTestCase(cinder.test.TestCase): def setUp(self): super(ControllerTestCase, self).setUp() self.controller = cinder.api.contrib.availability_zones.Controller() self.req = FakeRequest() self.stubs.Set(cinder.volume.api.API, 'list_availability_zones', list_availability_zones) def test_list_hosts(self): actual = self.controller.index(self.req) expected = { 'availabilityZoneInfo': [ {'zoneName': 'ping', 'zoneState': {'available': True}}, {'zoneName': 'pong', 'zoneState': {'available': False}}, ], } self.assertEqual(expected, actual) class XMLSerializerTest(cinder.test.TestCase): def test_index_xml(self): fixture = { 'availabilityZoneInfo': [ {'zoneName': 'ping', 'zoneState': {'available': True}}, {'zoneName': 'pong', 'zoneState': {'available': False}}, ], } serializer = cinder.api.contrib.availability_zones.ListTemplate() text = serializer.serialize(fixture) tree = etree.fromstring(text) self.assertEqual('availabilityZones', tree.tag) self.assertEqual(2, len(tree)) self.assertEqual('availabilityZone', tree[0].tag) self.assertEqual('ping', tree[0].get('name')) self.assertEqual('zoneState', tree[0][0].tag) self.assertEqual('True', tree[0][0].get('available')) self.assertEqual('pong', tree[1].get('name')) self.assertEqual('zoneState', tree[1][0].tag) self.assertEqual('False', tree[1][0].get('available'))
true
true
1c2bed98a4878cd82b3abdfca2bc12690e5daeec
910
py
Python
modulo 2/d068/par_impar_v2.py
rafa-evangelista/PYTHON
761ec7e01f1617263bc023a6b82b599a936275ee
[ "MIT" ]
null
null
null
modulo 2/d068/par_impar_v2.py
rafa-evangelista/PYTHON
761ec7e01f1617263bc023a6b82b599a936275ee
[ "MIT" ]
null
null
null
modulo 2/d068/par_impar_v2.py
rafa-evangelista/PYTHON
761ec7e01f1617263bc023a6b82b599a936275ee
[ "MIT" ]
null
null
null
from random import randint print('.'*35) print('PAR OU ÍMPAR') print('.'*35) soma = 0 while True: minha_escolha = '' while minha_escolha not in 'PI': minha_escolha = str( input('Você escolhe PAR ou ÍMPAR [P] ou [I]? ')).strip().upper()[0] if minha_escolha == 'P': escolha_computador = 'I' else: escolha_computador = 'P' comp = randint(1, 10) eu = int(input('Escolha um número: ')) resultado = (eu + comp) if resultado % 2 == 0: res_final = 'PAR' else: res_final = 'IMPAR' if res_final[0] == minha_escolha: soma += 1 print( f'O computador escolheu {comp} e você escolheu {eu}. Deu {res_final}. VOCÊ GANHOU!!!') else: print( f'O computador escolheu {comp} e você escolheu {eu}. Deu {res_final}. VOCÊ PERDEU!!!') break print(f'Você ganhou {soma} vez(es)!!!')
29.354839
98
0.562637
from random import randint print('.'*35) print('PAR OU ÍMPAR') print('.'*35) soma = 0 while True: minha_escolha = '' while minha_escolha not in 'PI': minha_escolha = str( input('Você escolhe PAR ou ÍMPAR [P] ou [I]? ')).strip().upper()[0] if minha_escolha == 'P': escolha_computador = 'I' else: escolha_computador = 'P' comp = randint(1, 10) eu = int(input('Escolha um número: ')) resultado = (eu + comp) if resultado % 2 == 0: res_final = 'PAR' else: res_final = 'IMPAR' if res_final[0] == minha_escolha: soma += 1 print( f'O computador escolheu {comp} e você escolheu {eu}. Deu {res_final}. VOCÊ GANHOU!!!') else: print( f'O computador escolheu {comp} e você escolheu {eu}. Deu {res_final}. VOCÊ PERDEU!!!') break print(f'Você ganhou {soma} vez(es)!!!')
true
true
1c2bee4abdea0305d9da67ec0e87f6ee51bf00a1
19,713
py
Python
src/vnsw/opencontrail-vrouter-netns/opencontrail_vrouter_netns/vrouter_netns.py
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
null
null
null
src/vnsw/opencontrail-vrouter-netns/opencontrail_vrouter_netns/vrouter_netns.py
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
null
null
null
src/vnsw/opencontrail-vrouter-netns/opencontrail_vrouter_netns/vrouter_netns.py
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
null
null
null
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2014 Cloudwatt # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # @author: Edouard Thuleau, Cloudwatt. """ Script to start or destroy a Linux network namespace plug between two virtual networks. Such that an application can be executed under the context of a virtualized network. """ from __future__ import print_function __docformat__ = "restructuredtext en" import argparse import netaddr import sys import uuid import subprocess import requests import json import os import shlex from linux import ip_lib import haproxy_process def validate_uuid(val): try: if str(uuid.UUID(val)) == val: return val except (TypeError, ValueError, AttributeError): raise ValueError('Invalid UUID format') class NetnsManager(object): SNAT_RT_TABLES_ID = 42 DEV_NAME_LEN = 14 NETNS_PREFIX = 'vrouter-' LEFT_DEV_PREFIX = 'int-' RIGH_DEV_PREFIX = 'gw-' TAP_PREFIX = 'veth' PORT_TYPE = 'NameSpacePort' BASE_URL = "http://localhost:9091/port" HEADERS = {'content-type': 'application/json'} LBAAS_DIR = "/var/lib/contrail/loadbalancer" def __init__(self, vm_uuid, nic_left, nic_right, other_nics=None, root_helper='sudo', cfg_file=None, update=False, pool_id=None, gw_ip=None, namespace_name=None, keystone_auth_cfg_file=None, loadbalancer_id=None): self.vm_uuid = vm_uuid if namespace_name is None: self.namespace = self.NETNS_PREFIX + self.vm_uuid else: self.namespace = namespace_name if pool_id: self.namespace = self.namespace + ":" + pool_id elif loadbalancer_id: self.namespace = self.namespace + ":" + loadbalancer_id self.nic_left = nic_left self.nic_right = nic_right self.root_helper = root_helper self.nics = other_nics or [] if self.nic_left: self.nic_left['name'] = (self.LEFT_DEV_PREFIX + self.nic_left['uuid'])[:self.DEV_NAME_LEN] self.nics.append(self.nic_left) if self.nic_right: self.nic_right['name'] = (self.RIGH_DEV_PREFIX + self.nic_right['uuid'])[:self.DEV_NAME_LEN] self.nics.append(self.nic_right) self.ip_ns = ip_lib.IPWrapper(root_helper=self.root_helper, namespace=self.namespace) self.cfg_file = cfg_file self.update = update self.gw_ip = gw_ip self.loadbalancer_id = loadbalancer_id self.keystone_auth_cfg_file = keystone_auth_cfg_file def _get_tap_name(self, uuid_str): return (self.TAP_PREFIX + uuid_str)[:self.DEV_NAME_LEN] def is_netns_already_exists(self): return self.ip_ns.netns.exists(self.namespace) def create(self): ip = ip_lib.IPWrapper(self.root_helper) ip.ensure_namespace(self.namespace) for nic in self.nics: self._create_interfaces(ip, nic) def set_snat(self): if not self.ip_ns.netns.exists(self.namespace): self.create() self.ip_ns.netns.execute(['sysctl', '-w', 'net.ipv4.ip_forward=1']) self.ip_ns.netns.execute(['iptables', '-t', 'nat', '-F']) self.ip_ns.netns.execute(['iptables', '-t', 'nat', '-A', 'POSTROUTING', '-s', '0.0.0.0/0', '-o', self.nic_right['name'], '-j', 'MASQUERADE']) self.ip_ns.netns.execute(['ip', 'route', 'replace', 'default', 'dev', self.nic_right['name']]) self.ip_ns.netns.execute(['ip', 'route', 'replace', 'default', 'dev', self.nic_left['name'], 'table', self.SNAT_RT_TABLES_ID]) try: self.ip_ns.netns.execute(['ip', 'rule', 'del', 'iif', str(self.nic_right['name']), 'table', self.SNAT_RT_TABLES_ID]) except RuntimeError: pass self.ip_ns.netns.execute(['ip', 'rule', 'add', 'iif', str(self.nic_right['name']), 'table', self.SNAT_RT_TABLES_ID]) self.ip_ns.netns.execute(['ip', 'route', 'del', 'default', 'table', self.SNAT_RT_TABLES_ID]) self.ip_ns.netns.execute(['ip', 'route', 'add', 'default', 'table', self.SNAT_RT_TABLES_ID, 'via', self.gw_ip, 'dev', str(self.nic_left['name'])]) def find_lbaas_type(self, cfg_file): lbaas_type = ''; if not os.path.exists(cfg_file): return lbaas_type f = open(cfg_file) content = f.read() f.close() kvps = content.split(':::::') for kvp in kvps or []: lbaas_type = kvp.split('::::')[0] if (lbaas_type == 'haproxy_config'): break; return lbaas_type def move_cfg_file_to_lbaas_dir(self, cfg_file): dir_name = self.LBAAS_DIR; if not os.path.exists(dir_name): cmd = "mkdir -p " + dir_name cmd_list = shlex.split(cmd) p = subprocess.Popen(cmd_list) p.communicate() cmd = "mv " + cfg_file + " " + dir_name cmd_list = shlex.split(cmd) p = subprocess.Popen(cmd_list) p.communicate(); return dir_name + '/' + os.path.basename(cfg_file) def remove_cfg_file(self, cfg_file): cmd = "rm " + cfg_file cmd_list = shlex.split(cmd) p = subprocess.Popen(cmd_list) p.communicate() def set_lbaas(self): if not self.ip_ns.netns.exists(self.namespace): self.create() lbaas_type = self.find_lbaas_type(self.cfg_file) if (lbaas_type == ''): raise ValueError('LBAAS_TYPE does not exist %s' % self.cfg_file) self.cfg_file = self.move_cfg_file_to_lbaas_dir(self.cfg_file) if (lbaas_type == 'haproxy_config'): haproxy_process.start_update_haproxy(self.loadbalancer_id, self.cfg_file, self.namespace, True, self.keystone_auth_cfg_file) try: self.ip_ns.netns.execute(['route', 'add', 'default', 'gw', self.gw_ip]) except RuntimeError: pass def release_lbaas(self): if not self.ip_ns.netns.exists(self.namespace): raise ValueError('Need to create the network namespace before ' 'relasing lbaas') cfg_file = self.LBAAS_DIR + "/" + self.loadbalancer_id + ".conf" lbaas_type = self.find_lbaas_type(cfg_file) if (lbaas_type == ''): return elif (lbaas_type == 'haproxy_config'): haproxy_process.stop_haproxy(self.loadbalancer_id, True) try: self.ip_ns.netns.execute(['route', 'del', 'default']) except RuntimeError: pass self.remove_cfg_file(cfg_file) def destroy(self): if not self.ip_ns.netns.exists(self.namespace): raise ValueError('Namespace %s does not exist' % self.namespace) for device in self.ip_ns.get_devices(exclude_loopback=True): ip_lib.IPDevice(device.name, self.root_helper, self.namespace).link.delete() self.ip_ns.netns.delete(self.namespace) def plug_namespace_interface(self): for nic in self.nics: self._add_port_to_agent(nic, display_name='NetNS-%s-%s-interface' % (self.vm_uuid, nic['name'])) def unplug_namespace_interface(self): for nic in self.nics: self._delete_port_to_agent(nic) def _create_interfaces(self, ip, nic): if ip_lib.device_exists(nic['name'], self.root_helper, namespace=self.namespace): ip_lib.IPDevice(nic['name'], self.root_helper, self.namespace).link.delete() root_dev, ns_dev = ip.add_veth(self._get_tap_name(nic['uuid']), nic['name'], namespace2=self.namespace) if nic['mac']: ns_dev.link.set_address(str(nic['mac'])) ns_dev.link.set_up() root_dev.link.set_up() if nic['ip']: ip = nic['ip'] ns_dev.addr.flush() ns_dev.addr.add(ip.version, str(ip), str(ip.broadcast)) else: #TODO(ethuleau): start DHCP client raise NotImplementedError # disable reverse path filtering self.ip_ns.netns.execute(['sysctl', '-w', 'net.ipv4.conf.%s.rp_filter=2' % nic['name']] ) def _request_to_agent(self, url, method, data): method = getattr(requests, method) resp = method(url, data=data, headers=self.HEADERS) if resp.status_code != requests.codes.ok: error_str = resp.text try: err = json.loads(resp.text) error_str = err['error'] except Exception: pass raise ValueError(error_str) def _add_port_to_agent(self, nic, display_name=None): if self.PORT_TYPE == "NovaVMPort": port_type_value = 0 elif self.PORT_TYPE == "NameSpacePort": port_type_value = 1 payload = {"ip-address": str(nic['ip'].ip), "tx-vlan-id": -1, "display-name": display_name, "id": nic['uuid'], "instance-id": self.vm_uuid, "ip6-address": '', "rx-vlan-id": -1, "system-name": self._get_tap_name(nic['uuid']), "vn-id": '', "vm-project-id": '', "type": port_type_value, "mac-address": str(nic['mac'])} json_dump = json.dumps(payload) self._request_to_agent(self.BASE_URL, 'post', json_dump) def _delete_port_to_agent(self, nic): url = self.BASE_URL + "/" + nic['uuid'] self._request_to_agent(url, 'delete', None) class VRouterNetns(object): """Create or destroy a Linux network namespace plug between two virtual networks. """ SOURCE_NAT = 'source-nat' LOAD_BALANCER = 'loadbalancer' SERVICE_TYPES = [SOURCE_NAT, LOAD_BALANCER] def __init__(self, args_str=None): self.args = None if not args_str: args_str = ' '.join(sys.argv[1:]) self._parse_args(args_str) def _parse_args(self, args_str): """Return an argparse.ArgumentParser for me""" conf_parser = argparse.ArgumentParser(add_help=False) conf_parser.add_argument("-c", "--root_helper", help="Helper to execute root commands. " "Default: 'sudo'", default="sudo") args, remaining_argv = conf_parser.parse_known_args(args_str.split()) # Override with CLI options # Don't surpress add_help here so it will handle -h parser = argparse.ArgumentParser( # Inherit options from config_parser parents=[conf_parser], # print script description with -h/--help description=__doc__, # Don't mess with format of description formatter_class=argparse.RawDescriptionHelpFormatter, ) subparsers = parser.add_subparsers() create_parser = subparsers.add_parser('create') create_parser.add_argument( "service_type", choices=self.SERVICE_TYPES, help="Service type to run into the namespace") create_parser.add_argument( "vm_id", help="Virtual machine UUID") create_parser.add_argument( "vmi_left_id", help="Left virtual machine interface UUID") create_parser.add_argument( "vmi_right_id", help="Right virtual machine interface UUID") create_parser.add_argument( "--vmi-left-mac", default=None, help=("Left virtual machine interface MAC. Default: automatically " "generated by the system")) create_parser.add_argument( "--vmi-left-ip", default=None, help=("Left virtual machine interface IPv4 and mask " "(ie: a.a.a.a/bb). Default mask to /32")) create_parser.add_argument( "--vmi-right-mac", default=None, help=("Right virtual machine interface MAC. Default: " "automatically generated by the system")) create_parser.add_argument( "--vmi-right-ip", default=None, help=("Right virtual machine interface IPv4 and mask " "(ie: a.a.a.a/bb). Default mask to /32")) create_parser.add_argument( "--update", action="store_true", default=False, help=("Update a created namespace (do nothing for the moment)")) create_parser.add_argument( "--cfg-file", default=None, help=("Config file for lbaas")) create_parser.add_argument( "--gw-ip", default=None, help=("Gateway IP for Virtual Network")) create_parser.add_argument( "--pool-id", default=None, help=("Loadbalancer Pool")) create_parser.add_argument( "--loadbalancer-id", default=None, help=("Loadbalancer")) create_parser.add_argument( "--keystone-auth-cfg-file", default=None, help=("Keystone auth config file for lbaas")) create_parser.set_defaults(func=self.create) destroy_parser = subparsers.add_parser('destroy') destroy_parser.add_argument( "service_type", choices=self.SERVICE_TYPES, help="Service type to run into the namespace") destroy_parser.add_argument( "vm_id", help="Virtual machine UUID") destroy_parser.add_argument( "vmi_left_id", help="Left virtual machine interface UUID") destroy_parser.add_argument( "vmi_right_id", help="Right virtual machine interface UUID") destroy_parser.add_argument( "--cfg-file", default=None, help=("config file for lbaas")) destroy_parser.add_argument( "--pool-id", default=None, help=("Loadbalancer Pool")) destroy_parser.add_argument( "--loadbalancer-id", default=None, help=("Loadbalancer")) destroy_parser.set_defaults(func=self.destroy) self.args = parser.parse_args(remaining_argv) def create(self): netns_name = validate_uuid(self.args.vm_id) nic_left = {} if uuid.UUID(self.args.vmi_left_id).int: nic_left['uuid'] = validate_uuid(self.args.vmi_left_id) if self.args.vmi_left_mac: nic_left['mac'] = netaddr.EUI(self.args.vmi_left_mac, dialect=netaddr.mac_unix) else: nic_left['mac'] = None if self.args.vmi_left_ip: nic_left['ip'] = netaddr.IPNetwork(self.args.vmi_left_ip) else: nic_left['ip'] = None nic_right = {} if uuid.UUID(self.args.vmi_right_id).int: nic_right['uuid'] = validate_uuid(self.args.vmi_right_id) if self.args.vmi_right_mac: nic_right['mac'] = netaddr.EUI(self.args.vmi_right_mac, dialect=netaddr.mac_unix) else: nic_right['mac'] = None if self.args.vmi_right_ip: nic_right['ip'] = netaddr.IPNetwork(self.args.vmi_right_ip) else: nic_right['ip'] = None netns_mgr = NetnsManager(netns_name, nic_left, nic_right, root_helper=self.args.root_helper, cfg_file=self.args.cfg_file, update=self.args.update, gw_ip=self.args.gw_ip, pool_id=self.args.pool_id, loadbalancer_id=self.args.loadbalancer_id, keystone_auth_cfg_file=self.args.keystone_auth_cfg_file) if (self.args.update is False): if netns_mgr.is_netns_already_exists(): # If the netns already exists, destroy it to be sure to set it # with new parameters like another external network if self.args.service_type == self.LOAD_BALANCER: netns_mgr.release_lbaas() netns_mgr.unplug_namespace_interface() netns_mgr.destroy() netns_mgr.create() if self.args.service_type == self.SOURCE_NAT: netns_mgr.set_snat() elif self.args.service_type == self.LOAD_BALANCER: netns_mgr.set_lbaas() else: msg = ('The %s service type is not supported' % self.args.service_type) raise NotImplementedError(msg) netns_mgr.plug_namespace_interface() def destroy(self): netns_name = validate_uuid(self.args.vm_id) nic_left = {} if uuid.UUID(self.args.vmi_left_id).int: nic_left = {'uuid': validate_uuid(self.args.vmi_left_id)} nic_right = {} if uuid.UUID(self.args.vmi_right_id).int: nic_right = {'uuid': validate_uuid(self.args.vmi_right_id)} netns_mgr = NetnsManager(netns_name, nic_left, nic_right, root_helper=self.args.root_helper, cfg_file=self.args.cfg_file, gw_ip=None, pool_id=self.args.pool_id, loadbalancer_id=self.args.loadbalancer_id) netns_mgr.unplug_namespace_interface() if self.args.service_type == self.SOURCE_NAT: netns_mgr.destroy() elif self.args.service_type == self.LOAD_BALANCER: netns_mgr.release_lbaas() netns_mgr.destroy() else: msg = ('The %s service type is not supported' % self.args.service_type) raise NotImplementedError(msg) def _check_output(cmd, flag=True): proc = subprocess.Popen(cmd, shell=flag, stdout=subprocess.PIPE) data, err = proc.communicate() retcode = proc.poll() if retcode: raise subprocess.CalledProcessError(retcode, cmd) return data def main(args_str=None): vrouter_netns = VRouterNetns(args_str) vrouter_netns.args.func()
38.805118
85
0.566022
from __future__ import print_function __docformat__ = "restructuredtext en" import argparse import netaddr import sys import uuid import subprocess import requests import json import os import shlex from linux import ip_lib import haproxy_process def validate_uuid(val): try: if str(uuid.UUID(val)) == val: return val except (TypeError, ValueError, AttributeError): raise ValueError('Invalid UUID format') class NetnsManager(object): SNAT_RT_TABLES_ID = 42 DEV_NAME_LEN = 14 NETNS_PREFIX = 'vrouter-' LEFT_DEV_PREFIX = 'int-' RIGH_DEV_PREFIX = 'gw-' TAP_PREFIX = 'veth' PORT_TYPE = 'NameSpacePort' BASE_URL = "http://localhost:9091/port" HEADERS = {'content-type': 'application/json'} LBAAS_DIR = "/var/lib/contrail/loadbalancer" def __init__(self, vm_uuid, nic_left, nic_right, other_nics=None, root_helper='sudo', cfg_file=None, update=False, pool_id=None, gw_ip=None, namespace_name=None, keystone_auth_cfg_file=None, loadbalancer_id=None): self.vm_uuid = vm_uuid if namespace_name is None: self.namespace = self.NETNS_PREFIX + self.vm_uuid else: self.namespace = namespace_name if pool_id: self.namespace = self.namespace + ":" + pool_id elif loadbalancer_id: self.namespace = self.namespace + ":" + loadbalancer_id self.nic_left = nic_left self.nic_right = nic_right self.root_helper = root_helper self.nics = other_nics or [] if self.nic_left: self.nic_left['name'] = (self.LEFT_DEV_PREFIX + self.nic_left['uuid'])[:self.DEV_NAME_LEN] self.nics.append(self.nic_left) if self.nic_right: self.nic_right['name'] = (self.RIGH_DEV_PREFIX + self.nic_right['uuid'])[:self.DEV_NAME_LEN] self.nics.append(self.nic_right) self.ip_ns = ip_lib.IPWrapper(root_helper=self.root_helper, namespace=self.namespace) self.cfg_file = cfg_file self.update = update self.gw_ip = gw_ip self.loadbalancer_id = loadbalancer_id self.keystone_auth_cfg_file = keystone_auth_cfg_file def _get_tap_name(self, uuid_str): return (self.TAP_PREFIX + uuid_str)[:self.DEV_NAME_LEN] def is_netns_already_exists(self): return self.ip_ns.netns.exists(self.namespace) def create(self): ip = ip_lib.IPWrapper(self.root_helper) ip.ensure_namespace(self.namespace) for nic in self.nics: self._create_interfaces(ip, nic) def set_snat(self): if not self.ip_ns.netns.exists(self.namespace): self.create() self.ip_ns.netns.execute(['sysctl', '-w', 'net.ipv4.ip_forward=1']) self.ip_ns.netns.execute(['iptables', '-t', 'nat', '-F']) self.ip_ns.netns.execute(['iptables', '-t', 'nat', '-A', 'POSTROUTING', '-s', '0.0.0.0/0', '-o', self.nic_right['name'], '-j', 'MASQUERADE']) self.ip_ns.netns.execute(['ip', 'route', 'replace', 'default', 'dev', self.nic_right['name']]) self.ip_ns.netns.execute(['ip', 'route', 'replace', 'default', 'dev', self.nic_left['name'], 'table', self.SNAT_RT_TABLES_ID]) try: self.ip_ns.netns.execute(['ip', 'rule', 'del', 'iif', str(self.nic_right['name']), 'table', self.SNAT_RT_TABLES_ID]) except RuntimeError: pass self.ip_ns.netns.execute(['ip', 'rule', 'add', 'iif', str(self.nic_right['name']), 'table', self.SNAT_RT_TABLES_ID]) self.ip_ns.netns.execute(['ip', 'route', 'del', 'default', 'table', self.SNAT_RT_TABLES_ID]) self.ip_ns.netns.execute(['ip', 'route', 'add', 'default', 'table', self.SNAT_RT_TABLES_ID, 'via', self.gw_ip, 'dev', str(self.nic_left['name'])]) def find_lbaas_type(self, cfg_file): lbaas_type = ''; if not os.path.exists(cfg_file): return lbaas_type f = open(cfg_file) content = f.read() f.close() kvps = content.split(':::::') for kvp in kvps or []: lbaas_type = kvp.split('::::')[0] if (lbaas_type == 'haproxy_config'): break; return lbaas_type def move_cfg_file_to_lbaas_dir(self, cfg_file): dir_name = self.LBAAS_DIR; if not os.path.exists(dir_name): cmd = "mkdir -p " + dir_name cmd_list = shlex.split(cmd) p = subprocess.Popen(cmd_list) p.communicate() cmd = "mv " + cfg_file + " " + dir_name cmd_list = shlex.split(cmd) p = subprocess.Popen(cmd_list) p.communicate(); return dir_name + '/' + os.path.basename(cfg_file) def remove_cfg_file(self, cfg_file): cmd = "rm " + cfg_file cmd_list = shlex.split(cmd) p = subprocess.Popen(cmd_list) p.communicate() def set_lbaas(self): if not self.ip_ns.netns.exists(self.namespace): self.create() lbaas_type = self.find_lbaas_type(self.cfg_file) if (lbaas_type == ''): raise ValueError('LBAAS_TYPE does not exist %s' % self.cfg_file) self.cfg_file = self.move_cfg_file_to_lbaas_dir(self.cfg_file) if (lbaas_type == 'haproxy_config'): haproxy_process.start_update_haproxy(self.loadbalancer_id, self.cfg_file, self.namespace, True, self.keystone_auth_cfg_file) try: self.ip_ns.netns.execute(['route', 'add', 'default', 'gw', self.gw_ip]) except RuntimeError: pass def release_lbaas(self): if not self.ip_ns.netns.exists(self.namespace): raise ValueError('Need to create the network namespace before ' 'relasing lbaas') cfg_file = self.LBAAS_DIR + "/" + self.loadbalancer_id + ".conf" lbaas_type = self.find_lbaas_type(cfg_file) if (lbaas_type == ''): return elif (lbaas_type == 'haproxy_config'): haproxy_process.stop_haproxy(self.loadbalancer_id, True) try: self.ip_ns.netns.execute(['route', 'del', 'default']) except RuntimeError: pass self.remove_cfg_file(cfg_file) def destroy(self): if not self.ip_ns.netns.exists(self.namespace): raise ValueError('Namespace %s does not exist' % self.namespace) for device in self.ip_ns.get_devices(exclude_loopback=True): ip_lib.IPDevice(device.name, self.root_helper, self.namespace).link.delete() self.ip_ns.netns.delete(self.namespace) def plug_namespace_interface(self): for nic in self.nics: self._add_port_to_agent(nic, display_name='NetNS-%s-%s-interface' % (self.vm_uuid, nic['name'])) def unplug_namespace_interface(self): for nic in self.nics: self._delete_port_to_agent(nic) def _create_interfaces(self, ip, nic): if ip_lib.device_exists(nic['name'], self.root_helper, namespace=self.namespace): ip_lib.IPDevice(nic['name'], self.root_helper, self.namespace).link.delete() root_dev, ns_dev = ip.add_veth(self._get_tap_name(nic['uuid']), nic['name'], namespace2=self.namespace) if nic['mac']: ns_dev.link.set_address(str(nic['mac'])) ns_dev.link.set_up() root_dev.link.set_up() if nic['ip']: ip = nic['ip'] ns_dev.addr.flush() ns_dev.addr.add(ip.version, str(ip), str(ip.broadcast)) else: raise NotImplementedError self.ip_ns.netns.execute(['sysctl', '-w', 'net.ipv4.conf.%s.rp_filter=2' % nic['name']] ) def _request_to_agent(self, url, method, data): method = getattr(requests, method) resp = method(url, data=data, headers=self.HEADERS) if resp.status_code != requests.codes.ok: error_str = resp.text try: err = json.loads(resp.text) error_str = err['error'] except Exception: pass raise ValueError(error_str) def _add_port_to_agent(self, nic, display_name=None): if self.PORT_TYPE == "NovaVMPort": port_type_value = 0 elif self.PORT_TYPE == "NameSpacePort": port_type_value = 1 payload = {"ip-address": str(nic['ip'].ip), "tx-vlan-id": -1, "display-name": display_name, "id": nic['uuid'], "instance-id": self.vm_uuid, "ip6-address": '', "rx-vlan-id": -1, "system-name": self._get_tap_name(nic['uuid']), "vn-id": '', "vm-project-id": '', "type": port_type_value, "mac-address": str(nic['mac'])} json_dump = json.dumps(payload) self._request_to_agent(self.BASE_URL, 'post', json_dump) def _delete_port_to_agent(self, nic): url = self.BASE_URL + "/" + nic['uuid'] self._request_to_agent(url, 'delete', None) class VRouterNetns(object): SOURCE_NAT = 'source-nat' LOAD_BALANCER = 'loadbalancer' SERVICE_TYPES = [SOURCE_NAT, LOAD_BALANCER] def __init__(self, args_str=None): self.args = None if not args_str: args_str = ' '.join(sys.argv[1:]) self._parse_args(args_str) def _parse_args(self, args_str): conf_parser = argparse.ArgumentParser(add_help=False) conf_parser.add_argument("-c", "--root_helper", help="Helper to execute root commands. " "Default: 'sudo'", default="sudo") args, remaining_argv = conf_parser.parse_known_args(args_str.split()) parser = argparse.ArgumentParser( # Inherit options from config_parser parents=[conf_parser], # print script description with -h/--help description=__doc__, # Don't mess with format of description formatter_class=argparse.RawDescriptionHelpFormatter, ) subparsers = parser.add_subparsers() create_parser = subparsers.add_parser('create') create_parser.add_argument( "service_type", choices=self.SERVICE_TYPES, help="Service type to run into the namespace") create_parser.add_argument( "vm_id", help="Virtual machine UUID") create_parser.add_argument( "vmi_left_id", help="Left virtual machine interface UUID") create_parser.add_argument( "vmi_right_id", help="Right virtual machine interface UUID") create_parser.add_argument( "--vmi-left-mac", default=None, help=("Left virtual machine interface MAC. Default: automatically " "generated by the system")) create_parser.add_argument( "--vmi-left-ip", default=None, help=("Left virtual machine interface IPv4 and mask " "(ie: a.a.a.a/bb). Default mask to /32")) create_parser.add_argument( "--vmi-right-mac", default=None, help=("Right virtual machine interface MAC. Default: " "automatically generated by the system")) create_parser.add_argument( "--vmi-right-ip", default=None, help=("Right virtual machine interface IPv4 and mask " "(ie: a.a.a.a/bb). Default mask to /32")) create_parser.add_argument( "--update", action="store_true", default=False, help=("Update a created namespace (do nothing for the moment)")) create_parser.add_argument( "--cfg-file", default=None, help=("Config file for lbaas")) create_parser.add_argument( "--gw-ip", default=None, help=("Gateway IP for Virtual Network")) create_parser.add_argument( "--pool-id", default=None, help=("Loadbalancer Pool")) create_parser.add_argument( "--loadbalancer-id", default=None, help=("Loadbalancer")) create_parser.add_argument( "--keystone-auth-cfg-file", default=None, help=("Keystone auth config file for lbaas")) create_parser.set_defaults(func=self.create) destroy_parser = subparsers.add_parser('destroy') destroy_parser.add_argument( "service_type", choices=self.SERVICE_TYPES, help="Service type to run into the namespace") destroy_parser.add_argument( "vm_id", help="Virtual machine UUID") destroy_parser.add_argument( "vmi_left_id", help="Left virtual machine interface UUID") destroy_parser.add_argument( "vmi_right_id", help="Right virtual machine interface UUID") destroy_parser.add_argument( "--cfg-file", default=None, help=("config file for lbaas")) destroy_parser.add_argument( "--pool-id", default=None, help=("Loadbalancer Pool")) destroy_parser.add_argument( "--loadbalancer-id", default=None, help=("Loadbalancer")) destroy_parser.set_defaults(func=self.destroy) self.args = parser.parse_args(remaining_argv) def create(self): netns_name = validate_uuid(self.args.vm_id) nic_left = {} if uuid.UUID(self.args.vmi_left_id).int: nic_left['uuid'] = validate_uuid(self.args.vmi_left_id) if self.args.vmi_left_mac: nic_left['mac'] = netaddr.EUI(self.args.vmi_left_mac, dialect=netaddr.mac_unix) else: nic_left['mac'] = None if self.args.vmi_left_ip: nic_left['ip'] = netaddr.IPNetwork(self.args.vmi_left_ip) else: nic_left['ip'] = None nic_right = {} if uuid.UUID(self.args.vmi_right_id).int: nic_right['uuid'] = validate_uuid(self.args.vmi_right_id) if self.args.vmi_right_mac: nic_right['mac'] = netaddr.EUI(self.args.vmi_right_mac, dialect=netaddr.mac_unix) else: nic_right['mac'] = None if self.args.vmi_right_ip: nic_right['ip'] = netaddr.IPNetwork(self.args.vmi_right_ip) else: nic_right['ip'] = None netns_mgr = NetnsManager(netns_name, nic_left, nic_right, root_helper=self.args.root_helper, cfg_file=self.args.cfg_file, update=self.args.update, gw_ip=self.args.gw_ip, pool_id=self.args.pool_id, loadbalancer_id=self.args.loadbalancer_id, keystone_auth_cfg_file=self.args.keystone_auth_cfg_file) if (self.args.update is False): if netns_mgr.is_netns_already_exists(): if self.args.service_type == self.LOAD_BALANCER: netns_mgr.release_lbaas() netns_mgr.unplug_namespace_interface() netns_mgr.destroy() netns_mgr.create() if self.args.service_type == self.SOURCE_NAT: netns_mgr.set_snat() elif self.args.service_type == self.LOAD_BALANCER: netns_mgr.set_lbaas() else: msg = ('The %s service type is not supported' % self.args.service_type) raise NotImplementedError(msg) netns_mgr.plug_namespace_interface() def destroy(self): netns_name = validate_uuid(self.args.vm_id) nic_left = {} if uuid.UUID(self.args.vmi_left_id).int: nic_left = {'uuid': validate_uuid(self.args.vmi_left_id)} nic_right = {} if uuid.UUID(self.args.vmi_right_id).int: nic_right = {'uuid': validate_uuid(self.args.vmi_right_id)} netns_mgr = NetnsManager(netns_name, nic_left, nic_right, root_helper=self.args.root_helper, cfg_file=self.args.cfg_file, gw_ip=None, pool_id=self.args.pool_id, loadbalancer_id=self.args.loadbalancer_id) netns_mgr.unplug_namespace_interface() if self.args.service_type == self.SOURCE_NAT: netns_mgr.destroy() elif self.args.service_type == self.LOAD_BALANCER: netns_mgr.release_lbaas() netns_mgr.destroy() else: msg = ('The %s service type is not supported' % self.args.service_type) raise NotImplementedError(msg) def _check_output(cmd, flag=True): proc = subprocess.Popen(cmd, shell=flag, stdout=subprocess.PIPE) data, err = proc.communicate() retcode = proc.poll() if retcode: raise subprocess.CalledProcessError(retcode, cmd) return data def main(args_str=None): vrouter_netns = VRouterNetns(args_str) vrouter_netns.args.func()
true
true
1c2bee4bac7fec0321a50314dc6ae2c0c1cf7725
428
py
Python
Informatik1/Midterms Prep/midterms hs19/find_sum.py
Queentaker/uzh
35cccaf910b95d15db21be80c8567eb427202591
[ "MIT" ]
8
2021-11-21T10:02:08.000Z
2022-03-15T21:02:02.000Z
Informatik1/Midterms Prep/midterms hs19/find_sum.py
Queentaker/uzh
35cccaf910b95d15db21be80c8567eb427202591
[ "MIT" ]
null
null
null
Informatik1/Midterms Prep/midterms hs19/find_sum.py
Queentaker/uzh
35cccaf910b95d15db21be80c8567eb427202591
[ "MIT" ]
3
2021-11-19T18:52:56.000Z
2022-02-27T15:45:59.000Z
def find_sum(list, target): for idx1, v1 in enumerate(list): for idx2, v2 in enumerate(list): if idx1 == idx2: continue if v1 + v2 == target: return(idx1, idx2) return None print(find_sum([], 9)) #None print(find_sum([1], 2)) #None print(find_sum([1, 1], 2)) #(0, 1) print(find_sum([1, 7, 2, 11], 9)) #(1, 2) print(find_sum([1, 2, 3, 4], 5)) #(0, 3)
26.75
41
0.511682
def find_sum(list, target): for idx1, v1 in enumerate(list): for idx2, v2 in enumerate(list): if idx1 == idx2: continue if v1 + v2 == target: return(idx1, idx2) return None print(find_sum([], 9)) print(find_sum([1], 2)) print(find_sum([1, 1], 2)) print(find_sum([1, 7, 2, 11], 9)) print(find_sum([1, 2, 3, 4], 5))
true
true
1c2beef66162473376677f0874951e423d99c133
5,824
py
Python
tests/integration_tests/dashboards/filter_state/api_tests.py
mabossert/superset
d9e9c3a3de2ec5fe90c613ac06ad2a5606c43ece
[ "Apache-2.0" ]
1
2021-12-02T03:47:56.000Z
2021-12-02T03:47:56.000Z
tests/integration_tests/dashboards/filter_state/api_tests.py
mabossert/superset
d9e9c3a3de2ec5fe90c613ac06ad2a5606c43ece
[ "Apache-2.0" ]
11
2021-12-04T14:16:33.000Z
2022-02-21T16:07:30.000Z
tests/integration_tests/dashboards/filter_state/api_tests.py
bretton7700/alertsAndReports
d3feca6973baa9a265805a095464650e6af7b0d9
[ "Apache-2.0" ]
null
null
null
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json from typing import Any from unittest.mock import patch import pytest from flask.testing import FlaskClient from sqlalchemy.orm import Session from superset import app from superset.dashboards.commands.exceptions import DashboardAccessDeniedError from superset.extensions import cache_manager from superset.key_value.utils import cache_key from superset.models.dashboard import Dashboard from tests.integration_tests.fixtures.world_bank_dashboard import ( load_world_bank_dashboard_with_slices, ) from tests.integration_tests.test_app import app dashboardId = 985374 key = "test-key" value = "test" class FilterStateTests: @pytest.fixture def client(self): with app.test_client() as client: with app.app_context(): yield client @pytest.fixture def dashboard_id(self, load_world_bank_dashboard_with_slices) -> int: with app.app_context() as ctx: session: Session = ctx.app.appbuilder.get_session dashboard = session.query(Dashboard).filter_by(slug="world_health").one() return dashboard.id @pytest.fixture def cache(self, dashboard_id): app.config["FILTER_STATE_CACHE_CONFIG"] = {"CACHE_TYPE": "SimpleCache"} cache_manager.init_app(app) cache_manager.filter_state_cache.set(cache_key(dashboard_id, key), value) def setUp(self): self.login(username="admin") def test_post(self, client, dashboard_id: int): payload = { "value": value, } resp = client.post( f"api/v1/dashboard/{dashboard_id}/filter_state", json=payload ) assert resp.status_code == 201 def test_post_bad_request(self, client, dashboard_id: int): payload = { "value": 1234, } resp = client.put( f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/", json=payload ) assert resp.status_code == 400 @patch("superset.security.SupersetSecurityManager.raise_for_dashboard_access") def test_post_access_denied( self, client, mock_raise_for_dashboard_access, dashboard_id: int ): mock_raise_for_dashboard_access.side_effect = DashboardAccessDeniedError() payload = { "value": value, } resp = client.post( f"api/v1/dashboard/{dashboard_id}/filter_state", json=payload ) assert resp.status_code == 403 def test_put(self, client, dashboard_id: int): payload = { "value": "new value", } resp = client.put( f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/", json=payload ) assert resp.status_code == 200 def test_put_bad_request(self, client, dashboard_id: int): payload = { "value": 1234, } resp = client.put( f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/", json=payload ) assert resp.status_code == 400 @patch("superset.security.SupersetSecurityManager.raise_for_dashboard_access") def test_put_access_denied( self, client, mock_raise_for_dashboard_access, dashboard_id: int ): mock_raise_for_dashboard_access.side_effect = DashboardAccessDeniedError() payload = { "value": "new value", } resp = client.put( f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/", json=payload ) assert resp.status_code == 403 def test_get_key_not_found(self, client): resp = client.get("unknown-key") assert resp.status_code == 404 def test_get_dashboard_not_found(self, client): resp = client.get(f"api/v1/dashboard/{-1}/filter_state/{key}/") assert resp.status_code == 404 def test_get(self, client, dashboard_id: int): resp = client.get(f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/") assert resp.status_code == 200 data = json.loads(resp.data.decode("utf-8")) assert value == data.get("value") @patch("superset.security.SupersetSecurityManager.raise_for_dashboard_access") def test_get_access_denied( self, client, mock_raise_for_dashboard_access, dashboard_id ): mock_raise_for_dashboard_access.side_effect = DashboardAccessDeniedError() resp = client.get(f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/") assert resp.status_code == 403 def test_delete(self, client, dashboard_id: int): resp = client.delete(f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/") assert resp.status_code == 200 @patch("superset.security.SupersetSecurityManager.raise_for_dashboard_access") def test_delete_access_denied( self, client, mock_raise_for_dashboard_access, dashboard_id: int ): mock_raise_for_dashboard_access.side_effect = DashboardAccessDeniedError() resp = client.delete(f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/") assert resp.status_code == 403
36.860759
85
0.684753
import json from typing import Any from unittest.mock import patch import pytest from flask.testing import FlaskClient from sqlalchemy.orm import Session from superset import app from superset.dashboards.commands.exceptions import DashboardAccessDeniedError from superset.extensions import cache_manager from superset.key_value.utils import cache_key from superset.models.dashboard import Dashboard from tests.integration_tests.fixtures.world_bank_dashboard import ( load_world_bank_dashboard_with_slices, ) from tests.integration_tests.test_app import app dashboardId = 985374 key = "test-key" value = "test" class FilterStateTests: @pytest.fixture def client(self): with app.test_client() as client: with app.app_context(): yield client @pytest.fixture def dashboard_id(self, load_world_bank_dashboard_with_slices) -> int: with app.app_context() as ctx: session: Session = ctx.app.appbuilder.get_session dashboard = session.query(Dashboard).filter_by(slug="world_health").one() return dashboard.id @pytest.fixture def cache(self, dashboard_id): app.config["FILTER_STATE_CACHE_CONFIG"] = {"CACHE_TYPE": "SimpleCache"} cache_manager.init_app(app) cache_manager.filter_state_cache.set(cache_key(dashboard_id, key), value) def setUp(self): self.login(username="admin") def test_post(self, client, dashboard_id: int): payload = { "value": value, } resp = client.post( f"api/v1/dashboard/{dashboard_id}/filter_state", json=payload ) assert resp.status_code == 201 def test_post_bad_request(self, client, dashboard_id: int): payload = { "value": 1234, } resp = client.put( f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/", json=payload ) assert resp.status_code == 400 @patch("superset.security.SupersetSecurityManager.raise_for_dashboard_access") def test_post_access_denied( self, client, mock_raise_for_dashboard_access, dashboard_id: int ): mock_raise_for_dashboard_access.side_effect = DashboardAccessDeniedError() payload = { "value": value, } resp = client.post( f"api/v1/dashboard/{dashboard_id}/filter_state", json=payload ) assert resp.status_code == 403 def test_put(self, client, dashboard_id: int): payload = { "value": "new value", } resp = client.put( f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/", json=payload ) assert resp.status_code == 200 def test_put_bad_request(self, client, dashboard_id: int): payload = { "value": 1234, } resp = client.put( f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/", json=payload ) assert resp.status_code == 400 @patch("superset.security.SupersetSecurityManager.raise_for_dashboard_access") def test_put_access_denied( self, client, mock_raise_for_dashboard_access, dashboard_id: int ): mock_raise_for_dashboard_access.side_effect = DashboardAccessDeniedError() payload = { "value": "new value", } resp = client.put( f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/", json=payload ) assert resp.status_code == 403 def test_get_key_not_found(self, client): resp = client.get("unknown-key") assert resp.status_code == 404 def test_get_dashboard_not_found(self, client): resp = client.get(f"api/v1/dashboard/{-1}/filter_state/{key}/") assert resp.status_code == 404 def test_get(self, client, dashboard_id: int): resp = client.get(f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/") assert resp.status_code == 200 data = json.loads(resp.data.decode("utf-8")) assert value == data.get("value") @patch("superset.security.SupersetSecurityManager.raise_for_dashboard_access") def test_get_access_denied( self, client, mock_raise_for_dashboard_access, dashboard_id ): mock_raise_for_dashboard_access.side_effect = DashboardAccessDeniedError() resp = client.get(f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/") assert resp.status_code == 403 def test_delete(self, client, dashboard_id: int): resp = client.delete(f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/") assert resp.status_code == 200 @patch("superset.security.SupersetSecurityManager.raise_for_dashboard_access") def test_delete_access_denied( self, client, mock_raise_for_dashboard_access, dashboard_id: int ): mock_raise_for_dashboard_access.side_effect = DashboardAccessDeniedError() resp = client.delete(f"api/v1/dashboard/{dashboard_id}/filter_state/{key}/") assert resp.status_code == 403
true
true
1c2bef230bc14bd35ef8b0f84b1a984e28b66c66
4,900
py
Python
sympy/plotting/textplot.py
msgoff/sympy
1e7daef7514902f5e89718fa957b7b36c6669a10
[ "BSD-3-Clause" ]
null
null
null
sympy/plotting/textplot.py
msgoff/sympy
1e7daef7514902f5e89718fa957b7b36c6669a10
[ "BSD-3-Clause" ]
null
null
null
sympy/plotting/textplot.py
msgoff/sympy
1e7daef7514902f5e89718fa957b7b36c6669a10
[ "BSD-3-Clause" ]
null
null
null
from __future__ import print_function, division from sympy.core.numbers import Float from sympy.core.symbol import Dummy from sympy.utilities.lambdify import lambdify import math def is_valid(x): """Check if a floating point number is valid""" if x is None: return False if isinstance(x, complex): return False return not math.isinf(x) and not math.isnan(x) def rescale(y, W, H, mi, ma): """Rescale the given array `y` to fit into the integer values between `0` and `H-1` for the values between ``mi`` and ``ma``. """ y_new = list() norm = ma - mi offset = (ma + mi) / 2 for x in range(W): if is_valid(y[x]): normalized = (y[x] - offset) / norm if not is_valid(normalized): y_new.append(None) else: # XXX There are some test failings because of the # difference between the python 2 and 3 rounding. rescaled = Float((normalized * H + H / 2) * (H - 1) / H).round() rescaled = int(rescaled) y_new.append(rescaled) else: y_new.append(None) return y_new def linspace(start, stop, num): return [start + (stop - start) * x / (num - 1) for x in range(num)] def textplot_str(expr, a, b, W=55, H=18): """Generator for the lines of the plot""" free = expr.free_symbols if len(free) > 1: raise ValueError( "The expression must have a single variable. (Got {})".format(free) ) x = free.pop() if free else Dummy() f = lambdify([x], expr) a = float(a) b = float(b) # Calculate function values x = linspace(a, b, W) y = list() for val in x: try: y.append(f(val)) # Not sure what exceptions to catch here or why... except (ValueError, TypeError, ZeroDivisionError): y.append(None) # Normalize height to screen space y_valid = list(filter(is_valid, y)) if y_valid: ma = max(y_valid) mi = min(y_valid) if ma == mi: if ma: mi, ma = sorted([0, 2 * ma]) else: mi, ma = -1, 1 else: mi, ma = -1, 1 y = rescale(y, W, H, mi, ma) y_bins = linspace(mi, ma, H) # Draw plot margin = 7 for h in range(H - 1, -1, -1): s = [" "] * W for i in range(W): if y[i] == h: if (i == 0 or y[i - 1] == h - 1) and (i == W - 1 or y[i + 1] == h + 1): s[i] = "/" elif (i == 0 or y[i - 1] == h + 1) and ( i == W - 1 or y[i + 1] == h - 1 ): s[i] = "\\" else: s[i] = "." # Print y values if h in (0, H // 2, H - 1): prefix = ("%g" % y_bins[h]).rjust(margin)[:margin] else: prefix = " " * margin s = "".join(s) if h == H // 2: s = s.replace(" ", "-") yield prefix + " | " + s # Print x values bottom = " " * (margin + 3) bottom += ("%g" % x[0]).ljust(W // 2) if W % 2 == 1: bottom += ("%g" % x[W // 2]).ljust(W // 2) else: bottom += ("%g" % x[W // 2]).ljust(W // 2 - 1) bottom += "%g" % x[-1] yield bottom def textplot(expr, a, b, W=55, H=18): r""" Print a crude ASCII art plot of the SymPy expression 'expr' (which should contain a single symbol, e.g. x or something else) over the interval [a, b]. Examples ======== >>> from sympy import Symbol, sin >>> from sympy.plotting import textplot >>> t = Symbol('t') >>> textplot(sin(t)*t, 0, 15) 14.1605 | ... | . | . | . . | .. | / .. . | / . | / 2.30284 | ------...---------------/--------.------------.-------- | .... ... / | .. \ / . . | .. / . | .. / . | ... . | . | . | \ . -11.037 | ... 0 7.5 15 """ for line in textplot_str(expr, a, b, W, H): print(line)
31.210191
87
0.380204
from __future__ import print_function, division from sympy.core.numbers import Float from sympy.core.symbol import Dummy from sympy.utilities.lambdify import lambdify import math def is_valid(x): if x is None: return False if isinstance(x, complex): return False return not math.isinf(x) and not math.isnan(x) def rescale(y, W, H, mi, ma): y_new = list() norm = ma - mi offset = (ma + mi) / 2 for x in range(W): if is_valid(y[x]): normalized = (y[x] - offset) / norm if not is_valid(normalized): y_new.append(None) else: rescaled = Float((normalized * H + H / 2) * (H - 1) / H).round() rescaled = int(rescaled) y_new.append(rescaled) else: y_new.append(None) return y_new def linspace(start, stop, num): return [start + (stop - start) * x / (num - 1) for x in range(num)] def textplot_str(expr, a, b, W=55, H=18): free = expr.free_symbols if len(free) > 1: raise ValueError( "The expression must have a single variable. (Got {})".format(free) ) x = free.pop() if free else Dummy() f = lambdify([x], expr) a = float(a) b = float(b) x = linspace(a, b, W) y = list() for val in x: try: y.append(f(val)) except (ValueError, TypeError, ZeroDivisionError): y.append(None) y_valid = list(filter(is_valid, y)) if y_valid: ma = max(y_valid) mi = min(y_valid) if ma == mi: if ma: mi, ma = sorted([0, 2 * ma]) else: mi, ma = -1, 1 else: mi, ma = -1, 1 y = rescale(y, W, H, mi, ma) y_bins = linspace(mi, ma, H) margin = 7 for h in range(H - 1, -1, -1): s = [" "] * W for i in range(W): if y[i] == h: if (i == 0 or y[i - 1] == h - 1) and (i == W - 1 or y[i + 1] == h + 1): s[i] = "/" elif (i == 0 or y[i - 1] == h + 1) and ( i == W - 1 or y[i + 1] == h - 1 ): s[i] = "\\" else: s[i] = "." if h in (0, H // 2, H - 1): prefix = ("%g" % y_bins[h]).rjust(margin)[:margin] else: prefix = " " * margin s = "".join(s) if h == H // 2: s = s.replace(" ", "-") yield prefix + " | " + s bottom = " " * (margin + 3) bottom += ("%g" % x[0]).ljust(W // 2) if W % 2 == 1: bottom += ("%g" % x[W // 2]).ljust(W // 2) else: bottom += ("%g" % x[W // 2]).ljust(W // 2 - 1) bottom += "%g" % x[-1] yield bottom def textplot(expr, a, b, W=55, H=18): for line in textplot_str(expr, a, b, W, H): print(line)
true
true
1c2bf09b1133e9b2ad9fd1508d657f6294cf8cfb
2,758
py
Python
catalog/bindings/gmd/arc_by_center_point_type.py
NIVANorge/s-enda-playground
56ae0a8978f0ba8a5546330786c882c31e17757a
[ "Apache-2.0" ]
null
null
null
catalog/bindings/gmd/arc_by_center_point_type.py
NIVANorge/s-enda-playground
56ae0a8978f0ba8a5546330786c882c31e17757a
[ "Apache-2.0" ]
null
null
null
catalog/bindings/gmd/arc_by_center_point_type.py
NIVANorge/s-enda-playground
56ae0a8978f0ba8a5546330786c882c31e17757a
[ "Apache-2.0" ]
null
null
null
from dataclasses import dataclass, field from typing import Optional from bindings.gmd.abstract_curve_segment_type import AbstractCurveSegmentType from bindings.gmd.angle_type import AngleType from bindings.gmd.coordinates import Coordinates from bindings.gmd.curve_interpolation_type import CurveInterpolationType from bindings.gmd.length_type import LengthType from bindings.gmd.point_property import PointProperty from bindings.gmd.point_rep import PointRep from bindings.gmd.pos import Pos from bindings.gmd.pos_list import PosList __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class ArcByCenterPointType(AbstractCurveSegmentType): pos: Optional[Pos] = field( default=None, metadata={ "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) point_property: Optional[PointProperty] = field( default=None, metadata={ "name": "pointProperty", "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) point_rep: Optional[PointRep] = field( default=None, metadata={ "name": "pointRep", "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) pos_list: Optional[PosList] = field( default=None, metadata={ "name": "posList", "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) coordinates: Optional[Coordinates] = field( default=None, metadata={ "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) radius: Optional[LengthType] = field( default=None, metadata={ "type": "Element", "namespace": "http://www.opengis.net/gml", "required": True, }, ) start_angle: Optional[AngleType] = field( default=None, metadata={ "name": "startAngle", "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) end_angle: Optional[AngleType] = field( default=None, metadata={ "name": "endAngle", "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) interpolation: CurveInterpolationType = field( init=False, default=CurveInterpolationType.CIRCULAR_ARC_CENTER_POINT_WITH_RADIUS, metadata={ "type": "Attribute", }, ) num_arc: int = field( init=False, default=1, metadata={ "name": "numArc", "type": "Attribute", "required": True, }, )
28.729167
77
0.568891
from dataclasses import dataclass, field from typing import Optional from bindings.gmd.abstract_curve_segment_type import AbstractCurveSegmentType from bindings.gmd.angle_type import AngleType from bindings.gmd.coordinates import Coordinates from bindings.gmd.curve_interpolation_type import CurveInterpolationType from bindings.gmd.length_type import LengthType from bindings.gmd.point_property import PointProperty from bindings.gmd.point_rep import PointRep from bindings.gmd.pos import Pos from bindings.gmd.pos_list import PosList __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class ArcByCenterPointType(AbstractCurveSegmentType): pos: Optional[Pos] = field( default=None, metadata={ "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) point_property: Optional[PointProperty] = field( default=None, metadata={ "name": "pointProperty", "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) point_rep: Optional[PointRep] = field( default=None, metadata={ "name": "pointRep", "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) pos_list: Optional[PosList] = field( default=None, metadata={ "name": "posList", "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) coordinates: Optional[Coordinates] = field( default=None, metadata={ "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) radius: Optional[LengthType] = field( default=None, metadata={ "type": "Element", "namespace": "http://www.opengis.net/gml", "required": True, }, ) start_angle: Optional[AngleType] = field( default=None, metadata={ "name": "startAngle", "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) end_angle: Optional[AngleType] = field( default=None, metadata={ "name": "endAngle", "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) interpolation: CurveInterpolationType = field( init=False, default=CurveInterpolationType.CIRCULAR_ARC_CENTER_POINT_WITH_RADIUS, metadata={ "type": "Attribute", }, ) num_arc: int = field( init=False, default=1, metadata={ "name": "numArc", "type": "Attribute", "required": True, }, )
true
true
1c2bf125fa33e0f79dc94f4ba4b890f6c187bae6
2,260
py
Python
tests/models/v2/average_analysed_drive_stats_test.py
NetApp/santricity-webapi-pythonsdk
1d3df4a00561192f4cdcdd1890f4d27547ed2de2
[ "BSD-3-Clause-Clear" ]
5
2016-08-23T17:52:22.000Z
2019-05-16T08:45:30.000Z
tests/models/v2/average_analysed_drive_stats_test.py
NetApp/santricity-webapi-pythonsdk
1d3df4a00561192f4cdcdd1890f4d27547ed2de2
[ "BSD-3-Clause-Clear" ]
2
2016-11-10T05:30:21.000Z
2019-04-05T15:03:37.000Z
tests/models/v2/average_analysed_drive_stats_test.py
NetApp/santricity-webapi-pythonsdk
1d3df4a00561192f4cdcdd1890f4d27547ed2de2
[ "BSD-3-Clause-Clear" ]
7
2016-08-25T16:11:44.000Z
2021-02-22T05:31:25.000Z
#!/usr/bin/env python # coding: utf-8 """ The Clear BSD License Copyright (c) – 2016, NetApp, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NetApp, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import unittest from netapp.santricity.models.v2.average_analysed_drive_stats import AverageAnalysedDriveStats class AverageAnalysedDriveStatsTest(unittest.TestCase): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ # Try instantiating the model def test_average_analysed_drive_stats(self): average_analysed_drive_stats_obj = AverageAnalysedDriveStats() self.assertNotEqual(average_analysed_drive_stats_obj, None)
59.473684
845
0.781416
import unittest from netapp.santricity.models.v2.average_analysed_drive_stats import AverageAnalysedDriveStats class AverageAnalysedDriveStatsTest(unittest.TestCase): def test_average_analysed_drive_stats(self): average_analysed_drive_stats_obj = AverageAnalysedDriveStats() self.assertNotEqual(average_analysed_drive_stats_obj, None)
true
true
1c2bf165335c159012d35da21c1793b566b09b91
578
py
Python
nevow/test/test_tabbedpane.py
wthie/nevow
e630de8f640f27df85c38bc37ecdaf4e7b931afc
[ "MIT" ]
49
2015-03-18T15:29:16.000Z
2021-11-17T12:30:51.000Z
src/nevow/test/test_tabbedpane.py
winjer/squeal
20401986e0d1698776f5b482b28e14c57b11833c
[ "Apache-2.0" ]
62
2015-01-21T08:48:08.000Z
2021-04-02T17:31:29.000Z
src/nevow/test/test_tabbedpane.py
winjer/squeal
20401986e0d1698776f5b482b28e14c57b11833c
[ "Apache-2.0" ]
30
2015-02-26T09:35:39.000Z
2021-07-24T12:45:04.000Z
# Copyright (c) 2009 Divmod. See LICENSE for details. """ Tests for L{nevow.taglibrary.tabbedPane}. """ from twisted.trial.unittest import TestCase class TabbedPaneTests(TestCase): def test_import(self): """ L{nevow.taglibrary.tabbedPane} can be imported. This is a very meager test, and it should certainly be augmented with friends later, but for the time being, it is sufficient to cover the fix I am making, which actually makes the module importable. -exarkun """ import nevow.taglibrary.tabbedPane
27.52381
72
0.681661
from twisted.trial.unittest import TestCase class TabbedPaneTests(TestCase): def test_import(self): import nevow.taglibrary.tabbedPane
true
true
1c2bf40f9814a7452866b58655c468474e01efdb
1,093
py
Python
setup.py
5long/forwardable
30d0f1989265acf05b0302abbf307d887f40ab05
[ "MIT" ]
31
2015-01-20T15:08:22.000Z
2020-11-24T20:52:58.000Z
setup.py
5long/forwardable
30d0f1989265acf05b0302abbf307d887f40ab05
[ "MIT" ]
2
2019-05-13T06:27:45.000Z
2019-08-15T06:10:36.000Z
setup.py
5long/forwardable
30d0f1989265acf05b0302abbf307d887f40ab05
[ "MIT" ]
6
2019-05-09T09:35:06.000Z
2021-08-16T09:01:56.000Z
#!/usr/bin/env python from setuptools import setup from forwardable import __version__ setup( name='forwardable', version=__version__, description="Forwardable as in Ruby's stdlib", url='https://github.com/5long/forwardable', long_description=open("README.rst").read(), author="Whyme Lyu", author_email="callme5long@gmail.com", packages=[ 'forwardable', 'forwardable.test', ], package_data={'': ['LICENSE', 'README.rst', 'CHANGELOG.rst']}, include_package_data=True, license="MIT", test_suite="forwardable.test", classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Code Generators', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ] )
30.361111
66
0.619396
from setuptools import setup from forwardable import __version__ setup( name='forwardable', version=__version__, description="Forwardable as in Ruby's stdlib", url='https://github.com/5long/forwardable', long_description=open("README.rst").read(), author="Whyme Lyu", author_email="callme5long@gmail.com", packages=[ 'forwardable', 'forwardable.test', ], package_data={'': ['LICENSE', 'README.rst', 'CHANGELOG.rst']}, include_package_data=True, license="MIT", test_suite="forwardable.test", classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Code Generators', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ] )
true
true
1c2bf5c725262d5b1f8d86c19cab70d1597efa3a
563
gyp
Python
binding.gyp
GaikwadPratik/node-linux-pam
9249114b2efb3b1ff86b8ee2d7c12c8605faaa23
[ "MIT" ]
null
null
null
binding.gyp
GaikwadPratik/node-linux-pam
9249114b2efb3b1ff86b8ee2d7c12c8605faaa23
[ "MIT" ]
null
null
null
binding.gyp
GaikwadPratik/node-linux-pam
9249114b2efb3b1ff86b8ee2d7c12c8605faaa23
[ "MIT" ]
null
null
null
{ "targets": [ { "target_name": "node-linux-pam", "cflags!": ["-fno-exceptions"], "cflags_cc!": ["-fno-exceptions"], "sources": [ "src/index.cc", "src/pam_worker.cpp" ], 'conditions': [ ['OS=="mac"', { 'xcode_settings': { 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' } }] ], "libraries": ["-lpam"], "include_dirs": [ "<!@(node -p \"require('node-addon-api').include\")" ], "defines": ["NAPI_DISABLE_CPP_EXCEPTIONS"], } ] }
21.653846
60
0.445826
{ "targets": [ { "target_name": "node-linux-pam", "cflags!": ["-fno-exceptions"], "cflags_cc!": ["-fno-exceptions"], "sources": [ "src/index.cc", "src/pam_worker.cpp" ], 'conditions': [ ['OS=="mac"', { 'xcode_settings': { 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' } }] ], "libraries": ["-lpam"], "include_dirs": [ "<!@(node -p \"require('node-addon-api').include\")" ], "defines": ["NAPI_DISABLE_CPP_EXCEPTIONS"], } ] }
true
true
1c2bf6a63fa7b00998e842355efee74c370d0689
3,447
py
Python
pymisp/tools/vehicleobject.py
kak-bo-che/PyMISP
23d732e398471ade1d28c7ec1e61977329df07ea
[ "BSD-2-Clause" ]
null
null
null
pymisp/tools/vehicleobject.py
kak-bo-che/PyMISP
23d732e398471ade1d28c7ec1e61977329df07ea
[ "BSD-2-Clause" ]
null
null
null
pymisp/tools/vehicleobject.py
kak-bo-che/PyMISP
23d732e398471ade1d28c7ec1e61977329df07ea
[ "BSD-2-Clause" ]
null
null
null
#!/usr/bin/python3 import requests import json from .abstractgenerator import AbstractMISPObjectGenerator # Original sourcecode: https://github.com/hayk57/MISP_registration_check class VehicleObject(AbstractMISPObjectGenerator): '''Vehicle object generator out of regcheck.org.uk''' country_urls = { 'fr': "http://www.regcheck.org.uk/api/reg.asmx/CheckFrance", 'es': "http://www.regcheck.org.uk/api/reg.asmx/CheckSpain", 'uk': "http://www.regcheck.org.uk/api/reg.asmx/Check" } def __init__(self, country: str, registration: str, username: str, standalone=True, **kwargs): super(VehicleObject, self).__init__("vehicle", standalone=standalone, **kwargs) self._country = country self._registration = registration self._username = username self._report = self._query() self.generate_attributes() @property def report(self): return self._report def generate_attributes(self): carDescription = self._report["Description"] carMake = self._report["CarMake"]["CurrentTextValue"] carModel = self._report["CarModel"]["CurrentTextValue"] ImageUrl = self._report["ImageUrl"] IndicativeValue = '' if (self._country == "fr"): IndicativeValue = self._report["IndicativeValue"]["CurrentTextValue"] # BodyStyle = vehicleJson["BodyStyle"]["CurrentTextValue"] # RegistrationDate = vehicleJson["RegistrationDate"] VIN = self._report["ExtendedData"]["numSerieMoteur"] gearbox = self._report["ExtendedData"]["boiteDeVitesse"] dynoHP = self._report["ExtendedData"]["puissanceDyn"] firstRegistration = self._report["ExtendedData"]["datePremiereMiseCirculation"] self.add_attribute('dyno-power', type='text', value=dynoHP) self.add_attribute('gearbox', type='text', value=gearbox) if (self._country == "es"): IndicativeValue = self._report["IndicativePrice"] if (self._country == "es" or self._country == "uk"): firstRegistration = self._report["RegistrationYear"] VIN = self._report["VehicleIdentificationNumber"] self.add_attribute('description', type='text', value=carDescription) self.add_attribute('make', type='text', value=carMake) self.add_attribute('model', type='text', value=carModel) self.add_attribute('vin', type='text', value=VIN) self.add_attribute('license-plate-number', type='text', value=self._registration) self.add_attribute('indicative-value', type='text', value=IndicativeValue) self.add_attribute('date-first-registration', type='text', value=firstRegistration) self.add_attribute('image-url', type='text', value=ImageUrl) def _query(self): payload = "RegistrationNumber={}&username={}".format(self._registration, self._username) headers = { 'Content-Type': "application/x-www-form-urlencoded", 'cache-control': "no-cache", } response = requests.request("POST", self.country_urls.get(self._country), data=payload, headers=headers) # FIXME: Clean that up. for item in response.text.split("</vehicleJson>"): if "<vehicleJson>" in item: responseJson = item[item.find("<vehicleJson>") + len("<vehicleJson>"):] return json.loads(responseJson)
42.036585
112
0.653612
import requests import json from .abstractgenerator import AbstractMISPObjectGenerator class VehicleObject(AbstractMISPObjectGenerator): country_urls = { 'fr': "http://www.regcheck.org.uk/api/reg.asmx/CheckFrance", 'es': "http://www.regcheck.org.uk/api/reg.asmx/CheckSpain", 'uk': "http://www.regcheck.org.uk/api/reg.asmx/Check" } def __init__(self, country: str, registration: str, username: str, standalone=True, **kwargs): super(VehicleObject, self).__init__("vehicle", standalone=standalone, **kwargs) self._country = country self._registration = registration self._username = username self._report = self._query() self.generate_attributes() @property def report(self): return self._report def generate_attributes(self): carDescription = self._report["Description"] carMake = self._report["CarMake"]["CurrentTextValue"] carModel = self._report["CarModel"]["CurrentTextValue"] ImageUrl = self._report["ImageUrl"] IndicativeValue = '' if (self._country == "fr"): IndicativeValue = self._report["IndicativeValue"]["CurrentTextValue"] VIN = self._report["ExtendedData"]["numSerieMoteur"] gearbox = self._report["ExtendedData"]["boiteDeVitesse"] dynoHP = self._report["ExtendedData"]["puissanceDyn"] firstRegistration = self._report["ExtendedData"]["datePremiereMiseCirculation"] self.add_attribute('dyno-power', type='text', value=dynoHP) self.add_attribute('gearbox', type='text', value=gearbox) if (self._country == "es"): IndicativeValue = self._report["IndicativePrice"] if (self._country == "es" or self._country == "uk"): firstRegistration = self._report["RegistrationYear"] VIN = self._report["VehicleIdentificationNumber"] self.add_attribute('description', type='text', value=carDescription) self.add_attribute('make', type='text', value=carMake) self.add_attribute('model', type='text', value=carModel) self.add_attribute('vin', type='text', value=VIN) self.add_attribute('license-plate-number', type='text', value=self._registration) self.add_attribute('indicative-value', type='text', value=IndicativeValue) self.add_attribute('date-first-registration', type='text', value=firstRegistration) self.add_attribute('image-url', type='text', value=ImageUrl) def _query(self): payload = "RegistrationNumber={}&username={}".format(self._registration, self._username) headers = { 'Content-Type': "application/x-www-form-urlencoded", 'cache-control': "no-cache", } response = requests.request("POST", self.country_urls.get(self._country), data=payload, headers=headers) for item in response.text.split("</vehicleJson>"): if "<vehicleJson>" in item: responseJson = item[item.find("<vehicleJson>") + len("<vehicleJson>"):] return json.loads(responseJson)
true
true
1c2bf8b07e26a0bf34dc5b1b7d2d271c2ab8488a
2,433
py
Python
huaweicloud-sdk-vpcep/huaweicloudsdkvpcep/v1/model/delete_endpoint_response.py
huaweicloud/huaweicloud-sdk-python-v3
7a6270390fcbf192b3882bf763e7016e6026ef78
[ "Apache-2.0" ]
64
2020-06-12T07:05:07.000Z
2022-03-30T03:32:50.000Z
huaweicloud-sdk-vpcep/huaweicloudsdkvpcep/v1/model/delete_endpoint_response.py
huaweicloud/huaweicloud-sdk-python-v3
7a6270390fcbf192b3882bf763e7016e6026ef78
[ "Apache-2.0" ]
11
2020-07-06T07:56:54.000Z
2022-01-11T11:14:40.000Z
huaweicloud-sdk-vpcep/huaweicloudsdkvpcep/v1/model/delete_endpoint_response.py
huaweicloud/huaweicloud-sdk-python-v3
7a6270390fcbf192b3882bf763e7016e6026ef78
[ "Apache-2.0" ]
24
2020-06-08T11:42:13.000Z
2022-03-04T06:44:08.000Z
# coding: utf-8 import re import six from huaweicloudsdkcore.sdk_response import SdkResponse from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class DeleteEndpointResponse(SdkResponse): """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { } attribute_map = { } def __init__(self): """DeleteEndpointResponse - a model defined in huaweicloud sdk""" super(DeleteEndpointResponse, self).__init__() self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, DeleteEndpointResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
28.290698
79
0.55076
import re import six from huaweicloudsdkcore.sdk_response import SdkResponse from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class DeleteEndpointResponse(SdkResponse): sensitive_list = [] openapi_types = { } attribute_map = { } def __init__(self): super(DeleteEndpointResponse, self).__init__() self.discriminator = None def to_dict(self): result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, DeleteEndpointResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
1c2bfc2d2277fd98cef9390d253e1790f4aebd3f
153
py
Python
src/fake-email/ruks.py
AboFatma512/fake-email
d9bf3c3001a36126d34671f78bf7ed77ded7701a
[ "MIT" ]
14
2021-10-31T20:39:40.000Z
2022-01-03T15:32:42.000Z
src/fake-email/ruks.py
AboFatma512/fake-email
d9bf3c3001a36126d34671f78bf7ed77ded7701a
[ "MIT" ]
null
null
null
src/fake-email/ruks.py
AboFatma512/fake-email
d9bf3c3001a36126d34671f78bf7ed77ded7701a
[ "MIT" ]
4
2021-11-01T11:42:45.000Z
2022-01-26T14:33:59.000Z
URL = "https://10minutemail.com" EMAIL = URL + "/session/address" MESSAGE_A = URL + "/messages/messagesAfter/" MESSAGE_C = URL + "/messages/messageCount"
38.25
44
0.718954
URL = "https://10minutemail.com" EMAIL = URL + "/session/address" MESSAGE_A = URL + "/messages/messagesAfter/" MESSAGE_C = URL + "/messages/messageCount"
true
true
1c2bfd3d9326aa478d6c1164c854527ce75f53b5
5,148
py
Python
standup_and_prosper_sdk/models/thread.py
Teaminator/standup-and-prosper-sdk.py
ccdba4a24f395dc0b45d9f9da9bdf5038e1b1617
[ "Apache-2.0" ]
1
2021-09-16T08:02:35.000Z
2021-09-16T08:02:35.000Z
standup_and_prosper_sdk/models/thread.py
Teaminator/standup-and-prosper-sdk.py
ccdba4a24f395dc0b45d9f9da9bdf5038e1b1617
[ "Apache-2.0" ]
1
2021-06-14T16:45:56.000Z
2021-06-14T16:56:05.000Z
standup_and_prosper_sdk/models/thread.py
Teaminator/standup-and-prosper-sdk.py
ccdba4a24f395dc0b45d9f9da9bdf5038e1b1617
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 import pprint import re import six class Thread(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'scheduled_date': 'str', 'last_updated': 'str', 'status': 'str', 'responses': 'list[Response]', } attribute_map = { 'scheduled_date': 'scheduledDate', 'last_updated': 'lastUpdated', 'status': 'status', 'responses': 'responses', } def __init__(self, scheduled_date=None, last_updated=None, status=None, responses=None): """Thread""" self._scheduled_date = None self._last_updated = None self._status = None self._responses = None self.discriminator = None self.scheduled_date = scheduled_date self.last_updated = last_updated self.status = status self.responses = responses @property def scheduled_date(self): """Gets the scheduled_date of this Thread. Unique identifier for the record, can be specified on record creation. :return: The scheduled_date of this Thread. :rtype: str """ return self._scheduled_date @scheduled_date.setter def scheduled_date(self, scheduled_date): """Sets the scheduled_date of this Thread. Unique identifier for the record, can be specified on record creation. :param scheduled_date: The scheduled_date of this Thread. :type: str """ if scheduled_date is None: raise ValueError("Invalid value for `scheduled_date`, must not be `None`") self._scheduled_date = scheduled_date @property def last_updated(self): """Gets the last_updated of this Thread. A helpful last_updated for this record :return: The last_updated of this Thread. :rtype: str """ return self._last_updated @last_updated.setter def last_updated(self, last_updated): """Sets the last_updated of this Thread. A helpful last_updated for this record :param last_updated: The last_updated of this Thread. :type: str """ if last_updated is None: raise ValueError("Invalid value for `last_updated`, must not be `None`") self._last_updated = last_updated @property def status(self): """Gets the status of this Thread. :return: The status of this Thread. :rtype: str """ return self._status @status.setter def status(self, status): """Sets the status of this Thread. :param status: The status of this Thread. :type: str """ if status is None: raise ValueError("Invalid value for `status`, must not be `None`") self._status = status @property def responses(self): """Gets the responses of this Thread. The list of responses this record applies to :return: The responses of this Thread. :rtype: list[Response] """ return self._responses @responses.setter def responses(self, responses): """Sets the responses of this Thread. The list of responses this record applies to :param responses: The responses of this Thread. :type: list[Response] """ if responses is None: raise ValueError("Invalid value for `responses`, must not be `None`") self._responses = responses def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Thread, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, Thread): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
27.677419
94
0.582168
import pprint import re import six class Thread(object): swagger_types = { 'scheduled_date': 'str', 'last_updated': 'str', 'status': 'str', 'responses': 'list[Response]', } attribute_map = { 'scheduled_date': 'scheduledDate', 'last_updated': 'lastUpdated', 'status': 'status', 'responses': 'responses', } def __init__(self, scheduled_date=None, last_updated=None, status=None, responses=None): self._scheduled_date = None self._last_updated = None self._status = None self._responses = None self.discriminator = None self.scheduled_date = scheduled_date self.last_updated = last_updated self.status = status self.responses = responses @property def scheduled_date(self): return self._scheduled_date @scheduled_date.setter def scheduled_date(self, scheduled_date): if scheduled_date is None: raise ValueError("Invalid value for `scheduled_date`, must not be `None`") self._scheduled_date = scheduled_date @property def last_updated(self): return self._last_updated @last_updated.setter def last_updated(self, last_updated): if last_updated is None: raise ValueError("Invalid value for `last_updated`, must not be `None`") self._last_updated = last_updated @property def status(self): return self._status @status.setter def status(self, status): if status is None: raise ValueError("Invalid value for `status`, must not be `None`") self._status = status @property def responses(self): return self._responses @responses.setter def responses(self, responses): if responses is None: raise ValueError("Invalid value for `responses`, must not be `None`") self._responses = responses def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Thread, dict): for key, value in self.items(): result[key] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, Thread): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
1c2bff6e021e13c1039c359c5299324d5c99df91
225
py
Python
mydays/01-03/01.py
josephrewald/100daysofcode-with-python-course
b51dfbf786c1a89694c4661805ef930516683439
[ "MIT" ]
null
null
null
mydays/01-03/01.py
josephrewald/100daysofcode-with-python-course
b51dfbf786c1a89694c4661805ef930516683439
[ "MIT" ]
null
null
null
mydays/01-03/01.py
josephrewald/100daysofcode-with-python-course
b51dfbf786c1a89694c4661805ef930516683439
[ "MIT" ]
null
null
null
from datetime import datetime from datetime import date from datetime import timedelta today = datetime.today() print(today) t = timedelta(days=4, hours=10) second = timedelta(seconds=1) seconds = t/second print(seconds)
16.071429
31
0.773333
from datetime import datetime from datetime import date from datetime import timedelta today = datetime.today() print(today) t = timedelta(days=4, hours=10) second = timedelta(seconds=1) seconds = t/second print(seconds)
true
true
1c2c000c1996218df929d4fbfc623e469922b650
677
py
Python
myapp/models.py
Palash51/kd
2f28adbff98756a84906a4170b428c3298e9273d
[ "MIT" ]
null
null
null
myapp/models.py
Palash51/kd
2f28adbff98756a84906a4170b428c3298e9273d
[ "MIT" ]
null
null
null
myapp/models.py
Palash51/kd
2f28adbff98756a84906a4170b428c3298e9273d
[ "MIT" ]
null
null
null
# from django.db import models # # Create your models here. # class RegistrationForm(models.Model): # first_name = models.CharField(max_length=45) # last_name = models.CharField(max_length=45) # email = models.EmailField() # password = models.CharField(max_length=100)#,widget=models.PasswordInput) # confirm_password = models.CharField(max_length=100)#,widget=models.PasswordInput) from __future__ import unicode_literals from django.db import models # Create your models here. class Crop_details(models.Model): Name = models.CharField(max_length=30) Phone = models.IntegerField() FieldLocation = models.CharField(max_length=30) CropAcres = models.IntegerField()
32.238095
84
0.781388
Crop_details(models.Model): Name = models.CharField(max_length=30) Phone = models.IntegerField() FieldLocation = models.CharField(max_length=30) CropAcres = models.IntegerField()
true
true
1c2c00a0ece3ea72ebeb3dcb891cf8b8a73360b4
11,136
py
Python
euca2ools/commands/argtypes.py
sjones4/euca2ools
03b0e421eeebd8f402422a0ad6994bd6ee4e4127
[ "BSD-2-Clause" ]
null
null
null
euca2ools/commands/argtypes.py
sjones4/euca2ools
03b0e421eeebd8f402422a0ad6994bd6ee4e4127
[ "BSD-2-Clause" ]
null
null
null
euca2ools/commands/argtypes.py
sjones4/euca2ools
03b0e421eeebd8f402422a0ad6994bd6ee4e4127
[ "BSD-2-Clause" ]
null
null
null
# Copyright 2012-2014 Eucalyptus Systems, Inc. # # Redistribution and use of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import argparse import base64 import sys from requestbuilder import EMPTY def manifest_block_device_mappings(mappings_as_str): mappings = {} mapping_strs = mappings_as_str.split(',') for mapping_str in mapping_strs: if mapping_str.strip(): bits = mapping_str.strip().split('=') if len(bits) == 2: mappings[bits[0].strip()] = bits[1].strip() else: raise argparse.ArgumentTypeError( "invalid device mapping '{0}' (must have format " "'VIRTUAL=DEVICE')".format(mapping_str)) return mappings def ec2_block_device_mapping(map_as_str): """ Parse a block device mapping from an image registration command line. """ try: (device, mapping) = map_as_str.split('=') except ValueError: raise argparse.ArgumentTypeError( 'block device mapping "{0}" must have form DEVICE=MAPPED' .format(map_as_str)) map_dict = {'DeviceName': device} if mapping.lower() == 'none': map_dict['NoDevice'] = 'true' elif mapping.startswith('ephemeral'): map_dict['VirtualName'] = mapping elif (mapping.startswith('snap-') or mapping.startswith('vol-') or mapping.startswith(':')): map_bits = mapping.split(':') while len(map_bits) < 5: map_bits.append(None) if len(map_bits) != 5: raise argparse.ArgumentTypeError( 'EBS block device mapping "{0}" must have form ' 'DEVICE=[SNAP-ID]:[GiB]:[true|false]:[standard|TYPE[:IOPS]]' .format(map_as_str)) map_dict['Ebs'] = {} if map_bits[0]: map_dict['Ebs']['SnapshotId'] = map_bits[0] if map_bits[1]: try: map_dict['Ebs']['VolumeSize'] = int(map_bits[1]) except ValueError: raise argparse.ArgumentTypeError( 'second element of EBS block device mapping "{0}" must be ' 'an integer'.format(map_as_str)) if map_bits[2]: if map_bits[2].lower() not in ('true', 'false'): raise argparse.ArgumentTypeError( 'third element of EBS block device mapping "{0}" must be ' '"true" or "false"'.format(map_as_str)) map_dict['Ebs']['DeleteOnTermination'] = map_bits[2].lower() if map_bits[3]: map_dict['Ebs']['VolumeType'] = map_bits[3] if map_bits[4]: if map_bits[3] == 'standard': raise argparse.ArgumentTypeError( 'fifth element of EBS block device mapping "{0}" is not ' 'allowed with volume type "standard"'.format(map_as_str)) map_dict['Ebs']['Iops'] = map_bits[4] if not map_dict['Ebs']: raise argparse.ArgumentTypeError( 'EBS block device mapping "{0}" must specify at least one ' 'element. Use "{1}=none" to suppress an existing mapping.' .format(map_as_str, device)) elif not mapping: raise argparse.ArgumentTypeError( 'invalid block device mapping "{0}". Use "{1}=none" to suppress ' 'an existing mapping.'.format(map_as_str, device)) else: raise argparse.ArgumentTypeError( 'invalid block device mapping "{0}"'.format(map_as_str)) return map_dict def flexible_bool(bool_str): if bool_str.strip().lower() in ('0', 'f', 'false', 'n', 'no'): return False if bool_str.strip().lower() in ('1', 't', 'true', 'y', 'yes'): return True raise TypeError("'{0}' must be 'true' or 'false'".format(bool_str)) def filesize(size): suffixes = 'kmgt' s_size = size.lower().rstrip('b') if len(s_size) > 0 and s_size[-1] in suffixes: multiplier = 1024 ** (suffixes.find(s_size[-1]) + 1) s_size = s_size[:-1] else: multiplier = 1 return multiplier * int(s_size) def vpc_interface(iface_as_str): """ Nine-part VPC network interface definition: [INTERFACE]:INDEX:[SUBNET]:[DESCRIPTION]:[PRIV_IP]:[GROUP1,GROUP2,...]: [true|false]:[SEC_IP_COUNT|:SEC_IP1,SEC_IP2,...] """ if len(iface_as_str) == 0: raise argparse.ArgumentTypeError( 'network interface definitions must be non-empty'.format( iface_as_str)) bits = iface_as_str.split(':') iface = {} if len(bits) < 2: raise argparse.ArgumentTypeError( 'network interface definition "{0}" must consist of at least 2 ' 'elements ({1} provided)'.format(iface_as_str, len(bits))) elif len(bits) > 9: raise argparse.ArgumentTypeError( 'network interface definition "{0}" must consist of at most 9 ' 'elements ({1} provided)'.format(iface_as_str, len(bits))) while len(bits) < 9: bits.append(None) if bits[0]: # Preexisting NetworkInterfaceId if bits[0].startswith('eni-') and len(bits[0]) == 12: iface['NetworkInterfaceId'] = bits[0] else: raise argparse.ArgumentTypeError( 'first element of network interface definition "{0}" must be ' 'a network interface ID'.format(iface_as_str)) if bits[1]: # DeviceIndex try: iface['DeviceIndex'] = int(bits[1]) except ValueError: raise argparse.ArgumentTypeError( 'second element of network interface definition "{0}" must be ' 'an integer'.format(iface_as_str)) else: raise argparse.ArgumentTypeError( 'second element of network interface definition "{0}" must be ' 'non-empty'.format(iface_as_str)) if bits[2]: # SubnetId if bits[2].startswith('subnet-'): iface['SubnetId'] = bits[2] else: raise argparse.ArgumentTypeError( 'third element of network interface definition "{0}" must be ' 'a subnet ID'.format(iface_as_str)) if bits[3]: # Description iface['Description'] = bits[3] if bits[4]: # PrivateIpAddresses.n.PrivateIpAddress # PrivateIpAddresses.n.Primary iface.setdefault('PrivateIpAddresses', []) iface['PrivateIpAddresses'].append({'PrivateIpAddress': bits[4], 'Primary': 'true'}) if bits[5]: # SecurityGroupId.n groups = [bit for bit in bits[5].split(',') if bit] if not all(group.startswith('sg-') for group in groups): raise argparse.ArgumentTypeError( 'sixth element of network interface definition "{0}" must ' 'refer to security groups by IDs, not names' .format(iface_as_str)) iface['SecurityGroupId'] = groups if bits[6]: # DeleteOnTermination if bits[6] in ('true', 'false'): iface['DeleteOnTermination'] = bits[6] else: raise argparse.ArgumentTypeError( 'seventh element of network interface definition "{0}" ' 'must be "true" or "false"'.format(iface_as_str)) if bits[7]: # SecondaryPrivateIpAddressCount if bits[8]: raise argparse.ArgumentTypeError( 'eighth and ninth elements of network interface definition ' '"{0}" must not both be non-empty'.format(iface_as_str)) try: iface['SecondaryPrivateIpAddressCount'] = int(bits[7]) except ValueError: raise argparse.ArgumentTypeError( 'eighth element of network interface definition "{0}" must be ' 'an integer'.format(iface_as_str)) if bits[8]: # PrivateIpAddresses.n.PrivateIpAddress sec_ips = [{'PrivateIpAddress': addr} for addr in bits[8].split(',') if addr] iface.setdefault('PrivateIpAddresses', []) iface['PrivateIpAddresses'].extend(sec_ips) return iface def file_contents(filename): if filename == '-': return sys.stdin.read() else: with open(filename) as arg_file: return arg_file.read() def b64encoded_file_contents(filename): if filename == '-': return base64.b64encode(sys.stdin.read()) else: with open(filename) as arg_file: return base64.b64encode(arg_file.read()) def binary_tag_def(tag_str): """ Parse a tag definition from the command line. Return a dict that depends on the format of the string given: - 'key=value': {'Key': key, 'Value': value} - 'key=': {'Key': key, 'Value': EMPTY} - 'key': {'Key': key, 'Value': EMPTY} """ if '=' in tag_str: (key, val) = tag_str.split('=', 1) return {'Key': key, 'Value': val or EMPTY} else: return {'Key': tag_str, 'Value': EMPTY} def ternary_tag_def(tag_str): """ Parse a tag definition from the command line. Return a dict that depends on the format of the string given: - 'key=value': {'Key': key, 'Value': value} - 'key=': {'Key': key, 'Value': EMPTY} - 'key': {'Key': key} """ if '=' in tag_str: (key, val) = tag_str.split('=', 1) return {'Key': key, 'Value': val or EMPTY} else: return {'Key': tag_str} def delimited_list(delimiter, item_type=str): def _concrete_delimited_list(list_as_str): if isinstance(list_as_str, str) and len(list_as_str) > 0: return [item_type(item.strip()) for item in list_as_str.split(delimiter) if len(item.strip()) > 0] else: return [] return _concrete_delimited_list
38.532872
79
0.599497
import argparse import base64 import sys from requestbuilder import EMPTY def manifest_block_device_mappings(mappings_as_str): mappings = {} mapping_strs = mappings_as_str.split(',') for mapping_str in mapping_strs: if mapping_str.strip(): bits = mapping_str.strip().split('=') if len(bits) == 2: mappings[bits[0].strip()] = bits[1].strip() else: raise argparse.ArgumentTypeError( "invalid device mapping '{0}' (must have format " "'VIRTUAL=DEVICE')".format(mapping_str)) return mappings def ec2_block_device_mapping(map_as_str): try: (device, mapping) = map_as_str.split('=') except ValueError: raise argparse.ArgumentTypeError( 'block device mapping "{0}" must have form DEVICE=MAPPED' .format(map_as_str)) map_dict = {'DeviceName': device} if mapping.lower() == 'none': map_dict['NoDevice'] = 'true' elif mapping.startswith('ephemeral'): map_dict['VirtualName'] = mapping elif (mapping.startswith('snap-') or mapping.startswith('vol-') or mapping.startswith(':')): map_bits = mapping.split(':') while len(map_bits) < 5: map_bits.append(None) if len(map_bits) != 5: raise argparse.ArgumentTypeError( 'EBS block device mapping "{0}" must have form ' 'DEVICE=[SNAP-ID]:[GiB]:[true|false]:[standard|TYPE[:IOPS]]' .format(map_as_str)) map_dict['Ebs'] = {} if map_bits[0]: map_dict['Ebs']['SnapshotId'] = map_bits[0] if map_bits[1]: try: map_dict['Ebs']['VolumeSize'] = int(map_bits[1]) except ValueError: raise argparse.ArgumentTypeError( 'second element of EBS block device mapping "{0}" must be ' 'an integer'.format(map_as_str)) if map_bits[2]: if map_bits[2].lower() not in ('true', 'false'): raise argparse.ArgumentTypeError( 'third element of EBS block device mapping "{0}" must be ' '"true" or "false"'.format(map_as_str)) map_dict['Ebs']['DeleteOnTermination'] = map_bits[2].lower() if map_bits[3]: map_dict['Ebs']['VolumeType'] = map_bits[3] if map_bits[4]: if map_bits[3] == 'standard': raise argparse.ArgumentTypeError( 'fifth element of EBS block device mapping "{0}" is not ' 'allowed with volume type "standard"'.format(map_as_str)) map_dict['Ebs']['Iops'] = map_bits[4] if not map_dict['Ebs']: raise argparse.ArgumentTypeError( 'EBS block device mapping "{0}" must specify at least one ' 'element. Use "{1}=none" to suppress an existing mapping.' .format(map_as_str, device)) elif not mapping: raise argparse.ArgumentTypeError( 'invalid block device mapping "{0}". Use "{1}=none" to suppress ' 'an existing mapping.'.format(map_as_str, device)) else: raise argparse.ArgumentTypeError( 'invalid block device mapping "{0}"'.format(map_as_str)) return map_dict def flexible_bool(bool_str): if bool_str.strip().lower() in ('0', 'f', 'false', 'n', 'no'): return False if bool_str.strip().lower() in ('1', 't', 'true', 'y', 'yes'): return True raise TypeError("'{0}' must be 'true' or 'false'".format(bool_str)) def filesize(size): suffixes = 'kmgt' s_size = size.lower().rstrip('b') if len(s_size) > 0 and s_size[-1] in suffixes: multiplier = 1024 ** (suffixes.find(s_size[-1]) + 1) s_size = s_size[:-1] else: multiplier = 1 return multiplier * int(s_size) def vpc_interface(iface_as_str): if len(iface_as_str) == 0: raise argparse.ArgumentTypeError( 'network interface definitions must be non-empty'.format( iface_as_str)) bits = iface_as_str.split(':') iface = {} if len(bits) < 2: raise argparse.ArgumentTypeError( 'network interface definition "{0}" must consist of at least 2 ' 'elements ({1} provided)'.format(iface_as_str, len(bits))) elif len(bits) > 9: raise argparse.ArgumentTypeError( 'network interface definition "{0}" must consist of at most 9 ' 'elements ({1} provided)'.format(iface_as_str, len(bits))) while len(bits) < 9: bits.append(None) if bits[0]: if bits[0].startswith('eni-') and len(bits[0]) == 12: iface['NetworkInterfaceId'] = bits[0] else: raise argparse.ArgumentTypeError( 'first element of network interface definition "{0}" must be ' 'a network interface ID'.format(iface_as_str)) if bits[1]: try: iface['DeviceIndex'] = int(bits[1]) except ValueError: raise argparse.ArgumentTypeError( 'second element of network interface definition "{0}" must be ' 'an integer'.format(iface_as_str)) else: raise argparse.ArgumentTypeError( 'second element of network interface definition "{0}" must be ' 'non-empty'.format(iface_as_str)) if bits[2]: if bits[2].startswith('subnet-'): iface['SubnetId'] = bits[2] else: raise argparse.ArgumentTypeError( 'third element of network interface definition "{0}" must be ' 'a subnet ID'.format(iface_as_str)) if bits[3]: iface['Description'] = bits[3] if bits[4]: iface.setdefault('PrivateIpAddresses', []) iface['PrivateIpAddresses'].append({'PrivateIpAddress': bits[4], 'Primary': 'true'}) if bits[5]: groups = [bit for bit in bits[5].split(',') if bit] if not all(group.startswith('sg-') for group in groups): raise argparse.ArgumentTypeError( 'sixth element of network interface definition "{0}" must ' 'refer to security groups by IDs, not names' .format(iface_as_str)) iface['SecurityGroupId'] = groups if bits[6]: if bits[6] in ('true', 'false'): iface['DeleteOnTermination'] = bits[6] else: raise argparse.ArgumentTypeError( 'seventh element of network interface definition "{0}" ' 'must be "true" or "false"'.format(iface_as_str)) if bits[7]: if bits[8]: raise argparse.ArgumentTypeError( 'eighth and ninth elements of network interface definition ' '"{0}" must not both be non-empty'.format(iface_as_str)) try: iface['SecondaryPrivateIpAddressCount'] = int(bits[7]) except ValueError: raise argparse.ArgumentTypeError( 'eighth element of network interface definition "{0}" must be ' 'an integer'.format(iface_as_str)) if bits[8]: sec_ips = [{'PrivateIpAddress': addr} for addr in bits[8].split(',') if addr] iface.setdefault('PrivateIpAddresses', []) iface['PrivateIpAddresses'].extend(sec_ips) return iface def file_contents(filename): if filename == '-': return sys.stdin.read() else: with open(filename) as arg_file: return arg_file.read() def b64encoded_file_contents(filename): if filename == '-': return base64.b64encode(sys.stdin.read()) else: with open(filename) as arg_file: return base64.b64encode(arg_file.read()) def binary_tag_def(tag_str): if '=' in tag_str: (key, val) = tag_str.split('=', 1) return {'Key': key, 'Value': val or EMPTY} else: return {'Key': tag_str, 'Value': EMPTY} def ternary_tag_def(tag_str): if '=' in tag_str: (key, val) = tag_str.split('=', 1) return {'Key': key, 'Value': val or EMPTY} else: return {'Key': tag_str} def delimited_list(delimiter, item_type=str): def _concrete_delimited_list(list_as_str): if isinstance(list_as_str, str) and len(list_as_str) > 0: return [item_type(item.strip()) for item in list_as_str.split(delimiter) if len(item.strip()) > 0] else: return [] return _concrete_delimited_list
true
true
1c2c0160bc99a9415b825ead5aeb916195464fa4
1,773
py
Python
RecursiveDescentAnalysis/TheoreticalParser.py
Miosolo/C-Lanaguage-Compiler
f38459e0a27b0e71eaad81fe3d3c25d72f3a0ca0
[ "MIT" ]
null
null
null
RecursiveDescentAnalysis/TheoreticalParser.py
Miosolo/C-Lanaguage-Compiler
f38459e0a27b0e71eaad81fe3d3c25d72f3a0ca0
[ "MIT" ]
null
null
null
RecursiveDescentAnalysis/TheoreticalParser.py
Miosolo/C-Lanaguage-Compiler
f38459e0a27b0e71eaad81fe3d3c25d72f3a0ca0
[ "MIT" ]
null
null
null
class Parser(object): V_N = ['E', 'e', 'T', 't', 'F'] first = { 'E': ['(', 'i'], 'e': ['+', '-'], 'T': ['(', 'i'], 't': ['*', '/'], 'F': ['(', 'i'] } follow = { 'E': [')', '#'], 'e': [')', '#'], 'T': ['+', '-', '#', ')'], 't': ['+', '-', '#', ')'], 'F': ['+', '-', '*', '/', ')', '#'] } producer = { 'E': [['T', 'e']], 'e': [['+', 'T', 'e'], ['-', 'T', 'e']], 'T': [['F', 't']], 't': [['*', 'F', 't'], ['/', 'F', 't']], 'F': [['(', 'E', ')'], ['i']] } def __init__(self, inputFileLocation): try: with open(inputFileLocation, 'r') as f: self.source = f.read() self.index = 0 except IOError: print("Open Source File Failed.") def step(self): try: self.sym = self.source[self.index] self.index += 1 except IndexError: self.sym = '#' def implement(self, seed): if self.sym in self.first[seed]: prods = [p for p in filter(lambda p: p[0] == self.sym or\ (p[0] in self.V_N and self.sym in self.first[p[0]]), self.producer[seed])] # then prods should be a len(1) list prod = prods[0] for v in prod: if v in self.V_N: if self.implement(v) == True: # 表达式可解析 pass else: return False else: # v in V_T if v == self.sym: self.step() else: # V_T not match return False else: return True elif self.sym in self.follow[seed]: return True else: # this char in neither FIRST() nor FOLLOW() return False def parse(self): self.step() return self.implement('E') and self.sym == '#'
23.025974
109
0.400451
class Parser(object): V_N = ['E', 'e', 'T', 't', 'F'] first = { 'E': ['(', 'i'], 'e': ['+', '-'], 'T': ['(', 'i'], 't': ['*', '/'], 'F': ['(', 'i'] } follow = { 'E': [')', '#'], 'e': [')', '#'], 'T': ['+', '-', '#', ')'], 't': ['+', '-', '#', ')'], 'F': ['+', '-', '*', '/', ')', '#'] } producer = { 'E': [['T', 'e']], 'e': [['+', 'T', 'e'], ['-', 'T', 'e']], 'T': [['F', 't']], 't': [['*', 'F', 't'], ['/', 'F', 't']], 'F': [['(', 'E', ')'], ['i']] } def __init__(self, inputFileLocation): try: with open(inputFileLocation, 'r') as f: self.source = f.read() self.index = 0 except IOError: print("Open Source File Failed.") def step(self): try: self.sym = self.source[self.index] self.index += 1 except IndexError: self.sym = '#' def implement(self, seed): if self.sym in self.first[seed]: prods = [p for p in filter(lambda p: p[0] == self.sym or\ (p[0] in self.V_N and self.sym in self.first[p[0]]), self.producer[seed])] prod = prods[0] for v in prod: if v in self.V_N: if self.implement(v) == True: pass else: return False else: if v == self.sym: self.step() else: return False else: return True elif self.sym in self.follow[seed]: return True else: return False def parse(self): self.step() return self.implement('E') and self.sym == '#'
true
true
1c2c01ba70600600132778eea97a6611aed1f678
7,415
py
Python
script.py
cgalaz01/acur_mri
3be85e62a3362f9498169edb87c233e4da35ddd8
[ "MIT" ]
null
null
null
script.py
cgalaz01/acur_mri
3be85e62a3362f9498169edb87c233e4da35ddd8
[ "MIT" ]
null
null
null
script.py
cgalaz01/acur_mri
3be85e62a3362f9498169edb87c233e4da35ddd8
[ "MIT" ]
null
null
null
import argparse from pathlib import Path from functions import anonymise_mri, catalogue, dicom_sort, sequence def parse_arguments() -> argparse.Namespace: """ Defines all accepted arguments. Returns ------- args : argparse.Namespace Values of the passed arguments. """ parser = argparse.ArgumentParser(description='Script to prepare the data.' + 'One flag should be given at a time.') parser.add_argument('-a', '--anonymise', action='store_true', help='Anonymises patient information in DICOM files. ' + 'Requires source and target directories.') parser.add_argument('-s', '--sort', action='store_true', help='Sorts the DICOM ' + 'files into subfolders based on the sequence descriptions' + ' per patient. Requires source and target directories.') parser.add_argument('-d', '--descriptions', action='store_true', help='Stores in a ' + 'csv file all the unique sequence descritipns found in the sorted ' + 'directory. This file is used for the renaming process.' + 'Requires source directory.') parser.add_argument('-r', '--rename', action='store_true', help='Renames specified' + ' sequences based on the csv file in the sorted directory.' + ' Requires target directory.') parser.add_argument('-o', '--sequence-overview', action='store_true', help='Generates a csv and HTML files with which sequence' + 'descriptions are available for each patient. Requires' + ' source directory.') parser.add_argument('-v', '--validate', action='store_true', help='Validates' + ' the files between the anonymised and sorted directory.' + ' Requires source and target directories.') parser.add_argument('-c', '--catalogue', action='store_true', help='Catalogues and visualises the sequqnce descriptors' + ' for the data. Requires source directory.') parser.add_argument('--source', nargs='?', default='', help='The source directory path (read-only).') parser.add_argument('--target', nargs='?', default='', help='The target directory path (create/modify).') args = parser.parse_args() return args def anonymise(source_directory: str, target_directory: str) -> None: """ Executes DICOM anonymise function. Parameters ---------- source_directory : str The directory containing the original DICOM files. target_directory : str The destination directory in which the anonymised DICOM files will be copied to. Returns ------- None """ if not source_directory: print("'source' is required for 'anonymise' operation.") if not target_directory: print("'target' is required for 'anonymise' operation.") anonymisation = anonymise_mri.Anonymisation('record_linkage.json', Path(source_directory), Path(target_directory)) anonymisation.anonymise() def sort(source_directory: str, target_directory: str) -> None: """ Executes DICOM sort function. Parameters ---------- source_directory : str The directory containing the unsorted DICOM files. target_directory : str The destination directory in which the sorted DICOM files will be copied to. Returns ------- None """ if not source_directory: print("'source' is required for 'sort' operation.") if not target_directory: print("'target' is required for 'sort' operation.") dicom_sort.sort(Path(source_directory), Path(target_directory)) def validate(source_directory: str, target_directory: str) -> None: """ Executes sort validation function. Parameters ---------- source_directory : str The directory containing the unsorted DICOM files. target_directory : str The directory containing the sorted DICOM files. Returns ------- None """ if not source_directory: print("'source' is required for 'validate' operation.") if not target_directory: print("'target' is required for 'validate' operation.") dicom_sort.validate(Path(source_directory), Path(target_directory)) def descriptions(source_directory: str) -> None: """ Executes sequence descriptions functoin, storing results into a csv file. Parameters ---------- source_directory : str The sorted direcotry. Returns ------- None """ if not source_directory: print("'source' is required for 'descriptions' operation.") unique_descriptions = sequence.get_descriptions(Path(source_directory)) sequence.create_csv_descriptions(unique_descriptions) def rename(target_directory: str) -> None: """ Executes rename function. Parameters ---------- target_directory : str The sorted directory. Returns ------- None """ if not target_directory: print("'target' is required for 'rename' operation.") sequence.rename_descriptors(Path(target_directory), None) def sequence_overview(source_directory: str) -> None: """ Executes patient sequence descriptions overview function. Parameters ---------- source_directory : str The sorted directory. Returns ------- None """ if not source_directory: print("'source' is required for 'sequence_overview' operation.") sequence.create_html_csv_table(Path(source_directory)) def catalogue_overview(source_directory: str) -> None: """ Parameters ---------- source_directory : str DESCRIPTION. Returns ------- None """ if not source_directory: print("'source' is required for 'catalogue' operation.") catalogue.overview(source_directory) if __name__ == '__main__': args = parse_arguments() if args.anonymise: anonymise(args.source.strip(), args.target.strip()) print("Finished executing 'anonymise'.") elif args.sort: sort(args.source.strip(), args.target.strip()) print("Finished executing 'sort'.") elif args.validate: validate(args.source.strip(), args.target.strip()) print("Finished executing 'validate'.") elif args.descriptions: descriptions(args.source.strip()) print("Finished executing 'descriptions'.") elif args.rename: rename(args.target.strip()) print("Finished executing 'rename'.") elif args.sequence_overview: sequence_overview(args.source.strip()) print("Finished executing 'sequence_overview'.") elif args.catalogue: catalogue_overview(args.source.strip()) print("Finished executing 'catalogue'.") else: print('No flags passed. Terminating...')
30.142276
94
0.599191
import argparse from pathlib import Path from functions import anonymise_mri, catalogue, dicom_sort, sequence def parse_arguments() -> argparse.Namespace: parser = argparse.ArgumentParser(description='Script to prepare the data.' + 'One flag should be given at a time.') parser.add_argument('-a', '--anonymise', action='store_true', help='Anonymises patient information in DICOM files. ' + 'Requires source and target directories.') parser.add_argument('-s', '--sort', action='store_true', help='Sorts the DICOM ' + 'files into subfolders based on the sequence descriptions' + ' per patient. Requires source and target directories.') parser.add_argument('-d', '--descriptions', action='store_true', help='Stores in a ' + 'csv file all the unique sequence descritipns found in the sorted ' + 'directory. This file is used for the renaming process.' + 'Requires source directory.') parser.add_argument('-r', '--rename', action='store_true', help='Renames specified' + ' sequences based on the csv file in the sorted directory.' + ' Requires target directory.') parser.add_argument('-o', '--sequence-overview', action='store_true', help='Generates a csv and HTML files with which sequence' + 'descriptions are available for each patient. Requires' + ' source directory.') parser.add_argument('-v', '--validate', action='store_true', help='Validates' + ' the files between the anonymised and sorted directory.' + ' Requires source and target directories.') parser.add_argument('-c', '--catalogue', action='store_true', help='Catalogues and visualises the sequqnce descriptors' + ' for the data. Requires source directory.') parser.add_argument('--source', nargs='?', default='', help='The source directory path (read-only).') parser.add_argument('--target', nargs='?', default='', help='The target directory path (create/modify).') args = parser.parse_args() return args def anonymise(source_directory: str, target_directory: str) -> None: if not source_directory: print("'source' is required for 'anonymise' operation.") if not target_directory: print("'target' is required for 'anonymise' operation.") anonymisation = anonymise_mri.Anonymisation('record_linkage.json', Path(source_directory), Path(target_directory)) anonymisation.anonymise() def sort(source_directory: str, target_directory: str) -> None: if not source_directory: print("'source' is required for 'sort' operation.") if not target_directory: print("'target' is required for 'sort' operation.") dicom_sort.sort(Path(source_directory), Path(target_directory)) def validate(source_directory: str, target_directory: str) -> None: if not source_directory: print("'source' is required for 'validate' operation.") if not target_directory: print("'target' is required for 'validate' operation.") dicom_sort.validate(Path(source_directory), Path(target_directory)) def descriptions(source_directory: str) -> None: if not source_directory: print("'source' is required for 'descriptions' operation.") unique_descriptions = sequence.get_descriptions(Path(source_directory)) sequence.create_csv_descriptions(unique_descriptions) def rename(target_directory: str) -> None: if not target_directory: print("'target' is required for 'rename' operation.") sequence.rename_descriptors(Path(target_directory), None) def sequence_overview(source_directory: str) -> None: if not source_directory: print("'source' is required for 'sequence_overview' operation.") sequence.create_html_csv_table(Path(source_directory)) def catalogue_overview(source_directory: str) -> None: if not source_directory: print("'source' is required for 'catalogue' operation.") catalogue.overview(source_directory) if __name__ == '__main__': args = parse_arguments() if args.anonymise: anonymise(args.source.strip(), args.target.strip()) print("Finished executing 'anonymise'.") elif args.sort: sort(args.source.strip(), args.target.strip()) print("Finished executing 'sort'.") elif args.validate: validate(args.source.strip(), args.target.strip()) print("Finished executing 'validate'.") elif args.descriptions: descriptions(args.source.strip()) print("Finished executing 'descriptions'.") elif args.rename: rename(args.target.strip()) print("Finished executing 'rename'.") elif args.sequence_overview: sequence_overview(args.source.strip()) print("Finished executing 'sequence_overview'.") elif args.catalogue: catalogue_overview(args.source.strip()) print("Finished executing 'catalogue'.") else: print('No flags passed. Terminating...')
true
true
1c2c01cdaa60e2de80735ae30dcb81a40e4f8ccd
3,055
py
Python
python/chapter10.py
Rokon-Uz-Zaman/thinkdiff_python_django
5010c5f1dd8a028fb9e5235319bb6bb434831e6c
[ "MIT" ]
92
2018-04-03T20:53:07.000Z
2022-03-04T05:53:10.000Z
python-language/python-beginner/chapter10.py
mostafijur-rahman299/thinkdiff
b0e0c01fe38c406f4dfa8cc80b2f0c5654017079
[ "MIT" ]
11
2018-10-01T15:35:33.000Z
2021-09-01T04:59:56.000Z
python-language/python-beginner/chapter10.py
mostafijur-rahman299/thinkdiff
b0e0c01fe38c406f4dfa8cc80b2f0c5654017079
[ "MIT" ]
98
2018-03-13T08:03:54.000Z
2022-03-22T08:11:44.000Z
# author: Mahmud Ahsan # code: https://github.com/mahmudahsan/thinkdiff # blog: http://thinkdiff.net # http://pythonbangla.com # MIT License # -------------------- # Exception # -------------------- ''' Exception are object in Python that arise runtime to handle error ''' ## Hello Exception def div(x, y): return x / y print ( div(4, 2) ) # print ( div(2, 0) ) # division by zero error ## try catch block def div(x, y): try: result = x / y except ZeroDivisionError: print ("Can not divide by zero") return None return result print ( div(4, 2) ) print ( div(2, 0) ) ## Catch all exceptions def div(x, y): try: result = x / y except ZeroDivisionError: print ("Can not divide by zero") return None except: print ("Error occurred") return None return result print ( div('5', '4') ) print ( div(2, 0) ) ## Catch all exceptions 2 def div(x, y): try: result = x / y except Exception as e: print ("Error happened: ", e) return None return result print ( div('4', '2') ) print ( div(4, 0) ) ## else block try: div_result = div(8, 2) # div_result = div(2, 0) except: print ("Division by zero not possible") else: print ("Div result is: " + str(div_result)) ## finally block for clean up actions def div(x, y): try: result = x / y except ZeroDivisionError: print ("Error Division by Zero") else: print ("Result is: ", result) finally: print ("Execute finally clause") div (100, 10) div (2, 0) # div ('30', '5') # TypeError ### When finally is necessary ''' # sample example for discussion try: big_data = read_from_internet() except: pass else: # do something on big_data finally: big_data = None ''' ## Ignore exception by pass try: div_result = div(2, 0) except: pass # do nothing else: print ("Div result is: " + str(div_result)) ## Multiple exceptions try: disk_file = open('filename') except (FileNotFoundError, PermissionError): # using tuple print ("Can not open the file") try: disk_file = open('filename') except FileNotFoundError: print ("File doesn't exist") except PermissionError: print ("Permission denied to open the file") ## Creating custom exception class VowelNotAccepted(Exception): def __init__(self, message, status): super().__init__(message, status) self.message = message self.status = status def check_chars(word): for char in word: if char.lower() in ['a', 'e', 'i', 'o', 'u']: raise VowelNotAccepted("Vowel is not accepted", 101) return word # print ( check_chars("love")) try: print ( check_chars("love")) # print ( check_chars('My') ) except Exception as e: print ("Error reason: " , e.message) # Built-in exceptions ''' https://docs.python.org/3/library/exceptions.html '''
20.782313
65
0.582651
return x / y print ( div(4, 2) ) = x / y except ZeroDivisionError: print ("Can not divide by zero") return None return result print ( div(4, 2) ) print ( div(2, 0) ) result = x / y except ZeroDivisionError: print ("Can not divide by zero") return None except: print ("Error occurred") return None return result print ( div('5', '4') ) print ( div(2, 0) ) result = x / y except Exception as e: print ("Error happened: ", e) return None return result print ( div('4', '2') ) print ( div(4, 0) ) v_result = div(8, 2) except: print ("Division by zero not possible") else: print ("Div result is: " + str(div_result)) ult = x / y except ZeroDivisionError: print ("Error Division by Zero") else: print ("Result is: ", result) finally: print ("Execute finally clause") div (100, 10) div (2, 0) " + str(div_result)) open('filename') except (FileNotFoundError, PermissionError): print ("Can not open the file") try: disk_file = open('filename') except FileNotFoundError: print ("File doesn't exist") except PermissionError: print ("Permission denied to open the file") ## Creating custom exception class VowelNotAccepted(Exception): def __init__(self, message, status): super().__init__(message, status) self.message = message self.status = status def check_chars(word): for char in word: if char.lower() in ['a', 'e', 'i', 'o', 'u']: raise VowelNotAccepted("Vowel is not accepted", 101) return word # print ( check_chars("love")) try: print ( check_chars("love")) # print ( check_chars('My') ) except Exception as e: print ("Error reason: " , e.message) # Built-in exceptions
true
true
1c2c0229bf58ba5a5e012acacea611bd236757cd
1,502
py
Python
pyzoo/test/zoo/orca/data/conftest.py
thalvari/analytics-zoo
4f4c5095c3db9363f5a23ca312a95bbdc6a3db91
[ "Apache-2.0" ]
null
null
null
pyzoo/test/zoo/orca/data/conftest.py
thalvari/analytics-zoo
4f4c5095c3db9363f5a23ca312a95bbdc6a3db91
[ "Apache-2.0" ]
null
null
null
pyzoo/test/zoo/orca/data/conftest.py
thalvari/analytics-zoo
4f4c5095c3db9363f5a23ca312a95bbdc6a3db91
[ "Apache-2.0" ]
null
null
null
# # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os from zoo.orca import OrcaContext import pytest sc = None ray_ctx = None @pytest.fixture(autouse=True, scope='package') def orca_data_fixture(): from zoo import init_spark_on_local from zoo.ray import RayContext OrcaContext._eager_mode = True sc = init_spark_on_local(cores=4, spark_log_level="INFO") access_key_id = os.getenv("AWS_ACCESS_KEY_ID") secret_access_key = os.getenv("AWS_SECRET_ACCESS_KEY") if access_key_id is not None and secret_access_key is not None: ray_ctx = RayContext(sc=sc, object_store_memory="1g", env={"AWS_ACCESS_KEY_ID": access_key_id, "AWS_SECRET_ACCESS_KEY": secret_access_key} ) else: ray_ctx = RayContext(sc=sc, object_store_memory="1g") ray_ctx.init() yield ray_ctx.stop() sc.stop()
33.377778
77
0.684421
import os from zoo.orca import OrcaContext import pytest sc = None ray_ctx = None @pytest.fixture(autouse=True, scope='package') def orca_data_fixture(): from zoo import init_spark_on_local from zoo.ray import RayContext OrcaContext._eager_mode = True sc = init_spark_on_local(cores=4, spark_log_level="INFO") access_key_id = os.getenv("AWS_ACCESS_KEY_ID") secret_access_key = os.getenv("AWS_SECRET_ACCESS_KEY") if access_key_id is not None and secret_access_key is not None: ray_ctx = RayContext(sc=sc, object_store_memory="1g", env={"AWS_ACCESS_KEY_ID": access_key_id, "AWS_SECRET_ACCESS_KEY": secret_access_key} ) else: ray_ctx = RayContext(sc=sc, object_store_memory="1g") ray_ctx.init() yield ray_ctx.stop() sc.stop()
true
true
1c2c02353792b04153b879efbe0813a32e4c9f76
672
py
Python
01. RPI - Python - Blink an LED/main.py
wyliodrinstudio/tutorials
bbb982fd2cae848d2b5d9e45a1d0408df9ced811
[ "Apache-2.0" ]
null
null
null
01. RPI - Python - Blink an LED/main.py
wyliodrinstudio/tutorials
bbb982fd2cae848d2b5d9e45a1d0408df9ced811
[ "Apache-2.0" ]
null
null
null
01. RPI - Python - Blink an LED/main.py
wyliodrinstudio/tutorials
bbb982fd2cae848d2b5d9e45a1d0408df9ced811
[ "Apache-2.0" ]
null
null
null
import RPi.GPIO as GPIO #import Raspberry Pi GPIO library from time import sleep #import the sleep method from time module GPIO.setmode(GPIO.BOARD) #setup BOARD numbering GPIO.setup(11, GPIO.OUT) #set pin 11 as output try: while True: #run forever untill you press Ctrl+C GPIO.output(11, 1) #turn on the LED sleep(1) #sleep for 1 second GPIO.output(11, 0) #turn off the LED sleep(0.5) #sleep for 0.5 second except KeyboardInterrupt: GPIO.cleanup() #clean up all the ports used
44.8
78
0.543155
import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.OUT) try: while True: GPIO.output(11, 1) sleep(1) GPIO.output(11, 0) sleep(0.5) except KeyboardInterrupt: GPIO.cleanup()
true
true
1c2c02fbc031c0a65d193085f3e43db29743163b
1,449
py
Python
WEEKS/CD_Sata-Structures/general/practice/PYTHON/09 - allLongestStrings.py
webdevhub42/Lambda
b04b84fb5b82fe7c8b12680149e25ae0d27a0960
[ "MIT" ]
null
null
null
WEEKS/CD_Sata-Structures/general/practice/PYTHON/09 - allLongestStrings.py
webdevhub42/Lambda
b04b84fb5b82fe7c8b12680149e25ae0d27a0960
[ "MIT" ]
null
null
null
WEEKS/CD_Sata-Structures/general/practice/PYTHON/09 - allLongestStrings.py
webdevhub42/Lambda
b04b84fb5b82fe7c8b12680149e25ae0d27a0960
[ "MIT" ]
null
null
null
"""Given an array of strings, return another array containing all of its longest strings. Example: For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be allLongestStrings(inputArray) = ["aba", "vcd", "aba"].""" def allLongestStrings(inputArray): # Step 1: We begin by defining an empty array called "max_arr", where we will store the longest strings from the given array. max_arr = [] # Step 2: The next step is to define the maximum string length inside our given array. # BE CAREFUL: Variable max_len should be defined as follows. If we break it into its components, we can see that: # max(inputArray, key = len) locates ONLY ONE of the strings that satisfies the maximum value in terms of the key parameter # provided (which, in this case, is the string's length) and the outside len() function defines the value of this maximum length. # You are free to test it on a random input array containing various random strings, using a Python compiler online. max_len = len(max(inputArray, key=len)) # Step 3: Now, we go over all strings inside the input array checking if their individual length is equal to the # maximum length value defined in step 2. If it is, then we append the respective string to the "max_arr" defined above. for i in inputArray: if len(i) == max_len: max_arr.append(i) # Step 4: We conclude by returning the max_arr. return max_arr
63
133
0.715666
def allLongestStrings(inputArray): max_arr = [] # You are free to test it on a random input array containing various random strings, using a Python compiler online. max_len = len(max(inputArray, key=len)) # Step 3: Now, we go over all strings inside the input array checking if their individual length is equal to the # maximum length value defined in step 2. If it is, then we append the respective string to the "max_arr" defined above. for i in inputArray: if len(i) == max_len: max_arr.append(i) # Step 4: We conclude by returning the max_arr. return max_arr
true
true
1c2c033ff22bbc05914c0d7d30afc0d5506fdeec
19,440
py
Python
salt/modules/boto_asg.py
robmessick/salt
95b44af831eeca3df261b3d61b7519fbd65319c6
[ "Apache-2.0" ]
null
null
null
salt/modules/boto_asg.py
robmessick/salt
95b44af831eeca3df261b3d61b7519fbd65319c6
[ "Apache-2.0" ]
null
null
null
salt/modules/boto_asg.py
robmessick/salt
95b44af831eeca3df261b3d61b7519fbd65319c6
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon Autoscale Groups .. versionadded:: 2014.7.0 :configuration: This module accepts explicit autoscale credentials but can also utilize IAM roles assigned to the instance trough Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: asg.keyid: GKTADJGHEIQSXMKKRBJ08H asg.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: asg.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # Import Python libs import logging import json import yaml import email.mime.multipart log = logging.getLogger(__name__) # Import third party libs try: import boto import boto.ec2 import boto.ec2.blockdevicemapping as blockdevicemapping import boto.ec2.autoscale as autoscale logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False from salt._compat import string_types import salt.utils.odict as odict def __virtual__(): ''' Only load if boto libraries exist. ''' if not HAS_BOTO: return False return True def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an autoscale group exists. CLI example:: salt myminion boto_asg.exists myasg region=us-east-1 ''' conn = _get_conn(region, key, keyid, profile) if not conn: return False try: conn.get_all_groups(names=[name]) return True except boto.exception.BotoServerError as e: log.debug(e) return False def get_config(name, region=None, key=None, keyid=None, profile=None): ''' Get the configuration for an autoscale group. CLI example:: salt myminion boto_asg.get_config myasg region=us-east-1 ''' conn = _get_conn(region, key, keyid, profile) if not conn: return None try: asg = conn.get_all_groups(names=[name]) if asg: asg = asg[0] else: return {} ret = odict.OrderedDict() attrs = ['name', 'availability_zones', 'default_cooldown', 'desired_capacity', 'health_check_period', 'health_check_type', 'launch_config_name', 'load_balancers', 'max_size', 'min_size', 'placement_group', 'vpc_zone_identifier', 'tags', 'termination_policies', 'suspended_processes'] for attr in attrs: # Tags are objects, so we need to turn them into dicts. if attr == 'tags': _tags = [] for tag in asg.tags: _tag = odict.OrderedDict() _tag['key'] = tag.key _tag['value'] = tag.value _tag['propagate_at_launch'] = tag.propagate_at_launch _tags.append(_tag) ret['tags'] = _tags # convert SuspendedProcess objects to names elif attr == 'suspended_processes': suspended_processes = getattr(asg, attr) ret[attr] = sorted([x.process_name for x in suspended_processes]) else: ret[attr] = getattr(asg, attr) # scaling policies policies = conn.get_all_policies(as_group=name) ret["scaling_policies"] = [] for policy in policies: ret["scaling_policies"].append( dict([ ("name", policy.name), ("adjustment_type", policy.adjustment_type), ("scaling_adjustment", policy.scaling_adjustment), ("min_adjustment_step", policy.min_adjustment_step), ("cooldown", policy.cooldown) ]) ) return ret except boto.exception.BotoServerError as e: log.debug(e) return {} def create(name, launch_config_name, availability_zones, min_size, max_size, desired_capacity=None, load_balancers=None, default_cooldown=None, health_check_type=None, health_check_period=None, placement_group=None, vpc_zone_identifier=None, tags=None, termination_policies=None, suspended_processes=None, scaling_policies=None, region=None, key=None, keyid=None, profile=None): ''' Create an autoscale group. CLI example:: salt myminion boto_asg.create myasg mylc '["us-east-1a", "us-east-1e"]' 1 10 load_balancers='["myelb", "myelb2"]' tags='[{"key": "Name", value="myasg", "propagate_at_launch": True}]' ''' conn = _get_conn(region, key, keyid, profile) if not conn: return False if isinstance(availability_zones, string_types): availability_zones = json.loads(availability_zones) if isinstance(load_balancers, string_types): load_balancers = json.loads(load_balancers) if isinstance(vpc_zone_identifier, string_types): vpc_zone_identifier = json.loads(vpc_zone_identifier) if isinstance(tags, string_types): tags = json.loads(tags) # Make a list of tag objects from the dict. _tags = [] for tag in tags: try: key = tag.get('key') except KeyError: log.error('Tag missing key.') return False try: value = tag.get('value') except KeyError: log.error('Tag missing value.') return False propagate_at_launch = tag.get('propagate_at_launch', False) _tag = autoscale.Tag(key=key, value=value, resource_id=name, propagate_at_launch=propagate_at_launch) _tags.append(_tag) if isinstance(termination_policies, string_types): termination_policies = json.loads(termination_policies) if isinstance(suspended_processes, string_types): suspended_processes = json.loads(suspended_processes) try: _asg = autoscale.AutoScalingGroup( name=name, launch_config=launch_config_name, availability_zones=availability_zones, min_size=min_size, max_size=max_size, desired_capacity=desired_capacity, load_balancers=load_balancers, default_cooldown=default_cooldown, health_check_type=health_check_type, health_check_period=health_check_period, placement_group=placement_group, tags=_tags, vpc_zone_identifier=vpc_zone_identifier, termination_policies=termination_policies, suspended_processes=suspended_processes) conn.create_auto_scaling_group(_asg) # create scaling policies _create_scaling_policies(conn, name, scaling_policies) log.info('Created ASG {0}'.format(name)) return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to create ASG {0}'.format(name) log.error(msg) return False def update(name, launch_config_name, availability_zones, min_size, max_size, desired_capacity=None, load_balancers=None, default_cooldown=None, health_check_type=None, health_check_period=None, placement_group=None, vpc_zone_identifier=None, tags=None, termination_policies=None, suspended_processes=None, scaling_policies=None, region=None, key=None, keyid=None, profile=None): ''' Update an autoscale group. CLI example:: salt myminion boto_asg.update myasg mylc '["us-east-1a", "us-east-1e"]' 1 10 load_balancers='["myelb", "myelb2"]' tags='[{"key": "Name", value="myasg", "propagate_at_launch": True}]' ''' conn = _get_conn(region, key, keyid, profile) if not conn: return False if isinstance(availability_zones, string_types): availability_zones = json.loads(availability_zones) if isinstance(load_balancers, string_types): load_balancers = json.loads(load_balancers) if isinstance(vpc_zone_identifier, string_types): vpc_zone_identifier = json.loads(vpc_zone_identifier) if isinstance(tags, string_types): tags = json.loads(tags) # Make a list of tag objects from the dict. _tags = [] for tag in tags: try: key = tag.get('key') except KeyError: log.error('Tag missing key.') return False try: value = tag.get('value') except KeyError: log.error('Tag missing value.') return False propagate_at_launch = tag.get('propagate_at_launch', False) _tag = autoscale.Tag(key=key, value=value, resource_id=name, propagate_at_launch=propagate_at_launch) _tags.append(_tag) if isinstance(termination_policies, string_types): termination_policies = json.loads(termination_policies) if isinstance(suspended_processes, string_types): suspended_processes = json.loads(suspended_processes) try: _asg = autoscale.AutoScalingGroup( connection=conn, name=name, launch_config=launch_config_name, availability_zones=availability_zones, min_size=min_size, max_size=max_size, desired_capacity=desired_capacity, load_balancers=load_balancers, default_cooldown=default_cooldown, health_check_type=health_check_type, health_check_period=health_check_period, placement_group=placement_group, tags=_tags, vpc_zone_identifier=vpc_zone_identifier, termination_policies=termination_policies) _asg.update() # Seems the update call doesn't handle tags, so we'll need to update # that separately. conn.create_or_update_tags(_tags) # update doesn't handle suspended_processes either # Resume all processes _asg.resume_processes() # suspend any that are specified. Note that the boto default of empty # list suspends all; don't do that. if suspended_processes is not None and len(suspended_processes) > 0: _asg.suspend_processes(suspended_processes) log.info('Updated ASG {0}'.format(name)) #### scaling policies # delete all policies, then recreate them for policy in conn.get_all_policies(as_group=name): conn.delete_policy(policy.name, autoscale_group=name) _create_scaling_policies(conn, name, scaling_policies) return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update ASG {0}'.format(name) log.error(msg) return False def _create_scaling_policies(conn, as_name, scaling_policies): 'helper function to create scaling policies' if scaling_policies: for policy in scaling_policies: policy = autoscale.policy.ScalingPolicy( name=policy["name"], as_name=as_name, adjustment_type=policy["adjustment_type"], scaling_adjustment=policy["scaling_adjustment"], min_adjustment_step=policy.get("min_adjustment_step", None), cooldown=policy["cooldown"]) conn.create_scaling_policy(policy) def delete(name, force=False, region=None, key=None, keyid=None, profile=None): ''' Delete an autoscale group. CLI example:: salt myminion boto_asg.delete myasg region=us-east-1 ''' conn = _get_conn(region, key, keyid, profile) if not conn: return False try: conn.delete_auto_scaling_group(name, force) msg = 'Deleted autoscale group {0}.'.format(name) log.info(msg) return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to delete autoscale group {0}'.format(name) log.error(msg) return False def get_cloud_init_mime(cloud_init): ''' Get a mime multipart encoded string from a cloud-init dict. Currently supports scripts and cloud-config. CLI Example: .. code-block:: bash salt myminion boto.get_cloud_init_mime <cloud init> ''' if isinstance(cloud_init, string_types): cloud_init = json.loads(cloud_init) _cloud_init = email.mime.multipart.MIMEMultipart() if 'scripts' in cloud_init: for script_name, script in cloud_init['scripts'].iteritems(): _script = email.mime.text.MIMEText(script, 'x-shellscript') _cloud_init.attach(_script) if 'cloud-config' in cloud_init: cloud_config = cloud_init['cloud-config'] _cloud_config = email.mime.text.MIMEText(yaml.dump(cloud_config), 'cloud-config') _cloud_init.attach(_cloud_config) return _cloud_init.as_string() def launch_configuration_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check for a launch configuration's existence. CLI example:: salt myminion boto_asg.launch_configuration_exists mylc ''' conn = _get_conn(region, key, keyid, profile) if not conn: return False lc = conn.get_all_launch_configurations(names=[name]) if lc: return True else: return False def create_launch_configuration(name, image_id, key_name=None, security_groups=None, user_data=None, instance_type='m1.small', kernel_id=None, ramdisk_id=None, block_device_mappings=None, instance_monitoring=False, spot_price=None, instance_profile_name=None, ebs_optimized=False, associate_public_ip_address=None, volume_type=None, delete_on_termination=True, iops=None, use_block_device_types=False, region=None, key=None, keyid=None, profile=None): ''' Create a launch configuration. CLI example:: salt myminion boto_asg.create_launch_configuration mylc image_id=ami-0b9c9f62 key_name='mykey' security_groups='["mygroup"]' instance_type='c3.2xlarge' ''' conn = _get_conn(region, key, keyid, profile) if not conn: return False if isinstance(security_groups, string_types): security_groups = json.loads(security_groups) if isinstance(block_device_mappings, string_types): block_device_mappings = json.loads(block_device_mappings) _bdms = [] if block_device_mappings: # Boto requires objects for the mappings and the devices. _block_device_map = blockdevicemapping.BlockDeviceMapping() for block_device_dict in block_device_mappings: for block_device, attributes in block_device_dict.iteritems(): _block_device = blockdevicemapping.EBSBlockDeviceType() for attribute, value in attributes.iteritems(): setattr(_block_device, attribute, value) _block_device_map[block_device] = _block_device _bdms = [_block_device_map] lc = autoscale.LaunchConfiguration( name=name, image_id=image_id, key_name=key_name, security_groups=security_groups, user_data=user_data, instance_type=instance_type, kernel_id=kernel_id, ramdisk_id=ramdisk_id, block_device_mappings=_bdms, instance_monitoring=instance_monitoring, spot_price=spot_price, instance_profile_name=instance_profile_name, ebs_optimized=ebs_optimized, associate_public_ip_address=associate_public_ip_address, volume_type=volume_type, delete_on_termination=delete_on_termination, iops=iops, use_block_device_types=use_block_device_types) try: conn.create_launch_configuration(lc) log.info('Created LC {0}'.format(name)) return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to create LC {0}'.format(name) log.error(msg) return False def delete_launch_configuration(name, region=None, key=None, keyid=None, profile=None): ''' Delete a launch configuration. CLI example:: salt myminion boto_asg.delete_launch_configuration mylc ''' conn = _get_conn(region, key, keyid, profile) if not conn: return False try: conn.delete_launch_configuration(name) log.info('Deleted LC {0}'.format(name)) return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to delete LC {0}'.format(name) log.error(msg) return False def get_scaling_policy_arn(as_group, scaling_policy_name, region=None, key=None, keyid=None, profile=None): ''' Return the arn for a scaling policy in a specific autoscale group or None if not found. Mainly used as a helper method for boto_cloudwatch_alarm, for linking alarms to scaling policies. CLI Example:: salt '*' boto_asg.get_scaling_policy_arn mygroup mypolicy ''' conn = _get_conn(region, key, keyid, profile) policies = conn.get_all_policies(as_group=as_group) for policy in policies: if policy.name == scaling_policy_name: return policy.policy_arn log.error('Could not convert: {0}'.format(as_group)) return None def _get_conn(region, key, keyid, profile): ''' Get a boto connection to autoscale. ''' if profile: if isinstance(profile, string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', None) if not region and __salt__['config.option']('asg.region'): region = __salt__['config.option']('asg.region') if not region: region = 'us-east-1' if not key and __salt__['config.option']('asg.key'): key = __salt__['config.option']('asg.key') if not keyid and __salt__['config.option']('asg.keyid'): keyid = __salt__['config.option']('asg.keyid') try: conn = autoscale.connect_to_region(region, aws_access_key_id=keyid, aws_secret_access_key=key) except boto.exception.NoAuthHandlerFound: log.error('No authentication credentials found when attempting to' ' make boto autoscale connection.') return None return conn
37.31286
190
0.639712
import logging import json import yaml import email.mime.multipart log = logging.getLogger(__name__) try: import boto import boto.ec2 import boto.ec2.blockdevicemapping as blockdevicemapping import boto.ec2.autoscale as autoscale logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False from salt._compat import string_types import salt.utils.odict as odict def __virtual__(): if not HAS_BOTO: return False return True def exists(name, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region, key, keyid, profile) if not conn: return False try: conn.get_all_groups(names=[name]) return True except boto.exception.BotoServerError as e: log.debug(e) return False def get_config(name, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region, key, keyid, profile) if not conn: return None try: asg = conn.get_all_groups(names=[name]) if asg: asg = asg[0] else: return {} ret = odict.OrderedDict() attrs = ['name', 'availability_zones', 'default_cooldown', 'desired_capacity', 'health_check_period', 'health_check_type', 'launch_config_name', 'load_balancers', 'max_size', 'min_size', 'placement_group', 'vpc_zone_identifier', 'tags', 'termination_policies', 'suspended_processes'] for attr in attrs: if attr == 'tags': _tags = [] for tag in asg.tags: _tag = odict.OrderedDict() _tag['key'] = tag.key _tag['value'] = tag.value _tag['propagate_at_launch'] = tag.propagate_at_launch _tags.append(_tag) ret['tags'] = _tags elif attr == 'suspended_processes': suspended_processes = getattr(asg, attr) ret[attr] = sorted([x.process_name for x in suspended_processes]) else: ret[attr] = getattr(asg, attr) policies = conn.get_all_policies(as_group=name) ret["scaling_policies"] = [] for policy in policies: ret["scaling_policies"].append( dict([ ("name", policy.name), ("adjustment_type", policy.adjustment_type), ("scaling_adjustment", policy.scaling_adjustment), ("min_adjustment_step", policy.min_adjustment_step), ("cooldown", policy.cooldown) ]) ) return ret except boto.exception.BotoServerError as e: log.debug(e) return {} def create(name, launch_config_name, availability_zones, min_size, max_size, desired_capacity=None, load_balancers=None, default_cooldown=None, health_check_type=None, health_check_period=None, placement_group=None, vpc_zone_identifier=None, tags=None, termination_policies=None, suspended_processes=None, scaling_policies=None, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region, key, keyid, profile) if not conn: return False if isinstance(availability_zones, string_types): availability_zones = json.loads(availability_zones) if isinstance(load_balancers, string_types): load_balancers = json.loads(load_balancers) if isinstance(vpc_zone_identifier, string_types): vpc_zone_identifier = json.loads(vpc_zone_identifier) if isinstance(tags, string_types): tags = json.loads(tags) _tags = [] for tag in tags: try: key = tag.get('key') except KeyError: log.error('Tag missing key.') return False try: value = tag.get('value') except KeyError: log.error('Tag missing value.') return False propagate_at_launch = tag.get('propagate_at_launch', False) _tag = autoscale.Tag(key=key, value=value, resource_id=name, propagate_at_launch=propagate_at_launch) _tags.append(_tag) if isinstance(termination_policies, string_types): termination_policies = json.loads(termination_policies) if isinstance(suspended_processes, string_types): suspended_processes = json.loads(suspended_processes) try: _asg = autoscale.AutoScalingGroup( name=name, launch_config=launch_config_name, availability_zones=availability_zones, min_size=min_size, max_size=max_size, desired_capacity=desired_capacity, load_balancers=load_balancers, default_cooldown=default_cooldown, health_check_type=health_check_type, health_check_period=health_check_period, placement_group=placement_group, tags=_tags, vpc_zone_identifier=vpc_zone_identifier, termination_policies=termination_policies, suspended_processes=suspended_processes) conn.create_auto_scaling_group(_asg) _create_scaling_policies(conn, name, scaling_policies) log.info('Created ASG {0}'.format(name)) return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to create ASG {0}'.format(name) log.error(msg) return False def update(name, launch_config_name, availability_zones, min_size, max_size, desired_capacity=None, load_balancers=None, default_cooldown=None, health_check_type=None, health_check_period=None, placement_group=None, vpc_zone_identifier=None, tags=None, termination_policies=None, suspended_processes=None, scaling_policies=None, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region, key, keyid, profile) if not conn: return False if isinstance(availability_zones, string_types): availability_zones = json.loads(availability_zones) if isinstance(load_balancers, string_types): load_balancers = json.loads(load_balancers) if isinstance(vpc_zone_identifier, string_types): vpc_zone_identifier = json.loads(vpc_zone_identifier) if isinstance(tags, string_types): tags = json.loads(tags) _tags = [] for tag in tags: try: key = tag.get('key') except KeyError: log.error('Tag missing key.') return False try: value = tag.get('value') except KeyError: log.error('Tag missing value.') return False propagate_at_launch = tag.get('propagate_at_launch', False) _tag = autoscale.Tag(key=key, value=value, resource_id=name, propagate_at_launch=propagate_at_launch) _tags.append(_tag) if isinstance(termination_policies, string_types): termination_policies = json.loads(termination_policies) if isinstance(suspended_processes, string_types): suspended_processes = json.loads(suspended_processes) try: _asg = autoscale.AutoScalingGroup( connection=conn, name=name, launch_config=launch_config_name, availability_zones=availability_zones, min_size=min_size, max_size=max_size, desired_capacity=desired_capacity, load_balancers=load_balancers, default_cooldown=default_cooldown, health_check_type=health_check_type, health_check_period=health_check_period, placement_group=placement_group, tags=_tags, vpc_zone_identifier=vpc_zone_identifier, termination_policies=termination_policies) _asg.update() conn.create_or_update_tags(_tags) # Resume all processes _asg.resume_processes() # suspend any that are specified. Note that the boto default of empty # list suspends all; don't do that. if suspended_processes is not None and len(suspended_processes) > 0: _asg.suspend_processes(suspended_processes) log.info('Updated ASG {0}'.format(name)) group=name): conn.delete_policy(policy.name, autoscale_group=name) _create_scaling_policies(conn, name, scaling_policies) return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update ASG {0}'.format(name) log.error(msg) return False def _create_scaling_policies(conn, as_name, scaling_policies): if scaling_policies: for policy in scaling_policies: policy = autoscale.policy.ScalingPolicy( name=policy["name"], as_name=as_name, adjustment_type=policy["adjustment_type"], scaling_adjustment=policy["scaling_adjustment"], min_adjustment_step=policy.get("min_adjustment_step", None), cooldown=policy["cooldown"]) conn.create_scaling_policy(policy) def delete(name, force=False, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region, key, keyid, profile) if not conn: return False try: conn.delete_auto_scaling_group(name, force) msg = 'Deleted autoscale group {0}.'.format(name) log.info(msg) return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to delete autoscale group {0}'.format(name) log.error(msg) return False def get_cloud_init_mime(cloud_init): if isinstance(cloud_init, string_types): cloud_init = json.loads(cloud_init) _cloud_init = email.mime.multipart.MIMEMultipart() if 'scripts' in cloud_init: for script_name, script in cloud_init['scripts'].iteritems(): _script = email.mime.text.MIMEText(script, 'x-shellscript') _cloud_init.attach(_script) if 'cloud-config' in cloud_init: cloud_config = cloud_init['cloud-config'] _cloud_config = email.mime.text.MIMEText(yaml.dump(cloud_config), 'cloud-config') _cloud_init.attach(_cloud_config) return _cloud_init.as_string() def launch_configuration_exists(name, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region, key, keyid, profile) if not conn: return False lc = conn.get_all_launch_configurations(names=[name]) if lc: return True else: return False def create_launch_configuration(name, image_id, key_name=None, security_groups=None, user_data=None, instance_type='m1.small', kernel_id=None, ramdisk_id=None, block_device_mappings=None, instance_monitoring=False, spot_price=None, instance_profile_name=None, ebs_optimized=False, associate_public_ip_address=None, volume_type=None, delete_on_termination=True, iops=None, use_block_device_types=False, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region, key, keyid, profile) if not conn: return False if isinstance(security_groups, string_types): security_groups = json.loads(security_groups) if isinstance(block_device_mappings, string_types): block_device_mappings = json.loads(block_device_mappings) _bdms = [] if block_device_mappings: _block_device_map = blockdevicemapping.BlockDeviceMapping() for block_device_dict in block_device_mappings: for block_device, attributes in block_device_dict.iteritems(): _block_device = blockdevicemapping.EBSBlockDeviceType() for attribute, value in attributes.iteritems(): setattr(_block_device, attribute, value) _block_device_map[block_device] = _block_device _bdms = [_block_device_map] lc = autoscale.LaunchConfiguration( name=name, image_id=image_id, key_name=key_name, security_groups=security_groups, user_data=user_data, instance_type=instance_type, kernel_id=kernel_id, ramdisk_id=ramdisk_id, block_device_mappings=_bdms, instance_monitoring=instance_monitoring, spot_price=spot_price, instance_profile_name=instance_profile_name, ebs_optimized=ebs_optimized, associate_public_ip_address=associate_public_ip_address, volume_type=volume_type, delete_on_termination=delete_on_termination, iops=iops, use_block_device_types=use_block_device_types) try: conn.create_launch_configuration(lc) log.info('Created LC {0}'.format(name)) return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to create LC {0}'.format(name) log.error(msg) return False def delete_launch_configuration(name, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region, key, keyid, profile) if not conn: return False try: conn.delete_launch_configuration(name) log.info('Deleted LC {0}'.format(name)) return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to delete LC {0}'.format(name) log.error(msg) return False def get_scaling_policy_arn(as_group, scaling_policy_name, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region, key, keyid, profile) policies = conn.get_all_policies(as_group=as_group) for policy in policies: if policy.name == scaling_policy_name: return policy.policy_arn log.error('Could not convert: {0}'.format(as_group)) return None def _get_conn(region, key, keyid, profile): if profile: if isinstance(profile, string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', None) if not region and __salt__['config.option']('asg.region'): region = __salt__['config.option']('asg.region') if not region: region = 'us-east-1' if not key and __salt__['config.option']('asg.key'): key = __salt__['config.option']('asg.key') if not keyid and __salt__['config.option']('asg.keyid'): keyid = __salt__['config.option']('asg.keyid') try: conn = autoscale.connect_to_region(region, aws_access_key_id=keyid, aws_secret_access_key=key) except boto.exception.NoAuthHandlerFound: log.error('No authentication credentials found when attempting to' ' make boto autoscale connection.') return None return conn
true
true
1c2c03a70656d1a7b8ce7938f0d27478e07cf865
1,559
py
Python
project/api/views.py
milkOSTpyt/Goods-accounting-system
ec223ed726cfa9f18d49c4233f9dc1520373c874
[ "BSD-3-Clause" ]
null
null
null
project/api/views.py
milkOSTpyt/Goods-accounting-system
ec223ed726cfa9f18d49c4233f9dc1520373c874
[ "BSD-3-Clause" ]
null
null
null
project/api/views.py
milkOSTpyt/Goods-accounting-system
ec223ed726cfa9f18d49c4233f9dc1520373c874
[ "BSD-3-Clause" ]
null
null
null
from rest_framework.viewsets import ModelViewSet from rest_framework import permissions from rest_framework.generics import ListAPIView from django_filters.rest_framework import DjangoFilterBackend from app.models import Product, Category, Shop, Warehouse from .serializers import (ProductSerializer, CategorySerializer, ShopSerializer, WarehouseSerializer) class ProductViewSet(ModelViewSet): """CRUD товара""" queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [permissions.IsAuthenticated] class CategoryViewSet(ModelViewSet): """CRUD котегории""" queryset = Category.objects.all() serializer_class = CategorySerializer permission_classes = [permissions.IsAuthenticated] class ShopViewSet(ModelViewSet): """CRUD магазина""" queryset = Shop.objects.all() serializer_class = ShopSerializer permission_classes = [permissions.IsAuthenticated] class WarehouseViewSet(ModelViewSet): """CRUD склада""" queryset = Warehouse.objects.all() serializer_class = WarehouseSerializer permission_classes = [permissions.IsAuthenticated] class SoldOutProduct(ListAPIView): """Вывод списка проданных товаров + фильтры""" queryset = Product.objects.filter(sold_out=True) serializer_class = ProductSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [DjangoFilterBackend] filterset_fields = ['name', 'shop', 'category', 'warehouse']
33.170213
64
0.736369
from rest_framework.viewsets import ModelViewSet from rest_framework import permissions from rest_framework.generics import ListAPIView from django_filters.rest_framework import DjangoFilterBackend from app.models import Product, Category, Shop, Warehouse from .serializers import (ProductSerializer, CategorySerializer, ShopSerializer, WarehouseSerializer) class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [permissions.IsAuthenticated] class CategoryViewSet(ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer permission_classes = [permissions.IsAuthenticated] class ShopViewSet(ModelViewSet): queryset = Shop.objects.all() serializer_class = ShopSerializer permission_classes = [permissions.IsAuthenticated] class WarehouseViewSet(ModelViewSet): queryset = Warehouse.objects.all() serializer_class = WarehouseSerializer permission_classes = [permissions.IsAuthenticated] class SoldOutProduct(ListAPIView): queryset = Product.objects.filter(sold_out=True) serializer_class = ProductSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [DjangoFilterBackend] filterset_fields = ['name', 'shop', 'category', 'warehouse']
true
true
1c2c04346d29c864bf3b404ac8b16744e1a6c5f6
2,850
py
Python
benchmark.py
padix-key/fastpdb
016c0211743fcbf4366fdaf6fb5579ff073c6274
[ "BSD-3-Clause" ]
2
2021-11-12T18:54:09.000Z
2022-03-29T10:20:28.000Z
benchmark.py
biotite-dev/fastpdb
016c0211743fcbf4366fdaf6fb5579ff073c6274
[ "BSD-3-Clause" ]
null
null
null
benchmark.py
biotite-dev/fastpdb
016c0211743fcbf4366fdaf6fb5579ff073c6274
[ "BSD-3-Clause" ]
null
null
null
import time import tempfile import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as ticker import numpy as np import biotite.database.rcsb as rcsb import biotite.structure.info as info import biotite.structure.io.pdb as pdb import fastpdb REPEATS = 1000 PDB_ID = "1AKI" WIDTH = 0.25 # Call this function before the benchmark # to avoid a bias due to the initial loading time info.bond_dataset() pdb_file_path = rcsb.fetch(PDB_ID, "pdb", tempfile.gettempdir()) fastpdb_runtimes = {} biotite_runtimes = {} now = time.time_ns() for _ in range(REPEATS): pdb_file = fastpdb.PDBFile.read(pdb_file_path) pdb_file.get_coord(model=1) fastpdb_runtimes["Read coord"] = (time.time_ns() - now) * 1e-6 / REPEATS now = time.time_ns() for _ in range(REPEATS): pdb_file = pdb.PDBFile.read(pdb_file_path) pdb_file.get_coord(model=1) biotite_runtimes["Read coord"] = (time.time_ns() - now) * 1e-6 / REPEATS now = time.time_ns() for _ in range(REPEATS): pdb_file = fastpdb.PDBFile.read(pdb_file_path) pdb_file.get_structure(model=1) fastpdb_runtimes["Read model"] = (time.time_ns() - now) * 1e-6 / REPEATS now = time.time_ns() for _ in range(REPEATS): pdb_file = pdb.PDBFile.read(pdb_file_path) pdb_file.get_structure(model=1) biotite_runtimes["Read model"] = (time.time_ns() - now) * 1e-6 / REPEATS pdb_file = pdb.PDBFile.read(pdb_file_path) atoms = pdb_file.get_structure(model=1) now = time.time_ns() for _ in range(REPEATS): pdb_file = fastpdb.PDBFile() pdb_file.set_structure(atoms) pdb_file.write(tempfile.TemporaryFile("w")) fastpdb_runtimes["Write model"] = (time.time_ns() - now) * 1e-6 / REPEATS now = time.time_ns() for _ in range(REPEATS): pdb_file = pdb.PDBFile() pdb_file.set_structure(atoms) pdb_file.write(tempfile.TemporaryFile("w")) biotite_runtimes["Write model"] = (time.time_ns() - now) * 1e-6 / REPEATS matplotlib.rc("font", size=12) fig, ax = plt.subplots(figsize=(8.0, 4.0)) labels = list(fastpdb_runtimes.keys()) fastpdb_speedup = np.array(list(biotite_runtimes.values())) / \ np.array(list(fastpdb_runtimes.values())) bars = ax.bar( np.arange(len(fastpdb_speedup)) - WIDTH/2, fastpdb_speedup, WIDTH, color="#0a6efd", linewidth=1.0, edgecolor="black", label="fastpdb" ) ax.bar_label(bars, padding=3, fmt="%.1f×") ax.bar( np.arange(len(fastpdb_speedup)) + WIDTH/2, np.ones(len(fastpdb_speedup)), WIDTH, color="#e1301d", linewidth=1.0, edgecolor="black", label="biotite" ) ax.legend(loc="upper left", frameon=False) ax.set_xticks(np.arange(len(fastpdb_runtimes))) ax.set_xticklabels(labels) ax.margins(y=0.1) ax.set_ylabel("Speedup") ax.yaxis.set_major_locator(ticker.IndexLocator(base=1, offset=1)) ax.yaxis.set_major_formatter(ticker.FormatStrFormatter("%d×")) fig.tight_layout() plt.savefig("benchmark.svg")
28.217822
77
0.723158
import time import tempfile import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as ticker import numpy as np import biotite.database.rcsb as rcsb import biotite.structure.info as info import biotite.structure.io.pdb as pdb import fastpdb REPEATS = 1000 PDB_ID = "1AKI" WIDTH = 0.25 info.bond_dataset() pdb_file_path = rcsb.fetch(PDB_ID, "pdb", tempfile.gettempdir()) fastpdb_runtimes = {} biotite_runtimes = {} now = time.time_ns() for _ in range(REPEATS): pdb_file = fastpdb.PDBFile.read(pdb_file_path) pdb_file.get_coord(model=1) fastpdb_runtimes["Read coord"] = (time.time_ns() - now) * 1e-6 / REPEATS now = time.time_ns() for _ in range(REPEATS): pdb_file = pdb.PDBFile.read(pdb_file_path) pdb_file.get_coord(model=1) biotite_runtimes["Read coord"] = (time.time_ns() - now) * 1e-6 / REPEATS now = time.time_ns() for _ in range(REPEATS): pdb_file = fastpdb.PDBFile.read(pdb_file_path) pdb_file.get_structure(model=1) fastpdb_runtimes["Read model"] = (time.time_ns() - now) * 1e-6 / REPEATS now = time.time_ns() for _ in range(REPEATS): pdb_file = pdb.PDBFile.read(pdb_file_path) pdb_file.get_structure(model=1) biotite_runtimes["Read model"] = (time.time_ns() - now) * 1e-6 / REPEATS pdb_file = pdb.PDBFile.read(pdb_file_path) atoms = pdb_file.get_structure(model=1) now = time.time_ns() for _ in range(REPEATS): pdb_file = fastpdb.PDBFile() pdb_file.set_structure(atoms) pdb_file.write(tempfile.TemporaryFile("w")) fastpdb_runtimes["Write model"] = (time.time_ns() - now) * 1e-6 / REPEATS now = time.time_ns() for _ in range(REPEATS): pdb_file = pdb.PDBFile() pdb_file.set_structure(atoms) pdb_file.write(tempfile.TemporaryFile("w")) biotite_runtimes["Write model"] = (time.time_ns() - now) * 1e-6 / REPEATS matplotlib.rc("font", size=12) fig, ax = plt.subplots(figsize=(8.0, 4.0)) labels = list(fastpdb_runtimes.keys()) fastpdb_speedup = np.array(list(biotite_runtimes.values())) / \ np.array(list(fastpdb_runtimes.values())) bars = ax.bar( np.arange(len(fastpdb_speedup)) - WIDTH/2, fastpdb_speedup, WIDTH, color="#0a6efd", linewidth=1.0, edgecolor="black", label="fastpdb" ) ax.bar_label(bars, padding=3, fmt="%.1f×") ax.bar( np.arange(len(fastpdb_speedup)) + WIDTH/2, np.ones(len(fastpdb_speedup)), WIDTH, color="#e1301d", linewidth=1.0, edgecolor="black", label="biotite" ) ax.legend(loc="upper left", frameon=False) ax.set_xticks(np.arange(len(fastpdb_runtimes))) ax.set_xticklabels(labels) ax.margins(y=0.1) ax.set_ylabel("Speedup") ax.yaxis.set_major_locator(ticker.IndexLocator(base=1, offset=1)) ax.yaxis.set_major_formatter(ticker.FormatStrFormatter("%d×")) fig.tight_layout() plt.savefig("benchmark.svg")
true
true
1c2c05041b07e62bc9988d892ca411996f34d53f
2,665
py
Python
basecase.py
sibson/dynoup
6f43c92c82f41bf9c1e3efeeca05bf8f566a4cf5
[ "MIT" ]
1
2020-09-13T17:26:31.000Z
2020-09-13T17:26:31.000Z
basecase.py
sibson/dynoup
6f43c92c82f41bf9c1e3efeeca05bf8f566a4cf5
[ "MIT" ]
3
2015-09-23T17:01:02.000Z
2015-11-21T03:58:13.000Z
basecase.py
sibson/dynoup
6f43c92c82f41bf9c1e3efeeca05bf8f566a4cf5
[ "MIT" ]
null
null
null
from contextlib import contextmanager import json import os import logging from unittest import TestCase from flask import appcontext_pushed, g import responses from dynoup import app, db from scaler import models class HerokuBouncerTestDoubleMiddleWare(object): def __init__(self, app): self._app = app def __call__(self, environ, start_response): environ['REMOTE_USER'] = 'testuser@example.com' environ['wsgioauth2.session'] = { 'username': 'testuser@example.com', 'access_token': 'test-access-token', 'user': { 'email': 'testuser@example.com', } } return self._app(environ, start_response) class DynoUPTestCase(TestCase): def setUp(self): logging.basicConfig() requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True app.config['FERNET_SECRET'] = 'ovoQLxYEfMnFks8ab7dpHB9RITEaDMaZutxlkHM1TVs=' app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres:///dynoup-test' app.config['TESTING'] = True app.wsgi_app = HerokuBouncerTestDoubleMiddleWare(app.wsgi_app) self.client = app.test_client() db.create_all() super(DynoUPTestCase, self).setUp() def tearDown(self): db.session.remove() db.drop_all() def add_heroku_response(self, verb, path, filename=None, **kwargs): if filename is None: filename = 'examples/{}{}.json'.format(verb, path) elif not filename.endswith('.json'): filename = filename + '.json' fh = open(os.path.join('fixtures', filename)) data = json.loads(fh.read()) responses.add(verb, 'https://api.heroku.com' + path, json=data, **kwargs) return data def create_user(self): user = models.User(id='01234567-89ab-cdef-0123-456789abcdef', email='testuser@example.com', htoken='testtoken') db.session.add(user) db.session.commit() return user def create_app(self): app = models.App(id='01234567-89ab-cdef-0123-456789abcdef', name='example') db.session.add(app) db.session.commit() return app def create_check(self, app=None): check = models.Check(app=app or self.app, url='http://example.com', dynotype='web') db.session.add(check) db.session.commit() return check @contextmanager def user_set(app, user): def handler(sender, **kwargs): g.user = user with appcontext_pushed.connected_to(handler, app): yield
28.052632
119
0.63152
from contextlib import contextmanager import json import os import logging from unittest import TestCase from flask import appcontext_pushed, g import responses from dynoup import app, db from scaler import models class HerokuBouncerTestDoubleMiddleWare(object): def __init__(self, app): self._app = app def __call__(self, environ, start_response): environ['REMOTE_USER'] = 'testuser@example.com' environ['wsgioauth2.session'] = { 'username': 'testuser@example.com', 'access_token': 'test-access-token', 'user': { 'email': 'testuser@example.com', } } return self._app(environ, start_response) class DynoUPTestCase(TestCase): def setUp(self): logging.basicConfig() requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True app.config['FERNET_SECRET'] = 'ovoQLxYEfMnFks8ab7dpHB9RITEaDMaZutxlkHM1TVs=' app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres:///dynoup-test' app.config['TESTING'] = True app.wsgi_app = HerokuBouncerTestDoubleMiddleWare(app.wsgi_app) self.client = app.test_client() db.create_all() super(DynoUPTestCase, self).setUp() def tearDown(self): db.session.remove() db.drop_all() def add_heroku_response(self, verb, path, filename=None, **kwargs): if filename is None: filename = 'examples/{}{}.json'.format(verb, path) elif not filename.endswith('.json'): filename = filename + '.json' fh = open(os.path.join('fixtures', filename)) data = json.loads(fh.read()) responses.add(verb, 'https://api.heroku.com' + path, json=data, **kwargs) return data def create_user(self): user = models.User(id='01234567-89ab-cdef-0123-456789abcdef', email='testuser@example.com', htoken='testtoken') db.session.add(user) db.session.commit() return user def create_app(self): app = models.App(id='01234567-89ab-cdef-0123-456789abcdef', name='example') db.session.add(app) db.session.commit() return app def create_check(self, app=None): check = models.Check(app=app or self.app, url='http://example.com', dynotype='web') db.session.add(check) db.session.commit() return check @contextmanager def user_set(app, user): def handler(sender, **kwargs): g.user = user with appcontext_pushed.connected_to(handler, app): yield
true
true
1c2c05bf84b5f4c73f4eca061fdcd88f931bb816
4,677
py
Python
examples/set_mnist_gan.py
bobelly/torchsupport
5aa0a04f20c193ec99310f5d6a3375d2e95e740d
[ "MIT" ]
18
2019-05-02T16:32:15.000Z
2021-04-16T09:33:54.000Z
examples/set_mnist_gan.py
bobelly/torchsupport
5aa0a04f20c193ec99310f5d6a3375d2e95e740d
[ "MIT" ]
5
2019-10-14T13:46:49.000Z
2021-06-08T11:48:34.000Z
examples/set_mnist_gan.py
bobelly/torchsupport
5aa0a04f20c193ec99310f5d6a3375d2e95e740d
[ "MIT" ]
12
2019-05-12T21:34:24.000Z
2021-07-15T14:14:16.000Z
import random import torch import torch.nn as nn import torch.nn.functional as func from torch.nn.utils import spectral_norm from torch.utils.data import Dataset from torch.distributions import Normal from torchvision.datasets import MNIST from torchvision.transforms import ToTensor from torchsupport.modules.basic import MLP from torchsupport.modules.residual import ResNetBlock2d from torchsupport.training.samplers import Langevin from torchsupport.training.few_shot_gan import FewShotGANTraining def normalize(image): return (image - image.min()) / (image.max() - image.min()) class EnergyDataset(Dataset): def __init__(self, data): self.data = data def __getitem__(self, index): data, label_index = self.data[index] label = torch.zeros(10) label[label_index] = 1 return data, label def __len__(self): return len(self.data) class MNISTSet(EnergyDataset): def __init__(self, data, size=5): super().__init__(data) self.size = size def __getitem__(self, index): data = [] label = random.randrange(10) for idx in range(self.size): d, l = super().__getitem__(random.randrange(len(self))) while l[label] < 1.0: d, l = super().__getitem__(random.randrange(len(self))) data.append(d.unsqueeze(0)) data = torch.cat(data, dim=0) return data, data class SingleEncoder(nn.Module): def __init__(self, latents=32): super(SingleEncoder, self).__init__() self.block = MLP(28 * 28, latents, hidden_size=64, depth=4) def forward(self, inputs): return self.block(inputs) class Encoder(nn.Module): def __init__(self, single, size=5, latents=16): super(Encoder, self).__init__() self.size = size self.single = single self.weight = nn.Linear(32, 1) self.combine = MLP(32, 32, 64, depth=3) self.mean = nn.Linear(32, latents) self.logvar = nn.Linear(32, latents) def forward(self, inputs): inputs = inputs.view(-1, 28 * 28) out = self.single(inputs) weights = self.weight(out) out = out.view(-1, self.size, 32) weights = weights.view(-1, self.size, 1).softmax(dim=1) pool = (weights * out).sum(dim=1) pool = self.combine(pool) return self.mean(pool), self.logvar(pool) class Generator(nn.Module): def __init__(self, size=5): super(Generator, self).__init__() self.size = size self.input = SingleEncoder() self.condition = Encoder(self.input) self.combine = MLP(32, 28 * 28, hidden_size=128, depth=4) def sample(self, data): support, values = data mean, logvar = self.condition(support) distribution = Normal(mean, torch.exp(0.5 * logvar)) latent_sample = distribution.rsample() latent_sample = torch.repeat_interleave(latent_sample, self.size, dim=0) local_samples = torch.randn(support.size(0) * self.size, 16) sample = torch.cat((latent_sample, local_samples), dim=1) return (support, sample), (mean, logvar) def forward(self, data): (support, sample), _ = data return support, self.combine(sample).view(-1, self.size, 1, 28, 28).sigmoid() class Discriminator(nn.Module): def __init__(self, encoder, size=5): super(Discriminator, self).__init__() self.size = size self.encoder = encoder self.input = encoder.single self.verdict = MLP(28 * 28 + 16, 1, hidden_size=128, depth=4, batch_norm=False, activation=func.leaky_relu) def forward(self, data): support, values = data mean, logvar = self.encoder(support) distribution = Normal(mean, torch.exp(0.5 * logvar)) latent_sample = distribution.rsample() latent_sample = torch.repeat_interleave(latent_sample, self.size, dim=0) combined = torch.cat((values.view(-1, 28 * 28), latent_sample), dim=1) return self.verdict(combined) class MNISTSetTraining(FewShotGANTraining): def each_generate(self, data, generated, sample): ref = generated[0] data = generated[1] samples = [sample for sample in ref.contiguous().view(-1, 1, 28, 28)[:10]] samples = torch.cat(samples, dim=-1) self.writer.add_image("reference", samples, self.step_id) samples = [sample for sample in data.view(-1, 1, 28, 28)[:10]] samples = torch.cat(samples, dim=-1) self.writer.add_image("samples", samples, self.step_id) if __name__ == "__main__": mnist = MNIST("examples/", download=False, transform=ToTensor()) data = MNISTSet(mnist) generator = Generator() discriminator = Discriminator(generator.condition) training = MNISTSetTraining( generator, discriminator, data, network_name="set-mnist-gan", device="cpu", batch_size=40, max_epochs=1000, n_critic=2, verbose=True ) training.train()
31.816327
111
0.6904
import random import torch import torch.nn as nn import torch.nn.functional as func from torch.nn.utils import spectral_norm from torch.utils.data import Dataset from torch.distributions import Normal from torchvision.datasets import MNIST from torchvision.transforms import ToTensor from torchsupport.modules.basic import MLP from torchsupport.modules.residual import ResNetBlock2d from torchsupport.training.samplers import Langevin from torchsupport.training.few_shot_gan import FewShotGANTraining def normalize(image): return (image - image.min()) / (image.max() - image.min()) class EnergyDataset(Dataset): def __init__(self, data): self.data = data def __getitem__(self, index): data, label_index = self.data[index] label = torch.zeros(10) label[label_index] = 1 return data, label def __len__(self): return len(self.data) class MNISTSet(EnergyDataset): def __init__(self, data, size=5): super().__init__(data) self.size = size def __getitem__(self, index): data = [] label = random.randrange(10) for idx in range(self.size): d, l = super().__getitem__(random.randrange(len(self))) while l[label] < 1.0: d, l = super().__getitem__(random.randrange(len(self))) data.append(d.unsqueeze(0)) data = torch.cat(data, dim=0) return data, data class SingleEncoder(nn.Module): def __init__(self, latents=32): super(SingleEncoder, self).__init__() self.block = MLP(28 * 28, latents, hidden_size=64, depth=4) def forward(self, inputs): return self.block(inputs) class Encoder(nn.Module): def __init__(self, single, size=5, latents=16): super(Encoder, self).__init__() self.size = size self.single = single self.weight = nn.Linear(32, 1) self.combine = MLP(32, 32, 64, depth=3) self.mean = nn.Linear(32, latents) self.logvar = nn.Linear(32, latents) def forward(self, inputs): inputs = inputs.view(-1, 28 * 28) out = self.single(inputs) weights = self.weight(out) out = out.view(-1, self.size, 32) weights = weights.view(-1, self.size, 1).softmax(dim=1) pool = (weights * out).sum(dim=1) pool = self.combine(pool) return self.mean(pool), self.logvar(pool) class Generator(nn.Module): def __init__(self, size=5): super(Generator, self).__init__() self.size = size self.input = SingleEncoder() self.condition = Encoder(self.input) self.combine = MLP(32, 28 * 28, hidden_size=128, depth=4) def sample(self, data): support, values = data mean, logvar = self.condition(support) distribution = Normal(mean, torch.exp(0.5 * logvar)) latent_sample = distribution.rsample() latent_sample = torch.repeat_interleave(latent_sample, self.size, dim=0) local_samples = torch.randn(support.size(0) * self.size, 16) sample = torch.cat((latent_sample, local_samples), dim=1) return (support, sample), (mean, logvar) def forward(self, data): (support, sample), _ = data return support, self.combine(sample).view(-1, self.size, 1, 28, 28).sigmoid() class Discriminator(nn.Module): def __init__(self, encoder, size=5): super(Discriminator, self).__init__() self.size = size self.encoder = encoder self.input = encoder.single self.verdict = MLP(28 * 28 + 16, 1, hidden_size=128, depth=4, batch_norm=False, activation=func.leaky_relu) def forward(self, data): support, values = data mean, logvar = self.encoder(support) distribution = Normal(mean, torch.exp(0.5 * logvar)) latent_sample = distribution.rsample() latent_sample = torch.repeat_interleave(latent_sample, self.size, dim=0) combined = torch.cat((values.view(-1, 28 * 28), latent_sample), dim=1) return self.verdict(combined) class MNISTSetTraining(FewShotGANTraining): def each_generate(self, data, generated, sample): ref = generated[0] data = generated[1] samples = [sample for sample in ref.contiguous().view(-1, 1, 28, 28)[:10]] samples = torch.cat(samples, dim=-1) self.writer.add_image("reference", samples, self.step_id) samples = [sample for sample in data.view(-1, 1, 28, 28)[:10]] samples = torch.cat(samples, dim=-1) self.writer.add_image("samples", samples, self.step_id) if __name__ == "__main__": mnist = MNIST("examples/", download=False, transform=ToTensor()) data = MNISTSet(mnist) generator = Generator() discriminator = Discriminator(generator.condition) training = MNISTSetTraining( generator, discriminator, data, network_name="set-mnist-gan", device="cpu", batch_size=40, max_epochs=1000, n_critic=2, verbose=True ) training.train()
true
true
1c2c0732857dffb457209f64f936c6c97ee67f82
49
py
Python
writer/__init__.py
thsis/timesheets
fa849e0e67aac30de777312adc5b232aa79ecb31
[ "WTFPL" ]
3
2020-07-26T18:04:37.000Z
2022-02-08T13:27:47.000Z
writer/__init__.py
thsis/timesheets
fa849e0e67aac30de777312adc5b232aa79ecb31
[ "WTFPL" ]
null
null
null
writer/__init__.py
thsis/timesheets
fa849e0e67aac30de777312adc5b232aa79ecb31
[ "WTFPL" ]
null
null
null
from ._writer import Writer __all__ = ["Writer"]
16.333333
27
0.734694
from ._writer import Writer __all__ = ["Writer"]
true
true
1c2c077f814bee6ca3254a928438dc8c529d69d6
12,450
py
Python
guilded/user.py
ShashankKumarSaxena/enhanced-guilded.py
285bf65f115362f69b36547ad77dc02598a70e28
[ "MIT" ]
null
null
null
guilded/user.py
ShashankKumarSaxena/enhanced-guilded.py
285bf65f115362f69b36547ad77dc02598a70e28
[ "MIT" ]
null
null
null
guilded/user.py
ShashankKumarSaxena/enhanced-guilded.py
285bf65f115362f69b36547ad77dc02598a70e28
[ "MIT" ]
null
null
null
""" MIT License Copyright (c) 2020-present shay (shayypy) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ This project includes code from https://github.com/Rapptz/discord.py, which is available under the MIT license: The MIT License (MIT) Copyright (c) 2015-present Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import guilded.abc from .colour import Colour from .utils import ISO8601, parse_hex_number from .file import File, MediaType class Device: """Represents a device that the :class:`ClientUser` is logged into. Attributes ------------ type: :class:`str` The type of device. Could be ``desktop`` or ``mobile``. id: :class:`str` The ID of this device. This is a UUID for mobile devices but an even longer string on desktops. last_online: :class:`datetime.datetime` When this device was last active. active: :class:`bool` Whether this device is "active". This seems to always be ``True``. """ def __init__(self, data): self.type = data.get('type') self.id = data.get('id') self.last_online = ISO8601(data.get('lastOnline')) self.active = data.get('isActive', False) class User(guilded.abc.User, guilded.abc.Messageable): """Represents a user in Guilded.""" async def block(self): """|coro| Block this user. """ await self._state.block_user(self.id) async def unblock(self): """|coro| Unblock this user. """ await self._state.unblock_user(self.id) async def accept_friend_request(self): """|coro| Accept this user's friend request, if it exists. """ await self._state.accept_friend_request(self.id) async def decline_friend_request(self): """|coro| Decline this user's friend request, if it exists. """ await self._state.decline_friend_request(self.id) async def send_friend_request(self): """|coro| Send a friend request to this user. """ await self._state.create_friend_request([self.id]) async def delete_friend_request(self): """|coro| Delete your friend request to this user, if it exists. """ await self._state.delete_friend_request(self.id) class Member(User): """Represents a member of a team. Attributes ------------ team: :class:`Team` The team this member is from. xp: :class:`int` This member's XP. Could be negative. joined_at: :class:`datetime.datetime` When this user joined their team. display_name: :class:`str` This member's display name (``nick`` if present, else ``name``) colour: Optional[:class:`int`] The color that this member's name displays with. There is an alias for this called ``color``. nick: Optional[:class:`str`] This member's nickname, if any. """ def __init__(self, *, state, data, **extra): super().__init__(state=state, data=data) self._team = extra.get('team') or data.get('team') self.team_id = data.get('teamId') or (self._team.id if self._team else None) self.nick = data.get('nickname') self.xp = data.get('teamXp') self.joined_at = ISO8601(data.get('joinDate')) colour = data.get('colour') or data.get('color') if colour is not None and not isinstance(colour, Colour): self.colour = parse_hex_number(colour) else: self.colour = colour def __str__(self) -> str: return self.nick def __repr__(self): return f'<Member id={self.id!r} name={self.name!r} team={self.team!r}>' @property def team(self): return self._team or self._state._get_team(self.team_id) @property def guild(self): return self.team @property def color(self): return self.colour @property def display_name(self): return self.nick or self.name async def edit(self, **kwargs): """|coro| Edit this member. Parameters ------------ nick: Optional[:class:`str`] A new nickname. Use ``None`` to reset. xp: Optional[:class:`int`] A new XP value. """ try: nick = kwargs.pop('nick') except KeyError: pass else: if nick is None: await self._state.reset_team_member_nickname(self.team.id, self.id) else: await self._state.change_team_member_nickname(self.team.id, self.id, nick) self.nick = nick try: xp = kwargs.pop('xp') except KeyError: pass else: await self._state.set_team_member_xp(self.team.id, self.id, xp) self.xp = xp async def ban(self, **kwargs): """|coro| Ban this member. Equivalent to :meth:`Team.ban`. """ return await self.team.ban(self, **kwargs) async def unban(self): """|coro| Unban this member. Equivalent to :meth:`Team.unban`. """ return await self.team.unban(self) async def kick(self): """|coro| Kick this member. Equivalent to :meth:`Team.kick`. """ return await self.team.kick(self) class ClientUser(guilded.abc.User): """Represents the current logged-in user. Attributes ------------ devices: List[:class:`Device`] The devices this account is logged in on. accepted_friends: List[:class:`User`] This account's accepted friends. Could be partial (only ID) if the user was not cached. pending_friends: List[:class:`User`] This account's pending friends (requested by this ``ClientUser``). Could be partial (only ID) if the user was not cached. requested_friends: List[:class:`User`] This account's requested friends. Could be partial (only ID) if the user was not cached. """ def __init__(self, *, state, data): super().__init__(state=state, data=data) user = data.get('user', data) self.devices = [Device(device_data) for device_data in user.get('devices', [])] self._accepted_friends = {} self._pending_friends = {} self._requested_friends = {} for partial_friend in data.get('friends', []): friend_user = self._state._get_user(partial_friend['friendUserId']) if not friend_user: friend_user = self._state.create_user( data={'id': partial_friend['friendUserId']}, friend_status=partial_friend['friendStatus'], friend_created_at=partial_friend['createdAt'] ) else: friend_user.friend_status = partial_friend['friendStatus'] friend_user.friend_requested_at = ISO8601(partial_friend['createdAt']) if friend_user.friend_status == 'accepted': self._accepted_friends[friend_user.id] = friend_user elif friend_user.friend_status == 'pending': self._pending_friends[friend_user.id] = friend_user elif friend_user.friend_status == 'requested': self._requested_friends[friend_user.id] = friend_user @property def friends(self): """This user's accepted, pending, and requested friends. All items in this list are expected to have ``id``, ``friend_status``, and ``friend_requested_at`` attributes at a bare minimum. """ return self.accepted_friends + self.pending_friends + self.requested_friends @property def accepted_friends(self): return list(self._accepted_friends.values()) @property def pending_friends(self): return list(self._pending_friends.values()) @property def requested_friends(self): return list(self._requested_friends.values()) def __repr__(self): return f'<ClientUser id={repr(self.id)} name={repr(self.name)}>' async def fetch_friends(self): """|coro| Fetch a list of this account's accepted, pending, and requested friends. Returns --------- List[:class:`User`] This user's accepted, pending, and requested friends. """ friends = await self._state.get_friends() for friend_data in friends.get('friends', []): friend = self._state.create_user(data=friend_data, friend_status='accepted') self._accepted_friends[friend.id] = friend for friend_data in friends.get('friendRequests', {}).get('pending', []): friend = self._state.create_user(data=friend_data, friend_status='pending') self._pending_friends[friend.id] = friend for friend_data in friends.get('friendRequests', {}).get('requested', []): friend = self._state.create_user(data=friend_data, friend_status='requested') self._requested_friends[friend.id] = friend return self.friends async def edit_settings(self, **kwargs): """|coro| Change client settings. """ payload = {} try: payload['useLegacyNav'] = kwargs.pop('legacy_navigation') except KeyError: pass async def edit(self, **kwargs): """|coro| Edit your account. """ try: avatar = kwargs.pop('avatar') except KeyError: pass else: if avatar is None: image_url = None else: file = File(avatar) file.set_media_type(MediaType.user_avatar) await file._upload(self._state) image_url = file.url await self._state.set_profile_images(image_url) try: banner = kwargs.pop('banner') except KeyError: pass else: if banner is None: image_url = None else: file = File(banner) file.set_media_type(MediaType.user_banner) await file._upload(self._state) image_url = file.url await self._state.set_profile_banner(image_url) #payload = {} #await self._state.edit_current_user()
33.2
90
0.621526
import guilded.abc from .colour import Colour from .utils import ISO8601, parse_hex_number from .file import File, MediaType class Device: def __init__(self, data): self.type = data.get('type') self.id = data.get('id') self.last_online = ISO8601(data.get('lastOnline')) self.active = data.get('isActive', False) class User(guilded.abc.User, guilded.abc.Messageable): async def block(self): await self._state.block_user(self.id) async def unblock(self): await self._state.unblock_user(self.id) async def accept_friend_request(self): await self._state.accept_friend_request(self.id) async def decline_friend_request(self): await self._state.decline_friend_request(self.id) async def send_friend_request(self): await self._state.create_friend_request([self.id]) async def delete_friend_request(self): await self._state.delete_friend_request(self.id) class Member(User): def __init__(self, *, state, data, **extra): super().__init__(state=state, data=data) self._team = extra.get('team') or data.get('team') self.team_id = data.get('teamId') or (self._team.id if self._team else None) self.nick = data.get('nickname') self.xp = data.get('teamXp') self.joined_at = ISO8601(data.get('joinDate')) colour = data.get('colour') or data.get('color') if colour is not None and not isinstance(colour, Colour): self.colour = parse_hex_number(colour) else: self.colour = colour def __str__(self) -> str: return self.nick def __repr__(self): return f'<Member id={self.id!r} name={self.name!r} team={self.team!r}>' @property def team(self): return self._team or self._state._get_team(self.team_id) @property def guild(self): return self.team @property def color(self): return self.colour @property def display_name(self): return self.nick or self.name async def edit(self, **kwargs): try: nick = kwargs.pop('nick') except KeyError: pass else: if nick is None: await self._state.reset_team_member_nickname(self.team.id, self.id) else: await self._state.change_team_member_nickname(self.team.id, self.id, nick) self.nick = nick try: xp = kwargs.pop('xp') except KeyError: pass else: await self._state.set_team_member_xp(self.team.id, self.id, xp) self.xp = xp async def ban(self, **kwargs): return await self.team.ban(self, **kwargs) async def unban(self): return await self.team.unban(self) async def kick(self): return await self.team.kick(self) class ClientUser(guilded.abc.User): def __init__(self, *, state, data): super().__init__(state=state, data=data) user = data.get('user', data) self.devices = [Device(device_data) for device_data in user.get('devices', [])] self._accepted_friends = {} self._pending_friends = {} self._requested_friends = {} for partial_friend in data.get('friends', []): friend_user = self._state._get_user(partial_friend['friendUserId']) if not friend_user: friend_user = self._state.create_user( data={'id': partial_friend['friendUserId']}, friend_status=partial_friend['friendStatus'], friend_created_at=partial_friend['createdAt'] ) else: friend_user.friend_status = partial_friend['friendStatus'] friend_user.friend_requested_at = ISO8601(partial_friend['createdAt']) if friend_user.friend_status == 'accepted': self._accepted_friends[friend_user.id] = friend_user elif friend_user.friend_status == 'pending': self._pending_friends[friend_user.id] = friend_user elif friend_user.friend_status == 'requested': self._requested_friends[friend_user.id] = friend_user @property def friends(self): return self.accepted_friends + self.pending_friends + self.requested_friends @property def accepted_friends(self): return list(self._accepted_friends.values()) @property def pending_friends(self): return list(self._pending_friends.values()) @property def requested_friends(self): return list(self._requested_friends.values()) def __repr__(self): return f'<ClientUser id={repr(self.id)} name={repr(self.name)}>' async def fetch_friends(self): friends = await self._state.get_friends() for friend_data in friends.get('friends', []): friend = self._state.create_user(data=friend_data, friend_status='accepted') self._accepted_friends[friend.id] = friend for friend_data in friends.get('friendRequests', {}).get('pending', []): friend = self._state.create_user(data=friend_data, friend_status='pending') self._pending_friends[friend.id] = friend for friend_data in friends.get('friendRequests', {}).get('requested', []): friend = self._state.create_user(data=friend_data, friend_status='requested') self._requested_friends[friend.id] = friend return self.friends async def edit_settings(self, **kwargs): payload = {} try: payload['useLegacyNav'] = kwargs.pop('legacy_navigation') except KeyError: pass async def edit(self, **kwargs): try: avatar = kwargs.pop('avatar') except KeyError: pass else: if avatar is None: image_url = None else: file = File(avatar) file.set_media_type(MediaType.user_avatar) await file._upload(self._state) image_url = file.url await self._state.set_profile_images(image_url) try: banner = kwargs.pop('banner') except KeyError: pass else: if banner is None: image_url = None else: file = File(banner) file.set_media_type(MediaType.user_banner) await file._upload(self._state) image_url = file.url await self._state.set_profile_banner(image_url)
true
true
1c2c087406338bf6b6a5c280270dabf1873aef85
6,991
py
Python
plotting.py
KonstantinIvanchenko/selfdriving_env_sim
2e524c9a7164020a0bc35af4f1b6556777a8289c
[ "MIT" ]
1
2020-08-26T19:41:02.000Z
2020-08-26T19:41:02.000Z
plotting.py
KonstantinIvanchenko/selfdriving_env_sim
2e524c9a7164020a0bc35af4f1b6556777a8289c
[ "MIT" ]
null
null
null
plotting.py
KonstantinIvanchenko/selfdriving_env_sim
2e524c9a7164020a0bc35af4f1b6556777a8289c
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. # # Modified work: Konstantin Ivanchenko # Date: December 25, 2019 from external_source import live_plotter as lp class MotionPlotter(object): def __init__(self, waypoints, num_local_path, trajectory = True, controls = True): self.tr_plot = lp.LivePlotter(tk_title="Trajectory Visualization") self.ct_plot = lp.LivePlotter(tk_title="Control Outputs") self.waypoints = waypoints self.wx = [waypoints[i].x for i in range(len(waypoints))] self.wy = [waypoints[i].y for i in range(len(waypoints))] #TODO: immplement dynamic window sizing self.win_size = len(self.wx)*10 self.fig_names = {"waypoints" : "waypoints", "trajectory" : "trajectory", "ego_a_pos" : "ego_A_pos", "ego_b_pos" : "ego_B_pos", "ego" : "ego", "speed" : "speed", "des_speed" : "des_speed", "throttle" : "throttle", "brake" : "brake", "steer" : "steer", "paths" : "local_path", "llines" : "llines", "rlines" : "rlines"} if trajectory is True and waypoints is not None: self.tr_fig = self.tr_plot.plot_new_dynamic_2d_figure( title='Motion Trajectory', figsize=(8, 8), # inches edgecolor="black", rect=[0.1, 0.1, 0.8, 0.8] # inches ) self.tr_fig.set_invert_x_axis() # to be inverted due to reversed coordinates in Carla self.tr_fig.set_axis_equal() ### for i in range(20): self.tr_fig.add_graph(self.fig_names["llines"]+str(i), window_size=200, x0=None, y0=None, color='b') ### for i in range(20): self.tr_fig.add_graph(self.fig_names["rlines"]+str(i), window_size=200, x0=None, y0=None, color='g') self.tr_fig.add_graph(self.fig_names["waypoints"], window_size=len(waypoints), x0=self.wx, y0=self.wy, linestyle="-", marker="", color='g') # Add trajectory markers self.tr_fig.add_graph(self.fig_names["trajectory"], window_size=self.win_size, x0=[self.wx[0]] * self.win_size, y0=[self.wy[0]] * self.win_size, color=[1, 0.5, 0]) # Add ego A marker self.tr_fig.add_graph(self.fig_names["ego_a_pos"], window_size=1, x0=[self.wx[0]], y0=[self.wy[0]], marker=11, color=[1, 0.5, 0], markertext="A", marker_text_offset=1) # Add ego B marker self.tr_fig.add_graph(self.fig_names["ego_b_pos"], window_size=1, x0=[self.wx[-1]], y0=[self.wy[-1]], marker=11, color=[1, 0.5, 0], markertext="B", marker_text_offset=1) # Add car marker self.tr_fig.add_graph(self.fig_names["ego"], window_size=1, marker="s", color='b', markertext="ego", marker_text_offset=1) # Add local path proposals for i in range(num_local_path): self.tr_fig.add_graph(self.fig_names["paths"] + str(i), window_size=200, x0=None, y0=None, color=[0.0, 0.0, 1.0]) """ # Add lead car information trajectory_fig.add_graph("leadcar", window_size=1, marker="s", color='g', markertext="Lead Car", marker_text_offset=1) # Add stop sign position trajectory_fig.add_graph("stopsign", window_size=1, x0=[stopsign_fences[0][0]], y0=[stopsign_fences[0][1]], marker="H", color="r", markertext="Stop Sign", marker_text_offset=1) # Add stop sign "stop line" trajectory_fig.add_graph("stopsign_fence", window_size=1, x0=[stopsign_fences[0][0], stopsign_fences[0][2]], y0=[stopsign_fences[0][1], stopsign_fences[0][3]], color="r") # Load parked car points parkedcar_box_pts_np = np.array(parkedcar_box_pts) trajectory_fig.add_graph("parkedcar_pts", window_size=parkedcar_box_pts_np.shape[0], x0=parkedcar_box_pts_np[:,0], y0=parkedcar_box_pts_np[:,1], linestyle="", marker="+", color='b') # Add lookahead path trajectory_fig.add_graph("selected_path", window_size=INTERP_MAX_POINTS_PLOT, x0=[start_x]*INTERP_MAX_POINTS_PLOT, y0=[start_y]*INTERP_MAX_POINTS_PLOT, color=[1, 0.5, 0.0], linewidth=3) # Add local path proposals for i in range(NUM_PATHS): trajectory_fig.add_graph("local_path " + str(i), window_size=200, x0=None, y0=None, color=[0.0, 0.0, 1.0]) """ if controls is True: self.ego_speed_fig = self.ct_plot.plot_new_dynamic_figure(title="Ego Speed (m/s)") self.ego_speed_fig.add_graph(self.fig_names["speed"], label="speed", window_size=self.win_size) self.ego_speed_fig.add_graph(self.fig_names["des_speed"], label="des_speed", window_size=self.win_size) self.throttle_fig = self.ct_plot.plot_new_dynamic_figure(title="Throttle Signal (0..1)") self.throttle_fig.add_graph(self.fig_names["throttle"], label="throttle", window_size=self.win_size) self.brake_fig = self.ct_plot.plot_new_dynamic_figure(title="Brake Signal (0..1)") self.brake_fig.add_graph(self.fig_names["brake"], label="brake", window_size=self.win_size) self.steer_fig = self.ct_plot.plot_new_dynamic_figure(title="Steer Signal (0..1)") self.steer_fig.add_graph(self.fig_names["steer"], label="steer", window_size=self.win_size) def refresh_plots(self): self.tr_plot.refresh() self.ct_plot.refresh() def get_step(self): return 1/self.win_size
46.919463
115
0.506508
from external_source import live_plotter as lp class MotionPlotter(object): def __init__(self, waypoints, num_local_path, trajectory = True, controls = True): self.tr_plot = lp.LivePlotter(tk_title="Trajectory Visualization") self.ct_plot = lp.LivePlotter(tk_title="Control Outputs") self.waypoints = waypoints self.wx = [waypoints[i].x for i in range(len(waypoints))] self.wy = [waypoints[i].y for i in range(len(waypoints))] self.win_size = len(self.wx)*10 self.fig_names = {"waypoints" : "waypoints", "trajectory" : "trajectory", "ego_a_pos" : "ego_A_pos", "ego_b_pos" : "ego_B_pos", "ego" : "ego", "speed" : "speed", "des_speed" : "des_speed", "throttle" : "throttle", "brake" : "brake", "steer" : "steer", "paths" : "local_path", "llines" : "llines", "rlines" : "rlines"} if trajectory is True and waypoints is not None: self.tr_fig = self.tr_plot.plot_new_dynamic_2d_figure( title='Motion Trajectory', figsize=(8, 8), edgecolor="black", rect=[0.1, 0.1, 0.8, 0.8] ) self.tr_fig.set_invert_x_axis() self.tr_fig.set_axis_equal() for i in range(20): self.tr_fig.add_graph(self.fig_names["llines"]+str(i), window_size=200, x0=None, y0=None, color='b') for i in range(20): self.tr_fig.add_graph(self.fig_names["rlines"]+str(i), window_size=200, x0=None, y0=None, color='g') self.tr_fig.add_graph(self.fig_names["waypoints"], window_size=len(waypoints), x0=self.wx, y0=self.wy, linestyle="-", marker="", color='g') self.tr_fig.add_graph(self.fig_names["trajectory"], window_size=self.win_size, x0=[self.wx[0]] * self.win_size, y0=[self.wy[0]] * self.win_size, color=[1, 0.5, 0]) self.tr_fig.add_graph(self.fig_names["ego_a_pos"], window_size=1, x0=[self.wx[0]], y0=[self.wy[0]], marker=11, color=[1, 0.5, 0], markertext="A", marker_text_offset=1) self.tr_fig.add_graph(self.fig_names["ego_b_pos"], window_size=1, x0=[self.wx[-1]], y0=[self.wy[-1]], marker=11, color=[1, 0.5, 0], markertext="B", marker_text_offset=1) self.tr_fig.add_graph(self.fig_names["ego"], window_size=1, marker="s", color='b', markertext="ego", marker_text_offset=1) for i in range(num_local_path): self.tr_fig.add_graph(self.fig_names["paths"] + str(i), window_size=200, x0=None, y0=None, color=[0.0, 0.0, 1.0]) if controls is True: self.ego_speed_fig = self.ct_plot.plot_new_dynamic_figure(title="Ego Speed (m/s)") self.ego_speed_fig.add_graph(self.fig_names["speed"], label="speed", window_size=self.win_size) self.ego_speed_fig.add_graph(self.fig_names["des_speed"], label="des_speed", window_size=self.win_size) self.throttle_fig = self.ct_plot.plot_new_dynamic_figure(title="Throttle Signal (0..1)") self.throttle_fig.add_graph(self.fig_names["throttle"], label="throttle", window_size=self.win_size) self.brake_fig = self.ct_plot.plot_new_dynamic_figure(title="Brake Signal (0..1)") self.brake_fig.add_graph(self.fig_names["brake"], label="brake", window_size=self.win_size) self.steer_fig = self.ct_plot.plot_new_dynamic_figure(title="Steer Signal (0..1)") self.steer_fig.add_graph(self.fig_names["steer"], label="steer", window_size=self.win_size) def refresh_plots(self): self.tr_plot.refresh() self.ct_plot.refresh() def get_step(self): return 1/self.win_size
true
true
1c2c08fa5eda507ae606cd60e1248cb0e025213c
1,650
py
Python
store/store_de_ro_prices.py
rkneusel9/SwarmOptimization
5445b6f90ab49339ca0fdb71e98d44e6827c95a8
[ "MIT" ]
2
2022-01-11T17:14:14.000Z
2022-03-07T10:22:32.000Z
store/store_de_ro_prices.py
rkneusel9/SwarmOptimization
5445b6f90ab49339ca0fdb71e98d44e6827c95a8
[ "MIT" ]
null
null
null
store/store_de_ro_prices.py
rkneusel9/SwarmOptimization
5445b6f90ab49339ca0fdb71e98d44e6827c95a8
[ "MIT" ]
1
2021-11-24T01:11:49.000Z
2021-11-24T01:11:49.000Z
import numpy as np import pickle import matplotlib.pylab as plt d = pickle.load(open("de_50_40_16000_results.pkl","rb")) r = pickle.load(open("ro_50_40_16000_results.pkl","rb")) #g = pickle.load(open("ga_50_40_16000_results.pkl","rb")) p = np.array(pickle.load(open("products.pkl","rb"))[-1]) w = np.array(pickle.load(open("products.pkl","rb"))[0]) w = w / w.sum() de = p[np.argsort(d["gpos"][-1])] wde = w[np.argsort(d["gpos"][-1])] ro = p[np.argsort(r["gpos"][-1])] wro = w[np.argsort(r["gpos"][-1])] #ga = p[np.argsort(g["gpos"][-1])] #wga = w[np.argsort(g["gpos"][-1])] plt.plot(de, marker='P', linestyle='none', color='k', label='DE') plt.plot(ro, marker='o', linestyle='none', color='k', label='RO') #plt.plot(ga, marker='>', linestyle='none', color='k', label='GA') plt.plot(de, linestyle='solid', color='k') plt.plot(ro, linestyle='dotted', color='k') #plt.plot(ga, linestyle='dashed', color='k') plt.xlabel("Product order") plt.ylabel("Cost") plt.legend(loc="upper right") plt.tight_layout(pad=0, w_pad=0, h_pad=0) plt.savefig("store_de_ro_prices.png", dpi=300) plt.show() plt.close() plt.plot(wde*de, marker='P', linestyle='none', color='k', label='DE') plt.plot(wro*ro, marker='o', linestyle='none', color='k', label='RO') #plt.plot(wga*ga, marker='>', linestyle='none', color='k', label='GA') plt.plot(wde*de, linestyle='solid', color='k') plt.plot(wro*ro, linestyle='dotted', color='k') #plt.plot(wga*ga, linestyle='dashed', color='k') plt.xlabel("Product order") plt.ylabel("Cost * Probability") plt.legend(loc="upper left") plt.tight_layout(pad=0, w_pad=0, h_pad=0) plt.savefig("store_de_ro_prob.png", dpi=300) plt.show()
36.666667
70
0.661818
import numpy as np import pickle import matplotlib.pylab as plt d = pickle.load(open("de_50_40_16000_results.pkl","rb")) r = pickle.load(open("ro_50_40_16000_results.pkl","rb")) p = np.array(pickle.load(open("products.pkl","rb"))[-1]) w = np.array(pickle.load(open("products.pkl","rb"))[0]) w = w / w.sum() de = p[np.argsort(d["gpos"][-1])] wde = w[np.argsort(d["gpos"][-1])] ro = p[np.argsort(r["gpos"][-1])] wro = w[np.argsort(r["gpos"][-1])] plt.plot(de, marker='P', linestyle='none', color='k', label='DE') plt.plot(ro, marker='o', linestyle='none', color='k', label='RO') plt.plot(de, linestyle='solid', color='k') plt.plot(ro, linestyle='dotted', color='k') plt.xlabel("Product order") plt.ylabel("Cost") plt.legend(loc="upper right") plt.tight_layout(pad=0, w_pad=0, h_pad=0) plt.savefig("store_de_ro_prices.png", dpi=300) plt.show() plt.close() plt.plot(wde*de, marker='P', linestyle='none', color='k', label='DE') plt.plot(wro*ro, marker='o', linestyle='none', color='k', label='RO') plt.plot(wde*de, linestyle='solid', color='k') plt.plot(wro*ro, linestyle='dotted', color='k') plt.xlabel("Product order") plt.ylabel("Cost * Probability") plt.legend(loc="upper left") plt.tight_layout(pad=0, w_pad=0, h_pad=0) plt.savefig("store_de_ro_prob.png", dpi=300) plt.show()
true
true
1c2c09d0914ee6083d8ca37494180d973848f2ef
10,083
py
Python
pcp_utils/cameras.py
YunchuZhang/Visually-Grounded-Library-of-Behaviors-for-Generalizing-Manipulation-Across-Objects-Configurations-
896afda942dfc04e4aaad2ee751c32df1eb17913
[ "MIT" ]
1
2022-03-14T22:25:17.000Z
2022-03-14T22:25:17.000Z
pcp_utils/cameras.py
YunchuZhang/Visually-Grounded-Library-of-Behaviors
896afda942dfc04e4aaad2ee751c32df1eb17913
[ "MIT" ]
null
null
null
pcp_utils/cameras.py
YunchuZhang/Visually-Grounded-Library-of-Behaviors
896afda942dfc04e4aaad2ee751c32df1eb17913
[ "MIT" ]
null
null
null
import numpy as np import math from scipy.linalg import inv, sqrtm import transformations def sym(w): return w.dot(inv(sqrtm(w.T.dot(w)))) def render_images(env, camera_img_height, camera_img_width, camera_fov, camera_positions, camera_quats, camera_name="ext_camera_0"): """ go through all the cameras and get rgbd """ n_cams = len(camera_positions) rgbs = [] depths = [] pix_T_cams = [] origin_T_camXs = [] for cam_id in range(n_cams): # need to reset everytime you want to take the picture: the camera has mass and it will fall during execution env.set_camera(camera_positions[cam_id, :], camera_quats[cam_id, :], camera_name= camera_name) rgb, depth = env.render_from_camera(camera_img_height, camera_img_width, camera_name=camera_name) # need to convert depth to real numbers pix_T_camX = get_intrinsics(camera_fov, camera_img_width, camera_img_height) origin_T_camX = gymenv_get_extrinsics(env, camera_name) rgbs.append(rgb) depths.append(depth) pix_T_cams.append(pix_T_camX) origin_T_camXs.append(origin_T_camX) images = dict() images['rgb_camXs'] = np.stack(rgbs, axis=0) images['depth_camXs'] = np.stack(depths, axis=0) images['pix_T_cams'] = np.stack(pix_T_cams, axis=0) images['origin_T_camXs'] = np.stack(origin_T_camXs, axis=0) return images def render_images_from_config(env, config): """ go through all the cameras and get rgbd """ camera_img_width = config['img_width'] camera_img_height = config['img_height'] camera_fov = config['fov_y'] camera_positions = config['pos'] camera_quats = config['quat'] camera_name = config['camera_name'] n_cams = len(camera_positions) rgbs = [] depths = [] for cam_id in range(n_cams): # need to reset everytime you want to take the picture: the camera has mass and it will fall during execution env.set_camera(camera_positions[cam_id, :], camera_quats[cam_id, :], camera_name=camera_name) rgb, depth = env.render_from_camera(camera_img_height, camera_img_width, camera_name=camera_name) rgbs.append(rgb) depths.append(depth) # return RGBD images of shape [n_cams, h, w, 4] return np.concatenate([np.array(rgbs), np.array(depths)[..., None]], -1) def render_image_from_camX(env, camera_img_height, camera_img_width, camera_fov, camera_name="ext_camera_0"): """ go through all the cameras and get rgbd """ n_cams = 1 rgbs = [] depths = [] pix_T_cams = [] origin_T_camXs = [] for cam_id in range(n_cams): rgb, depth = env.render_from_camera(camera_img_height, camera_img_width, camera_name=camera_name) # need to convert depth to real numbers pix_T_camX = get_intrinsics(camera_fov, camera_img_width, camera_img_height) origin_T_camX = gymenv_get_extrinsics(env, camera_name) rgbs.append(rgb) depths.append(depth) pix_T_cams.append(pix_T_camX) origin_T_camXs.append(origin_T_camX) images = dict() images['rgb_camXs'] = np.stack(rgbs, axis=0) images['depth_camXs'] = np.stack(depths, axis=0) images['pix_T_cams'] = np.stack(pix_T_cams, axis=0) images['origin_T_camXs'] = np.stack(origin_T_camXs, axis=0) return images def dm_get_extrinsics(physics, cam_id): """ physics: dm_control physics simulator object cam_id : id of the camera we want extrinsics for """ pos = physics.data.cam_xpos[cam_id] mat = physics.data.cam_xmat[cam_id].reshape(3,3) # mujoco z is pointing outwards of the lookat point # change it to have z looking at the lookat point rot_mat = np.asarray([[1, 0, 0], [0, -1, 0], [0, 0, -1]]) mat = np.dot(mat, rot_mat) # rot_mat_adam = np.asarray([[1, 0, 0], [0, 0, 1], [0, -1, 0]]) # rot_mat_adam = np.dot(rot_mat_adam, rot_mat) # mat = np.dot(rot_mat_adam, mat) ext = np.eye(4) ext[:3, :3] = mat ext[:3, 3] = pos return ext def gymenv_get_extrinsics(env, cam_name): """ physics: dm_control physics simulator object cam_id : id of the camera we want extrinsics for """ #pos, quat = env.get_object_pos(cam_name) pos, xmat = env.get_object_pos(cam_name) mat = np.zeros((4,4), np.float32) mat[3, 3] = 1 mat[:3, :3] = np.reshape(xmat, [3, 3]) #pos = physics.data.cam_xpos[cam_id] #mat = physics.data.cam_xmat[cam_id].reshape(3,3) #mat = transformations.quaternion_matrix(quat) # flip y and z mat[:,1] *= (-1) mat[:,2] *= (-1) mat[:3, 3] = pos return mat def get_intrinsics(fovy, img_width, img_height): """ fovy: fovy supplied in the y-direction cam_no: camera number in the scene img_width: width of the image img_height: height of the image """ # fovy = physics.model.cam_fovy[cam_no] # now compute the fovx # print(f'-- img_width: {img_width} --') # print(f'-- img_height: {img_height} --') aspect = float(img_width) / img_height # assert aspect == 1., "I am giving data such that aspect is 1" fovx = 2 * np.arctan(np.tan(np.deg2rad(fovy) * 0.5) * aspect) fovx = np.rad2deg(fovx) cx = img_width / 2. cy = img_height / 2. fx = cx / np.tan(np.deg2rad(fovx / 2.)) fy = cy / np.tan(np.deg2rad(fovy / 2.)) K = np.zeros((3,3), dtype=np.float) K[2][2] = 1 K[0][0] = fx K[1][1] = fy K[0][2] = cx K[1][2] = cy return K def get_quaternion(z_axis, world_up): """ z_axis = numpy.ndarray(n_pts, 3) world_up = axis representing the y axis """ world_up = np.tile(world_up, len(z_axis)).reshape(len(z_axis), 3) side_axis = np.cross(world_up, z_axis) side_axis = side_axis / np.linalg.norm(side_axis, axis=1).reshape(-1, 1) cam_locs_to_remove = np.where(np.isnan(np.linalg.norm(side_axis, axis=1))) cam_locs_to_take = np.ones(len(world_up)).astype(np.int) cam_locs_to_take[cam_locs_to_remove] = 0 world_up = world_up[cam_locs_to_take.astype(np.bool)] side_axis = side_axis[cam_locs_to_take.astype(np.bool)] z_axis = z_axis[cam_locs_to_take.astype(np.bool)] up_axis = np.cross(z_axis, side_axis) # TODO: find a better way to do this rot_mat = np.zeros((len(z_axis), 4, 4)) quats = list() for i in range(len(rot_mat)): rot_mat[i, :3, 0] = side_axis[i] rot_mat[i, :3, 1] = up_axis[i] rot_mat[i, :3, 2] = z_axis[i] rot_mat[i, 3, 3] = 1 if np.isnan(np.sum(rot_mat)): print('in the nan of utils while generating quaternions') from IPython import embed; embed() rot_mat[i] = sym(rot_mat[i]) quats.append(transformations.quaternion_from_matrix(rot_mat[i])) return cam_locs_to_take, np.stack(quats) def circle_pts(radius, angles): xs = radius*np.cos(angles) ys = radius*np.sin(angles) return np.c_[xs, ys] def generate_new_cameras_hemisphere(radius, lookat_point, pitch = [20, 60, 20], yaw = [0, 350, 36], yaw_list=None, rot_format="quat"): """ pitch: elevation [min_pitch, max_pitch, d_pitch] yaw: azimuth [min_yaw, max_yaw, d_yaw] """ min_pitch, max_pitch, d_pitch = pitch min_yaw, max_yaw, d_yaw = yaw xyz_points = [] quats = [] if yaw_list == None: yaw_list = range(min_yaw, max_yaw + 1, d_yaw) for pitch in range(min_pitch, max_pitch + 1, d_pitch): for yaw in yaw_list: mat_yaw = transformations.euler_matrix(0,0,math.radians(yaw), 'rxyz') mat_pitch = transformations.euler_matrix(0,math.radians(-pitch),0, 'rxyz') # camera at the origin is x+ = inverse lookat vector(z), y is x of camera # camera x: right, camera y: up, camera z: inverse lookat direction x_vector = np.zeros((4), dtype=np.float32) x_vector[0] = 1 y_vector = np.zeros((4), dtype=np.float32) y_vector[1] = 1 z_vector = np.zeros((4), dtype=np.float32) z_vector[2] = 1 z_vec_out = mat_yaw.dot(mat_pitch.dot(x_vector)) x_vec_out = mat_yaw.dot(mat_pitch.dot(y_vector)) y_vec_out = mat_yaw.dot(mat_pitch.dot(z_vector)) cam_loc = z_vec_out * radius rot_mat = np.eye(4, dtype=np.float32) rot_mat[:3, 0] = x_vec_out[:3] rot_mat[:3, 1] = y_vec_out[:3] rot_mat[:3, 2] = z_vec_out[:3] if rot_format == "quat": quat = transformations.quaternion_from_matrix(rot_mat) else: quat = np.reshape(rot_mat[:3,:3], [-1]) cam_loc = lookat_point + cam_loc[:3] xyz_points.append(cam_loc) quats.append(quat) quats = np.stack(quats, axis=0) xyz_points = np.stack(xyz_points, axis=0) return xyz_points, quats def generate_new_cameras(radius, center, lookat_vector, height, jitter_z=False, num_pts=50, jitter_amount=0.02): """ radius is the distance to the center on the xy plane center[2] is not used return: xyz_points: nviews x 3 quat: nviews x 4 """ # generate points on the circle angle = np.linspace(0, 2*np.pi, num=num_pts) # in radians # angle = np.asarray([0, np.pi/2., np.pi, 3*np.pi/2.]) xy_pts = circle_pts(radius, angle) # plt.scatter(xy_pts[:, 0], xy_pts[:, 1], c='b') # plt.show() # xyz_points xyz_points = np.c_[xy_pts[:, 0], xy_pts[:, 1], height*np.ones(len(xy_pts))] xyz_points[:, 0] += center[0] xyz_points[:, 1] += center[1] if jitter_z: xyz_points[:, 2] += (jitter_amount*np.random.normal(size=num_pts)) # generate the z-axis for each of these z_vector = xyz_points - lookat_vector z_axis = z_vector / np.linalg.norm(z_vector, axis=1).reshape(-1, 1) # now from this I will also generate the other two axis and quaternion _, quat = get_quaternion(z_axis, world_up=np.asarray([0., 0., 1.])) return xyz_points, quat
33.277228
134
0.632748
import numpy as np import math from scipy.linalg import inv, sqrtm import transformations def sym(w): return w.dot(inv(sqrtm(w.T.dot(w)))) def render_images(env, camera_img_height, camera_img_width, camera_fov, camera_positions, camera_quats, camera_name="ext_camera_0"): n_cams = len(camera_positions) rgbs = [] depths = [] pix_T_cams = [] origin_T_camXs = [] for cam_id in range(n_cams): env.set_camera(camera_positions[cam_id, :], camera_quats[cam_id, :], camera_name= camera_name) rgb, depth = env.render_from_camera(camera_img_height, camera_img_width, camera_name=camera_name) pix_T_camX = get_intrinsics(camera_fov, camera_img_width, camera_img_height) origin_T_camX = gymenv_get_extrinsics(env, camera_name) rgbs.append(rgb) depths.append(depth) pix_T_cams.append(pix_T_camX) origin_T_camXs.append(origin_T_camX) images = dict() images['rgb_camXs'] = np.stack(rgbs, axis=0) images['depth_camXs'] = np.stack(depths, axis=0) images['pix_T_cams'] = np.stack(pix_T_cams, axis=0) images['origin_T_camXs'] = np.stack(origin_T_camXs, axis=0) return images def render_images_from_config(env, config): camera_img_width = config['img_width'] camera_img_height = config['img_height'] camera_fov = config['fov_y'] camera_positions = config['pos'] camera_quats = config['quat'] camera_name = config['camera_name'] n_cams = len(camera_positions) rgbs = [] depths = [] for cam_id in range(n_cams): env.set_camera(camera_positions[cam_id, :], camera_quats[cam_id, :], camera_name=camera_name) rgb, depth = env.render_from_camera(camera_img_height, camera_img_width, camera_name=camera_name) rgbs.append(rgb) depths.append(depth) return np.concatenate([np.array(rgbs), np.array(depths)[..., None]], -1) def render_image_from_camX(env, camera_img_height, camera_img_width, camera_fov, camera_name="ext_camera_0"): n_cams = 1 rgbs = [] depths = [] pix_T_cams = [] origin_T_camXs = [] for cam_id in range(n_cams): rgb, depth = env.render_from_camera(camera_img_height, camera_img_width, camera_name=camera_name) pix_T_camX = get_intrinsics(camera_fov, camera_img_width, camera_img_height) origin_T_camX = gymenv_get_extrinsics(env, camera_name) rgbs.append(rgb) depths.append(depth) pix_T_cams.append(pix_T_camX) origin_T_camXs.append(origin_T_camX) images = dict() images['rgb_camXs'] = np.stack(rgbs, axis=0) images['depth_camXs'] = np.stack(depths, axis=0) images['pix_T_cams'] = np.stack(pix_T_cams, axis=0) images['origin_T_camXs'] = np.stack(origin_T_camXs, axis=0) return images def dm_get_extrinsics(physics, cam_id): pos = physics.data.cam_xpos[cam_id] mat = physics.data.cam_xmat[cam_id].reshape(3,3) rot_mat = np.asarray([[1, 0, 0], [0, -1, 0], [0, 0, -1]]) mat = np.dot(mat, rot_mat) ext = np.eye(4) ext[:3, :3] = mat ext[:3, 3] = pos return ext def gymenv_get_extrinsics(env, cam_name): pos, xmat = env.get_object_pos(cam_name) mat = np.zeros((4,4), np.float32) mat[3, 3] = 1 mat[:3, :3] = np.reshape(xmat, [3, 3]) mat[:,1] *= (-1) mat[:,2] *= (-1) mat[:3, 3] = pos return mat def get_intrinsics(fovy, img_width, img_height): aspect = float(img_width) / img_height fovx = 2 * np.arctan(np.tan(np.deg2rad(fovy) * 0.5) * aspect) fovx = np.rad2deg(fovx) cx = img_width / 2. cy = img_height / 2. fx = cx / np.tan(np.deg2rad(fovx / 2.)) fy = cy / np.tan(np.deg2rad(fovy / 2.)) K = np.zeros((3,3), dtype=np.float) K[2][2] = 1 K[0][0] = fx K[1][1] = fy K[0][2] = cx K[1][2] = cy return K def get_quaternion(z_axis, world_up): world_up = np.tile(world_up, len(z_axis)).reshape(len(z_axis), 3) side_axis = np.cross(world_up, z_axis) side_axis = side_axis / np.linalg.norm(side_axis, axis=1).reshape(-1, 1) cam_locs_to_remove = np.where(np.isnan(np.linalg.norm(side_axis, axis=1))) cam_locs_to_take = np.ones(len(world_up)).astype(np.int) cam_locs_to_take[cam_locs_to_remove] = 0 world_up = world_up[cam_locs_to_take.astype(np.bool)] side_axis = side_axis[cam_locs_to_take.astype(np.bool)] z_axis = z_axis[cam_locs_to_take.astype(np.bool)] up_axis = np.cross(z_axis, side_axis) rot_mat = np.zeros((len(z_axis), 4, 4)) quats = list() for i in range(len(rot_mat)): rot_mat[i, :3, 0] = side_axis[i] rot_mat[i, :3, 1] = up_axis[i] rot_mat[i, :3, 2] = z_axis[i] rot_mat[i, 3, 3] = 1 if np.isnan(np.sum(rot_mat)): print('in the nan of utils while generating quaternions') from IPython import embed; embed() rot_mat[i] = sym(rot_mat[i]) quats.append(transformations.quaternion_from_matrix(rot_mat[i])) return cam_locs_to_take, np.stack(quats) def circle_pts(radius, angles): xs = radius*np.cos(angles) ys = radius*np.sin(angles) return np.c_[xs, ys] def generate_new_cameras_hemisphere(radius, lookat_point, pitch = [20, 60, 20], yaw = [0, 350, 36], yaw_list=None, rot_format="quat"): min_pitch, max_pitch, d_pitch = pitch min_yaw, max_yaw, d_yaw = yaw xyz_points = [] quats = [] if yaw_list == None: yaw_list = range(min_yaw, max_yaw + 1, d_yaw) for pitch in range(min_pitch, max_pitch + 1, d_pitch): for yaw in yaw_list: mat_yaw = transformations.euler_matrix(0,0,math.radians(yaw), 'rxyz') mat_pitch = transformations.euler_matrix(0,math.radians(-pitch),0, 'rxyz') x_vector = np.zeros((4), dtype=np.float32) x_vector[0] = 1 y_vector = np.zeros((4), dtype=np.float32) y_vector[1] = 1 z_vector = np.zeros((4), dtype=np.float32) z_vector[2] = 1 z_vec_out = mat_yaw.dot(mat_pitch.dot(x_vector)) x_vec_out = mat_yaw.dot(mat_pitch.dot(y_vector)) y_vec_out = mat_yaw.dot(mat_pitch.dot(z_vector)) cam_loc = z_vec_out * radius rot_mat = np.eye(4, dtype=np.float32) rot_mat[:3, 0] = x_vec_out[:3] rot_mat[:3, 1] = y_vec_out[:3] rot_mat[:3, 2] = z_vec_out[:3] if rot_format == "quat": quat = transformations.quaternion_from_matrix(rot_mat) else: quat = np.reshape(rot_mat[:3,:3], [-1]) cam_loc = lookat_point + cam_loc[:3] xyz_points.append(cam_loc) quats.append(quat) quats = np.stack(quats, axis=0) xyz_points = np.stack(xyz_points, axis=0) return xyz_points, quats def generate_new_cameras(radius, center, lookat_vector, height, jitter_z=False, num_pts=50, jitter_amount=0.02): angle = np.linspace(0, 2*np.pi, num=num_pts) xy_pts = circle_pts(radius, angle) xyz_points = np.c_[xy_pts[:, 0], xy_pts[:, 1], height*np.ones(len(xy_pts))] xyz_points[:, 0] += center[0] xyz_points[:, 1] += center[1] if jitter_z: xyz_points[:, 2] += (jitter_amount*np.random.normal(size=num_pts)) z_vector = xyz_points - lookat_vector z_axis = z_vector / np.linalg.norm(z_vector, axis=1).reshape(-1, 1) _, quat = get_quaternion(z_axis, world_up=np.asarray([0., 0., 1.])) return xyz_points, quat
true
true
1c2c0a04625db08cdc0b0f638973ec5905bc5218
1,924
py
Python
tests/profiler_test.py
gully/jax
eb086f9b22154104b216b22ed006264989bcad41
[ "ECL-2.0", "Apache-2.0" ]
4
2021-04-02T03:46:28.000Z
2021-12-04T22:52:50.000Z
tests/profiler_test.py
gully/jax
eb086f9b22154104b216b22ed006264989bcad41
[ "ECL-2.0", "Apache-2.0" ]
1
2020-10-01T05:38:44.000Z
2020-10-01T05:38:44.000Z
tests/profiler_test.py
gully/jax
eb086f9b22154104b216b22ed006264989bcad41
[ "ECL-2.0", "Apache-2.0" ]
1
2020-08-28T18:42:08.000Z
2020-08-28T18:42:08.000Z
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from functools import partial import unittest from absl.testing import absltest import jax import jax.numpy as jnp import jax.profiler from jax.config import config import jax.test_util as jtu try: import portpicker except ImportError: portpicker = None config.parse_flags_with_absl() class ProfilerTest(unittest.TestCase): # These tests simply test that the profiler API does not crash; they do not # check functional correctness. @unittest.skipIf(not portpicker, "Test requires portpicker") def testStartServer(self): port = portpicker.pick_unused_port() jax.profiler.start_server(port=port) del port def testTraceContext(self): x = 3 with jax.profiler.TraceContext("mycontext"): x = x + 2 def testTraceFunction(self): @jax.profiler.trace_function def f(x): return x + 2 self.assertEqual(f(7), 9) @partial(jax.profiler.trace_function, name="aname") def g(x): return x + 2 self.assertEqual(g(7), 9) @partial(jax.profiler.trace_function, name="aname", akwarg="hello") def h(x): return x + 2 self.assertEqual(h(7), 9) def testDeviceMemoryProfile(self): x = jnp.ones((20,)) + 7. self.assertIsInstance(jax.profiler.device_memory_profile(), bytes) del x if __name__ == "__main__": absltest.main(testLoader=jtu.JaxTestLoader())
26.722222
77
0.723493
from functools import partial import unittest from absl.testing import absltest import jax import jax.numpy as jnp import jax.profiler from jax.config import config import jax.test_util as jtu try: import portpicker except ImportError: portpicker = None config.parse_flags_with_absl() class ProfilerTest(unittest.TestCase): @unittest.skipIf(not portpicker, "Test requires portpicker") def testStartServer(self): port = portpicker.pick_unused_port() jax.profiler.start_server(port=port) del port def testTraceContext(self): x = 3 with jax.profiler.TraceContext("mycontext"): x = x + 2 def testTraceFunction(self): @jax.profiler.trace_function def f(x): return x + 2 self.assertEqual(f(7), 9) @partial(jax.profiler.trace_function, name="aname") def g(x): return x + 2 self.assertEqual(g(7), 9) @partial(jax.profiler.trace_function, name="aname", akwarg="hello") def h(x): return x + 2 self.assertEqual(h(7), 9) def testDeviceMemoryProfile(self): x = jnp.ones((20,)) + 7. self.assertIsInstance(jax.profiler.device_memory_profile(), bytes) del x if __name__ == "__main__": absltest.main(testLoader=jtu.JaxTestLoader())
true
true
1c2c0a3497a3a7dcde3159a8843df11d37a8f392
1,381
py
Python
rplugin/python3/defx/column/size.py
sahwar/defx.nvim
bdd4896617f91800932ba2aaa4b2d019ae75ef1c
[ "MIT" ]
1
2019-04-14T20:18:26.000Z
2019-04-14T20:18:26.000Z
rplugin/python3/defx/column/size.py
sahwar/defx.nvim
bdd4896617f91800932ba2aaa4b2d019ae75ef1c
[ "MIT" ]
null
null
null
rplugin/python3/defx/column/size.py
sahwar/defx.nvim
bdd4896617f91800932ba2aaa4b2d019ae75ef1c
[ "MIT" ]
null
null
null
# ============================================================================ # FILE: size.py # AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com> # License: MIT license # ============================================================================ from defx.base.column import Base from defx.context import Context from defx.util import Nvim, readable import typing class Column(Base): def __init__(self, vim: Nvim) -> None: super().__init__(vim) self.name = 'size' def get(self, context: Context, candidate: typing.Dict[str, typing.Any]) -> str: path = candidate['action__path'] if not readable(path) or path.is_dir(): return ' ' * 8 size = self._get_size(path.stat().st_size) return '{:>5s}{:>3s}'.format(size[0], size[1]) def _get_size(self, size: float) -> typing.Tuple[str, str]: multiple = 1024 suffixes = ['KB', 'MB', 'GB', 'TB'] if size < multiple: return (str(size), 'B') for suffix in suffixes: size /= multiple if size < multiple: return ('{:.1f}'.format(size), suffix) return ('INF', '') def length(self, context: Context) -> int: return 8 def highlight(self) -> None: self.vim.command( f'highlight default link {self.syntax_name} Constant')
30.021739
78
0.5105
from defx.base.column import Base from defx.context import Context from defx.util import Nvim, readable import typing class Column(Base): def __init__(self, vim: Nvim) -> None: super().__init__(vim) self.name = 'size' def get(self, context: Context, candidate: typing.Dict[str, typing.Any]) -> str: path = candidate['action__path'] if not readable(path) or path.is_dir(): return ' ' * 8 size = self._get_size(path.stat().st_size) return '{:>5s}{:>3s}'.format(size[0], size[1]) def _get_size(self, size: float) -> typing.Tuple[str, str]: multiple = 1024 suffixes = ['KB', 'MB', 'GB', 'TB'] if size < multiple: return (str(size), 'B') for suffix in suffixes: size /= multiple if size < multiple: return ('{:.1f}'.format(size), suffix) return ('INF', '') def length(self, context: Context) -> int: return 8 def highlight(self) -> None: self.vim.command( f'highlight default link {self.syntax_name} Constant')
true
true
1c2c0c1f0313760161119e12ed53273a0b730353
7,463
py
Python
turtlefy/resources.py
nprutan/turtlefy
45ff9b592047607d04142f34fe30d0987c5052c5
[ "MIT" ]
1
2022-03-27T03:44:10.000Z
2022-03-27T03:44:10.000Z
turtlefy/resources.py
nprutan/turtlefy
45ff9b592047607d04142f34fe30d0987c5052c5
[ "MIT" ]
null
null
null
turtlefy/resources.py
nprutan/turtlefy
45ff9b592047607d04142f34fe30d0987c5052c5
[ "MIT" ]
null
null
null
def extract_tags(tags): return [tag.strip().lower() for tag in tags.split(',')] def append_tags(tags, new_tag): if tags: split_tags = tags.split(',') split_tags.append(f' {new_tag}') return ','.join(split_tags) return new_tag def tag_resource(client, resource, new_tag, resource_type=None): resource_id = int(resource['id']) updated_tags = append_tags(resource['tags'], new_tag) tag_data = { resource_type: { "id": resource_id, "tags": updated_tags } } url = f'{client.api_path}/{resource_type}s/{resource_id}.json' return client.put(url, json=tag_data).json()[resource_type] def get_customer_by_id(client, customer_id): return client.get(f'{client.api_path}/customers/{customer_id}.json').json()['customer'] def get_order_by_id(client, order_id): return client.get(f'{client.api_path}/orders/{order_id}.json').json()['order'] def get_token_access_status(client): return client.get(f'{client.base_uri}/admin/oauth/access_scopes.json').status_code def get_webhooks(client): return client.get(f'{client.api_path}/webhooks.json').json()['webhooks'] def update_webhooks_url(client, hooks, new_url): results = [] for hook in hooks: url = f'{client.api_path}/webhooks/{hook["id"]}.json' payload = { "webhook": { "id": hook['id'], "address": new_url } } results.append(client.put(url, json=payload).json()) return results def get_transactions(client, order_number): uri = f'{client.api_path}/orders/{order_number}/transactions.json' return client.get(uri).json()['transactions'] def get_fulfillment_orders(client, order_number): uri = f'{client.api_path}/orders/{order_number}/fulfillment_orders.json' return client.get(uri).json()['fulfillment_orders'] def get_fulfillments(client, order_number): uri = f'{client.api_path}/orders/{order_number}/fulfillments.json' return client.get(uri).json()['fulfillments'] def create_tracking_options(fulfillment_id, tracking_number, company=None, message=None, url=None, notify=False): return { "fulfillment": { "message": message, "notify_customer": notify, "tracking_info": { "number": tracking_number, "company": company, "url": url }, "line_items_by_fulfillment_order": [ { "fulfillment_order_id": fulfillment_id } ] } } def create_fulfillment_with_tracking(client, options): uri = f'{client.api_path}/fulfillments.json' return client.post(uri, json=options).json() def _generate_refund_line_items(fulfillments, restock_type): return [ { 'line_item_id': line['line_item_id'], 'quantity': line['quantity'], 'restock_type': restock_type, 'location_id': fulfillment['assigned_location_id'] } for fulfillment in fulfillments for line in fulfillment['line_items'] ] def _generate_refund_transactions(transactions): return [ { 'parent_id': tx['parent_id'], 'amount': tx['amount'], 'kind': 'refund', 'gateway': tx['gateway'] } for tx in transactions if tx['parent_id'] ] def create_refund(transactions, fulfillments, restock_type='cancel'): return { "refund": { "note": "FraudHooks Cancellation", "shipping": { "full_refund": True }, "refund_line_items": _generate_refund_line_items(fulfillments, restock_type), "transactions": _generate_refund_transactions(transactions) } } def get_order_risks(client, order_number): uri = f'{client.api_path}/orders/{order_number}/risks.json' return client.get(uri).json()['risks'] _cancellation_settings = { 'cancel': {'cause_cancel': True, 'score': 1.0}, 'investigate': {'cause_cancel': False, 'score': 0.5}, 'accept': {'cause_cancel': False, 'score': 0.0} } def _generate_risk_body(recommendation, message): settings = _cancellation_settings.get(recommendation) if not message: message = 'Order determined to be high risk' return { 'risk': { 'cause_cancel': settings['cause_cancel'], 'message': message, 'recommendation': recommendation, 'display': True, 'source': 'External', 'score': settings['score'] } } def create_order_risk(client, previous_risk, recommendation=None, message=None): if not recommendation: recommendation = 'cancel' new_risk = _generate_risk_body(recommendation, message) return client.post(f'{client.api_path}/orders/{previous_risk["order_id"]}/risks.json', json=new_risk) def create_cancel_options(options): refund = {} if options['refund']: restock_type = 'no_restock' if not options['restock'] else 'cancel' refund = create_refund(options['transactions'], options['fulfillments'], restock_type=restock_type) return { **refund, 'email': options['notify_customer'], 'reason': 'fraud' } def cancel_order(client, order_number, options=None): uri = f'{client.api_path}/orders/{order_number}/cancel.json' return client.post(uri, json=options).json() def get_fulfillment_orders(client, order_number): uri = f'{client.api_path}/orders/{order_number}/fulfillment_orders.json' return client.get(uri).json()['fulfillment_orders'] def get_fulfillment_order_id(fulfillment_orders, status=None): if not status: status = 'open' for fulfillment in fulfillment_orders: if fulfillment['status'] == status: return fulfillment['id'] def move_fulfillment_location(client, fulfillment_id, location_id): uri = f'{client.api_path}/fulfillment_orders/{fulfillment_id}/move.json' payload = { "fulfillment_order": { "new_location_id": location_id } } return client.post(uri, json=payload) def get_shopify_page_link(response): link = response.headers.get('link') if link: for uri in link.split(','): if 'next' in uri: split = uri.split(';')[0][1:-1] if '<' not in split: return split return uri.split(';')[0][2:-1] def get_all_resources(client, initial_uri, resources=None, resource_type=None): if not resources: resources = [] response = client.get(initial_uri) resources.extend(response.json()[resource_type]) page_link = get_shopify_page_link(response) if page_link: get_all_resources(client, page_link, resources, resource_type) return resources def get_all_resources_iter(client, initial_uri, resource_type=None): response = client.get(initial_uri) yield response.json()[resource_type] page_link = get_shopify_page_link(response) if page_link: yield from get_all_resources_iter(client, page_link, resource_type) def execute_gql_query(client, query): client.update_gql_headers() return client.post(f'{client.gql_endpoint}', data=query)
30.711934
107
0.627228
def extract_tags(tags): return [tag.strip().lower() for tag in tags.split(',')] def append_tags(tags, new_tag): if tags: split_tags = tags.split(',') split_tags.append(f' {new_tag}') return ','.join(split_tags) return new_tag def tag_resource(client, resource, new_tag, resource_type=None): resource_id = int(resource['id']) updated_tags = append_tags(resource['tags'], new_tag) tag_data = { resource_type: { "id": resource_id, "tags": updated_tags } } url = f'{client.api_path}/{resource_type}s/{resource_id}.json' return client.put(url, json=tag_data).json()[resource_type] def get_customer_by_id(client, customer_id): return client.get(f'{client.api_path}/customers/{customer_id}.json').json()['customer'] def get_order_by_id(client, order_id): return client.get(f'{client.api_path}/orders/{order_id}.json').json()['order'] def get_token_access_status(client): return client.get(f'{client.base_uri}/admin/oauth/access_scopes.json').status_code def get_webhooks(client): return client.get(f'{client.api_path}/webhooks.json').json()['webhooks'] def update_webhooks_url(client, hooks, new_url): results = [] for hook in hooks: url = f'{client.api_path}/webhooks/{hook["id"]}.json' payload = { "webhook": { "id": hook['id'], "address": new_url } } results.append(client.put(url, json=payload).json()) return results def get_transactions(client, order_number): uri = f'{client.api_path}/orders/{order_number}/transactions.json' return client.get(uri).json()['transactions'] def get_fulfillment_orders(client, order_number): uri = f'{client.api_path}/orders/{order_number}/fulfillment_orders.json' return client.get(uri).json()['fulfillment_orders'] def get_fulfillments(client, order_number): uri = f'{client.api_path}/orders/{order_number}/fulfillments.json' return client.get(uri).json()['fulfillments'] def create_tracking_options(fulfillment_id, tracking_number, company=None, message=None, url=None, notify=False): return { "fulfillment": { "message": message, "notify_customer": notify, "tracking_info": { "number": tracking_number, "company": company, "url": url }, "line_items_by_fulfillment_order": [ { "fulfillment_order_id": fulfillment_id } ] } } def create_fulfillment_with_tracking(client, options): uri = f'{client.api_path}/fulfillments.json' return client.post(uri, json=options).json() def _generate_refund_line_items(fulfillments, restock_type): return [ { 'line_item_id': line['line_item_id'], 'quantity': line['quantity'], 'restock_type': restock_type, 'location_id': fulfillment['assigned_location_id'] } for fulfillment in fulfillments for line in fulfillment['line_items'] ] def _generate_refund_transactions(transactions): return [ { 'parent_id': tx['parent_id'], 'amount': tx['amount'], 'kind': 'refund', 'gateway': tx['gateway'] } for tx in transactions if tx['parent_id'] ] def create_refund(transactions, fulfillments, restock_type='cancel'): return { "refund": { "note": "FraudHooks Cancellation", "shipping": { "full_refund": True }, "refund_line_items": _generate_refund_line_items(fulfillments, restock_type), "transactions": _generate_refund_transactions(transactions) } } def get_order_risks(client, order_number): uri = f'{client.api_path}/orders/{order_number}/risks.json' return client.get(uri).json()['risks'] _cancellation_settings = { 'cancel': {'cause_cancel': True, 'score': 1.0}, 'investigate': {'cause_cancel': False, 'score': 0.5}, 'accept': {'cause_cancel': False, 'score': 0.0} } def _generate_risk_body(recommendation, message): settings = _cancellation_settings.get(recommendation) if not message: message = 'Order determined to be high risk' return { 'risk': { 'cause_cancel': settings['cause_cancel'], 'message': message, 'recommendation': recommendation, 'display': True, 'source': 'External', 'score': settings['score'] } } def create_order_risk(client, previous_risk, recommendation=None, message=None): if not recommendation: recommendation = 'cancel' new_risk = _generate_risk_body(recommendation, message) return client.post(f'{client.api_path}/orders/{previous_risk["order_id"]}/risks.json', json=new_risk) def create_cancel_options(options): refund = {} if options['refund']: restock_type = 'no_restock' if not options['restock'] else 'cancel' refund = create_refund(options['transactions'], options['fulfillments'], restock_type=restock_type) return { **refund, 'email': options['notify_customer'], 'reason': 'fraud' } def cancel_order(client, order_number, options=None): uri = f'{client.api_path}/orders/{order_number}/cancel.json' return client.post(uri, json=options).json() def get_fulfillment_orders(client, order_number): uri = f'{client.api_path}/orders/{order_number}/fulfillment_orders.json' return client.get(uri).json()['fulfillment_orders'] def get_fulfillment_order_id(fulfillment_orders, status=None): if not status: status = 'open' for fulfillment in fulfillment_orders: if fulfillment['status'] == status: return fulfillment['id'] def move_fulfillment_location(client, fulfillment_id, location_id): uri = f'{client.api_path}/fulfillment_orders/{fulfillment_id}/move.json' payload = { "fulfillment_order": { "new_location_id": location_id } } return client.post(uri, json=payload) def get_shopify_page_link(response): link = response.headers.get('link') if link: for uri in link.split(','): if 'next' in uri: split = uri.split(';')[0][1:-1] if '<' not in split: return split return uri.split(';')[0][2:-1] def get_all_resources(client, initial_uri, resources=None, resource_type=None): if not resources: resources = [] response = client.get(initial_uri) resources.extend(response.json()[resource_type]) page_link = get_shopify_page_link(response) if page_link: get_all_resources(client, page_link, resources, resource_type) return resources def get_all_resources_iter(client, initial_uri, resource_type=None): response = client.get(initial_uri) yield response.json()[resource_type] page_link = get_shopify_page_link(response) if page_link: yield from get_all_resources_iter(client, page_link, resource_type) def execute_gql_query(client, query): client.update_gql_headers() return client.post(f'{client.gql_endpoint}', data=query)
true
true
1c2c0c2698e23924b849d04cd00c551d44130204
31,748
py
Python
Lib/test/test_warnings.py
akruis/stackless_historic
f8af5dd49558f0ef046cf99dc5d34db2b9a90ce2
[ "PSF-2.0" ]
1
2019-05-14T05:05:42.000Z
2019-05-14T05:05:42.000Z
Lib/test/test_warnings.py
akruis/stackless_historic
f8af5dd49558f0ef046cf99dc5d34db2b9a90ce2
[ "PSF-2.0" ]
null
null
null
Lib/test/test_warnings.py
akruis/stackless_historic
f8af5dd49558f0ef046cf99dc5d34db2b9a90ce2
[ "PSF-2.0" ]
2
2018-07-15T06:35:21.000Z
2019-05-14T05:05:31.000Z
from contextlib import contextmanager import linecache import os import StringIO import sys import unittest import subprocess from test import test_support from test.script_helper import assert_python_ok import warning_tests import warnings as original_warnings py_warnings = test_support.import_fresh_module('warnings', blocked=['_warnings']) c_warnings = test_support.import_fresh_module('warnings', fresh=['_warnings']) @contextmanager def warnings_state(module): """Use a specific warnings implementation in warning_tests.""" global __warningregistry__ for to_clear in (sys, warning_tests): try: to_clear.__warningregistry__.clear() except AttributeError: pass try: __warningregistry__.clear() except NameError: pass original_warnings = warning_tests.warnings original_filters = module.filters try: module.filters = original_filters[:] module.simplefilter("once") warning_tests.warnings = module yield finally: warning_tests.warnings = original_warnings module.filters = original_filters class BaseTest(unittest.TestCase): """Basic bookkeeping required for testing.""" def setUp(self): # The __warningregistry__ needs to be in a pristine state for tests # to work properly. if '__warningregistry__' in globals(): del globals()['__warningregistry__'] if hasattr(warning_tests, '__warningregistry__'): del warning_tests.__warningregistry__ if hasattr(sys, '__warningregistry__'): del sys.__warningregistry__ # The 'warnings' module must be explicitly set so that the proper # interaction between _warnings and 'warnings' can be controlled. sys.modules['warnings'] = self.module super(BaseTest, self).setUp() def tearDown(self): sys.modules['warnings'] = original_warnings super(BaseTest, self).tearDown() class FilterTests(object): """Testing the filtering functionality.""" def test_error(self): with original_warnings.catch_warnings(module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("error", category=UserWarning) self.assertRaises(UserWarning, self.module.warn, "FilterTests.test_error") def test_ignore(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("ignore", category=UserWarning) self.module.warn("FilterTests.test_ignore", UserWarning) self.assertEqual(len(w), 0) def test_always(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("always", category=UserWarning) message = "FilterTests.test_always" self.module.warn(message, UserWarning) self.assertTrue(message, w[-1].message) self.module.warn(message, UserWarning) self.assertTrue(w[-1].message, message) def test_default(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("default", category=UserWarning) message = UserWarning("FilterTests.test_default") for x in xrange(2): self.module.warn(message, UserWarning) if x == 0: self.assertEqual(w[-1].message, message) del w[:] elif x == 1: self.assertEqual(len(w), 0) else: raise ValueError("loop variant unhandled") def test_module(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("module", category=UserWarning) message = UserWarning("FilterTests.test_module") self.module.warn(message, UserWarning) self.assertEqual(w[-1].message, message) del w[:] self.module.warn(message, UserWarning) self.assertEqual(len(w), 0) def test_once(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("once", category=UserWarning) message = UserWarning("FilterTests.test_once") self.module.warn_explicit(message, UserWarning, "test_warnings.py", 42) self.assertEqual(w[-1].message, message) del w[:] self.module.warn_explicit(message, UserWarning, "test_warnings.py", 13) self.assertEqual(len(w), 0) self.module.warn_explicit(message, UserWarning, "test_warnings2.py", 42) self.assertEqual(len(w), 0) def test_inheritance(self): with original_warnings.catch_warnings(module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("error", category=Warning) self.assertRaises(UserWarning, self.module.warn, "FilterTests.test_inheritance", UserWarning) def test_ordering(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("ignore", category=UserWarning) self.module.filterwarnings("error", category=UserWarning, append=True) del w[:] try: self.module.warn("FilterTests.test_ordering", UserWarning) except UserWarning: self.fail("order handling for actions failed") self.assertEqual(len(w), 0) def test_filterwarnings(self): # Test filterwarnings(). # Implicitly also tests resetwarnings(). with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.filterwarnings("error", "", Warning, "", 0) self.assertRaises(UserWarning, self.module.warn, 'convert to error') self.module.resetwarnings() text = 'handle normally' self.module.warn(text) self.assertEqual(str(w[-1].message), text) self.assertTrue(w[-1].category is UserWarning) self.module.filterwarnings("ignore", "", Warning, "", 0) text = 'filtered out' self.module.warn(text) self.assertNotEqual(str(w[-1].message), text) self.module.resetwarnings() self.module.filterwarnings("error", "hex*", Warning, "", 0) self.assertRaises(UserWarning, self.module.warn, 'hex/oct') text = 'nonmatching text' self.module.warn(text) self.assertEqual(str(w[-1].message), text) self.assertTrue(w[-1].category is UserWarning) class CFilterTests(BaseTest, FilterTests): module = c_warnings class PyFilterTests(BaseTest, FilterTests): module = py_warnings class WarnTests(unittest.TestCase): """Test warnings.warn() and warnings.warn_explicit().""" def test_message(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.simplefilter("once") for i in range(4): text = 'multi %d' %i # Different text on each call. self.module.warn(text) self.assertEqual(str(w[-1].message), text) self.assertTrue(w[-1].category is UserWarning) def test_filename(self): with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner("spam1") self.assertEqual(os.path.basename(w[-1].filename), "warning_tests.py") warning_tests.outer("spam2") self.assertEqual(os.path.basename(w[-1].filename), "warning_tests.py") def test_stacklevel(self): # Test stacklevel argument # make sure all messages are different, so the warning won't be skipped with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner("spam3", stacklevel=1) self.assertEqual(os.path.basename(w[-1].filename), "warning_tests.py") warning_tests.outer("spam4", stacklevel=1) self.assertEqual(os.path.basename(w[-1].filename), "warning_tests.py") warning_tests.inner("spam5", stacklevel=2) self.assertEqual(os.path.basename(w[-1].filename), "test_warnings.py") warning_tests.outer("spam6", stacklevel=2) self.assertEqual(os.path.basename(w[-1].filename), "warning_tests.py") warning_tests.outer("spam6.5", stacklevel=3) self.assertEqual(os.path.basename(w[-1].filename), "test_warnings.py") warning_tests.inner("spam7", stacklevel=9999) self.assertEqual(os.path.basename(w[-1].filename), "sys") def test_missing_filename_not_main(self): # If __file__ is not specified and __main__ is not the module name, # then __file__ should be set to the module name. filename = warning_tests.__file__ try: del warning_tests.__file__ with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner("spam8", stacklevel=1) self.assertEqual(w[-1].filename, warning_tests.__name__) finally: warning_tests.__file__ = filename def test_missing_filename_main_with_argv(self): # If __file__ is not specified and the caller is __main__ and sys.argv # exists, then use sys.argv[0] as the file. if not hasattr(sys, 'argv'): return filename = warning_tests.__file__ module_name = warning_tests.__name__ try: del warning_tests.__file__ warning_tests.__name__ = '__main__' with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner('spam9', stacklevel=1) self.assertEqual(w[-1].filename, sys.argv[0]) finally: warning_tests.__file__ = filename warning_tests.__name__ = module_name def test_missing_filename_main_without_argv(self): # If __file__ is not specified, the caller is __main__, and sys.argv # is not set, then '__main__' is the file name. filename = warning_tests.__file__ module_name = warning_tests.__name__ argv = sys.argv try: del warning_tests.__file__ warning_tests.__name__ = '__main__' del sys.argv with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner('spam10', stacklevel=1) self.assertEqual(w[-1].filename, '__main__') finally: warning_tests.__file__ = filename warning_tests.__name__ = module_name sys.argv = argv def test_missing_filename_main_with_argv_empty_string(self): # If __file__ is not specified, the caller is __main__, and sys.argv[0] # is the empty string, then '__main__ is the file name. # Tests issue 2743. file_name = warning_tests.__file__ module_name = warning_tests.__name__ argv = sys.argv try: del warning_tests.__file__ warning_tests.__name__ = '__main__' sys.argv = [''] with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner('spam11', stacklevel=1) self.assertEqual(w[-1].filename, '__main__') finally: warning_tests.__file__ = file_name warning_tests.__name__ = module_name sys.argv = argv def test_warn_explicit_type_errors(self): # warn_explicit() shoud error out gracefully if it is given objects # of the wrong types. # lineno is expected to be an integer. self.assertRaises(TypeError, self.module.warn_explicit, None, UserWarning, None, None) # Either 'message' needs to be an instance of Warning or 'category' # needs to be a subclass. self.assertRaises(TypeError, self.module.warn_explicit, None, None, None, 1) # 'registry' must be a dict or None. self.assertRaises((TypeError, AttributeError), self.module.warn_explicit, None, Warning, None, 1, registry=42) def test_bad_str(self): # issue 6415 # Warnings instance with a bad format string for __str__ should not # trigger a bus error. class BadStrWarning(Warning): """Warning with a bad format string for __str__.""" def __str__(self): return ("A bad formatted string %(err)" % {"err" : "there is no %(err)s"}) with self.assertRaises(ValueError): self.module.warn(BadStrWarning()) class CWarnTests(BaseTest, WarnTests): module = c_warnings # As an early adopter, we sanity check the # test_support.import_fresh_module utility function def test_accelerated(self): self.assertFalse(original_warnings is self.module) self.assertFalse(hasattr(self.module.warn, 'func_code')) class PyWarnTests(BaseTest, WarnTests): module = py_warnings # As an early adopter, we sanity check the # test_support.import_fresh_module utility function def test_pure_python(self): self.assertFalse(original_warnings is self.module) self.assertTrue(hasattr(self.module.warn, 'func_code')) class WCmdLineTests(unittest.TestCase): def test_improper_input(self): # Uses the private _setoption() function to test the parsing # of command-line warning arguments with original_warnings.catch_warnings(module=self.module): self.assertRaises(self.module._OptionError, self.module._setoption, '1:2:3:4:5:6') self.assertRaises(self.module._OptionError, self.module._setoption, 'bogus::Warning') self.assertRaises(self.module._OptionError, self.module._setoption, 'ignore:2::4:-5') self.module._setoption('error::Warning::0') self.assertRaises(UserWarning, self.module.warn, 'convert to error') def test_improper_option(self): # Same as above, but check that the message is printed out when # the interpreter is executed. This also checks that options are # actually parsed at all. rc, out, err = assert_python_ok("-Wxxx", "-c", "pass") self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err) def test_warnings_bootstrap(self): # Check that the warnings module does get loaded when -W<some option> # is used (see issue #10372 for an example of silent bootstrap failure). rc, out, err = assert_python_ok("-Wi", "-c", "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)") # '-Wi' was observed self.assertFalse(out.strip()) self.assertNotIn(b'RuntimeWarning', err) class CWCmdLineTests(BaseTest, WCmdLineTests): module = c_warnings class PyWCmdLineTests(BaseTest, WCmdLineTests): module = py_warnings class _WarningsTests(BaseTest): """Tests specific to the _warnings module.""" module = c_warnings def test_filter(self): # Everything should function even if 'filters' is not in warnings. with original_warnings.catch_warnings(module=self.module) as w: self.module.filterwarnings("error", "", Warning, "", 0) self.assertRaises(UserWarning, self.module.warn, 'convert to error') del self.module.filters self.assertRaises(UserWarning, self.module.warn, 'convert to error') def test_onceregistry(self): # Replacing or removing the onceregistry should be okay. global __warningregistry__ message = UserWarning('onceregistry test') try: original_registry = self.module.onceregistry __warningregistry__ = {} with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("once", category=UserWarning) self.module.warn_explicit(message, UserWarning, "file", 42) self.assertEqual(w[-1].message, message) del w[:] self.module.warn_explicit(message, UserWarning, "file", 42) self.assertEqual(len(w), 0) # Test the resetting of onceregistry. self.module.onceregistry = {} __warningregistry__ = {} self.module.warn('onceregistry test') self.assertEqual(w[-1].message.args, message.args) # Removal of onceregistry is okay. del w[:] del self.module.onceregistry __warningregistry__ = {} self.module.warn_explicit(message, UserWarning, "file", 42) self.assertEqual(len(w), 0) finally: self.module.onceregistry = original_registry def test_default_action(self): # Replacing or removing defaultaction should be okay. message = UserWarning("defaultaction test") original = self.module.defaultaction try: with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() registry = {} self.module.warn_explicit(message, UserWarning, "<test>", 42, registry=registry) self.assertEqual(w[-1].message, message) self.assertEqual(len(w), 1) self.assertEqual(len(registry), 1) del w[:] # Test removal. del self.module.defaultaction __warningregistry__ = {} registry = {} self.module.warn_explicit(message, UserWarning, "<test>", 43, registry=registry) self.assertEqual(w[-1].message, message) self.assertEqual(len(w), 1) self.assertEqual(len(registry), 1) del w[:] # Test setting. self.module.defaultaction = "ignore" __warningregistry__ = {} registry = {} self.module.warn_explicit(message, UserWarning, "<test>", 44, registry=registry) self.assertEqual(len(w), 0) finally: self.module.defaultaction = original def test_showwarning_missing(self): # Test that showwarning() missing is okay. text = 'del showwarning test' with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) del self.module.showwarning with test_support.captured_output('stderr') as stream: self.module.warn(text) result = stream.getvalue() self.assertIn(text, result) def test_showwarning_not_callable(self): with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) old_showwarning = self.module.showwarning self.module.showwarning = 23 try: self.assertRaises(TypeError, self.module.warn, "Warning!") finally: self.module.showwarning = old_showwarning def test_show_warning_output(self): # With showarning() missing, make sure that output is okay. text = 'test show_warning' with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) del self.module.showwarning with test_support.captured_output('stderr') as stream: warning_tests.inner(text) result = stream.getvalue() self.assertEqual(result.count('\n'), 2, "Too many newlines in %r" % result) first_line, second_line = result.split('\n', 1) expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py' first_line_parts = first_line.rsplit(':', 3) path, line, warning_class, message = first_line_parts line = int(line) self.assertEqual(expected_file, path) self.assertEqual(warning_class, ' ' + UserWarning.__name__) self.assertEqual(message, ' ' + text) expected_line = ' ' + linecache.getline(path, line).strip() + '\n' assert expected_line self.assertEqual(second_line, expected_line) class WarningsDisplayTests(unittest.TestCase): """Test the displaying of warnings and the ability to overload functions related to displaying warnings.""" def test_formatwarning(self): message = "msg" category = Warning file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' line_num = 3 file_line = linecache.getline(file_name, line_num).strip() format = "%s:%s: %s: %s\n %s\n" expect = format % (file_name, line_num, category.__name__, message, file_line) self.assertEqual(expect, self.module.formatwarning(message, category, file_name, line_num)) # Test the 'line' argument. file_line += " for the win!" expect = format % (file_name, line_num, category.__name__, message, file_line) self.assertEqual(expect, self.module.formatwarning(message, category, file_name, line_num, file_line)) def test_showwarning(self): file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' line_num = 3 expected_file_line = linecache.getline(file_name, line_num).strip() message = 'msg' category = Warning file_object = StringIO.StringIO() expect = self.module.formatwarning(message, category, file_name, line_num) self.module.showwarning(message, category, file_name, line_num, file_object) self.assertEqual(file_object.getvalue(), expect) # Test 'line' argument. expected_file_line += "for the win!" expect = self.module.formatwarning(message, category, file_name, line_num, expected_file_line) file_object = StringIO.StringIO() self.module.showwarning(message, category, file_name, line_num, file_object, expected_file_line) self.assertEqual(expect, file_object.getvalue()) class CWarningsDisplayTests(BaseTest, WarningsDisplayTests): module = c_warnings class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests): module = py_warnings class CatchWarningTests(BaseTest): """Test catch_warnings().""" def test_catch_warnings_restore(self): wmod = self.module orig_filters = wmod.filters orig_showwarning = wmod.showwarning # Ensure both showwarning and filters are restored when recording with wmod.catch_warnings(module=wmod, record=True): wmod.filters = wmod.showwarning = object() self.assertTrue(wmod.filters is orig_filters) self.assertTrue(wmod.showwarning is orig_showwarning) # Same test, but with recording disabled with wmod.catch_warnings(module=wmod, record=False): wmod.filters = wmod.showwarning = object() self.assertTrue(wmod.filters is orig_filters) self.assertTrue(wmod.showwarning is orig_showwarning) def test_catch_warnings_recording(self): wmod = self.module # Ensure warnings are recorded when requested with wmod.catch_warnings(module=wmod, record=True) as w: self.assertEqual(w, []) self.assertTrue(type(w) is list) wmod.simplefilter("always") wmod.warn("foo") self.assertEqual(str(w[-1].message), "foo") wmod.warn("bar") self.assertEqual(str(w[-1].message), "bar") self.assertEqual(str(w[0].message), "foo") self.assertEqual(str(w[1].message), "bar") del w[:] self.assertEqual(w, []) # Ensure warnings are not recorded when not requested orig_showwarning = wmod.showwarning with wmod.catch_warnings(module=wmod, record=False) as w: self.assertTrue(w is None) self.assertTrue(wmod.showwarning is orig_showwarning) def test_catch_warnings_reentry_guard(self): wmod = self.module # Ensure catch_warnings is protected against incorrect usage x = wmod.catch_warnings(module=wmod, record=True) self.assertRaises(RuntimeError, x.__exit__) with x: self.assertRaises(RuntimeError, x.__enter__) # Same test, but with recording disabled x = wmod.catch_warnings(module=wmod, record=False) self.assertRaises(RuntimeError, x.__exit__) with x: self.assertRaises(RuntimeError, x.__enter__) def test_catch_warnings_defaults(self): wmod = self.module orig_filters = wmod.filters orig_showwarning = wmod.showwarning # Ensure default behaviour is not to record warnings with wmod.catch_warnings(module=wmod) as w: self.assertTrue(w is None) self.assertTrue(wmod.showwarning is orig_showwarning) self.assertTrue(wmod.filters is not orig_filters) self.assertTrue(wmod.filters is orig_filters) if wmod is sys.modules['warnings']: # Ensure the default module is this one with wmod.catch_warnings() as w: self.assertTrue(w is None) self.assertTrue(wmod.showwarning is orig_showwarning) self.assertTrue(wmod.filters is not orig_filters) self.assertTrue(wmod.filters is orig_filters) def test_check_warnings(self): # Explicit tests for the test_support convenience wrapper wmod = self.module if wmod is not sys.modules['warnings']: return with test_support.check_warnings(quiet=False) as w: self.assertEqual(w.warnings, []) wmod.simplefilter("always") wmod.warn("foo") self.assertEqual(str(w.message), "foo") wmod.warn("bar") self.assertEqual(str(w.message), "bar") self.assertEqual(str(w.warnings[0].message), "foo") self.assertEqual(str(w.warnings[1].message), "bar") w.reset() self.assertEqual(w.warnings, []) with test_support.check_warnings(): # defaults to quiet=True without argument pass with test_support.check_warnings(('foo', UserWarning)): wmod.warn("foo") with self.assertRaises(AssertionError): with test_support.check_warnings(('', RuntimeWarning)): # defaults to quiet=False with argument pass with self.assertRaises(AssertionError): with test_support.check_warnings(('foo', RuntimeWarning)): wmod.warn("foo") class CCatchWarningTests(CatchWarningTests): module = c_warnings class PyCatchWarningTests(CatchWarningTests): module = py_warnings class EnvironmentVariableTests(BaseTest): def test_single_warning(self): newenv = os.environ.copy() newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning" p = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']") self.assertEqual(p.wait(), 0) def test_comma_separated_warnings(self): newenv = os.environ.copy() newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning," "ignore::UnicodeWarning") p = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']") self.assertEqual(p.wait(), 0) def test_envvar_and_command_line(self): newenv = os.environ.copy() newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning" p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning", "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.communicate()[0], "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']") self.assertEqual(p.wait(), 0) class CEnvironmentVariableTests(EnvironmentVariableTests): module = c_warnings class PyEnvironmentVariableTests(EnvironmentVariableTests): module = py_warnings def test_main(): py_warnings.onceregistry.clear() c_warnings.onceregistry.clear() test_support.run_unittest(CFilterTests, PyFilterTests, CWarnTests, PyWarnTests, CWCmdLineTests, PyWCmdLineTests, _WarningsTests, CWarningsDisplayTests, PyWarningsDisplayTests, CCatchWarningTests, PyCatchWarningTests, CEnvironmentVariableTests, PyEnvironmentVariableTests ) if __name__ == "__main__": test_main()
42.330667
81
0.602085
from contextlib import contextmanager import linecache import os import StringIO import sys import unittest import subprocess from test import test_support from test.script_helper import assert_python_ok import warning_tests import warnings as original_warnings py_warnings = test_support.import_fresh_module('warnings', blocked=['_warnings']) c_warnings = test_support.import_fresh_module('warnings', fresh=['_warnings']) @contextmanager def warnings_state(module): global __warningregistry__ for to_clear in (sys, warning_tests): try: to_clear.__warningregistry__.clear() except AttributeError: pass try: __warningregistry__.clear() except NameError: pass original_warnings = warning_tests.warnings original_filters = module.filters try: module.filters = original_filters[:] module.simplefilter("once") warning_tests.warnings = module yield finally: warning_tests.warnings = original_warnings module.filters = original_filters class BaseTest(unittest.TestCase): def setUp(self): if '__warningregistry__' in globals(): del globals()['__warningregistry__'] if hasattr(warning_tests, '__warningregistry__'): del warning_tests.__warningregistry__ if hasattr(sys, '__warningregistry__'): del sys.__warningregistry__ sys.modules['warnings'] = self.module super(BaseTest, self).setUp() def tearDown(self): sys.modules['warnings'] = original_warnings super(BaseTest, self).tearDown() class FilterTests(object): def test_error(self): with original_warnings.catch_warnings(module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("error", category=UserWarning) self.assertRaises(UserWarning, self.module.warn, "FilterTests.test_error") def test_ignore(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("ignore", category=UserWarning) self.module.warn("FilterTests.test_ignore", UserWarning) self.assertEqual(len(w), 0) def test_always(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("always", category=UserWarning) message = "FilterTests.test_always" self.module.warn(message, UserWarning) self.assertTrue(message, w[-1].message) self.module.warn(message, UserWarning) self.assertTrue(w[-1].message, message) def test_default(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("default", category=UserWarning) message = UserWarning("FilterTests.test_default") for x in xrange(2): self.module.warn(message, UserWarning) if x == 0: self.assertEqual(w[-1].message, message) del w[:] elif x == 1: self.assertEqual(len(w), 0) else: raise ValueError("loop variant unhandled") def test_module(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("module", category=UserWarning) message = UserWarning("FilterTests.test_module") self.module.warn(message, UserWarning) self.assertEqual(w[-1].message, message) del w[:] self.module.warn(message, UserWarning) self.assertEqual(len(w), 0) def test_once(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("once", category=UserWarning) message = UserWarning("FilterTests.test_once") self.module.warn_explicit(message, UserWarning, "test_warnings.py", 42) self.assertEqual(w[-1].message, message) del w[:] self.module.warn_explicit(message, UserWarning, "test_warnings.py", 13) self.assertEqual(len(w), 0) self.module.warn_explicit(message, UserWarning, "test_warnings2.py", 42) self.assertEqual(len(w), 0) def test_inheritance(self): with original_warnings.catch_warnings(module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("error", category=Warning) self.assertRaises(UserWarning, self.module.warn, "FilterTests.test_inheritance", UserWarning) def test_ordering(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("ignore", category=UserWarning) self.module.filterwarnings("error", category=UserWarning, append=True) del w[:] try: self.module.warn("FilterTests.test_ordering", UserWarning) except UserWarning: self.fail("order handling for actions failed") self.assertEqual(len(w), 0) def test_filterwarnings(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.filterwarnings("error", "", Warning, "", 0) self.assertRaises(UserWarning, self.module.warn, 'convert to error') self.module.resetwarnings() text = 'handle normally' self.module.warn(text) self.assertEqual(str(w[-1].message), text) self.assertTrue(w[-1].category is UserWarning) self.module.filterwarnings("ignore", "", Warning, "", 0) text = 'filtered out' self.module.warn(text) self.assertNotEqual(str(w[-1].message), text) self.module.resetwarnings() self.module.filterwarnings("error", "hex*", Warning, "", 0) self.assertRaises(UserWarning, self.module.warn, 'hex/oct') text = 'nonmatching text' self.module.warn(text) self.assertEqual(str(w[-1].message), text) self.assertTrue(w[-1].category is UserWarning) class CFilterTests(BaseTest, FilterTests): module = c_warnings class PyFilterTests(BaseTest, FilterTests): module = py_warnings class WarnTests(unittest.TestCase): def test_message(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.simplefilter("once") for i in range(4): text = 'multi %d' %i self.module.warn(text) self.assertEqual(str(w[-1].message), text) self.assertTrue(w[-1].category is UserWarning) def test_filename(self): with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner("spam1") self.assertEqual(os.path.basename(w[-1].filename), "warning_tests.py") warning_tests.outer("spam2") self.assertEqual(os.path.basename(w[-1].filename), "warning_tests.py") def test_stacklevel(self): with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner("spam3", stacklevel=1) self.assertEqual(os.path.basename(w[-1].filename), "warning_tests.py") warning_tests.outer("spam4", stacklevel=1) self.assertEqual(os.path.basename(w[-1].filename), "warning_tests.py") warning_tests.inner("spam5", stacklevel=2) self.assertEqual(os.path.basename(w[-1].filename), "test_warnings.py") warning_tests.outer("spam6", stacklevel=2) self.assertEqual(os.path.basename(w[-1].filename), "warning_tests.py") warning_tests.outer("spam6.5", stacklevel=3) self.assertEqual(os.path.basename(w[-1].filename), "test_warnings.py") warning_tests.inner("spam7", stacklevel=9999) self.assertEqual(os.path.basename(w[-1].filename), "sys") def test_missing_filename_not_main(self): # If __file__ is not specified and __main__ is not the module name, # then __file__ should be set to the module name. filename = warning_tests.__file__ try: del warning_tests.__file__ with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner("spam8", stacklevel=1) self.assertEqual(w[-1].filename, warning_tests.__name__) finally: warning_tests.__file__ = filename def test_missing_filename_main_with_argv(self): # If __file__ is not specified and the caller is __main__ and sys.argv # exists, then use sys.argv[0] as the file. if not hasattr(sys, 'argv'): return filename = warning_tests.__file__ module_name = warning_tests.__name__ try: del warning_tests.__file__ warning_tests.__name__ = '__main__' with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner('spam9', stacklevel=1) self.assertEqual(w[-1].filename, sys.argv[0]) finally: warning_tests.__file__ = filename warning_tests.__name__ = module_name def test_missing_filename_main_without_argv(self): # If __file__ is not specified, the caller is __main__, and sys.argv # is not set, then '__main__' is the file name. filename = warning_tests.__file__ module_name = warning_tests.__name__ argv = sys.argv try: del warning_tests.__file__ warning_tests.__name__ = '__main__' del sys.argv with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner('spam10', stacklevel=1) self.assertEqual(w[-1].filename, '__main__') finally: warning_tests.__file__ = filename warning_tests.__name__ = module_name sys.argv = argv def test_missing_filename_main_with_argv_empty_string(self): # If __file__ is not specified, the caller is __main__, and sys.argv[0] # is the empty string, then '__main__ is the file name. file_name = warning_tests.__file__ module_name = warning_tests.__name__ argv = sys.argv try: del warning_tests.__file__ warning_tests.__name__ = '__main__' sys.argv = [''] with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner('spam11', stacklevel=1) self.assertEqual(w[-1].filename, '__main__') finally: warning_tests.__file__ = file_name warning_tests.__name__ = module_name sys.argv = argv def test_warn_explicit_type_errors(self): self.assertRaises(TypeError, self.module.warn_explicit, None, UserWarning, None, None) self.assertRaises(TypeError, self.module.warn_explicit, None, None, None, 1) self.assertRaises((TypeError, AttributeError), self.module.warn_explicit, None, Warning, None, 1, registry=42) def test_bad_str(self): class BadStrWarning(Warning): def __str__(self): return ("A bad formatted string %(err)" % {"err" : "there is no %(err)s"}) with self.assertRaises(ValueError): self.module.warn(BadStrWarning()) class CWarnTests(BaseTest, WarnTests): module = c_warnings def test_accelerated(self): self.assertFalse(original_warnings is self.module) self.assertFalse(hasattr(self.module.warn, 'func_code')) class PyWarnTests(BaseTest, WarnTests): module = py_warnings def test_pure_python(self): self.assertFalse(original_warnings is self.module) self.assertTrue(hasattr(self.module.warn, 'func_code')) class WCmdLineTests(unittest.TestCase): def test_improper_input(self): with original_warnings.catch_warnings(module=self.module): self.assertRaises(self.module._OptionError, self.module._setoption, '1:2:3:4:5:6') self.assertRaises(self.module._OptionError, self.module._setoption, 'bogus::Warning') self.assertRaises(self.module._OptionError, self.module._setoption, 'ignore:2::4:-5') self.module._setoption('error::Warning::0') self.assertRaises(UserWarning, self.module.warn, 'convert to error') def test_improper_option(self): rc, out, err = assert_python_ok("-Wxxx", "-c", "pass") self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err) def test_warnings_bootstrap(self): ", "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)") self.assertFalse(out.strip()) self.assertNotIn(b'RuntimeWarning', err) class CWCmdLineTests(BaseTest, WCmdLineTests): module = c_warnings class PyWCmdLineTests(BaseTest, WCmdLineTests): module = py_warnings class _WarningsTests(BaseTest): module = c_warnings def test_filter(self): with original_warnings.catch_warnings(module=self.module) as w: self.module.filterwarnings("error", "", Warning, "", 0) self.assertRaises(UserWarning, self.module.warn, 'convert to error') del self.module.filters self.assertRaises(UserWarning, self.module.warn, 'convert to error') def test_onceregistry(self): global __warningregistry__ message = UserWarning('onceregistry test') try: original_registry = self.module.onceregistry __warningregistry__ = {} with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("once", category=UserWarning) self.module.warn_explicit(message, UserWarning, "file", 42) self.assertEqual(w[-1].message, message) del w[:] self.module.warn_explicit(message, UserWarning, "file", 42) self.assertEqual(len(w), 0) self.module.onceregistry = {} __warningregistry__ = {} self.module.warn('onceregistry test') self.assertEqual(w[-1].message.args, message.args) del w[:] del self.module.onceregistry __warningregistry__ = {} self.module.warn_explicit(message, UserWarning, "file", 42) self.assertEqual(len(w), 0) finally: self.module.onceregistry = original_registry def test_default_action(self): message = UserWarning("defaultaction test") original = self.module.defaultaction try: with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() registry = {} self.module.warn_explicit(message, UserWarning, "<test>", 42, registry=registry) self.assertEqual(w[-1].message, message) self.assertEqual(len(w), 1) self.assertEqual(len(registry), 1) del w[:] del self.module.defaultaction __warningregistry__ = {} registry = {} self.module.warn_explicit(message, UserWarning, "<test>", 43, registry=registry) self.assertEqual(w[-1].message, message) self.assertEqual(len(w), 1) self.assertEqual(len(registry), 1) del w[:] self.module.defaultaction = "ignore" __warningregistry__ = {} registry = {} self.module.warn_explicit(message, UserWarning, "<test>", 44, registry=registry) self.assertEqual(len(w), 0) finally: self.module.defaultaction = original def test_showwarning_missing(self): text = 'del showwarning test' with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) del self.module.showwarning with test_support.captured_output('stderr') as stream: self.module.warn(text) result = stream.getvalue() self.assertIn(text, result) def test_showwarning_not_callable(self): with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) old_showwarning = self.module.showwarning self.module.showwarning = 23 try: self.assertRaises(TypeError, self.module.warn, "Warning!") finally: self.module.showwarning = old_showwarning def test_show_warning_output(self): text = 'test show_warning' with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) del self.module.showwarning with test_support.captured_output('stderr') as stream: warning_tests.inner(text) result = stream.getvalue() self.assertEqual(result.count('\n'), 2, "Too many newlines in %r" % result) first_line, second_line = result.split('\n', 1) expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py' first_line_parts = first_line.rsplit(':', 3) path, line, warning_class, message = first_line_parts line = int(line) self.assertEqual(expected_file, path) self.assertEqual(warning_class, ' ' + UserWarning.__name__) self.assertEqual(message, ' ' + text) expected_line = ' ' + linecache.getline(path, line).strip() + '\n' assert expected_line self.assertEqual(second_line, expected_line) class WarningsDisplayTests(unittest.TestCase): def test_formatwarning(self): message = "msg" category = Warning file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' line_num = 3 file_line = linecache.getline(file_name, line_num).strip() format = "%s:%s: %s: %s\n %s\n" expect = format % (file_name, line_num, category.__name__, message, file_line) self.assertEqual(expect, self.module.formatwarning(message, category, file_name, line_num)) file_line += " for the win!" expect = format % (file_name, line_num, category.__name__, message, file_line) self.assertEqual(expect, self.module.formatwarning(message, category, file_name, line_num, file_line)) def test_showwarning(self): file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' line_num = 3 expected_file_line = linecache.getline(file_name, line_num).strip() message = 'msg' category = Warning file_object = StringIO.StringIO() expect = self.module.formatwarning(message, category, file_name, line_num) self.module.showwarning(message, category, file_name, line_num, file_object) self.assertEqual(file_object.getvalue(), expect) expected_file_line += "for the win!" expect = self.module.formatwarning(message, category, file_name, line_num, expected_file_line) file_object = StringIO.StringIO() self.module.showwarning(message, category, file_name, line_num, file_object, expected_file_line) self.assertEqual(expect, file_object.getvalue()) class CWarningsDisplayTests(BaseTest, WarningsDisplayTests): module = c_warnings class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests): module = py_warnings class CatchWarningTests(BaseTest): def test_catch_warnings_restore(self): wmod = self.module orig_filters = wmod.filters orig_showwarning = wmod.showwarning with wmod.catch_warnings(module=wmod, record=True): wmod.filters = wmod.showwarning = object() self.assertTrue(wmod.filters is orig_filters) self.assertTrue(wmod.showwarning is orig_showwarning) with wmod.catch_warnings(module=wmod, record=False): wmod.filters = wmod.showwarning = object() self.assertTrue(wmod.filters is orig_filters) self.assertTrue(wmod.showwarning is orig_showwarning) def test_catch_warnings_recording(self): wmod = self.module with wmod.catch_warnings(module=wmod, record=True) as w: self.assertEqual(w, []) self.assertTrue(type(w) is list) wmod.simplefilter("always") wmod.warn("foo") self.assertEqual(str(w[-1].message), "foo") wmod.warn("bar") self.assertEqual(str(w[-1].message), "bar") self.assertEqual(str(w[0].message), "foo") self.assertEqual(str(w[1].message), "bar") del w[:] self.assertEqual(w, []) orig_showwarning = wmod.showwarning with wmod.catch_warnings(module=wmod, record=False) as w: self.assertTrue(w is None) self.assertTrue(wmod.showwarning is orig_showwarning) def test_catch_warnings_reentry_guard(self): wmod = self.module x = wmod.catch_warnings(module=wmod, record=True) self.assertRaises(RuntimeError, x.__exit__) with x: self.assertRaises(RuntimeError, x.__enter__) x = wmod.catch_warnings(module=wmod, record=False) self.assertRaises(RuntimeError, x.__exit__) with x: self.assertRaises(RuntimeError, x.__enter__) def test_catch_warnings_defaults(self): wmod = self.module orig_filters = wmod.filters orig_showwarning = wmod.showwarning with wmod.catch_warnings(module=wmod) as w: self.assertTrue(w is None) self.assertTrue(wmod.showwarning is orig_showwarning) self.assertTrue(wmod.filters is not orig_filters) self.assertTrue(wmod.filters is orig_filters) if wmod is sys.modules['warnings']: with wmod.catch_warnings() as w: self.assertTrue(w is None) self.assertTrue(wmod.showwarning is orig_showwarning) self.assertTrue(wmod.filters is not orig_filters) self.assertTrue(wmod.filters is orig_filters) def test_check_warnings(self): wmod = self.module if wmod is not sys.modules['warnings']: return with test_support.check_warnings(quiet=False) as w: self.assertEqual(w.warnings, []) wmod.simplefilter("always") wmod.warn("foo") self.assertEqual(str(w.message), "foo") wmod.warn("bar") self.assertEqual(str(w.message), "bar") self.assertEqual(str(w.warnings[0].message), "foo") self.assertEqual(str(w.warnings[1].message), "bar") w.reset() self.assertEqual(w.warnings, []) with test_support.check_warnings(): pass with test_support.check_warnings(('foo', UserWarning)): wmod.warn("foo") with self.assertRaises(AssertionError): with test_support.check_warnings(('', RuntimeWarning)): pass with self.assertRaises(AssertionError): with test_support.check_warnings(('foo', RuntimeWarning)): wmod.warn("foo") class CCatchWarningTests(CatchWarningTests): module = c_warnings class PyCatchWarningTests(CatchWarningTests): module = py_warnings class EnvironmentVariableTests(BaseTest): def test_single_warning(self): newenv = os.environ.copy() newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning" p = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']") self.assertEqual(p.wait(), 0) def test_comma_separated_warnings(self): newenv = os.environ.copy() newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning," "ignore::UnicodeWarning") p = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']") self.assertEqual(p.wait(), 0) def test_envvar_and_command_line(self): newenv = os.environ.copy() newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning" p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning", "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.communicate()[0], "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']") self.assertEqual(p.wait(), 0) class CEnvironmentVariableTests(EnvironmentVariableTests): module = c_warnings class PyEnvironmentVariableTests(EnvironmentVariableTests): module = py_warnings def test_main(): py_warnings.onceregistry.clear() c_warnings.onceregistry.clear() test_support.run_unittest(CFilterTests, PyFilterTests, CWarnTests, PyWarnTests, CWCmdLineTests, PyWCmdLineTests, _WarningsTests, CWarningsDisplayTests, PyWarningsDisplayTests, CCatchWarningTests, PyCatchWarningTests, CEnvironmentVariableTests, PyEnvironmentVariableTests ) if __name__ == "__main__": test_main()
true
true
1c2c0c82cb420667a554255138ca41a2122bf774
1,187
py
Python
tests/conda_env/utils/test_uploader.py
richmoore1962/conda
ef36713bfeca5b9a8505ff8ae6d7899c2d7c6306
[ "BSD-3-Clause" ]
107
2015-01-31T18:25:22.000Z
2021-06-12T16:33:26.000Z
tests/conda_env/utils/test_uploader.py
richmoore1962/conda
ef36713bfeca5b9a8505ff8ae6d7899c2d7c6306
[ "BSD-3-Clause" ]
213
2015-01-06T17:47:59.000Z
2017-06-02T11:54:22.000Z
tests/conda_env/utils/test_uploader.py
richmoore1962/conda
ef36713bfeca5b9a8505ff8ae6d7899c2d7c6306
[ "BSD-3-Clause" ]
62
2015-01-06T15:47:56.000Z
2021-08-23T05:42:17.000Z
import unittest try: from unittest import mock except ImportError: import mock from binstar_client import errors from conda_env.utils.uploader import Uploader class UploaderTestCase(unittest.TestCase): def test_unauthorized(self): uploader = Uploader('package', 'filename') with mock.patch.object(uploader.binstar, 'user') as get_user_mock: get_user_mock.side_effect = errors.Unauthorized self.assertEqual(uploader.authorized(), False) def test_authorized(self): uploader = Uploader('package', 'filename') with mock.patch.object(uploader.binstar, 'user') as get_user_mock: get_user_mock.return_value = {} self.assertEqual(uploader.authorized(), True) def test_package_already_exist(self): uploader = Uploader('package', 'filename') with mock.patch.object(uploader.binstar, 'user') as user_mock: user_mock.return_value = {'login': 'user'} with mock.patch.object(uploader.binstar, 'distribution') as distribution_mock: distribution_mock.return_value = True self.assertEqual(uploader.ensure_distribution(), False)
39.566667
90
0.68829
import unittest try: from unittest import mock except ImportError: import mock from binstar_client import errors from conda_env.utils.uploader import Uploader class UploaderTestCase(unittest.TestCase): def test_unauthorized(self): uploader = Uploader('package', 'filename') with mock.patch.object(uploader.binstar, 'user') as get_user_mock: get_user_mock.side_effect = errors.Unauthorized self.assertEqual(uploader.authorized(), False) def test_authorized(self): uploader = Uploader('package', 'filename') with mock.patch.object(uploader.binstar, 'user') as get_user_mock: get_user_mock.return_value = {} self.assertEqual(uploader.authorized(), True) def test_package_already_exist(self): uploader = Uploader('package', 'filename') with mock.patch.object(uploader.binstar, 'user') as user_mock: user_mock.return_value = {'login': 'user'} with mock.patch.object(uploader.binstar, 'distribution') as distribution_mock: distribution_mock.return_value = True self.assertEqual(uploader.ensure_distribution(), False)
true
true
1c2c0ca790fb83c200c37f1ebec40b4841886f8a
2,477
py
Python
pyrosm/boundary.py
geoDavey/pyrosm
9b28714680e93c1f12cf2dc457fbc7d0db1f2798
[ "MIT" ]
null
null
null
pyrosm/boundary.py
geoDavey/pyrosm
9b28714680e93c1f12cf2dc457fbc7d0db1f2798
[ "MIT" ]
null
null
null
pyrosm/boundary.py
geoDavey/pyrosm
9b28714680e93c1f12cf2dc457fbc7d0db1f2798
[ "MIT" ]
null
null
null
from pyrosm.data_manager import get_osm_data from pyrosm.frames import prepare_geodataframe from pyrosm.utils import validate_custom_filter import geopandas as gpd import warnings def get_boundary_data(node_coordinates, way_records, relations, tags_as_columns, custom_filter, boundary_type, name, bounding_box): if boundary_type == "all": boundary_type = True else: boundary_type = [boundary_type] # If custom_filter has not been defined, initialize with default if custom_filter is None: custom_filter = {"boundary": boundary_type} if "boundary" not in custom_filter.keys(): custom_filter["boundary"] = True # Check that the custom filter is in correct format custom_filter = validate_custom_filter(custom_filter) # Call signature for fetching buildings nodes, ways, relation_ways, relations = get_osm_data(node_arrays=None, way_records=way_records, relations=relations, tags_as_columns=tags_as_columns, data_filter=custom_filter, filter_type="keep", osm_keys=None ) # If there weren't any data, return empty GeoDataFrame if nodes is None and ways is None and relations is None: warnings.warn("Could not find any boundaries for given area.", UserWarning, stacklevel=2) return None # Prepare GeoDataFrame gdf = prepare_geodataframe(nodes, node_coordinates, ways, relations, relation_ways, tags_as_columns, bounding_box) if gdf is None: return None # Filter by name # (use Pandas for filtering, which allows using 'contains' more easily) if name is not None: if "name" not in gdf.columns: raise ValueError("Could not filter by name from given area. " "Any of the OSM elements did not have a name tag.") gdf = gdf.dropna(subset=["name"]) gdf = gdf.loc[gdf["name"].str.contains(name)].reset_index(drop=True).copy() return gdf
39.951613
89
0.557529
from pyrosm.data_manager import get_osm_data from pyrosm.frames import prepare_geodataframe from pyrosm.utils import validate_custom_filter import geopandas as gpd import warnings def get_boundary_data(node_coordinates, way_records, relations, tags_as_columns, custom_filter, boundary_type, name, bounding_box): if boundary_type == "all": boundary_type = True else: boundary_type = [boundary_type] if custom_filter is None: custom_filter = {"boundary": boundary_type} if "boundary" not in custom_filter.keys(): custom_filter["boundary"] = True custom_filter = validate_custom_filter(custom_filter) nodes, ways, relation_ways, relations = get_osm_data(node_arrays=None, way_records=way_records, relations=relations, tags_as_columns=tags_as_columns, data_filter=custom_filter, filter_type="keep", osm_keys=None ) if nodes is None and ways is None and relations is None: warnings.warn("Could not find any boundaries for given area.", UserWarning, stacklevel=2) return None # Prepare GeoDataFrame gdf = prepare_geodataframe(nodes, node_coordinates, ways, relations, relation_ways, tags_as_columns, bounding_box) if gdf is None: return None # Filter by name # (use Pandas for filtering, which allows using 'contains' more easily) if name is not None: if "name" not in gdf.columns: raise ValueError("Could not filter by name from given area. " "Any of the OSM elements did not have a name tag.") gdf = gdf.dropna(subset=["name"]) gdf = gdf.loc[gdf["name"].str.contains(name)].reset_index(drop=True).copy() return gdf
true
true
1c2c0d85d4fc5bb563185b72458addcfa70657d8
143
py
Python
xv_leak_tools/test_components/vpn_application/mobile_vpn_application.py
UAEKondaya1/expressvpn_leak_testing
9e4cee899ac04f7820ac351fa55efdc0c01370ba
[ "MIT" ]
219
2017-12-12T09:42:46.000Z
2022-03-13T08:25:13.000Z
xv_leak_tools/test_components/vpn_application/mobile_vpn_application.py
UAEKondaya1/expressvpn_leak_testing
9e4cee899ac04f7820ac351fa55efdc0c01370ba
[ "MIT" ]
11
2017-12-14T08:14:51.000Z
2021-08-09T18:37:45.000Z
xv_leak_tools/test_components/vpn_application/mobile_vpn_application.py
UAEKondaya1/expressvpn_leak_testing
9e4cee899ac04f7820ac351fa55efdc0c01370ba
[ "MIT" ]
45
2017-12-14T07:26:36.000Z
2022-03-11T09:36:56.000Z
from xv_leak_tools.test_components.vpn_application.vpn_application import VPNApplication class MobileVPNApplication(VPNApplication): pass
28.6
88
0.874126
from xv_leak_tools.test_components.vpn_application.vpn_application import VPNApplication class MobileVPNApplication(VPNApplication): pass
true
true
1c2c0e2371d49e308a5a1275f651283e3e0a2f39
4,190
py
Python
test/oauth_sig_check_test.py
rhargreaves/fastly-vcl-experiments
1514ee06ed5848c4c3701b10a46035b5d2a89277
[ "MIT" ]
3
2016-03-08T09:21:09.000Z
2016-04-13T21:20:00.000Z
test/oauth_sig_check_test.py
rhargreaves/fastly-vcl-experiments
1514ee06ed5848c4c3701b10a46035b5d2a89277
[ "MIT" ]
null
null
null
test/oauth_sig_check_test.py
rhargreaves/fastly-vcl-experiments
1514ee06ed5848c4c3701b10a46035b5d2a89277
[ "MIT" ]
null
null
null
import requests import os from requests_oauthlib import OAuth1 from oauthlib.oauth1 import SIGNATURE_TYPE_QUERY from nose.tools import assert_equals, assert_regex from freezegun import freeze_time from datetime import datetime, timedelta proxies = { 'http': 'http://nonssl.global.fastly.net:80' } service_host = os.environ['SERVICE_HOST'] def test_returns_200_when_authentication_passes_for_key_only(): oauth = OAuth1('foo', client_secret='foo_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( url=url, auth=oauth, proxies=proxies) assert_regex(response.text, 'Authenticated!') assert_equals(response.status_code, 200) def test_returns_200_when_authentication_passes_for_token(): oauth = OAuth1('foo', client_secret='foo_secret', resource_owner_key='bar', resource_owner_secret='bar_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( url=url, auth=oauth, proxies=proxies) assert_regex(response.text, 'Authenticated!') assert_equals(response.status_code, 200) def test_returns_401_when_consumer_key_missing(): url = 'http://{0}/baz'.format(service_host) response = requests.get( url=url, proxies=proxies) assert_regex(response.text, 'Missing Consumer Key') assert_equals(response.status_code, 401) def test_returns_401_when_consumer_key_not_defined(): oauth = OAuth1('unknown_key', client_secret='unknown_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( auth=oauth, url=url, proxies=proxies) assert_regex(response.text, 'Invalid Consumer Key') assert_equals(response.status_code, 401) def test_returns_401_when_access_token_not_defined(): oauth = OAuth1('foo', client_secret='foo_secret', resource_owner_key='unknown_token', resource_owner_secret='unknown_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( auth=oauth, url=url, proxies=proxies) assert_regex(response.text, 'Invalid Access Token') assert_equals(response.status_code, 401) def test_returns_401_when_missing_signature(): url = 'http://{0}/baz?oauth_consumer_key=foo'.format(service_host) response = requests.get( url=url, proxies=proxies) assert_regex(response.text, 'Missing Signature') assert_equals(response.status_code, 401) def test_returns_401_when_signature_invalid(): oauth = OAuth1('foo', client_secret='wrong_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( url=url, auth=oauth, proxies=proxies) assert_regex(response.text, 'Invalid OAuth Signature') assert_equals(response.status_code, 401) @freeze_time(datetime.utcnow() - timedelta(minutes=35)) def test_returns_401_when_timestamp_is_too_old(): oauth = OAuth1('foo', client_secret='foo_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( url=url, auth=oauth, proxies=proxies) assert_regex(response.text, 'Timestamp expired') assert_equals(response.status_code, 401) @freeze_time(datetime.utcnow() + timedelta(minutes=5)) def test_returns_401_when_timestamp_is_in_future(): oauth = OAuth1('foo', client_secret='foo_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( url=url, auth=oauth, proxies=proxies) assert_regex(response.text, 'Timestamp too far in future') assert_equals(response.status_code, 401)
33.790323
70
0.670644
import requests import os from requests_oauthlib import OAuth1 from oauthlib.oauth1 import SIGNATURE_TYPE_QUERY from nose.tools import assert_equals, assert_regex from freezegun import freeze_time from datetime import datetime, timedelta proxies = { 'http': 'http://nonssl.global.fastly.net:80' } service_host = os.environ['SERVICE_HOST'] def test_returns_200_when_authentication_passes_for_key_only(): oauth = OAuth1('foo', client_secret='foo_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( url=url, auth=oauth, proxies=proxies) assert_regex(response.text, 'Authenticated!') assert_equals(response.status_code, 200) def test_returns_200_when_authentication_passes_for_token(): oauth = OAuth1('foo', client_secret='foo_secret', resource_owner_key='bar', resource_owner_secret='bar_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( url=url, auth=oauth, proxies=proxies) assert_regex(response.text, 'Authenticated!') assert_equals(response.status_code, 200) def test_returns_401_when_consumer_key_missing(): url = 'http://{0}/baz'.format(service_host) response = requests.get( url=url, proxies=proxies) assert_regex(response.text, 'Missing Consumer Key') assert_equals(response.status_code, 401) def test_returns_401_when_consumer_key_not_defined(): oauth = OAuth1('unknown_key', client_secret='unknown_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( auth=oauth, url=url, proxies=proxies) assert_regex(response.text, 'Invalid Consumer Key') assert_equals(response.status_code, 401) def test_returns_401_when_access_token_not_defined(): oauth = OAuth1('foo', client_secret='foo_secret', resource_owner_key='unknown_token', resource_owner_secret='unknown_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( auth=oauth, url=url, proxies=proxies) assert_regex(response.text, 'Invalid Access Token') assert_equals(response.status_code, 401) def test_returns_401_when_missing_signature(): url = 'http://{0}/baz?oauth_consumer_key=foo'.format(service_host) response = requests.get( url=url, proxies=proxies) assert_regex(response.text, 'Missing Signature') assert_equals(response.status_code, 401) def test_returns_401_when_signature_invalid(): oauth = OAuth1('foo', client_secret='wrong_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( url=url, auth=oauth, proxies=proxies) assert_regex(response.text, 'Invalid OAuth Signature') assert_equals(response.status_code, 401) @freeze_time(datetime.utcnow() - timedelta(minutes=35)) def test_returns_401_when_timestamp_is_too_old(): oauth = OAuth1('foo', client_secret='foo_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( url=url, auth=oauth, proxies=proxies) assert_regex(response.text, 'Timestamp expired') assert_equals(response.status_code, 401) @freeze_time(datetime.utcnow() + timedelta(minutes=5)) def test_returns_401_when_timestamp_is_in_future(): oauth = OAuth1('foo', client_secret='foo_secret', signature_type=SIGNATURE_TYPE_QUERY) url = 'http://{0}/baz'.format(service_host) response = requests.get( url=url, auth=oauth, proxies=proxies) assert_regex(response.text, 'Timestamp too far in future') assert_equals(response.status_code, 401)
true
true
1c2c0f6de6cac6a96bebc2635b3a7d347d09f9f8
2,026
py
Python
tests/interplanetary_test.py
tomaszmrugalski/astro
c4d270a8d7830fcf799c2cbafe7f7b2070072cc9
[ "MIT" ]
null
null
null
tests/interplanetary_test.py
tomaszmrugalski/astro
c4d270a8d7830fcf799c2cbafe7f7b2070072cc9
[ "MIT" ]
null
null
null
tests/interplanetary_test.py
tomaszmrugalski/astro
c4d270a8d7830fcf799c2cbafe7f7b2070072cc9
[ "MIT" ]
null
null
null
from astropy import units as u from perylune import interplanetary from perylune.orbit_tools import * from poliastro.twobody import Orbit from poliastro.bodies import Earth, Sun import numpy as np from test_tools import * def test_escape_velocity(): # TEST CASE 1: # This is circular orbit, the escape velocity must be the same everywhere. # Escape velocity for position on the ground is 11.179km/s (source BMW2, page 30) o1 = Orbit.circular(Earth, 0*u.km) v,vp,va = interplanetary.escape_vel(o1, False) assert v == vp == va assert np.abs(v - 11179 * u.m/u.s) < 1 * u.m / u.s assert np.abs(vp - 11179 * u.m/u.s) < 1 * u.m / u.s assert np.abs(va - 11179 * u.m/u.s) < 1 * u.m / u.s # TEST CASE 2: # Escape velocity for position at the altitude of 7000km is 7719km/s (source BMW2, page 30) o2 = Orbit.circular(Earth, 7000*u.km) v,vp,va = interplanetary.escape_vel(o2, False) assert v == vp == va assert np.abs(v - 7719 * u.m/u.s) < 1 * u.m / u.s assert np.abs(vp - 7719 * u.m/u.s) < 1 * u.m / u.s assert np.abs(va - 7719 * u.m/u.s) < 1 * u.m / u.s o3 = Orbit.from_classical(Earth, Earth.R + 16000 * u.km, 0.5*u.one, 0*u.deg, 0*u.deg, 0*u.deg, 0*u.deg) print_orb(o3) v,vp,va = interplanetary.escape_vel(o3, False) print(v, vp, va) def test_transfer_vel(): """Tests if interplanetary Hohmann transfers are calculated properly.""" expected = [ # Reference: BMW 2nd ed, table 8-4, example on page 305 ["earth", "mars", 29.79, 24.13, 32.73, 21.48, 258.84 ] ] for case in expected: v = interplanetary.transfer_vel(case[0], case[1], None) print(len(v)) print(len(case)) close_enough(v[0].to(u.km/u.s).value, case[2], 0.3) close_enough(v[1].to(u.km/u.s).value, case[3], 0.3) close_enough(v[2].to(u.km/u.s).value, case[4], 0.5) close_enough(v[3].to(u.km/u.s).value, case[5], 0.5) close_enough(v[4].value, case[6], 2) # check the orbital period
34.931034
107
0.619941
from astropy import units as u from perylune import interplanetary from perylune.orbit_tools import * from poliastro.twobody import Orbit from poliastro.bodies import Earth, Sun import numpy as np from test_tools import * def test_escape_velocity(): o1 = Orbit.circular(Earth, 0*u.km) v,vp,va = interplanetary.escape_vel(o1, False) assert v == vp == va assert np.abs(v - 11179 * u.m/u.s) < 1 * u.m / u.s assert np.abs(vp - 11179 * u.m/u.s) < 1 * u.m / u.s assert np.abs(va - 11179 * u.m/u.s) < 1 * u.m / u.s o2 = Orbit.circular(Earth, 7000*u.km) v,vp,va = interplanetary.escape_vel(o2, False) assert v == vp == va assert np.abs(v - 7719 * u.m/u.s) < 1 * u.m / u.s assert np.abs(vp - 7719 * u.m/u.s) < 1 * u.m / u.s assert np.abs(va - 7719 * u.m/u.s) < 1 * u.m / u.s o3 = Orbit.from_classical(Earth, Earth.R + 16000 * u.km, 0.5*u.one, 0*u.deg, 0*u.deg, 0*u.deg, 0*u.deg) print_orb(o3) v,vp,va = interplanetary.escape_vel(o3, False) print(v, vp, va) def test_transfer_vel(): expected = [ ["earth", "mars", 29.79, 24.13, 32.73, 21.48, 258.84 ] ] for case in expected: v = interplanetary.transfer_vel(case[0], case[1], None) print(len(v)) print(len(case)) close_enough(v[0].to(u.km/u.s).value, case[2], 0.3) close_enough(v[1].to(u.km/u.s).value, case[3], 0.3) close_enough(v[2].to(u.km/u.s).value, case[4], 0.5) close_enough(v[3].to(u.km/u.s).value, case[5], 0.5) close_enough(v[4].value, case[6], 2)
true
true
1c2c100c56a532209cbf6ee9cbafb965b65a8d85
9,978
py
Python
rcnn/fio/rpn.py
truetqy/lesion_det_dual_att
5a5a77dd7f3aa195a2f5b84169822eb32c396d65
[ "Apache-2.0" ]
1
2020-02-25T02:25:44.000Z
2020-02-25T02:25:44.000Z
rcnn/fio/rpn.py
truetqy/lesion_det_dual_att
5a5a77dd7f3aa195a2f5b84169822eb32c396d65
[ "Apache-2.0" ]
null
null
null
rcnn/fio/rpn.py
truetqy/lesion_det_dual_att
5a5a77dd7f3aa195a2f5b84169822eb32c396d65
[ "Apache-2.0" ]
1
2020-06-16T03:07:35.000Z
2020-06-16T03:07:35.000Z
""" RPN: data = {'data': [num_images, c, h, w], 'im_info': [num_images, 4] (optional)} label = {'gt_boxes': [num_boxes, 5] (optional), 'label': [batch_size, 1] <- [batch_size, num_anchors, feat_height, feat_width], 'bbox_target': [batch_size, num_anchors, feat_height, feat_width], 'bbox_weight': [batch_size, num_anchors, feat_height, feat_width]} """ import logging import numpy as np import numpy.random as npr # from rcnn.utils.timer import Timer from ..logger import logger from ..config import config from .image import get_image, tensor_vstack from ..processing.generate_anchor import generate_anchors from ..processing.bbox_transform import bbox_overlaps, bbox_transform def get_rpn_testbatch(roidb): """ return a dict of testbatch :param roidb: ['image', 'flipped'] :return: data, label, im_info """ assert len(roidb) == 1, 'Single batch only' imgs, roidb = get_image(roidb) im_array = imgs[0] im_info = np.array([roidb[0]['im_info']], dtype=np.float32) data = {'data': im_array, 'im_info': im_info} label = {'gt_boxes': roidb[0]['boxes']} return data, label, im_info, roidb[0]['image'], roidb[0]['crop'] def get_rpn_batch(roidbs): """ prototype for rpn batch: data, im_info, gt_boxes :param roidb: ['image', 'flipped'] + ['gt_boxes', 'boxes', 'gt_classes'] :return: data, label """ # assert len(roidb) == 1, 'Single batch only' imgs, roidbs = get_image(roidbs) im_info = np.vstack([r['im_info'] for r in roidbs]) # gt boxes: (x1, y1, x2, y2, cls) gt_boxes_all = [] for r in roidbs: if r['gt_classes'].size > 0: gt_inds = np.where(r['gt_classes'] != 0)[0] gt_boxes = np.empty((r['boxes'].shape[0], 5), dtype=np.float32) gt_boxes[:, 0:4] = r['boxes'][gt_inds, :] gt_boxes[:, 4] = r['gt_classes'][gt_inds] else: gt_boxes = np.empty((0, 5), dtype=np.float32) gt_boxes_all.append(gt_boxes[np.newaxis, :, :]) data = {'data': tensor_vstack(imgs), 'im_info': im_info} label = {'gt_boxes': tensor_vstack(gt_boxes_all)} # print data['data'].shape return data, label def assign_anchor(feat_shape, gt_boxes, im_info, feat_stride=16, scales=(8, 16, 32), ratios=(0.5, 1, 2), allowed_border=0): """ assign ground truth boxes to anchor positions :param feat_shape: infer output shape :param gt_boxes: assign ground truth :param im_info: filter out anchors overlapped with edges :param feat_stride: anchor position step :param scales: used to generate anchors, affects num_anchors (per location) :param ratios: aspect ratios of generated anchors :param allowed_border: filter out anchors with edge overlap > allowed_border :return: dict of label 'label': of shape (batch_size, 1) <- (batch_size, num_anchors, feat_height, feat_width) 'bbox_target': of shape (batch_size, num_anchors * 4, feat_height, feat_width) 'bbox_inside_weight': *todo* mark the assigned anchors 'bbox_outside_weight': used to normalize the bbox_loss, all weights sums to RPN_POSITIVE_WEIGHT """ def _unmap(data, count, inds, fill=0): """" unmap a subset inds of data into original data of size count """ if len(data.shape) == 1: ret = np.empty((count,), dtype=np.float32) ret.fill(fill) ret[inds] = data else: ret = np.empty((count,) + data.shape[1:], dtype=np.float32) ret.fill(fill) ret[inds, :] = data return ret im_info = im_info[0] scales = np.array(scales, dtype=np.float32) base_anchors = generate_anchors(base_size=feat_stride, ratios=list(ratios), scales=scales) num_anchors = base_anchors.shape[0] feat_height, feat_width = feat_shape[-2:] logger.debug('anchors: %s' % base_anchors) logger.debug('anchor shapes: %s' % np.hstack((base_anchors[:, 2::4] - base_anchors[:, 0::4], base_anchors[:, 3::4] - base_anchors[:, 1::4]))) logger.debug('im_info %s' % im_info) logger.debug('height %d width %d' % (feat_height, feat_width)) logger.debug('gt_boxes shape %s' % np.array(gt_boxes.shape)) logger.debug('gt_boxes %s' % gt_boxes) # 1. generate proposals from bbox deltas and shifted anchors shift_x = np.arange(0, feat_width) * feat_stride shift_y = np.arange(0, feat_height) * feat_stride shift_x, shift_y = np.meshgrid(shift_x, shift_y) shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose() # add A anchors (1, A, 4) to # cell K shifts (K, 1, 4) to get # shift anchors (K, A, 4) # reshape to (K*A, 4) shifted anchors A = num_anchors K = shifts.shape[0] all_anchors = base_anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2)) all_anchors = all_anchors.reshape((K * A, 4)) total_anchors = int(K * A) # only keep anchors inside the image inds_inside = np.where((all_anchors[:, 0] >= -allowed_border) & (all_anchors[:, 1] >= -allowed_border) & (all_anchors[:, 2] < im_info[1] + allowed_border) & (all_anchors[:, 3] < im_info[0] + allowed_border))[0] logger.debug('total_anchors %d' % total_anchors) logger.debug('inds_inside %d' % len(inds_inside)) # keep only inside anchors anchors = all_anchors[inds_inside, :] logger.debug('anchors shape %s' % np.array(anchors.shape)) # label: 1 is positive, 0 is negative, -1 is dont care labels = np.empty((len(inds_inside),), dtype=np.float32) labels.fill(-1) if gt_boxes.size > 0: # overlap between the anchors and the gt boxes # overlaps (ex, gt) overlaps = bbox_overlaps(anchors.astype(np.float), gt_boxes.astype(np.float)) argmax_overlaps = overlaps.argmax(axis=1) max_overlaps = overlaps[np.arange(len(inds_inside)), argmax_overlaps] gt_argmax_overlaps = overlaps.argmax(axis=0) gt_max_overlaps = overlaps[gt_argmax_overlaps, np.arange(overlaps.shape[1])] gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0] if not config.TRAIN.RPN_CLOBBER_POSITIVES: # assign bg labels first so that positive labels can clobber them labels[max_overlaps < config.TRAIN.RPN_NEGATIVE_OVERLAP] = 0 # fg label: for each gt, anchor with highest overlap labels[gt_argmax_overlaps] = 1 # fg label: above threshold IoU labels[max_overlaps >= config.TRAIN.RPN_POSITIVE_OVERLAP] = 1 if config.TRAIN.RPN_CLOBBER_POSITIVES: # assign bg labels last so that negative labels can clobber positives labels[max_overlaps < config.TRAIN.RPN_NEGATIVE_OVERLAP] = 0 else: labels[:] = 0 # subsample positive labels if we have too many num_fg = int(config.TRAIN.RPN_FG_FRACTION * config.TRAIN.RPN_BATCH_SIZE) fg_inds = np.where(labels == 1)[0] if len(fg_inds) > num_fg: disable_inds = npr.choice(fg_inds, size=(len(fg_inds) - num_fg), replace=False) # if logger.level == logging.INFO: # disable_inds = fg_inds[:(len(fg_inds) - num_fg)] labels[disable_inds] = -1 # subsample negative labels if we have too many num_bg = config.TRAIN.RPN_BATCH_SIZE - np.sum(labels == 1) bg_inds = np.where(labels == 0)[0] if len(bg_inds) > num_bg: disable_inds = npr.choice(bg_inds, size=(len(bg_inds) - num_bg), replace=False) # if logger.level == logging.INFO: # disable_inds = bg_inds[:(len(bg_inds) - num_bg)] labels[disable_inds] = -1 bbox_targets = np.zeros((len(inds_inside), 4), dtype=np.float32) if gt_boxes.size > 0: bbox_targets[:] = bbox_transform(anchors, gt_boxes[argmax_overlaps, :4]) bbox_weights = np.zeros((len(inds_inside), 4), dtype=np.float32) bbox_weights[labels == 1, :] = np.array(config.TRAIN.RPN_BBOX_WEIGHTS) if logger.level == logging.DEBUG: _sums = bbox_targets[labels == 1, :].sum(axis=0) _squared_sums = (bbox_targets[labels == 1, :] ** 2).sum(axis=0) _counts = np.sum(labels == 1) means = _sums / (_counts + 1e-14) stds = np.sqrt(_squared_sums / _counts - means ** 2) logger.debug('means %s' % means) logger.debug('stdevs %s' % stds) # map up to original set of anchors labels = _unmap(labels, total_anchors, inds_inside, fill=-1) bbox_targets = _unmap(bbox_targets, total_anchors, inds_inside, fill=0) bbox_weights = _unmap(bbox_weights, total_anchors, inds_inside, fill=0) if logger.level == logging.DEBUG: if gt_boxes.size > 0: logger.debug('rpn: max max_overlaps %f' % np.max(max_overlaps)) logger.debug('rpn: num_positives %f' % np.sum(labels == 1)) logger.debug('rpn: num_negatives %f' % np.sum(labels == 0)) _fg_sum = np.sum(labels == 1) _bg_sum = np.sum(labels == 0) _count = 1 logger.debug('rpn: num_positive avg %f' % (_fg_sum / _count)) logger.debug('rpn: num_negative avg %f' % (_bg_sum / _count)) labels = labels.reshape((1, feat_height, feat_width, A)).transpose(0, 3, 1, 2) labels = labels.reshape((1, A * feat_height * feat_width)) bbox_targets = bbox_targets.reshape((1, feat_height, feat_width, A * 4)).transpose(0, 3, 1, 2) bbox_weights = bbox_weights.reshape((1, feat_height, feat_width, A * 4)).transpose((0, 3, 1, 2)) label = {'label': labels, 'bbox_target': bbox_targets, 'bbox_weight': bbox_weights} return label
43.008621
105
0.620265
import logging import numpy as np import numpy.random as npr from ..logger import logger from ..config import config from .image import get_image, tensor_vstack from ..processing.generate_anchor import generate_anchors from ..processing.bbox_transform import bbox_overlaps, bbox_transform def get_rpn_testbatch(roidb): assert len(roidb) == 1, 'Single batch only' imgs, roidb = get_image(roidb) im_array = imgs[0] im_info = np.array([roidb[0]['im_info']], dtype=np.float32) data = {'data': im_array, 'im_info': im_info} label = {'gt_boxes': roidb[0]['boxes']} return data, label, im_info, roidb[0]['image'], roidb[0]['crop'] def get_rpn_batch(roidbs): imgs, roidbs = get_image(roidbs) im_info = np.vstack([r['im_info'] for r in roidbs]) gt_boxes_all = [] for r in roidbs: if r['gt_classes'].size > 0: gt_inds = np.where(r['gt_classes'] != 0)[0] gt_boxes = np.empty((r['boxes'].shape[0], 5), dtype=np.float32) gt_boxes[:, 0:4] = r['boxes'][gt_inds, :] gt_boxes[:, 4] = r['gt_classes'][gt_inds] else: gt_boxes = np.empty((0, 5), dtype=np.float32) gt_boxes_all.append(gt_boxes[np.newaxis, :, :]) data = {'data': tensor_vstack(imgs), 'im_info': im_info} label = {'gt_boxes': tensor_vstack(gt_boxes_all)} return data, label def assign_anchor(feat_shape, gt_boxes, im_info, feat_stride=16, scales=(8, 16, 32), ratios=(0.5, 1, 2), allowed_border=0): def _unmap(data, count, inds, fill=0): if len(data.shape) == 1: ret = np.empty((count,), dtype=np.float32) ret.fill(fill) ret[inds] = data else: ret = np.empty((count,) + data.shape[1:], dtype=np.float32) ret.fill(fill) ret[inds, :] = data return ret im_info = im_info[0] scales = np.array(scales, dtype=np.float32) base_anchors = generate_anchors(base_size=feat_stride, ratios=list(ratios), scales=scales) num_anchors = base_anchors.shape[0] feat_height, feat_width = feat_shape[-2:] logger.debug('anchors: %s' % base_anchors) logger.debug('anchor shapes: %s' % np.hstack((base_anchors[:, 2::4] - base_anchors[:, 0::4], base_anchors[:, 3::4] - base_anchors[:, 1::4]))) logger.debug('im_info %s' % im_info) logger.debug('height %d width %d' % (feat_height, feat_width)) logger.debug('gt_boxes shape %s' % np.array(gt_boxes.shape)) logger.debug('gt_boxes %s' % gt_boxes) shift_x = np.arange(0, feat_width) * feat_stride shift_y = np.arange(0, feat_height) * feat_stride shift_x, shift_y = np.meshgrid(shift_x, shift_y) shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose() A = num_anchors K = shifts.shape[0] all_anchors = base_anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2)) all_anchors = all_anchors.reshape((K * A, 4)) total_anchors = int(K * A) inds_inside = np.where((all_anchors[:, 0] >= -allowed_border) & (all_anchors[:, 1] >= -allowed_border) & (all_anchors[:, 2] < im_info[1] + allowed_border) & (all_anchors[:, 3] < im_info[0] + allowed_border))[0] logger.debug('total_anchors %d' % total_anchors) logger.debug('inds_inside %d' % len(inds_inside)) anchors = all_anchors[inds_inside, :] logger.debug('anchors shape %s' % np.array(anchors.shape)) labels = np.empty((len(inds_inside),), dtype=np.float32) labels.fill(-1) if gt_boxes.size > 0: overlaps = bbox_overlaps(anchors.astype(np.float), gt_boxes.astype(np.float)) argmax_overlaps = overlaps.argmax(axis=1) max_overlaps = overlaps[np.arange(len(inds_inside)), argmax_overlaps] gt_argmax_overlaps = overlaps.argmax(axis=0) gt_max_overlaps = overlaps[gt_argmax_overlaps, np.arange(overlaps.shape[1])] gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0] if not config.TRAIN.RPN_CLOBBER_POSITIVES: labels[max_overlaps < config.TRAIN.RPN_NEGATIVE_OVERLAP] = 0 labels[gt_argmax_overlaps] = 1 labels[max_overlaps >= config.TRAIN.RPN_POSITIVE_OVERLAP] = 1 if config.TRAIN.RPN_CLOBBER_POSITIVES: labels[max_overlaps < config.TRAIN.RPN_NEGATIVE_OVERLAP] = 0 else: labels[:] = 0 num_fg = int(config.TRAIN.RPN_FG_FRACTION * config.TRAIN.RPN_BATCH_SIZE) fg_inds = np.where(labels == 1)[0] if len(fg_inds) > num_fg: disable_inds = npr.choice(fg_inds, size=(len(fg_inds) - num_fg), replace=False) labels[disable_inds] = -1 num_bg = config.TRAIN.RPN_BATCH_SIZE - np.sum(labels == 1) bg_inds = np.where(labels == 0)[0] if len(bg_inds) > num_bg: disable_inds = npr.choice(bg_inds, size=(len(bg_inds) - num_bg), replace=False) labels[disable_inds] = -1 bbox_targets = np.zeros((len(inds_inside), 4), dtype=np.float32) if gt_boxes.size > 0: bbox_targets[:] = bbox_transform(anchors, gt_boxes[argmax_overlaps, :4]) bbox_weights = np.zeros((len(inds_inside), 4), dtype=np.float32) bbox_weights[labels == 1, :] = np.array(config.TRAIN.RPN_BBOX_WEIGHTS) if logger.level == logging.DEBUG: _sums = bbox_targets[labels == 1, :].sum(axis=0) _squared_sums = (bbox_targets[labels == 1, :] ** 2).sum(axis=0) _counts = np.sum(labels == 1) means = _sums / (_counts + 1e-14) stds = np.sqrt(_squared_sums / _counts - means ** 2) logger.debug('means %s' % means) logger.debug('stdevs %s' % stds) labels = _unmap(labels, total_anchors, inds_inside, fill=-1) bbox_targets = _unmap(bbox_targets, total_anchors, inds_inside, fill=0) bbox_weights = _unmap(bbox_weights, total_anchors, inds_inside, fill=0) if logger.level == logging.DEBUG: if gt_boxes.size > 0: logger.debug('rpn: max max_overlaps %f' % np.max(max_overlaps)) logger.debug('rpn: num_positives %f' % np.sum(labels == 1)) logger.debug('rpn: num_negatives %f' % np.sum(labels == 0)) _fg_sum = np.sum(labels == 1) _bg_sum = np.sum(labels == 0) _count = 1 logger.debug('rpn: num_positive avg %f' % (_fg_sum / _count)) logger.debug('rpn: num_negative avg %f' % (_bg_sum / _count)) labels = labels.reshape((1, feat_height, feat_width, A)).transpose(0, 3, 1, 2) labels = labels.reshape((1, A * feat_height * feat_width)) bbox_targets = bbox_targets.reshape((1, feat_height, feat_width, A * 4)).transpose(0, 3, 1, 2) bbox_weights = bbox_weights.reshape((1, feat_height, feat_width, A * 4)).transpose((0, 3, 1, 2)) label = {'label': labels, 'bbox_target': bbox_targets, 'bbox_weight': bbox_weights} return label
true
true
1c2c102002b7e18f4787617786c66338410a3d69
329
py
Python
video_behavior_tracking/__init__.py
droumis/video_behavior_tracking
98b031a4a8dda1c0112f823b661ebad2feeaa43e
[ "MIT" ]
1
2018-10-01T23:33:44.000Z
2018-10-01T23:33:44.000Z
video_behavior_tracking/__init__.py
droumis/video_behavior_tracking
98b031a4a8dda1c0112f823b661ebad2feeaa43e
[ "MIT" ]
1
2020-01-07T01:55:30.000Z
2020-01-07T01:55:30.000Z
video_behavior_tracking/__init__.py
droumis/video_behavior_tracking
98b031a4a8dda1c0112f823b661ebad2feeaa43e
[ "MIT" ]
2
2018-11-15T00:14:35.000Z
2020-11-16T07:50:09.000Z
# flake8: noqa from .kalman import extract_position_data from .labeled_video import make_video from .LED_detection import detect_LEDs from .utils import (adjust_time, convert_to_loren_frank_data_format, position_dataframe, save_loren_frank_data, video_filename_to_epoch_key, write_config)
41.125
68
0.765957
from .kalman import extract_position_data from .labeled_video import make_video from .LED_detection import detect_LEDs from .utils import (adjust_time, convert_to_loren_frank_data_format, position_dataframe, save_loren_frank_data, video_filename_to_epoch_key, write_config)
true
true
1c2c109217c571684466b1b495a7f7640861afc1
12,450
py
Python
src/sage/combinat/integer_vector_weighted.py
UCD4IDS/sage
43474c96d533fd396fe29fe0782d44dc7f5164f7
[ "BSL-1.0" ]
1,742
2015-01-04T07:06:13.000Z
2022-03-30T11:32:52.000Z
src/sage/combinat/integer_vector_weighted.py
UCD4IDS/sage
43474c96d533fd396fe29fe0782d44dc7f5164f7
[ "BSL-1.0" ]
66
2015-03-19T19:17:24.000Z
2022-03-16T11:59:30.000Z
src/sage/combinat/integer_vector_weighted.py
UCD4IDS/sage
43474c96d533fd396fe29fe0782d44dc7f5164f7
[ "BSL-1.0" ]
495
2015-01-10T10:23:18.000Z
2022-03-24T22:06:11.000Z
""" Weighted Integer Vectors AUTHORS: - Mike Hansen (2007): initial version, ported from MuPAD-Combinat - Nicolas M. Thiery (2010-10-30): WeightedIntegerVectors(weights) + cleanup """ # **************************************************************************** # Copyright (C) 2007 Mike Hansen <mhansen@gmail.com> # 2010 Nicolas M. Thiery <nthiery at users.sf.net> # # Distributed under the terms of the GNU General Public License (GPL) # # https://www.gnu.org/licenses/ # **************************************************************************** from sage.structure.unique_representation import UniqueRepresentation from sage.structure.parent import Parent from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets from sage.categories.sets_with_grading import SetsWithGrading from sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets from sage.rings.integer import Integer from sage.rings.integer_ring import ZZ from sage.combinat.integer_vector import IntegerVector from sage.combinat.words.word import Word from sage.combinat.permutation import Permutation class WeightedIntegerVectors(Parent, UniqueRepresentation): r""" The class of integer vectors of `n` weighted by ``weight``, that is, the nonnegative integer vectors `(v_1, \ldots, v_{\ell})` satisfying `\sum_{i=1}^{\ell} v_i w_i = n` where `\ell` is ``length(weight)`` and `w_i` is ``weight[i]``. INPUT: - ``n`` -- a non negative integer (optional) - ``weight`` -- a tuple (or list or iterable) of positive integers EXAMPLES:: sage: WeightedIntegerVectors(8, [1,1,2]) Integer vectors of 8 weighted by [1, 1, 2] sage: WeightedIntegerVectors(8, [1,1,2]).first() [0, 0, 4] sage: WeightedIntegerVectors(8, [1,1,2]).last() [8, 0, 0] sage: WeightedIntegerVectors(8, [1,1,2]).cardinality() 25 sage: w = WeightedIntegerVectors(8, [1,1,2]).random_element() sage: w.parent() is WeightedIntegerVectors(8, [1,1,2]) True sage: WeightedIntegerVectors([1,1,2]) Integer vectors weighted by [1, 1, 2] sage: WeightedIntegerVectors([1,1,2]).cardinality() +Infinity sage: WeightedIntegerVectors([1,1,2]).first() [0, 0, 0] TESTS:: sage: WeightedIntegerVectors(None,None) Traceback (most recent call last): ... ValueError: the weights must be specified .. TODO:: Should the order of the arguments ``n`` and ``weight`` be exchanged to simplify the logic? """ @staticmethod def __classcall_private__(cls, n=None, weight=None): """ Normalize inputs to ensure a unique representation. TESTS:: sage: W = WeightedIntegerVectors(8, [1,1,2]) sage: W2 = WeightedIntegerVectors(int(8), (1,1,2)) sage: W is W2 True """ if weight is None: if n is None: raise ValueError("the weights must be specified") if n in ZZ: weight = (n,) else: weight = tuple(n) n = None weight = tuple(weight) if n is None: return WeightedIntegerVectors_all(weight) return super(WeightedIntegerVectors, cls).__classcall__(cls, n, weight) def __init__(self, n, weight): """ TESTS:: sage: WIV = WeightedIntegerVectors(8, [1,1,2]) sage: TestSuite(WIV).run() """ self._n = n self._weights = weight Parent.__init__(self, category=FiniteEnumeratedSets()) Element = IntegerVector def _element_constructor_(self, lst): """ Construct an element of ``self`` from ``lst``. EXAMPLES:: sage: WIV = WeightedIntegerVectors(3, [2,1,1]) sage: elt = WIV([1, 1, 0]); elt [1, 1, 0] sage: elt.parent() is WIV True sage: WIV([1, 1, 0]) [1, 1, 0] sage: WIV([1, 2, 0]) Traceback (most recent call last): ... ValueError: cannot convert [1, 2, 0] into Integer vectors of 3 weighted by [2, 1, 1] """ if isinstance(lst, IntegerVector): if lst.parent() is self: return lst if lst not in self: raise ValueError("cannot convert %s into %s" % (lst, self)) return self.element_class(self, lst) def _repr_(self): """ TESTS:: sage: WeightedIntegerVectors(8, [1,1,2]) Integer vectors of 8 weighted by [1, 1, 2] """ return "Integer vectors of %s weighted by %s" % (self._n, list(self._weights)) def __contains__(self, x): """ EXAMPLES:: sage: [] in WeightedIntegerVectors(0, []) True sage: [] in WeightedIntegerVectors(1, []) False sage: [3,0,0] in WeightedIntegerVectors(6, [2,1,1]) True sage: [1] in WeightedIntegerVectors(1, [1]) True sage: [1] in WeightedIntegerVectors(2, [2]) True sage: [2] in WeightedIntegerVectors(4, [2]) True sage: [2, 0] in WeightedIntegerVectors(4, [2, 2]) True sage: [2, 1] in WeightedIntegerVectors(4, [2, 2]) False sage: [2, 1] in WeightedIntegerVectors(6, [2, 2]) True sage: [2, 1, 0] in WeightedIntegerVectors(6, [2, 2]) False sage: [0] in WeightedIntegerVectors(0, []) False """ if not isinstance(x, (list, IntegerVector, Permutation)): return False if len(self._weights) != len(x): return False s = 0 for i, val in enumerate(x): if (not isinstance(val, (int, Integer))) and (val not in ZZ): return False s += x[i] * self._weights[i] return s == self._n def _recfun(self, n, l): """ EXAMPLES:: sage: w = WeightedIntegerVectors(3, [2,1,1]) sage: list(w._recfun(3, [1,1,2])) [[0, 1, 1], [1, 0, 1], [0, 3, 0], [1, 2, 0], [2, 1, 0], [3, 0, 0]] """ w = l[-1] l = l[:-1] if l == []: d = int(n) // int(w) if n % w == 0: yield [d] # Otherwise: bad branch return for d in range(int(n) // int(w), -1, -1): for x in self._recfun(n - d * w, l): yield x + [d] def __iter__(self): """ TESTS:: sage: WeightedIntegerVectors(7, [2,2]).list() [] sage: WeightedIntegerVectors(3, [2,1,1]).list() [[1, 0, 1], [1, 1, 0], [0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0]] :: sage: ivw = [ WeightedIntegerVectors(k, [1,1,1]) for k in range(11) ] sage: iv = [ IntegerVectors(k, 3) for k in range(11) ] sage: all(sorted(map(list, iv[k])) == sorted(map(list, ivw[k])) for k in range(11)) True :: sage: ivw = [ WeightedIntegerVectors(k, [2,3,7]) for k in range(11) ] sage: all(i.cardinality() == len(i.list()) for i in ivw) True """ if not self._weights: if self._n == 0: yield self.element_class(self, []) return perm = Word(self._weights).standard_permutation() perm = [len(self._weights) - i for i in perm] l = [x for x in sorted(self._weights, reverse=True)] for x in iterator_fast(self._n, l): yield self.element_class(self, [x[i] for i in perm]) # .action(x) # _left_to_right_multiply_on_right(Permutation(x)) class WeightedIntegerVectors_all(DisjointUnionEnumeratedSets): r""" Set of weighted integer vectors. EXAMPLES:: sage: W = WeightedIntegerVectors([3,1,1,2,1]); W Integer vectors weighted by [3, 1, 1, 2, 1] sage: W.cardinality() +Infinity sage: W12 = W.graded_component(12) sage: W12.an_element() [4, 0, 0, 0, 0] sage: W12.last() [0, 12, 0, 0, 0] sage: W12.cardinality() 441 sage: for w in W12: print(w) [4, 0, 0, 0, 0] [3, 0, 0, 1, 1] [3, 0, 1, 1, 0] ... [0, 11, 1, 0, 0] [0, 12, 0, 0, 0] """ def __init__(self, weight): """ TESTS:: sage: C = WeightedIntegerVectors([2,1,3]) sage: C.category() Category of facade infinite enumerated sets with grading sage: TestSuite(C).run() """ self._weights = weight from sage.sets.all import Family, NonNegativeIntegers # Use "partial" to make the basis function (with the weights # argument specified) pickleable. Otherwise, it seems to # cause problems... from functools import partial F = Family(NonNegativeIntegers(), partial(WeightedIntegerVectors, weight=weight)) cat = (SetsWithGrading(), InfiniteEnumeratedSets()) DisjointUnionEnumeratedSets.__init__(self, F, facade=True, keepkey=False, category=cat) def _repr_(self): """ EXAMPLES:: sage: WeightedIntegerVectors([2,1,3]) Integer vectors weighted by [2, 1, 3] """ return "Integer vectors weighted by %s" % list(self._weights) def __contains__(self, x): """ EXAMPLES:: sage: [] in WeightedIntegerVectors([]) True sage: [3,0,0] in WeightedIntegerVectors([2,1,1]) True sage: [3,0] in WeightedIntegerVectors([2,1,1]) False sage: [3,-1,0] in WeightedIntegerVectors([2,1,1]) False """ return (isinstance(x, (list, IntegerVector, Permutation)) and len(x) == len(self._weights) and all(i in ZZ and i >= 0 for i in x)) def subset(self, size = None): """ EXAMPLES:: sage: C = WeightedIntegerVectors([2,1,3]) sage: C.subset(4) Integer vectors of 4 weighted by [2, 1, 3] """ if size is None: return self return self._family[size] def grading(self, x): # or degree / grading """ EXAMPLES:: sage: C = WeightedIntegerVectors([2,1,3]) sage: C.grading((2,1,1)) 8 """ return sum(exp * deg for exp, deg in zip(x, self._weights)) def iterator_fast(n, l): """ Iterate over all ``l`` weighted integer vectors with total weight ``n``. INPUT: - ``n`` -- an integer - ``l`` -- the weights in weakly decreasing order EXAMPLES:: sage: from sage.combinat.integer_vector_weighted import iterator_fast sage: list(iterator_fast(3, [2,1,1])) [[1, 1, 0], [1, 0, 1], [0, 3, 0], [0, 2, 1], [0, 1, 2], [0, 0, 3]] sage: list(iterator_fast(2, [2])) [[1]] Test that :trac:`20491` is fixed:: sage: type(list(iterator_fast(2, [2]))[0][0]) <class 'sage.rings.integer.Integer'> """ if n < 0: return zero = ZZ.zero() one = ZZ.one() if not l: if n == 0: yield [] return if len(l) == 1: if n % l[0] == 0: yield [n // l[0]] return k = 0 cur = [n // l[k] + one] rem = n - cur[-1] * l[k] # Amount remaining while cur: cur[-1] -= one rem += l[k] if rem == zero: yield cur + [zero] * (len(l) - len(cur)) elif cur[-1] < zero or rem < zero: rem += cur.pop() * l[k] k -= 1 elif len(l) == len(cur) + 1: if rem % l[-1] == zero: yield cur + [rem // l[-1]] else: k += 1 cur.append(rem // l[k] + one) rem -= cur[-1] * l[k] from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.combinat.integer_vector_weighted', 'WeightedIntegerVectors_nweight', WeightedIntegerVectors)
30.970149
125
0.521446
from sage.structure.unique_representation import UniqueRepresentation from sage.structure.parent import Parent from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets from sage.categories.sets_with_grading import SetsWithGrading from sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets from sage.rings.integer import Integer from sage.rings.integer_ring import ZZ from sage.combinat.integer_vector import IntegerVector from sage.combinat.words.word import Word from sage.combinat.permutation import Permutation class WeightedIntegerVectors(Parent, UniqueRepresentation): @staticmethod def __classcall_private__(cls, n=None, weight=None): if weight is None: if n is None: raise ValueError("the weights must be specified") if n in ZZ: weight = (n,) else: weight = tuple(n) n = None weight = tuple(weight) if n is None: return WeightedIntegerVectors_all(weight) return super(WeightedIntegerVectors, cls).__classcall__(cls, n, weight) def __init__(self, n, weight): self._n = n self._weights = weight Parent.__init__(self, category=FiniteEnumeratedSets()) Element = IntegerVector def _element_constructor_(self, lst): if isinstance(lst, IntegerVector): if lst.parent() is self: return lst if lst not in self: raise ValueError("cannot convert %s into %s" % (lst, self)) return self.element_class(self, lst) def _repr_(self): return "Integer vectors of %s weighted by %s" % (self._n, list(self._weights)) def __contains__(self, x): if not isinstance(x, (list, IntegerVector, Permutation)): return False if len(self._weights) != len(x): return False s = 0 for i, val in enumerate(x): if (not isinstance(val, (int, Integer))) and (val not in ZZ): return False s += x[i] * self._weights[i] return s == self._n def _recfun(self, n, l): w = l[-1] l = l[:-1] if l == []: d = int(n) // int(w) if n % w == 0: yield [d] return for d in range(int(n) // int(w), -1, -1): for x in self._recfun(n - d * w, l): yield x + [d] def __iter__(self): if not self._weights: if self._n == 0: yield self.element_class(self, []) return perm = Word(self._weights).standard_permutation() perm = [len(self._weights) - i for i in perm] l = [x for x in sorted(self._weights, reverse=True)] for x in iterator_fast(self._n, l): yield self.element_class(self, [x[i] for i in perm]) class WeightedIntegerVectors_all(DisjointUnionEnumeratedSets): def __init__(self, weight): self._weights = weight from sage.sets.all import Family, NonNegativeIntegers from functools import partial F = Family(NonNegativeIntegers(), partial(WeightedIntegerVectors, weight=weight)) cat = (SetsWithGrading(), InfiniteEnumeratedSets()) DisjointUnionEnumeratedSets.__init__(self, F, facade=True, keepkey=False, category=cat) def _repr_(self): return "Integer vectors weighted by %s" % list(self._weights) def __contains__(self, x): return (isinstance(x, (list, IntegerVector, Permutation)) and len(x) == len(self._weights) and all(i in ZZ and i >= 0 for i in x)) def subset(self, size = None): if size is None: return self return self._family[size] def grading(self, x): return sum(exp * deg for exp, deg in zip(x, self._weights)) def iterator_fast(n, l): if n < 0: return zero = ZZ.zero() one = ZZ.one() if not l: if n == 0: yield [] return if len(l) == 1: if n % l[0] == 0: yield [n // l[0]] return k = 0 cur = [n // l[k] + one] rem = n - cur[-1] * l[k] while cur: cur[-1] -= one rem += l[k] if rem == zero: yield cur + [zero] * (len(l) - len(cur)) elif cur[-1] < zero or rem < zero: rem += cur.pop() * l[k] k -= 1 elif len(l) == len(cur) + 1: if rem % l[-1] == zero: yield cur + [rem // l[-1]] else: k += 1 cur.append(rem // l[k] + one) rem -= cur[-1] * l[k] from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.combinat.integer_vector_weighted', 'WeightedIntegerVectors_nweight', WeightedIntegerVectors)
true
true
1c2c10e98592060422a387974b993eddbea876b7
665
py
Python
appSchool/migrations/0002_auto_20190510_1914.py
NandyAkash/Sma
60b247d7b213516b94347626d09a8f329a70aa90
[ "MIT" ]
null
null
null
appSchool/migrations/0002_auto_20190510_1914.py
NandyAkash/Sma
60b247d7b213516b94347626d09a8f329a70aa90
[ "MIT" ]
null
null
null
appSchool/migrations/0002_auto_20190510_1914.py
NandyAkash/Sma
60b247d7b213516b94347626d09a8f329a70aa90
[ "MIT" ]
null
null
null
# Generated by Django 2.0.13 on 2019-05-10 13:14 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('appSchool', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='user', name='groups', ), migrations.RemoveField( model_name='user', name='roles', ), migrations.RemoveField( model_name='user', name='user_permissions', ), migrations.DeleteModel( name='Role', ), migrations.DeleteModel( name='User', ), ]
20.78125
48
0.512782
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('appSchool', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='user', name='groups', ), migrations.RemoveField( model_name='user', name='roles', ), migrations.RemoveField( model_name='user', name='user_permissions', ), migrations.DeleteModel( name='Role', ), migrations.DeleteModel( name='User', ), ]
true
true
1c2c12a5417aed49530556a1a522d4f26674df6b
2,137
py
Python
pyshadowsocks/protocol/socks5ssl/__init__.py
FTwOoO/pyShadowsocks
452323e30c4b97d322cbb67e9bbc7c4549e67b5f
[ "MIT" ]
21
2016-08-01T06:48:01.000Z
2021-04-05T18:20:53.000Z
pyshadowsocks/protocol/socks5ssl/__init__.py
zen-of-proxy/pyShadowsocks
452323e30c4b97d322cbb67e9bbc7c4549e67b5f
[ "MIT" ]
2
2016-07-23T02:33:17.000Z
2018-03-13T09:50:02.000Z
pyshadowsocks/protocol/socks5ssl/__init__.py
FTwOoO/pyShadowsocks
452323e30c4b97d322cbb67e9bbc7c4549e67b5f
[ "MIT" ]
7
2017-04-22T16:53:53.000Z
2021-02-08T06:33:05.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: booopooob@gmail.com # import os.path import ssl import subprocess import settings def create_self_signed_certs(): settings.SSL_PUBLIC_FILE = os.path.abspath(settings.SSL_PUBLIC_FILE) settings.SSL_RPIVATE_FILE = os.path.abspath(settings.SSL_RPIVATE_FILE) if not os.path.exists(settings.SSL_PUBLIC_FILE): os.makedirs(os.path.dirname(settings.SSL_PUBLIC_FILE), 400, exist_ok=True) os.makedirs(os.path.dirname(settings.SSL_RPIVATE_FILE), 400, exist_ok=True) try: subprocess.check_output('openssl req -x509 -nodes -days 3650 -newkey rsa:2048 ' '-subj "/C=US/ST=Oregon/L=Portland/CN={DOMAIN_NAME}" ' '-keyout {DEST_PRIVATE_PEM} ' '-out {DEST_PUB_PEM}'.format(DOMAIN_NAME='example.org', DEST_PRIVATE_PEM=settings.SSL_RPIVATE_FILE, DEST_PUB_PEM=settings.SSL_PUBLIC_FILE), shell=True) except subprocess.CalledProcessError as ex: settings.CONFIG_LOG.error(ex.output) raise def create_client_ssl_context(): # The certificate is created with pymotw.com as the hostname, # which will not match when the example code runs # elsewhere, so disable hostname verification. ssl_context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH) ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE return ssl_context def create_server_ssl_context(): # The certificate is created with pymotw.com as the hostname, # which will not match when the example code runs elsewhere, # so disable hostname verification. create_self_signed_certs() ssl_context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) ssl_context.check_hostname = False ssl_context.load_cert_chain(settings.SSL_PUBLIC_FILE, settings.SSL_RPIVATE_FILE) return ssl_context
38.160714
108
0.652316
import os.path import ssl import subprocess import settings def create_self_signed_certs(): settings.SSL_PUBLIC_FILE = os.path.abspath(settings.SSL_PUBLIC_FILE) settings.SSL_RPIVATE_FILE = os.path.abspath(settings.SSL_RPIVATE_FILE) if not os.path.exists(settings.SSL_PUBLIC_FILE): os.makedirs(os.path.dirname(settings.SSL_PUBLIC_FILE), 400, exist_ok=True) os.makedirs(os.path.dirname(settings.SSL_RPIVATE_FILE), 400, exist_ok=True) try: subprocess.check_output('openssl req -x509 -nodes -days 3650 -newkey rsa:2048 ' '-subj "/C=US/ST=Oregon/L=Portland/CN={DOMAIN_NAME}" ' '-keyout {DEST_PRIVATE_PEM} ' '-out {DEST_PUB_PEM}'.format(DOMAIN_NAME='example.org', DEST_PRIVATE_PEM=settings.SSL_RPIVATE_FILE, DEST_PUB_PEM=settings.SSL_PUBLIC_FILE), shell=True) except subprocess.CalledProcessError as ex: settings.CONFIG_LOG.error(ex.output) raise def create_client_ssl_context(): ssl_context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH) ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE return ssl_context def create_server_ssl_context(): create_self_signed_certs() ssl_context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) ssl_context.check_hostname = False ssl_context.load_cert_chain(settings.SSL_PUBLIC_FILE, settings.SSL_RPIVATE_FILE) return ssl_context
true
true
1c2c136b8fdad5a79ae05ac836de38ea9dbace3f
3,773
py
Python
gcloud/contrib/function/models.py
gangh/bk-sops
29f4b4915be42650c2eeee637e0cf798e4066f09
[ "Apache-2.0" ]
1
2019-12-23T07:23:35.000Z
2019-12-23T07:23:35.000Z
gcloud/contrib/function/models.py
bk-sops/bk-sops
9f5950b13473bf7b5032528b20016b7a571bb3cd
[ "Apache-2.0" ]
9
2020-02-12T03:15:49.000Z
2021-06-10T22:04:51.000Z
gcloud/contrib/function/models.py
bk-sops/bk-sops
9f5950b13473bf7b5032528b20016b7a571bb3cd
[ "Apache-2.0" ]
1
2022-01-17T11:32:05.000Z
2022-01-17T11:32:05.000Z
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from gcloud.core.utils import convert_readable_username from gcloud.taskflow3.models import TaskFlowInstance FUNCTION_TASK_STATUS = [ ('submitted', _(u"未认领")), ('claimed', _(u"已认领")), ('rejected', _(u"已驳回")), ('executed', _(u"已执行")), ('finished', _(u"已完成")), ] class FunctionTask(models.Model): """ 职能化认领单 """ task = models.ForeignKey(TaskFlowInstance, related_name='function_task', help_text=_(u"职能化单")) creator = models.CharField(_(u"提单人"), max_length=32) create_time = models.DateTimeField(_(u"提单时间"), auto_now_add=True) claimant = models.CharField(_(u"认领人"), max_length=32, blank=True) claim_time = models.DateTimeField(_(u"认领时间"), blank=True, null=True) rejecter = models.CharField(_(u"驳回人"), max_length=32, blank=True) reject_time = models.DateTimeField(_(u"驳回时间"), blank=True, null=True) predecessor = models.CharField(_(u"转单人"), max_length=32, blank=True) transfer_time = models.DateTimeField(_(u"转单时间"), blank=True, null=True) status = models.CharField(_(u"单据状态"), max_length=32, default='submitted', choices=FUNCTION_TASK_STATUS) def __unicode__(self): return u"%s_%s" % (self.task, self.id) class Meta: verbose_name = _(u"职能化认领单 FunctionTask") verbose_name_plural = _(u"职能化认领单 FunctionTask") ordering = ['-id'] @property def status_name(self): return self.get_status_display() @property def creator_name(self): return convert_readable_username(self.creator) @property def editor_name(self): return convert_readable_username(self.editor) def claim_task(self, username): if self.status != 'submitted': return {'result': False, 'message': 'task has been claimed by others'} self.claimant = username self.claim_time = timezone.now() self.status = 'claimed' self.save() return {'result': True, 'message': 'success', 'data': {}} # TODO 驳回后是否可以修改参数?还是走其他流程 def reject_task(self, username): if self.status != 'submitted': return {'result': False, 'message': 'task has been claimed by others'} self.rejecter = username self.reject_time = timezone.now() self.status = 'rejected' return {'result': True, 'message': 'success', 'data': {}} def transfer_task(self, username, claimant): if self.status not in ['claimed', 'executed']: return {'result': False, 'message': 'task with status:%s cannot be transferred' % self.status} if self.claimant != username: return {'result': False, 'message': 'task can only be transferred by claimant'} self.predecessor = self.claimant self.transfer_time = timezone.now() self.claimant = claimant self.claim_time = timezone.now() self.save() return {'result': True, 'message': 'success', 'data': {}}
39.715789
115
0.675855
from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from gcloud.core.utils import convert_readable_username from gcloud.taskflow3.models import TaskFlowInstance FUNCTION_TASK_STATUS = [ ('submitted', _(u"未认领")), ('claimed', _(u"已认领")), ('rejected', _(u"已驳回")), ('executed', _(u"已执行")), ('finished', _(u"已完成")), ] class FunctionTask(models.Model): task = models.ForeignKey(TaskFlowInstance, related_name='function_task', help_text=_(u"职能化单")) creator = models.CharField(_(u"提单人"), max_length=32) create_time = models.DateTimeField(_(u"提单时间"), auto_now_add=True) claimant = models.CharField(_(u"认领人"), max_length=32, blank=True) claim_time = models.DateTimeField(_(u"认领时间"), blank=True, null=True) rejecter = models.CharField(_(u"驳回人"), max_length=32, blank=True) reject_time = models.DateTimeField(_(u"驳回时间"), blank=True, null=True) predecessor = models.CharField(_(u"转单人"), max_length=32, blank=True) transfer_time = models.DateTimeField(_(u"转单时间"), blank=True, null=True) status = models.CharField(_(u"单据状态"), max_length=32, default='submitted', choices=FUNCTION_TASK_STATUS) def __unicode__(self): return u"%s_%s" % (self.task, self.id) class Meta: verbose_name = _(u"职能化认领单 FunctionTask") verbose_name_plural = _(u"职能化认领单 FunctionTask") ordering = ['-id'] @property def status_name(self): return self.get_status_display() @property def creator_name(self): return convert_readable_username(self.creator) @property def editor_name(self): return convert_readable_username(self.editor) def claim_task(self, username): if self.status != 'submitted': return {'result': False, 'message': 'task has been claimed by others'} self.claimant = username self.claim_time = timezone.now() self.status = 'claimed' self.save() return {'result': True, 'message': 'success', 'data': {}} def reject_task(self, username): if self.status != 'submitted': return {'result': False, 'message': 'task has been claimed by others'} self.rejecter = username self.reject_time = timezone.now() self.status = 'rejected' return {'result': True, 'message': 'success', 'data': {}} def transfer_task(self, username, claimant): if self.status not in ['claimed', 'executed']: return {'result': False, 'message': 'task with status:%s cannot be transferred' % self.status} if self.claimant != username: return {'result': False, 'message': 'task can only be transferred by claimant'} self.predecessor = self.claimant self.transfer_time = timezone.now() self.claimant = claimant self.claim_time = timezone.now() self.save() return {'result': True, 'message': 'success', 'data': {}}
true
true
1c2c15280a79e91e39d4330bed21a7be832e710f
1,175
py
Python
migrations/versions/cb9983b1a2b6_init.py
fengyc/flasky
49b822f7f8f1f8ec53007d4cc2467e4744fb213a
[ "MIT" ]
null
null
null
migrations/versions/cb9983b1a2b6_init.py
fengyc/flasky
49b822f7f8f1f8ec53007d4cc2467e4744fb213a
[ "MIT" ]
null
null
null
migrations/versions/cb9983b1a2b6_init.py
fengyc/flasky
49b822f7f8f1f8ec53007d4cc2467e4744fb213a
[ "MIT" ]
null
null
null
"""'init' Revision ID: cb9983b1a2b6 Revises: None Create Date: 2016-01-28 21:20:28.690752 """ # revision identifiers, used by Alembic. revision = 'cb9983b1a2b6' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('roles', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=64), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name') ) op.create_table('users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('username', sa.String(length=64), nullable=True), sa.Column('role_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_users_username'), table_name='users') op.drop_table('users') op.drop_table('roles') ### end Alembic commands ###
27.97619
82
0.666383
revision = 'cb9983b1a2b6' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): 4), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name') ) op.create_table('users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('username', sa.String(length=64), nullable=True), sa.Column('role_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
true
true
1c2c1604189928c066ede2845d4f2e385835cce4
848
py
Python
utils/config.py
Steve-Tod/3D_generation
75817f91f4a69da06375b4401d4182e932102cd1
[ "Apache-2.0" ]
null
null
null
utils/config.py
Steve-Tod/3D_generation
75817f91f4a69da06375b4401d4182e932102cd1
[ "Apache-2.0" ]
null
null
null
utils/config.py
Steve-Tod/3D_generation
75817f91f4a69da06375b4401d4182e932102cd1
[ "Apache-2.0" ]
1
2019-07-24T03:35:27.000Z
2019-07-24T03:35:27.000Z
import json from bunch import Bunch import os def get_config_from_json(json_file): """ Get the config from a json file :param json_file: :return: config(namespace) or config(dictionary) """ # parse the configurations from the config json file provided with open(json_file, 'r') as config_file: config_dict = json.load(config_file) # convert the dictionary to a namespace using bunch lib config = Bunch(config_dict) return config, config_dict def process_config(json_file): config, _ = get_config_from_json(json_file) config.summary_dir = os.path.join("../experiments", config.exp_name, "summary/") config.checkpoint_dir = os.path.join("../experiments", config.exp_name, "checkpoint/") return config
29.241379
75
0.646226
import json from bunch import Bunch import os def get_config_from_json(json_file): with open(json_file, 'r') as config_file: config_dict = json.load(config_file) config = Bunch(config_dict) return config, config_dict def process_config(json_file): config, _ = get_config_from_json(json_file) config.summary_dir = os.path.join("../experiments", config.exp_name, "summary/") config.checkpoint_dir = os.path.join("../experiments", config.exp_name, "checkpoint/") return config
true
true
1c2c1614938ba23c6d186eff22a13e0ea526a734
495
py
Python
plugins/whois/setup.py
lukaszlaszuk/insightconnect-plugins
8c6ce323bfbb12c55f8b5a9c08975d25eb9f8892
[ "MIT" ]
46
2019-06-05T20:47:58.000Z
2022-03-29T10:18:01.000Z
plugins/whois/setup.py
lukaszlaszuk/insightconnect-plugins
8c6ce323bfbb12c55f8b5a9c08975d25eb9f8892
[ "MIT" ]
386
2019-06-07T20:20:39.000Z
2022-03-30T17:35:01.000Z
plugins/whois/setup.py
lukaszlaszuk/insightconnect-plugins
8c6ce323bfbb12c55f8b5a9c08975d25eb9f8892
[ "MIT" ]
43
2019-07-09T14:13:58.000Z
2022-03-28T12:04:46.000Z
# GENERATED BY KOMAND SDK - DO NOT EDIT from setuptools import setup, find_packages setup(name="whois-rapid7-plugin", version="3.0.3", description="The WHOIS plugin enables address and domain lookups in the WHOIS databases", author="rapid7", author_email="", url="", packages=find_packages(), install_requires=['insightconnect-plugin-runtime'], # Add third-party dependencies to requirements.txt, not here! scripts=['bin/komand_whois'] )
33
120
0.684848
from setuptools import setup, find_packages setup(name="whois-rapid7-plugin", version="3.0.3", description="The WHOIS plugin enables address and domain lookups in the WHOIS databases", author="rapid7", author_email="", url="", packages=find_packages(), install_requires=['insightconnect-plugin-runtime'], scripts=['bin/komand_whois'] )
true
true
1c2c1691915643a8ab197499b02cd41d77a3f200
29,880
py
Python
tests/trainer/test_trainer.py
binshengliu/pytorch-lightning
8f6b7a2b4fea9b7bd0b873f5973e6364b3981412
[ "Apache-2.0" ]
null
null
null
tests/trainer/test_trainer.py
binshengliu/pytorch-lightning
8f6b7a2b4fea9b7bd0b873f5973e6364b3981412
[ "Apache-2.0" ]
null
null
null
tests/trainer/test_trainer.py
binshengliu/pytorch-lightning
8f6b7a2b4fea9b7bd0b873f5973e6364b3981412
[ "Apache-2.0" ]
1
2021-03-05T20:59:47.000Z
2021-03-05T20:59:47.000Z
import glob import math import os import types from argparse import Namespace import pytest import torch import yaml import tests.base.utils as tutils from pytorch_lightning import Callback, LightningModule from pytorch_lightning import Trainer from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.core.saving import load_hparams_from_tags_csv, load_hparams_from_yaml, save_hparams_to_tags_csv from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.trainer.logging import TrainerLoggingMixin from pytorch_lightning.utilities.exceptions import MisconfigurationException from tests.base import EvalModelTemplate def test_model_pickle(tmpdir): import pickle model = EvalModelTemplate() pickle.dumps(model) def test_hparams_save_load(tmpdir): model = EvalModelTemplate(vars(EvalModelTemplate.get_default_hparams())) trainer = Trainer( default_root_dir=tmpdir, max_epochs=1, ) # fit model result = trainer.fit(model) assert result == 1 # try to load the model now pretrained_model = tutils.load_model_from_checkpoint( trainer.checkpoint_callback.dirpath, module_class=EvalModelTemplate ) assert pretrained_model def test_no_val_module(tmpdir): """Tests use case where trainer saves the model, and user loads it from tags independently.""" model = EvalModelTemplate() # logger file to get meta logger = tutils.get_default_logger(tmpdir) trainer = Trainer( max_epochs=1, logger=logger, checkpoint_callback=ModelCheckpoint(tmpdir) ) # fit model result = trainer.fit(model) # training complete assert result == 1, 'amp + ddp model failed to complete' # save model new_weights_path = os.path.join(tmpdir, 'save_test.ckpt') trainer.save_checkpoint(new_weights_path) # assert ckpt has hparams ckpt = torch.load(new_weights_path) assert 'hparams' in ckpt.keys(), 'hparams missing from checkpoints' # load new model hparams_path = tutils.get_data_path(logger, path_dir=tmpdir) hparams_path = os.path.join(hparams_path, 'hparams.yaml') model_2 = EvalModelTemplate.load_from_checkpoint( checkpoint_path=new_weights_path, hparams_file=hparams_path ) model_2.eval() def test_no_val_end_module(tmpdir): """Tests use case where trainer saves the model, and user loads it from tags independently.""" model = EvalModelTemplate() # logger file to get meta logger = tutils.get_default_logger(tmpdir) # fit model trainer = Trainer( max_epochs=1, logger=logger, checkpoint_callback=ModelCheckpoint(tmpdir) ) result = trainer.fit(model) # traning complete assert result == 1, 'amp + ddp model failed to complete' # save model new_weights_path = os.path.join(tmpdir, 'save_test.ckpt') trainer.save_checkpoint(new_weights_path) # load new model hparams_path = tutils.get_data_path(logger, path_dir=tmpdir) hparams_path = os.path.join(hparams_path, 'hparams.yaml') model_2 = EvalModelTemplate.load_from_checkpoint( checkpoint_path=new_weights_path, hparams_file=hparams_path ) model_2.eval() def test_gradient_accumulation_scheduling(tmpdir): """ Test grad accumulation by the freq of optimizer updates """ # test incorrect configs with pytest.raises(IndexError): assert Trainer(accumulate_grad_batches={0: 3, 1: 4, 4: 6}) assert Trainer(accumulate_grad_batches={-2: 3}) with pytest.raises(TypeError): assert Trainer(accumulate_grad_batches={}) assert Trainer(accumulate_grad_batches=[[2, 3], [4, 6]]) assert Trainer(accumulate_grad_batches={1: 2, 3.: 4}) assert Trainer(accumulate_grad_batches={1: 2.5, 3: 5}) # test optimizer call freq matches scheduler def _optimizer_step(self, epoch, batch_idx, optimizer, optimizer_idx, second_order_closure=None): # only test the first 12 batches in epoch if batch_idx < 12: if epoch == 0: # reset counter when starting epoch if batch_idx == 0: self.prev_called_batch_idx = 0 # use this opportunity to test once assert self.trainer.accumulate_grad_batches == 1 assert batch_idx == self.prev_called_batch_idx self.prev_called_batch_idx += 1 elif 1 <= epoch <= 2: # reset counter when starting epoch if batch_idx == 1: self.prev_called_batch_idx = 1 # use this opportunity to test once assert self.trainer.accumulate_grad_batches == 2 assert batch_idx == self.prev_called_batch_idx self.prev_called_batch_idx += 2 else: if batch_idx == 3: self.prev_called_batch_idx = 3 # use this opportunity to test once assert self.trainer.accumulate_grad_batches == 4 assert batch_idx == self.prev_called_batch_idx self.prev_called_batch_idx += 3 optimizer.step() # clear gradients optimizer.zero_grad() model = EvalModelTemplate() schedule = {1: 2, 3: 4} trainer = Trainer(accumulate_grad_batches=schedule, train_percent_check=0.1, val_percent_check=0.1, max_epochs=2, default_root_dir=tmpdir) # for the test trainer.optimizer_step = _optimizer_step model.prev_called_batch_idx = 0 trainer.fit(model) def test_loading_meta_tags(tmpdir): """ test for backward compatibility to meta_tags.csv """ tutils.reset_seed() hparams = EvalModelTemplate.get_default_hparams() # save tags logger = tutils.get_default_logger(tmpdir) logger.log_hyperparams(Namespace(some_str='a_str', an_int=1, a_float=2.0)) logger.log_hyperparams(hparams) logger.save() # load hparams path_expt_dir = tutils.get_data_path(logger, path_dir=tmpdir) hparams_path = os.path.join(path_expt_dir, TensorBoardLogger.NAME_HPARAMS_FILE) hparams = load_hparams_from_yaml(hparams_path) # save as legacy meta_tags.csv tags_path = os.path.join(path_expt_dir, 'meta_tags.csv') save_hparams_to_tags_csv(tags_path, hparams) tags = load_hparams_from_tags_csv(tags_path) assert hparams == tags def test_loading_yaml(tmpdir): tutils.reset_seed() hparams = EvalModelTemplate.get_default_hparams() # save tags logger = tutils.get_default_logger(tmpdir) logger.log_hyperparams(Namespace(some_str='a_str', an_int=1, a_float=2.0)) logger.log_hyperparams(hparams) logger.save() # load hparams path_expt_dir = tutils.get_data_path(logger, path_dir=tmpdir) hparams_path = os.path.join(path_expt_dir, 'hparams.yaml') tags = load_hparams_from_yaml(hparams_path) assert tags['batch_size'] == 32 and tags['hidden_dim'] == 1000 def test_dp_output_reduce(): mixin = TrainerLoggingMixin() # test identity when we have a single gpu out = torch.rand(3, 1) assert mixin.reduce_distributed_output(out, num_gpus=1) is out # average when we have multiples assert mixin.reduce_distributed_output(out, num_gpus=2) == out.mean() # when we have a dict of vals out = { 'a': out, 'b': { 'c': out } } reduced = mixin.reduce_distributed_output(out, num_gpus=3) assert reduced['a'] == out['a'] assert reduced['b']['c'] == out['b']['c'] @pytest.mark.parametrize(["save_top_k", "file_prefix", "expected_files"], [ pytest.param(-1, '', {'epoch=4.ckpt', 'epoch=3.ckpt', 'epoch=2.ckpt', 'epoch=1.ckpt', 'epoch=0.ckpt'}, id="CASE K=-1 (all)"), pytest.param(1, 'test_prefix_', {'test_prefix_epoch=4.ckpt'}, id="CASE K=1 (2.5, epoch 4)"), pytest.param(2, '', {'epoch=4.ckpt', 'epoch=2.ckpt'}, id="CASE K=2 (2.5 epoch 4, 2.8 epoch 2)"), pytest.param(4, '', {'epoch=1.ckpt', 'epoch=4.ckpt', 'epoch=3.ckpt', 'epoch=2.ckpt'}, id="CASE K=4 (save all 4 base)"), pytest.param(3, '', {'epoch=2.ckpt', 'epoch=3.ckpt', 'epoch=4.ckpt'}, id="CASE K=3 (save the 2nd, 3rd, 4th model)"), ]) def test_model_checkpoint_options(tmpdir, save_top_k, file_prefix, expected_files): """Test ModelCheckpoint options.""" def mock_save_function(filepath, *args): open(filepath, 'a').close() # simulated losses losses = [10, 9, 2.8, 5, 2.5] checkpoint_callback = ModelCheckpoint(tmpdir, save_top_k=save_top_k, prefix=file_prefix, verbose=1) checkpoint_callback.save_function = mock_save_function trainer = Trainer() # emulate callback's calls during the training for i, loss in enumerate(losses): trainer.current_epoch = i trainer.callback_metrics = {'val_loss': loss} checkpoint_callback.on_validation_end(trainer, trainer.get_model()) file_lists = set(os.listdir(tmpdir)) assert len(file_lists) == len(expected_files), \ "Should save %i models when save_top_k=%i" % (len(expected_files), save_top_k) # verify correct naming for fname in expected_files: assert fname in file_lists def test_model_checkpoint_only_weights(tmpdir): """Tests use case where ModelCheckpoint is configured to save only model weights, and user tries to load checkpoint to resume training. """ model = EvalModelTemplate() trainer = Trainer( max_epochs=1, checkpoint_callback=ModelCheckpoint(tmpdir, save_weights_only=True) ) # fit model result = trainer.fit(model) # training complete assert result == 1, 'training failed to complete' checkpoint_path = list(trainer.checkpoint_callback.best_k_models.keys())[0] # assert saved checkpoint has no trainer data checkpoint = torch.load(checkpoint_path) assert 'optimizer_states' not in checkpoint, 'checkpoint should contain only model weights' assert 'lr_schedulers' not in checkpoint, 'checkpoint should contain only model weights' # assert loading model works when checkpoint has only weights assert EvalModelTemplate.load_from_checkpoint(checkpoint_path=checkpoint_path) # directly save model new_weights_path = os.path.join(tmpdir, 'save_test.ckpt') trainer.save_checkpoint(new_weights_path, weights_only=True) # assert saved checkpoint has no trainer data checkpoint = torch.load(new_weights_path) assert 'optimizer_states' not in checkpoint, 'checkpoint should contain only model weights' assert 'lr_schedulers' not in checkpoint, 'checkpoint should contain only model weights' # assert restoring train state fails with pytest.raises(KeyError, match='checkpoint contains only the model'): trainer.restore_training_state(checkpoint) def test_model_freeze_unfreeze(): model = EvalModelTemplate() model.freeze() model.unfreeze() def test_resume_from_checkpoint_epoch_restored(tmpdir): """Verify resuming from checkpoint runs the right number of epochs""" hparams = EvalModelTemplate.get_default_hparams() def _new_model(): # Create a model that tracks epochs and batches seen model = EvalModelTemplate(hparams) model.num_epochs_seen = 0 model.num_batches_seen = 0 model.num_on_load_checkpoint_called = 0 def increment_epoch(self): self.num_epochs_seen += 1 def increment_batch(self, _): self.num_batches_seen += 1 def increment_on_load_checkpoint(self, _): self.num_on_load_checkpoint_called += 1 # Bind methods to keep track of epoch numbers, batch numbers it has seen # as well as number of times it has called on_load_checkpoint() model.on_epoch_end = types.MethodType(increment_epoch, model) model.on_batch_start = types.MethodType(increment_batch, model) model.on_load_checkpoint = types.MethodType(increment_on_load_checkpoint, model) return model model = _new_model() trainer_options = dict( progress_bar_refresh_rate=0, max_epochs=2, train_percent_check=0.65, val_percent_check=1, checkpoint_callback=ModelCheckpoint(tmpdir, save_top_k=-1), default_root_dir=tmpdir, early_stop_callback=False, val_check_interval=1., ) trainer = Trainer(**trainer_options) # fit model trainer.fit(model) training_batches = trainer.num_training_batches assert model.num_epochs_seen == 2 assert model.num_batches_seen == training_batches * 2 assert model.num_on_load_checkpoint_called == 0 # Other checkpoints can be uncommented if/when resuming mid-epoch is supported checkpoints = sorted(glob.glob(os.path.join(trainer.checkpoint_callback.dirpath, '*.ckpt'))) for check in checkpoints: next_model = _new_model() state = torch.load(check) # Resume training trainer_options['max_epochs'] = 2 new_trainer = Trainer(**trainer_options, resume_from_checkpoint=check) new_trainer.fit(next_model) assert state['global_step'] + next_model.num_batches_seen == training_batches * trainer_options['max_epochs'] assert next_model.num_on_load_checkpoint_called == 1 def _init_steps_model(): """private method for initializing a model with 5% train epochs""" model = EvalModelTemplate() # define train epoch to 5% of data train_percent = 0.5 # get number of samples in 1 epoch num_train_samples = math.floor(len(model.train_dataloader()) * train_percent) trainer_options = dict( train_percent_check=train_percent, ) return model, trainer_options, num_train_samples def test_trainer_max_steps_and_epochs(tmpdir): """Verify model trains according to specified max steps""" model, trainer_options, num_train_samples = _init_steps_model() # define less train steps than epochs trainer_options.update( default_root_dir=tmpdir, max_epochs=3, max_steps=num_train_samples + 10 ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, "Training did not complete" # check training stopped at max_steps assert trainer.global_step == trainer.max_steps, "Model did not stop at max_steps" # define less train epochs than steps trainer_options.update( max_epochs=2, max_steps=trainer_options['max_epochs'] * 2 * num_train_samples ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, "Training did not complete" # check training stopped at max_epochs assert trainer.global_step == num_train_samples * trainer.max_epochs assert trainer.current_epoch == trainer.max_epochs - 1, "Model did not stop at max_epochs" def test_trainer_min_steps_and_epochs(tmpdir): """Verify model trains according to specified min steps""" model, trainer_options, num_train_samples = _init_steps_model() # define callback for stopping the model and default epochs trainer_options.update( default_root_dir=tmpdir, early_stop_callback=EarlyStopping(monitor='val_loss', min_delta=1.0), val_check_interval=2, min_epochs=1, max_epochs=5 ) # define less min steps than 1 epoch trainer_options['min_steps'] = math.floor(num_train_samples / 2) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, "Training did not complete" # check model ran for at least min_epochs assert trainer.global_step >= num_train_samples and \ trainer.current_epoch > 0, "Model did not train for at least min_epochs" # define less epochs than min_steps trainer_options['min_steps'] = math.floor(num_train_samples * 1.5) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, "Training did not complete" # check model ran for at least num_train_samples*1.5 assert trainer.global_step >= math.floor(num_train_samples * 1.5) and \ trainer.current_epoch > 0, "Model did not train for at least min_steps" def test_benchmark_option(tmpdir): """Verify benchmark option.""" model = EvalModelTemplate() model.val_dataloader = model.val_dataloader__multiple # verify torch.backends.cudnn.benchmark is not turned on assert not torch.backends.cudnn.benchmark # fit model trainer = Trainer( default_root_dir=tmpdir, max_epochs=1, benchmark=True, ) result = trainer.fit(model) # verify training completed assert result == 1 # verify torch.backends.cudnn.benchmark is not turned off assert torch.backends.cudnn.benchmark def test_testpass_overrides(tmpdir): # todo: check duplicated tests against trainer_checks hparams = EvalModelTemplate.get_default_hparams() # Misconfig when neither test_step or test_end is implemented with pytest.raises(MisconfigurationException, match='.*not implement `test_dataloader`.*'): model = EvalModelTemplate(hparams) model.test_dataloader = LightningModule.test_dataloader Trainer().test(model) # Misconfig when neither test_step or test_end is implemented with pytest.raises(MisconfigurationException): model = EvalModelTemplate(hparams) model.test_step = LightningModule.test_step Trainer().test(model) # No exceptions when one or both of test_step or test_end are implemented model = EvalModelTemplate(hparams) model.test_step_end = LightningModule.test_step_end Trainer().test(model) model = EvalModelTemplate(hparams) Trainer().test(model) def test_disabled_validation(): """Verify that `val_percent_check=0` disables the validation loop unless `fast_dev_run=True`.""" class CurrentModel(EvalModelTemplate): validation_step_invoked = False validation_epoch_end_invoked = False def validation_step(self, *args, **kwargs): self.validation_step_invoked = True return super().validation_step(*args, **kwargs) def validation_epoch_end(self, *args, **kwargs): self.validation_epoch_end_invoked = True return super().validation_epoch_end(*args, **kwargs) hparams = EvalModelTemplate.get_default_hparams() model = CurrentModel(hparams) trainer_options = dict( progress_bar_refresh_rate=0, max_epochs=2, train_percent_check=0.4, val_percent_check=0.0, fast_dev_run=False, ) trainer = Trainer(**trainer_options) result = trainer.fit(model) # check that val_percent_check=0 turns off validation assert result == 1, 'training failed to complete' assert trainer.current_epoch == 1 assert not model.validation_step_invoked, \ '`validation_step` should not run when `val_percent_check=0`' assert not model.validation_epoch_end_invoked, \ '`validation_epoch_end` should not run when `val_percent_check=0`' # check that val_percent_check has no influence when fast_dev_run is turned on model = CurrentModel(hparams) trainer_options.update(fast_dev_run=True) trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, 'training failed to complete' assert trainer.current_epoch == 0 assert model.validation_step_invoked, \ 'did not run `validation_step` with `fast_dev_run=True`' assert model.validation_epoch_end_invoked, \ 'did not run `validation_epoch_end` with `fast_dev_run=True`' def test_nan_loss_detection(tmpdir): class CurrentModel(EvalModelTemplate): test_batch_inf_loss = 8 def training_step(self, batch, batch_idx, optimizer_idx=None): output = super().training_step(batch, batch_idx, optimizer_idx) if batch_idx == self.test_batch_inf_loss: if isinstance(output, dict): output['loss'] *= torch.tensor(math.inf) # make loss infinite else: output /= 0 return output model = CurrentModel() # fit model trainer = Trainer( default_root_dir=tmpdir, max_steps=(model.test_batch_inf_loss + 1), terminate_on_nan=True ) with pytest.raises(ValueError, match=r'.*The loss returned in `training_step` is nan or inf.*'): trainer.fit(model) assert trainer.global_step == model.test_step_inf_loss for param in model.parameters(): assert torch.isfinite(param).all() def test_nan_params_detection(tmpdir): class CurrentModel(EvalModelTemplate): test_batch_nan = 8 def on_after_backward(self): if self.global_step == self.test_batch_nan: # simulate parameter that became nan torch.nn.init.constant_(self.c_d1.bias, math.nan) model = CurrentModel() trainer = Trainer( default_root_dir=tmpdir, max_steps=(model.test_batch_nan + 1), terminate_on_nan=True ) with pytest.raises(ValueError, match=r'.*Detected nan and/or inf values in `c_d1.bias`.*'): trainer.fit(model) assert trainer.global_step == model.test_batch_nan # after aborting the training loop, model still has nan-valued params params = torch.cat([param.view(-1) for param in model.parameters()]) assert not torch.isfinite(params).all() def test_trainer_interrupted_flag(tmpdir): """Test the flag denoting that a user interrupted training.""" model = EvalModelTemplate() class InterruptCallback(Callback): def __init__(self): super().__init__() def on_batch_start(self, trainer, pl_module): raise KeyboardInterrupt interrupt_callback = InterruptCallback() trainer = Trainer( callbacks=[interrupt_callback], max_epochs=1, val_percent_check=0.1, train_percent_check=0.2, progress_bar_refresh_rate=0, logger=False, default_root_dir=tmpdir, ) assert not trainer.interrupted trainer.fit(model) assert trainer.interrupted def test_gradient_clipping(tmpdir): """ Test gradient clipping """ model = EvalModelTemplate() # test that gradient is clipped correctly def _optimizer_step(*args, **kwargs): parameters = model.parameters() grad_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), 2) for p in parameters]), 2) assert (grad_norm - 1.0).abs() < 0.01, "Gradient norm != 1.0: {grad_norm}".format(grad_norm=grad_norm) trainer = Trainer(max_steps=1, max_epochs=1, gradient_clip_val=1.0, default_root_dir=tmpdir) # for the test model.optimizer_step = _optimizer_step model.prev_called_batch_idx = 0 trainer.fit(model) def test_gpu_choice(tmpdir): trainer_options = dict( default_save_path=tmpdir, ) # Only run if CUDA is available if not torch.cuda.is_available(): return num_gpus = torch.cuda.device_count() Trainer(**trainer_options, gpus=num_gpus, auto_select_gpus=True) with pytest.raises(RuntimeError, match=r'.*No GPUs available.*'): Trainer(**trainer_options, gpus=num_gpus + 1, auto_select_gpus=True) @pytest.mark.parametrize("trainer_kwargs,expected", [ pytest.param( dict(distributed_backend=None, gpus=None), dict(use_dp=False, use_ddp=False, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=1) ), pytest.param( dict(distributed_backend="dp", gpus=None), dict(use_dp=False, use_ddp=False, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=1) ), pytest.param( dict(distributed_backend="dp", gpus=None), dict(use_dp=False, use_ddp=False, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=1) ), pytest.param( dict(distributed_backend="ddp", gpus=None), dict(use_dp=False, use_ddp=False, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=1) ), pytest.param( dict(distributed_backend="ddp", num_processes=2, gpus=None), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=2) ), pytest.param( dict(distributed_backend="ddp", num_nodes=2, gpus=None), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=1) ), pytest.param( dict(distributed_backend="ddp_cpu", num_processes=2, gpus=None), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=2) ), pytest.param( dict(distributed_backend="ddp2", gpus=None), dict(use_dp=False, use_ddp=False, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=1) ), pytest.param( dict(distributed_backend=None, gpus=1), dict(use_dp=False, use_ddp=False, use_ddp2=False, num_gpus=1, on_gpu=True, single_gpu=True, num_processes=1), marks=[pytest.mark.skipif(torch.cuda.device_count() == 0, reason="GPU needed")] ), pytest.param( dict(distributed_backend="dp", gpus=1), dict(use_dp=True, use_ddp=False, use_ddp2=False, num_gpus=1, on_gpu=True, single_gpu=True, num_processes=1), marks=[pytest.mark.skipif(torch.cuda.device_count() == 0, reason="GPU needed")] ), pytest.param( dict(distributed_backend="ddp", gpus=1), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=1, on_gpu=True, single_gpu=True, num_processes=1), marks=[pytest.mark.skipif(torch.cuda.device_count() == 0, reason="GPU needed")] ), pytest.param( dict(distributed_backend="ddp_cpu", num_processes=2, gpus=1), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=2), marks=[pytest.mark.skipif(torch.cuda.device_count() == 0, reason="GPU needed")] ), pytest.param( dict(distributed_backend="ddp2", gpus=1), dict(use_dp=False, use_ddp=False, use_ddp2=True, num_gpus=1, on_gpu=True, single_gpu=False, num_processes=1), marks=[pytest.mark.skipif(torch.cuda.device_count() == 0, reason="GPU needed")] ), pytest.param( dict(distributed_backend=None, gpus=2), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=2, on_gpu=True, single_gpu=False, num_processes=2), marks=[pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Multiple GPUs needed")] ), pytest.param( dict(distributed_backend="dp", gpus=2), dict(use_dp=True, use_ddp=False, use_ddp2=False, num_gpus=2, on_gpu=True, single_gpu=False, num_processes=1), marks=[pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Multiple GPUs needed")] ), pytest.param( dict(distributed_backend="ddp", gpus=2), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=2, on_gpu=True, single_gpu=False, num_processes=2), marks=[pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Multiple GPUs needed")] ), pytest.param( dict(distributed_backend="ddp2", gpus=2), dict(use_dp=False, use_ddp=False, use_ddp2=True, num_gpus=2, on_gpu=True, single_gpu=False, num_processes=1), marks=[pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Multiple GPUs needed")] ), ]) def test_trainer_config(trainer_kwargs, expected): trainer = Trainer(**trainer_kwargs) assert trainer.use_dp is expected["use_dp"] assert trainer.use_ddp is expected["use_ddp"] assert trainer.use_ddp2 is expected["use_ddp2"] assert trainer.num_gpus == expected["num_gpus"] assert trainer.on_gpu is expected["on_gpu"] assert trainer.single_gpu is expected["single_gpu"] assert trainer.num_processes == expected["num_processes"] def test_trainer_subclassing(): model = EvalModelTemplate() # First way of pulling out args from signature is to list them class TrainerSubclass(Trainer): def __init__(self, custom_arg, *args, custom_kwarg='test', **kwargs): super().__init__(*args, **kwargs) self.custom_arg = custom_arg self.custom_kwarg = custom_kwarg trainer = TrainerSubclass(123, custom_kwarg='custom', fast_dev_run=True) result = trainer.fit(model) assert result == 1 assert trainer.custom_arg == 123 assert trainer.custom_kwarg == 'custom' assert trainer.fast_dev_run # Second way is to pop from the dict # It's a special case because Trainer does not have any positional args class TrainerSubclass(Trainer): def __init__(self, **kwargs): self.custom_arg = kwargs.pop('custom_arg', 0) self.custom_kwarg = kwargs.pop('custom_kwarg', 'test') super().__init__(**kwargs) trainer = TrainerSubclass(custom_kwarg='custom', fast_dev_run=True) result = trainer.fit(model) assert result == 1 assert trainer.custom_kwarg == 'custom' assert trainer.fast_dev_run # when we pass in an unknown arg, the base class should complain with pytest.raises(TypeError, match=r"__init__\(\) got an unexpected keyword argument 'abcdefg'") as e: TrainerSubclass(abcdefg='unknown_arg')
35.111633
118
0.683969
import glob import math import os import types from argparse import Namespace import pytest import torch import yaml import tests.base.utils as tutils from pytorch_lightning import Callback, LightningModule from pytorch_lightning import Trainer from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.core.saving import load_hparams_from_tags_csv, load_hparams_from_yaml, save_hparams_to_tags_csv from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.trainer.logging import TrainerLoggingMixin from pytorch_lightning.utilities.exceptions import MisconfigurationException from tests.base import EvalModelTemplate def test_model_pickle(tmpdir): import pickle model = EvalModelTemplate() pickle.dumps(model) def test_hparams_save_load(tmpdir): model = EvalModelTemplate(vars(EvalModelTemplate.get_default_hparams())) trainer = Trainer( default_root_dir=tmpdir, max_epochs=1, ) result = trainer.fit(model) assert result == 1 pretrained_model = tutils.load_model_from_checkpoint( trainer.checkpoint_callback.dirpath, module_class=EvalModelTemplate ) assert pretrained_model def test_no_val_module(tmpdir): model = EvalModelTemplate() logger = tutils.get_default_logger(tmpdir) trainer = Trainer( max_epochs=1, logger=logger, checkpoint_callback=ModelCheckpoint(tmpdir) ) result = trainer.fit(model) assert result == 1, 'amp + ddp model failed to complete' new_weights_path = os.path.join(tmpdir, 'save_test.ckpt') trainer.save_checkpoint(new_weights_path) ckpt = torch.load(new_weights_path) assert 'hparams' in ckpt.keys(), 'hparams missing from checkpoints' hparams_path = tutils.get_data_path(logger, path_dir=tmpdir) hparams_path = os.path.join(hparams_path, 'hparams.yaml') model_2 = EvalModelTemplate.load_from_checkpoint( checkpoint_path=new_weights_path, hparams_file=hparams_path ) model_2.eval() def test_no_val_end_module(tmpdir): model = EvalModelTemplate() logger = tutils.get_default_logger(tmpdir) trainer = Trainer( max_epochs=1, logger=logger, checkpoint_callback=ModelCheckpoint(tmpdir) ) result = trainer.fit(model) assert result == 1, 'amp + ddp model failed to complete' new_weights_path = os.path.join(tmpdir, 'save_test.ckpt') trainer.save_checkpoint(new_weights_path) hparams_path = tutils.get_data_path(logger, path_dir=tmpdir) hparams_path = os.path.join(hparams_path, 'hparams.yaml') model_2 = EvalModelTemplate.load_from_checkpoint( checkpoint_path=new_weights_path, hparams_file=hparams_path ) model_2.eval() def test_gradient_accumulation_scheduling(tmpdir): with pytest.raises(IndexError): assert Trainer(accumulate_grad_batches={0: 3, 1: 4, 4: 6}) assert Trainer(accumulate_grad_batches={-2: 3}) with pytest.raises(TypeError): assert Trainer(accumulate_grad_batches={}) assert Trainer(accumulate_grad_batches=[[2, 3], [4, 6]]) assert Trainer(accumulate_grad_batches={1: 2, 3.: 4}) assert Trainer(accumulate_grad_batches={1: 2.5, 3: 5}) def _optimizer_step(self, epoch, batch_idx, optimizer, optimizer_idx, second_order_closure=None): if batch_idx < 12: if epoch == 0: if batch_idx == 0: self.prev_called_batch_idx = 0 assert self.trainer.accumulate_grad_batches == 1 assert batch_idx == self.prev_called_batch_idx self.prev_called_batch_idx += 1 elif 1 <= epoch <= 2: if batch_idx == 1: self.prev_called_batch_idx = 1 assert self.trainer.accumulate_grad_batches == 2 assert batch_idx == self.prev_called_batch_idx self.prev_called_batch_idx += 2 else: if batch_idx == 3: self.prev_called_batch_idx = 3 assert self.trainer.accumulate_grad_batches == 4 assert batch_idx == self.prev_called_batch_idx self.prev_called_batch_idx += 3 optimizer.step() optimizer.zero_grad() model = EvalModelTemplate() schedule = {1: 2, 3: 4} trainer = Trainer(accumulate_grad_batches=schedule, train_percent_check=0.1, val_percent_check=0.1, max_epochs=2, default_root_dir=tmpdir) trainer.optimizer_step = _optimizer_step model.prev_called_batch_idx = 0 trainer.fit(model) def test_loading_meta_tags(tmpdir): tutils.reset_seed() hparams = EvalModelTemplate.get_default_hparams() logger = tutils.get_default_logger(tmpdir) logger.log_hyperparams(Namespace(some_str='a_str', an_int=1, a_float=2.0)) logger.log_hyperparams(hparams) logger.save() path_expt_dir = tutils.get_data_path(logger, path_dir=tmpdir) hparams_path = os.path.join(path_expt_dir, TensorBoardLogger.NAME_HPARAMS_FILE) hparams = load_hparams_from_yaml(hparams_path) tags_path = os.path.join(path_expt_dir, 'meta_tags.csv') save_hparams_to_tags_csv(tags_path, hparams) tags = load_hparams_from_tags_csv(tags_path) assert hparams == tags def test_loading_yaml(tmpdir): tutils.reset_seed() hparams = EvalModelTemplate.get_default_hparams() logger = tutils.get_default_logger(tmpdir) logger.log_hyperparams(Namespace(some_str='a_str', an_int=1, a_float=2.0)) logger.log_hyperparams(hparams) logger.save() path_expt_dir = tutils.get_data_path(logger, path_dir=tmpdir) hparams_path = os.path.join(path_expt_dir, 'hparams.yaml') tags = load_hparams_from_yaml(hparams_path) assert tags['batch_size'] == 32 and tags['hidden_dim'] == 1000 def test_dp_output_reduce(): mixin = TrainerLoggingMixin() out = torch.rand(3, 1) assert mixin.reduce_distributed_output(out, num_gpus=1) is out assert mixin.reduce_distributed_output(out, num_gpus=2) == out.mean() out = { 'a': out, 'b': { 'c': out } } reduced = mixin.reduce_distributed_output(out, num_gpus=3) assert reduced['a'] == out['a'] assert reduced['b']['c'] == out['b']['c'] @pytest.mark.parametrize(["save_top_k", "file_prefix", "expected_files"], [ pytest.param(-1, '', {'epoch=4.ckpt', 'epoch=3.ckpt', 'epoch=2.ckpt', 'epoch=1.ckpt', 'epoch=0.ckpt'}, id="CASE K=-1 (all)"), pytest.param(1, 'test_prefix_', {'test_prefix_epoch=4.ckpt'}, id="CASE K=1 (2.5, epoch 4)"), pytest.param(2, '', {'epoch=4.ckpt', 'epoch=2.ckpt'}, id="CASE K=2 (2.5 epoch 4, 2.8 epoch 2)"), pytest.param(4, '', {'epoch=1.ckpt', 'epoch=4.ckpt', 'epoch=3.ckpt', 'epoch=2.ckpt'}, id="CASE K=4 (save all 4 base)"), pytest.param(3, '', {'epoch=2.ckpt', 'epoch=3.ckpt', 'epoch=4.ckpt'}, id="CASE K=3 (save the 2nd, 3rd, 4th model)"), ]) def test_model_checkpoint_options(tmpdir, save_top_k, file_prefix, expected_files): def mock_save_function(filepath, *args): open(filepath, 'a').close() losses = [10, 9, 2.8, 5, 2.5] checkpoint_callback = ModelCheckpoint(tmpdir, save_top_k=save_top_k, prefix=file_prefix, verbose=1) checkpoint_callback.save_function = mock_save_function trainer = Trainer() for i, loss in enumerate(losses): trainer.current_epoch = i trainer.callback_metrics = {'val_loss': loss} checkpoint_callback.on_validation_end(trainer, trainer.get_model()) file_lists = set(os.listdir(tmpdir)) assert len(file_lists) == len(expected_files), \ "Should save %i models when save_top_k=%i" % (len(expected_files), save_top_k) # verify correct naming for fname in expected_files: assert fname in file_lists def test_model_checkpoint_only_weights(tmpdir): model = EvalModelTemplate() trainer = Trainer( max_epochs=1, checkpoint_callback=ModelCheckpoint(tmpdir, save_weights_only=True) ) # fit model result = trainer.fit(model) # training complete assert result == 1, 'training failed to complete' checkpoint_path = list(trainer.checkpoint_callback.best_k_models.keys())[0] # assert saved checkpoint has no trainer data checkpoint = torch.load(checkpoint_path) assert 'optimizer_states' not in checkpoint, 'checkpoint should contain only model weights' assert 'lr_schedulers' not in checkpoint, 'checkpoint should contain only model weights' # assert loading model works when checkpoint has only weights assert EvalModelTemplate.load_from_checkpoint(checkpoint_path=checkpoint_path) # directly save model new_weights_path = os.path.join(tmpdir, 'save_test.ckpt') trainer.save_checkpoint(new_weights_path, weights_only=True) # assert saved checkpoint has no trainer data checkpoint = torch.load(new_weights_path) assert 'optimizer_states' not in checkpoint, 'checkpoint should contain only model weights' assert 'lr_schedulers' not in checkpoint, 'checkpoint should contain only model weights' # assert restoring train state fails with pytest.raises(KeyError, match='checkpoint contains only the model'): trainer.restore_training_state(checkpoint) def test_model_freeze_unfreeze(): model = EvalModelTemplate() model.freeze() model.unfreeze() def test_resume_from_checkpoint_epoch_restored(tmpdir): hparams = EvalModelTemplate.get_default_hparams() def _new_model(): # Create a model that tracks epochs and batches seen model = EvalModelTemplate(hparams) model.num_epochs_seen = 0 model.num_batches_seen = 0 model.num_on_load_checkpoint_called = 0 def increment_epoch(self): self.num_epochs_seen += 1 def increment_batch(self, _): self.num_batches_seen += 1 def increment_on_load_checkpoint(self, _): self.num_on_load_checkpoint_called += 1 # Bind methods to keep track of epoch numbers, batch numbers it has seen # as well as number of times it has called on_load_checkpoint() model.on_epoch_end = types.MethodType(increment_epoch, model) model.on_batch_start = types.MethodType(increment_batch, model) model.on_load_checkpoint = types.MethodType(increment_on_load_checkpoint, model) return model model = _new_model() trainer_options = dict( progress_bar_refresh_rate=0, max_epochs=2, train_percent_check=0.65, val_percent_check=1, checkpoint_callback=ModelCheckpoint(tmpdir, save_top_k=-1), default_root_dir=tmpdir, early_stop_callback=False, val_check_interval=1., ) trainer = Trainer(**trainer_options) # fit model trainer.fit(model) training_batches = trainer.num_training_batches assert model.num_epochs_seen == 2 assert model.num_batches_seen == training_batches * 2 assert model.num_on_load_checkpoint_called == 0 # Other checkpoints can be uncommented if/when resuming mid-epoch is supported checkpoints = sorted(glob.glob(os.path.join(trainer.checkpoint_callback.dirpath, '*.ckpt'))) for check in checkpoints: next_model = _new_model() state = torch.load(check) # Resume training trainer_options['max_epochs'] = 2 new_trainer = Trainer(**trainer_options, resume_from_checkpoint=check) new_trainer.fit(next_model) assert state['global_step'] + next_model.num_batches_seen == training_batches * trainer_options['max_epochs'] assert next_model.num_on_load_checkpoint_called == 1 def _init_steps_model(): model = EvalModelTemplate() # define train epoch to 5% of data train_percent = 0.5 # get number of samples in 1 epoch num_train_samples = math.floor(len(model.train_dataloader()) * train_percent) trainer_options = dict( train_percent_check=train_percent, ) return model, trainer_options, num_train_samples def test_trainer_max_steps_and_epochs(tmpdir): model, trainer_options, num_train_samples = _init_steps_model() # define less train steps than epochs trainer_options.update( default_root_dir=tmpdir, max_epochs=3, max_steps=num_train_samples + 10 ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, "Training did not complete" # check training stopped at max_steps assert trainer.global_step == trainer.max_steps, "Model did not stop at max_steps" # define less train epochs than steps trainer_options.update( max_epochs=2, max_steps=trainer_options['max_epochs'] * 2 * num_train_samples ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, "Training did not complete" # check training stopped at max_epochs assert trainer.global_step == num_train_samples * trainer.max_epochs assert trainer.current_epoch == trainer.max_epochs - 1, "Model did not stop at max_epochs" def test_trainer_min_steps_and_epochs(tmpdir): model, trainer_options, num_train_samples = _init_steps_model() # define callback for stopping the model and default epochs trainer_options.update( default_root_dir=tmpdir, early_stop_callback=EarlyStopping(monitor='val_loss', min_delta=1.0), val_check_interval=2, min_epochs=1, max_epochs=5 ) # define less min steps than 1 epoch trainer_options['min_steps'] = math.floor(num_train_samples / 2) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, "Training did not complete" # check model ran for at least min_epochs assert trainer.global_step >= num_train_samples and \ trainer.current_epoch > 0, "Model did not train for at least min_epochs" # define less epochs than min_steps trainer_options['min_steps'] = math.floor(num_train_samples * 1.5) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, "Training did not complete" # check model ran for at least num_train_samples*1.5 assert trainer.global_step >= math.floor(num_train_samples * 1.5) and \ trainer.current_epoch > 0, "Model did not train for at least min_steps" def test_benchmark_option(tmpdir): model = EvalModelTemplate() model.val_dataloader = model.val_dataloader__multiple # verify torch.backends.cudnn.benchmark is not turned on assert not torch.backends.cudnn.benchmark # fit model trainer = Trainer( default_root_dir=tmpdir, max_epochs=1, benchmark=True, ) result = trainer.fit(model) # verify training completed assert result == 1 # verify torch.backends.cudnn.benchmark is not turned off assert torch.backends.cudnn.benchmark def test_testpass_overrides(tmpdir): # todo: check duplicated tests against trainer_checks hparams = EvalModelTemplate.get_default_hparams() # Misconfig when neither test_step or test_end is implemented with pytest.raises(MisconfigurationException, match='.*not implement `test_dataloader`.*'): model = EvalModelTemplate(hparams) model.test_dataloader = LightningModule.test_dataloader Trainer().test(model) # Misconfig when neither test_step or test_end is implemented with pytest.raises(MisconfigurationException): model = EvalModelTemplate(hparams) model.test_step = LightningModule.test_step Trainer().test(model) # No exceptions when one or both of test_step or test_end are implemented model = EvalModelTemplate(hparams) model.test_step_end = LightningModule.test_step_end Trainer().test(model) model = EvalModelTemplate(hparams) Trainer().test(model) def test_disabled_validation(): class CurrentModel(EvalModelTemplate): validation_step_invoked = False validation_epoch_end_invoked = False def validation_step(self, *args, **kwargs): self.validation_step_invoked = True return super().validation_step(*args, **kwargs) def validation_epoch_end(self, *args, **kwargs): self.validation_epoch_end_invoked = True return super().validation_epoch_end(*args, **kwargs) hparams = EvalModelTemplate.get_default_hparams() model = CurrentModel(hparams) trainer_options = dict( progress_bar_refresh_rate=0, max_epochs=2, train_percent_check=0.4, val_percent_check=0.0, fast_dev_run=False, ) trainer = Trainer(**trainer_options) result = trainer.fit(model) # check that val_percent_check=0 turns off validation assert result == 1, 'training failed to complete' assert trainer.current_epoch == 1 assert not model.validation_step_invoked, \ '`validation_step` should not run when `val_percent_check=0`' assert not model.validation_epoch_end_invoked, \ '`validation_epoch_end` should not run when `val_percent_check=0`' # check that val_percent_check has no influence when fast_dev_run is turned on model = CurrentModel(hparams) trainer_options.update(fast_dev_run=True) trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, 'training failed to complete' assert trainer.current_epoch == 0 assert model.validation_step_invoked, \ 'did not run `validation_step` with `fast_dev_run=True`' assert model.validation_epoch_end_invoked, \ 'did not run `validation_epoch_end` with `fast_dev_run=True`' def test_nan_loss_detection(tmpdir): class CurrentModel(EvalModelTemplate): test_batch_inf_loss = 8 def training_step(self, batch, batch_idx, optimizer_idx=None): output = super().training_step(batch, batch_idx, optimizer_idx) if batch_idx == self.test_batch_inf_loss: if isinstance(output, dict): output['loss'] *= torch.tensor(math.inf) # make loss infinite else: output /= 0 return output model = CurrentModel() # fit model trainer = Trainer( default_root_dir=tmpdir, max_steps=(model.test_batch_inf_loss + 1), terminate_on_nan=True ) with pytest.raises(ValueError, match=r'.*The loss returned in `training_step` is nan or inf.*'): trainer.fit(model) assert trainer.global_step == model.test_step_inf_loss for param in model.parameters(): assert torch.isfinite(param).all() def test_nan_params_detection(tmpdir): class CurrentModel(EvalModelTemplate): test_batch_nan = 8 def on_after_backward(self): if self.global_step == self.test_batch_nan: # simulate parameter that became nan torch.nn.init.constant_(self.c_d1.bias, math.nan) model = CurrentModel() trainer = Trainer( default_root_dir=tmpdir, max_steps=(model.test_batch_nan + 1), terminate_on_nan=True ) with pytest.raises(ValueError, match=r'.*Detected nan and/or inf values in `c_d1.bias`.*'): trainer.fit(model) assert trainer.global_step == model.test_batch_nan # after aborting the training loop, model still has nan-valued params params = torch.cat([param.view(-1) for param in model.parameters()]) assert not torch.isfinite(params).all() def test_trainer_interrupted_flag(tmpdir): model = EvalModelTemplate() class InterruptCallback(Callback): def __init__(self): super().__init__() def on_batch_start(self, trainer, pl_module): raise KeyboardInterrupt interrupt_callback = InterruptCallback() trainer = Trainer( callbacks=[interrupt_callback], max_epochs=1, val_percent_check=0.1, train_percent_check=0.2, progress_bar_refresh_rate=0, logger=False, default_root_dir=tmpdir, ) assert not trainer.interrupted trainer.fit(model) assert trainer.interrupted def test_gradient_clipping(tmpdir): model = EvalModelTemplate() # test that gradient is clipped correctly def _optimizer_step(*args, **kwargs): parameters = model.parameters() grad_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), 2) for p in parameters]), 2) assert (grad_norm - 1.0).abs() < 0.01, "Gradient norm != 1.0: {grad_norm}".format(grad_norm=grad_norm) trainer = Trainer(max_steps=1, max_epochs=1, gradient_clip_val=1.0, default_root_dir=tmpdir) # for the test model.optimizer_step = _optimizer_step model.prev_called_batch_idx = 0 trainer.fit(model) def test_gpu_choice(tmpdir): trainer_options = dict( default_save_path=tmpdir, ) # Only run if CUDA is available if not torch.cuda.is_available(): return num_gpus = torch.cuda.device_count() Trainer(**trainer_options, gpus=num_gpus, auto_select_gpus=True) with pytest.raises(RuntimeError, match=r'.*No GPUs available.*'): Trainer(**trainer_options, gpus=num_gpus + 1, auto_select_gpus=True) @pytest.mark.parametrize("trainer_kwargs,expected", [ pytest.param( dict(distributed_backend=None, gpus=None), dict(use_dp=False, use_ddp=False, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=1) ), pytest.param( dict(distributed_backend="dp", gpus=None), dict(use_dp=False, use_ddp=False, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=1) ), pytest.param( dict(distributed_backend="dp", gpus=None), dict(use_dp=False, use_ddp=False, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=1) ), pytest.param( dict(distributed_backend="ddp", gpus=None), dict(use_dp=False, use_ddp=False, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=1) ), pytest.param( dict(distributed_backend="ddp", num_processes=2, gpus=None), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=2) ), pytest.param( dict(distributed_backend="ddp", num_nodes=2, gpus=None), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=1) ), pytest.param( dict(distributed_backend="ddp_cpu", num_processes=2, gpus=None), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=2) ), pytest.param( dict(distributed_backend="ddp2", gpus=None), dict(use_dp=False, use_ddp=False, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=1) ), pytest.param( dict(distributed_backend=None, gpus=1), dict(use_dp=False, use_ddp=False, use_ddp2=False, num_gpus=1, on_gpu=True, single_gpu=True, num_processes=1), marks=[pytest.mark.skipif(torch.cuda.device_count() == 0, reason="GPU needed")] ), pytest.param( dict(distributed_backend="dp", gpus=1), dict(use_dp=True, use_ddp=False, use_ddp2=False, num_gpus=1, on_gpu=True, single_gpu=True, num_processes=1), marks=[pytest.mark.skipif(torch.cuda.device_count() == 0, reason="GPU needed")] ), pytest.param( dict(distributed_backend="ddp", gpus=1), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=1, on_gpu=True, single_gpu=True, num_processes=1), marks=[pytest.mark.skipif(torch.cuda.device_count() == 0, reason="GPU needed")] ), pytest.param( dict(distributed_backend="ddp_cpu", num_processes=2, gpus=1), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=0, on_gpu=False, single_gpu=False, num_processes=2), marks=[pytest.mark.skipif(torch.cuda.device_count() == 0, reason="GPU needed")] ), pytest.param( dict(distributed_backend="ddp2", gpus=1), dict(use_dp=False, use_ddp=False, use_ddp2=True, num_gpus=1, on_gpu=True, single_gpu=False, num_processes=1), marks=[pytest.mark.skipif(torch.cuda.device_count() == 0, reason="GPU needed")] ), pytest.param( dict(distributed_backend=None, gpus=2), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=2, on_gpu=True, single_gpu=False, num_processes=2), marks=[pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Multiple GPUs needed")] ), pytest.param( dict(distributed_backend="dp", gpus=2), dict(use_dp=True, use_ddp=False, use_ddp2=False, num_gpus=2, on_gpu=True, single_gpu=False, num_processes=1), marks=[pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Multiple GPUs needed")] ), pytest.param( dict(distributed_backend="ddp", gpus=2), dict(use_dp=False, use_ddp=True, use_ddp2=False, num_gpus=2, on_gpu=True, single_gpu=False, num_processes=2), marks=[pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Multiple GPUs needed")] ), pytest.param( dict(distributed_backend="ddp2", gpus=2), dict(use_dp=False, use_ddp=False, use_ddp2=True, num_gpus=2, on_gpu=True, single_gpu=False, num_processes=1), marks=[pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Multiple GPUs needed")] ), ]) def test_trainer_config(trainer_kwargs, expected): trainer = Trainer(**trainer_kwargs) assert trainer.use_dp is expected["use_dp"] assert trainer.use_ddp is expected["use_ddp"] assert trainer.use_ddp2 is expected["use_ddp2"] assert trainer.num_gpus == expected["num_gpus"] assert trainer.on_gpu is expected["on_gpu"] assert trainer.single_gpu is expected["single_gpu"] assert trainer.num_processes == expected["num_processes"] def test_trainer_subclassing(): model = EvalModelTemplate() # First way of pulling out args from signature is to list them class TrainerSubclass(Trainer): def __init__(self, custom_arg, *args, custom_kwarg='test', **kwargs): super().__init__(*args, **kwargs) self.custom_arg = custom_arg self.custom_kwarg = custom_kwarg trainer = TrainerSubclass(123, custom_kwarg='custom', fast_dev_run=True) result = trainer.fit(model) assert result == 1 assert trainer.custom_arg == 123 assert trainer.custom_kwarg == 'custom' assert trainer.fast_dev_run # Second way is to pop from the dict # It's a special case because Trainer does not have any positional args class TrainerSubclass(Trainer): def __init__(self, **kwargs): self.custom_arg = kwargs.pop('custom_arg', 0) self.custom_kwarg = kwargs.pop('custom_kwarg', 'test') super().__init__(**kwargs) trainer = TrainerSubclass(custom_kwarg='custom', fast_dev_run=True) result = trainer.fit(model) assert result == 1 assert trainer.custom_kwarg == 'custom' assert trainer.fast_dev_run with pytest.raises(TypeError, match=r"__init__\(\) got an unexpected keyword argument 'abcdefg'") as e: TrainerSubclass(abcdefg='unknown_arg')
true
true
1c2c16caae55b75e2804f678b6f990b595ff904d
8,503
py
Python
awips/test/dafTests/testGfeEditArea.py
mjames-upc/python-awips
e2b05f5587b02761df3b6dd5c6ee1f196bd5f11c
[ "BSD-3-Clause" ]
null
null
null
awips/test/dafTests/testGfeEditArea.py
mjames-upc/python-awips
e2b05f5587b02761df3b6dd5c6ee1f196bd5f11c
[ "BSD-3-Clause" ]
null
null
null
awips/test/dafTests/testGfeEditArea.py
mjames-upc/python-awips
e2b05f5587b02761df3b6dd5c6ee1f196bd5f11c
[ "BSD-3-Clause" ]
null
null
null
from __future__ import print_function from dynamicserialize.dstypes.com.raytheon.uf.common.dataquery.requests import RequestConstraint from awips.dataaccess import DataAccessLayer as DAL from awips.ThriftClient import ThriftRequestException from awips.test.dafTests import baseDafTestCase from awips.test.dafTests import params # # Test DAF support for GFE edit area data # # SOFTWARE HISTORY # # Date Ticket# Engineer Description # ------------ ---------- ----------- -------------------------- # 06/08/17 6298 mapeters Initial Creation. # 09/27/17 6463 tgurney Remove GID site identifier # # class GfeEditAreaTestCase(baseDafTestCase.DafTestCase): """Test DAF support for GFE edit area data""" datatype = 'gfeEditArea' siteIdKey = 'siteId' editAreaNames = ['ISC_NHA', 'SDZ066', 'StormSurgeWW_EditArea'] groupKey = 'group' groups = ['ISC', 'WFOs', 'FIPS_' + params.SITE_ID] def testGetAvailableParameters(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) with self.assertRaises(ThriftRequestException): self.runParametersTest(req) def testGetAvailableLocations(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) self.runLocationsTest(req) def testGetAvailableTimes(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) with self.assertRaises(ThriftRequestException): self.runTimesTest(req) def testGetGeometryDataWithoutSiteIdThrowsException(self): req = DAL.newDataRequest(self.datatype) with self.assertRaises(ThriftRequestException): self.runGeometryDataTest(req) def testGetGeometryData(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) data = self.runGeometryDataTest(req) for item in data: self.assertEqual(params.SITE_ID, item.getAttribute(self.siteIdKey)) def testGetGeometryDataWithLocNames(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) req.setLocationNames(*self.editAreaNames) data = self.runGeometryDataTest(req) for item in data: self.assertEqual(params.SITE_ID, item.getAttribute(self.siteIdKey)) self.assertIn(item.getLocationName(), self.editAreaNames) def testGetGeometryDataWithGroups(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) req.addIdentifier(self.groupKey, RequestConstraint.new('in', self.groups)) data = self.runGeometryDataTest(req) for item in data: self.assertEqual(params.SITE_ID, item.getAttribute(self.siteIdKey)) self.assertIn(item.getAttribute(self.groupKey), self.groups) def testGetGeometryDataWithLocNamesAndGroupsThrowException(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) req.setLocationNames(*self.editAreaNames) req.addIdentifier(self.groupKey, RequestConstraint.new('in', self.groups)) with self.assertRaises(ThriftRequestException): self.runGeometryDataTest(req) def testGetGeometryDataWithEnvelope(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) req.setEnvelope(params.ENVELOPE) data = self.runGeometryDataTest(req) for item in data: self.assertEqual(params.SITE_ID, item.getAttribute(self.siteIdKey)) self.assertTrue(params.ENVELOPE.intersects(item.getGeometry())) def testGetIdentifierValues(self): req = DAL.newDataRequest(self.datatype) optionalIds = set(DAL.getOptionalIdentifiers(req)) requiredIds = set(DAL.getRequiredIdentifiers(req)) self.runGetIdValuesTest(optionalIds | requiredIds) def testGetInvalidIdentifierValuesThrowsException(self): self.runInvalidIdValuesTest() def testGetNonexistentIdentifierValuesThrowsException(self): self.runNonexistentIdValuesTest() def _runConstraintTest(self, key, operator, value): req = DAL.newDataRequest(self.datatype) constraint = RequestConstraint.new(operator, value) req.addIdentifier(key, constraint) req.setLocationNames(*self.editAreaNames) return self.runGeometryDataTest(req) def testGetDataWithEqualsString(self): geomData = self._runConstraintTest(self.siteIdKey, '=', params.SITE_ID) for record in geomData: self.assertEqual(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithEqualsUnicode(self): geomData = self._runConstraintTest(self.siteIdKey, '=', params.SITE_ID.decode('unicode-escape')) for record in geomData: self.assertEqual(record.getAttribute(self.siteIdKey), params.SITE_ID) # No numeric tests since no numeric identifiers are available. def testGetDataWithEqualsNone(self): geomData = self._runConstraintTest(self.siteIdKey, '=', None) for record in geomData: self.assertIsNone(record.getAttribute(self.siteIdKey)) def testGetDataWithNotEquals(self): geomData = self._runConstraintTest(self.siteIdKey, '!=', params.SITE_ID) for record in geomData: self.assertNotEqual(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithNotEqualsNone(self): geomData = self._runConstraintTest(self.siteIdKey, '!=', None) for record in geomData: self.assertIsNotNone(record.getAttribute(self.siteIdKey)) def testGetDataWithGreaterThan(self): geomData = self._runConstraintTest(self.siteIdKey, '>', params.SITE_ID) for record in geomData: self.assertGreater(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithLessThan(self): geomData = self._runConstraintTest(self.siteIdKey, '<', params.SITE_ID) for record in geomData: self.assertLess(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithGreaterThanEquals(self): geomData = self._runConstraintTest(self.siteIdKey, '>=', params.SITE_ID) for record in geomData: self.assertGreaterEqual(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithLessThanEquals(self): geomData = self._runConstraintTest(self.siteIdKey, '<=', params.SITE_ID) for record in geomData: self.assertLessEqual(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithInTuple(self): collection = (params.SITE_ID,) geomData = self._runConstraintTest(self.siteIdKey, 'in', collection) for record in geomData: self.assertIn(record.getAttribute(self.siteIdKey), collection) def testGetDataWithInList(self): collection = [params.SITE_ID,] geomData = self._runConstraintTest(self.siteIdKey, 'in', collection) for record in geomData: self.assertIn(record.getAttribute(self.siteIdKey), collection) def testGetDataWithInGenerator(self): collection = (params.SITE_ID,) generator = (item for item in collection) geomData = self._runConstraintTest(self.siteIdKey, 'in', generator) for record in geomData: self.assertIn(record.getAttribute(self.siteIdKey), collection) def testGetDataWithNotInList(self): collection = [params.SITE_ID,] geomData = self._runConstraintTest(self.siteIdKey, 'not in', collection) for record in geomData: self.assertNotIn(record.getAttribute(self.siteIdKey), collection) def testGetDataWithInvalidConstraintTypeThrowsException(self): with self.assertRaises(ValueError): self._runConstraintTest(self.siteIdKey, 'junk', params.SITE_ID) def testGetDataWithInvalidConstraintValueThrowsException(self): with self.assertRaises(TypeError): self._runConstraintTest(self.siteIdKey, '=', {}) def testGetDataWithEmptyInConstraintThrowsException(self): with self.assertRaises(ValueError): self._runConstraintTest(self.siteIdKey, 'in', [])
42.303483
104
0.698342
from __future__ import print_function from dynamicserialize.dstypes.com.raytheon.uf.common.dataquery.requests import RequestConstraint from awips.dataaccess import DataAccessLayer as DAL from awips.ThriftClient import ThriftRequestException from awips.test.dafTests import baseDafTestCase from awips.test.dafTests import params baseDafTestCase.DafTestCase): datatype = 'gfeEditArea' siteIdKey = 'siteId' editAreaNames = ['ISC_NHA', 'SDZ066', 'StormSurgeWW_EditArea'] groupKey = 'group' groups = ['ISC', 'WFOs', 'FIPS_' + params.SITE_ID] def testGetAvailableParameters(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) with self.assertRaises(ThriftRequestException): self.runParametersTest(req) def testGetAvailableLocations(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) self.runLocationsTest(req) def testGetAvailableTimes(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) with self.assertRaises(ThriftRequestException): self.runTimesTest(req) def testGetGeometryDataWithoutSiteIdThrowsException(self): req = DAL.newDataRequest(self.datatype) with self.assertRaises(ThriftRequestException): self.runGeometryDataTest(req) def testGetGeometryData(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) data = self.runGeometryDataTest(req) for item in data: self.assertEqual(params.SITE_ID, item.getAttribute(self.siteIdKey)) def testGetGeometryDataWithLocNames(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) req.setLocationNames(*self.editAreaNames) data = self.runGeometryDataTest(req) for item in data: self.assertEqual(params.SITE_ID, item.getAttribute(self.siteIdKey)) self.assertIn(item.getLocationName(), self.editAreaNames) def testGetGeometryDataWithGroups(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) req.addIdentifier(self.groupKey, RequestConstraint.new('in', self.groups)) data = self.runGeometryDataTest(req) for item in data: self.assertEqual(params.SITE_ID, item.getAttribute(self.siteIdKey)) self.assertIn(item.getAttribute(self.groupKey), self.groups) def testGetGeometryDataWithLocNamesAndGroupsThrowException(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) req.setLocationNames(*self.editAreaNames) req.addIdentifier(self.groupKey, RequestConstraint.new('in', self.groups)) with self.assertRaises(ThriftRequestException): self.runGeometryDataTest(req) def testGetGeometryDataWithEnvelope(self): req = DAL.newDataRequest(self.datatype) req.addIdentifier(self.siteIdKey, params.SITE_ID) req.setEnvelope(params.ENVELOPE) data = self.runGeometryDataTest(req) for item in data: self.assertEqual(params.SITE_ID, item.getAttribute(self.siteIdKey)) self.assertTrue(params.ENVELOPE.intersects(item.getGeometry())) def testGetIdentifierValues(self): req = DAL.newDataRequest(self.datatype) optionalIds = set(DAL.getOptionalIdentifiers(req)) requiredIds = set(DAL.getRequiredIdentifiers(req)) self.runGetIdValuesTest(optionalIds | requiredIds) def testGetInvalidIdentifierValuesThrowsException(self): self.runInvalidIdValuesTest() def testGetNonexistentIdentifierValuesThrowsException(self): self.runNonexistentIdValuesTest() def _runConstraintTest(self, key, operator, value): req = DAL.newDataRequest(self.datatype) constraint = RequestConstraint.new(operator, value) req.addIdentifier(key, constraint) req.setLocationNames(*self.editAreaNames) return self.runGeometryDataTest(req) def testGetDataWithEqualsString(self): geomData = self._runConstraintTest(self.siteIdKey, '=', params.SITE_ID) for record in geomData: self.assertEqual(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithEqualsUnicode(self): geomData = self._runConstraintTest(self.siteIdKey, '=', params.SITE_ID.decode('unicode-escape')) for record in geomData: self.assertEqual(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithEqualsNone(self): geomData = self._runConstraintTest(self.siteIdKey, '=', None) for record in geomData: self.assertIsNone(record.getAttribute(self.siteIdKey)) def testGetDataWithNotEquals(self): geomData = self._runConstraintTest(self.siteIdKey, '!=', params.SITE_ID) for record in geomData: self.assertNotEqual(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithNotEqualsNone(self): geomData = self._runConstraintTest(self.siteIdKey, '!=', None) for record in geomData: self.assertIsNotNone(record.getAttribute(self.siteIdKey)) def testGetDataWithGreaterThan(self): geomData = self._runConstraintTest(self.siteIdKey, '>', params.SITE_ID) for record in geomData: self.assertGreater(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithLessThan(self): geomData = self._runConstraintTest(self.siteIdKey, '<', params.SITE_ID) for record in geomData: self.assertLess(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithGreaterThanEquals(self): geomData = self._runConstraintTest(self.siteIdKey, '>=', params.SITE_ID) for record in geomData: self.assertGreaterEqual(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithLessThanEquals(self): geomData = self._runConstraintTest(self.siteIdKey, '<=', params.SITE_ID) for record in geomData: self.assertLessEqual(record.getAttribute(self.siteIdKey), params.SITE_ID) def testGetDataWithInTuple(self): collection = (params.SITE_ID,) geomData = self._runConstraintTest(self.siteIdKey, 'in', collection) for record in geomData: self.assertIn(record.getAttribute(self.siteIdKey), collection) def testGetDataWithInList(self): collection = [params.SITE_ID,] geomData = self._runConstraintTest(self.siteIdKey, 'in', collection) for record in geomData: self.assertIn(record.getAttribute(self.siteIdKey), collection) def testGetDataWithInGenerator(self): collection = (params.SITE_ID,) generator = (item for item in collection) geomData = self._runConstraintTest(self.siteIdKey, 'in', generator) for record in geomData: self.assertIn(record.getAttribute(self.siteIdKey), collection) def testGetDataWithNotInList(self): collection = [params.SITE_ID,] geomData = self._runConstraintTest(self.siteIdKey, 'not in', collection) for record in geomData: self.assertNotIn(record.getAttribute(self.siteIdKey), collection) def testGetDataWithInvalidConstraintTypeThrowsException(self): with self.assertRaises(ValueError): self._runConstraintTest(self.siteIdKey, 'junk', params.SITE_ID) def testGetDataWithInvalidConstraintValueThrowsException(self): with self.assertRaises(TypeError): self._runConstraintTest(self.siteIdKey, '=', {}) def testGetDataWithEmptyInConstraintThrowsException(self): with self.assertRaises(ValueError): self._runConstraintTest(self.siteIdKey, 'in', [])
true
true
1c2c16d48b9a5ebedf2c92de374e40386c398822
6,268
py
Python
core/ook_lib.py
zdx198811/lab604-automation
f73acdce38422d9c3a0845a553efa4eebc662086
[ "MIT" ]
1
2020-10-30T15:22:20.000Z
2020-10-30T15:22:20.000Z
core/ook_lib.py
zdx198811/lab604-automation
f73acdce38422d9c3a0845a553efa4eebc662086
[ "MIT" ]
null
null
null
core/ook_lib.py
zdx198811/lab604-automation
f73acdce38422d9c3a0845a553efa4eebc662086
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Mon Jul 2 15:16:16 2018 @author: dongxucz """ import numpy as np import csv as csvlib from locale import atoi from os.path import exists # from torch.utils.data import Dataset class OOK_signal: """Create (randomly generate|load from file) or save an OOK signal. NOTE: Default OOK formating is RZ code, therefore, when external ref is given (data_ref or load_file), any sample beyond {0, 1} will be converted to 0 or 1 following the principle: x = 0 if sample_value <= 0 1 if sample_value > 0 In other words, given a ref signal of NRZ code, this automatically converts to default RZ code, stored in OOK_signal.data_bits Use OOK_signal.nrz() to get an NRZ code of data_bits. """ def __init__(self, data_len = 0, data_ref=[], load_file = ''): ''' Arguments: data_len - number of symbols to generate/load data_ref - a list containing reference symbols to copy from load_file - data file's name to copy from (should be xx.csv) ''' if (load_file!=''): # load data from disk if exists(load_file): if (load_file[-3:]!='csv'): raise ValueError('OOK_signal: only .csv is supported') else: with open(load_file, 'r') as f: #self.data_bits=np.array([atoi(item[0]) for item in csvlib.reader(f)]) self.data_bits=np.sign([np.max((0,atoi(item[0]))) for item in csvlib.reader(f)]) if (data_len==0)|((data_len!=0)&(data_len>len(self.data_bits))): self.data_len = len(self.data_bits) if data_len!=0: print('WARNING: load_file has less samples ({0}) than required ({1})'.format(self.data_len, data_len)) else: self.data_bits=self.data_bits[0:data_len] self.data_len = data_len else: raise ValueError('Class OOK_signal: {0} does not exist'.format(load_file)) else: # copy from reference or generate randomly if (len(data_ref) == 0): self.data_len = data_len self.data_bits = np.random.randint(2,size=data_len) else: if (data_len==0)|((data_len!=0)&(data_len>len(data_ref))): self.data_bits = np.sign([np.max((0,item)) for item in data_ref]) self.data_len = len(data_ref) if (data_len != 0): print('WARNING: data_ref has less samples ({0}) than required ({1})'.format(self.data_len, data_len)) else: self.data_bits = np.sign([np.max((0,item)) for item in data_ref[0:data_len]]) self.data_len = data_len def append(self, a): """ Append more data to the data_bits Arguments: a - can be another OOK_signal, or an 1d numpy array, or a list. Note that range of a's contents is not limited. Negtive values will be interprated as 0, positive as 1. """ #print(a.__class__, self.__class__) if (a.__class__ == np.ndarray or a.__class__ == list): a_ook = np.sign([np.max((0,item)) for item in a]) #elif (a.__class__== self.__class__): else: a_ook = a.data_bits self.data_bits = np.concatenate((self.data_bits, a_ook),axis=0) self.data_len = len(self.data_bits) def take(self, s): """ take a slice out of the data_bits Arguments: s - slice object. Example: OOK_signal.slicer(slice(0,10,2)) will output a numpy array containing OOK_signal's data_bits[0, 2, 4, 6, 8] elements. """ return self.data_bits[s] def nrz(self, dtype = int): temp_array = np.sign( self.data_bits - 0.5 ) return temp_array.astype(dtype) def data_bits_astype(self, dtype): return self.data_bits.astype(dtype) def save_to_csv(self, csv_name=None): if csv_name==None: raise ValueError('OOK_signal::save_to_csv() - please provide a file name') else: with open(csv_name,'w', newline='') as f: writer = csvlib.writer(f) for item in self.data_bits: writer.writerow([item]) #class nn_pd_dataset(Dataset): # """the customized data reader for Pytorch's DataLoader utility. # Inherited from the abstract class 'Dataset' with overided __len__() # and __getitem__() methods. Takes padas dataset as inputs. # """ # def __init__(self, pd_dataframe_x, pd_dataframe_y, transform=None): # """ # Args: # pd_dataframe_x/y, pandas dataframe of feature/label. # """ # self.pd_dataframe_x = pd_dataframe_x # self.pd_dataframe_y = pd_dataframe_y # self.transform = transform # # def __len__(self): # return self.pd_dataframe_x.shape[0] # # def __getitem__(self, idx): # sample = {'features':self.pd_dataframe_x.iloc[idx].get_values(), # 'labels':self.pd_dataframe_y.iloc[idx]} # return sample # getitem = __getitem__ # n_sample = __len__ # #class nn_ndarray_dataset(Dataset): # """the customized data reader for Pytorch's DataLoader utility. # Inherited from the abstract class 'Dataset' with overided __len__() # and __getitem__() methods. Takes ndarray as inputs. # """ # def __init__(self, dataframe_x, dataframe_y, transform=None): # """ # Args: # pd_dataframe_x/y, pandas dataframe of feature/label. # """ # self.dataframe_x = dataframe_x # self.dataframe_y = dataframe_y # self.transform = transform # # def __len__(self): # return self.dataframe_x.shape[0] # # def __getitem__(self, idx): # sample = {'features':self.dataframe_x[idx], # 'labels':self.dataframe_y[idx]} # return sample # getitem = __getitem__ # n_sample = __len__
40.701299
130
0.57275
import numpy as np import csv as csvlib from locale import atoi from os.path import exists class OOK_signal: def __init__(self, data_len = 0, data_ref=[], load_file = ''): if (load_file!=''): if exists(load_file): if (load_file[-3:]!='csv'): raise ValueError('OOK_signal: only .csv is supported') else: with open(load_file, 'r') as f: self.data_bits=np.sign([np.max((0,atoi(item[0]))) for item in csvlib.reader(f)]) if (data_len==0)|((data_len!=0)&(data_len>len(self.data_bits))): self.data_len = len(self.data_bits) if data_len!=0: print('WARNING: load_file has less samples ({0}) than required ({1})'.format(self.data_len, data_len)) else: self.data_bits=self.data_bits[0:data_len] self.data_len = data_len else: raise ValueError('Class OOK_signal: {0} does not exist'.format(load_file)) else: if (len(data_ref) == 0): self.data_len = data_len self.data_bits = np.random.randint(2,size=data_len) else: if (data_len==0)|((data_len!=0)&(data_len>len(data_ref))): self.data_bits = np.sign([np.max((0,item)) for item in data_ref]) self.data_len = len(data_ref) if (data_len != 0): print('WARNING: data_ref has less samples ({0}) than required ({1})'.format(self.data_len, data_len)) else: self.data_bits = np.sign([np.max((0,item)) for item in data_ref[0:data_len]]) self.data_len = data_len def append(self, a): if (a.__class__ == np.ndarray or a.__class__ == list): a_ook = np.sign([np.max((0,item)) for item in a]) else: a_ook = a.data_bits self.data_bits = np.concatenate((self.data_bits, a_ook),axis=0) self.data_len = len(self.data_bits) def take(self, s): return self.data_bits[s] def nrz(self, dtype = int): temp_array = np.sign( self.data_bits - 0.5 ) return temp_array.astype(dtype) def data_bits_astype(self, dtype): return self.data_bits.astype(dtype) def save_to_csv(self, csv_name=None): if csv_name==None: raise ValueError('OOK_signal::save_to_csv() - please provide a file name') else: with open(csv_name,'w', newline='') as f: writer = csvlib.writer(f) for item in self.data_bits: writer.writerow([item]) # Inherited from the abstract class 'Dataset' with overided __len__() # and __getitem__() methods. Takes padas dataset as inputs. # """ # def __init__(self, pd_dataframe_x, pd_dataframe_y, transform=None): # """ # Args: # pd_dataframe_x/y, pandas dataframe of feature/label. # """ # self.pd_dataframe_x = pd_dataframe_x # self.pd_dataframe_y = pd_dataframe_y # self.transform = transform # # def __len__(self): # return self.pd_dataframe_x.shape[0] # # def __getitem__(self, idx): # sample = {'features':self.pd_dataframe_x.iloc[idx].get_values(), # 'labels':self.pd_dataframe_y.iloc[idx]} # return sample # getitem = __getitem__ # n_sample = __len__ # #class nn_ndarray_dataset(Dataset): # """the customized data reader for Pytorch's DataLoader utility. # Inherited from the abstract class 'Dataset' with overided __len__() # and __getitem__() methods. Takes ndarray as inputs. # """ # Args: # pd_dataframe_x/y, pandas dataframe of feature/label. # """
true
true
1c2c17960aa80e454059311a01f72e7d705ed67e
279,211
py
Python
tensorflow/contrib/metrics/python/ops/metric_ops_test.py
AudioStreamTV/tensorflow
7277ed8ed2da84b227295216632dec52a81f63b3
[ "Apache-2.0" ]
null
null
null
tensorflow/contrib/metrics/python/ops/metric_ops_test.py
AudioStreamTV/tensorflow
7277ed8ed2da84b227295216632dec52a81f63b3
[ "Apache-2.0" ]
null
null
null
tensorflow/contrib/metrics/python/ops/metric_ops_test.py
AudioStreamTV/tensorflow
7277ed8ed2da84b227295216632dec52a81f63b3
[ "Apache-2.0" ]
null
null
null
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for metric_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.contrib import metrics as metrics_lib from tensorflow.contrib.metrics.python.ops import metric_ops from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes as dtypes_lib from tensorflow.python.framework import errors_impl from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import array_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test NAN = float('nan') metrics = metrics_lib def _enqueue_vector(sess, queue, values, shape=None): if not shape: shape = (1, len(values)) dtype = queue.dtypes[0] sess.run( queue.enqueue(constant_op.constant(values, dtype=dtype, shape=shape))) def _binary_2d_label_to_sparse_value(labels): """Convert dense 2D binary indicator tensor to sparse tensor. Only 1 values in `labels` are included in result. Args: labels: Dense 2D binary indicator tensor. Returns: `SparseTensorValue` whose values are indices along the last dimension of `labels`. """ indices = [] values = [] batch = 0 for row in labels: label = 0 xi = 0 for x in row: if x == 1: indices.append([batch, xi]) values.append(label) xi += 1 else: assert x == 0 label += 1 batch += 1 shape = [len(labels), len(labels[0])] return sparse_tensor.SparseTensorValue( np.array(indices, np.int64), np.array(values, np.int64), np.array(shape, np.int64)) def _binary_2d_label_to_sparse(labels): """Convert dense 2D binary indicator tensor to sparse tensor. Only 1 values in `labels` are included in result. Args: labels: Dense 2D binary indicator tensor. Returns: `SparseTensor` whose values are indices along the last dimension of `labels`. """ return sparse_tensor.SparseTensor.from_value( _binary_2d_label_to_sparse_value(labels)) def _binary_3d_label_to_sparse_value(labels): """Convert dense 3D binary indicator tensor to sparse tensor. Only 1 values in `labels` are included in result. Args: labels: Dense 2D binary indicator tensor. Returns: `SparseTensorValue` whose values are indices along the last dimension of `labels`. """ indices = [] values = [] for d0, labels_d0 in enumerate(labels): for d1, labels_d1 in enumerate(labels_d0): d2 = 0 for class_id, label in enumerate(labels_d1): if label == 1: values.append(class_id) indices.append([d0, d1, d2]) d2 += 1 else: assert label == 0 shape = [len(labels), len(labels[0]), len(labels[0][0])] return sparse_tensor.SparseTensorValue( np.array(indices, np.int64), np.array(values, np.int64), np.array(shape, np.int64)) def _binary_3d_label_to_sparse(labels): """Convert dense 3D binary indicator tensor to sparse tensor. Only 1 values in `labels` are included in result. Args: labels: Dense 2D binary indicator tensor. Returns: `SparseTensor` whose values are indices along the last dimension of `labels`. """ return sparse_tensor.SparseTensor.from_value( _binary_3d_label_to_sparse_value(labels)) def _assert_nan(test_case, actual): test_case.assertTrue(math.isnan(actual), 'Expected NAN, got %s.' % actual) def _assert_metric_variables(test_case, expected): test_case.assertEquals( set(expected), set(v.name for v in variables.local_variables())) test_case.assertEquals( set(expected), set(v.name for v in ops.get_collection(ops.GraphKeys.METRIC_VARIABLES))) class StreamingMeanTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_mean(array_ops.ones([4, 3])) _assert_metric_variables(self, ('mean/count:0', 'mean/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_mean( array_ops.ones([4, 3]), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean( array_ops.ones([4, 3]), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testBasic(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() mean, update_op = metrics.streaming_mean(values) sess.run(variables.local_variables_initializer()) for _ in range(4): sess.run(update_op) self.assertAlmostEqual(1.65, sess.run(mean), 5) def testUpdateOpsReturnsCurrentValue(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() mean, update_op = metrics.streaming_mean(values) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, sess.run(update_op), 5) self.assertAlmostEqual(1.475, sess.run(update_op), 5) self.assertAlmostEqual(12.4 / 6.0, sess.run(update_op), 5) self.assertAlmostEqual(1.65, sess.run(update_op), 5) self.assertAlmostEqual(1.65, sess.run(mean), 5) def test1dWeightedValues(self): with self.test_session() as sess: # Create the queue that populates the values. values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() # Create the queue that populates the weighted labels. weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, weights_queue, [1]) _enqueue_vector(sess, weights_queue, [0]) _enqueue_vector(sess, weights_queue, [0]) _enqueue_vector(sess, weights_queue, [1]) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean(values, weights) variables.local_variables_initializer().run() for _ in range(4): update_op.eval() self.assertAlmostEqual((0 + 1 - 3.2 + 4.0) / 4.0, mean.eval(), 5) def test1dWeightedValues_placeholders(self): with self.test_session() as sess: # Create the queue that populates the values. feed_values = ((0, 1), (-4.2, 9.1), (6.5, 0), (-3.2, 4.0)) values = array_ops.placeholder(dtype=dtypes_lib.float32) # Create the queue that populates the weighted labels. weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1,)) _enqueue_vector(sess, weights_queue, 1, shape=(1,)) _enqueue_vector(sess, weights_queue, 0, shape=(1,)) _enqueue_vector(sess, weights_queue, 0, shape=(1,)) _enqueue_vector(sess, weights_queue, 1, shape=(1,)) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean(values, weights) variables.local_variables_initializer().run() for i in range(4): update_op.eval(feed_dict={values: feed_values[i]}) self.assertAlmostEqual((0 + 1 - 3.2 + 4.0) / 4.0, mean.eval(), 5) def test2dWeightedValues(self): with self.test_session() as sess: # Create the queue that populates the values. values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() # Create the queue that populates the weighted labels. weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, weights_queue, [1, 1]) _enqueue_vector(sess, weights_queue, [1, 0]) _enqueue_vector(sess, weights_queue, [0, 1]) _enqueue_vector(sess, weights_queue, [0, 0]) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean(values, weights) variables.local_variables_initializer().run() for _ in range(4): update_op.eval() self.assertAlmostEqual((0 + 1 - 4.2 + 0) / 4.0, mean.eval(), 5) def test2dWeightedValues_placeholders(self): with self.test_session() as sess: # Create the queue that populates the values. feed_values = ((0, 1), (-4.2, 9.1), (6.5, 0), (-3.2, 4.0)) values = array_ops.placeholder(dtype=dtypes_lib.float32) # Create the queue that populates the weighted labels. weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(2,)) _enqueue_vector(sess, weights_queue, [1, 1], shape=(2,)) _enqueue_vector(sess, weights_queue, [1, 0], shape=(2,)) _enqueue_vector(sess, weights_queue, [0, 1], shape=(2,)) _enqueue_vector(sess, weights_queue, [0, 0], shape=(2,)) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean(values, weights) variables.local_variables_initializer().run() for i in range(4): update_op.eval(feed_dict={values: feed_values[i]}) self.assertAlmostEqual((0 + 1 - 4.2 + 0) / 4.0, mean.eval(), 5) class StreamingMeanTensorTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_mean_tensor(array_ops.ones([4, 3])) _assert_metric_variables(self, ('mean/total_tensor:0', 'mean/count_tensor:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_mean_tensor( array_ops.ones([4, 3]), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean_tensor( array_ops.ones([4, 3]), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testBasic(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() mean, update_op = metrics.streaming_mean_tensor(values) sess.run(variables.local_variables_initializer()) for _ in range(4): sess.run(update_op) self.assertAllClose([[-0.9 / 4., 3.525]], sess.run(mean)) def testMultiDimensional(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(2, 2, 2)) _enqueue_vector( sess, values_queue, [[[1, 2], [1, 2]], [[1, 2], [1, 2]]], shape=(2, 2, 2)) _enqueue_vector( sess, values_queue, [[[1, 2], [1, 2]], [[3, 4], [9, 10]]], shape=(2, 2, 2)) values = values_queue.dequeue() mean, update_op = metrics.streaming_mean_tensor(values) sess.run(variables.local_variables_initializer()) for _ in range(2): sess.run(update_op) self.assertAllClose([[[1, 2], [1, 2]], [[2, 3], [5, 6]]], sess.run(mean)) def testUpdateOpsReturnsCurrentValue(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() mean, update_op = metrics.streaming_mean_tensor(values) sess.run(variables.local_variables_initializer()) self.assertAllClose([[0, 1]], sess.run(update_op), 5) self.assertAllClose([[-2.1, 5.05]], sess.run(update_op), 5) self.assertAllClose([[2.3 / 3., 10.1 / 3.]], sess.run(update_op), 5) self.assertAllClose([[-0.9 / 4., 3.525]], sess.run(update_op), 5) self.assertAllClose([[-0.9 / 4., 3.525]], sess.run(mean), 5) def testWeighted1d(self): with self.test_session() as sess: # Create the queue that populates the values. values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() # Create the queue that populates the weights. weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, weights_queue, [[1]]) _enqueue_vector(sess, weights_queue, [[0]]) _enqueue_vector(sess, weights_queue, [[1]]) _enqueue_vector(sess, weights_queue, [[0]]) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean_tensor(values, weights) sess.run(variables.local_variables_initializer()) for _ in range(4): sess.run(update_op) self.assertAllClose([[3.25, 0.5]], sess.run(mean), 5) def testWeighted2d_1(self): with self.test_session() as sess: # Create the queue that populates the values. values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() # Create the queue that populates the weights. weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, weights_queue, [1, 1]) _enqueue_vector(sess, weights_queue, [1, 0]) _enqueue_vector(sess, weights_queue, [0, 1]) _enqueue_vector(sess, weights_queue, [0, 0]) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean_tensor(values, weights) sess.run(variables.local_variables_initializer()) for _ in range(4): sess.run(update_op) self.assertAllClose([[-2.1, 0.5]], sess.run(mean), 5) def testWeighted2d_2(self): with self.test_session() as sess: # Create the queue that populates the values. values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() # Create the queue that populates the weights. weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, weights_queue, [0, 1]) _enqueue_vector(sess, weights_queue, [0, 0]) _enqueue_vector(sess, weights_queue, [0, 1]) _enqueue_vector(sess, weights_queue, [0, 0]) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean_tensor(values, weights) sess.run(variables.local_variables_initializer()) for _ in range(4): sess.run(update_op) self.assertAllClose([[0, 0.5]], sess.run(mean), 5) class StreamingAccuracyTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_accuracy( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), name='my_accuracy') _assert_metric_variables(self, ('my_accuracy/count:0', 'my_accuracy/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_accuracy( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_accuracy( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testPredictionsAndLabelsOfDifferentSizeRaisesValueError(self): predictions = array_ops.ones((10, 3)) labels = array_ops.ones((10, 4)) with self.assertRaises(ValueError): metrics.streaming_accuracy(predictions, labels) def testPredictionsAndWeightsOfDifferentSizeRaisesValueError(self): predictions = array_ops.ones((10, 3)) labels = array_ops.ones((10, 3)) weights = array_ops.ones((9, 3)) with self.assertRaises(ValueError): metrics.streaming_accuracy(predictions, labels, weights) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=3, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=3, dtype=dtypes_lib.int64, seed=2) accuracy, update_op = metrics.streaming_accuracy(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_accuracy = accuracy.eval() for _ in range(10): self.assertEqual(initial_accuracy, accuracy.eval()) def testMultipleUpdates(self): with self.test_session() as sess: # Create the queue that populates the predictions. preds_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [2]) _enqueue_vector(sess, preds_queue, [1]) predictions = preds_queue.dequeue() # Create the queue that populates the labels. labels_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [2]) labels = labels_queue.dequeue() accuracy, update_op = metrics.streaming_accuracy(predictions, labels) sess.run(variables.local_variables_initializer()) for _ in xrange(3): sess.run(update_op) self.assertEqual(0.5, sess.run(update_op)) self.assertEqual(0.5, accuracy.eval()) def testEffectivelyEquivalentSizes(self): predictions = array_ops.ones((40, 1)) labels = array_ops.ones((40,)) with self.test_session() as sess: accuracy, update_op = metrics.streaming_accuracy(predictions, labels) sess.run(variables.local_variables_initializer()) self.assertEqual(1.0, update_op.eval()) self.assertEqual(1.0, accuracy.eval()) def testEffectivelyEquivalentSizesWithStaicShapedWeight(self): predictions = ops.convert_to_tensor([1, 1, 1]) # shape 3, labels = array_ops.expand_dims(ops.convert_to_tensor([1, 0, 0]), 1) # shape 3, 1 weights = array_ops.expand_dims(ops.convert_to_tensor([100, 1, 1]), 1) # shape 3, 1 with self.test_session() as sess: accuracy, update_op = metrics.streaming_accuracy(predictions, labels, weights) sess.run(variables.local_variables_initializer()) # if streaming_accuracy does not flatten the weight, accuracy would be # 0.33333334 due to an intended broadcast of weight. Due to flattening, # it will be higher than .95 self.assertGreater(update_op.eval(), .95) self.assertGreater(accuracy.eval(), .95) def testEffectivelyEquivalentSizesWithDynamicallyShapedWeight(self): predictions = ops.convert_to_tensor([1, 1, 1]) # shape 3, labels = array_ops.expand_dims(ops.convert_to_tensor([1, 0, 0]), 1) # shape 3, 1 weights = [[100], [1], [1]] # shape 3, 1 weights_placeholder = array_ops.placeholder( dtype=dtypes_lib.int32, name='weights') feed_dict = {weights_placeholder: weights} with self.test_session() as sess: accuracy, update_op = metrics.streaming_accuracy(predictions, labels, weights_placeholder) sess.run(variables.local_variables_initializer()) # if streaming_accuracy does not flatten the weight, accuracy would be # 0.33333334 due to an intended broadcast of weight. Due to flattening, # it will be higher than .95 self.assertGreater(update_op.eval(feed_dict=feed_dict), .95) self.assertGreater(accuracy.eval(feed_dict=feed_dict), .95) def testMultipleUpdatesWithWeightedValues(self): with self.test_session() as sess: # Create the queue that populates the predictions. preds_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [2]) _enqueue_vector(sess, preds_queue, [1]) predictions = preds_queue.dequeue() # Create the queue that populates the labels. labels_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [2]) labels = labels_queue.dequeue() # Create the queue that populates the weights. weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.int64, shapes=(1, 1)) _enqueue_vector(sess, weights_queue, [1]) _enqueue_vector(sess, weights_queue, [1]) _enqueue_vector(sess, weights_queue, [0]) _enqueue_vector(sess, weights_queue, [0]) weights = weights_queue.dequeue() accuracy, update_op = metrics.streaming_accuracy(predictions, labels, weights) sess.run(variables.local_variables_initializer()) for _ in xrange(3): sess.run(update_op) self.assertEqual(1.0, sess.run(update_op)) self.assertEqual(1.0, accuracy.eval()) class StreamingTruePositivesTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_true_positives((0, 1, 0), (0, 1, 1)) _assert_metric_variables(self, ('true_positives/count:0',)) def testUnweighted(self): for expand_predictions in [True, False]: for expand_labels in [True, False]: for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) if expand_predictions: predictions = array_ops.expand_dims(predictions, 2) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) if expand_labels: labels = array_ops.expand_dims(labels, 2) tp, tp_update_op = metrics.streaming_true_positives( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, tp.eval()) self.assertEqual(1, tp_update_op.eval()) self.assertEqual(1, tp.eval()) def testWeighted(self): for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) tp, tp_update_op = metrics.streaming_true_positives( predictions, labels, weights=37.0) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, tp.eval()) self.assertEqual(37.0, tp_update_op.eval()) self.assertEqual(37.0, tp.eval()) class StreamingFalseNegativesTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_negatives((0, 1, 0), (0, 1, 1)) _assert_metric_variables(self, ('false_negatives/count:0',)) def testUnweighted(self): for expand_predictions in [True, False]: for expand_labels in [True, False]: for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) if expand_predictions: predictions = array_ops.expand_dims(predictions, 2) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) if expand_labels: labels = array_ops.expand_dims(labels, 2) fn, fn_update_op = metrics.streaming_false_negatives( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, fn.eval()) self.assertEqual(2, fn_update_op.eval()) self.assertEqual(2, fn.eval()) def testWeighted(self): for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) fn, fn_update_op = metrics.streaming_false_negatives( predictions, labels, weights=((3.0,), (5.0,), (7.0,))) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, fn.eval()) self.assertEqual(8.0, fn_update_op.eval()) self.assertEqual(8.0, fn.eval()) class StreamingFalsePositivesTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_positives((0, 1, 0), (0, 1, 1)) _assert_metric_variables(self, ('false_positives/count:0',)) def testUnweighted(self): for expand_predictions in [True, False]: for expand_labels in [True, False]: for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) if expand_predictions: predictions = array_ops.expand_dims(predictions, 2) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) if expand_labels: labels = array_ops.expand_dims(labels, 2) fp, fp_update_op = metrics.streaming_false_positives( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, fp.eval()) self.assertEqual(4, fp_update_op.eval()) self.assertEqual(4, fp.eval()) def testWeighted(self): for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) fp, fp_update_op = metrics.streaming_false_positives( predictions, labels, weights=((1.0, 2.0, 3.0, 5.0), (7.0, 11.0, 13.0, 17.0), (19.0, 23.0, 29.0, 31.0))) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, fp.eval()) self.assertEqual(42.0, fp_update_op.eval()) self.assertEqual(42.0, fp.eval()) class StreamingTrueNegativesTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_true_negatives((0, 1, 0), (0, 1, 1)) _assert_metric_variables(self, ('true_negatives/count:0',)) def testUnweighted(self): for expand_predictions in [True, False]: for expand_labels in [True, False]: for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) if expand_predictions: predictions = array_ops.expand_dims(predictions, 2) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) if expand_labels: labels = array_ops.expand_dims(labels, 2) tn, tn_update_op = metrics.streaming_true_negatives( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, tn.eval()) self.assertEqual(5, tn_update_op.eval()) self.assertEqual(5, tn.eval()) def testWeighted(self): for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) tn, tn_update_op = metrics.streaming_true_negatives( predictions, labels, weights=((0.0, 2.0, 3.0, 5.0),)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, tn.eval()) self.assertEqual(15.0, tn_update_op.eval()) self.assertEqual(15.0, tn.eval()) class StreamingTruePositivesAtThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_true_positives_at_thresholds( (0.0, 1.0, 0.0), (0, 1, 1), thresholds=(0.15, 0.5, 0.85)) _assert_metric_variables(self, ('true_positives:0',)) def testUnweighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) tp, tp_update_op = metrics.streaming_true_positives_at_thresholds( predictions, labels, thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0, 0, 0), tp.eval()) self.assertAllEqual((3, 1, 0), tp_update_op.eval()) self.assertAllEqual((3, 1, 0), tp.eval()) def testWeighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) tp, tp_update_op = metrics.streaming_true_positives_at_thresholds( predictions, labels, weights=37.0, thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0.0, 0.0, 0.0), tp.eval()) self.assertAllEqual((111.0, 37.0, 0.0), tp_update_op.eval()) self.assertAllEqual((111.0, 37.0, 0.0), tp.eval()) class StreamingFalseNegativesAtThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_negatives_at_thresholds( (0.0, 1.0, 0.0), (0, 1, 1), thresholds=( 0.15, 0.5, 0.85, )) _assert_metric_variables(self, ('false_negatives:0',)) def testUnweighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) fn, fn_update_op = metrics.streaming_false_negatives_at_thresholds( predictions, labels, thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0, 0, 0), fn.eval()) self.assertAllEqual((0, 2, 3), fn_update_op.eval()) self.assertAllEqual((0, 2, 3), fn.eval()) def testWeighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) fn, fn_update_op = metrics.streaming_false_negatives_at_thresholds( predictions, labels, weights=((3.0,), (5.0,), (7.0,)), thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0.0, 0.0, 0.0), fn.eval()) self.assertAllEqual((0.0, 8.0, 11.0), fn_update_op.eval()) self.assertAllEqual((0.0, 8.0, 11.0), fn.eval()) class StreamingFalsePositivesAtThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_positives_at_thresholds( (0.0, 1.0, 0.0), (0, 1, 1), thresholds=(0.15, 0.5, 0.85)) _assert_metric_variables(self, ('false_positives:0',)) def testUnweighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) fp, fp_update_op = metrics.streaming_false_positives_at_thresholds( predictions, labels, thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0, 0, 0), fp.eval()) self.assertAllEqual((7, 4, 2), fp_update_op.eval()) self.assertAllEqual((7, 4, 2), fp.eval()) def testWeighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) fp, fp_update_op = metrics.streaming_false_positives_at_thresholds( predictions, labels, weights=((1.0, 2.0, 3.0, 5.0), (7.0, 11.0, 13.0, 17.0), (19.0, 23.0, 29.0, 31.0)), thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0.0, 0.0, 0.0), fp.eval()) self.assertAllEqual((125.0, 42.0, 12.0), fp_update_op.eval()) self.assertAllEqual((125.0, 42.0, 12.0), fp.eval()) class StreamingTrueNegativesAtThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_true_negatives_at_thresholds( (0.0, 1.0, 0.0), (0, 1, 1), thresholds=(0.15, 0.5, 0.85)) _assert_metric_variables(self, ('true_negatives:0',)) def testUnweighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) tn, tn_update_op = metrics.streaming_true_negatives_at_thresholds( predictions, labels, thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0, 0, 0), tn.eval()) self.assertAllEqual((2, 5, 7), tn_update_op.eval()) self.assertAllEqual((2, 5, 7), tn.eval()) def testWeighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) tn, tn_update_op = metrics.streaming_true_negatives_at_thresholds( predictions, labels, weights=((0.0, 2.0, 3.0, 5.0),), thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0.0, 0.0, 0.0), tn.eval()) self.assertAllEqual((5.0, 15.0, 23.0), tn_update_op.eval()) self.assertAllEqual((5.0, 15.0, 23.0), tn.eval()) class StreamingPrecisionTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables(self, ('precision/false_positives/count:0', 'precision/true_positives/count:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) precision, update_op = metrics.streaming_precision(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_precision = precision.eval() for _ in range(10): self.assertEqual(initial_precision, precision.eval()) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs) labels = constant_op.constant(inputs) precision, update_op = metrics.streaming_precision(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(1, sess.run(update_op)) self.assertAlmostEqual(1, precision.eval()) def testSomeCorrect(self): predictions = constant_op.constant([1, 0, 1, 0], shape=(1, 4)) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) precision, update_op = metrics.streaming_precision(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, update_op.eval()) self.assertAlmostEqual(0.5, precision.eval()) def testWeighted1d(self): predictions = constant_op.constant([[1, 0, 1, 0], [1, 0, 1, 0]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) precision, update_op = metrics.streaming_precision( predictions, labels, weights=constant_op.constant([[2], [5]])) with self.test_session(): variables.local_variables_initializer().run() weighted_tp = 2.0 + 5.0 weighted_positives = (2.0 + 2.0) + (5.0 + 5.0) expected_precision = weighted_tp / weighted_positives self.assertAlmostEqual(expected_precision, update_op.eval()) self.assertAlmostEqual(expected_precision, precision.eval()) def testWeighted1d_placeholders(self): predictions = array_ops.placeholder(dtype=dtypes_lib.float32) labels = array_ops.placeholder(dtype=dtypes_lib.float32) feed_dict = { predictions: ((1, 0, 1, 0), (1, 0, 1, 0)), labels: ((0, 1, 1, 0), (1, 0, 0, 1)) } precision, update_op = metrics.streaming_precision( predictions, labels, weights=constant_op.constant([[2], [5]])) with self.test_session(): variables.local_variables_initializer().run() weighted_tp = 2.0 + 5.0 weighted_positives = (2.0 + 2.0) + (5.0 + 5.0) expected_precision = weighted_tp / weighted_positives self.assertAlmostEqual( expected_precision, update_op.eval(feed_dict=feed_dict)) self.assertAlmostEqual( expected_precision, precision.eval(feed_dict=feed_dict)) def testWeighted2d(self): predictions = constant_op.constant([[1, 0, 1, 0], [1, 0, 1, 0]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) precision, update_op = metrics.streaming_precision( predictions, labels, weights=constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1]])) with self.test_session(): variables.local_variables_initializer().run() weighted_tp = 3.0 + 4.0 weighted_positives = (1.0 + 3.0) + (4.0 + 2.0) expected_precision = weighted_tp / weighted_positives self.assertAlmostEqual(expected_precision, update_op.eval()) self.assertAlmostEqual(expected_precision, precision.eval()) def testWeighted2d_placeholders(self): predictions = array_ops.placeholder(dtype=dtypes_lib.float32) labels = array_ops.placeholder(dtype=dtypes_lib.float32) feed_dict = { predictions: ((1, 0, 1, 0), (1, 0, 1, 0)), labels: ((0, 1, 1, 0), (1, 0, 0, 1)) } precision, update_op = metrics.streaming_precision( predictions, labels, weights=constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1]])) with self.test_session(): variables.local_variables_initializer().run() weighted_tp = 3.0 + 4.0 weighted_positives = (1.0 + 3.0) + (4.0 + 2.0) expected_precision = weighted_tp / weighted_positives self.assertAlmostEqual( expected_precision, update_op.eval(feed_dict=feed_dict)) self.assertAlmostEqual( expected_precision, precision.eval(feed_dict=feed_dict)) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs) labels = constant_op.constant(1 - inputs) precision, update_op = metrics.streaming_precision(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(0, precision.eval()) def testZeroTrueAndFalsePositivesGivesZeroPrecision(self): predictions = constant_op.constant([0, 0, 0, 0]) labels = constant_op.constant([0, 0, 0, 0]) precision, update_op = metrics.streaming_precision(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0.0, precision.eval()) class StreamingRecallTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_recall( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables( self, ('recall/false_negatives/count:0', 'recall/true_positives/count:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_recall( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_recall( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) recall, update_op = metrics.streaming_recall(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_recall = recall.eval() for _ in range(10): self.assertEqual(initial_recall, recall.eval()) def testAllCorrect(self): np_inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(np_inputs) labels = constant_op.constant(np_inputs) recall, update_op = metrics.streaming_recall(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(1, recall.eval()) def testSomeCorrect(self): predictions = constant_op.constant([1, 0, 1, 0], shape=(1, 4)) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) recall, update_op = metrics.streaming_recall(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, update_op.eval()) self.assertAlmostEqual(0.5, recall.eval()) def testWeighted1d(self): predictions = constant_op.constant([[1, 0, 1, 0], [0, 1, 0, 1]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) weights = constant_op.constant([[2], [5]]) recall, update_op = metrics.streaming_recall( predictions, labels, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) weighted_tp = 2.0 + 5.0 weighted_t = (2.0 + 2.0) + (5.0 + 5.0) expected_precision = weighted_tp / weighted_t self.assertAlmostEqual(expected_precision, update_op.eval()) self.assertAlmostEqual(expected_precision, recall.eval()) def testWeighted2d(self): predictions = constant_op.constant([[1, 0, 1, 0], [0, 1, 0, 1]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) weights = constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1]]) recall, update_op = metrics.streaming_recall( predictions, labels, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) weighted_tp = 3.0 + 1.0 weighted_t = (2.0 + 3.0) + (4.0 + 1.0) expected_precision = weighted_tp / weighted_t self.assertAlmostEqual(expected_precision, update_op.eval()) self.assertAlmostEqual(expected_precision, recall.eval()) def testAllIncorrect(self): np_inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(np_inputs) labels = constant_op.constant(1 - np_inputs) recall, update_op = metrics.streaming_recall(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, recall.eval()) def testZeroTruePositivesAndFalseNegativesGivesZeroRecall(self): predictions = array_ops.zeros((1, 4)) labels = array_ops.zeros((1, 4)) recall, update_op = metrics.streaming_recall(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, recall.eval()) class StreamingFPRTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_positive_rate( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables(self, ('false_positive_rate/false_positives/count:0', 'false_positive_rate/true_negatives/count:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_false_positive_rate( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_false_positive_rate( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) fpr, update_op = metrics.streaming_false_positive_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_fpr = fpr.eval() for _ in range(10): self.assertEqual(initial_fpr, fpr.eval()) def testAllCorrect(self): np_inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(np_inputs) labels = constant_op.constant(np_inputs) fpr, update_op = metrics.streaming_false_positive_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, fpr.eval()) def testSomeCorrect(self): predictions = constant_op.constant([1, 0, 1, 0], shape=(1, 4)) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) fpr, update_op = metrics.streaming_false_positive_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, update_op.eval()) self.assertAlmostEqual(0.5, fpr.eval()) def testWeighted1d(self): predictions = constant_op.constant([[1, 0, 1, 0], [0, 1, 0, 1]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) weights = constant_op.constant([[2], [5]]) fpr, update_op = metrics.streaming_false_positive_rate( predictions, labels, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) weighted_fp = 2.0 + 5.0 weighted_f = (2.0 + 2.0) + (5.0 + 5.0) expected_fpr = weighted_fp / weighted_f self.assertAlmostEqual(expected_fpr, update_op.eval()) self.assertAlmostEqual(expected_fpr, fpr.eval()) def testWeighted2d(self): predictions = constant_op.constant([[1, 0, 1, 0], [0, 1, 0, 1]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) weights = constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1]]) fpr, update_op = metrics.streaming_false_positive_rate( predictions, labels, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) weighted_fp = 1.0 + 3.0 weighted_f = (1.0 + 4.0) + (2.0 + 3.0) expected_fpr = weighted_fp / weighted_f self.assertAlmostEqual(expected_fpr, update_op.eval()) self.assertAlmostEqual(expected_fpr, fpr.eval()) def testAllIncorrect(self): np_inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(np_inputs) labels = constant_op.constant(1 - np_inputs) fpr, update_op = metrics.streaming_false_positive_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(1, fpr.eval()) def testZeroFalsePositivesAndTrueNegativesGivesZeroFPR(self): predictions = array_ops.ones((1, 4)) labels = array_ops.ones((1, 4)) fpr, update_op = metrics.streaming_false_positive_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, fpr.eval()) class StreamingFNRTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_negative_rate( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables(self, ('false_negative_rate/false_negatives/count:0', 'false_negative_rate/true_positives/count:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_false_negative_rate( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_false_negative_rate( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) fnr, update_op = metrics.streaming_false_negative_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_fnr = fnr.eval() for _ in range(10): self.assertEqual(initial_fnr, fnr.eval()) def testAllCorrect(self): np_inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(np_inputs) labels = constant_op.constant(np_inputs) fnr, update_op = metrics.streaming_false_negative_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, fnr.eval()) def testSomeCorrect(self): predictions = constant_op.constant([1, 0, 1, 0], shape=(1, 4)) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) fnr, update_op = metrics.streaming_false_negative_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, update_op.eval()) self.assertAlmostEqual(0.5, fnr.eval()) def testWeighted1d(self): predictions = constant_op.constant([[1, 0, 1, 0], [0, 1, 0, 1]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) weights = constant_op.constant([[2], [5]]) fnr, update_op = metrics.streaming_false_negative_rate( predictions, labels, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) weighted_fn = 2.0 + 5.0 weighted_t = (2.0 + 2.0) + (5.0 + 5.0) expected_fnr = weighted_fn / weighted_t self.assertAlmostEqual(expected_fnr, update_op.eval()) self.assertAlmostEqual(expected_fnr, fnr.eval()) def testWeighted2d(self): predictions = constant_op.constant([[1, 0, 1, 0], [0, 1, 0, 1]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) weights = constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1]]) fnr, update_op = metrics.streaming_false_negative_rate( predictions, labels, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) weighted_fn = 2.0 + 4.0 weighted_t = (2.0 + 3.0) + (1.0 + 4.0) expected_fnr = weighted_fn / weighted_t self.assertAlmostEqual(expected_fnr, update_op.eval()) self.assertAlmostEqual(expected_fnr, fnr.eval()) def testAllIncorrect(self): np_inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(np_inputs) labels = constant_op.constant(1 - np_inputs) fnr, update_op = metrics.streaming_false_negative_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(1, fnr.eval()) def testZeroFalseNegativesAndTruePositivesGivesZeroFNR(self): predictions = array_ops.zeros((1, 4)) labels = array_ops.zeros((1, 4)) fnr, update_op = metrics.streaming_false_negative_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, fnr.eval()) class StreamingCurvePointsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metric_ops.streaming_curve_points( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables( self, ('curve_points/true_positives:0', 'curve_points/false_negatives:0', 'curve_points/false_positives:0', 'curve_points/true_negatives:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' points, _ = metric_ops.streaming_curve_points( labels=array_ops.ones((10, 1)), predictions=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [points]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metric_ops.streaming_curve_points( labels=array_ops.ones((10, 1)), predictions=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def _testValueTensorIsIdempotent(self, curve): predictions = constant_op.constant( np.random.uniform(size=(10, 3)), dtype=dtypes_lib.float32) labels = constant_op.constant( np.random.uniform(high=2, size=(10, 3)), dtype=dtypes_lib.float32) points, update_op = metric_ops.streaming_curve_points( labels, predictions=predictions, curve=curve) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) initial_points = points.eval() sess.run(update_op) self.assertAllClose(initial_points, points.eval()) def testValueTensorIsIdempotentROC(self): self._testValueTensorIsIdempotent(curve='ROC') def testValueTensorIsIdempotentPR(self): self._testValueTensorIsIdempotent(curve='PR') def _testCase(self, labels, predictions, curve, expected_points): with self.test_session() as sess: predictions_tensor = constant_op.constant( predictions, dtype=dtypes_lib.float32) labels_tensor = constant_op.constant(labels, dtype=dtypes_lib.float32) points, update_op = metric_ops.streaming_curve_points( labels=labels_tensor, predictions=predictions_tensor, num_thresholds=3, curve=curve) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAllClose(expected_points, points.eval()) def testEdgeCasesROC(self): self._testCase([[1]], [[1]], 'ROC', [[0, 1], [0, 1], [0, 0]]) self._testCase([[0]], [[0]], 'ROC', [[1, 1], [0, 1], [0, 1]]) self._testCase([[0]], [[1]], 'ROC', [[1, 1], [1, 1], [0, 1]]) self._testCase([[1]], [[0]], 'ROC', [[0, 1], [0, 0], [0, 0]]) def testManyValuesROC(self): self._testCase([[1.0, 0.0, 0.0, 1.0, 1.0, 1.0]], [[0.2, 0.3, 0.4, 0.6, 0.7, 0.8]], 'ROC', [[1.0, 1.0], [0.0, 0.75], [0.0, 0.0]]) def testEdgeCasesPR(self): self._testCase([[1]], [[1]], 'PR', [[1, 1], [1, 1], [0, 1]]) self._testCase([[0]], [[0]], 'PR', [[1, 0], [1, 1], [1, 1]]) self._testCase([[0]], [[1]], 'PR', [[1, 0], [1, 0], [1, 1]]) self._testCase([[1]], [[0]], 'PR', [[1, 1], [0, 1], [0, 1]]) def testManyValuesPR(self): self._testCase([[1.0, 0.0, 0.0, 1.0, 1.0, 1.0]], [[0.2, 0.3, 0.4, 0.6, 0.7, 0.8]], 'PR', [[1.0, 4.0 / 6.0], [0.75, 1.0], [0.0, 1.0]]) def _np_auc(predictions, labels, weights=None): """Computes the AUC explicitly using Numpy. Args: predictions: an ndarray with shape [N]. labels: an ndarray with shape [N]. weights: an ndarray with shape [N]. Returns: the area under the ROC curve. """ if weights is None: weights = np.ones(np.size(predictions)) is_positive = labels > 0 num_positives = np.sum(weights[is_positive]) num_negatives = np.sum(weights[~is_positive]) # Sort descending: inds = np.argsort(-predictions) sorted_labels = labels[inds] sorted_weights = weights[inds] is_positive = sorted_labels > 0 tp = np.cumsum(sorted_weights * is_positive) / num_positives return np.sum((sorted_weights * tp)[~is_positive]) / num_negatives class StreamingAUCTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_auc( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables(self, ('auc/true_positives:0', 'auc/false_negatives:0', 'auc/false_positives:0', 'auc/true_negatives:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_auc( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_auc( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) auc, update_op = metrics.streaming_auc(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_auc = auc.eval() for _ in range(10): self.assertAlmostEqual(initial_auc, auc.eval(), 5) def testPredictionsOutOfRange(self): with self.test_session() as sess: predictions = constant_op.constant( [1, -1, 1, -1], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) _, update_op = metrics.streaming_auc(predictions, labels) sess.run(variables.local_variables_initializer()) self.assertRaises(errors_impl.InvalidArgumentError, update_op.eval) def testAllCorrect(self): self.allCorrectAsExpected('ROC') def allCorrectAsExpected(self, curve): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) auc, update_op = metrics.streaming_auc(predictions, labels, curve=curve) sess.run(variables.local_variables_initializer()) self.assertEqual(1, sess.run(update_op)) self.assertEqual(1, auc.eval()) def testSomeCorrect(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) auc, update_op = metrics.streaming_auc(predictions, labels) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, sess.run(update_op)) self.assertAlmostEqual(0.5, auc.eval()) def testWeighted1d(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) weights = constant_op.constant([2], shape=(1, 1)) auc, update_op = metrics.streaming_auc( predictions, labels, weights=weights) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, sess.run(update_op), 5) self.assertAlmostEqual(0.5, auc.eval(), 5) def testWeighted2d(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) weights = constant_op.constant([1, 2, 3, 4], shape=(1, 4)) auc, update_op = metrics.streaming_auc( predictions, labels, weights=weights) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.7, sess.run(update_op), 5) self.assertAlmostEqual(0.7, auc.eval(), 5) def testAUCPRSpecialCase(self): with self.test_session() as sess: predictions = constant_op.constant( [0.1, 0.4, 0.35, 0.8], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 0, 1, 1], shape=(1, 4)) auc, update_op = metrics.streaming_auc(predictions, labels, curve='PR') sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.79166, sess.run(update_op), delta=1e-3) self.assertAlmostEqual(0.79166, auc.eval(), delta=1e-3) def testAnotherAUCPRSpecialCase(self): with self.test_session() as sess: predictions = constant_op.constant( [0.1, 0.4, 0.35, 0.8, 0.1, 0.135, 0.81], shape=(1, 7), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 0, 1, 0, 1, 0, 1], shape=(1, 7)) auc, update_op = metrics.streaming_auc(predictions, labels, curve='PR') sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.610317, sess.run(update_op), delta=1e-3) self.assertAlmostEqual(0.610317, auc.eval(), delta=1e-3) def testThirdAUCPRSpecialCase(self): with self.test_session() as sess: predictions = constant_op.constant( [0.0, 0.1, 0.2, 0.33, 0.3, 0.4, 0.5], shape=(1, 7), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 0, 0, 0, 1, 1, 1], shape=(1, 7)) auc, update_op = metrics.streaming_auc(predictions, labels, curve='PR') sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.90277, sess.run(update_op), delta=1e-3) self.assertAlmostEqual(0.90277, auc.eval(), delta=1e-3) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(1 - inputs, dtype=dtypes_lib.float32) auc, update_op = metrics.streaming_auc(predictions, labels) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0, sess.run(update_op)) self.assertAlmostEqual(0, auc.eval()) def testZeroTruePositivesAndFalseNegativesGivesOneAUC(self): with self.test_session() as sess: predictions = array_ops.zeros([4], dtype=dtypes_lib.float32) labels = array_ops.zeros([4]) auc, update_op = metrics.streaming_auc(predictions, labels) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(1, sess.run(update_op), 6) self.assertAlmostEqual(1, auc.eval(), 6) def testRecallOneAndPrecisionOneGivesOnePRAUC(self): with self.test_session() as sess: predictions = array_ops.ones([4], dtype=dtypes_lib.float32) labels = array_ops.ones([4]) auc, update_op = metrics.streaming_auc(predictions, labels, curve='PR') sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(1, sess.run(update_op), 6) self.assertAlmostEqual(1, auc.eval(), 6) def testWithMultipleUpdates(self): num_samples = 1000 batch_size = 10 num_batches = int(num_samples / batch_size) # Create the labels and data. labels = np.random.randint(0, 2, size=num_samples) noise = np.random.normal(0.0, scale=0.2, size=num_samples) predictions = 0.4 + 0.2 * labels + noise predictions[predictions > 1] = 1 predictions[predictions < 0] = 0 def _enqueue_as_batches(x, enqueue_ops): x_batches = x.astype(np.float32).reshape((num_batches, batch_size)) x_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) for i in range(num_batches): enqueue_ops[i].append(x_queue.enqueue(x_batches[i, :])) return x_queue.dequeue() for weights in (None, np.ones(num_samples), np.random.exponential(scale=1.0, size=num_samples)): expected_auc = _np_auc(predictions, labels, weights) with self.test_session() as sess: enqueue_ops = [[] for i in range(num_batches)] tf_predictions = _enqueue_as_batches(predictions, enqueue_ops) tf_labels = _enqueue_as_batches(labels, enqueue_ops) tf_weights = ( _enqueue_as_batches(weights, enqueue_ops) if weights is not None else None) for i in range(num_batches): sess.run(enqueue_ops[i]) auc, update_op = metrics.streaming_auc( tf_predictions, tf_labels, curve='ROC', num_thresholds=500, weights=tf_weights) sess.run(variables.local_variables_initializer()) for i in range(num_batches): sess.run(update_op) # Since this is only approximate, we can't expect a 6 digits match. # Although with higher number of samples/thresholds we should see the # accuracy improving self.assertAlmostEqual(expected_auc, auc.eval(), 2) class StreamingDynamicAUCTest(test.TestCase): def setUp(self): super(StreamingDynamicAUCTest, self).setUp() np.random.seed(1) ops.reset_default_graph() def testUnknownCurve(self): with self.assertRaisesRegexp( ValueError, 'curve must be either ROC or PR, TEST_CURVE unknown'): metrics.streaming_dynamic_auc( labels=array_ops.ones((10, 1)), predictions=array_ops.ones((10, 1)), curve='TEST_CURVE') def testVars(self): metrics.streaming_dynamic_auc( labels=array_ops.ones((10, 1)), predictions=array_ops.ones((10, 1))) _assert_metric_variables(self, [ 'dynamic_auc/concat_labels/array:0', 'dynamic_auc/concat_labels/size:0', 'dynamic_auc/concat_preds/array:0', 'dynamic_auc/concat_preds/size:0' ]) def testMetricsCollection(self): my_collection_name = '__metrics__' auc, _ = metrics.streaming_dynamic_auc( labels=array_ops.ones((10, 1)), predictions=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertEqual(ops.get_collection(my_collection_name), [auc]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_dynamic_auc( labels=array_ops.ones((10, 1)), predictions=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in xrange(10): sess.run(update_op) # Then verify idempotency. initial_auc = auc.eval() for _ in xrange(10): self.assertAlmostEqual(initial_auc, auc.eval(), 5) def testAllLabelsOnes(self): with self.test_session() as sess: predictions = constant_op.constant([1., 1., 1.]) labels = constant_op.constant([1, 1, 1]) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, auc.eval()) def testAllLabelsZeros(self): with self.test_session() as sess: predictions = constant_op.constant([1., 1., 1.]) labels = constant_op.constant([0, 0, 0]) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, auc.eval()) def testNonZeroOnePredictions(self): with self.test_session() as sess: predictions = constant_op.constant( [2.5, -2.5, 2.5, -2.5], dtype=dtypes_lib.float32) labels = constant_op.constant([1, 0, 1, 0]) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(auc.eval(), 1.0) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs) labels = constant_op.constant(inputs) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(1, auc.eval()) def testSomeCorrect(self): with self.test_session() as sess: predictions = constant_op.constant([1, 0, 1, 0]) labels = constant_op.constant([0, 1, 1, 0]) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(0.5, auc.eval()) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(1 - inputs, dtype=dtypes_lib.float32) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(0, auc.eval()) def testExceptionOnIncompatibleShapes(self): with self.test_session() as sess: predictions = array_ops.ones([5]) labels = array_ops.zeros([6]) with self.assertRaisesRegexp(ValueError, 'Shapes .* are incompatible'): _, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) def testExceptionOnGreaterThanOneLabel(self): with self.test_session() as sess: predictions = constant_op.constant([1, 0.5, 0], dtypes_lib.float32) labels = constant_op.constant([2, 1, 0]) _, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) with self.assertRaisesRegexp( errors_impl.InvalidArgumentError, '.*labels must be 0 or 1, at least one is >1.*'): sess.run(update_op) def testExceptionOnNegativeLabel(self): with self.test_session() as sess: predictions = constant_op.constant([1, 0.5, 0], dtypes_lib.float32) labels = constant_op.constant([1, 0, -1]) _, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) with self.assertRaisesRegexp( errors_impl.InvalidArgumentError, '.*labels must be 0 or 1, at least one is <0.*'): sess.run(update_op) def testWithMultipleUpdates(self): batch_size = 10 num_batches = 100 labels = np.array([]) predictions = np.array([]) tf_labels = variables.Variable( array_ops.ones(batch_size, dtypes_lib.int32), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.int32) tf_predictions = variables.Variable( array_ops.ones(batch_size), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.float32) auc, update_op = metrics.streaming_dynamic_auc(tf_labels, tf_predictions) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in xrange(num_batches): new_labels = np.random.randint(0, 2, size=batch_size) noise = np.random.normal(0.0, scale=0.2, size=batch_size) new_predictions = 0.4 + 0.2 * new_labels + noise labels = np.concatenate([labels, new_labels]) predictions = np.concatenate([predictions, new_predictions]) sess.run(tf_labels.assign(new_labels)) sess.run(tf_predictions.assign(new_predictions)) sess.run(update_op) expected_auc = _np_auc(predictions, labels) self.assertAlmostEqual(expected_auc, auc.eval()) def testAUCPRReverseIncreasingPredictions(self): with self.test_session() as sess: predictions = constant_op.constant( [0.1, 0.4, 0.35, 0.8], dtype=dtypes_lib.float32) labels = constant_op.constant([0, 0, 1, 1]) auc, update_op = metrics.streaming_dynamic_auc( labels, predictions, curve='PR') sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(0.79166, auc.eval(), delta=1e-5) def testAUCPRJumbledPredictions(self): with self.test_session() as sess: predictions = constant_op.constant( [0.1, 0.4, 0.35, 0.8, 0.1, 0.135, 0.81], dtypes_lib.float32) labels = constant_op.constant([0, 0, 1, 0, 1, 0, 1]) auc, update_op = metrics.streaming_dynamic_auc( labels, predictions, curve='PR') sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(0.610317, auc.eval(), delta=1e-6) def testAUCPRPredictionsLessThanHalf(self): with self.test_session() as sess: predictions = constant_op.constant( [0.0, 0.1, 0.2, 0.33, 0.3, 0.4, 0.5], shape=(1, 7), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 0, 0, 0, 1, 1, 1], shape=(1, 7)) auc, update_op = metrics.streaming_dynamic_auc( labels, predictions, curve='PR') sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(0.90277, auc.eval(), delta=1e-5) def testWithWeights(self): batch_size = 10 num_batches = 100 labels = np.array([]) predictions = np.array([]) weights = np.array([]) tf_labels = variables.Variable( array_ops.ones(batch_size, dtypes_lib.int32), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.int32) tf_predictions = variables.Variable( array_ops.ones(batch_size), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.float32) tf_weights = variables.Variable( array_ops.ones(batch_size), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.float32) auc, update_op = metrics.streaming_dynamic_auc(tf_labels, tf_predictions, weights=tf_weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in xrange(num_batches): new_labels = np.random.randint(0, 2, size=batch_size) noise = np.random.uniform(-0.2, 0.2, size=batch_size) new_predictions = 0.4 + 0.2 * new_labels + noise new_weights = np.random.uniform(0.0, 3.0, size=batch_size) labels = np.concatenate([labels, new_labels]) predictions = np.concatenate([predictions, new_predictions]) weights = np.concatenate([weights, new_weights]) sess.run([tf_labels.assign(new_labels), tf_predictions.assign(new_predictions), tf_weights.assign(new_weights)]) sess.run(update_op) expected_auc = _np_auc(predictions, labels, weights) self.assertAlmostEqual(expected_auc, auc.eval()) class AucWithConfidenceIntervalsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def _testResultsEqual(self, expected_dict, gotten_result): """Tests that 2 results (dicts) represent the same data. Args: expected_dict: A dictionary with keys that are the names of properties of PrecisionRecallData and whose values are lists of floats. gotten_result: A AucWithConfidenceIntervalData object. """ gotten_dict = {k: t.eval() for k, t in gotten_result._asdict().items()} self.assertItemsEqual( list(expected_dict.keys()), list(gotten_dict.keys())) for key, expected_values in expected_dict.items(): self.assertAllClose(expected_values, gotten_dict[key]) def _testCase(self, predictions, labels, expected_result, weights=None): """Performs a test given a certain scenario of labels, predictions, weights. Args: predictions: The predictions tensor. Of type float32. labels: The labels tensor. Of type bool. expected_result: The expected result (dict) that maps to tensors. weights: Optional weights tensor. """ with self.test_session() as sess: predictions_tensor = constant_op.constant( predictions, dtype=dtypes_lib.float32) labels_tensor = constant_op.constant(labels, dtype=dtypes_lib.int64) weights_tensor = None if weights: weights_tensor = constant_op.constant(weights, dtype=dtypes_lib.float32) gotten_result, update_op = ( metric_ops.auc_with_confidence_intervals( labels=labels_tensor, predictions=predictions_tensor, weights=weights_tensor)) sess.run(variables.local_variables_initializer()) sess.run(update_op) self._testResultsEqual(expected_result, gotten_result) def testAucAllCorrect(self): self._testCase( predictions=[0., 0.2, 0.3, 0.3, 0.4, 0.5, 0.6, 0.6, 0.8, 1.0], labels=[0, 0, 1, 0, 0, 1, 0, 1, 1, 0], expected_result={ 'auc': 0.66666667, 'lower': 0.27826795, 'upper': 0.91208512, }) def testAucUnorderedInput(self): self._testCase( predictions=[1.0, 0.6, 0., 0.3, 0.4, 0.2, 0.5, 0.3, 0.6, 0.8], labels=[0, 1, 0, 1, 0, 0, 1, 0, 0, 1], expected_result={ 'auc': 0.66666667, 'lower': 0.27826795, 'upper': 0.91208512, }) def testAucWithWeights(self): self._testCase( predictions=[0., 0.2, 0.3, 0.3, 0.4, 0.5, 0.6, 0.6, 0.8, 1.0], labels=[0, 0, 1, 0, 0, 1, 0, 1, 1, 0], weights=[0.5, 0.6, 1.2, 1.5, 2.0, 2.0, 1.5, 1.2, 0.6, 0.5], expected_result={ 'auc': 0.65151515, 'lower': 0.28918604, 'upper': 0.89573906, }) def testAucEqualOne(self): self._testCase( predictions=[0, 0.2, 0.3, 0.3, 0.4, 0.5, 0.6, 0.6, 0.8, 1.0], labels=[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], expected_result={ 'auc': 1.0, 'lower': 1.0, 'upper': 1.0, }) def testAucEqualZero(self): self._testCase( predictions=[0, 0.2, 0.3, 0.3, 0.4, 0.5, 0.6, 0.6, 0.8, 1.0], labels=[1, 1, 1, 1, 1, 0, 0, 0, 0, 0], expected_result={ 'auc': 0.0, 'lower': 0.0, 'upper': 0.0, }) def testNonZeroOnePredictions(self): self._testCase( predictions=[2.5, -2.5, .5, -.5, 1], labels=[1, 0, 1, 0, 0], expected_result={ 'auc': 0.83333333, 'lower': 0.15229267, 'upper': 0.99286517, }) def testAllLabelsOnes(self): self._testCase( predictions=[1., 1., 1., 1., 1.], labels=[1, 1, 1, 1, 1], expected_result={ 'auc': 0., 'lower': 0., 'upper': 0., }) def testAllLabelsZeros(self): self._testCase( predictions=[0., 0., 0., 0., 0.], labels=[0, 0, 0, 0, 0], expected_result={ 'auc': 0., 'lower': 0., 'upper': 0., }) def testWeightSumLessThanOneAll(self): self._testCase( predictions=[1., 1., 0., 1., 0., 0.], labels=[1, 1, 1, 0, 0, 0], weights=[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], expected_result={ 'auc': 0., 'lower': 0., 'upper': 0., }) def testWithMultipleUpdates(self): batch_size = 50 num_batches = 100 labels = np.array([]) predictions = np.array([]) tf_labels = variables.Variable(array_ops.ones(batch_size, dtypes_lib.int32), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.int32) tf_predictions = variables.Variable( array_ops.ones(batch_size), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.float32) auc, update_op = metrics.auc_with_confidence_intervals(tf_labels, tf_predictions) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in xrange(num_batches): new_labels = np.random.randint(0, 2, size=batch_size) noise = np.random.normal(0.0, scale=0.2, size=batch_size) new_predictions = 0.4 + 0.2 * new_labels + noise labels = np.concatenate([labels, new_labels]) predictions = np.concatenate([predictions, new_predictions]) sess.run(tf_labels.assign(new_labels)) sess.run(tf_predictions.assign(new_predictions)) sess.run(update_op) expected_auc = _np_auc(predictions, labels) self.assertAllClose(expected_auc, auc.auc.eval()) def testExceptionOnFloatLabels(self): with self.test_session() as sess: predictions = constant_op.constant([1, 0.5, 0, 1, 0], dtypes_lib.float32) labels = constant_op.constant([0.7, 0, 1, 0, 1]) _, update_op = metrics.auc_with_confidence_intervals(labels, predictions) sess.run(variables.local_variables_initializer()) self.assertRaises(TypeError, sess.run(update_op)) def testExceptionOnGreaterThanOneLabel(self): with self.test_session() as sess: predictions = constant_op.constant([1, 0.5, 0, 1, 0], dtypes_lib.float32) labels = constant_op.constant([2, 1, 0, 1, 0]) _, update_op = metrics.auc_with_confidence_intervals(labels, predictions) sess.run(variables.local_variables_initializer()) with self.assertRaisesRegexp( errors_impl.InvalidArgumentError, '.*labels must be 0 or 1, at least one is >1.*'): sess.run(update_op) def testExceptionOnNegativeLabel(self): with self.test_session() as sess: predictions = constant_op.constant([1, 0.5, 0, 1, 0], dtypes_lib.float32) labels = constant_op.constant([1, 0, -1, 1, 0]) _, update_op = metrics.auc_with_confidence_intervals(labels, predictions) sess.run(variables.local_variables_initializer()) with self.assertRaisesRegexp( errors_impl.InvalidArgumentError, '.*labels must be 0 or 1, at least one is <0.*'): sess.run(update_op) class StreamingPrecisionRecallAtEqualThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def _testResultsEqual(self, expected_dict, gotten_result, eps=None): """Tests that 2 results (dicts) represent the same data. Args: expected_dict: A dictionary with keys that are the names of properties of PrecisionRecallData and whose values are lists of floats. gotten_result: A PrecisionRecallData object. eps: Epsilon value to use for testing output values. If unspecified, use default from assertAllClose. """ gotten_dict = {k: t.eval() for k, t in gotten_result._asdict().items()} self.assertItemsEqual(list(expected_dict.keys()), list(gotten_dict.keys())) for key, expected_values in expected_dict.items(): if eps is not None: self.assertAllClose(expected_values, gotten_dict[key], atol=eps) else: self.assertAllClose(expected_values, gotten_dict[key]) def testVars(self): metric_ops.precision_recall_at_equal_thresholds( labels=constant_op.constant([True], dtype=dtypes_lib.bool), predictions=constant_op.constant([0.42], dtype=dtypes_lib.float32)) _assert_metric_variables( self, ('precision_recall_at_equal_thresholds/variables/tp_buckets:0', 'precision_recall_at_equal_thresholds/variables/fp_buckets:0')) def testVarsWithName(self): metric_ops.precision_recall_at_equal_thresholds( labels=constant_op.constant([True], dtype=dtypes_lib.bool), predictions=constant_op.constant([0.42], dtype=dtypes_lib.float32), name='foo') _assert_metric_variables( self, ('foo/variables/tp_buckets:0', 'foo/variables/fp_buckets:0')) def testValuesAreIdempotent(self): predictions = constant_op.constant( np.random.uniform(size=(10, 3)), dtype=dtypes_lib.float32) labels = constant_op.constant( np.random.uniform(size=(10, 3)) > 0.5, dtype=dtypes_lib.bool) result, update_op = metric_ops.precision_recall_at_equal_thresholds( labels=labels, predictions=predictions) with self.test_session() as sess: # Run several updates. sess.run(variables.local_variables_initializer()) for _ in range(3): sess.run(update_op) # Then verify idempotency. initial_result = { k: value.eval().tolist() for k, value in result._asdict().items() } for _ in range(3): self._testResultsEqual(initial_result, result) def _testCase(self, predictions, labels, expected_result, dtype=dtypes_lib.float32, eps=None, weights=None): """Performs a test given a certain scenario of labels, predictions, weights. Args: predictions: The predictions tensor. Of type dtype. labels: The labels tensor. Of type bool. expected_result: The expected result (dict) that maps to tensors. dtype: Data type to use for predictions and weights tensor. Default is float32. eps: Epsilon value to use for testing output values. If unspecified, use default from assertAllClose. weights: Optional weights tensor. """ with self.test_session() as sess: predictions_tensor = constant_op.constant(predictions, dtype=dtype) labels_tensor = constant_op.constant(labels, dtype=dtypes_lib.bool) weights_tensor = None if weights: weights_tensor = constant_op.constant(weights, dtype=dtype) gotten_result, update_op = ( metric_ops.precision_recall_at_equal_thresholds( labels=labels_tensor, predictions=predictions_tensor, weights=weights_tensor, num_thresholds=3)) self.assertEqual(gotten_result.tp.dtype, dtype) self.assertEqual(gotten_result.fp.dtype, dtype) self.assertEqual(gotten_result.tn.dtype, dtype) self.assertEqual(gotten_result.fn.dtype, dtype) self.assertEqual(gotten_result.precision.dtype, dtype) self.assertEqual(gotten_result.recall.dtype, dtype) self.assertEqual(gotten_result.thresholds.dtype, dtype) sess.run(variables.local_variables_initializer()) sess.run(update_op) self._testResultsEqual(expected_result, gotten_result, eps=eps) def testAllTruePositives(self): self._testCase( [[1]], [[True]], { 'tp': [1, 1, 1], 'fp': [0, 0, 0], 'tn': [0, 0, 0], 'fn': [0, 0, 0], 'precision': [1.0, 1.0, 1.0], 'recall': [1.0, 1.0, 1.0], 'thresholds': [0.0, 0.5, 1.0], }) def testAllTrueNegatives(self): self._testCase( [[0]], [[False]], { 'tp': [0, 0, 0], 'fp': [1, 0, 0], 'tn': [0, 1, 1], 'fn': [0, 0, 0], 'precision': [0.0, 0.0, 0.0], 'recall': [0.0, 0.0, 0.0], 'thresholds': [0.0, 0.5, 1.0], }) def testAllFalsePositives(self): self._testCase( [[1]], [[False]], { 'tp': [0, 0, 0], 'fp': [1, 1, 1], 'tn': [0, 0, 0], 'fn': [0, 0, 0], 'precision': [0.0, 0.0, 0.0], 'recall': [0.0, 0.0, 0.0], 'thresholds': [0.0, 0.5, 1.0], }) def testAllFalseNegatives(self): self._testCase( [[0]], [[True]], { 'tp': [1, 0, 0], 'fp': [0, 0, 0], 'tn': [0, 0, 0], 'fn': [0, 1, 1], 'precision': [1.0, 0.0, 0.0], 'recall': [1.0, 0.0, 0.0], 'thresholds': [0.0, 0.5, 1.0], }) def testManyValues(self): self._testCase( [[0.2, 0.3, 0.4, 0.6, 0.7, 0.8]], [[True, False, False, True, True, True]], { 'tp': [4, 3, 0], 'fp': [2, 0, 0], 'tn': [0, 2, 2], 'fn': [0, 1, 4], 'precision': [2.0 / 3.0, 1.0, 0.0], 'recall': [1.0, 0.75, 0.0], 'thresholds': [0.0, 0.5, 1.0], }) def testManyValuesWithWeights(self): self._testCase( [[0.2, 0.3, 0.4, 0.6, 0.7, 0.8]], [[True, False, False, True, True, True]], { 'tp': [1.5, 1.5, 0.0], 'fp': [2.5, 0.0, 0.0], 'tn': [0.0, 2.5, 2.5], 'fn': [0.0, 0.0, 1.5], 'precision': [0.375, 1.0, 0.0], 'recall': [1.0, 1.0, 0.0], 'thresholds': [0.0, 0.5, 1.0], }, weights=[[0.0, 0.5, 2.0, 0.0, 0.5, 1.0]]) def testFloat64(self): self._testCase( [[0.2, 0.3, 0.4, 0.6, 0.7, 0.8]], [[True, False, False, True, True, True]], { 'tp': [4, 3, 0], 'fp': [2, 0, 0], 'tn': [0, 2, 2], 'fn': [0, 1, 4], 'precision': [2.0 / 3.0, 1.0, 0.0], 'recall': [1.0, 0.75, 0.0], 'thresholds': [0.0, 0.5, 1.0], }, dtype=dtypes_lib.float64) def testFloat16(self): self._testCase( [[0.2, 0.3, 0.4, 0.6, 0.7, 0.8]], [[True, False, False, True, True, True]], { 'tp': [4, 3, 0], 'fp': [2, 0, 0], 'tn': [0, 2, 2], 'fn': [0, 1, 4], 'precision': [2.0 / 3.0, 1.0, 0.0], 'recall': [1.0, 0.75, 0.0], 'thresholds': [0.0, 0.5, 1.0], }, dtype=dtypes_lib.float16, eps=1e-3) class StreamingSpecificityAtSensitivityTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_specificity_at_sensitivity( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), sensitivity=0.7) _assert_metric_variables(self, ('specificity_at_sensitivity/true_positives:0', 'specificity_at_sensitivity/false_negatives:0', 'specificity_at_sensitivity/false_positives:0', 'specificity_at_sensitivity/true_negatives:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_specificity_at_sensitivity( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), sensitivity=0.7, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_specificity_at_sensitivity( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), sensitivity=0.7, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) specificity, update_op = metrics.streaming_specificity_at_sensitivity( predictions, labels, sensitivity=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_specificity = specificity.eval() for _ in range(10): self.assertAlmostEqual(initial_specificity, specificity.eval(), 5) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) specificity, update_op = metrics.streaming_specificity_at_sensitivity( predictions, labels, sensitivity=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1, sess.run(update_op)) self.assertEqual(1, specificity.eval()) def testSomeCorrectHighSensitivity(self): predictions_values = [0.1, 0.2, 0.4, 0.3, 0.0, 0.1, 0.45, 0.5, 0.8, 0.9] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) specificity, update_op = metrics.streaming_specificity_at_sensitivity( predictions, labels, sensitivity=0.8) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(1.0, sess.run(update_op)) self.assertAlmostEqual(1.0, specificity.eval()) def testSomeCorrectLowSensitivity(self): predictions_values = [0.1, 0.2, 0.4, 0.3, 0.0, 0.1, 0.2, 0.2, 0.26, 0.26] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) specificity, update_op = metrics.streaming_specificity_at_sensitivity( predictions, labels, sensitivity=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.6, sess.run(update_op)) self.assertAlmostEqual(0.6, specificity.eval()) def testWeighted1d(self): predictions_values = [0.1, 0.2, 0.4, 0.3, 0.0, 0.1, 0.2, 0.2, 0.26, 0.26] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] weights_values = [3] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) weights = constant_op.constant(weights_values) specificity, update_op = metrics.streaming_specificity_at_sensitivity( predictions, labels, weights=weights, sensitivity=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.6, sess.run(update_op)) self.assertAlmostEqual(0.6, specificity.eval()) def testWeighted2d(self): predictions_values = [0.1, 0.2, 0.4, 0.3, 0.0, 0.1, 0.2, 0.2, 0.26, 0.26] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] weights_values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) weights = constant_op.constant(weights_values) specificity, update_op = metrics.streaming_specificity_at_sensitivity( predictions, labels, weights=weights, sensitivity=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(8.0 / 15.0, sess.run(update_op)) self.assertAlmostEqual(8.0 / 15.0, specificity.eval()) class StreamingSensitivityAtSpecificityTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_sensitivity_at_specificity( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), specificity=0.7) _assert_metric_variables(self, ('sensitivity_at_specificity/true_positives:0', 'sensitivity_at_specificity/false_negatives:0', 'sensitivity_at_specificity/false_positives:0', 'sensitivity_at_specificity/true_negatives:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_sensitivity_at_specificity( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), specificity=0.7, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_sensitivity_at_specificity( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), specificity=0.7, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) sensitivity, update_op = metrics.streaming_sensitivity_at_specificity( predictions, labels, specificity=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_sensitivity = sensitivity.eval() for _ in range(10): self.assertAlmostEqual(initial_sensitivity, sensitivity.eval(), 5) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) specificity, update_op = metrics.streaming_sensitivity_at_specificity( predictions, labels, specificity=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1, sess.run(update_op)) self.assertEqual(1, specificity.eval()) def testSomeCorrectHighSpecificity(self): predictions_values = [0.0, 0.1, 0.2, 0.3, 0.4, 0.1, 0.45, 0.5, 0.8, 0.9] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) specificity, update_op = metrics.streaming_sensitivity_at_specificity( predictions, labels, specificity=0.8) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.8, sess.run(update_op)) self.assertAlmostEqual(0.8, specificity.eval()) def testSomeCorrectLowSpecificity(self): predictions_values = [0.0, 0.1, 0.2, 0.3, 0.4, 0.01, 0.02, 0.25, 0.26, 0.26] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) specificity, update_op = metrics.streaming_sensitivity_at_specificity( predictions, labels, specificity=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.6, sess.run(update_op)) self.assertAlmostEqual(0.6, specificity.eval()) def testWeighted(self): predictions_values = [0.0, 0.1, 0.2, 0.3, 0.4, 0.01, 0.02, 0.25, 0.26, 0.26] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] weights_values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) weights = constant_op.constant(weights_values) specificity, update_op = metrics.streaming_sensitivity_at_specificity( predictions, labels, weights=weights, specificity=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.675, sess.run(update_op)) self.assertAlmostEqual(0.675, specificity.eval()) # TODO(nsilberman): Break this up into two sets of tests. class StreamingPrecisionRecallThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_precision_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0]) _assert_metric_variables(self, ( 'precision_at_thresholds/true_positives:0', 'precision_at_thresholds/false_positives:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' prec, _ = metrics.streaming_precision_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], metrics_collections=[my_collection_name]) rec, _ = metrics.streaming_recall_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [prec, rec]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, precision_op = metrics.streaming_precision_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], updates_collections=[my_collection_name]) _, recall_op = metrics.streaming_recall_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], updates_collections=[my_collection_name]) self.assertListEqual( ops.get_collection(my_collection_name), [precision_op, recall_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) thresholds = [0, 0.5, 1.0] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run([prec_op, rec_op]) # Then verify idempotency. initial_prec = prec.eval() initial_rec = rec.eval() for _ in range(10): self.assertAllClose(initial_prec, prec.eval()) self.assertAllClose(initial_rec, rec.eval()) # TODO(nsilberman): fix tests (passing but incorrect). def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) thresholds = [0.5] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertEqual(1, prec.eval()) self.assertEqual(1, rec.eval()) def testSomeCorrect(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) thresholds = [0.5] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertAlmostEqual(0.5, prec.eval()) self.assertAlmostEqual(0.5, rec.eval()) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(1 - inputs, dtype=dtypes_lib.float32) thresholds = [0.5] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertAlmostEqual(0, prec.eval()) self.assertAlmostEqual(0, rec.eval()) def testWeights1d(self): with self.test_session() as sess: predictions = constant_op.constant( [[1, 0], [1, 0]], shape=(2, 2), dtype=dtypes_lib.float32) labels = constant_op.constant([[0, 1], [1, 0]], shape=(2, 2)) weights = constant_op.constant( [[0], [1]], shape=(2, 1), dtype=dtypes_lib.float32) thresholds = [0.5, 1.1] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds, weights=weights) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds, weights=weights) prec_low = prec[0] prec_high = prec[1] rec_low = rec[0] rec_high = rec[1] sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertAlmostEqual(1.0, prec_low.eval(), places=5) self.assertAlmostEqual(0.0, prec_high.eval(), places=5) self.assertAlmostEqual(1.0, rec_low.eval(), places=5) self.assertAlmostEqual(0.0, rec_high.eval(), places=5) def testWeights2d(self): with self.test_session() as sess: predictions = constant_op.constant( [[1, 0], [1, 0]], shape=(2, 2), dtype=dtypes_lib.float32) labels = constant_op.constant([[0, 1], [1, 0]], shape=(2, 2)) weights = constant_op.constant( [[0, 0], [1, 1]], shape=(2, 2), dtype=dtypes_lib.float32) thresholds = [0.5, 1.1] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds, weights=weights) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds, weights=weights) prec_low = prec[0] prec_high = prec[1] rec_low = rec[0] rec_high = rec[1] sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertAlmostEqual(1.0, prec_low.eval(), places=5) self.assertAlmostEqual(0.0, prec_high.eval(), places=5) self.assertAlmostEqual(1.0, rec_low.eval(), places=5) self.assertAlmostEqual(0.0, rec_high.eval(), places=5) def testExtremeThresholds(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 1], shape=(1, 4)) thresholds = [-1.0, 2.0] # lower/higher than any values prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds) prec_low = prec[0] prec_high = prec[1] rec_low = rec[0] rec_high = rec[1] sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertAlmostEqual(0.75, prec_low.eval()) self.assertAlmostEqual(0.0, prec_high.eval()) self.assertAlmostEqual(1.0, rec_low.eval()) self.assertAlmostEqual(0.0, rec_high.eval()) def testZeroLabelsPredictions(self): with self.test_session() as sess: predictions = array_ops.zeros([4], dtype=dtypes_lib.float32) labels = array_ops.zeros([4]) thresholds = [0.5] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertAlmostEqual(0, prec.eval(), 6) self.assertAlmostEqual(0, rec.eval(), 6) def testWithMultipleUpdates(self): num_samples = 1000 batch_size = 10 num_batches = int(num_samples / batch_size) # Create the labels and data. labels = np.random.randint(0, 2, size=(num_samples, 1)) noise = np.random.normal(0.0, scale=0.2, size=(num_samples, 1)) predictions = 0.4 + 0.2 * labels + noise predictions[predictions > 1] = 1 predictions[predictions < 0] = 0 thresholds = [0.3] tp = 0 fp = 0 fn = 0 tn = 0 for i in range(num_samples): if predictions[i] > thresholds[0]: if labels[i] == 1: tp += 1 else: fp += 1 else: if labels[i] == 1: fn += 1 else: tn += 1 epsilon = 1e-7 expected_prec = tp / (epsilon + tp + fp) expected_rec = tp / (epsilon + tp + fn) labels = labels.astype(np.float32) predictions = predictions.astype(np.float32) with self.test_session() as sess: # Reshape the data so its easy to queue up: predictions_batches = predictions.reshape((batch_size, num_batches)) labels_batches = labels.reshape((batch_size, num_batches)) # Enqueue the data: predictions_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) labels_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) for i in range(int(num_batches)): tf_prediction = constant_op.constant(predictions_batches[:, i]) tf_label = constant_op.constant(labels_batches[:, i]) sess.run([ predictions_queue.enqueue(tf_prediction), labels_queue.enqueue(tf_label) ]) tf_predictions = predictions_queue.dequeue() tf_labels = labels_queue.dequeue() prec, prec_op = metrics.streaming_precision_at_thresholds( tf_predictions, tf_labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( tf_predictions, tf_labels, thresholds) sess.run(variables.local_variables_initializer()) for _ in range(int(num_samples / batch_size)): sess.run([prec_op, rec_op]) # Since this is only approximate, we can't expect a 6 digits match. # Although with higher number of samples/thresholds we should see the # accuracy improving self.assertAlmostEqual(expected_prec, prec.eval(), 2) self.assertAlmostEqual(expected_rec, rec.eval(), 2) class StreamingFPRThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_positive_rate_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0]) _assert_metric_variables(self, ( 'false_positive_rate_at_thresholds/false_positives:0', 'false_positive_rate_at_thresholds/true_negatives:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' fpr, _ = metrics.streaming_false_positive_rate_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [fpr]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_false_positive_rate_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) thresholds = [0, 0.5, 1.0] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(fpr_op) # Then verify idempotency. initial_fpr = fpr.eval() for _ in range(10): self.assertAllClose(initial_fpr, fpr.eval()) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) thresholds = [0.5] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertEqual(0, fpr.eval()) def testSomeCorrect(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) thresholds = [0.5] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertAlmostEqual(0.5, fpr.eval()) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(1 - inputs, dtype=dtypes_lib.float32) thresholds = [0.5] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertAlmostEqual(1, fpr.eval()) def testWeights1d(self): with self.test_session() as sess: predictions = constant_op.constant( [[1, 0], [1, 0]], shape=(2, 2), dtype=dtypes_lib.float32) labels = constant_op.constant([[0, 1], [1, 0]], shape=(2, 2)) weights = constant_op.constant( [[0], [1]], shape=(2, 1), dtype=dtypes_lib.float32) thresholds = [0.5, 1.1] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds, weights=weights) fpr_low = fpr[0] fpr_high = fpr[1] sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertAlmostEqual(0.0, fpr_low.eval(), places=5) self.assertAlmostEqual(0.0, fpr_high.eval(), places=5) def testWeights2d(self): with self.test_session() as sess: predictions = constant_op.constant( [[1, 0], [1, 0]], shape=(2, 2), dtype=dtypes_lib.float32) labels = constant_op.constant([[0, 1], [1, 0]], shape=(2, 2)) weights = constant_op.constant( [[0, 0], [1, 1]], shape=(2, 2), dtype=dtypes_lib.float32) thresholds = [0.5, 1.1] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds, weights=weights) fpr_low = fpr[0] fpr_high = fpr[1] sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertAlmostEqual(0.0, fpr_low.eval(), places=5) self.assertAlmostEqual(0.0, fpr_high.eval(), places=5) def testExtremeThresholds(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 1], shape=(1, 4)) thresholds = [-1.0, 2.0] # lower/higher than any values fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds) fpr_low = fpr[0] fpr_high = fpr[1] sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertAlmostEqual(1.0, fpr_low.eval(), places=5) self.assertAlmostEqual(0.0, fpr_high.eval(), places=5) def testZeroLabelsPredictions(self): with self.test_session() as sess: predictions = array_ops.zeros([4], dtype=dtypes_lib.float32) labels = array_ops.zeros([4]) thresholds = [0.5] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertAlmostEqual(0, fpr.eval(), 6) def testWithMultipleUpdates(self): num_samples = 1000 batch_size = 10 num_batches = int(num_samples / batch_size) # Create the labels and data. labels = np.random.randint(0, 2, size=(num_samples, 1)) noise = np.random.normal(0.0, scale=0.2, size=(num_samples, 1)) predictions = 0.4 + 0.2 * labels + noise predictions[predictions > 1] = 1 predictions[predictions < 0] = 0 thresholds = [0.3] fp = 0 tn = 0 for i in range(num_samples): if predictions[i] > thresholds[0]: if labels[i] == 0: fp += 1 else: if labels[i] == 0: tn += 1 epsilon = 1e-7 expected_fpr = fp / (epsilon + fp + tn) labels = labels.astype(np.float32) predictions = predictions.astype(np.float32) with self.test_session() as sess: # Reshape the data so its easy to queue up: predictions_batches = predictions.reshape((batch_size, num_batches)) labels_batches = labels.reshape((batch_size, num_batches)) # Enqueue the data: predictions_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) labels_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) for i in range(int(num_batches)): tf_prediction = constant_op.constant(predictions_batches[:, i]) tf_label = constant_op.constant(labels_batches[:, i]) sess.run([ predictions_queue.enqueue(tf_prediction), labels_queue.enqueue(tf_label) ]) tf_predictions = predictions_queue.dequeue() tf_labels = labels_queue.dequeue() fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( tf_predictions, tf_labels, thresholds) sess.run(variables.local_variables_initializer()) for _ in range(int(num_samples / batch_size)): sess.run(fpr_op) # Since this is only approximate, we can't expect a 6 digits match. # Although with higher number of samples/thresholds we should see the # accuracy improving self.assertAlmostEqual(expected_fpr, fpr.eval(), 2) class RecallAtPrecisionTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.recall_at_precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), precision=0.7) _assert_metric_variables(self, ('recall_at_precision/true_positives:0', 'recall_at_precision/false_negatives:0', 'recall_at_precision/false_positives:0', 'recall_at_precision/true_negatives:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.recall_at_precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), precision=0.7, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.recall_at_precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), precision=0.7, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) recall, update_op = metrics.recall_at_precision( labels, predictions, precision=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_recall = recall.eval() for _ in range(10): self.assertAlmostEqual(initial_recall, recall.eval(), 5) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) recall, update_op = metrics.recall_at_precision( labels, predictions, precision=1.0) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1, sess.run(update_op)) self.assertEqual(1, recall.eval()) def testSomeCorrectHighPrecision(self): predictions_values = [1, .9, .8, .7, .6, .5, .4, .3] labels_values = [1, 1, 1, 1, 0, 0, 0, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) recall, update_op = metrics.recall_at_precision( labels, predictions, precision=0.8) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.8, sess.run(update_op)) self.assertAlmostEqual(0.8, recall.eval()) def testSomeCorrectLowPrecision(self): predictions_values = [1, .9, .8, .7, .6, .5, .4, .3, .2, .1] labels_values = [1, 1, 0, 0, 0, 0, 0, 0, 0, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) recall, update_op = metrics.recall_at_precision( labels, predictions, precision=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) target_recall = 2.0 / 3.0 self.assertAlmostEqual(target_recall, sess.run(update_op)) self.assertAlmostEqual(target_recall, recall.eval()) def testWeighted(self): predictions_values = [1, .9, .8, .7, .6] labels_values = [1, 1, 0, 0, 1] weights_values = [1, 1, 3, 4, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) weights = constant_op.constant(weights_values) recall, update_op = metrics.recall_at_precision( labels, predictions, weights=weights, precision=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) target_recall = 2.0 / 3.0 self.assertAlmostEqual(target_recall, sess.run(update_op)) self.assertAlmostEqual(target_recall, recall.eval()) class PrecisionAtRecallTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.precision_at_recall( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), target_recall=0.7) _assert_metric_variables(self, ('precision_at_recall/true_positives:0', 'precision_at_recall/false_negatives:0', 'precision_at_recall/false_positives:0', 'precision_at_recall/true_negatives:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.precision_at_recall( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), target_recall=0.7, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.precision_at_recall( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), target_recall=0.7, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=1) precision, update_op = metrics.precision_at_recall( labels, predictions, target_recall=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_precision = precision.eval() for _ in range(10): self.assertAlmostEqual(initial_precision, precision.eval(), places=5) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) precision, update_op = metrics.precision_at_recall( labels, predictions, target_recall=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1, sess.run(update_op)) self.assertEqual(1, precision.eval()) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = 1.0 - predictions label_prior = math_ops.reduce_mean(labels) precision, update_op = metrics.precision_at_recall( labels, predictions, target_recall=0.2) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(sess.run(label_prior), sess.run(update_op)) self.assertEqual(sess.run(label_prior), precision.eval()) def testSomeCorrectHighRecall(self): predictions_values = [0.1, 0.2, 0.5, 0.3, 0.0, 0.1, 0.45, 0.5, 0.8, 0.9] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) precision, update_op = metrics.precision_at_recall( labels, predictions, target_recall=0.8) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.8, sess.run(update_op)) self.assertAlmostEqual(0.8, precision.eval()) def testSomeCorrectLowRecall(self): predictions_values = [0.1, 0.2, 0.7, 0.3, 0.0, 0.1, 0.45, 0.5, 0.6, 0.9] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) precision, update_op = metrics.precision_at_recall( labels, predictions, target_recall=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(2.0/3, sess.run(update_op)) self.assertAlmostEqual(2.0/3, precision.eval()) def testWeighted_multipleLabelDtypes(self): for label_dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions_values = [ 0.0, 0.1, 0.2, 0.3, 0.4, 0.1, 0.22, 0.25, 0.31, 0.35] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] weights_values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = math_ops.cast(labels_values, dtype=label_dtype) weights = constant_op.constant(weights_values) precision, update_op = metrics.precision_at_recall( labels, predictions, target_recall=0.8, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(34.0/43, sess.run(update_op)) self.assertAlmostEqual(34.0/43, precision.eval()) class StreamingFNRThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_negative_rate_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0]) _assert_metric_variables(self, ( 'false_negative_rate_at_thresholds/false_negatives:0', 'false_negative_rate_at_thresholds/true_positives:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' fnr, _ = metrics.streaming_false_negative_rate_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [fnr]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_false_negative_rate_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) thresholds = [0, 0.5, 1.0] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(fnr_op) # Then verify idempotency. initial_fnr = fnr.eval() for _ in range(10): self.assertAllClose(initial_fnr, fnr.eval()) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) thresholds = [0.5] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertEqual(0, fnr.eval()) def testSomeCorrect(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) thresholds = [0.5] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertAlmostEqual(0.5, fnr.eval()) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(1 - inputs, dtype=dtypes_lib.float32) thresholds = [0.5] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertAlmostEqual(1, fnr.eval()) def testWeights1d(self): with self.test_session() as sess: predictions = constant_op.constant( [[1, 0], [1, 0]], shape=(2, 2), dtype=dtypes_lib.float32) labels = constant_op.constant([[0, 1], [1, 0]], shape=(2, 2)) weights = constant_op.constant( [[0], [1]], shape=(2, 1), dtype=dtypes_lib.float32) thresholds = [0.5, 1.1] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds, weights=weights) fnr_low = fnr[0] fnr_high = fnr[1] sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertAlmostEqual(0.0, fnr_low.eval(), places=5) self.assertAlmostEqual(1.0, fnr_high.eval(), places=5) def testWeights2d(self): with self.test_session() as sess: predictions = constant_op.constant( [[1, 0], [1, 0]], shape=(2, 2), dtype=dtypes_lib.float32) labels = constant_op.constant([[0, 1], [1, 0]], shape=(2, 2)) weights = constant_op.constant( [[0, 0], [1, 1]], shape=(2, 2), dtype=dtypes_lib.float32) thresholds = [0.5, 1.1] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds, weights=weights) fnr_low = fnr[0] fnr_high = fnr[1] sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertAlmostEqual(0.0, fnr_low.eval(), places=5) self.assertAlmostEqual(1.0, fnr_high.eval(), places=5) def testExtremeThresholds(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 1], shape=(1, 4)) thresholds = [-1.0, 2.0] # lower/higher than any values fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds) fnr_low = fnr[0] fnr_high = fnr[1] sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertAlmostEqual(0.0, fnr_low.eval()) self.assertAlmostEqual(1.0, fnr_high.eval()) def testZeroLabelsPredictions(self): with self.test_session() as sess: predictions = array_ops.zeros([4], dtype=dtypes_lib.float32) labels = array_ops.zeros([4]) thresholds = [0.5] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertAlmostEqual(0, fnr.eval(), 6) def testWithMultipleUpdates(self): num_samples = 1000 batch_size = 10 num_batches = int(num_samples / batch_size) # Create the labels and data. labels = np.random.randint(0, 2, size=(num_samples, 1)) noise = np.random.normal(0.0, scale=0.2, size=(num_samples, 1)) predictions = 0.4 + 0.2 * labels + noise predictions[predictions > 1] = 1 predictions[predictions < 0] = 0 thresholds = [0.3] fn = 0 tp = 0 for i in range(num_samples): if predictions[i] > thresholds[0]: if labels[i] == 1: tp += 1 else: if labels[i] == 1: fn += 1 epsilon = 1e-7 expected_fnr = fn / (epsilon + fn + tp) labels = labels.astype(np.float32) predictions = predictions.astype(np.float32) with self.test_session() as sess: # Reshape the data so its easy to queue up: predictions_batches = predictions.reshape((batch_size, num_batches)) labels_batches = labels.reshape((batch_size, num_batches)) # Enqueue the data: predictions_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) labels_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) for i in range(int(num_batches)): tf_prediction = constant_op.constant(predictions_batches[:, i]) tf_label = constant_op.constant(labels_batches[:, i]) sess.run([ predictions_queue.enqueue(tf_prediction), labels_queue.enqueue(tf_label) ]) tf_predictions = predictions_queue.dequeue() tf_labels = labels_queue.dequeue() fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( tf_predictions, tf_labels, thresholds) sess.run(variables.local_variables_initializer()) for _ in range(int(num_samples / batch_size)): sess.run(fnr_op) # Since this is only approximate, we can't expect a 6 digits match. # Although with higher number of samples/thresholds we should see the # accuracy improving self.assertAlmostEqual(expected_fnr, fnr.eval(), 2) # TODO(ptucker): Remove when we remove `streaming_recall_at_k`. # This op will be deprecated soon in favor of `streaming_sparse_recall_at_k`. # Until then, this test validates that both ops yield the same results. class StreamingRecallAtKTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() self._batch_size = 4 self._num_classes = 3 self._np_predictions = np.matrix(('0.1 0.2 0.7;' '0.6 0.2 0.2;' '0.0 0.9 0.1;' '0.2 0.0 0.8')) self._np_labels = [0, 0, 0, 0] def testVars(self): metrics.streaming_recall_at_k( predictions=array_ops.ones((self._batch_size, self._num_classes)), labels=array_ops.ones((self._batch_size,), dtype=dtypes_lib.int32), k=1) _assert_metric_variables(self, ('recall_at_1/count:0', 'recall_at_1/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_recall_at_k( predictions=array_ops.ones((self._batch_size, self._num_classes)), labels=array_ops.ones((self._batch_size,), dtype=dtypes_lib.int32), k=1, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_recall_at_k( predictions=array_ops.ones((self._batch_size, self._num_classes)), labels=array_ops.ones((self._batch_size,), dtype=dtypes_lib.int32), k=1, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testSingleUpdateKIs1(self): predictions = constant_op.constant( self._np_predictions, shape=(self._batch_size, self._num_classes), dtype=dtypes_lib.float32) labels = constant_op.constant( self._np_labels, shape=(self._batch_size,), dtype=dtypes_lib.int64) recall, update_op = metrics.streaming_recall_at_k(predictions, labels, k=1) sp_recall, sp_update_op = metrics.streaming_sparse_recall_at_k( predictions, array_ops.reshape(labels, (self._batch_size, 1)), k=1) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0.25, sess.run(update_op)) self.assertEqual(0.25, recall.eval()) self.assertEqual(0.25, sess.run(sp_update_op)) self.assertEqual(0.25, sp_recall.eval()) def testSingleUpdateKIs2(self): predictions = constant_op.constant( self._np_predictions, shape=(self._batch_size, self._num_classes), dtype=dtypes_lib.float32) labels = constant_op.constant( self._np_labels, shape=(self._batch_size,), dtype=dtypes_lib.int64) recall, update_op = metrics.streaming_recall_at_k(predictions, labels, k=2) sp_recall, sp_update_op = metrics.streaming_sparse_recall_at_k( predictions, array_ops.reshape(labels, (self._batch_size, 1)), k=2) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0.5, sess.run(update_op)) self.assertEqual(0.5, recall.eval()) self.assertEqual(0.5, sess.run(sp_update_op)) self.assertEqual(0.5, sp_recall.eval()) def testSingleUpdateKIs3(self): predictions = constant_op.constant( self._np_predictions, shape=(self._batch_size, self._num_classes), dtype=dtypes_lib.float32) labels = constant_op.constant( self._np_labels, shape=(self._batch_size,), dtype=dtypes_lib.int64) recall, update_op = metrics.streaming_recall_at_k(predictions, labels, k=3) sp_recall, sp_update_op = metrics.streaming_sparse_recall_at_k( predictions, array_ops.reshape(labels, (self._batch_size, 1)), k=3) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1.0, sess.run(update_op)) self.assertEqual(1.0, recall.eval()) self.assertEqual(1.0, sess.run(sp_update_op)) self.assertEqual(1.0, sp_recall.eval()) def testSingleUpdateSomeMissingKIs2(self): predictions = constant_op.constant( self._np_predictions, shape=(self._batch_size, self._num_classes), dtype=dtypes_lib.float32) labels = constant_op.constant( self._np_labels, shape=(self._batch_size,), dtype=dtypes_lib.int64) weights = constant_op.constant( [0, 1, 0, 1], shape=(self._batch_size,), dtype=dtypes_lib.float32) recall, update_op = metrics.streaming_recall_at_k( predictions, labels, k=2, weights=weights) sp_recall, sp_update_op = metrics.streaming_sparse_recall_at_k( predictions, array_ops.reshape(labels, (self._batch_size, 1)), k=2, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1.0, sess.run(update_op)) self.assertEqual(1.0, recall.eval()) self.assertEqual(1.0, sess.run(sp_update_op)) self.assertEqual(1.0, sp_recall.eval()) class StreamingSparsePrecisionTest(test.TestCase): def _test_streaming_sparse_precision_at_k(self, predictions, labels, k, expected, class_id=None, weights=None): with ops.Graph().as_default() as g, self.session(g): if weights is not None: weights = constant_op.constant(weights, dtypes_lib.float32) metric, update = metrics.streaming_sparse_precision_at_k( predictions=constant_op.constant(predictions, dtypes_lib.float32), labels=labels, k=k, class_id=class_id, weights=weights) # Fails without initialized vars. self.assertRaises(errors_impl.OpError, metric.eval) self.assertRaises(errors_impl.OpError, update.eval) variables.variables_initializer(variables.local_variables()).run() # Run per-step op and assert expected values. if math.isnan(expected): _assert_nan(self, update.eval()) _assert_nan(self, metric.eval()) else: self.assertEqual(expected, update.eval()) self.assertEqual(expected, metric.eval()) def _test_streaming_sparse_precision_at_top_k(self, top_k_predictions, labels, expected, class_id=None, weights=None): with ops.Graph().as_default() as g, self.session(g): if weights is not None: weights = constant_op.constant(weights, dtypes_lib.float32) metric, update = metrics.streaming_sparse_precision_at_top_k( top_k_predictions=constant_op.constant(top_k_predictions, dtypes_lib.int32), labels=labels, class_id=class_id, weights=weights) # Fails without initialized vars. self.assertRaises(errors_impl.OpError, metric.eval) self.assertRaises(errors_impl.OpError, update.eval) variables.variables_initializer(variables.local_variables()).run() # Run per-step op and assert expected values. if math.isnan(expected): self.assertTrue(math.isnan(update.eval())) self.assertTrue(math.isnan(metric.eval())) else: self.assertEqual(expected, update.eval()) self.assertEqual(expected, metric.eval()) def _test_streaming_sparse_average_precision_at_k(self, predictions, labels, k, expected, weights=None): with ops.Graph().as_default() as g, self.session(g): if weights is not None: weights = constant_op.constant(weights, dtypes_lib.float32) predictions = constant_op.constant(predictions, dtypes_lib.float32) metric, update = metrics.streaming_sparse_average_precision_at_k( predictions, labels, k, weights=weights) # Fails without initialized vars. self.assertRaises(errors_impl.OpError, metric.eval) self.assertRaises(errors_impl.OpError, update.eval) local_variables = variables.local_variables() variables.variables_initializer(local_variables).run() # Run per-step op and assert expected values. if math.isnan(expected): _assert_nan(self, update.eval()) _assert_nan(self, metric.eval()) else: self.assertAlmostEqual(expected, update.eval()) self.assertAlmostEqual(expected, metric.eval()) def _test_streaming_sparse_average_precision_at_top_k(self, top_k_predictions, labels, expected, weights=None): with ops.Graph().as_default() as g, self.session(g): if weights is not None: weights = constant_op.constant(weights, dtypes_lib.float32) metric, update = metrics.streaming_sparse_average_precision_at_top_k( top_k_predictions, labels, weights=weights) # Fails without initialized vars. self.assertRaises(errors_impl.OpError, metric.eval) self.assertRaises(errors_impl.OpError, update.eval) local_variables = variables.local_variables() variables.variables_initializer(local_variables).run() # Run per-step op and assert expected values. if math.isnan(expected): _assert_nan(self, update.eval()) _assert_nan(self, metric.eval()) else: self.assertAlmostEqual(expected, update.eval()) self.assertAlmostEqual(expected, metric.eval()) def test_top_k_rank_invalid(self): with self.test_session(): # top_k_predictions has rank < 2. top_k_predictions = [9, 4, 6, 2, 0] sp_labels = sparse_tensor.SparseTensorValue( indices=np.array([[ 0, ], [ 1, ], [ 2, ]], np.int64), values=np.array([2, 7, 8], np.int64), dense_shape=np.array([ 10, ], np.int64)) with self.assertRaises(ValueError): precision, _ = metrics.streaming_sparse_precision_at_top_k( top_k_predictions=constant_op.constant(top_k_predictions, dtypes_lib.int64), labels=sp_labels) variables.variables_initializer(variables.local_variables()).run() precision.eval() def test_average_precision(self): # Example 1. # Matches example here: # fastml.com/what-you-wanted-to-know-about-mean-average-precision labels_ex1 = (0, 1, 2, 3, 4) labels = np.array([labels_ex1], dtype=np.int64) predictions_ex1 = (0.2, 0.1, 0.0, 0.4, 0.0, 0.5, 0.3) predictions = (predictions_ex1,) predictions_top_k_ex1 = (5, 3, 6, 0, 1, 2) precision_ex1 = (0.0 / 1, 1.0 / 2, 1.0 / 3, 2.0 / 4) avg_precision_ex1 = (0.0 / 1, precision_ex1[1] / 2, precision_ex1[1] / 3, (precision_ex1[1] + precision_ex1[3]) / 4) for i in xrange(4): k = i + 1 self._test_streaming_sparse_precision_at_k( predictions, labels, k, expected=precision_ex1[i]) self._test_streaming_sparse_precision_at_top_k( (predictions_top_k_ex1[:k],), labels, expected=precision_ex1[i]) self._test_streaming_sparse_average_precision_at_k( predictions, labels, k, expected=avg_precision_ex1[i]) self._test_streaming_sparse_average_precision_at_top_k( (predictions_top_k_ex1[:k],), labels, expected=avg_precision_ex1[i]) # Example 2. labels_ex2 = (0, 2, 4, 5, 6) labels = np.array([labels_ex2], dtype=np.int64) predictions_ex2 = (0.3, 0.5, 0.0, 0.4, 0.0, 0.1, 0.2) predictions = (predictions_ex2,) predictions_top_k_ex2 = (1, 3, 0, 6, 5) precision_ex2 = (0.0 / 1, 0.0 / 2, 1.0 / 3, 2.0 / 4) avg_precision_ex2 = (0.0 / 1, 0.0 / 2, precision_ex2[2] / 3, (precision_ex2[2] + precision_ex2[3]) / 4) for i in xrange(4): k = i + 1 self._test_streaming_sparse_precision_at_k( predictions, labels, k, expected=precision_ex2[i]) self._test_streaming_sparse_precision_at_top_k( (predictions_top_k_ex2[:k],), labels, expected=precision_ex2[i]) self._test_streaming_sparse_average_precision_at_k( predictions, labels, k, expected=avg_precision_ex2[i]) self._test_streaming_sparse_average_precision_at_top_k( (predictions_top_k_ex2[:k],), labels, expected=avg_precision_ex2[i]) # Both examples, we expect both precision and average precision to be the # average of the 2 examples. labels = np.array([labels_ex1, labels_ex2], dtype=np.int64) predictions = (predictions_ex1, predictions_ex2) streaming_precision = [ (ex1 + ex2) / 2 for ex1, ex2 in zip(precision_ex1, precision_ex2) ] streaming_average_precision = [ (ex1 + ex2) / 2 for ex1, ex2 in zip(avg_precision_ex1, avg_precision_ex2) ] for i in xrange(4): k = i + 1 self._test_streaming_sparse_precision_at_k( predictions, labels, k, expected=streaming_precision[i]) predictions_top_k = (predictions_top_k_ex1[:k], predictions_top_k_ex2[:k]) self._test_streaming_sparse_precision_at_top_k( predictions_top_k, labels, expected=streaming_precision[i]) self._test_streaming_sparse_average_precision_at_k( predictions, labels, k, expected=streaming_average_precision[i]) self._test_streaming_sparse_average_precision_at_top_k( predictions_top_k, labels, expected=streaming_average_precision[i]) # Weighted examples, we expect streaming average precision to be the # weighted average of the 2 examples. weights = (0.3, 0.6) streaming_average_precision = [ (weights[0] * ex1 + weights[1] * ex2) / (weights[0] + weights[1]) for ex1, ex2 in zip(avg_precision_ex1, avg_precision_ex2) ] for i in xrange(4): k = i + 1 self._test_streaming_sparse_average_precision_at_k( predictions, labels, k, expected=streaming_average_precision[i], weights=weights) self._test_streaming_sparse_average_precision_at_top_k( (predictions_top_k_ex1[:k], predictions_top_k_ex2[:k]), labels, expected=streaming_average_precision[i], weights=weights) def test_average_precision_some_labels_out_of_range(self): """Tests that labels outside the [0, n_classes) range are ignored.""" labels_ex1 = (-1, 0, 1, 2, 3, 4, 7) labels = np.array([labels_ex1], dtype=np.int64) predictions_ex1 = (0.2, 0.1, 0.0, 0.4, 0.0, 0.5, 0.3) predictions = (predictions_ex1,) predictions_top_k_ex1 = (5, 3, 6, 0, 1, 2) precision_ex1 = (0.0 / 1, 1.0 / 2, 1.0 / 3, 2.0 / 4) avg_precision_ex1 = (0.0 / 1, precision_ex1[1] / 2, precision_ex1[1] / 3, (precision_ex1[1] + precision_ex1[3]) / 4) for i in xrange(4): k = i + 1 self._test_streaming_sparse_precision_at_k( predictions, labels, k, expected=precision_ex1[i]) self._test_streaming_sparse_precision_at_top_k( (predictions_top_k_ex1[:k],), labels, expected=precision_ex1[i]) self._test_streaming_sparse_average_precision_at_k( predictions, labels, k, expected=avg_precision_ex1[i]) self._test_streaming_sparse_average_precision_at_top_k( (predictions_top_k_ex1[:k],), labels, expected=avg_precision_ex1[i]) def test_average_precision_at_top_k_static_shape_check(self): predictions_top_k = array_ops.placeholder( shape=(2, None), dtype=dtypes_lib.int64) labels = np.array(((1,), (2,)), dtype=np.int64) # Fails due to non-static predictions_idx shape. with self.assertRaises(ValueError): metric_ops.streaming_sparse_average_precision_at_top_k( predictions_top_k, labels) predictions_top_k = (2, 1) # Fails since rank of predictions_idx is less than one. with self.assertRaises(ValueError): metric_ops.streaming_sparse_average_precision_at_top_k( predictions_top_k, labels) predictions_top_k = ((2,), (1,)) # Valid static shape. metric_ops.streaming_sparse_average_precision_at_top_k( predictions_top_k, labels) def test_one_label_at_k1_nan(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] top_k_predictions = [[3], [3]] sparse_labels = _binary_2d_label_to_sparse_value([[0, 0, 0, 1], [0, 0, 1, 0]]) dense_labels = np.array([[3], [2]], dtype=np.int64) for labels in (sparse_labels, dense_labels): # Classes 0,1,2 have 0 predictions, classes -1 and 4 are out of range. for class_id in (-1, 0, 1, 2, 4): self._test_streaming_sparse_precision_at_k( predictions, labels, k=1, expected=NAN, class_id=class_id) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, class_id=class_id) def test_one_label_at_k1(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] top_k_predictions = [[3], [3]] sparse_labels = _binary_2d_label_to_sparse_value([[0, 0, 0, 1], [0, 0, 1, 0]]) dense_labels = np.array([[3], [2]], dtype=np.int64) for labels in (sparse_labels, dense_labels): # Class 3: 1 label, 2 predictions, 1 correct. self._test_streaming_sparse_precision_at_k( predictions, labels, k=1, expected=1.0 / 2, class_id=3) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=1.0 / 2, class_id=3) # All classes: 2 labels, 2 predictions, 1 correct. self._test_streaming_sparse_precision_at_k( predictions, labels, k=1, expected=1.0 / 2) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=1.0 / 2) def test_three_labels_at_k5_no_predictions(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sparse_labels = _binary_2d_label_to_sparse_value( [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]]) dense_labels = np.array([[2, 7, 8], [1, 2, 5]], dtype=np.int64) for labels in (sparse_labels, dense_labels): # Classes 1,3,8 have 0 predictions, classes -1 and 10 are out of range. for class_id in (-1, 1, 3, 8, 10): self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, class_id=class_id) def test_three_labels_at_k5_no_labels(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sparse_labels = _binary_2d_label_to_sparse_value( [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]]) dense_labels = np.array([[2, 7, 8], [1, 2, 5]], dtype=np.int64) for labels in (sparse_labels, dense_labels): # Classes 0,4,6,9: 0 labels, >=1 prediction. for class_id in (0, 4, 6, 9): self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=0.0, class_id=class_id) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=0.0, class_id=class_id) def test_three_labels_at_k5(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sparse_labels = _binary_2d_label_to_sparse_value( [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]]) dense_labels = np.array([[2, 7, 8], [1, 2, 5]], dtype=np.int64) for labels in (sparse_labels, dense_labels): # Class 2: 2 labels, 2 correct predictions. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=2.0 / 2, class_id=2) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=2.0 / 2, class_id=2) # Class 5: 1 label, 1 correct prediction. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=1.0 / 1, class_id=5) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=1.0 / 1, class_id=5) # Class 7: 1 label, 1 incorrect prediction. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=0.0 / 1, class_id=7) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=0.0 / 1, class_id=7) # All classes: 10 predictions, 3 correct. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=3.0 / 10) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=3.0 / 10) def test_three_labels_at_k5_some_out_of_range(self): """Tests that labels outside the [0, n_classes) range are ignored.""" predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sp_labels = sparse_tensor.SparseTensorValue( indices=[[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3]], # values -1 and 10 are outside the [0, n_classes) range and are ignored. values=np.array([2, 7, -1, 8, 1, 2, 5, 10], np.int64), dense_shape=[2, 4]) # Class 2: 2 labels, 2 correct predictions. self._test_streaming_sparse_precision_at_k( predictions, sp_labels, k=5, expected=2.0 / 2, class_id=2) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, sp_labels, expected=2.0 / 2, class_id=2) # Class 5: 1 label, 1 correct prediction. self._test_streaming_sparse_precision_at_k( predictions, sp_labels, k=5, expected=1.0 / 1, class_id=5) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, sp_labels, expected=1.0 / 1, class_id=5) # Class 7: 1 label, 1 incorrect prediction. self._test_streaming_sparse_precision_at_k( predictions, sp_labels, k=5, expected=0.0 / 1, class_id=7) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, sp_labels, expected=0.0 / 1, class_id=7) # All classes: 10 predictions, 3 correct. self._test_streaming_sparse_precision_at_k( predictions, sp_labels, k=5, expected=3.0 / 10) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, sp_labels, expected=3.0 / 10) def test_3d_nan(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) # Classes 1,3,8 have 0 predictions, classes -1 and 10 are out of range. for class_id in (-1, 1, 3, 8, 10): self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, class_id=class_id) def test_3d_no_labels(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) # Classes 0,4,6,9: 0 labels, >=1 prediction. for class_id in (0, 4, 6, 9): self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=0.0, class_id=class_id) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=0.0, class_id=class_id) def test_3d(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) # Class 2: 4 predictions, all correct. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=4.0 / 4, class_id=2) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=4.0 / 4, class_id=2) # Class 5: 2 predictions, both correct. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=2.0 / 2, class_id=5) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=2.0 / 2, class_id=5) # Class 7: 2 predictions, 1 correct. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=1.0 / 2, class_id=7) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=1.0 / 2, class_id=7) # All classes: 20 predictions, 7 correct. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=7.0 / 20) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=7.0 / 20) def test_3d_ignore_all(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) for class_id in xrange(10): self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id, weights=[[0], [0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, class_id=class_id, weights=[[0], [0]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id, weights=[[0, 0], [0, 0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, class_id=class_id, weights=[[0, 0], [0, 0]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, weights=[[0], [0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, weights=[[0], [0]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, weights=[[0, 0], [0, 0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, weights=[[0, 0], [0, 0]]) def test_3d_ignore_some(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) # Class 2: 2 predictions, both correct. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=2.0 / 2.0, class_id=2, weights=[[1], [0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=2.0 / 2.0, class_id=2, weights=[[1], [0]]) # Class 2: 2 predictions, both correct. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=2.0 / 2.0, class_id=2, weights=[[0], [1]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=2.0 / 2.0, class_id=2, weights=[[0], [1]]) # Class 7: 1 incorrect prediction. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=0.0 / 1.0, class_id=7, weights=[[1], [0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=0.0 / 1.0, class_id=7, weights=[[1], [0]]) # Class 7: 1 correct prediction. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=1.0 / 1.0, class_id=7, weights=[[0], [1]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=1.0 / 1.0, class_id=7, weights=[[0], [1]]) # Class 7: no predictions. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, class_id=7, weights=[[1, 0], [0, 1]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, class_id=7, weights=[[1, 0], [0, 1]]) # Class 7: 2 predictions, 1 correct. self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=1.0 / 2.0, class_id=7, weights=[[0, 1], [1, 0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=1.0 / 2.0, class_id=7, weights=[[0, 1], [1, 0]]) def test_sparse_tensor_value(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] labels = [[0, 0, 0, 1], [0, 0, 1, 0]] expected_precision = 0.5 with self.test_session(): _, precision = metrics.streaming_sparse_precision_at_k( predictions=constant_op.constant(predictions, dtypes_lib.float32), labels=_binary_2d_label_to_sparse_value(labels), k=1) variables.variables_initializer(variables.local_variables()).run() self.assertEqual(expected_precision, precision.eval()) class StreamingSparseRecallTest(test.TestCase): def _test_streaming_sparse_recall_at_k(self, predictions, labels, k, expected, class_id=None, weights=None): with ops.Graph().as_default() as g, self.session(g): if weights is not None: weights = constant_op.constant(weights, dtypes_lib.float32) metric, update = metrics.streaming_sparse_recall_at_k( predictions=constant_op.constant(predictions, dtypes_lib.float32), labels=labels, k=k, class_id=class_id, weights=weights) # Fails without initialized vars. self.assertRaises(errors_impl.OpError, metric.eval) self.assertRaises(errors_impl.OpError, update.eval) variables.variables_initializer(variables.local_variables()).run() # Run per-step op and assert expected values. if math.isnan(expected): _assert_nan(self, update.eval()) _assert_nan(self, metric.eval()) else: self.assertEqual(expected, update.eval()) self.assertEqual(expected, metric.eval()) def _test_sparse_recall_at_top_k(self, labels, top_k_predictions, expected, class_id=None, weights=None): with ops.Graph().as_default() as g, self.session(g): if weights is not None: weights = constant_op.constant(weights, dtypes_lib.float32) metric, update = metric_ops.sparse_recall_at_top_k( labels=labels, top_k_predictions=constant_op.constant(top_k_predictions, dtypes_lib.int32), class_id=class_id, weights=weights) # Fails without initialized vars. self.assertRaises(errors_impl.OpError, metric.eval) self.assertRaises(errors_impl.OpError, update.eval) variables.variables_initializer(variables.local_variables()).run() # Run per-step op and assert expected values. if math.isnan(expected): self.assertTrue(math.isnan(update.eval())) self.assertTrue(math.isnan(metric.eval())) else: self.assertEqual(expected, update.eval()) self.assertEqual(expected, metric.eval()) def test_one_label_at_k1_nan(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] top_k_predictions = [[3], [3]] sparse_labels = _binary_2d_label_to_sparse_value([[0, 0, 0, 1], [0, 0, 1, 0]]) dense_labels = np.array([[3], [2]], dtype=np.int64) # Classes 0,1 have 0 labels, 0 predictions, classes -1 and 4 are out of # range. for labels in (sparse_labels, dense_labels): for class_id in (-1, 0, 1, 4): self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=NAN, class_id=class_id) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=class_id) def test_one_label_at_k1_no_predictions(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] top_k_predictions = [[3], [3]] sparse_labels = _binary_2d_label_to_sparse_value([[0, 0, 0, 1], [0, 0, 1, 0]]) dense_labels = np.array([[3], [2]], dtype=np.int64) for labels in (sparse_labels, dense_labels): # Class 2: 0 predictions. self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=0.0, class_id=2) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.0, class_id=2) def test_one_label_at_k1(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] top_k_predictions = [[3], [3]] sparse_labels = _binary_2d_label_to_sparse_value([[0, 0, 0, 1], [0, 0, 1, 0]]) dense_labels = np.array([[3], [2]], dtype=np.int64) for labels in (sparse_labels, dense_labels): # Class 3: 1 label, 2 predictions, 1 correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 1, class_id=3) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, class_id=3) # All classes: 2 labels, 2 predictions, 1 correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 2) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 2) def _test_one_label_at_k1_weighted(self, labels): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] top_k_predictions = [[3], [3]] # Class 3: 1 label, 2 predictions, 1 correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=NAN, class_id=3, weights=(0.0,)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=3, weights=(0.0,)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 1, class_id=3, weights=(1.0,)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, class_id=3, weights=(1.0,)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 1, class_id=3, weights=(2.0,)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, class_id=3, weights=(2.0,)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=NAN, class_id=3, weights=(0.0, 0.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=3, weights=(0.0, 0.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=NAN, class_id=3, weights=(0.0, 1.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=3, weights=(0.0, 1.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 1, class_id=3, weights=(1.0, 0.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, class_id=3, weights=(1.0, 0.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 1, class_id=3, weights=(1.0, 1.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, class_id=3, weights=(1.0, 1.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=2.0 / 2, class_id=3, weights=(2.0, 3.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=2.0 / 2, class_id=3, weights=(2.0, 3.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=3.0 / 3, class_id=3, weights=(3.0, 2.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=3.0 / 3, class_id=3, weights=(3.0, 2.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=0.3 / 0.3, class_id=3, weights=(0.3, 0.6)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.3 / 0.3, class_id=3, weights=(0.3, 0.6)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=0.6 / 0.6, class_id=3, weights=(0.6, 0.3)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.6 / 0.6, class_id=3, weights=(0.6, 0.3)) # All classes: 2 labels, 2 predictions, 1 correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=NAN, weights=(0.0,)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, weights=(0.0,)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 2, weights=(1.0,)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 2, weights=(1.0,)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 2, weights=(2.0,)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 2, weights=(2.0,)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 1, weights=(1.0, 0.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, weights=(1.0, 0.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=0.0 / 1, weights=(0.0, 1.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.0 / 1, weights=(0.0, 1.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 2, weights=(1.0, 1.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 2, weights=(1.0, 1.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=2.0 / 5, weights=(2.0, 3.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=2.0 / 5, weights=(2.0, 3.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=3.0 / 5, weights=(3.0, 2.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=3.0 / 5, weights=(3.0, 2.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=0.3 / 0.9, weights=(0.3, 0.6)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.3 / 0.9, weights=(0.3, 0.6)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=0.6 / 0.9, weights=(0.6, 0.3)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.6 / 0.9, weights=(0.6, 0.3)) def test_one_label_at_k1_weighted_sparse_labels(self): sparse_labels = _binary_2d_label_to_sparse_value([[0, 0, 0, 1], [0, 0, 1, 0]]) self._test_one_label_at_k1_weighted(sparse_labels) def test_one_label_at_k1_weighted_dense_labels(self): dense_labels = np.array([[3], [2]], dtype=np.int64) self._test_one_label_at_k1_weighted(dense_labels) def test_three_labels_at_k5_nan(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sparse_labels = _binary_2d_label_to_sparse_value( [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]]) dense_labels = np.array([[2, 7, 8], [1, 2, 5]], dtype=np.int64) for labels in (sparse_labels, dense_labels): # Classes 0,3,4,6,9 have 0 labels, class 10 is out of range. for class_id in (0, 3, 4, 6, 9, 10): self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=class_id) def test_three_labels_at_k5_no_predictions(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sparse_labels = _binary_2d_label_to_sparse_value( [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]]) dense_labels = np.array([[2, 7, 8], [1, 2, 5]], dtype=np.int64) for labels in (sparse_labels, dense_labels): # Class 8: 1 label, no predictions. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=0.0 / 1, class_id=8) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.0 / 1, class_id=8) def test_three_labels_at_k5(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sparse_labels = _binary_2d_label_to_sparse_value( [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]]) dense_labels = np.array([[2, 7, 8], [1, 2, 5]], dtype=np.int64) for labels in (sparse_labels, dense_labels): # Class 2: 2 labels, both correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=2.0 / 2, class_id=2) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=2.0 / 2, class_id=2) # Class 5: 1 label, incorrect. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=1.0 / 1, class_id=5) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, class_id=5) # Class 7: 1 label, incorrect. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=0.0 / 1, class_id=7) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.0 / 1, class_id=7) # All classes: 6 labels, 3 correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=3.0 / 6) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=3.0 / 6) def test_three_labels_at_k5_some_out_of_range(self): """Tests that labels outside the [0, n_classes) count in denominator.""" predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sp_labels = sparse_tensor.SparseTensorValue( indices=[[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3]], # values -1 and 10 are outside the [0, n_classes) range. values=np.array([2, 7, -1, 8, 1, 2, 5, 10], np.int64), dense_shape=[2, 4]) # Class 2: 2 labels, both correct. self._test_streaming_sparse_recall_at_k( predictions=predictions, labels=sp_labels, k=5, expected=2.0 / 2, class_id=2) self._test_sparse_recall_at_top_k( sp_labels, top_k_predictions, expected=2.0 / 2, class_id=2) # Class 5: 1 label, incorrect. self._test_streaming_sparse_recall_at_k( predictions=predictions, labels=sp_labels, k=5, expected=1.0 / 1, class_id=5) self._test_sparse_recall_at_top_k( sp_labels, top_k_predictions, expected=1.0 / 1, class_id=5) # Class 7: 1 label, incorrect. self._test_streaming_sparse_recall_at_k( predictions=predictions, labels=sp_labels, k=5, expected=0.0 / 1, class_id=7) self._test_sparse_recall_at_top_k( sp_labels, top_k_predictions, expected=0.0 / 1, class_id=7) # All classes: 8 labels, 3 correct. self._test_streaming_sparse_recall_at_k( predictions=predictions, labels=sp_labels, k=5, expected=3.0 / 8) self._test_sparse_recall_at_top_k( sp_labels, top_k_predictions, expected=3.0 / 8) def test_3d_nan(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] sparse_labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 1, 1, 0]]]) dense_labels = np.array( [[[2, 7, 8], [1, 2, 5]], [ [1, 2, 5], [2, 7, 8], ]], dtype=np.int64) for labels in (sparse_labels, dense_labels): # Classes 0,3,4,6,9 have 0 labels, class 10 is out of range. for class_id in (0, 3, 4, 6, 9, 10): self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=class_id) def test_3d_no_predictions(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] sparse_labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 1, 1, 0]]]) dense_labels = np.array( [[[2, 7, 8], [1, 2, 5]], [ [1, 2, 5], [2, 7, 8], ]], dtype=np.int64) for labels in (sparse_labels, dense_labels): # Classes 1,8 have 0 predictions, >=1 label. for class_id in (1, 8): self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=0.0, class_id=class_id) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.0, class_id=class_id) def test_3d(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) # Class 2: 4 labels, all correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=4.0 / 4, class_id=2) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=4.0 / 4, class_id=2) # Class 5: 2 labels, both correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=2.0 / 2, class_id=5) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=2.0 / 2, class_id=5) # Class 7: 2 labels, 1 incorrect. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=1.0 / 2, class_id=7) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 2, class_id=7) # All classes: 12 labels, 7 correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=7.0 / 12) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=7.0 / 12) def test_3d_ignore_all(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) for class_id in xrange(10): self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id, weights=[[0], [0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=class_id, weights=[[0], [0]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id, weights=[[0, 0], [0, 0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=class_id, weights=[[0, 0], [0, 0]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, weights=[[0], [0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, weights=[[0], [0]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, weights=[[0, 0], [0, 0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, weights=[[0, 0], [0, 0]]) def test_3d_ignore_some(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) # Class 2: 2 labels, both correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=2.0 / 2.0, class_id=2, weights=[[1], [0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=2.0 / 2.0, class_id=2, weights=[[1], [0]]) # Class 2: 2 labels, both correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=2.0 / 2.0, class_id=2, weights=[[0], [1]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=2.0 / 2.0, class_id=2, weights=[[0], [1]]) # Class 7: 1 label, correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=1.0 / 1.0, class_id=7, weights=[[0], [1]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1.0, class_id=7, weights=[[0], [1]]) # Class 7: 1 label, incorrect. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=0.0 / 1.0, class_id=7, weights=[[1], [0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.0 / 1.0, class_id=7, weights=[[1], [0]]) # Class 7: 2 labels, 1 correct. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=1.0 / 2.0, class_id=7, weights=[[1, 0], [1, 0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 2.0, class_id=7, weights=[[1, 0], [1, 0]]) # Class 7: No labels. self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, class_id=7, weights=[[0, 1], [0, 1]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=7, weights=[[0, 1], [0, 1]]) def test_sparse_tensor_value(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] labels = [[0, 0, 1, 0], [0, 0, 0, 1]] expected_recall = 0.5 with self.test_session(): _, recall = metrics.streaming_sparse_recall_at_k( predictions=constant_op.constant(predictions, dtypes_lib.float32), labels=_binary_2d_label_to_sparse_value(labels), k=1) variables.variables_initializer(variables.local_variables()).run() self.assertEqual(expected_recall, recall.eval()) class StreamingMeanAbsoluteErrorTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_mean_absolute_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables( self, ('mean_absolute_error/count:0', 'mean_absolute_error/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_mean_absolute_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean_absolute_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_normal((10, 3), seed=1) labels = random_ops.random_normal((10, 3), seed=2) error, update_op = metrics.streaming_mean_absolute_error( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_error = error.eval() for _ in range(10): self.assertEqual(initial_error, error.eval()) def testSingleUpdateWithErrorAndWeights(self): predictions = constant_op.constant( [2, 4, 6, 8], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2, 3], shape=(1, 4), dtype=dtypes_lib.float32) weights = constant_op.constant([0, 1, 0, 1], shape=(1, 4)) error, update_op = metrics.streaming_mean_absolute_error( predictions, labels, weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(3, sess.run(update_op)) self.assertEqual(3, error.eval()) class StreamingMeanRelativeErrorTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_mean_relative_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), normalizer=array_ops.ones((10, 1))) _assert_metric_variables( self, ('mean_relative_error/count:0', 'mean_relative_error/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_mean_relative_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), normalizer=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean_relative_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), normalizer=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_normal((10, 3), seed=1) labels = random_ops.random_normal((10, 3), seed=2) normalizer = random_ops.random_normal((10, 3), seed=3) error, update_op = metrics.streaming_mean_relative_error( predictions, labels, normalizer) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_error = error.eval() for _ in range(10): self.assertEqual(initial_error, error.eval()) def testSingleUpdateNormalizedByLabels(self): np_predictions = np.asarray([2, 4, 6, 8], dtype=np.float32) np_labels = np.asarray([1, 3, 2, 3], dtype=np.float32) expected_error = np.mean( np.divide(np.absolute(np_predictions - np_labels), np_labels)) predictions = constant_op.constant( np_predictions, shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant(np_labels, shape=(1, 4)) error, update_op = metrics.streaming_mean_relative_error( predictions, labels, normalizer=labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(expected_error, sess.run(update_op)) self.assertEqual(expected_error, error.eval()) def testSingleUpdateNormalizedByZeros(self): np_predictions = np.asarray([2, 4, 6, 8], dtype=np.float32) predictions = constant_op.constant( np_predictions, shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2, 3], shape=(1, 4), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_relative_error( predictions, labels, normalizer=array_ops.zeros_like(labels)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0.0, sess.run(update_op)) self.assertEqual(0.0, error.eval()) class StreamingMeanSquaredErrorTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables( self, ('mean_squared_error/count:0', 'mean_squared_error/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_normal((10, 3), seed=1) labels = random_ops.random_normal((10, 3), seed=2) error, update_op = metrics.streaming_mean_squared_error(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_error = error.eval() for _ in range(10): self.assertEqual(initial_error, error.eval()) def testSingleUpdateZeroError(self): predictions = array_ops.zeros((1, 3), dtype=dtypes_lib.float32) labels = array_ops.zeros((1, 3), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_squared_error(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, sess.run(update_op)) self.assertEqual(0, error.eval()) def testSingleUpdateWithError(self): predictions = constant_op.constant( [2, 4, 6], shape=(1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2], shape=(1, 3), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_squared_error(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(6, sess.run(update_op)) self.assertEqual(6, error.eval()) def testSingleUpdateWithErrorAndWeights(self): predictions = constant_op.constant( [2, 4, 6, 8], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2, 3], shape=(1, 4), dtype=dtypes_lib.float32) weights = constant_op.constant([0, 1, 0, 1], shape=(1, 4)) error, update_op = metrics.streaming_mean_squared_error( predictions, labels, weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(13, sess.run(update_op)) self.assertEqual(13, error.eval()) def testMultipleBatchesOfSizeOne(self): with self.test_session() as sess: # Create the queue that populates the predictions. preds_queue = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, preds_queue, [10, 8, 6]) _enqueue_vector(sess, preds_queue, [-4, 3, -1]) predictions = preds_queue.dequeue() # Create the queue that populates the labels. labels_queue = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, labels_queue, [1, 3, 2]) _enqueue_vector(sess, labels_queue, [2, 4, 6]) labels = labels_queue.dequeue() error, update_op = metrics.streaming_mean_squared_error( predictions, labels) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(208.0 / 6, sess.run(update_op), 5) self.assertAlmostEqual(208.0 / 6, error.eval(), 5) def testMetricsComputedConcurrently(self): with self.test_session() as sess: # Create the queue that populates one set of predictions. preds_queue0 = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, preds_queue0, [10, 8, 6]) _enqueue_vector(sess, preds_queue0, [-4, 3, -1]) predictions0 = preds_queue0.dequeue() # Create the queue that populates one set of predictions. preds_queue1 = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, preds_queue1, [0, 1, 1]) _enqueue_vector(sess, preds_queue1, [1, 1, 0]) predictions1 = preds_queue1.dequeue() # Create the queue that populates one set of labels. labels_queue0 = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, labels_queue0, [1, 3, 2]) _enqueue_vector(sess, labels_queue0, [2, 4, 6]) labels0 = labels_queue0.dequeue() # Create the queue that populates another set of labels. labels_queue1 = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, labels_queue1, [-5, -3, -1]) _enqueue_vector(sess, labels_queue1, [5, 4, 3]) labels1 = labels_queue1.dequeue() mse0, update_op0 = metrics.streaming_mean_squared_error( predictions0, labels0, name='msd0') mse1, update_op1 = metrics.streaming_mean_squared_error( predictions1, labels1, name='msd1') sess.run(variables.local_variables_initializer()) sess.run([update_op0, update_op1]) sess.run([update_op0, update_op1]) mse0, mse1 = sess.run([mse0, mse1]) self.assertAlmostEqual(208.0 / 6, mse0, 5) self.assertAlmostEqual(79.0 / 6, mse1, 5) def testMultipleMetricsOnMultipleBatchesOfSizeOne(self): with self.test_session() as sess: # Create the queue that populates the predictions. preds_queue = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, preds_queue, [10, 8, 6]) _enqueue_vector(sess, preds_queue, [-4, 3, -1]) predictions = preds_queue.dequeue() # Create the queue that populates the labels. labels_queue = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, labels_queue, [1, 3, 2]) _enqueue_vector(sess, labels_queue, [2, 4, 6]) labels = labels_queue.dequeue() mae, ma_update_op = metrics.streaming_mean_absolute_error( predictions, labels) mse, ms_update_op = metrics.streaming_mean_squared_error( predictions, labels) sess.run(variables.local_variables_initializer()) sess.run([ma_update_op, ms_update_op]) sess.run([ma_update_op, ms_update_op]) self.assertAlmostEqual(32.0 / 6, mae.eval(), 5) self.assertAlmostEqual(208.0 / 6, mse.eval(), 5) class StreamingRootMeanSquaredErrorTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_root_mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables( self, ('root_mean_squared_error/count:0', 'root_mean_squared_error/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_root_mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_root_mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_normal((10, 3), seed=1) labels = random_ops.random_normal((10, 3), seed=2) error, update_op = metrics.streaming_root_mean_squared_error( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_error = error.eval() for _ in range(10): self.assertEqual(initial_error, error.eval()) def testSingleUpdateZeroError(self): with self.test_session() as sess: predictions = constant_op.constant( 0.0, shape=(1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant(0.0, shape=(1, 3), dtype=dtypes_lib.float32) rmse, update_op = metrics.streaming_root_mean_squared_error( predictions, labels) sess.run(variables.local_variables_initializer()) self.assertEqual(0, sess.run(update_op)) self.assertEqual(0, rmse.eval()) def testSingleUpdateWithError(self): with self.test_session() as sess: predictions = constant_op.constant( [2, 4, 6], shape=(1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2], shape=(1, 3), dtype=dtypes_lib.float32) rmse, update_op = metrics.streaming_root_mean_squared_error( predictions, labels) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(math.sqrt(6), update_op.eval(), 5) self.assertAlmostEqual(math.sqrt(6), rmse.eval(), 5) def testSingleUpdateWithErrorAndWeights(self): with self.test_session() as sess: predictions = constant_op.constant( [2, 4, 6, 8], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2, 3], shape=(1, 4), dtype=dtypes_lib.float32) weights = constant_op.constant([0, 1, 0, 1], shape=(1, 4)) rmse, update_op = metrics.streaming_root_mean_squared_error( predictions, labels, weights) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(math.sqrt(13), sess.run(update_op)) self.assertAlmostEqual(math.sqrt(13), rmse.eval(), 5) class StreamingCovarianceTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_covariance( predictions=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), labels=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10])) _assert_metric_variables(self, ( 'covariance/comoment:0', 'covariance/count:0', 'covariance/mean_label:0', 'covariance/mean_prediction:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' cov, _ = metrics.streaming_covariance( predictions=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), labels=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [cov]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_covariance( predictions=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), labels=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): labels = random_ops.random_normal((10, 3), seed=2) predictions = labels * 0.5 + random_ops.random_normal((10, 3), seed=1) * 0.5 cov, update_op = metrics.streaming_covariance(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_cov = cov.eval() for _ in range(10): self.assertEqual(initial_cov, cov.eval()) def testSingleUpdateIdentical(self): with self.test_session() as sess: predictions = math_ops.to_float(math_ops.range(10)) labels = math_ops.to_float(math_ops.range(10)) cov, update_op = metrics.streaming_covariance(predictions, labels) expected_cov = np.cov(np.arange(10), np.arange(10))[0, 1] sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expected_cov, sess.run(update_op), 5) self.assertAlmostEqual(expected_cov, cov.eval(), 5) def testSingleUpdateNonIdentical(self): with self.test_session() as sess: predictions = constant_op.constant( [2, 4, 6], shape=(1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2], shape=(1, 3), dtype=dtypes_lib.float32) cov, update_op = metrics.streaming_covariance(predictions, labels) expected_cov = np.cov([2, 4, 6], [1, 3, 2])[0, 1] sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expected_cov, update_op.eval()) self.assertAlmostEqual(expected_cov, cov.eval()) def testSingleUpdateWithErrorAndWeights(self): with self.test_session() as sess: predictions = constant_op.constant( [2, 4, 6, 8], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2, 7], shape=(1, 4), dtype=dtypes_lib.float32) weights = constant_op.constant( [0, 1, 3, 1], shape=(1, 4), dtype=dtypes_lib.float32) cov, update_op = metrics.streaming_covariance( predictions, labels, weights=weights) expected_cov = np.cov( [2, 4, 6, 8], [1, 3, 2, 7], fweights=[0, 1, 3, 1])[0, 1] sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expected_cov, sess.run(update_op)) self.assertAlmostEqual(expected_cov, cov.eval()) def testMultiUpdateWithErrorNoWeights(self): with self.test_session() as sess: np.random.seed(123) n = 100 predictions = np.random.randn(n) labels = 0.5 * predictions + np.random.randn(n) stride = 10 predictions_t = array_ops.placeholder(dtypes_lib.float32, [stride]) labels_t = array_ops.placeholder(dtypes_lib.float32, [stride]) cov, update_op = metrics.streaming_covariance(predictions_t, labels_t) sess.run(variables.local_variables_initializer()) prev_expected_cov = NAN for i in range(n // stride): feed_dict = { predictions_t: predictions[stride * i:stride * (i + 1)], labels_t: labels[stride * i:stride * (i + 1)] } self.assertEqual( np.isnan(prev_expected_cov), np.isnan(sess.run(cov, feed_dict=feed_dict))) if not np.isnan(prev_expected_cov): self.assertAlmostEqual(prev_expected_cov, sess.run(cov, feed_dict=feed_dict), 5) expected_cov = np.cov(predictions[:stride * (i + 1)], labels[:stride * (i + 1)])[0, 1] self.assertAlmostEqual(expected_cov, sess.run(update_op, feed_dict=feed_dict), 5) self.assertAlmostEqual(expected_cov, sess.run(cov, feed_dict=feed_dict), 5) prev_expected_cov = expected_cov def testMultiUpdateWithErrorAndWeights(self): with self.test_session() as sess: np.random.seed(123) n = 100 predictions = np.random.randn(n) labels = 0.5 * predictions + np.random.randn(n) weights = np.tile(np.arange(n // 10), n // 10) np.random.shuffle(weights) stride = 10 predictions_t = array_ops.placeholder(dtypes_lib.float32, [stride]) labels_t = array_ops.placeholder(dtypes_lib.float32, [stride]) weights_t = array_ops.placeholder(dtypes_lib.float32, [stride]) cov, update_op = metrics.streaming_covariance( predictions_t, labels_t, weights=weights_t) sess.run(variables.local_variables_initializer()) prev_expected_cov = NAN for i in range(n // stride): feed_dict = { predictions_t: predictions[stride * i:stride * (i + 1)], labels_t: labels[stride * i:stride * (i + 1)], weights_t: weights[stride * i:stride * (i + 1)] } self.assertEqual( np.isnan(prev_expected_cov), np.isnan(sess.run(cov, feed_dict=feed_dict))) if not np.isnan(prev_expected_cov): self.assertAlmostEqual(prev_expected_cov, sess.run(cov, feed_dict=feed_dict), 5) expected_cov = np.cov( predictions[:stride * (i + 1)], labels[:stride * (i + 1)], fweights=weights[:stride * (i + 1)])[0, 1] self.assertAlmostEqual(expected_cov, sess.run(update_op, feed_dict=feed_dict), 5) self.assertAlmostEqual(expected_cov, sess.run(cov, feed_dict=feed_dict), 5) prev_expected_cov = expected_cov class StreamingPearsonRTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_pearson_correlation( predictions=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), labels=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10])) _assert_metric_variables(self, ( 'pearson_r/covariance/comoment:0', 'pearson_r/covariance/count:0', 'pearson_r/covariance/mean_label:0', 'pearson_r/covariance/mean_prediction:0', 'pearson_r/variance_labels/count:0', 'pearson_r/variance_labels/comoment:0', 'pearson_r/variance_labels/mean_label:0', 'pearson_r/variance_labels/mean_prediction:0', 'pearson_r/variance_predictions/comoment:0', 'pearson_r/variance_predictions/count:0', 'pearson_r/variance_predictions/mean_label:0', 'pearson_r/variance_predictions/mean_prediction:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' pearson_r, _ = metrics.streaming_pearson_correlation( predictions=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), labels=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [pearson_r]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_pearson_correlation( predictions=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), labels=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): labels = random_ops.random_normal((10, 3), seed=2) predictions = labels * 0.5 + random_ops.random_normal((10, 3), seed=1) * 0.5 pearson_r, update_op = metrics.streaming_pearson_correlation( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_r = pearson_r.eval() for _ in range(10): self.assertEqual(initial_r, pearson_r.eval()) def testSingleUpdateIdentical(self): with self.test_session() as sess: predictions = math_ops.to_float(math_ops.range(10)) labels = math_ops.to_float(math_ops.range(10)) pearson_r, update_op = metrics.streaming_pearson_correlation( predictions, labels) expected_r = np.corrcoef(np.arange(10), np.arange(10))[0, 1] sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expected_r, sess.run(update_op), 5) self.assertAlmostEqual(expected_r, pearson_r.eval(), 5) def testSingleUpdateNonIdentical(self): with self.test_session() as sess: predictions = constant_op.constant( [2, 4, 6], shape=(1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2], shape=(1, 3), dtype=dtypes_lib.float32) pearson_r, update_op = metrics.streaming_pearson_correlation( predictions, labels) expected_r = np.corrcoef([2, 4, 6], [1, 3, 2])[0, 1] sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expected_r, update_op.eval()) self.assertAlmostEqual(expected_r, pearson_r.eval()) def testSingleUpdateWithErrorAndWeights(self): with self.test_session() as sess: predictions = np.array([2, 4, 6, 8]) labels = np.array([1, 3, 2, 7]) weights = np.array([0, 1, 3, 1]) predictions_t = constant_op.constant( predictions, shape=(1, 4), dtype=dtypes_lib.float32) labels_t = constant_op.constant( labels, shape=(1, 4), dtype=dtypes_lib.float32) weights_t = constant_op.constant( weights, shape=(1, 4), dtype=dtypes_lib.float32) pearson_r, update_op = metrics.streaming_pearson_correlation( predictions_t, labels_t, weights=weights_t) cmat = np.cov(predictions, labels, fweights=weights) expected_r = cmat[0, 1] / np.sqrt(cmat[0, 0] * cmat[1, 1]) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expected_r, sess.run(update_op)) self.assertAlmostEqual(expected_r, pearson_r.eval()) def testMultiUpdateWithErrorNoWeights(self): with self.test_session() as sess: np.random.seed(123) n = 100 predictions = np.random.randn(n) labels = 0.5 * predictions + np.random.randn(n) stride = 10 predictions_t = array_ops.placeholder(dtypes_lib.float32, [stride]) labels_t = array_ops.placeholder(dtypes_lib.float32, [stride]) pearson_r, update_op = metrics.streaming_pearson_correlation( predictions_t, labels_t) sess.run(variables.local_variables_initializer()) prev_expected_r = NAN for i in range(n // stride): feed_dict = { predictions_t: predictions[stride * i:stride * (i + 1)], labels_t: labels[stride * i:stride * (i + 1)] } self.assertEqual( np.isnan(prev_expected_r), np.isnan(sess.run(pearson_r, feed_dict=feed_dict))) if not np.isnan(prev_expected_r): self.assertAlmostEqual(prev_expected_r, sess.run(pearson_r, feed_dict=feed_dict), 5) expected_r = np.corrcoef(predictions[:stride * (i + 1)], labels[:stride * (i + 1)])[0, 1] self.assertAlmostEqual(expected_r, sess.run(update_op, feed_dict=feed_dict), 5) self.assertAlmostEqual(expected_r, sess.run(pearson_r, feed_dict=feed_dict), 5) prev_expected_r = expected_r def testMultiUpdateWithErrorAndWeights(self): with self.test_session() as sess: np.random.seed(123) n = 100 predictions = np.random.randn(n) labels = 0.5 * predictions + np.random.randn(n) weights = np.tile(np.arange(n // 10), n // 10) np.random.shuffle(weights) stride = 10 predictions_t = array_ops.placeholder(dtypes_lib.float32, [stride]) labels_t = array_ops.placeholder(dtypes_lib.float32, [stride]) weights_t = array_ops.placeholder(dtypes_lib.float32, [stride]) pearson_r, update_op = metrics.streaming_pearson_correlation( predictions_t, labels_t, weights=weights_t) sess.run(variables.local_variables_initializer()) prev_expected_r = NAN for i in range(n // stride): feed_dict = { predictions_t: predictions[stride * i:stride * (i + 1)], labels_t: labels[stride * i:stride * (i + 1)], weights_t: weights[stride * i:stride * (i + 1)] } self.assertEqual( np.isnan(prev_expected_r), np.isnan(sess.run(pearson_r, feed_dict=feed_dict))) if not np.isnan(prev_expected_r): self.assertAlmostEqual(prev_expected_r, sess.run(pearson_r, feed_dict=feed_dict), 5) cmat = np.cov( predictions[:stride * (i + 1)], labels[:stride * (i + 1)], fweights=weights[:stride * (i + 1)]) expected_r = cmat[0, 1] / np.sqrt(cmat[0, 0] * cmat[1, 1]) self.assertAlmostEqual(expected_r, sess.run(update_op, feed_dict=feed_dict), 5) self.assertAlmostEqual(expected_r, sess.run(pearson_r, feed_dict=feed_dict), 5) prev_expected_r = expected_r def testMultiUpdateWithErrorAndSingletonBatches(self): with self.test_session() as sess: np.random.seed(123) n = 100 predictions = np.random.randn(n) labels = 0.5 * predictions + np.random.randn(n) stride = 10 weights = (np.arange(n).reshape(n // stride, stride) % stride == 0) for row in weights: np.random.shuffle(row) # Now, weights is one-hot by row - one item per batch has non-zero weight. weights = weights.reshape((n,)) predictions_t = array_ops.placeholder(dtypes_lib.float32, [stride]) labels_t = array_ops.placeholder(dtypes_lib.float32, [stride]) weights_t = array_ops.placeholder(dtypes_lib.float32, [stride]) pearson_r, update_op = metrics.streaming_pearson_correlation( predictions_t, labels_t, weights=weights_t) sess.run(variables.local_variables_initializer()) for i in range(n // stride): feed_dict = { predictions_t: predictions[stride * i:stride * (i + 1)], labels_t: labels[stride * i:stride * (i + 1)], weights_t: weights[stride * i:stride * (i + 1)] } cmat = np.cov( predictions[:stride * (i + 1)], labels[:stride * (i + 1)], fweights=weights[:stride * (i + 1)]) expected_r = cmat[0, 1] / np.sqrt(cmat[0, 0] * cmat[1, 1]) actual_r = sess.run(update_op, feed_dict=feed_dict) self.assertEqual(np.isnan(expected_r), np.isnan(actual_r)) self.assertEqual( np.isnan(expected_r), np.isnan(sess.run(pearson_r, feed_dict=feed_dict))) if not np.isnan(expected_r): self.assertAlmostEqual(expected_r, actual_r, 5) self.assertAlmostEqual(expected_r, sess.run(pearson_r, feed_dict=feed_dict), 5) class StreamingMeanCosineDistanceTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_mean_cosine_distance( predictions=array_ops.ones((10, 3)), labels=array_ops.ones((10, 3)), dim=1) _assert_metric_variables(self, ( 'mean_cosine_distance/count:0', 'mean_cosine_distance/total:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_mean_cosine_distance( predictions=array_ops.ones((10, 3)), labels=array_ops.ones((10, 3)), dim=1, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean_cosine_distance( predictions=array_ops.ones((10, 3)), labels=array_ops.ones((10, 3)), dim=1, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_normal((10, 3), seed=1) labels = random_ops.random_normal((10, 3), seed=2) error, update_op = metrics.streaming_mean_cosine_distance( predictions, labels, dim=1) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_error = error.eval() for _ in range(10): self.assertEqual(initial_error, error.eval()) def testSingleUpdateZeroError(self): np_labels = np.matrix(('1 0 0;' '0 0 1;' '0 1 0')) predictions = constant_op.constant( np_labels, shape=(1, 3, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( np_labels, shape=(1, 3, 3), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_cosine_distance( predictions, labels, dim=2) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, sess.run(update_op)) self.assertEqual(0, error.eval()) def testSingleUpdateWithError1(self): np_labels = np.matrix(('1 0 0;' '0 0 1;' '0 1 0')) np_predictions = np.matrix(('1 0 0;' '0 0 -1;' '1 0 0')) predictions = constant_op.constant( np_predictions, shape=(3, 1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( np_labels, shape=(3, 1, 3), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_cosine_distance( predictions, labels, dim=2) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(1, sess.run(update_op), 5) self.assertAlmostEqual(1, error.eval(), 5) def testSingleUpdateWithError2(self): np_predictions = np.matrix( ('0.819031913261206 0.567041924552012 0.087465312324590;' '-0.665139432070255 -0.739487441769973 -0.103671883216994;' '0.707106781186548 -0.707106781186548 0')) np_labels = np.matrix( ('0.819031913261206 0.567041924552012 0.087465312324590;' '0.665139432070255 0.739487441769973 0.103671883216994;' '0.707106781186548 0.707106781186548 0')) predictions = constant_op.constant( np_predictions, shape=(3, 1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( np_labels, shape=(3, 1, 3), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_cosine_distance( predictions, labels, dim=2) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(1.0, sess.run(update_op), 5) self.assertAlmostEqual(1.0, error.eval(), 5) def testSingleUpdateWithErrorAndWeights1(self): np_predictions = np.matrix(('1 0 0;' '0 0 -1;' '1 0 0')) np_labels = np.matrix(('1 0 0;' '0 0 1;' '0 1 0')) predictions = constant_op.constant( np_predictions, shape=(3, 1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( np_labels, shape=(3, 1, 3), dtype=dtypes_lib.float32) weights = constant_op.constant( [1, 0, 0], shape=(3, 1, 1), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_cosine_distance( predictions, labels, dim=2, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, sess.run(update_op)) self.assertEqual(0, error.eval()) def testSingleUpdateWithErrorAndWeights2(self): np_predictions = np.matrix(('1 0 0;' '0 0 -1;' '1 0 0')) np_labels = np.matrix(('1 0 0;' '0 0 1;' '0 1 0')) predictions = constant_op.constant( np_predictions, shape=(3, 1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( np_labels, shape=(3, 1, 3), dtype=dtypes_lib.float32) weights = constant_op.constant( [0, 1, 1], shape=(3, 1, 1), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_cosine_distance( predictions, labels, dim=2, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1.5, update_op.eval()) self.assertEqual(1.5, error.eval()) class PcntBelowThreshTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_percentage_less(values=array_ops.ones((10,)), threshold=2) _assert_metric_variables(self, ( 'percentage_below_threshold/count:0', 'percentage_below_threshold/total:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_percentage_less( values=array_ops.ones((10,)), threshold=2, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_percentage_less( values=array_ops.ones((10,)), threshold=2, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testOneUpdate(self): with self.test_session() as sess: values = constant_op.constant( [2, 4, 6, 8], shape=(1, 4), dtype=dtypes_lib.float32) pcnt0, update_op0 = metrics.streaming_percentage_less( values, 100, name='high') pcnt1, update_op1 = metrics.streaming_percentage_less( values, 7, name='medium') pcnt2, update_op2 = metrics.streaming_percentage_less( values, 1, name='low') sess.run(variables.local_variables_initializer()) sess.run([update_op0, update_op1, update_op2]) pcnt0, pcnt1, pcnt2 = sess.run([pcnt0, pcnt1, pcnt2]) self.assertAlmostEqual(1.0, pcnt0, 5) self.assertAlmostEqual(0.75, pcnt1, 5) self.assertAlmostEqual(0.0, pcnt2, 5) def testSomePresentOneUpdate(self): with self.test_session() as sess: values = constant_op.constant( [2, 4, 6, 8], shape=(1, 4), dtype=dtypes_lib.float32) weights = constant_op.constant( [1, 0, 0, 1], shape=(1, 4), dtype=dtypes_lib.float32) pcnt0, update_op0 = metrics.streaming_percentage_less( values, 100, weights=weights, name='high') pcnt1, update_op1 = metrics.streaming_percentage_less( values, 7, weights=weights, name='medium') pcnt2, update_op2 = metrics.streaming_percentage_less( values, 1, weights=weights, name='low') sess.run(variables.local_variables_initializer()) self.assertListEqual([1.0, 0.5, 0.0], sess.run([update_op0, update_op1, update_op2])) pcnt0, pcnt1, pcnt2 = sess.run([pcnt0, pcnt1, pcnt2]) self.assertAlmostEqual(1.0, pcnt0, 5) self.assertAlmostEqual(0.5, pcnt1, 5) self.assertAlmostEqual(0.0, pcnt2, 5) class StreamingMeanIOUTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_mean_iou( predictions=array_ops.ones([10, 1]), labels=array_ops.ones([10, 1]), num_classes=2) _assert_metric_variables(self, ('mean_iou/total_confusion_matrix:0',)) def testMetricsCollections(self): my_collection_name = '__metrics__' mean_iou, _ = metrics.streaming_mean_iou( predictions=array_ops.ones([10, 1]), labels=array_ops.ones([10, 1]), num_classes=2, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean_iou]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean_iou( predictions=array_ops.ones([10, 1]), labels=array_ops.ones([10, 1]), num_classes=2, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testPredictionsAndLabelsOfDifferentSizeRaisesValueError(self): predictions = array_ops.ones([10, 3]) labels = array_ops.ones([10, 4]) with self.assertRaises(ValueError): metrics.streaming_mean_iou(predictions, labels, num_classes=2) def testLabelsAndWeightsOfDifferentSizeRaisesValueError(self): predictions = array_ops.ones([10]) labels = array_ops.ones([10]) weights = array_ops.zeros([9]) with self.assertRaises(ValueError): metrics.streaming_mean_iou( predictions, labels, num_classes=2, weights=weights) def testValueTensorIsIdempotent(self): num_classes = 3 predictions = random_ops.random_uniform( [10], maxval=num_classes, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( [10], maxval=num_classes, dtype=dtypes_lib.int64, seed=2) miou, update_op = metrics.streaming_mean_iou( predictions, labels, num_classes=num_classes) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_miou = miou.eval() for _ in range(10): self.assertEqual(initial_miou, miou.eval()) def testMultipleUpdates(self): num_classes = 3 with self.test_session() as sess: # Create the queue that populates the predictions. preds_queue = data_flow_ops.FIFOQueue( 5, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [2]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [0]) predictions = preds_queue.dequeue() # Create the queue that populates the labels. labels_queue = data_flow_ops.FIFOQueue( 5, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [2]) _enqueue_vector(sess, labels_queue, [1]) labels = labels_queue.dequeue() miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) for _ in range(5): sess.run(update_op) desired_output = np.mean([1.0 / 2.0, 1.0 / 4.0, 0.]) self.assertEqual(desired_output, miou.eval()) def testMultipleUpdatesWithWeights(self): num_classes = 2 with self.test_session() as sess: # Create the queue that populates the predictions. preds_queue = data_flow_ops.FIFOQueue( 6, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) predictions = preds_queue.dequeue() # Create the queue that populates the labels. labels_queue = data_flow_ops.FIFOQueue( 6, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) labels = labels_queue.dequeue() # Create the queue that populates the weights. weights_queue = data_flow_ops.FIFOQueue( 6, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, weights_queue, [1.0]) _enqueue_vector(sess, weights_queue, [1.0]) _enqueue_vector(sess, weights_queue, [1.0]) _enqueue_vector(sess, weights_queue, [0.0]) _enqueue_vector(sess, weights_queue, [1.0]) _enqueue_vector(sess, weights_queue, [0.0]) weights = weights_queue.dequeue() miou, update_op = metrics.streaming_mean_iou( predictions, labels, num_classes, weights=weights) sess.run(variables.local_variables_initializer()) for _ in range(6): sess.run(update_op) desired_output = np.mean([2.0 / 3.0, 1.0 / 2.0]) self.assertAlmostEqual(desired_output, miou.eval()) def testMultipleUpdatesWithMissingClass(self): # Test the case where there are no predicions and labels for # one class, and thus there is one row and one column with # zero entries in the confusion matrix. num_classes = 3 with self.test_session() as sess: # Create the queue that populates the predictions. # There is no prediction for class 2. preds_queue = data_flow_ops.FIFOQueue( 5, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [0]) predictions = preds_queue.dequeue() # Create the queue that populates the labels. # There is label for class 2. labels_queue = data_flow_ops.FIFOQueue( 5, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) labels = labels_queue.dequeue() miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) for _ in range(5): sess.run(update_op) desired_output = np.mean([1.0 / 3.0, 2.0 / 4.0]) self.assertAlmostEqual(desired_output, miou.eval()) def testUpdateOpEvalIsAccumulatedConfusionMatrix(self): predictions = array_ops.concat([ constant_op.constant(0, shape=[5]), constant_op.constant(1, shape=[5]) ], 0) labels = array_ops.concat([ constant_op.constant(0, shape=[3]), constant_op.constant(1, shape=[7]) ], 0) num_classes = 2 with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) confusion_matrix = update_op.eval() self.assertAllEqual([[3, 0], [2, 5]], confusion_matrix) desired_miou = np.mean([3. / 5., 5. / 7.]) self.assertAlmostEqual(desired_miou, miou.eval()) def testAllCorrect(self): predictions = array_ops.zeros([40]) labels = array_ops.zeros([40]) num_classes = 1 with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) self.assertEqual(40, update_op.eval()[0]) self.assertEqual(1.0, miou.eval()) def testAllWrong(self): predictions = array_ops.zeros([40]) labels = array_ops.ones([40]) num_classes = 2 with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) self.assertAllEqual([[0, 0], [40, 0]], update_op.eval()) self.assertEqual(0., miou.eval()) def testResultsWithSomeMissing(self): predictions = array_ops.concat([ constant_op.constant(0, shape=[5]), constant_op.constant(1, shape=[5]) ], 0) labels = array_ops.concat([ constant_op.constant(0, shape=[3]), constant_op.constant(1, shape=[7]) ], 0) num_classes = 2 weights = array_ops.concat([ constant_op.constant(0, shape=[1]), constant_op.constant(1, shape=[8]), constant_op.constant(0, shape=[1]) ], 0) with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou( predictions, labels, num_classes, weights=weights) sess.run(variables.local_variables_initializer()) self.assertAllEqual([[2, 0], [2, 4]], update_op.eval()) desired_miou = np.mean([2. / 4., 4. / 6.]) self.assertAlmostEqual(desired_miou, miou.eval()) def testMissingClassInLabels(self): labels = constant_op.constant([[[0, 0, 1, 1, 0, 0], [1, 0, 0, 0, 0, 1]], [[1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]]]) predictions = constant_op.constant( [[[0, 0, 2, 1, 1, 0], [0, 1, 2, 2, 0, 1]], [[0, 0, 2, 1, 1, 1], [1, 1, 2, 0, 0, 0]]]) num_classes = 3 with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) self.assertAllEqual([[7, 4, 3], [3, 5, 2], [0, 0, 0]], update_op.eval()) self.assertAlmostEqual(1 / 3 * (7 / (7 + 3 + 7) + 5 / (5 + 4 + 5) + 0 / (0 + 5 + 0)), miou.eval()) def testMissingClassOverallSmall(self): labels = constant_op.constant([0]) predictions = constant_op.constant([0]) num_classes = 2 with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) self.assertAllEqual([[1, 0], [0, 0]], update_op.eval()) self.assertAlmostEqual(1, miou.eval()) def testMissingClassOverallLarge(self): labels = constant_op.constant([[[0, 0, 1, 1, 0, 0], [1, 0, 0, 0, 0, 1]], [[1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]]]) predictions = constant_op.constant( [[[0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1]], [[0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0]]]) num_classes = 3 with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) self.assertAllEqual([[9, 5, 0], [3, 7, 0], [0, 0, 0]], update_op.eval()) self.assertAlmostEqual(1 / 2 * (9 / (9 + 3 + 5) + 7 / (7 + 5 + 3)), miou.eval()) class StreamingConcatTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_concat(values=array_ops.ones((10,))) _assert_metric_variables(self, ( 'streaming_concat/array:0', 'streaming_concat/size:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' value, _ = metrics.streaming_concat( values=array_ops.ones((10,)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [value]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_concat( values=array_ops.ones((10,)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testNextArraySize(self): next_array_size = metric_ops._next_array_size # pylint: disable=protected-access with self.test_session(): self.assertEqual(next_array_size(2, growth_factor=2).eval(), 2) self.assertEqual(next_array_size(3, growth_factor=2).eval(), 4) self.assertEqual(next_array_size(4, growth_factor=2).eval(), 4) self.assertEqual(next_array_size(5, growth_factor=2).eval(), 8) self.assertEqual(next_array_size(6, growth_factor=2).eval(), 8) def testStreamingConcat(self): with self.test_session() as sess: values = array_ops.placeholder(dtypes_lib.int32, [None]) concatenated, update_op = metrics.streaming_concat(values) sess.run(variables.local_variables_initializer()) self.assertAllEqual([], concatenated.eval()) sess.run([update_op], feed_dict={values: [0, 1, 2]}) self.assertAllEqual([0, 1, 2], concatenated.eval()) sess.run([update_op], feed_dict={values: [3, 4]}) self.assertAllEqual([0, 1, 2, 3, 4], concatenated.eval()) sess.run([update_op], feed_dict={values: [5, 6, 7, 8, 9]}) self.assertAllEqual(np.arange(10), concatenated.eval()) def testStreamingConcatStringValues(self): with self.test_session() as sess: values = array_ops.placeholder(dtypes_lib.string, [None]) concatenated, update_op = metrics.streaming_concat(values) sess.run(variables.local_variables_initializer()) self.assertItemsEqual([], concatenated.eval()) sess.run([update_op], feed_dict={values: ['a', 'b', 'c']}) self.assertItemsEqual([b'a', b'b', b'c'], concatenated.eval()) sess.run([update_op], feed_dict={values: ['d', 'e']}) self.assertItemsEqual([b'a', b'b', b'c', b'd', b'e'], concatenated.eval()) sess.run([update_op], feed_dict={values: ['f', 'g', 'h', 'i', 'j']}) self.assertItemsEqual( [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j'], concatenated.eval()) def testStreamingConcatMaxSize(self): with self.test_session() as sess: values = math_ops.range(3) concatenated, update_op = metrics.streaming_concat(values, max_size=5) sess.run(variables.local_variables_initializer()) self.assertAllEqual([], concatenated.eval()) sess.run([update_op]) self.assertAllEqual([0, 1, 2], concatenated.eval()) sess.run([update_op]) self.assertAllEqual([0, 1, 2, 0, 1], concatenated.eval()) sess.run([update_op]) self.assertAllEqual([0, 1, 2, 0, 1], concatenated.eval()) def testStreamingConcat2D(self): with self.test_session() as sess: values = array_ops.reshape(math_ops.range(3), (3, 1)) concatenated, update_op = metrics.streaming_concat(values, axis=-1) sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run([update_op]) self.assertAllEqual([[0] * 10, [1] * 10, [2] * 10], concatenated.eval()) def testStreamingConcatErrors(self): with self.assertRaises(ValueError): metrics.streaming_concat(array_ops.placeholder(dtypes_lib.float32)) values = array_ops.zeros((2, 3)) with self.assertRaises(ValueError): metrics.streaming_concat(values, axis=-3, max_size=3) with self.assertRaises(ValueError): metrics.streaming_concat(values, axis=2, max_size=3) with self.assertRaises(ValueError): metrics.streaming_concat( array_ops.placeholder(dtypes_lib.float32, [None, None])) def testStreamingConcatReset(self): with self.test_session() as sess: values = array_ops.placeholder(dtypes_lib.int32, [None]) concatenated, update_op = metrics.streaming_concat(values) sess.run(variables.local_variables_initializer()) self.assertAllEqual([], concatenated.eval()) sess.run([update_op], feed_dict={values: [0, 1, 2]}) self.assertAllEqual([0, 1, 2], concatenated.eval()) sess.run(variables.local_variables_initializer()) sess.run([update_op], feed_dict={values: [3, 4]}) self.assertAllEqual([3, 4], concatenated.eval()) class AggregateMetricsTest(test.TestCase): def testAggregateNoMetricsRaisesValueError(self): with self.assertRaises(ValueError): metrics.aggregate_metrics() def testAggregateSingleMetricReturnsOneItemLists(self): values = array_ops.ones((10, 4)) value_tensors, update_ops = metrics.aggregate_metrics( metrics.streaming_mean(values)) self.assertEqual(len(value_tensors), 1) self.assertEqual(len(update_ops), 1) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1, update_ops[0].eval()) self.assertEqual(1, value_tensors[0].eval()) def testAggregateMultipleMetricsReturnsListsInOrder(self): predictions = array_ops.ones((10, 4)) labels = array_ops.ones((10, 4)) * 3 value_tensors, update_ops = metrics.aggregate_metrics( metrics.streaming_mean_absolute_error(predictions, labels), metrics.streaming_mean_squared_error(predictions, labels)) self.assertEqual(len(value_tensors), 2) self.assertEqual(len(update_ops), 2) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(2, update_ops[0].eval()) self.assertEqual(4, update_ops[1].eval()) self.assertEqual(2, value_tensors[0].eval()) self.assertEqual(4, value_tensors[1].eval()) class AggregateMetricMapTest(test.TestCase): def testAggregateMultipleMetricsReturnsListsInOrder(self): predictions = array_ops.ones((10, 4)) labels = array_ops.ones((10, 4)) * 3 names_to_values, names_to_updates = metrics.aggregate_metric_map({ 'm1': metrics.streaming_mean_absolute_error(predictions, labels), 'm2': metrics.streaming_mean_squared_error(predictions, labels), }) self.assertEqual(2, len(names_to_values)) self.assertEqual(2, len(names_to_updates)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(2, names_to_updates['m1'].eval()) self.assertEqual(4, names_to_updates['m2'].eval()) self.assertEqual(2, names_to_values['m1'].eval()) self.assertEqual(4, names_to_values['m2'].eval()) class CountTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.count(array_ops.ones([4, 3])) _assert_metric_variables(self, ['count/count:0']) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.count( array_ops.ones([4, 3]), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.count( array_ops.ones([4, 3]), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testReturnType(self): c, op = metrics.count(array_ops.ones([4, 3])) self.assertTrue(isinstance(c, ops.Tensor)) self.assertTrue(isinstance(op, ops.Operation) or isinstance(op, ops.Tensor)) def testBasic(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() result, update_op = metrics.count(values) sess.run(variables.local_variables_initializer()) for _ in range(4): sess.run(update_op) self.assertAlmostEqual(8.0, sess.run(result), 5) def testUpdateOpsReturnsCurrentValue(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() result, update_op = metrics.count(values) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(2.0, sess.run(update_op), 5) self.assertAlmostEqual(4.0, sess.run(update_op), 5) self.assertAlmostEqual(6.0, sess.run(update_op), 5) self.assertAlmostEqual(8.0, sess.run(update_op), 5) self.assertAlmostEqual(8.0, sess.run(result), 5) def test1dWeightedValues(self): with self.test_session() as sess: # Create the queue that populates the values. values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() # Create the queue that populates the weighted labels. weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, weights_queue, [0.5]) _enqueue_vector(sess, weights_queue, [0]) _enqueue_vector(sess, weights_queue, [0]) _enqueue_vector(sess, weights_queue, [1.2]) weights = weights_queue.dequeue() result, update_op = metrics.count(values, weights) variables.local_variables_initializer().run() for _ in range(4): update_op.eval() self.assertAlmostEqual(3.4, result.eval(), 5) def test1dWeightedValues_placeholders(self): with self.test_session() as sess: # Create the queue that populates the values. feed_values = ((0, 1), (-4.2, 9.1), (6.5, 0), (-3.2, 4.0)) values = array_ops.placeholder(dtype=dtypes_lib.float32) # Create the queue that populates the weighted labels. weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1,)) _enqueue_vector(sess, weights_queue, 0.5, shape=(1,)) _enqueue_vector(sess, weights_queue, 0, shape=(1,)) _enqueue_vector(sess, weights_queue, 0, shape=(1,)) _enqueue_vector(sess, weights_queue, 1.2, shape=(1,)) weights = weights_queue.dequeue() result, update_op = metrics.count(values, weights) variables.local_variables_initializer().run() for i in range(4): update_op.eval(feed_dict={values: feed_values[i]}) self.assertAlmostEqual(3.4, result.eval(), 5) def test2dWeightedValues(self): with self.test_session() as sess: # Create the queue that populates the values. values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() # Create the queue that populates the weighted labels. weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, weights_queue, [1.1, 1]) _enqueue_vector(sess, weights_queue, [1, 0]) _enqueue_vector(sess, weights_queue, [0, 1]) _enqueue_vector(sess, weights_queue, [0, 0]) weights = weights_queue.dequeue() result, update_op = metrics.count(values, weights) variables.local_variables_initializer().run() for _ in range(4): update_op.eval() self.assertAlmostEqual(4.1, result.eval(), 5) def test2dWeightedValues_placeholders(self): with self.test_session() as sess: # Create the queue that populates the values. feed_values = ((0, 1), (-4.2, 9.1), (6.5, 0), (-3.2, 4.0)) values = array_ops.placeholder(dtype=dtypes_lib.float32) # Create the queue that populates the weighted labels. weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(2,)) _enqueue_vector(sess, weights_queue, [1.1, 1], shape=(2,)) _enqueue_vector(sess, weights_queue, [1, 0], shape=(2,)) _enqueue_vector(sess, weights_queue, [0, 1], shape=(2,)) _enqueue_vector(sess, weights_queue, [0, 0], shape=(2,)) weights = weights_queue.dequeue() result, update_op = metrics.count(values, weights) variables.local_variables_initializer().run() for i in range(4): update_op.eval(feed_dict={values: feed_values[i]}) self.assertAlmostEqual(4.1, result.eval(), 5) class CohenKappaTest(test.TestCase): def _confusion_matrix_to_samples(self, confusion_matrix): x, y = confusion_matrix.shape pairs = [] for label in range(x): for feature in range(y): pairs += [label, feature] * confusion_matrix[label, feature] pairs = np.array(pairs).reshape((-1, 2)) return pairs[:, 0], pairs[:, 1] def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.cohen_kappa( predictions_idx=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), num_classes=2) _assert_metric_variables(self, ( 'cohen_kappa/po:0', 'cohen_kappa/pe_row:0', 'cohen_kappa/pe_col:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' kappa, _ = metrics.cohen_kappa( predictions_idx=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), num_classes=2, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [kappa]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.cohen_kappa( predictions_idx=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), num_classes=2, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 1), maxval=3, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( (10, 1), maxval=3, dtype=dtypes_lib.int64, seed=2) kappa, update_op = metrics.cohen_kappa(labels, predictions, 3) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_kappa = kappa.eval() for _ in range(10): self.assertAlmostEqual(initial_kappa, kappa.eval(), 5) def testBasic(self): confusion_matrix = np.array([[9, 3, 1], [4, 8, 2], [2, 1, 6]]) # overall total = 36 # po = [9, 8, 6], sum(po) = 23 # pe_row = [15, 12, 9], pe_col = [13, 14, 9], so pe = [5.42, 4.67, 2.25] # finally, kappa = (sum(po) - sum(pe)) / (N - sum(pe)) # = (23 - 12.34) / (36 - 12.34) # = 0.45 # see: http://psych.unl.edu/psycrs/handcomp/hckappa.PDF expect = 0.45 labels, predictions = self._confusion_matrix_to_samples(confusion_matrix) dtypes = [dtypes_lib.int16, dtypes_lib.int32, dtypes_lib.int64] shapes = [ (len(labels,)), # 1-dim (len(labels), 1) ] # 2-dim weights = [None, np.ones_like(labels)] for dtype in dtypes: for shape in shapes: for weight in weights: with self.test_session() as sess: predictions_tensor = constant_op.constant( np.reshape(predictions, shape), dtype=dtype) labels_tensor = constant_op.constant( np.reshape(labels, shape), dtype=dtype) kappa, update_op = metrics.cohen_kappa( labels_tensor, predictions_tensor, 3, weights=weight) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expect, sess.run(update_op), 2) self.assertAlmostEqual(expect, kappa.eval(), 2) def testAllCorrect(self): inputs = np.arange(0, 100) % 4 # confusion matrix # [[25, 0, 0], # [0, 25, 0], # [0, 0, 25]] # Calculated by v0.19: sklearn.metrics.cohen_kappa_score(inputs, inputs) expect = 1.0 with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) kappa, update_op = metrics.cohen_kappa(labels, predictions, 4) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expect, sess.run(update_op), 5) self.assertAlmostEqual(expect, kappa.eval(), 5) def testAllIncorrect(self): labels = np.arange(0, 100) % 4 predictions = (labels + 1) % 4 # confusion matrix # [[0, 25, 0], # [0, 0, 25], # [25, 0, 0]] # Calculated by v0.19: sklearn.metrics.cohen_kappa_score(labels, predictions) expect = -0.333333333333 with self.test_session() as sess: predictions = constant_op.constant(predictions, dtype=dtypes_lib.float32) labels = constant_op.constant(labels) kappa, update_op = metrics.cohen_kappa(labels, predictions, 4) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expect, sess.run(update_op), 5) self.assertAlmostEqual(expect, kappa.eval(), 5) def testWeighted(self): confusion_matrix = np.array([[9, 3, 1], [4, 8, 2], [2, 1, 6]]) labels, predictions = self._confusion_matrix_to_samples(confusion_matrix) num_samples = np.sum(confusion_matrix, dtype=np.int32) weights = (np.arange(0, num_samples) % 5) / 5.0 # Calculated by v0.19: sklearn.metrics.cohen_kappa_score( # labels, predictions, sample_weight=weights) expect = 0.453466583385 with self.test_session() as sess: predictions = constant_op.constant(predictions, dtype=dtypes_lib.float32) labels = constant_op.constant(labels) kappa, update_op = metrics.cohen_kappa( labels, predictions, 4, weights=weights) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expect, sess.run(update_op), 5) self.assertAlmostEqual(expect, kappa.eval(), 5) def testWithMultipleUpdates(self): confusion_matrix = np.array([[90, 30, 10, 20], [40, 80, 20, 30], [20, 10, 60, 35], [15, 25, 30, 25]]) labels, predictions = self._confusion_matrix_to_samples(confusion_matrix) num_samples = np.sum(confusion_matrix, dtype=np.int32) weights = (np.arange(0, num_samples) % 5) / 5.0 num_classes = confusion_matrix.shape[0] batch_size = num_samples // 10 predictions_t = array_ops.placeholder( dtypes_lib.float32, shape=(batch_size,)) labels_t = array_ops.placeholder(dtypes_lib.int32, shape=(batch_size,)) weights_t = array_ops.placeholder(dtypes_lib.float32, shape=(batch_size,)) kappa, update_op = metrics.cohen_kappa( labels_t, predictions_t, num_classes, weights=weights_t) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for idx in range(0, num_samples, batch_size): batch_start, batch_end = idx, idx + batch_size sess.run( update_op, feed_dict={ labels_t: labels[batch_start:batch_end], predictions_t: predictions[batch_start:batch_end], weights_t: weights[batch_start:batch_end] }) # Calculated by v0.19: sklearn.metrics.cohen_kappa_score( # labels_np, predictions_np, sample_weight=weights_np) expect = 0.289965397924 self.assertAlmostEqual(expect, kappa.eval(), 5) def testInvalidNumClasses(self): predictions = array_ops.placeholder(dtypes_lib.float32, shape=(4, 1)) labels = array_ops.placeholder(dtypes_lib.int32, shape=(4, 1)) with self.assertRaisesRegexp(ValueError, 'num_classes'): metrics.cohen_kappa(labels, predictions, 1) def testInvalidDimension(self): predictions = array_ops.placeholder(dtypes_lib.float32, shape=(4, 1)) invalid_labels = array_ops.placeholder(dtypes_lib.int32, shape=(4, 2)) with self.assertRaises(ValueError): metrics.cohen_kappa(invalid_labels, predictions, 3) invalid_predictions = array_ops.placeholder( dtypes_lib.float32, shape=(4, 2)) labels = array_ops.placeholder(dtypes_lib.int32, shape=(4, 1)) with self.assertRaises(ValueError): metrics.cohen_kappa(labels, invalid_predictions, 3) def testConditionalPackingOptimization(self): placeholder = array_ops.placeholder(dtypes_lib.float32, [None]) values, update_op = metric_ops.streaming_concat(placeholder) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for feed in range(10): sess.run(update_op, feed_dict={placeholder: [feed]}) print(sess.run(values)) if __name__ == '__main__': test.main()
38.709414
85
0.64169
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np from six.moves import xrange from tensorflow.contrib import metrics as metrics_lib from tensorflow.contrib.metrics.python.ops import metric_ops from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes as dtypes_lib from tensorflow.python.framework import errors_impl from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import array_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test NAN = float('nan') metrics = metrics_lib def _enqueue_vector(sess, queue, values, shape=None): if not shape: shape = (1, len(values)) dtype = queue.dtypes[0] sess.run( queue.enqueue(constant_op.constant(values, dtype=dtype, shape=shape))) def _binary_2d_label_to_sparse_value(labels): indices = [] values = [] batch = 0 for row in labels: label = 0 xi = 0 for x in row: if x == 1: indices.append([batch, xi]) values.append(label) xi += 1 else: assert x == 0 label += 1 batch += 1 shape = [len(labels), len(labels[0])] return sparse_tensor.SparseTensorValue( np.array(indices, np.int64), np.array(values, np.int64), np.array(shape, np.int64)) def _binary_2d_label_to_sparse(labels): return sparse_tensor.SparseTensor.from_value( _binary_2d_label_to_sparse_value(labels)) def _binary_3d_label_to_sparse_value(labels): indices = [] values = [] for d0, labels_d0 in enumerate(labels): for d1, labels_d1 in enumerate(labels_d0): d2 = 0 for class_id, label in enumerate(labels_d1): if label == 1: values.append(class_id) indices.append([d0, d1, d2]) d2 += 1 else: assert label == 0 shape = [len(labels), len(labels[0]), len(labels[0][0])] return sparse_tensor.SparseTensorValue( np.array(indices, np.int64), np.array(values, np.int64), np.array(shape, np.int64)) def _binary_3d_label_to_sparse(labels): return sparse_tensor.SparseTensor.from_value( _binary_3d_label_to_sparse_value(labels)) def _assert_nan(test_case, actual): test_case.assertTrue(math.isnan(actual), 'Expected NAN, got %s.' % actual) def _assert_metric_variables(test_case, expected): test_case.assertEquals( set(expected), set(v.name for v in variables.local_variables())) test_case.assertEquals( set(expected), set(v.name for v in ops.get_collection(ops.GraphKeys.METRIC_VARIABLES))) class StreamingMeanTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_mean(array_ops.ones([4, 3])) _assert_metric_variables(self, ('mean/count:0', 'mean/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_mean( array_ops.ones([4, 3]), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean( array_ops.ones([4, 3]), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testBasic(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() mean, update_op = metrics.streaming_mean(values) sess.run(variables.local_variables_initializer()) for _ in range(4): sess.run(update_op) self.assertAlmostEqual(1.65, sess.run(mean), 5) def testUpdateOpsReturnsCurrentValue(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() mean, update_op = metrics.streaming_mean(values) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, sess.run(update_op), 5) self.assertAlmostEqual(1.475, sess.run(update_op), 5) self.assertAlmostEqual(12.4 / 6.0, sess.run(update_op), 5) self.assertAlmostEqual(1.65, sess.run(update_op), 5) self.assertAlmostEqual(1.65, sess.run(mean), 5) def test1dWeightedValues(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, weights_queue, [1]) _enqueue_vector(sess, weights_queue, [0]) _enqueue_vector(sess, weights_queue, [0]) _enqueue_vector(sess, weights_queue, [1]) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean(values, weights) variables.local_variables_initializer().run() for _ in range(4): update_op.eval() self.assertAlmostEqual((0 + 1 - 3.2 + 4.0) / 4.0, mean.eval(), 5) def test1dWeightedValues_placeholders(self): with self.test_session() as sess: feed_values = ((0, 1), (-4.2, 9.1), (6.5, 0), (-3.2, 4.0)) values = array_ops.placeholder(dtype=dtypes_lib.float32) weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1,)) _enqueue_vector(sess, weights_queue, 1, shape=(1,)) _enqueue_vector(sess, weights_queue, 0, shape=(1,)) _enqueue_vector(sess, weights_queue, 0, shape=(1,)) _enqueue_vector(sess, weights_queue, 1, shape=(1,)) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean(values, weights) variables.local_variables_initializer().run() for i in range(4): update_op.eval(feed_dict={values: feed_values[i]}) self.assertAlmostEqual((0 + 1 - 3.2 + 4.0) / 4.0, mean.eval(), 5) def test2dWeightedValues(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, weights_queue, [1, 1]) _enqueue_vector(sess, weights_queue, [1, 0]) _enqueue_vector(sess, weights_queue, [0, 1]) _enqueue_vector(sess, weights_queue, [0, 0]) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean(values, weights) variables.local_variables_initializer().run() for _ in range(4): update_op.eval() self.assertAlmostEqual((0 + 1 - 4.2 + 0) / 4.0, mean.eval(), 5) def test2dWeightedValues_placeholders(self): with self.test_session() as sess: feed_values = ((0, 1), (-4.2, 9.1), (6.5, 0), (-3.2, 4.0)) values = array_ops.placeholder(dtype=dtypes_lib.float32) weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(2,)) _enqueue_vector(sess, weights_queue, [1, 1], shape=(2,)) _enqueue_vector(sess, weights_queue, [1, 0], shape=(2,)) _enqueue_vector(sess, weights_queue, [0, 1], shape=(2,)) _enqueue_vector(sess, weights_queue, [0, 0], shape=(2,)) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean(values, weights) variables.local_variables_initializer().run() for i in range(4): update_op.eval(feed_dict={values: feed_values[i]}) self.assertAlmostEqual((0 + 1 - 4.2 + 0) / 4.0, mean.eval(), 5) class StreamingMeanTensorTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_mean_tensor(array_ops.ones([4, 3])) _assert_metric_variables(self, ('mean/total_tensor:0', 'mean/count_tensor:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_mean_tensor( array_ops.ones([4, 3]), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean_tensor( array_ops.ones([4, 3]), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testBasic(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() mean, update_op = metrics.streaming_mean_tensor(values) sess.run(variables.local_variables_initializer()) for _ in range(4): sess.run(update_op) self.assertAllClose([[-0.9 / 4., 3.525]], sess.run(mean)) def testMultiDimensional(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(2, 2, 2)) _enqueue_vector( sess, values_queue, [[[1, 2], [1, 2]], [[1, 2], [1, 2]]], shape=(2, 2, 2)) _enqueue_vector( sess, values_queue, [[[1, 2], [1, 2]], [[3, 4], [9, 10]]], shape=(2, 2, 2)) values = values_queue.dequeue() mean, update_op = metrics.streaming_mean_tensor(values) sess.run(variables.local_variables_initializer()) for _ in range(2): sess.run(update_op) self.assertAllClose([[[1, 2], [1, 2]], [[2, 3], [5, 6]]], sess.run(mean)) def testUpdateOpsReturnsCurrentValue(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() mean, update_op = metrics.streaming_mean_tensor(values) sess.run(variables.local_variables_initializer()) self.assertAllClose([[0, 1]], sess.run(update_op), 5) self.assertAllClose([[-2.1, 5.05]], sess.run(update_op), 5) self.assertAllClose([[2.3 / 3., 10.1 / 3.]], sess.run(update_op), 5) self.assertAllClose([[-0.9 / 4., 3.525]], sess.run(update_op), 5) self.assertAllClose([[-0.9 / 4., 3.525]], sess.run(mean), 5) def testWeighted1d(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, weights_queue, [[1]]) _enqueue_vector(sess, weights_queue, [[0]]) _enqueue_vector(sess, weights_queue, [[1]]) _enqueue_vector(sess, weights_queue, [[0]]) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean_tensor(values, weights) sess.run(variables.local_variables_initializer()) for _ in range(4): sess.run(update_op) self.assertAllClose([[3.25, 0.5]], sess.run(mean), 5) def testWeighted2d_1(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, weights_queue, [1, 1]) _enqueue_vector(sess, weights_queue, [1, 0]) _enqueue_vector(sess, weights_queue, [0, 1]) _enqueue_vector(sess, weights_queue, [0, 0]) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean_tensor(values, weights) sess.run(variables.local_variables_initializer()) for _ in range(4): sess.run(update_op) self.assertAllClose([[-2.1, 0.5]], sess.run(mean), 5) def testWeighted2d_2(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, weights_queue, [0, 1]) _enqueue_vector(sess, weights_queue, [0, 0]) _enqueue_vector(sess, weights_queue, [0, 1]) _enqueue_vector(sess, weights_queue, [0, 0]) weights = weights_queue.dequeue() mean, update_op = metrics.streaming_mean_tensor(values, weights) sess.run(variables.local_variables_initializer()) for _ in range(4): sess.run(update_op) self.assertAllClose([[0, 0.5]], sess.run(mean), 5) class StreamingAccuracyTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_accuracy( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), name='my_accuracy') _assert_metric_variables(self, ('my_accuracy/count:0', 'my_accuracy/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_accuracy( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_accuracy( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testPredictionsAndLabelsOfDifferentSizeRaisesValueError(self): predictions = array_ops.ones((10, 3)) labels = array_ops.ones((10, 4)) with self.assertRaises(ValueError): metrics.streaming_accuracy(predictions, labels) def testPredictionsAndWeightsOfDifferentSizeRaisesValueError(self): predictions = array_ops.ones((10, 3)) labels = array_ops.ones((10, 3)) weights = array_ops.ones((9, 3)) with self.assertRaises(ValueError): metrics.streaming_accuracy(predictions, labels, weights) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=3, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=3, dtype=dtypes_lib.int64, seed=2) accuracy, update_op = metrics.streaming_accuracy(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_accuracy = accuracy.eval() for _ in range(10): self.assertEqual(initial_accuracy, accuracy.eval()) def testMultipleUpdates(self): with self.test_session() as sess: preds_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [2]) _enqueue_vector(sess, preds_queue, [1]) predictions = preds_queue.dequeue() labels_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [2]) labels = labels_queue.dequeue() accuracy, update_op = metrics.streaming_accuracy(predictions, labels) sess.run(variables.local_variables_initializer()) for _ in xrange(3): sess.run(update_op) self.assertEqual(0.5, sess.run(update_op)) self.assertEqual(0.5, accuracy.eval()) def testEffectivelyEquivalentSizes(self): predictions = array_ops.ones((40, 1)) labels = array_ops.ones((40,)) with self.test_session() as sess: accuracy, update_op = metrics.streaming_accuracy(predictions, labels) sess.run(variables.local_variables_initializer()) self.assertEqual(1.0, update_op.eval()) self.assertEqual(1.0, accuracy.eval()) def testEffectivelyEquivalentSizesWithStaicShapedWeight(self): predictions = ops.convert_to_tensor([1, 1, 1]) labels = array_ops.expand_dims(ops.convert_to_tensor([1, 0, 0]), 1) weights = array_ops.expand_dims(ops.convert_to_tensor([100, 1, 1]), 1) with self.test_session() as sess: accuracy, update_op = metrics.streaming_accuracy(predictions, labels, weights) sess.run(variables.local_variables_initializer()) self.assertGreater(update_op.eval(), .95) self.assertGreater(accuracy.eval(), .95) def testEffectivelyEquivalentSizesWithDynamicallyShapedWeight(self): predictions = ops.convert_to_tensor([1, 1, 1]) labels = array_ops.expand_dims(ops.convert_to_tensor([1, 0, 0]), 1) weights = [[100], [1], [1]] weights_placeholder = array_ops.placeholder( dtype=dtypes_lib.int32, name='weights') feed_dict = {weights_placeholder: weights} with self.test_session() as sess: accuracy, update_op = metrics.streaming_accuracy(predictions, labels, weights_placeholder) sess.run(variables.local_variables_initializer()) self.assertGreater(update_op.eval(feed_dict=feed_dict), .95) self.assertGreater(accuracy.eval(feed_dict=feed_dict), .95) def testMultipleUpdatesWithWeightedValues(self): with self.test_session() as sess: preds_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [2]) _enqueue_vector(sess, preds_queue, [1]) predictions = preds_queue.dequeue() labels_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [2]) labels = labels_queue.dequeue() weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.int64, shapes=(1, 1)) _enqueue_vector(sess, weights_queue, [1]) _enqueue_vector(sess, weights_queue, [1]) _enqueue_vector(sess, weights_queue, [0]) _enqueue_vector(sess, weights_queue, [0]) weights = weights_queue.dequeue() accuracy, update_op = metrics.streaming_accuracy(predictions, labels, weights) sess.run(variables.local_variables_initializer()) for _ in xrange(3): sess.run(update_op) self.assertEqual(1.0, sess.run(update_op)) self.assertEqual(1.0, accuracy.eval()) class StreamingTruePositivesTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_true_positives((0, 1, 0), (0, 1, 1)) _assert_metric_variables(self, ('true_positives/count:0',)) def testUnweighted(self): for expand_predictions in [True, False]: for expand_labels in [True, False]: for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) if expand_predictions: predictions = array_ops.expand_dims(predictions, 2) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) if expand_labels: labels = array_ops.expand_dims(labels, 2) tp, tp_update_op = metrics.streaming_true_positives( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, tp.eval()) self.assertEqual(1, tp_update_op.eval()) self.assertEqual(1, tp.eval()) def testWeighted(self): for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) tp, tp_update_op = metrics.streaming_true_positives( predictions, labels, weights=37.0) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, tp.eval()) self.assertEqual(37.0, tp_update_op.eval()) self.assertEqual(37.0, tp.eval()) class StreamingFalseNegativesTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_negatives((0, 1, 0), (0, 1, 1)) _assert_metric_variables(self, ('false_negatives/count:0',)) def testUnweighted(self): for expand_predictions in [True, False]: for expand_labels in [True, False]: for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) if expand_predictions: predictions = array_ops.expand_dims(predictions, 2) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) if expand_labels: labels = array_ops.expand_dims(labels, 2) fn, fn_update_op = metrics.streaming_false_negatives( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, fn.eval()) self.assertEqual(2, fn_update_op.eval()) self.assertEqual(2, fn.eval()) def testWeighted(self): for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) fn, fn_update_op = metrics.streaming_false_negatives( predictions, labels, weights=((3.0,), (5.0,), (7.0,))) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, fn.eval()) self.assertEqual(8.0, fn_update_op.eval()) self.assertEqual(8.0, fn.eval()) class StreamingFalsePositivesTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_positives((0, 1, 0), (0, 1, 1)) _assert_metric_variables(self, ('false_positives/count:0',)) def testUnweighted(self): for expand_predictions in [True, False]: for expand_labels in [True, False]: for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) if expand_predictions: predictions = array_ops.expand_dims(predictions, 2) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) if expand_labels: labels = array_ops.expand_dims(labels, 2) fp, fp_update_op = metrics.streaming_false_positives( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, fp.eval()) self.assertEqual(4, fp_update_op.eval()) self.assertEqual(4, fp.eval()) def testWeighted(self): for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) fp, fp_update_op = metrics.streaming_false_positives( predictions, labels, weights=((1.0, 2.0, 3.0, 5.0), (7.0, 11.0, 13.0, 17.0), (19.0, 23.0, 29.0, 31.0))) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, fp.eval()) self.assertEqual(42.0, fp_update_op.eval()) self.assertEqual(42.0, fp.eval()) class StreamingTrueNegativesTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_true_negatives((0, 1, 0), (0, 1, 1)) _assert_metric_variables(self, ('true_negatives/count:0',)) def testUnweighted(self): for expand_predictions in [True, False]: for expand_labels in [True, False]: for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) if expand_predictions: predictions = array_ops.expand_dims(predictions, 2) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) if expand_labels: labels = array_ops.expand_dims(labels, 2) tn, tn_update_op = metrics.streaming_true_negatives( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, tn.eval()) self.assertEqual(5, tn_update_op.eval()) self.assertEqual(5, tn.eval()) def testWeighted(self): for dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions = math_ops.cast( constant_op.constant(((1, 0, 1, 0), (0, 1, 1, 1), (0, 0, 0, 0))), dtype=dtype) labels = math_ops.cast( constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))), dtype=dtype) tn, tn_update_op = metrics.streaming_true_negatives( predictions, labels, weights=((0.0, 2.0, 3.0, 5.0),)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, tn.eval()) self.assertEqual(15.0, tn_update_op.eval()) self.assertEqual(15.0, tn.eval()) class StreamingTruePositivesAtThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_true_positives_at_thresholds( (0.0, 1.0, 0.0), (0, 1, 1), thresholds=(0.15, 0.5, 0.85)) _assert_metric_variables(self, ('true_positives:0',)) def testUnweighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) tp, tp_update_op = metrics.streaming_true_positives_at_thresholds( predictions, labels, thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0, 0, 0), tp.eval()) self.assertAllEqual((3, 1, 0), tp_update_op.eval()) self.assertAllEqual((3, 1, 0), tp.eval()) def testWeighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) tp, tp_update_op = metrics.streaming_true_positives_at_thresholds( predictions, labels, weights=37.0, thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0.0, 0.0, 0.0), tp.eval()) self.assertAllEqual((111.0, 37.0, 0.0), tp_update_op.eval()) self.assertAllEqual((111.0, 37.0, 0.0), tp.eval()) class StreamingFalseNegativesAtThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_negatives_at_thresholds( (0.0, 1.0, 0.0), (0, 1, 1), thresholds=( 0.15, 0.5, 0.85, )) _assert_metric_variables(self, ('false_negatives:0',)) def testUnweighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) fn, fn_update_op = metrics.streaming_false_negatives_at_thresholds( predictions, labels, thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0, 0, 0), fn.eval()) self.assertAllEqual((0, 2, 3), fn_update_op.eval()) self.assertAllEqual((0, 2, 3), fn.eval()) def testWeighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) fn, fn_update_op = metrics.streaming_false_negatives_at_thresholds( predictions, labels, weights=((3.0,), (5.0,), (7.0,)), thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0.0, 0.0, 0.0), fn.eval()) self.assertAllEqual((0.0, 8.0, 11.0), fn_update_op.eval()) self.assertAllEqual((0.0, 8.0, 11.0), fn.eval()) class StreamingFalsePositivesAtThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_positives_at_thresholds( (0.0, 1.0, 0.0), (0, 1, 1), thresholds=(0.15, 0.5, 0.85)) _assert_metric_variables(self, ('false_positives:0',)) def testUnweighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) fp, fp_update_op = metrics.streaming_false_positives_at_thresholds( predictions, labels, thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0, 0, 0), fp.eval()) self.assertAllEqual((7, 4, 2), fp_update_op.eval()) self.assertAllEqual((7, 4, 2), fp.eval()) def testWeighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) fp, fp_update_op = metrics.streaming_false_positives_at_thresholds( predictions, labels, weights=((1.0, 2.0, 3.0, 5.0), (7.0, 11.0, 13.0, 17.0), (19.0, 23.0, 29.0, 31.0)), thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0.0, 0.0, 0.0), fp.eval()) self.assertAllEqual((125.0, 42.0, 12.0), fp_update_op.eval()) self.assertAllEqual((125.0, 42.0, 12.0), fp.eval()) class StreamingTrueNegativesAtThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_true_negatives_at_thresholds( (0.0, 1.0, 0.0), (0, 1, 1), thresholds=(0.15, 0.5, 0.85)) _assert_metric_variables(self, ('true_negatives:0',)) def testUnweighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) tn, tn_update_op = metrics.streaming_true_negatives_at_thresholds( predictions, labels, thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0, 0, 0), tn.eval()) self.assertAllEqual((2, 5, 7), tn_update_op.eval()) self.assertAllEqual((2, 5, 7), tn.eval()) def testWeighted(self): predictions = constant_op.constant( ((0.9, 0.2, 0.8, 0.1), (0.2, 0.9, 0.7, 0.6), (0.1, 0.2, 0.4, 0.3))) labels = constant_op.constant(((0, 1, 1, 0), (1, 0, 0, 0), (0, 0, 0, 0))) tn, tn_update_op = metrics.streaming_true_negatives_at_thresholds( predictions, labels, weights=((0.0, 2.0, 3.0, 5.0),), thresholds=(0.15, 0.5, 0.85)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAllEqual((0.0, 0.0, 0.0), tn.eval()) self.assertAllEqual((5.0, 15.0, 23.0), tn_update_op.eval()) self.assertAllEqual((5.0, 15.0, 23.0), tn.eval()) class StreamingPrecisionTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables(self, ('precision/false_positives/count:0', 'precision/true_positives/count:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) precision, update_op = metrics.streaming_precision(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_precision = precision.eval() for _ in range(10): self.assertEqual(initial_precision, precision.eval()) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs) labels = constant_op.constant(inputs) precision, update_op = metrics.streaming_precision(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(1, sess.run(update_op)) self.assertAlmostEqual(1, precision.eval()) def testSomeCorrect(self): predictions = constant_op.constant([1, 0, 1, 0], shape=(1, 4)) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) precision, update_op = metrics.streaming_precision(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, update_op.eval()) self.assertAlmostEqual(0.5, precision.eval()) def testWeighted1d(self): predictions = constant_op.constant([[1, 0, 1, 0], [1, 0, 1, 0]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) precision, update_op = metrics.streaming_precision( predictions, labels, weights=constant_op.constant([[2], [5]])) with self.test_session(): variables.local_variables_initializer().run() weighted_tp = 2.0 + 5.0 weighted_positives = (2.0 + 2.0) + (5.0 + 5.0) expected_precision = weighted_tp / weighted_positives self.assertAlmostEqual(expected_precision, update_op.eval()) self.assertAlmostEqual(expected_precision, precision.eval()) def testWeighted1d_placeholders(self): predictions = array_ops.placeholder(dtype=dtypes_lib.float32) labels = array_ops.placeholder(dtype=dtypes_lib.float32) feed_dict = { predictions: ((1, 0, 1, 0), (1, 0, 1, 0)), labels: ((0, 1, 1, 0), (1, 0, 0, 1)) } precision, update_op = metrics.streaming_precision( predictions, labels, weights=constant_op.constant([[2], [5]])) with self.test_session(): variables.local_variables_initializer().run() weighted_tp = 2.0 + 5.0 weighted_positives = (2.0 + 2.0) + (5.0 + 5.0) expected_precision = weighted_tp / weighted_positives self.assertAlmostEqual( expected_precision, update_op.eval(feed_dict=feed_dict)) self.assertAlmostEqual( expected_precision, precision.eval(feed_dict=feed_dict)) def testWeighted2d(self): predictions = constant_op.constant([[1, 0, 1, 0], [1, 0, 1, 0]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) precision, update_op = metrics.streaming_precision( predictions, labels, weights=constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1]])) with self.test_session(): variables.local_variables_initializer().run() weighted_tp = 3.0 + 4.0 weighted_positives = (1.0 + 3.0) + (4.0 + 2.0) expected_precision = weighted_tp / weighted_positives self.assertAlmostEqual(expected_precision, update_op.eval()) self.assertAlmostEqual(expected_precision, precision.eval()) def testWeighted2d_placeholders(self): predictions = array_ops.placeholder(dtype=dtypes_lib.float32) labels = array_ops.placeholder(dtype=dtypes_lib.float32) feed_dict = { predictions: ((1, 0, 1, 0), (1, 0, 1, 0)), labels: ((0, 1, 1, 0), (1, 0, 0, 1)) } precision, update_op = metrics.streaming_precision( predictions, labels, weights=constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1]])) with self.test_session(): variables.local_variables_initializer().run() weighted_tp = 3.0 + 4.0 weighted_positives = (1.0 + 3.0) + (4.0 + 2.0) expected_precision = weighted_tp / weighted_positives self.assertAlmostEqual( expected_precision, update_op.eval(feed_dict=feed_dict)) self.assertAlmostEqual( expected_precision, precision.eval(feed_dict=feed_dict)) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs) labels = constant_op.constant(1 - inputs) precision, update_op = metrics.streaming_precision(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(0, precision.eval()) def testZeroTrueAndFalsePositivesGivesZeroPrecision(self): predictions = constant_op.constant([0, 0, 0, 0]) labels = constant_op.constant([0, 0, 0, 0]) precision, update_op = metrics.streaming_precision(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0.0, precision.eval()) class StreamingRecallTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_recall( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables( self, ('recall/false_negatives/count:0', 'recall/true_positives/count:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_recall( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_recall( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) recall, update_op = metrics.streaming_recall(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_recall = recall.eval() for _ in range(10): self.assertEqual(initial_recall, recall.eval()) def testAllCorrect(self): np_inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(np_inputs) labels = constant_op.constant(np_inputs) recall, update_op = metrics.streaming_recall(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(1, recall.eval()) def testSomeCorrect(self): predictions = constant_op.constant([1, 0, 1, 0], shape=(1, 4)) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) recall, update_op = metrics.streaming_recall(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, update_op.eval()) self.assertAlmostEqual(0.5, recall.eval()) def testWeighted1d(self): predictions = constant_op.constant([[1, 0, 1, 0], [0, 1, 0, 1]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) weights = constant_op.constant([[2], [5]]) recall, update_op = metrics.streaming_recall( predictions, labels, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) weighted_tp = 2.0 + 5.0 weighted_t = (2.0 + 2.0) + (5.0 + 5.0) expected_precision = weighted_tp / weighted_t self.assertAlmostEqual(expected_precision, update_op.eval()) self.assertAlmostEqual(expected_precision, recall.eval()) def testWeighted2d(self): predictions = constant_op.constant([[1, 0, 1, 0], [0, 1, 0, 1]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) weights = constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1]]) recall, update_op = metrics.streaming_recall( predictions, labels, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) weighted_tp = 3.0 + 1.0 weighted_t = (2.0 + 3.0) + (4.0 + 1.0) expected_precision = weighted_tp / weighted_t self.assertAlmostEqual(expected_precision, update_op.eval()) self.assertAlmostEqual(expected_precision, recall.eval()) def testAllIncorrect(self): np_inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(np_inputs) labels = constant_op.constant(1 - np_inputs) recall, update_op = metrics.streaming_recall(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, recall.eval()) def testZeroTruePositivesAndFalseNegativesGivesZeroRecall(self): predictions = array_ops.zeros((1, 4)) labels = array_ops.zeros((1, 4)) recall, update_op = metrics.streaming_recall(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, recall.eval()) class StreamingFPRTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_positive_rate( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables(self, ('false_positive_rate/false_positives/count:0', 'false_positive_rate/true_negatives/count:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_false_positive_rate( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_false_positive_rate( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) fpr, update_op = metrics.streaming_false_positive_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_fpr = fpr.eval() for _ in range(10): self.assertEqual(initial_fpr, fpr.eval()) def testAllCorrect(self): np_inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(np_inputs) labels = constant_op.constant(np_inputs) fpr, update_op = metrics.streaming_false_positive_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, fpr.eval()) def testSomeCorrect(self): predictions = constant_op.constant([1, 0, 1, 0], shape=(1, 4)) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) fpr, update_op = metrics.streaming_false_positive_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, update_op.eval()) self.assertAlmostEqual(0.5, fpr.eval()) def testWeighted1d(self): predictions = constant_op.constant([[1, 0, 1, 0], [0, 1, 0, 1]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) weights = constant_op.constant([[2], [5]]) fpr, update_op = metrics.streaming_false_positive_rate( predictions, labels, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) weighted_fp = 2.0 + 5.0 weighted_f = (2.0 + 2.0) + (5.0 + 5.0) expected_fpr = weighted_fp / weighted_f self.assertAlmostEqual(expected_fpr, update_op.eval()) self.assertAlmostEqual(expected_fpr, fpr.eval()) def testWeighted2d(self): predictions = constant_op.constant([[1, 0, 1, 0], [0, 1, 0, 1]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) weights = constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1]]) fpr, update_op = metrics.streaming_false_positive_rate( predictions, labels, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) weighted_fp = 1.0 + 3.0 weighted_f = (1.0 + 4.0) + (2.0 + 3.0) expected_fpr = weighted_fp / weighted_f self.assertAlmostEqual(expected_fpr, update_op.eval()) self.assertAlmostEqual(expected_fpr, fpr.eval()) def testAllIncorrect(self): np_inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(np_inputs) labels = constant_op.constant(1 - np_inputs) fpr, update_op = metrics.streaming_false_positive_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(1, fpr.eval()) def testZeroFalsePositivesAndTrueNegativesGivesZeroFPR(self): predictions = array_ops.ones((1, 4)) labels = array_ops.ones((1, 4)) fpr, update_op = metrics.streaming_false_positive_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, fpr.eval()) class StreamingFNRTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_negative_rate( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables(self, ('false_negative_rate/false_negatives/count:0', 'false_negative_rate/true_positives/count:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_false_negative_rate( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_false_negative_rate( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) fnr, update_op = metrics.streaming_false_negative_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_fnr = fnr.eval() for _ in range(10): self.assertEqual(initial_fnr, fnr.eval()) def testAllCorrect(self): np_inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(np_inputs) labels = constant_op.constant(np_inputs) fnr, update_op = metrics.streaming_false_negative_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, fnr.eval()) def testSomeCorrect(self): predictions = constant_op.constant([1, 0, 1, 0], shape=(1, 4)) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) fnr, update_op = metrics.streaming_false_negative_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, update_op.eval()) self.assertAlmostEqual(0.5, fnr.eval()) def testWeighted1d(self): predictions = constant_op.constant([[1, 0, 1, 0], [0, 1, 0, 1]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) weights = constant_op.constant([[2], [5]]) fnr, update_op = metrics.streaming_false_negative_rate( predictions, labels, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) weighted_fn = 2.0 + 5.0 weighted_t = (2.0 + 2.0) + (5.0 + 5.0) expected_fnr = weighted_fn / weighted_t self.assertAlmostEqual(expected_fnr, update_op.eval()) self.assertAlmostEqual(expected_fnr, fnr.eval()) def testWeighted2d(self): predictions = constant_op.constant([[1, 0, 1, 0], [0, 1, 0, 1]]) labels = constant_op.constant([[0, 1, 1, 0], [1, 0, 0, 1]]) weights = constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1]]) fnr, update_op = metrics.streaming_false_negative_rate( predictions, labels, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) weighted_fn = 2.0 + 4.0 weighted_t = (2.0 + 3.0) + (1.0 + 4.0) expected_fnr = weighted_fn / weighted_t self.assertAlmostEqual(expected_fnr, update_op.eval()) self.assertAlmostEqual(expected_fnr, fnr.eval()) def testAllIncorrect(self): np_inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(np_inputs) labels = constant_op.constant(1 - np_inputs) fnr, update_op = metrics.streaming_false_negative_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(1, fnr.eval()) def testZeroFalseNegativesAndTruePositivesGivesZeroFNR(self): predictions = array_ops.zeros((1, 4)) labels = array_ops.zeros((1, 4)) fnr, update_op = metrics.streaming_false_negative_rate(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, fnr.eval()) class StreamingCurvePointsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metric_ops.streaming_curve_points( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables( self, ('curve_points/true_positives:0', 'curve_points/false_negatives:0', 'curve_points/false_positives:0', 'curve_points/true_negatives:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' points, _ = metric_ops.streaming_curve_points( labels=array_ops.ones((10, 1)), predictions=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [points]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metric_ops.streaming_curve_points( labels=array_ops.ones((10, 1)), predictions=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def _testValueTensorIsIdempotent(self, curve): predictions = constant_op.constant( np.random.uniform(size=(10, 3)), dtype=dtypes_lib.float32) labels = constant_op.constant( np.random.uniform(high=2, size=(10, 3)), dtype=dtypes_lib.float32) points, update_op = metric_ops.streaming_curve_points( labels, predictions=predictions, curve=curve) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) sess.run(update_op) initial_points = points.eval() sess.run(update_op) self.assertAllClose(initial_points, points.eval()) def testValueTensorIsIdempotentROC(self): self._testValueTensorIsIdempotent(curve='ROC') def testValueTensorIsIdempotentPR(self): self._testValueTensorIsIdempotent(curve='PR') def _testCase(self, labels, predictions, curve, expected_points): with self.test_session() as sess: predictions_tensor = constant_op.constant( predictions, dtype=dtypes_lib.float32) labels_tensor = constant_op.constant(labels, dtype=dtypes_lib.float32) points, update_op = metric_ops.streaming_curve_points( labels=labels_tensor, predictions=predictions_tensor, num_thresholds=3, curve=curve) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAllClose(expected_points, points.eval()) def testEdgeCasesROC(self): self._testCase([[1]], [[1]], 'ROC', [[0, 1], [0, 1], [0, 0]]) self._testCase([[0]], [[0]], 'ROC', [[1, 1], [0, 1], [0, 1]]) self._testCase([[0]], [[1]], 'ROC', [[1, 1], [1, 1], [0, 1]]) self._testCase([[1]], [[0]], 'ROC', [[0, 1], [0, 0], [0, 0]]) def testManyValuesROC(self): self._testCase([[1.0, 0.0, 0.0, 1.0, 1.0, 1.0]], [[0.2, 0.3, 0.4, 0.6, 0.7, 0.8]], 'ROC', [[1.0, 1.0], [0.0, 0.75], [0.0, 0.0]]) def testEdgeCasesPR(self): self._testCase([[1]], [[1]], 'PR', [[1, 1], [1, 1], [0, 1]]) self._testCase([[0]], [[0]], 'PR', [[1, 0], [1, 1], [1, 1]]) self._testCase([[0]], [[1]], 'PR', [[1, 0], [1, 0], [1, 1]]) self._testCase([[1]], [[0]], 'PR', [[1, 1], [0, 1], [0, 1]]) def testManyValuesPR(self): self._testCase([[1.0, 0.0, 0.0, 1.0, 1.0, 1.0]], [[0.2, 0.3, 0.4, 0.6, 0.7, 0.8]], 'PR', [[1.0, 4.0 / 6.0], [0.75, 1.0], [0.0, 1.0]]) def _np_auc(predictions, labels, weights=None): if weights is None: weights = np.ones(np.size(predictions)) is_positive = labels > 0 num_positives = np.sum(weights[is_positive]) num_negatives = np.sum(weights[~is_positive]) inds = np.argsort(-predictions) sorted_labels = labels[inds] sorted_weights = weights[inds] is_positive = sorted_labels > 0 tp = np.cumsum(sorted_weights * is_positive) / num_positives return np.sum((sorted_weights * tp)[~is_positive]) / num_negatives class StreamingAUCTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_auc( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables(self, ('auc/true_positives:0', 'auc/false_negatives:0', 'auc/false_positives:0', 'auc/true_negatives:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_auc( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_auc( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) auc, update_op = metrics.streaming_auc(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_auc = auc.eval() for _ in range(10): self.assertAlmostEqual(initial_auc, auc.eval(), 5) def testPredictionsOutOfRange(self): with self.test_session() as sess: predictions = constant_op.constant( [1, -1, 1, -1], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) _, update_op = metrics.streaming_auc(predictions, labels) sess.run(variables.local_variables_initializer()) self.assertRaises(errors_impl.InvalidArgumentError, update_op.eval) def testAllCorrect(self): self.allCorrectAsExpected('ROC') def allCorrectAsExpected(self, curve): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) auc, update_op = metrics.streaming_auc(predictions, labels, curve=curve) sess.run(variables.local_variables_initializer()) self.assertEqual(1, sess.run(update_op)) self.assertEqual(1, auc.eval()) def testSomeCorrect(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) auc, update_op = metrics.streaming_auc(predictions, labels) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, sess.run(update_op)) self.assertAlmostEqual(0.5, auc.eval()) def testWeighted1d(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) weights = constant_op.constant([2], shape=(1, 1)) auc, update_op = metrics.streaming_auc( predictions, labels, weights=weights) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.5, sess.run(update_op), 5) self.assertAlmostEqual(0.5, auc.eval(), 5) def testWeighted2d(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) weights = constant_op.constant([1, 2, 3, 4], shape=(1, 4)) auc, update_op = metrics.streaming_auc( predictions, labels, weights=weights) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.7, sess.run(update_op), 5) self.assertAlmostEqual(0.7, auc.eval(), 5) def testAUCPRSpecialCase(self): with self.test_session() as sess: predictions = constant_op.constant( [0.1, 0.4, 0.35, 0.8], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 0, 1, 1], shape=(1, 4)) auc, update_op = metrics.streaming_auc(predictions, labels, curve='PR') sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.79166, sess.run(update_op), delta=1e-3) self.assertAlmostEqual(0.79166, auc.eval(), delta=1e-3) def testAnotherAUCPRSpecialCase(self): with self.test_session() as sess: predictions = constant_op.constant( [0.1, 0.4, 0.35, 0.8, 0.1, 0.135, 0.81], shape=(1, 7), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 0, 1, 0, 1, 0, 1], shape=(1, 7)) auc, update_op = metrics.streaming_auc(predictions, labels, curve='PR') sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.610317, sess.run(update_op), delta=1e-3) self.assertAlmostEqual(0.610317, auc.eval(), delta=1e-3) def testThirdAUCPRSpecialCase(self): with self.test_session() as sess: predictions = constant_op.constant( [0.0, 0.1, 0.2, 0.33, 0.3, 0.4, 0.5], shape=(1, 7), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 0, 0, 0, 1, 1, 1], shape=(1, 7)) auc, update_op = metrics.streaming_auc(predictions, labels, curve='PR') sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.90277, sess.run(update_op), delta=1e-3) self.assertAlmostEqual(0.90277, auc.eval(), delta=1e-3) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(1 - inputs, dtype=dtypes_lib.float32) auc, update_op = metrics.streaming_auc(predictions, labels) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0, sess.run(update_op)) self.assertAlmostEqual(0, auc.eval()) def testZeroTruePositivesAndFalseNegativesGivesOneAUC(self): with self.test_session() as sess: predictions = array_ops.zeros([4], dtype=dtypes_lib.float32) labels = array_ops.zeros([4]) auc, update_op = metrics.streaming_auc(predictions, labels) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(1, sess.run(update_op), 6) self.assertAlmostEqual(1, auc.eval(), 6) def testRecallOneAndPrecisionOneGivesOnePRAUC(self): with self.test_session() as sess: predictions = array_ops.ones([4], dtype=dtypes_lib.float32) labels = array_ops.ones([4]) auc, update_op = metrics.streaming_auc(predictions, labels, curve='PR') sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(1, sess.run(update_op), 6) self.assertAlmostEqual(1, auc.eval(), 6) def testWithMultipleUpdates(self): num_samples = 1000 batch_size = 10 num_batches = int(num_samples / batch_size) labels = np.random.randint(0, 2, size=num_samples) noise = np.random.normal(0.0, scale=0.2, size=num_samples) predictions = 0.4 + 0.2 * labels + noise predictions[predictions > 1] = 1 predictions[predictions < 0] = 0 def _enqueue_as_batches(x, enqueue_ops): x_batches = x.astype(np.float32).reshape((num_batches, batch_size)) x_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) for i in range(num_batches): enqueue_ops[i].append(x_queue.enqueue(x_batches[i, :])) return x_queue.dequeue() for weights in (None, np.ones(num_samples), np.random.exponential(scale=1.0, size=num_samples)): expected_auc = _np_auc(predictions, labels, weights) with self.test_session() as sess: enqueue_ops = [[] for i in range(num_batches)] tf_predictions = _enqueue_as_batches(predictions, enqueue_ops) tf_labels = _enqueue_as_batches(labels, enqueue_ops) tf_weights = ( _enqueue_as_batches(weights, enqueue_ops) if weights is not None else None) for i in range(num_batches): sess.run(enqueue_ops[i]) auc, update_op = metrics.streaming_auc( tf_predictions, tf_labels, curve='ROC', num_thresholds=500, weights=tf_weights) sess.run(variables.local_variables_initializer()) for i in range(num_batches): sess.run(update_op) # Although with higher number of samples/thresholds we should see the # accuracy improving self.assertAlmostEqual(expected_auc, auc.eval(), 2) class StreamingDynamicAUCTest(test.TestCase): def setUp(self): super(StreamingDynamicAUCTest, self).setUp() np.random.seed(1) ops.reset_default_graph() def testUnknownCurve(self): with self.assertRaisesRegexp( ValueError, 'curve must be either ROC or PR, TEST_CURVE unknown'): metrics.streaming_dynamic_auc( labels=array_ops.ones((10, 1)), predictions=array_ops.ones((10, 1)), curve='TEST_CURVE') def testVars(self): metrics.streaming_dynamic_auc( labels=array_ops.ones((10, 1)), predictions=array_ops.ones((10, 1))) _assert_metric_variables(self, [ 'dynamic_auc/concat_labels/array:0', 'dynamic_auc/concat_labels/size:0', 'dynamic_auc/concat_preds/array:0', 'dynamic_auc/concat_preds/size:0' ]) def testMetricsCollection(self): my_collection_name = '__metrics__' auc, _ = metrics.streaming_dynamic_auc( labels=array_ops.ones((10, 1)), predictions=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertEqual(ops.get_collection(my_collection_name), [auc]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_dynamic_auc( labels=array_ops.ones((10, 1)), predictions=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in xrange(10): sess.run(update_op) # Then verify idempotency. initial_auc = auc.eval() for _ in xrange(10): self.assertAlmostEqual(initial_auc, auc.eval(), 5) def testAllLabelsOnes(self): with self.test_session() as sess: predictions = constant_op.constant([1., 1., 1.]) labels = constant_op.constant([1, 1, 1]) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, auc.eval()) def testAllLabelsZeros(self): with self.test_session() as sess: predictions = constant_op.constant([1., 1., 1.]) labels = constant_op.constant([0, 0, 0]) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(0, auc.eval()) def testNonZeroOnePredictions(self): with self.test_session() as sess: predictions = constant_op.constant( [2.5, -2.5, 2.5, -2.5], dtype=dtypes_lib.float32) labels = constant_op.constant([1, 0, 1, 0]) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(auc.eval(), 1.0) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs) labels = constant_op.constant(inputs) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertEqual(1, auc.eval()) def testSomeCorrect(self): with self.test_session() as sess: predictions = constant_op.constant([1, 0, 1, 0]) labels = constant_op.constant([0, 1, 1, 0]) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(0.5, auc.eval()) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(1 - inputs, dtype=dtypes_lib.float32) auc, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(0, auc.eval()) def testExceptionOnIncompatibleShapes(self): with self.test_session() as sess: predictions = array_ops.ones([5]) labels = array_ops.zeros([6]) with self.assertRaisesRegexp(ValueError, 'Shapes .* are incompatible'): _, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) sess.run(update_op) def testExceptionOnGreaterThanOneLabel(self): with self.test_session() as sess: predictions = constant_op.constant([1, 0.5, 0], dtypes_lib.float32) labels = constant_op.constant([2, 1, 0]) _, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) with self.assertRaisesRegexp( errors_impl.InvalidArgumentError, '.*labels must be 0 or 1, at least one is >1.*'): sess.run(update_op) def testExceptionOnNegativeLabel(self): with self.test_session() as sess: predictions = constant_op.constant([1, 0.5, 0], dtypes_lib.float32) labels = constant_op.constant([1, 0, -1]) _, update_op = metrics.streaming_dynamic_auc(labels, predictions) sess.run(variables.local_variables_initializer()) with self.assertRaisesRegexp( errors_impl.InvalidArgumentError, '.*labels must be 0 or 1, at least one is <0.*'): sess.run(update_op) def testWithMultipleUpdates(self): batch_size = 10 num_batches = 100 labels = np.array([]) predictions = np.array([]) tf_labels = variables.Variable( array_ops.ones(batch_size, dtypes_lib.int32), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.int32) tf_predictions = variables.Variable( array_ops.ones(batch_size), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.float32) auc, update_op = metrics.streaming_dynamic_auc(tf_labels, tf_predictions) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in xrange(num_batches): new_labels = np.random.randint(0, 2, size=batch_size) noise = np.random.normal(0.0, scale=0.2, size=batch_size) new_predictions = 0.4 + 0.2 * new_labels + noise labels = np.concatenate([labels, new_labels]) predictions = np.concatenate([predictions, new_predictions]) sess.run(tf_labels.assign(new_labels)) sess.run(tf_predictions.assign(new_predictions)) sess.run(update_op) expected_auc = _np_auc(predictions, labels) self.assertAlmostEqual(expected_auc, auc.eval()) def testAUCPRReverseIncreasingPredictions(self): with self.test_session() as sess: predictions = constant_op.constant( [0.1, 0.4, 0.35, 0.8], dtype=dtypes_lib.float32) labels = constant_op.constant([0, 0, 1, 1]) auc, update_op = metrics.streaming_dynamic_auc( labels, predictions, curve='PR') sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(0.79166, auc.eval(), delta=1e-5) def testAUCPRJumbledPredictions(self): with self.test_session() as sess: predictions = constant_op.constant( [0.1, 0.4, 0.35, 0.8, 0.1, 0.135, 0.81], dtypes_lib.float32) labels = constant_op.constant([0, 0, 1, 0, 1, 0, 1]) auc, update_op = metrics.streaming_dynamic_auc( labels, predictions, curve='PR') sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(0.610317, auc.eval(), delta=1e-6) def testAUCPRPredictionsLessThanHalf(self): with self.test_session() as sess: predictions = constant_op.constant( [0.0, 0.1, 0.2, 0.33, 0.3, 0.4, 0.5], shape=(1, 7), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 0, 0, 0, 1, 1, 1], shape=(1, 7)) auc, update_op = metrics.streaming_dynamic_auc( labels, predictions, curve='PR') sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(0.90277, auc.eval(), delta=1e-5) def testWithWeights(self): batch_size = 10 num_batches = 100 labels = np.array([]) predictions = np.array([]) weights = np.array([]) tf_labels = variables.Variable( array_ops.ones(batch_size, dtypes_lib.int32), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.int32) tf_predictions = variables.Variable( array_ops.ones(batch_size), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.float32) tf_weights = variables.Variable( array_ops.ones(batch_size), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.float32) auc, update_op = metrics.streaming_dynamic_auc(tf_labels, tf_predictions, weights=tf_weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in xrange(num_batches): new_labels = np.random.randint(0, 2, size=batch_size) noise = np.random.uniform(-0.2, 0.2, size=batch_size) new_predictions = 0.4 + 0.2 * new_labels + noise new_weights = np.random.uniform(0.0, 3.0, size=batch_size) labels = np.concatenate([labels, new_labels]) predictions = np.concatenate([predictions, new_predictions]) weights = np.concatenate([weights, new_weights]) sess.run([tf_labels.assign(new_labels), tf_predictions.assign(new_predictions), tf_weights.assign(new_weights)]) sess.run(update_op) expected_auc = _np_auc(predictions, labels, weights) self.assertAlmostEqual(expected_auc, auc.eval()) class AucWithConfidenceIntervalsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def _testResultsEqual(self, expected_dict, gotten_result): gotten_dict = {k: t.eval() for k, t in gotten_result._asdict().items()} self.assertItemsEqual( list(expected_dict.keys()), list(gotten_dict.keys())) for key, expected_values in expected_dict.items(): self.assertAllClose(expected_values, gotten_dict[key]) def _testCase(self, predictions, labels, expected_result, weights=None): with self.test_session() as sess: predictions_tensor = constant_op.constant( predictions, dtype=dtypes_lib.float32) labels_tensor = constant_op.constant(labels, dtype=dtypes_lib.int64) weights_tensor = None if weights: weights_tensor = constant_op.constant(weights, dtype=dtypes_lib.float32) gotten_result, update_op = ( metric_ops.auc_with_confidence_intervals( labels=labels_tensor, predictions=predictions_tensor, weights=weights_tensor)) sess.run(variables.local_variables_initializer()) sess.run(update_op) self._testResultsEqual(expected_result, gotten_result) def testAucAllCorrect(self): self._testCase( predictions=[0., 0.2, 0.3, 0.3, 0.4, 0.5, 0.6, 0.6, 0.8, 1.0], labels=[0, 0, 1, 0, 0, 1, 0, 1, 1, 0], expected_result={ 'auc': 0.66666667, 'lower': 0.27826795, 'upper': 0.91208512, }) def testAucUnorderedInput(self): self._testCase( predictions=[1.0, 0.6, 0., 0.3, 0.4, 0.2, 0.5, 0.3, 0.6, 0.8], labels=[0, 1, 0, 1, 0, 0, 1, 0, 0, 1], expected_result={ 'auc': 0.66666667, 'lower': 0.27826795, 'upper': 0.91208512, }) def testAucWithWeights(self): self._testCase( predictions=[0., 0.2, 0.3, 0.3, 0.4, 0.5, 0.6, 0.6, 0.8, 1.0], labels=[0, 0, 1, 0, 0, 1, 0, 1, 1, 0], weights=[0.5, 0.6, 1.2, 1.5, 2.0, 2.0, 1.5, 1.2, 0.6, 0.5], expected_result={ 'auc': 0.65151515, 'lower': 0.28918604, 'upper': 0.89573906, }) def testAucEqualOne(self): self._testCase( predictions=[0, 0.2, 0.3, 0.3, 0.4, 0.5, 0.6, 0.6, 0.8, 1.0], labels=[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], expected_result={ 'auc': 1.0, 'lower': 1.0, 'upper': 1.0, }) def testAucEqualZero(self): self._testCase( predictions=[0, 0.2, 0.3, 0.3, 0.4, 0.5, 0.6, 0.6, 0.8, 1.0], labels=[1, 1, 1, 1, 1, 0, 0, 0, 0, 0], expected_result={ 'auc': 0.0, 'lower': 0.0, 'upper': 0.0, }) def testNonZeroOnePredictions(self): self._testCase( predictions=[2.5, -2.5, .5, -.5, 1], labels=[1, 0, 1, 0, 0], expected_result={ 'auc': 0.83333333, 'lower': 0.15229267, 'upper': 0.99286517, }) def testAllLabelsOnes(self): self._testCase( predictions=[1., 1., 1., 1., 1.], labels=[1, 1, 1, 1, 1], expected_result={ 'auc': 0., 'lower': 0., 'upper': 0., }) def testAllLabelsZeros(self): self._testCase( predictions=[0., 0., 0., 0., 0.], labels=[0, 0, 0, 0, 0], expected_result={ 'auc': 0., 'lower': 0., 'upper': 0., }) def testWeightSumLessThanOneAll(self): self._testCase( predictions=[1., 1., 0., 1., 0., 0.], labels=[1, 1, 1, 0, 0, 0], weights=[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], expected_result={ 'auc': 0., 'lower': 0., 'upper': 0., }) def testWithMultipleUpdates(self): batch_size = 50 num_batches = 100 labels = np.array([]) predictions = np.array([]) tf_labels = variables.Variable(array_ops.ones(batch_size, dtypes_lib.int32), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.int32) tf_predictions = variables.Variable( array_ops.ones(batch_size), collections=[ops.GraphKeys.LOCAL_VARIABLES], dtype=dtypes_lib.float32) auc, update_op = metrics.auc_with_confidence_intervals(tf_labels, tf_predictions) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in xrange(num_batches): new_labels = np.random.randint(0, 2, size=batch_size) noise = np.random.normal(0.0, scale=0.2, size=batch_size) new_predictions = 0.4 + 0.2 * new_labels + noise labels = np.concatenate([labels, new_labels]) predictions = np.concatenate([predictions, new_predictions]) sess.run(tf_labels.assign(new_labels)) sess.run(tf_predictions.assign(new_predictions)) sess.run(update_op) expected_auc = _np_auc(predictions, labels) self.assertAllClose(expected_auc, auc.auc.eval()) def testExceptionOnFloatLabels(self): with self.test_session() as sess: predictions = constant_op.constant([1, 0.5, 0, 1, 0], dtypes_lib.float32) labels = constant_op.constant([0.7, 0, 1, 0, 1]) _, update_op = metrics.auc_with_confidence_intervals(labels, predictions) sess.run(variables.local_variables_initializer()) self.assertRaises(TypeError, sess.run(update_op)) def testExceptionOnGreaterThanOneLabel(self): with self.test_session() as sess: predictions = constant_op.constant([1, 0.5, 0, 1, 0], dtypes_lib.float32) labels = constant_op.constant([2, 1, 0, 1, 0]) _, update_op = metrics.auc_with_confidence_intervals(labels, predictions) sess.run(variables.local_variables_initializer()) with self.assertRaisesRegexp( errors_impl.InvalidArgumentError, '.*labels must be 0 or 1, at least one is >1.*'): sess.run(update_op) def testExceptionOnNegativeLabel(self): with self.test_session() as sess: predictions = constant_op.constant([1, 0.5, 0, 1, 0], dtypes_lib.float32) labels = constant_op.constant([1, 0, -1, 1, 0]) _, update_op = metrics.auc_with_confidence_intervals(labels, predictions) sess.run(variables.local_variables_initializer()) with self.assertRaisesRegexp( errors_impl.InvalidArgumentError, '.*labels must be 0 or 1, at least one is <0.*'): sess.run(update_op) class StreamingPrecisionRecallAtEqualThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def _testResultsEqual(self, expected_dict, gotten_result, eps=None): gotten_dict = {k: t.eval() for k, t in gotten_result._asdict().items()} self.assertItemsEqual(list(expected_dict.keys()), list(gotten_dict.keys())) for key, expected_values in expected_dict.items(): if eps is not None: self.assertAllClose(expected_values, gotten_dict[key], atol=eps) else: self.assertAllClose(expected_values, gotten_dict[key]) def testVars(self): metric_ops.precision_recall_at_equal_thresholds( labels=constant_op.constant([True], dtype=dtypes_lib.bool), predictions=constant_op.constant([0.42], dtype=dtypes_lib.float32)) _assert_metric_variables( self, ('precision_recall_at_equal_thresholds/variables/tp_buckets:0', 'precision_recall_at_equal_thresholds/variables/fp_buckets:0')) def testVarsWithName(self): metric_ops.precision_recall_at_equal_thresholds( labels=constant_op.constant([True], dtype=dtypes_lib.bool), predictions=constant_op.constant([0.42], dtype=dtypes_lib.float32), name='foo') _assert_metric_variables( self, ('foo/variables/tp_buckets:0', 'foo/variables/fp_buckets:0')) def testValuesAreIdempotent(self): predictions = constant_op.constant( np.random.uniform(size=(10, 3)), dtype=dtypes_lib.float32) labels = constant_op.constant( np.random.uniform(size=(10, 3)) > 0.5, dtype=dtypes_lib.bool) result, update_op = metric_ops.precision_recall_at_equal_thresholds( labels=labels, predictions=predictions) with self.test_session() as sess: # Run several updates. sess.run(variables.local_variables_initializer()) for _ in range(3): sess.run(update_op) # Then verify idempotency. initial_result = { k: value.eval().tolist() for k, value in result._asdict().items() } for _ in range(3): self._testResultsEqual(initial_result, result) def _testCase(self, predictions, labels, expected_result, dtype=dtypes_lib.float32, eps=None, weights=None): with self.test_session() as sess: predictions_tensor = constant_op.constant(predictions, dtype=dtype) labels_tensor = constant_op.constant(labels, dtype=dtypes_lib.bool) weights_tensor = None if weights: weights_tensor = constant_op.constant(weights, dtype=dtype) gotten_result, update_op = ( metric_ops.precision_recall_at_equal_thresholds( labels=labels_tensor, predictions=predictions_tensor, weights=weights_tensor, num_thresholds=3)) self.assertEqual(gotten_result.tp.dtype, dtype) self.assertEqual(gotten_result.fp.dtype, dtype) self.assertEqual(gotten_result.tn.dtype, dtype) self.assertEqual(gotten_result.fn.dtype, dtype) self.assertEqual(gotten_result.precision.dtype, dtype) self.assertEqual(gotten_result.recall.dtype, dtype) self.assertEqual(gotten_result.thresholds.dtype, dtype) sess.run(variables.local_variables_initializer()) sess.run(update_op) self._testResultsEqual(expected_result, gotten_result, eps=eps) def testAllTruePositives(self): self._testCase( [[1]], [[True]], { 'tp': [1, 1, 1], 'fp': [0, 0, 0], 'tn': [0, 0, 0], 'fn': [0, 0, 0], 'precision': [1.0, 1.0, 1.0], 'recall': [1.0, 1.0, 1.0], 'thresholds': [0.0, 0.5, 1.0], }) def testAllTrueNegatives(self): self._testCase( [[0]], [[False]], { 'tp': [0, 0, 0], 'fp': [1, 0, 0], 'tn': [0, 1, 1], 'fn': [0, 0, 0], 'precision': [0.0, 0.0, 0.0], 'recall': [0.0, 0.0, 0.0], 'thresholds': [0.0, 0.5, 1.0], }) def testAllFalsePositives(self): self._testCase( [[1]], [[False]], { 'tp': [0, 0, 0], 'fp': [1, 1, 1], 'tn': [0, 0, 0], 'fn': [0, 0, 0], 'precision': [0.0, 0.0, 0.0], 'recall': [0.0, 0.0, 0.0], 'thresholds': [0.0, 0.5, 1.0], }) def testAllFalseNegatives(self): self._testCase( [[0]], [[True]], { 'tp': [1, 0, 0], 'fp': [0, 0, 0], 'tn': [0, 0, 0], 'fn': [0, 1, 1], 'precision': [1.0, 0.0, 0.0], 'recall': [1.0, 0.0, 0.0], 'thresholds': [0.0, 0.5, 1.0], }) def testManyValues(self): self._testCase( [[0.2, 0.3, 0.4, 0.6, 0.7, 0.8]], [[True, False, False, True, True, True]], { 'tp': [4, 3, 0], 'fp': [2, 0, 0], 'tn': [0, 2, 2], 'fn': [0, 1, 4], 'precision': [2.0 / 3.0, 1.0, 0.0], 'recall': [1.0, 0.75, 0.0], 'thresholds': [0.0, 0.5, 1.0], }) def testManyValuesWithWeights(self): self._testCase( [[0.2, 0.3, 0.4, 0.6, 0.7, 0.8]], [[True, False, False, True, True, True]], { 'tp': [1.5, 1.5, 0.0], 'fp': [2.5, 0.0, 0.0], 'tn': [0.0, 2.5, 2.5], 'fn': [0.0, 0.0, 1.5], 'precision': [0.375, 1.0, 0.0], 'recall': [1.0, 1.0, 0.0], 'thresholds': [0.0, 0.5, 1.0], }, weights=[[0.0, 0.5, 2.0, 0.0, 0.5, 1.0]]) def testFloat64(self): self._testCase( [[0.2, 0.3, 0.4, 0.6, 0.7, 0.8]], [[True, False, False, True, True, True]], { 'tp': [4, 3, 0], 'fp': [2, 0, 0], 'tn': [0, 2, 2], 'fn': [0, 1, 4], 'precision': [2.0 / 3.0, 1.0, 0.0], 'recall': [1.0, 0.75, 0.0], 'thresholds': [0.0, 0.5, 1.0], }, dtype=dtypes_lib.float64) def testFloat16(self): self._testCase( [[0.2, 0.3, 0.4, 0.6, 0.7, 0.8]], [[True, False, False, True, True, True]], { 'tp': [4, 3, 0], 'fp': [2, 0, 0], 'tn': [0, 2, 2], 'fn': [0, 1, 4], 'precision': [2.0 / 3.0, 1.0, 0.0], 'recall': [1.0, 0.75, 0.0], 'thresholds': [0.0, 0.5, 1.0], }, dtype=dtypes_lib.float16, eps=1e-3) class StreamingSpecificityAtSensitivityTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_specificity_at_sensitivity( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), sensitivity=0.7) _assert_metric_variables(self, ('specificity_at_sensitivity/true_positives:0', 'specificity_at_sensitivity/false_negatives:0', 'specificity_at_sensitivity/false_positives:0', 'specificity_at_sensitivity/true_negatives:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_specificity_at_sensitivity( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), sensitivity=0.7, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_specificity_at_sensitivity( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), sensitivity=0.7, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) specificity, update_op = metrics.streaming_specificity_at_sensitivity( predictions, labels, sensitivity=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_specificity = specificity.eval() for _ in range(10): self.assertAlmostEqual(initial_specificity, specificity.eval(), 5) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) specificity, update_op = metrics.streaming_specificity_at_sensitivity( predictions, labels, sensitivity=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1, sess.run(update_op)) self.assertEqual(1, specificity.eval()) def testSomeCorrectHighSensitivity(self): predictions_values = [0.1, 0.2, 0.4, 0.3, 0.0, 0.1, 0.45, 0.5, 0.8, 0.9] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) specificity, update_op = metrics.streaming_specificity_at_sensitivity( predictions, labels, sensitivity=0.8) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(1.0, sess.run(update_op)) self.assertAlmostEqual(1.0, specificity.eval()) def testSomeCorrectLowSensitivity(self): predictions_values = [0.1, 0.2, 0.4, 0.3, 0.0, 0.1, 0.2, 0.2, 0.26, 0.26] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) specificity, update_op = metrics.streaming_specificity_at_sensitivity( predictions, labels, sensitivity=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.6, sess.run(update_op)) self.assertAlmostEqual(0.6, specificity.eval()) def testWeighted1d(self): predictions_values = [0.1, 0.2, 0.4, 0.3, 0.0, 0.1, 0.2, 0.2, 0.26, 0.26] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] weights_values = [3] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) weights = constant_op.constant(weights_values) specificity, update_op = metrics.streaming_specificity_at_sensitivity( predictions, labels, weights=weights, sensitivity=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.6, sess.run(update_op)) self.assertAlmostEqual(0.6, specificity.eval()) def testWeighted2d(self): predictions_values = [0.1, 0.2, 0.4, 0.3, 0.0, 0.1, 0.2, 0.2, 0.26, 0.26] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] weights_values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) weights = constant_op.constant(weights_values) specificity, update_op = metrics.streaming_specificity_at_sensitivity( predictions, labels, weights=weights, sensitivity=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(8.0 / 15.0, sess.run(update_op)) self.assertAlmostEqual(8.0 / 15.0, specificity.eval()) class StreamingSensitivityAtSpecificityTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_sensitivity_at_specificity( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), specificity=0.7) _assert_metric_variables(self, ('sensitivity_at_specificity/true_positives:0', 'sensitivity_at_specificity/false_negatives:0', 'sensitivity_at_specificity/false_positives:0', 'sensitivity_at_specificity/true_negatives:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_sensitivity_at_specificity( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), specificity=0.7, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_sensitivity_at_specificity( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), specificity=0.7, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) sensitivity, update_op = metrics.streaming_sensitivity_at_specificity( predictions, labels, specificity=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_sensitivity = sensitivity.eval() for _ in range(10): self.assertAlmostEqual(initial_sensitivity, sensitivity.eval(), 5) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) specificity, update_op = metrics.streaming_sensitivity_at_specificity( predictions, labels, specificity=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1, sess.run(update_op)) self.assertEqual(1, specificity.eval()) def testSomeCorrectHighSpecificity(self): predictions_values = [0.0, 0.1, 0.2, 0.3, 0.4, 0.1, 0.45, 0.5, 0.8, 0.9] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) specificity, update_op = metrics.streaming_sensitivity_at_specificity( predictions, labels, specificity=0.8) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.8, sess.run(update_op)) self.assertAlmostEqual(0.8, specificity.eval()) def testSomeCorrectLowSpecificity(self): predictions_values = [0.0, 0.1, 0.2, 0.3, 0.4, 0.01, 0.02, 0.25, 0.26, 0.26] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) specificity, update_op = metrics.streaming_sensitivity_at_specificity( predictions, labels, specificity=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.6, sess.run(update_op)) self.assertAlmostEqual(0.6, specificity.eval()) def testWeighted(self): predictions_values = [0.0, 0.1, 0.2, 0.3, 0.4, 0.01, 0.02, 0.25, 0.26, 0.26] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] weights_values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) weights = constant_op.constant(weights_values) specificity, update_op = metrics.streaming_sensitivity_at_specificity( predictions, labels, weights=weights, specificity=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.675, sess.run(update_op)) self.assertAlmostEqual(0.675, specificity.eval()) # TODO(nsilberman): Break this up into two sets of tests. class StreamingPrecisionRecallThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_precision_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0]) _assert_metric_variables(self, ( 'precision_at_thresholds/true_positives:0', 'precision_at_thresholds/false_positives:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' prec, _ = metrics.streaming_precision_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], metrics_collections=[my_collection_name]) rec, _ = metrics.streaming_recall_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [prec, rec]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, precision_op = metrics.streaming_precision_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], updates_collections=[my_collection_name]) _, recall_op = metrics.streaming_recall_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], updates_collections=[my_collection_name]) self.assertListEqual( ops.get_collection(my_collection_name), [precision_op, recall_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) thresholds = [0, 0.5, 1.0] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run([prec_op, rec_op]) # Then verify idempotency. initial_prec = prec.eval() initial_rec = rec.eval() for _ in range(10): self.assertAllClose(initial_prec, prec.eval()) self.assertAllClose(initial_rec, rec.eval()) # TODO(nsilberman): fix tests (passing but incorrect). def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) thresholds = [0.5] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertEqual(1, prec.eval()) self.assertEqual(1, rec.eval()) def testSomeCorrect(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) thresholds = [0.5] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertAlmostEqual(0.5, prec.eval()) self.assertAlmostEqual(0.5, rec.eval()) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(1 - inputs, dtype=dtypes_lib.float32) thresholds = [0.5] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertAlmostEqual(0, prec.eval()) self.assertAlmostEqual(0, rec.eval()) def testWeights1d(self): with self.test_session() as sess: predictions = constant_op.constant( [[1, 0], [1, 0]], shape=(2, 2), dtype=dtypes_lib.float32) labels = constant_op.constant([[0, 1], [1, 0]], shape=(2, 2)) weights = constant_op.constant( [[0], [1]], shape=(2, 1), dtype=dtypes_lib.float32) thresholds = [0.5, 1.1] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds, weights=weights) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds, weights=weights) prec_low = prec[0] prec_high = prec[1] rec_low = rec[0] rec_high = rec[1] sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertAlmostEqual(1.0, prec_low.eval(), places=5) self.assertAlmostEqual(0.0, prec_high.eval(), places=5) self.assertAlmostEqual(1.0, rec_low.eval(), places=5) self.assertAlmostEqual(0.0, rec_high.eval(), places=5) def testWeights2d(self): with self.test_session() as sess: predictions = constant_op.constant( [[1, 0], [1, 0]], shape=(2, 2), dtype=dtypes_lib.float32) labels = constant_op.constant([[0, 1], [1, 0]], shape=(2, 2)) weights = constant_op.constant( [[0, 0], [1, 1]], shape=(2, 2), dtype=dtypes_lib.float32) thresholds = [0.5, 1.1] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds, weights=weights) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds, weights=weights) prec_low = prec[0] prec_high = prec[1] rec_low = rec[0] rec_high = rec[1] sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertAlmostEqual(1.0, prec_low.eval(), places=5) self.assertAlmostEqual(0.0, prec_high.eval(), places=5) self.assertAlmostEqual(1.0, rec_low.eval(), places=5) self.assertAlmostEqual(0.0, rec_high.eval(), places=5) def testExtremeThresholds(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 1], shape=(1, 4)) thresholds = [-1.0, 2.0] # lower/higher than any values prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds) prec_low = prec[0] prec_high = prec[1] rec_low = rec[0] rec_high = rec[1] sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertAlmostEqual(0.75, prec_low.eval()) self.assertAlmostEqual(0.0, prec_high.eval()) self.assertAlmostEqual(1.0, rec_low.eval()) self.assertAlmostEqual(0.0, rec_high.eval()) def testZeroLabelsPredictions(self): with self.test_session() as sess: predictions = array_ops.zeros([4], dtype=dtypes_lib.float32) labels = array_ops.zeros([4]) thresholds = [0.5] prec, prec_op = metrics.streaming_precision_at_thresholds( predictions, labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run([prec_op, rec_op]) self.assertAlmostEqual(0, prec.eval(), 6) self.assertAlmostEqual(0, rec.eval(), 6) def testWithMultipleUpdates(self): num_samples = 1000 batch_size = 10 num_batches = int(num_samples / batch_size) # Create the labels and data. labels = np.random.randint(0, 2, size=(num_samples, 1)) noise = np.random.normal(0.0, scale=0.2, size=(num_samples, 1)) predictions = 0.4 + 0.2 * labels + noise predictions[predictions > 1] = 1 predictions[predictions < 0] = 0 thresholds = [0.3] tp = 0 fp = 0 fn = 0 tn = 0 for i in range(num_samples): if predictions[i] > thresholds[0]: if labels[i] == 1: tp += 1 else: fp += 1 else: if labels[i] == 1: fn += 1 else: tn += 1 epsilon = 1e-7 expected_prec = tp / (epsilon + tp + fp) expected_rec = tp / (epsilon + tp + fn) labels = labels.astype(np.float32) predictions = predictions.astype(np.float32) with self.test_session() as sess: # Reshape the data so its easy to queue up: predictions_batches = predictions.reshape((batch_size, num_batches)) labels_batches = labels.reshape((batch_size, num_batches)) # Enqueue the data: predictions_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) labels_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) for i in range(int(num_batches)): tf_prediction = constant_op.constant(predictions_batches[:, i]) tf_label = constant_op.constant(labels_batches[:, i]) sess.run([ predictions_queue.enqueue(tf_prediction), labels_queue.enqueue(tf_label) ]) tf_predictions = predictions_queue.dequeue() tf_labels = labels_queue.dequeue() prec, prec_op = metrics.streaming_precision_at_thresholds( tf_predictions, tf_labels, thresholds) rec, rec_op = metrics.streaming_recall_at_thresholds( tf_predictions, tf_labels, thresholds) sess.run(variables.local_variables_initializer()) for _ in range(int(num_samples / batch_size)): sess.run([prec_op, rec_op]) # Since this is only approximate, we can't expect a 6 digits match. self.assertAlmostEqual(expected_prec, prec.eval(), 2) self.assertAlmostEqual(expected_rec, rec.eval(), 2) class StreamingFPRThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_positive_rate_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0]) _assert_metric_variables(self, ( 'false_positive_rate_at_thresholds/false_positives:0', 'false_positive_rate_at_thresholds/true_negatives:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' fpr, _ = metrics.streaming_false_positive_rate_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [fpr]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_false_positive_rate_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) thresholds = [0, 0.5, 1.0] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(fpr_op) initial_fpr = fpr.eval() for _ in range(10): self.assertAllClose(initial_fpr, fpr.eval()) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) thresholds = [0.5] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertEqual(0, fpr.eval()) def testSomeCorrect(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) thresholds = [0.5] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertAlmostEqual(0.5, fpr.eval()) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(1 - inputs, dtype=dtypes_lib.float32) thresholds = [0.5] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertAlmostEqual(1, fpr.eval()) def testWeights1d(self): with self.test_session() as sess: predictions = constant_op.constant( [[1, 0], [1, 0]], shape=(2, 2), dtype=dtypes_lib.float32) labels = constant_op.constant([[0, 1], [1, 0]], shape=(2, 2)) weights = constant_op.constant( [[0], [1]], shape=(2, 1), dtype=dtypes_lib.float32) thresholds = [0.5, 1.1] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds, weights=weights) fpr_low = fpr[0] fpr_high = fpr[1] sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertAlmostEqual(0.0, fpr_low.eval(), places=5) self.assertAlmostEqual(0.0, fpr_high.eval(), places=5) def testWeights2d(self): with self.test_session() as sess: predictions = constant_op.constant( [[1, 0], [1, 0]], shape=(2, 2), dtype=dtypes_lib.float32) labels = constant_op.constant([[0, 1], [1, 0]], shape=(2, 2)) weights = constant_op.constant( [[0, 0], [1, 1]], shape=(2, 2), dtype=dtypes_lib.float32) thresholds = [0.5, 1.1] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds, weights=weights) fpr_low = fpr[0] fpr_high = fpr[1] sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertAlmostEqual(0.0, fpr_low.eval(), places=5) self.assertAlmostEqual(0.0, fpr_high.eval(), places=5) def testExtremeThresholds(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 1], shape=(1, 4)) thresholds = [-1.0, 2.0] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds) fpr_low = fpr[0] fpr_high = fpr[1] sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertAlmostEqual(1.0, fpr_low.eval(), places=5) self.assertAlmostEqual(0.0, fpr_high.eval(), places=5) def testZeroLabelsPredictions(self): with self.test_session() as sess: predictions = array_ops.zeros([4], dtype=dtypes_lib.float32) labels = array_ops.zeros([4]) thresholds = [0.5] fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fpr_op) self.assertAlmostEqual(0, fpr.eval(), 6) def testWithMultipleUpdates(self): num_samples = 1000 batch_size = 10 num_batches = int(num_samples / batch_size) labels = np.random.randint(0, 2, size=(num_samples, 1)) noise = np.random.normal(0.0, scale=0.2, size=(num_samples, 1)) predictions = 0.4 + 0.2 * labels + noise predictions[predictions > 1] = 1 predictions[predictions < 0] = 0 thresholds = [0.3] fp = 0 tn = 0 for i in range(num_samples): if predictions[i] > thresholds[0]: if labels[i] == 0: fp += 1 else: if labels[i] == 0: tn += 1 epsilon = 1e-7 expected_fpr = fp / (epsilon + fp + tn) labels = labels.astype(np.float32) predictions = predictions.astype(np.float32) with self.test_session() as sess: predictions_batches = predictions.reshape((batch_size, num_batches)) labels_batches = labels.reshape((batch_size, num_batches)) predictions_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) labels_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) for i in range(int(num_batches)): tf_prediction = constant_op.constant(predictions_batches[:, i]) tf_label = constant_op.constant(labels_batches[:, i]) sess.run([ predictions_queue.enqueue(tf_prediction), labels_queue.enqueue(tf_label) ]) tf_predictions = predictions_queue.dequeue() tf_labels = labels_queue.dequeue() fpr, fpr_op = metrics.streaming_false_positive_rate_at_thresholds( tf_predictions, tf_labels, thresholds) sess.run(variables.local_variables_initializer()) for _ in range(int(num_samples / batch_size)): sess.run(fpr_op) # Although with higher number of samples/thresholds we should see the # accuracy improving self.assertAlmostEqual(expected_fpr, fpr.eval(), 2) class RecallAtPrecisionTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.recall_at_precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), precision=0.7) _assert_metric_variables(self, ('recall_at_precision/true_positives:0', 'recall_at_precision/false_negatives:0', 'recall_at_precision/false_positives:0', 'recall_at_precision/true_negatives:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.recall_at_precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), precision=0.7, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.recall_at_precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), precision=0.7, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) recall, update_op = metrics.recall_at_precision( labels, predictions, precision=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_recall = recall.eval() for _ in range(10): self.assertAlmostEqual(initial_recall, recall.eval(), 5) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) recall, update_op = metrics.recall_at_precision( labels, predictions, precision=1.0) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1, sess.run(update_op)) self.assertEqual(1, recall.eval()) def testSomeCorrectHighPrecision(self): predictions_values = [1, .9, .8, .7, .6, .5, .4, .3] labels_values = [1, 1, 1, 1, 0, 0, 0, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) recall, update_op = metrics.recall_at_precision( labels, predictions, precision=0.8) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.8, sess.run(update_op)) self.assertAlmostEqual(0.8, recall.eval()) def testSomeCorrectLowPrecision(self): predictions_values = [1, .9, .8, .7, .6, .5, .4, .3, .2, .1] labels_values = [1, 1, 0, 0, 0, 0, 0, 0, 0, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) recall, update_op = metrics.recall_at_precision( labels, predictions, precision=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) target_recall = 2.0 / 3.0 self.assertAlmostEqual(target_recall, sess.run(update_op)) self.assertAlmostEqual(target_recall, recall.eval()) def testWeighted(self): predictions_values = [1, .9, .8, .7, .6] labels_values = [1, 1, 0, 0, 1] weights_values = [1, 1, 3, 4, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) weights = constant_op.constant(weights_values) recall, update_op = metrics.recall_at_precision( labels, predictions, weights=weights, precision=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) target_recall = 2.0 / 3.0 self.assertAlmostEqual(target_recall, sess.run(update_op)) self.assertAlmostEqual(target_recall, recall.eval()) class PrecisionAtRecallTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.precision_at_recall( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), target_recall=0.7) _assert_metric_variables(self, ('precision_at_recall/true_positives:0', 'precision_at_recall/false_negatives:0', 'precision_at_recall/false_positives:0', 'precision_at_recall/true_negatives:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.precision_at_recall( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), target_recall=0.7, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.precision_at_recall( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), target_recall=0.7, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=1) precision, update_op = metrics.precision_at_recall( labels, predictions, target_recall=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(update_op) # Then verify idempotency. initial_precision = precision.eval() for _ in range(10): self.assertAlmostEqual(initial_precision, precision.eval(), places=5) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) precision, update_op = metrics.precision_at_recall( labels, predictions, target_recall=0.7) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1, sess.run(update_op)) self.assertEqual(1, precision.eval()) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = 1.0 - predictions label_prior = math_ops.reduce_mean(labels) precision, update_op = metrics.precision_at_recall( labels, predictions, target_recall=0.2) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(sess.run(label_prior), sess.run(update_op)) self.assertEqual(sess.run(label_prior), precision.eval()) def testSomeCorrectHighRecall(self): predictions_values = [0.1, 0.2, 0.5, 0.3, 0.0, 0.1, 0.45, 0.5, 0.8, 0.9] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) precision, update_op = metrics.precision_at_recall( labels, predictions, target_recall=0.8) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(0.8, sess.run(update_op)) self.assertAlmostEqual(0.8, precision.eval()) def testSomeCorrectLowRecall(self): predictions_values = [0.1, 0.2, 0.7, 0.3, 0.0, 0.1, 0.45, 0.5, 0.6, 0.9] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = constant_op.constant(labels_values) precision, update_op = metrics.precision_at_recall( labels, predictions, target_recall=0.4) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(2.0/3, sess.run(update_op)) self.assertAlmostEqual(2.0/3, precision.eval()) def testWeighted_multipleLabelDtypes(self): for label_dtype in (dtypes_lib.bool, dtypes_lib.int32, dtypes_lib.float32): predictions_values = [ 0.0, 0.1, 0.2, 0.3, 0.4, 0.1, 0.22, 0.25, 0.31, 0.35] labels_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] weights_values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] predictions = constant_op.constant( predictions_values, dtype=dtypes_lib.float32) labels = math_ops.cast(labels_values, dtype=label_dtype) weights = constant_op.constant(weights_values) precision, update_op = metrics.precision_at_recall( labels, predictions, target_recall=0.8, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(34.0/43, sess.run(update_op)) self.assertAlmostEqual(34.0/43, precision.eval()) class StreamingFNRThresholdsTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_false_negative_rate_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0]) _assert_metric_variables(self, ( 'false_negative_rate_at_thresholds/false_negatives:0', 'false_negative_rate_at_thresholds/true_positives:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' fnr, _ = metrics.streaming_false_negative_rate_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [fnr]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_false_negative_rate_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0], updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 3), maxval=1, dtype=dtypes_lib.float32, seed=1) labels = random_ops.random_uniform( (10, 3), maxval=2, dtype=dtypes_lib.int64, seed=2) thresholds = [0, 0.5, 1.0] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) # Run several updates. for _ in range(10): sess.run(fnr_op) # Then verify idempotency. initial_fnr = fnr.eval() for _ in range(10): self.assertAllClose(initial_fnr, fnr.eval()) def testAllCorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) thresholds = [0.5] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertEqual(0, fnr.eval()) def testSomeCorrect(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 0], shape=(1, 4)) thresholds = [0.5] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertAlmostEqual(0.5, fnr.eval()) def testAllIncorrect(self): inputs = np.random.randint(0, 2, size=(100, 1)) with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(1 - inputs, dtype=dtypes_lib.float32) thresholds = [0.5] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertAlmostEqual(1, fnr.eval()) def testWeights1d(self): with self.test_session() as sess: predictions = constant_op.constant( [[1, 0], [1, 0]], shape=(2, 2), dtype=dtypes_lib.float32) labels = constant_op.constant([[0, 1], [1, 0]], shape=(2, 2)) weights = constant_op.constant( [[0], [1]], shape=(2, 1), dtype=dtypes_lib.float32) thresholds = [0.5, 1.1] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds, weights=weights) fnr_low = fnr[0] fnr_high = fnr[1] sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertAlmostEqual(0.0, fnr_low.eval(), places=5) self.assertAlmostEqual(1.0, fnr_high.eval(), places=5) def testWeights2d(self): with self.test_session() as sess: predictions = constant_op.constant( [[1, 0], [1, 0]], shape=(2, 2), dtype=dtypes_lib.float32) labels = constant_op.constant([[0, 1], [1, 0]], shape=(2, 2)) weights = constant_op.constant( [[0, 0], [1, 1]], shape=(2, 2), dtype=dtypes_lib.float32) thresholds = [0.5, 1.1] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds, weights=weights) fnr_low = fnr[0] fnr_high = fnr[1] sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertAlmostEqual(0.0, fnr_low.eval(), places=5) self.assertAlmostEqual(1.0, fnr_high.eval(), places=5) def testExtremeThresholds(self): with self.test_session() as sess: predictions = constant_op.constant( [1, 0, 1, 0], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant([0, 1, 1, 1], shape=(1, 4)) thresholds = [-1.0, 2.0] # lower/higher than any values fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds) fnr_low = fnr[0] fnr_high = fnr[1] sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertAlmostEqual(0.0, fnr_low.eval()) self.assertAlmostEqual(1.0, fnr_high.eval()) def testZeroLabelsPredictions(self): with self.test_session() as sess: predictions = array_ops.zeros([4], dtype=dtypes_lib.float32) labels = array_ops.zeros([4]) thresholds = [0.5] fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( predictions, labels, thresholds) sess.run(variables.local_variables_initializer()) sess.run(fnr_op) self.assertAlmostEqual(0, fnr.eval(), 6) def testWithMultipleUpdates(self): num_samples = 1000 batch_size = 10 num_batches = int(num_samples / batch_size) # Create the labels and data. labels = np.random.randint(0, 2, size=(num_samples, 1)) noise = np.random.normal(0.0, scale=0.2, size=(num_samples, 1)) predictions = 0.4 + 0.2 * labels + noise predictions[predictions > 1] = 1 predictions[predictions < 0] = 0 thresholds = [0.3] fn = 0 tp = 0 for i in range(num_samples): if predictions[i] > thresholds[0]: if labels[i] == 1: tp += 1 else: if labels[i] == 1: fn += 1 epsilon = 1e-7 expected_fnr = fn / (epsilon + fn + tp) labels = labels.astype(np.float32) predictions = predictions.astype(np.float32) with self.test_session() as sess: # Reshape the data so its easy to queue up: predictions_batches = predictions.reshape((batch_size, num_batches)) labels_batches = labels.reshape((batch_size, num_batches)) # Enqueue the data: predictions_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) labels_queue = data_flow_ops.FIFOQueue( num_batches, dtypes=dtypes_lib.float32, shapes=(batch_size,)) for i in range(int(num_batches)): tf_prediction = constant_op.constant(predictions_batches[:, i]) tf_label = constant_op.constant(labels_batches[:, i]) sess.run([ predictions_queue.enqueue(tf_prediction), labels_queue.enqueue(tf_label) ]) tf_predictions = predictions_queue.dequeue() tf_labels = labels_queue.dequeue() fnr, fnr_op = metrics.streaming_false_negative_rate_at_thresholds( tf_predictions, tf_labels, thresholds) sess.run(variables.local_variables_initializer()) for _ in range(int(num_samples / batch_size)): sess.run(fnr_op) # Since this is only approximate, we can't expect a 6 digits match. self.assertAlmostEqual(expected_fnr, fnr.eval(), 2) class StreamingRecallAtKTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() self._batch_size = 4 self._num_classes = 3 self._np_predictions = np.matrix(('0.1 0.2 0.7;' '0.6 0.2 0.2;' '0.0 0.9 0.1;' '0.2 0.0 0.8')) self._np_labels = [0, 0, 0, 0] def testVars(self): metrics.streaming_recall_at_k( predictions=array_ops.ones((self._batch_size, self._num_classes)), labels=array_ops.ones((self._batch_size,), dtype=dtypes_lib.int32), k=1) _assert_metric_variables(self, ('recall_at_1/count:0', 'recall_at_1/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_recall_at_k( predictions=array_ops.ones((self._batch_size, self._num_classes)), labels=array_ops.ones((self._batch_size,), dtype=dtypes_lib.int32), k=1, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_recall_at_k( predictions=array_ops.ones((self._batch_size, self._num_classes)), labels=array_ops.ones((self._batch_size,), dtype=dtypes_lib.int32), k=1, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testSingleUpdateKIs1(self): predictions = constant_op.constant( self._np_predictions, shape=(self._batch_size, self._num_classes), dtype=dtypes_lib.float32) labels = constant_op.constant( self._np_labels, shape=(self._batch_size,), dtype=dtypes_lib.int64) recall, update_op = metrics.streaming_recall_at_k(predictions, labels, k=1) sp_recall, sp_update_op = metrics.streaming_sparse_recall_at_k( predictions, array_ops.reshape(labels, (self._batch_size, 1)), k=1) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0.25, sess.run(update_op)) self.assertEqual(0.25, recall.eval()) self.assertEqual(0.25, sess.run(sp_update_op)) self.assertEqual(0.25, sp_recall.eval()) def testSingleUpdateKIs2(self): predictions = constant_op.constant( self._np_predictions, shape=(self._batch_size, self._num_classes), dtype=dtypes_lib.float32) labels = constant_op.constant( self._np_labels, shape=(self._batch_size,), dtype=dtypes_lib.int64) recall, update_op = metrics.streaming_recall_at_k(predictions, labels, k=2) sp_recall, sp_update_op = metrics.streaming_sparse_recall_at_k( predictions, array_ops.reshape(labels, (self._batch_size, 1)), k=2) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0.5, sess.run(update_op)) self.assertEqual(0.5, recall.eval()) self.assertEqual(0.5, sess.run(sp_update_op)) self.assertEqual(0.5, sp_recall.eval()) def testSingleUpdateKIs3(self): predictions = constant_op.constant( self._np_predictions, shape=(self._batch_size, self._num_classes), dtype=dtypes_lib.float32) labels = constant_op.constant( self._np_labels, shape=(self._batch_size,), dtype=dtypes_lib.int64) recall, update_op = metrics.streaming_recall_at_k(predictions, labels, k=3) sp_recall, sp_update_op = metrics.streaming_sparse_recall_at_k( predictions, array_ops.reshape(labels, (self._batch_size, 1)), k=3) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1.0, sess.run(update_op)) self.assertEqual(1.0, recall.eval()) self.assertEqual(1.0, sess.run(sp_update_op)) self.assertEqual(1.0, sp_recall.eval()) def testSingleUpdateSomeMissingKIs2(self): predictions = constant_op.constant( self._np_predictions, shape=(self._batch_size, self._num_classes), dtype=dtypes_lib.float32) labels = constant_op.constant( self._np_labels, shape=(self._batch_size,), dtype=dtypes_lib.int64) weights = constant_op.constant( [0, 1, 0, 1], shape=(self._batch_size,), dtype=dtypes_lib.float32) recall, update_op = metrics.streaming_recall_at_k( predictions, labels, k=2, weights=weights) sp_recall, sp_update_op = metrics.streaming_sparse_recall_at_k( predictions, array_ops.reshape(labels, (self._batch_size, 1)), k=2, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1.0, sess.run(update_op)) self.assertEqual(1.0, recall.eval()) self.assertEqual(1.0, sess.run(sp_update_op)) self.assertEqual(1.0, sp_recall.eval()) class StreamingSparsePrecisionTest(test.TestCase): def _test_streaming_sparse_precision_at_k(self, predictions, labels, k, expected, class_id=None, weights=None): with ops.Graph().as_default() as g, self.session(g): if weights is not None: weights = constant_op.constant(weights, dtypes_lib.float32) metric, update = metrics.streaming_sparse_precision_at_k( predictions=constant_op.constant(predictions, dtypes_lib.float32), labels=labels, k=k, class_id=class_id, weights=weights) self.assertRaises(errors_impl.OpError, metric.eval) self.assertRaises(errors_impl.OpError, update.eval) variables.variables_initializer(variables.local_variables()).run() if math.isnan(expected): _assert_nan(self, update.eval()) _assert_nan(self, metric.eval()) else: self.assertEqual(expected, update.eval()) self.assertEqual(expected, metric.eval()) def _test_streaming_sparse_precision_at_top_k(self, top_k_predictions, labels, expected, class_id=None, weights=None): with ops.Graph().as_default() as g, self.session(g): if weights is not None: weights = constant_op.constant(weights, dtypes_lib.float32) metric, update = metrics.streaming_sparse_precision_at_top_k( top_k_predictions=constant_op.constant(top_k_predictions, dtypes_lib.int32), labels=labels, class_id=class_id, weights=weights) self.assertRaises(errors_impl.OpError, metric.eval) self.assertRaises(errors_impl.OpError, update.eval) variables.variables_initializer(variables.local_variables()).run() if math.isnan(expected): self.assertTrue(math.isnan(update.eval())) self.assertTrue(math.isnan(metric.eval())) else: self.assertEqual(expected, update.eval()) self.assertEqual(expected, metric.eval()) def _test_streaming_sparse_average_precision_at_k(self, predictions, labels, k, expected, weights=None): with ops.Graph().as_default() as g, self.session(g): if weights is not None: weights = constant_op.constant(weights, dtypes_lib.float32) predictions = constant_op.constant(predictions, dtypes_lib.float32) metric, update = metrics.streaming_sparse_average_precision_at_k( predictions, labels, k, weights=weights) self.assertRaises(errors_impl.OpError, metric.eval) self.assertRaises(errors_impl.OpError, update.eval) local_variables = variables.local_variables() variables.variables_initializer(local_variables).run() if math.isnan(expected): _assert_nan(self, update.eval()) _assert_nan(self, metric.eval()) else: self.assertAlmostEqual(expected, update.eval()) self.assertAlmostEqual(expected, metric.eval()) def _test_streaming_sparse_average_precision_at_top_k(self, top_k_predictions, labels, expected, weights=None): with ops.Graph().as_default() as g, self.session(g): if weights is not None: weights = constant_op.constant(weights, dtypes_lib.float32) metric, update = metrics.streaming_sparse_average_precision_at_top_k( top_k_predictions, labels, weights=weights) self.assertRaises(errors_impl.OpError, metric.eval) self.assertRaises(errors_impl.OpError, update.eval) local_variables = variables.local_variables() variables.variables_initializer(local_variables).run() if math.isnan(expected): _assert_nan(self, update.eval()) _assert_nan(self, metric.eval()) else: self.assertAlmostEqual(expected, update.eval()) self.assertAlmostEqual(expected, metric.eval()) def test_top_k_rank_invalid(self): with self.test_session(): top_k_predictions = [9, 4, 6, 2, 0] sp_labels = sparse_tensor.SparseTensorValue( indices=np.array([[ 0, ], [ 1, ], [ 2, ]], np.int64), values=np.array([2, 7, 8], np.int64), dense_shape=np.array([ 10, ], np.int64)) with self.assertRaises(ValueError): precision, _ = metrics.streaming_sparse_precision_at_top_k( top_k_predictions=constant_op.constant(top_k_predictions, dtypes_lib.int64), labels=sp_labels) variables.variables_initializer(variables.local_variables()).run() precision.eval() def test_average_precision(self): labels_ex1 = (0, 1, 2, 3, 4) labels = np.array([labels_ex1], dtype=np.int64) predictions_ex1 = (0.2, 0.1, 0.0, 0.4, 0.0, 0.5, 0.3) predictions = (predictions_ex1,) predictions_top_k_ex1 = (5, 3, 6, 0, 1, 2) precision_ex1 = (0.0 / 1, 1.0 / 2, 1.0 / 3, 2.0 / 4) avg_precision_ex1 = (0.0 / 1, precision_ex1[1] / 2, precision_ex1[1] / 3, (precision_ex1[1] + precision_ex1[3]) / 4) for i in xrange(4): k = i + 1 self._test_streaming_sparse_precision_at_k( predictions, labels, k, expected=precision_ex1[i]) self._test_streaming_sparse_precision_at_top_k( (predictions_top_k_ex1[:k],), labels, expected=precision_ex1[i]) self._test_streaming_sparse_average_precision_at_k( predictions, labels, k, expected=avg_precision_ex1[i]) self._test_streaming_sparse_average_precision_at_top_k( (predictions_top_k_ex1[:k],), labels, expected=avg_precision_ex1[i]) labels_ex2 = (0, 2, 4, 5, 6) labels = np.array([labels_ex2], dtype=np.int64) predictions_ex2 = (0.3, 0.5, 0.0, 0.4, 0.0, 0.1, 0.2) predictions = (predictions_ex2,) predictions_top_k_ex2 = (1, 3, 0, 6, 5) precision_ex2 = (0.0 / 1, 0.0 / 2, 1.0 / 3, 2.0 / 4) avg_precision_ex2 = (0.0 / 1, 0.0 / 2, precision_ex2[2] / 3, (precision_ex2[2] + precision_ex2[3]) / 4) for i in xrange(4): k = i + 1 self._test_streaming_sparse_precision_at_k( predictions, labels, k, expected=precision_ex2[i]) self._test_streaming_sparse_precision_at_top_k( (predictions_top_k_ex2[:k],), labels, expected=precision_ex2[i]) self._test_streaming_sparse_average_precision_at_k( predictions, labels, k, expected=avg_precision_ex2[i]) self._test_streaming_sparse_average_precision_at_top_k( (predictions_top_k_ex2[:k],), labels, expected=avg_precision_ex2[i]) labels = np.array([labels_ex1, labels_ex2], dtype=np.int64) predictions = (predictions_ex1, predictions_ex2) streaming_precision = [ (ex1 + ex2) / 2 for ex1, ex2 in zip(precision_ex1, precision_ex2) ] streaming_average_precision = [ (ex1 + ex2) / 2 for ex1, ex2 in zip(avg_precision_ex1, avg_precision_ex2) ] for i in xrange(4): k = i + 1 self._test_streaming_sparse_precision_at_k( predictions, labels, k, expected=streaming_precision[i]) predictions_top_k = (predictions_top_k_ex1[:k], predictions_top_k_ex2[:k]) self._test_streaming_sparse_precision_at_top_k( predictions_top_k, labels, expected=streaming_precision[i]) self._test_streaming_sparse_average_precision_at_k( predictions, labels, k, expected=streaming_average_precision[i]) self._test_streaming_sparse_average_precision_at_top_k( predictions_top_k, labels, expected=streaming_average_precision[i]) weights = (0.3, 0.6) streaming_average_precision = [ (weights[0] * ex1 + weights[1] * ex2) / (weights[0] + weights[1]) for ex1, ex2 in zip(avg_precision_ex1, avg_precision_ex2) ] for i in xrange(4): k = i + 1 self._test_streaming_sparse_average_precision_at_k( predictions, labels, k, expected=streaming_average_precision[i], weights=weights) self._test_streaming_sparse_average_precision_at_top_k( (predictions_top_k_ex1[:k], predictions_top_k_ex2[:k]), labels, expected=streaming_average_precision[i], weights=weights) def test_average_precision_some_labels_out_of_range(self): labels_ex1 = (-1, 0, 1, 2, 3, 4, 7) labels = np.array([labels_ex1], dtype=np.int64) predictions_ex1 = (0.2, 0.1, 0.0, 0.4, 0.0, 0.5, 0.3) predictions = (predictions_ex1,) predictions_top_k_ex1 = (5, 3, 6, 0, 1, 2) precision_ex1 = (0.0 / 1, 1.0 / 2, 1.0 / 3, 2.0 / 4) avg_precision_ex1 = (0.0 / 1, precision_ex1[1] / 2, precision_ex1[1] / 3, (precision_ex1[1] + precision_ex1[3]) / 4) for i in xrange(4): k = i + 1 self._test_streaming_sparse_precision_at_k( predictions, labels, k, expected=precision_ex1[i]) self._test_streaming_sparse_precision_at_top_k( (predictions_top_k_ex1[:k],), labels, expected=precision_ex1[i]) self._test_streaming_sparse_average_precision_at_k( predictions, labels, k, expected=avg_precision_ex1[i]) self._test_streaming_sparse_average_precision_at_top_k( (predictions_top_k_ex1[:k],), labels, expected=avg_precision_ex1[i]) def test_average_precision_at_top_k_static_shape_check(self): predictions_top_k = array_ops.placeholder( shape=(2, None), dtype=dtypes_lib.int64) labels = np.array(((1,), (2,)), dtype=np.int64) with self.assertRaises(ValueError): metric_ops.streaming_sparse_average_precision_at_top_k( predictions_top_k, labels) predictions_top_k = (2, 1) with self.assertRaises(ValueError): metric_ops.streaming_sparse_average_precision_at_top_k( predictions_top_k, labels) predictions_top_k = ((2,), (1,)) metric_ops.streaming_sparse_average_precision_at_top_k( predictions_top_k, labels) def test_one_label_at_k1_nan(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] top_k_predictions = [[3], [3]] sparse_labels = _binary_2d_label_to_sparse_value([[0, 0, 0, 1], [0, 0, 1, 0]]) dense_labels = np.array([[3], [2]], dtype=np.int64) for labels in (sparse_labels, dense_labels): for class_id in (-1, 0, 1, 2, 4): self._test_streaming_sparse_precision_at_k( predictions, labels, k=1, expected=NAN, class_id=class_id) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, class_id=class_id) def test_one_label_at_k1(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] top_k_predictions = [[3], [3]] sparse_labels = _binary_2d_label_to_sparse_value([[0, 0, 0, 1], [0, 0, 1, 0]]) dense_labels = np.array([[3], [2]], dtype=np.int64) for labels in (sparse_labels, dense_labels): self._test_streaming_sparse_precision_at_k( predictions, labels, k=1, expected=1.0 / 2, class_id=3) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=1.0 / 2, class_id=3) self._test_streaming_sparse_precision_at_k( predictions, labels, k=1, expected=1.0 / 2) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=1.0 / 2) def test_three_labels_at_k5_no_predictions(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sparse_labels = _binary_2d_label_to_sparse_value( [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]]) dense_labels = np.array([[2, 7, 8], [1, 2, 5]], dtype=np.int64) for labels in (sparse_labels, dense_labels): for class_id in (-1, 1, 3, 8, 10): self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, class_id=class_id) def test_three_labels_at_k5_no_labels(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sparse_labels = _binary_2d_label_to_sparse_value( [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]]) dense_labels = np.array([[2, 7, 8], [1, 2, 5]], dtype=np.int64) for labels in (sparse_labels, dense_labels): for class_id in (0, 4, 6, 9): self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=0.0, class_id=class_id) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=0.0, class_id=class_id) def test_three_labels_at_k5(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sparse_labels = _binary_2d_label_to_sparse_value( [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]]) dense_labels = np.array([[2, 7, 8], [1, 2, 5]], dtype=np.int64) for labels in (sparse_labels, dense_labels): self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=2.0 / 2, class_id=2) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=2.0 / 2, class_id=2) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=1.0 / 1, class_id=5) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=1.0 / 1, class_id=5) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=0.0 / 1, class_id=7) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=0.0 / 1, class_id=7) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=3.0 / 10) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=3.0 / 10) def test_three_labels_at_k5_some_out_of_range(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sp_labels = sparse_tensor.SparseTensorValue( indices=[[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3]], values=np.array([2, 7, -1, 8, 1, 2, 5, 10], np.int64), dense_shape=[2, 4]) self._test_streaming_sparse_precision_at_k( predictions, sp_labels, k=5, expected=2.0 / 2, class_id=2) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, sp_labels, expected=2.0 / 2, class_id=2) self._test_streaming_sparse_precision_at_k( predictions, sp_labels, k=5, expected=1.0 / 1, class_id=5) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, sp_labels, expected=1.0 / 1, class_id=5) self._test_streaming_sparse_precision_at_k( predictions, sp_labels, k=5, expected=0.0 / 1, class_id=7) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, sp_labels, expected=0.0 / 1, class_id=7) self._test_streaming_sparse_precision_at_k( predictions, sp_labels, k=5, expected=3.0 / 10) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, sp_labels, expected=3.0 / 10) def test_3d_nan(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) for class_id in (-1, 1, 3, 8, 10): self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, class_id=class_id) def test_3d_no_labels(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) for class_id in (0, 4, 6, 9): self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=0.0, class_id=class_id) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=0.0, class_id=class_id) def test_3d(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=4.0 / 4, class_id=2) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=4.0 / 4, class_id=2) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=2.0 / 2, class_id=5) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=2.0 / 2, class_id=5) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=1.0 / 2, class_id=7) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=1.0 / 2, class_id=7) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=7.0 / 20) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=7.0 / 20) def test_3d_ignore_all(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) for class_id in xrange(10): self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id, weights=[[0], [0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, class_id=class_id, weights=[[0], [0]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id, weights=[[0, 0], [0, 0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, class_id=class_id, weights=[[0, 0], [0, 0]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, weights=[[0], [0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, weights=[[0], [0]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, weights=[[0, 0], [0, 0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, weights=[[0, 0], [0, 0]]) def test_3d_ignore_some(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=2.0 / 2.0, class_id=2, weights=[[1], [0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=2.0 / 2.0, class_id=2, weights=[[1], [0]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=2.0 / 2.0, class_id=2, weights=[[0], [1]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=2.0 / 2.0, class_id=2, weights=[[0], [1]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=0.0 / 1.0, class_id=7, weights=[[1], [0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=0.0 / 1.0, class_id=7, weights=[[1], [0]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=1.0 / 1.0, class_id=7, weights=[[0], [1]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=1.0 / 1.0, class_id=7, weights=[[0], [1]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=NAN, class_id=7, weights=[[1, 0], [0, 1]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=NAN, class_id=7, weights=[[1, 0], [0, 1]]) self._test_streaming_sparse_precision_at_k( predictions, labels, k=5, expected=1.0 / 2.0, class_id=7, weights=[[0, 1], [1, 0]]) self._test_streaming_sparse_precision_at_top_k( top_k_predictions, labels, expected=1.0 / 2.0, class_id=7, weights=[[0, 1], [1, 0]]) def test_sparse_tensor_value(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] labels = [[0, 0, 0, 1], [0, 0, 1, 0]] expected_precision = 0.5 with self.test_session(): _, precision = metrics.streaming_sparse_precision_at_k( predictions=constant_op.constant(predictions, dtypes_lib.float32), labels=_binary_2d_label_to_sparse_value(labels), k=1) variables.variables_initializer(variables.local_variables()).run() self.assertEqual(expected_precision, precision.eval()) class StreamingSparseRecallTest(test.TestCase): def _test_streaming_sparse_recall_at_k(self, predictions, labels, k, expected, class_id=None, weights=None): with ops.Graph().as_default() as g, self.session(g): if weights is not None: weights = constant_op.constant(weights, dtypes_lib.float32) metric, update = metrics.streaming_sparse_recall_at_k( predictions=constant_op.constant(predictions, dtypes_lib.float32), labels=labels, k=k, class_id=class_id, weights=weights) self.assertRaises(errors_impl.OpError, metric.eval) self.assertRaises(errors_impl.OpError, update.eval) variables.variables_initializer(variables.local_variables()).run() if math.isnan(expected): _assert_nan(self, update.eval()) _assert_nan(self, metric.eval()) else: self.assertEqual(expected, update.eval()) self.assertEqual(expected, metric.eval()) def _test_sparse_recall_at_top_k(self, labels, top_k_predictions, expected, class_id=None, weights=None): with ops.Graph().as_default() as g, self.session(g): if weights is not None: weights = constant_op.constant(weights, dtypes_lib.float32) metric, update = metric_ops.sparse_recall_at_top_k( labels=labels, top_k_predictions=constant_op.constant(top_k_predictions, dtypes_lib.int32), class_id=class_id, weights=weights) self.assertRaises(errors_impl.OpError, metric.eval) self.assertRaises(errors_impl.OpError, update.eval) variables.variables_initializer(variables.local_variables()).run() if math.isnan(expected): self.assertTrue(math.isnan(update.eval())) self.assertTrue(math.isnan(metric.eval())) else: self.assertEqual(expected, update.eval()) self.assertEqual(expected, metric.eval()) def test_one_label_at_k1_nan(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] top_k_predictions = [[3], [3]] sparse_labels = _binary_2d_label_to_sparse_value([[0, 0, 0, 1], [0, 0, 1, 0]]) dense_labels = np.array([[3], [2]], dtype=np.int64) for labels in (sparse_labels, dense_labels): for class_id in (-1, 0, 1, 4): self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=NAN, class_id=class_id) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=class_id) def test_one_label_at_k1_no_predictions(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] top_k_predictions = [[3], [3]] sparse_labels = _binary_2d_label_to_sparse_value([[0, 0, 0, 1], [0, 0, 1, 0]]) dense_labels = np.array([[3], [2]], dtype=np.int64) for labels in (sparse_labels, dense_labels): self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=0.0, class_id=2) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.0, class_id=2) def test_one_label_at_k1(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] top_k_predictions = [[3], [3]] sparse_labels = _binary_2d_label_to_sparse_value([[0, 0, 0, 1], [0, 0, 1, 0]]) dense_labels = np.array([[3], [2]], dtype=np.int64) for labels in (sparse_labels, dense_labels): self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 1, class_id=3) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, class_id=3) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 2) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 2) def _test_one_label_at_k1_weighted(self, labels): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] top_k_predictions = [[3], [3]] self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=NAN, class_id=3, weights=(0.0,)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=3, weights=(0.0,)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 1, class_id=3, weights=(1.0,)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, class_id=3, weights=(1.0,)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 1, class_id=3, weights=(2.0,)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, class_id=3, weights=(2.0,)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=NAN, class_id=3, weights=(0.0, 0.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=3, weights=(0.0, 0.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=NAN, class_id=3, weights=(0.0, 1.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=3, weights=(0.0, 1.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 1, class_id=3, weights=(1.0, 0.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, class_id=3, weights=(1.0, 0.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 1, class_id=3, weights=(1.0, 1.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, class_id=3, weights=(1.0, 1.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=2.0 / 2, class_id=3, weights=(2.0, 3.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=2.0 / 2, class_id=3, weights=(2.0, 3.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=3.0 / 3, class_id=3, weights=(3.0, 2.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=3.0 / 3, class_id=3, weights=(3.0, 2.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=0.3 / 0.3, class_id=3, weights=(0.3, 0.6)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.3 / 0.3, class_id=3, weights=(0.3, 0.6)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=0.6 / 0.6, class_id=3, weights=(0.6, 0.3)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.6 / 0.6, class_id=3, weights=(0.6, 0.3)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=NAN, weights=(0.0,)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, weights=(0.0,)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 2, weights=(1.0,)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 2, weights=(1.0,)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 2, weights=(2.0,)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 2, weights=(2.0,)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 1, weights=(1.0, 0.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, weights=(1.0, 0.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=0.0 / 1, weights=(0.0, 1.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.0 / 1, weights=(0.0, 1.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=1.0 / 2, weights=(1.0, 1.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 2, weights=(1.0, 1.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=2.0 / 5, weights=(2.0, 3.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=2.0 / 5, weights=(2.0, 3.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=3.0 / 5, weights=(3.0, 2.0)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=3.0 / 5, weights=(3.0, 2.0)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=0.3 / 0.9, weights=(0.3, 0.6)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.3 / 0.9, weights=(0.3, 0.6)) self._test_streaming_sparse_recall_at_k( predictions, labels, k=1, expected=0.6 / 0.9, weights=(0.6, 0.3)) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.6 / 0.9, weights=(0.6, 0.3)) def test_one_label_at_k1_weighted_sparse_labels(self): sparse_labels = _binary_2d_label_to_sparse_value([[0, 0, 0, 1], [0, 0, 1, 0]]) self._test_one_label_at_k1_weighted(sparse_labels) def test_one_label_at_k1_weighted_dense_labels(self): dense_labels = np.array([[3], [2]], dtype=np.int64) self._test_one_label_at_k1_weighted(dense_labels) def test_three_labels_at_k5_nan(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sparse_labels = _binary_2d_label_to_sparse_value( [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]]) dense_labels = np.array([[2, 7, 8], [1, 2, 5]], dtype=np.int64) for labels in (sparse_labels, dense_labels): for class_id in (0, 3, 4, 6, 9, 10): self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=class_id) def test_three_labels_at_k5_no_predictions(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sparse_labels = _binary_2d_label_to_sparse_value( [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]]) dense_labels = np.array([[2, 7, 8], [1, 2, 5]], dtype=np.int64) for labels in (sparse_labels, dense_labels): self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=0.0 / 1, class_id=8) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.0 / 1, class_id=8) def test_three_labels_at_k5(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sparse_labels = _binary_2d_label_to_sparse_value( [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]]) dense_labels = np.array([[2, 7, 8], [1, 2, 5]], dtype=np.int64) for labels in (sparse_labels, dense_labels): self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=2.0 / 2, class_id=2) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=2.0 / 2, class_id=2) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=1.0 / 1, class_id=5) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1, class_id=5) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=0.0 / 1, class_id=7) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.0 / 1, class_id=7) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=3.0 / 6) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=3.0 / 6) def test_three_labels_at_k5_some_out_of_range(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] top_k_predictions = [ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ] sp_labels = sparse_tensor.SparseTensorValue( indices=[[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3]], values=np.array([2, 7, -1, 8, 1, 2, 5, 10], np.int64), dense_shape=[2, 4]) self._test_streaming_sparse_recall_at_k( predictions=predictions, labels=sp_labels, k=5, expected=2.0 / 2, class_id=2) self._test_sparse_recall_at_top_k( sp_labels, top_k_predictions, expected=2.0 / 2, class_id=2) self._test_streaming_sparse_recall_at_k( predictions=predictions, labels=sp_labels, k=5, expected=1.0 / 1, class_id=5) self._test_sparse_recall_at_top_k( sp_labels, top_k_predictions, expected=1.0 / 1, class_id=5) self._test_streaming_sparse_recall_at_k( predictions=predictions, labels=sp_labels, k=5, expected=0.0 / 1, class_id=7) self._test_sparse_recall_at_top_k( sp_labels, top_k_predictions, expected=0.0 / 1, class_id=7) self._test_streaming_sparse_recall_at_k( predictions=predictions, labels=sp_labels, k=5, expected=3.0 / 8) self._test_sparse_recall_at_top_k( sp_labels, top_k_predictions, expected=3.0 / 8) def test_3d_nan(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] sparse_labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 1, 1, 0]]]) dense_labels = np.array( [[[2, 7, 8], [1, 2, 5]], [ [1, 2, 5], [2, 7, 8], ]], dtype=np.int64) for labels in (sparse_labels, dense_labels): for class_id in (0, 3, 4, 6, 9, 10): self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=class_id) def test_3d_no_predictions(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] sparse_labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 1, 1, 0]]]) dense_labels = np.array( [[[2, 7, 8], [1, 2, 5]], [ [1, 2, 5], [2, 7, 8], ]], dtype=np.int64) for labels in (sparse_labels, dense_labels): for class_id in (1, 8): self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=0.0, class_id=class_id) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.0, class_id=class_id) def test_3d(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=4.0 / 4, class_id=2) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=4.0 / 4, class_id=2) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=2.0 / 2, class_id=5) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=2.0 / 2, class_id=5) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=1.0 / 2, class_id=7) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 2, class_id=7) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=7.0 / 12) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=7.0 / 12) def test_3d_ignore_all(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) for class_id in xrange(10): self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id, weights=[[0], [0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=class_id, weights=[[0], [0]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, class_id=class_id, weights=[[0, 0], [0, 0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=class_id, weights=[[0, 0], [0, 0]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, weights=[[0], [0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, weights=[[0], [0]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, weights=[[0, 0], [0, 0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, weights=[[0, 0], [0, 0]]) def test_3d_ignore_some(self): predictions = [[[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]], [[0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6], [0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9]]] top_k_predictions = [[ [9, 4, 6, 2, 0], [5, 7, 2, 9, 6], ], [ [5, 7, 2, 9, 6], [9, 4, 6, 2, 0], ]] labels = _binary_3d_label_to_sparse_value( [[[0, 0, 1, 0, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0, 0]], [[0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=2.0 / 2.0, class_id=2, weights=[[1], [0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=2.0 / 2.0, class_id=2, weights=[[1], [0]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=2.0 / 2.0, class_id=2, weights=[[0], [1]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=2.0 / 2.0, class_id=2, weights=[[0], [1]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=1.0 / 1.0, class_id=7, weights=[[0], [1]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 1.0, class_id=7, weights=[[0], [1]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=0.0 / 1.0, class_id=7, weights=[[1], [0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=0.0 / 1.0, class_id=7, weights=[[1], [0]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=1.0 / 2.0, class_id=7, weights=[[1, 0], [1, 0]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=1.0 / 2.0, class_id=7, weights=[[1, 0], [1, 0]]) self._test_streaming_sparse_recall_at_k( predictions, labels, k=5, expected=NAN, class_id=7, weights=[[0, 1], [0, 1]]) self._test_sparse_recall_at_top_k( labels, top_k_predictions, expected=NAN, class_id=7, weights=[[0, 1], [0, 1]]) def test_sparse_tensor_value(self): predictions = [[0.1, 0.3, 0.2, 0.4], [0.1, 0.2, 0.3, 0.4]] labels = [[0, 0, 1, 0], [0, 0, 0, 1]] expected_recall = 0.5 with self.test_session(): _, recall = metrics.streaming_sparse_recall_at_k( predictions=constant_op.constant(predictions, dtypes_lib.float32), labels=_binary_2d_label_to_sparse_value(labels), k=1) variables.variables_initializer(variables.local_variables()).run() self.assertEqual(expected_recall, recall.eval()) class StreamingMeanAbsoluteErrorTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_mean_absolute_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables( self, ('mean_absolute_error/count:0', 'mean_absolute_error/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_mean_absolute_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean_absolute_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_normal((10, 3), seed=1) labels = random_ops.random_normal((10, 3), seed=2) error, update_op = metrics.streaming_mean_absolute_error( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_error = error.eval() for _ in range(10): self.assertEqual(initial_error, error.eval()) def testSingleUpdateWithErrorAndWeights(self): predictions = constant_op.constant( [2, 4, 6, 8], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2, 3], shape=(1, 4), dtype=dtypes_lib.float32) weights = constant_op.constant([0, 1, 0, 1], shape=(1, 4)) error, update_op = metrics.streaming_mean_absolute_error( predictions, labels, weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(3, sess.run(update_op)) self.assertEqual(3, error.eval()) class StreamingMeanRelativeErrorTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_mean_relative_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), normalizer=array_ops.ones((10, 1))) _assert_metric_variables( self, ('mean_relative_error/count:0', 'mean_relative_error/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_mean_relative_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), normalizer=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean_relative_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), normalizer=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_normal((10, 3), seed=1) labels = random_ops.random_normal((10, 3), seed=2) normalizer = random_ops.random_normal((10, 3), seed=3) error, update_op = metrics.streaming_mean_relative_error( predictions, labels, normalizer) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_error = error.eval() for _ in range(10): self.assertEqual(initial_error, error.eval()) def testSingleUpdateNormalizedByLabels(self): np_predictions = np.asarray([2, 4, 6, 8], dtype=np.float32) np_labels = np.asarray([1, 3, 2, 3], dtype=np.float32) expected_error = np.mean( np.divide(np.absolute(np_predictions - np_labels), np_labels)) predictions = constant_op.constant( np_predictions, shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant(np_labels, shape=(1, 4)) error, update_op = metrics.streaming_mean_relative_error( predictions, labels, normalizer=labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(expected_error, sess.run(update_op)) self.assertEqual(expected_error, error.eval()) def testSingleUpdateNormalizedByZeros(self): np_predictions = np.asarray([2, 4, 6, 8], dtype=np.float32) predictions = constant_op.constant( np_predictions, shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2, 3], shape=(1, 4), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_relative_error( predictions, labels, normalizer=array_ops.zeros_like(labels)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0.0, sess.run(update_op)) self.assertEqual(0.0, error.eval()) class StreamingMeanSquaredErrorTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables( self, ('mean_squared_error/count:0', 'mean_squared_error/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_normal((10, 3), seed=1) labels = random_ops.random_normal((10, 3), seed=2) error, update_op = metrics.streaming_mean_squared_error(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_error = error.eval() for _ in range(10): self.assertEqual(initial_error, error.eval()) def testSingleUpdateZeroError(self): predictions = array_ops.zeros((1, 3), dtype=dtypes_lib.float32) labels = array_ops.zeros((1, 3), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_squared_error(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, sess.run(update_op)) self.assertEqual(0, error.eval()) def testSingleUpdateWithError(self): predictions = constant_op.constant( [2, 4, 6], shape=(1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2], shape=(1, 3), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_squared_error(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(6, sess.run(update_op)) self.assertEqual(6, error.eval()) def testSingleUpdateWithErrorAndWeights(self): predictions = constant_op.constant( [2, 4, 6, 8], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2, 3], shape=(1, 4), dtype=dtypes_lib.float32) weights = constant_op.constant([0, 1, 0, 1], shape=(1, 4)) error, update_op = metrics.streaming_mean_squared_error( predictions, labels, weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(13, sess.run(update_op)) self.assertEqual(13, error.eval()) def testMultipleBatchesOfSizeOne(self): with self.test_session() as sess: preds_queue = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, preds_queue, [10, 8, 6]) _enqueue_vector(sess, preds_queue, [-4, 3, -1]) predictions = preds_queue.dequeue() labels_queue = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, labels_queue, [1, 3, 2]) _enqueue_vector(sess, labels_queue, [2, 4, 6]) labels = labels_queue.dequeue() error, update_op = metrics.streaming_mean_squared_error( predictions, labels) sess.run(variables.local_variables_initializer()) sess.run(update_op) self.assertAlmostEqual(208.0 / 6, sess.run(update_op), 5) self.assertAlmostEqual(208.0 / 6, error.eval(), 5) def testMetricsComputedConcurrently(self): with self.test_session() as sess: preds_queue0 = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, preds_queue0, [10, 8, 6]) _enqueue_vector(sess, preds_queue0, [-4, 3, -1]) predictions0 = preds_queue0.dequeue() preds_queue1 = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, preds_queue1, [0, 1, 1]) _enqueue_vector(sess, preds_queue1, [1, 1, 0]) predictions1 = preds_queue1.dequeue() labels_queue0 = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, labels_queue0, [1, 3, 2]) _enqueue_vector(sess, labels_queue0, [2, 4, 6]) labels0 = labels_queue0.dequeue() labels_queue1 = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, labels_queue1, [-5, -3, -1]) _enqueue_vector(sess, labels_queue1, [5, 4, 3]) labels1 = labels_queue1.dequeue() mse0, update_op0 = metrics.streaming_mean_squared_error( predictions0, labels0, name='msd0') mse1, update_op1 = metrics.streaming_mean_squared_error( predictions1, labels1, name='msd1') sess.run(variables.local_variables_initializer()) sess.run([update_op0, update_op1]) sess.run([update_op0, update_op1]) mse0, mse1 = sess.run([mse0, mse1]) self.assertAlmostEqual(208.0 / 6, mse0, 5) self.assertAlmostEqual(79.0 / 6, mse1, 5) def testMultipleMetricsOnMultipleBatchesOfSizeOne(self): with self.test_session() as sess: preds_queue = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, preds_queue, [10, 8, 6]) _enqueue_vector(sess, preds_queue, [-4, 3, -1]) predictions = preds_queue.dequeue() labels_queue = data_flow_ops.FIFOQueue( 2, dtypes=dtypes_lib.float32, shapes=(1, 3)) _enqueue_vector(sess, labels_queue, [1, 3, 2]) _enqueue_vector(sess, labels_queue, [2, 4, 6]) labels = labels_queue.dequeue() mae, ma_update_op = metrics.streaming_mean_absolute_error( predictions, labels) mse, ms_update_op = metrics.streaming_mean_squared_error( predictions, labels) sess.run(variables.local_variables_initializer()) sess.run([ma_update_op, ms_update_op]) sess.run([ma_update_op, ms_update_op]) self.assertAlmostEqual(32.0 / 6, mae.eval(), 5) self.assertAlmostEqual(208.0 / 6, mse.eval(), 5) class StreamingRootMeanSquaredErrorTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_root_mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables( self, ('root_mean_squared_error/count:0', 'root_mean_squared_error/total:0')) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_root_mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_root_mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_normal((10, 3), seed=1) labels = random_ops.random_normal((10, 3), seed=2) error, update_op = metrics.streaming_root_mean_squared_error( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_error = error.eval() for _ in range(10): self.assertEqual(initial_error, error.eval()) def testSingleUpdateZeroError(self): with self.test_session() as sess: predictions = constant_op.constant( 0.0, shape=(1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant(0.0, shape=(1, 3), dtype=dtypes_lib.float32) rmse, update_op = metrics.streaming_root_mean_squared_error( predictions, labels) sess.run(variables.local_variables_initializer()) self.assertEqual(0, sess.run(update_op)) self.assertEqual(0, rmse.eval()) def testSingleUpdateWithError(self): with self.test_session() as sess: predictions = constant_op.constant( [2, 4, 6], shape=(1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2], shape=(1, 3), dtype=dtypes_lib.float32) rmse, update_op = metrics.streaming_root_mean_squared_error( predictions, labels) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(math.sqrt(6), update_op.eval(), 5) self.assertAlmostEqual(math.sqrt(6), rmse.eval(), 5) def testSingleUpdateWithErrorAndWeights(self): with self.test_session() as sess: predictions = constant_op.constant( [2, 4, 6, 8], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2, 3], shape=(1, 4), dtype=dtypes_lib.float32) weights = constant_op.constant([0, 1, 0, 1], shape=(1, 4)) rmse, update_op = metrics.streaming_root_mean_squared_error( predictions, labels, weights) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(math.sqrt(13), sess.run(update_op)) self.assertAlmostEqual(math.sqrt(13), rmse.eval(), 5) class StreamingCovarianceTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_covariance( predictions=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), labels=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10])) _assert_metric_variables(self, ( 'covariance/comoment:0', 'covariance/count:0', 'covariance/mean_label:0', 'covariance/mean_prediction:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' cov, _ = metrics.streaming_covariance( predictions=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), labels=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [cov]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_covariance( predictions=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), labels=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): labels = random_ops.random_normal((10, 3), seed=2) predictions = labels * 0.5 + random_ops.random_normal((10, 3), seed=1) * 0.5 cov, update_op = metrics.streaming_covariance(predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_cov = cov.eval() for _ in range(10): self.assertEqual(initial_cov, cov.eval()) def testSingleUpdateIdentical(self): with self.test_session() as sess: predictions = math_ops.to_float(math_ops.range(10)) labels = math_ops.to_float(math_ops.range(10)) cov, update_op = metrics.streaming_covariance(predictions, labels) expected_cov = np.cov(np.arange(10), np.arange(10))[0, 1] sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expected_cov, sess.run(update_op), 5) self.assertAlmostEqual(expected_cov, cov.eval(), 5) def testSingleUpdateNonIdentical(self): with self.test_session() as sess: predictions = constant_op.constant( [2, 4, 6], shape=(1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2], shape=(1, 3), dtype=dtypes_lib.float32) cov, update_op = metrics.streaming_covariance(predictions, labels) expected_cov = np.cov([2, 4, 6], [1, 3, 2])[0, 1] sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expected_cov, update_op.eval()) self.assertAlmostEqual(expected_cov, cov.eval()) def testSingleUpdateWithErrorAndWeights(self): with self.test_session() as sess: predictions = constant_op.constant( [2, 4, 6, 8], shape=(1, 4), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2, 7], shape=(1, 4), dtype=dtypes_lib.float32) weights = constant_op.constant( [0, 1, 3, 1], shape=(1, 4), dtype=dtypes_lib.float32) cov, update_op = metrics.streaming_covariance( predictions, labels, weights=weights) expected_cov = np.cov( [2, 4, 6, 8], [1, 3, 2, 7], fweights=[0, 1, 3, 1])[0, 1] sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expected_cov, sess.run(update_op)) self.assertAlmostEqual(expected_cov, cov.eval()) def testMultiUpdateWithErrorNoWeights(self): with self.test_session() as sess: np.random.seed(123) n = 100 predictions = np.random.randn(n) labels = 0.5 * predictions + np.random.randn(n) stride = 10 predictions_t = array_ops.placeholder(dtypes_lib.float32, [stride]) labels_t = array_ops.placeholder(dtypes_lib.float32, [stride]) cov, update_op = metrics.streaming_covariance(predictions_t, labels_t) sess.run(variables.local_variables_initializer()) prev_expected_cov = NAN for i in range(n // stride): feed_dict = { predictions_t: predictions[stride * i:stride * (i + 1)], labels_t: labels[stride * i:stride * (i + 1)] } self.assertEqual( np.isnan(prev_expected_cov), np.isnan(sess.run(cov, feed_dict=feed_dict))) if not np.isnan(prev_expected_cov): self.assertAlmostEqual(prev_expected_cov, sess.run(cov, feed_dict=feed_dict), 5) expected_cov = np.cov(predictions[:stride * (i + 1)], labels[:stride * (i + 1)])[0, 1] self.assertAlmostEqual(expected_cov, sess.run(update_op, feed_dict=feed_dict), 5) self.assertAlmostEqual(expected_cov, sess.run(cov, feed_dict=feed_dict), 5) prev_expected_cov = expected_cov def testMultiUpdateWithErrorAndWeights(self): with self.test_session() as sess: np.random.seed(123) n = 100 predictions = np.random.randn(n) labels = 0.5 * predictions + np.random.randn(n) weights = np.tile(np.arange(n // 10), n // 10) np.random.shuffle(weights) stride = 10 predictions_t = array_ops.placeholder(dtypes_lib.float32, [stride]) labels_t = array_ops.placeholder(dtypes_lib.float32, [stride]) weights_t = array_ops.placeholder(dtypes_lib.float32, [stride]) cov, update_op = metrics.streaming_covariance( predictions_t, labels_t, weights=weights_t) sess.run(variables.local_variables_initializer()) prev_expected_cov = NAN for i in range(n // stride): feed_dict = { predictions_t: predictions[stride * i:stride * (i + 1)], labels_t: labels[stride * i:stride * (i + 1)], weights_t: weights[stride * i:stride * (i + 1)] } self.assertEqual( np.isnan(prev_expected_cov), np.isnan(sess.run(cov, feed_dict=feed_dict))) if not np.isnan(prev_expected_cov): self.assertAlmostEqual(prev_expected_cov, sess.run(cov, feed_dict=feed_dict), 5) expected_cov = np.cov( predictions[:stride * (i + 1)], labels[:stride * (i + 1)], fweights=weights[:stride * (i + 1)])[0, 1] self.assertAlmostEqual(expected_cov, sess.run(update_op, feed_dict=feed_dict), 5) self.assertAlmostEqual(expected_cov, sess.run(cov, feed_dict=feed_dict), 5) prev_expected_cov = expected_cov class StreamingPearsonRTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_pearson_correlation( predictions=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), labels=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10])) _assert_metric_variables(self, ( 'pearson_r/covariance/comoment:0', 'pearson_r/covariance/count:0', 'pearson_r/covariance/mean_label:0', 'pearson_r/covariance/mean_prediction:0', 'pearson_r/variance_labels/count:0', 'pearson_r/variance_labels/comoment:0', 'pearson_r/variance_labels/mean_label:0', 'pearson_r/variance_labels/mean_prediction:0', 'pearson_r/variance_predictions/comoment:0', 'pearson_r/variance_predictions/count:0', 'pearson_r/variance_predictions/mean_label:0', 'pearson_r/variance_predictions/mean_prediction:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' pearson_r, _ = metrics.streaming_pearson_correlation( predictions=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), labels=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [pearson_r]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_pearson_correlation( predictions=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), labels=math_ops.to_float(math_ops.range(10)) + array_ops.ones([10, 10]), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): labels = random_ops.random_normal((10, 3), seed=2) predictions = labels * 0.5 + random_ops.random_normal((10, 3), seed=1) * 0.5 pearson_r, update_op = metrics.streaming_pearson_correlation( predictions, labels) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_r = pearson_r.eval() for _ in range(10): self.assertEqual(initial_r, pearson_r.eval()) def testSingleUpdateIdentical(self): with self.test_session() as sess: predictions = math_ops.to_float(math_ops.range(10)) labels = math_ops.to_float(math_ops.range(10)) pearson_r, update_op = metrics.streaming_pearson_correlation( predictions, labels) expected_r = np.corrcoef(np.arange(10), np.arange(10))[0, 1] sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expected_r, sess.run(update_op), 5) self.assertAlmostEqual(expected_r, pearson_r.eval(), 5) def testSingleUpdateNonIdentical(self): with self.test_session() as sess: predictions = constant_op.constant( [2, 4, 6], shape=(1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( [1, 3, 2], shape=(1, 3), dtype=dtypes_lib.float32) pearson_r, update_op = metrics.streaming_pearson_correlation( predictions, labels) expected_r = np.corrcoef([2, 4, 6], [1, 3, 2])[0, 1] sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expected_r, update_op.eval()) self.assertAlmostEqual(expected_r, pearson_r.eval()) def testSingleUpdateWithErrorAndWeights(self): with self.test_session() as sess: predictions = np.array([2, 4, 6, 8]) labels = np.array([1, 3, 2, 7]) weights = np.array([0, 1, 3, 1]) predictions_t = constant_op.constant( predictions, shape=(1, 4), dtype=dtypes_lib.float32) labels_t = constant_op.constant( labels, shape=(1, 4), dtype=dtypes_lib.float32) weights_t = constant_op.constant( weights, shape=(1, 4), dtype=dtypes_lib.float32) pearson_r, update_op = metrics.streaming_pearson_correlation( predictions_t, labels_t, weights=weights_t) cmat = np.cov(predictions, labels, fweights=weights) expected_r = cmat[0, 1] / np.sqrt(cmat[0, 0] * cmat[1, 1]) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expected_r, sess.run(update_op)) self.assertAlmostEqual(expected_r, pearson_r.eval()) def testMultiUpdateWithErrorNoWeights(self): with self.test_session() as sess: np.random.seed(123) n = 100 predictions = np.random.randn(n) labels = 0.5 * predictions + np.random.randn(n) stride = 10 predictions_t = array_ops.placeholder(dtypes_lib.float32, [stride]) labels_t = array_ops.placeholder(dtypes_lib.float32, [stride]) pearson_r, update_op = metrics.streaming_pearson_correlation( predictions_t, labels_t) sess.run(variables.local_variables_initializer()) prev_expected_r = NAN for i in range(n // stride): feed_dict = { predictions_t: predictions[stride * i:stride * (i + 1)], labels_t: labels[stride * i:stride * (i + 1)] } self.assertEqual( np.isnan(prev_expected_r), np.isnan(sess.run(pearson_r, feed_dict=feed_dict))) if not np.isnan(prev_expected_r): self.assertAlmostEqual(prev_expected_r, sess.run(pearson_r, feed_dict=feed_dict), 5) expected_r = np.corrcoef(predictions[:stride * (i + 1)], labels[:stride * (i + 1)])[0, 1] self.assertAlmostEqual(expected_r, sess.run(update_op, feed_dict=feed_dict), 5) self.assertAlmostEqual(expected_r, sess.run(pearson_r, feed_dict=feed_dict), 5) prev_expected_r = expected_r def testMultiUpdateWithErrorAndWeights(self): with self.test_session() as sess: np.random.seed(123) n = 100 predictions = np.random.randn(n) labels = 0.5 * predictions + np.random.randn(n) weights = np.tile(np.arange(n // 10), n // 10) np.random.shuffle(weights) stride = 10 predictions_t = array_ops.placeholder(dtypes_lib.float32, [stride]) labels_t = array_ops.placeholder(dtypes_lib.float32, [stride]) weights_t = array_ops.placeholder(dtypes_lib.float32, [stride]) pearson_r, update_op = metrics.streaming_pearson_correlation( predictions_t, labels_t, weights=weights_t) sess.run(variables.local_variables_initializer()) prev_expected_r = NAN for i in range(n // stride): feed_dict = { predictions_t: predictions[stride * i:stride * (i + 1)], labels_t: labels[stride * i:stride * (i + 1)], weights_t: weights[stride * i:stride * (i + 1)] } self.assertEqual( np.isnan(prev_expected_r), np.isnan(sess.run(pearson_r, feed_dict=feed_dict))) if not np.isnan(prev_expected_r): self.assertAlmostEqual(prev_expected_r, sess.run(pearson_r, feed_dict=feed_dict), 5) cmat = np.cov( predictions[:stride * (i + 1)], labels[:stride * (i + 1)], fweights=weights[:stride * (i + 1)]) expected_r = cmat[0, 1] / np.sqrt(cmat[0, 0] * cmat[1, 1]) self.assertAlmostEqual(expected_r, sess.run(update_op, feed_dict=feed_dict), 5) self.assertAlmostEqual(expected_r, sess.run(pearson_r, feed_dict=feed_dict), 5) prev_expected_r = expected_r def testMultiUpdateWithErrorAndSingletonBatches(self): with self.test_session() as sess: np.random.seed(123) n = 100 predictions = np.random.randn(n) labels = 0.5 * predictions + np.random.randn(n) stride = 10 weights = (np.arange(n).reshape(n // stride, stride) % stride == 0) for row in weights: np.random.shuffle(row) weights = weights.reshape((n,)) predictions_t = array_ops.placeholder(dtypes_lib.float32, [stride]) labels_t = array_ops.placeholder(dtypes_lib.float32, [stride]) weights_t = array_ops.placeholder(dtypes_lib.float32, [stride]) pearson_r, update_op = metrics.streaming_pearson_correlation( predictions_t, labels_t, weights=weights_t) sess.run(variables.local_variables_initializer()) for i in range(n // stride): feed_dict = { predictions_t: predictions[stride * i:stride * (i + 1)], labels_t: labels[stride * i:stride * (i + 1)], weights_t: weights[stride * i:stride * (i + 1)] } cmat = np.cov( predictions[:stride * (i + 1)], labels[:stride * (i + 1)], fweights=weights[:stride * (i + 1)]) expected_r = cmat[0, 1] / np.sqrt(cmat[0, 0] * cmat[1, 1]) actual_r = sess.run(update_op, feed_dict=feed_dict) self.assertEqual(np.isnan(expected_r), np.isnan(actual_r)) self.assertEqual( np.isnan(expected_r), np.isnan(sess.run(pearson_r, feed_dict=feed_dict))) if not np.isnan(expected_r): self.assertAlmostEqual(expected_r, actual_r, 5) self.assertAlmostEqual(expected_r, sess.run(pearson_r, feed_dict=feed_dict), 5) class StreamingMeanCosineDistanceTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_mean_cosine_distance( predictions=array_ops.ones((10, 3)), labels=array_ops.ones((10, 3)), dim=1) _assert_metric_variables(self, ( 'mean_cosine_distance/count:0', 'mean_cosine_distance/total:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_mean_cosine_distance( predictions=array_ops.ones((10, 3)), labels=array_ops.ones((10, 3)), dim=1, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean_cosine_distance( predictions=array_ops.ones((10, 3)), labels=array_ops.ones((10, 3)), dim=1, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_normal((10, 3), seed=1) labels = random_ops.random_normal((10, 3), seed=2) error, update_op = metrics.streaming_mean_cosine_distance( predictions, labels, dim=1) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_error = error.eval() for _ in range(10): self.assertEqual(initial_error, error.eval()) def testSingleUpdateZeroError(self): np_labels = np.matrix(('1 0 0;' '0 0 1;' '0 1 0')) predictions = constant_op.constant( np_labels, shape=(1, 3, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( np_labels, shape=(1, 3, 3), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_cosine_distance( predictions, labels, dim=2) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, sess.run(update_op)) self.assertEqual(0, error.eval()) def testSingleUpdateWithError1(self): np_labels = np.matrix(('1 0 0;' '0 0 1;' '0 1 0')) np_predictions = np.matrix(('1 0 0;' '0 0 -1;' '1 0 0')) predictions = constant_op.constant( np_predictions, shape=(3, 1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( np_labels, shape=(3, 1, 3), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_cosine_distance( predictions, labels, dim=2) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(1, sess.run(update_op), 5) self.assertAlmostEqual(1, error.eval(), 5) def testSingleUpdateWithError2(self): np_predictions = np.matrix( ('0.819031913261206 0.567041924552012 0.087465312324590;' '-0.665139432070255 -0.739487441769973 -0.103671883216994;' '0.707106781186548 -0.707106781186548 0')) np_labels = np.matrix( ('0.819031913261206 0.567041924552012 0.087465312324590;' '0.665139432070255 0.739487441769973 0.103671883216994;' '0.707106781186548 0.707106781186548 0')) predictions = constant_op.constant( np_predictions, shape=(3, 1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( np_labels, shape=(3, 1, 3), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_cosine_distance( predictions, labels, dim=2) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(1.0, sess.run(update_op), 5) self.assertAlmostEqual(1.0, error.eval(), 5) def testSingleUpdateWithErrorAndWeights1(self): np_predictions = np.matrix(('1 0 0;' '0 0 -1;' '1 0 0')) np_labels = np.matrix(('1 0 0;' '0 0 1;' '0 1 0')) predictions = constant_op.constant( np_predictions, shape=(3, 1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( np_labels, shape=(3, 1, 3), dtype=dtypes_lib.float32) weights = constant_op.constant( [1, 0, 0], shape=(3, 1, 1), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_cosine_distance( predictions, labels, dim=2, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(0, sess.run(update_op)) self.assertEqual(0, error.eval()) def testSingleUpdateWithErrorAndWeights2(self): np_predictions = np.matrix(('1 0 0;' '0 0 -1;' '1 0 0')) np_labels = np.matrix(('1 0 0;' '0 0 1;' '0 1 0')) predictions = constant_op.constant( np_predictions, shape=(3, 1, 3), dtype=dtypes_lib.float32) labels = constant_op.constant( np_labels, shape=(3, 1, 3), dtype=dtypes_lib.float32) weights = constant_op.constant( [0, 1, 1], shape=(3, 1, 1), dtype=dtypes_lib.float32) error, update_op = metrics.streaming_mean_cosine_distance( predictions, labels, dim=2, weights=weights) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1.5, update_op.eval()) self.assertEqual(1.5, error.eval()) class PcntBelowThreshTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_percentage_less(values=array_ops.ones((10,)), threshold=2) _assert_metric_variables(self, ( 'percentage_below_threshold/count:0', 'percentage_below_threshold/total:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_percentage_less( values=array_ops.ones((10,)), threshold=2, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_percentage_less( values=array_ops.ones((10,)), threshold=2, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testOneUpdate(self): with self.test_session() as sess: values = constant_op.constant( [2, 4, 6, 8], shape=(1, 4), dtype=dtypes_lib.float32) pcnt0, update_op0 = metrics.streaming_percentage_less( values, 100, name='high') pcnt1, update_op1 = metrics.streaming_percentage_less( values, 7, name='medium') pcnt2, update_op2 = metrics.streaming_percentage_less( values, 1, name='low') sess.run(variables.local_variables_initializer()) sess.run([update_op0, update_op1, update_op2]) pcnt0, pcnt1, pcnt2 = sess.run([pcnt0, pcnt1, pcnt2]) self.assertAlmostEqual(1.0, pcnt0, 5) self.assertAlmostEqual(0.75, pcnt1, 5) self.assertAlmostEqual(0.0, pcnt2, 5) def testSomePresentOneUpdate(self): with self.test_session() as sess: values = constant_op.constant( [2, 4, 6, 8], shape=(1, 4), dtype=dtypes_lib.float32) weights = constant_op.constant( [1, 0, 0, 1], shape=(1, 4), dtype=dtypes_lib.float32) pcnt0, update_op0 = metrics.streaming_percentage_less( values, 100, weights=weights, name='high') pcnt1, update_op1 = metrics.streaming_percentage_less( values, 7, weights=weights, name='medium') pcnt2, update_op2 = metrics.streaming_percentage_less( values, 1, weights=weights, name='low') sess.run(variables.local_variables_initializer()) self.assertListEqual([1.0, 0.5, 0.0], sess.run([update_op0, update_op1, update_op2])) pcnt0, pcnt1, pcnt2 = sess.run([pcnt0, pcnt1, pcnt2]) self.assertAlmostEqual(1.0, pcnt0, 5) self.assertAlmostEqual(0.5, pcnt1, 5) self.assertAlmostEqual(0.0, pcnt2, 5) class StreamingMeanIOUTest(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.streaming_mean_iou( predictions=array_ops.ones([10, 1]), labels=array_ops.ones([10, 1]), num_classes=2) _assert_metric_variables(self, ('mean_iou/total_confusion_matrix:0',)) def testMetricsCollections(self): my_collection_name = '__metrics__' mean_iou, _ = metrics.streaming_mean_iou( predictions=array_ops.ones([10, 1]), labels=array_ops.ones([10, 1]), num_classes=2, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean_iou]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_mean_iou( predictions=array_ops.ones([10, 1]), labels=array_ops.ones([10, 1]), num_classes=2, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testPredictionsAndLabelsOfDifferentSizeRaisesValueError(self): predictions = array_ops.ones([10, 3]) labels = array_ops.ones([10, 4]) with self.assertRaises(ValueError): metrics.streaming_mean_iou(predictions, labels, num_classes=2) def testLabelsAndWeightsOfDifferentSizeRaisesValueError(self): predictions = array_ops.ones([10]) labels = array_ops.ones([10]) weights = array_ops.zeros([9]) with self.assertRaises(ValueError): metrics.streaming_mean_iou( predictions, labels, num_classes=2, weights=weights) def testValueTensorIsIdempotent(self): num_classes = 3 predictions = random_ops.random_uniform( [10], maxval=num_classes, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( [10], maxval=num_classes, dtype=dtypes_lib.int64, seed=2) miou, update_op = metrics.streaming_mean_iou( predictions, labels, num_classes=num_classes) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_miou = miou.eval() for _ in range(10): self.assertEqual(initial_miou, miou.eval()) def testMultipleUpdates(self): num_classes = 3 with self.test_session() as sess: preds_queue = data_flow_ops.FIFOQueue( 5, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [2]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [0]) predictions = preds_queue.dequeue() labels_queue = data_flow_ops.FIFOQueue( 5, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [2]) _enqueue_vector(sess, labels_queue, [1]) labels = labels_queue.dequeue() miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) for _ in range(5): sess.run(update_op) desired_output = np.mean([1.0 / 2.0, 1.0 / 4.0, 0.]) self.assertEqual(desired_output, miou.eval()) def testMultipleUpdatesWithWeights(self): num_classes = 2 with self.test_session() as sess: preds_queue = data_flow_ops.FIFOQueue( 6, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) predictions = preds_queue.dequeue() labels_queue = data_flow_ops.FIFOQueue( 6, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) labels = labels_queue.dequeue() weights_queue = data_flow_ops.FIFOQueue( 6, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, weights_queue, [1.0]) _enqueue_vector(sess, weights_queue, [1.0]) _enqueue_vector(sess, weights_queue, [1.0]) _enqueue_vector(sess, weights_queue, [0.0]) _enqueue_vector(sess, weights_queue, [1.0]) _enqueue_vector(sess, weights_queue, [0.0]) weights = weights_queue.dequeue() miou, update_op = metrics.streaming_mean_iou( predictions, labels, num_classes, weights=weights) sess.run(variables.local_variables_initializer()) for _ in range(6): sess.run(update_op) desired_output = np.mean([2.0 / 3.0, 1.0 / 2.0]) self.assertAlmostEqual(desired_output, miou.eval()) def testMultipleUpdatesWithMissingClass(self): num_classes = 3 with self.test_session() as sess: preds_queue = data_flow_ops.FIFOQueue( 5, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [0]) predictions = preds_queue.dequeue() labels_queue = data_flow_ops.FIFOQueue( 5, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) labels = labels_queue.dequeue() miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) for _ in range(5): sess.run(update_op) desired_output = np.mean([1.0 / 3.0, 2.0 / 4.0]) self.assertAlmostEqual(desired_output, miou.eval()) def testUpdateOpEvalIsAccumulatedConfusionMatrix(self): predictions = array_ops.concat([ constant_op.constant(0, shape=[5]), constant_op.constant(1, shape=[5]) ], 0) labels = array_ops.concat([ constant_op.constant(0, shape=[3]), constant_op.constant(1, shape=[7]) ], 0) num_classes = 2 with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) confusion_matrix = update_op.eval() self.assertAllEqual([[3, 0], [2, 5]], confusion_matrix) desired_miou = np.mean([3. / 5., 5. / 7.]) self.assertAlmostEqual(desired_miou, miou.eval()) def testAllCorrect(self): predictions = array_ops.zeros([40]) labels = array_ops.zeros([40]) num_classes = 1 with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) self.assertEqual(40, update_op.eval()[0]) self.assertEqual(1.0, miou.eval()) def testAllWrong(self): predictions = array_ops.zeros([40]) labels = array_ops.ones([40]) num_classes = 2 with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) self.assertAllEqual([[0, 0], [40, 0]], update_op.eval()) self.assertEqual(0., miou.eval()) def testResultsWithSomeMissing(self): predictions = array_ops.concat([ constant_op.constant(0, shape=[5]), constant_op.constant(1, shape=[5]) ], 0) labels = array_ops.concat([ constant_op.constant(0, shape=[3]), constant_op.constant(1, shape=[7]) ], 0) num_classes = 2 weights = array_ops.concat([ constant_op.constant(0, shape=[1]), constant_op.constant(1, shape=[8]), constant_op.constant(0, shape=[1]) ], 0) with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou( predictions, labels, num_classes, weights=weights) sess.run(variables.local_variables_initializer()) self.assertAllEqual([[2, 0], [2, 4]], update_op.eval()) desired_miou = np.mean([2. / 4., 4. / 6.]) self.assertAlmostEqual(desired_miou, miou.eval()) def testMissingClassInLabels(self): labels = constant_op.constant([[[0, 0, 1, 1, 0, 0], [1, 0, 0, 0, 0, 1]], [[1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]]]) predictions = constant_op.constant( [[[0, 0, 2, 1, 1, 0], [0, 1, 2, 2, 0, 1]], [[0, 0, 2, 1, 1, 1], [1, 1, 2, 0, 0, 0]]]) num_classes = 3 with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) self.assertAllEqual([[7, 4, 3], [3, 5, 2], [0, 0, 0]], update_op.eval()) self.assertAlmostEqual(1 / 3 * (7 / (7 + 3 + 7) + 5 / (5 + 4 + 5) + 0 / (0 + 5 + 0)), miou.eval()) def testMissingClassOverallSmall(self): labels = constant_op.constant([0]) predictions = constant_op.constant([0]) num_classes = 2 with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) self.assertAllEqual([[1, 0], [0, 0]], update_op.eval()) self.assertAlmostEqual(1, miou.eval()) def testMissingClassOverallLarge(self): labels = constant_op.constant([[[0, 0, 1, 1, 0, 0], [1, 0, 0, 0, 0, 1]], [[1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]]]) predictions = constant_op.constant( [[[0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1]], [[0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0]]]) num_classes = 3 with self.test_session() as sess: miou, update_op = metrics.streaming_mean_iou(predictions, labels, num_classes) sess.run(variables.local_variables_initializer()) self.assertAllEqual([[9, 5, 0], [3, 7, 0], [0, 0, 0]], update_op.eval()) self.assertAlmostEqual(1 / 2 * (9 / (9 + 3 + 5) + 7 / (7 + 5 + 3)), miou.eval()) class StreamingConcatTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.streaming_concat(values=array_ops.ones((10,))) _assert_metric_variables(self, ( 'streaming_concat/array:0', 'streaming_concat/size:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' value, _ = metrics.streaming_concat( values=array_ops.ones((10,)), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [value]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.streaming_concat( values=array_ops.ones((10,)), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testNextArraySize(self): next_array_size = metric_ops._next_array_size with self.test_session(): self.assertEqual(next_array_size(2, growth_factor=2).eval(), 2) self.assertEqual(next_array_size(3, growth_factor=2).eval(), 4) self.assertEqual(next_array_size(4, growth_factor=2).eval(), 4) self.assertEqual(next_array_size(5, growth_factor=2).eval(), 8) self.assertEqual(next_array_size(6, growth_factor=2).eval(), 8) def testStreamingConcat(self): with self.test_session() as sess: values = array_ops.placeholder(dtypes_lib.int32, [None]) concatenated, update_op = metrics.streaming_concat(values) sess.run(variables.local_variables_initializer()) self.assertAllEqual([], concatenated.eval()) sess.run([update_op], feed_dict={values: [0, 1, 2]}) self.assertAllEqual([0, 1, 2], concatenated.eval()) sess.run([update_op], feed_dict={values: [3, 4]}) self.assertAllEqual([0, 1, 2, 3, 4], concatenated.eval()) sess.run([update_op], feed_dict={values: [5, 6, 7, 8, 9]}) self.assertAllEqual(np.arange(10), concatenated.eval()) def testStreamingConcatStringValues(self): with self.test_session() as sess: values = array_ops.placeholder(dtypes_lib.string, [None]) concatenated, update_op = metrics.streaming_concat(values) sess.run(variables.local_variables_initializer()) self.assertItemsEqual([], concatenated.eval()) sess.run([update_op], feed_dict={values: ['a', 'b', 'c']}) self.assertItemsEqual([b'a', b'b', b'c'], concatenated.eval()) sess.run([update_op], feed_dict={values: ['d', 'e']}) self.assertItemsEqual([b'a', b'b', b'c', b'd', b'e'], concatenated.eval()) sess.run([update_op], feed_dict={values: ['f', 'g', 'h', 'i', 'j']}) self.assertItemsEqual( [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j'], concatenated.eval()) def testStreamingConcatMaxSize(self): with self.test_session() as sess: values = math_ops.range(3) concatenated, update_op = metrics.streaming_concat(values, max_size=5) sess.run(variables.local_variables_initializer()) self.assertAllEqual([], concatenated.eval()) sess.run([update_op]) self.assertAllEqual([0, 1, 2], concatenated.eval()) sess.run([update_op]) self.assertAllEqual([0, 1, 2, 0, 1], concatenated.eval()) sess.run([update_op]) self.assertAllEqual([0, 1, 2, 0, 1], concatenated.eval()) def testStreamingConcat2D(self): with self.test_session() as sess: values = array_ops.reshape(math_ops.range(3), (3, 1)) concatenated, update_op = metrics.streaming_concat(values, axis=-1) sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run([update_op]) self.assertAllEqual([[0] * 10, [1] * 10, [2] * 10], concatenated.eval()) def testStreamingConcatErrors(self): with self.assertRaises(ValueError): metrics.streaming_concat(array_ops.placeholder(dtypes_lib.float32)) values = array_ops.zeros((2, 3)) with self.assertRaises(ValueError): metrics.streaming_concat(values, axis=-3, max_size=3) with self.assertRaises(ValueError): metrics.streaming_concat(values, axis=2, max_size=3) with self.assertRaises(ValueError): metrics.streaming_concat( array_ops.placeholder(dtypes_lib.float32, [None, None])) def testStreamingConcatReset(self): with self.test_session() as sess: values = array_ops.placeholder(dtypes_lib.int32, [None]) concatenated, update_op = metrics.streaming_concat(values) sess.run(variables.local_variables_initializer()) self.assertAllEqual([], concatenated.eval()) sess.run([update_op], feed_dict={values: [0, 1, 2]}) self.assertAllEqual([0, 1, 2], concatenated.eval()) sess.run(variables.local_variables_initializer()) sess.run([update_op], feed_dict={values: [3, 4]}) self.assertAllEqual([3, 4], concatenated.eval()) class AggregateMetricsTest(test.TestCase): def testAggregateNoMetricsRaisesValueError(self): with self.assertRaises(ValueError): metrics.aggregate_metrics() def testAggregateSingleMetricReturnsOneItemLists(self): values = array_ops.ones((10, 4)) value_tensors, update_ops = metrics.aggregate_metrics( metrics.streaming_mean(values)) self.assertEqual(len(value_tensors), 1) self.assertEqual(len(update_ops), 1) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(1, update_ops[0].eval()) self.assertEqual(1, value_tensors[0].eval()) def testAggregateMultipleMetricsReturnsListsInOrder(self): predictions = array_ops.ones((10, 4)) labels = array_ops.ones((10, 4)) * 3 value_tensors, update_ops = metrics.aggregate_metrics( metrics.streaming_mean_absolute_error(predictions, labels), metrics.streaming_mean_squared_error(predictions, labels)) self.assertEqual(len(value_tensors), 2) self.assertEqual(len(update_ops), 2) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(2, update_ops[0].eval()) self.assertEqual(4, update_ops[1].eval()) self.assertEqual(2, value_tensors[0].eval()) self.assertEqual(4, value_tensors[1].eval()) class AggregateMetricMapTest(test.TestCase): def testAggregateMultipleMetricsReturnsListsInOrder(self): predictions = array_ops.ones((10, 4)) labels = array_ops.ones((10, 4)) * 3 names_to_values, names_to_updates = metrics.aggregate_metric_map({ 'm1': metrics.streaming_mean_absolute_error(predictions, labels), 'm2': metrics.streaming_mean_squared_error(predictions, labels), }) self.assertEqual(2, len(names_to_values)) self.assertEqual(2, len(names_to_updates)) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) self.assertEqual(2, names_to_updates['m1'].eval()) self.assertEqual(4, names_to_updates['m2'].eval()) self.assertEqual(2, names_to_values['m1'].eval()) self.assertEqual(4, names_to_values['m2'].eval()) class CountTest(test.TestCase): def setUp(self): ops.reset_default_graph() def testVars(self): metrics.count(array_ops.ones([4, 3])) _assert_metric_variables(self, ['count/count:0']) def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.count( array_ops.ones([4, 3]), metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [mean]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.count( array_ops.ones([4, 3]), updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testReturnType(self): c, op = metrics.count(array_ops.ones([4, 3])) self.assertTrue(isinstance(c, ops.Tensor)) self.assertTrue(isinstance(op, ops.Operation) or isinstance(op, ops.Tensor)) def testBasic(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() result, update_op = metrics.count(values) sess.run(variables.local_variables_initializer()) for _ in range(4): sess.run(update_op) self.assertAlmostEqual(8.0, sess.run(result), 5) def testUpdateOpsReturnsCurrentValue(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() result, update_op = metrics.count(values) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(2.0, sess.run(update_op), 5) self.assertAlmostEqual(4.0, sess.run(update_op), 5) self.assertAlmostEqual(6.0, sess.run(update_op), 5) self.assertAlmostEqual(8.0, sess.run(update_op), 5) self.assertAlmostEqual(8.0, sess.run(result), 5) def test1dWeightedValues(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, weights_queue, [0.5]) _enqueue_vector(sess, weights_queue, [0]) _enqueue_vector(sess, weights_queue, [0]) _enqueue_vector(sess, weights_queue, [1.2]) weights = weights_queue.dequeue() result, update_op = metrics.count(values, weights) variables.local_variables_initializer().run() for _ in range(4): update_op.eval() self.assertAlmostEqual(3.4, result.eval(), 5) def test1dWeightedValues_placeholders(self): with self.test_session() as sess: feed_values = ((0, 1), (-4.2, 9.1), (6.5, 0), (-3.2, 4.0)) values = array_ops.placeholder(dtype=dtypes_lib.float32) weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1,)) _enqueue_vector(sess, weights_queue, 0.5, shape=(1,)) _enqueue_vector(sess, weights_queue, 0, shape=(1,)) _enqueue_vector(sess, weights_queue, 0, shape=(1,)) _enqueue_vector(sess, weights_queue, 1.2, shape=(1,)) weights = weights_queue.dequeue() result, update_op = metrics.count(values, weights) variables.local_variables_initializer().run() for i in range(4): update_op.eval(feed_dict={values: feed_values[i]}) self.assertAlmostEqual(3.4, result.eval(), 5) def test2dWeightedValues(self): with self.test_session() as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(1, 2)) _enqueue_vector(sess, weights_queue, [1.1, 1]) _enqueue_vector(sess, weights_queue, [1, 0]) _enqueue_vector(sess, weights_queue, [0, 1]) _enqueue_vector(sess, weights_queue, [0, 0]) weights = weights_queue.dequeue() result, update_op = metrics.count(values, weights) variables.local_variables_initializer().run() for _ in range(4): update_op.eval() self.assertAlmostEqual(4.1, result.eval(), 5) def test2dWeightedValues_placeholders(self): with self.test_session() as sess: feed_values = ((0, 1), (-4.2, 9.1), (6.5, 0), (-3.2, 4.0)) values = array_ops.placeholder(dtype=dtypes_lib.float32) weights_queue = data_flow_ops.FIFOQueue( 4, dtypes=dtypes_lib.float32, shapes=(2,)) _enqueue_vector(sess, weights_queue, [1.1, 1], shape=(2,)) _enqueue_vector(sess, weights_queue, [1, 0], shape=(2,)) _enqueue_vector(sess, weights_queue, [0, 1], shape=(2,)) _enqueue_vector(sess, weights_queue, [0, 0], shape=(2,)) weights = weights_queue.dequeue() result, update_op = metrics.count(values, weights) variables.local_variables_initializer().run() for i in range(4): update_op.eval(feed_dict={values: feed_values[i]}) self.assertAlmostEqual(4.1, result.eval(), 5) class CohenKappaTest(test.TestCase): def _confusion_matrix_to_samples(self, confusion_matrix): x, y = confusion_matrix.shape pairs = [] for label in range(x): for feature in range(y): pairs += [label, feature] * confusion_matrix[label, feature] pairs = np.array(pairs).reshape((-1, 2)) return pairs[:, 0], pairs[:, 1] def setUp(self): np.random.seed(1) ops.reset_default_graph() def testVars(self): metrics.cohen_kappa( predictions_idx=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), num_classes=2) _assert_metric_variables(self, ( 'cohen_kappa/po:0', 'cohen_kappa/pe_row:0', 'cohen_kappa/pe_col:0', )) def testMetricsCollection(self): my_collection_name = '__metrics__' kappa, _ = metrics.cohen_kappa( predictions_idx=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), num_classes=2, metrics_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [kappa]) def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.cohen_kappa( predictions_idx=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), num_classes=2, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) def testValueTensorIsIdempotent(self): predictions = random_ops.random_uniform( (10, 1), maxval=3, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( (10, 1), maxval=3, dtype=dtypes_lib.int64, seed=2) kappa, update_op = metrics.cohen_kappa(labels, predictions, 3) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for _ in range(10): sess.run(update_op) initial_kappa = kappa.eval() for _ in range(10): self.assertAlmostEqual(initial_kappa, kappa.eval(), 5) def testBasic(self): confusion_matrix = np.array([[9, 3, 1], [4, 8, 2], [2, 1, 6]]) expect = 0.45 labels, predictions = self._confusion_matrix_to_samples(confusion_matrix) dtypes = [dtypes_lib.int16, dtypes_lib.int32, dtypes_lib.int64] shapes = [ (len(labels,)), (len(labels), 1) ] weights = [None, np.ones_like(labels)] for dtype in dtypes: for shape in shapes: for weight in weights: with self.test_session() as sess: predictions_tensor = constant_op.constant( np.reshape(predictions, shape), dtype=dtype) labels_tensor = constant_op.constant( np.reshape(labels, shape), dtype=dtype) kappa, update_op = metrics.cohen_kappa( labels_tensor, predictions_tensor, 3, weights=weight) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expect, sess.run(update_op), 2) self.assertAlmostEqual(expect, kappa.eval(), 2) def testAllCorrect(self): inputs = np.arange(0, 100) % 4 expect = 1.0 with self.test_session() as sess: predictions = constant_op.constant(inputs, dtype=dtypes_lib.float32) labels = constant_op.constant(inputs) kappa, update_op = metrics.cohen_kappa(labels, predictions, 4) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expect, sess.run(update_op), 5) self.assertAlmostEqual(expect, kappa.eval(), 5) def testAllIncorrect(self): labels = np.arange(0, 100) % 4 predictions = (labels + 1) % 4 expect = -0.333333333333 with self.test_session() as sess: predictions = constant_op.constant(predictions, dtype=dtypes_lib.float32) labels = constant_op.constant(labels) kappa, update_op = metrics.cohen_kappa(labels, predictions, 4) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expect, sess.run(update_op), 5) self.assertAlmostEqual(expect, kappa.eval(), 5) def testWeighted(self): confusion_matrix = np.array([[9, 3, 1], [4, 8, 2], [2, 1, 6]]) labels, predictions = self._confusion_matrix_to_samples(confusion_matrix) num_samples = np.sum(confusion_matrix, dtype=np.int32) weights = (np.arange(0, num_samples) % 5) / 5.0 expect = 0.453466583385 with self.test_session() as sess: predictions = constant_op.constant(predictions, dtype=dtypes_lib.float32) labels = constant_op.constant(labels) kappa, update_op = metrics.cohen_kappa( labels, predictions, 4, weights=weights) sess.run(variables.local_variables_initializer()) self.assertAlmostEqual(expect, sess.run(update_op), 5) self.assertAlmostEqual(expect, kappa.eval(), 5) def testWithMultipleUpdates(self): confusion_matrix = np.array([[90, 30, 10, 20], [40, 80, 20, 30], [20, 10, 60, 35], [15, 25, 30, 25]]) labels, predictions = self._confusion_matrix_to_samples(confusion_matrix) num_samples = np.sum(confusion_matrix, dtype=np.int32) weights = (np.arange(0, num_samples) % 5) / 5.0 num_classes = confusion_matrix.shape[0] batch_size = num_samples // 10 predictions_t = array_ops.placeholder( dtypes_lib.float32, shape=(batch_size,)) labels_t = array_ops.placeholder(dtypes_lib.int32, shape=(batch_size,)) weights_t = array_ops.placeholder(dtypes_lib.float32, shape=(batch_size,)) kappa, update_op = metrics.cohen_kappa( labels_t, predictions_t, num_classes, weights=weights_t) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for idx in range(0, num_samples, batch_size): batch_start, batch_end = idx, idx + batch_size sess.run( update_op, feed_dict={ labels_t: labels[batch_start:batch_end], predictions_t: predictions[batch_start:batch_end], weights_t: weights[batch_start:batch_end] }) expect = 0.289965397924 self.assertAlmostEqual(expect, kappa.eval(), 5) def testInvalidNumClasses(self): predictions = array_ops.placeholder(dtypes_lib.float32, shape=(4, 1)) labels = array_ops.placeholder(dtypes_lib.int32, shape=(4, 1)) with self.assertRaisesRegexp(ValueError, 'num_classes'): metrics.cohen_kappa(labels, predictions, 1) def testInvalidDimension(self): predictions = array_ops.placeholder(dtypes_lib.float32, shape=(4, 1)) invalid_labels = array_ops.placeholder(dtypes_lib.int32, shape=(4, 2)) with self.assertRaises(ValueError): metrics.cohen_kappa(invalid_labels, predictions, 3) invalid_predictions = array_ops.placeholder( dtypes_lib.float32, shape=(4, 2)) labels = array_ops.placeholder(dtypes_lib.int32, shape=(4, 1)) with self.assertRaises(ValueError): metrics.cohen_kappa(labels, invalid_predictions, 3) def testConditionalPackingOptimization(self): placeholder = array_ops.placeholder(dtypes_lib.float32, [None]) values, update_op = metric_ops.streaming_concat(placeholder) with self.test_session() as sess: sess.run(variables.local_variables_initializer()) for feed in range(10): sess.run(update_op, feed_dict={placeholder: [feed]}) print(sess.run(values)) if __name__ == '__main__': test.main()
true
true
1c2c17ca3ae40240b1b72a93c6615a29cbb7031c
2,982
py
Python
faasmcli/faasmcli/tasks/codegen.py
BieVic/faasm
90081b3c9596a0f5bfe576725199ad1ef0242f12
[ "Apache-2.0" ]
254
2018-10-12T10:09:43.000Z
2020-06-02T17:42:04.000Z
faasmcli/faasmcli/tasks/codegen.py
BieVic/faasm
90081b3c9596a0f5bfe576725199ad1ef0242f12
[ "Apache-2.0" ]
49
2019-11-18T17:33:01.000Z
2020-05-23T13:15:23.000Z
faasmcli/faasmcli/tasks/codegen.py
BieVic/faasm
90081b3c9596a0f5bfe576725199ad1ef0242f12
[ "Apache-2.0" ]
22
2019-11-05T15:01:54.000Z
2020-06-02T17:42:05.000Z
from subprocess import run from invoke import task from copy import copy from os import environ from os.path import join from faasmcli.util.codegen import find_codegen_func, find_codegen_shared_lib from faasmcli.util.env import FAASM_RUNTIME_ROOT LIB_FAKE_FILES = [ join(FAASM_RUNTIME_ROOT, "lib", "fake", "libfakeLibA.so"), join(FAASM_RUNTIME_ROOT, "lib", "fake", "libfakeLibB.so"), ] WAMR_ALLOWED_FUNCS = [ # Misc ["demo", "chain"], ["ffmpeg", "check"], # Environment ["demo", "argc_argv_test"], ["demo", "exit"], ["demo", "getenv"], ["errors", "ret_one"], # Filesystem ["demo", "fcntl"], ["demo", "file"], ["demo", "filedescriptor"], ["demo", "fstat"], ["demo", "fread"], ["demo", "shared_file"], # Input output ["demo", "check_input"], ["demo", "echo"], ["demo", "stdout"], ["demo", "stderr"], ] SGX_ALLOWED_FUNCS = [ ["demo", "hello"], ["demo", "chain_named_a"], ["demo", "chain_named_b"], ["demo", "chain_named_c"], # Environment ["demo", "argc_argv_test"], ] @task(default=True) def codegen(ctx, user, function): """ Generates machine code for the given function """ env = copy(environ) env.update( { "LD_LIBRARY_PATH": "/usr/local/lib/", } ) binary = find_codegen_func() run( "{} {} {}".format(binary, user, function), shell=True, env=env, check=True, ) @task def user(ctx, user): """ Generates machine for all the functions belonging to the given user """ _do_codegen_user(user) def _do_codegen_user(user): print("Running WAVM codegen for user {}".format(user)) binary = find_codegen_func() env = copy(environ) env.update( { "WASM_VM": "wavm", "LD_LIBRARY_PATH": "/usr/local/lib/", } ) run("{} {}".format(binary, user), shell=True, env=env, check=True) def _do_codegen_file(path): binary = find_codegen_shared_lib() env = copy(environ) env.update( { "LD_LIBRARY_PATH": "/usr/local/lib/", } ) run("{} {}".format(binary, path), env=env, shell=True, check=True) @task def local(ctx): """ Runs codegen on functions used in tests """ _do_codegen_user("demo") _do_codegen_user("errors") _do_codegen_user("ffmpeg") _do_codegen_user("mpi") _do_codegen_user("omp") _do_codegen_user("python") # Do codegen for libfake for so in LIB_FAKE_FILES: _do_codegen_file(so) # For WAMR and SGX codegen, we need to update the environment env = copy(environ) # Run the WAMR codegen required by the tests env.update({"WASM_VM": "wamr"}) for user, func in WAMR_ALLOWED_FUNCS: codegen(ctx, user, func) # Run the SGX codegen required by the tests env.update({"WASM_VM": "sgx"}) for user, func in SGX_ALLOWED_FUNCS: codegen(ctx, user, func)
22.421053
76
0.595909
from subprocess import run from invoke import task from copy import copy from os import environ from os.path import join from faasmcli.util.codegen import find_codegen_func, find_codegen_shared_lib from faasmcli.util.env import FAASM_RUNTIME_ROOT LIB_FAKE_FILES = [ join(FAASM_RUNTIME_ROOT, "lib", "fake", "libfakeLibA.so"), join(FAASM_RUNTIME_ROOT, "lib", "fake", "libfakeLibB.so"), ] WAMR_ALLOWED_FUNCS = [ ["demo", "chain"], ["ffmpeg", "check"], ["demo", "argc_argv_test"], ["demo", "exit"], ["demo", "getenv"], ["errors", "ret_one"], ["demo", "fcntl"], ["demo", "file"], ["demo", "filedescriptor"], ["demo", "fstat"], ["demo", "fread"], ["demo", "shared_file"], ["demo", "check_input"], ["demo", "echo"], ["demo", "stdout"], ["demo", "stderr"], ] SGX_ALLOWED_FUNCS = [ ["demo", "hello"], ["demo", "chain_named_a"], ["demo", "chain_named_b"], ["demo", "chain_named_c"], ["demo", "argc_argv_test"], ] @task(default=True) def codegen(ctx, user, function): env = copy(environ) env.update( { "LD_LIBRARY_PATH": "/usr/local/lib/", } ) binary = find_codegen_func() run( "{} {} {}".format(binary, user, function), shell=True, env=env, check=True, ) @task def user(ctx, user): _do_codegen_user(user) def _do_codegen_user(user): print("Running WAVM codegen for user {}".format(user)) binary = find_codegen_func() env = copy(environ) env.update( { "WASM_VM": "wavm", "LD_LIBRARY_PATH": "/usr/local/lib/", } ) run("{} {}".format(binary, user), shell=True, env=env, check=True) def _do_codegen_file(path): binary = find_codegen_shared_lib() env = copy(environ) env.update( { "LD_LIBRARY_PATH": "/usr/local/lib/", } ) run("{} {}".format(binary, path), env=env, shell=True, check=True) @task def local(ctx): _do_codegen_user("demo") _do_codegen_user("errors") _do_codegen_user("ffmpeg") _do_codegen_user("mpi") _do_codegen_user("omp") _do_codegen_user("python") for so in LIB_FAKE_FILES: _do_codegen_file(so) env = copy(environ) env.update({"WASM_VM": "wamr"}) for user, func in WAMR_ALLOWED_FUNCS: codegen(ctx, user, func) env.update({"WASM_VM": "sgx"}) for user, func in SGX_ALLOWED_FUNCS: codegen(ctx, user, func)
true
true
1c2c181ecf11238b04a9e12154632e2445d0eb4d
3,448
py
Python
testsuite/data/scores/score_api/score_api.py
ICONationDevTeam/goloop
45241c021e7ba56408b8cc9a1440c965bef28411
[ "Apache-2.0" ]
47
2020-09-11T01:40:37.000Z
2022-03-29T02:41:17.000Z
testsuite/data/scores/score_api/score_api.py
pranav925/goloop
19f19e6ba6ccb25f464ae0cc31b76a9b30a13f0f
[ "Apache-2.0" ]
41
2020-09-11T01:33:13.000Z
2022-03-22T11:21:53.000Z
testsuite/data/scores/score_api/score_api.py
pranav925/goloop
19f19e6ba6ccb25f464ae0cc31b76a9b30a13f0f
[ "Apache-2.0" ]
24
2020-09-22T08:23:38.000Z
2022-03-19T11:14:10.000Z
from iconservice import * TAG = 'ScoreApi' class Person(TypedDict): name: str age: int class ScoreApi(IconScoreBase): def __init__(self, db: IconScoreDatabase) -> None: super().__init__(db) def on_install(self) -> None: super().on_install() def on_update(self) -> None: super().on_update() @external def externalMethod(self) -> str: return "externalMethod" @external(readonly=True) def externalReadonlyMethod(self) -> str: return "externalReadonlyMethod" # This should not be exposed to the API list @payable def payableMethod(self) -> str: return "payableMethod" @payable @external def payableExternalMethod(self) -> str: return "payableExternalMethod" @external @payable def externalPayableMethod(self) -> str: return "externalPayableMethod" @external(readonly=False) def externalReadonlyFalseMethod(self) -> str: return "externalReadonlyFalseMethod" # Possible data types for function parameters are int, str, bytes, bool, Address. # List and Struct parameters are now newly supported. # Return types can be int, str, bytes, bool, Address, list, dict. @external(readonly=True) def param_int(self, param1: int) -> int: return param1 @external(readonly=True) def param_str(self, param1: str) -> str: return param1 @external(readonly=True) def param_bytes(self, param1: bytes) -> bytes: return param1 @external(readonly=True) def param_bool(self, param1: bool) -> bool: return param1 @external(readonly=True) def param_Address(self, param1: Address) -> Address: return param1 @external(readonly=True) def param_List(self, param1: List[str]) -> List[str]: return param1 @external(readonly=True) def param_ListList(self, param1: List[List[str]]) -> List[List[str]]: return param1 @external(readonly=True) def param_Struct(self, param1: Person) -> Person: return param1 @external(readonly=True) def param_ListStruct(self, param1: List[Person]) -> List[Person]: return param1 @external(readonly=True) def return_list(self, rtype: str) -> list: if rtype == "str": return ["hello", "world"] elif rtype == "bytes": hello = bytes([0x68, 0x65, 0x6c, 0x6c, 0x6f]) world = bytes([0x77, 0x6f, 0x72, 0x6c, 0x64]) return [hello, world] elif rtype == "bool": return [True, False] elif rtype == "Address": return [self.address, self.owner] return [0, 1, 100] @external(readonly=True) def return_dict(self, rtype: str) -> dict: if rtype == "str": return {"key0": "hello", "key1": "world"} elif rtype == "bytes": hello = bytes([0x68, 0x65, 0x6c, 0x6c, 0x6f]) world = bytes([0x77, 0x6f, 0x72, 0x6c, 0x64]) return {"key0": hello, "key1": world} elif rtype == "bool": return {"key0": True, "key1": False} elif rtype == "Address": return {"key0": self.address, "key1": self.owner} return {"key0": 0, "key1": 1, "key2": 100} @payable def fallback(self): Logger.debug("fallback", TAG) @eventlog(indexed=1) def eventlog_index1(self, param1: int, param2: str): pass
27.806452
85
0.603538
from iconservice import * TAG = 'ScoreApi' class Person(TypedDict): name: str age: int class ScoreApi(IconScoreBase): def __init__(self, db: IconScoreDatabase) -> None: super().__init__(db) def on_install(self) -> None: super().on_install() def on_update(self) -> None: super().on_update() @external def externalMethod(self) -> str: return "externalMethod" @external(readonly=True) def externalReadonlyMethod(self) -> str: return "externalReadonlyMethod" @payable def payableMethod(self) -> str: return "payableMethod" @payable @external def payableExternalMethod(self) -> str: return "payableExternalMethod" @external @payable def externalPayableMethod(self) -> str: return "externalPayableMethod" @external(readonly=False) def externalReadonlyFalseMethod(self) -> str: return "externalReadonlyFalseMethod" @external(readonly=True) def param_int(self, param1: int) -> int: return param1 @external(readonly=True) def param_str(self, param1: str) -> str: return param1 @external(readonly=True) def param_bytes(self, param1: bytes) -> bytes: return param1 @external(readonly=True) def param_bool(self, param1: bool) -> bool: return param1 @external(readonly=True) def param_Address(self, param1: Address) -> Address: return param1 @external(readonly=True) def param_List(self, param1: List[str]) -> List[str]: return param1 @external(readonly=True) def param_ListList(self, param1: List[List[str]]) -> List[List[str]]: return param1 @external(readonly=True) def param_Struct(self, param1: Person) -> Person: return param1 @external(readonly=True) def param_ListStruct(self, param1: List[Person]) -> List[Person]: return param1 @external(readonly=True) def return_list(self, rtype: str) -> list: if rtype == "str": return ["hello", "world"] elif rtype == "bytes": hello = bytes([0x68, 0x65, 0x6c, 0x6c, 0x6f]) world = bytes([0x77, 0x6f, 0x72, 0x6c, 0x64]) return [hello, world] elif rtype == "bool": return [True, False] elif rtype == "Address": return [self.address, self.owner] return [0, 1, 100] @external(readonly=True) def return_dict(self, rtype: str) -> dict: if rtype == "str": return {"key0": "hello", "key1": "world"} elif rtype == "bytes": hello = bytes([0x68, 0x65, 0x6c, 0x6c, 0x6f]) world = bytes([0x77, 0x6f, 0x72, 0x6c, 0x64]) return {"key0": hello, "key1": world} elif rtype == "bool": return {"key0": True, "key1": False} elif rtype == "Address": return {"key0": self.address, "key1": self.owner} return {"key0": 0, "key1": 1, "key2": 100} @payable def fallback(self): Logger.debug("fallback", TAG) @eventlog(indexed=1) def eventlog_index1(self, param1: int, param2: str): pass
true
true
1c2c18773aad320c335162241a9041be30c4ee83
9,337
bzl
Python
rules/framework/vfs_overlay.bzl
cdoky/rules_ios
35c3cbb69a86a0f607b21bd5c65cabcfa3e12666
[ "Apache-2.0" ]
null
null
null
rules/framework/vfs_overlay.bzl
cdoky/rules_ios
35c3cbb69a86a0f607b21bd5c65cabcfa3e12666
[ "Apache-2.0" ]
null
null
null
rules/framework/vfs_overlay.bzl
cdoky/rules_ios
35c3cbb69a86a0f607b21bd5c65cabcfa3e12666
[ "Apache-2.0" ]
null
null
null
load("//rules:providers.bzl", "FrameworkInfo") load("//rules:features.bzl", "feature_names") FRAMEWORK_SEARCH_PATH = "/build_bazel_rules_ios/frameworks" VFSOverlayInfo = provider( doc = "Propagates vfs overlays", fields = { "files": "depset with overlays", "vfs_info": "intneral obj", }, ) # Computes the "back" segment for a path length def _make_relative_prefix(length): dots = "../" prefix = "" for i in range(0, length): prefix += dots return prefix # Internal to swift and clang - LLVM `VirtualFileSystem` object can # serialize paths relative to the absolute path of the overlay. This # requires the paths are relative to the overlay. While deriving the # in-memory tree roots, it pre-pends the prefix of the `vfsoverlay` path # to each of the entries. def _get_external_contents(prefix, path_str): return prefix + path_str def _get_vfs_parent(ctx): return (ctx.bin_dir.path + "/" + ctx.build_file_path) # Make roots for a given framework. For now this is done in starlark for speed # and incrementality. For imported frameworks, there is additional search paths # enabled def _make_root(vfs_parent, bin_dir_path, build_file_path, framework_name, root_dir, extra_search_paths, module_map, hdrs, private_hdrs, has_swift): extra_roots = [] vfs_prefix = _make_relative_prefix(len(vfs_parent.split("/")) - 1) if extra_search_paths: sub_dir = "Headers" # Strip the build file path base_path = "/".join(build_file_path.split("/")[:-1]) rooted_path = base_path + "/" + extra_search_paths + "/" + sub_dir + "/" extra_roots = [{ "type": "file", "name": file.path.replace(rooted_path, ""), "external-contents": _get_external_contents(vfs_prefix, file.path), } for file in hdrs] extra_roots += [{ "type": "file", "name": framework_name + "/" + file.path.replace(rooted_path, ""), "external-contents": _get_external_contents(vfs_prefix, file.path), } for file in hdrs] modules_contents = [] if len(module_map): modules_contents.append({ "type": "file", "name": "module.modulemap", "external-contents": _get_external_contents(vfs_prefix, module_map[0].path), }) modules = [] if len(modules_contents): modules = [{ "name": "Modules", "type": "directory", "contents": modules_contents, }] headers_contents = extra_roots headers_contents.extend([ { "type": "file", "name": file.basename, "external-contents": _get_external_contents(vfs_prefix, file.path), } for file in hdrs ]) headers = [] if len(headers_contents): headers = [{ "name": "Headers", "type": "directory", "contents": headers_contents, }] private_headers_contents = { "name": "PrivateHeaders", "type": "directory", "contents": [ { "type": "file", "name": file.basename, "external-contents": _get_external_contents(vfs_prefix, file.path), } for file in private_hdrs ], } private_headers = [] if len(private_hdrs): private_headers = [private_headers_contents] roots = [] if len(headers) or len(private_headers) or len(modules): roots.append({ "name": root_dir, "type": "directory", "contents": headers + private_headers + modules, }) if has_swift: roots.append(_vfs_swift_module_contents(bin_dir_path, build_file_path, vfs_prefix, framework_name, FRAMEWORK_SEARCH_PATH)) return roots def _vfs_swift_module_contents(bin_dir_path, build_file_path, vfs_prefix, framework_name, root_dir): # Forumlate the framework's swiftmodule - don't have the swiftmodule when # creating with apple_library. Consider removing that codepath to make this # and other situations easier base_path = "/".join(build_file_path.split("/")[:-1]) rooted_path = bin_dir_path + "/" + base_path # Note: Swift translates the input framework name to this because - is an # invalid character in module name name = framework_name.replace("-", "_") + ".swiftmodule" external_contents = rooted_path + "/" + name return { "type": "file", "name": root_dir + "/" + name, "external-contents": _get_external_contents(vfs_prefix, external_contents), } def _framework_vfs_overlay_impl(ctx): vfsoverlays = [] # Conditionally collect and pass in the VFS overlay here. virtualize_frameworks = feature_names.virtualize_frameworks in ctx.features if virtualize_frameworks: for dep in ctx.attr.deps: if FrameworkInfo in dep: vfsoverlays.extend(dep[FrameworkInfo].vfsoverlay_infos) if VFSOverlayInfo in dep: vfsoverlays.append(dep[VFSOverlayInfo].vfs_info) vfs = make_vfsoverlay( ctx, hdrs = ctx.files.hdrs, module_map = ctx.files.modulemap, private_hdrs = ctx.files.private_hdrs, has_swift = ctx.attr.has_swift, merge_vfsoverlays = vfsoverlays, output = ctx.outputs.vfsoverlay_file, extra_search_paths = ctx.attr.extra_search_paths, ) headers = depset([vfs.vfsoverlay_file]) cc_info = CcInfo( compilation_context = cc_common.create_compilation_context( headers = headers, ), ) return [ apple_common.new_objc_provider(), cc_info, VFSOverlayInfo( files = depset([vfs.vfsoverlay_file]), vfs_info = vfs.vfs_info, ), ] def _merge_vfs_infos(base, vfs_infos): for vfs_info in vfs_infos: base.update(vfs_info) return base # Internally the "vfs obj" is represented as a dictionary, which is keyed on # the name of the root. This is an opaque value to consumers def _make_vfs_info(name, data): keys = {} keys[name] = data return keys # Roots must be computed _relative_ to the vfs_parent. It is no longer possible # to memoize VFS computations because of this. def _roots_from_datas(vfs_parent, datas): roots = [] for data in datas: roots.extend(_make_root( vfs_parent = vfs_parent, bin_dir_path = data.bin_dir_path, build_file_path = data.build_file_path, framework_name = data.framework_name, root_dir = data.framework_path, extra_search_paths = data.extra_search_paths, module_map = data.module_map, hdrs = data.hdrs, private_hdrs = data.private_hdrs, has_swift = data.has_swift, )) return roots def make_vfsoverlay(ctx, hdrs, module_map, private_hdrs, has_swift, merge_vfsoverlays = [], extra_search_paths = None, output = None): framework_name = ctx.attr.framework_name framework_path = "{search_path}/{framework_name}.framework".format( search_path = FRAMEWORK_SEARCH_PATH, framework_name = framework_name, ) vfs_parent = _get_vfs_parent(ctx) data = struct( bin_dir_path = ctx.bin_dir.path, build_file_path = ctx.build_file_path, framework_name = framework_name, framework_path = framework_path, extra_search_paths = extra_search_paths, module_map = module_map, hdrs = hdrs, private_hdrs = private_hdrs, has_swift = has_swift, ) roots = _make_root( vfs_parent, bin_dir_path = ctx.bin_dir.path, build_file_path = ctx.build_file_path, framework_name = framework_name, root_dir = framework_path, extra_search_paths = extra_search_paths, module_map = module_map, hdrs = hdrs, private_hdrs = private_hdrs, has_swift = has_swift, ) vfs_info = _make_vfs_info(framework_name, data) if len(merge_vfsoverlays) > 0: vfs_info = _merge_vfs_infos(vfs_info, merge_vfsoverlays) roots = _roots_from_datas(vfs_parent, vfs_info.values() + [data]) if output == None: return struct(vfsoverlay_file = None, vfs_info = vfs_info) vfsoverlay_object = { "version": 0, "case-sensitive": True, "overlay-relative": True, "use-external-names": False, "roots": roots, } vfsoverlay_yaml = struct(**vfsoverlay_object).to_json() ctx.actions.write( content = vfsoverlay_yaml, output = output, ) return struct(vfsoverlay_file = output, vfs_info = vfs_info) framework_vfs_overlay = rule( implementation = _framework_vfs_overlay_impl, attrs = { "framework_name": attr.string(mandatory = True), "extra_search_paths": attr.string(mandatory = False), "has_swift": attr.bool(default = False), "modulemap": attr.label(allow_single_file = True), "hdrs": attr.label_list(allow_files = True), "private_hdrs": attr.label_list(allow_files = True, default = []), "deps": attr.label_list(allow_files = True, default = []), }, outputs = { "vfsoverlay_file": "%{name}.yaml", }, )
33.46595
147
0.633501
load("//rules:providers.bzl", "FrameworkInfo") load("//rules:features.bzl", "feature_names") FRAMEWORK_SEARCH_PATH = "/build_bazel_rules_ios/frameworks" VFSOverlayInfo = provider( doc = "Propagates vfs overlays", fields = { "files": "depset with overlays", "vfs_info": "intneral obj", }, ) def _make_relative_prefix(length): dots = "../" prefix = "" for i in range(0, length): prefix += dots return prefix def _get_external_contents(prefix, path_str): return prefix + path_str def _get_vfs_parent(ctx): return (ctx.bin_dir.path + "/" + ctx.build_file_path) def _make_root(vfs_parent, bin_dir_path, build_file_path, framework_name, root_dir, extra_search_paths, module_map, hdrs, private_hdrs, has_swift): extra_roots = [] vfs_prefix = _make_relative_prefix(len(vfs_parent.split("/")) - 1) if extra_search_paths: sub_dir = "Headers" base_path = "/".join(build_file_path.split("/")[:-1]) rooted_path = base_path + "/" + extra_search_paths + "/" + sub_dir + "/" extra_roots = [{ "type": "file", "name": file.path.replace(rooted_path, ""), "external-contents": _get_external_contents(vfs_prefix, file.path), } for file in hdrs] extra_roots += [{ "type": "file", "name": framework_name + "/" + file.path.replace(rooted_path, ""), "external-contents": _get_external_contents(vfs_prefix, file.path), } for file in hdrs] modules_contents = [] if len(module_map): modules_contents.append({ "type": "file", "name": "module.modulemap", "external-contents": _get_external_contents(vfs_prefix, module_map[0].path), }) modules = [] if len(modules_contents): modules = [{ "name": "Modules", "type": "directory", "contents": modules_contents, }] headers_contents = extra_roots headers_contents.extend([ { "type": "file", "name": file.basename, "external-contents": _get_external_contents(vfs_prefix, file.path), } for file in hdrs ]) headers = [] if len(headers_contents): headers = [{ "name": "Headers", "type": "directory", "contents": headers_contents, }] private_headers_contents = { "name": "PrivateHeaders", "type": "directory", "contents": [ { "type": "file", "name": file.basename, "external-contents": _get_external_contents(vfs_prefix, file.path), } for file in private_hdrs ], } private_headers = [] if len(private_hdrs): private_headers = [private_headers_contents] roots = [] if len(headers) or len(private_headers) or len(modules): roots.append({ "name": root_dir, "type": "directory", "contents": headers + private_headers + modules, }) if has_swift: roots.append(_vfs_swift_module_contents(bin_dir_path, build_file_path, vfs_prefix, framework_name, FRAMEWORK_SEARCH_PATH)) return roots def _vfs_swift_module_contents(bin_dir_path, build_file_path, vfs_prefix, framework_name, root_dir): base_path = "/".join(build_file_path.split("/")[:-1]) rooted_path = bin_dir_path + "/" + base_path name = framework_name.replace("-", "_") + ".swiftmodule" external_contents = rooted_path + "/" + name return { "type": "file", "name": root_dir + "/" + name, "external-contents": _get_external_contents(vfs_prefix, external_contents), } def _framework_vfs_overlay_impl(ctx): vfsoverlays = [] virtualize_frameworks = feature_names.virtualize_frameworks in ctx.features if virtualize_frameworks: for dep in ctx.attr.deps: if FrameworkInfo in dep: vfsoverlays.extend(dep[FrameworkInfo].vfsoverlay_infos) if VFSOverlayInfo in dep: vfsoverlays.append(dep[VFSOverlayInfo].vfs_info) vfs = make_vfsoverlay( ctx, hdrs = ctx.files.hdrs, module_map = ctx.files.modulemap, private_hdrs = ctx.files.private_hdrs, has_swift = ctx.attr.has_swift, merge_vfsoverlays = vfsoverlays, output = ctx.outputs.vfsoverlay_file, extra_search_paths = ctx.attr.extra_search_paths, ) headers = depset([vfs.vfsoverlay_file]) cc_info = CcInfo( compilation_context = cc_common.create_compilation_context( headers = headers, ), ) return [ apple_common.new_objc_provider(), cc_info, VFSOverlayInfo( files = depset([vfs.vfsoverlay_file]), vfs_info = vfs.vfs_info, ), ] def _merge_vfs_infos(base, vfs_infos): for vfs_info in vfs_infos: base.update(vfs_info) return base def _make_vfs_info(name, data): keys = {} keys[name] = data return keys def _roots_from_datas(vfs_parent, datas): roots = [] for data in datas: roots.extend(_make_root( vfs_parent = vfs_parent, bin_dir_path = data.bin_dir_path, build_file_path = data.build_file_path, framework_name = data.framework_name, root_dir = data.framework_path, extra_search_paths = data.extra_search_paths, module_map = data.module_map, hdrs = data.hdrs, private_hdrs = data.private_hdrs, has_swift = data.has_swift, )) return roots def make_vfsoverlay(ctx, hdrs, module_map, private_hdrs, has_swift, merge_vfsoverlays = [], extra_search_paths = None, output = None): framework_name = ctx.attr.framework_name framework_path = "{search_path}/{framework_name}.framework".format( search_path = FRAMEWORK_SEARCH_PATH, framework_name = framework_name, ) vfs_parent = _get_vfs_parent(ctx) data = struct( bin_dir_path = ctx.bin_dir.path, build_file_path = ctx.build_file_path, framework_name = framework_name, framework_path = framework_path, extra_search_paths = extra_search_paths, module_map = module_map, hdrs = hdrs, private_hdrs = private_hdrs, has_swift = has_swift, ) roots = _make_root( vfs_parent, bin_dir_path = ctx.bin_dir.path, build_file_path = ctx.build_file_path, framework_name = framework_name, root_dir = framework_path, extra_search_paths = extra_search_paths, module_map = module_map, hdrs = hdrs, private_hdrs = private_hdrs, has_swift = has_swift, ) vfs_info = _make_vfs_info(framework_name, data) if len(merge_vfsoverlays) > 0: vfs_info = _merge_vfs_infos(vfs_info, merge_vfsoverlays) roots = _roots_from_datas(vfs_parent, vfs_info.values() + [data]) if output == None: return struct(vfsoverlay_file = None, vfs_info = vfs_info) vfsoverlay_object = { "version": 0, "case-sensitive": True, "overlay-relative": True, "use-external-names": False, "roots": roots, } vfsoverlay_yaml = struct(**vfsoverlay_object).to_json() ctx.actions.write( content = vfsoverlay_yaml, output = output, ) return struct(vfsoverlay_file = output, vfs_info = vfs_info) framework_vfs_overlay = rule( implementation = _framework_vfs_overlay_impl, attrs = { "framework_name": attr.string(mandatory = True), "extra_search_paths": attr.string(mandatory = False), "has_swift": attr.bool(default = False), "modulemap": attr.label(allow_single_file = True), "hdrs": attr.label_list(allow_files = True), "private_hdrs": attr.label_list(allow_files = True, default = []), "deps": attr.label_list(allow_files = True, default = []), }, outputs = { "vfsoverlay_file": "%{name}.yaml", }, )
true
true
1c2c19476fea3bdf4fb4b6553a526732eba38284
6,035
py
Python
sdks/python/http_client/v1/polyaxon_sdk/models/v1_list_dashboards_response.py
admariner/polyaxon
ba355c38166047eb11e60de4cee4d7c3b48db323
[ "Apache-2.0" ]
null
null
null
sdks/python/http_client/v1/polyaxon_sdk/models/v1_list_dashboards_response.py
admariner/polyaxon
ba355c38166047eb11e60de4cee4d7c3b48db323
[ "Apache-2.0" ]
null
null
null
sdks/python/http_client/v1/polyaxon_sdk/models/v1_list_dashboards_response.py
admariner/polyaxon
ba355c38166047eb11e60de4cee4d7c3b48db323
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding: utf-8 """ Polyaxon SDKs and REST API specification. Polyaxon SDKs and REST API specification. # noqa: E501 The version of the OpenAPI document: 1.11.0 Contact: contact@polyaxon.com Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from polyaxon_sdk.configuration import Configuration class V1ListDashboardsResponse(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'count': 'int', 'results': 'list[V1Dashboard]', 'previous': 'str', 'next': 'str' } attribute_map = { 'count': 'count', 'results': 'results', 'previous': 'previous', 'next': 'next' } def __init__(self, count=None, results=None, previous=None, next=None, local_vars_configuration=None): # noqa: E501 """V1ListDashboardsResponse - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._count = None self._results = None self._previous = None self._next = None self.discriminator = None if count is not None: self.count = count if results is not None: self.results = results if previous is not None: self.previous = previous if next is not None: self.next = next @property def count(self): """Gets the count of this V1ListDashboardsResponse. # noqa: E501 :return: The count of this V1ListDashboardsResponse. # noqa: E501 :rtype: int """ return self._count @count.setter def count(self, count): """Sets the count of this V1ListDashboardsResponse. :param count: The count of this V1ListDashboardsResponse. # noqa: E501 :type: int """ self._count = count @property def results(self): """Gets the results of this V1ListDashboardsResponse. # noqa: E501 :return: The results of this V1ListDashboardsResponse. # noqa: E501 :rtype: list[V1Dashboard] """ return self._results @results.setter def results(self, results): """Sets the results of this V1ListDashboardsResponse. :param results: The results of this V1ListDashboardsResponse. # noqa: E501 :type: list[V1Dashboard] """ self._results = results @property def previous(self): """Gets the previous of this V1ListDashboardsResponse. # noqa: E501 :return: The previous of this V1ListDashboardsResponse. # noqa: E501 :rtype: str """ return self._previous @previous.setter def previous(self, previous): """Sets the previous of this V1ListDashboardsResponse. :param previous: The previous of this V1ListDashboardsResponse. # noqa: E501 :type: str """ self._previous = previous @property def next(self): """Gets the next of this V1ListDashboardsResponse. # noqa: E501 :return: The next of this V1ListDashboardsResponse. # noqa: E501 :rtype: str """ return self._next @next.setter def next(self, next): """Sets the next of this V1ListDashboardsResponse. :param next: The next of this V1ListDashboardsResponse. # noqa: E501 :type: str """ self._next = next def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1ListDashboardsResponse): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1ListDashboardsResponse): return True return self.to_dict() != other.to_dict()
27.939815
120
0.600663
import pprint import re import six from polyaxon_sdk.configuration import Configuration class V1ListDashboardsResponse(object): openapi_types = { 'count': 'int', 'results': 'list[V1Dashboard]', 'previous': 'str', 'next': 'str' } attribute_map = { 'count': 'count', 'results': 'results', 'previous': 'previous', 'next': 'next' } def __init__(self, count=None, results=None, previous=None, next=None, local_vars_configuration=None): if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._count = None self._results = None self._previous = None self._next = None self.discriminator = None if count is not None: self.count = count if results is not None: self.results = results if previous is not None: self.previous = previous if next is not None: self.next = next @property def count(self): return self._count @count.setter def count(self, count): self._count = count @property def results(self): return self._results @results.setter def results(self, results): self._results = results @property def previous(self): return self._previous @previous.setter def previous(self, previous): self._previous = previous @property def next(self): return self._next @next.setter def next(self, next): self._next = next def to_dict(self): result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, V1ListDashboardsResponse): return False return self.to_dict() == other.to_dict() def __ne__(self, other): if not isinstance(other, V1ListDashboardsResponse): return True return self.to_dict() != other.to_dict()
true
true
1c2c19a12b87b250f7609372d69771a1c72c1620
4,740
py
Python
app/users/migrations/0001_initial.py
chriskmamo/greenvoice
11306e939612907da21f89350b4446e47081e695
[ "MIT" ]
null
null
null
app/users/migrations/0001_initial.py
chriskmamo/greenvoice
11306e939612907da21f89350b4446e47081e695
[ "MIT" ]
2
2022-02-13T20:16:39.000Z
2022-02-19T06:27:31.000Z
app/users/migrations/0001_initial.py
chriskmamo/greenvoice
11306e939612907da21f89350b4446e47081e695
[ "MIT" ]
null
null
null
# Generated by Django 3.0.10 on 2020-10-10 11:16 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='CustomUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('email', models.EmailField(max_length=254, unique=True, verbose_name='email address')), ('is_staff', models.BooleanField(default=False)), ('is_active', models.BooleanField(default=True)), ('date_joined', models.DateTimeField(default=django.utils.timezone.now)), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'verbose_name': 'User', 'verbose_name_plural': 'Users', }, ), migrations.CreateModel( name='Address', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('line_1', models.CharField(blank=True, max_length=200, verbose_name='line 1')), ('line_2', models.CharField(blank=True, max_length=200, verbose_name='line 2')), ('city', models.CharField(blank=True, max_length=200, verbose_name='city')), ('zip', models.CharField(blank=True, max_length=200, verbose_name='postal code')), ('country', models.CharField(blank=True, max_length=200, verbose_name='country')), ], ), migrations.CreateModel( name='BodyMeasurements', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('age', models.IntegerField(blank=True, verbose_name='age')), ('chest', models.IntegerField(blank=True, verbose_name='chest')), ('hip', models.IntegerField(blank=True, verbose_name='hip')), ('inseam', models.IntegerField(blank=True, verbose_name='inseam')), ('size', models.IntegerField(blank=True, verbose_name='size')), ('sleeve_length', models.IntegerField(blank=True, verbose_name='sleeve length')), ('thigh', models.CharField(blank=True, max_length=200, verbose_name='thigh')), ('upper_arm', models.IntegerField(blank=True, verbose_name='upper arm')), ('waist', models.IntegerField(blank=True, verbose_name='waist')), ], ), migrations.CreateModel( name='Customer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('gender', models.PositiveSmallIntegerField(blank=True, choices=[(1, 'women'), (2, 'men')], null=True, verbose_name='gender')), ('name', models.CharField(blank=True, max_length=200, verbose_name='name')), ('created', models.DateTimeField(auto_now_add=True, verbose_name='created')), ('address', models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='users.Address', verbose_name='address')), ('body_measurements', models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='users.BodyMeasurements', verbose_name='body measurements')), ('user', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user')), ], options={ 'ordering': ['created'], }, ), ]
60
266
0.621941
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='CustomUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('email', models.EmailField(max_length=254, unique=True, verbose_name='email address')), ('is_staff', models.BooleanField(default=False)), ('is_active', models.BooleanField(default=True)), ('date_joined', models.DateTimeField(default=django.utils.timezone.now)), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'verbose_name': 'User', 'verbose_name_plural': 'Users', }, ), migrations.CreateModel( name='Address', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('line_1', models.CharField(blank=True, max_length=200, verbose_name='line 1')), ('line_2', models.CharField(blank=True, max_length=200, verbose_name='line 2')), ('city', models.CharField(blank=True, max_length=200, verbose_name='city')), ('zip', models.CharField(blank=True, max_length=200, verbose_name='postal code')), ('country', models.CharField(blank=True, max_length=200, verbose_name='country')), ], ), migrations.CreateModel( name='BodyMeasurements', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('age', models.IntegerField(blank=True, verbose_name='age')), ('chest', models.IntegerField(blank=True, verbose_name='chest')), ('hip', models.IntegerField(blank=True, verbose_name='hip')), ('inseam', models.IntegerField(blank=True, verbose_name='inseam')), ('size', models.IntegerField(blank=True, verbose_name='size')), ('sleeve_length', models.IntegerField(blank=True, verbose_name='sleeve length')), ('thigh', models.CharField(blank=True, max_length=200, verbose_name='thigh')), ('upper_arm', models.IntegerField(blank=True, verbose_name='upper arm')), ('waist', models.IntegerField(blank=True, verbose_name='waist')), ], ), migrations.CreateModel( name='Customer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('gender', models.PositiveSmallIntegerField(blank=True, choices=[(1, 'women'), (2, 'men')], null=True, verbose_name='gender')), ('name', models.CharField(blank=True, max_length=200, verbose_name='name')), ('created', models.DateTimeField(auto_now_add=True, verbose_name='created')), ('address', models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='users.Address', verbose_name='address')), ('body_measurements', models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='users.BodyMeasurements', verbose_name='body measurements')), ('user', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user')), ], options={ 'ordering': ['created'], }, ), ]
true
true
1c2c1a6931ccebf375a10d9ed09224fe6b4d6c2d
8,204
py
Python
hyperion/model/image.py
astrofrog/hyperion
e90d7af1df4f064a960594d812c07ff27d87fcc7
[ "BSD-2-Clause" ]
2
2015-05-14T17:26:16.000Z
2019-03-13T17:33:18.000Z
hyperion/model/image.py
astrofrog/hyperion
e90d7af1df4f064a960594d812c07ff27d87fcc7
[ "BSD-2-Clause" ]
null
null
null
hyperion/model/image.py
astrofrog/hyperion
e90d7af1df4f064a960594d812c07ff27d87fcc7
[ "BSD-2-Clause" ]
null
null
null
import numpy as np from ..util.functions import FreezableClass, is_numpy_array from ..util.constants import c class Image(FreezableClass): """ Class to represent an image or set of images Parameters ---------- nu : ndarray The frequencies at which the image is defined, in Hz flux : ndarray, optional The fluxes for the image. The last dimensions should match the number of frequencies. This flux can be f_nu or nu * f_nu. unc : ndarray, optional The flux uncertainties for the image. The last dimensions should match the number of frequencies. units : str The units of the flux """ def __init__(self, nu, flux=None, unc=None, units=None): self.nu = nu self.flux = flux self.unc = unc self.units = units self.x_min = None self.x_max = None self.y_min = None self.y_max = None self.lon_min = None self.lon_max = None self.lat_min = None self.lat_max = None self.distance = None self.pix_area_sr = None self.inside_observer = False self._freeze() @property def nu(self): return self._nu @nu.setter def nu(self, value): if type(value) in [list, tuple]: value = np.array(value) if value is None: self._nu = value elif isinstance(value, np.ndarray) and value.ndim == 1: self._nu = value else: raise TypeError("nu should be a 1-d sequence") @property def flux(self): return self._flux @flux.setter def flux(self, value): if type(value) in [list, tuple]: value = np.array(value) if value is None: self._flux = value elif isinstance(value, np.ndarray) and value.ndim >= 1: if self.nu is not None and len(self.nu) != value.shape[-1]: raise ValueError("the last dimension of the flux array should match the length of the nu array (expected {0} but found {1})".format(len(self.nu), value.shape[-1])) else: if hasattr(self, 'unc') and self.unc is not None: if value.shape != self.unc.shape: raise ValueError("dimensions should match that of unc") self._flux = value else: raise TypeError("flux should be a multi-dimensional array") @property def unc(self): return self._unc @unc.setter def unc(self, value): if type(value) in [list, tuple]: value = np.array(value) if value is None: self._unc = value elif isinstance(value, np.ndarray) and value.ndim >= 1: if self.nu is not None and len(self.nu) != value.shape[-1]: raise ValueError("the last dimension of the unc array should match the length of the nu array (expected {0} but found {1})".format(len(self.nu), value.shape[-1])) else: if hasattr(self, 'flux') and self.flux is not None: if value.shape != self.flux.shape: raise ValueError("dimensions should match that of flux") self._unc = value else: raise TypeError("unc should be a multi-dimensional array") @property def unit(self): return self._unit @unit.setter def unit(self, value): if value is None or isinstance(value, basestring): self._unit = value else: raise ValueError("unit should be a string") @property def wav(self): return c / self.nu * 1e4 def __iter__(self): if self.unc is None: return (x for x in [self.wav, self.flux]) else: return (x for x in [self.wav, self.flux, self.unc]) @property def x_min(self): """ Lower extent of the image in the x direction in cm. """ return self._x_min @x_min.setter def x_min(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._x_min = value else: raise ValueError("x_min should be a real scalar value") @property def x_max(self): """ Upper extent of the image in the x direction in cm. """ return self._x_max @x_max.setter def x_max(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._x_max = value else: raise ValueError("x_max should be a real scalar value") @property def y_min(self): """ Lower extent of the image in the y direction in cm. """ return self._y_min @y_min.setter def y_min(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._y_min = value else: raise ValueError("y_min should be a real scalar value") @property def y_max(self): """ Upper extent of the image in the y direction in cm. """ return self._y_max @y_max.setter def y_max(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._y_max = value else: raise ValueError("y_max should be a real scalar value") @property def lon_min(self): """ Lower extent of the image in the x direction in degrees. """ return self._lon_min @lon_min.setter def lon_min(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._lon_min = value else: raise ValueError("lon_min should be a real scalar value") @property def lon_max(self): """ Upper extent of the image in the x direction in degrees. """ return self._lon_max @lon_max.setter def lon_max(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._lon_max = value else: raise ValueError("lon_max should be a real scalar value") @property def lat_min(self): """ Lower extent of the image in the y direction in degrees. """ return self._lat_min @lat_min.setter def lat_min(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._lat_min = value else: raise ValueError("lat_min should be a real scalar value") @property def lat_max(self): """ Upper extent of the image in the y direction in degrees. """ return self._lat_max @lat_max.setter def lat_max(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._lat_max = value else: raise ValueError("lat_max should be a real scalar value") @property def distance(self): """ Distance assumed for the image. """ return self._distance @distance.setter def distance(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._distance = value else: raise ValueError("distance should be a real scalar value") @property def pix_area_sr(self): """ Pixel area in steradians. """ return self._pix_area_sr @pix_area_sr.setter def pix_area_sr(self, value): if value is None or (np.isscalar(value) and np.isreal(value)) or (is_numpy_array(value) and value.ndim == 2): self._pix_area_sr = value else: raise ValueError("pix_area_sr should be a real scalar value or a 2-d array") @property def inside_observer(self): """ Whether the image was from an inside observer. """ return self._inside_observer @inside_observer.setter def inside_observer(self, value): if value is None or type(value) is bool: self._inside_observer = value else: raise ValueError("inside_observer should be a boolean")
29.3
179
0.574963
import numpy as np from ..util.functions import FreezableClass, is_numpy_array from ..util.constants import c class Image(FreezableClass): def __init__(self, nu, flux=None, unc=None, units=None): self.nu = nu self.flux = flux self.unc = unc self.units = units self.x_min = None self.x_max = None self.y_min = None self.y_max = None self.lon_min = None self.lon_max = None self.lat_min = None self.lat_max = None self.distance = None self.pix_area_sr = None self.inside_observer = False self._freeze() @property def nu(self): return self._nu @nu.setter def nu(self, value): if type(value) in [list, tuple]: value = np.array(value) if value is None: self._nu = value elif isinstance(value, np.ndarray) and value.ndim == 1: self._nu = value else: raise TypeError("nu should be a 1-d sequence") @property def flux(self): return self._flux @flux.setter def flux(self, value): if type(value) in [list, tuple]: value = np.array(value) if value is None: self._flux = value elif isinstance(value, np.ndarray) and value.ndim >= 1: if self.nu is not None and len(self.nu) != value.shape[-1]: raise ValueError("the last dimension of the flux array should match the length of the nu array (expected {0} but found {1})".format(len(self.nu), value.shape[-1])) else: if hasattr(self, 'unc') and self.unc is not None: if value.shape != self.unc.shape: raise ValueError("dimensions should match that of unc") self._flux = value else: raise TypeError("flux should be a multi-dimensional array") @property def unc(self): return self._unc @unc.setter def unc(self, value): if type(value) in [list, tuple]: value = np.array(value) if value is None: self._unc = value elif isinstance(value, np.ndarray) and value.ndim >= 1: if self.nu is not None and len(self.nu) != value.shape[-1]: raise ValueError("the last dimension of the unc array should match the length of the nu array (expected {0} but found {1})".format(len(self.nu), value.shape[-1])) else: if hasattr(self, 'flux') and self.flux is not None: if value.shape != self.flux.shape: raise ValueError("dimensions should match that of flux") self._unc = value else: raise TypeError("unc should be a multi-dimensional array") @property def unit(self): return self._unit @unit.setter def unit(self, value): if value is None or isinstance(value, basestring): self._unit = value else: raise ValueError("unit should be a string") @property def wav(self): return c / self.nu * 1e4 def __iter__(self): if self.unc is None: return (x for x in [self.wav, self.flux]) else: return (x for x in [self.wav, self.flux, self.unc]) @property def x_min(self): return self._x_min @x_min.setter def x_min(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._x_min = value else: raise ValueError("x_min should be a real scalar value") @property def x_max(self): return self._x_max @x_max.setter def x_max(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._x_max = value else: raise ValueError("x_max should be a real scalar value") @property def y_min(self): return self._y_min @y_min.setter def y_min(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._y_min = value else: raise ValueError("y_min should be a real scalar value") @property def y_max(self): return self._y_max @y_max.setter def y_max(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._y_max = value else: raise ValueError("y_max should be a real scalar value") @property def lon_min(self): return self._lon_min @lon_min.setter def lon_min(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._lon_min = value else: raise ValueError("lon_min should be a real scalar value") @property def lon_max(self): return self._lon_max @lon_max.setter def lon_max(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._lon_max = value else: raise ValueError("lon_max should be a real scalar value") @property def lat_min(self): return self._lat_min @lat_min.setter def lat_min(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._lat_min = value else: raise ValueError("lat_min should be a real scalar value") @property def lat_max(self): return self._lat_max @lat_max.setter def lat_max(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._lat_max = value else: raise ValueError("lat_max should be a real scalar value") @property def distance(self): return self._distance @distance.setter def distance(self, value): if value is None or (np.isscalar(value) and np.isreal(value)): self._distance = value else: raise ValueError("distance should be a real scalar value") @property def pix_area_sr(self): return self._pix_area_sr @pix_area_sr.setter def pix_area_sr(self, value): if value is None or (np.isscalar(value) and np.isreal(value)) or (is_numpy_array(value) and value.ndim == 2): self._pix_area_sr = value else: raise ValueError("pix_area_sr should be a real scalar value or a 2-d array") @property def inside_observer(self): return self._inside_observer @inside_observer.setter def inside_observer(self, value): if value is None or type(value) is bool: self._inside_observer = value else: raise ValueError("inside_observer should be a boolean")
true
true
1c2c1bf41a6b57bdda5539eb2df9272b3e718ab5
3,276
py
Python
setup.py
VincentRPS/hikari-views
b641dd6f02baee144daaa1b41f6337effa870325
[ "MIT" ]
1
2022-01-31T16:59:55.000Z
2022-01-31T16:59:55.000Z
setup.py
VincentRPS/hikari-views
b641dd6f02baee144daaa1b41f6337effa870325
[ "MIT" ]
null
null
null
setup.py
VincentRPS/hikari-views
b641dd6f02baee144daaa1b41f6337effa870325
[ "MIT" ]
null
null
null
""" MIT License Copyright (c) 2022-present HyperGH Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import os import re import types from setuptools import find_namespace_packages from setuptools import setup name = "miru" def parse_meta(): with open(os.path.join(name, "__init__.py")) as fp: code = fp.read() token_pattern = re.compile(r"^__(?P<key>\w+)?__\s*=\s*(?P<quote>(?:'{3}|\"{3}|'|\"))(?P<value>.*?)(?P=quote)", re.M) groups = {} for match in token_pattern.finditer(code): group = match.groupdict() groups[group["key"]] = group["value"] return types.SimpleNamespace(**groups) def long_description(): with open("README.md") as fp: return fp.read() def parse_requirements_file(path): with open(path) as fp: dependencies = (d.strip() for d in fp.read().split("\n") if d.strip()) return [d for d in dependencies if not d.startswith("#")] meta = parse_meta() setup( name="hikari-miru", version=meta.version, description="An alternative component handler for hikari, inspired by discord.py's views.", long_description=long_description(), long_description_content_type="text/markdown", author="HyperGH", author_email="46067571+HyperGH@users.noreply.github.com", url="https://github.com/HyperGH/hikari-miru", packages=find_namespace_packages(include=[name + "*"]), license="MIT", include_package_data=True, zip_safe=False, install_requires=["hikari~=2.0.0.dev105"], python_requires=">=3.8.0,<3.11", classifiers=[ "Development Status :: 5 - Production/Stable", "Framework :: AsyncIO", "Intended Audience :: Developers", "Natural Language :: English", "Topic :: Software Development :: Libraries :: Python Modules", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: 3 :: Only", "Topic :: Software Development :: Libraries", "Topic :: Software Development :: Libraries :: Application Frameworks", "Topic :: Software Development :: Libraries :: Python Modules", ], )
34.851064
120
0.690171
import os import re import types from setuptools import find_namespace_packages from setuptools import setup name = "miru" def parse_meta(): with open(os.path.join(name, "__init__.py")) as fp: code = fp.read() token_pattern = re.compile(r"^__(?P<key>\w+)?__\s*=\s*(?P<quote>(?:'{3}|\"{3}|'|\"))(?P<value>.*?)(?P=quote)", re.M) groups = {} for match in token_pattern.finditer(code): group = match.groupdict() groups[group["key"]] = group["value"] return types.SimpleNamespace(**groups) def long_description(): with open("README.md") as fp: return fp.read() def parse_requirements_file(path): with open(path) as fp: dependencies = (d.strip() for d in fp.read().split("\n") if d.strip()) return [d for d in dependencies if not d.startswith("#")] meta = parse_meta() setup( name="hikari-miru", version=meta.version, description="An alternative component handler for hikari, inspired by discord.py's views.", long_description=long_description(), long_description_content_type="text/markdown", author="HyperGH", author_email="46067571+HyperGH@users.noreply.github.com", url="https://github.com/HyperGH/hikari-miru", packages=find_namespace_packages(include=[name + "*"]), license="MIT", include_package_data=True, zip_safe=False, install_requires=["hikari~=2.0.0.dev105"], python_requires=">=3.8.0,<3.11", classifiers=[ "Development Status :: 5 - Production/Stable", "Framework :: AsyncIO", "Intended Audience :: Developers", "Natural Language :: English", "Topic :: Software Development :: Libraries :: Python Modules", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: 3 :: Only", "Topic :: Software Development :: Libraries", "Topic :: Software Development :: Libraries :: Application Frameworks", "Topic :: Software Development :: Libraries :: Python Modules", ], )
true
true
1c2c1c7b3896f407d171c284c7c03dfea1455844
58,209
py
Python
lte/gateway/python/integ_tests/s1aptests/s1ap_utils.py
ashish-acl/magma
d938f420b56b867a7c64101e6fac63f50be58a46
[ "BSD-3-Clause" ]
null
null
null
lte/gateway/python/integ_tests/s1aptests/s1ap_utils.py
ashish-acl/magma
d938f420b56b867a7c64101e6fac63f50be58a46
[ "BSD-3-Clause" ]
null
null
null
lte/gateway/python/integ_tests/s1aptests/s1ap_utils.py
ashish-acl/magma
d938f420b56b867a7c64101e6fac63f50be58a46
[ "BSD-3-Clause" ]
null
null
null
""" Copyright 2020 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import ctypes import ipaddress import logging import os import shlex import threading import time from enum import Enum from queue import Queue from typing import Optional import grpc import subprocess import json import s1ap_types from integ_tests.gateway.rpc import get_rpc_channel from lte.protos.policydb_pb2 import ( FlowDescription, FlowMatch, FlowQos, PolicyRule, QosArp, ) from lte.protos.mobilityd_pb2 import IPAddress from lte.protos.session_manager_pb2 import ( DynamicRuleInstall, PolicyReAuthRequest, QoSInformation, RuleSet, RulesPerSubscriber, SessionRules, ) from lte.protos.abort_session_pb2 import ( AbortSessionRequest, AbortSessionResult, ) from lte.protos.spgw_service_pb2 import ( CreateBearerRequest, DeleteBearerRequest, ) from lte.protos.spgw_service_pb2_grpc import SpgwServiceStub from magma.subscriberdb.sid import SIDUtils from lte.protos.abort_session_pb2_grpc import AbortSessionResponderStub from lte.protos.session_manager_pb2_grpc import ( LocalSessionManagerStub, SessionProxyResponderStub, ) from orc8r.protos.directoryd_pb2 import GetDirectoryFieldRequest from orc8r.protos.directoryd_pb2_grpc import GatewayDirectoryServiceStub from integ_tests.s1aptests.ovs.rest_api import get_datapath, get_flows from lte.protos.ha_service_pb2_grpc import HaServiceStub from lte.protos.ha_service_pb2 import ( StartAgwOffloadRequest, EnbOffloadType, ) from orc8r.protos.common_pb2 import Void DEFAULT_GRPC_TIMEOUT = 10 class S1ApUtil(object): """ Helper class to wrap the initialization and API interface of S1APTester Note that some of the values that are not that interesting are set through config files, that this class doesn't override. Examples include the various interface timeout params. """ # Extracted from TestCntlrApp/src/ueApp/ue_esm.h CM_ESM_PDN_IPV4 = 0b01 CM_ESM_PDN_IPV6 = 0b10 CM_ESM_PDN_IPV4V6 = 0b11 PROT_CFG_CID_PCSCF_IPV6_ADDR_REQUEST = 0x0001 PROT_CFG_CID_PCSCF_IPV4_ADDR_REQUEST = 0x000C PROT_CFG_CID_DNS_SERVER_IPV6_ADDR_REQUEST = 0x0003 lib_name = "libtfw.so" _cond = threading.Condition() _msg = Queue() MAX_NUM_RETRIES = 5 datapath = get_datapath() SPGW_TABLE = 0 LOCAL_PORT = "LOCAL" class Msg(object): def __init__(self, msg_type, msg_p, msg_len): self.msg_type = msg_type self.msg_p = ctypes.create_string_buffer(msg_len) ctypes.memmove(self.msg_p, msg_p, msg_len) self.msg_len = msg_len def cast(self, msg_class): return ctypes.cast(self.msg_p, ctypes.POINTER(msg_class)).contents @staticmethod def s1ap_callback(msg_type, msg_p, msg_len): """ S1ap tester compatible callback""" with S1ApUtil._cond: S1ApUtil._msg.put(S1ApUtil.Msg(msg_type, msg_p, msg_len)) S1ApUtil._cond.notify_all() def __init__(self): """ Initialize the s1aplibrary and its callbacks. """ self._imsi_idx = 1 self.IMSI_LEN = 15 lib_path = os.environ["S1AP_TESTER_ROOT"] lib = os.path.join(lib_path, "bin", S1ApUtil.lib_name) os.chdir(lib_path) self._test_lib = ctypes.cdll.LoadLibrary(lib) self._callback_type = ctypes.CFUNCTYPE( None, ctypes.c_short, ctypes.c_void_p, ctypes.c_short ) # Maintain a reference to the function object so GC doesn't release it. self._callback_fn = self._callback_type(S1ApUtil.s1ap_callback) self._test_lib.initTestFrameWork(self._callback_fn) self._test_api = self._test_lib.tfwApi self._test_api.restype = ctypes.c_int16 self._test_api.argtypes = [ctypes.c_uint16, ctypes.c_void_p] # Mutex for state change operations self._lock = threading.RLock() # Maintain a map of UE IDs to IPs self._ue_ip_map = {} self.gtpBridgeUtil = GTPBridgeUtils() def cleanup(self): """ Cleanup the dll loaded explicitly so the next run doesn't reuse the same globals as ctypes LoadLibrary uses dlopen under the covers Also clear out the UE ID: IP mappings """ # self._test_lib.dlclose(self._test_lib._handle) self._test_lib = None self._ue_ip_map = {} def issue_cmd(self, cmd_type, req): """ Issue a command to the s1aptester and blocks until response is recvd. Args: cmd_type: The cmd type enum req: The request Structure Returns: None """ c_req = None if req: # For non NULL requests obtain the address. c_req = ctypes.byref(req) with self._cond: rc = self._test_api(cmd_type.value, c_req) if rc: print("Error executing command %s" % repr(cmd_type)) return rc return 0 def get_ip(self, ue_id): """ Returns the IP assigned to a given UE ID Args: ue_id: the ue_id to query Returns an ipaddress.ip_address for the given UE ID, or None if no IP has been observed to be assigned to this IP """ with self._lock: if ue_id in self._ue_ip_map: return self._ue_ip_map[ue_id] return None def get_response(self): # Wait until callback is invoked. return self._msg.get(True) def populate_pco( self, protCfgOpts_pr, pcscf_addr_type=None, dns_ipv6_addr=False ): """ Populates the PCO values. Args: protCfgOpts_pr: PCO structure pcscf_addr_type: ipv4/ipv6/ipv4v6 flag dns_ipv6_addr: True/False flag Returns: None """ # PCO parameters # Presence mask protCfgOpts_pr.pres = 1 # Length protCfgOpts_pr.len = 4 # Configuration protocol protCfgOpts_pr.cfgProt = 0 # Extension bit for the additional parameters protCfgOpts_pr.ext = 1 # Number of protocol IDs protCfgOpts_pr.numProtId = 0 # Fill Number of container IDs and Container ID idx = 0 if pcscf_addr_type == "ipv4": protCfgOpts_pr.numContId += 1 protCfgOpts_pr.c[ idx ].cid = S1ApUtil.PROT_CFG_CID_PCSCF_IPV4_ADDR_REQUEST idx += 1 elif pcscf_addr_type == "ipv6": protCfgOpts_pr.numContId += 1 protCfgOpts_pr.c[ idx ].cid = S1ApUtil.PROT_CFG_CID_PCSCF_IPV6_ADDR_REQUEST idx += 1 elif pcscf_addr_type == "ipv4v6": protCfgOpts_pr.numContId += 2 protCfgOpts_pr.c[ idx ].cid = S1ApUtil.PROT_CFG_CID_PCSCF_IPV4_ADDR_REQUEST idx += 1 protCfgOpts_pr.c[ idx ].cid = S1ApUtil.PROT_CFG_CID_PCSCF_IPV6_ADDR_REQUEST idx += 1 if dns_ipv6_addr: protCfgOpts_pr.numContId += 1 protCfgOpts_pr.c[ idx ].cid = S1ApUtil.PROT_CFG_CID_DNS_SERVER_IPV6_ADDR_REQUEST def attach( self, ue_id, attach_type, resp_type, resp_msg_type, sec_ctxt=s1ap_types.TFW_CREATE_NEW_SECURITY_CONTEXT, id_type=s1ap_types.TFW_MID_TYPE_IMSI, eps_type=s1ap_types.TFW_EPS_ATTACH_TYPE_EPS_ATTACH, pdn_type=1, pcscf_addr_type=None, dns_ipv6_addr=False, ): """ Given a UE issue the attach request of specified type Caches the assigned IP address, if any is assigned Args: ue_id: The eNB ue_id attach_type: The type of attach e.g. UE_END_TO_END_ATTACH_REQUEST resp_type: enum type of the expected response sec_ctxt: Optional param allows for the reuse of the security context, defaults to creating a new security context. id_type: Optional param allows for changing up the ID type, defaults to s1ap_types.TFW_MID_TYPE_IMSI. eps_type: Optional param allows for variation in the EPS attach type, defaults to s1ap_types.TFW_EPS_ATTACH_TYPE_EPS_ATTACH. pdn_type:1 for IPv4, 2 for IPv6 and 3 for IPv4v6 pcscf_addr_type:IPv4/IPv6/IPv4v6 """ attach_req = s1ap_types.ueAttachRequest_t() attach_req.ue_Id = ue_id attach_req.mIdType = id_type attach_req.epsAttachType = eps_type attach_req.useOldSecCtxt = sec_ctxt attach_req.pdnType_pr.pres = True attach_req.pdnType_pr.pdn_type = pdn_type # Populate PCO only if pcscf_addr_type is set if pcscf_addr_type or dns_ipv6_addr: self.populate_pco( attach_req.protCfgOpts_pr, pcscf_addr_type, dns_ipv6_addr ) assert self.issue_cmd(attach_type, attach_req) == 0 response = self.get_response() # The MME actually sends INT_CTX_SETUP_IND and UE_ATTACH_ACCEPT_IND in # one message, but the s1aptester splits it and sends the tests 2 # messages. Usually context setup comes before attach accept, but # it's possible it may happen the other way if s1ap_types.tfwCmd.INT_CTX_SETUP_IND.value == response.msg_type: response = self.get_response() elif s1ap_types.tfwCmd.UE_ATTACH_ACCEPT_IND.value == response.msg_type: context_setup = self.get_response() assert ( context_setup.msg_type == s1ap_types.tfwCmd.INT_CTX_SETUP_IND.value ) logging.debug( "s1ap response expected, received: %d, %d", resp_type.value, response.msg_type, ) assert resp_type.value == response.msg_type msg = response.cast(resp_msg_type) # We only support IPv4 right now, as max PDN address in S1AP tester is # currently 13 bytes, which is too short for IPv6 (which requires 16) if resp_msg_type == s1ap_types.ueAttachAccept_t: pdn_type = msg.esmInfo.pAddr.pdnType addr = msg.esmInfo.pAddr.addrInfo if S1ApUtil.CM_ESM_PDN_IPV4 == pdn_type: # Cast and cache the IPv4 address ip = ipaddress.ip_address(bytes(addr[:4])) with self._lock: self._ue_ip_map[ue_id] = ip elif S1ApUtil.CM_ESM_PDN_IPV6 == pdn_type: print("IPv6 PDN type received") elif S1ApUtil.CM_ESM_PDN_IPV4V6 == pdn_type: print("IPv4v6 PDN type received") return msg def receive_emm_info(self): response = self.get_response() logging.debug( "s1ap message expected, received: %d, %d", s1ap_types.tfwCmd.UE_EMM_INFORMATION.value, response.msg_type, ) assert response.msg_type == s1ap_types.tfwCmd.UE_EMM_INFORMATION.value def detach(self, ue_id, reason_type, wait_for_s1_ctxt_release=True): """ Given a UE issue a detach request """ detach_req = s1ap_types.uedetachReq_t() detach_req.ue_Id = ue_id detach_req.ueDetType = reason_type assert ( self.issue_cmd(s1ap_types.tfwCmd.UE_DETACH_REQUEST, detach_req) == 0 ) if reason_type == s1ap_types.ueDetachType_t.UE_NORMAL_DETACH.value: response = self.get_response() assert ( s1ap_types.tfwCmd.UE_DETACH_ACCEPT_IND.value == response.msg_type ) # Now wait for the context release response if wait_for_s1_ctxt_release: response = self.get_response() assert s1ap_types.tfwCmd.UE_CTX_REL_IND.value == response.msg_type with self._lock: del self._ue_ip_map[ue_id] def _verify_dl_flow(self, dl_flow_rules=None): # try at least 5 times before failing as gateway # might take some time to install the flows in ovs # Verify the total number of DL flows for this UE ip address num_dl_flows = 1 for key, value in dl_flow_rules.items(): tcp_src_port = 0 ip_proto = 0 ue_ip6_str = None ue_ip_str = str(key) if key.version == 6: ue_ip6_str = ipaddress.ip_network( (ue_ip_str + "/64"), strict=False ).with_netmask ue_ip_addr = ue_ip6_str if key.version == 6 else ue_ip_str dst_addr = "nw_dst" if key.version == 4 else "ipv6_dst" key_to_be_matched = "ipv4_src" if key.version == 4 else "ipv6_src" eth_typ = 2048 if key.version == 4 else 34525 # Set to 1 for the default bearer total_num_dl_flows_to_be_verified = 1 for item in value: for flow in item: if ( flow["direction"] == FlowMatch.DOWNLINK and key_to_be_matched in flow ): total_num_dl_flows_to_be_verified += 1 total_dl_ovs_flows_created = get_flows( self.datapath, { "table_id": self.SPGW_TABLE, "match": { dst_addr: ue_ip_addr, "eth_type": eth_typ, "in_port": self.LOCAL_PORT, }, }, ) assert ( len(total_dl_ovs_flows_created) == total_num_dl_flows_to_be_verified ) # Now verify the rules for every flow for item in value: for flow in item: if ( flow["direction"] == FlowMatch.DOWNLINK and key_to_be_matched in flow ): ip_src_addr = flow[key_to_be_matched] ip_src = "ipv4_src" if key.version == 4 else "ipv6_src" ip_dst = "ipv4_dst" if key.version == 4 else "ipv6_dst" tcp_src_port = flow["tcp_src_port"] ip_proto = flow["ip_proto"] for i in range(self.MAX_NUM_RETRIES): print("Get downlink flows: attempt ", i) downlink_flows = get_flows( self.datapath, { "table_id": self.SPGW_TABLE, "match": { ip_dst: ue_ip_addr, "eth_type": eth_typ, "in_port": self.LOCAL_PORT, ip_src: ip_src_addr, "tcp_src": tcp_src_port, "ip_proto": ip_proto, }, }, ) if len(downlink_flows) >= num_dl_flows: break time.sleep( 5 ) # sleep for 5 seconds before retrying assert ( len(downlink_flows) >= num_dl_flows ), "Downlink flow missing for UE" assert downlink_flows[0]["match"][ip_dst] == ue_ip_addr actions = downlink_flows[0]["instructions"][0][ "actions" ] has_tunnel_action = any( action for action in actions if action["field"] == "tunnel_id" and action["type"] == "SET_FIELD" ) assert bool(has_tunnel_action) def verify_flow_rules(self, num_ul_flows, dl_flow_rules=None): GTP_PORT = self.gtpBridgeUtil.get_gtp_port_no() # Check if UL and DL OVS flows are created print("************ Verifying flow rules") # UPLINK print("Checking for uplink flow") # try at least 5 times before failing as gateway # might take some time to install the flows in ovs for i in range(self.MAX_NUM_RETRIES): print("Get uplink flows: attempt ", i) uplink_flows = get_flows( self.datapath, { "table_id": self.SPGW_TABLE, "match": { "in_port": GTP_PORT, } }, ) if len(uplink_flows) == num_ul_flows: break time.sleep(5) # sleep for 5 seconds before retrying assert len(uplink_flows) == num_ul_flows,\ "Uplink flow missing for UE: %d !=" % (len(uplink_flows), num_ul_flows) assert uplink_flows[0]["match"]["tunnel_id"] is not None # DOWNLINK print("Checking for downlink flow") self._verify_dl_flow(dl_flow_rules) def verify_paging_flow_rules(self, ip_list): # Check if paging flows are created print("************ Verifying paging flow rules") num_paging_flows_to_be_verified = 1 for ip in ip_list: ue_ip_str = str(ip) print("Verifying paging flow for ip", ue_ip_str) for i in range(self.MAX_NUM_RETRIES): print("Get paging flows: attempt ", i) paging_flows = get_flows( self.datapath, { "table_id": self.SPGW_TABLE, "match": { "nw_dst": ue_ip_str, "eth_type": 2048, "priority": 5, }, }, ) if len(paging_flows) == num_paging_flows_to_be_verified: break time.sleep(5) # sleep for 5 seconds before retrying assert ( len(paging_flows) == num_paging_flows_to_be_verified ), "Paging flow missing for UE" # TODO - Verify that the action is to send to controller """controller_port = 4294967293 actions = paging_flows[0]["instructions"][0]["actions"] has_tunnel_action = any( action for action in actions if action["type"] == "OUTPUT" and action["port"] == controller_port ) assert bool(has_tunnel_action)""" def generate_imsi(self, prefix=None): """ Generate imsi based on index offset and prefix """ assert (prefix is not None), "IMSI prefix is empty" idx = str(self._imsi_idx) # Add 0 padding padding = self.IMSI_LEN - len(idx) - len(prefix[4:]) imsi = prefix + "0" * padding + idx assert(len(imsi[4:]) == self.IMSI_LEN), "Invalid IMSI length" self._imsi_idx += 1 print("Using subscriber IMSI %s" % imsi) return imsi class SubscriberUtil(object): """ Helper class to manage subscriber data for the tests. """ SID_PREFIX = "IMSI00101" IMSI_LEN = 15 def __init__(self, subscriber_client): """ Initialize subscriber util. Args: subscriber_client (subscriber_db_client.SubscriberDbClient): client interacting with our subscriber APIs """ self._sid_idx = 1 self._ue_id = 1 # Maintain references to UE configs to prevent GC self._ue_cfgs = [] self._subscriber_client = subscriber_client def _gen_next_sid(self): """ Generate the sid based on index offset and prefix """ idx = str(self._sid_idx) # Find the 0 padding we need to add padding = self.IMSI_LEN - len(idx) - len(self.SID_PREFIX[4:]) sid = self.SID_PREFIX + "0" * padding + idx self._sid_idx += 1 print("Using subscriber IMSI %s" % sid) return sid def _get_s1ap_sub(self, sid): """ Get the subscriber data in s1aptester format. Args: The string representation of the subscriber id """ ue_cfg = s1ap_types.ueConfig_t() ue_cfg.ue_id = self._ue_id ue_cfg.auth_key = 1 # Some s1ap silliness, the char field is modelled as an int and then # cast into a uint8. for i in range(0, 15): ue_cfg.imsi[i] = ctypes.c_ubyte(int(sid[4 + i])) ue_cfg.imei[i] = ctypes.c_ubyte(int("1")) ue_cfg.imei[15] = ctypes.c_ubyte(int("1")) ue_cfg.imsiLen = self.IMSI_LEN self._ue_cfgs.append(ue_cfg) self._ue_id += 1 return ue_cfg def add_sub(self, num_ues=1): """ Add subscribers to the EPC, is blocking """ # Add the default IMSI used for the tests subscribers = [] for _ in range(num_ues): sid = self._gen_next_sid() self._subscriber_client.add_subscriber(sid) subscribers.append(self._get_s1ap_sub(sid)) self._subscriber_client.wait_for_changes() return subscribers def config_apn_data(self, imsi, apn_list): """ Add APN details """ self._subscriber_client.config_apn_details(imsi, apn_list) def cleanup(self): """ Cleanup added subscriber from subscriberdb """ self._subscriber_client.clean_up() # block until changes propagate self._subscriber_client.wait_for_changes() class MagmadUtil(object): stateless_cmds = Enum("stateless_cmds", "CHECK DISABLE ENABLE") config_update_cmds = Enum("config_update_cmds", "MODIFY RESTORE") apn_correction_cmds = Enum("apn_correction_cmds", "DISABLE ENABLE") health_service_cmds = Enum("health_service_cmds", "DISABLE ENABLE") def __init__(self, magmad_client): """ Init magmad util. Args: magmad_client: MagmadServiceClient """ self._magmad_client = magmad_client self._data = { "user": "vagrant", "host": "192.168.60.142", "password": "vagrant", "command": "test", } self._command = ( "sshpass -p {password} ssh " "-o UserKnownHostsFile=/dev/null " "-o StrictHostKeyChecking=no " "-o LogLevel=ERROR " "{user}@{host} {command}" ) def exec_command(self, command): """ Run a command remotely on magma_dev VM. Args: command: command (str) to be executed on remote host e.g. 'sed -i \'s/config1/config2/g\' /etc/magma/mme.yml' """ data = self._data data["command"] = '"' + command + '"' param_list = shlex.split(self._command.format(**data)) return subprocess.call( param_list, shell=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) def exec_command_output(self, command): """ Run a command remotely on magma_dev VM. Args: command: command (str) to be executed on remote host e.g. 'sed -i \'s/config1/config2/g\' /etc/magma/mme.yml' """ data = self._data data["command"] = '"' + command + '"' param_list = shlex.split(self._command.format(**data)) return subprocess.check_output( param_list, shell=False, ).decode("utf-8") def config_stateless(self, cmd): """ Configure the stateless mode on the access gateway Args: cmd: Specify how to configure stateless mode on AGW, should be one of check: Run a check whether AGW is stateless or not enable: Enable stateless mode, do nothing if already stateless disable: Disable stateless mode, do nothing if already stateful """ magtivate_cmd = "source /home/vagrant/build/python/bin/activate" venvsudo_cmd = "sudo -E PATH=$PATH PYTHONPATH=$PYTHONPATH env" config_stateless_script = "/usr/local/bin/config_stateless_agw.py" ret_code = self.exec_command( magtivate_cmd + " && " + venvsudo_cmd + " python3 " + config_stateless_script + " " + cmd.name.lower() ) if ret_code == 0: print("AGW is stateless") elif ret_code == 1: print("AGW is stateful") elif ret_code == 2: print("AGW is in a mixed config, check gateway") else: print("Unknown command") def corrupt_agw_state(self, key: str): """ Corrupts data on redis of stateless AGW Args: key: """ magtivate_cmd = "source /home/vagrant/build/python/bin/activate" state_corrupt_cmd = "state_cli.py corrupt %s" % key.lower() self.exec_command(magtivate_cmd + " && " + state_corrupt_cmd) print("Corrupted %s on redis" % key) def restart_all_services(self): """ Restart all magma services on magma_dev VM """ self.exec_command( "sudo service magma@* stop ; sudo service magma@magmad start" ) print( "Waiting for all services to restart. Sleeping for 60 seconds.." ) timeSlept = 0 while timeSlept < 60: time.sleep(5) timeSlept += 5 print("*********** Slept for " + str(timeSlept) + " seconds") def restart_services(self, services): """ Restart a list of magmad services. Args: services: List of (str) services names """ self._magmad_client.restart_services(services) def enable_service(self, service): """ Enables a magma service on magma_dev VM and starts it Args: service: (str) service to enable """ self.exec_command("sudo systemctl unmask magma@{}".format(service)) self.exec_command("sudo systemctl start magma@{}".format(service)) def disable_service(self, service): """ Disables a magma service on magma_dev VM, preventing from starting again Args: service: (str) service to disable """ self.exec_command("sudo systemctl mask magma@{}".format(service)) self.exec_command("sudo systemctl stop magma@{}".format(service)) def is_service_enabled(self, service) -> bool: """ Checks if a magma service on magma_dev VM is enabled Args: service: (str) service to disable """ is_enabled_service_cmd = "systemctl is-enabled magma@" + service try: result_str = self.exec_command_output(is_enabled_service_cmd) except subprocess.CalledProcessError as e: # if service is disabled / masked, is-enabled will return # non-zero exit status result_str = e.output if result_str in ("masked", "disabled"): return False return True def update_mme_config_for_sanity(self, cmd): mme_config_update_script = ( "/home/vagrant/magma/lte/gateway/deploy/roles/magma/files/" "update_mme_config_for_sanity.sh" ) action = cmd.name.lower() ret_code = self.exec_command( "sudo -E " + mme_config_update_script + " " + action ) if ret_code == 0: print("MME configuration is updated successfully") elif ret_code == 1: assert False, ( "Failed to " + action + " MME configuration. Error: Invalid command" ) elif ret_code == 2: assert False, ( "Failed to " + action + " MME configuration. Error: MME configuration file is " + "missing" ) elif ret_code == 3: assert False, ( "Failed to " + action + " MME configuration. Error: MME configuration's backup file " + "is missing" ) else: assert False, ( "Failed to " + action + " MME configuration. Error: Unknown error" ) def config_apn_correction(self, cmd): """ Configure the apn correction mode on the access gateway Args: cmd: Specify how to configure apn correction mode on AGW, should be one of enable: Enable apn correction feature, do nothing if already enabled disable: Disable apn correction feature, do nothing if already disabled """ apn_correction_cmd = "" if cmd.name == MagmadUtil.apn_correction_cmds.ENABLE.name: apn_correction_cmd = "sed -i \'s/enable_apn_correction: false/enable_apn_correction: true/g\' /etc/magma/mme.yml" else: apn_correction_cmd = "sed -i \'s/enable_apn_correction: true/enable_apn_correction: false/g\' /etc/magma/mme.yml" ret_code = self.exec_command( "sudo " + apn_correction_cmd) if ret_code == 0: print("APN Correction configured") else: print("APN Correction failed") def config_health_service(self, cmd: health_service_cmds): """ Configure magma@health service on access gateway Args: cmd: Enable / Disable cmd to configure service """ magma_health_service_name = "health" if cmd.name == MagmadUtil.health_service_cmds.DISABLE.name: if self.is_service_enabled(magma_health_service_name): self.disable_service(magma_health_service_name) print("Health service is disabled") elif cmd.name == MagmadUtil.health_service_cmds.ENABLE.name: if not self.is_service_enabled(magma_health_service_name): self.enable_service("health") print("Health service is enabled") def restart_mme_and_wait(self): print("Restarting mme service on gateway") self.restart_services(["mme"]) print("Waiting for mme to restart. 20 sec") time.sleep(20) def restart_sctpd(self): """ The Sctpd service is not managed by magmad, hence needs to be restarted explicitly """ self.exec_command( "sudo service sctpd restart" ) for j in range(30): print("Waiting for", 30-j, "seconds for restart to complete") time.sleep(1) def print_redis_state(self): """ Print the per-IMSI state in Redis data store on AGW """ magtivate_cmd = "source /home/vagrant/build/python/bin/activate" imsi_state_cmd = "state_cli.py keys IMSI*" redis_imsi_keys = self.exec_command_output( magtivate_cmd + " && " + imsi_state_cmd ) keys_to_be_cleaned = [] for key in redis_imsi_keys.split('\n'): # Ignore directoryd per-IMSI keys in this analysis as they will # persist after each test if "directory" not in key: keys_to_be_cleaned.append(key) mme_nas_state_cmd = "state_cli.py parse mme_nas_state" mme_nas_state = self.exec_command_output( magtivate_cmd + " && " + mme_nas_state_cmd ) num_htbl_entries = 0 for state in mme_nas_state.split("\n"): if "nb_enb_connected" in state or "nb_ue_attached" in state: keys_to_be_cleaned.append(state) elif "htbl" in state: num_htbl_entries += 1 print( "Keys left in Redis (list should be empty)[\n", "\n".join(keys_to_be_cleaned), "\n]" ) print("Entries left in hashtables (should be zero):", num_htbl_entries) class MobilityUtil(object): """ Utility wrapper for interacting with mobilityd """ def __init__(self, mobility_client): """ Initialize mobility util. Args: mobility_client (mobility_service_client.MobilityServiceClient): client interacting with our mobility APIs """ self._mobility_client = mobility_client def add_ip_block(self, ip_block): """ Add an ip block Args: ip_block (str | ipaddress.ip_network): the IP block to add """ ip_network_block = ipaddress.ip_network(ip_block) self._mobility_client.add_ip_block(ip_network_block) def remove_all_ip_blocks(self): """ Delete all allocated IP blocks. """ self._mobility_client.remove_all_ip_blocks() def get_subscriber_table(self): """ Retrieve subscriber table from mobilityd """ table = self._mobility_client.get_subscriber_ip_table() return table def list_ip_blocks(self): """ List all IP blocks in mobilityd """ blocks = self._mobility_client.list_added_blocks() return blocks def remove_ip_blocks(self, blocks): """ Attempt to remove the given blocks from mobilityd Args: blocks (tuple(ip_network)): tuple of ipaddress.ip_network objects representing the IP blocks to remove. Returns: removed_blocks (tuple(ip_network)): tuple of ipaddress.ip_netework objects representing the removed IP blocks. """ removed_blocks = self._mobility_client.remove_ip_blocks(blocks) return removed_blocks def cleanup(self): """ Cleanup added IP blocks """ blocks = self.list_ip_blocks() self.remove_ip_blocks(blocks) def wait_for_changes(self): self._mobility_client.wait_for_changes() class SpgwUtil(object): """ Helper class to communicate with spgw for the tests. """ def __init__(self): """ Initialize spgw util. """ self._stub = SpgwServiceStub(get_rpc_channel("spgw_service")) def create_bearer(self, imsi, lbi, qci_val=1, rule_id='1'): """ Sends a CreateBearer Request to SPGW service """ print("Sending CreateBearer request to spgw service") req = CreateBearerRequest( sid=SIDUtils.to_pb(imsi), link_bearer_id=lbi, policy_rules=[ PolicyRule( id="rar_rule_"+rule_id, qos=FlowQos( qci=qci_val, gbr_ul=10000000, gbr_dl=10000000, max_req_bw_ul=10000000, max_req_bw_dl=10000000, arp=QosArp( priority_level=1, pre_capability=1, pre_vulnerability=0, ), ), flow_list=[ FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV4, address="0.0.0.0/0".encode('utf-8')), tcp_dst=5001, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV4, address="192.168.129.42/24".encode('utf-8') ), tcp_dst=5002, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV4, address="192.168.129.42".encode('utf-8')), tcp_dst=5003, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV4, address="192.168.129.42".encode('utf-8')), tcp_dst=5004, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV4, address="192.168.129.42".encode('utf-8')), tcp_dst=5005, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.DENY, ), FlowDescription( match=FlowMatch( ip_src=IPAddress( version=IPAddress.IPV4, address="192.168.129.42".encode('utf-8')), tcp_src=5001, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_src=IPAddress(version=IPAddress.IPV4, address="".encode('utf-8')), tcp_dst=5002, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_src=IPAddress( version=IPAddress.IPV4, address="192.168.129.64/26".encode('utf-8') ), tcp_src=5003, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_src=IPAddress( version=IPAddress.IPV4, address="192.168.129.42/16".encode('utf-8') ), tcp_src=5004, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_src=IPAddress( version=IPAddress.IPV4, address="192.168.129.42".encode('utf-8')), tcp_src=5005, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.DENY, ), ], ) ], ) self._stub.CreateBearer(req) def create_bearer_ipv4v6( self, imsi, lbi, qci_val=1, ipv4=False, ipv6=False ): """ Sends a CreateBearer Request with ipv4/ipv6/ipv4v6 packet """ """ filters to SPGW service """ print("Sending CreateBearer request to spgw service") flow_match_list = [] if ipv4: flow_match_list.append( FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV4, address="192.168.129.42/24".encode("utf-8"), ), tcp_dst=5001, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.PERMIT, ) ) flow_match_list.append( FlowDescription( match=FlowMatch( ip_src=IPAddress( version=IPAddress.IPV4, address="192.168.129.42".encode("utf-8"), ), tcp_src=5001, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.PERMIT, ) ) if ipv6: flow_match_list.append( FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV6, address="5546:222:2259::226".encode("utf-8"), ), tcp_dst=5001, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.PERMIT, ) ) flow_match_list.append( FlowDescription( match=FlowMatch( ip_src=IPAddress( version=IPAddress.IPV6, address="fdee:0005:006c:018c::8c99".encode( "utf-8" ), ), tcp_src=5002, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.PERMIT, ) ) req = CreateBearerRequest( sid=SIDUtils.to_pb(imsi), link_bearer_id=lbi, policy_rules=[ PolicyRule( id="rar_rule_1", qos=FlowQos( qci=qci_val, gbr_ul=10000000, gbr_dl=10000000, max_req_bw_ul=10000000, max_req_bw_dl=10000000, arp=QosArp( priority_level=1, pre_capability=1, pre_vulnerability=0, ), ), flow_list=flow_match_list, ) ], ) self._stub.CreateBearer(req) def delete_bearer(self, imsi, lbi, ebi): """ Sends a DeleteBearer Request to SPGW service """ print("Sending DeleteBearer request to spgw service") req = DeleteBearerRequest( sid=SIDUtils.to_pb(imsi), link_bearer_id=lbi, eps_bearer_ids=[ebi] ) self._stub.DeleteBearer(req) def delete_bearers(self, imsi, lbi, ebi): """ Sends a DeleteBearer Request to SPGW service """ print("Sending DeleteBearer request to spgw service") req = DeleteBearerRequest( sid=SIDUtils.to_pb(imsi), link_bearer_id=lbi, eps_bearer_ids=ebi ) self._stub.DeleteBearer(req) class SessionManagerUtil(object): """ Helper class to communicate with session manager for the tests. """ def __init__(self): """ Initialize sessionManager util. """ self._session_proxy_stub = SessionProxyResponderStub( get_rpc_channel("sessiond") ) self._abort_session_stub = AbortSessionResponderStub( get_rpc_channel("abort_session_service") ) self._directorydstub = GatewayDirectoryServiceStub( get_rpc_channel("directoryd") ) self._local_session_manager_stub = LocalSessionManagerStub( get_rpc_channel("sessiond") ) def get_flow_match(self, flow_list, flow_match_list): """ Populates flow match list """ for flow in flow_list: flow_direction = flow["direction"] ip_protocol = flow["ip_proto"] if ip_protocol == FlowMatch.IPPROTO_TCP: udp_src_port = 0 udp_dst_port = 0 tcp_src_port = ( int(flow["tcp_src_port"]) if "tcp_src_port" in flow else 0 ) tcp_dst_port = ( int(flow["tcp_dst_port"]) if "tcp_dst_port" in flow else 0 ) elif ip_protocol == FlowMatch.IPPROTO_UDP: tcp_src_port = 0 tcp_dst_port = 0 udp_src_port = ( int(flow["udp_src_port"]) if "udp_src_port" in flow else 0 ) udp_dst_port = ( int(flow["udp_dst_port"]) if "udp_dst_port" in flow else 0 ) else: udp_src_port = 0 udp_dst_port = 0 tcp_src_port = 0 tcp_dst_port = 0 src_addr = None if flow.get("ipv4_src", None): src_addr = IPAddress( version=IPAddress.IPV4, address=flow.get("ipv4_src").encode('utf-8')) elif flow.get("ipv6_src", None): src_addr = IPAddress( version=IPAddress.IPV6, address=flow.get("ipv6_src").encode('utf-8')) dst_addr = None if flow.get("ipv4_dst", None): dst_addr = IPAddress( version=IPAddress.IPV4, address=flow.get("ipv4_dst").encode('utf-8')) elif flow.get("ipv6_dst", None): dst_addr = IPAddress( version=IPAddress.IPV6, address=flow.get("ipv6_dst").encode('utf-8')) flow_match_list.append( FlowDescription( match=FlowMatch( ip_dst=dst_addr, ip_src=src_addr, tcp_src=tcp_src_port, tcp_dst=tcp_dst_port, udp_src=udp_src_port, udp_dst=udp_dst_port, ip_proto=ip_protocol, direction=flow_direction, ), action=FlowDescription.PERMIT, ) ) def get_policy_rule(self, policy_id, qos=None, flow_match_list=None, he_urls=None): if qos is not None: policy_qos = FlowQos( qci=qos["qci"], max_req_bw_ul=qos["max_req_bw_ul"], max_req_bw_dl=qos["max_req_bw_dl"], gbr_ul=qos["gbr_ul"], gbr_dl=qos["gbr_dl"], arp=QosArp( priority_level=qos["arp_prio"], pre_capability=qos["pre_cap"], pre_vulnerability=qos["pre_vul"], ), ) priority = qos["priority"] else: policy_qos = None priority = 2 policy_rule = PolicyRule( id=policy_id, priority=priority, flow_list=flow_match_list, tracking_type=PolicyRule.NO_TRACKING, rating_group=1, monitoring_key=None, qos=policy_qos, he=he_urls, ) return policy_rule def send_ReAuthRequest(self, imsi, policy_id, flow_list, qos, he_urls=None): """ Sends Policy RAR message to session manager """ print("Sending Policy RAR message to session manager") flow_match_list = [] res = None self.get_flow_match(flow_list, flow_match_list) policy_rule = self.get_policy_rule(policy_id, qos, flow_match_list, he_urls) qos = QoSInformation(qci=qos["qci"]) # Get sessionid res = None req = GetDirectoryFieldRequest(id=imsi, field_key="session_id") try: res = self._directorydstub.GetDirectoryField( req, DEFAULT_GRPC_TIMEOUT ) except grpc.RpcError as err: print("error: GetDirectoryFieldRequest error for id: " "%s! [%s] %s" % (imsi, err.code(),err.details()) ) if res == None: print("error: Couldn't find sessionid. Directoryd content:") self._print_directoryd_content() self._session_proxy_stub.PolicyReAuth( PolicyReAuthRequest( session_id=res.value, imsi=imsi, rules_to_remove=[], rules_to_install=[], dynamic_rules_to_install=[ DynamicRuleInstall(policy_rule=policy_rule) ], event_triggers=[], revalidation_time=None, usage_monitoring_credits=[], qos_info=qos, ) ) def create_AbortSessionRequest(self, imsi: str) -> AbortSessionResult: # Get SessionID req = GetDirectoryFieldRequest(id=imsi, field_key="session_id") try: res = self._directorydstub.GetDirectoryField( req, DEFAULT_GRPC_TIMEOUT ) except grpc.RpcError as err: print("Error: GetDirectoryFieldRequest error for id: %s! [%s] %s" % (imsi, err.code(), err.details())) self._print_directoryd_content() return self._abort_session_stub.AbortSession( AbortSessionRequest( session_id=res.value, user_name=imsi, ) ) def _print_directoryd_content(self): try: allRecordsResponse = self._directorydstub.GetAllDirectoryRecords(Void(), DEFAULT_GRPC_TIMEOUT) except grpc.RpcError as e: print("error: couldnt print directoryd content. gRPC failed with %s: %s" % (e.code(), e.details())) return if allRecordsResponse is None: print("No records were found at directoryd") else: for record in allRecordsResponse.records: print("%s" % str(record)) def send_SetSessionRules(self, imsi, policy_id, flow_list, qos): """ Sends Policy SetSessionRules message to session manager """ print("Sending session rules to session manager") flow_match_list = [] self.get_flow_match(flow_list, flow_match_list) policy_rule = self.get_policy_rule(policy_id, qos, flow_match_list) ulFlow1 = { "ip_proto": FlowMatch.IPPROTO_IP, "direction": FlowMatch.UPLINK, # Direction } dlFlow1 = { "ip_proto": FlowMatch.IPPROTO_IP, "direction": FlowMatch.DOWNLINK, # Direction } default_flow_rules = [ulFlow1, dlFlow1] default_flow_match_list = [] self.get_flow_match(default_flow_rules, default_flow_match_list) default_policy_rule = self.get_policy_rule( "allow_list_" + imsi, None, default_flow_match_list) rule_set = RuleSet( apply_subscriber_wide = True, apn = "", static_rules = [], dynamic_rules = [ DynamicRuleInstall(policy_rule=policy_rule), DynamicRuleInstall(policy_rule=default_policy_rule) ], ) self._local_session_manager_stub.SetSessionRules( SessionRules( rules_per_subscriber = [ RulesPerSubscriber( imsi = imsi, rule_set = [rule_set], ) ] ) ) class GTPBridgeUtils: def __init__(self): self.magma_utils = MagmadUtil(None) ret = self.magma_utils.exec_command_output( "sudo grep ovs_multi_tunnel /etc/magma/spgw.yml" ) if "false" in ret: self.gtp_port_name = "gtp0" else: self.gtp_port_name = "g_8d3ca8c0" self.proxy_port = "proxy_port" def get_gtp_port_no(self) -> Optional[int]: output = self.magma_utils.exec_command_output( "sudo ovsdb-client dump Interface name ofport" ) for line in output.split("\n"): if self.gtp_port_name in line: port_info = line.split() return port_info[1] def get_proxy_port_no(self) -> Optional[int]: output = self.magma_utils.exec_command_output( "sudo ovsdb-client dump Interface name ofport" ) for line in output.split("\n"): if self.proxy_port in line: port_info = line.split() return port_info[1] # RYU rest API is not able dump flows from non zero table. # this adds similar API using `ovs-ofctl` cmd def get_flows(self, table_id) -> []: output = self.magma_utils.exec_command_output( "sudo ovs-ofctl dump-flows gtp_br0 table={}".format(table_id) ) return output.split("\n") class HaUtil: def __init__(self): self._ha_stub = HaServiceStub(get_rpc_channel("spgw_service")) def offload_agw(self, imsi, enbID, offloadtype=0): req = StartAgwOffloadRequest( enb_id=enbID, enb_offload_type=offloadtype, imsi=imsi, ) try: self._ha_stub.StartAgwOffload(req) except grpc.RpcError as e: print("gRPC failed with %s: %s" % (e.code(), e.details())) return False return True class HeaderEnrichmentUtils: def __init__(self): self.magma_utils = MagmadUtil(None) self.dump = None def restart_envoy_service(self): print("restarting envoy") self.magma_utils.exec_command_output("sudo service magma@envoy_controller restart") time.sleep(5) self.magma_utils.exec_command_output("sudo service magma_dp@envoy restart") time.sleep(20) print("restarting envoy done") def get_envoy_config(self): output = self.magma_utils.exec_command_output( "sudo ip netns exec envoy_ns1 curl 127.0.0.1:9000/config_dump") self.dump = json.loads(output) return self.dump def get_route_config(self): self.dump = self.get_envoy_config() for conf in self.dump['configs']: if 'dynamic_listeners' in conf: return conf['dynamic_listeners'][0]['active_state']['listener']['filter_chains'][0]['filters'] return [] def he_count_record_of_imsi_to_domain(self, imsi, domain) -> int: envoy_conf1 = self.get_route_config() cnt = 0 for conf in envoy_conf1: virtual_host_config = conf['typed_config']['route_config']['virtual_hosts'] for host_conf in virtual_host_config: if domain in host_conf['domains']: he_headers = host_conf['request_headers_to_add'] for hdr in he_headers: he_key = hdr['header']['key'] he_val = hdr['header']['value'] if he_key == 'imsi' and he_val == imsi: cnt = cnt + 1 return cnt
36.335206
125
0.530588
import ctypes import ipaddress import logging import os import shlex import threading import time from enum import Enum from queue import Queue from typing import Optional import grpc import subprocess import json import s1ap_types from integ_tests.gateway.rpc import get_rpc_channel from lte.protos.policydb_pb2 import ( FlowDescription, FlowMatch, FlowQos, PolicyRule, QosArp, ) from lte.protos.mobilityd_pb2 import IPAddress from lte.protos.session_manager_pb2 import ( DynamicRuleInstall, PolicyReAuthRequest, QoSInformation, RuleSet, RulesPerSubscriber, SessionRules, ) from lte.protos.abort_session_pb2 import ( AbortSessionRequest, AbortSessionResult, ) from lte.protos.spgw_service_pb2 import ( CreateBearerRequest, DeleteBearerRequest, ) from lte.protos.spgw_service_pb2_grpc import SpgwServiceStub from magma.subscriberdb.sid import SIDUtils from lte.protos.abort_session_pb2_grpc import AbortSessionResponderStub from lte.protos.session_manager_pb2_grpc import ( LocalSessionManagerStub, SessionProxyResponderStub, ) from orc8r.protos.directoryd_pb2 import GetDirectoryFieldRequest from orc8r.protos.directoryd_pb2_grpc import GatewayDirectoryServiceStub from integ_tests.s1aptests.ovs.rest_api import get_datapath, get_flows from lte.protos.ha_service_pb2_grpc import HaServiceStub from lte.protos.ha_service_pb2 import ( StartAgwOffloadRequest, EnbOffloadType, ) from orc8r.protos.common_pb2 import Void DEFAULT_GRPC_TIMEOUT = 10 class S1ApUtil(object): CM_ESM_PDN_IPV4 = 0b01 CM_ESM_PDN_IPV6 = 0b10 CM_ESM_PDN_IPV4V6 = 0b11 PROT_CFG_CID_PCSCF_IPV6_ADDR_REQUEST = 0x0001 PROT_CFG_CID_PCSCF_IPV4_ADDR_REQUEST = 0x000C PROT_CFG_CID_DNS_SERVER_IPV6_ADDR_REQUEST = 0x0003 lib_name = "libtfw.so" _cond = threading.Condition() _msg = Queue() MAX_NUM_RETRIES = 5 datapath = get_datapath() SPGW_TABLE = 0 LOCAL_PORT = "LOCAL" class Msg(object): def __init__(self, msg_type, msg_p, msg_len): self.msg_type = msg_type self.msg_p = ctypes.create_string_buffer(msg_len) ctypes.memmove(self.msg_p, msg_p, msg_len) self.msg_len = msg_len def cast(self, msg_class): return ctypes.cast(self.msg_p, ctypes.POINTER(msg_class)).contents @staticmethod def s1ap_callback(msg_type, msg_p, msg_len): with S1ApUtil._cond: S1ApUtil._msg.put(S1ApUtil.Msg(msg_type, msg_p, msg_len)) S1ApUtil._cond.notify_all() def __init__(self): self._imsi_idx = 1 self.IMSI_LEN = 15 lib_path = os.environ["S1AP_TESTER_ROOT"] lib = os.path.join(lib_path, "bin", S1ApUtil.lib_name) os.chdir(lib_path) self._test_lib = ctypes.cdll.LoadLibrary(lib) self._callback_type = ctypes.CFUNCTYPE( None, ctypes.c_short, ctypes.c_void_p, ctypes.c_short ) self._callback_fn = self._callback_type(S1ApUtil.s1ap_callback) self._test_lib.initTestFrameWork(self._callback_fn) self._test_api = self._test_lib.tfwApi self._test_api.restype = ctypes.c_int16 self._test_api.argtypes = [ctypes.c_uint16, ctypes.c_void_p] # Mutex for state change operations self._lock = threading.RLock() # Maintain a map of UE IDs to IPs self._ue_ip_map = {} self.gtpBridgeUtil = GTPBridgeUtils() def cleanup(self): # self._test_lib.dlclose(self._test_lib._handle) self._test_lib = None self._ue_ip_map = {} def issue_cmd(self, cmd_type, req): c_req = None if req: # For non NULL requests obtain the address. c_req = ctypes.byref(req) with self._cond: rc = self._test_api(cmd_type.value, c_req) if rc: print("Error executing command %s" % repr(cmd_type)) return rc return 0 def get_ip(self, ue_id): with self._lock: if ue_id in self._ue_ip_map: return self._ue_ip_map[ue_id] return None def get_response(self): # Wait until callback is invoked. return self._msg.get(True) def populate_pco( self, protCfgOpts_pr, pcscf_addr_type=None, dns_ipv6_addr=False ): # PCO parameters # Presence mask protCfgOpts_pr.pres = 1 # Length protCfgOpts_pr.len = 4 # Configuration protocol protCfgOpts_pr.cfgProt = 0 # Extension bit for the additional parameters protCfgOpts_pr.ext = 1 # Number of protocol IDs protCfgOpts_pr.numProtId = 0 # Fill Number of container IDs and Container ID idx = 0 if pcscf_addr_type == "ipv4": protCfgOpts_pr.numContId += 1 protCfgOpts_pr.c[ idx ].cid = S1ApUtil.PROT_CFG_CID_PCSCF_IPV4_ADDR_REQUEST idx += 1 elif pcscf_addr_type == "ipv6": protCfgOpts_pr.numContId += 1 protCfgOpts_pr.c[ idx ].cid = S1ApUtil.PROT_CFG_CID_PCSCF_IPV6_ADDR_REQUEST idx += 1 elif pcscf_addr_type == "ipv4v6": protCfgOpts_pr.numContId += 2 protCfgOpts_pr.c[ idx ].cid = S1ApUtil.PROT_CFG_CID_PCSCF_IPV4_ADDR_REQUEST idx += 1 protCfgOpts_pr.c[ idx ].cid = S1ApUtil.PROT_CFG_CID_PCSCF_IPV6_ADDR_REQUEST idx += 1 if dns_ipv6_addr: protCfgOpts_pr.numContId += 1 protCfgOpts_pr.c[ idx ].cid = S1ApUtil.PROT_CFG_CID_DNS_SERVER_IPV6_ADDR_REQUEST def attach( self, ue_id, attach_type, resp_type, resp_msg_type, sec_ctxt=s1ap_types.TFW_CREATE_NEW_SECURITY_CONTEXT, id_type=s1ap_types.TFW_MID_TYPE_IMSI, eps_type=s1ap_types.TFW_EPS_ATTACH_TYPE_EPS_ATTACH, pdn_type=1, pcscf_addr_type=None, dns_ipv6_addr=False, ): attach_req = s1ap_types.ueAttachRequest_t() attach_req.ue_Id = ue_id attach_req.mIdType = id_type attach_req.epsAttachType = eps_type attach_req.useOldSecCtxt = sec_ctxt attach_req.pdnType_pr.pres = True attach_req.pdnType_pr.pdn_type = pdn_type # Populate PCO only if pcscf_addr_type is set if pcscf_addr_type or dns_ipv6_addr: self.populate_pco( attach_req.protCfgOpts_pr, pcscf_addr_type, dns_ipv6_addr ) assert self.issue_cmd(attach_type, attach_req) == 0 response = self.get_response() # The MME actually sends INT_CTX_SETUP_IND and UE_ATTACH_ACCEPT_IND in # one message, but the s1aptester splits it and sends the tests 2 # messages. Usually context setup comes before attach accept, but # it's possible it may happen the other way if s1ap_types.tfwCmd.INT_CTX_SETUP_IND.value == response.msg_type: response = self.get_response() elif s1ap_types.tfwCmd.UE_ATTACH_ACCEPT_IND.value == response.msg_type: context_setup = self.get_response() assert ( context_setup.msg_type == s1ap_types.tfwCmd.INT_CTX_SETUP_IND.value ) logging.debug( "s1ap response expected, received: %d, %d", resp_type.value, response.msg_type, ) assert resp_type.value == response.msg_type msg = response.cast(resp_msg_type) if resp_msg_type == s1ap_types.ueAttachAccept_t: pdn_type = msg.esmInfo.pAddr.pdnType addr = msg.esmInfo.pAddr.addrInfo if S1ApUtil.CM_ESM_PDN_IPV4 == pdn_type: ip = ipaddress.ip_address(bytes(addr[:4])) with self._lock: self._ue_ip_map[ue_id] = ip elif S1ApUtil.CM_ESM_PDN_IPV6 == pdn_type: print("IPv6 PDN type received") elif S1ApUtil.CM_ESM_PDN_IPV4V6 == pdn_type: print("IPv4v6 PDN type received") return msg def receive_emm_info(self): response = self.get_response() logging.debug( "s1ap message expected, received: %d, %d", s1ap_types.tfwCmd.UE_EMM_INFORMATION.value, response.msg_type, ) assert response.msg_type == s1ap_types.tfwCmd.UE_EMM_INFORMATION.value def detach(self, ue_id, reason_type, wait_for_s1_ctxt_release=True): detach_req = s1ap_types.uedetachReq_t() detach_req.ue_Id = ue_id detach_req.ueDetType = reason_type assert ( self.issue_cmd(s1ap_types.tfwCmd.UE_DETACH_REQUEST, detach_req) == 0 ) if reason_type == s1ap_types.ueDetachType_t.UE_NORMAL_DETACH.value: response = self.get_response() assert ( s1ap_types.tfwCmd.UE_DETACH_ACCEPT_IND.value == response.msg_type ) if wait_for_s1_ctxt_release: response = self.get_response() assert s1ap_types.tfwCmd.UE_CTX_REL_IND.value == response.msg_type with self._lock: del self._ue_ip_map[ue_id] def _verify_dl_flow(self, dl_flow_rules=None): num_dl_flows = 1 for key, value in dl_flow_rules.items(): tcp_src_port = 0 ip_proto = 0 ue_ip6_str = None ue_ip_str = str(key) if key.version == 6: ue_ip6_str = ipaddress.ip_network( (ue_ip_str + "/64"), strict=False ).with_netmask ue_ip_addr = ue_ip6_str if key.version == 6 else ue_ip_str dst_addr = "nw_dst" if key.version == 4 else "ipv6_dst" key_to_be_matched = "ipv4_src" if key.version == 4 else "ipv6_src" eth_typ = 2048 if key.version == 4 else 34525 total_num_dl_flows_to_be_verified = 1 for item in value: for flow in item: if ( flow["direction"] == FlowMatch.DOWNLINK and key_to_be_matched in flow ): total_num_dl_flows_to_be_verified += 1 total_dl_ovs_flows_created = get_flows( self.datapath, { "table_id": self.SPGW_TABLE, "match": { dst_addr: ue_ip_addr, "eth_type": eth_typ, "in_port": self.LOCAL_PORT, }, }, ) assert ( len(total_dl_ovs_flows_created) == total_num_dl_flows_to_be_verified ) for item in value: for flow in item: if ( flow["direction"] == FlowMatch.DOWNLINK and key_to_be_matched in flow ): ip_src_addr = flow[key_to_be_matched] ip_src = "ipv4_src" if key.version == 4 else "ipv6_src" ip_dst = "ipv4_dst" if key.version == 4 else "ipv6_dst" tcp_src_port = flow["tcp_src_port"] ip_proto = flow["ip_proto"] for i in range(self.MAX_NUM_RETRIES): print("Get downlink flows: attempt ", i) downlink_flows = get_flows( self.datapath, { "table_id": self.SPGW_TABLE, "match": { ip_dst: ue_ip_addr, "eth_type": eth_typ, "in_port": self.LOCAL_PORT, ip_src: ip_src_addr, "tcp_src": tcp_src_port, "ip_proto": ip_proto, }, }, ) if len(downlink_flows) >= num_dl_flows: break time.sleep( 5 ) assert ( len(downlink_flows) >= num_dl_flows ), "Downlink flow missing for UE" assert downlink_flows[0]["match"][ip_dst] == ue_ip_addr actions = downlink_flows[0]["instructions"][0][ "actions" ] has_tunnel_action = any( action for action in actions if action["field"] == "tunnel_id" and action["type"] == "SET_FIELD" ) assert bool(has_tunnel_action) def verify_flow_rules(self, num_ul_flows, dl_flow_rules=None): GTP_PORT = self.gtpBridgeUtil.get_gtp_port_no() print("************ Verifying flow rules") print("Checking for uplink flow") for i in range(self.MAX_NUM_RETRIES): print("Get uplink flows: attempt ", i) uplink_flows = get_flows( self.datapath, { "table_id": self.SPGW_TABLE, "match": { "in_port": GTP_PORT, } }, ) if len(uplink_flows) == num_ul_flows: break time.sleep(5) assert len(uplink_flows) == num_ul_flows,\ "Uplink flow missing for UE: %d !=" % (len(uplink_flows), num_ul_flows) assert uplink_flows[0]["match"]["tunnel_id"] is not None print("Checking for downlink flow") self._verify_dl_flow(dl_flow_rules) def verify_paging_flow_rules(self, ip_list): print("************ Verifying paging flow rules") num_paging_flows_to_be_verified = 1 for ip in ip_list: ue_ip_str = str(ip) print("Verifying paging flow for ip", ue_ip_str) for i in range(self.MAX_NUM_RETRIES): print("Get paging flows: attempt ", i) paging_flows = get_flows( self.datapath, { "table_id": self.SPGW_TABLE, "match": { "nw_dst": ue_ip_str, "eth_type": 2048, "priority": 5, }, }, ) if len(paging_flows) == num_paging_flows_to_be_verified: break time.sleep(5) assert ( len(paging_flows) == num_paging_flows_to_be_verified ), "Paging flow missing for UE" def generate_imsi(self, prefix=None): assert (prefix is not None), "IMSI prefix is empty" idx = str(self._imsi_idx) padding = self.IMSI_LEN - len(idx) - len(prefix[4:]) imsi = prefix + "0" * padding + idx assert(len(imsi[4:]) == self.IMSI_LEN), "Invalid IMSI length" self._imsi_idx += 1 print("Using subscriber IMSI %s" % imsi) return imsi class SubscriberUtil(object): SID_PREFIX = "IMSI00101" IMSI_LEN = 15 def __init__(self, subscriber_client): self._sid_idx = 1 self._ue_id = 1 self._ue_cfgs = [] self._subscriber_client = subscriber_client def _gen_next_sid(self): idx = str(self._sid_idx) padding = self.IMSI_LEN - len(idx) - len(self.SID_PREFIX[4:]) sid = self.SID_PREFIX + "0" * padding + idx self._sid_idx += 1 print("Using subscriber IMSI %s" % sid) return sid def _get_s1ap_sub(self, sid): ue_cfg = s1ap_types.ueConfig_t() ue_cfg.ue_id = self._ue_id ue_cfg.auth_key = 1 for i in range(0, 15): ue_cfg.imsi[i] = ctypes.c_ubyte(int(sid[4 + i])) ue_cfg.imei[i] = ctypes.c_ubyte(int("1")) ue_cfg.imei[15] = ctypes.c_ubyte(int("1")) ue_cfg.imsiLen = self.IMSI_LEN self._ue_cfgs.append(ue_cfg) self._ue_id += 1 return ue_cfg def add_sub(self, num_ues=1): subscribers = [] for _ in range(num_ues): sid = self._gen_next_sid() self._subscriber_client.add_subscriber(sid) subscribers.append(self._get_s1ap_sub(sid)) self._subscriber_client.wait_for_changes() return subscribers def config_apn_data(self, imsi, apn_list): self._subscriber_client.config_apn_details(imsi, apn_list) def cleanup(self): self._subscriber_client.clean_up() self._subscriber_client.wait_for_changes() class MagmadUtil(object): stateless_cmds = Enum("stateless_cmds", "CHECK DISABLE ENABLE") config_update_cmds = Enum("config_update_cmds", "MODIFY RESTORE") apn_correction_cmds = Enum("apn_correction_cmds", "DISABLE ENABLE") health_service_cmds = Enum("health_service_cmds", "DISABLE ENABLE") def __init__(self, magmad_client): self._magmad_client = magmad_client self._data = { "user": "vagrant", "host": "192.168.60.142", "password": "vagrant", "command": "test", } self._command = ( "sshpass -p {password} ssh " "-o UserKnownHostsFile=/dev/null " "-o StrictHostKeyChecking=no " "-o LogLevel=ERROR " "{user}@{host} {command}" ) def exec_command(self, command): data = self._data data["command"] = '"' + command + '"' param_list = shlex.split(self._command.format(**data)) return subprocess.call( param_list, shell=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) def exec_command_output(self, command): data = self._data data["command"] = '"' + command + '"' param_list = shlex.split(self._command.format(**data)) return subprocess.check_output( param_list, shell=False, ).decode("utf-8") def config_stateless(self, cmd): magtivate_cmd = "source /home/vagrant/build/python/bin/activate" venvsudo_cmd = "sudo -E PATH=$PATH PYTHONPATH=$PYTHONPATH env" config_stateless_script = "/usr/local/bin/config_stateless_agw.py" ret_code = self.exec_command( magtivate_cmd + " && " + venvsudo_cmd + " python3 " + config_stateless_script + " " + cmd.name.lower() ) if ret_code == 0: print("AGW is stateless") elif ret_code == 1: print("AGW is stateful") elif ret_code == 2: print("AGW is in a mixed config, check gateway") else: print("Unknown command") def corrupt_agw_state(self, key: str): magtivate_cmd = "source /home/vagrant/build/python/bin/activate" state_corrupt_cmd = "state_cli.py corrupt %s" % key.lower() self.exec_command(magtivate_cmd + " && " + state_corrupt_cmd) print("Corrupted %s on redis" % key) def restart_all_services(self): self.exec_command( "sudo service magma@* stop ; sudo service magma@magmad start" ) print( "Waiting for all services to restart. Sleeping for 60 seconds.." ) timeSlept = 0 while timeSlept < 60: time.sleep(5) timeSlept += 5 print("*********** Slept for " + str(timeSlept) + " seconds") def restart_services(self, services): self._magmad_client.restart_services(services) def enable_service(self, service): self.exec_command("sudo systemctl unmask magma@{}".format(service)) self.exec_command("sudo systemctl start magma@{}".format(service)) def disable_service(self, service): self.exec_command("sudo systemctl mask magma@{}".format(service)) self.exec_command("sudo systemctl stop magma@{}".format(service)) def is_service_enabled(self, service) -> bool: is_enabled_service_cmd = "systemctl is-enabled magma@" + service try: result_str = self.exec_command_output(is_enabled_service_cmd) except subprocess.CalledProcessError as e: result_str = e.output if result_str in ("masked", "disabled"): return False return True def update_mme_config_for_sanity(self, cmd): mme_config_update_script = ( "/home/vagrant/magma/lte/gateway/deploy/roles/magma/files/" "update_mme_config_for_sanity.sh" ) action = cmd.name.lower() ret_code = self.exec_command( "sudo -E " + mme_config_update_script + " " + action ) if ret_code == 0: print("MME configuration is updated successfully") elif ret_code == 1: assert False, ( "Failed to " + action + " MME configuration. Error: Invalid command" ) elif ret_code == 2: assert False, ( "Failed to " + action + " MME configuration. Error: MME configuration file is " + "missing" ) elif ret_code == 3: assert False, ( "Failed to " + action + " MME configuration. Error: MME configuration's backup file " + "is missing" ) else: assert False, ( "Failed to " + action + " MME configuration. Error: Unknown error" ) def config_apn_correction(self, cmd): apn_correction_cmd = "" if cmd.name == MagmadUtil.apn_correction_cmds.ENABLE.name: apn_correction_cmd = "sed -i \'s/enable_apn_correction: false/enable_apn_correction: true/g\' /etc/magma/mme.yml" else: apn_correction_cmd = "sed -i \'s/enable_apn_correction: true/enable_apn_correction: false/g\' /etc/magma/mme.yml" ret_code = self.exec_command( "sudo " + apn_correction_cmd) if ret_code == 0: print("APN Correction configured") else: print("APN Correction failed") def config_health_service(self, cmd: health_service_cmds): magma_health_service_name = "health" if cmd.name == MagmadUtil.health_service_cmds.DISABLE.name: if self.is_service_enabled(magma_health_service_name): self.disable_service(magma_health_service_name) print("Health service is disabled") elif cmd.name == MagmadUtil.health_service_cmds.ENABLE.name: if not self.is_service_enabled(magma_health_service_name): self.enable_service("health") print("Health service is enabled") def restart_mme_and_wait(self): print("Restarting mme service on gateway") self.restart_services(["mme"]) print("Waiting for mme to restart. 20 sec") time.sleep(20) def restart_sctpd(self): self.exec_command( "sudo service sctpd restart" ) for j in range(30): print("Waiting for", 30-j, "seconds for restart to complete") time.sleep(1) def print_redis_state(self): magtivate_cmd = "source /home/vagrant/build/python/bin/activate" imsi_state_cmd = "state_cli.py keys IMSI*" redis_imsi_keys = self.exec_command_output( magtivate_cmd + " && " + imsi_state_cmd ) keys_to_be_cleaned = [] for key in redis_imsi_keys.split('\n'): # Ignore directoryd per-IMSI keys in this analysis as they will # persist after each test if "directory" not in key: keys_to_be_cleaned.append(key) mme_nas_state_cmd = "state_cli.py parse mme_nas_state" mme_nas_state = self.exec_command_output( magtivate_cmd + " && " + mme_nas_state_cmd ) num_htbl_entries = 0 for state in mme_nas_state.split("\n"): if "nb_enb_connected" in state or "nb_ue_attached" in state: keys_to_be_cleaned.append(state) elif "htbl" in state: num_htbl_entries += 1 print( "Keys left in Redis (list should be empty)[\n", "\n".join(keys_to_be_cleaned), "\n]" ) print("Entries left in hashtables (should be zero):", num_htbl_entries) class MobilityUtil(object): def __init__(self, mobility_client): self._mobility_client = mobility_client def add_ip_block(self, ip_block): ip_network_block = ipaddress.ip_network(ip_block) self._mobility_client.add_ip_block(ip_network_block) def remove_all_ip_blocks(self): self._mobility_client.remove_all_ip_blocks() def get_subscriber_table(self): table = self._mobility_client.get_subscriber_ip_table() return table def list_ip_blocks(self): blocks = self._mobility_client.list_added_blocks() return blocks def remove_ip_blocks(self, blocks): removed_blocks = self._mobility_client.remove_ip_blocks(blocks) return removed_blocks def cleanup(self): blocks = self.list_ip_blocks() self.remove_ip_blocks(blocks) def wait_for_changes(self): self._mobility_client.wait_for_changes() class SpgwUtil(object): def __init__(self): self._stub = SpgwServiceStub(get_rpc_channel("spgw_service")) def create_bearer(self, imsi, lbi, qci_val=1, rule_id='1'): print("Sending CreateBearer request to spgw service") req = CreateBearerRequest( sid=SIDUtils.to_pb(imsi), link_bearer_id=lbi, policy_rules=[ PolicyRule( id="rar_rule_"+rule_id, qos=FlowQos( qci=qci_val, gbr_ul=10000000, gbr_dl=10000000, max_req_bw_ul=10000000, max_req_bw_dl=10000000, arp=QosArp( priority_level=1, pre_capability=1, pre_vulnerability=0, ), ), flow_list=[ FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV4, address="0.0.0.0/0".encode('utf-8')), tcp_dst=5001, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV4, address="192.168.129.42/24".encode('utf-8') ), tcp_dst=5002, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV4, address="192.168.129.42".encode('utf-8')), tcp_dst=5003, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV4, address="192.168.129.42".encode('utf-8')), tcp_dst=5004, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV4, address="192.168.129.42".encode('utf-8')), tcp_dst=5005, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.DENY, ), FlowDescription( match=FlowMatch( ip_src=IPAddress( version=IPAddress.IPV4, address="192.168.129.42".encode('utf-8')), tcp_src=5001, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_src=IPAddress(version=IPAddress.IPV4, address="".encode('utf-8')), tcp_dst=5002, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_src=IPAddress( version=IPAddress.IPV4, address="192.168.129.64/26".encode('utf-8') ), tcp_src=5003, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_src=IPAddress( version=IPAddress.IPV4, address="192.168.129.42/16".encode('utf-8') ), tcp_src=5004, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.PERMIT, ), FlowDescription( match=FlowMatch( ip_src=IPAddress( version=IPAddress.IPV4, address="192.168.129.42".encode('utf-8')), tcp_src=5005, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.DENY, ), ], ) ], ) self._stub.CreateBearer(req) def create_bearer_ipv4v6( self, imsi, lbi, qci_val=1, ipv4=False, ipv6=False ): print("Sending CreateBearer request to spgw service") flow_match_list = [] if ipv4: flow_match_list.append( FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV4, address="192.168.129.42/24".encode("utf-8"), ), tcp_dst=5001, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.PERMIT, ) ) flow_match_list.append( FlowDescription( match=FlowMatch( ip_src=IPAddress( version=IPAddress.IPV4, address="192.168.129.42".encode("utf-8"), ), tcp_src=5001, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.PERMIT, ) ) if ipv6: flow_match_list.append( FlowDescription( match=FlowMatch( ip_dst=IPAddress( version=IPAddress.IPV6, address="5546:222:2259::226".encode("utf-8"), ), tcp_dst=5001, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.UPLINK, ), action=FlowDescription.PERMIT, ) ) flow_match_list.append( FlowDescription( match=FlowMatch( ip_src=IPAddress( version=IPAddress.IPV6, address="fdee:0005:006c:018c::8c99".encode( "utf-8" ), ), tcp_src=5002, ip_proto=FlowMatch.IPPROTO_TCP, direction=FlowMatch.DOWNLINK, ), action=FlowDescription.PERMIT, ) ) req = CreateBearerRequest( sid=SIDUtils.to_pb(imsi), link_bearer_id=lbi, policy_rules=[ PolicyRule( id="rar_rule_1", qos=FlowQos( qci=qci_val, gbr_ul=10000000, gbr_dl=10000000, max_req_bw_ul=10000000, max_req_bw_dl=10000000, arp=QosArp( priority_level=1, pre_capability=1, pre_vulnerability=0, ), ), flow_list=flow_match_list, ) ], ) self._stub.CreateBearer(req) def delete_bearer(self, imsi, lbi, ebi): print("Sending DeleteBearer request to spgw service") req = DeleteBearerRequest( sid=SIDUtils.to_pb(imsi), link_bearer_id=lbi, eps_bearer_ids=[ebi] ) self._stub.DeleteBearer(req) def delete_bearers(self, imsi, lbi, ebi): print("Sending DeleteBearer request to spgw service") req = DeleteBearerRequest( sid=SIDUtils.to_pb(imsi), link_bearer_id=lbi, eps_bearer_ids=ebi ) self._stub.DeleteBearer(req) class SessionManagerUtil(object): def __init__(self): self._session_proxy_stub = SessionProxyResponderStub( get_rpc_channel("sessiond") ) self._abort_session_stub = AbortSessionResponderStub( get_rpc_channel("abort_session_service") ) self._directorydstub = GatewayDirectoryServiceStub( get_rpc_channel("directoryd") ) self._local_session_manager_stub = LocalSessionManagerStub( get_rpc_channel("sessiond") ) def get_flow_match(self, flow_list, flow_match_list): for flow in flow_list: flow_direction = flow["direction"] ip_protocol = flow["ip_proto"] if ip_protocol == FlowMatch.IPPROTO_TCP: udp_src_port = 0 udp_dst_port = 0 tcp_src_port = ( int(flow["tcp_src_port"]) if "tcp_src_port" in flow else 0 ) tcp_dst_port = ( int(flow["tcp_dst_port"]) if "tcp_dst_port" in flow else 0 ) elif ip_protocol == FlowMatch.IPPROTO_UDP: tcp_src_port = 0 tcp_dst_port = 0 udp_src_port = ( int(flow["udp_src_port"]) if "udp_src_port" in flow else 0 ) udp_dst_port = ( int(flow["udp_dst_port"]) if "udp_dst_port" in flow else 0 ) else: udp_src_port = 0 udp_dst_port = 0 tcp_src_port = 0 tcp_dst_port = 0 src_addr = None if flow.get("ipv4_src", None): src_addr = IPAddress( version=IPAddress.IPV4, address=flow.get("ipv4_src").encode('utf-8')) elif flow.get("ipv6_src", None): src_addr = IPAddress( version=IPAddress.IPV6, address=flow.get("ipv6_src").encode('utf-8')) dst_addr = None if flow.get("ipv4_dst", None): dst_addr = IPAddress( version=IPAddress.IPV4, address=flow.get("ipv4_dst").encode('utf-8')) elif flow.get("ipv6_dst", None): dst_addr = IPAddress( version=IPAddress.IPV6, address=flow.get("ipv6_dst").encode('utf-8')) flow_match_list.append( FlowDescription( match=FlowMatch( ip_dst=dst_addr, ip_src=src_addr, tcp_src=tcp_src_port, tcp_dst=tcp_dst_port, udp_src=udp_src_port, udp_dst=udp_dst_port, ip_proto=ip_protocol, direction=flow_direction, ), action=FlowDescription.PERMIT, ) ) def get_policy_rule(self, policy_id, qos=None, flow_match_list=None, he_urls=None): if qos is not None: policy_qos = FlowQos( qci=qos["qci"], max_req_bw_ul=qos["max_req_bw_ul"], max_req_bw_dl=qos["max_req_bw_dl"], gbr_ul=qos["gbr_ul"], gbr_dl=qos["gbr_dl"], arp=QosArp( priority_level=qos["arp_prio"], pre_capability=qos["pre_cap"], pre_vulnerability=qos["pre_vul"], ), ) priority = qos["priority"] else: policy_qos = None priority = 2 policy_rule = PolicyRule( id=policy_id, priority=priority, flow_list=flow_match_list, tracking_type=PolicyRule.NO_TRACKING, rating_group=1, monitoring_key=None, qos=policy_qos, he=he_urls, ) return policy_rule def send_ReAuthRequest(self, imsi, policy_id, flow_list, qos, he_urls=None): print("Sending Policy RAR message to session manager") flow_match_list = [] res = None self.get_flow_match(flow_list, flow_match_list) policy_rule = self.get_policy_rule(policy_id, qos, flow_match_list, he_urls) qos = QoSInformation(qci=qos["qci"]) # Get sessionid res = None req = GetDirectoryFieldRequest(id=imsi, field_key="session_id") try: res = self._directorydstub.GetDirectoryField( req, DEFAULT_GRPC_TIMEOUT ) except grpc.RpcError as err: print("error: GetDirectoryFieldRequest error for id: " "%s! [%s] %s" % (imsi, err.code(),err.details()) ) if res == None: print("error: Couldn't find sessionid. Directoryd content:") self._print_directoryd_content() self._session_proxy_stub.PolicyReAuth( PolicyReAuthRequest( session_id=res.value, imsi=imsi, rules_to_remove=[], rules_to_install=[], dynamic_rules_to_install=[ DynamicRuleInstall(policy_rule=policy_rule) ], event_triggers=[], revalidation_time=None, usage_monitoring_credits=[], qos_info=qos, ) ) def create_AbortSessionRequest(self, imsi: str) -> AbortSessionResult: req = GetDirectoryFieldRequest(id=imsi, field_key="session_id") try: res = self._directorydstub.GetDirectoryField( req, DEFAULT_GRPC_TIMEOUT ) except grpc.RpcError as err: print("Error: GetDirectoryFieldRequest error for id: %s! [%s] %s" % (imsi, err.code(), err.details())) self._print_directoryd_content() return self._abort_session_stub.AbortSession( AbortSessionRequest( session_id=res.value, user_name=imsi, ) ) def _print_directoryd_content(self): try: allRecordsResponse = self._directorydstub.GetAllDirectoryRecords(Void(), DEFAULT_GRPC_TIMEOUT) except grpc.RpcError as e: print("error: couldnt print directoryd content. gRPC failed with %s: %s" % (e.code(), e.details())) return if allRecordsResponse is None: print("No records were found at directoryd") else: for record in allRecordsResponse.records: print("%s" % str(record)) def send_SetSessionRules(self, imsi, policy_id, flow_list, qos): print("Sending session rules to session manager") flow_match_list = [] self.get_flow_match(flow_list, flow_match_list) policy_rule = self.get_policy_rule(policy_id, qos, flow_match_list) ulFlow1 = { "ip_proto": FlowMatch.IPPROTO_IP, "direction": FlowMatch.UPLINK, } dlFlow1 = { "ip_proto": FlowMatch.IPPROTO_IP, "direction": FlowMatch.DOWNLINK, } default_flow_rules = [ulFlow1, dlFlow1] default_flow_match_list = [] self.get_flow_match(default_flow_rules, default_flow_match_list) default_policy_rule = self.get_policy_rule( "allow_list_" + imsi, None, default_flow_match_list) rule_set = RuleSet( apply_subscriber_wide = True, apn = "", static_rules = [], dynamic_rules = [ DynamicRuleInstall(policy_rule=policy_rule), DynamicRuleInstall(policy_rule=default_policy_rule) ], ) self._local_session_manager_stub.SetSessionRules( SessionRules( rules_per_subscriber = [ RulesPerSubscriber( imsi = imsi, rule_set = [rule_set], ) ] ) ) class GTPBridgeUtils: def __init__(self): self.magma_utils = MagmadUtil(None) ret = self.magma_utils.exec_command_output( "sudo grep ovs_multi_tunnel /etc/magma/spgw.yml" ) if "false" in ret: self.gtp_port_name = "gtp0" else: self.gtp_port_name = "g_8d3ca8c0" self.proxy_port = "proxy_port" def get_gtp_port_no(self) -> Optional[int]: output = self.magma_utils.exec_command_output( "sudo ovsdb-client dump Interface name ofport" ) for line in output.split("\n"): if self.gtp_port_name in line: port_info = line.split() return port_info[1] def get_proxy_port_no(self) -> Optional[int]: output = self.magma_utils.exec_command_output( "sudo ovsdb-client dump Interface name ofport" ) for line in output.split("\n"): if self.proxy_port in line: port_info = line.split() return port_info[1] def get_flows(self, table_id) -> []: output = self.magma_utils.exec_command_output( "sudo ovs-ofctl dump-flows gtp_br0 table={}".format(table_id) ) return output.split("\n") class HaUtil: def __init__(self): self._ha_stub = HaServiceStub(get_rpc_channel("spgw_service")) def offload_agw(self, imsi, enbID, offloadtype=0): req = StartAgwOffloadRequest( enb_id=enbID, enb_offload_type=offloadtype, imsi=imsi, ) try: self._ha_stub.StartAgwOffload(req) except grpc.RpcError as e: print("gRPC failed with %s: %s" % (e.code(), e.details())) return False return True class HeaderEnrichmentUtils: def __init__(self): self.magma_utils = MagmadUtil(None) self.dump = None def restart_envoy_service(self): print("restarting envoy") self.magma_utils.exec_command_output("sudo service magma@envoy_controller restart") time.sleep(5) self.magma_utils.exec_command_output("sudo service magma_dp@envoy restart") time.sleep(20) print("restarting envoy done") def get_envoy_config(self): output = self.magma_utils.exec_command_output( "sudo ip netns exec envoy_ns1 curl 127.0.0.1:9000/config_dump") self.dump = json.loads(output) return self.dump def get_route_config(self): self.dump = self.get_envoy_config() for conf in self.dump['configs']: if 'dynamic_listeners' in conf: return conf['dynamic_listeners'][0]['active_state']['listener']['filter_chains'][0]['filters'] return [] def he_count_record_of_imsi_to_domain(self, imsi, domain) -> int: envoy_conf1 = self.get_route_config() cnt = 0 for conf in envoy_conf1: virtual_host_config = conf['typed_config']['route_config']['virtual_hosts'] for host_conf in virtual_host_config: if domain in host_conf['domains']: he_headers = host_conf['request_headers_to_add'] for hdr in he_headers: he_key = hdr['header']['key'] he_val = hdr['header']['value'] if he_key == 'imsi' and he_val == imsi: cnt = cnt + 1 return cnt
true
true
1c2c1d7890efc23e0bdea96dce3259aa992eba31
99,719
py
Python
ai4water/preprocessing/datahandler.py
csiro-hydroinformatics/AI4Water
cdb18bd4bf298f77b381f1829045a1e790146985
[ "MIT" ]
12
2020-10-13T08:23:17.000Z
2021-01-22T04:36:21.000Z
ai4water/preprocessing/datahandler.py
csiro-hydroinformatics/AI4Water
cdb18bd4bf298f77b381f1829045a1e790146985
[ "MIT" ]
1
2020-10-15T02:42:52.000Z
2020-10-15T02:51:07.000Z
ai4water/preprocessing/datahandler.py
csiro-hydroinformatics/AI4Water
cdb18bd4bf298f77b381f1829045a1e790146985
[ "MIT" ]
2
2020-11-23T04:45:38.000Z
2020-11-26T10:12:34.000Z
import os import copy import json import warnings from typing import Union, Tuple import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.patches import Patch from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold, LeaveOneOut, TimeSeriesSplit from sklearn.preprocessing import OneHotEncoder from ai4water.utils.utils import prepare_data, jsonize, to_datetime_index from ai4water.datasets import all_datasets from ai4water.preprocessing.transformations import Transformations from ai4water.preprocessing.imputation import Imputation import ai4water.datasets as datasets from ai4water.utils.utils import print_something cmap_cv = plt.cm.coolwarm try: import h5py except ModuleNotFoundError: h5py = None # todo # detrend class AttributeContainer(object): def __init__(self): self._from_h5 = False self.is_multi_source = False self.source_is_list = False self.source_is_dict = False class DataHandler(AttributeContainer): """ Using the data source provided by the user, this class divides the data into training, validation and test set. It handles all operations around data for data preparation. The core idea on which DataHandler is based is of `local` and `global` attributes of `data` sources. However, this local and global concept comes into play only when multiple data sources are used. Methods ------------ - training_data: returns training data - validation_data: returns validation data - test_data: returns test data - from_disk: - KFold_splits: creates splits using `KFold` of sklearn - LeaveOneOut_splits: creates splits using `LeaveOneOut` of sklearn - TimeSeriesSplit_splits: creates splits using `TimeSeriesSplit` of sklearn """ def __init__(self, data, input_features: Union[list, dict, str, None] = None, output_features: Union[list, dict, str, None] = None, dataset_args: dict = None, val_fraction: float = 0.2, test_fraction: float = 0.2, input_step: int = 1, lookback: int = 1, forecast_len: int = 1, forecast_step: int = 0, known_future_inputs: bool = False, allow_input_nans: bool = False, train_data: Union[str, list] = None, val_data: Union[str, list, np.ndarray, None] = None, intervals=None, transformation: Union[str, list, dict] = None, shuffle: bool = True, allow_nan_labels: int = 0, nan_filler: dict = None, batch_size: int = 32, drop_remainder: bool = False, teacher_forcing: bool = False, seed: int = 313, save: bool = False, verbosity: int = 1, mode=None, category=None, ): """ Arguments: data : source from which to make the data. It can be one of the following: - pandas dataframe: each columns is a feature and each row is an example - xarray dataset: it can be xarray dataset or it - list of pandas dataframes : - dictionary of pandas dataframes : - path like: if the path is the path of a file, then this file can be a csv/xlsx/nc/npz/mat/parquet/feather file. The .nc file will be read using xarray to load datasets. If the path refers to a directory, it is supposed that each file in the directory refers to one example. - ai4water dataset : any of dataset name from ai4water.datasets input_features : features to use as input. If `data` is pandas dataframe then this is list of column names from `data` to be used as input. output_features : features to use as output. When `data` is dataframe then it is list of column names from `data` to be used as output. If `data` is `dict`, then it must be consistent with `data`. Default is None,which means the last column of data will be used as output. In case of multi-class classification, the output column is not supposed to be one-hot-encoded rather in the form of [0,1,2,0,1,2,1,2,0] for 3 classes. One-hot-encoding is done inside the model. dataset_args : additional arguments for AI4Water's datasets val_fraction : The fraction of the training data to be used for validation. Set to 0.0 if no validation data is to be used. test_fraction : Fraction of the complete data to be used for test purpose. Must be greater than 0.0. This is also the hold-out data. input_step : step size to keep in input data. lookback : The number of lookback steps. The term lookback has been adopted from Francois Chollet's "deep learning with keras" book. It means how many historical time-steps of data, we want to feed to model at time-step to predict next value. This value must be one for any non timeseries forecasting related problems. forecast_len : how many future values/horizons we want to predict. forecast_step : how many steps ahead we want to predict. default is 0 which means nowcasting. known_future_inputs : allow_input_nans : don't know why it exists todo train_data : Determines sampling strategy of training data. Possible values are - `random` - list of indices to be used `None` means the trainign data is chosen based upon val_fraction and `test_fraction`. In this case, the first x fraction of data is is used for training where $x = 1 - (val_fraction + test_fraction)$. val_data :Data to be used for validation. If you want to use same data for validation and test purpose, then set this argument to 'same'. This can also be indices to be used for selecting validation data. intervals : tuple of tuples where each tuple consits of two integers, marking the start and end of interval. An interval here means indices from the input file/dataframe to be used when when preparing data/batches for NN. This is handly when we want our input data contains chunks of missing values or we don't want to consider several rows in input data to be considered during data_preparation. For further usage see `examples/using_intervals` transformation : type of transformation to be applied. The transformation can be any transformation name from ai4water.utils.transformations.py. The user can specify more than one transformation. Moreover, the user can also determine which transformation to be applied on which input feature. Default is 'minmax'. To apply a single transformation on all the data ```python transformation = 'minmax' ``` To apply different transformations on different input and output features ```python transformation = [{'method': 'minmax', 'features': ['input1', 'input2']}, {'method': 'zscore', 'features': ['input3', 'output']} ] ``` Here `input1`, `input2`, `input3` and `outptu` are the columns in the `data`. shuffle : allow_nan_labels : whether to allow examples with nan labels or not. if it is > 0, and if target values contain Nans, those examples will not be ignored and will be used as it is. In such a case a customized training and evaluation step is performed where the loss is not calculated for predictions corresponding to nan observations. Thus this option can be useful when we are predicting more than 1 target and some of the examples have some of their labels missing. In such a scenario, if we set this option to >0, we don't need to ignore those samples at all during data preparation. This option should be set to > 0 only when using tensorflow for deep learning models. if == 1, then if an example has label [nan, 1] it will not be removed while the example with label [nan, nan] will be ignored/removed. If ==2, both examples (mentioned before) will be considered/will not be removed. This means for multi-outputs, we can end up having examples whose all labels are nans. if the number of outputs are just one. Then this must be set to 2 in order to use samples with nan labels. nan_filler : Determines how to deal with missing values in the data. The default value is None, which will raise error if missing/nan values are encountered in the input data. The user can however specify a dictionary whose key must be either `fillna` or `interpolate` the value of this dictionary should be the keyword arguments will be forwarded to pandas .fillna() or .iterpolate() method. For example, to do forward filling, the user can do as following ```python >>>{'fillna': {'method': 'ffill'}} ``` For details about fillna keyword options [see](https://pandas.pydata.org/pandas-docs/version/0.22.0/generated/pandas.DataFrame.fillna.html) For `interpolate`, the user can specify the type of interpolation for example ```python >>>{'interpolate': {'method': 'spline', 'order': 2}} ``` will perform spline interpolation with 2nd order. For other possible options/keyword arguments for interpolate [see](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.interpolate.html) The filling or interpolation is done columnwise, however, the user can specify how to do for each column by providing the above mentioned arguments as dictionary or list. The sklearn based imputation methods can also be used in a similar fashion. For KNN ```python >>>{'KNNImputer': {'n_neighbors': 3}} ``` or for iterative imputation ```python >>>{'IterativeImputer': {'n_nearest_features': 2}} ``` To pass additional arguments one can make use of `imputer_args` keyword argument ```python >>>{'method': 'KNNImputer', 'features': ['b'], 'imputer_args': {'n_neighbors': 4}}, ``` For more on sklearn based imputation methods [see](https://scikit-learn.org/stable/auto_examples/impute/plot_missing_values.html#sphx-glr-auto-examples-impute-plot-missing-values-py) batch_size : size of one batch. Only relevent if `drop_remainder` is True. drop_remainder : whether to drop the remainder if len(data) % batch_size != 0 or not? teacher_forcing : whether to return previous output/target/ground truth or not. This is useful when the user wants to feed output at t-1 as input at timestep t. For details about this technique see [this article](https://machinelearningmastery.com/teacher-forcing-for-recurrent-neural-networks/) seed : random seed for reproducibility save : whether to save the data in an h5 file or not. Note: If `indices` are given for `train_data` or `val_data` then these indices do not correspond to indices of original data but rather indices of 'available examples'. For example if lookback is 10, indices will shift backwards by 10, because we have to ignore first 9 rows. Example ------- ```python import pandas as pd import numpy as np from ai4water.pre_processing import DataHandler data = pd.DataFrame(np.random.randint(0, 1000, (50, 2)), columns=['input', 'output']) data_handler = DataHandler(data=data, lookback=5) x,y = data_handler.training_data() ``` # Note The word 'index' is not allowed as column name, input_features or output_features """ super().__init__() self.config = make_config(input_features=input_features, output_features=output_features, dataset_args=dataset_args or {}, val_fraction=val_fraction, test_fraction=test_fraction, input_step=input_step, lookback=lookback, forecast_len=forecast_len, forecast_step=forecast_step, known_future_inputs=known_future_inputs, allow_input_nans=allow_input_nans, # todo why this is even allowed train_data=train_data, val_data=val_data, intervals=intervals, transformation=transformation, shuffle=False, # todo allow_nan_labels=allow_nan_labels, nan_filler=nan_filler, batch_size=batch_size, drop_remainder=drop_remainder, seed=seed, category=category, ) self.data = self._process_source(data, input_features, output_features) self.verbosity = verbosity self.teacher_forcing = teacher_forcing self.mode = mode self.scalers = {} self.indexes = {} if save: self._to_disk() def __getattr__(self, item): if item in ['lookback', 'input_step', 'transformation', 'forecast_step', 'forecast_len', # todo, can it be local? 'known_future_inputs', 'allow_nan_labels', 'allow_input_nans']: if self.source_is_df: return self.config[item] elif self.source_is_list: attr = self.config[item] if not isinstance(attr, list): attr = [attr for _ in range(len(self.data))] assert len(attr) == len(self.data) return attr elif self.source_is_dict: attr = self.config[item] if not isinstance(attr, dict): attr = {key: attr for key in self.data.keys()} assert len(attr) == len(self.data), f"There are {len(attr)} values for {item} while" \ f" {len(self.data)} values for data" return attr else: raise NotImplementedError(f"Unknown data type {self.data.__class__.__name__}") else: # Default behaviour raise AttributeError(f"DataLoader does not have an attribute {item}") @property def classes(self): _classes = [] if self.mode == 'classification': if self.num_outs == 1: # for binary/multiclass array = self.data[self.output_features].values _classes = np.unique(array[~np.isnan(array)]) else: # for one-hot encoded _classes = self.output_features return _classes @property def num_classes(self): return len(self.classes) @property def is_binary(self) -> bool: """Returns True if the porblem is binary classification""" _default = False if self.mode == 'classification': if self.num_outs == 1: array = self.data[self.output_features].values unique_vals = np.unique(array[~np.isnan(array)]) if len(unique_vals) == 2: _default = True else: pass # todo, check when output columns are one-hot encoded return _default @property def is_multiclass(self) -> bool: """Returns True if the porblem is multiclass classification""" _default = False if self.mode == 'classification': if self.num_outs == 1: array = self.data[self.output_features].values unique_vals = np.unique(array[~np.isnan(array)]) if len(unique_vals) > 2: _default = True else: pass # todo, check when output columns are one-hot encoded return _default @property def is_multilabel(self) -> bool: """Returns True if the porblem is multilabel classification""" _default = False if self.mode == 'classification': if self.num_outs > 1: _default = True return _default @property def _to_categorical(self): # whether we have to convert y into one-hot encoded form _defualt = False if self.is_binary or self.is_multiclass: if self.num_outs == 1: _defualt = True if self.is_binary and self.category == 'ML': # todo, don't do for ML algorithms _defualt = False return _defualt @property def teacher_forcing(self): return self._teacher_forcing @teacher_forcing.setter def teacher_forcing(self, x): self._teacher_forcing = x @property def category(self): return self.config['category'] @property def batch_dim(self): if self.source_is_df: batch_dim = batch_dim_from_lookback(self.lookback) elif self.source_is_list: if isinstance(self.lookback, int): batch_dim = [batch_dim_from_lookback(self.lookback) for _ in range(len(self.data))] elif isinstance(self.lookback, list): batch_dim = [batch_dim_from_lookback(lb) for lb in self.lookback] else: raise NotImplementedError elif self.source_is_dict: if isinstance(self.lookback, int): batch_dim = {k: batch_dim_from_lookback(self.lookback) for k, v in zip(self.data.keys(), range(len(self.data)))} elif isinstance(self.lookback, dict): batch_dim = {k: batch_dim_from_lookback(lb) for k, lb in self.lookback.items()} else: raise NotImplementedError(f"incompatible lookback {self.lookback} with data " f"definition {self.data.__class__.__name__}.") else: raise NotImplementedError return batch_dim @property def is_multiinput(self): if len(self.num_outs) > 1: return True return False @property def input_features(self): _inputs = self.config['input_features'] if isinstance(self.data, list): assert isinstance(_inputs, list) elif isinstance(self.data, dict): assert isinstance(_inputs, dict), f'input_features are of type {_inputs.__class__.__name__}' elif _inputs is None and self.data is not None: assert isinstance(self.data, pd.DataFrame) _inputs = self.data.columns[0:-1].to_list() return _inputs @property def output_features(self): _outputs = self.config['output_features'] if isinstance(self.data, list): assert isinstance(_outputs, list) elif isinstance(self.data, dict): assert isinstance(_outputs, dict), f'data is of type dict while output_features are ' \ f'of type {_outputs.__class__.__name__}' for k in self.data.keys(): if k not in _outputs: _outputs[k] = [] elif _outputs is None and self.data is not None: assert isinstance(self.data, pd.DataFrame) _outputs = [col for col in self.data.columns if col not in self.input_features] return _outputs @property def is_multioutput(self): if isinstance(self.data, list) or isinstance(self.data, dict): return True return False @property def input_sources(self): return @property def output_sources(self): return @property def equal_io_sources(self): return @property def any_3d_source(self): return @property def all_2d_sources(self): return @property def all_3d_sources(self): return @property def source_is_df(self): if isinstance(self.data, pd.DataFrame): return True return False def len(self): """Returns number of examples available where each example refers to an input-output pair.""" if isinstance(self.data, pd.DataFrame): # the total number of examples will be less than _len = len(self.data) - (self.lookback - 1) elif isinstance(self.data, list): _len = 0 for s in self.data: _len += len(s) elif isinstance(self.data, dict): _len = 0 for k, v in self.data.items(): _len += len(v) else: raise NotImplementedError return _len def _process_source(self, data, input_features, output_features): if isinstance(data, str): _source = self._get_source_from_str(data, input_features, output_features) if isinstance(_source, str) and _source.endswith('.h5'): self._from_h5 = True self.num_sources = 1 elif isinstance(data, pd.DataFrame): if input_features is None and output_features is not None: if isinstance(output_features, str): output_features = [output_features] assert isinstance(output_features, list) input_features = [col for col in data.columns if col not in output_features] # since we have inferred the input_features, they should be put back into config self.config['input_features'] = input_features _source = data self.is_multi_source = False self.num_sources = 1 elif isinstance(data, np.ndarray): assert data.ndim == 2, f"input data as numpy array must be 2 dimension, found {data.ndim} dimensions" # if output_features is not defined, consider 1 output and name it as 'output' if output_features is None: output_features = ['outout'] self.config['output_features'] = output_features # we should put it in config as well elif isinstance(output_features, str): output_features = [output_features] else: assert isinstance(output_features, list) if input_features is None: # define dummy names for input_features input_features = [f'input_{i}' for i in range(data.shape[1]-len(output_features))] self.config['input_features'] = input_features _source = pd.DataFrame(data, columns=input_features + output_features) elif data.__class__.__name__ == "Dataset": _source = data self.num_sources = 1 elif isinstance(data, list): _source = [] for s in data: _source.append(self._process_one_source(s)) self.is_multi_source = True self.source_is_list = True self.num_sources = len(data) elif isinstance(data, dict): _source = {} for s_name, s_val in data.items(): _source[s_name] = self._process_one_source(s_val) self.is_multi_source = True self.source_is_dict = True self.num_sources = len(data) elif data is None: return data else: assert data is not None raise ValueError(f"unregnizable source of data of type {data.__class__.__name__} given") _source = self.impute(_source) return _source def add_noice(self): return @property def val_data(self): if self.source_is_df or self.source_is_list or self.source_is_dict: return self.config['val_data'] else: raise NotImplementedError def impute(self, data): """Imputes the missing values in the data using `Imputation` module""" if self.config['nan_filler'] is not None: if isinstance(data, pd.DataFrame): _source = self._impute_one_source(data, self.config['nan_filler']) else: raise NotImplementedError else: _source = data return _source def _impute_one_source(self, data, impute_config): if isinstance(impute_config, str): method, impute_args = impute_config, {} data = Imputation(data, method=method, **impute_args)() elif isinstance(impute_config, dict): data = Imputation(data, **impute_config)() elif isinstance(impute_config, list): for imp_conf in impute_config: data = Imputation(data, **imp_conf)() else: raise NotImplementedError(f'{impute_config.__class__.__name__}') return data def tot_obs_for_one_df(self): if self.source_is_df: tot_obs = tot_obs_for_one_df(self.data, self.allow_nan_labels, self.output_features, self.lookback, self.input_step, self.num_outs, self.forecast_step, self.forecast_len, self.config['intervals'], self.input_features, ) elif self.source_is_list: tot_obs = [] for idx in range(len(self.data)): _tot_obs = tot_obs_for_one_df(self.data[idx], self.allow_nan_labels[idx], self.output_features[idx], self.lookback[idx], self.input_step[idx], self.num_outs[idx], self.forecast_step[idx], self.forecast_len[idx], self.config['intervals'], self.input_features[idx] ) tot_obs.append(_tot_obs) elif self.source_is_dict: tot_obs = {} for src_name in self.data.keys(): _tot_obs = tot_obs_for_one_df(self.data[src_name], self.allow_nan_labels[src_name], self.output_features[src_name], self.lookback[src_name], self.input_step[src_name], self.num_outs[src_name], self.forecast_step[src_name], self.forecast_len[src_name], self.config['intervals'], self.input_features[src_name] ) tot_obs[src_name] = _tot_obs else: raise NotImplementedError return tot_obs def get_indices(self): """If the data is to be divded into train/test based upon indices, here we create train_indices and test_indices. """ if self.source_is_df or self.source_is_list or self.source_is_dict: indices = self.config['train_data'] if isinstance(indices, str): # if isinstance(indices, str): assert indices == 'random' tot_obs = self.tot_obs_for_one_df() # tot_obs can be dictionary because lookback is local # but tot_obs must be same for all sources if isinstance(tot_obs, dict): tot_obs = np.unique(list(tot_obs.values())).item() total_indices = np.arange(tot_obs) if self.config['test_fraction'] > 0.0: train_indices, test_indices = train_test_split(total_indices, test_size=self.config['test_fraction'], random_state=self.config['seed']) else: # all the indices belong to training train_indices, test_indices = total_indices, None elif indices is None: train_indices, test_indices = None, None else: assert isinstance(np.array(indices), np.ndarray) tot_obs = self.tot_obs_for_one_df() if isinstance(tot_obs, dict): tot_obs = np.unique(list(tot_obs.values())).item() tot_indices = np.arange(tot_obs) train_indices = np.array(indices) test_indices = np.delete(tot_indices, train_indices) else: raise NotImplementedError(f'Indices can not be found for source of type {self.data.__class__.__name__}') setattr(self, 'train_indices', train_indices) setattr(self, 'test_indices', test_indices) return train_indices, test_indices def get_train_args(self): """train_data key in config can consist of following keys st, en, indices""" indices = self.config['train_data'] if indices is not None: if isinstance(indices, str): assert indices == 'random', f'invalid value of indices {indices}' else: assert isinstance(np.array(indices), np.ndarray), f'invalid value of indices {indices}' train_indices, _ = self.get_indices() return train_indices @property def num_ins(self): if self.source_is_df or self.data is None: return len(self.input_features) elif self.source_is_list or self.data is None: return [len(in_feat) for in_feat in self.input_features] elif self.source_is_dict or self.data is None: return {k: len(in_feat) for k, in_feat in self.input_features.items()} else: raise NotImplementedError @property def num_outs(self): if self.source_is_df: return len(self.output_features) elif self.source_is_list: return [len(out_feat) for out_feat in self.output_features] elif self.source_is_dict: return {k: len(out_feat) for k, out_feat in self.output_features.items()} elif self.data.__class__.__name__ == "NoneType": return None else: raise NotImplementedError(f"Can not determine output features for data " f"of type {self.data.__class__.__name__}") def KFold_splits(self, n_splits=5): """returns an iterator for kfold cross validation. The iterator yields two tuples of training and test x,y pairs. The iterator on every iteration returns following `(train_x, train_y), (test_x, test_y)` Note: only `training_data` and `validation_data` are used to make kfolds. Example ------- ```python >>>data = pd.DataFrame(np.random.randint(0, 10, (20, 3)), columns=['a', 'b', 'c']) >>>data_handler = DataHandler(data=data, config={'lookback': 1}) >>>kfold_splits = data_handler.KFold_splits() >>>for (train_x, train_y), (test_x, test_y) in kfold_splits: ... print(train_x, train_y, test_x, test_y) ``` """ x, y = self._get_xy() spliter = self._get_kfold_splitter(x=x, n_splits=n_splits) for tr_idx, test_idx in spliter: yield (x[tr_idx], y[tr_idx]), (x[test_idx], y[test_idx]) def LeaveOneOut_splits(self): """Yields leave one out splits The iterator on every iteration returns following `(train_x, train_y), (test_x, test_y)`""" x, y = self._get_xy() kf = LeaveOneOut() for tr_idx, test_idx in kf.split(x): yield (x[tr_idx], y[tr_idx]), (x[test_idx], y[test_idx]) def TimeSeriesSplit_splits(self, n_splits=5, **kwargs): """returns an iterator for TimeSeriesSplit. The iterator on every iteration returns following `(train_x, train_y), (test_x, test_y)` """ x, y = self._get_xy() tscv = TimeSeriesSplit(n_splits=n_splits, **kwargs) for tr_idx, test_idx in tscv.split(x): yield (x[tr_idx], y[tr_idx]), (x[test_idx], y[test_idx]) def _get_kfold_splitter(self, x, n_splits=5): kf = KFold(n_splits=n_splits, random_state=self.config['seed'] if self.config['shuffle'] else None, shuffle=self.config['shuffle']) spliter = kf.split(x) return spliter def plot_KFold_splits(self, n_splits=5, show=True, **kwargs): """Plots the indices of kfold splits""" x, y = self._get_xy() spliter = self._get_kfold_splitter(x=x, n_splits=n_splits) self._plot_splits(spliter, x, title="KFoldCV", show=show, **kwargs) return def plot_LeaveOneOut_splits(self, show=True, **kwargs): """Plots the indices obtained from LeaveOneOut strategy""" x, y = self._get_xy() spliter = LeaveOneOut().split(x) self._plot_splits(spliter=spliter, x=x, title="LeaveOneOutCV", show=show, **kwargs) return def plot_TimeSeriesSplit_splits(self, n_splits=5, show=True, **kwargs): """Plots the indices obtained from TimeSeriesSplit strategy""" x, y = self._get_xy() spliter = TimeSeriesSplit(n_splits=n_splits, **kwargs).split(x) self._plot_splits(spliter=spliter, x=x, title="TimeSeriesCV", show=show, **kwargs) return def _plot_splits(self, spliter, x, show=True, **kwargs): splits = list(spliter) figsize = kwargs.get('figsize', (10, 8)) legend_fs = kwargs.get('legend_fs', 20) legend_pos = kwargs.get('legend_pos', (1.02, 0.8)) title = kwargs.get("title", "CV") plt.close('all') fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) for ii, split in enumerate(splits): indices = np.array([np.nan] * len(x)) indices[split[0]] = 1 indices[split[1]] = 0 ax.scatter(range(len(indices)), [ii + .5] * len(indices), c=indices, marker='_', lw=10, cmap="coolwarm", vmin=-.2, vmax=1.2) yticklabels = list(range(len(splits))) ax.set(yticks=np.arange(len(splits)) + .5, yticklabels=yticklabels, xlabel='Sample index', ylabel="CV iteration") ax.set_title(title, fontsize=20) ax.legend([Patch(color=cmap_cv(.8)), Patch(color=cmap_cv(.02))], ['Training set', 'Test set'], loc=legend_pos, fontsize=legend_fs) if show: plt.show() return def _get_xy(self): if self.teacher_forcing: tr_x, _, tr_y = self.training_data() val_x, _, val_y = self.validation_data() else: tr_x, tr_y = self.training_data() val_x, val_y = self.validation_data() def check_if_none(X, Y): if X is None: shape = list(tr_x.shape) shape[0] = 0 X = np.zeros(tuple(shape)) if Y is None: shape = list(tr_y.shape) shape[0] = 0 Y = np.zeros(tuple(shape)) return X, Y if self.source_is_df: val_x, val_y = check_if_none(val_x, val_y) x = np.concatenate([tr_x, val_x]) y = np.concatenate([tr_y, val_y]) else: raise NotImplementedError return x, y def make_val_frac_zero(self): # It is good that the user knows explicitly that either of val_fraction or test_fraction is used so # one of them must be set to 0.0 if self.config['val_fraction'] > 0.0: warnings.warn(f"Setting val_fraction from {self.config['val_fraction']} to 0.0") self.config['val_fraction'] = 0.0 return def _indexify_y(self, src: pd.DataFrame, out_features: list): # this function is only called when data is a list/dictionary src = src.copy() # make a copy so that df in original data is not altered # since there are multiple sources/dfs, we need to keep track that y's in each # data are same i.e. y[10] of data[0] is same as y[10] of data[1] # but this should only be done if nans in y are ignored src['dummy_id'] = np.arange(len(src), dtype=np.int32) out_features = out_features + ['dummy_id'] # original should not be changed. # todo, all sources should have same length return src, out_features def _make_data_for_one_src(self, key, indices, shuffle, identifier=None, deindexify=False ): """Makes the data for each source.""" data = self.data if identifier is None else self.data[identifier] output_features = self.output_features if identifier is None else self.output_features[identifier] if self.source_is_list and all([flag == 0 for flag in self.allow_nan_labels]): data, output_features = self._indexify_y(data, output_features) data_maker = MakeData( input_features=self.input_features if identifier is None else self.input_features[identifier], output_features=output_features, lookback=self.lookback if identifier is None else self.lookback[identifier], input_step=self.input_step if identifier is None else self.input_step[identifier], forecast_step=self.forecast_step if identifier is None else self.forecast_step[identifier], forecast_len=self.forecast_len if identifier is None else self.forecast_len[identifier], known_future_inputs=self.known_future_inputs if identifier is None else self.known_future_inputs[identifier], batch_dim=self.batch_dim if identifier is None else self.batch_dim[identifier], allow_input_nans=self.allow_input_nans if identifier is None else self.allow_input_nans[identifier], allow_nan_labels=self.allow_nan_labels if identifier is None else self.allow_nan_labels[identifier], verbosity=self.verbosity ) data, scalers = data_maker.transform( data=data, transformation=self.transformation if identifier is None else self.transformation[identifier], key=key ) self.scalers.update(scalers) # numpy arrays are not indexed and is supposed that the whole array is use as input if not isinstance(data, np.ndarray): data = data_maker.indexify(data, key) x, prev_y, y = data_maker( data, shuffle=shuffle, intervals=self.config['intervals'], indices=indices ) if x is not None and deindexify and not isinstance(data, np.ndarray): # if x.shape[0] >0: x, self.indexes[key] = data_maker.deindexify(x, key) # if 'dummy_id' in data_maker.output_features: # x, prev_y, y = deindexify_y(x, prev_y, y, np.argmax(self.lookback).item()) return x, prev_y, y, data_maker def _post_process_train_args(self, x, prev_y, y): if self.val_data == 'same': self.make_val_frac_zero() if self.config['val_fraction'] + self.config['test_fraction'] > 0.0: if self.train_indices is None: train_frac = 1.0 - self.config['test_fraction'] train_idx_en = int(round(train_frac * len(x))) x = x[0: train_idx_en, ...] prev_y = prev_y[0: train_idx_en, ...] y = y[0: train_idx_en, ...] if self.config['val_fraction'] > 0.0: train_frac = 1.0 - self.config['val_fraction'] train_idx_en = int(round(train_frac * len(x))) x = x[0: train_idx_en, ...] prev_y = prev_y[0: train_idx_en, ...] y = y[0: train_idx_en, ...] return x, prev_y, y def training_data(self, key: str = None, **kwargs) -> Tuple[np.ndarray, np.ndarray]: """Renders the training data.""" if self._from_h5: return load_data_from_hdf5('training_data', self.data) train_indices = self.get_train_args() if self.source_is_df: x, prev_y, y, data_maker = self._make_data_for_one_src( key, train_indices, False, deindexify=False ) x, prev_y, y = self._post_process_train_args(x, prev_y, y) x, prev_y, y = self.check_for_batch_size(x, prev_y, y) if not isinstance(self.data, np.ndarray): x, self.indexes[key] = data_maker.deindexify(x, key) elif self.is_multi_source: if self.source_is_list: x, prev_y, y = [], [], [] for idx, src in enumerate(self.data): _key = f'{key}_{idx}' _x, _prev_y, _y, data_maker = self._make_data_for_one_src( f'{key}_{idx}', train_indices, False, identifier=idx, deindexify=False, ) _x, _prev_y, _y = self._post_process_train_args(_x, _prev_y, _y) _x, _prev_y, _y = self.check_for_batch_size(_x, _prev_y, _y) if not isinstance(self.data[idx], np.ndarray): # todo, one source is indexified and other is not? _x, self.indexes[_key] = data_maker.deindexify(_x, f'{key}_{idx}') x.append(_x) prev_y.append(_prev_y) y.append(_y) if 'dummy_id' in data_maker.output_features: x, prev_y, y = deindexify_y(x, prev_y, y, np.argmax(self.lookback).item()) elif self.source_is_dict: x, prev_y, y = {}, {},{} for src_name, src in self.data.items(): _key = f'{key}_{src_name}' _x, _prev_y, _y, data_maker = self._make_data_for_one_src( f'{key}_{src_name}', train_indices, False, identifier=src_name, deindexify=False ) _x, _prev_y, _y = self._post_process_train_args( _x, _prev_y, _y ) _x, _prev_y, _y = self.check_for_batch_size(_x, _prev_y, _y) # todo, one source may be indexified and other is not? if not isinstance(self.data[src_name], np.ndarray): _x, self.indexes[_key] = data_maker.deindexify(_x, f'{key}_{src_name}') x[src_name], prev_y[src_name], y[src_name] = _x, _prev_y, _y # if 'dummy_id' in data_maker.output_features: # x, prev_y, y = deindexify_y(x, prev_y, y, max(self.lookback, key=self.lookback.get)) else: raise NotImplementedError elif isinstance(self.data, dict) or isinstance(self.data, list): raise NotImplementedError else: raise NotImplementedError prev_y = filter_zero_sized_arrays(prev_y) y = filter_zero_sized_arrays(y) if self.mode == 'classification': y = check_for_classification(y, self._to_categorical) if self.teacher_forcing: return return_x_yy(x, prev_y, y, "Training", self.verbosity) return return_xy(x, y, "Training", self.verbosity) def _make_val_data_from_src(self, indices, key, tot_obs, identifier=None ): x, prev_y, y = None, None, None run = True split1 = False split2 = False if self.val_data == "same": self.make_val_frac_zero() assert self.config['test_fraction'] > 0.0, f"test_fraction should be > 0.0. " \ f"It is {self.config['test_fraction']}" if indices is None: split1 = True elif np.array(self.val_data).shape.__len__() > 0: indices = np.array(self.val_data) elif self.config['val_fraction'] == 0.0: run = False else: if indices is None: indices = self.get_train_args() split2 = True if run: x, prev_y, y, data_maker = self._make_data_for_one_src( key, indices, False, identifier=identifier ) if split1: # if indices is None: # we have to remove training data from it which is the first %x percent train_frac = 1.0 - self.config['test_fraction'] test_frac = self.config['test_fraction'] train_idx_en = int(round(train_frac * len(x))) test_idx_st = train_idx_en + int(round(train_frac + test_frac * len(x))) x = x[train_idx_en: test_idx_st, ...] prev_y = prev_y[train_idx_en: test_idx_st, ...] y = y[train_idx_en: test_idx_st, ...] elif indices is None and self.config['val_fraction'] == 0.0: # no validation data x, prev_y, y = None, None, None elif split2: if indices is None: train_frac = 1.0 - self.config['test_fraction'] train_idx_en = int(round(train_frac * len(x))) x = x[0: train_idx_en, ...] prev_y = prev_y[0: train_idx_en, ...] y = y[0: train_idx_en, ...] else: train_idx_en = len(x) if self.config['val_fraction']>0.0: train_frac = 1.0 - self.config['val_fraction'] train_idx_st = int(round(train_frac * len(x))) x = x[train_idx_st:train_idx_en, ...] prev_y = prev_y[train_idx_st:train_idx_en, ...] y = y[train_idx_st:train_idx_en, ...] if x is not None: if x.shape[0] == 0: # instead of returning arrays with 0 in first dimension, return None x, prev_y, y = None, None, None else: # np.ndarray is not indexified if identifier and isinstance(self.data[identifier], np.ndarray): pass else: x, prev_y, y = self.check_for_batch_size(x, prev_y, y) x, self.indexes[key] = data_maker.deindexify(x, key) return x, prev_y, y def validation_data(self, key='val', **kwargs ) -> Tuple[Union[np.ndarray, None], Union[np.ndarray, None]]: """Returns the validation data""" if self._from_h5: return load_data_from_hdf5('validation_data', self.data) if getattr(self, 'val_dataset', None).__class__.__name__ in ['BatchDataset', 'TorchDataset']: return self.val_dataset test_indices = None if self.config['val_data'] == 'same': _, test_indices = self.get_indices() if self.source_is_df: x, prev_y, y = self._make_val_data_from_src( test_indices, key, self.tot_obs_for_one_df() ) elif self.source_is_list: x, prev_y, y = [], [], [] for idx, src in enumerate(self.data): output_features = self.output_features[idx] if all([flag == 0 for flag in self.allow_nan_labels]): src, output_features = self._indexify_y(src, output_features) _x, _prev_y, _y = self._make_val_data_from_src( test_indices, f'{key}_{idx}', self.tot_obs_for_one_df()[idx], identifier=idx ) x.append(_x) prev_y.append(_prev_y) if _y.size > 0: y.append(_y) if 'dummy_id' in output_features: # todo why here as well x, prev_y, y = deindexify_y(x, prev_y, y, np.argmax(self.lookback).item()) elif self.source_is_dict: x, prev_y, y = {}, {}, {} for src_name, src in self.data.items(): _x, _prev_y, _y = self._make_val_data_from_src( test_indices, f'{key}_{src_name}', self.tot_obs_for_one_df()[src_name], identifier=src_name ) x[src_name] = _x prev_y[src_name] = _prev_y y[src_name] = _y elif self.data.__class__.__name__ == "NoneType": return None, None else: raise NotImplementedError(f"Can not calculate validation data for data " f"of type {self.data.__class__.__name__}") prev_y = filter_zero_sized_arrays(prev_y) y = filter_zero_sized_arrays(y) if self.mode == 'classification': y = check_for_classification(y, self._to_categorical) if self.teacher_forcing: return return_x_yy(x, prev_y, y, "Validation", self.verbosity) return return_xy(x, y, "Validation", self.verbosity) def test_data(self, key='test', data_keys=None, **kwargs ) -> Tuple[Union[np.ndarray, None], Union[np.ndarray, None]]: """Returns the test_data""" # user may have defined its own data by overwriting training_data/validation_data # and `val_data` is same as test data, thus avoid the situation if the user # has not overwritten test_data method. if self._from_h5: return load_data_from_hdf5('test_data', self.data) if self.config['val_data'] == "same" and self.data is None: return self.validation_data(key=key, data_keys=data_keys, **kwargs) if self.data.__class__.__name__ == "NoneType": return None, None _, test_indices = self.get_indices() if self.val_data == "same": return self.validation_data(key=key) if self.source_is_df: x, prev_y, y = self.test_data_from_one_src( key, test_indices, self.tot_obs_for_one_df() ) elif self.source_is_list: x, prev_y, y = [], [], [] for idx, src in enumerate(self.data): output_features = self.output_features[idx] if all([flag == 0 for flag in self.allow_nan_labels]): src, output_features = self._indexify_y(src, output_features) _x, _prev_y, _y = self.test_data_from_one_src( f'{key}_{idx}', test_indices, self.tot_obs_for_one_df()[idx], identifier=idx ) x.append(_x) prev_y.append(_prev_y) if _y.size > 0: y.append(_y) if 'dummy_id' in output_features: x, prev_y, y = deindexify_y(x, prev_y, y, np.argmax(self.lookback).item()) elif self.source_is_dict: x, prev_y, y = {}, {}, {} for src_name, src in self.data.items(): x[src_name], prev_y[src_name], y[src_name] = self.test_data_from_one_src( f'{key}_{src_name}', test_indices, self.tot_obs_for_one_df()[src_name], identifier=src_name, ) else: raise NotImplementedError prev_y = filter_zero_sized_arrays(prev_y) y = filter_zero_sized_arrays(y) if self.mode == 'classification': y = check_for_classification(y, self._to_categorical) if self.teacher_forcing: return return_x_yy(x, prev_y, y, "Test", self.verbosity) return return_xy(x, y, "Test", self.verbosity) def test_data_from_one_src(self, key, test_indices, tot_obs, identifier=None ): x, prev_y, y, data_maker = self._make_data_for_one_src( key, test_indices, False, identifier=identifier ) if test_indices is None: # we need to divide the data into train/val/test based upon given fractions. train_frac = 1.0 - self.config['test_fraction'] # val_frac = self.config['val_fraction'] train_idx_en = int(round(train_frac * len(x))) # val_idx = train_idx + int(round(train_frac + val_frac * tot_obs)) x = x[train_idx_en:, ...] prev_y = prev_y[train_idx_en:, ...] y = y[train_idx_en:, ...] if x is not None: if x.shape[0] == 0: x, prev_y, y = None, None, None else: if identifier and isinstance(self.data[identifier], np.ndarray): pass else: x, prev_y, y = self.check_for_batch_size(x, prev_y, y) x, self.indexes[key] = data_maker.deindexify(x, key) return x, prev_y, y def deindexify(self, data, key): if self.source_is_df: if key not in self.indexes: raise ValueError(f"key `{key}` not found. Available keys are {list(self.indexes.keys())}") index = self.indexes[key] elif self.source_is_list: index = None for idx, src in enumerate(data): _key = f'{key}_{idx}' if _key not in self.indexes: raise ValueError(f"key `{_key}` not found. Available keys are {list(self.indexes.keys())}") index = self.indexes[_key] elif self.source_is_dict: index = None for src_name, src in data.items(): _key = f'{key}_{src_name}' if _key not in self.indexes: raise ValueError(f"key `{_key}` not found. Available keys are {list(self.indexes.keys())}") index = self.indexes[_key] else: raise ValueError return data, index def transform(self): return def inverse_transform(self, data, key): transformation = self.transformation if self.source_is_df: data = self._inv_transform_one_src(data, key, transformation) elif self.source_is_list: assert isinstance(data, list) _data = [] for idx, src in enumerate(data): __data = self._inv_transform_one_src(src, f'{key}_{idx}', transformation[idx]) _data.append(__data) data = _data elif self.source_is_dict: assert isinstance(data, dict) _data = {} for src_name, src in data.items(): _data[src_name] = self._inv_transform_one_src(src, f'{key}_{src_name}', transformation[src_name]) data = _data else: raise NotImplementedError return data def _inv_transform_one_src(self, data, key, transformation): if transformation is not None: if isinstance(transformation, str): if key not in self.scalers: raise ValueError(f""" key `{key}` for inverse transformation not found. Available keys are {list(self.scalers.keys())}""") scaler = self.scalers[key] scaler, shape, _key = scaler['scaler'], scaler['shape'], scaler['key'] original_shape = data.shape data, dummy_features = conform_shape(data, shape) # get data to transform transformed_data = scaler.inverse_transform(data) data = transformed_data[:, dummy_features:] # remove the dummy data data = data.reshape(original_shape) elif isinstance(transformation, list): assert data.__class__.__name__ in ['DataFrame', 'Series'] for idx, trans in reversed(list(enumerate(transformation))): # idx and trans both in reverse form if trans['method'] is not None: features = trans['features'] # if any of the feature in data was transformed if any([True if f in data else False for f in features]): orig_cols = data.columns # copy teh columns in the original df scaler = self.scalers[f'{key}_{trans["method"]}_{idx}'] scaler, shape, _key = scaler['scaler'], scaler['shape'], scaler['key'] data, dummy_features = conform_shape(data, shape, features) # get data to transform transformed_data = Transformations(data=data, **trans)(what='inverse', scaler=scaler) data = transformed_data[orig_cols] # remove the dummy data elif isinstance(transformation, dict): assert data.__class__.__name__ in ['DataFrame', 'Series'], f'data is of type {data.__class__.__name__}' if any([True if f in data else False for f in transformation['features']]): orig_cols = data.columns scaler = self.scalers[key] scaler, shape, _key = scaler['scaler'], scaler['shape'], scaler['key'] data, dummy_features = conform_shape(data, shape, features=transformation['features']) transformed_data = Transformations(data=data, **transformation)(what='inverse', scaler=scaler) data = transformed_data[orig_cols] # remove the dummy data return data def check_nans(self): return @classmethod def from_h5(cls, path): """Creates an instance of DataLoader from .h5 class.""" f = h5py.File(path, mode='r') config = {} for k, v in f.attrs.items(): if isinstance(v, bytes): v = decode(v) config[k] = v cls._from_h5 = True f.close() return cls(path, **config) def _to_disk(self, path=None): path = path or os.path.join(os.getcwd(), "results") filepath = os.path.join(path, "data.h5") f = h5py.File(filepath, mode='w') for k,v in self.config.items(): if isinstance(v, (dict, list, tuple)): f.attrs[k] = json.dumps( v, default=jsonize).encode('utf8') elif v is not None: f.attrs[k] = v x, prev_y, y = self.training_data() # save in disk self._save_data_to_hdf5('training_data', x, prev_y, y, f) x, prev_y, y = self.validation_data() self._save_data_to_hdf5('validation_data', x, prev_y, y, f) x, prev_y, y = self.validation_data() self._save_data_to_hdf5('test_data', x, prev_y, y, f) f.close() return def _get_source_from_str(self, data, input_features, output_features): if isinstance(output_features, str): output_features = [output_features] # dir path/file path/ ai4water dataset name if data.endswith('.h5'): _source = data if data.endswith('.csv'): _source = pd.read_csv(data) if _source.columns[0] in ['index', 'time', 'date']: _source.index = pd.to_datetime(_source.pop('index')) elif data.endswith('.xlsx') or data.endswith('xlx'): _source = pd.read_excel(data) if _source.columns[0] in ['index', 'time', 'date']: _source.index = pd.to_datetime(_source.pop('index')) elif data.endswith('.parquet'): _source = pd.read_parquet(data) elif data.endswith('.feather'): _source = pd.read_feather(data) if _source.columns[0] in ['index', 'time', 'date']: _source.index = pd.to_datetime(_source.pop('index')) # netcdf file elif data.endswith('.nc'): import xarray as xr _source = xr.open_dataset(data) _source = _source.to_dataframe() elif data.endswith('npz'): data = np.load(data) assert len(data) == 1 d = [] for k,v in data.items(): d.append(v) data:np.ndarray = d[0] _source = pd.DataFrame(data, columns=input_features + output_features) # matlab's mat file elif data.endswith('.mat'): import scipy mat = scipy.io.loadmat(data) data:np.ndarray = mat['data'] _source = pd.DataFrame(data, columns=input_features + output_features) elif os.path.isfile(data): assert os.path.exists(data) assert len(os.listdir(data)) > 1 # read from directory raise NotImplementedError elif data in all_datasets: _source = self._get_data_from_ai4w_datasets(data) else: raise ValueError(f"unregnizable source of data given {data}") return _source def _process_one_source(self, data): if isinstance(data, str): _source = self._get_source_from_str(data) elif isinstance(data, pd.DataFrame): _source = data elif isinstance(data, np.ndarray): _source = data # elif data.__class.__.__name__ == "Dataset": # _source = data else: raise ValueError(f"unregnizable source of data of type {data.__class__.__name__}") return _source def _get_data_from_ai4w_datasets(self, data): Dataset = getattr(datasets, data) dataset = Dataset() dataset_args = self.config['dataset_args'] if dataset_args is None: dataset_args = {} # if self.config['input_features'] is not None: dynamic_features = self.config['input_features'] + self.config['output_features'] data = dataset.fetch(dynamic_features = dynamic_features, **dataset_args ) data = data.to_dataframe(['time', 'dynamic_features']).unstack() data.columns = [a[1] for a in data.columns.to_flat_index()] return data def _save_data_to_hdf5(self, data_type, x, prev_y, y, f): """Saves one data_type in h5py. data_type is string indicating whether it is training, validation or test data.""" if x is not None: model_weights_group = f.create_group(data_type) if self.source_is_list: idx = 0 for xi, prevyi, yi in zip(x, prev_y, y): save_in_a_group(xi, prevyi, yi, model_weights_group, prefix=idx) idx += 1 elif self.source_is_dict: for src_name in self.data.keys(): save_in_a_group(x.get(src_name, None), prev_y.get(src_name, None), y.get(src_name, None), model_weights_group, prefix=src_name) else: save_in_a_group(x, prev_y, y, model_weights_group) return def check_for_batch_size(self, x, prev_y, y): if self.config['drop_remainder']: remainder = len(x) % self.config['batch_size'] if remainder: if isinstance(x, list): _x = [] for val in x: _x.append(val[0:-remainder]) x = _x else: x = x[0:-remainder] prev_y = prev_y[0:-remainder] y = y[0:-remainder] return x, prev_y, y class MakeData(object): def __init__(self, input_features, output_features, lookback, input_step, forecast_step, forecast_len, known_future_inputs, batch_dim="3D", allow_input_nans=False, allow_nan_labels=0, verbosity=1, ): self.input_features = copy_features(input_features) self.output_features = copy_features(output_features) self.allow_nan_labels = allow_nan_labels self.lookback = lookback self.input_step = input_step self.forecast_step = forecast_step self.forecast_len = forecast_len self.allow_input_nans = allow_input_nans self.verbosity = verbosity self.batch_dim = batch_dim self.known_future_inputs = known_future_inputs self.nans_removed_4m_st = 0 self.scalers = {} self.indexes = {} self.index_types = {} # saves the information whether an index was datetime index or not? def check_nans(self, data, input_x, input_y, label_y, outs, lookback): """Checks whether anns are present or not and checks shapes of arrays being prepared.""" if isinstance(data, pd.DataFrame): nans = data[self.output_features].isna() nans = nans.sum().sum() data = data.values else: nans = np.isnan(data[:, -outs:]) # df[self.out_cols].isna().sum() nans = int(nans.sum()) if nans > 0: if self.allow_nan_labels == 2: if self.verbosity > 0: print("\n{} Allowing NANs in predictions {}\n".format(10 * '*', 10 * '*')) elif self.allow_nan_labels == 1: if self.verbosity>0: print("\n{} Ignoring examples whose all labels are NaNs {}\n".format(10 * '*', 10 * '*')) idx = ~np.array([all([np.isnan(x) for x in label_y[i]]) for i in range(len(label_y))]) input_x = input_x[idx] input_y = input_y[idx] label_y = label_y[idx] if int(np.isnan(data[:, -outs:][0:lookback]).sum() / outs) >= lookback: self.nans_removed_4m_st = -9999 else: if self.verbosity > 0: print('\n{} Removing Examples with nan in labels {}\n'.format(10 * '*', 10 * '*')) if outs == 1: # find out how many nans were present from start of data until lookback, these nans will be removed self.nans_removed_4m_st = np.isnan(data[:, -outs:][0:lookback]).sum() # find out such labels where 'y' has at least one nan nan_idx = np.array([np.any(i) for i in np.isnan(label_y)]) non_nan_idx = np.invert(nan_idx) label_y = label_y[non_nan_idx] input_x = input_x[non_nan_idx] input_y = input_y[non_nan_idx] assert np.isnan(label_y).sum() < 1, "label still contains {} nans".format(np.isnan(label_y).sum()) assert input_x.shape[0] == input_y.shape[0] == label_y.shape[0], "shapes are not same" if not self.allow_input_nans: assert np.isnan(input_x).sum() == 0, "input still contains {} nans".format(np.isnan(input_x).sum()) return input_x, input_y, label_y def transform(self, data, transformation, key='5'): # it is better to make a copy here because all the operations on data happen after this. data = data.copy() scalers = {} if transformation: if isinstance(transformation, dict): data, scaler = Transformations(data=data, **transformation)('transformation', return_key=True) scalers[key] = scaler # we want to apply multiple transformations elif isinstance(transformation, list): for idx, trans in enumerate(transformation): if trans['method'] is not None: data, scaler = Transformations(data=data, **trans)('transformation', return_key=True) scalers[f'{key}_{trans["method"]}_{idx}'] = scaler else: assert isinstance(transformation, str) data, scaler = Transformations(data=data, method=transformation)('transformation', return_key=True) scalers[key] = scaler self.scalers.update(scalers) return data, scalers def indexify(self, data: pd.DataFrame, key): dummy_index = False # for dataframes if isinstance(data.index, pd.DatetimeIndex): index = list(map(int, np.array(data.index.strftime('%Y%m%d%H%M')))) # datetime index self.index_types[key] = 'dt' original_index = index else: try: index = list(map(int, np.array(data.index))) self.index_types[key] = 'int' original_index = index except ValueError: # index may not be convertible to integer, it may be string values dummy_index = np.arange(len(data), dtype=np.int64).tolist() original_index = pd.Series(data.index, index=dummy_index) index = dummy_index self.index_types[key] = 'str' self.indexes[key] = {'dummy': dummy_index, 'original': original_index} # pandas will add the 'datetime' column as first column. This columns will only be used to keep # track of indices of train and test data. data.insert(0, 'index', index) self.input_features = ['index'] + self.input_features # setattr(self, 'input_features', ['index'] + self.input_features) self.indexes[key] = {'index': index, 'dummy_index': dummy_index, 'original': original_index} return data def deindexify(self, data, key): if isinstance(data, np.ndarray): _data, _index = self.deindexify_nparray(data, key) elif isinstance(data, list): _data, _index = [], [] for d in data: data_, index_ = self.deindexify_nparray(d, key) _data.append(data_) _index.append(index_) else: raise NotImplementedError if self.indexes[key]['dummy_index']: _index = self.indexes[key]['original'].loc[_index].values.tolist() if self.index_types[key] == 'dt': _index = to_datetime_index(_index) return _data, _index def get_batches(self, data, num_ins, num_outs): if self.batch_dim == "2D": return self.get_2d_batches(data, num_ins, num_outs) else: return self.check_nans(data, *prepare_data(data, num_outputs=num_outs, lookback_steps=self.lookback, input_steps=self.input_step, forecast_step=self.forecast_step, forecast_len=self.forecast_len, known_future_inputs=self.known_future_inputs), num_outs, self.lookback) def get_2d_batches(self, data, ins, outs): if not isinstance(data, np.ndarray): if isinstance(data, pd.DataFrame): data = data.values else: raise TypeError(f"unknown data type {data.__class__.__name__} for data ") if outs>0: input_x, input_y, label_y = data[:, 0:ins], data[:, -outs:], data[:, -outs:] else: input_x, input_y, label_y = data[:, 0:ins], np.random.random((len(data), outs)), np.random.random((len(data), outs)) assert self.lookback == 1, """lookback should be one for MLP/Dense layer based model, but it is {} """.format(self.lookback) return self.check_nans(data, input_x, input_y, np.expand_dims(label_y, axis=2), outs, self.lookback) def __call__( self, data, st=0, en=None, indices=None, intervals=None, shuffle=False ): num_ins = len(self.input_features) num_outs = len(self.output_features) if st is not None: assert isinstance(st, int), "starting point must be integer." if indices is not None: assert isinstance(np.array(indices), np.ndarray), "indices must be array like" if en is not None or st != 0: raise ValueError(f'When using indices, st and en can not be used. while st:{st}, and en:{en}') if en is None: en = data.shape[0] if isinstance(data, pd.DataFrame): data = data[self.input_features + self.output_features].copy() df = data else: num_ins = data.shape[-1] num_outs = 0 data = data.copy() df = data if intervals is None: df = df[st:en] x, prev_y, y = self.get_batches(df, num_ins, num_outs) if indices is not None: # if indices are given then this should be done after `get_batches` method x = x[indices] prev_y = prev_y[indices] y = y[indices] else: xs, prev_ys, ys = [], [], [] for _st, _en in intervals: df1 = data[_st:_en] if df1.shape[0] > 0: x, prev_y, y = self.get_batches(df1.values, num_ins, num_outs) xs.append(x) prev_ys.append(prev_y) ys.append(y) if indices is None: x = np.vstack(xs)[st:en] prev_y = np.vstack(prev_ys)[st:en] y = np.vstack(ys)[st:en] else: x = np.vstack(xs)[indices] prev_y = np.vstack(prev_ys)[indices] y = np.vstack(ys)[indices] if shuffle: raise NotImplementedError if 'index' in data: data.pop('index') return x, prev_y, y def deindexify_nparray(self, data, key): if data.ndim == 3: _data, index = data[..., 1:].astype(np.float32), data[:, -1, 0] elif data.ndim == 2: _data, index = data[..., 1:].astype(np.float32), data[:, 0] elif data.ndim == 4: _data, index = data[..., 1:].astype(np.float32), data[:, -1, -1, 0] elif data.ndim == 5: _data, index = data[..., 1:].astype(np.float32), data[:, -1, -1, -1, 0] else: raise NotImplementedError if self.index_types[key] != 'str': index = np.array(index, dtype=np.int64) return _data, index class SiteDistributedDataHandler(object): """Prepares data for mulpltiple sites/locations. This class is useful to prepare data when we have data of different sites/locations. A `site` here refers to a specific context i.e. data of one site is different from another site. In such a case, training and test spearation can be done in one of following two ways 1) We may wish to use data of some sites for training and data of some other sites for validation and/or test. In such a case, the user must provide the names of sites as `training_sites`, `validation_sites` and `test_sites`. 2) We may wish to use a fraction of data from each site for training validation and test. In such a case, do not provide any argument for `training_sites`, `validation_sites` and `test_sites`, rather define the validation and test fraction for each site using the keyword arguments. Note: The first two axis of the output data are swapped unless `swap_axes` is set to `False`. That means for 3d batches the x will have the shape: `(num_examples, num_sites, lookback, input_features)` And the `y` will have shape: `(num_examples, num_sites, num_outs, forecast_len)` See Example for more illustration Methods ----------------- - training_data - validation_data - test_data """ def __init__(self, data: dict, config: dict, training_sites: list = None, validation_sites: list = None, test_sites: list = None, swap_axes: bool = True, allow_variable_len: bool = False, verbosity: int = 1 ): """ Initiates data Arguments: data : Must be a dictionary of data for each site. config : Must be a dictionary of keyword arguments for each site. The keys of `data` and `config` must be same. training_sites : List of names of sites to be used as training. If `None`, data from all sites will be used to extract training data based upon keyword arguments of corresponding site. validation_sites : List of names of sites to be used as validation. test_sites : List of names of sites to be used as test. swap_axes : If True, the returned x data will have shape `(num_examples, num_sites, lookback, input_features)` otherwise the returned x values will have shape `(num_sites, num_examples, lookback, input_features)`. allow_variable_len : If the number of examples for different sites differ from each other, then this argument can be set to `True` to avoid `ValueError` from numpy. If the data of different sites results in different number of examples and this argument is False, then numpy will raise `ValueError` because arrays of different lengths can not be stacked together. If this argument is set to `True`, then the returned `x` will not be a numpy array but it will be a dictionary of numpy arrays where each key correspond to one `site`. Note that setting this argument to `True` will render `swap_axes` redundent. Example ------- ```python examples = 50 data = np.arange(int(examples * 3), dtype=np.int32).reshape(-1, examples).transpose() df = pd.DataFrame(data, columns=['a', 'b', 'c'], index=pd.date_range('20110101', periods=examples, freq='D')) config = {'input_features': ['a', 'b'], 'output_features': ['c'], 'lookback': 4} data = {'0': df, '1': df, '2': df, '3': df} configs = {'0': config, '1': config, '2': config, '3': config} dh = SiteDistributedDataHandler(data, configs) train_x, train_y = dh.training_data() val_x, val_y = dh.validation_data() test_x, test_y = dh.test_data() dh = SiteDistributedDataHandler(data, configs, training_sites=['0', '1'], validation_sites=['2'], test_sites=['3']) train_x, train_y = dh.training_data() val_x, val_y = dh.validation_data() test_x, test_y = dh.test_data() ``` A slightly more complicated example where data of each site consits of 2 sources ```python examples = 40 data = np.arange(int(examples * 4), dtype=np.int32).reshape(-1, examples).transpose() cont_df = pd.DataFrame(data, columns=['a', 'b', 'c', 'd'], index=pd.date_range('20110101', periods=examples, freq='D')) static_df = pd.DataFrame(np.array([[5],[6], [7]]).repeat(examples, axis=1).transpose(), columns=['len', 'dep', 'width'], index=pd.date_range('20110101', periods=examples, freq='D')) config = {'input_features': {'cont_data': ['a', 'b', 'c'], 'static_data': ['len', 'dep', 'width']}, 'output_features': {'cont_data': ['d']}, 'lookback': {'cont_data': 4, 'static_data':1} } data = {'cont_data': cont_df, 'static_data': static_df} datas = {'0': data, '1': data, '2': data, '3': data, '4': data, '5': data, '6': data} configs = {'0': config, '1': config, '2': config, '3': config, '4': config, '5': config, '6': config} dh = SiteDistributedDataHandler(datas, configs) train_x, train_y = dh.training_data() val_x, val_y = dh.validation_data() test_x, test_y = dh.test_data() dh = SiteDistributedDataHandler(datas, configs, training_sites=['0', '1', '2'], validation_sites=['3', '4'], test_sites=['5', '6']) train_x, train_y = dh.training_data() val_x, val_y = dh.validation_data() test_x, test_y = dh.test_data() ``` """ assert isinstance(data, dict), f'data must be of type dict but it is of type {data.__class__.__name__}' self.data = data new_config = self.process_config(config) if training_sites is not None: assert all([isinstance(obj, list) for obj in [training_sites, validation_sites, test_sites]]) for site in [training_sites, validation_sites, test_sites]: for s in site: assert s in data self.config = new_config self.training_sites = training_sites self.validation_sites = validation_sites self.test_sites = test_sites self.swap_axes = swap_axes self.allow_variable_len = allow_variable_len self.dhs = {} self.verbosity = verbosity def process_config(self, config): assert isinstance(config, dict) if len(config) > 1: for k in self.data.keys(): assert k in config, f'{k} present in data but not available in config' new_config = config.copy() else: new_config = {} for k in self.data.keys(): new_config[k] = config return new_config def training_data(self) -> Tuple[np.ndarray, np.ndarray]: """Returns the x,y pairs for training data""" x, y = [], [] training_sites = self.training_sites if training_sites is None: training_sites = self.data.keys() for site in training_sites: src, conf = self.data[site], self.config[site] conf['verbosity'] = 0 if self.training_sites is not None: conf['test_fraction'] = 0.0 conf['val_fraction'] = 0.0 dh = DataHandler(src, **conf) self.dhs[site] = dh # save in memory _x, _y = dh.training_data() x.append(_x) y.append(_y) x = self.stack(x, training_sites) y = self.stack(y, training_sites) if self.verbosity: print(f"{'*' * 5} Training data {'*' * 5}") print_something(x, 'x') print_something(y, 'y') return x, y def validation_data(self) -> Tuple[np.ndarray, np.ndarray]: """Returns the x,y pairs for the validation data""" x, y = [], [] validation_sites = self.validation_sites if validation_sites is None: validation_sites = self.data.keys() for site in validation_sites: src, conf = self.data[site], self.config[site] conf['verbosity'] = 0 if self.validation_sites is not None: # we have sites, so all the data from these sites is used as validation conf['test_fraction'] = 0.0 conf['val_fraction'] = 0.0 dh = DataHandler(src, **conf) self.dhs[site] = dh # save in memory _x, _y = dh.training_data() else: dh = DataHandler(src, **conf) self.dhs[site] = dh # save in memory _x, _y = dh.validation_data() x.append(_x) y.append(_y) x = self.stack(x, validation_sites) y = self.stack(y, validation_sites) if self.verbosity: print(f"{'*' * 5} Validation data {'*' * 5}") print_something(x, 'x') print_something(y, 'y') return x, y def test_data(self) -> Tuple[np.ndarray, np.ndarray]: """Returns the x,y pairs for the test data""" x, y = [], [] test_sites = self.test_sites if test_sites is None: test_sites = self.data.keys() for site in test_sites: src, conf = self.data[site], self.config[site] if self.test_sites is not None: # we have sites, so all the data from these sites is used as test conf['test_fraction'] = 0.0 conf['val_fraction'] = 0.0 conf['verbosity'] = 0 dh = DataHandler(src, **conf) self.dhs[site] = dh # save in memory _x, _y = dh.training_data() else: conf['verbosity'] = 0 dh = DataHandler(src, **conf) _x, _y = dh.test_data() x.append(_x) y.append(_y) x = self.stack(x, test_sites) y = self.stack(y, test_sites) if self.verbosity: print(f"{'*' * 5} Test data {'*' * 5}") print_something(x, 'x') print_something(y, 'y') return x, y def stack(self, data: list, site_names): if isinstance(data[0], np.ndarray): if len(set([len(i) for i in data])) == 1: # all arrays in data are of equal length data = np.stack(data) # (num_sites, num_examples, lookback, num_features) if self.swap_axes: data = data.swapaxes(0, 1) # (num_examples, num_sites, lookback, num_features) elif self.allow_variable_len: data = {k: v for k, v in zip(site_names, data)} else: raise NotImplementedError(f"number of examples are {[len(i) for i in data]}. " f"set `allow_variable_len` to `True`") elif isinstance(data[0], dict): if self.allow_variable_len: raise NotImplementedError # todo new_data = {k: None for k in data[0].keys()} for src_name in new_data.keys(): temp = [] for src in data: temp.append(src[src_name]) if self.swap_axes: new_data[src_name] = np.stack(temp).swapaxes(0, 1) else: new_data[src_name] = np.stack(temp) data = new_data else: raise ValueError return data class MultiLocDataHandler(object): def __init__(self): pass def training_data(self, data, **kwargs): dh = DataHandler(data=data, val_fraction=0.0, test_fraction=0.0, save=False, verbosity=0, **kwargs) setattr(self, 'train_dh', dh) return dh.training_data() def validation_data(self, data, **kwargs) -> Tuple[np.ndarray, np.ndarray]: dh = DataHandler(data=data, val_fraction=0.0, test_fraction=0.0, save=False, verbosity=0, **kwargs) setattr(self, 'val_dh', dh) return dh.training_data() def test_data(self, data, **kwargs): dh = DataHandler(data=data, val_fraction=0.0, test_fraction=0.0, save=False, verbosity=0, **kwargs) setattr(self, 'test_dh', dh) return dh.training_data() def decode(json_string): return json.loads(json_string, object_hook=_decode_helper) def _decode_helper(obj): """A decoding helper that is TF-object aware.""" if isinstance(obj, dict) and 'class_name' in obj: if obj['class_name'] == '__tuple__': return tuple(_decode_helper(i) for i in obj['items']) elif obj['class_name'] == '__ellipsis__': return Ellipsis return obj def load_data_from_hdf5(data_type, data): f = h5py.File(data, mode='r') weight_names = ['x', 'prev_y', 'y'] g = f[data_type] weight_values = (np.asarray(g[weight_name]) for weight_name in weight_names) f.close() return weight_values def save_in_a_group(x, prev_y, y, group_name, prefix=None): container = {} if x is not None: key = f'{prefix}_x' if prefix else 'x' container[key] = x if prev_y is not None: key = f'{prefix}_prev_y' if prefix else 'prev_y' container[key] = prev_y if y is not None: key = f'{prefix}_y' if prefix else 'y' container[key] = y for name, val in container.items(): param_dset = group_name.create_dataset(name, val.shape, dtype=val.dtype) if not val.shape: # scalar param_dset[()] = val else: param_dset[:] = val return def make_config(**kwargs): return kwargs def copy_features(features): if isinstance(features, str): _features = copy.deepcopy(features) elif isinstance(features, list) or isinstance(features, pd.Index): _features = [] for f in features: _features.append(copy.deepcopy(f)) else: raise NotImplementedError return _features def conform_shape(data, shape, features=None): # if the difference is of only 1 dim, we resolve it if data.ndim > len(shape): data = np.squeeze(data, axis=-1) elif data.ndim < len(shape): data = np.expand_dims(data, axis=-1) assert data.ndim == len(shape), f"original data had {len(shape)} wihle the new data has {data.ndim} dimensions" dummy_features = shape[-1] - data.shape[-1] # how manu dummy features we have to add to match the shape if data.__class__.__name__ in ['DataFrame', 'Series']: # we know what features must be in data, so put them in data one by one if they do not exist in data already if features: for f in features: if f not in data: data[f] = np.random.random(len(data)) # identify how many features to be added by shape information elif dummy_features > 0: dummy_data = pd.DataFrame(np.random.random((len(data), dummy_features))) data = pd.concat([dummy_data, data], axis=1) else: dummy_data = np.random.random((len(data), dummy_features)) data = np.concatenate([dummy_data, data], axis=1) return data, dummy_features def consider_intervals(data, intervals): _source = data if intervals is not None: if isinstance(data, pd.DataFrame): try: # if indices in intervals are of same type as that of index # -1 so that .loc and .iloc give same results, however this is not possible # with DatetimeIndex if isinstance(data.index, pd.DatetimeIndex): _source = pd.concat([data.loc[st:en] for st, en in intervals]) else: _source = pd.concat([data.loc[st:en - 1] for st, en in intervals]) except TypeError: # assuming indices in intervals are integers _source = pd.concat([data.iloc[st:en] for st, en in intervals]) return _source def tot_obs_for_one_df(data, allow_nan_labels, output_features, lookback, input_step, num_outs, forecast_step, forecast_len, intervals, input_features:list): data = consider_intervals(data, intervals) max_tot_obs = 0 if not allow_nan_labels and intervals is None: _data = data[input_features + output_features] if isinstance(data, pd.DataFrame) else data x, _, _ = prepare_data(_data, lookback, num_outputs=num_outs, input_steps=input_step, forecast_step=forecast_step, forecast_len=forecast_len, mask=np.nan) max_tot_obs = len(x) # we need to ignore some values at the start more = (lookback * input_step) - 1 if isinstance(data, np.ndarray): return len(data) - more # todo, why not when allow_nan_labels>0? if forecast_step > 0: more += forecast_step if forecast_len > 1: more += forecast_len if intervals is None: intervals = [()] more *= len(intervals) if allow_nan_labels == 2: tot_obs = data.shape[0] - more elif allow_nan_labels == 1: label_y = data[output_features].values idx = ~np.array([all([np.isnan(x) for x in label_y[i]]) for i in range(len(label_y))]) tot_obs = np.sum(idx) - more else: if num_outs == 1: tot_obs = data.shape[0] - int(data[output_features].isna().sum()) - more tot_obs = max(tot_obs, max_tot_obs) else: # count by droping all the rows when nans occur in output features tot_obs = len(data.dropna(subset=output_features)) tot_obs -= more return tot_obs def batch_dim_from_lookback(lookback): default = "3D" if lookback == 1: default = "2D" return default def deindexify_y(x: list, prev_y: list, y:list, based_upon: int): indices_to_keep = [] for e in y[based_upon]: indices_to_keep.append(int(e[-1])) if isinstance(x, list): return deindexify_lists(x, prev_y, y, indices_to_keep) else: return deindexify_dicts(x, prev_y, y, indices_to_keep) def deindexify_lists(x, prev_y, y, indices_to_keep): _x, _prevy, _y = [], [], [] # for x,y of each source for xi, prevyi, yi in zip(x, prev_y, y): __x, __prevy, __y = [], [], [] # for individual examples of one source, check that if that example is to included or not for _xi, _prevyi, _yi in zip(xi, prevyi, yi): if int(_yi[-1]) in indices_to_keep: __x.append(_xi) __prevy.append(_prevyi) __y.append(_yi[0:-1]) # don't consider the last value, that was dummy_index _x.append(np.stack(__x)) _prevy.append(np.stack(__prevy)) _y.append(np.stack(__y)) return _x, _prevy, _y def deindexify_dicts(x: dict, prev_y: dict, y: dict, indices_to_keep): _x, _prevy, _y = {}, {}, {} for (key, xi), (key, prevyi), (key, yi) in zip(x.items(), prev_y.items(), y.items()): __x, __prevy, __y = [], [], [] # for individual examples of one source, check that if that example is to included or not for _xi, _prevyi, _yi in zip(xi, prevyi, yi): if int(_yi[-1]) in indices_to_keep: __x.append(_xi) __prevy.append(_prevyi) __y.append(_yi[0:-1]) # don't consider the last value, that was dummy_index _x[key] = np.stack(__x) _prevy[key] = np.stack(__prevy) _y[key] = np.stack(__y) return _x, _prevy, _y def filter_zero_sized_arrays(array): if isinstance(array, list): new_array = [] for a in array: if a.size > 0: new_array.append(a) elif isinstance(array, dict): new_array = {} for k, v in array.items(): if v.size > 0: new_array[k] = v else: new_array = array return new_array def check_for_classification(label: np.ndarray, to_categorical): assert isinstance(label, np.ndarray), f""" classification problem for label of type {label.__class__.__name__} not implemented yet""" # for clsasification, it should be 2d label = label.reshape(-1, label.shape[1]) if to_categorical: assert label.shape[1] == 1 label = OneHotEncoder(sparse=False).fit_transform(label) # else: # mutlti_label/binary problem # # todo, is only binary_crossentropy is binary/multi_label problem? # pass #assert self.loss_name() in ['binary_crossentropy'] return label def return_x_yy(x, prev_y, y, initial, verbosity): if verbosity > 0: print(f"{'*' * 5} {initial} data {'*' * 5}") print_something(x, "input_x") print_something(prev_y, "prev_y") print_something(y, "target") return x, prev_y, y def return_xy(x, y, initial, verbosity): if verbosity > 0: print(f"{'*' * 5} {initial} {'*' * 5}") print_something(x, "input_x") print_something(y, "target") return x, y
38.74087
153
0.556444
import os import copy import json import warnings from typing import Union, Tuple import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.patches import Patch from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold, LeaveOneOut, TimeSeriesSplit from sklearn.preprocessing import OneHotEncoder from ai4water.utils.utils import prepare_data, jsonize, to_datetime_index from ai4water.datasets import all_datasets from ai4water.preprocessing.transformations import Transformations from ai4water.preprocessing.imputation import Imputation import ai4water.datasets as datasets from ai4water.utils.utils import print_something cmap_cv = plt.cm.coolwarm try: import h5py except ModuleNotFoundError: h5py = None class AttributeContainer(object): def __init__(self): self._from_h5 = False self.is_multi_source = False self.source_is_list = False self.source_is_dict = False class DataHandler(AttributeContainer): def __init__(self, data, input_features: Union[list, dict, str, None] = None, output_features: Union[list, dict, str, None] = None, dataset_args: dict = None, val_fraction: float = 0.2, test_fraction: float = 0.2, input_step: int = 1, lookback: int = 1, forecast_len: int = 1, forecast_step: int = 0, known_future_inputs: bool = False, allow_input_nans: bool = False, train_data: Union[str, list] = None, val_data: Union[str, list, np.ndarray, None] = None, intervals=None, transformation: Union[str, list, dict] = None, shuffle: bool = True, allow_nan_labels: int = 0, nan_filler: dict = None, batch_size: int = 32, drop_remainder: bool = False, teacher_forcing: bool = False, seed: int = 313, save: bool = False, verbosity: int = 1, mode=None, category=None, ): super().__init__() self.config = make_config(input_features=input_features, output_features=output_features, dataset_args=dataset_args or {}, val_fraction=val_fraction, test_fraction=test_fraction, input_step=input_step, lookback=lookback, forecast_len=forecast_len, forecast_step=forecast_step, known_future_inputs=known_future_inputs, allow_input_nans=allow_input_nans, train_data=train_data, val_data=val_data, intervals=intervals, transformation=transformation, shuffle=False, allow_nan_labels=allow_nan_labels, nan_filler=nan_filler, batch_size=batch_size, drop_remainder=drop_remainder, seed=seed, category=category, ) self.data = self._process_source(data, input_features, output_features) self.verbosity = verbosity self.teacher_forcing = teacher_forcing self.mode = mode self.scalers = {} self.indexes = {} if save: self._to_disk() def __getattr__(self, item): if item in ['lookback', 'input_step', 'transformation', 'forecast_step', 'forecast_len', 'known_future_inputs', 'allow_nan_labels', 'allow_input_nans']: if self.source_is_df: return self.config[item] elif self.source_is_list: attr = self.config[item] if not isinstance(attr, list): attr = [attr for _ in range(len(self.data))] assert len(attr) == len(self.data) return attr elif self.source_is_dict: attr = self.config[item] if not isinstance(attr, dict): attr = {key: attr for key in self.data.keys()} assert len(attr) == len(self.data), f"There are {len(attr)} values for {item} while" \ f" {len(self.data)} values for data" return attr else: raise NotImplementedError(f"Unknown data type {self.data.__class__.__name__}") else: raise AttributeError(f"DataLoader does not have an attribute {item}") @property def classes(self): _classes = [] if self.mode == 'classification': if self.num_outs == 1: array = self.data[self.output_features].values _classes = np.unique(array[~np.isnan(array)]) else: _classes = self.output_features return _classes @property def num_classes(self): return len(self.classes) @property def is_binary(self) -> bool: _default = False if self.mode == 'classification': if self.num_outs == 1: array = self.data[self.output_features].values unique_vals = np.unique(array[~np.isnan(array)]) if len(unique_vals) == 2: _default = True else: pass return _default @property def is_multiclass(self) -> bool: _default = False if self.mode == 'classification': if self.num_outs == 1: array = self.data[self.output_features].values unique_vals = np.unique(array[~np.isnan(array)]) if len(unique_vals) > 2: _default = True else: pass return _default @property def is_multilabel(self) -> bool: _default = False if self.mode == 'classification': if self.num_outs > 1: _default = True return _default @property def _to_categorical(self): _defualt = False if self.is_binary or self.is_multiclass: if self.num_outs == 1: _defualt = True if self.is_binary and self.category == 'ML': _defualt = False return _defualt @property def teacher_forcing(self): return self._teacher_forcing @teacher_forcing.setter def teacher_forcing(self, x): self._teacher_forcing = x @property def category(self): return self.config['category'] @property def batch_dim(self): if self.source_is_df: batch_dim = batch_dim_from_lookback(self.lookback) elif self.source_is_list: if isinstance(self.lookback, int): batch_dim = [batch_dim_from_lookback(self.lookback) for _ in range(len(self.data))] elif isinstance(self.lookback, list): batch_dim = [batch_dim_from_lookback(lb) for lb in self.lookback] else: raise NotImplementedError elif self.source_is_dict: if isinstance(self.lookback, int): batch_dim = {k: batch_dim_from_lookback(self.lookback) for k, v in zip(self.data.keys(), range(len(self.data)))} elif isinstance(self.lookback, dict): batch_dim = {k: batch_dim_from_lookback(lb) for k, lb in self.lookback.items()} else: raise NotImplementedError(f"incompatible lookback {self.lookback} with data " f"definition {self.data.__class__.__name__}.") else: raise NotImplementedError return batch_dim @property def is_multiinput(self): if len(self.num_outs) > 1: return True return False @property def input_features(self): _inputs = self.config['input_features'] if isinstance(self.data, list): assert isinstance(_inputs, list) elif isinstance(self.data, dict): assert isinstance(_inputs, dict), f'input_features are of type {_inputs.__class__.__name__}' elif _inputs is None and self.data is not None: assert isinstance(self.data, pd.DataFrame) _inputs = self.data.columns[0:-1].to_list() return _inputs @property def output_features(self): _outputs = self.config['output_features'] if isinstance(self.data, list): assert isinstance(_outputs, list) elif isinstance(self.data, dict): assert isinstance(_outputs, dict), f'data is of type dict while output_features are ' \ f'of type {_outputs.__class__.__name__}' for k in self.data.keys(): if k not in _outputs: _outputs[k] = [] elif _outputs is None and self.data is not None: assert isinstance(self.data, pd.DataFrame) _outputs = [col for col in self.data.columns if col not in self.input_features] return _outputs @property def is_multioutput(self): if isinstance(self.data, list) or isinstance(self.data, dict): return True return False @property def input_sources(self): return @property def output_sources(self): return @property def equal_io_sources(self): return @property def any_3d_source(self): return @property def all_2d_sources(self): return @property def all_3d_sources(self): return @property def source_is_df(self): if isinstance(self.data, pd.DataFrame): return True return False def len(self): if isinstance(self.data, pd.DataFrame): # the total number of examples will be less than _len = len(self.data) - (self.lookback - 1) elif isinstance(self.data, list): _len = 0 for s in self.data: _len += len(s) elif isinstance(self.data, dict): _len = 0 for k, v in self.data.items(): _len += len(v) else: raise NotImplementedError return _len def _process_source(self, data, input_features, output_features): if isinstance(data, str): _source = self._get_source_from_str(data, input_features, output_features) if isinstance(_source, str) and _source.endswith('.h5'): self._from_h5 = True self.num_sources = 1 elif isinstance(data, pd.DataFrame): if input_features is None and output_features is not None: if isinstance(output_features, str): output_features = [output_features] assert isinstance(output_features, list) input_features = [col for col in data.columns if col not in output_features] # since we have inferred the input_features, they should be put back into config self.config['input_features'] = input_features _source = data self.is_multi_source = False self.num_sources = 1 elif isinstance(data, np.ndarray): assert data.ndim == 2, f"input data as numpy array must be 2 dimension, found {data.ndim} dimensions" # if output_features is not defined, consider 1 output and name it as 'output' if output_features is None: output_features = ['outout'] self.config['output_features'] = output_features # we should put it in config as well elif isinstance(output_features, str): output_features = [output_features] else: assert isinstance(output_features, list) if input_features is None: # define dummy names for input_features input_features = [f'input_{i}' for i in range(data.shape[1]-len(output_features))] self.config['input_features'] = input_features _source = pd.DataFrame(data, columns=input_features + output_features) elif data.__class__.__name__ == "Dataset": _source = data self.num_sources = 1 elif isinstance(data, list): _source = [] for s in data: _source.append(self._process_one_source(s)) self.is_multi_source = True self.source_is_list = True self.num_sources = len(data) elif isinstance(data, dict): _source = {} for s_name, s_val in data.items(): _source[s_name] = self._process_one_source(s_val) self.is_multi_source = True self.source_is_dict = True self.num_sources = len(data) elif data is None: return data else: assert data is not None raise ValueError(f"unregnizable source of data of type {data.__class__.__name__} given") _source = self.impute(_source) return _source def add_noice(self): return @property def val_data(self): if self.source_is_df or self.source_is_list or self.source_is_dict: return self.config['val_data'] else: raise NotImplementedError def impute(self, data): if self.config['nan_filler'] is not None: if isinstance(data, pd.DataFrame): _source = self._impute_one_source(data, self.config['nan_filler']) else: raise NotImplementedError else: _source = data return _source def _impute_one_source(self, data, impute_config): if isinstance(impute_config, str): method, impute_args = impute_config, {} data = Imputation(data, method=method, **impute_args)() elif isinstance(impute_config, dict): data = Imputation(data, **impute_config)() elif isinstance(impute_config, list): for imp_conf in impute_config: data = Imputation(data, **imp_conf)() else: raise NotImplementedError(f'{impute_config.__class__.__name__}') return data def tot_obs_for_one_df(self): if self.source_is_df: tot_obs = tot_obs_for_one_df(self.data, self.allow_nan_labels, self.output_features, self.lookback, self.input_step, self.num_outs, self.forecast_step, self.forecast_len, self.config['intervals'], self.input_features, ) elif self.source_is_list: tot_obs = [] for idx in range(len(self.data)): _tot_obs = tot_obs_for_one_df(self.data[idx], self.allow_nan_labels[idx], self.output_features[idx], self.lookback[idx], self.input_step[idx], self.num_outs[idx], self.forecast_step[idx], self.forecast_len[idx], self.config['intervals'], self.input_features[idx] ) tot_obs.append(_tot_obs) elif self.source_is_dict: tot_obs = {} for src_name in self.data.keys(): _tot_obs = tot_obs_for_one_df(self.data[src_name], self.allow_nan_labels[src_name], self.output_features[src_name], self.lookback[src_name], self.input_step[src_name], self.num_outs[src_name], self.forecast_step[src_name], self.forecast_len[src_name], self.config['intervals'], self.input_features[src_name] ) tot_obs[src_name] = _tot_obs else: raise NotImplementedError return tot_obs def get_indices(self): if self.source_is_df or self.source_is_list or self.source_is_dict: indices = self.config['train_data'] if isinstance(indices, str): # if isinstance(indices, str): assert indices == 'random' tot_obs = self.tot_obs_for_one_df() # tot_obs can be dictionary because lookback is local # but tot_obs must be same for all sources if isinstance(tot_obs, dict): tot_obs = np.unique(list(tot_obs.values())).item() total_indices = np.arange(tot_obs) if self.config['test_fraction'] > 0.0: train_indices, test_indices = train_test_split(total_indices, test_size=self.config['test_fraction'], random_state=self.config['seed']) else: # all the indices belong to training train_indices, test_indices = total_indices, None elif indices is None: train_indices, test_indices = None, None else: assert isinstance(np.array(indices), np.ndarray) tot_obs = self.tot_obs_for_one_df() if isinstance(tot_obs, dict): tot_obs = np.unique(list(tot_obs.values())).item() tot_indices = np.arange(tot_obs) train_indices = np.array(indices) test_indices = np.delete(tot_indices, train_indices) else: raise NotImplementedError(f'Indices can not be found for source of type {self.data.__class__.__name__}') setattr(self, 'train_indices', train_indices) setattr(self, 'test_indices', test_indices) return train_indices, test_indices def get_train_args(self): indices = self.config['train_data'] if indices is not None: if isinstance(indices, str): assert indices == 'random', f'invalid value of indices {indices}' else: assert isinstance(np.array(indices), np.ndarray), f'invalid value of indices {indices}' train_indices, _ = self.get_indices() return train_indices @property def num_ins(self): if self.source_is_df or self.data is None: return len(self.input_features) elif self.source_is_list or self.data is None: return [len(in_feat) for in_feat in self.input_features] elif self.source_is_dict or self.data is None: return {k: len(in_feat) for k, in_feat in self.input_features.items()} else: raise NotImplementedError @property def num_outs(self): if self.source_is_df: return len(self.output_features) elif self.source_is_list: return [len(out_feat) for out_feat in self.output_features] elif self.source_is_dict: return {k: len(out_feat) for k, out_feat in self.output_features.items()} elif self.data.__class__.__name__ == "NoneType": return None else: raise NotImplementedError(f"Can not determine output features for data " f"of type {self.data.__class__.__name__}") def KFold_splits(self, n_splits=5): x, y = self._get_xy() spliter = self._get_kfold_splitter(x=x, n_splits=n_splits) for tr_idx, test_idx in spliter: yield (x[tr_idx], y[tr_idx]), (x[test_idx], y[test_idx]) def LeaveOneOut_splits(self): x, y = self._get_xy() kf = LeaveOneOut() for tr_idx, test_idx in kf.split(x): yield (x[tr_idx], y[tr_idx]), (x[test_idx], y[test_idx]) def TimeSeriesSplit_splits(self, n_splits=5, **kwargs): x, y = self._get_xy() tscv = TimeSeriesSplit(n_splits=n_splits, **kwargs) for tr_idx, test_idx in tscv.split(x): yield (x[tr_idx], y[tr_idx]), (x[test_idx], y[test_idx]) def _get_kfold_splitter(self, x, n_splits=5): kf = KFold(n_splits=n_splits, random_state=self.config['seed'] if self.config['shuffle'] else None, shuffle=self.config['shuffle']) spliter = kf.split(x) return spliter def plot_KFold_splits(self, n_splits=5, show=True, **kwargs): x, y = self._get_xy() spliter = self._get_kfold_splitter(x=x, n_splits=n_splits) self._plot_splits(spliter, x, title="KFoldCV", show=show, **kwargs) return def plot_LeaveOneOut_splits(self, show=True, **kwargs): x, y = self._get_xy() spliter = LeaveOneOut().split(x) self._plot_splits(spliter=spliter, x=x, title="LeaveOneOutCV", show=show, **kwargs) return def plot_TimeSeriesSplit_splits(self, n_splits=5, show=True, **kwargs): x, y = self._get_xy() spliter = TimeSeriesSplit(n_splits=n_splits, **kwargs).split(x) self._plot_splits(spliter=spliter, x=x, title="TimeSeriesCV", show=show, **kwargs) return def _plot_splits(self, spliter, x, show=True, **kwargs): splits = list(spliter) figsize = kwargs.get('figsize', (10, 8)) legend_fs = kwargs.get('legend_fs', 20) legend_pos = kwargs.get('legend_pos', (1.02, 0.8)) title = kwargs.get("title", "CV") plt.close('all') fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) for ii, split in enumerate(splits): indices = np.array([np.nan] * len(x)) indices[split[0]] = 1 indices[split[1]] = 0 ax.scatter(range(len(indices)), [ii + .5] * len(indices), c=indices, marker='_', lw=10, cmap="coolwarm", vmin=-.2, vmax=1.2) yticklabels = list(range(len(splits))) ax.set(yticks=np.arange(len(splits)) + .5, yticklabels=yticklabels, xlabel='Sample index', ylabel="CV iteration") ax.set_title(title, fontsize=20) ax.legend([Patch(color=cmap_cv(.8)), Patch(color=cmap_cv(.02))], ['Training set', 'Test set'], loc=legend_pos, fontsize=legend_fs) if show: plt.show() return def _get_xy(self): if self.teacher_forcing: tr_x, _, tr_y = self.training_data() val_x, _, val_y = self.validation_data() else: tr_x, tr_y = self.training_data() val_x, val_y = self.validation_data() def check_if_none(X, Y): if X is None: shape = list(tr_x.shape) shape[0] = 0 X = np.zeros(tuple(shape)) if Y is None: shape = list(tr_y.shape) shape[0] = 0 Y = np.zeros(tuple(shape)) return X, Y if self.source_is_df: val_x, val_y = check_if_none(val_x, val_y) x = np.concatenate([tr_x, val_x]) y = np.concatenate([tr_y, val_y]) else: raise NotImplementedError return x, y def make_val_frac_zero(self): # It is good that the user knows explicitly that either of val_fraction or test_fraction is used so # one of them must be set to 0.0 if self.config['val_fraction'] > 0.0: warnings.warn(f"Setting val_fraction from {self.config['val_fraction']} to 0.0") self.config['val_fraction'] = 0.0 return def _indexify_y(self, src: pd.DataFrame, out_features: list): # this function is only called when data is a list/dictionary src = src.copy() # make a copy so that df in original data is not altered # since there are multiple sources/dfs, we need to keep track that y's in each src['dummy_id'] = np.arange(len(src), dtype=np.int32) out_features = out_features + ['dummy_id'] return src, out_features def _make_data_for_one_src(self, key, indices, shuffle, identifier=None, deindexify=False ): data = self.data if identifier is None else self.data[identifier] output_features = self.output_features if identifier is None else self.output_features[identifier] if self.source_is_list and all([flag == 0 for flag in self.allow_nan_labels]): data, output_features = self._indexify_y(data, output_features) data_maker = MakeData( input_features=self.input_features if identifier is None else self.input_features[identifier], output_features=output_features, lookback=self.lookback if identifier is None else self.lookback[identifier], input_step=self.input_step if identifier is None else self.input_step[identifier], forecast_step=self.forecast_step if identifier is None else self.forecast_step[identifier], forecast_len=self.forecast_len if identifier is None else self.forecast_len[identifier], known_future_inputs=self.known_future_inputs if identifier is None else self.known_future_inputs[identifier], batch_dim=self.batch_dim if identifier is None else self.batch_dim[identifier], allow_input_nans=self.allow_input_nans if identifier is None else self.allow_input_nans[identifier], allow_nan_labels=self.allow_nan_labels if identifier is None else self.allow_nan_labels[identifier], verbosity=self.verbosity ) data, scalers = data_maker.transform( data=data, transformation=self.transformation if identifier is None else self.transformation[identifier], key=key ) self.scalers.update(scalers) if not isinstance(data, np.ndarray): data = data_maker.indexify(data, key) x, prev_y, y = data_maker( data, shuffle=shuffle, intervals=self.config['intervals'], indices=indices ) if x is not None and deindexify and not isinstance(data, np.ndarray): x, self.indexes[key] = data_maker.deindexify(x, key) return x, prev_y, y, data_maker def _post_process_train_args(self, x, prev_y, y): if self.val_data == 'same': self.make_val_frac_zero() if self.config['val_fraction'] + self.config['test_fraction'] > 0.0: if self.train_indices is None: train_frac = 1.0 - self.config['test_fraction'] train_idx_en = int(round(train_frac * len(x))) x = x[0: train_idx_en, ...] prev_y = prev_y[0: train_idx_en, ...] y = y[0: train_idx_en, ...] if self.config['val_fraction'] > 0.0: train_frac = 1.0 - self.config['val_fraction'] train_idx_en = int(round(train_frac * len(x))) x = x[0: train_idx_en, ...] prev_y = prev_y[0: train_idx_en, ...] y = y[0: train_idx_en, ...] return x, prev_y, y def training_data(self, key: str = None, **kwargs) -> Tuple[np.ndarray, np.ndarray]: if self._from_h5: return load_data_from_hdf5('training_data', self.data) train_indices = self.get_train_args() if self.source_is_df: x, prev_y, y, data_maker = self._make_data_for_one_src( key, train_indices, False, deindexify=False ) x, prev_y, y = self._post_process_train_args(x, prev_y, y) x, prev_y, y = self.check_for_batch_size(x, prev_y, y) if not isinstance(self.data, np.ndarray): x, self.indexes[key] = data_maker.deindexify(x, key) elif self.is_multi_source: if self.source_is_list: x, prev_y, y = [], [], [] for idx, src in enumerate(self.data): _key = f'{key}_{idx}' _x, _prev_y, _y, data_maker = self._make_data_for_one_src( f'{key}_{idx}', train_indices, False, identifier=idx, deindexify=False, ) _x, _prev_y, _y = self._post_process_train_args(_x, _prev_y, _y) _x, _prev_y, _y = self.check_for_batch_size(_x, _prev_y, _y) if not isinstance(self.data[idx], np.ndarray): _x, self.indexes[_key] = data_maker.deindexify(_x, f'{key}_{idx}') x.append(_x) prev_y.append(_prev_y) y.append(_y) if 'dummy_id' in data_maker.output_features: x, prev_y, y = deindexify_y(x, prev_y, y, np.argmax(self.lookback).item()) elif self.source_is_dict: x, prev_y, y = {}, {},{} for src_name, src in self.data.items(): _key = f'{key}_{src_name}' _x, _prev_y, _y, data_maker = self._make_data_for_one_src( f'{key}_{src_name}', train_indices, False, identifier=src_name, deindexify=False ) _x, _prev_y, _y = self._post_process_train_args( _x, _prev_y, _y ) _x, _prev_y, _y = self.check_for_batch_size(_x, _prev_y, _y) if not isinstance(self.data[src_name], np.ndarray): _x, self.indexes[_key] = data_maker.deindexify(_x, f'{key}_{src_name}') x[src_name], prev_y[src_name], y[src_name] = _x, _prev_y, _y else: raise NotImplementedError elif isinstance(self.data, dict) or isinstance(self.data, list): raise NotImplementedError else: raise NotImplementedError prev_y = filter_zero_sized_arrays(prev_y) y = filter_zero_sized_arrays(y) if self.mode == 'classification': y = check_for_classification(y, self._to_categorical) if self.teacher_forcing: return return_x_yy(x, prev_y, y, "Training", self.verbosity) return return_xy(x, y, "Training", self.verbosity) def _make_val_data_from_src(self, indices, key, tot_obs, identifier=None ): x, prev_y, y = None, None, None run = True split1 = False split2 = False if self.val_data == "same": self.make_val_frac_zero() assert self.config['test_fraction'] > 0.0, f"test_fraction should be > 0.0. " \ f"It is {self.config['test_fraction']}" if indices is None: split1 = True elif np.array(self.val_data).shape.__len__() > 0: indices = np.array(self.val_data) elif self.config['val_fraction'] == 0.0: run = False else: if indices is None: indices = self.get_train_args() split2 = True if run: x, prev_y, y, data_maker = self._make_data_for_one_src( key, indices, False, identifier=identifier ) if split1: train_frac = 1.0 - self.config['test_fraction'] test_frac = self.config['test_fraction'] train_idx_en = int(round(train_frac * len(x))) test_idx_st = train_idx_en + int(round(train_frac + test_frac * len(x))) x = x[train_idx_en: test_idx_st, ...] prev_y = prev_y[train_idx_en: test_idx_st, ...] y = y[train_idx_en: test_idx_st, ...] elif indices is None and self.config['val_fraction'] == 0.0: x, prev_y, y = None, None, None elif split2: if indices is None: train_frac = 1.0 - self.config['test_fraction'] train_idx_en = int(round(train_frac * len(x))) x = x[0: train_idx_en, ...] prev_y = prev_y[0: train_idx_en, ...] y = y[0: train_idx_en, ...] else: train_idx_en = len(x) if self.config['val_fraction']>0.0: train_frac = 1.0 - self.config['val_fraction'] train_idx_st = int(round(train_frac * len(x))) x = x[train_idx_st:train_idx_en, ...] prev_y = prev_y[train_idx_st:train_idx_en, ...] y = y[train_idx_st:train_idx_en, ...] if x is not None: if x.shape[0] == 0: x, prev_y, y = None, None, None else: if identifier and isinstance(self.data[identifier], np.ndarray): pass else: x, prev_y, y = self.check_for_batch_size(x, prev_y, y) x, self.indexes[key] = data_maker.deindexify(x, key) return x, prev_y, y def validation_data(self, key='val', **kwargs ) -> Tuple[Union[np.ndarray, None], Union[np.ndarray, None]]: if self._from_h5: return load_data_from_hdf5('validation_data', self.data) if getattr(self, 'val_dataset', None).__class__.__name__ in ['BatchDataset', 'TorchDataset']: return self.val_dataset test_indices = None if self.config['val_data'] == 'same': _, test_indices = self.get_indices() if self.source_is_df: x, prev_y, y = self._make_val_data_from_src( test_indices, key, self.tot_obs_for_one_df() ) elif self.source_is_list: x, prev_y, y = [], [], [] for idx, src in enumerate(self.data): output_features = self.output_features[idx] if all([flag == 0 for flag in self.allow_nan_labels]): src, output_features = self._indexify_y(src, output_features) _x, _prev_y, _y = self._make_val_data_from_src( test_indices, f'{key}_{idx}', self.tot_obs_for_one_df()[idx], identifier=idx ) x.append(_x) prev_y.append(_prev_y) if _y.size > 0: y.append(_y) if 'dummy_id' in output_features: x, prev_y, y = deindexify_y(x, prev_y, y, np.argmax(self.lookback).item()) elif self.source_is_dict: x, prev_y, y = {}, {}, {} for src_name, src in self.data.items(): _x, _prev_y, _y = self._make_val_data_from_src( test_indices, f'{key}_{src_name}', self.tot_obs_for_one_df()[src_name], identifier=src_name ) x[src_name] = _x prev_y[src_name] = _prev_y y[src_name] = _y elif self.data.__class__.__name__ == "NoneType": return None, None else: raise NotImplementedError(f"Can not calculate validation data for data " f"of type {self.data.__class__.__name__}") prev_y = filter_zero_sized_arrays(prev_y) y = filter_zero_sized_arrays(y) if self.mode == 'classification': y = check_for_classification(y, self._to_categorical) if self.teacher_forcing: return return_x_yy(x, prev_y, y, "Validation", self.verbosity) return return_xy(x, y, "Validation", self.verbosity) def test_data(self, key='test', data_keys=None, **kwargs ) -> Tuple[Union[np.ndarray, None], Union[np.ndarray, None]]: if self._from_h5: return load_data_from_hdf5('test_data', self.data) if self.config['val_data'] == "same" and self.data is None: return self.validation_data(key=key, data_keys=data_keys, **kwargs) if self.data.__class__.__name__ == "NoneType": return None, None _, test_indices = self.get_indices() if self.val_data == "same": return self.validation_data(key=key) if self.source_is_df: x, prev_y, y = self.test_data_from_one_src( key, test_indices, self.tot_obs_for_one_df() ) elif self.source_is_list: x, prev_y, y = [], [], [] for idx, src in enumerate(self.data): output_features = self.output_features[idx] if all([flag == 0 for flag in self.allow_nan_labels]): src, output_features = self._indexify_y(src, output_features) _x, _prev_y, _y = self.test_data_from_one_src( f'{key}_{idx}', test_indices, self.tot_obs_for_one_df()[idx], identifier=idx ) x.append(_x) prev_y.append(_prev_y) if _y.size > 0: y.append(_y) if 'dummy_id' in output_features: x, prev_y, y = deindexify_y(x, prev_y, y, np.argmax(self.lookback).item()) elif self.source_is_dict: x, prev_y, y = {}, {}, {} for src_name, src in self.data.items(): x[src_name], prev_y[src_name], y[src_name] = self.test_data_from_one_src( f'{key}_{src_name}', test_indices, self.tot_obs_for_one_df()[src_name], identifier=src_name, ) else: raise NotImplementedError prev_y = filter_zero_sized_arrays(prev_y) y = filter_zero_sized_arrays(y) if self.mode == 'classification': y = check_for_classification(y, self._to_categorical) if self.teacher_forcing: return return_x_yy(x, prev_y, y, "Test", self.verbosity) return return_xy(x, y, "Test", self.verbosity) def test_data_from_one_src(self, key, test_indices, tot_obs, identifier=None ): x, prev_y, y, data_maker = self._make_data_for_one_src( key, test_indices, False, identifier=identifier ) if test_indices is None: train_frac = 1.0 - self.config['test_fraction'] train_idx_en = int(round(train_frac * len(x))) x = x[train_idx_en:, ...] prev_y = prev_y[train_idx_en:, ...] y = y[train_idx_en:, ...] if x is not None: if x.shape[0] == 0: x, prev_y, y = None, None, None else: if identifier and isinstance(self.data[identifier], np.ndarray): pass else: x, prev_y, y = self.check_for_batch_size(x, prev_y, y) x, self.indexes[key] = data_maker.deindexify(x, key) return x, prev_y, y def deindexify(self, data, key): if self.source_is_df: if key not in self.indexes: raise ValueError(f"key `{key}` not found. Available keys are {list(self.indexes.keys())}") index = self.indexes[key] elif self.source_is_list: index = None for idx, src in enumerate(data): _key = f'{key}_{idx}' if _key not in self.indexes: raise ValueError(f"key `{_key}` not found. Available keys are {list(self.indexes.keys())}") index = self.indexes[_key] elif self.source_is_dict: index = None for src_name, src in data.items(): _key = f'{key}_{src_name}' if _key not in self.indexes: raise ValueError(f"key `{_key}` not found. Available keys are {list(self.indexes.keys())}") index = self.indexes[_key] else: raise ValueError return data, index def transform(self): return def inverse_transform(self, data, key): transformation = self.transformation if self.source_is_df: data = self._inv_transform_one_src(data, key, transformation) elif self.source_is_list: assert isinstance(data, list) _data = [] for idx, src in enumerate(data): __data = self._inv_transform_one_src(src, f'{key}_{idx}', transformation[idx]) _data.append(__data) data = _data elif self.source_is_dict: assert isinstance(data, dict) _data = {} for src_name, src in data.items(): _data[src_name] = self._inv_transform_one_src(src, f'{key}_{src_name}', transformation[src_name]) data = _data else: raise NotImplementedError return data def _inv_transform_one_src(self, data, key, transformation): if transformation is not None: if isinstance(transformation, str): if key not in self.scalers: raise ValueError(f""" key `{key}` for inverse transformation not found. Available keys are {list(self.scalers.keys())}""") scaler = self.scalers[key] scaler, shape, _key = scaler['scaler'], scaler['shape'], scaler['key'] original_shape = data.shape data, dummy_features = conform_shape(data, shape) transformed_data = scaler.inverse_transform(data) data = transformed_data[:, dummy_features:] data = data.reshape(original_shape) elif isinstance(transformation, list): assert data.__class__.__name__ in ['DataFrame', 'Series'] for idx, trans in reversed(list(enumerate(transformation))): if trans['method'] is not None: features = trans['features'] if any([True if f in data else False for f in features]): orig_cols = data.columns scaler = self.scalers[f'{key}_{trans["method"]}_{idx}'] scaler, shape, _key = scaler['scaler'], scaler['shape'], scaler['key'] data, dummy_features = conform_shape(data, shape, features) transformed_data = Transformations(data=data, **trans)(what='inverse', scaler=scaler) data = transformed_data[orig_cols] elif isinstance(transformation, dict): assert data.__class__.__name__ in ['DataFrame', 'Series'], f'data is of type {data.__class__.__name__}' if any([True if f in data else False for f in transformation['features']]): orig_cols = data.columns scaler = self.scalers[key] scaler, shape, _key = scaler['scaler'], scaler['shape'], scaler['key'] data, dummy_features = conform_shape(data, shape, features=transformation['features']) transformed_data = Transformations(data=data, **transformation)(what='inverse', scaler=scaler) data = transformed_data[orig_cols] return data def check_nans(self): return @classmethod def from_h5(cls, path): f = h5py.File(path, mode='r') config = {} for k, v in f.attrs.items(): if isinstance(v, bytes): v = decode(v) config[k] = v cls._from_h5 = True f.close() return cls(path, **config) def _to_disk(self, path=None): path = path or os.path.join(os.getcwd(), "results") filepath = os.path.join(path, "data.h5") f = h5py.File(filepath, mode='w') for k,v in self.config.items(): if isinstance(v, (dict, list, tuple)): f.attrs[k] = json.dumps( v, default=jsonize).encode('utf8') elif v is not None: f.attrs[k] = v x, prev_y, y = self.training_data() self._save_data_to_hdf5('training_data', x, prev_y, y, f) x, prev_y, y = self.validation_data() self._save_data_to_hdf5('validation_data', x, prev_y, y, f) x, prev_y, y = self.validation_data() self._save_data_to_hdf5('test_data', x, prev_y, y, f) f.close() return def _get_source_from_str(self, data, input_features, output_features): if isinstance(output_features, str): output_features = [output_features] if data.endswith('.h5'): _source = data if data.endswith('.csv'): _source = pd.read_csv(data) if _source.columns[0] in ['index', 'time', 'date']: _source.index = pd.to_datetime(_source.pop('index')) elif data.endswith('.xlsx') or data.endswith('xlx'): _source = pd.read_excel(data) if _source.columns[0] in ['index', 'time', 'date']: _source.index = pd.to_datetime(_source.pop('index')) elif data.endswith('.parquet'): _source = pd.read_parquet(data) elif data.endswith('.feather'): _source = pd.read_feather(data) if _source.columns[0] in ['index', 'time', 'date']: _source.index = pd.to_datetime(_source.pop('index')) elif data.endswith('.nc'): import xarray as xr _source = xr.open_dataset(data) _source = _source.to_dataframe() elif data.endswith('npz'): data = np.load(data) assert len(data) == 1 d = [] for k,v in data.items(): d.append(v) data:np.ndarray = d[0] _source = pd.DataFrame(data, columns=input_features + output_features) elif data.endswith('.mat'): import scipy mat = scipy.io.loadmat(data) data:np.ndarray = mat['data'] _source = pd.DataFrame(data, columns=input_features + output_features) elif os.path.isfile(data): assert os.path.exists(data) assert len(os.listdir(data)) > 1 # read from directory raise NotImplementedError elif data in all_datasets: _source = self._get_data_from_ai4w_datasets(data) else: raise ValueError(f"unregnizable source of data given {data}") return _source def _process_one_source(self, data): if isinstance(data, str): _source = self._get_source_from_str(data) elif isinstance(data, pd.DataFrame): _source = data elif isinstance(data, np.ndarray): _source = data # elif data.__class.__.__name__ == "Dataset": # _source = data else: raise ValueError(f"unregnizable source of data of type {data.__class__.__name__}") return _source def _get_data_from_ai4w_datasets(self, data): Dataset = getattr(datasets, data) dataset = Dataset() dataset_args = self.config['dataset_args'] if dataset_args is None: dataset_args = {} # if self.config['input_features'] is not None: dynamic_features = self.config['input_features'] + self.config['output_features'] data = dataset.fetch(dynamic_features = dynamic_features, **dataset_args ) data = data.to_dataframe(['time', 'dynamic_features']).unstack() data.columns = [a[1] for a in data.columns.to_flat_index()] return data def _save_data_to_hdf5(self, data_type, x, prev_y, y, f): if x is not None: model_weights_group = f.create_group(data_type) if self.source_is_list: idx = 0 for xi, prevyi, yi in zip(x, prev_y, y): save_in_a_group(xi, prevyi, yi, model_weights_group, prefix=idx) idx += 1 elif self.source_is_dict: for src_name in self.data.keys(): save_in_a_group(x.get(src_name, None), prev_y.get(src_name, None), y.get(src_name, None), model_weights_group, prefix=src_name) else: save_in_a_group(x, prev_y, y, model_weights_group) return def check_for_batch_size(self, x, prev_y, y): if self.config['drop_remainder']: remainder = len(x) % self.config['batch_size'] if remainder: if isinstance(x, list): _x = [] for val in x: _x.append(val[0:-remainder]) x = _x else: x = x[0:-remainder] prev_y = prev_y[0:-remainder] y = y[0:-remainder] return x, prev_y, y class MakeData(object): def __init__(self, input_features, output_features, lookback, input_step, forecast_step, forecast_len, known_future_inputs, batch_dim="3D", allow_input_nans=False, allow_nan_labels=0, verbosity=1, ): self.input_features = copy_features(input_features) self.output_features = copy_features(output_features) self.allow_nan_labels = allow_nan_labels self.lookback = lookback self.input_step = input_step self.forecast_step = forecast_step self.forecast_len = forecast_len self.allow_input_nans = allow_input_nans self.verbosity = verbosity self.batch_dim = batch_dim self.known_future_inputs = known_future_inputs self.nans_removed_4m_st = 0 self.scalers = {} self.indexes = {} self.index_types = {} # saves the information whether an index was datetime index or not? def check_nans(self, data, input_x, input_y, label_y, outs, lookback): if isinstance(data, pd.DataFrame): nans = data[self.output_features].isna() nans = nans.sum().sum() data = data.values else: nans = np.isnan(data[:, -outs:]) # df[self.out_cols].isna().sum() nans = int(nans.sum()) if nans > 0: if self.allow_nan_labels == 2: if self.verbosity > 0: print("\n{} Allowing NANs in predictions {}\n".format(10 * '*', 10 * '*')) elif self.allow_nan_labels == 1: if self.verbosity>0: print("\n{} Ignoring examples whose all labels are NaNs {}\n".format(10 * '*', 10 * '*')) idx = ~np.array([all([np.isnan(x) for x in label_y[i]]) for i in range(len(label_y))]) input_x = input_x[idx] input_y = input_y[idx] label_y = label_y[idx] if int(np.isnan(data[:, -outs:][0:lookback]).sum() / outs) >= lookback: self.nans_removed_4m_st = -9999 else: if self.verbosity > 0: print('\n{} Removing Examples with nan in labels {}\n'.format(10 * '*', 10 * '*')) if outs == 1: # find out how many nans were present from start of data until lookback, these nans will be removed self.nans_removed_4m_st = np.isnan(data[:, -outs:][0:lookback]).sum() # find out such labels where 'y' has at least one nan nan_idx = np.array([np.any(i) for i in np.isnan(label_y)]) non_nan_idx = np.invert(nan_idx) label_y = label_y[non_nan_idx] input_x = input_x[non_nan_idx] input_y = input_y[non_nan_idx] assert np.isnan(label_y).sum() < 1, "label still contains {} nans".format(np.isnan(label_y).sum()) assert input_x.shape[0] == input_y.shape[0] == label_y.shape[0], "shapes are not same" if not self.allow_input_nans: assert np.isnan(input_x).sum() == 0, "input still contains {} nans".format(np.isnan(input_x).sum()) return input_x, input_y, label_y def transform(self, data, transformation, key='5'): # it is better to make a copy here because all the operations on data happen after this. data = data.copy() scalers = {} if transformation: if isinstance(transformation, dict): data, scaler = Transformations(data=data, **transformation)('transformation', return_key=True) scalers[key] = scaler # we want to apply multiple transformations elif isinstance(transformation, list): for idx, trans in enumerate(transformation): if trans['method'] is not None: data, scaler = Transformations(data=data, **trans)('transformation', return_key=True) scalers[f'{key}_{trans["method"]}_{idx}'] = scaler else: assert isinstance(transformation, str) data, scaler = Transformations(data=data, method=transformation)('transformation', return_key=True) scalers[key] = scaler self.scalers.update(scalers) return data, scalers def indexify(self, data: pd.DataFrame, key): dummy_index = False # for dataframes if isinstance(data.index, pd.DatetimeIndex): index = list(map(int, np.array(data.index.strftime('%Y%m%d%H%M')))) # datetime index self.index_types[key] = 'dt' original_index = index else: try: index = list(map(int, np.array(data.index))) self.index_types[key] = 'int' original_index = index except ValueError: # index may not be convertible to integer, it may be string values dummy_index = np.arange(len(data), dtype=np.int64).tolist() original_index = pd.Series(data.index, index=dummy_index) index = dummy_index self.index_types[key] = 'str' self.indexes[key] = {'dummy': dummy_index, 'original': original_index} # pandas will add the 'datetime' column as first column. This columns will only be used to keep # track of indices of train and test data. data.insert(0, 'index', index) self.input_features = ['index'] + self.input_features # setattr(self, 'input_features', ['index'] + self.input_features) self.indexes[key] = {'index': index, 'dummy_index': dummy_index, 'original': original_index} return data def deindexify(self, data, key): if isinstance(data, np.ndarray): _data, _index = self.deindexify_nparray(data, key) elif isinstance(data, list): _data, _index = [], [] for d in data: data_, index_ = self.deindexify_nparray(d, key) _data.append(data_) _index.append(index_) else: raise NotImplementedError if self.indexes[key]['dummy_index']: _index = self.indexes[key]['original'].loc[_index].values.tolist() if self.index_types[key] == 'dt': _index = to_datetime_index(_index) return _data, _index def get_batches(self, data, num_ins, num_outs): if self.batch_dim == "2D": return self.get_2d_batches(data, num_ins, num_outs) else: return self.check_nans(data, *prepare_data(data, num_outputs=num_outs, lookback_steps=self.lookback, input_steps=self.input_step, forecast_step=self.forecast_step, forecast_len=self.forecast_len, known_future_inputs=self.known_future_inputs), num_outs, self.lookback) def get_2d_batches(self, data, ins, outs): if not isinstance(data, np.ndarray): if isinstance(data, pd.DataFrame): data = data.values else: raise TypeError(f"unknown data type {data.__class__.__name__} for data ") if outs>0: input_x, input_y, label_y = data[:, 0:ins], data[:, -outs:], data[:, -outs:] else: input_x, input_y, label_y = data[:, 0:ins], np.random.random((len(data), outs)), np.random.random((len(data), outs)) assert self.lookback == 1, """lookback should be one for MLP/Dense layer based model, but it is {} """.format(self.lookback) return self.check_nans(data, input_x, input_y, np.expand_dims(label_y, axis=2), outs, self.lookback) def __call__( self, data, st=0, en=None, indices=None, intervals=None, shuffle=False ): num_ins = len(self.input_features) num_outs = len(self.output_features) if st is not None: assert isinstance(st, int), "starting point must be integer." if indices is not None: assert isinstance(np.array(indices), np.ndarray), "indices must be array like" if en is not None or st != 0: raise ValueError(f'When using indices, st and en can not be used. while st:{st}, and en:{en}') if en is None: en = data.shape[0] if isinstance(data, pd.DataFrame): data = data[self.input_features + self.output_features].copy() df = data else: num_ins = data.shape[-1] num_outs = 0 data = data.copy() df = data if intervals is None: df = df[st:en] x, prev_y, y = self.get_batches(df, num_ins, num_outs) if indices is not None: # if indices are given then this should be done after `get_batches` method x = x[indices] prev_y = prev_y[indices] y = y[indices] else: xs, prev_ys, ys = [], [], [] for _st, _en in intervals: df1 = data[_st:_en] if df1.shape[0] > 0: x, prev_y, y = self.get_batches(df1.values, num_ins, num_outs) xs.append(x) prev_ys.append(prev_y) ys.append(y) if indices is None: x = np.vstack(xs)[st:en] prev_y = np.vstack(prev_ys)[st:en] y = np.vstack(ys)[st:en] else: x = np.vstack(xs)[indices] prev_y = np.vstack(prev_ys)[indices] y = np.vstack(ys)[indices] if shuffle: raise NotImplementedError if 'index' in data: data.pop('index') return x, prev_y, y def deindexify_nparray(self, data, key): if data.ndim == 3: _data, index = data[..., 1:].astype(np.float32), data[:, -1, 0] elif data.ndim == 2: _data, index = data[..., 1:].astype(np.float32), data[:, 0] elif data.ndim == 4: _data, index = data[..., 1:].astype(np.float32), data[:, -1, -1, 0] elif data.ndim == 5: _data, index = data[..., 1:].astype(np.float32), data[:, -1, -1, -1, 0] else: raise NotImplementedError if self.index_types[key] != 'str': index = np.array(index, dtype=np.int64) return _data, index class SiteDistributedDataHandler(object): def __init__(self, data: dict, config: dict, training_sites: list = None, validation_sites: list = None, test_sites: list = None, swap_axes: bool = True, allow_variable_len: bool = False, verbosity: int = 1 ): assert isinstance(data, dict), f'data must be of type dict but it is of type {data.__class__.__name__}' self.data = data new_config = self.process_config(config) if training_sites is not None: assert all([isinstance(obj, list) for obj in [training_sites, validation_sites, test_sites]]) for site in [training_sites, validation_sites, test_sites]: for s in site: assert s in data self.config = new_config self.training_sites = training_sites self.validation_sites = validation_sites self.test_sites = test_sites self.swap_axes = swap_axes self.allow_variable_len = allow_variable_len self.dhs = {} self.verbosity = verbosity def process_config(self, config): assert isinstance(config, dict) if len(config) > 1: for k in self.data.keys(): assert k in config, f'{k} present in data but not available in config' new_config = config.copy() else: new_config = {} for k in self.data.keys(): new_config[k] = config return new_config def training_data(self) -> Tuple[np.ndarray, np.ndarray]: x, y = [], [] training_sites = self.training_sites if training_sites is None: training_sites = self.data.keys() for site in training_sites: src, conf = self.data[site], self.config[site] conf['verbosity'] = 0 if self.training_sites is not None: conf['test_fraction'] = 0.0 conf['val_fraction'] = 0.0 dh = DataHandler(src, **conf) self.dhs[site] = dh # save in memory _x, _y = dh.training_data() x.append(_x) y.append(_y) x = self.stack(x, training_sites) y = self.stack(y, training_sites) if self.verbosity: print(f"{'*' * 5} Training data {'*' * 5}") print_something(x, 'x') print_something(y, 'y') return x, y def validation_data(self) -> Tuple[np.ndarray, np.ndarray]: x, y = [], [] validation_sites = self.validation_sites if validation_sites is None: validation_sites = self.data.keys() for site in validation_sites: src, conf = self.data[site], self.config[site] conf['verbosity'] = 0 if self.validation_sites is not None: # we have sites, so all the data from these sites is used as validation conf['test_fraction'] = 0.0 conf['val_fraction'] = 0.0 dh = DataHandler(src, **conf) self.dhs[site] = dh # save in memory _x, _y = dh.training_data() else: dh = DataHandler(src, **conf) self.dhs[site] = dh # save in memory _x, _y = dh.validation_data() x.append(_x) y.append(_y) x = self.stack(x, validation_sites) y = self.stack(y, validation_sites) if self.verbosity: print(f"{'*' * 5} Validation data {'*' * 5}") print_something(x, 'x') print_something(y, 'y') return x, y def test_data(self) -> Tuple[np.ndarray, np.ndarray]: x, y = [], [] test_sites = self.test_sites if test_sites is None: test_sites = self.data.keys() for site in test_sites: src, conf = self.data[site], self.config[site] if self.test_sites is not None: # we have sites, so all the data from these sites is used as test conf['test_fraction'] = 0.0 conf['val_fraction'] = 0.0 conf['verbosity'] = 0 dh = DataHandler(src, **conf) self.dhs[site] = dh # save in memory _x, _y = dh.training_data() else: conf['verbosity'] = 0 dh = DataHandler(src, **conf) _x, _y = dh.test_data() x.append(_x) y.append(_y) x = self.stack(x, test_sites) y = self.stack(y, test_sites) if self.verbosity: print(f"{'*' * 5} Test data {'*' * 5}") print_something(x, 'x') print_something(y, 'y') return x, y def stack(self, data: list, site_names): if isinstance(data[0], np.ndarray): if len(set([len(i) for i in data])) == 1: # all arrays in data are of equal length data = np.stack(data) # (num_sites, num_examples, lookback, num_features) if self.swap_axes: data = data.swapaxes(0, 1) # (num_examples, num_sites, lookback, num_features) elif self.allow_variable_len: data = {k: v for k, v in zip(site_names, data)} else: raise NotImplementedError(f"number of examples are {[len(i) for i in data]}. " f"set `allow_variable_len` to `True`") elif isinstance(data[0], dict): if self.allow_variable_len: raise NotImplementedError # todo new_data = {k: None for k in data[0].keys()} for src_name in new_data.keys(): temp = [] for src in data: temp.append(src[src_name]) if self.swap_axes: new_data[src_name] = np.stack(temp).swapaxes(0, 1) else: new_data[src_name] = np.stack(temp) data = new_data else: raise ValueError return data class MultiLocDataHandler(object): def __init__(self): pass def training_data(self, data, **kwargs): dh = DataHandler(data=data, val_fraction=0.0, test_fraction=0.0, save=False, verbosity=0, **kwargs) setattr(self, 'train_dh', dh) return dh.training_data() def validation_data(self, data, **kwargs) -> Tuple[np.ndarray, np.ndarray]: dh = DataHandler(data=data, val_fraction=0.0, test_fraction=0.0, save=False, verbosity=0, **kwargs) setattr(self, 'val_dh', dh) return dh.training_data() def test_data(self, data, **kwargs): dh = DataHandler(data=data, val_fraction=0.0, test_fraction=0.0, save=False, verbosity=0, **kwargs) setattr(self, 'test_dh', dh) return dh.training_data() def decode(json_string): return json.loads(json_string, object_hook=_decode_helper) def _decode_helper(obj): if isinstance(obj, dict) and 'class_name' in obj: if obj['class_name'] == '__tuple__': return tuple(_decode_helper(i) for i in obj['items']) elif obj['class_name'] == '__ellipsis__': return Ellipsis return obj def load_data_from_hdf5(data_type, data): f = h5py.File(data, mode='r') weight_names = ['x', 'prev_y', 'y'] g = f[data_type] weight_values = (np.asarray(g[weight_name]) for weight_name in weight_names) f.close() return weight_values def save_in_a_group(x, prev_y, y, group_name, prefix=None): container = {} if x is not None: key = f'{prefix}_x' if prefix else 'x' container[key] = x if prev_y is not None: key = f'{prefix}_prev_y' if prefix else 'prev_y' container[key] = prev_y if y is not None: key = f'{prefix}_y' if prefix else 'y' container[key] = y for name, val in container.items(): param_dset = group_name.create_dataset(name, val.shape, dtype=val.dtype) if not val.shape: # scalar param_dset[()] = val else: param_dset[:] = val return def make_config(**kwargs): return kwargs def copy_features(features): if isinstance(features, str): _features = copy.deepcopy(features) elif isinstance(features, list) or isinstance(features, pd.Index): _features = [] for f in features: _features.append(copy.deepcopy(f)) else: raise NotImplementedError return _features def conform_shape(data, shape, features=None): # if the difference is of only 1 dim, we resolve it if data.ndim > len(shape): data = np.squeeze(data, axis=-1) elif data.ndim < len(shape): data = np.expand_dims(data, axis=-1) assert data.ndim == len(shape), f"original data had {len(shape)} wihle the new data has {data.ndim} dimensions" dummy_features = shape[-1] - data.shape[-1] # how manu dummy features we have to add to match the shape if data.__class__.__name__ in ['DataFrame', 'Series']: # we know what features must be in data, so put them in data one by one if they do not exist in data already if features: for f in features: if f not in data: data[f] = np.random.random(len(data)) # identify how many features to be added by shape information elif dummy_features > 0: dummy_data = pd.DataFrame(np.random.random((len(data), dummy_features))) data = pd.concat([dummy_data, data], axis=1) else: dummy_data = np.random.random((len(data), dummy_features)) data = np.concatenate([dummy_data, data], axis=1) return data, dummy_features def consider_intervals(data, intervals): _source = data if intervals is not None: if isinstance(data, pd.DataFrame): try: # if indices in intervals are of same type as that of index # -1 so that .loc and .iloc give same results, however this is not possible # with DatetimeIndex if isinstance(data.index, pd.DatetimeIndex): _source = pd.concat([data.loc[st:en] for st, en in intervals]) else: _source = pd.concat([data.loc[st:en - 1] for st, en in intervals]) except TypeError: # assuming indices in intervals are integers _source = pd.concat([data.iloc[st:en] for st, en in intervals]) return _source def tot_obs_for_one_df(data, allow_nan_labels, output_features, lookback, input_step, num_outs, forecast_step, forecast_len, intervals, input_features:list): data = consider_intervals(data, intervals) max_tot_obs = 0 if not allow_nan_labels and intervals is None: _data = data[input_features + output_features] if isinstance(data, pd.DataFrame) else data x, _, _ = prepare_data(_data, lookback, num_outputs=num_outs, input_steps=input_step, forecast_step=forecast_step, forecast_len=forecast_len, mask=np.nan) max_tot_obs = len(x) # we need to ignore some values at the start more = (lookback * input_step) - 1 if isinstance(data, np.ndarray): return len(data) - more # todo, why not when allow_nan_labels>0? if forecast_step > 0: more += forecast_step if forecast_len > 1: more += forecast_len if intervals is None: intervals = [()] more *= len(intervals) if allow_nan_labels == 2: tot_obs = data.shape[0] - more elif allow_nan_labels == 1: label_y = data[output_features].values idx = ~np.array([all([np.isnan(x) for x in label_y[i]]) for i in range(len(label_y))]) tot_obs = np.sum(idx) - more else: if num_outs == 1: tot_obs = data.shape[0] - int(data[output_features].isna().sum()) - more tot_obs = max(tot_obs, max_tot_obs) else: # count by droping all the rows when nans occur in output features tot_obs = len(data.dropna(subset=output_features)) tot_obs -= more return tot_obs def batch_dim_from_lookback(lookback): default = "3D" if lookback == 1: default = "2D" return default def deindexify_y(x: list, prev_y: list, y:list, based_upon: int): indices_to_keep = [] for e in y[based_upon]: indices_to_keep.append(int(e[-1])) if isinstance(x, list): return deindexify_lists(x, prev_y, y, indices_to_keep) else: return deindexify_dicts(x, prev_y, y, indices_to_keep) def deindexify_lists(x, prev_y, y, indices_to_keep): _x, _prevy, _y = [], [], [] # for x,y of each source for xi, prevyi, yi in zip(x, prev_y, y): __x, __prevy, __y = [], [], [] # for individual examples of one source, check that if that example is to included or not for _xi, _prevyi, _yi in zip(xi, prevyi, yi): if int(_yi[-1]) in indices_to_keep: __x.append(_xi) __prevy.append(_prevyi) __y.append(_yi[0:-1]) # don't consider the last value, that was dummy_index _x.append(np.stack(__x)) _prevy.append(np.stack(__prevy)) _y.append(np.stack(__y)) return _x, _prevy, _y def deindexify_dicts(x: dict, prev_y: dict, y: dict, indices_to_keep): _x, _prevy, _y = {}, {}, {} for (key, xi), (key, prevyi), (key, yi) in zip(x.items(), prev_y.items(), y.items()): __x, __prevy, __y = [], [], [] for _xi, _prevyi, _yi in zip(xi, prevyi, yi): if int(_yi[-1]) in indices_to_keep: __x.append(_xi) __prevy.append(_prevyi) __y.append(_yi[0:-1]) _x[key] = np.stack(__x) _prevy[key] = np.stack(__prevy) _y[key] = np.stack(__y) return _x, _prevy, _y def filter_zero_sized_arrays(array): if isinstance(array, list): new_array = [] for a in array: if a.size > 0: new_array.append(a) elif isinstance(array, dict): new_array = {} for k, v in array.items(): if v.size > 0: new_array[k] = v else: new_array = array return new_array def check_for_classification(label: np.ndarray, to_categorical): assert isinstance(label, np.ndarray), f""" classification problem for label of type {label.__class__.__name__} not implemented yet""" # for clsasification, it should be 2d label = label.reshape(-1, label.shape[1]) if to_categorical: assert label.shape[1] == 1 label = OneHotEncoder(sparse=False).fit_transform(label) # else: # mutlti_label/binary problem # # todo, is only binary_crossentropy is binary/multi_label problem? # pass #assert self.loss_name() in ['binary_crossentropy'] return label def return_x_yy(x, prev_y, y, initial, verbosity): if verbosity > 0: print(f"{'*' * 5} {initial} data {'*' * 5}") print_something(x, "input_x") print_something(prev_y, "prev_y") print_something(y, "target") return x, prev_y, y def return_xy(x, y, initial, verbosity): if verbosity > 0: print(f"{'*' * 5} {initial} {'*' * 5}") print_something(x, "input_x") print_something(y, "target") return x, y
true
true
1c2c1ecd58a4917781ee5a0596ac3eb30799d735
485
py
Python
Python/SimplifyPathTest.py
TonnyL/Windary
39f85cdedaaf5b85f7ce842ecef975301fc974cf
[ "MIT" ]
205
2017-11-16T08:38:46.000Z
2022-03-06T05:50:03.000Z
Python/SimplifyPathTest.py
santosh241/Windary
39f85cdedaaf5b85f7ce842ecef975301fc974cf
[ "MIT" ]
3
2018-04-10T10:17:52.000Z
2020-12-11T08:00:09.000Z
Python/SimplifyPathTest.py
santosh241/Windary
39f85cdedaaf5b85f7ce842ecef975301fc974cf
[ "MIT" ]
28
2018-04-10T06:42:42.000Z
2021-09-14T14:15:39.000Z
from unittest import TestCase from SimplifyPath import SimplifyPath class TestSimplifyPath(TestCase): def test_simplifyPath(self): sp = SimplifyPath() self.assertEqual(sp.simplifyPath("/home/"), "/home") self.assertEqual(sp.simplifyPath("/a/./b/../../c/"), "/c") self.assertEqual(sp.simplifyPath("/../"), "/") self.assertEqual(sp.simplifyPath("/home/foo/"), "/home/foo") self.assertEqual(sp.simplifyPath("/a/b/c"), "/a/b/c")
25.526316
68
0.626804
from unittest import TestCase from SimplifyPath import SimplifyPath class TestSimplifyPath(TestCase): def test_simplifyPath(self): sp = SimplifyPath() self.assertEqual(sp.simplifyPath("/home/"), "/home") self.assertEqual(sp.simplifyPath("/a/./b/../../c/"), "/c") self.assertEqual(sp.simplifyPath("/../"), "/") self.assertEqual(sp.simplifyPath("/home/foo/"), "/home/foo") self.assertEqual(sp.simplifyPath("/a/b/c"), "/a/b/c")
true
true
1c2c1ecff02208f628aa2e65eae53abaf0c94bd6
1,527
py
Python
docs/conf.py
alexweav/nisystemlink-clients-python
f19a30907a7fef536043ecbddc5a755e5fedf846
[ "MIT" ]
null
null
null
docs/conf.py
alexweav/nisystemlink-clients-python
f19a30907a7fef536043ecbddc5a755e5fedf846
[ "MIT" ]
null
null
null
docs/conf.py
alexweav/nisystemlink-clients-python
f19a30907a7fef536043ecbddc5a755e5fedf846
[ "MIT" ]
null
null
null
import os import sys sys.path.insert(0, os.path.abspath("..")) # -------------------------------------------------------------------------------------- project = "nisystemlink" copyright = "2020, National Instruments" author = "National Instruments" # The short X.Y version version = "0.1" # The full version, including alpha/beta/rc tags release = "0.1.3" # -------------------------------------------------------------------------------------- extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", "sphinx.ext.viewcode", "sphinx_autodoc_typehints", "docs.cleanup", ] master_doc = "index" html_theme = "sphinx_rtd_theme" html_extra_path = [ "../LICENSE", ] nitpicky = True nitpick_ignore = [ ("py:class", "datetime.datetime"), ("py:class", "datetime.timedelta"), ("py:class", "pathlib.Path"), ("py:data", "typing.Any"), ("py:data", "typing.Awaitable"), ("py:data", "typing.Dict"), ("py:data", "typing.Iterable"), ("py:data", "typing.List"), ("py:data", "typing.Optional"), ("py:data", "typing.Sequence"), ("py:data", "typing.Tuple"), ("py:data", "typing.Union"), ] autodoc_default_options = { "inherited-members": True, "special-members": "__init__", "no-private-members": True, } # Don't let napoleon force methods to be included in the docs; use autodoc flags and our # own docs.cleanup module for that. napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = False
26.789474
88
0.587426
import os import sys sys.path.insert(0, os.path.abspath("..")) project = "nisystemlink" copyright = "2020, National Instruments" author = "National Instruments" version = "0.1" release = "0.1.3" extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", "sphinx.ext.viewcode", "sphinx_autodoc_typehints", "docs.cleanup", ] master_doc = "index" html_theme = "sphinx_rtd_theme" html_extra_path = [ "../LICENSE", ] nitpicky = True nitpick_ignore = [ ("py:class", "datetime.datetime"), ("py:class", "datetime.timedelta"), ("py:class", "pathlib.Path"), ("py:data", "typing.Any"), ("py:data", "typing.Awaitable"), ("py:data", "typing.Dict"), ("py:data", "typing.Iterable"), ("py:data", "typing.List"), ("py:data", "typing.Optional"), ("py:data", "typing.Sequence"), ("py:data", "typing.Tuple"), ("py:data", "typing.Union"), ] autodoc_default_options = { "inherited-members": True, "special-members": "__init__", "no-private-members": True, } # own docs.cleanup module for that. napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = False
true
true
1c2c1edc237faeeb210a95b60ce48beaa5f33843
3,010
py
Python
tests/nlu/classifiers/test_embedding_intent_classifier.py
anil-slt/Rasa
53685e85a3c9185f51e4f12cc055d2a65bb5314d
[ "Apache-2.0" ]
4
2020-04-17T17:08:59.000Z
2021-07-21T16:25:00.000Z
tests/nlu/classifiers/test_embedding_intent_classifier.py
anil-slt/Rasa
53685e85a3c9185f51e4f12cc055d2a65bb5314d
[ "Apache-2.0" ]
5
2020-04-10T09:08:46.000Z
2021-08-25T14:40:03.000Z
tests/nlu/classifiers/test_embedding_intent_classifier.py
anil-slt/Rasa
53685e85a3c9185f51e4f12cc055d2a65bb5314d
[ "Apache-2.0" ]
2
2020-11-04T04:03:30.000Z
2021-01-27T04:41:42.000Z
import numpy as np import pytest import scipy.sparse from rasa.nlu.constants import ( TEXT_ATTRIBUTE, SPARSE_FEATURE_NAMES, DENSE_FEATURE_NAMES, INTENT_ATTRIBUTE, ) from rasa.nlu.classifiers.embedding_intent_classifier import EmbeddingIntentClassifier from rasa.nlu.training_data import Message def test_compute_default_label_features(): label_features = [ Message("test a"), Message("test b"), Message("test c"), Message("test d"), ] output = EmbeddingIntentClassifier._compute_default_label_features(label_features) output = output[0] for i, o in enumerate(output): assert isinstance(o, np.ndarray) assert o[0][i] == 1 assert o.shape == (1, len(label_features)) def test_get_num_of_features(): session_data = { "text_features": [ np.array( [ np.random.rand(5, 14), np.random.rand(2, 14), np.random.rand(3, 14), np.random.rand(1, 14), np.random.rand(3, 14), ] ), np.array( [ scipy.sparse.csr_matrix(np.random.randint(5, size=(5, 10))), scipy.sparse.csr_matrix(np.random.randint(5, size=(2, 10))), scipy.sparse.csr_matrix(np.random.randint(5, size=(3, 10))), scipy.sparse.csr_matrix(np.random.randint(5, size=(1, 10))), scipy.sparse.csr_matrix(np.random.randint(5, size=(3, 10))), ] ), ] } num_features = EmbeddingIntentClassifier._get_num_of_features( session_data, "text_features" ) assert num_features == 24 @pytest.mark.parametrize( "messages, expected", [ ( [ Message( "test a", data={ SPARSE_FEATURE_NAMES[TEXT_ATTRIBUTE]: np.zeros(1), DENSE_FEATURE_NAMES[TEXT_ATTRIBUTE]: np.zeros(1), }, ), Message( "test b", data={ SPARSE_FEATURE_NAMES[TEXT_ATTRIBUTE]: np.zeros(1), DENSE_FEATURE_NAMES[TEXT_ATTRIBUTE]: np.zeros(1), }, ), ], True, ), ( [ Message( "test a", data={ SPARSE_FEATURE_NAMES[INTENT_ATTRIBUTE]: np.zeros(1), DENSE_FEATURE_NAMES[INTENT_ATTRIBUTE]: np.zeros(1), }, ) ], False, ), ], ) def test_check_labels_features_exist(messages, expected): attribute = TEXT_ATTRIBUTE assert ( EmbeddingIntentClassifier._check_labels_features_exist(messages, attribute) == expected )
28.130841
86
0.498671
import numpy as np import pytest import scipy.sparse from rasa.nlu.constants import ( TEXT_ATTRIBUTE, SPARSE_FEATURE_NAMES, DENSE_FEATURE_NAMES, INTENT_ATTRIBUTE, ) from rasa.nlu.classifiers.embedding_intent_classifier import EmbeddingIntentClassifier from rasa.nlu.training_data import Message def test_compute_default_label_features(): label_features = [ Message("test a"), Message("test b"), Message("test c"), Message("test d"), ] output = EmbeddingIntentClassifier._compute_default_label_features(label_features) output = output[0] for i, o in enumerate(output): assert isinstance(o, np.ndarray) assert o[0][i] == 1 assert o.shape == (1, len(label_features)) def test_get_num_of_features(): session_data = { "text_features": [ np.array( [ np.random.rand(5, 14), np.random.rand(2, 14), np.random.rand(3, 14), np.random.rand(1, 14), np.random.rand(3, 14), ] ), np.array( [ scipy.sparse.csr_matrix(np.random.randint(5, size=(5, 10))), scipy.sparse.csr_matrix(np.random.randint(5, size=(2, 10))), scipy.sparse.csr_matrix(np.random.randint(5, size=(3, 10))), scipy.sparse.csr_matrix(np.random.randint(5, size=(1, 10))), scipy.sparse.csr_matrix(np.random.randint(5, size=(3, 10))), ] ), ] } num_features = EmbeddingIntentClassifier._get_num_of_features( session_data, "text_features" ) assert num_features == 24 @pytest.mark.parametrize( "messages, expected", [ ( [ Message( "test a", data={ SPARSE_FEATURE_NAMES[TEXT_ATTRIBUTE]: np.zeros(1), DENSE_FEATURE_NAMES[TEXT_ATTRIBUTE]: np.zeros(1), }, ), Message( "test b", data={ SPARSE_FEATURE_NAMES[TEXT_ATTRIBUTE]: np.zeros(1), DENSE_FEATURE_NAMES[TEXT_ATTRIBUTE]: np.zeros(1), }, ), ], True, ), ( [ Message( "test a", data={ SPARSE_FEATURE_NAMES[INTENT_ATTRIBUTE]: np.zeros(1), DENSE_FEATURE_NAMES[INTENT_ATTRIBUTE]: np.zeros(1), }, ) ], False, ), ], ) def test_check_labels_features_exist(messages, expected): attribute = TEXT_ATTRIBUTE assert ( EmbeddingIntentClassifier._check_labels_features_exist(messages, attribute) == expected )
true
true
1c2c1f26c46eb966c4b21455bbacceee4e343723
3,179
py
Python
eth/beacon/_utils/random.py
Bhargavasomu/py-evm
ee8f72d5a70805575a967cde0a43942e1526264e
[ "MIT" ]
null
null
null
eth/beacon/_utils/random.py
Bhargavasomu/py-evm
ee8f72d5a70805575a967cde0a43942e1526264e
[ "MIT" ]
null
null
null
eth/beacon/_utils/random.py
Bhargavasomu/py-evm
ee8f72d5a70805575a967cde0a43942e1526264e
[ "MIT" ]
2
2019-09-05T01:31:56.000Z
2019-09-17T09:09:16.000Z
from typing import ( Any, Iterable, Sequence, Tuple, TypeVar, ) from eth_typing import ( Hash32, ) from eth_utils import ( to_tuple, ) from eth.beacon._utils.hash import ( hash_eth2, ) from eth.beacon.constants import ( RAND_BYTES, RAND_MAX, ) TItem = TypeVar('TItem') @to_tuple def shuffle(values: Sequence[Any], seed: Hash32) -> Iterable[Any]: """ Returns the shuffled ``values`` with seed as entropy. Mainly for shuffling active validators in-protocol. Spec: https://github.com/ethereum/eth2.0-specs/blob/70cef14a08de70e7bd0455d75cf380eb69694bfb/specs/core/0_beacon-chain.md#helper-functions # noqa: E501 """ values_count = len(values) # The range of the RNG places an upper-bound on the size of the list that # may be shuffled. It is a logic error to supply an oversized list. if values_count >= RAND_MAX: raise ValueError( "values_count (%s) should less than RAND_MAX (%s)." % (values_count, RAND_MAX) ) output = [x for x in values] source = seed index = 0 while index < values_count - 1: # Re-hash the `source` to obtain a new pattern of bytes. source = hash_eth2(source) # Iterate through the `source` bytes in 3-byte chunks. for position in range(0, 32 - (32 % RAND_BYTES), RAND_BYTES): # Determine the number of indices remaining in `values` and exit # once the last index is reached. remaining = values_count - index if remaining == 1: break # Read 3-bytes of `source` as a 24-bit big-endian integer. sample_from_source = int.from_bytes( source[position:position + RAND_BYTES], 'big' ) # Sample values greater than or equal to `sample_max` will cause # modulo bias when mapped into the `remaining` range. sample_max = RAND_MAX - RAND_MAX % remaining # Perform a swap if the consumed entropy will not cause modulo bias. if sample_from_source < sample_max: # Select a replacement index for the current index. replacement_position = (sample_from_source % remaining) + index # Swap the current index with the replacement index. (output[index], output[replacement_position]) = ( output[replacement_position], output[index] ) index += 1 else: # The sample causes modulo bias. A new sample should be read. pass return output def split(values: Sequence[TItem], split_count: int) -> Tuple[Any, ...]: """ Returns the split ``values`` in ``split_count`` pieces in protocol. Spec: https://github.com/ethereum/eth2.0-specs/blob/70cef14a08de70e7bd0455d75cf380eb69694bfb/specs/core/0_beacon-chain.md#helper-functions # noqa: E501 """ list_length = len(values) return tuple( values[(list_length * i // split_count): (list_length * (i + 1) // split_count)] for i in range(split_count) )
32.111111
156
0.612142
from typing import ( Any, Iterable, Sequence, Tuple, TypeVar, ) from eth_typing import ( Hash32, ) from eth_utils import ( to_tuple, ) from eth.beacon._utils.hash import ( hash_eth2, ) from eth.beacon.constants import ( RAND_BYTES, RAND_MAX, ) TItem = TypeVar('TItem') @to_tuple def shuffle(values: Sequence[Any], seed: Hash32) -> Iterable[Any]: values_count = len(values) if values_count >= RAND_MAX: raise ValueError( "values_count (%s) should less than RAND_MAX (%s)." % (values_count, RAND_MAX) ) output = [x for x in values] source = seed index = 0 while index < values_count - 1: source = hash_eth2(source) for position in range(0, 32 - (32 % RAND_BYTES), RAND_BYTES): remaining = values_count - index if remaining == 1: break sample_from_source = int.from_bytes( source[position:position + RAND_BYTES], 'big' ) sample_max = RAND_MAX - RAND_MAX % remaining if sample_from_source < sample_max: replacement_position = (sample_from_source % remaining) + index (output[index], output[replacement_position]) = ( output[replacement_position], output[index] ) index += 1 else: pass return output def split(values: Sequence[TItem], split_count: int) -> Tuple[Any, ...]: list_length = len(values) return tuple( values[(list_length * i // split_count): (list_length * (i + 1) // split_count)] for i in range(split_count) )
true
true
1c2c1fae3f0888772ce80d4a08476f303b3afbcd
1,697
py
Python
app/notifications/notifications_email_callback.py
davidbgk/notification-api
0ede6a61b48289236d1873124965d2bc22a9b27b
[ "MIT" ]
1
2021-08-13T13:46:04.000Z
2021-08-13T13:46:04.000Z
app/notifications/notifications_email_callback.py
davidbgk/notification-api
0ede6a61b48289236d1873124965d2bc22a9b27b
[ "MIT" ]
null
null
null
app/notifications/notifications_email_callback.py
davidbgk/notification-api
0ede6a61b48289236d1873124965d2bc22a9b27b
[ "MIT" ]
1
2021-09-29T18:25:48.000Z
2021-09-29T18:25:48.000Z
from datetime import datetime from flask import Blueprint from flask import current_app from flask import json from flask import request, jsonify from app.errors import InvalidRequest, register_errors from app.clients.email.sendgrid_client import get_sendgrid_responses from app import statsd_client from app.dao import notifications_dao email_callback_blueprint = Blueprint("email_callback", __name__, url_prefix="/notifications/email") register_errors(email_callback_blueprint) @email_callback_blueprint.route('/sendgrid', methods=['POST']) def process_sendgrid_response(): data = json.loads(request.data) try: for obj in data: notification_status = get_sendgrid_responses(obj["event"]) reference = obj['sg_message_id'].split(".")[0] notification = notifications_dao.dao_get_notification_by_reference(reference) notifications_dao._update_notification_status(notification=notification, status=notification_status) current_app.logger.info('SendGird callback return status of {} for notification: {}'.format( notification_status, notification.id )) statsd_client.incr('callback.sendgrid.{}'.format(notification_status)) if notification.sent_at: statsd_client.timing_with_dates( 'callback.sendgrid.elapsed-time', datetime.utcnow(), notification.sent_at) except Exception as e: current_app.logger.exception('Error processing SendGrid results: {}'.format(type(e))) raise InvalidRequest(message="Error processing SendGrid results", status_code=400) else: return jsonify(result='success'), 200
36.891304
112
0.728344
from datetime import datetime from flask import Blueprint from flask import current_app from flask import json from flask import request, jsonify from app.errors import InvalidRequest, register_errors from app.clients.email.sendgrid_client import get_sendgrid_responses from app import statsd_client from app.dao import notifications_dao email_callback_blueprint = Blueprint("email_callback", __name__, url_prefix="/notifications/email") register_errors(email_callback_blueprint) @email_callback_blueprint.route('/sendgrid', methods=['POST']) def process_sendgrid_response(): data = json.loads(request.data) try: for obj in data: notification_status = get_sendgrid_responses(obj["event"]) reference = obj['sg_message_id'].split(".")[0] notification = notifications_dao.dao_get_notification_by_reference(reference) notifications_dao._update_notification_status(notification=notification, status=notification_status) current_app.logger.info('SendGird callback return status of {} for notification: {}'.format( notification_status, notification.id )) statsd_client.incr('callback.sendgrid.{}'.format(notification_status)) if notification.sent_at: statsd_client.timing_with_dates( 'callback.sendgrid.elapsed-time', datetime.utcnow(), notification.sent_at) except Exception as e: current_app.logger.exception('Error processing SendGrid results: {}'.format(type(e))) raise InvalidRequest(message="Error processing SendGrid results", status_code=400) else: return jsonify(result='success'), 200
true
true
1c2c1fba38356b075ac9c9a513394587f74d6627
952
py
Python
var/spack/repos/builtin/packages/r-remotes/package.py
carlabguillen/spack
7070bb892f9bdb5cf9e76e0eecd64f6cc5f4695c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
9
2018-04-18T07:51:40.000Z
2021-09-10T03:56:57.000Z
var/spack/repos/builtin/packages/r-remotes/package.py
carlabguillen/spack
7070bb892f9bdb5cf9e76e0eecd64f6cc5f4695c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
907
2018-04-18T11:17:57.000Z
2022-03-31T13:20:25.000Z
var/spack/repos/builtin/packages/r-remotes/package.py
carlabguillen/spack
7070bb892f9bdb5cf9e76e0eecd64f6cc5f4695c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
29
2018-11-05T16:14:23.000Z
2022-02-03T16:07:09.000Z
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RRemotes(RPackage): """Download and install R packages stored in 'GitHub', 'BitBucket', or plain 'subversion' or 'git' repositories. This package provides the 'install_*' functions in 'devtools'. Indeed most of the code was copied over from 'devtools'. """ homepage = "https://github.com/r-lib/remotes#readme" url = "https://cloud.r-project.org/src/contrib/remotes_2.1.0.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/remotes" version('2.1.1', sha256='4e590746fce618094089372b185e1ea234b3337b23c44c44118e942d0fb5118b') version('2.1.0', sha256='8944c8f6fc9f0cd0ca04d6cf1221b716eee08facef9f4b4c4d91d0346d6d68a7') depends_on('r@3.0.0:', type=('build', 'run'))
41.391304
95
0.730042
from spack import * class RRemotes(RPackage): homepage = "https://github.com/r-lib/remotes#readme" url = "https://cloud.r-project.org/src/contrib/remotes_2.1.0.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/remotes" version('2.1.1', sha256='4e590746fce618094089372b185e1ea234b3337b23c44c44118e942d0fb5118b') version('2.1.0', sha256='8944c8f6fc9f0cd0ca04d6cf1221b716eee08facef9f4b4c4d91d0346d6d68a7') depends_on('r@3.0.0:', type=('build', 'run'))
true
true
1c2c205102b642af21d582fa7a41363dad38b9ff
3,851
py
Python
tests/test_linalg/test_solvers/test_belief_updates/test_matrix_based/test_symmetric_matrix_based_linear_belief_update.py
NDOWAH/probnum
91a5cf920fe0793d01f3d7dae4b3909c4a74d201
[ "MIT" ]
1
2021-06-22T14:25:43.000Z
2021-06-22T14:25:43.000Z
tests/test_linalg/test_solvers/test_belief_updates/test_matrix_based/test_symmetric_matrix_based_linear_belief_update.py
pitmonticone/probnum
1fed705b2443a14d08419e16f98f6ef815ae9ffa
[ "MIT" ]
42
2021-03-08T07:20:40.000Z
2022-03-28T05:04:48.000Z
tests/test_linalg/test_solvers/test_belief_updates/test_matrix_based/test_symmetric_matrix_based_linear_belief_update.py
pitmonticone/probnum
1fed705b2443a14d08419e16f98f6ef815ae9ffa
[ "MIT" ]
null
null
null
"""Tests for the symmetric matrix-based belief update for linear information.""" import pathlib import numpy as np import pytest from pytest_cases import parametrize_with_cases from probnum import linops, randvars from probnum.linalg.solvers import LinearSolverState, belief_updates, beliefs case_modules = (pathlib.Path(__file__).parent.parent / "cases").stem cases_belief_updates = case_modules + ".belief_updates" cases_states = case_modules + ".states" @parametrize_with_cases( "belief_update", cases=cases_belief_updates, glob="symmetric_matrix_based_linear*", ) @parametrize_with_cases( "state", cases=cases_states, has_tag=["has_action", "has_observation", "symmetric_matrix_based"], ) def test_returns_linear_system_belief( belief_update: belief_updates.matrix_based.SymmetricMatrixBasedLinearBeliefUpdate, state: LinearSolverState, ): belief = belief_update(solver_state=state) assert isinstance(belief, beliefs.LinearSystemBelief) @parametrize_with_cases( "belief_update", cases=cases_belief_updates, glob="symmetric_matrix_based_linear*" ) @parametrize_with_cases( "state", cases=cases_states, has_tag=["has_action", "has_observation", "matrix_based"], ) def test_raises_error_for_non_symmetric_Kronecker_structured_covariances( belief_update: belief_updates.matrix_based.SymmetricMatrixBasedLinearBeliefUpdate, state: LinearSolverState, ): with pytest.raises(ValueError): belief_update(solver_state=state) @parametrize_with_cases( "belief_update", cases=cases_belief_updates, glob="symmetric_matrix_based_linear*" ) @parametrize_with_cases( "state", cases=cases_states, has_tag=["has_action", "has_observation", "symmetric_matrix_based"], ) def test_against_naive_implementation( belief_update: belief_updates.matrix_based.MatrixBasedLinearBeliefUpdate, state: LinearSolverState, ): """Compare the updated belief to a naive implementation.""" def dense_matrix_based_update( matrix: randvars.Normal, action: np.ndarray, observ: np.ndarray ): pred = matrix.mean @ action resid = observ - pred covfactor_Ms = matrix.cov.A @ action gram = action.T @ covfactor_Ms gram_pinv = 1.0 / gram if gram > 0.0 else 0.0 gain = covfactor_Ms * gram_pinv covfactor_update = gain[:, None] @ covfactor_Ms[None, :] resid_gain = np.outer(resid, gain) return randvars.Normal( mean=matrix.mean + resid_gain + resid_gain.T - np.outer(gain, action.T @ resid_gain), cov=linops.SymmetricKronecker(A=matrix.cov.A - covfactor_update), ) updated_belief = belief_update(solver_state=state) A_naive = dense_matrix_based_update( matrix=state.belief.A, action=state.action, observ=state.observation ) Ainv_naive = dense_matrix_based_update( matrix=state.belief.Ainv, action=state.observation, observ=state.action ) # System matrix np.testing.assert_allclose( updated_belief.A.mean.todense(), A_naive.mean.todense(), err_msg="Mean of system matrix estimate does not match naive implementation.", ) np.testing.assert_allclose( updated_belief.A.cov.todense(), A_naive.cov.todense(), err_msg="Covariance of system matrix estimate does not match naive implementation.", ) # Inverse np.testing.assert_allclose( updated_belief.Ainv.mean.todense(), Ainv_naive.mean.todense(), err_msg="Mean of matrix inverse estimate does not match naive implementation.", ) np.testing.assert_allclose( updated_belief.Ainv.cov.todense(), Ainv_naive.cov.todense(), err_msg="Covariance of matrix inverse estimate does not match naive implementation.", )
33.198276
93
0.719294
import pathlib import numpy as np import pytest from pytest_cases import parametrize_with_cases from probnum import linops, randvars from probnum.linalg.solvers import LinearSolverState, belief_updates, beliefs case_modules = (pathlib.Path(__file__).parent.parent / "cases").stem cases_belief_updates = case_modules + ".belief_updates" cases_states = case_modules + ".states" @parametrize_with_cases( "belief_update", cases=cases_belief_updates, glob="symmetric_matrix_based_linear*", ) @parametrize_with_cases( "state", cases=cases_states, has_tag=["has_action", "has_observation", "symmetric_matrix_based"], ) def test_returns_linear_system_belief( belief_update: belief_updates.matrix_based.SymmetricMatrixBasedLinearBeliefUpdate, state: LinearSolverState, ): belief = belief_update(solver_state=state) assert isinstance(belief, beliefs.LinearSystemBelief) @parametrize_with_cases( "belief_update", cases=cases_belief_updates, glob="symmetric_matrix_based_linear*" ) @parametrize_with_cases( "state", cases=cases_states, has_tag=["has_action", "has_observation", "matrix_based"], ) def test_raises_error_for_non_symmetric_Kronecker_structured_covariances( belief_update: belief_updates.matrix_based.SymmetricMatrixBasedLinearBeliefUpdate, state: LinearSolverState, ): with pytest.raises(ValueError): belief_update(solver_state=state) @parametrize_with_cases( "belief_update", cases=cases_belief_updates, glob="symmetric_matrix_based_linear*" ) @parametrize_with_cases( "state", cases=cases_states, has_tag=["has_action", "has_observation", "symmetric_matrix_based"], ) def test_against_naive_implementation( belief_update: belief_updates.matrix_based.MatrixBasedLinearBeliefUpdate, state: LinearSolverState, ): def dense_matrix_based_update( matrix: randvars.Normal, action: np.ndarray, observ: np.ndarray ): pred = matrix.mean @ action resid = observ - pred covfactor_Ms = matrix.cov.A @ action gram = action.T @ covfactor_Ms gram_pinv = 1.0 / gram if gram > 0.0 else 0.0 gain = covfactor_Ms * gram_pinv covfactor_update = gain[:, None] @ covfactor_Ms[None, :] resid_gain = np.outer(resid, gain) return randvars.Normal( mean=matrix.mean + resid_gain + resid_gain.T - np.outer(gain, action.T @ resid_gain), cov=linops.SymmetricKronecker(A=matrix.cov.A - covfactor_update), ) updated_belief = belief_update(solver_state=state) A_naive = dense_matrix_based_update( matrix=state.belief.A, action=state.action, observ=state.observation ) Ainv_naive = dense_matrix_based_update( matrix=state.belief.Ainv, action=state.observation, observ=state.action ) np.testing.assert_allclose( updated_belief.A.mean.todense(), A_naive.mean.todense(), err_msg="Mean of system matrix estimate does not match naive implementation.", ) np.testing.assert_allclose( updated_belief.A.cov.todense(), A_naive.cov.todense(), err_msg="Covariance of system matrix estimate does not match naive implementation.", ) np.testing.assert_allclose( updated_belief.Ainv.mean.todense(), Ainv_naive.mean.todense(), err_msg="Mean of matrix inverse estimate does not match naive implementation.", ) np.testing.assert_allclose( updated_belief.Ainv.cov.todense(), Ainv_naive.cov.todense(), err_msg="Covariance of matrix inverse estimate does not match naive implementation.", )
true
true
1c2c20ac8a769d65250428a6409c0ab27e840ff7
706
py
Python
specs/default/cluster-init/tests/test_uid.py
hmeiland/cyclecloud-slurm
2b5efb3dda92a8f58e4bc57f0b040eb5f77de30f
[ "MIT" ]
1
2021-05-12T15:37:07.000Z
2021-05-12T15:37:07.000Z
specs/default/cluster-init/tests/test_uid.py
hmeiland/cyclecloud-slurm
2b5efb3dda92a8f58e4bc57f0b040eb5f77de30f
[ "MIT" ]
null
null
null
specs/default/cluster-init/tests/test_uid.py
hmeiland/cyclecloud-slurm
2b5efb3dda92a8f58e4bc57f0b040eb5f77de30f
[ "MIT" ]
null
null
null
#!/opt/cycle/jetpack/system/embedded/bin/python -m pytest # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import subprocess import jetpack.config def test_slurm_uid(): suid = jetpack.config.get('slurm.user.uid').strip() suser = jetpack.config.get('slurm.user.name').strip() muid = jetpack.config.get('munge.user.uid').strip() muser = jetpack.config.get('munge.user.name').strip() # Check that slurm uid and username match what is in data store subprocess.check_call(['grep', suid, '|', 'grep', suser]) # Check that munge uid and username match what is in data store subprocess.check_call(['grep', muid, '|', 'grep', muser])
37.157895
67
0.70255
import subprocess import jetpack.config def test_slurm_uid(): suid = jetpack.config.get('slurm.user.uid').strip() suser = jetpack.config.get('slurm.user.name').strip() muid = jetpack.config.get('munge.user.uid').strip() muser = jetpack.config.get('munge.user.name').strip() subprocess.check_call(['grep', suid, '|', 'grep', suser]) subprocess.check_call(['grep', muid, '|', 'grep', muser])
true
true
1c2c20b962b505f8179a00c3b2d9fa46fae9ef17
7,819
py
Python
wrfpy/utils.py
rvanharen/wrfpy
caa1159326abcc59e5e25921f5de72a274962275
[ "Apache-2.0" ]
11
2018-01-06T22:20:04.000Z
2022-03-10T15:26:21.000Z
wrfpy/utils.py
ERA-URBAN/wrfpy
caa1159326abcc59e5e25921f5de72a274962275
[ "Apache-2.0" ]
14
2017-04-11T13:11:38.000Z
2021-03-19T22:49:42.000Z
wrfpy/utils.py
rvanharen/wrfpy
caa1159326abcc59e5e25921f5de72a274962275
[ "Apache-2.0" ]
5
2017-06-13T12:17:54.000Z
2021-09-26T02:44:52.000Z
#!/usr/bin/env python3 ''' description: Utilities used in wrfpy license: APACHE 2.0 author: Ronald van Haren, NLeSC (r.vanharen@esciencecenter.nl) ''' import logging import sys import os # define global LOG variables DEFAULT_LOG_LEVEL = 'debug' LOG_LEVELS = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL} LOG_LEVELS_LIST = LOG_LEVELS.keys() # LOG_FORMAT = '%(asctime)-15s %(message)s' LOG_FORMAT = '%(asctime)s - %(levelname)s - %(message)s' DATE_FORMAT = "%Y/%m/%d/%H:%M:%S" logger = None def devnull(): ''' define devnull based on python version ''' if sys.version_info >= (3, 3): from subprocess import DEVNULL as devnull elif sys.version_info >= (2, 4): devnull = open(os.devnull, 'wb') else: assert sys.version_info >= (2, 4) return devnull def silentremove(filename): ''' Remove a file or directory without raising an error if the file or directory does not exist ''' import errno import shutil try: os.remove(filename) except OSError as e: if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory if e.errno == errno.EISDIR: shutil.rmtree(filename) else: raise # re-raise exception if a different error occured def return_validate(date_text, format='%Y-%m-%d_%H'): ''' validate date_text and return datetime.datetime object ''' from datetime import datetime try: date_time = datetime.strptime(date_text, format).replace(tzinfo=None) except ValueError: logger.error('Incorrect date format, should be %s' % format) raise ValueError('Incorrect date format, should be %s' % format) return date_time def check_file_exists(filename, boolean=False): ''' check if file exists and is readable, else raise IOError ''' try: with open(filename): if boolean: return True else: pass # file exists and is readable, nothing else to do except IOError: if boolean: return False else: # file does not exist OR no read permissions logger.error('Unable to open file: %s' % filename) raise # re-raise exception def validate_time_wrfout(wrfout, current_time): ''' Validate if current_time is in wrfout file ''' # get list of timesteps in wrfout file (list of datetime objects) time_steps = timesteps_wrfout(wrfout) # convert current_time to datetime object ctime = return_validate(current_time) if ctime not in time_steps: message = ('Time ' + current_time + 'not found in wrfout file: ' + wrfout) logger.error(message) raise ValueError(message) def timesteps_wrfout(wrfout): ''' return a list of timesteps (as datetime objects) in a wrfout file Input variables: - wrfout: path to a wrfout file ''' from netCDF4 import Dataset as ncdf from datetime import timedelta check_file_exists(wrfout) # check if wrfout file exists # read time information from wrfout file ncfile = ncdf(wrfout, format='NETCDF4') # minutes since start of simulation, rounded to 1 decimal float tvar = [round(nc, 0) for nc in ncfile.variables['XTIME'][:]] ncfile.close() # get start date from wrfout filename time_string = wrfout[-19:-6] start_time = return_validate(time_string) # times in netcdf file time_steps = [start_time + timedelta(minutes=step) for step in tvar] return time_steps def datetime_to_string(dtime, format='%Y-%m-%d_%H'): ''' convert datetime object to string. Standard format is 'YYYY-MM-DD_HH' Input variables: - dtime: datetime object - (optional) format: string format to return ''' from datetime import datetime # check if dtime is of instance datetime if not isinstance(dtime, datetime): message = 'input variable dtime is not of type datetime' logger.error(message) raise IOError(message) # return datetime as a string return dtime.strftime(format) def start_logging(filename, level=DEFAULT_LOG_LEVEL): ''' Start logging with given filename and level. ''' global logger if logger is None: logger = logging.getLogger() else: # wish there was a logger.close() for handler in logger.handlers[:]: # make a copy of the list logger.removeHandler(handler) logger.setLevel(LOG_LEVELS[level]) formatter = logging.Formatter(LOG_FORMAT, datefmt=DATE_FORMAT) fh = logging.FileHandler(filename) fh.setFormatter(formatter) logger.addHandler(fh) return logger def get_logger(): pass def datetime_range(start, end, delta): ''' Return a generator of all timesteps between two datetime.date(time) objects. Time between timesteps is provided by the argument delta. ''' import datetime current = start if not isinstance(delta, datetime.timedelta): try: delta = datetime.timedelta(**delta) except TypeError: message = ('delta argument in utils.datetime_range should be of ', 'a mapping of datetime.timedelta type') logger.error(message) raise TypeError(message) while current < end: yield current current += delta def excepthook(*args): ''' Replace sys.excepthook with custom handler so any uncaught exception gets logged ''' logger.error('Uncaught exception:', exc_info=args) def _create_directory(path): ''' Create a directory if it does not exist yet ''' import errno try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: # directory already exists, no problem raise # re-raise exception if a different error occured def get_wrfpy_path(): ''' get the path of wrfpy installation ''' import wrfpy return os.path.dirname(os.path.realpath(wrfpy.__file__)) def testjob(j_id): import subprocess command = "squeue -j %s" % j_id output = subprocess.check_output(command.split()) try: if j_id == int(output.split()[-8]): return True else: return False except ValueError: return False def testjobsucces(j_id): import subprocess command = "sacct -j %s --format=state" % j_id output = subprocess.check_output(command.split()) if any(x in ['CANCELED', 'FAILED', 'TIMEOUT'] for x in output.split()): raise IOError('slurm command failed') else: return True def waitJobToFinish(j_id): import time while True: time.sleep(1) if not testjob(j_id): testjobsucces(j_id) break def convert_cylc_time(string): import datetime import dateutil.parser try: return datetime.datetime.strptime( string, '%Y%m%dT%H00+01').replace(tzinfo=None) except ValueError: return dateutil.parser.parse(string).replace(tzinfo=None) def get_max_dom(namelist): ''' get maximum domain number from WRF namelist.input ''' import f90nml wrf_nml = f90nml.read(namelist) # maximum domain number return wrf_nml['domains']['max_dom'] def days_hours_minutes_seconds(td): ''' return days, hours, minutes, seconds input: datetime.timedelta ''' return (td.days, td.seconds//3600, (td.seconds//60) % 60, td.seconds % 60)
28.959259
79
0.62783
import logging import sys import os DEFAULT_LOG_LEVEL = 'debug' LOG_LEVELS = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL} LOG_LEVELS_LIST = LOG_LEVELS.keys() LOG_FORMAT = '%(asctime)s - %(levelname)s - %(message)s' DATE_FORMAT = "%Y/%m/%d/%H:%M:%S" logger = None def devnull(): if sys.version_info >= (3, 3): from subprocess import DEVNULL as devnull elif sys.version_info >= (2, 4): devnull = open(os.devnull, 'wb') else: assert sys.version_info >= (2, 4) return devnull def silentremove(filename): import errno import shutil try: os.remove(filename) except OSError as e: if e.errno != errno.ENOENT: if e.errno == errno.EISDIR: shutil.rmtree(filename) else: raise def return_validate(date_text, format='%Y-%m-%d_%H'): from datetime import datetime try: date_time = datetime.strptime(date_text, format).replace(tzinfo=None) except ValueError: logger.error('Incorrect date format, should be %s' % format) raise ValueError('Incorrect date format, should be %s' % format) return date_time def check_file_exists(filename, boolean=False): try: with open(filename): if boolean: return True else: pass except IOError: if boolean: return False else: logger.error('Unable to open file: %s' % filename) raise def validate_time_wrfout(wrfout, current_time): time_steps = timesteps_wrfout(wrfout) ctime = return_validate(current_time) if ctime not in time_steps: message = ('Time ' + current_time + 'not found in wrfout file: ' + wrfout) logger.error(message) raise ValueError(message) def timesteps_wrfout(wrfout): from netCDF4 import Dataset as ncdf from datetime import timedelta check_file_exists(wrfout) ncfile = ncdf(wrfout, format='NETCDF4') tvar = [round(nc, 0) for nc in ncfile.variables['XTIME'][:]] ncfile.close() time_string = wrfout[-19:-6] start_time = return_validate(time_string) time_steps = [start_time + timedelta(minutes=step) for step in tvar] return time_steps def datetime_to_string(dtime, format='%Y-%m-%d_%H'): from datetime import datetime if not isinstance(dtime, datetime): message = 'input variable dtime is not of type datetime' logger.error(message) raise IOError(message) return dtime.strftime(format) def start_logging(filename, level=DEFAULT_LOG_LEVEL): global logger if logger is None: logger = logging.getLogger() else: for handler in logger.handlers[:]: logger.removeHandler(handler) logger.setLevel(LOG_LEVELS[level]) formatter = logging.Formatter(LOG_FORMAT, datefmt=DATE_FORMAT) fh = logging.FileHandler(filename) fh.setFormatter(formatter) logger.addHandler(fh) return logger def get_logger(): pass def datetime_range(start, end, delta): import datetime current = start if not isinstance(delta, datetime.timedelta): try: delta = datetime.timedelta(**delta) except TypeError: message = ('delta argument in utils.datetime_range should be of ', 'a mapping of datetime.timedelta type') logger.error(message) raise TypeError(message) while current < end: yield current current += delta def excepthook(*args): logger.error('Uncaught exception:', exc_info=args) def _create_directory(path): import errno try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise def get_wrfpy_path(): import wrfpy return os.path.dirname(os.path.realpath(wrfpy.__file__)) def testjob(j_id): import subprocess command = "squeue -j %s" % j_id output = subprocess.check_output(command.split()) try: if j_id == int(output.split()[-8]): return True else: return False except ValueError: return False def testjobsucces(j_id): import subprocess command = "sacct -j %s --format=state" % j_id output = subprocess.check_output(command.split()) if any(x in ['CANCELED', 'FAILED', 'TIMEOUT'] for x in output.split()): raise IOError('slurm command failed') else: return True def waitJobToFinish(j_id): import time while True: time.sleep(1) if not testjob(j_id): testjobsucces(j_id) break def convert_cylc_time(string): import datetime import dateutil.parser try: return datetime.datetime.strptime( string, '%Y%m%dT%H00+01').replace(tzinfo=None) except ValueError: return dateutil.parser.parse(string).replace(tzinfo=None) def get_max_dom(namelist): import f90nml wrf_nml = f90nml.read(namelist) return wrf_nml['domains']['max_dom'] def days_hours_minutes_seconds(td): return (td.days, td.seconds//3600, (td.seconds//60) % 60, td.seconds % 60)
true
true
1c2c21bf1d1f3f2b5b0226a69d6c7dc8f0d87e0a
15,249
py
Python
src/python/twitter/pants/binary_util.py
wfarner/commons
42988a7a49f012665174538cca53604c7846ee86
[ "Apache-2.0" ]
1
2019-12-20T14:13:27.000Z
2019-12-20T14:13:27.000Z
src/python/twitter/pants/binary_util.py
wfarner/commons
42988a7a49f012665174538cca53604c7846ee86
[ "Apache-2.0" ]
null
null
null
src/python/twitter/pants/binary_util.py
wfarner/commons
42988a7a49f012665174538cca53604c7846ee86
[ "Apache-2.0" ]
1
2019-12-20T14:13:29.000Z
2019-12-20T14:13:29.000Z
# ================================================================================================== # Copyright 2011 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the License. # You may obtain a copy of the License in the LICENSE file, or at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ================================================================================================== from __future__ import division, print_function import os import errno import itertools import posixpath import subprocess from contextlib import closing, contextmanager from twitter.common import log from twitter.common.contextutil import environment_as, temporary_file, temporary_dir from twitter.common.dirutil import chmod_plus_x, safe_delete, safe_mkdir, safe_open, touch from twitter.common.lang import Compatibility from twitter.pants.goal.workunit import WorkUnit if Compatibility.PY3: import urllib.request as urllib_request import urllib.error as urllib_error else: import urllib2 as urllib_request import urllib2 as urllib_error from twitter.pants.base import Config from . import TaskError _ID_BY_OS = { 'linux': lambda release, machine: ('linux', machine), 'darwin': lambda release, machine: ('darwin', release.split('.')[0]), } _PATH_BY_ID = { ('linux', 'x86_64'): ['linux', 'x86_64'], ('linux', 'amd64'): ['linux', 'x86_64'], ('linux', 'i386'): ['linux', 'i386'], ('darwin', '9'): ['mac', '10.5'], ('darwin', '10'): ['mac', '10.6'], ('darwin', '11'): ['mac', '10.7'], ('darwin', '12'): ['mac', '10.8'], } def select_binary(base_path, version, name, config=None): """Selects a binary matching the current os and architecture. Raises TaskError if no binary of the given version and name could be found. """ # TODO(John Sirois): finish doc of the path structure expexcted under base_path config = config or Config.load() cachedir = config.getdefault('pants_cachedir', default=os.path.expanduser('~/.pants.d')) baseurl = config.getdefault('pants_support_baseurl') timeout_secs = config.getdefault('pants_support_fetch_timeout_secs', type=int, default=30) sysname, _, release, _, machine = os.uname() os_id = _ID_BY_OS[sysname.lower()] if os_id: middle_path = _PATH_BY_ID[os_id(release, machine)] if middle_path: binary_path = os.path.join(base_path, *(middle_path + [version, name])) cached_binary_path = os.path.join(cachedir, binary_path) if not os.path.exists(cached_binary_path): url = posixpath.join(baseurl, binary_path) log.info('Fetching %s binary from: %s' % (name, url)) downloadpath = cached_binary_path + '~' try: with closing(urllib_request.urlopen(url, timeout=timeout_secs)) as binary: with safe_open(downloadpath, 'wb') as cached_binary: cached_binary.write(binary.read()) os.rename(downloadpath, cached_binary_path) chmod_plus_x(cached_binary_path) except (IOError, urllib_error.HTTPError, urllib_error.URLError) as e: raise TaskError('Failed to fetch binary from %s: %s' % (url, e)) finally: safe_delete(downloadpath) log.debug('Selected %s binary cached at: %s' % (name, cached_binary_path)) return cached_binary_path raise TaskError('No %s binary found for: %s' % (name, (sysname, release, machine))) @contextmanager def safe_args(args, max_args=None, config=None, argfile=None, delimiter='\n', quoter=None, delete=True): """ Yields args if there are less than a limit otherwise writes args to an argfile and yields an argument list with one argument formed from the path of the argfile. :args The args to work with. :max_args The maximum number of args to let though without writing an argfile. If not specified then the maximum will be loaded from config. :config Used to lookup the configured maximum number of args that can be passed to a subprocess; defaults to the default config and looks for key 'max_subprocess_args' in the DEFAULTS. :argfile The file to write args to when there are too many; defaults to a temporary file. :delimiter The delimiter to insert between args written to the argfile, defaults to '\n' :quoter A function that can take the argfile path and return a single argument value; defaults to: <code>lambda f: '@' + f<code> :delete If True deletes any arg files created upon exit from this context; defaults to True. """ max_args = max_args or (config or Config.load()).getdefault('max_subprocess_args', int, 10) if len(args) > max_args: def create_argfile(fp): fp.write(delimiter.join(args)) fp.close() return [quoter(fp.name) if quoter else '@%s' % fp.name] if argfile: try: with safe_open(argfile, 'w') as fp: yield create_argfile(fp) finally: if delete and os.path.exists(argfile): os.unlink(argfile) else: with temporary_file(cleanup=delete) as fp: yield create_argfile(fp) else: yield args @contextmanager def safe_classpath(logger=None): """ Yields to a block in an environment with no CLASSPATH. This is useful to ensure hermetic java invocations. """ classpath = os.getenv('CLASSPATH') if classpath: logger = logger or log.warn logger('Scrubbing CLASSPATH=%s' % classpath) with environment_as(CLASSPATH=None): yield class JvmCommandLine(object): def __init__(self, jvmargs=None, classpath=None, main=None, opts=None, args=None): object.__init__(self) tuplize = lambda x: tuple(x) if x else None self.jvmargs = tuplize(jvmargs) self.classpath = tuplize(classpath) self.main = main self.opts = tuplize(opts) self.args = tuplize(args) def __str__(self): cmd = self.callable_cmd() str = ' '.join(cmd) del cmd return str def call(self, indivisible=True, **kwargs): if indivisible: cmd_with_args = self.callable_cmd() with safe_classpath(): returncode = _subprocess_call(cmd_with_args, **kwargs) else: cmd = self.callable_cmd(use_args=False) with safe_classpath(): returncode = _subprocess_call_with_args(cmd, self.args, **kwargs) return returncode def callable_cmd(self, use_args=True): """Returns a list ready to be used by subprocess.call() or subprocess.Popen() opts= can be either a list of strings or (better) a list of tuples args= is a list of paths""" cmd = ['java'] if self.jvmargs: cmd.extend(self.jvmargs) if self.classpath: cmd.extend(('-cp' if self.main else '-jar', os.pathsep.join(self.classpath))) if self.main: cmd.append(self.main) if self.opts: # opts can be [ opt1, val1, opt2, val2, opt3, opt4 ] # or # opts can be [(opt1, val1), (opt2, val2), (opt3,), (opt4,)] # the latter is prefered because it adds more useful structure # itertools.chain flattens the latter into the former cmd.extend(itertools.chain(*self.opts)) if self.args and use_args: cmd.extend(self.args) return cmd def _runjava_cmd(jvmargs=None, classpath=None, main=None, opts=None, args=None): cmd = ['java'] if jvmargs: cmd.extend(jvmargs) if classpath: cmd.extend(('-cp' if main else '-jar', os.pathsep.join(classpath))) if main: cmd.append(main) if opts: cmd.extend(opts) if args: cmd.extend(args) return cmd def _runjava_cmd_to_str(cmd): return ' '.join(cmd) def runjava_cmd_str(jvmargs=None, classpath=None, main=None, opts=None, args=None): cmd = _runjava_cmd(jvmargs=jvmargs, classpath=classpath, main=main, opts=opts, args=args) return _runjava_cmd_to_str(cmd) def runjava_indivisible(jvmargs=None, classpath=None, main=None, opts=None, args=None, dryrun=False, workunit_factory=None, workunit_name=None, **kwargs): """Spawns a java process with the supplied configuration and returns its exit code. The args list is indivisible so it can't be split across multiple invocations of the command similiar to xargs. Passes kwargs through to subproccess.call. """ cmd_with_args = _runjava_cmd(jvmargs=jvmargs, classpath=classpath, main=main, opts=opts, args=args) if dryrun: return _runjava_cmd_to_str(cmd_with_args) else: with safe_classpath(): return _subprocess_call(cmd_with_args, workunit_factory=workunit_factory, workunit_name=workunit_name or main, **kwargs) def runjava(jvmargs=None, classpath=None, main=None, opts=None, args=None, dryrun=False, workunit_factory=None, workunit_name=None, **kwargs): """Spawns a java process with the supplied configuration and returns its exit code. The args list is divisable so it can be split across multiple invocations of the command similiar to xargs. Passes kwargs through to subproccess.call. """ cmd = _runjava_cmd(jvmargs=jvmargs, classpath=classpath, main=main, opts=opts) if dryrun: return _runjava_cmd_to_str(cmd) else: with safe_classpath(): return _subprocess_call_with_args(cmd, args, workunit_factory=workunit_factory, workunit_name=workunit_name or main, **kwargs) def _split_args(i): l = list(i) half = len(l)//2 return l[:half], l[half:] def _subprocess_call(cmd_with_args, call=subprocess.call, workunit_factory=None, workunit_name=None, **kwargs): cmd_str = ' '.join(cmd_with_args) log.debug('Executing: %s' % cmd_str) if workunit_factory: workunit_labels = [WorkUnit.TOOL, WorkUnit.JVM] with workunit_factory(name=workunit_name, labels=workunit_labels, cmd=cmd_str) as workunit: try: ret = call(cmd_with_args, stdout=workunit.output('stdout'), stderr=workunit.output('stderr'), **kwargs) workunit.set_outcome(WorkUnit.FAILURE if ret else WorkUnit.SUCCESS) return ret except OSError as e: if errno.E2BIG == e.errno: # _subprocess_call_with_args will split and retry, # so we want this to appear to have succeeded. workunit.set_outcome(WorkUnit.SUCCESS) else: return call(cmd_with_args, **kwargs) def _subprocess_call_with_args(cmd, args, call=subprocess.call, workunit_factory=None, workunit_name=None, **kwargs): cmd_with_args = cmd[:] if args: cmd_with_args.extend(args) try: with safe_classpath(): return _subprocess_call(cmd_with_args, call=call, workunit_factory=workunit_factory, workunit_name=workunit_name, **kwargs) except OSError as e: if errno.E2BIG == e.errno and args and len(args) > 1: args1, args2 = _split_args(args) result1 = _subprocess_call_with_args(cmd, args1, call=call, **kwargs) result2 = _subprocess_call_with_args(cmd, args2, call=call, **kwargs) # we are making one command into two so if either fails we return fail result = 0 if 0 != result1 or 0 != result2: result = 1 return result else: raise e def profile_classpath(profile, java_runner=None, config=None, ivy_jar=None, ivy_settings=None, workunit_factory=None): # TODO(John Sirois): consider rework when ant backend is gone and there is no more need to share # path structure java_runner = java_runner or runjava_indivisible config = config or Config.load() profile_dir = config.get('ivy-profiles', 'workdir') profile_libdir = os.path.join(profile_dir, '%s.libs' % profile) profile_check = '%s.checked' % profile_libdir if not os.path.exists(profile_check): # TODO(John Sirois): refactor IvyResolve to share ivy invocation command line bits ivy_classpath = [ivy_jar] if ivy_jar else config.getlist('ivy', 'classpath') safe_mkdir(profile_libdir) ivy_settings = ivy_settings or config.get('ivy', 'ivy_settings') ivy_xml = os.path.join(profile_dir, '%s.ivy.xml' % profile) ivy_opts = [ '-settings', ivy_settings, '-ivy', ivy_xml, # TODO(John Sirois): this pattern omits an [organisation]- prefix to satisfy IDEA jar naming # needs for scala - isolate this hack to idea.py where it belongs '-retrieve', '%s/[artifact]-[revision](-[classifier]).[ext]' % profile_libdir, '-sync', '-symlink', '-types', 'jar', 'bundle', '-confs', 'default' ] result = java_runner(classpath=ivy_classpath, main='org.apache.ivy.Main', workunit_factory=workunit_factory, workunit_name='%s:bootstrap' % profile, opts=ivy_opts) if result != 0: raise TaskError('Failed to load profile %s, ivy exit code %s' % (profile, str(result))) touch(profile_check) return [os.path.join(profile_libdir, jar) for jar in os.listdir(profile_libdir)] def _mac_open(files): subprocess.call(['open'] + list(files)) def _linux_open(files): for f in list(files): subprocess.call(['xdg-open', f]) _OPENER_BY_OS = { 'darwin': _mac_open, 'linux': _linux_open } def ui_open(*files): """Attempts to open the given files using the preferred native viewer or editor.""" if files: osname = os.uname()[0].lower() if not osname in _OPENER_BY_OS: print('Sorry, open currently not supported for ' + osname) else: _OPENER_BY_OS[osname](files) def find_java_home(): # A kind-of-insane hack to find the effective java home. On some platforms there are so # many hard and symbolic links into the JRE dirs that it's actually quite hard to # establish what path to use as the java home, e.g., for the purpose of rebasing. # In practice, this seems to work fine. # # TODO: In the future we should probably hermeticize the Java enivronment rather than relying # on whatever's on the shell's PATH. E.g., you either specify a path to the Java home via a # cmd-line flag or .pantsrc, or we infer one with this method but verify that it's of a # supported version. with temporary_dir() as tmpdir: with open(os.path.join(tmpdir, 'X.java'), 'w') as srcfile: srcfile.write(''' class X { public static void main(String[] argv) { System.out.println(System.getProperty("java.home")); } }''') subprocess.Popen(['javac', '-d', tmpdir, srcfile.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() return subprocess.Popen(['java', '-cp', tmpdir, 'X'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
37.651852
100
0.66365
from __future__ import division, print_function import os import errno import itertools import posixpath import subprocess from contextlib import closing, contextmanager from twitter.common import log from twitter.common.contextutil import environment_as, temporary_file, temporary_dir from twitter.common.dirutil import chmod_plus_x, safe_delete, safe_mkdir, safe_open, touch from twitter.common.lang import Compatibility from twitter.pants.goal.workunit import WorkUnit if Compatibility.PY3: import urllib.request as urllib_request import urllib.error as urllib_error else: import urllib2 as urllib_request import urllib2 as urllib_error from twitter.pants.base import Config from . import TaskError _ID_BY_OS = { 'linux': lambda release, machine: ('linux', machine), 'darwin': lambda release, machine: ('darwin', release.split('.')[0]), } _PATH_BY_ID = { ('linux', 'x86_64'): ['linux', 'x86_64'], ('linux', 'amd64'): ['linux', 'x86_64'], ('linux', 'i386'): ['linux', 'i386'], ('darwin', '9'): ['mac', '10.5'], ('darwin', '10'): ['mac', '10.6'], ('darwin', '11'): ['mac', '10.7'], ('darwin', '12'): ['mac', '10.8'], } def select_binary(base_path, version, name, config=None): config = config or Config.load() cachedir = config.getdefault('pants_cachedir', default=os.path.expanduser('~/.pants.d')) baseurl = config.getdefault('pants_support_baseurl') timeout_secs = config.getdefault('pants_support_fetch_timeout_secs', type=int, default=30) sysname, _, release, _, machine = os.uname() os_id = _ID_BY_OS[sysname.lower()] if os_id: middle_path = _PATH_BY_ID[os_id(release, machine)] if middle_path: binary_path = os.path.join(base_path, *(middle_path + [version, name])) cached_binary_path = os.path.join(cachedir, binary_path) if not os.path.exists(cached_binary_path): url = posixpath.join(baseurl, binary_path) log.info('Fetching %s binary from: %s' % (name, url)) downloadpath = cached_binary_path + '~' try: with closing(urllib_request.urlopen(url, timeout=timeout_secs)) as binary: with safe_open(downloadpath, 'wb') as cached_binary: cached_binary.write(binary.read()) os.rename(downloadpath, cached_binary_path) chmod_plus_x(cached_binary_path) except (IOError, urllib_error.HTTPError, urllib_error.URLError) as e: raise TaskError('Failed to fetch binary from %s: %s' % (url, e)) finally: safe_delete(downloadpath) log.debug('Selected %s binary cached at: %s' % (name, cached_binary_path)) return cached_binary_path raise TaskError('No %s binary found for: %s' % (name, (sysname, release, machine))) @contextmanager def safe_args(args, max_args=None, config=None, argfile=None, delimiter='\n', quoter=None, delete=True): max_args = max_args or (config or Config.load()).getdefault('max_subprocess_args', int, 10) if len(args) > max_args: def create_argfile(fp): fp.write(delimiter.join(args)) fp.close() return [quoter(fp.name) if quoter else '@%s' % fp.name] if argfile: try: with safe_open(argfile, 'w') as fp: yield create_argfile(fp) finally: if delete and os.path.exists(argfile): os.unlink(argfile) else: with temporary_file(cleanup=delete) as fp: yield create_argfile(fp) else: yield args @contextmanager def safe_classpath(logger=None): classpath = os.getenv('CLASSPATH') if classpath: logger = logger or log.warn logger('Scrubbing CLASSPATH=%s' % classpath) with environment_as(CLASSPATH=None): yield class JvmCommandLine(object): def __init__(self, jvmargs=None, classpath=None, main=None, opts=None, args=None): object.__init__(self) tuplize = lambda x: tuple(x) if x else None self.jvmargs = tuplize(jvmargs) self.classpath = tuplize(classpath) self.main = main self.opts = tuplize(opts) self.args = tuplize(args) def __str__(self): cmd = self.callable_cmd() str = ' '.join(cmd) del cmd return str def call(self, indivisible=True, **kwargs): if indivisible: cmd_with_args = self.callable_cmd() with safe_classpath(): returncode = _subprocess_call(cmd_with_args, **kwargs) else: cmd = self.callable_cmd(use_args=False) with safe_classpath(): returncode = _subprocess_call_with_args(cmd, self.args, **kwargs) return returncode def callable_cmd(self, use_args=True): cmd = ['java'] if self.jvmargs: cmd.extend(self.jvmargs) if self.classpath: cmd.extend(('-cp' if self.main else '-jar', os.pathsep.join(self.classpath))) if self.main: cmd.append(self.main) if self.opts: cmd.extend(itertools.chain(*self.opts)) if self.args and use_args: cmd.extend(self.args) return cmd def _runjava_cmd(jvmargs=None, classpath=None, main=None, opts=None, args=None): cmd = ['java'] if jvmargs: cmd.extend(jvmargs) if classpath: cmd.extend(('-cp' if main else '-jar', os.pathsep.join(classpath))) if main: cmd.append(main) if opts: cmd.extend(opts) if args: cmd.extend(args) return cmd def _runjava_cmd_to_str(cmd): return ' '.join(cmd) def runjava_cmd_str(jvmargs=None, classpath=None, main=None, opts=None, args=None): cmd = _runjava_cmd(jvmargs=jvmargs, classpath=classpath, main=main, opts=opts, args=args) return _runjava_cmd_to_str(cmd) def runjava_indivisible(jvmargs=None, classpath=None, main=None, opts=None, args=None, dryrun=False, workunit_factory=None, workunit_name=None, **kwargs): cmd_with_args = _runjava_cmd(jvmargs=jvmargs, classpath=classpath, main=main, opts=opts, args=args) if dryrun: return _runjava_cmd_to_str(cmd_with_args) else: with safe_classpath(): return _subprocess_call(cmd_with_args, workunit_factory=workunit_factory, workunit_name=workunit_name or main, **kwargs) def runjava(jvmargs=None, classpath=None, main=None, opts=None, args=None, dryrun=False, workunit_factory=None, workunit_name=None, **kwargs): cmd = _runjava_cmd(jvmargs=jvmargs, classpath=classpath, main=main, opts=opts) if dryrun: return _runjava_cmd_to_str(cmd) else: with safe_classpath(): return _subprocess_call_with_args(cmd, args, workunit_factory=workunit_factory, workunit_name=workunit_name or main, **kwargs) def _split_args(i): l = list(i) half = len(l)//2 return l[:half], l[half:] def _subprocess_call(cmd_with_args, call=subprocess.call, workunit_factory=None, workunit_name=None, **kwargs): cmd_str = ' '.join(cmd_with_args) log.debug('Executing: %s' % cmd_str) if workunit_factory: workunit_labels = [WorkUnit.TOOL, WorkUnit.JVM] with workunit_factory(name=workunit_name, labels=workunit_labels, cmd=cmd_str) as workunit: try: ret = call(cmd_with_args, stdout=workunit.output('stdout'), stderr=workunit.output('stderr'), **kwargs) workunit.set_outcome(WorkUnit.FAILURE if ret else WorkUnit.SUCCESS) return ret except OSError as e: if errno.E2BIG == e.errno: workunit.set_outcome(WorkUnit.SUCCESS) else: return call(cmd_with_args, **kwargs) def _subprocess_call_with_args(cmd, args, call=subprocess.call, workunit_factory=None, workunit_name=None, **kwargs): cmd_with_args = cmd[:] if args: cmd_with_args.extend(args) try: with safe_classpath(): return _subprocess_call(cmd_with_args, call=call, workunit_factory=workunit_factory, workunit_name=workunit_name, **kwargs) except OSError as e: if errno.E2BIG == e.errno and args and len(args) > 1: args1, args2 = _split_args(args) result1 = _subprocess_call_with_args(cmd, args1, call=call, **kwargs) result2 = _subprocess_call_with_args(cmd, args2, call=call, **kwargs) result = 0 if 0 != result1 or 0 != result2: result = 1 return result else: raise e def profile_classpath(profile, java_runner=None, config=None, ivy_jar=None, ivy_settings=None, workunit_factory=None): java_runner = java_runner or runjava_indivisible config = config or Config.load() profile_dir = config.get('ivy-profiles', 'workdir') profile_libdir = os.path.join(profile_dir, '%s.libs' % profile) profile_check = '%s.checked' % profile_libdir if not os.path.exists(profile_check): ivy_classpath = [ivy_jar] if ivy_jar else config.getlist('ivy', 'classpath') safe_mkdir(profile_libdir) ivy_settings = ivy_settings or config.get('ivy', 'ivy_settings') ivy_xml = os.path.join(profile_dir, '%s.ivy.xml' % profile) ivy_opts = [ '-settings', ivy_settings, '-ivy', ivy_xml, '-retrieve', '%s/[artifact]-[revision](-[classifier]).[ext]' % profile_libdir, '-sync', '-symlink', '-types', 'jar', 'bundle', '-confs', 'default' ] result = java_runner(classpath=ivy_classpath, main='org.apache.ivy.Main', workunit_factory=workunit_factory, workunit_name='%s:bootstrap' % profile, opts=ivy_opts) if result != 0: raise TaskError('Failed to load profile %s, ivy exit code %s' % (profile, str(result))) touch(profile_check) return [os.path.join(profile_libdir, jar) for jar in os.listdir(profile_libdir)] def _mac_open(files): subprocess.call(['open'] + list(files)) def _linux_open(files): for f in list(files): subprocess.call(['xdg-open', f]) _OPENER_BY_OS = { 'darwin': _mac_open, 'linux': _linux_open } def ui_open(*files): if files: osname = os.uname()[0].lower() if not osname in _OPENER_BY_OS: print('Sorry, open currently not supported for ' + osname) else: _OPENER_BY_OS[osname](files) def find_java_home(): # establish what path to use as the java home, e.g., for the purpose of rebasing. # In practice, this seems to work fine. # # TODO: In the future we should probably hermeticize the Java enivronment rather than relying # on whatever's on the shell's PATH. E.g., you either specify a path to the Java home via a # cmd-line flag or .pantsrc, or we infer one with this method but verify that it's of a with temporary_dir() as tmpdir: with open(os.path.join(tmpdir, 'X.java'), 'w') as srcfile: srcfile.write(''' class X { public static void main(String[] argv) { System.out.println(System.getProperty("java.home")); } }''') subprocess.Popen(['javac', '-d', tmpdir, srcfile.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() return subprocess.Popen(['java', '-cp', tmpdir, 'X'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
true
true
1c2c2271471e2c0763c1446eef497c2efa5dc733
1,885
py
Python
discrete_fuzzy_operators/base/operators/binary_operators/suboperators/fuzzy_aggregation_suboperators/nullnorm.py
mmunar97/discrete-fuzzy-operators
e97646faa82a732b7d24c2e6621704b981b80b60
[ "MIT" ]
null
null
null
discrete_fuzzy_operators/base/operators/binary_operators/suboperators/fuzzy_aggregation_suboperators/nullnorm.py
mmunar97/discrete-fuzzy-operators
e97646faa82a732b7d24c2e6621704b981b80b60
[ "MIT" ]
null
null
null
discrete_fuzzy_operators/base/operators/binary_operators/suboperators/fuzzy_aggregation_suboperators/nullnorm.py
mmunar97/discrete-fuzzy-operators
e97646faa82a732b7d24c2e6621704b981b80b60
[ "MIT" ]
null
null
null
import numpy from discrete_fuzzy_operators.base.operators.binary_operators.suboperators.fuzzy_aggregation_operator import \ DiscreteFuzzyAggregationBinaryOperator from typing import Callable class Nullnorm(DiscreteFuzzyAggregationBinaryOperator): def __init__(self, n: int, k: int, operator_matrix: numpy.ndarray = None, operator_expression: Callable[[int, int, int], int] = None): """ Initializes the object that represents a nullnorm G: L x L -> L over a finite chain L={0, 1, ..., n} from its matrix or its analytical expression. Args: n: An integer, representing the dimension of the space where the nullnorm is defined. k: An integer, representing the absorbing element. operator_matrix: A two-dimensional matrix of integers, representing the images of the operator; that is, in the row x and column y, the entry (x,y) represents the value of F(x, y). operator_expression: A callable method with three parameters (x, y, n), which returns an integer value. """ if operator_matrix is None and operator_expression is None: raise Exception("To initialise a nullnorm it is necessary to provide its matrix expression or a callable " "method.") if not(0 <= k <= n): raise Exception("The absorbing element must be between 0 and n.") super(Nullnorm, self).__init__(n, operator_matrix, operator_expression) if not(self.is_associative() and self.is_commutative() and self.absorbing_element(element=k)): raise Exception("With the input arguments, the generated operator is not a nullnorm since not verifies " "the associativity, the commutativity or the absorbing element nullnorm.")
50.945946
118
0.661538
import numpy from discrete_fuzzy_operators.base.operators.binary_operators.suboperators.fuzzy_aggregation_operator import \ DiscreteFuzzyAggregationBinaryOperator from typing import Callable class Nullnorm(DiscreteFuzzyAggregationBinaryOperator): def __init__(self, n: int, k: int, operator_matrix: numpy.ndarray = None, operator_expression: Callable[[int, int, int], int] = None): if operator_matrix is None and operator_expression is None: raise Exception("To initialise a nullnorm it is necessary to provide its matrix expression or a callable " "method.") if not(0 <= k <= n): raise Exception("The absorbing element must be between 0 and n.") super(Nullnorm, self).__init__(n, operator_matrix, operator_expression) if not(self.is_associative() and self.is_commutative() and self.absorbing_element(element=k)): raise Exception("With the input arguments, the generated operator is not a nullnorm since not verifies " "the associativity, the commutativity or the absorbing element nullnorm.")
true
true
1c2c240ba51aa9a5a97742a7d246ed58d9c144e7
1,582
py
Python
src/test/task_scoring/tasks_tests_handler/previous_errors_test.py
JetBrains-Research/codetracker-data
6fb3900bd3cfe44d900d7fa8e89c7c35818424ed
[ "MIT" ]
4
2020-05-12T10:29:15.000Z
2020-08-21T04:26:12.000Z
src/test/task_scoring/tasks_tests_handler/previous_errors_test.py
JetBrains-Research/task-tracker-post-processing
6fb3900bd3cfe44d900d7fa8e89c7c35818424ed
[ "MIT" ]
15
2020-02-05T12:18:00.000Z
2020-05-08T09:22:50.000Z
src/test/task_scoring/tasks_tests_handler/previous_errors_test.py
JetBrains-Research/task-tracker-post-processing
6fb3900bd3cfe44d900d7fa8e89c7c35818424ed
[ "MIT" ]
1
2020-06-21T06:50:11.000Z
2020-06-21T06:50:11.000Z
# Copyright (c) 2020 Anastasiia Birillo, Elena Lyulina import os import pytest from src.main.util.consts import TEST_DATA_PATH, TASK from src.main.util.language_util import get_language_by_extension from src.main.task_scoring.tasks_tests_handler import create_in_and_out_dict, check_tasks, run_tests from src.main.util.file_util import get_all_file_system_items, get_extension_from_file, get_content_from_file PREVIOUS_ERRORS_TEST_DATA = os.path.join(TEST_DATA_PATH, 'task_scoring/tasks_tests_handler/previous_errors') REASON = 'These tests aren\'t included in all tests running because the stage of getting tasks rates has already ' \ 'passed. \nAll previous cases when some fragments had raised any errors while getting rates are fixed now.' @pytest.mark.skip(reason=REASON) # just to be sure it won't raise any errors again class TestPreviousErrors: @pytest.mark.parametrize('fragment_file', get_all_file_system_items(PREVIOUS_ERRORS_TEST_DATA, (lambda name: 'fragment' in name))) def test_fragments(self, fragment_file: str) -> None: in_and_out_files_dict = create_in_and_out_dict(TASK.tasks()) language = get_language_by_extension(get_extension_from_file(fragment_file)) check_tasks(TASK.tasks(), get_content_from_file(fragment_file), in_and_out_files_dict, language, False) # need to test ati_327/Main_67885, put it in PREVIOUS_ERRORS_TEST_DATA before running def test_codetracker_data(self) -> None: run_tests(PREVIOUS_ERRORS_TEST_DATA)
49.4375
116
0.764223
import os import pytest from src.main.util.consts import TEST_DATA_PATH, TASK from src.main.util.language_util import get_language_by_extension from src.main.task_scoring.tasks_tests_handler import create_in_and_out_dict, check_tasks, run_tests from src.main.util.file_util import get_all_file_system_items, get_extension_from_file, get_content_from_file PREVIOUS_ERRORS_TEST_DATA = os.path.join(TEST_DATA_PATH, 'task_scoring/tasks_tests_handler/previous_errors') REASON = 'These tests aren\'t included in all tests running because the stage of getting tasks rates has already ' \ 'passed. \nAll previous cases when some fragments had raised any errors while getting rates are fixed now.' @pytest.mark.skip(reason=REASON) # just to be sure it won't raise any errors again class TestPreviousErrors: @pytest.mark.parametrize('fragment_file', get_all_file_system_items(PREVIOUS_ERRORS_TEST_DATA, (lambda name: 'fragment' in name))) def test_fragments(self, fragment_file: str) -> None: in_and_out_files_dict = create_in_and_out_dict(TASK.tasks()) language = get_language_by_extension(get_extension_from_file(fragment_file)) check_tasks(TASK.tasks(), get_content_from_file(fragment_file), in_and_out_files_dict, language, False) def test_codetracker_data(self) -> None: run_tests(PREVIOUS_ERRORS_TEST_DATA)
true
true
1c2c2424c796938fda7f59e099075098b3c146c7
7,492
py
Python
test/unit/tasks/test_forecasting.py
bahia14/Fedot_Times_Series_Forecast
995751068733541ba2f546065082709ce0fb63ae
[ "BSD-3-Clause" ]
null
null
null
test/unit/tasks/test_forecasting.py
bahia14/Fedot_Times_Series_Forecast
995751068733541ba2f546065082709ce0fb63ae
[ "BSD-3-Clause" ]
null
null
null
test/unit/tasks/test_forecasting.py
bahia14/Fedot_Times_Series_Forecast
995751068733541ba2f546065082709ce0fb63ae
[ "BSD-3-Clause" ]
null
null
null
from random import seed import numpy as np import pytest from sklearn.metrics import mean_absolute_error, mean_squared_error from statsmodels.tsa.arima_process import ArmaProcess from fedot.core.data.data import InputData from fedot.core.data.data_split import train_test_data_setup from fedot.core.pipelines.node import PrimaryNode, SecondaryNode from fedot.core.pipelines.pipeline import Pipeline from fedot.core.pipelines.ts_wrappers import in_sample_ts_forecast, out_of_sample_ts_forecast from fedot.core.repository.dataset_types import DataTypesEnum from fedot.core.repository.tasks import Task, TaskTypesEnum, TsForecastingParams from fedot.utilities.synth_dataset_generator import generate_synthetic_data np.random.seed(42) seed(42) def _max_rmse_threshold_by_std(values, is_strict=True): tolerance_coeff = 3.0 if is_strict else 5.0 return np.std(values) * tolerance_coeff def get_synthetic_ts_data_period(n_steps=1000, forecast_length=5): simulated_data = ArmaProcess().generate_sample(nsample=n_steps) x1 = np.arange(0, n_steps) x2 = np.arange(0, n_steps) + 1 simulated_data = simulated_data + x1 * 0.0005 - x2 * 0.0001 periodicity = np.sin(x1 / 50) simulated_data = simulated_data + periodicity task = Task(TaskTypesEnum.ts_forecasting, TsForecastingParams(forecast_length=forecast_length)) data = InputData(idx=np.arange(0, n_steps), features=simulated_data, target=simulated_data, task=task, data_type=DataTypesEnum.ts) return train_test_data_setup(data) def get_multiscale_pipeline(): # First branch node_lagged_1 = PrimaryNode('lagged') node_lagged_1.custom_params = {'window_size': 20} node_ridge_1 = SecondaryNode('ridge', nodes_from=[node_lagged_1]) # Second branch, which will try to make prediction based on smoothed ts node_filtering = PrimaryNode('gaussian_filter') node_filtering.custom_params = {'sigma': 3} node_lagged_2 = SecondaryNode('lagged', nodes_from=[node_filtering]) node_lagged_2.custom_params = {'window_size': 100} node_ridge_2 = SecondaryNode('ridge', nodes_from=[node_lagged_2]) node_final = SecondaryNode('linear', nodes_from=[node_ridge_1, node_ridge_2]) pipeline = Pipeline(node_final) return pipeline def get_simple_ts_pipeline(model_root: str = 'ridge', window_size: int = 20): node_lagged = PrimaryNode('lagged') node_lagged.custom_params = {'window_size': window_size} node_root = SecondaryNode(model_root, nodes_from=[node_lagged]) pipeline = Pipeline(node_root) return pipeline def get_statsmodels_pipeline(): node_ar = PrimaryNode('ar') node_ar.custom_params = {'lag_1': 20, 'lag_2': 100} pipeline = Pipeline(node_ar) return pipeline def test_arima_pipeline_fit_correct(): train_data, test_data = get_synthetic_ts_data_period(forecast_length=12) pipeline = get_statsmodels_pipeline() pipeline.fit(input_data=train_data) test_pred = pipeline.predict(input_data=test_data) # Calculate metric test_pred = np.ravel(np.array(test_pred.predict)) test_target = np.ravel(np.array(test_data.target)) rmse_test = mean_squared_error(test_target, test_pred, squared=False) rmse_threshold = _max_rmse_threshold_by_std(test_data.target) assert rmse_test < rmse_threshold def test_simple_pipeline_forecast_correct(): train_data, test_data = get_synthetic_ts_data_period(forecast_length=5) pipeline = get_simple_ts_pipeline() pipeline.fit(input_data=train_data) test_pred = pipeline.predict(input_data=test_data) # Calculate metric test_pred = np.ravel(np.array(test_pred.predict)) test_target = np.ravel(np.array(test_data.target)) rmse_test = mean_squared_error(test_target, test_pred, squared=False) rmse_threshold = _max_rmse_threshold_by_std(test_data.target, is_strict=True) assert rmse_test < rmse_threshold def test_regression_multiscale_pipeline_forecast_correct(): train_data, test_data = get_synthetic_ts_data_period(forecast_length=5) pipeline = get_multiscale_pipeline() pipeline.fit(input_data=train_data) test_pred = pipeline.predict(input_data=test_data) # Calculate metric test_pred = np.ravel(np.array(test_pred.predict)) test_target = np.ravel(np.array(test_data.target)) rmse_test = mean_squared_error(test_target, test_pred, squared=False) rmse_threshold = _max_rmse_threshold_by_std(test_data.target, is_strict=True) assert rmse_test < rmse_threshold def test_ts_single_pipeline_model_without_multiotput_support(): time_series = generate_synthetic_data(20) len_forecast = 2 train_part = time_series[:-len_forecast] test_part = time_series[-len_forecast:] task = Task(TaskTypesEnum.ts_forecasting, TsForecastingParams(forecast_length=len_forecast)) train_data = InputData(idx=np.arange(0, len(train_part)), features=train_part, target=train_part, task=task, data_type=DataTypesEnum.ts) start_forecast = len(train_part) end_forecast = start_forecast + len_forecast idx_for_predict = np.arange(start_forecast, end_forecast) # Data for making prediction for a specific length test_data = InputData(idx=idx_for_predict, features=train_part, target=test_part, task=task, data_type=DataTypesEnum.ts) for model_id in ['xgbreg', 'gbr', 'adareg', 'svr', 'sgdr']: pipeline = get_simple_ts_pipeline(model_root=model_id, window_size=2) # making predictions for the missing part in the time series pipeline.fit_from_scratch(train_data) predicted_values = pipeline.predict(test_data) pipeline_forecast = np.ravel(np.array(predicted_values.predict)) test_part = np.ravel(np.array(test_part)) mae = mean_absolute_error(test_part, pipeline_forecast) assert mae < 50 def test_exception_if_incorrect_forecast_length(): with pytest.raises(ValueError) as exc: _, _ = get_synthetic_ts_data_period(forecast_length=0) assert str(exc.value) == f'Forecast length should be more then 0' def test_multistep_out_of_sample_forecasting(): horizon = 12 train_data, test_data = get_synthetic_ts_data_period(forecast_length=5) pipeline = get_multiscale_pipeline() # Fit pipeline to make forecasts 5 elements above pipeline.fit(input_data=train_data) # Make prediction for 12 elements predicted = out_of_sample_ts_forecast(pipeline=pipeline, input_data=test_data, horizon=horizon) assert len(predicted) == horizon def test_multistep_in_sample_forecasting(): horizon = 12 train_data, test_data = get_synthetic_ts_data_period(forecast_length=5) pipeline = get_multiscale_pipeline() # Fit pipeline to make forecasts 5 elements above pipeline.fit(input_data=train_data) # Make prediction for 12 elements predicted = in_sample_ts_forecast(pipeline=pipeline, input_data=test_data, horizon=horizon) assert len(predicted) == horizon
34.366972
93
0.712493
from random import seed import numpy as np import pytest from sklearn.metrics import mean_absolute_error, mean_squared_error from statsmodels.tsa.arima_process import ArmaProcess from fedot.core.data.data import InputData from fedot.core.data.data_split import train_test_data_setup from fedot.core.pipelines.node import PrimaryNode, SecondaryNode from fedot.core.pipelines.pipeline import Pipeline from fedot.core.pipelines.ts_wrappers import in_sample_ts_forecast, out_of_sample_ts_forecast from fedot.core.repository.dataset_types import DataTypesEnum from fedot.core.repository.tasks import Task, TaskTypesEnum, TsForecastingParams from fedot.utilities.synth_dataset_generator import generate_synthetic_data np.random.seed(42) seed(42) def _max_rmse_threshold_by_std(values, is_strict=True): tolerance_coeff = 3.0 if is_strict else 5.0 return np.std(values) * tolerance_coeff def get_synthetic_ts_data_period(n_steps=1000, forecast_length=5): simulated_data = ArmaProcess().generate_sample(nsample=n_steps) x1 = np.arange(0, n_steps) x2 = np.arange(0, n_steps) + 1 simulated_data = simulated_data + x1 * 0.0005 - x2 * 0.0001 periodicity = np.sin(x1 / 50) simulated_data = simulated_data + periodicity task = Task(TaskTypesEnum.ts_forecasting, TsForecastingParams(forecast_length=forecast_length)) data = InputData(idx=np.arange(0, n_steps), features=simulated_data, target=simulated_data, task=task, data_type=DataTypesEnum.ts) return train_test_data_setup(data) def get_multiscale_pipeline(): node_lagged_1 = PrimaryNode('lagged') node_lagged_1.custom_params = {'window_size': 20} node_ridge_1 = SecondaryNode('ridge', nodes_from=[node_lagged_1]) node_filtering = PrimaryNode('gaussian_filter') node_filtering.custom_params = {'sigma': 3} node_lagged_2 = SecondaryNode('lagged', nodes_from=[node_filtering]) node_lagged_2.custom_params = {'window_size': 100} node_ridge_2 = SecondaryNode('ridge', nodes_from=[node_lagged_2]) node_final = SecondaryNode('linear', nodes_from=[node_ridge_1, node_ridge_2]) pipeline = Pipeline(node_final) return pipeline def get_simple_ts_pipeline(model_root: str = 'ridge', window_size: int = 20): node_lagged = PrimaryNode('lagged') node_lagged.custom_params = {'window_size': window_size} node_root = SecondaryNode(model_root, nodes_from=[node_lagged]) pipeline = Pipeline(node_root) return pipeline def get_statsmodels_pipeline(): node_ar = PrimaryNode('ar') node_ar.custom_params = {'lag_1': 20, 'lag_2': 100} pipeline = Pipeline(node_ar) return pipeline def test_arima_pipeline_fit_correct(): train_data, test_data = get_synthetic_ts_data_period(forecast_length=12) pipeline = get_statsmodels_pipeline() pipeline.fit(input_data=train_data) test_pred = pipeline.predict(input_data=test_data) test_pred = np.ravel(np.array(test_pred.predict)) test_target = np.ravel(np.array(test_data.target)) rmse_test = mean_squared_error(test_target, test_pred, squared=False) rmse_threshold = _max_rmse_threshold_by_std(test_data.target) assert rmse_test < rmse_threshold def test_simple_pipeline_forecast_correct(): train_data, test_data = get_synthetic_ts_data_period(forecast_length=5) pipeline = get_simple_ts_pipeline() pipeline.fit(input_data=train_data) test_pred = pipeline.predict(input_data=test_data) test_pred = np.ravel(np.array(test_pred.predict)) test_target = np.ravel(np.array(test_data.target)) rmse_test = mean_squared_error(test_target, test_pred, squared=False) rmse_threshold = _max_rmse_threshold_by_std(test_data.target, is_strict=True) assert rmse_test < rmse_threshold def test_regression_multiscale_pipeline_forecast_correct(): train_data, test_data = get_synthetic_ts_data_period(forecast_length=5) pipeline = get_multiscale_pipeline() pipeline.fit(input_data=train_data) test_pred = pipeline.predict(input_data=test_data) test_pred = np.ravel(np.array(test_pred.predict)) test_target = np.ravel(np.array(test_data.target)) rmse_test = mean_squared_error(test_target, test_pred, squared=False) rmse_threshold = _max_rmse_threshold_by_std(test_data.target, is_strict=True) assert rmse_test < rmse_threshold def test_ts_single_pipeline_model_without_multiotput_support(): time_series = generate_synthetic_data(20) len_forecast = 2 train_part = time_series[:-len_forecast] test_part = time_series[-len_forecast:] task = Task(TaskTypesEnum.ts_forecasting, TsForecastingParams(forecast_length=len_forecast)) train_data = InputData(idx=np.arange(0, len(train_part)), features=train_part, target=train_part, task=task, data_type=DataTypesEnum.ts) start_forecast = len(train_part) end_forecast = start_forecast + len_forecast idx_for_predict = np.arange(start_forecast, end_forecast) test_data = InputData(idx=idx_for_predict, features=train_part, target=test_part, task=task, data_type=DataTypesEnum.ts) for model_id in ['xgbreg', 'gbr', 'adareg', 'svr', 'sgdr']: pipeline = get_simple_ts_pipeline(model_root=model_id, window_size=2) pipeline.fit_from_scratch(train_data) predicted_values = pipeline.predict(test_data) pipeline_forecast = np.ravel(np.array(predicted_values.predict)) test_part = np.ravel(np.array(test_part)) mae = mean_absolute_error(test_part, pipeline_forecast) assert mae < 50 def test_exception_if_incorrect_forecast_length(): with pytest.raises(ValueError) as exc: _, _ = get_synthetic_ts_data_period(forecast_length=0) assert str(exc.value) == f'Forecast length should be more then 0' def test_multistep_out_of_sample_forecasting(): horizon = 12 train_data, test_data = get_synthetic_ts_data_period(forecast_length=5) pipeline = get_multiscale_pipeline() pipeline.fit(input_data=train_data) predicted = out_of_sample_ts_forecast(pipeline=pipeline, input_data=test_data, horizon=horizon) assert len(predicted) == horizon def test_multistep_in_sample_forecasting(): horizon = 12 train_data, test_data = get_synthetic_ts_data_period(forecast_length=5) pipeline = get_multiscale_pipeline() pipeline.fit(input_data=train_data) predicted = in_sample_ts_forecast(pipeline=pipeline, input_data=test_data, horizon=horizon) assert len(predicted) == horizon
true
true
1c2c2446168078597ab5cdb68e8d9c24293893b6
881
py
Python
atom/nucleus/python/test/test_card_details_vo.py
AbhiGupta03/SDK
f3a61aae7a847f07f0c22a154ca88dc378e9d25e
[ "Apache-2.0" ]
null
null
null
atom/nucleus/python/test/test_card_details_vo.py
AbhiGupta03/SDK
f3a61aae7a847f07f0c22a154ca88dc378e9d25e
[ "Apache-2.0" ]
null
null
null
atom/nucleus/python/test/test_card_details_vo.py
AbhiGupta03/SDK
f3a61aae7a847f07f0c22a154ca88dc378e9d25e
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 """ Hydrogen Nucleus API The Hydrogen Nucleus API # noqa: E501 OpenAPI spec version: 1.9.5 Contact: info@hydrogenplatform.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import nucleus_api from nucleus_api.models.card_details_vo import CardDetailsVO # noqa: E501 from nucleus_api.rest import ApiException class TestCardDetailsVO(unittest.TestCase): """CardDetailsVO unit test stubs""" def setUp(self): pass def tearDown(self): pass def testCardDetailsVO(self): """Test CardDetailsVO""" # FIXME: construct object with mandatory attributes with example values # model = nucleus_api.models.card_details_vo.CardDetailsVO() # noqa: E501 pass if __name__ == '__main__': unittest.main()
21.487805
82
0.701476
from __future__ import absolute_import import unittest import nucleus_api from nucleus_api.models.card_details_vo import CardDetailsVO from nucleus_api.rest import ApiException class TestCardDetailsVO(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testCardDetailsVO(self): s if __name__ == '__main__': unittest.main()
true
true
1c2c24be7988d5e0d24c50cfd0f5ee10081a7573
665
py
Python
day16/coffeeMachine/main.py
nurmatthias/100DaysOfCode
22002e4b31d13e6b52e6b9222d2e91c2070c5744
[ "Apache-2.0" ]
null
null
null
day16/coffeeMachine/main.py
nurmatthias/100DaysOfCode
22002e4b31d13e6b52e6b9222d2e91c2070c5744
[ "Apache-2.0" ]
null
null
null
day16/coffeeMachine/main.py
nurmatthias/100DaysOfCode
22002e4b31d13e6b52e6b9222d2e91c2070c5744
[ "Apache-2.0" ]
null
null
null
from menu import Menu, MenuItem from coffee_maker import CoffeeMaker from money_machine import MoneyMachine machine = CoffeeMaker() moneyBox = MoneyMachine() menu = Menu() machine_running = True while machine_running: choice = input(f"Our menu: {menu.get_items()} \nWhat would you like? ").lower() if choice == "off": machine_running = False print("Shutingdown...") elif choice == "report": machine.report() moneyBox.report() else: drink = menu.find_drink(choice) if machine.is_resource_sufficient(drink) and moneyBox.make_payment(drink.cost): machine.make_coffee(drink)
25.576923
87
0.666165
from menu import Menu, MenuItem from coffee_maker import CoffeeMaker from money_machine import MoneyMachine machine = CoffeeMaker() moneyBox = MoneyMachine() menu = Menu() machine_running = True while machine_running: choice = input(f"Our menu: {menu.get_items()} \nWhat would you like? ").lower() if choice == "off": machine_running = False print("Shutingdown...") elif choice == "report": machine.report() moneyBox.report() else: drink = menu.find_drink(choice) if machine.is_resource_sufficient(drink) and moneyBox.make_payment(drink.cost): machine.make_coffee(drink)
true
true
1c2c25bc1316e2704e991e848fb9a89dcf6f36b1
4,656
py
Python
config_utils/re_train_deeplab_v3plus.py
charleshsc/autodeeplab
03809e5aeb8fe7d570921b0265520e9fa976da88
[ "MIT" ]
90
2020-05-19T07:19:12.000Z
2022-03-21T18:11:45.000Z
config_utils/re_train_deeplab_v3plus.py
hjl-yul154/autodeeplab
1bd8399ac830fcafd506a4207b75e05682d1e260
[ "MIT" ]
17
2020-05-18T13:52:05.000Z
2021-09-08T04:51:58.000Z
config_utils/re_train_deeplab_v3plus.py
hjl-yul154/autodeeplab
1bd8399ac830fcafd506a4207b75e05682d1e260
[ "MIT" ]
28
2020-06-14T22:30:35.000Z
2022-02-23T12:17:42.000Z
import argparse def obtain_retrain_deeplab_v3plus_args(): parser = argparse.ArgumentParser(description="PyTorch DeeplabV3Plus Training") parser.add_argument('--backbone', type=str, default='resnet', choices=['resnet', 'xception', 'drn', 'mobilenet'], help='backbone name (default: resnet)') parser.add_argument('--out-stride', type=int, default=16, help='network output stride (default: 8)') parser.add_argument('--dataset', type=str, default='pascal', choices=['pascal', 'coco', 'cityscapes'], help='dataset name (default: pascal)') parser.add_argument('--use-sbd', action='store_true', default=True, help='whether to use SBD dataset (default: True)') parser.add_argument('--workers', type=int, default=4, metavar='N', help='dataloader threads') parser.add_argument('--base-size', type=int, default=513, help='base image size') parser.add_argument('--crop-size', type=int, default=513, help='crop image size') parser.add_argument('--sync-bn', type=bool, default=None, help='whether to use sync bn (default: auto)') parser.add_argument('--freeze-bn', type=bool, default=False, help='whether to freeze bn parameters (default: False)') parser.add_argument('--loss-type', type=str, default='ce', choices=['ce', 'focal'], help='loss func type (default: ce)') # training hyper params parser.add_argument('--epochs', type=int, default=None, metavar='N', help='number of epochs to train (default: auto)') parser.add_argument('--start_epoch', type=int, default=0, metavar='N', help='start epochs (default:0)') parser.add_argument('--batch-size', type=int, default=None, metavar='N', help='input batch size for \ training (default: auto)') parser.add_argument('--test-batch-size', type=int, default=None, metavar='N', help='input batch size for \ testing (default: auto)') parser.add_argument('--use-balanced-weights', action='store_true', default=False, help='whether to use balanced weights (default: False)') # optimizer params parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (default: auto)') parser.add_argument('--lr-scheduler', type=str, default='poly', choices=['poly', 'step', 'cos'], help='lr scheduler mode: (default: poly)') parser.add_argument('--momentum', type=float, default=0.9, metavar='M', help='momentum (default: 0.9)') parser.add_argument('--weight-decay', type=float, default=5e-4, metavar='M', help='w-decay (default: 5e-4)') parser.add_argument('--nesterov', action='store_true', default=False, help='whether use nesterov (default: False)') # cuda, seed and logging parser.add_argument('--no-cuda', action='store_true', default= False, help='disables CUDA training') parser.add_argument('--gpu-ids', type=str, default='0', help='use which gpu to train, must be a \ comma-separated list of integers only (default=0)') parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') # checking point parser.add_argument('--resume', type=str, default=None, help='put the path to resuming file if needed') parser.add_argument('--checkname', type=str, default=None, help='set the checkpoint name') # finetuning pre-trained models parser.add_argument('--ft', action='store_true', default=False, help='finetuning on a different dataset') # evaluation option parser.add_argument('--eval-interval', type=int, default=1, help='evaluuation interval (default: 1)') parser.add_argument('--no-val', action='store_true', default=False, help='skip validation during training') parser.add_argument('--use-ABN', default=True, type=bool, help='whether use ABN') parser.add_argument('--affine', default=False, type=bool, help='whether use affine in BN') args = parser.parse_args() return args
58.936709
94
0.577964
import argparse def obtain_retrain_deeplab_v3plus_args(): parser = argparse.ArgumentParser(description="PyTorch DeeplabV3Plus Training") parser.add_argument('--backbone', type=str, default='resnet', choices=['resnet', 'xception', 'drn', 'mobilenet'], help='backbone name (default: resnet)') parser.add_argument('--out-stride', type=int, default=16, help='network output stride (default: 8)') parser.add_argument('--dataset', type=str, default='pascal', choices=['pascal', 'coco', 'cityscapes'], help='dataset name (default: pascal)') parser.add_argument('--use-sbd', action='store_true', default=True, help='whether to use SBD dataset (default: True)') parser.add_argument('--workers', type=int, default=4, metavar='N', help='dataloader threads') parser.add_argument('--base-size', type=int, default=513, help='base image size') parser.add_argument('--crop-size', type=int, default=513, help='crop image size') parser.add_argument('--sync-bn', type=bool, default=None, help='whether to use sync bn (default: auto)') parser.add_argument('--freeze-bn', type=bool, default=False, help='whether to freeze bn parameters (default: False)') parser.add_argument('--loss-type', type=str, default='ce', choices=['ce', 'focal'], help='loss func type (default: ce)') parser.add_argument('--epochs', type=int, default=None, metavar='N', help='number of epochs to train (default: auto)') parser.add_argument('--start_epoch', type=int, default=0, metavar='N', help='start epochs (default:0)') parser.add_argument('--batch-size', type=int, default=None, metavar='N', help='input batch size for \ training (default: auto)') parser.add_argument('--test-batch-size', type=int, default=None, metavar='N', help='input batch size for \ testing (default: auto)') parser.add_argument('--use-balanced-weights', action='store_true', default=False, help='whether to use balanced weights (default: False)') parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (default: auto)') parser.add_argument('--lr-scheduler', type=str, default='poly', choices=['poly', 'step', 'cos'], help='lr scheduler mode: (default: poly)') parser.add_argument('--momentum', type=float, default=0.9, metavar='M', help='momentum (default: 0.9)') parser.add_argument('--weight-decay', type=float, default=5e-4, metavar='M', help='w-decay (default: 5e-4)') parser.add_argument('--nesterov', action='store_true', default=False, help='whether use nesterov (default: False)') parser.add_argument('--no-cuda', action='store_true', default= False, help='disables CUDA training') parser.add_argument('--gpu-ids', type=str, default='0', help='use which gpu to train, must be a \ comma-separated list of integers only (default=0)') parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') parser.add_argument('--resume', type=str, default=None, help='put the path to resuming file if needed') parser.add_argument('--checkname', type=str, default=None, help='set the checkpoint name') parser.add_argument('--ft', action='store_true', default=False, help='finetuning on a different dataset') parser.add_argument('--eval-interval', type=int, default=1, help='evaluuation interval (default: 1)') parser.add_argument('--no-val', action='store_true', default=False, help='skip validation during training') parser.add_argument('--use-ABN', default=True, type=bool, help='whether use ABN') parser.add_argument('--affine', default=False, type=bool, help='whether use affine in BN') args = parser.parse_args() return args
true
true
1c2c26bb3d367a174b0673cc8756efbe51e0ec91
2,329
py
Python
tfx/extensions/google_cloud_ai_platform/tuner/component_test.py
avelez93/tfx
75fbb6a7d50e99138609be3ca4c3a204a13a2195
[ "Apache-2.0" ]
1,813
2019-02-04T17:17:30.000Z
2022-03-29T13:39:30.000Z
tfx/extensions/google_cloud_ai_platform/tuner/component_test.py
avelez93/tfx
75fbb6a7d50e99138609be3ca4c3a204a13a2195
[ "Apache-2.0" ]
2,710
2019-02-14T00:41:00.000Z
2022-03-31T07:23:00.000Z
tfx/extensions/google_cloud_ai_platform/tuner/component_test.py
avelez93/tfx
75fbb6a7d50e99138609be3ca4c3a204a13a2195
[ "Apache-2.0" ]
731
2019-02-04T17:59:18.000Z
2022-03-31T06:45:51.000Z
# Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for tfx.components.tuner.component.""" import tensorflow as tf from tfx.extensions.google_cloud_ai_platform.tuner import component from tfx.proto import trainer_pb2 from tfx.proto import tuner_pb2 from tfx.types import channel_utils from tfx.types import standard_artifacts class TunerTest(tf.test.TestCase): def setUp(self): super().setUp() self.examples = channel_utils.as_channel([standard_artifacts.Examples()]) self.schema = channel_utils.as_channel([standard_artifacts.Schema()]) self.transform_graph = channel_utils.as_channel( [standard_artifacts.TransformGraph()]) self.train_args = trainer_pb2.TrainArgs(num_steps=100) self.eval_args = trainer_pb2.EvalArgs(num_steps=50) self.tune_args = tuner_pb2.TuneArgs(num_parallel_trials=3) self.custom_config = {'key': 'value'} def _verify_output(self, tuner): self.assertEqual(standard_artifacts.HyperParameters.TYPE_NAME, tuner.outputs['best_hyperparameters'].type_name) def testConstructWithCustomConfig(self): tuner = component.Tuner( examples=self.examples, schema=self.schema, train_args=self.train_args, eval_args=self.eval_args, tune_args=self.tune_args, module_file='/path/to/module/file', custom_config=self.custom_config, ) self._verify_output(tuner) def testConstructWithoutCustomConfig(self): tuner = component.Tuner( examples=self.examples, schema=self.schema, train_args=self.train_args, eval_args=self.eval_args, tune_args=self.tune_args, module_file='/path/to/module/file', ) self._verify_output(tuner) if __name__ == '__main__': tf.test.main()
34.761194
77
0.731215
import tensorflow as tf from tfx.extensions.google_cloud_ai_platform.tuner import component from tfx.proto import trainer_pb2 from tfx.proto import tuner_pb2 from tfx.types import channel_utils from tfx.types import standard_artifacts class TunerTest(tf.test.TestCase): def setUp(self): super().setUp() self.examples = channel_utils.as_channel([standard_artifacts.Examples()]) self.schema = channel_utils.as_channel([standard_artifacts.Schema()]) self.transform_graph = channel_utils.as_channel( [standard_artifacts.TransformGraph()]) self.train_args = trainer_pb2.TrainArgs(num_steps=100) self.eval_args = trainer_pb2.EvalArgs(num_steps=50) self.tune_args = tuner_pb2.TuneArgs(num_parallel_trials=3) self.custom_config = {'key': 'value'} def _verify_output(self, tuner): self.assertEqual(standard_artifacts.HyperParameters.TYPE_NAME, tuner.outputs['best_hyperparameters'].type_name) def testConstructWithCustomConfig(self): tuner = component.Tuner( examples=self.examples, schema=self.schema, train_args=self.train_args, eval_args=self.eval_args, tune_args=self.tune_args, module_file='/path/to/module/file', custom_config=self.custom_config, ) self._verify_output(tuner) def testConstructWithoutCustomConfig(self): tuner = component.Tuner( examples=self.examples, schema=self.schema, train_args=self.train_args, eval_args=self.eval_args, tune_args=self.tune_args, module_file='/path/to/module/file', ) self._verify_output(tuner) if __name__ == '__main__': tf.test.main()
true
true
1c2c2728763b798c6f57925fcb7432baa6f7fd51
9,048
py
Python
idea/migrations/0019_auto__add_field_banner_slug__add_field_banner_private__chg_field_vote_.py
mikiec84/idea-box
02df9e5130ab4d463ad7f43f7a4a3a51dc640840
[ "CC0-1.0" ]
111
2015-01-05T21:15:31.000Z
2021-08-18T18:07:53.000Z
idea/migrations/0019_auto__add_field_banner_slug__add_field_banner_private__chg_field_vote_.py
mikiec84/idea-box
02df9e5130ab4d463ad7f43f7a4a3a51dc640840
[ "CC0-1.0" ]
30
2015-02-11T21:09:49.000Z
2022-03-11T23:26:07.000Z
idea/migrations/0019_auto__add_field_banner_slug__add_field_banner_private__chg_field_vote_.py
gaybro8777/idea-box
02df9e5130ab4d463ad7f43f7a4a3a51dc640840
[ "CC0-1.0" ]
39
2015-01-06T07:41:49.000Z
2022-02-24T14:03:04.000Z
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Banner.slug', unique=False for now to prevent duplicate key errors db.add_column(u'idea_banner', 'slug', self.gf('django.db.models.fields.SlugField')(default='', unique=False, max_length=50, blank=True), keep_default=False) # Adding field 'Banner.private' db.add_column(u'idea_banner', 'private', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): # Deleting field 'Banner.slug' db.delete_column(u'idea_banner', 'slug') # Deleting field 'Banner.private' db.delete_column(u'idea_banner', 'private') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'idea.banner': { 'Meta': {'object_name': 'Banner'}, 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'False', 'max_length': '50', 'blank': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {}), 'text': ('django.db.models.fields.TextField', [], {'max_length': '2000'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'idea.config': { 'Meta': {'object_name': 'Config'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'}), 'value': ('django.db.models.fields.TextField', [], {'max_length': '2000'}) }, u'idea.idea': { 'Meta': {'object_name': 'Idea'}, 'banner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['idea.Banner']", 'null': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'state': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['idea.State']"}), 'summary': ('django.db.models.fields.TextField', [], {'max_length': '200'}), 'text': ('django.db.models.fields.TextField', [], {'max_length': '2000'}), 'time': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 12, 8, 0, 0)'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'voters': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'idea_vote_creator'", 'null': 'True', 'through': u"orm['idea.Vote']", 'to': u"orm['auth.User']"}) }, u'idea.state': { 'Meta': {'object_name': 'State'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'previous': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['idea.State']", 'unique': 'True', 'null': 'True', 'blank': 'True'}) }, u'idea.vote': { 'Meta': {'object_name': 'Vote'}, 'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'idea': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['idea.Idea']"}), 'time': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 12, 8, 0, 0)'}), 'vote': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}) }, u'taggit.tag': { 'Meta': {'object_name': 'Tag'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '150'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, u'taggit.tagcategory': { 'Meta': {'object_name': 'TagCategory'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '255'}) }, u'taggit.taggeditem': { 'Meta': {'object_name': 'TaggedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_tagged_items'", 'to': u"orm['contenttypes.ContentType']"}), 'create_timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_items'", 'to': u"orm['taggit.Tag']"}), 'tag_category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['taggit.TagCategory']", 'null': 'True'}), 'tag_creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_related'", 'null': 'True', 'to': u"orm['auth.User']"}) } } complete_apps = ['idea']
68.545455
217
0.556698
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): db.add_column(u'idea_banner', 'slug', self.gf('django.db.models.fields.SlugField')(default='', unique=False, max_length=50, blank=True), keep_default=False) db.add_column(u'idea_banner', 'private', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): db.delete_column(u'idea_banner', 'slug') db.delete_column(u'idea_banner', 'private') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'idea.banner': { 'Meta': {'object_name': 'Banner'}, 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'False', 'max_length': '50', 'blank': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {}), 'text': ('django.db.models.fields.TextField', [], {'max_length': '2000'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'idea.config': { 'Meta': {'object_name': 'Config'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'}), 'value': ('django.db.models.fields.TextField', [], {'max_length': '2000'}) }, u'idea.idea': { 'Meta': {'object_name': 'Idea'}, 'banner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['idea.Banner']", 'null': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'state': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['idea.State']"}), 'summary': ('django.db.models.fields.TextField', [], {'max_length': '200'}), 'text': ('django.db.models.fields.TextField', [], {'max_length': '2000'}), 'time': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 12, 8, 0, 0)'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'voters': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'idea_vote_creator'", 'null': 'True', 'through': u"orm['idea.Vote']", 'to': u"orm['auth.User']"}) }, u'idea.state': { 'Meta': {'object_name': 'State'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'previous': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['idea.State']", 'unique': 'True', 'null': 'True', 'blank': 'True'}) }, u'idea.vote': { 'Meta': {'object_name': 'Vote'}, 'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'idea': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['idea.Idea']"}), 'time': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 12, 8, 0, 0)'}), 'vote': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}) }, u'taggit.tag': { 'Meta': {'object_name': 'Tag'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '150'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, u'taggit.tagcategory': { 'Meta': {'object_name': 'TagCategory'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '255'}) }, u'taggit.taggeditem': { 'Meta': {'object_name': 'TaggedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_tagged_items'", 'to': u"orm['contenttypes.ContentType']"}), 'create_timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_items'", 'to': u"orm['taggit.Tag']"}), 'tag_category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['taggit.TagCategory']", 'null': 'True'}), 'tag_creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_related'", 'null': 'True', 'to': u"orm['auth.User']"}) } } complete_apps = ['idea']
true
true
1c2c2763a791d54ccbcb6ac7a676edd5885da2ed
47,092
py
Python
course/utils.py
hanjianwei/relate
971e27a1bdd69236dc6dc294024b50584435a18d
[ "Unlicense" ]
null
null
null
course/utils.py
hanjianwei/relate
971e27a1bdd69236dc6dc294024b50584435a18d
[ "Unlicense" ]
6
2015-08-18T00:13:40.000Z
2018-01-31T05:55:13.000Z
course/utils.py
dzhuang/relate
f90cc146861e1523f50d29fa1e90ded32e351428
[ "Unlicense" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import division __copyright__ = "Copyright (C) 2014 Andreas Kloeckner" __license__ = """ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from typing import cast, Text import datetime # noqa import markdown from django.shortcuts import ( # noqa render, get_object_or_404) from django import http from django.core.exceptions import ObjectDoesNotExist from django.utils import translation from django.utils.translation import ( gettext as _, pgettext_lazy) from contextlib import ContextDecorator from relate.utils import string_concat from course.content import ( get_course_repo, get_flow_desc, parse_date_spec, get_course_commit_sha, CourseCommitSHADoesNotExist) from course.constants import ( flow_permission, flow_rule_kind) from course.content import ( # noqa FlowDesc, FlowPageDesc, FlowSessionStartRuleDesc, FlowSessionAccessRuleDesc, FlowSessionGradingRuleDesc, ) from course.page.base import ( # noqa PageBase, PageContext, ) # {{{ mypy from typing import ( # noqa Tuple, List, Iterable, Any, Optional, Union, Dict, FrozenSet, Text, TYPE_CHECKING) if TYPE_CHECKING: from relate.utils import Repo_ish # noqa from course.models import ( # noqa Course, Participation, ExamTicket, FlowSession, FlowPageData, ) from course.content import Repo_ish # noqa from codemirror import CodeMirrorTextarea # noqa # }}} import re CODE_CELL_DIV_ATTRS_RE = re.compile('(<div class="[^>]*code_cell[^>"]*")(>)') def getattr_with_fallback(aggregates, attr_name, default=None): # type: (Iterable[Any], Text, Any) -> Any for agg in aggregates: result = getattr(agg, attr_name, None) if result is not None: return result return default # {{{ flow permissions class FlowSessionRuleBase(object): pass class FlowSessionStartRule(FlowSessionRuleBase): def __init__( self, tag_session=None, # type: Optional[Text] may_start_new_session=None, # type: Optional[bool] may_list_existing_sessions=None, # type: Optional[bool] default_expiration_mode=None, # type: Optional[Text] ): # type: (...) -> None self.tag_session = tag_session self.may_start_new_session = may_start_new_session self.may_list_existing_sessions = may_list_existing_sessions self.default_expiration_mode = default_expiration_mode class FlowSessionAccessRule(FlowSessionRuleBase): def __init__( self, permissions, # type: FrozenSet[Text] message=None, # type: Optional[Text] ): # type: (...) -> None self.permissions = permissions self.message = message def human_readable_permissions(self): from course.models import FLOW_PERMISSION_CHOICES permission_dict = dict(FLOW_PERMISSION_CHOICES) return [permission_dict[p] for p in self.permissions] class FlowSessionGradingRule(FlowSessionRuleBase): def __init__( self, grade_identifier, # type: Optional[Text] grade_aggregation_strategy, # type: Text due, # type: Optional[datetime.datetime] generates_grade, # type: bool description=None, # type: Optional[Text] credit_percent=None, # type: Optional[float] use_last_activity_as_completion_time=None, # type: Optional[bool] max_points=None, # type: Optional[float] max_points_enforced_cap=None, # type: Optional[float] bonus_points=None, # type: Optional[float] ): # type: (...) -> None self.grade_identifier = grade_identifier self.grade_aggregation_strategy = grade_aggregation_strategy self.due = due self.generates_grade = generates_grade self.description = description self.credit_percent = credit_percent self.use_last_activity_as_completion_time = \ use_last_activity_as_completion_time self.max_points = max_points self.max_points_enforced_cap = max_points_enforced_cap self.bonus_points = bonus_points def _eval_generic_conditions( rule, # type: Any course, # type: Course participation, # type: Optional[Participation] now_datetime, # type: datetime.datetime flow_id, # type: Text login_exam_ticket, # type: Optional[ExamTicket] ): # type: (...) -> bool if hasattr(rule, "if_before"): ds = parse_date_spec(course, rule.if_before) if not (now_datetime <= ds): return False if hasattr(rule, "if_after"): ds = parse_date_spec(course, rule.if_after) if not (now_datetime >= ds): return False if hasattr(rule, "if_has_role"): from course.enrollment import get_participation_role_identifiers roles = get_participation_role_identifiers(course, participation) if all(role not in rule.if_has_role for role in roles): return False if (hasattr(rule, "if_signed_in_with_matching_exam_ticket") and rule.if_signed_in_with_matching_exam_ticket): if login_exam_ticket is None: return False if login_exam_ticket.exam.flow_id != flow_id: return False return True def _eval_generic_session_conditions( rule, # type: Any session, # type: FlowSession now_datetime, # type: datetime.datetime ): # type: (...) -> bool if hasattr(rule, "if_has_tag"): if session.access_rules_tag != rule.if_has_tag: return False if hasattr(rule, "if_started_before"): ds = parse_date_spec(session.course, rule.if_started_before) if not session.start_time < ds: return False return True def _eval_participation_tags_conditions( rule, # type: Any participation, # type: Optional[Participation] ): # type: (...) -> bool participation_tags_any_set = ( set(getattr(rule, "if_has_participation_tags_any", []))) participation_tags_all_set = ( set(getattr(rule, "if_has_participation_tags_all", []))) if participation_tags_any_set or participation_tags_all_set: if not participation: # Return False for anonymous users if only # if_has_participation_tags_any or if_has_participation_tags_all # is not empty. return False ptag_set = set(participation.tags.all().values_list("name", flat=True)) if not ptag_set: return False if ( participation_tags_any_set and not participation_tags_any_set & ptag_set): return False if ( participation_tags_all_set and not participation_tags_all_set <= ptag_set): return False return True def get_flow_rules( flow_desc, # type: FlowDesc kind, # type: Text participation, # type: Optional[Participation] flow_id, # type: Text now_datetime, # type: datetime.datetime consider_exceptions=True, # type: bool default_rules_desc=[] # type: List[Any] ): # type: (...) -> List[Any] if (not hasattr(flow_desc, "rules") or not hasattr(flow_desc.rules, kind)): rules = default_rules_desc[:] else: rules = getattr(flow_desc.rules, kind)[:] from course.models import FlowRuleException if consider_exceptions: for exc in ( FlowRuleException.objects .filter( participation=participation, active=True, kind=kind, flow_id=flow_id) # rules created first will get inserted first, and show up last .order_by("creation_time")): if exc.expiration is not None and now_datetime > exc.expiration: continue from relate.utils import dict_to_struct rules.insert(0, dict_to_struct(exc.rule)) return rules def get_session_start_rule( course, # type: Course participation, # type: Optional[Participation] flow_id, # type: Text flow_desc, # type: FlowDesc now_datetime, # type: datetime.datetime facilities=None, # type: Optional[FrozenSet[Text]] for_rollover=False, # type: bool login_exam_ticket=None, # type: Optional[ExamTicket] ): # type: (...) -> FlowSessionStartRule """Return a :class:`FlowSessionStartRule` if a new session is permitted or *None* if no new session is allowed. """ if facilities is None: facilities = frozenset() from relate.utils import dict_to_struct rules: List[FlowSessionStartRuleDesc] = get_flow_rules( flow_desc, flow_rule_kind.start, participation, flow_id, now_datetime, default_rules_desc=[ dict_to_struct(dict( may_start_new_session=True, may_list_existing_sessions=False))]) from course.models import FlowSession # noqa for rule in rules: if not _eval_generic_conditions(rule, course, participation, now_datetime, flow_id=flow_id, login_exam_ticket=login_exam_ticket): continue if not _eval_participation_tags_conditions(rule, participation): continue if not for_rollover and hasattr(rule, "if_in_facility"): if rule.if_in_facility not in facilities: continue if not for_rollover and hasattr(rule, "if_has_in_progress_session"): session_count = FlowSession.objects.filter( participation=participation, course=course, flow_id=flow_id, in_progress=True).count() if bool(session_count) != rule.if_has_in_progress_session: continue if not for_rollover and hasattr(rule, "if_has_session_tagged"): tagged_session_count = FlowSession.objects.filter( participation=participation, course=course, access_rules_tag=rule.if_has_session_tagged, flow_id=flow_id).count() if not tagged_session_count: continue if not for_rollover and hasattr(rule, "if_has_fewer_sessions_than"): session_count = FlowSession.objects.filter( participation=participation, course=course, flow_id=flow_id).count() if session_count >= rule.if_has_fewer_sessions_than: continue if not for_rollover and hasattr(rule, "if_has_fewer_tagged_sessions_than"): tagged_session_count = FlowSession.objects.filter( participation=participation, course=course, access_rules_tag__isnull=False, flow_id=flow_id).count() if tagged_session_count >= rule.if_has_fewer_tagged_sessions_than: continue return FlowSessionStartRule( tag_session=getattr(rule, "tag_session", None), may_start_new_session=getattr( rule, "may_start_new_session", True), may_list_existing_sessions=getattr( rule, "may_list_existing_sessions", True), default_expiration_mode=getattr( rule, "default_expiration_mode", None), ) return FlowSessionStartRule( may_list_existing_sessions=False, may_start_new_session=False) def get_session_access_rule( session, # type: FlowSession flow_desc, # type: FlowDesc now_datetime, # type: datetime.datetime facilities=None, # type: Optional[FrozenSet[Text]] login_exam_ticket=None, # type: Optional[ExamTicket] ): # type: (...) -> FlowSessionAccessRule """Return a :class:`ExistingFlowSessionRule`` to describe how a flow may be accessed. """ if facilities is None: facilities = frozenset() from relate.utils import dict_to_struct rules: List[FlowSessionAccessRuleDesc] = get_flow_rules( flow_desc, flow_rule_kind.access, session.participation, session.flow_id, now_datetime, default_rules_desc=[ dict_to_struct(dict( permissions=[flow_permission.view], ))]) for rule in rules: if not _eval_generic_conditions( rule, session.course, session.participation, now_datetime, flow_id=session.flow_id, login_exam_ticket=login_exam_ticket): continue if not _eval_participation_tags_conditions(rule, session.participation): continue if not _eval_generic_session_conditions(rule, session, now_datetime): continue if hasattr(rule, "if_in_facility"): if rule.if_in_facility not in facilities: continue if hasattr(rule, "if_in_progress"): if session.in_progress != rule.if_in_progress: continue if hasattr(rule, "if_expiration_mode"): if session.expiration_mode != rule.if_expiration_mode: continue if hasattr(rule, "if_session_duration_shorter_than_minutes"): duration_min = (now_datetime - session.start_time).total_seconds() / 60 if session.participation is not None: duration_min /= float(session.participation.time_factor) if duration_min > rule.if_session_duration_shorter_than_minutes: continue permissions = set(rule.permissions) # {{{ deal with deprecated permissions if "modify" in permissions: permissions.remove("modify") permissions.update([ flow_permission.submit_answer, flow_permission.end_session, ]) if "see_answer" in permissions: permissions.remove("see_answer") permissions.add(flow_permission.see_answer_after_submission) # }}} # Remove 'modify' permission from not-in-progress sessions if not session.in_progress: for perm in [ flow_permission.submit_answer, flow_permission.end_session, ]: if perm in permissions: permissions.remove(perm) return FlowSessionAccessRule( permissions=frozenset(permissions), message=getattr(rule, "message", None) ) return FlowSessionAccessRule(permissions=frozenset()) def get_session_grading_rule( session, # type: FlowSession flow_desc, # type: FlowDesc now_datetime # type: datetime.datetime ): # type: (...) -> FlowSessionGradingRule flow_desc_rules = getattr(flow_desc, "rules", None) from relate.utils import dict_to_struct rules: List[FlowSessionGradingRuleDesc] = get_flow_rules( flow_desc, flow_rule_kind.grading, session.participation, session.flow_id, now_datetime, default_rules_desc=[ dict_to_struct(dict( generates_grade=False, ))]) from course.enrollment import get_participation_role_identifiers roles = get_participation_role_identifiers(session.course, session.participation) for rule in rules: if hasattr(rule, "if_has_role"): if all(role not in rule.if_has_role for role in roles): continue if not _eval_generic_session_conditions(rule, session, now_datetime): continue if not _eval_participation_tags_conditions(rule, session.participation): continue if hasattr(rule, "if_completed_before"): ds = parse_date_spec(session.course, rule.if_completed_before) use_last_activity_as_completion_time = False if hasattr(rule, "use_last_activity_as_completion_time"): use_last_activity_as_completion_time = \ rule.use_last_activity_as_completion_time if use_last_activity_as_completion_time: last_activity = session.last_activity() if last_activity is not None: completion_time = last_activity else: completion_time = now_datetime else: if session.in_progress: completion_time = now_datetime else: completion_time = session.completion_time if completion_time > ds: continue due = parse_date_spec(session.course, getattr(rule, "due", None)) if due is not None: assert due.tzinfo is not None generates_grade = getattr(rule, "generates_grade", True) grade_identifier = None grade_aggregation_strategy = None if flow_desc_rules is not None: grade_identifier = flow_desc_rules.grade_identifier grade_aggregation_strategy = getattr( flow_desc_rules, "grade_aggregation_strategy", None) bonus_points = getattr_with_fallback((rule, flow_desc), "bonus_points", 0) max_points = getattr_with_fallback((rule, flow_desc), "max_points", None) max_points_enforced_cap = getattr_with_fallback( (rule, flow_desc), "max_points_enforced_cap", None) grade_aggregation_strategy = cast(Text, grade_aggregation_strategy) return FlowSessionGradingRule( grade_identifier=grade_identifier, grade_aggregation_strategy=grade_aggregation_strategy, due=due, generates_grade=generates_grade, description=getattr(rule, "description", None), credit_percent=getattr(rule, "credit_percent", 100), use_last_activity_as_completion_time=getattr( rule, "use_last_activity_as_completion_time", False), bonus_points=bonus_points, max_points=max_points, max_points_enforced_cap=max_points_enforced_cap, ) raise RuntimeError(_("grading rule determination was unable to find " "a grading rule")) # }}} # {{{ contexts class AnyArgumentType: # noqa pass ANY_ARGUMENT = AnyArgumentType() class CoursePageContext(object): def __init__(self, request, course_identifier): # type: (http.HttpRequest, Text) -> None self.request = request self.course_identifier = course_identifier self._permissions_cache = None # type: Optional[FrozenSet[Tuple[Text, Optional[Text]]]] # noqa self._role_identifiers_cache = None # type: Optional[List[Text]] self.old_language = None # using this to prevent nested using as context manager self._is_in_context_manager = False from course.models import Course # noqa self.course = get_object_or_404(Course, identifier=course_identifier) from course.enrollment import get_participation_for_request self.participation = get_participation_for_request( request, self.course) from course.views import check_course_state check_course_state(self.course, self.participation) self.repo = get_course_repo(self.course) try: sha = get_course_commit_sha( self.course, self.participation, repo=self.repo, raise_on_nonexistent_preview_commit=True) except CourseCommitSHADoesNotExist as e: from django.contrib import messages messages.add_message(request, messages.ERROR, str(e)) sha = self.course.active_git_commit_sha.encode() self.course_commit_sha = sha def role_identifiers(self): # type: () -> List[Text] if self._role_identifiers_cache is not None: return self._role_identifiers_cache from course.enrollment import get_participation_role_identifiers self._role_identifiers_cache = get_participation_role_identifiers( self.course, self.participation) return self._role_identifiers_cache def permissions(self): # type: () -> FrozenSet[Tuple[Text, Optional[Text]]] if self.participation is None: if self._permissions_cache is not None: return self._permissions_cache from course.enrollment import get_participation_permissions perm = get_participation_permissions(self.course, self.participation) self._permissions_cache = perm return perm else: return self.participation.permissions() def has_permission(self, perm, argument=None): # type: (Text, Union[Text, AnyArgumentType, None]) -> bool if argument is ANY_ARGUMENT: return any(perm == p for p, arg in self.permissions()) else: return (perm, argument) in self.permissions() def _set_course_lang(self, action): # type: (Text) -> None if self.course.force_lang and self.course.force_lang.strip(): if action == "activate": self.old_language = translation.get_language() translation.activate(self.course.force_lang) else: if self.old_language is None: # This should be a rare case, but get_language() can be None. # See django.utils.translation.override.__exit__() translation.deactivate_all() else: translation.activate(self.old_language) def __enter__(self): if self._is_in_context_manager: raise RuntimeError( "Nested use of 'course_view' as context manager " "is not allowed.") self._is_in_context_manager = True self._set_course_lang(action="activate") return self def __exit__(self, exc_type, exc_val, exc_tb): self._is_in_context_manager = False self._set_course_lang(action="deactivate") self.repo.close() class FlowContext(object): def __init__(self, repo, course, flow_id, participation=None): # type: (Repo_ish, Course, Text, Optional[Participation]) -> None """*participation* and *flow_session* are not stored and only used to figure out versioning of the flow content. """ self.repo = repo self.course = course self.flow_id = flow_id from django.core.exceptions import ObjectDoesNotExist self.course_commit_sha = get_course_commit_sha( self.course, participation) try: self.flow_desc = get_flow_desc(self.repo, self.course, flow_id, self.course_commit_sha) except ObjectDoesNotExist: raise http.Http404() class PageOrdinalOutOfRange(http.Http404): pass class FlowPageContext(FlowContext): """This object acts as a container for all the information that a flow page may need to render itself or respond to a POST. Note that this is different from :class:`course.page.PageContext`, which is used for in the page API. """ def __init__( self, repo, # type: Repo_ish course, # type: Course flow_id, # type: Text page_ordinal, # type: int participation, # type: Optional[Participation] flow_session, # type: FlowSession request=None, # type: Optional[http.HttpRequest] ): # type: (...) -> None super(FlowPageContext, self).__init__(repo, course, flow_id, participation) if page_ordinal >= flow_session.page_count: raise PageOrdinalOutOfRange() from course.models import FlowPageData # noqa page_data = self.page_data = get_object_or_404( FlowPageData, flow_session=flow_session, page_ordinal=page_ordinal) from course.content import get_flow_page_desc try: self.page_desc = get_flow_page_desc( flow_session.flow_id, self.flow_desc, page_data.group_id, page_data.page_id) # type: Optional[FlowPageDesc] except ObjectDoesNotExist: self.page_desc = None self.page = None # type: Optional[PageBase] self.page_context = None # type: Optional[PageContext] else: self.page = instantiate_flow_page_with_ctx(self, page_data) page_uri = None if request is not None: from django.urls import reverse page_uri = request.build_absolute_uri( reverse( "relate-view_flow_page", args=(course.identifier, flow_session.id, page_ordinal))) self.page_context = PageContext( course=self.course, repo=self.repo, commit_sha=self.course_commit_sha, flow_session=flow_session, page_uri=page_uri) self._prev_answer_visit = False @property def prev_answer_visit(self): if self._prev_answer_visit is False: from course.flow import get_prev_answer_visit self._prev_answer_visit = get_prev_answer_visit(self.page_data) return self._prev_answer_visit @property def page_ordinal(self): return self.page_data.page_ordinal def instantiate_flow_page_with_ctx(fctx, page_data): # type: (FlowContext, FlowPageData) -> PageBase from course.content import get_flow_page_desc page_desc = get_flow_page_desc( fctx.flow_id, fctx.flow_desc, page_data.group_id, page_data.page_id) from course.content import instantiate_flow_page return instantiate_flow_page( "course '%s', flow '%s', page '%s/%s'" % (fctx.course.identifier, fctx.flow_id, page_data.group_id, page_data.page_id), fctx.repo, page_desc, fctx.course_commit_sha) # }}} # {{{ utilties for course-based views def course_view(f): def wrapper(request, course_identifier, *args, **kwargs): with CoursePageContext(request, course_identifier) as pctx: response = f(pctx, *args, **kwargs) pctx.repo.close() return response from functools import update_wrapper update_wrapper(wrapper, f) return wrapper class ParticipationPermissionWrapper(object): def __init__(self, pctx): # type: (CoursePageContext) -> None self.pctx = pctx def __getitem__(self, perm): # type: (Text) -> bool from course.constants import participation_permission try: getattr(participation_permission, perm) except AttributeError: raise ValueError("permission name '%s' not valid" % perm) return self.pctx.has_permission(perm, ANY_ARGUMENT) def __iter__(self): raise TypeError("ParticipationPermissionWrapper is not iterable.") def render_course_page(pctx, template_name, args, allow_instant_flow_requests=True): # type: (CoursePageContext, Text, Dict[Text, Any], bool) -> http.HttpResponse args = args.copy() from course.views import get_now_or_fake_time now_datetime = get_now_or_fake_time(pctx.request) if allow_instant_flow_requests: from course.models import InstantFlowRequest instant_flow_requests = list((InstantFlowRequest.objects .filter( course=pctx.course, start_time__lte=now_datetime, end_time__gte=now_datetime, cancelled=False) .order_by("start_time"))) else: instant_flow_requests = [] args.update({ "course": pctx.course, "pperm": ParticipationPermissionWrapper(pctx), "participation": pctx.participation, "num_instant_flow_requests": len(instant_flow_requests), "instant_flow_requests": [(i+1, r) for i, r in enumerate(instant_flow_requests)], }) return render(pctx.request, template_name, args) # }}} # {{{ page cache class PageInstanceCache(object): """Caches instances of :class:`course.page.Page`.""" def __init__(self, repo, course, flow_id): self.repo = repo self.course = course self.flow_id = flow_id self.flow_desc_cache = {} self.page_cache = {} def get_flow_desc_from_cache(self, commit_sha): try: return self.flow_desc_cache[commit_sha] except KeyError: flow_desc = get_flow_desc(self.repo, self.course, self.flow_id, commit_sha) self.flow_desc_cache[commit_sha] = flow_desc return flow_desc def get_page(self, group_id, page_id, commit_sha): key = (group_id, page_id, commit_sha) try: return self.page_cache[key] except KeyError: from course.content import get_flow_page_desc, instantiate_flow_page page_desc = get_flow_page_desc( self.flow_id, self.get_flow_desc_from_cache(commit_sha), group_id, page_id) page = instantiate_flow_page( location="flow '%s', group, '%s', page '%s'" % (self.flow_id, group_id, page_id), repo=self.repo, page_desc=page_desc, commit_sha=commit_sha) self.page_cache[key] = page return page # }}} # {{{ codemirror config def get_codemirror_widget( language_mode, # type: Text interaction_mode, # type: Text config=None, # type: Optional[Dict] addon_css=(), # type: Tuple addon_js=(), # type: Tuple dependencies=(), # type: Tuple read_only=False, # type: bool autofocus=False, # type: bool ): # type: (...) -> Tuple[CodeMirrorTextarea,Text] from codemirror import CodeMirrorTextarea, CodeMirrorJavascript # noqa theme = "default" if read_only: theme += " relate-readonly" from django.urls import reverse help_text = (_("Press F9 to toggle full-screen mode. ") + _("Set editor mode in <a href='%s'>user profile</a>.") % reverse("relate-user_profile")) actual_addon_css = ( "dialog/dialog", "display/fullscreen", ) + addon_css actual_addon_js = ( "search/searchcursor", "dialog/dialog", "search/search", "comment/comment", "edit/matchbrackets", "display/fullscreen", "selection/active-line", "edit/trailingspace", ) + addon_js if language_mode == "python": indent_unit = 4 else: indent_unit = 2 actual_config = { "fixedGutter": True, "matchBrackets": True, "styleActiveLine": True, "showTrailingSpace": True, "indentUnit": indent_unit, "readOnly": read_only, "extraKeys": CodeMirrorJavascript(""" { "Ctrl-/": "toggleComment", "Tab": function(cm) { // from https://github.com/codemirror/CodeMirror/issues/988 if (cm.doc.somethingSelected()) { return CodeMirror.Pass; } var spacesPerTab = cm.getOption("indentUnit"); var spacesToInsert = ( spacesPerTab - (cm.doc.getCursor("start").ch % spacesPerTab)); var spaces = Array(spacesToInsert + 1).join(" "); cm.replaceSelection(spaces, "end", "+input"); }, "Shift-Tab": "indentLess", "F9": function(cm) { cm.setOption("fullScreen", !cm.getOption("fullScreen")); } } """) } if autofocus: actual_config["autofocus"] = True if interaction_mode == "vim": actual_config["vimMode"] = True actual_addon_js += ("../keymap/vim",) elif interaction_mode == "emacs": actual_config["keyMap"] = "emacs" actual_addon_js += ("../keymap/emacs",) elif interaction_mode == "sublime": actual_config["keyMap"] = "sublime" actual_addon_js += ("../keymap/sublime",) # every other interaction mode goes to default if config is not None: actual_config.update(config) return CodeMirrorTextarea( mode=language_mode, dependencies=dependencies, theme=theme, addon_css=actual_addon_css, addon_js=actual_addon_js, config=actual_config), help_text # }}} # {{{ facility processing def get_facilities_config(request=None): # type: (Optional[http.HttpRequest]) -> Optional[Dict[Text, Dict[Text, Any]]] from django.conf import settings # This is called during offline validation, where Django isn't really set up. # The getattr makes this usable. facilities = getattr(settings, "RELATE_FACILITIES", None) if facilities is None: # Only happens during offline validation. Suppresses errors there. return None if callable(facilities): from course.views import get_now_or_fake_time now_datetime = get_now_or_fake_time(request) result = facilities(now_datetime) if not isinstance(result, dict): raise RuntimeError("RELATE_FACILITIES must return a dictionary") return result else: return facilities class FacilityFindingMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): pretend_facilities = request.session.get("relate_pretend_facilities") if pretend_facilities is not None: facilities = pretend_facilities else: import ipaddress remote_address = ipaddress.ip_address( str(request.META["REMOTE_ADDR"])) facilities = set() for name, props in get_facilities_config(request).items(): ip_ranges = props.get("ip_ranges", []) for ir in ip_ranges: if remote_address in ipaddress.ip_network(str(ir)): facilities.add(name) request.relate_facilities = frozenset(facilities) return self.get_response(request) # }}} def get_col_contents_or_empty(row, index): if index >= len(row): return "" else: return row[index] def csv_data_importable(file_contents, column_idx_list, header_count): import csv spamreader = csv.reader(file_contents) n_header_row = 0 try: row0 = spamreader.__next__() except Exception as e: err_msg = type(e).__name__ err_str = str(e) if err_msg == "Error": err_msg = "" else: err_msg += ": " err_msg += err_str if "line contains NUL" in err_str: err_msg = err_msg.rstrip(".") + ". " # This message changed over time. # Make the message uniform to please the tests. err_msg = err_msg.replace("NULL byte", "NUL") err_msg += _("Are you sure the file is a CSV file other " "than a Microsoft Excel file?") return False, ( string_concat( pgettext_lazy("Starting of Error message", "Error"), ": %s" % err_msg)) from itertools import chain for row in chain([row0], spamreader): n_header_row += 1 if n_header_row <= header_count: continue try: for column_idx in column_idx_list: if column_idx is not None: str(get_col_contents_or_empty(row, column_idx-1)) except UnicodeDecodeError: return False, ( _("Error: Columns to be imported contain " "non-ASCII characters. " "Please save your CSV file as utf-8 encoded " "and import again.") ) except Exception as e: return False, ( string_concat( pgettext_lazy("Starting of Error message", "Error"), ": %(err_type)s: %(err_str)s") % { "err_type": type(e).__name__, "err_str": str(e)} ) return True, "" def will_use_masked_profile_for_email(recipient_email): # type: (Union[None, Text, List[Text]]) -> bool if not recipient_email: return False if not isinstance(recipient_email, list): recipient_email = [recipient_email] from course.models import Participation # noqa recepient_participations = ( Participation.objects.filter( user__email__in=recipient_email )) from course.constants import participation_permission as pperm for part in recepient_participations: if part.has_permission(pperm.view_participant_masked_profile): return True return False def get_course_specific_language_choices(): # type: () -> Tuple[Tuple[str, Any], ...] from django.conf import settings from collections import OrderedDict all_options = ((settings.LANGUAGE_CODE, None),) + tuple(settings.LANGUAGES) filtered_options_dict = OrderedDict(all_options) def get_default_option(): # type: () -> Tuple[Text, Text] # For the default language used, if USE_I18N is True, display # "Disabled". Otherwise display its lang info. if not settings.USE_I18N: formatted_descr = ( get_formatted_options(settings.LANGUAGE_CODE, None)[1]) else: formatted_descr = _("disabled (i.e., displayed language is " "determined by user's browser preference)") return "", string_concat("%s: " % _("Default"), formatted_descr) def get_formatted_options(lang_code, lang_descr): # type: (Text, Optional[Text]) -> Tuple[Text, Text] if lang_descr is None: lang_descr = OrderedDict(settings.LANGUAGES).get(lang_code) if lang_descr is None: try: lang_info = translation.get_language_info(lang_code) lang_descr = lang_info["name_translated"] except KeyError: return (lang_code.strip(), lang_code) return (lang_code.strip(), string_concat(_(lang_descr), " (%s)" % lang_code)) filtered_options = ( [get_default_option()] + [get_formatted_options(k, v) for k, v in filtered_options_dict.items()]) # filtered_options[1] is the option for settings.LANGUAGE_CODE # it's already displayed when settings.USE_I18N is False if not settings.USE_I18N: filtered_options.pop(1) return tuple(filtered_options) class LanguageOverride(ContextDecorator): def __init__(self, course, deactivate=False): # type: (Course, bool) -> None self.course = course self.deactivate = deactivate if course.force_lang: self.language = course.force_lang else: from django.conf import settings self.language = settings.RELATE_ADMIN_EMAIL_LOCALE def __enter__(self): # type: () -> None self.old_language = translation.get_language() if self.language is not None: translation.activate(self.language) else: translation.deactivate_all() def __exit__(self, exc_type, exc_value, traceback): # type: (Any, Any, Any) -> None if self.old_language is None: translation.deactivate_all() elif self.deactivate: translation.deactivate() else: translation.activate(self.old_language) class RelateJinjaMacroBase(object): def __init__(self, course, repo, commit_sha): # type: (Optional[Course], Repo_ish, bytes) -> None self.course = course self.repo = repo self.commit_sha = commit_sha @property def name(self): # The name of the method used in the template raise NotImplementedError() def __call__(self, *args, **kwargs): # type: (*Any, **Any) -> Text raise NotImplementedError() # {{{ ipynb utilities class IpynbJinjaMacro(RelateJinjaMacroBase): name = "render_notebook_cells" def _render_notebook_cells(self, ipynb_path, indices=None, clear_output=False, clear_markdown=False, **kwargs): # type: (Text, Optional[Any], Optional[bool], Optional[bool], **Any) -> Text from course.content import get_repo_blob_data_cached try: ipynb_source = get_repo_blob_data_cached(self.repo, ipynb_path, self.commit_sha).decode() return self._render_notebook_from_source( ipynb_source, indices=indices, clear_output=clear_output, clear_markdown=clear_markdown, **kwargs ) except ObjectDoesNotExist: raise __call__ = _render_notebook_cells # type: ignore def _render_notebook_from_source( self, ipynb_source, indices=None, clear_output=False, clear_markdown=False, **kwargs): # type: (Text, Optional[Any], Optional[bool], Optional[bool], **Any) -> Text """ Get HTML format of ipython notebook so as to be rendered in RELATE flow pages. :param ipynb_source: the :class:`text` read from a ipython notebook. :param indices: a :class:`list` instance, 0-based indices of notebook cells which are expected to be rendered. :param clear_output: a :class:`bool` instance, indicating whether existing execution output of code cells should be removed. :param clear_markdown: a :class:`bool` instance, indicating whether markdown cells will be ignored.. :return: """ import nbformat from nbformat.reader import parse_json nb_source_dict = parse_json(ipynb_source) if indices: nb_source_dict.update( {"cells": [nb_source_dict["cells"][idx] for idx in indices]}) if clear_markdown: nb_source_dict.update( {"cells": [cell for cell in nb_source_dict["cells"] if cell["cell_type"] != "markdown"]}) nb_source_dict.update({"cells": nb_source_dict["cells"]}) import json ipynb_source = json.dumps(nb_source_dict) notebook = nbformat.reads(ipynb_source, as_version=4) from traitlets.config import Config c = Config() # This is to prevent execution of arbitrary code from note book c.ExecutePreprocessor.enabled = False if clear_output: c.ClearOutputPreprocessor.enabled = True c.CSSHTMLHeaderPreprocessor.enabled = False c.HighlightMagicsPreprocessor.enabled = False import os # Place the template in course template dir import course template_path = os.path.join( os.path.dirname(course.__file__), "templates", "course", "jinja2") c.TemplateExporter.template_path.append(template_path) from nbconvert import HTMLExporter html_exporter = HTMLExporter( config=c, template_file="nbconvert_template.tpl" ) (body, resources) = html_exporter.from_notebook_node(notebook) return "<div class='relate-notebook-container'>%s</div>" % body NBCONVERT_PRE_OPEN_RE = re.compile(r"<pre\s*>\s*<relate_ipynb\s*>") NBCONVERT_PRE_CLOSE_RE = re.compile(r"</relate_ipynb\s*>\s*</pre\s*>") class NBConvertHTMLPostprocessor(markdown.postprocessors.Postprocessor): def run(self, text): text = NBCONVERT_PRE_OPEN_RE.sub("", text) text = NBCONVERT_PRE_CLOSE_RE.sub("", text) return text class NBConvertExtension(markdown.Extension): def extendMarkdown(self, md, md_globals): # noqa md.postprocessors["relate_nbconvert"] = NBConvertHTMLPostprocessor(md) # }}} def get_custom_page_types_stop_support_deadline(): # type: () -> Optional[datetime.datetime] from django.conf import settings custom_page_types_removed_deadline = getattr( settings, "RELATE_CUSTOM_PAGE_TYPES_REMOVED_DEADLINE", None) force_deadline = datetime.datetime(2019, 1, 1, 0, 0, 0, 0) if (custom_page_types_removed_deadline is None or custom_page_types_removed_deadline > force_deadline): custom_page_types_removed_deadline = force_deadline from relate.utils import localize_datetime return localize_datetime(custom_page_types_removed_deadline) # vim: foldmethod=marker
34.298616
104
0.616347
from __future__ import division __copyright__ = "Copyright (C) 2014 Andreas Kloeckner" __license__ = """ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from typing import cast, Text import datetime import markdown from django.shortcuts import ( render, get_object_or_404) from django import http from django.core.exceptions import ObjectDoesNotExist from django.utils import translation from django.utils.translation import ( gettext as _, pgettext_lazy) from contextlib import ContextDecorator from relate.utils import string_concat from course.content import ( get_course_repo, get_flow_desc, parse_date_spec, get_course_commit_sha, CourseCommitSHADoesNotExist) from course.constants import ( flow_permission, flow_rule_kind) from course.content import ( FlowDesc, FlowPageDesc, FlowSessionStartRuleDesc, FlowSessionAccessRuleDesc, FlowSessionGradingRuleDesc, ) from course.page.base import ( PageBase, PageContext, ) from typing import ( Tuple, List, Iterable, Any, Optional, Union, Dict, FrozenSet, Text, TYPE_CHECKING) if TYPE_CHECKING: from relate.utils import Repo_ish from course.models import ( Course, Participation, ExamTicket, FlowSession, FlowPageData, ) from course.content import Repo_ish from codemirror import CodeMirrorTextarea import re CODE_CELL_DIV_ATTRS_RE = re.compile('(<div class="[^>]*code_cell[^>"]*")(>)') def getattr_with_fallback(aggregates, attr_name, default=None): # type: (Iterable[Any], Text, Any) -> Any for agg in aggregates: result = getattr(agg, attr_name, None) if result is not None: return result return default # {{{ flow permissions class FlowSessionRuleBase(object): pass class FlowSessionStartRule(FlowSessionRuleBase): def __init__( self, tag_session=None, # type: Optional[Text] may_start_new_session=None, # type: Optional[bool] may_list_existing_sessions=None, # type: Optional[bool] default_expiration_mode=None, # type: Optional[Text] ): # type: (...) -> None self.tag_session = tag_session self.may_start_new_session = may_start_new_session self.may_list_existing_sessions = may_list_existing_sessions self.default_expiration_mode = default_expiration_mode class FlowSessionAccessRule(FlowSessionRuleBase): def __init__( self, permissions, # type: FrozenSet[Text] message=None, # type: Optional[Text] ): # type: (...) -> None self.permissions = permissions self.message = message def human_readable_permissions(self): from course.models import FLOW_PERMISSION_CHOICES permission_dict = dict(FLOW_PERMISSION_CHOICES) return [permission_dict[p] for p in self.permissions] class FlowSessionGradingRule(FlowSessionRuleBase): def __init__( self, grade_identifier, # type: Optional[Text] grade_aggregation_strategy, # type: Text due, # type: Optional[datetime.datetime] generates_grade, # type: bool description=None, # type: Optional[Text] credit_percent=None, # type: Optional[float] use_last_activity_as_completion_time=None, # type: Optional[bool] max_points=None, # type: Optional[float] max_points_enforced_cap=None, # type: Optional[float] bonus_points=None, # type: Optional[float] ): # type: (...) -> None self.grade_identifier = grade_identifier self.grade_aggregation_strategy = grade_aggregation_strategy self.due = due self.generates_grade = generates_grade self.description = description self.credit_percent = credit_percent self.use_last_activity_as_completion_time = \ use_last_activity_as_completion_time self.max_points = max_points self.max_points_enforced_cap = max_points_enforced_cap self.bonus_points = bonus_points def _eval_generic_conditions( rule, # type: Any course, # type: Course participation, # type: Optional[Participation] now_datetime, # type: datetime.datetime flow_id, # type: Text login_exam_ticket, # type: Optional[ExamTicket] ): # type: (...) -> bool if hasattr(rule, "if_before"): ds = parse_date_spec(course, rule.if_before) if not (now_datetime <= ds): return False if hasattr(rule, "if_after"): ds = parse_date_spec(course, rule.if_after) if not (now_datetime >= ds): return False if hasattr(rule, "if_has_role"): from course.enrollment import get_participation_role_identifiers roles = get_participation_role_identifiers(course, participation) if all(role not in rule.if_has_role for role in roles): return False if (hasattr(rule, "if_signed_in_with_matching_exam_ticket") and rule.if_signed_in_with_matching_exam_ticket): if login_exam_ticket is None: return False if login_exam_ticket.exam.flow_id != flow_id: return False return True def _eval_generic_session_conditions( rule, # type: Any session, # type: FlowSession now_datetime, # type: datetime.datetime ): # type: (...) -> bool if hasattr(rule, "if_has_tag"): if session.access_rules_tag != rule.if_has_tag: return False if hasattr(rule, "if_started_before"): ds = parse_date_spec(session.course, rule.if_started_before) if not session.start_time < ds: return False return True def _eval_participation_tags_conditions( rule, # type: Any participation, # type: Optional[Participation] ): # type: (...) -> bool participation_tags_any_set = ( set(getattr(rule, "if_has_participation_tags_any", []))) participation_tags_all_set = ( set(getattr(rule, "if_has_participation_tags_all", []))) if participation_tags_any_set or participation_tags_all_set: if not participation: # Return False for anonymous users if only # if_has_participation_tags_any or if_has_participation_tags_all # is not empty. return False ptag_set = set(participation.tags.all().values_list("name", flat=True)) if not ptag_set: return False if ( participation_tags_any_set and not participation_tags_any_set & ptag_set): return False if ( participation_tags_all_set and not participation_tags_all_set <= ptag_set): return False return True def get_flow_rules( flow_desc, # type: FlowDesc kind, # type: Text participation, # type: Optional[Participation] flow_id, # type: Text now_datetime, # type: datetime.datetime consider_exceptions=True, # type: bool default_rules_desc=[] # type: List[Any] ): # type: (...) -> List[Any] if (not hasattr(flow_desc, "rules") or not hasattr(flow_desc.rules, kind)): rules = default_rules_desc[:] else: rules = getattr(flow_desc.rules, kind)[:] from course.models import FlowRuleException if consider_exceptions: for exc in ( FlowRuleException.objects .filter( participation=participation, active=True, kind=kind, flow_id=flow_id) # rules created first will get inserted first, and show up last .order_by("creation_time")): if exc.expiration is not None and now_datetime > exc.expiration: continue from relate.utils import dict_to_struct rules.insert(0, dict_to_struct(exc.rule)) return rules def get_session_start_rule( course, # type: Course participation, # type: Optional[Participation] flow_id, # type: Text flow_desc, # type: FlowDesc now_datetime, # type: datetime.datetime facilities=None, # type: Optional[FrozenSet[Text]] for_rollover=False, # type: bool login_exam_ticket=None, # type: Optional[ExamTicket] ): # type: (...) -> FlowSessionStartRule if facilities is None: facilities = frozenset() from relate.utils import dict_to_struct rules: List[FlowSessionStartRuleDesc] = get_flow_rules( flow_desc, flow_rule_kind.start, participation, flow_id, now_datetime, default_rules_desc=[ dict_to_struct(dict( may_start_new_session=True, may_list_existing_sessions=False))]) from course.models import FlowSession # noqa for rule in rules: if not _eval_generic_conditions(rule, course, participation, now_datetime, flow_id=flow_id, login_exam_ticket=login_exam_ticket): continue if not _eval_participation_tags_conditions(rule, participation): continue if not for_rollover and hasattr(rule, "if_in_facility"): if rule.if_in_facility not in facilities: continue if not for_rollover and hasattr(rule, "if_has_in_progress_session"): session_count = FlowSession.objects.filter( participation=participation, course=course, flow_id=flow_id, in_progress=True).count() if bool(session_count) != rule.if_has_in_progress_session: continue if not for_rollover and hasattr(rule, "if_has_session_tagged"): tagged_session_count = FlowSession.objects.filter( participation=participation, course=course, access_rules_tag=rule.if_has_session_tagged, flow_id=flow_id).count() if not tagged_session_count: continue if not for_rollover and hasattr(rule, "if_has_fewer_sessions_than"): session_count = FlowSession.objects.filter( participation=participation, course=course, flow_id=flow_id).count() if session_count >= rule.if_has_fewer_sessions_than: continue if not for_rollover and hasattr(rule, "if_has_fewer_tagged_sessions_than"): tagged_session_count = FlowSession.objects.filter( participation=participation, course=course, access_rules_tag__isnull=False, flow_id=flow_id).count() if tagged_session_count >= rule.if_has_fewer_tagged_sessions_than: continue return FlowSessionStartRule( tag_session=getattr(rule, "tag_session", None), may_start_new_session=getattr( rule, "may_start_new_session", True), may_list_existing_sessions=getattr( rule, "may_list_existing_sessions", True), default_expiration_mode=getattr( rule, "default_expiration_mode", None), ) return FlowSessionStartRule( may_list_existing_sessions=False, may_start_new_session=False) def get_session_access_rule( session, # type: FlowSession flow_desc, # type: FlowDesc now_datetime, # type: datetime.datetime facilities=None, # type: Optional[FrozenSet[Text]] login_exam_ticket=None, # type: Optional[ExamTicket] ): # type: (...) -> FlowSessionAccessRule if facilities is None: facilities = frozenset() from relate.utils import dict_to_struct rules: List[FlowSessionAccessRuleDesc] = get_flow_rules( flow_desc, flow_rule_kind.access, session.participation, session.flow_id, now_datetime, default_rules_desc=[ dict_to_struct(dict( permissions=[flow_permission.view], ))]) for rule in rules: if not _eval_generic_conditions( rule, session.course, session.participation, now_datetime, flow_id=session.flow_id, login_exam_ticket=login_exam_ticket): continue if not _eval_participation_tags_conditions(rule, session.participation): continue if not _eval_generic_session_conditions(rule, session, now_datetime): continue if hasattr(rule, "if_in_facility"): if rule.if_in_facility not in facilities: continue if hasattr(rule, "if_in_progress"): if session.in_progress != rule.if_in_progress: continue if hasattr(rule, "if_expiration_mode"): if session.expiration_mode != rule.if_expiration_mode: continue if hasattr(rule, "if_session_duration_shorter_than_minutes"): duration_min = (now_datetime - session.start_time).total_seconds() / 60 if session.participation is not None: duration_min /= float(session.participation.time_factor) if duration_min > rule.if_session_duration_shorter_than_minutes: continue permissions = set(rule.permissions) # {{{ deal with deprecated permissions if "modify" in permissions: permissions.remove("modify") permissions.update([ flow_permission.submit_answer, flow_permission.end_session, ]) if "see_answer" in permissions: permissions.remove("see_answer") permissions.add(flow_permission.see_answer_after_submission) # }}} # Remove 'modify' permission from not-in-progress sessions if not session.in_progress: for perm in [ flow_permission.submit_answer, flow_permission.end_session, ]: if perm in permissions: permissions.remove(perm) return FlowSessionAccessRule( permissions=frozenset(permissions), message=getattr(rule, "message", None) ) return FlowSessionAccessRule(permissions=frozenset()) def get_session_grading_rule( session, # type: FlowSession flow_desc, # type: FlowDesc now_datetime # type: datetime.datetime ): # type: (...) -> FlowSessionGradingRule flow_desc_rules = getattr(flow_desc, "rules", None) from relate.utils import dict_to_struct rules: List[FlowSessionGradingRuleDesc] = get_flow_rules( flow_desc, flow_rule_kind.grading, session.participation, session.flow_id, now_datetime, default_rules_desc=[ dict_to_struct(dict( generates_grade=False, ))]) from course.enrollment import get_participation_role_identifiers roles = get_participation_role_identifiers(session.course, session.participation) for rule in rules: if hasattr(rule, "if_has_role"): if all(role not in rule.if_has_role for role in roles): continue if not _eval_generic_session_conditions(rule, session, now_datetime): continue if not _eval_participation_tags_conditions(rule, session.participation): continue if hasattr(rule, "if_completed_before"): ds = parse_date_spec(session.course, rule.if_completed_before) use_last_activity_as_completion_time = False if hasattr(rule, "use_last_activity_as_completion_time"): use_last_activity_as_completion_time = \ rule.use_last_activity_as_completion_time if use_last_activity_as_completion_time: last_activity = session.last_activity() if last_activity is not None: completion_time = last_activity else: completion_time = now_datetime else: if session.in_progress: completion_time = now_datetime else: completion_time = session.completion_time if completion_time > ds: continue due = parse_date_spec(session.course, getattr(rule, "due", None)) if due is not None: assert due.tzinfo is not None generates_grade = getattr(rule, "generates_grade", True) grade_identifier = None grade_aggregation_strategy = None if flow_desc_rules is not None: grade_identifier = flow_desc_rules.grade_identifier grade_aggregation_strategy = getattr( flow_desc_rules, "grade_aggregation_strategy", None) bonus_points = getattr_with_fallback((rule, flow_desc), "bonus_points", 0) max_points = getattr_with_fallback((rule, flow_desc), "max_points", None) max_points_enforced_cap = getattr_with_fallback( (rule, flow_desc), "max_points_enforced_cap", None) grade_aggregation_strategy = cast(Text, grade_aggregation_strategy) return FlowSessionGradingRule( grade_identifier=grade_identifier, grade_aggregation_strategy=grade_aggregation_strategy, due=due, generates_grade=generates_grade, description=getattr(rule, "description", None), credit_percent=getattr(rule, "credit_percent", 100), use_last_activity_as_completion_time=getattr( rule, "use_last_activity_as_completion_time", False), bonus_points=bonus_points, max_points=max_points, max_points_enforced_cap=max_points_enforced_cap, ) raise RuntimeError(_("grading rule determination was unable to find " "a grading rule")) # }}} # {{{ contexts class AnyArgumentType: # noqa pass ANY_ARGUMENT = AnyArgumentType() class CoursePageContext(object): def __init__(self, request, course_identifier): # type: (http.HttpRequest, Text) -> None self.request = request self.course_identifier = course_identifier self._permissions_cache = None # type: Optional[FrozenSet[Tuple[Text, Optional[Text]]]] # noqa self._role_identifiers_cache = None # type: Optional[List[Text]] self.old_language = None # using this to prevent nested using as context manager self._is_in_context_manager = False from course.models import Course # noqa self.course = get_object_or_404(Course, identifier=course_identifier) from course.enrollment import get_participation_for_request self.participation = get_participation_for_request( request, self.course) from course.views import check_course_state check_course_state(self.course, self.participation) self.repo = get_course_repo(self.course) try: sha = get_course_commit_sha( self.course, self.participation, repo=self.repo, raise_on_nonexistent_preview_commit=True) except CourseCommitSHADoesNotExist as e: from django.contrib import messages messages.add_message(request, messages.ERROR, str(e)) sha = self.course.active_git_commit_sha.encode() self.course_commit_sha = sha def role_identifiers(self): # type: () -> List[Text] if self._role_identifiers_cache is not None: return self._role_identifiers_cache from course.enrollment import get_participation_role_identifiers self._role_identifiers_cache = get_participation_role_identifiers( self.course, self.participation) return self._role_identifiers_cache def permissions(self): # type: () -> FrozenSet[Tuple[Text, Optional[Text]]] if self.participation is None: if self._permissions_cache is not None: return self._permissions_cache from course.enrollment import get_participation_permissions perm = get_participation_permissions(self.course, self.participation) self._permissions_cache = perm return perm else: return self.participation.permissions() def has_permission(self, perm, argument=None): # type: (Text, Union[Text, AnyArgumentType, None]) -> bool if argument is ANY_ARGUMENT: return any(perm == p for p, arg in self.permissions()) else: return (perm, argument) in self.permissions() def _set_course_lang(self, action): # type: (Text) -> None if self.course.force_lang and self.course.force_lang.strip(): if action == "activate": self.old_language = translation.get_language() translation.activate(self.course.force_lang) else: if self.old_language is None: # This should be a rare case, but get_language() can be None. # See django.utils.translation.override.__exit__() translation.deactivate_all() else: translation.activate(self.old_language) def __enter__(self): if self._is_in_context_manager: raise RuntimeError( "Nested use of 'course_view' as context manager " "is not allowed.") self._is_in_context_manager = True self._set_course_lang(action="activate") return self def __exit__(self, exc_type, exc_val, exc_tb): self._is_in_context_manager = False self._set_course_lang(action="deactivate") self.repo.close() class FlowContext(object): def __init__(self, repo, course, flow_id, participation=None): # type: (Repo_ish, Course, Text, Optional[Participation]) -> None self.repo = repo self.course = course self.flow_id = flow_id from django.core.exceptions import ObjectDoesNotExist self.course_commit_sha = get_course_commit_sha( self.course, participation) try: self.flow_desc = get_flow_desc(self.repo, self.course, flow_id, self.course_commit_sha) except ObjectDoesNotExist: raise http.Http404() class PageOrdinalOutOfRange(http.Http404): pass class FlowPageContext(FlowContext): def __init__( self, repo, # type: Repo_ish course, # type: Course flow_id, # type: Text page_ordinal, # type: int participation, # type: Optional[Participation] flow_session, # type: FlowSession request=None, # type: Optional[http.HttpRequest] ): # type: (...) -> None super(FlowPageContext, self).__init__(repo, course, flow_id, participation) if page_ordinal >= flow_session.page_count: raise PageOrdinalOutOfRange() from course.models import FlowPageData # noqa page_data = self.page_data = get_object_or_404( FlowPageData, flow_session=flow_session, page_ordinal=page_ordinal) from course.content import get_flow_page_desc try: self.page_desc = get_flow_page_desc( flow_session.flow_id, self.flow_desc, page_data.group_id, page_data.page_id) # type: Optional[FlowPageDesc] except ObjectDoesNotExist: self.page_desc = None self.page = None # type: Optional[PageBase] self.page_context = None # type: Optional[PageContext] else: self.page = instantiate_flow_page_with_ctx(self, page_data) page_uri = None if request is not None: from django.urls import reverse page_uri = request.build_absolute_uri( reverse( "relate-view_flow_page", args=(course.identifier, flow_session.id, page_ordinal))) self.page_context = PageContext( course=self.course, repo=self.repo, commit_sha=self.course_commit_sha, flow_session=flow_session, page_uri=page_uri) self._prev_answer_visit = False @property def prev_answer_visit(self): if self._prev_answer_visit is False: from course.flow import get_prev_answer_visit self._prev_answer_visit = get_prev_answer_visit(self.page_data) return self._prev_answer_visit @property def page_ordinal(self): return self.page_data.page_ordinal def instantiate_flow_page_with_ctx(fctx, page_data): # type: (FlowContext, FlowPageData) -> PageBase from course.content import get_flow_page_desc page_desc = get_flow_page_desc( fctx.flow_id, fctx.flow_desc, page_data.group_id, page_data.page_id) from course.content import instantiate_flow_page return instantiate_flow_page( "course '%s', flow '%s', page '%s/%s'" % (fctx.course.identifier, fctx.flow_id, page_data.group_id, page_data.page_id), fctx.repo, page_desc, fctx.course_commit_sha) # }}} # {{{ utilties for course-based views def course_view(f): def wrapper(request, course_identifier, *args, **kwargs): with CoursePageContext(request, course_identifier) as pctx: response = f(pctx, *args, **kwargs) pctx.repo.close() return response from functools import update_wrapper update_wrapper(wrapper, f) return wrapper class ParticipationPermissionWrapper(object): def __init__(self, pctx): # type: (CoursePageContext) -> None self.pctx = pctx def __getitem__(self, perm): # type: (Text) -> bool from course.constants import participation_permission try: getattr(participation_permission, perm) except AttributeError: raise ValueError("permission name '%s' not valid" % perm) return self.pctx.has_permission(perm, ANY_ARGUMENT) def __iter__(self): raise TypeError("ParticipationPermissionWrapper is not iterable.") def render_course_page(pctx, template_name, args, allow_instant_flow_requests=True): # type: (CoursePageContext, Text, Dict[Text, Any], bool) -> http.HttpResponse args = args.copy() from course.views import get_now_or_fake_time now_datetime = get_now_or_fake_time(pctx.request) if allow_instant_flow_requests: from course.models import InstantFlowRequest instant_flow_requests = list((InstantFlowRequest.objects .filter( course=pctx.course, start_time__lte=now_datetime, end_time__gte=now_datetime, cancelled=False) .order_by("start_time"))) else: instant_flow_requests = [] args.update({ "course": pctx.course, "pperm": ParticipationPermissionWrapper(pctx), "participation": pctx.participation, "num_instant_flow_requests": len(instant_flow_requests), "instant_flow_requests": [(i+1, r) for i, r in enumerate(instant_flow_requests)], }) return render(pctx.request, template_name, args) # }}} # {{{ page cache class PageInstanceCache(object): def __init__(self, repo, course, flow_id): self.repo = repo self.course = course self.flow_id = flow_id self.flow_desc_cache = {} self.page_cache = {} def get_flow_desc_from_cache(self, commit_sha): try: return self.flow_desc_cache[commit_sha] except KeyError: flow_desc = get_flow_desc(self.repo, self.course, self.flow_id, commit_sha) self.flow_desc_cache[commit_sha] = flow_desc return flow_desc def get_page(self, group_id, page_id, commit_sha): key = (group_id, page_id, commit_sha) try: return self.page_cache[key] except KeyError: from course.content import get_flow_page_desc, instantiate_flow_page page_desc = get_flow_page_desc( self.flow_id, self.get_flow_desc_from_cache(commit_sha), group_id, page_id) page = instantiate_flow_page( location="flow '%s', group, '%s', page '%s'" % (self.flow_id, group_id, page_id), repo=self.repo, page_desc=page_desc, commit_sha=commit_sha) self.page_cache[key] = page return page # }}} # {{{ codemirror config def get_codemirror_widget( language_mode, # type: Text interaction_mode, # type: Text config=None, # type: Optional[Dict] addon_css=(), # type: Tuple addon_js=(), # type: Tuple dependencies=(), # type: Tuple read_only=False, # type: bool autofocus=False, # type: bool ): # type: (...) -> Tuple[CodeMirrorTextarea,Text] from codemirror import CodeMirrorTextarea, CodeMirrorJavascript # noqa theme = "default" if read_only: theme += " relate-readonly" from django.urls import reverse help_text = (_("Press F9 to toggle full-screen mode. ") + _("Set editor mode in <a href='%s'>user profile</a>.") % reverse("relate-user_profile")) actual_addon_css = ( "dialog/dialog", "display/fullscreen", ) + addon_css actual_addon_js = ( "search/searchcursor", "dialog/dialog", "search/search", "comment/comment", "edit/matchbrackets", "display/fullscreen", "selection/active-line", "edit/trailingspace", ) + addon_js if language_mode == "python": indent_unit = 4 else: indent_unit = 2 actual_config = { "fixedGutter": True, "matchBrackets": True, "styleActiveLine": True, "showTrailingSpace": True, "indentUnit": indent_unit, "readOnly": read_only, "extraKeys": CodeMirrorJavascript(""" { "Ctrl-/": "toggleComment", "Tab": function(cm) { // from https://github.com/codemirror/CodeMirror/issues/988 if (cm.doc.somethingSelected()) { return CodeMirror.Pass; } var spacesPerTab = cm.getOption("indentUnit"); var spacesToInsert = ( spacesPerTab - (cm.doc.getCursor("start").ch % spacesPerTab)); var spaces = Array(spacesToInsert + 1).join(" "); cm.replaceSelection(spaces, "end", "+input"); }, "Shift-Tab": "indentLess", "F9": function(cm) { cm.setOption("fullScreen", !cm.getOption("fullScreen")); } } """) } if autofocus: actual_config["autofocus"] = True if interaction_mode == "vim": actual_config["vimMode"] = True actual_addon_js += ("../keymap/vim",) elif interaction_mode == "emacs": actual_config["keyMap"] = "emacs" actual_addon_js += ("../keymap/emacs",) elif interaction_mode == "sublime": actual_config["keyMap"] = "sublime" actual_addon_js += ("../keymap/sublime",) # every other interaction mode goes to default if config is not None: actual_config.update(config) return CodeMirrorTextarea( mode=language_mode, dependencies=dependencies, theme=theme, addon_css=actual_addon_css, addon_js=actual_addon_js, config=actual_config), help_text # }}} # {{{ facility processing def get_facilities_config(request=None): # type: (Optional[http.HttpRequest]) -> Optional[Dict[Text, Dict[Text, Any]]] from django.conf import settings # This is called during offline validation, where Django isn't really set up. # The getattr makes this usable. facilities = getattr(settings, "RELATE_FACILITIES", None) if facilities is None: # Only happens during offline validation. Suppresses errors there. return None if callable(facilities): from course.views import get_now_or_fake_time now_datetime = get_now_or_fake_time(request) result = facilities(now_datetime) if not isinstance(result, dict): raise RuntimeError("RELATE_FACILITIES must return a dictionary") return result else: return facilities class FacilityFindingMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): pretend_facilities = request.session.get("relate_pretend_facilities") if pretend_facilities is not None: facilities = pretend_facilities else: import ipaddress remote_address = ipaddress.ip_address( str(request.META["REMOTE_ADDR"])) facilities = set() for name, props in get_facilities_config(request).items(): ip_ranges = props.get("ip_ranges", []) for ir in ip_ranges: if remote_address in ipaddress.ip_network(str(ir)): facilities.add(name) request.relate_facilities = frozenset(facilities) return self.get_response(request) # }}} def get_col_contents_or_empty(row, index): if index >= len(row): return "" else: return row[index] def csv_data_importable(file_contents, column_idx_list, header_count): import csv spamreader = csv.reader(file_contents) n_header_row = 0 try: row0 = spamreader.__next__() except Exception as e: err_msg = type(e).__name__ err_str = str(e) if err_msg == "Error": err_msg = "" else: err_msg += ": " err_msg += err_str if "line contains NUL" in err_str: err_msg = err_msg.rstrip(".") + ". " # This message changed over time. # Make the message uniform to please the tests. err_msg = err_msg.replace("NULL byte", "NUL") err_msg += _("Are you sure the file is a CSV file other " "than a Microsoft Excel file?") return False, ( string_concat( pgettext_lazy("Starting of Error message", "Error"), ": %s" % err_msg)) from itertools import chain for row in chain([row0], spamreader): n_header_row += 1 if n_header_row <= header_count: continue try: for column_idx in column_idx_list: if column_idx is not None: str(get_col_contents_or_empty(row, column_idx-1)) except UnicodeDecodeError: return False, ( _("Error: Columns to be imported contain " "non-ASCII characters. " "Please save your CSV file as utf-8 encoded " "and import again.") ) except Exception as e: return False, ( string_concat( pgettext_lazy("Starting of Error message", "Error"), ": %(err_type)s: %(err_str)s") % { "err_type": type(e).__name__, "err_str": str(e)} ) return True, "" def will_use_masked_profile_for_email(recipient_email): # type: (Union[None, Text, List[Text]]) -> bool if not recipient_email: return False if not isinstance(recipient_email, list): recipient_email = [recipient_email] from course.models import Participation # noqa recepient_participations = ( Participation.objects.filter( user__email__in=recipient_email )) from course.constants import participation_permission as pperm for part in recepient_participations: if part.has_permission(pperm.view_participant_masked_profile): return True return False def get_course_specific_language_choices(): # type: () -> Tuple[Tuple[str, Any], ...] from django.conf import settings from collections import OrderedDict all_options = ((settings.LANGUAGE_CODE, None),) + tuple(settings.LANGUAGES) filtered_options_dict = OrderedDict(all_options) def get_default_option(): # type: () -> Tuple[Text, Text] # For the default language used, if USE_I18N is True, display # "Disabled". Otherwise display its lang info. if not settings.USE_I18N: formatted_descr = ( get_formatted_options(settings.LANGUAGE_CODE, None)[1]) else: formatted_descr = _("disabled (i.e., displayed language is " "determined by user's browser preference)") return "", string_concat("%s: " % _("Default"), formatted_descr) def get_formatted_options(lang_code, lang_descr): # type: (Text, Optional[Text]) -> Tuple[Text, Text] if lang_descr is None: lang_descr = OrderedDict(settings.LANGUAGES).get(lang_code) if lang_descr is None: try: lang_info = translation.get_language_info(lang_code) lang_descr = lang_info["name_translated"] except KeyError: return (lang_code.strip(), lang_code) return (lang_code.strip(), string_concat(_(lang_descr), " (%s)" % lang_code)) filtered_options = ( [get_default_option()] + [get_formatted_options(k, v) for k, v in filtered_options_dict.items()]) # filtered_options[1] is the option for settings.LANGUAGE_CODE # it's already displayed when settings.USE_I18N is False if not settings.USE_I18N: filtered_options.pop(1) return tuple(filtered_options) class LanguageOverride(ContextDecorator): def __init__(self, course, deactivate=False): # type: (Course, bool) -> None self.course = course self.deactivate = deactivate if course.force_lang: self.language = course.force_lang else: from django.conf import settings self.language = settings.RELATE_ADMIN_EMAIL_LOCALE def __enter__(self): # type: () -> None self.old_language = translation.get_language() if self.language is not None: translation.activate(self.language) else: translation.deactivate_all() def __exit__(self, exc_type, exc_value, traceback): # type: (Any, Any, Any) -> None if self.old_language is None: translation.deactivate_all() elif self.deactivate: translation.deactivate() else: translation.activate(self.old_language) class RelateJinjaMacroBase(object): def __init__(self, course, repo, commit_sha): # type: (Optional[Course], Repo_ish, bytes) -> None self.course = course self.repo = repo self.commit_sha = commit_sha @property def name(self): # The name of the method used in the template raise NotImplementedError() def __call__(self, *args, **kwargs): # type: (*Any, **Any) -> Text raise NotImplementedError() # {{{ ipynb utilities class IpynbJinjaMacro(RelateJinjaMacroBase): name = "render_notebook_cells" def _render_notebook_cells(self, ipynb_path, indices=None, clear_output=False, clear_markdown=False, **kwargs): # type: (Text, Optional[Any], Optional[bool], Optional[bool], **Any) -> Text from course.content import get_repo_blob_data_cached try: ipynb_source = get_repo_blob_data_cached(self.repo, ipynb_path, self.commit_sha).decode() return self._render_notebook_from_source( ipynb_source, indices=indices, clear_output=clear_output, clear_markdown=clear_markdown, **kwargs ) except ObjectDoesNotExist: raise __call__ = _render_notebook_cells # type: ignore def _render_notebook_from_source( self, ipynb_source, indices=None, clear_output=False, clear_markdown=False, **kwargs): # type: (Text, Optional[Any], Optional[bool], Optional[bool], **Any) -> Text import nbformat from nbformat.reader import parse_json nb_source_dict = parse_json(ipynb_source) if indices: nb_source_dict.update( {"cells": [nb_source_dict["cells"][idx] for idx in indices]}) if clear_markdown: nb_source_dict.update( {"cells": [cell for cell in nb_source_dict["cells"] if cell["cell_type"] != "markdown"]}) nb_source_dict.update({"cells": nb_source_dict["cells"]}) import json ipynb_source = json.dumps(nb_source_dict) notebook = nbformat.reads(ipynb_source, as_version=4) from traitlets.config import Config c = Config() # This is to prevent execution of arbitrary code from note book c.ExecutePreprocessor.enabled = False if clear_output: c.ClearOutputPreprocessor.enabled = True c.CSSHTMLHeaderPreprocessor.enabled = False c.HighlightMagicsPreprocessor.enabled = False import os # Place the template in course template dir import course template_path = os.path.join( os.path.dirname(course.__file__), "templates", "course", "jinja2") c.TemplateExporter.template_path.append(template_path) from nbconvert import HTMLExporter html_exporter = HTMLExporter( config=c, template_file="nbconvert_template.tpl" ) (body, resources) = html_exporter.from_notebook_node(notebook) return "<div class='relate-notebook-container'>%s</div>" % body NBCONVERT_PRE_OPEN_RE = re.compile(r"<pre\s*>\s*<relate_ipynb\s*>") NBCONVERT_PRE_CLOSE_RE = re.compile(r"</relate_ipynb\s*>\s*</pre\s*>") class NBConvertHTMLPostprocessor(markdown.postprocessors.Postprocessor): def run(self, text): text = NBCONVERT_PRE_OPEN_RE.sub("", text) text = NBCONVERT_PRE_CLOSE_RE.sub("", text) return text class NBConvertExtension(markdown.Extension): def extendMarkdown(self, md, md_globals): # noqa md.postprocessors["relate_nbconvert"] = NBConvertHTMLPostprocessor(md) # }}} def get_custom_page_types_stop_support_deadline(): # type: () -> Optional[datetime.datetime] from django.conf import settings custom_page_types_removed_deadline = getattr( settings, "RELATE_CUSTOM_PAGE_TYPES_REMOVED_DEADLINE", None) force_deadline = datetime.datetime(2019, 1, 1, 0, 0, 0, 0) if (custom_page_types_removed_deadline is None or custom_page_types_removed_deadline > force_deadline): custom_page_types_removed_deadline = force_deadline from relate.utils import localize_datetime return localize_datetime(custom_page_types_removed_deadline) # vim: foldmethod=marker
true
true
1c2c2abc292e094c964304994a04f514ca6a06e2
11,092
py
Python
deslib/des/knop.py
hossen-code/DESlib
77d0ccb491c522e7505d9ac6081b72cac001cb9e
[ "BSD-3-Clause" ]
149
2018-01-18T08:35:07.000Z
2021-11-11T19:43:40.000Z
deslib/des/knop.py
hossen-code/DESlib
77d0ccb491c522e7505d9ac6081b72cac001cb9e
[ "BSD-3-Clause" ]
90
2018-01-18T22:18:58.000Z
2020-02-08T04:39:36.000Z
deslib/des/knop.py
hossen-code/DESlib
77d0ccb491c522e7505d9ac6081b72cac001cb9e
[ "BSD-3-Clause" ]
49
2018-01-17T21:28:06.000Z
2021-02-04T21:56:13.000Z
# coding=utf-8 # Author: Rafael Menelau Oliveira e Cruz <rafaelmenelau@gmail.com> # # License: BSD 3 clause import numpy as np from deslib.des.base import BaseDES class KNOP(BaseDES): """k-Nearest Output Profiles (KNOP). This method selects all classifiers that correctly classified at least one sample belonging to the region of competence of the query sample. In this case, the region of competence is estimated using the decisions of the base classifier (output profiles). Thus, the similarity between the query and the validation samples are measured in the decision space rather than the feature space. Each selected classifier has a number of votes equals to the number of samples in the region of competence that it predicts the correct label. The votes obtained by all base classifiers are aggregated to obtain the final ensemble decision. Parameters ---------- pool_classifiers : list of classifiers (Default = None) The generated_pool of classifiers trained for the corresponding classification problem. Each base classifiers should support the method "predict". If None, then the pool of classifiers is a bagging classifier. k : int (Default = 7) Number of neighbors used to estimate the competence of the base classifiers. DFP : Boolean (Default = False) Determines if the dynamic frienemy pruning is applied. with_IH : Boolean (Default = False) Whether the hardness level of the region of competence is used to decide between using the DS algorithm or the KNN for classification of a given query sample. safe_k : int (default = None) The size of the indecision region. IH_rate : float (default = 0.3) Hardness threshold. If the hardness level of the competence region is lower than the IH_rate the KNN classifier is used. Otherwise, the DS algorithm is used for classification. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. knn_classifier : {'knn', 'faiss', None} (Default = 'knn') The algorithm used to estimate the region of competence: - 'knn' will use :class:`KNeighborsClassifier` from sklearn :class:`KNNE` available on `deslib.utils.knne` - 'faiss' will use Facebook's Faiss similarity search through the class :class:`FaissKNNClassifier` - None, will use sklearn :class:`KNeighborsClassifier`. knne : bool (Default=False) Whether to use K-Nearest Neighbor Equality (KNNE) for the region of competence estimation. DSEL_perc : float (Default = 0.5) Percentage of the input data used to fit DSEL. Note: This parameter is only used if the pool of classifier is None or unfitted. References ---------- Cavalin, Paulo R., Robert Sabourin, and Ching Y. Suen. "LoGID: An adaptive framework combining local and global incremental learning for dynamic selection of ensembles of HMMs." Pattern Recognition 45.9 (2012): 3544-3556. Cavalin, Paulo R., Robert Sabourin, and Ching Y. Suen. "Dynamic selection approaches for multiple classifier systems." Neural Computing and Applications 22.3-4 (2013): 673-688. Ko, Albert HR, Robert Sabourin, and Alceu Souza Britto Jr. "From dynamic classifier selection to dynamic ensemble selection." Pattern Recognition 41.5 (2008): 1718-1731. Britto, Alceu S., Robert Sabourin, and Luiz ES Oliveira. "Dynamic selection of classifiers—a comprehensive review." Pattern Recognition 47.11 (2014): 3665-3680 R. M. O. Cruz, R. Sabourin, and G. D. Cavalcanti, “Dynamic classifier selection: Recent advances and perspectives,” Information Fusion, vol. 41, pp. 195 – 216, 2018. """ def __init__(self, pool_classifiers=None, k=7, DFP=False, with_IH=False, safe_k=None, IH_rate=0.30, random_state=None, knn_classifier='knn', knne=False, DSEL_perc=0.5): super(KNOP, self).__init__(pool_classifiers, k, DFP=DFP, with_IH=with_IH, safe_k=safe_k, IH_rate=IH_rate, mode='weighting', needs_proba=True, random_state=random_state, knn_classifier=knn_classifier, knne=knne, DSEL_perc=DSEL_perc) def fit(self, X, y): """Train the DS model by setting the KNN algorithm and pre-process the information required to apply the DS methods. In this case, the scores of the base classifiers for the dynamic selection dataset (DSEL) are pre-calculated to transform each sample in DSEL into an output profile. Parameters ---------- X : array of shape (n_samples, n_features) Data used to fit the model. y : array of shape (n_samples) class labels of each example in X. Returns ------- self """ super(KNOP, self).fit(X, y) if self.n_classes_ == 1: raise ValueError( "Error. KNOP does not accept one class datasets!") self._check_predict_proba() self.dsel_scores_ = self._preprocess_dsel_scores() # Reshape DSEL_scores as a 2-D array for nearest neighbor calculations dsel_output_profiles = self.dsel_scores_.reshape(self.n_samples_, self.n_classifiers_ * self.n_classes_) self._fit_OP(dsel_output_profiles, self.DSEL_target_, self.k_) return self def _fit_OP(self, X_op, y_op, k): """ Fit the set of output profiles. Parameters ---------- X_op : array of shape (n_samples, n_features) Output profiles of the training data. n_features is equals to (n_classifiers x n_classes). y_op : array of shape (n_samples) Class labels of each sample in X_op. k : int Number of output profiles used in the region of competence estimation. """ self.op_knn_ = self.knn_class_(k) if self.n_classes_ == 2: # Get only the scores for one class since they are complementary X_temp = X_op[:, ::2] self.op_knn_.fit(X_temp, y_op) else: self.op_knn_.fit(X_op, y_op) def _get_similar_out_profiles(self, probabilities): """Get the most similar output profiles of the query sample. Parameters ---------- probabilities : array of shape (n_samples, n_classifiers, n_classes) predictions of each base classifier for all samples. Returns ------- dists : list of shape = [n_samples, k] The distances between the query and each sample in the region of competence. The vector is ordered in an ascending fashion. idx : list of shape = [n_samples, k] Indices of the instances belonging to the region of competence of the given query sample. """ if self.n_classes_ == 2: # Get only the scores for one class since they are complementary query_op = probabilities[:, :, 0] else: query_op = probabilities.reshape((probabilities.shape[0], self.n_classifiers_ * self.n_classes_)) dists, idx = self.op_knn_.kneighbors(query_op, n_neighbors=self.k_, return_distance=True) return dists, np.atleast_2d(idx) def estimate_competence_from_proba(self, query, probabilities, neighbors=None, distances=None): """The competence of the base classifiers is simply estimated as the number of samples in the region of competence that it correctly classified. This method received an array with the pre-calculated probability estimates for each query. This information is later used to determine the number of votes obtained for each base classifier. Parameters ---------- query : array of shape (n_samples, n_features) The test examples. neighbors : array of shape (n_samples, n_neighbors) Indices of the k nearest neighbors according for each test sample distances : array of shape (n_samples, n_neighbors) Distances of the k nearest neighbors according for each test sample. probabilities : array of shape (n_samples, n_classifiers, n_classes) Probabilities estimates obtained by each each base classifier for each query sample. Returns ------- competences : array of shape (n_samples, n_classifiers) Competence level estimated for each base classifier and test example. """ _, idx_neighbors = self._get_similar_out_profiles(probabilities) competences = np.sum(self.DSEL_processed_[idx_neighbors, :], axis=1, dtype=np.float) return competences def select(self, competences): """Select the base classifiers for the classification of the query sample. Each base classifier can be selected more than once. The number of times a base classifier is selected (votes) is equals to the number of samples it correctly classified in the region of competence. Parameters ---------- competences : array of shape (n_samples, n_classifiers) Competence level estimated for each base classifier and test example. Returns ------- selected_classifiers : array of shape (n_samples, n_classifiers) Boolean matrix containing True if the base classifier is selected, False otherwise. """ if competences.ndim < 2: competences = competences.reshape(1, -1) # Select classifier if it correctly classified at least one sample selected_classifiers = (competences > 0) # For the rows that are all False (i.e., no base classifier # was selected, select all classifiers (set all True) selected_classifiers[~np.any(selected_classifiers, axis=1), :] = True return selected_classifiers
39.47331
79
0.617652
import numpy as np from deslib.des.base import BaseDES class KNOP(BaseDES): def __init__(self, pool_classifiers=None, k=7, DFP=False, with_IH=False, safe_k=None, IH_rate=0.30, random_state=None, knn_classifier='knn', knne=False, DSEL_perc=0.5): super(KNOP, self).__init__(pool_classifiers, k, DFP=DFP, with_IH=with_IH, safe_k=safe_k, IH_rate=IH_rate, mode='weighting', needs_proba=True, random_state=random_state, knn_classifier=knn_classifier, knne=knne, DSEL_perc=DSEL_perc) def fit(self, X, y): super(KNOP, self).fit(X, y) if self.n_classes_ == 1: raise ValueError( "Error. KNOP does not accept one class datasets!") self._check_predict_proba() self.dsel_scores_ = self._preprocess_dsel_scores() dsel_output_profiles = self.dsel_scores_.reshape(self.n_samples_, self.n_classifiers_ * self.n_classes_) self._fit_OP(dsel_output_profiles, self.DSEL_target_, self.k_) return self def _fit_OP(self, X_op, y_op, k): self.op_knn_ = self.knn_class_(k) if self.n_classes_ == 2: X_temp = X_op[:, ::2] self.op_knn_.fit(X_temp, y_op) else: self.op_knn_.fit(X_op, y_op) def _get_similar_out_profiles(self, probabilities): if self.n_classes_ == 2: query_op = probabilities[:, :, 0] else: query_op = probabilities.reshape((probabilities.shape[0], self.n_classifiers_ * self.n_classes_)) dists, idx = self.op_knn_.kneighbors(query_op, n_neighbors=self.k_, return_distance=True) return dists, np.atleast_2d(idx) def estimate_competence_from_proba(self, query, probabilities, neighbors=None, distances=None): _, idx_neighbors = self._get_similar_out_profiles(probabilities) competences = np.sum(self.DSEL_processed_[idx_neighbors, :], axis=1, dtype=np.float) return competences def select(self, competences): if competences.ndim < 2: competences = competences.reshape(1, -1) selected_classifiers = (competences > 0) selected_classifiers[~np.any(selected_classifiers, axis=1), :] = True return selected_classifiers
true
true
1c2c2adca765359b609e0eae49e49254f7d6d57d
4,258
py
Python
.history/src/Simulador_20200707150756.py
eduardodut/Trabalho_final_estatistica_cd
fbedbbea6bdd7a79e1d62030cde0fab4e93fc338
[ "MIT" ]
null
null
null
.history/src/Simulador_20200707150756.py
eduardodut/Trabalho_final_estatistica_cd
fbedbbea6bdd7a79e1d62030cde0fab4e93fc338
[ "MIT" ]
null
null
null
.history/src/Simulador_20200707150756.py
eduardodut/Trabalho_final_estatistica_cd
fbedbbea6bdd7a79e1d62030cde0fab4e93fc338
[ "MIT" ]
null
null
null
import pandas as pd import numpy as np from Matriz_esferica import Matriz_esferica from Individuo import Individuo import random class Simulador(): def __init__( self, tamanho_matriz, #numero de linhas e colunas da matriz esférica densidade_populacional_inicial, #percentual de ocupação inicial da matriz percentual_inicial_tipo1, #percentual inicial da população que será infectada tipo 1 percentual_inicial_tipo2, #percentual inicial da população que será infectada tipo 2 chance_infeccao, #chance que um infectado tipo 2 tem de infectar um indivíduo saudável chance_infeccao_tipo2, #chance de um indivíduo infectado se tornar contagioso chance_morte, #chance de um indivíduo tipo 2 morrer ao fim de uma atualização atualizacoes_cura): #número de atualizações necessárias para a cura de um indivíduo tipo 1 ou 2 self.num_atualizacoes = 0 self.indices_infectados_tipo_2 = [] self.indices_infectados_tipo_1 = [] self.matriz_individuos = [] self.fabrica_individuo = Fabrica_individuo( chance_infeccao, chance_infeccao_tipo2, chance_morte, atualizacoes_cura) #objeto que é responsável por validar a movimentação no grid n x n self.matriz_esferica = Matriz_esferica(tamanho_matriz) self.populacao_inicial = densidade_populacional_inicial * tamanho_matriz**2 self.num_inicial_tipo2 = self.populacao_inicial * percentual_inicial_tipo2 self.num_inicial_tipo1 = self.populacao_inicial * percentual_inicial_tipo1 self.num_inicial_sadios = self.populacao_inicial - (self.num_inicial_tipo2 + self.num_inicial_tipo1) dict = { 'num_sadios':self.num_inicial_sadios, 'num_infect_t1':self.num_inicial_tipo1, 'num_infect_t2':self.num_inicial_tipo2, 'num_curados':0, 'num_mortos':0} #dataframe que guardará os resultados de cada atualização self.dataframe = pd.DataFrame(dict, index = [0]) class Fabrica_individuo(): def __init__( self, chance_infeccao, #chance que um infectado tipo 2 tem de infectar um indivíduo saudável chance_infeccao_tipo2, #chance de um indivíduo infectado se tornar contagioso chance_morte, #chance de um indivíduo tipo 2 morrer ao fim de uma atualização atualizacoes_cura): #número de atualizações necessárias para a cura de um indivíduo tipo 1 ou 2 self.chance_infeccao = chance_infeccao self.chance_infeccao_tipo2 = chance_infeccao_tipo2 self.chance_morte = chance_morte self.atualizacoes_cura = atualizacoes_cura def criar_individuo(self, status_inicial): return Individuo( status_inicial, self.chance_infeccao, self.chance_infeccao_tipo2, self.chance_morte, self.atualizacoes_cura) chance_infeccao = 0.3 chance_infeccao_tipo2 = 0.2 chance_morte = 0.2 atualizacoes_cura = 10 percentual_inicial_tipo1 = 0.05 percentual_inicial_tipo2 = 0.01 sim = Simulador( 1000, 1, percentual_inicial_tipo1, percentual_inicial_tipo2, chance_infeccao, chance_infeccao_tipo2, chance_morte,atualizacoes_cura) ind = sim.fabrica_individuo.criar_individuo(Individuo.MORTO) dict = {'num_sadios':1, 'num_infect_t1':2, 'num_infect_t2':3, 'num_curados':4, 'num_mortos':5} #sim.dataframe = sim.dataframe.append(dict) print(sim.dataframe) #print(sim.num_inicial_tipo2) list1 = list(range(10)) list2 = random.shuffle(list1) print(list1) print(list2)
32.257576
115
0.61038
import pandas as pd import numpy as np from Matriz_esferica import Matriz_esferica from Individuo import Individuo import random class Simulador(): def __init__( self, tamanho_matriz, densidade_populacional_inicial, percentual_inicial_tipo1, percentual_inicial_tipo2, chance_infeccao, chance_infeccao_tipo2, chance_morte, atualizacoes_cura): self.num_atualizacoes = 0 self.indices_infectados_tipo_2 = [] self.indices_infectados_tipo_1 = [] self.matriz_individuos = [] self.fabrica_individuo = Fabrica_individuo( chance_infeccao, chance_infeccao_tipo2, chance_morte, atualizacoes_cura) self.matriz_esferica = Matriz_esferica(tamanho_matriz) self.populacao_inicial = densidade_populacional_inicial * tamanho_matriz**2 self.num_inicial_tipo2 = self.populacao_inicial * percentual_inicial_tipo2 self.num_inicial_tipo1 = self.populacao_inicial * percentual_inicial_tipo1 self.num_inicial_sadios = self.populacao_inicial - (self.num_inicial_tipo2 + self.num_inicial_tipo1) dict = { 'num_sadios':self.num_inicial_sadios, 'num_infect_t1':self.num_inicial_tipo1, 'num_infect_t2':self.num_inicial_tipo2, 'num_curados':0, 'num_mortos':0} self.dataframe = pd.DataFrame(dict, index = [0]) class Fabrica_individuo(): def __init__( self, chance_infeccao, chance_infeccao_tipo2, chance_morte, atualizacoes_cura): self.chance_infeccao = chance_infeccao self.chance_infeccao_tipo2 = chance_infeccao_tipo2 self.chance_morte = chance_morte self.atualizacoes_cura = atualizacoes_cura def criar_individuo(self, status_inicial): return Individuo( status_inicial, self.chance_infeccao, self.chance_infeccao_tipo2, self.chance_morte, self.atualizacoes_cura) chance_infeccao = 0.3 chance_infeccao_tipo2 = 0.2 chance_morte = 0.2 atualizacoes_cura = 10 percentual_inicial_tipo1 = 0.05 percentual_inicial_tipo2 = 0.01 sim = Simulador( 1000, 1, percentual_inicial_tipo1, percentual_inicial_tipo2, chance_infeccao, chance_infeccao_tipo2, chance_morte,atualizacoes_cura) ind = sim.fabrica_individuo.criar_individuo(Individuo.MORTO) dict = {'num_sadios':1, 'num_infect_t1':2, 'num_infect_t2':3, 'num_curados':4, 'num_mortos':5} print(sim.dataframe) list1 = list(range(10)) list2 = random.shuffle(list1) print(list1) print(list2)
true
true
1c2c2b2f401390f97d3f410f2ad9b8f7c67bcfea
1,007
py
Python
convert_codes.py
rhoposit/sentencepiece
ae818bca6ecd73c2dde63ee5b84950352a136a2e
[ "Apache-2.0" ]
null
null
null
convert_codes.py
rhoposit/sentencepiece
ae818bca6ecd73c2dde63ee5b84950352a136a2e
[ "Apache-2.0" ]
null
null
null
convert_codes.py
rhoposit/sentencepiece
ae818bca6ecd73c2dde63ee5b84950352a136a2e
[ "Apache-2.0" ]
null
null
null
import sys from collections import defaultdict infile = sys.argv[1] outfile = sys.argv[2] refile = "topokanji/lists/wikipedia.txt" input = open(infile, "r") data = input.read().split("\n")[:-1] input.close() input = open(refile, "r") kanji = input.read().split("\n")[:-1] input.close() mapping = defaultdict(str) for line in data: codes = line.split(".") if codes != ['']: # print(codes) for c in codes: key = int(c) value = kanji[key] mapping[key] = value # katakana = 48 # hiragana = 46 # latin = 27 # kanji = 8000 L = [] output = open(outfile, "w") for line in data: codes = line.split(".") L.append(len(codes)) if codes != ['']: new_codes = [] for c in codes: key = int(c) nc = mapping[key] new_codes.append(nc) outstring = "".join(new_codes)+"\n" output.write(outstring) output.close() avg_len = sum(L) / float(len(L)) print("codes avg len:", avg_len)
19.365385
43
0.559086
import sys from collections import defaultdict infile = sys.argv[1] outfile = sys.argv[2] refile = "topokanji/lists/wikipedia.txt" input = open(infile, "r") data = input.read().split("\n")[:-1] input.close() input = open(refile, "r") kanji = input.read().split("\n")[:-1] input.close() mapping = defaultdict(str) for line in data: codes = line.split(".") if codes != ['']: for c in codes: key = int(c) value = kanji[key] mapping[key] = value L = [] output = open(outfile, "w") for line in data: codes = line.split(".") L.append(len(codes)) if codes != ['']: new_codes = [] for c in codes: key = int(c) nc = mapping[key] new_codes.append(nc) outstring = "".join(new_codes)+"\n" output.write(outstring) output.close() avg_len = sum(L) / float(len(L)) print("codes avg len:", avg_len)
true
true
1c2c2c09db0e78f1effee834c48a644cedbb7993
2,802
py
Python
src/hard/continuous_median.py
JadielTeofilo/General-Algorithms
dfcf86c6ecd727573079f8971187c47bdb7a37bb
[ "MIT" ]
null
null
null
src/hard/continuous_median.py
JadielTeofilo/General-Algorithms
dfcf86c6ecd727573079f8971187c47bdb7a37bb
[ "MIT" ]
null
null
null
src/hard/continuous_median.py
JadielTeofilo/General-Algorithms
dfcf86c6ecd727573079f8971187c47bdb7a37bb
[ "MIT" ]
null
null
null
""" Continuous Median: Numbers are randomly generated and passed to a method. Write a program to find and maintain the median value as new values are generated. median is the 50th percentil 3 7 2 9 2 1 sort and get the element in the middle either keep a sorted list and insert sorted (O(n)) Another approach is to use two heaps, a min and max heap, insertions are roughtly log(n) max [2] min [7] decide where to insert (the one with the smallest amount) check if it would violate the two heaps inserts rebalances if needed to get the median just take one from the largest heap or pick from one of them In number: int Out None """ import collections import heapq from typing import List Value = collections.namedtuple('Value', 'indexing val') class MedianHandler: def __init__(self) -> None: self.min_heap: List[Value] = [] self.max_heap: List[Value] = [] def insert(self, number: int) -> None: target_heap: str = self.find_heap_to_insert(number) indexing: int = (-number if target_heap == 'max_heap' else number) heapq.heappush(getattr(self, target_heap), Value(indexing, number)) if self.needs_rebalancing(): self.rebalance() def find_heap_to_insert(self, number: int) -> str: """ Finds which heap should be inserted in The first condition is the size, choosing the smaller. The second condition is if it keeps the property all_elements(max_heap) < all_elements(min_heap) """ if len(self.min_heap) < len(self.max_heap): top_from_max: Value = self.max_heap[0] if number <= top_from_max.val: return 'max_heap' return 'min_heap' else: if not self.min_heap: return 'max_heap' bot_from_min: Value = self.min_heap[0] if number >= bot_from_min.val: return 'min_heap' return 'max_heap' def needs_rebalancing(self) -> bool: return abs(len(self.min_heap) - len(self.max_heap)) > 1 def rebalance(self) -> None: if len(self.min_heap) < len(self.max_heap): target: List[Value] = self.min_heap origin: List[Value] = self.max_heap else: target: List[Value] = self.max_heap origin: List[Value] = self.min_heap value: Value = heapq.heappop(origin) # Flips the indexing to cope with the max_heap inversion new_value: Value = Value(value.indexing*-1, value.val) heapq.heappush(target, new_value) def get_median(self) -> int: target_heap: List[Value] = self.find_heap_with_median() return target_heap[0].val def find_heap_with_median(self) -> List[Value]: if len(self.min_heap) > len(self.max_heap): return self.min_heap elif len(self.max_heap) > len(self.min_heap): return self.max_heap if self.max_heap or self.min_heap: return self.max_heap or self.min_heap raise ValueError('Empty median') asdf = MedianHandler() import pdb;pdb.set_trace()
26.433962
89
0.717345
import collections import heapq from typing import List Value = collections.namedtuple('Value', 'indexing val') class MedianHandler: def __init__(self) -> None: self.min_heap: List[Value] = [] self.max_heap: List[Value] = [] def insert(self, number: int) -> None: target_heap: str = self.find_heap_to_insert(number) indexing: int = (-number if target_heap == 'max_heap' else number) heapq.heappush(getattr(self, target_heap), Value(indexing, number)) if self.needs_rebalancing(): self.rebalance() def find_heap_to_insert(self, number: int) -> str: if len(self.min_heap) < len(self.max_heap): top_from_max: Value = self.max_heap[0] if number <= top_from_max.val: return 'max_heap' return 'min_heap' else: if not self.min_heap: return 'max_heap' bot_from_min: Value = self.min_heap[0] if number >= bot_from_min.val: return 'min_heap' return 'max_heap' def needs_rebalancing(self) -> bool: return abs(len(self.min_heap) - len(self.max_heap)) > 1 def rebalance(self) -> None: if len(self.min_heap) < len(self.max_heap): target: List[Value] = self.min_heap origin: List[Value] = self.max_heap else: target: List[Value] = self.max_heap origin: List[Value] = self.min_heap value: Value = heapq.heappop(origin) new_value: Value = Value(value.indexing*-1, value.val) heapq.heappush(target, new_value) def get_median(self) -> int: target_heap: List[Value] = self.find_heap_with_median() return target_heap[0].val def find_heap_with_median(self) -> List[Value]: if len(self.min_heap) > len(self.max_heap): return self.min_heap elif len(self.max_heap) > len(self.min_heap): return self.max_heap if self.max_heap or self.min_heap: return self.max_heap or self.min_heap raise ValueError('Empty median') asdf = MedianHandler() import pdb;pdb.set_trace()
true
true
1c2c2ce9673a9c978a1ab6e29b493c8185ce9a69
2,228
py
Python
tests/algorithms/graph/dijkstras_test.py
TylerYep/workshop
69b19afc81c1b84b7f60723077670fb789b55744
[ "MIT" ]
1
2021-06-14T01:20:09.000Z
2021-06-14T01:20:09.000Z
tests/algorithms/graph/dijkstras_test.py
TylerYep/workshop
69b19afc81c1b84b7f60723077670fb789b55744
[ "MIT" ]
null
null
null
tests/algorithms/graph/dijkstras_test.py
TylerYep/workshop
69b19afc81c1b84b7f60723077670fb789b55744
[ "MIT" ]
null
null
null
from typing import Any import pytest from cs.algorithms import dijkstra_search, dijkstra_shortest_paths from cs.structures import Graph from tests.algorithms.graph.problems.apsp import AllPairsShortestPaths, APSPFunction @pytest.mark.add_function("shortest_paths_fn") class TestDijkstras(AllPairsShortestPaths): shortest_paths_fn = AllPairsShortestPaths.single_source_to_all_pairs( dijkstra_shortest_paths ) @staticmethod def test_no_search_path() -> None: graph = Graph[str]({"a": {}, "b": {}, "c": {}}) assert dijkstra_search(graph, "a", "b") == Graph.INFINITY @staticmethod def test_dijkstra_search() -> None: G = Graph[str]( { "A": {"B": 2, "C": 5}, "B": {"A": 2, "D": 3, "E": 1, "F": 1}, "C": {"A": 5, "F": 3}, "D": {"B": 3}, "E": {"B": 4, "F": 3}, "F": {"C": 3, "E": 3}, } ) G2 = Graph[int]({2: {3: 1}, 3: {4: 1}, 4: {6: 1}, 5: {2: 1, 6: 3}, 6: {}}) G3 = Graph[str]( { "B": {"C": 1}, "C": {"D": 1}, "D": {"F": 1}, "E": {"B": 1, "G": 2}, "F": {}, "G": {"F": 1}, } ) assert dijkstra_search(G, "E", "C") == 6 assert dijkstra_search(G2, 5, 6) == 3 assert dijkstra_search(G3, "E", "F") == 3 @staticmethod def test_adj_list_neg_weights(shortest_paths_fn: APSPFunction[Any]) -> None: graph = Graph[str]( { "a": {"b": -1, "c": 4}, "b": {"c": 3, "d": 2, "e": 2}, "c": {}, "d": {"b": 1, "c": 5}, "e": {"d": -3}, } ) with pytest.raises(RuntimeError): _ = shortest_paths_fn(graph) graph = Graph[str]( { "S": {"A": 6}, "A": {"B": 3}, "B": {"C": 4, "E": 5}, "C": {"A": -3, "D": 3}, "D": {}, "E": {}, } ) with pytest.raises(RuntimeError): _ = shortest_paths_fn(graph)
28.202532
84
0.406643
from typing import Any import pytest from cs.algorithms import dijkstra_search, dijkstra_shortest_paths from cs.structures import Graph from tests.algorithms.graph.problems.apsp import AllPairsShortestPaths, APSPFunction @pytest.mark.add_function("shortest_paths_fn") class TestDijkstras(AllPairsShortestPaths): shortest_paths_fn = AllPairsShortestPaths.single_source_to_all_pairs( dijkstra_shortest_paths ) @staticmethod def test_no_search_path() -> None: graph = Graph[str]({"a": {}, "b": {}, "c": {}}) assert dijkstra_search(graph, "a", "b") == Graph.INFINITY @staticmethod def test_dijkstra_search() -> None: G = Graph[str]( { "A": {"B": 2, "C": 5}, "B": {"A": 2, "D": 3, "E": 1, "F": 1}, "C": {"A": 5, "F": 3}, "D": {"B": 3}, "E": {"B": 4, "F": 3}, "F": {"C": 3, "E": 3}, } ) G2 = Graph[int]({2: {3: 1}, 3: {4: 1}, 4: {6: 1}, 5: {2: 1, 6: 3}, 6: {}}) G3 = Graph[str]( { "B": {"C": 1}, "C": {"D": 1}, "D": {"F": 1}, "E": {"B": 1, "G": 2}, "F": {}, "G": {"F": 1}, } ) assert dijkstra_search(G, "E", "C") == 6 assert dijkstra_search(G2, 5, 6) == 3 assert dijkstra_search(G3, "E", "F") == 3 @staticmethod def test_adj_list_neg_weights(shortest_paths_fn: APSPFunction[Any]) -> None: graph = Graph[str]( { "a": {"b": -1, "c": 4}, "b": {"c": 3, "d": 2, "e": 2}, "c": {}, "d": {"b": 1, "c": 5}, "e": {"d": -3}, } ) with pytest.raises(RuntimeError): _ = shortest_paths_fn(graph) graph = Graph[str]( { "S": {"A": 6}, "A": {"B": 3}, "B": {"C": 4, "E": 5}, "C": {"A": -3, "D": 3}, "D": {}, "E": {}, } ) with pytest.raises(RuntimeError): _ = shortest_paths_fn(graph)
true
true
1c2c2d60ce873022688a95ab211893f36a8cabdf
1,657
py
Python
test/test_db_matches_ui.py
Elen-T/python_training
69383759e4229441657bd57af28a7a38b04d026d
[ "Apache-2.0" ]
null
null
null
test/test_db_matches_ui.py
Elen-T/python_training
69383759e4229441657bd57af28a7a38b04d026d
[ "Apache-2.0" ]
null
null
null
test/test_db_matches_ui.py
Elen-T/python_training
69383759e4229441657bd57af28a7a38b04d026d
[ "Apache-2.0" ]
null
null
null
# тест для проверки соответствия списка групп выгруженного из БД и из приложения from model.group import Group from timeit import timeit # для измерения времени def test_group_list(app, db): # передаем два параметра app - для получения доступа к приложению, db - фикстура для получения доступа к бд print(timeit(lambda: app.group.get_group_list(), number=1)) # измеряем время выполнения lambda(функции загрузки чз приложение), вызов 1 раз number=1 def clean(group): # удляем лишние пробелы в начале и конце, после применения этой ф-ии объекты в обоих случаях д выглядеть одинаково return Group(id=group.id, name=group.name.strip()) print(timeit(lambda: map(clean, db.get_group_list()), number=1000)) # список загруженный через бд, применяем к списку функцию clean #assert False #False - чтобы тест упал и получитьвывод на консоль # sorted(ui_list, key=Group.id_or_max) == sorted(db_list,key=Group.id_or_max) # проверка отсортированных списков """def test_group_list(app, db): # передаем два параметра app - для получения доступа к приложению, db - фикстура для получения доступа к бд ui_list = app.group.get_group_list() # сравниваем результаты, список загруженный через приложение def clean(group): # удляем лишние пробелы в начале и конце, после применения этой ф-ии объекты в обоих случаях д выглядеть одинаково return Group(id=group.id, name=group.name.strip()) db_list = map(clean, db.get_group_list()) # список загруженный через бд, применяем к списку функцию clean assert sorted(ui_list, key=Group.id_or_max) == sorted(db_list,key=Group.id_or_max) # проверка отсортированных списков"""
78.904762
183
0.76041
from model.group import Group from timeit import timeit def test_group_list(app, db): print(timeit(lambda: app.group.get_group_list(), number=1)) def clean(group): return Group(id=group.id, name=group.name.strip()) print(timeit(lambda: map(clean, db.get_group_list()), number=1000))
true
true
1c2c2e831b629332f9d2f535a5e165b805911787
436
py
Python
babyrev/test.py
FantasqueX/2020p
fd6df5ad8bced932398c94dd8a0b4669f5db8d4c
[ "MIT" ]
22
2020-12-20T08:01:00.000Z
2021-09-13T04:53:34.000Z
babyrev/test.py
FantasqueX/2020p
fd6df5ad8bced932398c94dd8a0b4669f5db8d4c
[ "MIT" ]
2
2020-12-20T11:39:17.000Z
2021-07-05T17:33:52.000Z
babyrev/test.py
FantasqueX/2020p
fd6df5ad8bced932398c94dd8a0b4669f5db8d4c
[ "MIT" ]
4
2020-12-20T13:22:29.000Z
2021-09-13T04:54:16.000Z
import requests def check(HOST="172.17.0.2"): def pre(): if b"we{" in (requests.get(f"http://{HOST}/").content): print("Flag appear directly") else: print("OK") def get_flag(): if b"we{" not in (requests.get(f"http://{HOST}/", headers={ "User-Agent": "Flag Viewer 2.0" }).content): print("Cannot get flag") else: print("OK")
24.222222
67
0.486239
import requests def check(HOST="172.17.0.2"): def pre(): if b"we{" in (requests.get(f"http://{HOST}/").content): print("Flag appear directly") else: print("OK") def get_flag(): if b"we{" not in (requests.get(f"http://{HOST}/", headers={ "User-Agent": "Flag Viewer 2.0" }).content): print("Cannot get flag") else: print("OK")
true
true
1c2c31397ee9e10bde8f40a3b4a3bde328a8df0c
162
py
Python
reid/scripts/triplet_reid/__init__.py
VisualComputingInstitute/CROWDBOT_perception
df98f3f658c39fb3fa4ac0456f1214f7918009f6
[ "MIT" ]
1
2022-03-07T06:24:27.000Z
2022-03-07T06:24:27.000Z
reid/scripts/triplet_reid/__init__.py
VisualComputingInstitute/CROWDBOT_perception
df98f3f658c39fb3fa4ac0456f1214f7918009f6
[ "MIT" ]
null
null
null
reid/scripts/triplet_reid/__init__.py
VisualComputingInstitute/CROWDBOT_perception
df98f3f658c39fb3fa4ac0456f1214f7918009f6
[ "MIT" ]
null
null
null
from importlib import import_module def build_cfg_fn(name): module = import_module('schedulers.scheduler') return getattr(module, '{}_cfg'.format(name))
27
50
0.753086
from importlib import import_module def build_cfg_fn(name): module = import_module('schedulers.scheduler') return getattr(module, '{}_cfg'.format(name))
true
true
1c2c31e005ccedfb263e13c84488b2699bfca794
9,698
py
Python
jax/experimental/ode.py
yurodiviy/jax
fbf10c697004327e13037e009612b756864d47e5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
jax/experimental/ode.py
yurodiviy/jax
fbf10c697004327e13037e009612b756864d47e5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
jax/experimental/ode.py
yurodiviy/jax
fbf10c697004327e13037e009612b756864d47e5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """JAX-based Dormand-Prince ODE integration with adaptive stepsize. Integrate systems of ordinary differential equations (ODEs) using the JAX autograd/diff library and the Dormand-Prince method for adaptive integration stepsize calculation. Provides improved integration accuracy over fixed stepsize integration methods. Adjoint algorithm based on Appendix C of https://arxiv.org/pdf/1806.07366.pdf """ from functools import partial import operator as op import jax import jax.numpy as jnp from jax import core from jax import lax from jax import ops from jax.util import safe_map, safe_zip from jax.flatten_util import ravel_pytree from jax.tree_util import tree_map from jax import linear_util as lu map = safe_map zip = safe_zip def ravel_first_arg(f, unravel): return ravel_first_arg_(lu.wrap_init(f), unravel).call_wrapped @lu.transformation def ravel_first_arg_(unravel, y_flat, *args): y = unravel(y_flat) ans = yield (y,) + args, {} ans_flat, _ = ravel_pytree(ans) yield ans_flat def interp_fit_dopri(y0, y1, k, dt): # Fit a polynomial to the results of a Runge-Kutta step. dps_c_mid = jnp.array([ 6025192743 / 30085553152 / 2, 0, 51252292925 / 65400821598 / 2, -2691868925 / 45128329728 / 2, 187940372067 / 1594534317056 / 2, -1776094331 / 19743644256 / 2, 11237099 / 235043384 / 2]) y_mid = y0 + dt * jnp.dot(dps_c_mid, k) return jnp.array(fit_4th_order_polynomial(y0, y1, y_mid, k[0], k[-1], dt)) def fit_4th_order_polynomial(y0, y1, y_mid, dy0, dy1, dt): a = -2.*dt*dy0 + 2.*dt*dy1 - 8.*y0 - 8.*y1 + 16.*y_mid b = 5.*dt*dy0 - 3.*dt*dy1 + 18.*y0 + 14.*y1 - 32.*y_mid c = -4.*dt*dy0 + dt*dy1 - 11.*y0 - 5.*y1 + 16.*y_mid d = dt * dy0 e = y0 return a, b, c, d, e def initial_step_size(fun, t0, y0, order, rtol, atol, f0): # Algorithm from: # E. Hairer, S. P. Norsett G. Wanner, # Solving Ordinary Differential Equations I: Nonstiff Problems, Sec. II.4. scale = atol + jnp.abs(y0) * rtol d0 = jnp.linalg.norm(y0 / scale) d1 = jnp.linalg.norm(f0 / scale) h0 = jnp.where((d0 < 1e-5) | (d1 < 1e-5), 1e-6, 0.01 * d0 / d1) y1 = y0 + h0 * f0 f1 = fun(y1, t0 + h0) d2 = jnp.linalg.norm((f1 - f0) / scale) / h0 h1 = jnp.where((d1 <= 1e-15) & (d2 <= 1e-15), jnp.maximum(1e-6, h0 * 1e-3), (0.01 / jnp.max(d1 + d2)) ** (1. / (order + 1.))) return jnp.minimum(100. * h0, h1) def runge_kutta_step(func, y0, f0, t0, dt): # Dopri5 Butcher tableaux alpha = jnp.array([1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1., 0]) beta = jnp.array([ [1 / 5, 0, 0, 0, 0, 0, 0], [3 / 40, 9 / 40, 0, 0, 0, 0, 0], [44 / 45, -56 / 15, 32 / 9, 0, 0, 0, 0], [19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729, 0, 0, 0], [9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176, -5103 / 18656, 0, 0], [35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0] ]) c_sol = jnp.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0]) c_error = jnp.array([35 / 384 - 1951 / 21600, 0, 500 / 1113 - 22642 / 50085, 125 / 192 - 451 / 720, -2187 / 6784 - -12231 / 42400, 11 / 84 - 649 / 6300, -1. / 60.]) def body_fun(i, k): ti = t0 + dt * alpha[i-1] yi = y0 + dt * jnp.dot(beta[i-1, :], k) ft = func(yi, ti) return ops.index_update(k, jax.ops.index[i, :], ft) k = ops.index_update(jnp.zeros((7, f0.shape[0])), ops.index[0, :], f0) k = lax.fori_loop(1, 7, body_fun, k) y1 = dt * jnp.dot(c_sol, k) + y0 y1_error = dt * jnp.dot(c_error, k) f1 = k[-1] return y1, f1, y1_error, k def error_ratio(error_estimate, rtol, atol, y0, y1): err_tol = atol + rtol * jnp.maximum(jnp.abs(y0), jnp.abs(y1)) err_ratio = error_estimate / err_tol return jnp.mean(err_ratio ** 2) def optimal_step_size(last_step, mean_error_ratio, safety=0.9, ifactor=10.0, dfactor=0.2, order=5.0): """Compute optimal Runge-Kutta stepsize.""" mean_error_ratio = jnp.max(mean_error_ratio) dfactor = jnp.where(mean_error_ratio < 1, 1.0, dfactor) err_ratio = jnp.sqrt(mean_error_ratio) factor = jnp.maximum(1.0 / ifactor, jnp.minimum(err_ratio**(1.0 / order) / safety, 1.0 / dfactor)) return jnp.where(mean_error_ratio == 0, last_step * ifactor, last_step / factor) def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf): """Adaptive stepsize (Dormand-Prince) Runge-Kutta odeint implementation. Args: func: function to evaluate the time derivative of the solution `y` at time `t` as `func(y, t, *args)`, producing the same shape/structure as `y0`. y0: array or pytree of arrays representing the initial value for the state. t: array of float times for evaluation, like `jnp.linspace(0., 10., 101)`, in which the values must be strictly increasing. *args: tuple of additional arguments for `func`, which must be arrays scalars, or (nested) standard Python containers (tuples, lists, dicts, namedtuples, i.e. pytrees) of those types. rtol: float, relative local error tolerance for solver (optional). atol: float, absolute local error tolerance for solver (optional). mxstep: int, maximum number of steps to take for each timepoint (optional). Returns: Values of the solution `y` (i.e. integrated system values) at each time point in `t`, represented as an array (or pytree of arrays) with the same shape/structure as `y0` except with a new leading axis of length `len(t)`. """ def _check_arg(arg): if not isinstance(arg, core.Tracer) and not core.valid_jaxtype(arg): msg = ("The contents of odeint *args must be arrays or scalars, but got " "\n{}.") raise TypeError(msg.format(arg)) tree_map(_check_arg, args) return _odeint_wrapper(func, rtol, atol, mxstep, y0, t, *args) @partial(jax.jit, static_argnums=(0, 1, 2, 3)) def _odeint_wrapper(func, rtol, atol, mxstep, y0, ts, *args): y0, unravel = ravel_pytree(y0) func = ravel_first_arg(func, unravel) out = _odeint(func, rtol, atol, mxstep, y0, ts, *args) return jax.vmap(unravel)(out) @partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2, 3)) def _odeint(func, rtol, atol, mxstep, y0, ts, *args): func_ = lambda y, t: func(y, t, *args) def scan_fun(carry, target_t): def cond_fun(state): i, _, _, t, dt, _, _ = state return (t < target_t) & (i < mxstep) & (dt > 0) def body_fun(state): i, y, f, t, dt, last_t, interp_coeff = state next_y, next_f, next_y_error, k = runge_kutta_step(func_, y, f, t, dt) next_t = t + dt error_ratios = error_ratio(next_y_error, rtol, atol, y, next_y) new_interp_coeff = interp_fit_dopri(y, next_y, k, dt) dt = optimal_step_size(dt, error_ratios) new = [i + 1, next_y, next_f, next_t, dt, t, new_interp_coeff] old = [i + 1, y, f, t, dt, last_t, interp_coeff] return map(partial(jnp.where, jnp.all(error_ratios <= 1.)), new, old) _, *carry = lax.while_loop(cond_fun, body_fun, [0] + carry) _, _, t, _, last_t, interp_coeff = carry relative_output_time = (target_t - last_t) / (t - last_t) y_target = jnp.polyval(interp_coeff, relative_output_time) return carry, y_target f0 = func_(y0, ts[0]) dt = initial_step_size(func_, ts[0], y0, 4, rtol, atol, f0) interp_coeff = jnp.array([y0] * 5) init_carry = [y0, f0, ts[0], dt, ts[0], interp_coeff] _, ys = lax.scan(scan_fun, init_carry, ts[1:]) return jnp.concatenate((y0[None], ys)) def _odeint_fwd(func, rtol, atol, mxstep, y0, ts, *args): ys = _odeint(func, rtol, atol, mxstep, y0, ts, *args) return ys, (ys, ts, args) def _odeint_rev(func, rtol, atol, mxstep, res, g): ys, ts, args = res def aug_dynamics(augmented_state, t, *args): """Original system augmented with vjp_y, vjp_t and vjp_args.""" y, y_bar, *_ = augmented_state # `t` here is negatice time, so we need to negate again to get back to # normal time. See the `odeint` invocation in `scan_fun` below. y_dot, vjpfun = jax.vjp(func, y, -t, *args) return (-y_dot, *vjpfun(y_bar)) y_bar = g[-1] ts_bar = [] t0_bar = 0. def scan_fun(carry, i): y_bar, t0_bar, args_bar = carry # Compute effect of moving measurement time t_bar = jnp.dot(func(ys[i], ts[i], *args), g[i]) t0_bar = t0_bar - t_bar # Run augmented system backwards to previous observation _, y_bar, t0_bar, args_bar = odeint( aug_dynamics, (ys[i], y_bar, t0_bar, args_bar), jnp.array([-ts[i], -ts[i - 1]]), *args, rtol=rtol, atol=atol, mxstep=mxstep) y_bar, t0_bar, args_bar = tree_map(op.itemgetter(1), (y_bar, t0_bar, args_bar)) # Add gradient from current output y_bar = y_bar + g[i - 1] return (y_bar, t0_bar, args_bar), t_bar init_carry = (g[-1], 0., tree_map(jnp.zeros_like, args)) (y_bar, t0_bar, args_bar), rev_ts_bar = lax.scan( scan_fun, init_carry, jnp.arange(len(ts) - 1, 0, -1)) ts_bar = jnp.concatenate([jnp.array([t0_bar]), rev_ts_bar[::-1]]) return (y_bar, ts_bar, *args_bar) _odeint.defvjp(_odeint_fwd, _odeint_rev)
39.104839
84
0.646216
from functools import partial import operator as op import jax import jax.numpy as jnp from jax import core from jax import lax from jax import ops from jax.util import safe_map, safe_zip from jax.flatten_util import ravel_pytree from jax.tree_util import tree_map from jax import linear_util as lu map = safe_map zip = safe_zip def ravel_first_arg(f, unravel): return ravel_first_arg_(lu.wrap_init(f), unravel).call_wrapped @lu.transformation def ravel_first_arg_(unravel, y_flat, *args): y = unravel(y_flat) ans = yield (y,) + args, {} ans_flat, _ = ravel_pytree(ans) yield ans_flat def interp_fit_dopri(y0, y1, k, dt): dps_c_mid = jnp.array([ 6025192743 / 30085553152 / 2, 0, 51252292925 / 65400821598 / 2, -2691868925 / 45128329728 / 2, 187940372067 / 1594534317056 / 2, -1776094331 / 19743644256 / 2, 11237099 / 235043384 / 2]) y_mid = y0 + dt * jnp.dot(dps_c_mid, k) return jnp.array(fit_4th_order_polynomial(y0, y1, y_mid, k[0], k[-1], dt)) def fit_4th_order_polynomial(y0, y1, y_mid, dy0, dy1, dt): a = -2.*dt*dy0 + 2.*dt*dy1 - 8.*y0 - 8.*y1 + 16.*y_mid b = 5.*dt*dy0 - 3.*dt*dy1 + 18.*y0 + 14.*y1 - 32.*y_mid c = -4.*dt*dy0 + dt*dy1 - 11.*y0 - 5.*y1 + 16.*y_mid d = dt * dy0 e = y0 return a, b, c, d, e def initial_step_size(fun, t0, y0, order, rtol, atol, f0): scale = atol + jnp.abs(y0) * rtol d0 = jnp.linalg.norm(y0 / scale) d1 = jnp.linalg.norm(f0 / scale) h0 = jnp.where((d0 < 1e-5) | (d1 < 1e-5), 1e-6, 0.01 * d0 / d1) y1 = y0 + h0 * f0 f1 = fun(y1, t0 + h0) d2 = jnp.linalg.norm((f1 - f0) / scale) / h0 h1 = jnp.where((d1 <= 1e-15) & (d2 <= 1e-15), jnp.maximum(1e-6, h0 * 1e-3), (0.01 / jnp.max(d1 + d2)) ** (1. / (order + 1.))) return jnp.minimum(100. * h0, h1) def runge_kutta_step(func, y0, f0, t0, dt): alpha = jnp.array([1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1., 0]) beta = jnp.array([ [1 / 5, 0, 0, 0, 0, 0, 0], [3 / 40, 9 / 40, 0, 0, 0, 0, 0], [44 / 45, -56 / 15, 32 / 9, 0, 0, 0, 0], [19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729, 0, 0, 0], [9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176, -5103 / 18656, 0, 0], [35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0] ]) c_sol = jnp.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0]) c_error = jnp.array([35 / 384 - 1951 / 21600, 0, 500 / 1113 - 22642 / 50085, 125 / 192 - 451 / 720, -2187 / 6784 - -12231 / 42400, 11 / 84 - 649 / 6300, -1. / 60.]) def body_fun(i, k): ti = t0 + dt * alpha[i-1] yi = y0 + dt * jnp.dot(beta[i-1, :], k) ft = func(yi, ti) return ops.index_update(k, jax.ops.index[i, :], ft) k = ops.index_update(jnp.zeros((7, f0.shape[0])), ops.index[0, :], f0) k = lax.fori_loop(1, 7, body_fun, k) y1 = dt * jnp.dot(c_sol, k) + y0 y1_error = dt * jnp.dot(c_error, k) f1 = k[-1] return y1, f1, y1_error, k def error_ratio(error_estimate, rtol, atol, y0, y1): err_tol = atol + rtol * jnp.maximum(jnp.abs(y0), jnp.abs(y1)) err_ratio = error_estimate / err_tol return jnp.mean(err_ratio ** 2) def optimal_step_size(last_step, mean_error_ratio, safety=0.9, ifactor=10.0, dfactor=0.2, order=5.0): mean_error_ratio = jnp.max(mean_error_ratio) dfactor = jnp.where(mean_error_ratio < 1, 1.0, dfactor) err_ratio = jnp.sqrt(mean_error_ratio) factor = jnp.maximum(1.0 / ifactor, jnp.minimum(err_ratio**(1.0 / order) / safety, 1.0 / dfactor)) return jnp.where(mean_error_ratio == 0, last_step * ifactor, last_step / factor) def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf): def _check_arg(arg): if not isinstance(arg, core.Tracer) and not core.valid_jaxtype(arg): msg = ("The contents of odeint *args must be arrays or scalars, but got " "\n{}.") raise TypeError(msg.format(arg)) tree_map(_check_arg, args) return _odeint_wrapper(func, rtol, atol, mxstep, y0, t, *args) @partial(jax.jit, static_argnums=(0, 1, 2, 3)) def _odeint_wrapper(func, rtol, atol, mxstep, y0, ts, *args): y0, unravel = ravel_pytree(y0) func = ravel_first_arg(func, unravel) out = _odeint(func, rtol, atol, mxstep, y0, ts, *args) return jax.vmap(unravel)(out) @partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2, 3)) def _odeint(func, rtol, atol, mxstep, y0, ts, *args): func_ = lambda y, t: func(y, t, *args) def scan_fun(carry, target_t): def cond_fun(state): i, _, _, t, dt, _, _ = state return (t < target_t) & (i < mxstep) & (dt > 0) def body_fun(state): i, y, f, t, dt, last_t, interp_coeff = state next_y, next_f, next_y_error, k = runge_kutta_step(func_, y, f, t, dt) next_t = t + dt error_ratios = error_ratio(next_y_error, rtol, atol, y, next_y) new_interp_coeff = interp_fit_dopri(y, next_y, k, dt) dt = optimal_step_size(dt, error_ratios) new = [i + 1, next_y, next_f, next_t, dt, t, new_interp_coeff] old = [i + 1, y, f, t, dt, last_t, interp_coeff] return map(partial(jnp.where, jnp.all(error_ratios <= 1.)), new, old) _, *carry = lax.while_loop(cond_fun, body_fun, [0] + carry) _, _, t, _, last_t, interp_coeff = carry relative_output_time = (target_t - last_t) / (t - last_t) y_target = jnp.polyval(interp_coeff, relative_output_time) return carry, y_target f0 = func_(y0, ts[0]) dt = initial_step_size(func_, ts[0], y0, 4, rtol, atol, f0) interp_coeff = jnp.array([y0] * 5) init_carry = [y0, f0, ts[0], dt, ts[0], interp_coeff] _, ys = lax.scan(scan_fun, init_carry, ts[1:]) return jnp.concatenate((y0[None], ys)) def _odeint_fwd(func, rtol, atol, mxstep, y0, ts, *args): ys = _odeint(func, rtol, atol, mxstep, y0, ts, *args) return ys, (ys, ts, args) def _odeint_rev(func, rtol, atol, mxstep, res, g): ys, ts, args = res def aug_dynamics(augmented_state, t, *args): y, y_bar, *_ = augmented_state y_dot, vjpfun = jax.vjp(func, y, -t, *args) return (-y_dot, *vjpfun(y_bar)) y_bar = g[-1] ts_bar = [] t0_bar = 0. def scan_fun(carry, i): y_bar, t0_bar, args_bar = carry t_bar = jnp.dot(func(ys[i], ts[i], *args), g[i]) t0_bar = t0_bar - t_bar _, y_bar, t0_bar, args_bar = odeint( aug_dynamics, (ys[i], y_bar, t0_bar, args_bar), jnp.array([-ts[i], -ts[i - 1]]), *args, rtol=rtol, atol=atol, mxstep=mxstep) y_bar, t0_bar, args_bar = tree_map(op.itemgetter(1), (y_bar, t0_bar, args_bar)) y_bar = y_bar + g[i - 1] return (y_bar, t0_bar, args_bar), t_bar init_carry = (g[-1], 0., tree_map(jnp.zeros_like, args)) (y_bar, t0_bar, args_bar), rev_ts_bar = lax.scan( scan_fun, init_carry, jnp.arange(len(ts) - 1, 0, -1)) ts_bar = jnp.concatenate([jnp.array([t0_bar]), rev_ts_bar[::-1]]) return (y_bar, ts_bar, *args_bar) _odeint.defvjp(_odeint_fwd, _odeint_rev)
true
true
1c2c324d027847f578914ab7ae65bf477ce41dfc
57,707
py
Python
Tests/otlLib/builder_test.py
odidev/fonttools
27b5f568f562971d7fbf64eeb027ea61e4939db4
[ "Apache-2.0", "MIT" ]
null
null
null
Tests/otlLib/builder_test.py
odidev/fonttools
27b5f568f562971d7fbf64eeb027ea61e4939db4
[ "Apache-2.0", "MIT" ]
1
2015-11-30T17:47:38.000Z
2015-11-30T17:47:38.000Z
Tests/otlLib/builder_test.py
odidev/fonttools
27b5f568f562971d7fbf64eeb027ea61e4939db4
[ "Apache-2.0", "MIT" ]
null
null
null
import io import struct from fontTools.misc.fixedTools import floatToFixed from fontTools.misc.testTools import getXML from fontTools.otlLib import builder, error from fontTools import ttLib from fontTools.ttLib.tables import otTables import pytest class BuilderTest(object): GLYPHS = ( ".notdef space zero one two three four five six " "A B C a b c grave acute cedilla f_f_i f_i c_t" ).split() GLYPHMAP = {name: num for num, name in enumerate(GLYPHS)} ANCHOR1 = builder.buildAnchor(11, -11) ANCHOR2 = builder.buildAnchor(22, -22) ANCHOR3 = builder.buildAnchor(33, -33) def test_buildAnchor_format1(self): anchor = builder.buildAnchor(23, 42) assert getXML(anchor.toXML) == [ '<Anchor Format="1">', ' <XCoordinate value="23"/>', ' <YCoordinate value="42"/>', "</Anchor>", ] def test_buildAnchor_format2(self): anchor = builder.buildAnchor(23, 42, point=17) assert getXML(anchor.toXML) == [ '<Anchor Format="2">', ' <XCoordinate value="23"/>', ' <YCoordinate value="42"/>', ' <AnchorPoint value="17"/>', "</Anchor>", ] def test_buildAnchor_format3(self): anchor = builder.buildAnchor( 23, 42, deviceX=builder.buildDevice({1: 1, 0: 0}), deviceY=builder.buildDevice({7: 7}), ) assert getXML(anchor.toXML) == [ '<Anchor Format="3">', ' <XCoordinate value="23"/>', ' <YCoordinate value="42"/>', " <XDeviceTable>", ' <StartSize value="0"/>', ' <EndSize value="1"/>', ' <DeltaFormat value="1"/>', ' <DeltaValue value="[0, 1]"/>', " </XDeviceTable>", " <YDeviceTable>", ' <StartSize value="7"/>', ' <EndSize value="7"/>', ' <DeltaFormat value="2"/>', ' <DeltaValue value="[7]"/>', " </YDeviceTable>", "</Anchor>", ] def test_buildAttachList(self): attachList = builder.buildAttachList( {"zero": [23, 7], "one": [1]}, self.GLYPHMAP ) assert getXML(attachList.toXML) == [ "<AttachList>", " <Coverage>", ' <Glyph value="zero"/>', ' <Glyph value="one"/>', " </Coverage>", " <!-- GlyphCount=2 -->", ' <AttachPoint index="0">', " <!-- PointCount=2 -->", ' <PointIndex index="0" value="7"/>', ' <PointIndex index="1" value="23"/>', " </AttachPoint>", ' <AttachPoint index="1">', " <!-- PointCount=1 -->", ' <PointIndex index="0" value="1"/>', " </AttachPoint>", "</AttachList>", ] def test_buildAttachList_empty(self): assert builder.buildAttachList({}, self.GLYPHMAP) is None def test_buildAttachPoint(self): attachPoint = builder.buildAttachPoint([7, 3]) assert getXML(attachPoint.toXML) == [ "<AttachPoint>", " <!-- PointCount=2 -->", ' <PointIndex index="0" value="3"/>', ' <PointIndex index="1" value="7"/>', "</AttachPoint>", ] def test_buildAttachPoint_empty(self): assert builder.buildAttachPoint([]) is None def test_buildAttachPoint_duplicate(self): attachPoint = builder.buildAttachPoint([7, 3, 7]) assert getXML(attachPoint.toXML) == [ "<AttachPoint>", " <!-- PointCount=2 -->", ' <PointIndex index="0" value="3"/>', ' <PointIndex index="1" value="7"/>', "</AttachPoint>", ] def test_buildBaseArray(self): anchor = builder.buildAnchor baseArray = builder.buildBaseArray( {"a": {2: anchor(300, 80)}, "c": {1: anchor(300, 80), 2: anchor(300, -20)}}, numMarkClasses=4, glyphMap=self.GLYPHMAP, ) assert getXML(baseArray.toXML) == [ "<BaseArray>", " <!-- BaseCount=2 -->", ' <BaseRecord index="0">', ' <BaseAnchor index="0" empty="1"/>', ' <BaseAnchor index="1" empty="1"/>', ' <BaseAnchor index="2" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="80"/>', " </BaseAnchor>", ' <BaseAnchor index="3" empty="1"/>', " </BaseRecord>", ' <BaseRecord index="1">', ' <BaseAnchor index="0" empty="1"/>', ' <BaseAnchor index="1" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="80"/>', " </BaseAnchor>", ' <BaseAnchor index="2" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-20"/>', " </BaseAnchor>", ' <BaseAnchor index="3" empty="1"/>', " </BaseRecord>", "</BaseArray>", ] def test_buildBaseRecord(self): a = builder.buildAnchor rec = builder.buildBaseRecord([a(500, -20), None, a(300, -15)]) assert getXML(rec.toXML) == [ "<BaseRecord>", ' <BaseAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </BaseAnchor>", ' <BaseAnchor index="1" empty="1"/>', ' <BaseAnchor index="2" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-15"/>', " </BaseAnchor>", "</BaseRecord>", ] def test_buildCaretValueForCoord(self): caret = builder.buildCaretValueForCoord(500) assert getXML(caret.toXML) == [ '<CaretValue Format="1">', ' <Coordinate value="500"/>', "</CaretValue>", ] def test_buildCaretValueForPoint(self): caret = builder.buildCaretValueForPoint(23) assert getXML(caret.toXML) == [ '<CaretValue Format="2">', ' <CaretValuePoint value="23"/>', "</CaretValue>", ] def test_buildComponentRecord(self): a = builder.buildAnchor rec = builder.buildComponentRecord([a(500, -20), None, a(300, -15)]) assert getXML(rec.toXML) == [ "<ComponentRecord>", ' <LigatureAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </LigatureAnchor>", ' <LigatureAnchor index="1" empty="1"/>', ' <LigatureAnchor index="2" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-15"/>', " </LigatureAnchor>", "</ComponentRecord>", ] def test_buildComponentRecord_empty(self): assert builder.buildComponentRecord([]) is None def test_buildComponentRecord_None(self): assert builder.buildComponentRecord(None) is None def test_buildCoverage(self): cov = builder.buildCoverage({"two", "four"}, {"two": 2, "four": 4}) assert getXML(cov.toXML) == [ "<Coverage>", ' <Glyph value="two"/>', ' <Glyph value="four"/>', "</Coverage>", ] def test_buildCursivePos(self): pos = builder.buildCursivePosSubtable( {"two": (self.ANCHOR1, self.ANCHOR2), "four": (self.ANCHOR3, self.ANCHOR1)}, self.GLYPHMAP, ) assert getXML(pos.toXML) == [ '<CursivePos Format="1">', " <Coverage>", ' <Glyph value="two"/>', ' <Glyph value="four"/>', " </Coverage>", " <!-- EntryExitCount=2 -->", ' <EntryExitRecord index="0">', ' <EntryAnchor Format="1">', ' <XCoordinate value="11"/>', ' <YCoordinate value="-11"/>', " </EntryAnchor>", ' <ExitAnchor Format="1">', ' <XCoordinate value="22"/>', ' <YCoordinate value="-22"/>', " </ExitAnchor>", " </EntryExitRecord>", ' <EntryExitRecord index="1">', ' <EntryAnchor Format="1">', ' <XCoordinate value="33"/>', ' <YCoordinate value="-33"/>', " </EntryAnchor>", ' <ExitAnchor Format="1">', ' <XCoordinate value="11"/>', ' <YCoordinate value="-11"/>', " </ExitAnchor>", " </EntryExitRecord>", "</CursivePos>", ] def test_buildDevice_format1(self): device = builder.buildDevice({1: 1, 0: 0}) assert getXML(device.toXML) == [ "<Device>", ' <StartSize value="0"/>', ' <EndSize value="1"/>', ' <DeltaFormat value="1"/>', ' <DeltaValue value="[0, 1]"/>', "</Device>", ] def test_buildDevice_format2(self): device = builder.buildDevice({2: 2, 0: 1, 1: 0}) assert getXML(device.toXML) == [ "<Device>", ' <StartSize value="0"/>', ' <EndSize value="2"/>', ' <DeltaFormat value="2"/>', ' <DeltaValue value="[1, 0, 2]"/>', "</Device>", ] def test_buildDevice_format3(self): device = builder.buildDevice({5: 3, 1: 77}) assert getXML(device.toXML) == [ "<Device>", ' <StartSize value="1"/>', ' <EndSize value="5"/>', ' <DeltaFormat value="3"/>', ' <DeltaValue value="[77, 0, 0, 0, 3]"/>', "</Device>", ] def test_buildLigatureArray(self): anchor = builder.buildAnchor ligatureArray = builder.buildLigatureArray( { "f_i": [{2: anchor(300, -20)}, {}], "c_t": [{}, {1: anchor(500, 350), 2: anchor(1300, -20)}], }, numMarkClasses=4, glyphMap=self.GLYPHMAP, ) assert getXML(ligatureArray.toXML) == [ "<LigatureArray>", " <!-- LigatureCount=2 -->", ' <LigatureAttach index="0">', # f_i " <!-- ComponentCount=2 -->", ' <ComponentRecord index="0">', ' <LigatureAnchor index="0" empty="1"/>', ' <LigatureAnchor index="1" empty="1"/>', ' <LigatureAnchor index="2" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-20"/>', " </LigatureAnchor>", ' <LigatureAnchor index="3" empty="1"/>', " </ComponentRecord>", ' <ComponentRecord index="1">', ' <LigatureAnchor index="0" empty="1"/>', ' <LigatureAnchor index="1" empty="1"/>', ' <LigatureAnchor index="2" empty="1"/>', ' <LigatureAnchor index="3" empty="1"/>', " </ComponentRecord>", " </LigatureAttach>", ' <LigatureAttach index="1">', " <!-- ComponentCount=2 -->", ' <ComponentRecord index="0">', ' <LigatureAnchor index="0" empty="1"/>', ' <LigatureAnchor index="1" empty="1"/>', ' <LigatureAnchor index="2" empty="1"/>', ' <LigatureAnchor index="3" empty="1"/>', " </ComponentRecord>", ' <ComponentRecord index="1">', ' <LigatureAnchor index="0" empty="1"/>', ' <LigatureAnchor index="1" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="350"/>', " </LigatureAnchor>", ' <LigatureAnchor index="2" Format="1">', ' <XCoordinate value="1300"/>', ' <YCoordinate value="-20"/>', " </LigatureAnchor>", ' <LigatureAnchor index="3" empty="1"/>', " </ComponentRecord>", " </LigatureAttach>", "</LigatureArray>", ] def test_buildLigatureAttach(self): anchor = builder.buildAnchor attach = builder.buildLigatureAttach( [[anchor(500, -10), None], [None, anchor(300, -20), None]] ) assert getXML(attach.toXML) == [ "<LigatureAttach>", " <!-- ComponentCount=2 -->", ' <ComponentRecord index="0">', ' <LigatureAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-10"/>', " </LigatureAnchor>", ' <LigatureAnchor index="1" empty="1"/>', " </ComponentRecord>", ' <ComponentRecord index="1">', ' <LigatureAnchor index="0" empty="1"/>', ' <LigatureAnchor index="1" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-20"/>', " </LigatureAnchor>", ' <LigatureAnchor index="2" empty="1"/>', " </ComponentRecord>", "</LigatureAttach>", ] def test_buildLigatureAttach_emptyComponents(self): attach = builder.buildLigatureAttach([[], None]) assert getXML(attach.toXML) == [ "<LigatureAttach>", " <!-- ComponentCount=2 -->", ' <ComponentRecord index="0" empty="1"/>', ' <ComponentRecord index="1" empty="1"/>', "</LigatureAttach>", ] def test_buildLigatureAttach_noComponents(self): attach = builder.buildLigatureAttach([]) assert getXML(attach.toXML) == [ "<LigatureAttach>", " <!-- ComponentCount=0 -->", "</LigatureAttach>", ] def test_buildLigCaretList(self): carets = builder.buildLigCaretList( {"f_f_i": [300, 600]}, {"c_t": [42]}, self.GLYPHMAP ) assert getXML(carets.toXML) == [ "<LigCaretList>", " <Coverage>", ' <Glyph value="f_f_i"/>', ' <Glyph value="c_t"/>', " </Coverage>", " <!-- LigGlyphCount=2 -->", ' <LigGlyph index="0">', " <!-- CaretCount=2 -->", ' <CaretValue index="0" Format="1">', ' <Coordinate value="300"/>', " </CaretValue>", ' <CaretValue index="1" Format="1">', ' <Coordinate value="600"/>', " </CaretValue>", " </LigGlyph>", ' <LigGlyph index="1">', " <!-- CaretCount=1 -->", ' <CaretValue index="0" Format="2">', ' <CaretValuePoint value="42"/>', " </CaretValue>", " </LigGlyph>", "</LigCaretList>", ] def test_buildLigCaretList_bothCoordsAndPointsForSameGlyph(self): carets = builder.buildLigCaretList( {"f_f_i": [300]}, {"f_f_i": [7]}, self.GLYPHMAP ) assert getXML(carets.toXML) == [ "<LigCaretList>", " <Coverage>", ' <Glyph value="f_f_i"/>', " </Coverage>", " <!-- LigGlyphCount=1 -->", ' <LigGlyph index="0">', " <!-- CaretCount=2 -->", ' <CaretValue index="0" Format="1">', ' <Coordinate value="300"/>', " </CaretValue>", ' <CaretValue index="1" Format="2">', ' <CaretValuePoint value="7"/>', " </CaretValue>", " </LigGlyph>", "</LigCaretList>", ] def test_buildLigCaretList_empty(self): assert builder.buildLigCaretList({}, {}, self.GLYPHMAP) is None def test_buildLigCaretList_None(self): assert builder.buildLigCaretList(None, None, self.GLYPHMAP) is None def test_buildLigGlyph_coords(self): lig = builder.buildLigGlyph([500, 800], None) assert getXML(lig.toXML) == [ "<LigGlyph>", " <!-- CaretCount=2 -->", ' <CaretValue index="0" Format="1">', ' <Coordinate value="500"/>', " </CaretValue>", ' <CaretValue index="1" Format="1">', ' <Coordinate value="800"/>', " </CaretValue>", "</LigGlyph>", ] def test_buildLigGlyph_empty(self): assert builder.buildLigGlyph([], []) is None def test_buildLigGlyph_None(self): assert builder.buildLigGlyph(None, None) is None def test_buildLigGlyph_points(self): lig = builder.buildLigGlyph(None, [2]) assert getXML(lig.toXML) == [ "<LigGlyph>", " <!-- CaretCount=1 -->", ' <CaretValue index="0" Format="2">', ' <CaretValuePoint value="2"/>', " </CaretValue>", "</LigGlyph>", ] def test_buildLookup(self): s1 = builder.buildSingleSubstSubtable({"one": "two"}) s2 = builder.buildSingleSubstSubtable({"three": "four"}) lookup = builder.buildLookup([s1, s2], flags=7) assert getXML(lookup.toXML) == [ "<Lookup>", ' <LookupType value="1"/>', ' <LookupFlag value="7"/><!-- rightToLeft ignoreBaseGlyphs ignoreLigatures -->', " <!-- SubTableCount=2 -->", ' <SingleSubst index="0">', ' <Substitution in="one" out="two"/>', " </SingleSubst>", ' <SingleSubst index="1">', ' <Substitution in="three" out="four"/>', " </SingleSubst>", "</Lookup>", ] def test_buildLookup_badFlags(self): s = builder.buildSingleSubstSubtable({"one": "two"}) with pytest.raises( AssertionError, match=( "if markFilterSet is None, flags must not set " "LOOKUP_FLAG_USE_MARK_FILTERING_SET; flags=0x0010" ), ) as excinfo: builder.buildLookup([s], builder.LOOKUP_FLAG_USE_MARK_FILTERING_SET, None) def test_buildLookup_conflictingSubtableTypes(self): s1 = builder.buildSingleSubstSubtable({"one": "two"}) s2 = builder.buildAlternateSubstSubtable({"one": ["two", "three"]}) with pytest.raises( AssertionError, match="all subtables must have the same LookupType" ) as excinfo: builder.buildLookup([s1, s2]) def test_buildLookup_noSubtables(self): assert builder.buildLookup([]) is None assert builder.buildLookup(None) is None assert builder.buildLookup([None]) is None assert builder.buildLookup([None, None]) is None def test_buildLookup_markFilterSet(self): s = builder.buildSingleSubstSubtable({"one": "two"}) flags = ( builder.LOOKUP_FLAG_RIGHT_TO_LEFT | builder.LOOKUP_FLAG_USE_MARK_FILTERING_SET ) lookup = builder.buildLookup([s], flags, markFilterSet=999) assert getXML(lookup.toXML) == [ "<Lookup>", ' <LookupType value="1"/>', ' <LookupFlag value="17"/><!-- rightToLeft useMarkFilteringSet -->', " <!-- SubTableCount=1 -->", ' <SingleSubst index="0">', ' <Substitution in="one" out="two"/>', " </SingleSubst>", ' <MarkFilteringSet value="999"/>', "</Lookup>", ] def test_buildMarkArray(self): markArray = builder.buildMarkArray( { "acute": (7, builder.buildAnchor(300, 800)), "grave": (2, builder.buildAnchor(10, 80)), }, self.GLYPHMAP, ) assert self.GLYPHMAP["grave"] < self.GLYPHMAP["acute"] assert getXML(markArray.toXML) == [ "<MarkArray>", " <!-- MarkCount=2 -->", ' <MarkRecord index="0">', ' <Class value="2"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="10"/>', ' <YCoordinate value="80"/>', " </MarkAnchor>", " </MarkRecord>", ' <MarkRecord index="1">', ' <Class value="7"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="800"/>', " </MarkAnchor>", " </MarkRecord>", "</MarkArray>", ] def test_buildMarkBasePosSubtable(self): anchor = builder.buildAnchor marks = { "acute": (0, anchor(300, 700)), "cedilla": (1, anchor(300, -100)), "grave": (0, anchor(300, 700)), } bases = { # Make sure we can handle missing entries. "A": {}, # no entry for any markClass "B": {0: anchor(500, 900)}, # only markClass 0 specified "C": {1: anchor(500, -10)}, # only markClass 1 specified "a": {0: anchor(500, 400), 1: anchor(500, -20)}, "b": {0: anchor(500, 800), 1: anchor(500, -20)}, } table = builder.buildMarkBasePosSubtable(marks, bases, self.GLYPHMAP) assert getXML(table.toXML) == [ '<MarkBasePos Format="1">', " <MarkCoverage>", ' <Glyph value="grave"/>', ' <Glyph value="acute"/>', ' <Glyph value="cedilla"/>', " </MarkCoverage>", " <BaseCoverage>", ' <Glyph value="A"/>', ' <Glyph value="B"/>', ' <Glyph value="C"/>', ' <Glyph value="a"/>', ' <Glyph value="b"/>', " </BaseCoverage>", " <!-- ClassCount=2 -->", " <MarkArray>", " <!-- MarkCount=3 -->", ' <MarkRecord index="0">', # grave ' <Class value="0"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="700"/>', " </MarkAnchor>", " </MarkRecord>", ' <MarkRecord index="1">', # acute ' <Class value="0"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="700"/>', " </MarkAnchor>", " </MarkRecord>", ' <MarkRecord index="2">', # cedilla ' <Class value="1"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-100"/>', " </MarkAnchor>", " </MarkRecord>", " </MarkArray>", " <BaseArray>", " <!-- BaseCount=5 -->", ' <BaseRecord index="0">', # A ' <BaseAnchor index="0" empty="1"/>', ' <BaseAnchor index="1" empty="1"/>', " </BaseRecord>", ' <BaseRecord index="1">', # B ' <BaseAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="900"/>', " </BaseAnchor>", ' <BaseAnchor index="1" empty="1"/>', " </BaseRecord>", ' <BaseRecord index="2">', # C ' <BaseAnchor index="0" empty="1"/>', ' <BaseAnchor index="1" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-10"/>', " </BaseAnchor>", " </BaseRecord>", ' <BaseRecord index="3">', # a ' <BaseAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="400"/>', " </BaseAnchor>", ' <BaseAnchor index="1" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </BaseAnchor>", " </BaseRecord>", ' <BaseRecord index="4">', # b ' <BaseAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="800"/>', " </BaseAnchor>", ' <BaseAnchor index="1" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </BaseAnchor>", " </BaseRecord>", " </BaseArray>", "</MarkBasePos>", ] def test_buildMarkGlyphSetsDef(self): marksets = builder.buildMarkGlyphSetsDef( [{"acute", "grave"}, {"cedilla", "grave"}], self.GLYPHMAP ) assert getXML(marksets.toXML) == [ "<MarkGlyphSetsDef>", ' <MarkSetTableFormat value="1"/>', " <!-- MarkSetCount=2 -->", ' <Coverage index="0">', ' <Glyph value="grave"/>', ' <Glyph value="acute"/>', " </Coverage>", ' <Coverage index="1">', ' <Glyph value="grave"/>', ' <Glyph value="cedilla"/>', " </Coverage>", "</MarkGlyphSetsDef>", ] def test_buildMarkGlyphSetsDef_empty(self): assert builder.buildMarkGlyphSetsDef([], self.GLYPHMAP) is None def test_buildMarkGlyphSetsDef_None(self): assert builder.buildMarkGlyphSetsDef(None, self.GLYPHMAP) is None def test_buildMarkLigPosSubtable(self): anchor = builder.buildAnchor marks = { "acute": (0, anchor(300, 700)), "cedilla": (1, anchor(300, -100)), "grave": (0, anchor(300, 700)), } bases = { "f_i": [{}, {0: anchor(200, 400)}], # nothing on f; only 1 on i "c_t": [ {0: anchor(500, 600), 1: anchor(500, -20)}, # c {0: anchor(1300, 800), 1: anchor(1300, -20)}, # t ], } table = builder.buildMarkLigPosSubtable(marks, bases, self.GLYPHMAP) assert getXML(table.toXML) == [ '<MarkLigPos Format="1">', " <MarkCoverage>", ' <Glyph value="grave"/>', ' <Glyph value="acute"/>', ' <Glyph value="cedilla"/>', " </MarkCoverage>", " <LigatureCoverage>", ' <Glyph value="f_i"/>', ' <Glyph value="c_t"/>', " </LigatureCoverage>", " <!-- ClassCount=2 -->", " <MarkArray>", " <!-- MarkCount=3 -->", ' <MarkRecord index="0">', ' <Class value="0"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="700"/>', " </MarkAnchor>", " </MarkRecord>", ' <MarkRecord index="1">', ' <Class value="0"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="700"/>', " </MarkAnchor>", " </MarkRecord>", ' <MarkRecord index="2">', ' <Class value="1"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-100"/>', " </MarkAnchor>", " </MarkRecord>", " </MarkArray>", " <LigatureArray>", " <!-- LigatureCount=2 -->", ' <LigatureAttach index="0">', " <!-- ComponentCount=2 -->", ' <ComponentRecord index="0">', ' <LigatureAnchor index="0" empty="1"/>', ' <LigatureAnchor index="1" empty="1"/>', " </ComponentRecord>", ' <ComponentRecord index="1">', ' <LigatureAnchor index="0" Format="1">', ' <XCoordinate value="200"/>', ' <YCoordinate value="400"/>', " </LigatureAnchor>", ' <LigatureAnchor index="1" empty="1"/>', " </ComponentRecord>", " </LigatureAttach>", ' <LigatureAttach index="1">', " <!-- ComponentCount=2 -->", ' <ComponentRecord index="0">', ' <LigatureAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="600"/>', " </LigatureAnchor>", ' <LigatureAnchor index="1" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </LigatureAnchor>", " </ComponentRecord>", ' <ComponentRecord index="1">', ' <LigatureAnchor index="0" Format="1">', ' <XCoordinate value="1300"/>', ' <YCoordinate value="800"/>', " </LigatureAnchor>", ' <LigatureAnchor index="1" Format="1">', ' <XCoordinate value="1300"/>', ' <YCoordinate value="-20"/>', " </LigatureAnchor>", " </ComponentRecord>", " </LigatureAttach>", " </LigatureArray>", "</MarkLigPos>", ] def test_buildMarkRecord(self): rec = builder.buildMarkRecord(17, builder.buildAnchor(500, -20)) assert getXML(rec.toXML) == [ "<MarkRecord>", ' <Class value="17"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </MarkAnchor>", "</MarkRecord>", ] def test_buildMark2Record(self): a = builder.buildAnchor rec = builder.buildMark2Record([a(500, -20), None, a(300, -15)]) assert getXML(rec.toXML) == [ "<Mark2Record>", ' <Mark2Anchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </Mark2Anchor>", ' <Mark2Anchor index="1" empty="1"/>', ' <Mark2Anchor index="2" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-15"/>', " </Mark2Anchor>", "</Mark2Record>", ] def test_buildPairPosClassesSubtable(self): d20 = builder.buildValue({"XPlacement": -20}) d50 = builder.buildValue({"XPlacement": -50}) d0 = builder.buildValue({}) d8020 = builder.buildValue({"XPlacement": -80, "YPlacement": -20}) subtable = builder.buildPairPosClassesSubtable( { (tuple("A"), tuple(["zero"])): (d0, d50), (tuple("A"), tuple(["one", "two"])): (None, d20), (tuple(["B", "C"]), tuple(["zero"])): (d8020, d50), }, self.GLYPHMAP, ) assert getXML(subtable.toXML) == [ '<PairPos Format="2">', " <Coverage>", ' <Glyph value="A"/>', ' <Glyph value="B"/>', ' <Glyph value="C"/>', " </Coverage>", ' <ValueFormat1 value="3"/>', ' <ValueFormat2 value="1"/>', " <ClassDef1>", ' <ClassDef glyph="A" class="1"/>', " </ClassDef1>", " <ClassDef2>", ' <ClassDef glyph="one" class="1"/>', ' <ClassDef glyph="two" class="1"/>', ' <ClassDef glyph="zero" class="2"/>', " </ClassDef2>", " <!-- Class1Count=2 -->", " <!-- Class2Count=3 -->", ' <Class1Record index="0">', ' <Class2Record index="0">', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="0"/>', " </Class2Record>", ' <Class2Record index="1">', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="0"/>', " </Class2Record>", ' <Class2Record index="2">', ' <Value1 XPlacement="-80" YPlacement="-20"/>', ' <Value2 XPlacement="-50"/>', " </Class2Record>", " </Class1Record>", ' <Class1Record index="1">', ' <Class2Record index="0">', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="0"/>', " </Class2Record>", ' <Class2Record index="1">', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="-20"/>', " </Class2Record>", ' <Class2Record index="2">', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="-50"/>', " </Class2Record>", " </Class1Record>", "</PairPos>", ] def test_buildPairPosGlyphs(self): d50 = builder.buildValue({"XPlacement": -50}) d8020 = builder.buildValue({"XPlacement": -80, "YPlacement": -20}) subtables = builder.buildPairPosGlyphs( {("A", "zero"): (None, d50), ("A", "one"): (d8020, d50)}, self.GLYPHMAP ) assert sum([getXML(t.toXML) for t in subtables], []) == [ '<PairPos Format="1">', " <Coverage>", ' <Glyph value="A"/>', " </Coverage>", ' <ValueFormat1 value="0"/>', ' <ValueFormat2 value="1"/>', " <!-- PairSetCount=1 -->", ' <PairSet index="0">', " <!-- PairValueCount=1 -->", ' <PairValueRecord index="0">', ' <SecondGlyph value="zero"/>', ' <Value2 XPlacement="-50"/>', " </PairValueRecord>", " </PairSet>", "</PairPos>", '<PairPos Format="1">', " <Coverage>", ' <Glyph value="A"/>', " </Coverage>", ' <ValueFormat1 value="3"/>', ' <ValueFormat2 value="1"/>', " <!-- PairSetCount=1 -->", ' <PairSet index="0">', " <!-- PairValueCount=1 -->", ' <PairValueRecord index="0">', ' <SecondGlyph value="one"/>', ' <Value1 XPlacement="-80" YPlacement="-20"/>', ' <Value2 XPlacement="-50"/>', " </PairValueRecord>", " </PairSet>", "</PairPos>", ] def test_buildPairPosGlyphsSubtable(self): d20 = builder.buildValue({"XPlacement": -20}) d50 = builder.buildValue({"XPlacement": -50}) d0 = builder.buildValue({}) d8020 = builder.buildValue({"XPlacement": -80, "YPlacement": -20}) subtable = builder.buildPairPosGlyphsSubtable( { ("A", "zero"): (d0, d50), ("A", "one"): (None, d20), ("B", "five"): (d8020, d50), }, self.GLYPHMAP, ) assert getXML(subtable.toXML) == [ '<PairPos Format="1">', " <Coverage>", ' <Glyph value="A"/>', ' <Glyph value="B"/>', " </Coverage>", ' <ValueFormat1 value="3"/>', ' <ValueFormat2 value="1"/>', " <!-- PairSetCount=2 -->", ' <PairSet index="0">', " <!-- PairValueCount=2 -->", ' <PairValueRecord index="0">', ' <SecondGlyph value="zero"/>', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="-50"/>', " </PairValueRecord>", ' <PairValueRecord index="1">', ' <SecondGlyph value="one"/>', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="-20"/>', " </PairValueRecord>", " </PairSet>", ' <PairSet index="1">', " <!-- PairValueCount=1 -->", ' <PairValueRecord index="0">', ' <SecondGlyph value="five"/>', ' <Value1 XPlacement="-80" YPlacement="-20"/>', ' <Value2 XPlacement="-50"/>', " </PairValueRecord>", " </PairSet>", "</PairPos>", ] def test_buildSinglePos(self): subtables = builder.buildSinglePos( { "one": builder.buildValue({"XPlacement": 500}), "two": builder.buildValue({"XPlacement": 500}), "three": builder.buildValue({"XPlacement": 200}), "four": builder.buildValue({"XPlacement": 400}), "five": builder.buildValue({"XPlacement": 500}), "six": builder.buildValue({"YPlacement": -6}), }, self.GLYPHMAP, ) assert sum([getXML(t.toXML) for t in subtables], []) == [ '<SinglePos Format="2">', " <Coverage>", ' <Glyph value="one"/>', ' <Glyph value="two"/>', ' <Glyph value="three"/>', ' <Glyph value="four"/>', ' <Glyph value="five"/>', " </Coverage>", ' <ValueFormat value="1"/>', " <!-- ValueCount=5 -->", ' <Value index="0" XPlacement="500"/>', ' <Value index="1" XPlacement="500"/>', ' <Value index="2" XPlacement="200"/>', ' <Value index="3" XPlacement="400"/>', ' <Value index="4" XPlacement="500"/>', "</SinglePos>", '<SinglePos Format="1">', " <Coverage>", ' <Glyph value="six"/>', " </Coverage>", ' <ValueFormat value="2"/>', ' <Value YPlacement="-6"/>', "</SinglePos>", ] def test_buildSinglePos_ValueFormat0(self): subtables = builder.buildSinglePos( {"zero": builder.buildValue({})}, self.GLYPHMAP ) assert sum([getXML(t.toXML) for t in subtables], []) == [ '<SinglePos Format="1">', " <Coverage>", ' <Glyph value="zero"/>', " </Coverage>", ' <ValueFormat value="0"/>', "</SinglePos>", ] def test_buildSinglePosSubtable_format1(self): subtable = builder.buildSinglePosSubtable( { "one": builder.buildValue({"XPlacement": 777}), "two": builder.buildValue({"XPlacement": 777}), }, self.GLYPHMAP, ) assert getXML(subtable.toXML) == [ '<SinglePos Format="1">', " <Coverage>", ' <Glyph value="one"/>', ' <Glyph value="two"/>', " </Coverage>", ' <ValueFormat value="1"/>', ' <Value XPlacement="777"/>', "</SinglePos>", ] def test_buildSinglePosSubtable_format2(self): subtable = builder.buildSinglePosSubtable( { "one": builder.buildValue({"XPlacement": 777}), "two": builder.buildValue({"YPlacement": -888}), }, self.GLYPHMAP, ) assert getXML(subtable.toXML) == [ '<SinglePos Format="2">', " <Coverage>", ' <Glyph value="one"/>', ' <Glyph value="two"/>', " </Coverage>", ' <ValueFormat value="3"/>', " <!-- ValueCount=2 -->", ' <Value index="0" XPlacement="777" YPlacement="0"/>', ' <Value index="1" XPlacement="0" YPlacement="-888"/>', "</SinglePos>", ] def test_buildValue(self): value = builder.buildValue({"XPlacement": 7, "YPlacement": 23}) func = lambda writer, font: value.toXML(writer, font, valueName="Val") assert getXML(func) == ['<Val XPlacement="7" YPlacement="23"/>'] def test_getLigatureKey(self): components = lambda s: [tuple(word) for word in s.split()] c = components("fi fl ff ffi fff") c.sort(key=builder._getLigatureKey) assert c == components("fff ffi ff fi fl") def test_getSinglePosValueKey(self): device = builder.buildDevice({10: 1, 11: 3}) a1 = builder.buildValue({"XPlacement": 500, "XPlaDevice": device}) a2 = builder.buildValue({"XPlacement": 500, "XPlaDevice": device}) b = builder.buildValue({"XPlacement": 500}) keyA1 = builder._getSinglePosValueKey(a1) keyA2 = builder._getSinglePosValueKey(a1) keyB = builder._getSinglePosValueKey(b) assert keyA1 == keyA2 assert hash(keyA1) == hash(keyA2) assert keyA1 != keyB assert hash(keyA1) != hash(keyB) class ClassDefBuilderTest(object): def test_build_usingClass0(self): b = builder.ClassDefBuilder(useClass0=True) b.add({"aa", "bb"}) b.add({"a", "b"}) b.add({"c"}) b.add({"e", "f", "g", "h"}) cdef = b.build() assert isinstance(cdef, otTables.ClassDef) assert cdef.classDefs == {"a": 2, "b": 2, "c": 3, "aa": 1, "bb": 1} def test_build_notUsingClass0(self): b = builder.ClassDefBuilder(useClass0=False) b.add({"a", "b"}) b.add({"c"}) b.add({"e", "f", "g", "h"}) cdef = b.build() assert isinstance(cdef, otTables.ClassDef) assert cdef.classDefs == { "a": 2, "b": 2, "c": 3, "e": 1, "f": 1, "g": 1, "h": 1, } def test_canAdd(self): b = builder.ClassDefBuilder(useClass0=True) b.add({"a", "b", "c", "d"}) b.add({"e", "f"}) assert b.canAdd({"a", "b", "c", "d"}) assert b.canAdd({"e", "f"}) assert b.canAdd({"g", "h", "i"}) assert not b.canAdd({"b", "c", "d"}) assert not b.canAdd({"a", "b", "c", "d", "e", "f"}) assert not b.canAdd({"d", "e", "f"}) assert not b.canAdd({"f"}) def test_add_exception(self): b = builder.ClassDefBuilder(useClass0=True) b.add({"a", "b", "c"}) with pytest.raises(error.OpenTypeLibError): b.add({"a", "d"}) buildStatTable_test_data = [ ([ dict( tag="wght", name="Weight", values=[ dict(value=100, name='Thin'), dict(value=400, name='Regular', flags=0x2), dict(value=900, name='Black')])], None, "Regular", [ ' <STAT>', ' <Version value="0x00010001"/>', ' <DesignAxisRecordSize value="8"/>', ' <!-- DesignAxisCount=1 -->', ' <DesignAxisRecord>', ' <Axis index="0">', ' <AxisTag value="wght"/>', ' <AxisNameID value="257"/> <!-- Weight -->', ' <AxisOrdering value="0"/>', ' </Axis>', ' </DesignAxisRecord>', ' <!-- AxisValueCount=3 -->', ' <AxisValueArray>', ' <AxisValue index="0" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="258"/> <!-- Thin -->', ' <Value value="100.0"/>', ' </AxisValue>', ' <AxisValue index="1" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="2"/> <!-- ElidableAxisValueName -->', ' <ValueNameID value="256"/> <!-- Regular -->', ' <Value value="400.0"/>', ' </AxisValue>', ' <AxisValue index="2" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="259"/> <!-- Black -->', ' <Value value="900.0"/>', ' </AxisValue>', ' </AxisValueArray>', ' <ElidedFallbackNameID value="256"/> <!-- Regular -->', ' </STAT>']), ([ dict( tag="wght", name=dict(en="Weight", nl="Gewicht"), values=[ dict(value=100, name=dict(en='Thin', nl='Dun')), dict(value=400, name='Regular', flags=0x2), dict(value=900, name='Black'), ]), dict( tag="wdth", name="Width", values=[ dict(value=50, name='Condensed'), dict(value=100, name='Regular', flags=0x2), dict(value=200, name='Extended')])], None, 2, [ ' <STAT>', ' <Version value="0x00010001"/>', ' <DesignAxisRecordSize value="8"/>', ' <!-- DesignAxisCount=2 -->', ' <DesignAxisRecord>', ' <Axis index="0">', ' <AxisTag value="wght"/>', ' <AxisNameID value="256"/> <!-- Weight -->', ' <AxisOrdering value="0"/>', ' </Axis>', ' <Axis index="1">', ' <AxisTag value="wdth"/>', ' <AxisNameID value="260"/> <!-- Width -->', ' <AxisOrdering value="1"/>', ' </Axis>', ' </DesignAxisRecord>', ' <!-- AxisValueCount=6 -->', ' <AxisValueArray>', ' <AxisValue index="0" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="257"/> <!-- Thin -->', ' <Value value="100.0"/>', ' </AxisValue>', ' <AxisValue index="1" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="2"/> <!-- ElidableAxisValueName -->', ' <ValueNameID value="258"/> <!-- Regular -->', ' <Value value="400.0"/>', ' </AxisValue>', ' <AxisValue index="2" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="259"/> <!-- Black -->', ' <Value value="900.0"/>', ' </AxisValue>', ' <AxisValue index="3" Format="1">', ' <AxisIndex value="1"/>', ' <Flags value="0"/>', ' <ValueNameID value="261"/> <!-- Condensed -->', ' <Value value="50.0"/>', ' </AxisValue>', ' <AxisValue index="4" Format="1">', ' <AxisIndex value="1"/>', ' <Flags value="2"/> <!-- ElidableAxisValueName -->', ' <ValueNameID value="258"/> <!-- Regular -->', ' <Value value="100.0"/>', ' </AxisValue>', ' <AxisValue index="5" Format="1">', ' <AxisIndex value="1"/>', ' <Flags value="0"/>', ' <ValueNameID value="262"/> <!-- Extended -->', ' <Value value="200.0"/>', ' </AxisValue>', ' </AxisValueArray>', ' <ElidedFallbackNameID value="2"/> <!-- missing from name table -->', ' </STAT>']), ([ dict( tag="wght", name="Weight", values=[ dict(value=400, name='Regular', flags=0x2), dict(value=600, linkedValue=650, name='Bold')])], None, 18, [ ' <STAT>', ' <Version value="0x00010001"/>', ' <DesignAxisRecordSize value="8"/>', ' <!-- DesignAxisCount=1 -->', ' <DesignAxisRecord>', ' <Axis index="0">', ' <AxisTag value="wght"/>', ' <AxisNameID value="256"/> <!-- Weight -->', ' <AxisOrdering value="0"/>', ' </Axis>', ' </DesignAxisRecord>', ' <!-- AxisValueCount=2 -->', ' <AxisValueArray>', ' <AxisValue index="0" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="2"/> <!-- ElidableAxisValueName -->', ' <ValueNameID value="257"/> <!-- Regular -->', ' <Value value="400.0"/>', ' </AxisValue>', ' <AxisValue index="1" Format="3">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="258"/> <!-- Bold -->', ' <Value value="600.0"/>', ' <LinkedValue value="650.0"/>', ' </AxisValue>', ' </AxisValueArray>', ' <ElidedFallbackNameID value="18"/> <!-- missing from name table -->', ' </STAT>']), ([ dict( tag="opsz", name="Optical Size", values=[ dict(nominalValue=6, rangeMaxValue=10, name='Small'), dict(rangeMinValue=10, nominalValue=14, rangeMaxValue=24, name='Text', flags=0x2), dict(rangeMinValue=24, nominalValue=600, name='Display')])], None, 2, [ ' <STAT>', ' <Version value="0x00010001"/>', ' <DesignAxisRecordSize value="8"/>', ' <!-- DesignAxisCount=1 -->', ' <DesignAxisRecord>', ' <Axis index="0">', ' <AxisTag value="opsz"/>', ' <AxisNameID value="256"/> <!-- Optical Size -->', ' <AxisOrdering value="0"/>', ' </Axis>', ' </DesignAxisRecord>', ' <!-- AxisValueCount=3 -->', ' <AxisValueArray>', ' <AxisValue index="0" Format="2">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="257"/> <!-- Small -->', ' <NominalValue value="6.0"/>', ' <RangeMinValue value="-32768.0"/>', ' <RangeMaxValue value="10.0"/>', ' </AxisValue>', ' <AxisValue index="1" Format="2">', ' <AxisIndex value="0"/>', ' <Flags value="2"/> <!-- ElidableAxisValueName -->', ' <ValueNameID value="258"/> <!-- Text -->', ' <NominalValue value="14.0"/>', ' <RangeMinValue value="10.0"/>', ' <RangeMaxValue value="24.0"/>', ' </AxisValue>', ' <AxisValue index="2" Format="2">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="259"/> <!-- Display -->', ' <NominalValue value="600.0"/>', ' <RangeMinValue value="24.0"/>', ' <RangeMaxValue value="32767.99998"/>', ' </AxisValue>', ' </AxisValueArray>', ' <ElidedFallbackNameID value="2"/> <!-- missing from name table -->', ' </STAT>']), ([ dict( tag="wght", name="Weight", ordering=1, values=[]), dict( tag="ABCD", name="ABCDTest", ordering=0, values=[ dict(value=100, name="Regular", flags=0x2)])], [dict(location=dict(wght=300, ABCD=100), name='Regular ABCD')], 18, [ ' <STAT>', ' <Version value="0x00010002"/>', ' <DesignAxisRecordSize value="8"/>', ' <!-- DesignAxisCount=2 -->', ' <DesignAxisRecord>', ' <Axis index="0">', ' <AxisTag value="wght"/>', ' <AxisNameID value="256"/> <!-- Weight -->', ' <AxisOrdering value="1"/>', ' </Axis>', ' <Axis index="1">', ' <AxisTag value="ABCD"/>', ' <AxisNameID value="257"/> <!-- ABCDTest -->', ' <AxisOrdering value="0"/>', ' </Axis>', ' </DesignAxisRecord>', ' <!-- AxisValueCount=2 -->', ' <AxisValueArray>', ' <AxisValue index="0" Format="4">', ' <!-- AxisCount=2 -->', ' <Flags value="0"/>', ' <ValueNameID value="259"/> <!-- Regular ABCD -->', ' <AxisValueRecord index="0">', ' <AxisIndex value="0"/>', ' <Value value="300.0"/>', ' </AxisValueRecord>', ' <AxisValueRecord index="1">', ' <AxisIndex value="1"/>', ' <Value value="100.0"/>', ' </AxisValueRecord>', ' </AxisValue>', ' <AxisValue index="1" Format="1">', ' <AxisIndex value="1"/>', ' <Flags value="2"/> <!-- ElidableAxisValueName -->', ' <ValueNameID value="258"/> <!-- Regular -->', ' <Value value="100.0"/>', ' </AxisValue>', ' </AxisValueArray>', ' <ElidedFallbackNameID value="18"/> <!-- missing from name table -->', ' </STAT>']), ] @pytest.mark.parametrize("axes, axisValues, elidedFallbackName, expected_ttx", buildStatTable_test_data) def test_buildStatTable(axes, axisValues, elidedFallbackName, expected_ttx): font = ttLib.TTFont() font["name"] = ttLib.newTable("name") font["name"].names = [] # https://github.com/fonttools/fonttools/issues/1985 # Add nameID < 256 that matches a test axis name, to test whether # the nameID is not reused: AxisNameIDs must be > 255 according # to the spec. font["name"].addMultilingualName(dict(en="ABCDTest"), nameID=6) builder.buildStatTable(font, axes, axisValues, elidedFallbackName) f = io.StringIO() font.saveXML(f, tables=["STAT"]) ttx = f.getvalue().splitlines() ttx = ttx[3:-2] # strip XML header and <ttFont> element assert expected_ttx == ttx # Compile and round-trip f = io.BytesIO() font.save(f) font = ttLib.TTFont(f) f = io.StringIO() font.saveXML(f, tables=["STAT"]) ttx = f.getvalue().splitlines() ttx = ttx[3:-2] # strip XML header and <ttFont> element assert expected_ttx == ttx def test_stat_infinities(): negInf = floatToFixed(builder.AXIS_VALUE_NEGATIVE_INFINITY, 16) assert struct.pack(">l", negInf) == b"\x80\x00\x00\x00" posInf = floatToFixed(builder.AXIS_VALUE_POSITIVE_INFINITY, 16) assert struct.pack(">l", posInf) == b"\x7f\xff\xff\xff" class ChainContextualRulesetTest(object): def test_makeRulesets(self): font = ttLib.TTFont() font.setGlyphOrder(["a","b","c","d","A","B","C","D","E"]) sb = builder.ChainContextSubstBuilder(font, None) prefix, input_, suffix, lookups = [["a"], ["b"]], [["c"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) prefix, input_, suffix, lookups = [["a"], ["d"]], [["c"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) sb.add_subtable_break(None) # Second subtable has some glyph classes prefix, input_, suffix, lookups = [["A"]], [["E"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) prefix, input_, suffix, lookups = [["A"]], [["C","D"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) prefix, input_, suffix, lookups = [["A", "B"]], [["E"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) sb.add_subtable_break(None) # Third subtable has no pre/post context prefix, input_, suffix, lookups = [], [["E"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) prefix, input_, suffix, lookups = [], [["C","D"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) rulesets = sb.rulesets() assert len(rulesets) == 3 assert rulesets[0].hasPrefixOrSuffix assert not rulesets[0].hasAnyGlyphClasses cd = rulesets[0].format2ClassDefs() assert set(cd[0].classes()[1:]) == set([("d",),("b",),("a",)]) assert set(cd[1].classes()[1:]) == set([("c",)]) assert set(cd[2].classes()[1:]) == set() assert rulesets[1].hasPrefixOrSuffix assert rulesets[1].hasAnyGlyphClasses assert not rulesets[1].format2ClassDefs() assert not rulesets[2].hasPrefixOrSuffix assert rulesets[2].hasAnyGlyphClasses assert rulesets[2].format2ClassDefs() cd = rulesets[2].format2ClassDefs() assert set(cd[0].classes()[1:]) == set() assert set(cd[1].classes()[1:]) == set([("C","D"), ("E",)]) assert set(cd[2].classes()[1:]) == set() if __name__ == "__main__": import sys sys.exit(pytest.main(sys.argv))
39.336742
104
0.451158
import io import struct from fontTools.misc.fixedTools import floatToFixed from fontTools.misc.testTools import getXML from fontTools.otlLib import builder, error from fontTools import ttLib from fontTools.ttLib.tables import otTables import pytest class BuilderTest(object): GLYPHS = ( ".notdef space zero one two three four five six " "A B C a b c grave acute cedilla f_f_i f_i c_t" ).split() GLYPHMAP = {name: num for num, name in enumerate(GLYPHS)} ANCHOR1 = builder.buildAnchor(11, -11) ANCHOR2 = builder.buildAnchor(22, -22) ANCHOR3 = builder.buildAnchor(33, -33) def test_buildAnchor_format1(self): anchor = builder.buildAnchor(23, 42) assert getXML(anchor.toXML) == [ '<Anchor Format="1">', ' <XCoordinate value="23"/>', ' <YCoordinate value="42"/>', "</Anchor>", ] def test_buildAnchor_format2(self): anchor = builder.buildAnchor(23, 42, point=17) assert getXML(anchor.toXML) == [ '<Anchor Format="2">', ' <XCoordinate value="23"/>', ' <YCoordinate value="42"/>', ' <AnchorPoint value="17"/>', "</Anchor>", ] def test_buildAnchor_format3(self): anchor = builder.buildAnchor( 23, 42, deviceX=builder.buildDevice({1: 1, 0: 0}), deviceY=builder.buildDevice({7: 7}), ) assert getXML(anchor.toXML) == [ '<Anchor Format="3">', ' <XCoordinate value="23"/>', ' <YCoordinate value="42"/>', " <XDeviceTable>", ' <StartSize value="0"/>', ' <EndSize value="1"/>', ' <DeltaFormat value="1"/>', ' <DeltaValue value="[0, 1]"/>', " </XDeviceTable>", " <YDeviceTable>", ' <StartSize value="7"/>', ' <EndSize value="7"/>', ' <DeltaFormat value="2"/>', ' <DeltaValue value="[7]"/>', " </YDeviceTable>", "</Anchor>", ] def test_buildAttachList(self): attachList = builder.buildAttachList( {"zero": [23, 7], "one": [1]}, self.GLYPHMAP ) assert getXML(attachList.toXML) == [ "<AttachList>", " <Coverage>", ' <Glyph value="zero"/>', ' <Glyph value="one"/>', " </Coverage>", " <!-- GlyphCount=2 -->", ' <AttachPoint index="0">', " <!-- PointCount=2 -->", ' <PointIndex index="0" value="7"/>', ' <PointIndex index="1" value="23"/>', " </AttachPoint>", ' <AttachPoint index="1">', " <!-- PointCount=1 -->", ' <PointIndex index="0" value="1"/>', " </AttachPoint>", "</AttachList>", ] def test_buildAttachList_empty(self): assert builder.buildAttachList({}, self.GLYPHMAP) is None def test_buildAttachPoint(self): attachPoint = builder.buildAttachPoint([7, 3]) assert getXML(attachPoint.toXML) == [ "<AttachPoint>", " <!-- PointCount=2 -->", ' <PointIndex index="0" value="3"/>', ' <PointIndex index="1" value="7"/>', "</AttachPoint>", ] def test_buildAttachPoint_empty(self): assert builder.buildAttachPoint([]) is None def test_buildAttachPoint_duplicate(self): attachPoint = builder.buildAttachPoint([7, 3, 7]) assert getXML(attachPoint.toXML) == [ "<AttachPoint>", " <!-- PointCount=2 -->", ' <PointIndex index="0" value="3"/>', ' <PointIndex index="1" value="7"/>', "</AttachPoint>", ] def test_buildBaseArray(self): anchor = builder.buildAnchor baseArray = builder.buildBaseArray( {"a": {2: anchor(300, 80)}, "c": {1: anchor(300, 80), 2: anchor(300, -20)}}, numMarkClasses=4, glyphMap=self.GLYPHMAP, ) assert getXML(baseArray.toXML) == [ "<BaseArray>", " <!-- BaseCount=2 -->", ' <BaseRecord index="0">', ' <BaseAnchor index="0" empty="1"/>', ' <BaseAnchor index="1" empty="1"/>', ' <BaseAnchor index="2" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="80"/>', " </BaseAnchor>", ' <BaseAnchor index="3" empty="1"/>', " </BaseRecord>", ' <BaseRecord index="1">', ' <BaseAnchor index="0" empty="1"/>', ' <BaseAnchor index="1" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="80"/>', " </BaseAnchor>", ' <BaseAnchor index="2" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-20"/>', " </BaseAnchor>", ' <BaseAnchor index="3" empty="1"/>', " </BaseRecord>", "</BaseArray>", ] def test_buildBaseRecord(self): a = builder.buildAnchor rec = builder.buildBaseRecord([a(500, -20), None, a(300, -15)]) assert getXML(rec.toXML) == [ "<BaseRecord>", ' <BaseAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </BaseAnchor>", ' <BaseAnchor index="1" empty="1"/>', ' <BaseAnchor index="2" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-15"/>', " </BaseAnchor>", "</BaseRecord>", ] def test_buildCaretValueForCoord(self): caret = builder.buildCaretValueForCoord(500) assert getXML(caret.toXML) == [ '<CaretValue Format="1">', ' <Coordinate value="500"/>', "</CaretValue>", ] def test_buildCaretValueForPoint(self): caret = builder.buildCaretValueForPoint(23) assert getXML(caret.toXML) == [ '<CaretValue Format="2">', ' <CaretValuePoint value="23"/>', "</CaretValue>", ] def test_buildComponentRecord(self): a = builder.buildAnchor rec = builder.buildComponentRecord([a(500, -20), None, a(300, -15)]) assert getXML(rec.toXML) == [ "<ComponentRecord>", ' <LigatureAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </LigatureAnchor>", ' <LigatureAnchor index="1" empty="1"/>', ' <LigatureAnchor index="2" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-15"/>', " </LigatureAnchor>", "</ComponentRecord>", ] def test_buildComponentRecord_empty(self): assert builder.buildComponentRecord([]) is None def test_buildComponentRecord_None(self): assert builder.buildComponentRecord(None) is None def test_buildCoverage(self): cov = builder.buildCoverage({"two", "four"}, {"two": 2, "four": 4}) assert getXML(cov.toXML) == [ "<Coverage>", ' <Glyph value="two"/>', ' <Glyph value="four"/>', "</Coverage>", ] def test_buildCursivePos(self): pos = builder.buildCursivePosSubtable( {"two": (self.ANCHOR1, self.ANCHOR2), "four": (self.ANCHOR3, self.ANCHOR1)}, self.GLYPHMAP, ) assert getXML(pos.toXML) == [ '<CursivePos Format="1">', " <Coverage>", ' <Glyph value="two"/>', ' <Glyph value="four"/>', " </Coverage>", " <!-- EntryExitCount=2 -->", ' <EntryExitRecord index="0">', ' <EntryAnchor Format="1">', ' <XCoordinate value="11"/>', ' <YCoordinate value="-11"/>', " </EntryAnchor>", ' <ExitAnchor Format="1">', ' <XCoordinate value="22"/>', ' <YCoordinate value="-22"/>', " </ExitAnchor>", " </EntryExitRecord>", ' <EntryExitRecord index="1">', ' <EntryAnchor Format="1">', ' <XCoordinate value="33"/>', ' <YCoordinate value="-33"/>', " </EntryAnchor>", ' <ExitAnchor Format="1">', ' <XCoordinate value="11"/>', ' <YCoordinate value="-11"/>', " </ExitAnchor>", " </EntryExitRecord>", "</CursivePos>", ] def test_buildDevice_format1(self): device = builder.buildDevice({1: 1, 0: 0}) assert getXML(device.toXML) == [ "<Device>", ' <StartSize value="0"/>', ' <EndSize value="1"/>', ' <DeltaFormat value="1"/>', ' <DeltaValue value="[0, 1]"/>', "</Device>", ] def test_buildDevice_format2(self): device = builder.buildDevice({2: 2, 0: 1, 1: 0}) assert getXML(device.toXML) == [ "<Device>", ' <StartSize value="0"/>', ' <EndSize value="2"/>', ' <DeltaFormat value="2"/>', ' <DeltaValue value="[1, 0, 2]"/>', "</Device>", ] def test_buildDevice_format3(self): device = builder.buildDevice({5: 3, 1: 77}) assert getXML(device.toXML) == [ "<Device>", ' <StartSize value="1"/>', ' <EndSize value="5"/>', ' <DeltaFormat value="3"/>', ' <DeltaValue value="[77, 0, 0, 0, 3]"/>', "</Device>", ] def test_buildLigatureArray(self): anchor = builder.buildAnchor ligatureArray = builder.buildLigatureArray( { "f_i": [{2: anchor(300, -20)}, {}], "c_t": [{}, {1: anchor(500, 350), 2: anchor(1300, -20)}], }, numMarkClasses=4, glyphMap=self.GLYPHMAP, ) assert getXML(ligatureArray.toXML) == [ "<LigatureArray>", " <!-- LigatureCount=2 -->", ' <LigatureAttach index="0">', " <!-- ComponentCount=2 -->", ' <ComponentRecord index="0">', ' <LigatureAnchor index="0" empty="1"/>', ' <LigatureAnchor index="1" empty="1"/>', ' <LigatureAnchor index="2" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-20"/>', " </LigatureAnchor>", ' <LigatureAnchor index="3" empty="1"/>', " </ComponentRecord>", ' <ComponentRecord index="1">', ' <LigatureAnchor index="0" empty="1"/>', ' <LigatureAnchor index="1" empty="1"/>', ' <LigatureAnchor index="2" empty="1"/>', ' <LigatureAnchor index="3" empty="1"/>', " </ComponentRecord>", " </LigatureAttach>", ' <LigatureAttach index="1">', " <!-- ComponentCount=2 -->", ' <ComponentRecord index="0">', ' <LigatureAnchor index="0" empty="1"/>', ' <LigatureAnchor index="1" empty="1"/>', ' <LigatureAnchor index="2" empty="1"/>', ' <LigatureAnchor index="3" empty="1"/>', " </ComponentRecord>", ' <ComponentRecord index="1">', ' <LigatureAnchor index="0" empty="1"/>', ' <LigatureAnchor index="1" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="350"/>', " </LigatureAnchor>", ' <LigatureAnchor index="2" Format="1">', ' <XCoordinate value="1300"/>', ' <YCoordinate value="-20"/>', " </LigatureAnchor>", ' <LigatureAnchor index="3" empty="1"/>', " </ComponentRecord>", " </LigatureAttach>", "</LigatureArray>", ] def test_buildLigatureAttach(self): anchor = builder.buildAnchor attach = builder.buildLigatureAttach( [[anchor(500, -10), None], [None, anchor(300, -20), None]] ) assert getXML(attach.toXML) == [ "<LigatureAttach>", " <!-- ComponentCount=2 -->", ' <ComponentRecord index="0">', ' <LigatureAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-10"/>', " </LigatureAnchor>", ' <LigatureAnchor index="1" empty="1"/>', " </ComponentRecord>", ' <ComponentRecord index="1">', ' <LigatureAnchor index="0" empty="1"/>', ' <LigatureAnchor index="1" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-20"/>', " </LigatureAnchor>", ' <LigatureAnchor index="2" empty="1"/>', " </ComponentRecord>", "</LigatureAttach>", ] def test_buildLigatureAttach_emptyComponents(self): attach = builder.buildLigatureAttach([[], None]) assert getXML(attach.toXML) == [ "<LigatureAttach>", " <!-- ComponentCount=2 -->", ' <ComponentRecord index="0" empty="1"/>', ' <ComponentRecord index="1" empty="1"/>', "</LigatureAttach>", ] def test_buildLigatureAttach_noComponents(self): attach = builder.buildLigatureAttach([]) assert getXML(attach.toXML) == [ "<LigatureAttach>", " <!-- ComponentCount=0 -->", "</LigatureAttach>", ] def test_buildLigCaretList(self): carets = builder.buildLigCaretList( {"f_f_i": [300, 600]}, {"c_t": [42]}, self.GLYPHMAP ) assert getXML(carets.toXML) == [ "<LigCaretList>", " <Coverage>", ' <Glyph value="f_f_i"/>', ' <Glyph value="c_t"/>', " </Coverage>", " <!-- LigGlyphCount=2 -->", ' <LigGlyph index="0">', " <!-- CaretCount=2 -->", ' <CaretValue index="0" Format="1">', ' <Coordinate value="300"/>', " </CaretValue>", ' <CaretValue index="1" Format="1">', ' <Coordinate value="600"/>', " </CaretValue>", " </LigGlyph>", ' <LigGlyph index="1">', " <!-- CaretCount=1 -->", ' <CaretValue index="0" Format="2">', ' <CaretValuePoint value="42"/>', " </CaretValue>", " </LigGlyph>", "</LigCaretList>", ] def test_buildLigCaretList_bothCoordsAndPointsForSameGlyph(self): carets = builder.buildLigCaretList( {"f_f_i": [300]}, {"f_f_i": [7]}, self.GLYPHMAP ) assert getXML(carets.toXML) == [ "<LigCaretList>", " <Coverage>", ' <Glyph value="f_f_i"/>', " </Coverage>", " <!-- LigGlyphCount=1 -->", ' <LigGlyph index="0">', " <!-- CaretCount=2 -->", ' <CaretValue index="0" Format="1">', ' <Coordinate value="300"/>', " </CaretValue>", ' <CaretValue index="1" Format="2">', ' <CaretValuePoint value="7"/>', " </CaretValue>", " </LigGlyph>", "</LigCaretList>", ] def test_buildLigCaretList_empty(self): assert builder.buildLigCaretList({}, {}, self.GLYPHMAP) is None def test_buildLigCaretList_None(self): assert builder.buildLigCaretList(None, None, self.GLYPHMAP) is None def test_buildLigGlyph_coords(self): lig = builder.buildLigGlyph([500, 800], None) assert getXML(lig.toXML) == [ "<LigGlyph>", " <!-- CaretCount=2 -->", ' <CaretValue index="0" Format="1">', ' <Coordinate value="500"/>', " </CaretValue>", ' <CaretValue index="1" Format="1">', ' <Coordinate value="800"/>', " </CaretValue>", "</LigGlyph>", ] def test_buildLigGlyph_empty(self): assert builder.buildLigGlyph([], []) is None def test_buildLigGlyph_None(self): assert builder.buildLigGlyph(None, None) is None def test_buildLigGlyph_points(self): lig = builder.buildLigGlyph(None, [2]) assert getXML(lig.toXML) == [ "<LigGlyph>", " <!-- CaretCount=1 -->", ' <CaretValue index="0" Format="2">', ' <CaretValuePoint value="2"/>', " </CaretValue>", "</LigGlyph>", ] def test_buildLookup(self): s1 = builder.buildSingleSubstSubtable({"one": "two"}) s2 = builder.buildSingleSubstSubtable({"three": "four"}) lookup = builder.buildLookup([s1, s2], flags=7) assert getXML(lookup.toXML) == [ "<Lookup>", ' <LookupType value="1"/>', ' <LookupFlag value="7"/><!-- rightToLeft ignoreBaseGlyphs ignoreLigatures -->', " <!-- SubTableCount=2 -->", ' <SingleSubst index="0">', ' <Substitution in="one" out="two"/>', " </SingleSubst>", ' <SingleSubst index="1">', ' <Substitution in="three" out="four"/>', " </SingleSubst>", "</Lookup>", ] def test_buildLookup_badFlags(self): s = builder.buildSingleSubstSubtable({"one": "two"}) with pytest.raises( AssertionError, match=( "if markFilterSet is None, flags must not set " "LOOKUP_FLAG_USE_MARK_FILTERING_SET; flags=0x0010" ), ) as excinfo: builder.buildLookup([s], builder.LOOKUP_FLAG_USE_MARK_FILTERING_SET, None) def test_buildLookup_conflictingSubtableTypes(self): s1 = builder.buildSingleSubstSubtable({"one": "two"}) s2 = builder.buildAlternateSubstSubtable({"one": ["two", "three"]}) with pytest.raises( AssertionError, match="all subtables must have the same LookupType" ) as excinfo: builder.buildLookup([s1, s2]) def test_buildLookup_noSubtables(self): assert builder.buildLookup([]) is None assert builder.buildLookup(None) is None assert builder.buildLookup([None]) is None assert builder.buildLookup([None, None]) is None def test_buildLookup_markFilterSet(self): s = builder.buildSingleSubstSubtable({"one": "two"}) flags = ( builder.LOOKUP_FLAG_RIGHT_TO_LEFT | builder.LOOKUP_FLAG_USE_MARK_FILTERING_SET ) lookup = builder.buildLookup([s], flags, markFilterSet=999) assert getXML(lookup.toXML) == [ "<Lookup>", ' <LookupType value="1"/>', ' <LookupFlag value="17"/><!-- rightToLeft useMarkFilteringSet -->', " <!-- SubTableCount=1 -->", ' <SingleSubst index="0">', ' <Substitution in="one" out="two"/>', " </SingleSubst>", ' <MarkFilteringSet value="999"/>', "</Lookup>", ] def test_buildMarkArray(self): markArray = builder.buildMarkArray( { "acute": (7, builder.buildAnchor(300, 800)), "grave": (2, builder.buildAnchor(10, 80)), }, self.GLYPHMAP, ) assert self.GLYPHMAP["grave"] < self.GLYPHMAP["acute"] assert getXML(markArray.toXML) == [ "<MarkArray>", " <!-- MarkCount=2 -->", ' <MarkRecord index="0">', ' <Class value="2"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="10"/>', ' <YCoordinate value="80"/>', " </MarkAnchor>", " </MarkRecord>", ' <MarkRecord index="1">', ' <Class value="7"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="800"/>', " </MarkAnchor>", " </MarkRecord>", "</MarkArray>", ] def test_buildMarkBasePosSubtable(self): anchor = builder.buildAnchor marks = { "acute": (0, anchor(300, 700)), "cedilla": (1, anchor(300, -100)), "grave": (0, anchor(300, 700)), } bases = { "A": {}, "B": {0: anchor(500, 900)}, "C": {1: anchor(500, -10)}, "a": {0: anchor(500, 400), 1: anchor(500, -20)}, "b": {0: anchor(500, 800), 1: anchor(500, -20)}, } table = builder.buildMarkBasePosSubtable(marks, bases, self.GLYPHMAP) assert getXML(table.toXML) == [ '<MarkBasePos Format="1">', " <MarkCoverage>", ' <Glyph value="grave"/>', ' <Glyph value="acute"/>', ' <Glyph value="cedilla"/>', " </MarkCoverage>", " <BaseCoverage>", ' <Glyph value="A"/>', ' <Glyph value="B"/>', ' <Glyph value="C"/>', ' <Glyph value="a"/>', ' <Glyph value="b"/>', " </BaseCoverage>", " <!-- ClassCount=2 -->", " <MarkArray>", " <!-- MarkCount=3 -->", ' <MarkRecord index="0">', ' <Class value="0"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="700"/>', " </MarkAnchor>", " </MarkRecord>", ' <MarkRecord index="1">', ' <Class value="0"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="700"/>', " </MarkAnchor>", " </MarkRecord>", ' <MarkRecord index="2">', ' <Class value="1"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-100"/>', " </MarkAnchor>", " </MarkRecord>", " </MarkArray>", " <BaseArray>", " <!-- BaseCount=5 -->", ' <BaseRecord index="0">', ' <BaseAnchor index="0" empty="1"/>', ' <BaseAnchor index="1" empty="1"/>', " </BaseRecord>", ' <BaseRecord index="1">', ' <BaseAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="900"/>', " </BaseAnchor>", ' <BaseAnchor index="1" empty="1"/>', " </BaseRecord>", ' <BaseRecord index="2">', ' <BaseAnchor index="0" empty="1"/>', ' <BaseAnchor index="1" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-10"/>', " </BaseAnchor>", " </BaseRecord>", ' <BaseRecord index="3">', ' <BaseAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="400"/>', " </BaseAnchor>", ' <BaseAnchor index="1" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </BaseAnchor>", " </BaseRecord>", ' <BaseRecord index="4">', ' <BaseAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="800"/>', " </BaseAnchor>", ' <BaseAnchor index="1" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </BaseAnchor>", " </BaseRecord>", " </BaseArray>", "</MarkBasePos>", ] def test_buildMarkGlyphSetsDef(self): marksets = builder.buildMarkGlyphSetsDef( [{"acute", "grave"}, {"cedilla", "grave"}], self.GLYPHMAP ) assert getXML(marksets.toXML) == [ "<MarkGlyphSetsDef>", ' <MarkSetTableFormat value="1"/>', " <!-- MarkSetCount=2 -->", ' <Coverage index="0">', ' <Glyph value="grave"/>', ' <Glyph value="acute"/>', " </Coverage>", ' <Coverage index="1">', ' <Glyph value="grave"/>', ' <Glyph value="cedilla"/>', " </Coverage>", "</MarkGlyphSetsDef>", ] def test_buildMarkGlyphSetsDef_empty(self): assert builder.buildMarkGlyphSetsDef([], self.GLYPHMAP) is None def test_buildMarkGlyphSetsDef_None(self): assert builder.buildMarkGlyphSetsDef(None, self.GLYPHMAP) is None def test_buildMarkLigPosSubtable(self): anchor = builder.buildAnchor marks = { "acute": (0, anchor(300, 700)), "cedilla": (1, anchor(300, -100)), "grave": (0, anchor(300, 700)), } bases = { "f_i": [{}, {0: anchor(200, 400)}], "c_t": [ {0: anchor(500, 600), 1: anchor(500, -20)}, {0: anchor(1300, 800), 1: anchor(1300, -20)}, ], } table = builder.buildMarkLigPosSubtable(marks, bases, self.GLYPHMAP) assert getXML(table.toXML) == [ '<MarkLigPos Format="1">', " <MarkCoverage>", ' <Glyph value="grave"/>', ' <Glyph value="acute"/>', ' <Glyph value="cedilla"/>', " </MarkCoverage>", " <LigatureCoverage>", ' <Glyph value="f_i"/>', ' <Glyph value="c_t"/>', " </LigatureCoverage>", " <!-- ClassCount=2 -->", " <MarkArray>", " <!-- MarkCount=3 -->", ' <MarkRecord index="0">', ' <Class value="0"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="700"/>', " </MarkAnchor>", " </MarkRecord>", ' <MarkRecord index="1">', ' <Class value="0"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="700"/>', " </MarkAnchor>", " </MarkRecord>", ' <MarkRecord index="2">', ' <Class value="1"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-100"/>', " </MarkAnchor>", " </MarkRecord>", " </MarkArray>", " <LigatureArray>", " <!-- LigatureCount=2 -->", ' <LigatureAttach index="0">', " <!-- ComponentCount=2 -->", ' <ComponentRecord index="0">', ' <LigatureAnchor index="0" empty="1"/>', ' <LigatureAnchor index="1" empty="1"/>', " </ComponentRecord>", ' <ComponentRecord index="1">', ' <LigatureAnchor index="0" Format="1">', ' <XCoordinate value="200"/>', ' <YCoordinate value="400"/>', " </LigatureAnchor>", ' <LigatureAnchor index="1" empty="1"/>', " </ComponentRecord>", " </LigatureAttach>", ' <LigatureAttach index="1">', " <!-- ComponentCount=2 -->", ' <ComponentRecord index="0">', ' <LigatureAnchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="600"/>', " </LigatureAnchor>", ' <LigatureAnchor index="1" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </LigatureAnchor>", " </ComponentRecord>", ' <ComponentRecord index="1">', ' <LigatureAnchor index="0" Format="1">', ' <XCoordinate value="1300"/>', ' <YCoordinate value="800"/>', " </LigatureAnchor>", ' <LigatureAnchor index="1" Format="1">', ' <XCoordinate value="1300"/>', ' <YCoordinate value="-20"/>', " </LigatureAnchor>", " </ComponentRecord>", " </LigatureAttach>", " </LigatureArray>", "</MarkLigPos>", ] def test_buildMarkRecord(self): rec = builder.buildMarkRecord(17, builder.buildAnchor(500, -20)) assert getXML(rec.toXML) == [ "<MarkRecord>", ' <Class value="17"/>', ' <MarkAnchor Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </MarkAnchor>", "</MarkRecord>", ] def test_buildMark2Record(self): a = builder.buildAnchor rec = builder.buildMark2Record([a(500, -20), None, a(300, -15)]) assert getXML(rec.toXML) == [ "<Mark2Record>", ' <Mark2Anchor index="0" Format="1">', ' <XCoordinate value="500"/>', ' <YCoordinate value="-20"/>', " </Mark2Anchor>", ' <Mark2Anchor index="1" empty="1"/>', ' <Mark2Anchor index="2" Format="1">', ' <XCoordinate value="300"/>', ' <YCoordinate value="-15"/>', " </Mark2Anchor>", "</Mark2Record>", ] def test_buildPairPosClassesSubtable(self): d20 = builder.buildValue({"XPlacement": -20}) d50 = builder.buildValue({"XPlacement": -50}) d0 = builder.buildValue({}) d8020 = builder.buildValue({"XPlacement": -80, "YPlacement": -20}) subtable = builder.buildPairPosClassesSubtable( { (tuple("A"), tuple(["zero"])): (d0, d50), (tuple("A"), tuple(["one", "two"])): (None, d20), (tuple(["B", "C"]), tuple(["zero"])): (d8020, d50), }, self.GLYPHMAP, ) assert getXML(subtable.toXML) == [ '<PairPos Format="2">', " <Coverage>", ' <Glyph value="A"/>', ' <Glyph value="B"/>', ' <Glyph value="C"/>', " </Coverage>", ' <ValueFormat1 value="3"/>', ' <ValueFormat2 value="1"/>', " <ClassDef1>", ' <ClassDef glyph="A" class="1"/>', " </ClassDef1>", " <ClassDef2>", ' <ClassDef glyph="one" class="1"/>', ' <ClassDef glyph="two" class="1"/>', ' <ClassDef glyph="zero" class="2"/>', " </ClassDef2>", " <!-- Class1Count=2 -->", " <!-- Class2Count=3 -->", ' <Class1Record index="0">', ' <Class2Record index="0">', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="0"/>', " </Class2Record>", ' <Class2Record index="1">', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="0"/>', " </Class2Record>", ' <Class2Record index="2">', ' <Value1 XPlacement="-80" YPlacement="-20"/>', ' <Value2 XPlacement="-50"/>', " </Class2Record>", " </Class1Record>", ' <Class1Record index="1">', ' <Class2Record index="0">', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="0"/>', " </Class2Record>", ' <Class2Record index="1">', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="-20"/>', " </Class2Record>", ' <Class2Record index="2">', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="-50"/>', " </Class2Record>", " </Class1Record>", "</PairPos>", ] def test_buildPairPosGlyphs(self): d50 = builder.buildValue({"XPlacement": -50}) d8020 = builder.buildValue({"XPlacement": -80, "YPlacement": -20}) subtables = builder.buildPairPosGlyphs( {("A", "zero"): (None, d50), ("A", "one"): (d8020, d50)}, self.GLYPHMAP ) assert sum([getXML(t.toXML) for t in subtables], []) == [ '<PairPos Format="1">', " <Coverage>", ' <Glyph value="A"/>', " </Coverage>", ' <ValueFormat1 value="0"/>', ' <ValueFormat2 value="1"/>', " <!-- PairSetCount=1 -->", ' <PairSet index="0">', " <!-- PairValueCount=1 -->", ' <PairValueRecord index="0">', ' <SecondGlyph value="zero"/>', ' <Value2 XPlacement="-50"/>', " </PairValueRecord>", " </PairSet>", "</PairPos>", '<PairPos Format="1">', " <Coverage>", ' <Glyph value="A"/>', " </Coverage>", ' <ValueFormat1 value="3"/>', ' <ValueFormat2 value="1"/>', " <!-- PairSetCount=1 -->", ' <PairSet index="0">', " <!-- PairValueCount=1 -->", ' <PairValueRecord index="0">', ' <SecondGlyph value="one"/>', ' <Value1 XPlacement="-80" YPlacement="-20"/>', ' <Value2 XPlacement="-50"/>', " </PairValueRecord>", " </PairSet>", "</PairPos>", ] def test_buildPairPosGlyphsSubtable(self): d20 = builder.buildValue({"XPlacement": -20}) d50 = builder.buildValue({"XPlacement": -50}) d0 = builder.buildValue({}) d8020 = builder.buildValue({"XPlacement": -80, "YPlacement": -20}) subtable = builder.buildPairPosGlyphsSubtable( { ("A", "zero"): (d0, d50), ("A", "one"): (None, d20), ("B", "five"): (d8020, d50), }, self.GLYPHMAP, ) assert getXML(subtable.toXML) == [ '<PairPos Format="1">', " <Coverage>", ' <Glyph value="A"/>', ' <Glyph value="B"/>', " </Coverage>", ' <ValueFormat1 value="3"/>', ' <ValueFormat2 value="1"/>', " <!-- PairSetCount=2 -->", ' <PairSet index="0">', " <!-- PairValueCount=2 -->", ' <PairValueRecord index="0">', ' <SecondGlyph value="zero"/>', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="-50"/>', " </PairValueRecord>", ' <PairValueRecord index="1">', ' <SecondGlyph value="one"/>', ' <Value1 XPlacement="0" YPlacement="0"/>', ' <Value2 XPlacement="-20"/>', " </PairValueRecord>", " </PairSet>", ' <PairSet index="1">', " <!-- PairValueCount=1 -->", ' <PairValueRecord index="0">', ' <SecondGlyph value="five"/>', ' <Value1 XPlacement="-80" YPlacement="-20"/>', ' <Value2 XPlacement="-50"/>', " </PairValueRecord>", " </PairSet>", "</PairPos>", ] def test_buildSinglePos(self): subtables = builder.buildSinglePos( { "one": builder.buildValue({"XPlacement": 500}), "two": builder.buildValue({"XPlacement": 500}), "three": builder.buildValue({"XPlacement": 200}), "four": builder.buildValue({"XPlacement": 400}), "five": builder.buildValue({"XPlacement": 500}), "six": builder.buildValue({"YPlacement": -6}), }, self.GLYPHMAP, ) assert sum([getXML(t.toXML) for t in subtables], []) == [ '<SinglePos Format="2">', " <Coverage>", ' <Glyph value="one"/>', ' <Glyph value="two"/>', ' <Glyph value="three"/>', ' <Glyph value="four"/>', ' <Glyph value="five"/>', " </Coverage>", ' <ValueFormat value="1"/>', " <!-- ValueCount=5 -->", ' <Value index="0" XPlacement="500"/>', ' <Value index="1" XPlacement="500"/>', ' <Value index="2" XPlacement="200"/>', ' <Value index="3" XPlacement="400"/>', ' <Value index="4" XPlacement="500"/>', "</SinglePos>", '<SinglePos Format="1">', " <Coverage>", ' <Glyph value="six"/>', " </Coverage>", ' <ValueFormat value="2"/>', ' <Value YPlacement="-6"/>', "</SinglePos>", ] def test_buildSinglePos_ValueFormat0(self): subtables = builder.buildSinglePos( {"zero": builder.buildValue({})}, self.GLYPHMAP ) assert sum([getXML(t.toXML) for t in subtables], []) == [ '<SinglePos Format="1">', " <Coverage>", ' <Glyph value="zero"/>', " </Coverage>", ' <ValueFormat value="0"/>', "</SinglePos>", ] def test_buildSinglePosSubtable_format1(self): subtable = builder.buildSinglePosSubtable( { "one": builder.buildValue({"XPlacement": 777}), "two": builder.buildValue({"XPlacement": 777}), }, self.GLYPHMAP, ) assert getXML(subtable.toXML) == [ '<SinglePos Format="1">', " <Coverage>", ' <Glyph value="one"/>', ' <Glyph value="two"/>', " </Coverage>", ' <ValueFormat value="1"/>', ' <Value XPlacement="777"/>', "</SinglePos>", ] def test_buildSinglePosSubtable_format2(self): subtable = builder.buildSinglePosSubtable( { "one": builder.buildValue({"XPlacement": 777}), "two": builder.buildValue({"YPlacement": -888}), }, self.GLYPHMAP, ) assert getXML(subtable.toXML) == [ '<SinglePos Format="2">', " <Coverage>", ' <Glyph value="one"/>', ' <Glyph value="two"/>', " </Coverage>", ' <ValueFormat value="3"/>', " <!-- ValueCount=2 -->", ' <Value index="0" XPlacement="777" YPlacement="0"/>', ' <Value index="1" XPlacement="0" YPlacement="-888"/>', "</SinglePos>", ] def test_buildValue(self): value = builder.buildValue({"XPlacement": 7, "YPlacement": 23}) func = lambda writer, font: value.toXML(writer, font, valueName="Val") assert getXML(func) == ['<Val XPlacement="7" YPlacement="23"/>'] def test_getLigatureKey(self): components = lambda s: [tuple(word) for word in s.split()] c = components("fi fl ff ffi fff") c.sort(key=builder._getLigatureKey) assert c == components("fff ffi ff fi fl") def test_getSinglePosValueKey(self): device = builder.buildDevice({10: 1, 11: 3}) a1 = builder.buildValue({"XPlacement": 500, "XPlaDevice": device}) a2 = builder.buildValue({"XPlacement": 500, "XPlaDevice": device}) b = builder.buildValue({"XPlacement": 500}) keyA1 = builder._getSinglePosValueKey(a1) keyA2 = builder._getSinglePosValueKey(a1) keyB = builder._getSinglePosValueKey(b) assert keyA1 == keyA2 assert hash(keyA1) == hash(keyA2) assert keyA1 != keyB assert hash(keyA1) != hash(keyB) class ClassDefBuilderTest(object): def test_build_usingClass0(self): b = builder.ClassDefBuilder(useClass0=True) b.add({"aa", "bb"}) b.add({"a", "b"}) b.add({"c"}) b.add({"e", "f", "g", "h"}) cdef = b.build() assert isinstance(cdef, otTables.ClassDef) assert cdef.classDefs == {"a": 2, "b": 2, "c": 3, "aa": 1, "bb": 1} def test_build_notUsingClass0(self): b = builder.ClassDefBuilder(useClass0=False) b.add({"a", "b"}) b.add({"c"}) b.add({"e", "f", "g", "h"}) cdef = b.build() assert isinstance(cdef, otTables.ClassDef) assert cdef.classDefs == { "a": 2, "b": 2, "c": 3, "e": 1, "f": 1, "g": 1, "h": 1, } def test_canAdd(self): b = builder.ClassDefBuilder(useClass0=True) b.add({"a", "b", "c", "d"}) b.add({"e", "f"}) assert b.canAdd({"a", "b", "c", "d"}) assert b.canAdd({"e", "f"}) assert b.canAdd({"g", "h", "i"}) assert not b.canAdd({"b", "c", "d"}) assert not b.canAdd({"a", "b", "c", "d", "e", "f"}) assert not b.canAdd({"d", "e", "f"}) assert not b.canAdd({"f"}) def test_add_exception(self): b = builder.ClassDefBuilder(useClass0=True) b.add({"a", "b", "c"}) with pytest.raises(error.OpenTypeLibError): b.add({"a", "d"}) buildStatTable_test_data = [ ([ dict( tag="wght", name="Weight", values=[ dict(value=100, name='Thin'), dict(value=400, name='Regular', flags=0x2), dict(value=900, name='Black')])], None, "Regular", [ ' <STAT>', ' <Version value="0x00010001"/>', ' <DesignAxisRecordSize value="8"/>', ' <!-- DesignAxisCount=1 -->', ' <DesignAxisRecord>', ' <Axis index="0">', ' <AxisTag value="wght"/>', ' <AxisNameID value="257"/> <!-- Weight -->', ' <AxisOrdering value="0"/>', ' </Axis>', ' </DesignAxisRecord>', ' <!-- AxisValueCount=3 -->', ' <AxisValueArray>', ' <AxisValue index="0" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="258"/> <!-- Thin -->', ' <Value value="100.0"/>', ' </AxisValue>', ' <AxisValue index="1" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="2"/> <!-- ElidableAxisValueName -->', ' <ValueNameID value="256"/> <!-- Regular -->', ' <Value value="400.0"/>', ' </AxisValue>', ' <AxisValue index="2" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="259"/> <!-- Black -->', ' <Value value="900.0"/>', ' </AxisValue>', ' </AxisValueArray>', ' <ElidedFallbackNameID value="256"/> <!-- Regular -->', ' </STAT>']), ([ dict( tag="wght", name=dict(en="Weight", nl="Gewicht"), values=[ dict(value=100, name=dict(en='Thin', nl='Dun')), dict(value=400, name='Regular', flags=0x2), dict(value=900, name='Black'), ]), dict( tag="wdth", name="Width", values=[ dict(value=50, name='Condensed'), dict(value=100, name='Regular', flags=0x2), dict(value=200, name='Extended')])], None, 2, [ ' <STAT>', ' <Version value="0x00010001"/>', ' <DesignAxisRecordSize value="8"/>', ' <!-- DesignAxisCount=2 -->', ' <DesignAxisRecord>', ' <Axis index="0">', ' <AxisTag value="wght"/>', ' <AxisNameID value="256"/> <!-- Weight -->', ' <AxisOrdering value="0"/>', ' </Axis>', ' <Axis index="1">', ' <AxisTag value="wdth"/>', ' <AxisNameID value="260"/> <!-- Width -->', ' <AxisOrdering value="1"/>', ' </Axis>', ' </DesignAxisRecord>', ' <!-- AxisValueCount=6 -->', ' <AxisValueArray>', ' <AxisValue index="0" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="257"/> <!-- Thin -->', ' <Value value="100.0"/>', ' </AxisValue>', ' <AxisValue index="1" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="2"/> <!-- ElidableAxisValueName -->', ' <ValueNameID value="258"/> <!-- Regular -->', ' <Value value="400.0"/>', ' </AxisValue>', ' <AxisValue index="2" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="259"/> <!-- Black -->', ' <Value value="900.0"/>', ' </AxisValue>', ' <AxisValue index="3" Format="1">', ' <AxisIndex value="1"/>', ' <Flags value="0"/>', ' <ValueNameID value="261"/> <!-- Condensed -->', ' <Value value="50.0"/>', ' </AxisValue>', ' <AxisValue index="4" Format="1">', ' <AxisIndex value="1"/>', ' <Flags value="2"/> <!-- ElidableAxisValueName -->', ' <ValueNameID value="258"/> <!-- Regular -->', ' <Value value="100.0"/>', ' </AxisValue>', ' <AxisValue index="5" Format="1">', ' <AxisIndex value="1"/>', ' <Flags value="0"/>', ' <ValueNameID value="262"/> <!-- Extended -->', ' <Value value="200.0"/>', ' </AxisValue>', ' </AxisValueArray>', ' <ElidedFallbackNameID value="2"/> <!-- missing from name table -->', ' </STAT>']), ([ dict( tag="wght", name="Weight", values=[ dict(value=400, name='Regular', flags=0x2), dict(value=600, linkedValue=650, name='Bold')])], None, 18, [ ' <STAT>', ' <Version value="0x00010001"/>', ' <DesignAxisRecordSize value="8"/>', ' <!-- DesignAxisCount=1 -->', ' <DesignAxisRecord>', ' <Axis index="0">', ' <AxisTag value="wght"/>', ' <AxisNameID value="256"/> <!-- Weight -->', ' <AxisOrdering value="0"/>', ' </Axis>', ' </DesignAxisRecord>', ' <!-- AxisValueCount=2 -->', ' <AxisValueArray>', ' <AxisValue index="0" Format="1">', ' <AxisIndex value="0"/>', ' <Flags value="2"/> <!-- ElidableAxisValueName -->', ' <ValueNameID value="257"/> <!-- Regular -->', ' <Value value="400.0"/>', ' </AxisValue>', ' <AxisValue index="1" Format="3">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="258"/> <!-- Bold -->', ' <Value value="600.0"/>', ' <LinkedValue value="650.0"/>', ' </AxisValue>', ' </AxisValueArray>', ' <ElidedFallbackNameID value="18"/> <!-- missing from name table -->', ' </STAT>']), ([ dict( tag="opsz", name="Optical Size", values=[ dict(nominalValue=6, rangeMaxValue=10, name='Small'), dict(rangeMinValue=10, nominalValue=14, rangeMaxValue=24, name='Text', flags=0x2), dict(rangeMinValue=24, nominalValue=600, name='Display')])], None, 2, [ ' <STAT>', ' <Version value="0x00010001"/>', ' <DesignAxisRecordSize value="8"/>', ' <!-- DesignAxisCount=1 -->', ' <DesignAxisRecord>', ' <Axis index="0">', ' <AxisTag value="opsz"/>', ' <AxisNameID value="256"/> <!-- Optical Size -->', ' <AxisOrdering value="0"/>', ' </Axis>', ' </DesignAxisRecord>', ' <!-- AxisValueCount=3 -->', ' <AxisValueArray>', ' <AxisValue index="0" Format="2">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="257"/> <!-- Small -->', ' <NominalValue value="6.0"/>', ' <RangeMinValue value="-32768.0"/>', ' <RangeMaxValue value="10.0"/>', ' </AxisValue>', ' <AxisValue index="1" Format="2">', ' <AxisIndex value="0"/>', ' <Flags value="2"/> <!-- ElidableAxisValueName -->', ' <ValueNameID value="258"/> <!-- Text -->', ' <NominalValue value="14.0"/>', ' <RangeMinValue value="10.0"/>', ' <RangeMaxValue value="24.0"/>', ' </AxisValue>', ' <AxisValue index="2" Format="2">', ' <AxisIndex value="0"/>', ' <Flags value="0"/>', ' <ValueNameID value="259"/> <!-- Display -->', ' <NominalValue value="600.0"/>', ' <RangeMinValue value="24.0"/>', ' <RangeMaxValue value="32767.99998"/>', ' </AxisValue>', ' </AxisValueArray>', ' <ElidedFallbackNameID value="2"/> <!-- missing from name table -->', ' </STAT>']), ([ dict( tag="wght", name="Weight", ordering=1, values=[]), dict( tag="ABCD", name="ABCDTest", ordering=0, values=[ dict(value=100, name="Regular", flags=0x2)])], [dict(location=dict(wght=300, ABCD=100), name='Regular ABCD')], 18, [ ' <STAT>', ' <Version value="0x00010002"/>', ' <DesignAxisRecordSize value="8"/>', ' <!-- DesignAxisCount=2 -->', ' <DesignAxisRecord>', ' <Axis index="0">', ' <AxisTag value="wght"/>', ' <AxisNameID value="256"/> <!-- Weight -->', ' <AxisOrdering value="1"/>', ' </Axis>', ' <Axis index="1">', ' <AxisTag value="ABCD"/>', ' <AxisNameID value="257"/> <!-- ABCDTest -->', ' <AxisOrdering value="0"/>', ' </Axis>', ' </DesignAxisRecord>', ' <!-- AxisValueCount=2 -->', ' <AxisValueArray>', ' <AxisValue index="0" Format="4">', ' <!-- AxisCount=2 -->', ' <Flags value="0"/>', ' <ValueNameID value="259"/> <!-- Regular ABCD -->', ' <AxisValueRecord index="0">', ' <AxisIndex value="0"/>', ' <Value value="300.0"/>', ' </AxisValueRecord>', ' <AxisValueRecord index="1">', ' <AxisIndex value="1"/>', ' <Value value="100.0"/>', ' </AxisValueRecord>', ' </AxisValue>', ' <AxisValue index="1" Format="1">', ' <AxisIndex value="1"/>', ' <Flags value="2"/> <!-- ElidableAxisValueName -->', ' <ValueNameID value="258"/> <!-- Regular -->', ' <Value value="100.0"/>', ' </AxisValue>', ' </AxisValueArray>', ' <ElidedFallbackNameID value="18"/> <!-- missing from name table -->', ' </STAT>']), ] @pytest.mark.parametrize("axes, axisValues, elidedFallbackName, expected_ttx", buildStatTable_test_data) def test_buildStatTable(axes, axisValues, elidedFallbackName, expected_ttx): font = ttLib.TTFont() font["name"] = ttLib.newTable("name") font["name"].names = [] font["name"].addMultilingualName(dict(en="ABCDTest"), nameID=6) builder.buildStatTable(font, axes, axisValues, elidedFallbackName) f = io.StringIO() font.saveXML(f, tables=["STAT"]) ttx = f.getvalue().splitlines() ttx = ttx[3:-2] assert expected_ttx == ttx f = io.BytesIO() font.save(f) font = ttLib.TTFont(f) f = io.StringIO() font.saveXML(f, tables=["STAT"]) ttx = f.getvalue().splitlines() ttx = ttx[3:-2] assert expected_ttx == ttx def test_stat_infinities(): negInf = floatToFixed(builder.AXIS_VALUE_NEGATIVE_INFINITY, 16) assert struct.pack(">l", negInf) == b"\x80\x00\x00\x00" posInf = floatToFixed(builder.AXIS_VALUE_POSITIVE_INFINITY, 16) assert struct.pack(">l", posInf) == b"\x7f\xff\xff\xff" class ChainContextualRulesetTest(object): def test_makeRulesets(self): font = ttLib.TTFont() font.setGlyphOrder(["a","b","c","d","A","B","C","D","E"]) sb = builder.ChainContextSubstBuilder(font, None) prefix, input_, suffix, lookups = [["a"], ["b"]], [["c"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) prefix, input_, suffix, lookups = [["a"], ["d"]], [["c"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) sb.add_subtable_break(None) prefix, input_, suffix, lookups = [["A"]], [["E"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) prefix, input_, suffix, lookups = [["A"]], [["C","D"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) prefix, input_, suffix, lookups = [["A", "B"]], [["E"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) sb.add_subtable_break(None) prefix, input_, suffix, lookups = [], [["E"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) prefix, input_, suffix, lookups = [], [["C","D"]], [], [None] sb.rules.append(builder.ChainContextualRule(prefix, input_, suffix, lookups)) rulesets = sb.rulesets() assert len(rulesets) == 3 assert rulesets[0].hasPrefixOrSuffix assert not rulesets[0].hasAnyGlyphClasses cd = rulesets[0].format2ClassDefs() assert set(cd[0].classes()[1:]) == set([("d",),("b",),("a",)]) assert set(cd[1].classes()[1:]) == set([("c",)]) assert set(cd[2].classes()[1:]) == set() assert rulesets[1].hasPrefixOrSuffix assert rulesets[1].hasAnyGlyphClasses assert not rulesets[1].format2ClassDefs() assert not rulesets[2].hasPrefixOrSuffix assert rulesets[2].hasAnyGlyphClasses assert rulesets[2].format2ClassDefs() cd = rulesets[2].format2ClassDefs() assert set(cd[0].classes()[1:]) == set() assert set(cd[1].classes()[1:]) == set([("C","D"), ("E",)]) assert set(cd[2].classes()[1:]) == set() if __name__ == "__main__": import sys sys.exit(pytest.main(sys.argv))
true
true
1c2c33b94326f7fadbce2d5da8d21dea6a03aecb
29,473
py
Python
io_scene_gmdc/export_gmdc.py
actioninja/blender-gmdc
2de19b9f50efea8ce794f928d06cb1660f2c576d
[ "MIT" ]
null
null
null
io_scene_gmdc/export_gmdc.py
actioninja/blender-gmdc
2de19b9f50efea8ce794f928d06cb1660f2c576d
[ "MIT" ]
null
null
null
io_scene_gmdc/export_gmdc.py
actioninja/blender-gmdc
2de19b9f50efea8ce794f928d06cb1660f2c576d
[ "MIT" ]
null
null
null
#!BPY """ Name: 'GMDC (.gmdc)' Blender: 249 Group: 'Export' Tooltip: 'Export to TS2 GMDC file' """ # ------------------------------------------------------------------------------- # Copyright (C) 2016 DjAlex88 (https://github.com/djalex88/) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ------------------------------------------------------------------------------- import os from struct import pack from io_scene_gmdc.gmdc_tools import * from itertools import count, repeat import bpy from mathutils import Vector as BlenderVector ######################################## ## Exporter ######################################## def prepare_geometry(settings): scene = bpy.data.scenes.active # get all mesh objects objects = filter(lambda obj: obj.type == 'Mesh', scene.objects) # check whether visual transforms applied v = [obj for obj in objects if tuple(obj.rot) != (0, 0, 0) or tuple(obj.size) != (1, 1, 1)] if v: error('Error! The following mesh ' + ( 'objects have' if len(v) > 1 else 'object has') + ' non-applied visual transforms:') for obj in v: error('\x20\x20%s -> rot: %s, size: %s' % (str(obj), str(obj.rot), str(obj.size))) error('Solution: apply visual transforms (Ctrl+A).') return False if settings['export_bmesh']: # does bounding mesh exist? v = [i for i, obj in enumerate(objects) if obj.name == settings['bmesh_name']] if not v: error('Error! Could not find bounding mesh.') return False # remove from objects del objects[v[0]] if not objects: error('Error! Object list is empty.') return False # # inverse transforms # inverse_transforms = None if settings['export_rigging']: if scene.properties.has_key('gmdc_inverse_transforms'): v = tuple(scene.properties['gmdc_inverse_transforms']) assert len(v) % 7 == 0 v = [chunk(t, 4) for t in chunk(v, 7)] inverse_transforms = v else: error('Error! No inverse transforms. (scene.properties["gmdc_inverse_transforms"] is not defined.)') return False # # process main geometry # DATA_GROUPS = []; INDEX_GROUPS = [] MORPH_NAMES = [] # [index] -> name log('Main geometry') for obj in objects: log(str(obj)) # make current object active and activate basic shape key scene.objects.active = obj obj.activeShape = 1 bpy.app.Window.EditMode(1) bpy.app.Window.EditMode(0) mesh = obj.getData(mesh=True) all_vertices = [] # for non-indexed vertices bone_indices = {} # used to enumerate bones { global_bone_index -> local_bone_index } # faces # mesh_faces = mesh.faces if not mesh_faces: error('Error! Mesh object has no faces.') return False # all faces must have texture coordinates try: assert all(face.uv for face in mesh_faces) except: error('Error! Mesh object has faces with no texture coordinates.') return False # tangents if settings['export_tangents']: mesh_tangents = [[tuple(x.xyz) for x in tangents] for tangents in mesh.getTangents()] else: mesh_tangents = repeat((None, None, None, None)) # no tangents obj_loc = obj.matrix[3].xyz # rigging rigging = settings['export_rigging'] for face, tangents in zip(mesh_faces, mesh_tangents): verts = [tuple((v.co + obj_loc).xyz) for v in face.verts] norms = [tuple(v.no.xyz) for v in face.verts] if face.smooth else [tuple(face.no.xyz)] * len(verts) uv = [(t.x, 1.0 - t.y) for t in face.uv] # OpenGL -> Direct3D if rigging: bones = [] weights = [] for v in face.verts: v_groups = mesh.getVertexInfluences(v.index) b = tuple() w = tuple() for name, f in v_groups: # get bone index s = name.split('#') try: assert f > 0.0 idx = int(s[-1]) if len(s) < 2 or idx < 0: raise Exception() except AssertionError: pass except: log( 'Warning! Could not extract bone index from vertex group name "%s". Influence on vertex # %i ignored.' % ( name, v.index)) else: k = bone_indices.get(idx) if k == None: k = len(bone_indices) bone_indices[idx] = k b += (k,) w += (f,) if len(b) > 4: error('Error! Vertex # %i of mesh object "%s" is in more that 4 vertex groups.' % ( v.index, obj.name)) return False # normalize weights f = sum(w) if f > 0.0001: w = tuple(x / f for x in w) else: w = tuple(0.0 for x in w) # ? bones.append(b) weights.append(w) else: bones = [(), (), (), ()] weights = [(), (), (), ()] # triangulate (if needed) if len(face.verts) == 4: order = (0, 1, 2, 0, 2, 3) verts = [verts[i] for i in order] norms = [norms[i] for i in order] uv = [uv[i] for i in order] bones = [bones[i] for i in order] weights = [weights[i] for i in order] tangents = [tangents[i] for i in order] # add vertices to list all_vertices += zip(verts, norms, uv, bones, weights, tangents) # <- faces mesh_tangents = None # # morphs / vertex animations # morphing = settings['export_morphs'] and mesh.key and len(mesh.key.blocks) > 1 if morphing: morphing = settings['export_morphs'] # 1 - dVerts only; 2 - dVerts & dNorms log('--Processing shape keys...') mesh_morphs = [] # current mesh morphs first_new_morph_index = None # first new morph that is not present in MORPH_NAMES dVerts = [] dNorms = [] # compute differences for k, key_block in enumerate(mesh.key.blocks[1:], 2): name = tuple(key_block.name.strip().split('::')) if len(name) != 2: error('Error! Invalid morph name: "%s"' % '::'.join(name)) return False try: j = MORPH_NAMES.index(name) except ValueError: # new morph j = len(MORPH_NAMES) MORPH_NAMES.append(name) if first_new_morph_index == None: first_new_morph_index = j mesh_morphs.append(j) log('--Key "%s" (%i)' % (name, k)) # activate morph obj.activeShape = k bpy.app.Window.EditMode(1) bpy.app.Window.EditMode(0) key_block_verts = key_block.getData() # add difference arrays dv = []; dVerts.append(dv) dn = []; dNorms.append(dn) # loop through all faces and compute vertex differences j = 0 for face in mesh_faces: verts = [(key_block_verts[v.index] + obj_loc) for v in face.verts] norms = [v.no for v in face.verts] if face.smooth else [face.no] * len(verts) if len(face.verts) == 4: order = (0, 1, 2, 0, 2, 3) verts = [verts[i] for i in order] norms = [norms[i] for i in order] for v, w in zip(verts, norms): dv.append(tuple((v - BlenderVector(all_vertices[j][0])).xyz)) dn.append(tuple((w - BlenderVector(all_vertices[j][1])).xyz)) j += 1 assert j == len(all_vertices) log('--Packing...') k = len(all_vertices) keys = [[] for i in range(k)] if morphing == 2: # vertices and normals v = [[] for i in range(k)] w = [[] for i in range(k)] for i, dv, dn in zip(mesh_morphs, dVerts, dNorms): # loop through all difference arrays (morphs) for x, y, k, a, b in zip(dv, dn, keys, v, w): if x != (0.0, 0.0, 0.0) or y != (0.0, 0.0, 0.0): # vertex affected if len(k) == 4: error('Error! Some vertices are affected by more than 4 morphs (shape keys).') return False # morph index k.append(i) # difference a.append(x) b.append(y) dVerts = v; v = None dNorms = w; w = None else: # vertices only v = [[] for i in range(k)] for i, dv in zip(mesh_morphs, dVerts): for x, k, a in zip(dv, keys, v): if x != (0.0, 0.0, 0.0): if len(k) == 4: error('Error! Some vertices are affected by more than 4 morphs (shape keys).') return False # morph index k.append(i) # difference a.append(x) dVerts = v; v = None assert len(dVerts) == len(all_vertices) if not any(keys): log('--Differeces between shape keys of mesh object "%s" were not detected.' % obj.name) morphing = False if first_new_morph_index != None: del MORPH_NAMES[first_new_morph_index:] # remove newly added morph names else: keys = map(tuple, keys) j = max(len(v) for v in dVerts) # number of difference arrays log('--Number of arrays:', j) dVerts = [(tuple(dv) + ((0.0, 0.0, 0.0),) * 4)[:j] for dv in dVerts] # align if morphing == 2: dNorms = [(tuple(dn) + ((0.0, 0.0, 0.0),) * 4)[:j] for dn in dNorms] for i, k, dv, dn in zip(count(), keys, dVerts, dNorms): all_vertices[i] += (k, dv, dn) else: for i, k, dv in zip(count(), keys, dVerts): all_vertices[i] += (k, dv) dVerts = dNorms = None; keys = None # <- morphing # # index geometry # log('--Indexing geometry...') unique_verts = {} # { vertex -> index } indices = [] for vertex in all_vertices: k = unique_verts.setdefault(vertex, len(unique_verts)) indices.append(k) unique_verts = [v for v, i in sorted(unique_verts.iteritems(), key=lambda x: x[1])] log('\x20\x20--Vertex count: %i -> %i' % (len(all_vertices), len(unique_verts))) del all_vertices V, N, T, B, W, X, K, dV, dN = map(list, zip(*unique_verts)) + ( [None, None, None] if not morphing else [None] * (2 - morphing)) del unique_verts # # add new data group or extend an existing one # # does the mesh have rigging data ? rigging = rigging and any(B) # try to find a suitable data group group = None for i, g in enumerate(DATA_GROUPS): b1 = bool(g.bones) == rigging if morphing: b2 = sum(bool(x) for x in g.dVerts) == len(dV[0]) # same number of difference arrays else: b2 = not bool(g.dVerts[0]) # no difference arrays if b1 and b2: # found ref_group, group = i, g break if group: k = group.count indices = map(lambda x: x + k, indices) # shift indices log('--Extending group # %i...' % ref_group) else: ref_group = len(DATA_GROUPS) group = DataGroup(); DATA_GROUPS.append(group) log('--Adding new group # %i...' % ref_group) # add vertices to group # group.vertices.extend(V) group.normals.extend(N) group.tex_coords.extend(T) if rigging: group.bones.extend(B) group.weights.extend(W) if settings['export_tangents']: group.tangents.extend(X) if morphing: group.keys.extend(K) dV = map(list, zip(*dV)) + [[], [], []] for v, w in zip(group.dVerts, dV): v.extend(w) if morphing > 1: dN = map(list, zip(*dN)) + [[], [], []] for v, w in zip(group.dNorms, dV): v.extend(w) del V, N, T, B, W, X, K, dV, dN k = group.count group.count = len(group.vertices) log('\x20\x20--Vertex count:', '%i -> %i' % (k, group.count) if k else group.count) # # create index group # # name name = obj.name if settings['use_obj_props']: try: x = obj.getProperty('name') assert x.type == 'STRING' and x.data != '' except AssertionError: log('Warning! Invalid data for property "name". Ignored.') except: pass else: name = x.data log('--Creating new index group # %i, "%s" (triangles: %i)...' % (len(INDEX_GROUPS), name, len(indices) / 3)) group = IndexGroup(name); INDEX_GROUPS.append(group) group.data_group_index = ref_group group.indices = chunk(tuple(indices), 3) # triangles indices = None # flags if settings['use_obj_props']: x = None try: x = obj.getProperty('flags') try: assert x.type == 'STRING' x = int(x.data, 16) log('--Flags:', to_hex(pack('<L', x))) except: x = None log('Warning! Invalid data for property "flags". Ignored.') else: group.flags = x except: # property not found pass # bone index mapping if rigging: # order items by local bone index bone_indices = sorted(bone_indices.iteritems(), None, key=lambda x: x[1]) # put global indices group.bones = [] for idx, j in bone_indices: if idx >= len(inverse_transforms): error('Error! No inverse transform for bone # %i.' % idx) return False group.bones.append(idx) bone_indices = None # <- objects # # bounding geometry # static_bmesh = None; dynamic_bmesh = None if settings['export_bmesh']: bmesh_obj = bpy.app.Object.Get(settings['bmesh_name']) mesh = bmesh_obj.getData(mesh=True) obj_loc = bmesh_obj.matrix[3].xyz log('Bounding mesh object %s:' % bmesh_obj) if settings['export_rigging']: dynamic_bmesh = [] v_groups = {} # { bone_index -> v_group_name } for name in mesh.getVertGroupNames(): # get bone index s = name.split('#') try: idx = int(s[-1]) if len(s) < 2 or idx < 0: raise Exception() except: error('Error! Could not extract bone index from vertex group name "%s".' % name) return False v_groups[idx] = name for idx in range(max(v_groups) + 1): if idx in v_groups: indices = set(v[0] for v in mesh.getVertsFromGroup(v_groups[idx], 1) if v[1] > 0.0) # do not accept vertices with weight == 0 I = []; dd = {} for face in mesh.faces: vi = [v.index for v in face.verts] flags = sum(2 ** i for i, j in enumerate(vi) if j in indices) if (flags & 0b0111) == 0b0111: # (0, 1, 2) I.extend([ dd.setdefault(vi[0], len(dd)), dd.setdefault(vi[1], len(dd)), dd.setdefault(vi[2], len(dd))]) if (flags & 0b1101) == 0b1101: # (0, 2, 3) I.extend([ dd.setdefault(vi[0], len(dd)), dd.setdefault(vi[2], len(dd)), dd.setdefault(vi[3], len(dd))]) if dd: V = [] # get inverse transform # if idx >= len(inverse_transforms): error('Error! No inverse transform for bone # %i.' % idx) return False rot, loc = inverse_transforms[idx] t = Transform(loc, rot) dd = sorted(dd.iteritems(), None, key=lambda x: x[1]) # set coords for i, j in dd: # transform coord into bone space a = mesh.verts[i].co.xyz + obj_loc a = t.transformPoint(Vector(a.x, a.y, a.z)).to_tuple() V.append(a) I = chunk(I, 3) dynamic_bmesh.append((V, I)) log('--Part # %02i -> vertices: %i, triangles: %i' % (idx, len(V), len(I))) else: dynamic_bmesh.append(None) else: dynamic_bmesh.append(None) if not any(dynamic_bmesh): dynamic_bmesh = None else: V = [tuple((v.co + obj_loc).xyz) for v in mesh.verts] I = [] for face in mesh.faces: if len(face.verts) == 3: I.append(tuple(v.index for v in face.verts)) else: I.append((face.verts[0].index, face.verts[1].index, face.verts[2].index)) I.append((face.verts[0].index, face.verts[2].index, face.verts[3].index)) static_bmesh = (V, I) log('--Static bounding mesh -> vertices: %i, triangles: %i' % (len(V), len(I))) return GeometryData(DATA_GROUPS, INDEX_GROUPS, inverse_transforms, MORPH_NAMES, static_bmesh, dynamic_bmesh) # ------------------------------------------------------------------------------- # this function does basic checks and initiates the exporter def begin_export(): bpy.app.Window.EditMode(0) settings = { 'SGResource': str_resource_name.val.strip(), 'name_suffix': btn_name_suffix.val, 'export_rigging': btn_export_rigging.val, 'export_tangents': btn_export_tangents.val, 'export_bmesh': btn_export_bmesh.val, 'bmesh_name': str_bmesh_name.val.strip(), 'export_morphs': menu_export_morphs.val, 'use_obj_props': btn_use_obj_props.val, } _save_log = bool(btn_save_log.val) gmdc_filename = str_gmdc_filename.val.strip() if not gmdc_filename: display_menu('Error!', ['Select filename for GMDC file.']); return elif not os.path.basename(gmdc_filename): display_menu('Error!', ['Invalid filename for GMDC file.']); return elif os.path.isfile(gmdc_filename): if display_menu("File '%s' exists. Rewrite?" % os.path.basename(gmdc_filename), ['Yes, rewrite.']) != 0: return if settings['export_bmesh'] and not settings['bmesh_name']: display_menu('Error!', ['Enter bounding mesh\'s object name.']) return # create log file (if needed) if _save_log: s = gmdc_filename + '.export_log.txt' log('Opening log file "%s" for writing... ' % s) try: f = open(s, 'w') except IOError as e: error(e) display_menu('Error!', ['Could not open log file for writing.']) return # Ok set_log_file(f) # # begin export # log('==Geometry Data Container Exporter======') log('GMDC File:', gmdc_filename) log('Settings:') log('--SGResource:', settings['SGResource'] and '"%s"' % settings['SGResource'] or 'none') log('--Name suffix: ', settings['name_suffix']) log('--Export rigging: ', settings['export_rigging']) log('--Export tangents: ', settings['export_tangents']) log('--Export bounding geometry:', settings['export_bmesh']) log('--Bounding mesh name:', settings['bmesh_name'] and '"%s"' % settings['bmesh_name'] or 'none') log('--Export morphs: ', settings['export_morphs']) log('--Use properties: ', settings['use_obj_props']) log() s = settings['SGResource'] if not s: s = os.path.basename(gmdc_filename).split(".") s = ".".join(s[:-1] or s) if settings['name_suffix']: s += '_tslocator_gmdc' log('Preparing geometry...') geometry = None try: geometry = prepare_geometry(settings) except: print_last_exception() if not geometry: display_menu('Error!', ['An error has occured while preparing geometry. See log for details.']) close_log_file() return log() log('Creating GMDC file "%s"... ' % gmdc_filename) try: create_gmdc_file(gmdc_filename, s, geometry) except: print_last_exception() display_menu('Error!', ['An error has occured while creating GMDC file. See log for details.']) else: # Ok log('Finished!') # exit prompt if display_menu("Export complete!", ['Quit']) == 0: bpy.app.Exit() finally: close_log_file() ######################################## # GUI ######################################## def display_menu(caption, items, choice_required=False): b = True while b: choice = bpy.app.PupMenu('%s%%t|' % caption + "|".join('%s%%x%i' % (s, i) for i, s in enumerate(items)), 0x100) b = choice_required and choice < 0 return choice def draw_gui(): global str_gmdc_filename, str_cres_filename, str_resource_name, btn_name_suffix, \ btn_export_tangents, btn_export_rigging, btn_export_bmesh, btn_save_log, \ menu_export_morphs, btn_use_obj_props, str_bmesh_name pos_y = 340; MAX_PATH = 200 # frame Blender.BGL.glColor3f(0.75, 0.75, 0.75) Blender.BGL.glRecti(10, 10, 430, pos_y) pos_y -= 30 # plugin's header s = "GMDC Exporter (TS2)" Blender.BGL.glColor3f(0.8, 0.8, 0.8) Blender.BGL.glRecti(10, pos_y, 430, pos_y + 30) bpy.app.Label(s, 20, pos_y, 400, 30) pos_y -= 30 # GMDC file selector bpy.app.Label("GMDC file (output)", 20, pos_y, 200, 20) pos_y -= 20 bpy.app.BeginAlign() str_gmdc_filename = bpy.app.String("", 0x10, 20, pos_y, 300, 20, str_gmdc_filename.val, MAX_PATH, "Path to GMDC file") bpy.app.PushButton("Select file", 0x11, 320, pos_y, 100, 20, "Open file browser") bpy.app.EndAlign() pos_y -= 35 # geometry name Blender.BGL.glColor3f(0.7, 0.7, 0.7) Blender.BGL.glRecti(20, pos_y - 60, 420, pos_y + 20) bpy.app.Label("SGResource name (optional)", 25, pos_y, 400, 20); pos_y -= 20 bpy.app.Label("If not provided then GMDC filename is used", 25, pos_y, 400, 20); pos_y -= 30 bpy.app.BeginAlign() str_resource_name = bpy.app.String("", 0x50, 70, pos_y, 180, 20, str_resource_name.val, 50, "SGResource name of this geometry") btn_name_suffix = bpy.app.Toggle("_tslocator_gmdc", 0x51, 250, pos_y, 120, 20, btn_name_suffix.val, "Add default suffix") bpy.app.EndAlign() pos_y -= 45 # options bpy.app.BeginAlign() btn_export_rigging = bpy.app.Toggle("Rigging", 0x31, 20, pos_y, 100, 20, btn_export_rigging.val, "Export rigging data (bone indices, weights)") btn_export_tangents = bpy.app.Toggle("Tangents", 0x32, 120, pos_y, 100, 20, btn_export_tangents.val, "Export tangents (required for bump mapping)") btn_export_bmesh = bpy.app.Toggle("Bound. mesh", 0x33, 220, pos_y, 100, 20, btn_export_bmesh.val, "Export bounding geometry") btn_save_log = bpy.app.Toggle("Save log", 0x34, 320, pos_y, 100, 20, btn_save_log.val, "Write script's log data into file *.export_log.txt") bpy.app.EndAlign() pos_y -= 30 bpy.app.BeginAlign() menu_export_morphs = bpy.app.Menu( "Export morphs %t|Do not export morphs %x0|Diff. in v.coords only %x1|Diff. in v.coords and normals %x2", 0x35, 20, pos_y, 200, 20, menu_export_morphs.val) btn_use_obj_props = bpy.app.Toggle("Use object properties", 0x36, 220, pos_y, 200, 20, btn_use_obj_props.val, "Properties can be assigned in logic panel") bpy.app.EndAlign() pos_y -= 30 # bounding mesh name bpy.app.Label("Bounding mesh:", 20, pos_y, 100, 20) str_bmesh_name = bpy.app.String("", 0x40, 120, pos_y, 200, 20, str_bmesh_name.val, 50, "Name of mesh object that will be exported as bounding mesh") pos_y -= 50 # buttons bpy.app.BeginAlign() bpy.app.PushButton("Export", 1, 120, pos_y, 100, 30, "Export geometry (Ctrl + Enter)") bpy.app.PushButton("Exit", 0, 220, pos_y, 100, 30, "Terminate the script (Esc)") bpy.app.EndAlign() # --------------------------------------- # event handlers l_ctrl_key_pressed = 0 r_ctrl_key_pressed = 0 def set_gmdc_filename(filename): global gmdc_filename str_gmdc_filename.val = filename def event_handler(evt, val): global l_ctrl_key_pressed, r_ctrl_key_pressed if evt == bpy.app.ESCKEY and val: bpy.app.Exit() elif evt == bpy.app.LEFTCTRLKEY: l_ctrl_key_pressed = val elif evt == bpy.app.RIGHTCTRLKEY: r_ctrl_key_pressed = val elif evt == bpy.app.RETKEY and val and (l_ctrl_key_pressed or r_ctrl_key_pressed): begin_export() l_ctrl_key_pressed = 0 r_ctrl_key_pressed = 0 def button_events(evt): if evt == 0: bpy.app.Exit() elif evt == 1: begin_export() elif evt == 0x11: bpy.app.Window.FileSelector(set_gmdc_filename, 'Select', bpy.sys.makename(ext='.gmdc')) # ------------------------------------------------------------------------------- # set default values for GUI elements and run event loop str_gmdc_filename = bpy.app.Create("") str_resource_name = bpy.app.Create("") btn_name_suffix = bpy.app.Create(1) btn_export_rigging = bpy.app.Create(0) btn_export_tangents = bpy.app.Create(0) btn_export_bmesh = bpy.app.Create(0) btn_save_log = bpy.app.Create(0) btn_use_obj_props = bpy.app.Create(0) menu_export_morphs = bpy.app.Create(0) str_bmesh_name = bpy.app.Create("b_mesh") bpy.app.Register(draw_gui, event_handler, button_events)
35.212664
138
0.506022
import os from struct import pack from io_scene_gmdc.gmdc_tools import * from itertools import count, repeat import bpy from mathutils import Vector as BlenderVector jects: log(str(obj)) scene.objects.active = obj obj.activeShape = 1 bpy.app.Window.EditMode(1) bpy.app.Window.EditMode(0) mesh = obj.getData(mesh=True) all_vertices = [] bone_indices = {} mesh_faces = mesh.faces if not mesh_faces: error('Error! Mesh object has no faces.') return False try: assert all(face.uv for face in mesh_faces) except: error('Error! Mesh object has faces with no texture coordinates.') return False if settings['export_tangents']: mesh_tangents = [[tuple(x.xyz) for x in tangents] for tangents in mesh.getTangents()] else: mesh_tangents = repeat((None, None, None, None)) obj_loc = obj.matrix[3].xyz rigging = settings['export_rigging'] for face, tangents in zip(mesh_faces, mesh_tangents): verts = [tuple((v.co + obj_loc).xyz) for v in face.verts] norms = [tuple(v.no.xyz) for v in face.verts] if face.smooth else [tuple(face.no.xyz)] * len(verts) uv = [(t.x, 1.0 - t.y) for t in face.uv] if rigging: bones = [] weights = [] for v in face.verts: v_groups = mesh.getVertexInfluences(v.index) b = tuple() w = tuple() for name, f in v_groups: s = name.split('#') try: assert f > 0.0 idx = int(s[-1]) if len(s) < 2 or idx < 0: raise Exception() except AssertionError: pass except: log( 'Warning! Could not extract bone index from vertex group name "%s". Influence on vertex # %i ignored.' % ( name, v.index)) else: k = bone_indices.get(idx) if k == None: k = len(bone_indices) bone_indices[idx] = k b += (k,) w += (f,) if len(b) > 4: error('Error! Vertex # %i of mesh object "%s" is in more that 4 vertex groups.' % ( v.index, obj.name)) return False f = sum(w) if f > 0.0001: w = tuple(x / f for x in w) else: w = tuple(0.0 for x in w) bones.append(b) weights.append(w) else: bones = [(), (), (), ()] weights = [(), (), (), ()] if len(face.verts) == 4: order = (0, 1, 2, 0, 2, 3) verts = [verts[i] for i in order] norms = [norms[i] for i in order] uv = [uv[i] for i in order] bones = [bones[i] for i in order] weights = [weights[i] for i in order] tangents = [tangents[i] for i in order] all_vertices += zip(verts, norms, uv, bones, weights, tangents) mesh_tangents = None morphing = settings['export_morphs'] and mesh.key and len(mesh.key.blocks) > 1 if morphing: morphing = settings['export_morphs'] log('--Processing shape keys...') mesh_morphs = [] first_new_morph_index = None dVerts = [] dNorms = [] for k, key_block in enumerate(mesh.key.blocks[1:], 2): name = tuple(key_block.name.strip().split('::')) if len(name) != 2: error('Error! Invalid morph name: "%s"' % '::'.join(name)) return False try: j = MORPH_NAMES.index(name) except ValueError: j = len(MORPH_NAMES) MORPH_NAMES.append(name) if first_new_morph_index == None: first_new_morph_index = j mesh_morphs.append(j) log('--Key "%s" (%i)' % (name, k)) obj.activeShape = k bpy.app.Window.EditMode(1) bpy.app.Window.EditMode(0) key_block_verts = key_block.getData() dv = []; dVerts.append(dv) dn = []; dNorms.append(dn) j = 0 for face in mesh_faces: verts = [(key_block_verts[v.index] + obj_loc) for v in face.verts] norms = [v.no for v in face.verts] if face.smooth else [face.no] * len(verts) if len(face.verts) == 4: order = (0, 1, 2, 0, 2, 3) verts = [verts[i] for i in order] norms = [norms[i] for i in order] for v, w in zip(verts, norms): dv.append(tuple((v - BlenderVector(all_vertices[j][0])).xyz)) dn.append(tuple((w - BlenderVector(all_vertices[j][1])).xyz)) j += 1 assert j == len(all_vertices) log('--Packing...') k = len(all_vertices) keys = [[] for i in range(k)] if morphing == 2: v = [[] for i in range(k)] w = [[] for i in range(k)] for i, dv, dn in zip(mesh_morphs, dVerts, dNorms): for x, y, k, a, b in zip(dv, dn, keys, v, w): if x != (0.0, 0.0, 0.0) or y != (0.0, 0.0, 0.0): if len(k) == 4: error('Error! Some vertices are affected by more than 4 morphs (shape keys).') return False k.append(i) a.append(x) b.append(y) dVerts = v; v = None dNorms = w; w = None else: v = [[] for i in range(k)] for i, dv in zip(mesh_morphs, dVerts): for x, k, a in zip(dv, keys, v): if x != (0.0, 0.0, 0.0): if len(k) == 4: error('Error! Some vertices are affected by more than 4 morphs (shape keys).') return False k.append(i) a.append(x) dVerts = v; v = None assert len(dVerts) == len(all_vertices) if not any(keys): log('--Differeces between shape keys of mesh object "%s" were not detected.' % obj.name) morphing = False if first_new_morph_index != None: del MORPH_NAMES[first_new_morph_index:] else: keys = map(tuple, keys) j = max(len(v) for v in dVerts) log('--Number of arrays:', j) dVerts = [(tuple(dv) + ((0.0, 0.0, 0.0),) * 4)[:j] for dv in dVerts] if morphing == 2: dNorms = [(tuple(dn) + ((0.0, 0.0, 0.0),) * 4)[:j] for dn in dNorms] for i, k, dv, dn in zip(count(), keys, dVerts, dNorms): all_vertices[i] += (k, dv, dn) else: for i, k, dv in zip(count(), keys, dVerts): all_vertices[i] += (k, dv) dVerts = dNorms = None; keys = None log('--Indexing geometry...') unique_verts = {} indices = [] for vertex in all_vertices: k = unique_verts.setdefault(vertex, len(unique_verts)) indices.append(k) unique_verts = [v for v, i in sorted(unique_verts.iteritems(), key=lambda x: x[1])] log('\x20\x20--Vertex count: %i -> %i' % (len(all_vertices), len(unique_verts))) del all_vertices V, N, T, B, W, X, K, dV, dN = map(list, zip(*unique_verts)) + ( [None, None, None] if not morphing else [None] * (2 - morphing)) del unique_verts rigging = rigging and any(B) group = None for i, g in enumerate(DATA_GROUPS): b1 = bool(g.bones) == rigging if morphing: b2 = sum(bool(x) for x in g.dVerts) == len(dV[0]) else: b2 = not bool(g.dVerts[0]) if b1 and b2: ref_group, group = i, g break if group: k = group.count indices = map(lambda x: x + k, indices) log('--Extending group # %i...' % ref_group) else: ref_group = len(DATA_GROUPS) group = DataGroup(); DATA_GROUPS.append(group) log('--Adding new group # %i...' % ref_group) group.vertices.extend(V) group.normals.extend(N) group.tex_coords.extend(T) if rigging: group.bones.extend(B) group.weights.extend(W) if settings['export_tangents']: group.tangents.extend(X) if morphing: group.keys.extend(K) dV = map(list, zip(*dV)) + [[], [], []] for v, w in zip(group.dVerts, dV): v.extend(w) if morphing > 1: dN = map(list, zip(*dN)) + [[], [], []] for v, w in zip(group.dNorms, dV): v.extend(w) del V, N, T, B, W, X, K, dV, dN k = group.count group.count = len(group.vertices) log('\x20\x20--Vertex count:', '%i -> %i' % (k, group.count) if k else group.count) name = obj.name if settings['use_obj_props']: try: x = obj.getProperty('name') assert x.type == 'STRING' and x.data != '' except AssertionError: log('Warning! Invalid data for property "name". Ignored.') except: pass else: name = x.data log('--Creating new index group # %i, "%s" (triangles: %i)...' % (len(INDEX_GROUPS), name, len(indices) / 3)) group = IndexGroup(name); INDEX_GROUPS.append(group) group.data_group_index = ref_group group.indices = chunk(tuple(indices), 3) indices = None if settings['use_obj_props']: x = None try: x = obj.getProperty('flags') try: assert x.type == 'STRING' x = int(x.data, 16) log('--Flags:', to_hex(pack('<L', x))) except: x = None log('Warning! Invalid data for property "flags". Ignored.') else: group.flags = x except: pass if rigging: bone_indices = sorted(bone_indices.iteritems(), None, key=lambda x: x[1]) group.bones = [] for idx, j in bone_indices: if idx >= len(inverse_transforms): error('Error! No inverse transform for bone # %i.' % idx) return False group.bones.append(idx) bone_indices = None static_bmesh = None; dynamic_bmesh = None if settings['export_bmesh']: bmesh_obj = bpy.app.Object.Get(settings['bmesh_name']) mesh = bmesh_obj.getData(mesh=True) obj_loc = bmesh_obj.matrix[3].xyz log('Bounding mesh object %s:' % bmesh_obj) if settings['export_rigging']: dynamic_bmesh = [] v_groups = {} for name in mesh.getVertGroupNames(): s = name.split('#') try: idx = int(s[-1]) if len(s) < 2 or idx < 0: raise Exception() except: error('Error! Could not extract bone index from vertex group name "%s".' % name) return False v_groups[idx] = name for idx in range(max(v_groups) + 1): if idx in v_groups: indices = set(v[0] for v in mesh.getVertsFromGroup(v_groups[idx], 1) if v[1] > 0.0) I = []; dd = {} for face in mesh.faces: vi = [v.index for v in face.verts] flags = sum(2 ** i for i, j in enumerate(vi) if j in indices) if (flags & 0b0111) == 0b0111: I.extend([ dd.setdefault(vi[0], len(dd)), dd.setdefault(vi[1], len(dd)), dd.setdefault(vi[2], len(dd))]) if (flags & 0b1101) == 0b1101: I.extend([ dd.setdefault(vi[0], len(dd)), dd.setdefault(vi[2], len(dd)), dd.setdefault(vi[3], len(dd))]) if dd: V = [] if idx >= len(inverse_transforms): error('Error! No inverse transform for bone # %i.' % idx) return False rot, loc = inverse_transforms[idx] t = Transform(loc, rot) dd = sorted(dd.iteritems(), None, key=lambda x: x[1]) for i, j in dd: a = mesh.verts[i].co.xyz + obj_loc a = t.transformPoint(Vector(a.x, a.y, a.z)).to_tuple() V.append(a) I = chunk(I, 3) dynamic_bmesh.append((V, I)) log('--Part # %02i -> vertices: %i, triangles: %i' % (idx, len(V), len(I))) else: dynamic_bmesh.append(None) else: dynamic_bmesh.append(None) if not any(dynamic_bmesh): dynamic_bmesh = None else: V = [tuple((v.co + obj_loc).xyz) for v in mesh.verts] I = [] for face in mesh.faces: if len(face.verts) == 3: I.append(tuple(v.index for v in face.verts)) else: I.append((face.verts[0].index, face.verts[1].index, face.verts[2].index)) I.append((face.verts[0].index, face.verts[2].index, face.verts[3].index)) static_bmesh = (V, I) log('--Static bounding mesh -> vertices: %i, triangles: %i' % (len(V), len(I))) return GeometryData(DATA_GROUPS, INDEX_GROUPS, inverse_transforms, MORPH_NAMES, static_bmesh, dynamic_bmesh) def begin_export(): bpy.app.Window.EditMode(0) settings = { 'SGResource': str_resource_name.val.strip(), 'name_suffix': btn_name_suffix.val, 'export_rigging': btn_export_rigging.val, 'export_tangents': btn_export_tangents.val, 'export_bmesh': btn_export_bmesh.val, 'bmesh_name': str_bmesh_name.val.strip(), 'export_morphs': menu_export_morphs.val, 'use_obj_props': btn_use_obj_props.val, } _save_log = bool(btn_save_log.val) gmdc_filename = str_gmdc_filename.val.strip() if not gmdc_filename: display_menu('Error!', ['Select filename for GMDC file.']); return elif not os.path.basename(gmdc_filename): display_menu('Error!', ['Invalid filename for GMDC file.']); return elif os.path.isfile(gmdc_filename): if display_menu("File '%s' exists. Rewrite?" % os.path.basename(gmdc_filename), ['Yes, rewrite.']) != 0: return if settings['export_bmesh'] and not settings['bmesh_name']: display_menu('Error!', ['Enter bounding mesh\'s object name.']) return # create log file (if needed) if _save_log: s = gmdc_filename + '.export_log.txt' log('Opening log file "%s" for writing... ' % s) try: f = open(s, 'w') except IOError as e: error(e) display_menu('Error!', ['Could not open log file for writing.']) return # Ok set_log_file(f) # # begin export # log('==Geometry Data Container Exporter======') log('GMDC File:', gmdc_filename) log('Settings:') log('--SGResource:', settings['SGResource'] and '"%s"' % settings['SGResource'] or 'none') log('--Name suffix: ', settings['name_suffix']) log('--Export rigging: ', settings['export_rigging']) log('--Export tangents: ', settings['export_tangents']) log('--Export bounding geometry:', settings['export_bmesh']) log('--Bounding mesh name:', settings['bmesh_name'] and '"%s"' % settings['bmesh_name'] or 'none') log('--Export morphs: ', settings['export_morphs']) log('--Use properties: ', settings['use_obj_props']) log() s = settings['SGResource'] if not s: s = os.path.basename(gmdc_filename).split(".") s = ".".join(s[:-1] or s) if settings['name_suffix']: s += '_tslocator_gmdc' log('Preparing geometry...') geometry = None try: geometry = prepare_geometry(settings) except: print_last_exception() if not geometry: display_menu('Error!', ['An error has occured while preparing geometry. See log for details.']) close_log_file() return log() log('Creating GMDC file "%s"... ' % gmdc_filename) try: create_gmdc_file(gmdc_filename, s, geometry) except: print_last_exception() display_menu('Error!', ['An error has occured while creating GMDC file. See log for details.']) else: # Ok log('Finished!') # exit prompt if display_menu("Export complete!", ['Quit']) == 0: bpy.app.Exit() finally: close_log_file() ######################################## # GUI ######################################## def display_menu(caption, items, choice_required=False): b = True while b: choice = bpy.app.PupMenu('%s%%t|' % caption + "|".join('%s%%x%i' % (s, i) for i, s in enumerate(items)), 0x100) b = choice_required and choice < 0 return choice def draw_gui(): global str_gmdc_filename, str_cres_filename, str_resource_name, btn_name_suffix, \ btn_export_tangents, btn_export_rigging, btn_export_bmesh, btn_save_log, \ menu_export_morphs, btn_use_obj_props, str_bmesh_name pos_y = 340; MAX_PATH = 200 # frame Blender.BGL.glColor3f(0.75, 0.75, 0.75) Blender.BGL.glRecti(10, 10, 430, pos_y) pos_y -= 30 # plugin's header s = "GMDC Exporter (TS2)" Blender.BGL.glColor3f(0.8, 0.8, 0.8) Blender.BGL.glRecti(10, pos_y, 430, pos_y + 30) bpy.app.Label(s, 20, pos_y, 400, 30) pos_y -= 30 bpy.app.Label("GMDC file (output)", 20, pos_y, 200, 20) pos_y -= 20 bpy.app.BeginAlign() str_gmdc_filename = bpy.app.String("", 0x10, 20, pos_y, 300, 20, str_gmdc_filename.val, MAX_PATH, "Path to GMDC file") bpy.app.PushButton("Select file", 0x11, 320, pos_y, 100, 20, "Open file browser") bpy.app.EndAlign() pos_y -= 35 Blender.BGL.glColor3f(0.7, 0.7, 0.7) Blender.BGL.glRecti(20, pos_y - 60, 420, pos_y + 20) bpy.app.Label("SGResource name (optional)", 25, pos_y, 400, 20); pos_y -= 20 bpy.app.Label("If not provided then GMDC filename is used", 25, pos_y, 400, 20); pos_y -= 30 bpy.app.BeginAlign() str_resource_name = bpy.app.String("", 0x50, 70, pos_y, 180, 20, str_resource_name.val, 50, "SGResource name of this geometry") btn_name_suffix = bpy.app.Toggle("_tslocator_gmdc", 0x51, 250, pos_y, 120, 20, btn_name_suffix.val, "Add default suffix") bpy.app.EndAlign() pos_y -= 45 bpy.app.BeginAlign() btn_export_rigging = bpy.app.Toggle("Rigging", 0x31, 20, pos_y, 100, 20, btn_export_rigging.val, "Export rigging data (bone indices, weights)") btn_export_tangents = bpy.app.Toggle("Tangents", 0x32, 120, pos_y, 100, 20, btn_export_tangents.val, "Export tangents (required for bump mapping)") btn_export_bmesh = bpy.app.Toggle("Bound. mesh", 0x33, 220, pos_y, 100, 20, btn_export_bmesh.val, "Export bounding geometry") btn_save_log = bpy.app.Toggle("Save log", 0x34, 320, pos_y, 100, 20, btn_save_log.val, "Write script's log data into file *.export_log.txt") bpy.app.EndAlign() pos_y -= 30 bpy.app.BeginAlign() menu_export_morphs = bpy.app.Menu( "Export morphs %t|Do not export morphs %x0|Diff. in v.coords only %x1|Diff. in v.coords and normals %x2", 0x35, 20, pos_y, 200, 20, menu_export_morphs.val) btn_use_obj_props = bpy.app.Toggle("Use object properties", 0x36, 220, pos_y, 200, 20, btn_use_obj_props.val, "Properties can be assigned in logic panel") bpy.app.EndAlign() pos_y -= 30 # bounding mesh name bpy.app.Label("Bounding mesh:", 20, pos_y, 100, 20) str_bmesh_name = bpy.app.String("", 0x40, 120, pos_y, 200, 20, str_bmesh_name.val, 50, "Name of mesh object that will be exported as bounding mesh") pos_y -= 50 # buttons bpy.app.BeginAlign() bpy.app.PushButton("Export", 1, 120, pos_y, 100, 30, "Export geometry (Ctrl + Enter)") bpy.app.PushButton("Exit", 0, 220, pos_y, 100, 30, "Terminate the script (Esc)") bpy.app.EndAlign() # --------------------------------------- # event handlers l_ctrl_key_pressed = 0 r_ctrl_key_pressed = 0 def set_gmdc_filename(filename): global gmdc_filename str_gmdc_filename.val = filename def event_handler(evt, val): global l_ctrl_key_pressed, r_ctrl_key_pressed if evt == bpy.app.ESCKEY and val: bpy.app.Exit() elif evt == bpy.app.LEFTCTRLKEY: l_ctrl_key_pressed = val elif evt == bpy.app.RIGHTCTRLKEY: r_ctrl_key_pressed = val elif evt == bpy.app.RETKEY and val and (l_ctrl_key_pressed or r_ctrl_key_pressed): begin_export() l_ctrl_key_pressed = 0 r_ctrl_key_pressed = 0 def button_events(evt): if evt == 0: bpy.app.Exit() elif evt == 1: begin_export() elif evt == 0x11: bpy.app.Window.FileSelector(set_gmdc_filename, 'Select', bpy.sys.makename(ext='.gmdc')) # ------------------------------------------------------------------------------- # set default values for GUI elements and run event loop str_gmdc_filename = bpy.app.Create("") str_resource_name = bpy.app.Create("") btn_name_suffix = bpy.app.Create(1) btn_export_rigging = bpy.app.Create(0) btn_export_tangents = bpy.app.Create(0) btn_export_bmesh = bpy.app.Create(0) btn_save_log = bpy.app.Create(0) btn_use_obj_props = bpy.app.Create(0) menu_export_morphs = bpy.app.Create(0) str_bmesh_name = bpy.app.Create("b_mesh") bpy.app.Register(draw_gui, event_handler, button_events)
true
true
1c2c341372f9515eb232275aba6071181a5e278b
24,349
py
Python
evaluation/semantic_segmentation/mmcv_custom/checkpoint.py
taokong/ibot
a2ee1ae7495d4ea8fb9ba100434c062f1bd3d1f0
[ "Apache-2.0" ]
327
2021-12-09T10:03:55.000Z
2022-03-31T12:26:22.000Z
evaluation/semantic_segmentation/mmcv_custom/checkpoint.py
taokong/ibot
a2ee1ae7495d4ea8fb9ba100434c062f1bd3d1f0
[ "Apache-2.0" ]
11
2021-12-30T11:39:43.000Z
2022-03-28T05:40:48.000Z
evaluation/semantic_segmentation/mmcv_custom/checkpoint.py
taokong/ibot
a2ee1ae7495d4ea8fb9ba100434c062f1bd3d1f0
[ "Apache-2.0" ]
43
2021-12-09T10:48:26.000Z
2022-03-29T06:58:40.000Z
# Copyright (c) ByteDance, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Copy-paste from mmcv library: https://github.com/open-mmlab/mmcv/ """ import io import os import os.path as osp import pkgutil import time import warnings import mmcv import torch import torchvision import numpy as np import math from collections import OrderedDict from importlib import import_module from tempfile import TemporaryDirectory from torch.optim import Optimizer from torch.nn import functional as F from mmcv.fileio import FileClient from mmcv.fileio import load as load_file from mmcv.parallel import is_module_wrapper from mmcv.utils import mkdir_or_exist from mmcv.runner import get_dist_info from scipy import interpolate ENV_MMCV_HOME = 'MMCV_HOME' ENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME' DEFAULT_CACHE_DIR = '~/.cache' def _get_mmcv_home(): mmcv_home = os.path.expanduser( os.getenv( ENV_MMCV_HOME, os.path.join( os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'mmcv'))) mkdir_or_exist(mmcv_home) return mmcv_home def load_state_dict(module, state_dict, strict=False, logger=None): """Load state_dict to a module. This method is modified from :meth:`torch.nn.Module.load_state_dict`. Default value for ``strict`` is set to ``False`` and the message for param mismatch will be shown even if strict is False. Args: module (Module): Module that receives the state_dict. state_dict (OrderedDict): Weights. strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` match the keys returned by this module's :meth:`~torch.nn.Module.state_dict` function. Default: ``False``. logger (:obj:`logging.Logger`, optional): Logger to log the error message. If not specified, print function will be used. """ unexpected_keys = [] all_missing_keys = [] err_msg = [] metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if metadata is not None: state_dict._metadata = metadata # use _load_from_state_dict to enable checkpoint version control def load(module, prefix=''): # recursively check parallel module in case that the model has a # complicated structure, e.g., nn.Module(nn.Module(DDP)) if is_module_wrapper(module): module = module.module local_metadata = {} if metadata is None else metadata.get( prefix[:-1], {}) module._load_from_state_dict(state_dict, prefix, local_metadata, True, all_missing_keys, unexpected_keys, err_msg) for name, child in module._modules.items(): if child is not None: load(child, prefix + name + '.') load(module) load = None # break load->load reference cycle # ignore "num_batches_tracked" of BN layers missing_keys = [ key for key in all_missing_keys if 'num_batches_tracked' not in key ] if unexpected_keys: err_msg.append('unexpected key in source ' f'state_dict: {", ".join(unexpected_keys)}\n') if missing_keys: err_msg.append( f'missing keys in source state_dict: {", ".join(missing_keys)}\n') rank, _ = get_dist_info() if len(err_msg) > 0 and rank == 0: err_msg.insert( 0, 'The model and loaded state dict do not match exactly\n') err_msg = '\n'.join(err_msg) if strict: raise RuntimeError(err_msg) elif logger is not None: logger.warning(err_msg) else: print(err_msg) def load_url_dist(url, model_dir=None, map_location="cpu"): """In distributed setting, this function only download checkpoint at local rank 0.""" rank, world_size = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if rank == 0: checkpoint = model_zoo.load_url(url, model_dir=model_dir, map_location=map_location) if world_size > 1: torch.distributed.barrier() if rank > 0: checkpoint = model_zoo.load_url(url, model_dir=model_dir, map_location=map_location) return checkpoint def load_pavimodel_dist(model_path, map_location=None): """In distributed setting, this function only download checkpoint at local rank 0.""" try: from pavi import modelscloud except ImportError: raise ImportError( 'Please install pavi to load checkpoint from modelcloud.') rank, world_size = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if rank == 0: model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load(downloaded_file, map_location=map_location) if world_size > 1: torch.distributed.barrier() if rank > 0: model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load( downloaded_file, map_location=map_location) return checkpoint def load_fileclient_dist(filename, backend, map_location): """In distributed setting, this function only download checkpoint at local rank 0.""" rank, world_size = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) allowed_backends = ['ceph'] if backend not in allowed_backends: raise ValueError(f'Load from Backend {backend} is not supported.') if rank == 0: fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) if world_size > 1: torch.distributed.barrier() if rank > 0: fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) return checkpoint def get_torchvision_models(): model_urls = dict() for _, name, ispkg in pkgutil.walk_packages(torchvision.models.__path__): if ispkg: continue _zoo = import_module(f'torchvision.models.{name}') if hasattr(_zoo, 'model_urls'): _urls = getattr(_zoo, 'model_urls') model_urls.update(_urls) return model_urls def get_external_models(): mmcv_home = _get_mmcv_home() default_json_path = osp.join(mmcv.__path__[0], 'model_zoo/open_mmlab.json') default_urls = load_file(default_json_path) assert isinstance(default_urls, dict) external_json_path = osp.join(mmcv_home, 'open_mmlab.json') if osp.exists(external_json_path): external_urls = load_file(external_json_path) assert isinstance(external_urls, dict) default_urls.update(external_urls) return default_urls def get_mmcls_models(): mmcls_json_path = osp.join(mmcv.__path__[0], 'model_zoo/mmcls.json') mmcls_urls = load_file(mmcls_json_path) return mmcls_urls def get_deprecated_model_names(): deprecate_json_path = osp.join(mmcv.__path__[0], 'model_zoo/deprecated.json') deprecate_urls = load_file(deprecate_json_path) assert isinstance(deprecate_urls, dict) return deprecate_urls def _process_mmcls_checkpoint(checkpoint): state_dict = checkpoint['state_dict'] new_state_dict = OrderedDict() for k, v in state_dict.items(): if k.startswith('backbone.'): new_state_dict[k[9:]] = v new_checkpoint = dict(state_dict=new_state_dict) return new_checkpoint def _load_checkpoint(filename, map_location=None): """Load checkpoint from somewhere (modelzoo, file, url). Args: filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str | None): Same as :func:`torch.load`. Default: None. Returns: dict | OrderedDict: The loaded checkpoint. It can be either an OrderedDict storing model weights or a dict containing other information, which depends on the checkpoint. """ if filename.startswith('modelzoo://'): warnings.warn('The URL scheme of "modelzoo://" is deprecated, please ' 'use "torchvision://" instead') model_urls = get_torchvision_models() model_name = filename[11:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('torchvision://'): model_urls = get_torchvision_models() model_name = filename[14:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('open-mmlab://'): model_urls = get_external_models() model_name = filename[13:] deprecated_urls = get_deprecated_model_names() if model_name in deprecated_urls: warnings.warn(f'open-mmlab://{model_name} is deprecated in favor ' f'of open-mmlab://{deprecated_urls[model_name]}') model_name = deprecated_urls[model_name] model_url = model_urls[model_name] # check if is url if model_url.startswith(('http://', 'https://')): checkpoint = load_url_dist(model_url) else: filename = osp.join(_get_mmcv_home(), model_url) if not osp.isfile(filename): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) elif filename.startswith('mmcls://'): model_urls = get_mmcls_models() model_name = filename[8:] checkpoint = load_url_dist(model_urls[model_name]) checkpoint = _process_mmcls_checkpoint(checkpoint) elif filename.startswith(('http://', 'https://')): checkpoint = load_url_dist(filename) elif filename.startswith('pavi://'): model_path = filename[7:] checkpoint = load_pavimodel_dist(model_path, map_location=map_location) elif filename.startswith('s3://'): checkpoint = load_fileclient_dist( filename, backend='ceph', map_location=map_location) else: if not osp.isfile(filename): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) return checkpoint def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0, start_warmup_value=0, warmup_steps=-1): warmup_schedule = np.array([]) warmup_iters = warmup_epochs * niter_per_ep if warmup_steps > 0: warmup_iters = warmup_steps print("Set warmup steps = %d" % warmup_iters) if warmup_epochs > 0: warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters) iters = np.arange(epochs * niter_per_ep - warmup_iters) schedule = np.array( [final_value + 0.5 * (base_value - final_value) * (1 + math.cos(math.pi * i / (len(iters)))) for i in iters]) schedule = np.concatenate((warmup_schedule, schedule)) assert len(schedule) == epochs * niter_per_ep return schedule def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None): """Load checkpoint from a file or URI. Args: model (Module): Module to load checkpoint. filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str): Same as :func:`torch.load`. strict (bool): Whether to allow different params for the model and checkpoint. logger (:mod:`logging.Logger` or None): The logger for error message. Returns: dict or OrderedDict: The loaded checkpoint. """ checkpoint = _load_checkpoint(filename, map_location) # OrderedDict is a subclass of dict if not isinstance(checkpoint, dict): raise RuntimeError( f'No state_dict found in checkpoint file {filename}') # get state_dict from checkpoint if 'state_dict' in checkpoint: state_dict = checkpoint['state_dict'] elif 'model' in checkpoint: state_dict = checkpoint['model'] elif 'module' in checkpoint: state_dict = checkpoint['module'] else: state_dict = checkpoint # strip prefix of state_dict if list(state_dict.keys())[0].startswith('module.'): state_dict = {k[7:]: v for k, v in state_dict.items()} # for MoBY, load model of online branch if sorted(list(state_dict.keys()))[0].startswith('encoder'): state_dict = {k.replace('encoder.', ''): v for k, v in state_dict.items() if k.startswith('encoder.')} # reshape absolute position embedding for Swin if state_dict.get('absolute_pos_embed') is not None: absolute_pos_embed = state_dict['absolute_pos_embed'] N1, L, C1 = absolute_pos_embed.size() N2, C2, H, W = model.absolute_pos_embed.size() if N1 != N2 or C1 != C2 or L != H*W: logger.warning("Error in loading absolute_pos_embed, pass") else: state_dict['absolute_pos_embed'] = absolute_pos_embed.view(N2, H, W, C2).permute(0, 3, 1, 2) rank, _ = get_dist_info() all_keys = list(state_dict.keys()) for key in all_keys: if "relative_position_index" in key: state_dict.pop(key) if "relative_position_bias_table" in key: rel_pos_bias = state_dict[key] src_num_pos, num_attn_heads = rel_pos_bias.size() dst_num_pos, _ = model.state_dict()[key].size() dst_patch_shape = model.patch_embed.patch_shape if dst_patch_shape[0] != dst_patch_shape[1]: raise NotImplementedError() num_extra_tokens = dst_num_pos - (dst_patch_shape[0] * 2 - 1) * (dst_patch_shape[1] * 2 - 1) src_size = int((src_num_pos - num_extra_tokens) ** 0.5) dst_size = int((dst_num_pos - num_extra_tokens) ** 0.5) if src_size != dst_size: if rank == 0: print("Position interpolate for %s from %dx%d to %dx%d" % ( key, src_size, src_size, dst_size, dst_size)) extra_tokens = rel_pos_bias[-num_extra_tokens:, :] rel_pos_bias = rel_pos_bias[:-num_extra_tokens, :] def geometric_progression(a, r, n): return a * (1.0 - r ** n) / (1.0 - r) left, right = 1.01, 1.5 while right - left > 1e-6: q = (left + right) / 2.0 gp = geometric_progression(1, q, src_size // 2) if gp > dst_size // 2: right = q else: left = q # if q > 1.13492: # q = 1.13492 dis = [] cur = 1 for i in range(src_size // 2): dis.append(cur) cur += q ** (i + 1) r_ids = [-_ for _ in reversed(dis)] x = r_ids + [0] + dis y = r_ids + [0] + dis t = dst_size // 2.0 dx = np.arange(-t, t + 0.1, 1.0) dy = np.arange(-t, t + 0.1, 1.0) if rank == 0: print("x = {}".format(x)) print("dx = {}".format(dx)) all_rel_pos_bias = [] for i in range(num_attn_heads): z = rel_pos_bias[:, i].view(src_size, src_size).float().numpy() f = interpolate.interp2d(x, y, z, kind='cubic') all_rel_pos_bias.append( torch.Tensor(f(dx, dy)).contiguous().view(-1, 1).to(rel_pos_bias.device)) rel_pos_bias = torch.cat(all_rel_pos_bias, dim=-1) new_rel_pos_bias = torch.cat((rel_pos_bias, extra_tokens), dim=0) state_dict[key] = new_rel_pos_bias if 'pos_embed' in state_dict: pos_embed_checkpoint = state_dict['pos_embed'] embedding_size = pos_embed_checkpoint.shape[-1] num_patches = model.patch_embed.num_patches num_extra_tokens = model.pos_embed.shape[-2] - num_patches # height (== width) for the checkpoint position embedding orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) # height (== width) for the new position embedding new_size = int(num_patches ** 0.5) # class_token and dist_token are kept unchanged if orig_size != new_size: if rank == 0: print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size)) extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] # only the position tokens are interpolated pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) pos_tokens = torch.nn.functional.interpolate( pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) state_dict['pos_embed'] = new_pos_embed # interpolate position bias table if needed relative_position_bias_table_keys = [k for k in state_dict.keys() if "relative_position_bias_table" in k] for table_key in relative_position_bias_table_keys: table_pretrained = state_dict[table_key] table_current = model.state_dict()[table_key] L1, nH1 = table_pretrained.size() L2, nH2 = table_current.size() if nH1 != nH2: logger.warning(f"Error in loading {table_key}, pass") else: if L1 != L2: S1 = int(L1 ** 0.5) S2 = int(L2 ** 0.5) table_pretrained_resized = F.interpolate( table_pretrained.permute(1, 0).view(1, nH1, S1, S1), size=(S2, S2), mode='bicubic') state_dict[table_key] = table_pretrained_resized.view(nH2, L2).permute(1, 0) # load state_dict load_state_dict(model, state_dict, strict, logger) return checkpoint def weights_to_cpu(state_dict): """Copy a model state_dict to cpu. Args: state_dict (OrderedDict): Model weights on GPU. Returns: OrderedDict: Model weights on GPU. """ state_dict_cpu = OrderedDict() for key, val in state_dict.items(): state_dict_cpu[key] = val.cpu() return state_dict_cpu def _save_to_state_dict(module, destination, prefix, keep_vars): """Saves module state to `destination` dictionary. This method is modified from :meth:`torch.nn.Module._save_to_state_dict`. Args: module (nn.Module): The module to generate state_dict. destination (dict): A dict where state will be stored. prefix (str): The prefix for parameters and buffers used in this module. """ for name, param in module._parameters.items(): if param is not None: destination[prefix + name] = param if keep_vars else param.detach() for name, buf in module._buffers.items(): # remove check of _non_persistent_buffers_set to allow nn.BatchNorm2d if buf is not None: destination[prefix + name] = buf if keep_vars else buf.detach() def get_state_dict(module, destination=None, prefix='', keep_vars=False): """Returns a dictionary containing a whole state of the module. Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. This method is modified from :meth:`torch.nn.Module.state_dict` to recursively check parallel module in case that the model has a complicated structure, e.g., nn.Module(nn.Module(DDP)). Args: module (nn.Module): The module to generate state_dict. destination (OrderedDict): Returned dict for the state of the module. prefix (str): Prefix of the key. keep_vars (bool): Whether to keep the variable property of the parameters. Default: False. Returns: dict: A dictionary containing a whole state of the module. """ # recursively check parallel module in case that the model has a # complicated structure, e.g., nn.Module(nn.Module(DDP)) if is_module_wrapper(module): module = module.module # below is the same as torch.nn.Module.state_dict() if destination is None: destination = OrderedDict() destination._metadata = OrderedDict() destination._metadata[prefix[:-1]] = local_metadata = dict( version=module._version) _save_to_state_dict(module, destination, prefix, keep_vars) for name, child in module._modules.items(): if child is not None: get_state_dict( child, destination, prefix + name + '.', keep_vars=keep_vars) for hook in module._state_dict_hooks.values(): hook_result = hook(module, destination, prefix, local_metadata) if hook_result is not None: destination = hook_result return destination def save_checkpoint(model, filename, optimizer=None, meta=None): """Save checkpoint to file. The checkpoint will have 3 fields: ``meta``, ``state_dict`` and ``optimizer``. By default ``meta`` will contain version and time info. Args: model (Module): Module whose params are to be saved. filename (str): Checkpoint filename. optimizer (:obj:`Optimizer`, optional): Optimizer to be saved. meta (dict, optional): Metadata to be saved in checkpoint. """ if meta is None: meta = {} elif not isinstance(meta, dict): raise TypeError(f'meta must be a dict or None, but got {type(meta)}') meta.update(mmcv_version=mmcv.__version__, time=time.asctime()) if is_module_wrapper(model): model = model.module if hasattr(model, 'CLASSES') and model.CLASSES is not None: # save class name to the meta meta.update(CLASSES=model.CLASSES) checkpoint = { 'meta': meta, 'state_dict': weights_to_cpu(get_state_dict(model)) } # save optimizer state dict in the checkpoint if isinstance(optimizer, Optimizer): checkpoint['optimizer'] = optimizer.state_dict() elif isinstance(optimizer, dict): checkpoint['optimizer'] = {} for name, optim in optimizer.items(): checkpoint['optimizer'][name] = optim.state_dict() if filename.startswith('pavi://'): try: from pavi import modelscloud from pavi.exception import NodeNotFoundError except ImportError: raise ImportError( 'Please install pavi to load checkpoint from modelcloud.') model_path = filename[7:] root = modelcloud.Folder() model_dir, model_name = osp.split(model_path) try: model = modelcloud.get(model_dir) except NodeNotFoundError: model = root.create_training_model(model_dir) with TemporaryDirectory() as tmp_dir: checkpoint_file = osp.join(tmp_dir, model_name) with open(checkpoint_file, 'wb') as f: torch.save(checkpoint, f) f.flush() model.create_file(checkpoint_file, name=model_name) else: mmcv.mkdir_or_exist(osp.dirname(filename)) # immediately flush buffer with open(filename, 'wb') as f: torch.save(checkpoint, f) f.flush()
39.020833
117
0.630293
import io import os import os.path as osp import pkgutil import time import warnings import mmcv import torch import torchvision import numpy as np import math from collections import OrderedDict from importlib import import_module from tempfile import TemporaryDirectory from torch.optim import Optimizer from torch.nn import functional as F from mmcv.fileio import FileClient from mmcv.fileio import load as load_file from mmcv.parallel import is_module_wrapper from mmcv.utils import mkdir_or_exist from mmcv.runner import get_dist_info from scipy import interpolate ENV_MMCV_HOME = 'MMCV_HOME' ENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME' DEFAULT_CACHE_DIR = '~/.cache' def _get_mmcv_home(): mmcv_home = os.path.expanduser( os.getenv( ENV_MMCV_HOME, os.path.join( os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'mmcv'))) mkdir_or_exist(mmcv_home) return mmcv_home def load_state_dict(module, state_dict, strict=False, logger=None): unexpected_keys = [] all_missing_keys = [] err_msg = [] metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if metadata is not None: state_dict._metadata = metadata def load(module, prefix=''): if is_module_wrapper(module): module = module.module local_metadata = {} if metadata is None else metadata.get( prefix[:-1], {}) module._load_from_state_dict(state_dict, prefix, local_metadata, True, all_missing_keys, unexpected_keys, err_msg) for name, child in module._modules.items(): if child is not None: load(child, prefix + name + '.') load(module) load = None missing_keys = [ key for key in all_missing_keys if 'num_batches_tracked' not in key ] if unexpected_keys: err_msg.append('unexpected key in source ' f'state_dict: {", ".join(unexpected_keys)}\n') if missing_keys: err_msg.append( f'missing keys in source state_dict: {", ".join(missing_keys)}\n') rank, _ = get_dist_info() if len(err_msg) > 0 and rank == 0: err_msg.insert( 0, 'The model and loaded state dict do not match exactly\n') err_msg = '\n'.join(err_msg) if strict: raise RuntimeError(err_msg) elif logger is not None: logger.warning(err_msg) else: print(err_msg) def load_url_dist(url, model_dir=None, map_location="cpu"): rank, world_size = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if rank == 0: checkpoint = model_zoo.load_url(url, model_dir=model_dir, map_location=map_location) if world_size > 1: torch.distributed.barrier() if rank > 0: checkpoint = model_zoo.load_url(url, model_dir=model_dir, map_location=map_location) return checkpoint def load_pavimodel_dist(model_path, map_location=None): try: from pavi import modelscloud except ImportError: raise ImportError( 'Please install pavi to load checkpoint from modelcloud.') rank, world_size = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if rank == 0: model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load(downloaded_file, map_location=map_location) if world_size > 1: torch.distributed.barrier() if rank > 0: model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load( downloaded_file, map_location=map_location) return checkpoint def load_fileclient_dist(filename, backend, map_location): rank, world_size = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) allowed_backends = ['ceph'] if backend not in allowed_backends: raise ValueError(f'Load from Backend {backend} is not supported.') if rank == 0: fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) if world_size > 1: torch.distributed.barrier() if rank > 0: fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) return checkpoint def get_torchvision_models(): model_urls = dict() for _, name, ispkg in pkgutil.walk_packages(torchvision.models.__path__): if ispkg: continue _zoo = import_module(f'torchvision.models.{name}') if hasattr(_zoo, 'model_urls'): _urls = getattr(_zoo, 'model_urls') model_urls.update(_urls) return model_urls def get_external_models(): mmcv_home = _get_mmcv_home() default_json_path = osp.join(mmcv.__path__[0], 'model_zoo/open_mmlab.json') default_urls = load_file(default_json_path) assert isinstance(default_urls, dict) external_json_path = osp.join(mmcv_home, 'open_mmlab.json') if osp.exists(external_json_path): external_urls = load_file(external_json_path) assert isinstance(external_urls, dict) default_urls.update(external_urls) return default_urls def get_mmcls_models(): mmcls_json_path = osp.join(mmcv.__path__[0], 'model_zoo/mmcls.json') mmcls_urls = load_file(mmcls_json_path) return mmcls_urls def get_deprecated_model_names(): deprecate_json_path = osp.join(mmcv.__path__[0], 'model_zoo/deprecated.json') deprecate_urls = load_file(deprecate_json_path) assert isinstance(deprecate_urls, dict) return deprecate_urls def _process_mmcls_checkpoint(checkpoint): state_dict = checkpoint['state_dict'] new_state_dict = OrderedDict() for k, v in state_dict.items(): if k.startswith('backbone.'): new_state_dict[k[9:]] = v new_checkpoint = dict(state_dict=new_state_dict) return new_checkpoint def _load_checkpoint(filename, map_location=None): if filename.startswith('modelzoo://'): warnings.warn('The URL scheme of "modelzoo://" is deprecated, please ' 'use "torchvision://" instead') model_urls = get_torchvision_models() model_name = filename[11:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('torchvision://'): model_urls = get_torchvision_models() model_name = filename[14:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('open-mmlab://'): model_urls = get_external_models() model_name = filename[13:] deprecated_urls = get_deprecated_model_names() if model_name in deprecated_urls: warnings.warn(f'open-mmlab://{model_name} is deprecated in favor ' f'of open-mmlab://{deprecated_urls[model_name]}') model_name = deprecated_urls[model_name] model_url = model_urls[model_name] if model_url.startswith(('http://', 'https://')): checkpoint = load_url_dist(model_url) else: filename = osp.join(_get_mmcv_home(), model_url) if not osp.isfile(filename): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) elif filename.startswith('mmcls://'): model_urls = get_mmcls_models() model_name = filename[8:] checkpoint = load_url_dist(model_urls[model_name]) checkpoint = _process_mmcls_checkpoint(checkpoint) elif filename.startswith(('http://', 'https://')): checkpoint = load_url_dist(filename) elif filename.startswith('pavi://'): model_path = filename[7:] checkpoint = load_pavimodel_dist(model_path, map_location=map_location) elif filename.startswith('s3://'): checkpoint = load_fileclient_dist( filename, backend='ceph', map_location=map_location) else: if not osp.isfile(filename): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) return checkpoint def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0, start_warmup_value=0, warmup_steps=-1): warmup_schedule = np.array([]) warmup_iters = warmup_epochs * niter_per_ep if warmup_steps > 0: warmup_iters = warmup_steps print("Set warmup steps = %d" % warmup_iters) if warmup_epochs > 0: warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters) iters = np.arange(epochs * niter_per_ep - warmup_iters) schedule = np.array( [final_value + 0.5 * (base_value - final_value) * (1 + math.cos(math.pi * i / (len(iters)))) for i in iters]) schedule = np.concatenate((warmup_schedule, schedule)) assert len(schedule) == epochs * niter_per_ep return schedule def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None): checkpoint = _load_checkpoint(filename, map_location) if not isinstance(checkpoint, dict): raise RuntimeError( f'No state_dict found in checkpoint file {filename}') if 'state_dict' in checkpoint: state_dict = checkpoint['state_dict'] elif 'model' in checkpoint: state_dict = checkpoint['model'] elif 'module' in checkpoint: state_dict = checkpoint['module'] else: state_dict = checkpoint if list(state_dict.keys())[0].startswith('module.'): state_dict = {k[7:]: v for k, v in state_dict.items()} if sorted(list(state_dict.keys()))[0].startswith('encoder'): state_dict = {k.replace('encoder.', ''): v for k, v in state_dict.items() if k.startswith('encoder.')} if state_dict.get('absolute_pos_embed') is not None: absolute_pos_embed = state_dict['absolute_pos_embed'] N1, L, C1 = absolute_pos_embed.size() N2, C2, H, W = model.absolute_pos_embed.size() if N1 != N2 or C1 != C2 or L != H*W: logger.warning("Error in loading absolute_pos_embed, pass") else: state_dict['absolute_pos_embed'] = absolute_pos_embed.view(N2, H, W, C2).permute(0, 3, 1, 2) rank, _ = get_dist_info() all_keys = list(state_dict.keys()) for key in all_keys: if "relative_position_index" in key: state_dict.pop(key) if "relative_position_bias_table" in key: rel_pos_bias = state_dict[key] src_num_pos, num_attn_heads = rel_pos_bias.size() dst_num_pos, _ = model.state_dict()[key].size() dst_patch_shape = model.patch_embed.patch_shape if dst_patch_shape[0] != dst_patch_shape[1]: raise NotImplementedError() num_extra_tokens = dst_num_pos - (dst_patch_shape[0] * 2 - 1) * (dst_patch_shape[1] * 2 - 1) src_size = int((src_num_pos - num_extra_tokens) ** 0.5) dst_size = int((dst_num_pos - num_extra_tokens) ** 0.5) if src_size != dst_size: if rank == 0: print("Position interpolate for %s from %dx%d to %dx%d" % ( key, src_size, src_size, dst_size, dst_size)) extra_tokens = rel_pos_bias[-num_extra_tokens:, :] rel_pos_bias = rel_pos_bias[:-num_extra_tokens, :] def geometric_progression(a, r, n): return a * (1.0 - r ** n) / (1.0 - r) left, right = 1.01, 1.5 while right - left > 1e-6: q = (left + right) / 2.0 gp = geometric_progression(1, q, src_size // 2) if gp > dst_size // 2: right = q else: left = q dis = [] cur = 1 for i in range(src_size // 2): dis.append(cur) cur += q ** (i + 1) r_ids = [-_ for _ in reversed(dis)] x = r_ids + [0] + dis y = r_ids + [0] + dis t = dst_size // 2.0 dx = np.arange(-t, t + 0.1, 1.0) dy = np.arange(-t, t + 0.1, 1.0) if rank == 0: print("x = {}".format(x)) print("dx = {}".format(dx)) all_rel_pos_bias = [] for i in range(num_attn_heads): z = rel_pos_bias[:, i].view(src_size, src_size).float().numpy() f = interpolate.interp2d(x, y, z, kind='cubic') all_rel_pos_bias.append( torch.Tensor(f(dx, dy)).contiguous().view(-1, 1).to(rel_pos_bias.device)) rel_pos_bias = torch.cat(all_rel_pos_bias, dim=-1) new_rel_pos_bias = torch.cat((rel_pos_bias, extra_tokens), dim=0) state_dict[key] = new_rel_pos_bias if 'pos_embed' in state_dict: pos_embed_checkpoint = state_dict['pos_embed'] embedding_size = pos_embed_checkpoint.shape[-1] num_patches = model.patch_embed.num_patches num_extra_tokens = model.pos_embed.shape[-2] - num_patches orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) new_size = int(num_patches ** 0.5) if orig_size != new_size: if rank == 0: print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size)) extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) pos_tokens = torch.nn.functional.interpolate( pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) state_dict['pos_embed'] = new_pos_embed relative_position_bias_table_keys = [k for k in state_dict.keys() if "relative_position_bias_table" in k] for table_key in relative_position_bias_table_keys: table_pretrained = state_dict[table_key] table_current = model.state_dict()[table_key] L1, nH1 = table_pretrained.size() L2, nH2 = table_current.size() if nH1 != nH2: logger.warning(f"Error in loading {table_key}, pass") else: if L1 != L2: S1 = int(L1 ** 0.5) S2 = int(L2 ** 0.5) table_pretrained_resized = F.interpolate( table_pretrained.permute(1, 0).view(1, nH1, S1, S1), size=(S2, S2), mode='bicubic') state_dict[table_key] = table_pretrained_resized.view(nH2, L2).permute(1, 0) load_state_dict(model, state_dict, strict, logger) return checkpoint def weights_to_cpu(state_dict): state_dict_cpu = OrderedDict() for key, val in state_dict.items(): state_dict_cpu[key] = val.cpu() return state_dict_cpu def _save_to_state_dict(module, destination, prefix, keep_vars): for name, param in module._parameters.items(): if param is not None: destination[prefix + name] = param if keep_vars else param.detach() for name, buf in module._buffers.items(): if buf is not None: destination[prefix + name] = buf if keep_vars else buf.detach() def get_state_dict(module, destination=None, prefix='', keep_vars=False): if is_module_wrapper(module): module = module.module if destination is None: destination = OrderedDict() destination._metadata = OrderedDict() destination._metadata[prefix[:-1]] = local_metadata = dict( version=module._version) _save_to_state_dict(module, destination, prefix, keep_vars) for name, child in module._modules.items(): if child is not None: get_state_dict( child, destination, prefix + name + '.', keep_vars=keep_vars) for hook in module._state_dict_hooks.values(): hook_result = hook(module, destination, prefix, local_metadata) if hook_result is not None: destination = hook_result return destination def save_checkpoint(model, filename, optimizer=None, meta=None): if meta is None: meta = {} elif not isinstance(meta, dict): raise TypeError(f'meta must be a dict or None, but got {type(meta)}') meta.update(mmcv_version=mmcv.__version__, time=time.asctime()) if is_module_wrapper(model): model = model.module if hasattr(model, 'CLASSES') and model.CLASSES is not None: meta.update(CLASSES=model.CLASSES) checkpoint = { 'meta': meta, 'state_dict': weights_to_cpu(get_state_dict(model)) } if isinstance(optimizer, Optimizer): checkpoint['optimizer'] = optimizer.state_dict() elif isinstance(optimizer, dict): checkpoint['optimizer'] = {} for name, optim in optimizer.items(): checkpoint['optimizer'][name] = optim.state_dict() if filename.startswith('pavi://'): try: from pavi import modelscloud from pavi.exception import NodeNotFoundError except ImportError: raise ImportError( 'Please install pavi to load checkpoint from modelcloud.') model_path = filename[7:] root = modelcloud.Folder() model_dir, model_name = osp.split(model_path) try: model = modelcloud.get(model_dir) except NodeNotFoundError: model = root.create_training_model(model_dir) with TemporaryDirectory() as tmp_dir: checkpoint_file = osp.join(tmp_dir, model_name) with open(checkpoint_file, 'wb') as f: torch.save(checkpoint, f) f.flush() model.create_file(checkpoint_file, name=model_name) else: mmcv.mkdir_or_exist(osp.dirname(filename)) with open(filename, 'wb') as f: torch.save(checkpoint, f) f.flush()
true
true
1c2c3457b127439091e661d78762077ed473ac78
2,017
py
Python
tests/test_dict.py
potipot/Montreal-Forced-Aligner
6d665e9c63a4e3c795d27ec3bb8d9d1a5604bb91
[ "MIT" ]
null
null
null
tests/test_dict.py
potipot/Montreal-Forced-Aligner
6d665e9c63a4e3c795d27ec3bb8d9d1a5604bb91
[ "MIT" ]
null
null
null
tests/test_dict.py
potipot/Montreal-Forced-Aligner
6d665e9c63a4e3c795d27ec3bb8d9d1a5604bb91
[ "MIT" ]
null
null
null
import os import pytest from montreal_forced_aligner.dictionary import Dictionary def ListLines(path): lines = [] thefile = open(path) text = thefile.readlines() for line in text: stripped = line.strip() if stripped != '': lines.append(stripped) return lines def test_basic(basic_dict_path, generated_dir): d = Dictionary(basic_dict_path, os.path.join(generated_dir, 'basic')) d.write() assert set(d.phones) == {'sil', 'sp', 'spn', 'phonea', 'phoneb', 'phonec'} assert set(d.positional_nonsil_phones) == {'phonea_B', 'phonea_I', 'phonea_E', 'phonea_S', 'phoneb_B', 'phoneb_I', 'phoneb_E', 'phoneb_S', 'phonec_B', 'phonec_I', 'phonec_E', 'phonec_S'} def test_extra_annotations(extra_annotations_path, generated_dir): d = Dictionary(extra_annotations_path, os.path.join(generated_dir, 'extra')) assert '{' in d.graphemes d.write() def test_basic_noposition(basic_dict_path, generated_dir): d = Dictionary(basic_dict_path, os.path.join(generated_dir, 'basic'), position_dependent_phones=False) x = d.write() assert set(d.phones) == {'sil', 'sp', 'spn', 'phonea', 'phoneb', 'phonec'} def test_frclitics(frclitics_dict_path, generated_dir): d = Dictionary(frclitics_dict_path, os.path.join(generated_dir, 'frclitics')) x = d.write() assert d.split_clitics('aujourd') == ['aujourd'] assert d.split_clitics('aujourd\'hui') == ['aujourd\'hui'] assert d.split_clitics('vingt-six') == ['vingt', 'six'] assert d.split_clitics('m\'appelle') == ['m\'', 'appelle'] assert d.split_clitics('c\'est') == ['c\'est'] assert d.split_clitics('purple-people-eater') == ['purple-people-eater'] assert d.split_clitics('m\'appele') == ['m\'', 'appele'] assert d.split_clitics('m\'ving-sic') == ["m'", 'ving', 'sic'] assert d.split_clitics('flying\'purple-people-eater') == ['flying\'purple-people-eater']
39.54902
106
0.636589
import os import pytest from montreal_forced_aligner.dictionary import Dictionary def ListLines(path): lines = [] thefile = open(path) text = thefile.readlines() for line in text: stripped = line.strip() if stripped != '': lines.append(stripped) return lines def test_basic(basic_dict_path, generated_dir): d = Dictionary(basic_dict_path, os.path.join(generated_dir, 'basic')) d.write() assert set(d.phones) == {'sil', 'sp', 'spn', 'phonea', 'phoneb', 'phonec'} assert set(d.positional_nonsil_phones) == {'phonea_B', 'phonea_I', 'phonea_E', 'phonea_S', 'phoneb_B', 'phoneb_I', 'phoneb_E', 'phoneb_S', 'phonec_B', 'phonec_I', 'phonec_E', 'phonec_S'} def test_extra_annotations(extra_annotations_path, generated_dir): d = Dictionary(extra_annotations_path, os.path.join(generated_dir, 'extra')) assert '{' in d.graphemes d.write() def test_basic_noposition(basic_dict_path, generated_dir): d = Dictionary(basic_dict_path, os.path.join(generated_dir, 'basic'), position_dependent_phones=False) x = d.write() assert set(d.phones) == {'sil', 'sp', 'spn', 'phonea', 'phoneb', 'phonec'} def test_frclitics(frclitics_dict_path, generated_dir): d = Dictionary(frclitics_dict_path, os.path.join(generated_dir, 'frclitics')) x = d.write() assert d.split_clitics('aujourd') == ['aujourd'] assert d.split_clitics('aujourd\'hui') == ['aujourd\'hui'] assert d.split_clitics('vingt-six') == ['vingt', 'six'] assert d.split_clitics('m\'appelle') == ['m\'', 'appelle'] assert d.split_clitics('c\'est') == ['c\'est'] assert d.split_clitics('purple-people-eater') == ['purple-people-eater'] assert d.split_clitics('m\'appele') == ['m\'', 'appele'] assert d.split_clitics('m\'ving-sic') == ["m'", 'ving', 'sic'] assert d.split_clitics('flying\'purple-people-eater') == ['flying\'purple-people-eater']
true
true