edited_code
stringlengths
17
978k
original_code
stringlengths
17
978k
# stdlib from typing import Any from typing import Callable as CallableT import warnings # third party from google.protobuf.reflection import GeneratedProtocolMessageType # syft absolute import syft # relative from ....util import aggressive_set_attr from .deserialize import CAPNP_REGISTRY module_type = type(syft) # this will overwrite the ._sy_serializable_wrapper_type with an auto generated # wrapper which will basically just hold the object being wrapped. def GenerateWrapper( wrapped_type: type, import_path: str, protobuf_scheme: GeneratedProtocolMessageType, type_object2proto: CallableT, type_proto2object: CallableT, ) -> None: @serializable() class Wrapper: def __init__(self, value: object): self.obj = value def _object2proto(self) -> Any: return type_object2proto(self.obj) @staticmethod def _proto2object(proto: Any) -> Any: return type_proto2object(proto) @staticmethod def get_protobuf_schema() -> GeneratedProtocolMessageType: return protobuf_scheme def upcast(self) -> Any: return self.obj @staticmethod def wrapped_type() -> type: return wrapped_type # TODO: refactor like proxy class to get correct name # WARNING: Changing this can break the Wrapper lookup during deserialize module_parts = import_path.split(".") klass = module_parts.pop() Wrapper.__name__ = f"{klass}Wrapper" Wrapper.__module__ = f"syft.wrappers.{".".join(module_parts)}" # create a fake module `wrappers` under `syft` if "wrappers" not in syft.__dict__: syft.__dict__["wrappers"] = module_type(name="wrappers") # for each part of the path, create a fake module and add it to it's parent parent = syft.__dict__["wrappers"] for n in module_parts: if n not in parent.__dict__: parent.__dict__[n] = module_type(name=n) parent = parent.__dict__[n] # finally add our wrapper class to the end of the path parent.__dict__[Wrapper.__name__] = Wrapper aggressive_set_attr( obj=wrapped_type, name="_sy_serializable_wrapper_type", attr=Wrapper ) def GenerateProtobufWrapper( cls_pb: GeneratedProtocolMessageType, import_path: str ) -> None: def object2proto(obj: Any) -> Any: return obj def proto2object(proto: Any) -> Any: return proto GenerateWrapper( wrapped_type=cls_pb, import_path=import_path, protobuf_scheme=cls_pb, type_object2proto=object2proto, type_proto2object=proto2object, ) def serializable( generate_wrapper: bool = False, protobuf_object: bool = False, recursive_serde: bool = False, capnp_bytes: bool = False, ) -> Any: def rs_decorator(cls: Any) -> Any: # relative from .recursive import rs_get_protobuf_schema from .recursive import rs_object2proto from .recursive import rs_proto2object if not hasattr(cls, "__attr_allowlist__"): warnings.warn( f"__attr_allowlist__ not defined for type {cls.__name__}," " even if it uses recursive serde, defaulting on the empty list." ) cls.__attr_allowlist__ = [] if not hasattr(cls, "__serde_overrides__"): cls.__serde_overrides__ = {} cls._object2proto = rs_object2proto cls._proto2object = staticmethod(rs_proto2object) cls.get_protobuf_schema = staticmethod(rs_get_protobuf_schema) return cls def serializable_decorator(cls: Any) -> Any: protobuf_schema = cls.get_protobuf_schema() # overloading a protobuf by adding multiple classes and we will check the # obj_type string later to dispatch to the correct one if hasattr(protobuf_schema, "schema2type"): if isinstance(protobuf_schema.schema2type, list): protobuf_schema.schema2type.append(cls) else: protobuf_schema.schema2type = [protobuf_schema.schema2type, cls] else: protobuf_schema.schema2type = cls return cls def capnp_decorator(cls: Any) -> Any: # register deserialize with the capnp registry CAPNP_REGISTRY[cls.__name__] = cls._bytes2object return cls if capnp_bytes: return capnp_decorator if generate_wrapper: return GenerateWrapper if recursive_serde: return rs_decorator return serializable_decorator
# stdlib from typing import Any from typing import Callable as CallableT import warnings # third party from google.protobuf.reflection import GeneratedProtocolMessageType # syft absolute import syft # relative from ....util import aggressive_set_attr from .deserialize import CAPNP_REGISTRY module_type = type(syft) # this will overwrite the ._sy_serializable_wrapper_type with an auto generated # wrapper which will basically just hold the object being wrapped. def GenerateWrapper( wrapped_type: type, import_path: str, protobuf_scheme: GeneratedProtocolMessageType, type_object2proto: CallableT, type_proto2object: CallableT, ) -> None: @serializable() class Wrapper: def __init__(self, value: object): self.obj = value def _object2proto(self) -> Any: return type_object2proto(self.obj) @staticmethod def _proto2object(proto: Any) -> Any: return type_proto2object(proto) @staticmethod def get_protobuf_schema() -> GeneratedProtocolMessageType: return protobuf_scheme def upcast(self) -> Any: return self.obj @staticmethod def wrapped_type() -> type: return wrapped_type # TODO: refactor like proxy class to get correct name # WARNING: Changing this can break the Wrapper lookup during deserialize module_parts = import_path.split(".") klass = module_parts.pop() Wrapper.__name__ = f"{klass}Wrapper" Wrapper.__module__ = f"syft.wrappers.{'.'.join(module_parts)}" # create a fake module `wrappers` under `syft` if "wrappers" not in syft.__dict__: syft.__dict__["wrappers"] = module_type(name="wrappers") # for each part of the path, create a fake module and add it to it's parent parent = syft.__dict__["wrappers"] for n in module_parts: if n not in parent.__dict__: parent.__dict__[n] = module_type(name=n) parent = parent.__dict__[n] # finally add our wrapper class to the end of the path parent.__dict__[Wrapper.__name__] = Wrapper aggressive_set_attr( obj=wrapped_type, name="_sy_serializable_wrapper_type", attr=Wrapper ) def GenerateProtobufWrapper( cls_pb: GeneratedProtocolMessageType, import_path: str ) -> None: def object2proto(obj: Any) -> Any: return obj def proto2object(proto: Any) -> Any: return proto GenerateWrapper( wrapped_type=cls_pb, import_path=import_path, protobuf_scheme=cls_pb, type_object2proto=object2proto, type_proto2object=proto2object, ) def serializable( generate_wrapper: bool = False, protobuf_object: bool = False, recursive_serde: bool = False, capnp_bytes: bool = False, ) -> Any: def rs_decorator(cls: Any) -> Any: # relative from .recursive import rs_get_protobuf_schema from .recursive import rs_object2proto from .recursive import rs_proto2object if not hasattr(cls, "__attr_allowlist__"): warnings.warn( f"__attr_allowlist__ not defined for type {cls.__name__}," " even if it uses recursive serde, defaulting on the empty list." ) cls.__attr_allowlist__ = [] if not hasattr(cls, "__serde_overrides__"): cls.__serde_overrides__ = {} cls._object2proto = rs_object2proto cls._proto2object = staticmethod(rs_proto2object) cls.get_protobuf_schema = staticmethod(rs_get_protobuf_schema) return cls def serializable_decorator(cls: Any) -> Any: protobuf_schema = cls.get_protobuf_schema() # overloading a protobuf by adding multiple classes and we will check the # obj_type string later to dispatch to the correct one if hasattr(protobuf_schema, "schema2type"): if isinstance(protobuf_schema.schema2type, list): protobuf_schema.schema2type.append(cls) else: protobuf_schema.schema2type = [protobuf_schema.schema2type, cls] else: protobuf_schema.schema2type = cls return cls def capnp_decorator(cls: Any) -> Any: # register deserialize with the capnp registry CAPNP_REGISTRY[cls.__name__] = cls._bytes2object return cls if capnp_bytes: return capnp_decorator if generate_wrapper: return GenerateWrapper if recursive_serde: return rs_decorator return serializable_decorator
#!/usr/bin/env python # Licensed to Elasticsearch B.V under one or more agreements. # Elasticsearch B.V licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information import json import tempfile import collections import black from click.testing import CliRunner from jinja2 import Environment, FileSystemLoader from pathlib import Path code_root = Path(__file__).absolute().parent.parent asciidocs_dir = code_root / "docs/examples" flight_recorder_dir = code_root.parent / "clients-flight-recorder" report_path = flight_recorder_dir / "recordings/docs/parsed-alternative-report.json" substitutions = {"type": "doc_type", "from": "from_"} jinja_env = Environment( loader=FileSystemLoader([code_root / "utils" / "templates"]), trim_blocks=True, lstrip_blocks=True, ) files_to_generate = [ "search/request-body.asciidoc", "mapping.asciidoc", "query-dsl.asciidoc", "query-dsl/query-string-query.asciidoc", "getting-started.asciidoc", "query-dsl/query_filter_context.asciidoc", "query-dsl/bool-query.asciidoc", "query-dsl/match-query.asciidoc", "indices/create-index.asciidoc", "docs/index_.asciidoc", "aggregations/bucket/terms-aggregation.asciidoc", "query-dsl/range-query.asciidoc", "/search/search.asciidoc", "query-dsl/multi-match-query.asciidoc", "docs/bulk.asciidoc", "indices/delete-index.asciidoc", "indices/put-mapping.asciidoc", "docs/reindex.asciidoc", "query-dsl/term-query.asciidoc", "indices/templates.asciidoc", "getting-started.asciidoc", "docs/update.asciidoc", "query-dsl/match-all-query.asciidoc", "docs/get.asciidoc", "query-dsl/wildcard-query.asciidoc", "query-dsl/exists-query.asciidoc", "docs/delete-by-query.asciidoc", "mapping/params/format.asciidoc", "mapping/types/nested.asciidoc", "query-dsl/terms-query.asciidoc", "search/request/sort.asciidoc", "mapping/types/date.asciidoc", "indices/update-settings.asciidoc", "indices/aliases.asciidoc", "setup/install/check-running.asciidoc", "query-dsl/regexp-query.asciidoc", "query-dsl/function-score-query.asciidoc", "search/request/from-size.asciidoc", "cluster/health.asciidoc", "query-dsl/nested-query.asciidoc", "mapping/types/array.asciidoc", "mapping/params/fielddata.asciidoc", "search/count.asciidoc", "mapping/types/keyword.asciidoc", "docs/update-by-query.asciidoc", "search/suggesters.asciidoc", "api-conventions.asciidoc", "cat/indices.asciidoc", "query-dsl/match-phrase-query.asciidoc", "indices/get-index.asciidoc", "setup/logging-config.asciidoc", "docs/delete.asciidoc", "aggregations/metrics/valuecount-aggregation.asciidoc", "indices/get-mapping.asciidoc", "aggregations/bucket/filter-aggregation.asciidoc", "aggregations/bucket/datehistogram-aggregation.asciidoc", "mapping/types/numeric.asciidoc", "search/request/scroll.asciidoc", "mapping/fields/id-field.asciidoc", "search.asciidoc", "mapping/params/multi-fields.asciidoc", ] ParsedSource = collections.namedtuple("ParsedSource", ["api", "params", "body"]) def blacken(filename): runner = CliRunner() result = runner.invoke( black.main, [str(filename), "--line-length=75", "--target-version=py27"] ) assert result.exit_code == 0, result.output def main(): for filepath in asciidocs_dir.iterdir(): if filepath.name.endswith(".asciidoc"): filepath.unlink() if not flight_recorder_dir.exists() or not report_path.exists(): raise RuntimeError( f"clients-flight-recorder repository not checked out at {flight_recorder_dir}" ) with report_path.open() as f: report = json.loads(f.read()) t = jinja_env.get_template("example") for exm in report: if exm["lang"] != "console": continue if exm["source_location"]["file"] not in files_to_generate: continue parsed_sources = [] for src in exm["parsed_source"]: params = (src.get("params") or {}).copy() params.update(src.get("query") or {}) params = {k: (list(v.split(",")) if isinstance(v, str) and "," in v else v) for k, v in params.items()} parsed_sources.append( ParsedSource( api=src["api"], params={ substitutions.get(k, k): repr(v) for k, v in params.items() }, body=src.get("body", None) or None, ) ) tmp_path = Path(tempfile.mktemp()) with tmp_path.open(mode="w") as f: f.write(t.render(parsed_sources=parsed_sources)) blacken(tmp_path) with tmp_path.open(mode="r") as f: data = f.read() data = data.rstrip().replace(",)", ")") tmp_path.unlink() with (asciidocs_dir / f"{exm["digest"]}.asciidoc").open(mode="w") as f: f.truncate() f.write( f"""// {exm['source_location']['file']}:{exm['source_location']['line']} [source, python] ---- {data} ----""" ) if __name__ == "__main__": main()
#!/usr/bin/env python # Licensed to Elasticsearch B.V under one or more agreements. # Elasticsearch B.V licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information import json import tempfile import collections import black from click.testing import CliRunner from jinja2 import Environment, FileSystemLoader from pathlib import Path code_root = Path(__file__).absolute().parent.parent asciidocs_dir = code_root / "docs/examples" flight_recorder_dir = code_root.parent / "clients-flight-recorder" report_path = flight_recorder_dir / "recordings/docs/parsed-alternative-report.json" substitutions = {"type": "doc_type", "from": "from_"} jinja_env = Environment( loader=FileSystemLoader([code_root / "utils" / "templates"]), trim_blocks=True, lstrip_blocks=True, ) files_to_generate = [ "search/request-body.asciidoc", "mapping.asciidoc", "query-dsl.asciidoc", "query-dsl/query-string-query.asciidoc", "getting-started.asciidoc", "query-dsl/query_filter_context.asciidoc", "query-dsl/bool-query.asciidoc", "query-dsl/match-query.asciidoc", "indices/create-index.asciidoc", "docs/index_.asciidoc", "aggregations/bucket/terms-aggregation.asciidoc", "query-dsl/range-query.asciidoc", "/search/search.asciidoc", "query-dsl/multi-match-query.asciidoc", "docs/bulk.asciidoc", "indices/delete-index.asciidoc", "indices/put-mapping.asciidoc", "docs/reindex.asciidoc", "query-dsl/term-query.asciidoc", "indices/templates.asciidoc", "getting-started.asciidoc", "docs/update.asciidoc", "query-dsl/match-all-query.asciidoc", "docs/get.asciidoc", "query-dsl/wildcard-query.asciidoc", "query-dsl/exists-query.asciidoc", "docs/delete-by-query.asciidoc", "mapping/params/format.asciidoc", "mapping/types/nested.asciidoc", "query-dsl/terms-query.asciidoc", "search/request/sort.asciidoc", "mapping/types/date.asciidoc", "indices/update-settings.asciidoc", "indices/aliases.asciidoc", "setup/install/check-running.asciidoc", "query-dsl/regexp-query.asciidoc", "query-dsl/function-score-query.asciidoc", "search/request/from-size.asciidoc", "cluster/health.asciidoc", "query-dsl/nested-query.asciidoc", "mapping/types/array.asciidoc", "mapping/params/fielddata.asciidoc", "search/count.asciidoc", "mapping/types/keyword.asciidoc", "docs/update-by-query.asciidoc", "search/suggesters.asciidoc", "api-conventions.asciidoc", "cat/indices.asciidoc", "query-dsl/match-phrase-query.asciidoc", "indices/get-index.asciidoc", "setup/logging-config.asciidoc", "docs/delete.asciidoc", "aggregations/metrics/valuecount-aggregation.asciidoc", "indices/get-mapping.asciidoc", "aggregations/bucket/filter-aggregation.asciidoc", "aggregations/bucket/datehistogram-aggregation.asciidoc", "mapping/types/numeric.asciidoc", "search/request/scroll.asciidoc", "mapping/fields/id-field.asciidoc", "search.asciidoc", "mapping/params/multi-fields.asciidoc", ] ParsedSource = collections.namedtuple("ParsedSource", ["api", "params", "body"]) def blacken(filename): runner = CliRunner() result = runner.invoke( black.main, [str(filename), "--line-length=75", "--target-version=py27"] ) assert result.exit_code == 0, result.output def main(): for filepath in asciidocs_dir.iterdir(): if filepath.name.endswith(".asciidoc"): filepath.unlink() if not flight_recorder_dir.exists() or not report_path.exists(): raise RuntimeError( f"clients-flight-recorder repository not checked out at {flight_recorder_dir}" ) with report_path.open() as f: report = json.loads(f.read()) t = jinja_env.get_template("example") for exm in report: if exm["lang"] != "console": continue if exm["source_location"]["file"] not in files_to_generate: continue parsed_sources = [] for src in exm["parsed_source"]: params = (src.get("params") or {}).copy() params.update(src.get("query") or {}) params = {k: (list(v.split(",")) if isinstance(v, str) and "," in v else v) for k, v in params.items()} parsed_sources.append( ParsedSource( api=src["api"], params={ substitutions.get(k, k): repr(v) for k, v in params.items() }, body=src.get("body", None) or None, ) ) tmp_path = Path(tempfile.mktemp()) with tmp_path.open(mode="w") as f: f.write(t.render(parsed_sources=parsed_sources)) blacken(tmp_path) with tmp_path.open(mode="r") as f: data = f.read() data = data.rstrip().replace(",)", ")") tmp_path.unlink() with (asciidocs_dir / f"{exm['digest']}.asciidoc").open(mode="w") as f: f.truncate() f.write( f"""// {exm['source_location']['file']}:{exm['source_location']['line']} [source, python] ---- {data} ----""" ) if __name__ == "__main__": main()
from decimal import Decimal import eth_abi import pytest from vyper.exceptions import ( ArgumentException, EventDeclarationException, InvalidType, NamespaceCollision, TypeMismatch, UndeclaredDefinition, ) from vyper.utils import keccak256 pytestmark = pytest.mark.usefixtures("memory_mocker") def test_empty_event_logging(w3, tester, keccak, get_contract_with_gas_estimation): loggy_code = """ event MyLog: pass @external def foo(): log MyLog() """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog()", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [], "anonymous": False, "type": "event", } # Event is decoded correctly assert hasattr(c._classic_contract.events, "MyLog") def test_event_logging_with_topics(w3, tester, keccak, get_logs, get_contract_with_gas_estimation): loggy_code = """ a: Bytes[3] event MyLog: arg1: indexed(Bytes[3]) @external def foo(): self.a = b"bar" log MyLog(self.a) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(bytes)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [{"type": "bytes", "name": "arg1", "indexed": True}], "anonymous": False, "type": "event", } def test_event_logging_with_multiple_topics( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: indexed(int128) arg2: indexed(bool) arg3: indexed(address) @external def foo(): log MyLog(-2, True, self) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(int128,bool,address)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "int128", "name": "arg1", "indexed": True}, {"type": "bool", "name": "arg2", "indexed": True}, {"type": "address", "name": "arg3", "indexed": True}, ], "anonymous": False, "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") assert logs[0].event == "MyLog" assert logs[0].args.arg1 == -2 assert logs[0].args.arg2 is True assert logs[0].args.arg3 == c._classic_contract.address def test_event_logging_with_multiple_topics_var_and_store( tester, get_contract_with_gas_estimation, get_logs ): code = """ event MyLog: arg1: indexed(int128) arg2: indexed(bool) arg3: indexed(address) b: address @external def foo(arg1: int128): a: bool = True self.b = self log MyLog(arg1, a, self.b) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(31337, transact={}) # Event is decoded correctly log = get_logs(tx_hash, c, "MyLog")[0] assert log.args.arg1 == 31337 assert log.args.arg2 is True assert log.args.arg3 == c.address def test_logging_the_same_event_multiple_times_with_topics( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: indexed(int128) arg2: indexed(address) @external def foo(): log MyLog(1, self) log MyLog(1, self) @external def bar(): log MyLog(1, self) log MyLog(1, self) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash1 = c.foo(transact={}) tx_hash2 = c.bar(transact={}) receipt1 = tester.get_transaction_receipt(tx_hash1.hex()) receipt2 = tester.get_transaction_receipt(tx_hash2.hex()) event_id = keccak(bytes("MyLog(int128,address)", "utf-8")) # Event id is always the first topic assert receipt1["logs"][0]["topics"][0] == event_id.hex() assert receipt2["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "int128", "name": "arg1", "indexed": True}, {"type": "address", "name": "arg2", "indexed": True}, ], "anonymous": False, "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash1, c, "MyLog") assert logs[0].args.arg1 == 1 assert logs[0].args.arg2 == c.address assert logs[1].args.arg1 == 1 assert logs[1].args.arg2 == c.address def test_event_logging_cannot_have_more_than_three_topics( assert_tx_failed, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: indexed(Bytes[3]) arg2: indexed(Bytes[4]) arg3: indexed(address) arg4: indexed(int128) """ assert_tx_failed( lambda: get_contract_with_gas_estimation(loggy_code), EventDeclarationException ) def test_event_logging_with_data(w3, tester, keccak, get_logs, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: int128 @external def foo(): log MyLog(123) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(int128)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [{"type": "int128", "name": "arg1", "indexed": False}], "anonymous": False, "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == 123 def test_event_logging_with_fixed_array_data( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: int128[2] arg2: uint256[3] arg3: int128[2][2] @external def foo(): log MyLog([1,2], [block.timestamp, block.timestamp+1, block.timestamp+2], [[1,2],[1,2]]) log MyLog([1,2], [block.timestamp, block.timestamp+1, block.timestamp+2], [[1,2],[1,2]]) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(int128[2],uint256[3],int128[2][2])", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "int128[2]", "name": "arg1", "indexed": False}, {"type": "uint256[3]", "name": "arg2", "indexed": False}, {"type": "int128[2][2]", "name": "arg3", "indexed": False}, ], "anonymous": False, "type": "event", } # Event is decoded correctly timestamp = w3.eth.get_block(w3.eth.block_number).timestamp logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == [1, 2] assert logs[0].args.arg2 == [timestamp, timestamp + 1, timestamp + 2] assert logs[0].args.arg3 == [[1, 2], [1, 2]] def test_logging_with_input_bytes_1( w3, tester, keccak, get_logs, bytes_helper, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: Bytes[4] arg2: indexed(Bytes[29]) arg3: Bytes[31] @external def foo(arg1: Bytes[29], arg2: Bytes[31]): log MyLog(b'bar', arg1, arg2) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(b"bar", b"foo", transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(bytes,bytes,bytes)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "bytes", "name": "arg1", "indexed": False}, {"type": "bytes", "name": "arg2", "indexed": True}, {"type": "bytes", "name": "arg3", "indexed": False}, ], "anonymous": False, "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == b"bar" assert logs[0].args.arg2 == keccak(b"bar") assert logs[0].args.arg3 == b"foo" def test_event_logging_with_bytes_input_2( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: Bytes[20] @external def foo(_arg1: Bytes[20]): log MyLog(_arg1) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(b"hello", transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(bytes)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "anonymous": False, "inputs": [{"indexed": False, "name": "arg1", "type": "bytes"}], "name": "MyLog", "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == b"hello" def test_event_logging_with_bytes_input_3(w3, tester, keccak, get_logs, get_contract): loggy_code = """ event MyLog: arg1: Bytes[5] @external def foo(_arg1: Bytes[5]): log MyLog(_arg1) """ c = get_contract(loggy_code) tx_hash = c.foo(b"hello", transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(bytes)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "anonymous": False, "inputs": [{"indexed": False, "name": "arg1", "type": "bytes"}], "name": "MyLog", "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == b"hello" def test_event_logging_with_data_with_different_types( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: int128 arg2: Bytes[4] arg3: Bytes[3] arg4: address arg5: address arg6: uint256 @external def foo(): log MyLog(123, b'home', b'bar', 0xc305c901078781C232A2a521C2aF7980f8385ee9, self, block.timestamp) # noqa: E501 """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(int128,bytes,bytes,address,address,uint256)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "int128", "name": "arg1", "indexed": False}, {"type": "bytes", "name": "arg2", "indexed": False}, {"type": "bytes", "name": "arg3", "indexed": False}, {"type": "address", "name": "arg4", "indexed": False}, {"type": "address", "name": "arg5", "indexed": False}, {"type": "uint256", "name": "arg6", "indexed": False}, ], "anonymous": False, "type": "event", } # Event is decoded correctly timestamp = w3.eth.get_block(w3.eth.block_number).timestamp logs = get_logs(tx_hash, c, "MyLog") args = logs[0].args assert args.arg1 == 123 assert args.arg2 == b"home" assert args.arg3 == b"bar" assert args.arg4 == "0xc305c901078781C232A2a521C2aF7980f8385ee9" assert args.arg5 == c.address assert args.arg6 == timestamp def test_event_logging_with_topics_and_data_1( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: indexed(int128) arg2: Bytes[3] @external def foo(): log MyLog(1, b'bar') """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(int128,bytes)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "anonymous": False, "inputs": [ {"indexed": True, "name": "arg1", "type": "int128"}, {"indexed": False, "name": "arg2", "type": "bytes"}, ], "name": "MyLog", "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") args = logs[0].args assert args.arg1 == 1 assert args.arg2 == b"bar" def test_event_logging_with_multiple_logs_topics_and_data( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: indexed(int128) arg2: Bytes[3] event YourLog: arg1: indexed(address) arg2: Bytes[5] @external def foo(): log MyLog(1, b'bar') log YourLog(self, b'house') """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) logs1 = receipt["logs"][0] logs2 = receipt["logs"][1] event_id1 = keccak(bytes("MyLog(int128,bytes)", "utf-8")) event_id2 = keccak(bytes("YourLog(address,bytes)", "utf-8")) # Event id is always the first topic assert logs1["topics"][0] == event_id1.hex() assert logs2["topics"][0] == event_id2.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "int128", "name": "arg1", "indexed": True}, {"type": "bytes", "name": "arg2", "indexed": False}, ], "anonymous": False, "type": "event", } assert c._classic_contract.abi[1] == { "name": "YourLog", "inputs": [ {"type": "address", "name": "arg1", "indexed": True}, {"type": "bytes", "name": "arg2", "indexed": False}, ], "anonymous": False, "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") args = logs[0].args assert args.arg1 == 1 assert args.arg2 == b"bar" logs = get_logs(tx_hash, c, "YourLog") args = logs[0].args assert args.arg1 == c.address assert args.arg2 == b"house" def test_fails_when_input_is_the_wrong_type(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: indexed(int128) @external def foo_(): log MyLog(b'yo') """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), InvalidType) def test_fails_when_topic_is_the_wrong_size(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: indexed(Bytes[3]) @external def foo(): log MyLog(b'bars') """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), InvalidType) def test_fails_when_input_topic_is_the_wrong_size( assert_tx_failed, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: indexed(Bytes[3]) @external def foo(arg1: Bytes[4]): log MyLog(arg1) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), TypeMismatch) def test_fails_when_data_is_the_wrong_size(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: Bytes[3] @external def foo(): log MyLog(b'bars') """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), InvalidType) def test_fails_when_input_data_is_the_wrong_size( assert_tx_failed, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: Bytes[3] @external def foo(arg1: Bytes[4]): log MyLog(arg1) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), TypeMismatch) def test_topic_over_32_bytes(get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: indexed(Bytes[100]) @external def foo(): pass """ get_contract_with_gas_estimation(loggy_code) def test_logging_fails_with_over_three_topics(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: indexed(int128) arg2: indexed(int128) arg3: indexed(int128) arg4: indexed(int128) @external def __init__(): log MyLog(1, 2, 3, 4) """ assert_tx_failed( lambda: get_contract_with_gas_estimation(loggy_code), EventDeclarationException ) def test_logging_fails_with_duplicate_log_names(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: pass event MyLog: pass @external def foo(): log MyLog() """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), NamespaceCollision) def test_logging_fails_with_when_log_is_undeclared( assert_tx_failed, get_contract_with_gas_estimation ): loggy_code = """ @external def foo(): log MyLog() """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), UndeclaredDefinition) def test_logging_fails_with_topic_type_mismatch(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: indexed(int128) @external def foo(): log MyLog(self) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), TypeMismatch) def test_logging_fails_with_data_type_mismatch(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: Bytes[3] @external def foo(): log MyLog(self) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), TypeMismatch) def test_logging_fails_when_number_of_arguments_is_greater_than_declaration( assert_tx_failed, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: int128 @external def foo(): log MyLog(1, 2) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), ArgumentException) def test_logging_fails_when_number_of_arguments_is_less_than_declaration( assert_tx_failed, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: int128 arg2: int128 @external def foo(): log MyLog(1) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), ArgumentException) def test_loggy_code(w3, tester, get_contract_with_gas_estimation): loggy_code = """ s: Bytes[100] @external def foo(): raw_log([], b"moo") @external def goo(): raw_log([0x1234567812345678123456781234567812345678123456781234567812345678], b"moo2") @external def hoo(): self.s = b"moo3" raw_log([], self.s) @external def ioo(inp: Bytes[100]): raw_log([], inp) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) logs = receipt["logs"] assert w3.toText(logs[0]["data"]) == "moo" tx_hash = c.goo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) logs = receipt["logs"] assert w3.toText(logs[0]["data"]) == "moo2" assert ( logs[0]["topics"][0] == "0x1234567812345678123456781234567812345678123456781234567812345678" ) # noqa: E501 tx_hash = c.hoo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) logs = receipt["logs"] assert w3.toText(logs[0]["data"]) == "moo3" tx_hash = c.ioo(b"moo4", transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) logs = receipt["logs"] assert w3.toText(logs[0]["data"]) == "moo4" print("Passed raw log tests") def test_raw_call_bytes32_data(w3, tester, get_contract_with_gas_estimation): code = """ b: uint256 @external def foo(): a: uint256 = 1234 self.b = 4321 raw_log([], convert(a, bytes32)) raw_log([], convert(self.b, bytes32)) raw_log([], convert(b"testmessage", bytes32)) raw_log([], keccak256(b"")) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) logs = receipt["logs"] assert logs[0]["data"] == w3.toHex((1234).to_bytes(32, "big")) assert logs[1]["data"] == w3.toHex((4321).to_bytes(32, "big")) assert logs[2]["data"] == w3.toHex(b"testmessage").ljust(32 * 2 + 2, "0") assert logs[3]["data"] == w3.toHex(keccak256(b"")) def test_variable_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: _value: int128[4] @external def foo(): a: int128[4] = [1, 2, 3, 4] log Bar(a) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [1, 2, 3, 4] def test_literal_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: _value: int128[4] @external def foo(): log Bar([1, 2, 3, 4]) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [1, 2, 3, 4] def test_storage_list_packing(get_logs, bytes_helper, get_contract_with_gas_estimation): code = """ event Bar: _value: int128[4] x: int128[4] @external def foo(): log Bar(self.x) @external def set_list(): self.x = [1, 2, 3, 4] """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [0, 0, 0, 0] c.set_list(transact={}) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [1, 2, 3, 4] def test_passed_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: _value: int128[4] @external def foo(barbaric: int128[4]): log Bar(barbaric) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo([4, 5, 6, 7], transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [4, 5, 6, 7] def test_variable_decimal_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: _value: decimal[4] @external def foo(): log Bar([1.11, 2.22, 3.33, 4.44]) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [ Decimal("1.11"), Decimal("2.22"), Decimal("3.33"), Decimal("4.44"), ] def test_storage_byte_packing(get_logs, bytes_helper, get_contract_with_gas_estimation): code = """ event MyLog: arg1: Bytes[29] x:Bytes[5] @external def foo(a: int128): log MyLog(self.x) @external def setbytez(): self.x = b'hello' """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(0, transact={}) logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == b"" c.setbytez(transact={}) tx_hash = c.foo(0, transact={}) logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == b"hello" def test_storage_decimal_list_packing(get_logs, bytes_helper, get_contract_with_gas_estimation): code = """ event Bar: _value: decimal[4] x: decimal[4] @external def foo(): log Bar(self.x) @external def set_list(): self.x = [1.33, 2.33, 3.33, 4.33] """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [Decimal("0"), Decimal("0"), Decimal("0"), Decimal("0")] c.set_list(transact={}) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [ Decimal("1.33"), Decimal("2.33"), Decimal("3.33"), Decimal("4.33"), ] def test_logging_fails_when_input_is_too_big(assert_tx_failed, get_contract_with_gas_estimation): code = """ event Bar: _value: indexed(Bytes[32]) @external def foo(inp: Bytes[33]): log Bar(inp) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(code), TypeMismatch) def test_2nd_var_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: arg1: int128 arg2: int128[4] @external def foo(): a: int128[4] = [1, 2, 3, 4] log Bar(10, a) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) assert get_logs(tx_hash, c, "Bar")[0].args.arg2 == [1, 2, 3, 4] def test_2nd_var_storage_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: arg1: int128 arg2: int128[4] x: int128[4] @external def foo(): log Bar(10, self.x) @external def set_list(): self.x = [1, 2, 3, 4] """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) assert get_logs(tx_hash, c, "Bar")[0].args.arg2 == [0, 0, 0, 0] c.set_list(transact={}) tx_hash = c.foo(transact={}) assert get_logs(tx_hash, c, "Bar")[0].args.arg2 == [1, 2, 3, 4] def test_mixed_var_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: arg1: int128 arg2: int128[4] arg3 :Bytes[4] arg4: int128[3] arg5: int128[2] x: int128[4] y: int128[2] @external def __init__(): self.y = [1024, 2048] @external def foo(): v: int128[3] = [7, 8, 9] log Bar(10, self.x, b"test", v, self.y) @external def set_list(): self.x = [1, 2, 3, 4] """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) log = get_logs(tx_hash, c, "Bar")[0] assert log.args["arg2"] == [0, 0, 0, 0] assert log.args["arg3"] == b"test" assert log.args["arg4"] == [7, 8, 9] assert log.args["arg5"] == [1024, 2048] c.set_list(transact={}) tx_hash = c.foo(transact={}) log = get_logs(tx_hash, c, "Bar")[0] assert log.args["arg2"] == [1, 2, 3, 4] assert log.args["arg3"] == b"test" assert log.args["arg4"] == [7, 8, 9] assert log.args["arg5"] == [1024, 2048] def test_hashed_indexed_topics_calldata(tester, keccak, get_contract): loggy_code = """ event MyLog: arg1: indexed(Bytes[36]) arg2: indexed(int128) arg3: indexed(String[7]) @external def foo(a: Bytes[36], b: int128, c: String[7]): log MyLog(a, b, c) """ c = get_contract(loggy_code) tx_hash = c.foo(b"bar", 1, "weird", transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) # Event id is always the first topic event_id = keccak(b"MyLog(bytes,int128,string)") assert receipt["logs"][0]["topics"][0] == event_id.hex() topic1 = f"0x{keccak256(b"bar").hex()}" assert receipt["logs"][0]["topics"][1] == topic1 topic2 = f"0x{eth_abi.encode_single("int128", 1).hex()}" assert receipt["logs"][0]["topics"][2] == topic2 topic3 = f"0x{keccak256(b"weird").hex()}" assert receipt["logs"][0]["topics"][3] == topic3 # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "bytes", "name": "arg1", "indexed": True}, {"type": "int128", "name": "arg2", "indexed": True}, {"type": "string", "name": "arg3", "indexed": True}, ], "anonymous": False, "type": "event", } def test_hashed_indexed_topics_memory(tester, keccak, get_contract): loggy_code = """ event MyLog: arg1: indexed(Bytes[10]) arg2: indexed(int128) arg3: indexed(String[44]) @external def foo(): a: Bytes[10] = b"potato" b: int128 = -777 c: String[44] = "why hello, neighbor! how are you today?" log MyLog(a, b, c) """ c = get_contract(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) # Event id is always the first topic event_id = keccak(b"MyLog(bytes,int128,string)") assert receipt["logs"][0]["topics"][0] == event_id.hex() topic1 = f"0x{keccak256(b"potato").hex()}" assert receipt["logs"][0]["topics"][1] == topic1 topic2 = f"0x{eth_abi.encode_single("int128", -777).hex()}" assert receipt["logs"][0]["topics"][2] == topic2 topic3 = f"0x{keccak256(b"why hello, neighbor! how are you today?").hex()}" assert receipt["logs"][0]["topics"][3] == topic3 # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "bytes", "name": "arg1", "indexed": True}, {"type": "int128", "name": "arg2", "indexed": True}, {"type": "string", "name": "arg3", "indexed": True}, ], "anonymous": False, "type": "event", } def test_hashed_indexed_topics_storage(tester, keccak, get_contract): loggy_code = """ event MyLog: arg1: indexed(Bytes[32]) arg2: indexed(int128) arg3: indexed(String[6]) a: Bytes[32] b: int128 c: String[6] @external def setter(_a: Bytes[32], _b: int128, _c: String[6]): self.a = _a self.b = _b self.c = _c @external def foo(): log MyLog(self.a, self.b, self.c) """ c = get_contract(loggy_code) c.setter(b"zonk", -2109, "yessir", transact={}) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) # Event id is always the first topic event_id = keccak(b"MyLog(bytes,int128,string)") assert receipt["logs"][0]["topics"][0] == event_id.hex() topic1 = f"0x{keccak256(b"zonk").hex()}" assert receipt["logs"][0]["topics"][1] == topic1 topic2 = f"0x{eth_abi.encode_single("int128", -2109).hex()}" assert receipt["logs"][0]["topics"][2] == topic2 topic3 = f"0x{keccak256(b"yessir").hex()}" assert receipt["logs"][0]["topics"][3] == topic3 # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "bytes", "name": "arg1", "indexed": True}, {"type": "int128", "name": "arg2", "indexed": True}, {"type": "string", "name": "arg3", "indexed": True}, ], "anonymous": False, "type": "event", } def test_hashed_indexed_topics_storxxage(tester, keccak, get_contract): loggy_code = """ event MyLog: arg1: indexed(Bytes[64]) arg2: indexed(int128) arg3: indexed(String[21]) @external def foo(): log MyLog(b"wow", 666, "madness!") """ c = get_contract(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) # Event id is always the first topic event_id = keccak(b"MyLog(bytes,int128,string)") assert receipt["logs"][0]["topics"][0] == event_id.hex() topic1 = f"0x{keccak256(b"wow").hex()}" assert receipt["logs"][0]["topics"][1] == topic1 topic2 = f"0x{eth_abi.encode_single("int128", 666).hex()}" assert receipt["logs"][0]["topics"][2] == topic2 topic3 = f"0x{keccak256(b"madness!").hex()}" assert receipt["logs"][0]["topics"][3] == topic3
from decimal import Decimal import eth_abi import pytest from vyper.exceptions import ( ArgumentException, EventDeclarationException, InvalidType, NamespaceCollision, TypeMismatch, UndeclaredDefinition, ) from vyper.utils import keccak256 pytestmark = pytest.mark.usefixtures("memory_mocker") def test_empty_event_logging(w3, tester, keccak, get_contract_with_gas_estimation): loggy_code = """ event MyLog: pass @external def foo(): log MyLog() """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog()", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [], "anonymous": False, "type": "event", } # Event is decoded correctly assert hasattr(c._classic_contract.events, "MyLog") def test_event_logging_with_topics(w3, tester, keccak, get_logs, get_contract_with_gas_estimation): loggy_code = """ a: Bytes[3] event MyLog: arg1: indexed(Bytes[3]) @external def foo(): self.a = b"bar" log MyLog(self.a) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(bytes)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [{"type": "bytes", "name": "arg1", "indexed": True}], "anonymous": False, "type": "event", } def test_event_logging_with_multiple_topics( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: indexed(int128) arg2: indexed(bool) arg3: indexed(address) @external def foo(): log MyLog(-2, True, self) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(int128,bool,address)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "int128", "name": "arg1", "indexed": True}, {"type": "bool", "name": "arg2", "indexed": True}, {"type": "address", "name": "arg3", "indexed": True}, ], "anonymous": False, "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") assert logs[0].event == "MyLog" assert logs[0].args.arg1 == -2 assert logs[0].args.arg2 is True assert logs[0].args.arg3 == c._classic_contract.address def test_event_logging_with_multiple_topics_var_and_store( tester, get_contract_with_gas_estimation, get_logs ): code = """ event MyLog: arg1: indexed(int128) arg2: indexed(bool) arg3: indexed(address) b: address @external def foo(arg1: int128): a: bool = True self.b = self log MyLog(arg1, a, self.b) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(31337, transact={}) # Event is decoded correctly log = get_logs(tx_hash, c, "MyLog")[0] assert log.args.arg1 == 31337 assert log.args.arg2 is True assert log.args.arg3 == c.address def test_logging_the_same_event_multiple_times_with_topics( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: indexed(int128) arg2: indexed(address) @external def foo(): log MyLog(1, self) log MyLog(1, self) @external def bar(): log MyLog(1, self) log MyLog(1, self) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash1 = c.foo(transact={}) tx_hash2 = c.bar(transact={}) receipt1 = tester.get_transaction_receipt(tx_hash1.hex()) receipt2 = tester.get_transaction_receipt(tx_hash2.hex()) event_id = keccak(bytes("MyLog(int128,address)", "utf-8")) # Event id is always the first topic assert receipt1["logs"][0]["topics"][0] == event_id.hex() assert receipt2["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "int128", "name": "arg1", "indexed": True}, {"type": "address", "name": "arg2", "indexed": True}, ], "anonymous": False, "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash1, c, "MyLog") assert logs[0].args.arg1 == 1 assert logs[0].args.arg2 == c.address assert logs[1].args.arg1 == 1 assert logs[1].args.arg2 == c.address def test_event_logging_cannot_have_more_than_three_topics( assert_tx_failed, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: indexed(Bytes[3]) arg2: indexed(Bytes[4]) arg3: indexed(address) arg4: indexed(int128) """ assert_tx_failed( lambda: get_contract_with_gas_estimation(loggy_code), EventDeclarationException ) def test_event_logging_with_data(w3, tester, keccak, get_logs, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: int128 @external def foo(): log MyLog(123) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(int128)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [{"type": "int128", "name": "arg1", "indexed": False}], "anonymous": False, "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == 123 def test_event_logging_with_fixed_array_data( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: int128[2] arg2: uint256[3] arg3: int128[2][2] @external def foo(): log MyLog([1,2], [block.timestamp, block.timestamp+1, block.timestamp+2], [[1,2],[1,2]]) log MyLog([1,2], [block.timestamp, block.timestamp+1, block.timestamp+2], [[1,2],[1,2]]) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(int128[2],uint256[3],int128[2][2])", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "int128[2]", "name": "arg1", "indexed": False}, {"type": "uint256[3]", "name": "arg2", "indexed": False}, {"type": "int128[2][2]", "name": "arg3", "indexed": False}, ], "anonymous": False, "type": "event", } # Event is decoded correctly timestamp = w3.eth.get_block(w3.eth.block_number).timestamp logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == [1, 2] assert logs[0].args.arg2 == [timestamp, timestamp + 1, timestamp + 2] assert logs[0].args.arg3 == [[1, 2], [1, 2]] def test_logging_with_input_bytes_1( w3, tester, keccak, get_logs, bytes_helper, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: Bytes[4] arg2: indexed(Bytes[29]) arg3: Bytes[31] @external def foo(arg1: Bytes[29], arg2: Bytes[31]): log MyLog(b'bar', arg1, arg2) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(b"bar", b"foo", transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(bytes,bytes,bytes)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "bytes", "name": "arg1", "indexed": False}, {"type": "bytes", "name": "arg2", "indexed": True}, {"type": "bytes", "name": "arg3", "indexed": False}, ], "anonymous": False, "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == b"bar" assert logs[0].args.arg2 == keccak(b"bar") assert logs[0].args.arg3 == b"foo" def test_event_logging_with_bytes_input_2( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: Bytes[20] @external def foo(_arg1: Bytes[20]): log MyLog(_arg1) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(b"hello", transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(bytes)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "anonymous": False, "inputs": [{"indexed": False, "name": "arg1", "type": "bytes"}], "name": "MyLog", "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == b"hello" def test_event_logging_with_bytes_input_3(w3, tester, keccak, get_logs, get_contract): loggy_code = """ event MyLog: arg1: Bytes[5] @external def foo(_arg1: Bytes[5]): log MyLog(_arg1) """ c = get_contract(loggy_code) tx_hash = c.foo(b"hello", transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(bytes)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "anonymous": False, "inputs": [{"indexed": False, "name": "arg1", "type": "bytes"}], "name": "MyLog", "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == b"hello" def test_event_logging_with_data_with_different_types( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: int128 arg2: Bytes[4] arg3: Bytes[3] arg4: address arg5: address arg6: uint256 @external def foo(): log MyLog(123, b'home', b'bar', 0xc305c901078781C232A2a521C2aF7980f8385ee9, self, block.timestamp) # noqa: E501 """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(int128,bytes,bytes,address,address,uint256)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "int128", "name": "arg1", "indexed": False}, {"type": "bytes", "name": "arg2", "indexed": False}, {"type": "bytes", "name": "arg3", "indexed": False}, {"type": "address", "name": "arg4", "indexed": False}, {"type": "address", "name": "arg5", "indexed": False}, {"type": "uint256", "name": "arg6", "indexed": False}, ], "anonymous": False, "type": "event", } # Event is decoded correctly timestamp = w3.eth.get_block(w3.eth.block_number).timestamp logs = get_logs(tx_hash, c, "MyLog") args = logs[0].args assert args.arg1 == 123 assert args.arg2 == b"home" assert args.arg3 == b"bar" assert args.arg4 == "0xc305c901078781C232A2a521C2aF7980f8385ee9" assert args.arg5 == c.address assert args.arg6 == timestamp def test_event_logging_with_topics_and_data_1( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: indexed(int128) arg2: Bytes[3] @external def foo(): log MyLog(1, b'bar') """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) event_id = keccak(bytes("MyLog(int128,bytes)", "utf-8")) # Event id is always the first topic assert receipt["logs"][0]["topics"][0] == event_id.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "anonymous": False, "inputs": [ {"indexed": True, "name": "arg1", "type": "int128"}, {"indexed": False, "name": "arg2", "type": "bytes"}, ], "name": "MyLog", "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") args = logs[0].args assert args.arg1 == 1 assert args.arg2 == b"bar" def test_event_logging_with_multiple_logs_topics_and_data( w3, tester, keccak, get_logs, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: indexed(int128) arg2: Bytes[3] event YourLog: arg1: indexed(address) arg2: Bytes[5] @external def foo(): log MyLog(1, b'bar') log YourLog(self, b'house') """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) logs1 = receipt["logs"][0] logs2 = receipt["logs"][1] event_id1 = keccak(bytes("MyLog(int128,bytes)", "utf-8")) event_id2 = keccak(bytes("YourLog(address,bytes)", "utf-8")) # Event id is always the first topic assert logs1["topics"][0] == event_id1.hex() assert logs2["topics"][0] == event_id2.hex() # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "int128", "name": "arg1", "indexed": True}, {"type": "bytes", "name": "arg2", "indexed": False}, ], "anonymous": False, "type": "event", } assert c._classic_contract.abi[1] == { "name": "YourLog", "inputs": [ {"type": "address", "name": "arg1", "indexed": True}, {"type": "bytes", "name": "arg2", "indexed": False}, ], "anonymous": False, "type": "event", } # Event is decoded correctly logs = get_logs(tx_hash, c, "MyLog") args = logs[0].args assert args.arg1 == 1 assert args.arg2 == b"bar" logs = get_logs(tx_hash, c, "YourLog") args = logs[0].args assert args.arg1 == c.address assert args.arg2 == b"house" def test_fails_when_input_is_the_wrong_type(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: indexed(int128) @external def foo_(): log MyLog(b'yo') """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), InvalidType) def test_fails_when_topic_is_the_wrong_size(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: indexed(Bytes[3]) @external def foo(): log MyLog(b'bars') """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), InvalidType) def test_fails_when_input_topic_is_the_wrong_size( assert_tx_failed, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: indexed(Bytes[3]) @external def foo(arg1: Bytes[4]): log MyLog(arg1) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), TypeMismatch) def test_fails_when_data_is_the_wrong_size(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: Bytes[3] @external def foo(): log MyLog(b'bars') """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), InvalidType) def test_fails_when_input_data_is_the_wrong_size( assert_tx_failed, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: Bytes[3] @external def foo(arg1: Bytes[4]): log MyLog(arg1) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), TypeMismatch) def test_topic_over_32_bytes(get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: indexed(Bytes[100]) @external def foo(): pass """ get_contract_with_gas_estimation(loggy_code) def test_logging_fails_with_over_three_topics(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: indexed(int128) arg2: indexed(int128) arg3: indexed(int128) arg4: indexed(int128) @external def __init__(): log MyLog(1, 2, 3, 4) """ assert_tx_failed( lambda: get_contract_with_gas_estimation(loggy_code), EventDeclarationException ) def test_logging_fails_with_duplicate_log_names(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: pass event MyLog: pass @external def foo(): log MyLog() """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), NamespaceCollision) def test_logging_fails_with_when_log_is_undeclared( assert_tx_failed, get_contract_with_gas_estimation ): loggy_code = """ @external def foo(): log MyLog() """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), UndeclaredDefinition) def test_logging_fails_with_topic_type_mismatch(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: indexed(int128) @external def foo(): log MyLog(self) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), TypeMismatch) def test_logging_fails_with_data_type_mismatch(assert_tx_failed, get_contract_with_gas_estimation): loggy_code = """ event MyLog: arg1: Bytes[3] @external def foo(): log MyLog(self) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), TypeMismatch) def test_logging_fails_when_number_of_arguments_is_greater_than_declaration( assert_tx_failed, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: int128 @external def foo(): log MyLog(1, 2) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), ArgumentException) def test_logging_fails_when_number_of_arguments_is_less_than_declaration( assert_tx_failed, get_contract_with_gas_estimation ): loggy_code = """ event MyLog: arg1: int128 arg2: int128 @external def foo(): log MyLog(1) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(loggy_code), ArgumentException) def test_loggy_code(w3, tester, get_contract_with_gas_estimation): loggy_code = """ s: Bytes[100] @external def foo(): raw_log([], b"moo") @external def goo(): raw_log([0x1234567812345678123456781234567812345678123456781234567812345678], b"moo2") @external def hoo(): self.s = b"moo3" raw_log([], self.s) @external def ioo(inp: Bytes[100]): raw_log([], inp) """ c = get_contract_with_gas_estimation(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) logs = receipt["logs"] assert w3.toText(logs[0]["data"]) == "moo" tx_hash = c.goo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) logs = receipt["logs"] assert w3.toText(logs[0]["data"]) == "moo2" assert ( logs[0]["topics"][0] == "0x1234567812345678123456781234567812345678123456781234567812345678" ) # noqa: E501 tx_hash = c.hoo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) logs = receipt["logs"] assert w3.toText(logs[0]["data"]) == "moo3" tx_hash = c.ioo(b"moo4", transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) logs = receipt["logs"] assert w3.toText(logs[0]["data"]) == "moo4" print("Passed raw log tests") def test_raw_call_bytes32_data(w3, tester, get_contract_with_gas_estimation): code = """ b: uint256 @external def foo(): a: uint256 = 1234 self.b = 4321 raw_log([], convert(a, bytes32)) raw_log([], convert(self.b, bytes32)) raw_log([], convert(b"testmessage", bytes32)) raw_log([], keccak256(b"")) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) logs = receipt["logs"] assert logs[0]["data"] == w3.toHex((1234).to_bytes(32, "big")) assert logs[1]["data"] == w3.toHex((4321).to_bytes(32, "big")) assert logs[2]["data"] == w3.toHex(b"testmessage").ljust(32 * 2 + 2, "0") assert logs[3]["data"] == w3.toHex(keccak256(b"")) def test_variable_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: _value: int128[4] @external def foo(): a: int128[4] = [1, 2, 3, 4] log Bar(a) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [1, 2, 3, 4] def test_literal_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: _value: int128[4] @external def foo(): log Bar([1, 2, 3, 4]) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [1, 2, 3, 4] def test_storage_list_packing(get_logs, bytes_helper, get_contract_with_gas_estimation): code = """ event Bar: _value: int128[4] x: int128[4] @external def foo(): log Bar(self.x) @external def set_list(): self.x = [1, 2, 3, 4] """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [0, 0, 0, 0] c.set_list(transact={}) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [1, 2, 3, 4] def test_passed_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: _value: int128[4] @external def foo(barbaric: int128[4]): log Bar(barbaric) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo([4, 5, 6, 7], transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [4, 5, 6, 7] def test_variable_decimal_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: _value: decimal[4] @external def foo(): log Bar([1.11, 2.22, 3.33, 4.44]) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [ Decimal("1.11"), Decimal("2.22"), Decimal("3.33"), Decimal("4.44"), ] def test_storage_byte_packing(get_logs, bytes_helper, get_contract_with_gas_estimation): code = """ event MyLog: arg1: Bytes[29] x:Bytes[5] @external def foo(a: int128): log MyLog(self.x) @external def setbytez(): self.x = b'hello' """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(0, transact={}) logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == b"" c.setbytez(transact={}) tx_hash = c.foo(0, transact={}) logs = get_logs(tx_hash, c, "MyLog") assert logs[0].args.arg1 == b"hello" def test_storage_decimal_list_packing(get_logs, bytes_helper, get_contract_with_gas_estimation): code = """ event Bar: _value: decimal[4] x: decimal[4] @external def foo(): log Bar(self.x) @external def set_list(): self.x = [1.33, 2.33, 3.33, 4.33] """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [Decimal("0"), Decimal("0"), Decimal("0"), Decimal("0")] c.set_list(transact={}) tx_hash = c.foo(transact={}) logs = get_logs(tx_hash, c, "Bar") assert logs[0].args._value == [ Decimal("1.33"), Decimal("2.33"), Decimal("3.33"), Decimal("4.33"), ] def test_logging_fails_when_input_is_too_big(assert_tx_failed, get_contract_with_gas_estimation): code = """ event Bar: _value: indexed(Bytes[32]) @external def foo(inp: Bytes[33]): log Bar(inp) """ assert_tx_failed(lambda: get_contract_with_gas_estimation(code), TypeMismatch) def test_2nd_var_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: arg1: int128 arg2: int128[4] @external def foo(): a: int128[4] = [1, 2, 3, 4] log Bar(10, a) """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) assert get_logs(tx_hash, c, "Bar")[0].args.arg2 == [1, 2, 3, 4] def test_2nd_var_storage_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: arg1: int128 arg2: int128[4] x: int128[4] @external def foo(): log Bar(10, self.x) @external def set_list(): self.x = [1, 2, 3, 4] """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) assert get_logs(tx_hash, c, "Bar")[0].args.arg2 == [0, 0, 0, 0] c.set_list(transact={}) tx_hash = c.foo(transact={}) assert get_logs(tx_hash, c, "Bar")[0].args.arg2 == [1, 2, 3, 4] def test_mixed_var_list_packing(get_logs, get_contract_with_gas_estimation): code = """ event Bar: arg1: int128 arg2: int128[4] arg3 :Bytes[4] arg4: int128[3] arg5: int128[2] x: int128[4] y: int128[2] @external def __init__(): self.y = [1024, 2048] @external def foo(): v: int128[3] = [7, 8, 9] log Bar(10, self.x, b"test", v, self.y) @external def set_list(): self.x = [1, 2, 3, 4] """ c = get_contract_with_gas_estimation(code) tx_hash = c.foo(transact={}) log = get_logs(tx_hash, c, "Bar")[0] assert log.args["arg2"] == [0, 0, 0, 0] assert log.args["arg3"] == b"test" assert log.args["arg4"] == [7, 8, 9] assert log.args["arg5"] == [1024, 2048] c.set_list(transact={}) tx_hash = c.foo(transact={}) log = get_logs(tx_hash, c, "Bar")[0] assert log.args["arg2"] == [1, 2, 3, 4] assert log.args["arg3"] == b"test" assert log.args["arg4"] == [7, 8, 9] assert log.args["arg5"] == [1024, 2048] def test_hashed_indexed_topics_calldata(tester, keccak, get_contract): loggy_code = """ event MyLog: arg1: indexed(Bytes[36]) arg2: indexed(int128) arg3: indexed(String[7]) @external def foo(a: Bytes[36], b: int128, c: String[7]): log MyLog(a, b, c) """ c = get_contract(loggy_code) tx_hash = c.foo(b"bar", 1, "weird", transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) # Event id is always the first topic event_id = keccak(b"MyLog(bytes,int128,string)") assert receipt["logs"][0]["topics"][0] == event_id.hex() topic1 = f"0x{keccak256(b'bar').hex()}" assert receipt["logs"][0]["topics"][1] == topic1 topic2 = f"0x{eth_abi.encode_single('int128', 1).hex()}" assert receipt["logs"][0]["topics"][2] == topic2 topic3 = f"0x{keccak256(b'weird').hex()}" assert receipt["logs"][0]["topics"][3] == topic3 # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "bytes", "name": "arg1", "indexed": True}, {"type": "int128", "name": "arg2", "indexed": True}, {"type": "string", "name": "arg3", "indexed": True}, ], "anonymous": False, "type": "event", } def test_hashed_indexed_topics_memory(tester, keccak, get_contract): loggy_code = """ event MyLog: arg1: indexed(Bytes[10]) arg2: indexed(int128) arg3: indexed(String[44]) @external def foo(): a: Bytes[10] = b"potato" b: int128 = -777 c: String[44] = "why hello, neighbor! how are you today?" log MyLog(a, b, c) """ c = get_contract(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) # Event id is always the first topic event_id = keccak(b"MyLog(bytes,int128,string)") assert receipt["logs"][0]["topics"][0] == event_id.hex() topic1 = f"0x{keccak256(b'potato').hex()}" assert receipt["logs"][0]["topics"][1] == topic1 topic2 = f"0x{eth_abi.encode_single('int128', -777).hex()}" assert receipt["logs"][0]["topics"][2] == topic2 topic3 = f"0x{keccak256(b'why hello, neighbor! how are you today?').hex()}" assert receipt["logs"][0]["topics"][3] == topic3 # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "bytes", "name": "arg1", "indexed": True}, {"type": "int128", "name": "arg2", "indexed": True}, {"type": "string", "name": "arg3", "indexed": True}, ], "anonymous": False, "type": "event", } def test_hashed_indexed_topics_storage(tester, keccak, get_contract): loggy_code = """ event MyLog: arg1: indexed(Bytes[32]) arg2: indexed(int128) arg3: indexed(String[6]) a: Bytes[32] b: int128 c: String[6] @external def setter(_a: Bytes[32], _b: int128, _c: String[6]): self.a = _a self.b = _b self.c = _c @external def foo(): log MyLog(self.a, self.b, self.c) """ c = get_contract(loggy_code) c.setter(b"zonk", -2109, "yessir", transact={}) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) # Event id is always the first topic event_id = keccak(b"MyLog(bytes,int128,string)") assert receipt["logs"][0]["topics"][0] == event_id.hex() topic1 = f"0x{keccak256(b'zonk').hex()}" assert receipt["logs"][0]["topics"][1] == topic1 topic2 = f"0x{eth_abi.encode_single('int128', -2109).hex()}" assert receipt["logs"][0]["topics"][2] == topic2 topic3 = f"0x{keccak256(b'yessir').hex()}" assert receipt["logs"][0]["topics"][3] == topic3 # Event abi is created correctly assert c._classic_contract.abi[0] == { "name": "MyLog", "inputs": [ {"type": "bytes", "name": "arg1", "indexed": True}, {"type": "int128", "name": "arg2", "indexed": True}, {"type": "string", "name": "arg3", "indexed": True}, ], "anonymous": False, "type": "event", } def test_hashed_indexed_topics_storxxage(tester, keccak, get_contract): loggy_code = """ event MyLog: arg1: indexed(Bytes[64]) arg2: indexed(int128) arg3: indexed(String[21]) @external def foo(): log MyLog(b"wow", 666, "madness!") """ c = get_contract(loggy_code) tx_hash = c.foo(transact={}) receipt = tester.get_transaction_receipt(tx_hash.hex()) # Event id is always the first topic event_id = keccak(b"MyLog(bytes,int128,string)") assert receipt["logs"][0]["topics"][0] == event_id.hex() topic1 = f"0x{keccak256(b'wow').hex()}" assert receipt["logs"][0]["topics"][1] == topic1 topic2 = f"0x{eth_abi.encode_single('int128', 666).hex()}" assert receipt["logs"][0]["topics"][2] == topic2 topic3 = f"0x{keccak256(b'madness!').hex()}" assert receipt["logs"][0]["topics"][3] == topic3
# Copyright 2020 ByteDance 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. import pickle import tensorflow as tf import tensorflow.keras.backend as K from absl import logging from neurst.exps import register_exp from neurst.exps.sequence_generator import SequenceGenerator from neurst.utils import compat from neurst.utils.flags_core import Flag @register_exp(["mask_predict", "mask_generation"]) class MaskSequenceGenerator(SequenceGenerator): """ Entry for sequence generation. """ def __init__(self, args, **kwargs): """ Initializes a util class for sequence generation. """ self._loaded_mask = None if args["mask_pkl"]: logging.info(f"Loading mask from {args["mask_pkl"]}") with tf.io.gfile.GFile(args["mask_pkl"], 'rb') as f: self._loaded_mask = pickle.load(f) super(MaskSequenceGenerator, self).__init__(args, **kwargs) @staticmethod def class_or_method_args(): this_flags = super(MaskSequenceGenerator, MaskSequenceGenerator).class_or_method_args() this_flags.append(Flag("mask_pkl", dtype=Flag.TYPE.STRING, default=None, help="The path to the mask pkl file."), ) return this_flags @staticmethod def build_generation_model(task, model, search_layer, output_sequence_only=True): """ Build keras model for generation. Args: task: The task object. model: An instance of neurst.models.model.BaseModel search_layer: A sequence search object. output_sequence_only: Only generated sequences will output if True. Returns: the generation model. """ if search_layer is None: raise ValueError( "The parameters for generation method must be provided: " "search_method, search_method.params, ...") inps = task.create_inputs(compat.ModeKeys.INFER) formatted_inps = task.example_to_input(inps, compat.ModeKeys.INFER) search_layer.set_model(model) generation_ops = search_layer(formatted_inps) if output_sequence_only: generation_ops = generation_ops[0] keras_model = tf.keras.Model(inps, generation_ops) return keras_model def apply_mask(self, model, masks): tuples = [] for (weight, mask) in list(zip(model.trainable_weights, masks)): masked_weight = weight * tf.cast(mask, weight.dtype.base_dtype) tuples.append((weight, masked_weight)) K.batch_set_value(tuples) def _build_and_restore_model(self): """ Build a single model or ensemble model. """ model = super(MaskSequenceGenerator, self)._build_and_restore_model() if self._loaded_mask is not None: self.apply_mask(model, self._loaded_mask) return model
# Copyright 2020 ByteDance 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. import pickle import tensorflow as tf import tensorflow.keras.backend as K from absl import logging from neurst.exps import register_exp from neurst.exps.sequence_generator import SequenceGenerator from neurst.utils import compat from neurst.utils.flags_core import Flag @register_exp(["mask_predict", "mask_generation"]) class MaskSequenceGenerator(SequenceGenerator): """ Entry for sequence generation. """ def __init__(self, args, **kwargs): """ Initializes a util class for sequence generation. """ self._loaded_mask = None if args["mask_pkl"]: logging.info(f"Loading mask from {args['mask_pkl']}") with tf.io.gfile.GFile(args["mask_pkl"], 'rb') as f: self._loaded_mask = pickle.load(f) super(MaskSequenceGenerator, self).__init__(args, **kwargs) @staticmethod def class_or_method_args(): this_flags = super(MaskSequenceGenerator, MaskSequenceGenerator).class_or_method_args() this_flags.append(Flag("mask_pkl", dtype=Flag.TYPE.STRING, default=None, help="The path to the mask pkl file."), ) return this_flags @staticmethod def build_generation_model(task, model, search_layer, output_sequence_only=True): """ Build keras model for generation. Args: task: The task object. model: An instance of neurst.models.model.BaseModel search_layer: A sequence search object. output_sequence_only: Only generated sequences will output if True. Returns: the generation model. """ if search_layer is None: raise ValueError( "The parameters for generation method must be provided: " "search_method, search_method.params, ...") inps = task.create_inputs(compat.ModeKeys.INFER) formatted_inps = task.example_to_input(inps, compat.ModeKeys.INFER) search_layer.set_model(model) generation_ops = search_layer(formatted_inps) if output_sequence_only: generation_ops = generation_ops[0] keras_model = tf.keras.Model(inps, generation_ops) return keras_model def apply_mask(self, model, masks): tuples = [] for (weight, mask) in list(zip(model.trainable_weights, masks)): masked_weight = weight * tf.cast(mask, weight.dtype.base_dtype) tuples.append((weight, masked_weight)) K.batch_set_value(tuples) def _build_and_restore_model(self): """ Build a single model or ensemble model. """ model = super(MaskSequenceGenerator, self)._build_and_restore_model() if self._loaded_mask is not None: self.apply_mask(model, self._loaded_mask) return model
from discord.ext import commands from pyourls3 import Yourls from utils.permissions import level class Links(commands.Cog): """A cog for link shortening and statistics.""" def __init__(self, bot: commands.Bot): self.bot = bot config = bot.cfg.module("links") self.api = Yourls(addr=config["url"], user="bot", passwd=config["password"]) @commands.command(name="shorturl") @level(40) async def shorturl(self, ctx: commands.Context, url: str, short: str = None): """Creates a new short URL for a given address.""" if "mcatho.me" in url: return await ctx.reply("You can't shorten already shortened URLs.") try: short_url = self.api.shorten(url, short) except: return await ctx.reply( "Shortening the URL failed. Perhaps it is a dumplicate?" ) await ctx.reply(f"Shortened URL: <{short_url["shorturl"]}>") @commands.command(name="urlstats") @level(40) async def urlstats(self, ctx: commands.Context, url: str = "all"): """Gets click statistics for the given URL.""" if url == "all": stats = self.api.stats() return await ctx.reply( f"**__All Link Stats:__**\nTotal Links: {stats["total_links"]}\nTotal Clicks: {stats["total_clicks"]}" ) try: stats = self.api.url_stats(url) return await ctx.reply( f"**__Link Stats for <{stats["shorturl"]}>:__**\nTotal Clicks: {stats["clicks"]}" ) except Exception as e: await ctx.reply("That link couldn't be found.") def setup(bot: commands.Bot): bot.add_cog(Links(bot))
from discord.ext import commands from pyourls3 import Yourls from utils.permissions import level class Links(commands.Cog): """A cog for link shortening and statistics.""" def __init__(self, bot: commands.Bot): self.bot = bot config = bot.cfg.module("links") self.api = Yourls(addr=config["url"], user="bot", passwd=config["password"]) @commands.command(name="shorturl") @level(40) async def shorturl(self, ctx: commands.Context, url: str, short: str = None): """Creates a new short URL for a given address.""" if "mcatho.me" in url: return await ctx.reply("You can't shorten already shortened URLs.") try: short_url = self.api.shorten(url, short) except: return await ctx.reply( "Shortening the URL failed. Perhaps it is a dumplicate?" ) await ctx.reply(f"Shortened URL: <{short_url['shorturl']}>") @commands.command(name="urlstats") @level(40) async def urlstats(self, ctx: commands.Context, url: str = "all"): """Gets click statistics for the given URL.""" if url == "all": stats = self.api.stats() return await ctx.reply( f"**__All Link Stats:__**\nTotal Links: {stats['total_links']}\nTotal Clicks: {stats['total_clicks']}" ) try: stats = self.api.url_stats(url) return await ctx.reply( f"**__Link Stats for <{stats['shorturl']}>:__**\nTotal Clicks: {stats['clicks']}" ) except Exception as e: await ctx.reply("That link couldn't be found.") def setup(bot: commands.Bot): bot.add_cog(Links(bot))
#!/usr/bin/python3 """Alta3 Research - Exploring OpenAPIs with requests""" # documentation for this API is at # https://anapioficeandfire.com/Documentation import requests AOIF_BOOKS = "https://www.anapioficeandfire.com/api/books" def main(): ## Send HTTPS GET to the API of ICE and Fire gotresp = requests.get(AOIF_BOOKS) ## Decode the response got_dj = gotresp.json() ## loop through response for singlebook in got_dj: ## display each book name ## all the below statements do the same thing #print(singlebook["name"] + ",", "pages -", singlebook["numberOfPages"]) #print("{}, pages - {}".format(singlebook["name"], singlebook["numberOfPages"])) print(f"{singlebook["name"]}, pages - {singlebook["numberOfPages"]}") print(f"\tAPI URL -> {singlebook["url"]}\n") # print ISBN print(f"\tISBN -> {singlebook["isbn"]}\n") print(f"\tPUBLISHER -> {singlebook["publisher"]}\n") print(f"\tNo. of CHARACTERS -> {len(singlebook["characters"])}\n") if __name__ == "__main__": main()
#!/usr/bin/python3 """Alta3 Research - Exploring OpenAPIs with requests""" # documentation for this API is at # https://anapioficeandfire.com/Documentation import requests AOIF_BOOKS = "https://www.anapioficeandfire.com/api/books" def main(): ## Send HTTPS GET to the API of ICE and Fire gotresp = requests.get(AOIF_BOOKS) ## Decode the response got_dj = gotresp.json() ## loop through response for singlebook in got_dj: ## display each book name ## all the below statements do the same thing #print(singlebook["name"] + ",", "pages -", singlebook["numberOfPages"]) #print("{}, pages - {}".format(singlebook["name"], singlebook["numberOfPages"])) print(f"{singlebook['name']}, pages - {singlebook['numberOfPages']}") print(f"\tAPI URL -> {singlebook['url']}\n") # print ISBN print(f"\tISBN -> {singlebook['isbn']}\n") print(f"\tPUBLISHER -> {singlebook['publisher']}\n") print(f"\tNo. of CHARACTERS -> {len(singlebook['characters'])}\n") if __name__ == "__main__": main()
import builtins import importlib import inspect import io import linecache import os.path import types from contextlib import contextmanager from pathlib import Path from typing import cast, Any, BinaryIO, Callable, Dict, List, Optional, Union from weakref import WeakValueDictionary import torch from torch.serialization import _get_restore_location, _maybe_decode_ascii from ._directory_reader import DirectoryReader from ._importlib import ( _calc___package__, _normalize_line_endings, _normalize_path, _resolve_name, _sanity_check, ) from ._mangling import PackageMangler, demangle from ._package_unpickler import PackageUnpickler from .file_structure_representation import Directory, _create_directory_from_file_list from .glob_group import GlobPattern from .importer import Importer class PackageImporter(Importer): """Importers allow you to load code written to packages by :class:`PackageExporter`. Code is loaded in a hermetic way, using files from the package rather than the normal python import system. This allows for the packaging of PyTorch model code and data so that it can be run on a server or used in the future for transfer learning. The importer for packages ensures that code in the module can only be loaded from within the package, except for modules explicitly listed as external during export. The file ``extern_modules`` in the zip archive lists all the modules that a package externally depends on. This prevents "implicit" dependencies where the package runs locally because it is importing a locally-installed package, but then fails when the package is copied to another machine. """ """The dictionary of already loaded modules from this package, equivalent to ``sys.modules`` but local to this importer. """ modules: Dict[str, types.ModuleType] def __init__( self, file_or_buffer: Union[str, torch._C.PyTorchFileReader, Path, BinaryIO], module_allowed: Callable[[str], bool] = lambda module_name: True, ): """Open ``file_or_buffer`` for importing. This checks that the imported package only requires modules allowed by ``module_allowed`` Args: file_or_buffer: a file-like object (has to implement :meth:`read`, :meth:`readline`, :meth:`tell`, and :meth:`seek`), a string, or an ``os.PathLike`` object containing a filename. module_allowed (Callable[[str], bool], optional): A method to determine if a externally provided module should be allowed. Can be used to ensure packages loaded do not depend on modules that the server does not support. Defaults to allowing anything. Raises: ImportError: If the package will use a disallowed module. """ self.zip_reader: Any if isinstance(file_or_buffer, torch._C.PyTorchFileReader): self.filename = "<pytorch_file_reader>" self.zip_reader = file_or_buffer elif isinstance(file_or_buffer, (Path, str)): self.filename = str(file_or_buffer) if not os.path.isdir(self.filename): self.zip_reader = torch._C.PyTorchFileReader(self.filename) else: self.zip_reader = DirectoryReader(self.filename) else: self.filename = "<binary>" self.zip_reader = torch._C.PyTorchFileReader(file_or_buffer) self.root = _PackageNode(None) self.modules = {} self.extern_modules = self._read_extern() for extern_module in self.extern_modules: if not module_allowed(extern_module): raise ImportError( f"package '{file_or_buffer}' needs the external module '{extern_module}' " f"but that module has been disallowed" ) self._add_extern(extern_module) for fname in self.zip_reader.get_all_records(): self._add_file(fname) self.patched_builtins = builtins.__dict__.copy() self.patched_builtins["__import__"] = self.__import__ # Allow packaged modules to reference their PackageImporter self.modules["torch_package_importer"] = self # type: ignore[assignment] self._mangler = PackageMangler() # used for reduce deserializaiton self.storage_context: Any = None self.last_map_location = None # used for torch.serialization._load self.Unpickler = lambda *args, **kwargs: PackageUnpickler(self, *args, **kwargs) def import_module(self, name: str, package=None): """Load a module from the package if it hasn't already been loaded, and then return the module. Modules are loaded locally to the importer and will appear in ``self.modules`` rather than ``sys.modules``. Args: name (str): Fully qualified name of the module to load. package ([type], optional): Unused, but present to match the signature of importlib.import_module. Defaults to ``None``. Returns: types.ModuleType: The (possibly already) loaded module. """ return self._gcd_import(name) def load_binary(self, package: str, resource: str) -> bytes: """Load raw bytes. Args: package (str): The name of module package (e.g. ``"my_package.my_subpackage"``). resource (str): The unique name for the resource. Returns: bytes: The loaded data. """ path = self._zipfile_path(package, resource) return self.zip_reader.get_record(path) def load_text( self, package: str, resource: str, encoding: str = "utf-8", errors: str = "strict", ) -> str: """Load a string. Args: package (str): The name of module package (e.g. ``"my_package.my_subpackage"``). resource (str): The unique name for the resource. encoding (str, optional): Passed to ``decode``. Defaults to ``'utf-8'``. errors (str, optional): Passed to ``decode``. Defaults to ``'strict'``. Returns: str: The loaded text. """ data = self.load_binary(package, resource) return data.decode(encoding, errors) def load_pickle(self, package: str, resource: str, map_location=None) -> Any: """Unpickles the resource from the package, loading any modules that are needed to construct the objects using :meth:`import_module`. Args: package (str): The name of module package (e.g. ``"my_package.my_subpackage"``). resource (str): The unique name for the resource. map_location: Passed to `torch.load` to determine how tensors are mapped to devices. Defaults to ``None``. Returns: Any: The unpickled object. """ pickle_file = self._zipfile_path(package, resource) restore_location = _get_restore_location(map_location) loaded_storages = {} loaded_reduces = {} storage_context = torch._C.DeserializationStorageContext() def load_tensor(data_type, size, key, location, restore_location): name = f"{int(key)}.storage" dtype = data_type(0).dtype if storage_context.has_storage(name): storage = storage_context.get_storage(name, dtype).storage() else: tensor = self.zip_reader.get_storage_from_record( ".data/" + name, size, dtype ) if isinstance(self.zip_reader, torch._C.PyTorchFileReader): storage_context.add_storage(name, tensor) storage = tensor.storage() loaded_storages[key] = restore_location(storage, location) def persistent_load(saved_id): assert isinstance(saved_id, tuple) typename = _maybe_decode_ascii(saved_id[0]) data = saved_id[1:] if typename == "storage": data_type, key, location, size = data if key not in loaded_storages: load_tensor( data_type, size, key, _maybe_decode_ascii(location), restore_location, ) storage = loaded_storages[key] return storage elif typename == "reduce_package": # to fix BC breaking change, objects on this load path # will be loaded multiple times erroneously if len(data) == 2: func, args = data return func(self, *args) reduce_id, func, args = data if reduce_id not in loaded_reduces: loaded_reduces[reduce_id] = func(self, *args) return loaded_reduces[reduce_id] else: f"Unknown typename for persistent_load, expected 'storage' or 'reduce_package' but got '{typename}'" # Load the data (which may in turn use `persistent_load` to load tensors) data_file = io.BytesIO(self.zip_reader.get_record(pickle_file)) unpickler = self.Unpickler(data_file) unpickler.persistent_load = persistent_load @contextmanager def set_deserialization_context(): # to let reduce_package access deserializaiton context self.storage_context = storage_context self.last_map_location = map_location try: yield finally: self.storage_context = None self.last_map_location = None with set_deserialization_context(): result = unpickler.load() # TODO from zdevito: # This stateful weird function will need to be removed in our efforts # to unify the format. It has a race condition if multiple python # threads try to read independent files torch._utils._validate_loaded_sparse_tensors() return result def id(self): """ Returns internal identifier that torch.package uses to distinguish :class:`PackageImporter` instances. Looks like:: <torch_package_0> """ return self._mangler.parent_name() def file_structure( self, *, include: "GlobPattern" = "**", exclude: "GlobPattern" = () ) -> Directory: """Returns a file structure representation of package's zipfile. Args: include (Union[List[str], str]): An optional string e.g. ``"my_package.my_subpackage"``, or optional list of strings for the names of the files to be inluded in the zipfile representation. This can also be a glob-style pattern, as described in :meth:`PackageExporter.mock` exclude (Union[List[str], str]): An optional pattern that excludes files whose name match the pattern. Returns: :class:`Directory` """ return _create_directory_from_file_list( self.filename, self.zip_reader.get_all_records(), include, exclude ) def _read_extern(self): return ( self.zip_reader.get_record(".data/extern_modules") .decode("utf-8") .splitlines(keepends=False) ) def _make_module( self, name: str, filename: Optional[str], is_package: bool, parent: str ): mangled_filename = self._mangler.mangle(filename) if filename else None spec = importlib.machinery.ModuleSpec( name, self, # type: ignore[arg-type] origin="<package_importer>", is_package=is_package, ) module = importlib.util.module_from_spec(spec) self.modules[name] = module module.__name__ = self._mangler.mangle(name) ns = module.__dict__ ns["__spec__"] = spec ns["__loader__"] = self ns["__file__"] = mangled_filename ns["__cached__"] = None ns["__builtins__"] = self.patched_builtins ns["__torch_package__"] = True # Add this module to our private global registry. It should be unique due to mangling. assert module.__name__ not in _package_imported_modules _package_imported_modules[module.__name__] = module # pre-emptively install on the parent to prevent IMPORT_FROM from trying to # access sys.modules self._install_on_parent(parent, name, module) if filename is not None: assert mangled_filename is not None # pre-emptively install the source in `linecache` so that stack traces, # `inspect`, etc. work. assert filename not in linecache.cache # type: ignore[attr-defined] linecache.lazycache(mangled_filename, ns) code = self._compile_source(filename, mangled_filename) exec(code, ns) return module def _load_module(self, name: str, parent: str): cur: _PathNode = self.root for atom in name.split("."): if not isinstance(cur, _PackageNode) or atom not in cur.children: raise ModuleNotFoundError( f'No module named "{name}" in self-contained archive "{self.filename}"' f" and the module is also not in the list of allowed external modules: {self.extern_modules}", name=name, ) cur = cur.children[atom] if isinstance(cur, _ExternNode): module = self.modules[name] = importlib.import_module(name) return module return self._make_module(name, cur.source_file, isinstance(cur, _PackageNode), parent) # type: ignore[attr-defined] def _compile_source(self, fullpath: str, mangled_filename: str): source = self.zip_reader.get_record(fullpath) source = _normalize_line_endings(source) return compile(source, mangled_filename, "exec", dont_inherit=True) # note: named `get_source` so that linecache can find the source # when this is the __loader__ of a module. def get_source(self, module_name) -> str: # linecache calls `get_source` with the `module.__name__` as the argument, so we must demangle it here. module = self.import_module(demangle(module_name)) return self.zip_reader.get_record(demangle(module.__file__)).decode("utf-8") # note: named `get_resource_reader` so that importlib.resources can find it. # This is otherwise considered an internal method. def get_resource_reader(self, fullname): try: package = self._get_package(fullname) except ImportError: return None if package.__loader__ is not self: return None return _PackageResourceReader(self, fullname) def _install_on_parent(self, parent: str, name: str, module: types.ModuleType): if not parent: return # Set the module as an attribute on its parent. parent_module = self.modules[parent] if parent_module.__loader__ is self: setattr(parent_module, name.rpartition(".")[2], module) # note: copied from cpython's import code, with call to create module replaced with _make_module def _do_find_and_load(self, name): path = None parent = name.rpartition(".")[0] if parent: if parent not in self.modules: self._gcd_import(parent) # Crazy side-effects! if name in self.modules: return self.modules[name] parent_module = self.modules[parent] try: path = parent_module.__path__ # type: ignore[attr-defined] except AttributeError: msg = (_ERR_MSG + "; {!r} is not a package").format(name, parent) raise ModuleNotFoundError(msg, name=name) from None module = self._load_module(name, parent) self._install_on_parent(parent, name, module) return module # note: copied from cpython's import code def _find_and_load(self, name): module = self.modules.get(name, _NEEDS_LOADING) if module is _NEEDS_LOADING: return self._do_find_and_load(name) if module is None: message = "import of {} halted; " "None in sys.modules".format(name) raise ModuleNotFoundError(message, name=name) # To handle https://github.com/pytorch/pytorch/issues/57490, where std's # creation of fake submodules via the hacking of sys.modules is not import # friendly if name == "os": self.modules["os.path"] = cast(Any, module).path elif name == "typing": self.modules["typing.io"] = cast(Any, module).io self.modules["typing.re"] = cast(Any, module).re return module def _gcd_import(self, name, package=None, level=0): """Import and return the module based on its name, the package the call is being made from, and the level adjustment. This function represents the greatest common denominator of functionality between import_module and __import__. This includes setting __package__ if the loader did not. """ _sanity_check(name, package, level) if level > 0: name = _resolve_name(name, package, level) return self._find_and_load(name) # note: copied from cpython's import code def _handle_fromlist(self, module, fromlist, *, recursive=False): """Figure out what __import__ should return. The import_ parameter is a callable which takes the name of module to import. It is required to decouple the function from assuming importlib's import implementation is desired. """ module_name = demangle(module.__name__) # The hell that is fromlist ... # If a package was imported, try to import stuff from fromlist. if hasattr(module, "__path__"): for x in fromlist: if not isinstance(x, str): if recursive: where = module_name + ".__all__" else: where = "``from list''" raise TypeError( f"Item in {where} must be str, " f"not {type(x).__name__}" ) elif x == "*": if not recursive and hasattr(module, "__all__"): self._handle_fromlist(module, module.__all__, recursive=True) elif not hasattr(module, x): from_name = "{}.{}".format(module_name, x) try: self._gcd_import(from_name) except ModuleNotFoundError as exc: # Backwards-compatibility dictates we ignore failed # imports triggered by fromlist for modules that don't # exist. if ( exc.name == from_name and self.modules.get(from_name, _NEEDS_LOADING) is not None ): continue raise return module def __import__(self, name, globals=None, locals=None, fromlist=(), level=0): if level == 0: module = self._gcd_import(name) else: globals_ = globals if globals is not None else {} package = _calc___package__(globals_) module = self._gcd_import(name, package, level) if not fromlist: # Return up to the first dot in 'name'. This is complicated by the fact # that 'name' may be relative. if level == 0: return self._gcd_import(name.partition(".")[0]) elif not name: return module else: # Figure out where to slice the module's name up to the first dot # in 'name'. cut_off = len(name) - len(name.partition(".")[0]) # Slice end needs to be positive to alleviate need to special-case # when ``'.' not in name``. module_name = demangle(module.__name__) return self.modules[module_name[: len(module_name) - cut_off]] else: return self._handle_fromlist(module, fromlist) def _get_package(self, package): """Take a package name or module object and return the module. If a name, the module is imported. If the passed or imported module object is not a package, raise an exception. """ if hasattr(package, "__spec__"): if package.__spec__.submodule_search_locations is None: raise TypeError("{!r} is not a package".format(package.__spec__.name)) else: return package else: module = self.import_module(package) if module.__spec__.submodule_search_locations is None: raise TypeError("{!r} is not a package".format(package)) else: return module def _zipfile_path(self, package, resource=None): package = self._get_package(package) assert package.__loader__ is self name = demangle(package.__name__) if resource is not None: resource = _normalize_path(resource) return f"{name.replace(".", "/")}/{resource}" else: return f"{name.replace(".", "/")}" def _get_or_create_package( self, atoms: List[str] ) -> "Union[_PackageNode, _ExternNode]": cur = self.root for i, atom in enumerate(atoms): node = cur.children.get(atom, None) if node is None: node = cur.children[atom] = _PackageNode(None) if isinstance(node, _ExternNode): return node if isinstance(node, _ModuleNode): name = ".".join(atoms[:i]) raise ImportError( f"inconsistent module structure. module {name} is not a package, but has submodules" ) assert isinstance(node, _PackageNode) cur = node return cur def _add_file(self, filename: str): """Assembles a Python module out of the given file. Will ignore files in the .data directory. Args: filename (str): the name of the file inside of the package archive to be added """ *prefix, last = filename.split("/") if len(prefix) > 1 and prefix[0] == ".data": return package = self._get_or_create_package(prefix) if isinstance(package, _ExternNode): raise ImportError( f"inconsistent module structure. package contains a module file {filename}" f" that is a subpackage of a module marked external." ) if last == "__init__.py": package.source_file = filename elif last.endswith(".py"): package_name = last[: -len(".py")] package.children[package_name] = _ModuleNode(filename) def _add_extern(self, extern_name: str): *prefix, last = extern_name.split(".") package = self._get_or_create_package(prefix) if isinstance(package, _ExternNode): return # the shorter extern covers this extern case package.children[last] = _ExternNode() _NEEDS_LOADING = object() _ERR_MSG_PREFIX = "No module named " _ERR_MSG = _ERR_MSG_PREFIX + "{!r}" class _PathNode: pass class _PackageNode(_PathNode): def __init__(self, source_file: Optional[str]): self.source_file = source_file self.children: Dict[str, _PathNode] = {} class _ModuleNode(_PathNode): __slots__ = ["source_file"] def __init__(self, source_file: str): self.source_file = source_file class _ExternNode(_PathNode): pass # A private global registry of all modules that have been package-imported. _package_imported_modules: WeakValueDictionary = WeakValueDictionary() # `inspect` by default only looks in `sys.modules` to find source files for classes. # Patch it to check our private registry of package-imported modules as well. _orig_getfile = inspect.getfile def patched_getfile(object): if inspect.isclass(object): if object.__module__ in _package_imported_modules: return _package_imported_modules[object.__module__].__file__ return _orig_getfile(object) inspect.getfile = patched_getfile class _PackageResourceReader: """Private class used to support PackageImporter.get_resource_reader(). Confirms to the importlib.abc.ResourceReader interface. Allowed to access the innards of PackageImporter. """ def __init__(self, importer, fullname): self.importer = importer self.fullname = fullname def open_resource(self, resource): from io import BytesIO return BytesIO(self.importer.load_binary(self.fullname, resource)) def resource_path(self, resource): # The contract for resource_path is that it either returns a concrete # file system path or raises FileNotFoundError. if isinstance( self.importer.zip_reader, DirectoryReader ) and self.importer.zip_reader.has_record( os.path.join(self.fullname, resource) ): return os.path.join( self.importer.zip_reader.directory, self.fullname, resource ) raise FileNotFoundError def is_resource(self, name): path = self.importer._zipfile_path(self.fullname, name) return self.importer.zip_reader.has_record(path) def contents(self): from pathlib import Path filename = self.fullname.replace(".", "/") fullname_path = Path(self.importer._zipfile_path(self.fullname)) files = self.importer.zip_reader.get_all_records() subdirs_seen = set() for filename in files: try: relative = Path(filename).relative_to(fullname_path) except ValueError: continue # If the path of the file (which is relative to the top of the zip # namespace), relative to the package given when the resource # reader was created, has a parent, then it's a name in a # subdirectory and thus we skip it. parent_name = relative.parent.name if len(parent_name) == 0: yield relative.name elif parent_name not in subdirs_seen: subdirs_seen.add(parent_name) yield parent_name
import builtins import importlib import inspect import io import linecache import os.path import types from contextlib import contextmanager from pathlib import Path from typing import cast, Any, BinaryIO, Callable, Dict, List, Optional, Union from weakref import WeakValueDictionary import torch from torch.serialization import _get_restore_location, _maybe_decode_ascii from ._directory_reader import DirectoryReader from ._importlib import ( _calc___package__, _normalize_line_endings, _normalize_path, _resolve_name, _sanity_check, ) from ._mangling import PackageMangler, demangle from ._package_unpickler import PackageUnpickler from .file_structure_representation import Directory, _create_directory_from_file_list from .glob_group import GlobPattern from .importer import Importer class PackageImporter(Importer): """Importers allow you to load code written to packages by :class:`PackageExporter`. Code is loaded in a hermetic way, using files from the package rather than the normal python import system. This allows for the packaging of PyTorch model code and data so that it can be run on a server or used in the future for transfer learning. The importer for packages ensures that code in the module can only be loaded from within the package, except for modules explicitly listed as external during export. The file ``extern_modules`` in the zip archive lists all the modules that a package externally depends on. This prevents "implicit" dependencies where the package runs locally because it is importing a locally-installed package, but then fails when the package is copied to another machine. """ """The dictionary of already loaded modules from this package, equivalent to ``sys.modules`` but local to this importer. """ modules: Dict[str, types.ModuleType] def __init__( self, file_or_buffer: Union[str, torch._C.PyTorchFileReader, Path, BinaryIO], module_allowed: Callable[[str], bool] = lambda module_name: True, ): """Open ``file_or_buffer`` for importing. This checks that the imported package only requires modules allowed by ``module_allowed`` Args: file_or_buffer: a file-like object (has to implement :meth:`read`, :meth:`readline`, :meth:`tell`, and :meth:`seek`), a string, or an ``os.PathLike`` object containing a filename. module_allowed (Callable[[str], bool], optional): A method to determine if a externally provided module should be allowed. Can be used to ensure packages loaded do not depend on modules that the server does not support. Defaults to allowing anything. Raises: ImportError: If the package will use a disallowed module. """ self.zip_reader: Any if isinstance(file_or_buffer, torch._C.PyTorchFileReader): self.filename = "<pytorch_file_reader>" self.zip_reader = file_or_buffer elif isinstance(file_or_buffer, (Path, str)): self.filename = str(file_or_buffer) if not os.path.isdir(self.filename): self.zip_reader = torch._C.PyTorchFileReader(self.filename) else: self.zip_reader = DirectoryReader(self.filename) else: self.filename = "<binary>" self.zip_reader = torch._C.PyTorchFileReader(file_or_buffer) self.root = _PackageNode(None) self.modules = {} self.extern_modules = self._read_extern() for extern_module in self.extern_modules: if not module_allowed(extern_module): raise ImportError( f"package '{file_or_buffer}' needs the external module '{extern_module}' " f"but that module has been disallowed" ) self._add_extern(extern_module) for fname in self.zip_reader.get_all_records(): self._add_file(fname) self.patched_builtins = builtins.__dict__.copy() self.patched_builtins["__import__"] = self.__import__ # Allow packaged modules to reference their PackageImporter self.modules["torch_package_importer"] = self # type: ignore[assignment] self._mangler = PackageMangler() # used for reduce deserializaiton self.storage_context: Any = None self.last_map_location = None # used for torch.serialization._load self.Unpickler = lambda *args, **kwargs: PackageUnpickler(self, *args, **kwargs) def import_module(self, name: str, package=None): """Load a module from the package if it hasn't already been loaded, and then return the module. Modules are loaded locally to the importer and will appear in ``self.modules`` rather than ``sys.modules``. Args: name (str): Fully qualified name of the module to load. package ([type], optional): Unused, but present to match the signature of importlib.import_module. Defaults to ``None``. Returns: types.ModuleType: The (possibly already) loaded module. """ return self._gcd_import(name) def load_binary(self, package: str, resource: str) -> bytes: """Load raw bytes. Args: package (str): The name of module package (e.g. ``"my_package.my_subpackage"``). resource (str): The unique name for the resource. Returns: bytes: The loaded data. """ path = self._zipfile_path(package, resource) return self.zip_reader.get_record(path) def load_text( self, package: str, resource: str, encoding: str = "utf-8", errors: str = "strict", ) -> str: """Load a string. Args: package (str): The name of module package (e.g. ``"my_package.my_subpackage"``). resource (str): The unique name for the resource. encoding (str, optional): Passed to ``decode``. Defaults to ``'utf-8'``. errors (str, optional): Passed to ``decode``. Defaults to ``'strict'``. Returns: str: The loaded text. """ data = self.load_binary(package, resource) return data.decode(encoding, errors) def load_pickle(self, package: str, resource: str, map_location=None) -> Any: """Unpickles the resource from the package, loading any modules that are needed to construct the objects using :meth:`import_module`. Args: package (str): The name of module package (e.g. ``"my_package.my_subpackage"``). resource (str): The unique name for the resource. map_location: Passed to `torch.load` to determine how tensors are mapped to devices. Defaults to ``None``. Returns: Any: The unpickled object. """ pickle_file = self._zipfile_path(package, resource) restore_location = _get_restore_location(map_location) loaded_storages = {} loaded_reduces = {} storage_context = torch._C.DeserializationStorageContext() def load_tensor(data_type, size, key, location, restore_location): name = f"{int(key)}.storage" dtype = data_type(0).dtype if storage_context.has_storage(name): storage = storage_context.get_storage(name, dtype).storage() else: tensor = self.zip_reader.get_storage_from_record( ".data/" + name, size, dtype ) if isinstance(self.zip_reader, torch._C.PyTorchFileReader): storage_context.add_storage(name, tensor) storage = tensor.storage() loaded_storages[key] = restore_location(storage, location) def persistent_load(saved_id): assert isinstance(saved_id, tuple) typename = _maybe_decode_ascii(saved_id[0]) data = saved_id[1:] if typename == "storage": data_type, key, location, size = data if key not in loaded_storages: load_tensor( data_type, size, key, _maybe_decode_ascii(location), restore_location, ) storage = loaded_storages[key] return storage elif typename == "reduce_package": # to fix BC breaking change, objects on this load path # will be loaded multiple times erroneously if len(data) == 2: func, args = data return func(self, *args) reduce_id, func, args = data if reduce_id not in loaded_reduces: loaded_reduces[reduce_id] = func(self, *args) return loaded_reduces[reduce_id] else: f"Unknown typename for persistent_load, expected 'storage' or 'reduce_package' but got '{typename}'" # Load the data (which may in turn use `persistent_load` to load tensors) data_file = io.BytesIO(self.zip_reader.get_record(pickle_file)) unpickler = self.Unpickler(data_file) unpickler.persistent_load = persistent_load @contextmanager def set_deserialization_context(): # to let reduce_package access deserializaiton context self.storage_context = storage_context self.last_map_location = map_location try: yield finally: self.storage_context = None self.last_map_location = None with set_deserialization_context(): result = unpickler.load() # TODO from zdevito: # This stateful weird function will need to be removed in our efforts # to unify the format. It has a race condition if multiple python # threads try to read independent files torch._utils._validate_loaded_sparse_tensors() return result def id(self): """ Returns internal identifier that torch.package uses to distinguish :class:`PackageImporter` instances. Looks like:: <torch_package_0> """ return self._mangler.parent_name() def file_structure( self, *, include: "GlobPattern" = "**", exclude: "GlobPattern" = () ) -> Directory: """Returns a file structure representation of package's zipfile. Args: include (Union[List[str], str]): An optional string e.g. ``"my_package.my_subpackage"``, or optional list of strings for the names of the files to be inluded in the zipfile representation. This can also be a glob-style pattern, as described in :meth:`PackageExporter.mock` exclude (Union[List[str], str]): An optional pattern that excludes files whose name match the pattern. Returns: :class:`Directory` """ return _create_directory_from_file_list( self.filename, self.zip_reader.get_all_records(), include, exclude ) def _read_extern(self): return ( self.zip_reader.get_record(".data/extern_modules") .decode("utf-8") .splitlines(keepends=False) ) def _make_module( self, name: str, filename: Optional[str], is_package: bool, parent: str ): mangled_filename = self._mangler.mangle(filename) if filename else None spec = importlib.machinery.ModuleSpec( name, self, # type: ignore[arg-type] origin="<package_importer>", is_package=is_package, ) module = importlib.util.module_from_spec(spec) self.modules[name] = module module.__name__ = self._mangler.mangle(name) ns = module.__dict__ ns["__spec__"] = spec ns["__loader__"] = self ns["__file__"] = mangled_filename ns["__cached__"] = None ns["__builtins__"] = self.patched_builtins ns["__torch_package__"] = True # Add this module to our private global registry. It should be unique due to mangling. assert module.__name__ not in _package_imported_modules _package_imported_modules[module.__name__] = module # pre-emptively install on the parent to prevent IMPORT_FROM from trying to # access sys.modules self._install_on_parent(parent, name, module) if filename is not None: assert mangled_filename is not None # pre-emptively install the source in `linecache` so that stack traces, # `inspect`, etc. work. assert filename not in linecache.cache # type: ignore[attr-defined] linecache.lazycache(mangled_filename, ns) code = self._compile_source(filename, mangled_filename) exec(code, ns) return module def _load_module(self, name: str, parent: str): cur: _PathNode = self.root for atom in name.split("."): if not isinstance(cur, _PackageNode) or atom not in cur.children: raise ModuleNotFoundError( f'No module named "{name}" in self-contained archive "{self.filename}"' f" and the module is also not in the list of allowed external modules: {self.extern_modules}", name=name, ) cur = cur.children[atom] if isinstance(cur, _ExternNode): module = self.modules[name] = importlib.import_module(name) return module return self._make_module(name, cur.source_file, isinstance(cur, _PackageNode), parent) # type: ignore[attr-defined] def _compile_source(self, fullpath: str, mangled_filename: str): source = self.zip_reader.get_record(fullpath) source = _normalize_line_endings(source) return compile(source, mangled_filename, "exec", dont_inherit=True) # note: named `get_source` so that linecache can find the source # when this is the __loader__ of a module. def get_source(self, module_name) -> str: # linecache calls `get_source` with the `module.__name__` as the argument, so we must demangle it here. module = self.import_module(demangle(module_name)) return self.zip_reader.get_record(demangle(module.__file__)).decode("utf-8") # note: named `get_resource_reader` so that importlib.resources can find it. # This is otherwise considered an internal method. def get_resource_reader(self, fullname): try: package = self._get_package(fullname) except ImportError: return None if package.__loader__ is not self: return None return _PackageResourceReader(self, fullname) def _install_on_parent(self, parent: str, name: str, module: types.ModuleType): if not parent: return # Set the module as an attribute on its parent. parent_module = self.modules[parent] if parent_module.__loader__ is self: setattr(parent_module, name.rpartition(".")[2], module) # note: copied from cpython's import code, with call to create module replaced with _make_module def _do_find_and_load(self, name): path = None parent = name.rpartition(".")[0] if parent: if parent not in self.modules: self._gcd_import(parent) # Crazy side-effects! if name in self.modules: return self.modules[name] parent_module = self.modules[parent] try: path = parent_module.__path__ # type: ignore[attr-defined] except AttributeError: msg = (_ERR_MSG + "; {!r} is not a package").format(name, parent) raise ModuleNotFoundError(msg, name=name) from None module = self._load_module(name, parent) self._install_on_parent(parent, name, module) return module # note: copied from cpython's import code def _find_and_load(self, name): module = self.modules.get(name, _NEEDS_LOADING) if module is _NEEDS_LOADING: return self._do_find_and_load(name) if module is None: message = "import of {} halted; " "None in sys.modules".format(name) raise ModuleNotFoundError(message, name=name) # To handle https://github.com/pytorch/pytorch/issues/57490, where std's # creation of fake submodules via the hacking of sys.modules is not import # friendly if name == "os": self.modules["os.path"] = cast(Any, module).path elif name == "typing": self.modules["typing.io"] = cast(Any, module).io self.modules["typing.re"] = cast(Any, module).re return module def _gcd_import(self, name, package=None, level=0): """Import and return the module based on its name, the package the call is being made from, and the level adjustment. This function represents the greatest common denominator of functionality between import_module and __import__. This includes setting __package__ if the loader did not. """ _sanity_check(name, package, level) if level > 0: name = _resolve_name(name, package, level) return self._find_and_load(name) # note: copied from cpython's import code def _handle_fromlist(self, module, fromlist, *, recursive=False): """Figure out what __import__ should return. The import_ parameter is a callable which takes the name of module to import. It is required to decouple the function from assuming importlib's import implementation is desired. """ module_name = demangle(module.__name__) # The hell that is fromlist ... # If a package was imported, try to import stuff from fromlist. if hasattr(module, "__path__"): for x in fromlist: if not isinstance(x, str): if recursive: where = module_name + ".__all__" else: where = "``from list''" raise TypeError( f"Item in {where} must be str, " f"not {type(x).__name__}" ) elif x == "*": if not recursive and hasattr(module, "__all__"): self._handle_fromlist(module, module.__all__, recursive=True) elif not hasattr(module, x): from_name = "{}.{}".format(module_name, x) try: self._gcd_import(from_name) except ModuleNotFoundError as exc: # Backwards-compatibility dictates we ignore failed # imports triggered by fromlist for modules that don't # exist. if ( exc.name == from_name and self.modules.get(from_name, _NEEDS_LOADING) is not None ): continue raise return module def __import__(self, name, globals=None, locals=None, fromlist=(), level=0): if level == 0: module = self._gcd_import(name) else: globals_ = globals if globals is not None else {} package = _calc___package__(globals_) module = self._gcd_import(name, package, level) if not fromlist: # Return up to the first dot in 'name'. This is complicated by the fact # that 'name' may be relative. if level == 0: return self._gcd_import(name.partition(".")[0]) elif not name: return module else: # Figure out where to slice the module's name up to the first dot # in 'name'. cut_off = len(name) - len(name.partition(".")[0]) # Slice end needs to be positive to alleviate need to special-case # when ``'.' not in name``. module_name = demangle(module.__name__) return self.modules[module_name[: len(module_name) - cut_off]] else: return self._handle_fromlist(module, fromlist) def _get_package(self, package): """Take a package name or module object and return the module. If a name, the module is imported. If the passed or imported module object is not a package, raise an exception. """ if hasattr(package, "__spec__"): if package.__spec__.submodule_search_locations is None: raise TypeError("{!r} is not a package".format(package.__spec__.name)) else: return package else: module = self.import_module(package) if module.__spec__.submodule_search_locations is None: raise TypeError("{!r} is not a package".format(package)) else: return module def _zipfile_path(self, package, resource=None): package = self._get_package(package) assert package.__loader__ is self name = demangle(package.__name__) if resource is not None: resource = _normalize_path(resource) return f"{name.replace('.', '/')}/{resource}" else: return f"{name.replace('.', '/')}" def _get_or_create_package( self, atoms: List[str] ) -> "Union[_PackageNode, _ExternNode]": cur = self.root for i, atom in enumerate(atoms): node = cur.children.get(atom, None) if node is None: node = cur.children[atom] = _PackageNode(None) if isinstance(node, _ExternNode): return node if isinstance(node, _ModuleNode): name = ".".join(atoms[:i]) raise ImportError( f"inconsistent module structure. module {name} is not a package, but has submodules" ) assert isinstance(node, _PackageNode) cur = node return cur def _add_file(self, filename: str): """Assembles a Python module out of the given file. Will ignore files in the .data directory. Args: filename (str): the name of the file inside of the package archive to be added """ *prefix, last = filename.split("/") if len(prefix) > 1 and prefix[0] == ".data": return package = self._get_or_create_package(prefix) if isinstance(package, _ExternNode): raise ImportError( f"inconsistent module structure. package contains a module file {filename}" f" that is a subpackage of a module marked external." ) if last == "__init__.py": package.source_file = filename elif last.endswith(".py"): package_name = last[: -len(".py")] package.children[package_name] = _ModuleNode(filename) def _add_extern(self, extern_name: str): *prefix, last = extern_name.split(".") package = self._get_or_create_package(prefix) if isinstance(package, _ExternNode): return # the shorter extern covers this extern case package.children[last] = _ExternNode() _NEEDS_LOADING = object() _ERR_MSG_PREFIX = "No module named " _ERR_MSG = _ERR_MSG_PREFIX + "{!r}" class _PathNode: pass class _PackageNode(_PathNode): def __init__(self, source_file: Optional[str]): self.source_file = source_file self.children: Dict[str, _PathNode] = {} class _ModuleNode(_PathNode): __slots__ = ["source_file"] def __init__(self, source_file: str): self.source_file = source_file class _ExternNode(_PathNode): pass # A private global registry of all modules that have been package-imported. _package_imported_modules: WeakValueDictionary = WeakValueDictionary() # `inspect` by default only looks in `sys.modules` to find source files for classes. # Patch it to check our private registry of package-imported modules as well. _orig_getfile = inspect.getfile def patched_getfile(object): if inspect.isclass(object): if object.__module__ in _package_imported_modules: return _package_imported_modules[object.__module__].__file__ return _orig_getfile(object) inspect.getfile = patched_getfile class _PackageResourceReader: """Private class used to support PackageImporter.get_resource_reader(). Confirms to the importlib.abc.ResourceReader interface. Allowed to access the innards of PackageImporter. """ def __init__(self, importer, fullname): self.importer = importer self.fullname = fullname def open_resource(self, resource): from io import BytesIO return BytesIO(self.importer.load_binary(self.fullname, resource)) def resource_path(self, resource): # The contract for resource_path is that it either returns a concrete # file system path or raises FileNotFoundError. if isinstance( self.importer.zip_reader, DirectoryReader ) and self.importer.zip_reader.has_record( os.path.join(self.fullname, resource) ): return os.path.join( self.importer.zip_reader.directory, self.fullname, resource ) raise FileNotFoundError def is_resource(self, name): path = self.importer._zipfile_path(self.fullname, name) return self.importer.zip_reader.has_record(path) def contents(self): from pathlib import Path filename = self.fullname.replace(".", "/") fullname_path = Path(self.importer._zipfile_path(self.fullname)) files = self.importer.zip_reader.get_all_records() subdirs_seen = set() for filename in files: try: relative = Path(filename).relative_to(fullname_path) except ValueError: continue # If the path of the file (which is relative to the top of the zip # namespace), relative to the package given when the resource # reader was created, has a parent, then it's a name in a # subdirectory and thus we skip it. parent_name = relative.parent.name if len(parent_name) == 0: yield relative.name elif parent_name not in subdirs_seen: subdirs_seen.add(parent_name) yield parent_name
from talon import Context, Module, actions, imgui, registry ctx = Context() mod = Module() mod.list("code_libraries", desc="List of libraries for active language") mod.tag( "code_libraries_gui_showing", desc="Active when the library picker GUI is showing" ) # global library_list = [] @mod.capture(rule="{user.code_libraries}") def code_libraries(m) -> str: """Returns a type""" return m.code_libraries mod.tag("code_libraries_gui", desc="Tag for enabling GUI support for common libraries") @mod.action_class class Actions: def code_toggle_libraries(): """GUI: List libraries for active language""" global library_list if gui_libraries.showing: library_list = [] gui_libraries.hide() ctx.tags.discard("user.code_libraries_gui_showing") else: update_library_list_and_freeze() def code_select_library(number: int, selection: str): """Inserts the selected library when the imgui is open""" if gui_libraries.showing and number < len(library_list): actions.user.code_insert_library( registry.lists["user.code_libraries"][0][library_list[number]], selection, ) # TODO: clarify the relation between `code_insert_library` # and `code_import` def code_insert_library(text: str, selection: str): """Inserts a library and positions the cursor appropriately""" @imgui.open() def gui_libraries(gui: imgui.GUI): gui.text("Libraries") gui.line() for i, entry in enumerate(library_list, 1): gui.text(f"{i}. {entry}: {registry.lists["user.code_libraries"][0][entry]}") gui.spacer() if gui.button("Toggle libraries close"): actions.user.code_toggle_libraries_hide() def update_library_list_and_freeze(): global library_list if "user.code_libraries" in registry.lists: library_list = sorted(registry.lists["user.code_libraries"][0].keys()) else: library_list = [] gui_libraries.show() ctx.tags.add("user.code_libraries_gui_showing") def commands_updated(_): if gui_libraries.showing: update_library_list_and_freeze() registry.register("update_commands", commands_updated)
from talon import Context, Module, actions, imgui, registry ctx = Context() mod = Module() mod.list("code_libraries", desc="List of libraries for active language") mod.tag( "code_libraries_gui_showing", desc="Active when the library picker GUI is showing" ) # global library_list = [] @mod.capture(rule="{user.code_libraries}") def code_libraries(m) -> str: """Returns a type""" return m.code_libraries mod.tag("code_libraries_gui", desc="Tag for enabling GUI support for common libraries") @mod.action_class class Actions: def code_toggle_libraries(): """GUI: List libraries for active language""" global library_list if gui_libraries.showing: library_list = [] gui_libraries.hide() ctx.tags.discard("user.code_libraries_gui_showing") else: update_library_list_and_freeze() def code_select_library(number: int, selection: str): """Inserts the selected library when the imgui is open""" if gui_libraries.showing and number < len(library_list): actions.user.code_insert_library( registry.lists["user.code_libraries"][0][library_list[number]], selection, ) # TODO: clarify the relation between `code_insert_library` # and `code_import` def code_insert_library(text: str, selection: str): """Inserts a library and positions the cursor appropriately""" @imgui.open() def gui_libraries(gui: imgui.GUI): gui.text("Libraries") gui.line() for i, entry in enumerate(library_list, 1): gui.text(f"{i}. {entry}: {registry.lists['user.code_libraries'][0][entry]}") gui.spacer() if gui.button("Toggle libraries close"): actions.user.code_toggle_libraries_hide() def update_library_list_and_freeze(): global library_list if "user.code_libraries" in registry.lists: library_list = sorted(registry.lists["user.code_libraries"][0].keys()) else: library_list = [] gui_libraries.show() ctx.tags.add("user.code_libraries_gui_showing") def commands_updated(_): if gui_libraries.showing: update_library_list_and_freeze() registry.register("update_commands", commands_updated)
import importlib from collections import defaultdict import torch.nn as nn import torch.optim as optim class TrainerMaker: def __init__(self, args, model, data): print("[Make Trainer]") if args.mode == 'train': criterion = self.__set_criterion(args.criterion) optimizer = self.__set_optimizer(args, model) scheduler = self.__set_scheduler(args, optimizer) # history = self.__make_history(args.metrics) history = defaultdict(list) self.trainer = self.__make_trainer(args=args, model=model, data=data, criterion=criterion, optimizer=optimizer, scheduler=scheduler, history=history) else: criterion = self.__set_criterion(args.criterion) history = defaultdict(list) self.trainer = self.__make_trainer(args=args, model=model, data=data, criterion=criterion, history=history) print("") def __set_criterion(self, criterion): if criterion == "MSE": criterion = nn.MSELoss() elif criterion == "CEE": criterion = nn.CrossEntropyLoss() return criterion def __set_optimizer(self, args, model): if args.opt == "SGD": optimizer = optim.SGD(model.parameters(), lr=args.lr, weight_decay=args.wd) elif args.opt == "Adam": optimizer = optim.Adam(list(model.parameters()), lr=args.lr, weight_decay=args.wd) elif args.opt == 'AdamW': optimizer = optim.AdamW(list(model.parameters()), lr=args.lr, weight_decay=args.wd) else: raise ValueError(f"Not supported {args.opt}.") return optimizer def __set_scheduler(self, args, optimizer): if args.scheduler is None: return None elif args.scheduler == 'exp': scheduler = optim.lr_scheduler.ExponentialLR(optimizer, gamma=args.gamma) elif args.scheduler == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=args.step_size, gamma=args.gamma) elif args.scheduler == 'multi_step': scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=args.milestones, gamma=args.gamma) elif args.scheduler == 'plateau': scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=20, threshold=0.1, threshold_mode='abs', verbose=True) elif args.scheduler == 'cosine': scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.T_max if args.T_max else args.epochs, eta_min=args.eta_min if args.eta_min else 0) else: raise ValueError(f"Not supported {args.scheduler}.") return scheduler def __make_trainer(self, **kwargs): module = importlib.import_module(f"trainers.{kwargs["args"].model}_trainer") trainer = getattr(module, 'Trainer')(**kwargs) return trainer
import importlib from collections import defaultdict import torch.nn as nn import torch.optim as optim class TrainerMaker: def __init__(self, args, model, data): print("[Make Trainer]") if args.mode == 'train': criterion = self.__set_criterion(args.criterion) optimizer = self.__set_optimizer(args, model) scheduler = self.__set_scheduler(args, optimizer) # history = self.__make_history(args.metrics) history = defaultdict(list) self.trainer = self.__make_trainer(args=args, model=model, data=data, criterion=criterion, optimizer=optimizer, scheduler=scheduler, history=history) else: criterion = self.__set_criterion(args.criterion) history = defaultdict(list) self.trainer = self.__make_trainer(args=args, model=model, data=data, criterion=criterion, history=history) print("") def __set_criterion(self, criterion): if criterion == "MSE": criterion = nn.MSELoss() elif criterion == "CEE": criterion = nn.CrossEntropyLoss() return criterion def __set_optimizer(self, args, model): if args.opt == "SGD": optimizer = optim.SGD(model.parameters(), lr=args.lr, weight_decay=args.wd) elif args.opt == "Adam": optimizer = optim.Adam(list(model.parameters()), lr=args.lr, weight_decay=args.wd) elif args.opt == 'AdamW': optimizer = optim.AdamW(list(model.parameters()), lr=args.lr, weight_decay=args.wd) else: raise ValueError(f"Not supported {args.opt}.") return optimizer def __set_scheduler(self, args, optimizer): if args.scheduler is None: return None elif args.scheduler == 'exp': scheduler = optim.lr_scheduler.ExponentialLR(optimizer, gamma=args.gamma) elif args.scheduler == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=args.step_size, gamma=args.gamma) elif args.scheduler == 'multi_step': scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=args.milestones, gamma=args.gamma) elif args.scheduler == 'plateau': scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=20, threshold=0.1, threshold_mode='abs', verbose=True) elif args.scheduler == 'cosine': scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.T_max if args.T_max else args.epochs, eta_min=args.eta_min if args.eta_min else 0) else: raise ValueError(f"Not supported {args.scheduler}.") return scheduler def __make_trainer(self, **kwargs): module = importlib.import_module(f"trainers.{kwargs['args'].model}_trainer") trainer = getattr(module, 'Trainer')(**kwargs) return trainer
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. import os import json from torchvision import datasets, transforms from torchvision.datasets.folder import ImageFolder, default_loader from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.data import create_transform class INatDataset(ImageFolder): def __init__(self, root, train=True, year=2018, transform=None, target_transform=None, category='name', loader=default_loader): self.transform = transform self.loader = loader self.target_transform = target_transform self.year = year # assert category in ['kingdom','phylum','class','order','supercategory','family','genus','name'] path_json = os.path.join(root, f'{'train' if train else 'val'}{year}.json') with open(path_json) as json_file: data = json.load(json_file) with open(os.path.join(root, 'categories.json')) as json_file: data_catg = json.load(json_file) path_json_for_targeter = os.path.join(root, f"train{year}.json") with open(path_json_for_targeter) as json_file: data_for_targeter = json.load(json_file) targeter = {} indexer = 0 for elem in data_for_targeter['annotations']: king = [] king.append(data_catg[int(elem['category_id'])][category]) if king[0] not in targeter.keys(): targeter[king[0]] = indexer indexer += 1 self.nb_classes = len(targeter) self.samples = [] for elem in data['images']: cut = elem['file_name'].split('/') target_current = int(cut[2]) path_current = os.path.join(root, cut[0], cut[2], cut[3]) categors = data_catg[target_current] target_current_true = targeter[categors[category]] self.samples.append((path_current, target_current_true)) # __getitem__ and __len__ inherited from ImageFolder def build_dataset(is_train, args): transform = build_transform(is_train, args) if args.data_set == 'CIFAR': dataset = datasets.CIFAR100(args.data_path, train=is_train, transform=transform, download=True) nb_classes = 100 elif args.data_set == 'IMNET': root = os.path.join(args.data_path, 'train' if is_train else 'val') dataset = datasets.ImageFolder(root, transform=transform) nb_classes = 1000 elif args.data_set == 'INAT': dataset = INatDataset(args.data_path, train=is_train, year=2018, category=args.inat_category, transform=transform) nb_classes = dataset.nb_classes elif args.data_set == 'INAT19': dataset = INatDataset(args.data_path, train=is_train, year=2019, category=args.inat_category, transform=transform) nb_classes = dataset.nb_classes return dataset, nb_classes def build_transform(is_train, args): resize_im = args.input_size > 32 if is_train: # this should always dispatch to transforms_imagenet_train transform = create_transform( input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation=args.train_interpolation, re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, ) if not resize_im: # replace RandomResizedCropAndInterpolation with # RandomCrop transform.transforms[0] = transforms.RandomCrop( args.input_size, padding=4) return transform t = [] if resize_im: size = int((256 / 224) * args.input_size) t.append( transforms.Resize(size, interpolation=3), # to maintain same ratio w.r.t. 224 images ) t.append(transforms.CenterCrop(args.input_size)) t.append(transforms.ToTensor()) t.append(transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD)) return transforms.Compose(t)
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. import os import json from torchvision import datasets, transforms from torchvision.datasets.folder import ImageFolder, default_loader from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.data import create_transform class INatDataset(ImageFolder): def __init__(self, root, train=True, year=2018, transform=None, target_transform=None, category='name', loader=default_loader): self.transform = transform self.loader = loader self.target_transform = target_transform self.year = year # assert category in ['kingdom','phylum','class','order','supercategory','family','genus','name'] path_json = os.path.join(root, f'{"train" if train else "val"}{year}.json') with open(path_json) as json_file: data = json.load(json_file) with open(os.path.join(root, 'categories.json')) as json_file: data_catg = json.load(json_file) path_json_for_targeter = os.path.join(root, f"train{year}.json") with open(path_json_for_targeter) as json_file: data_for_targeter = json.load(json_file) targeter = {} indexer = 0 for elem in data_for_targeter['annotations']: king = [] king.append(data_catg[int(elem['category_id'])][category]) if king[0] not in targeter.keys(): targeter[king[0]] = indexer indexer += 1 self.nb_classes = len(targeter) self.samples = [] for elem in data['images']: cut = elem['file_name'].split('/') target_current = int(cut[2]) path_current = os.path.join(root, cut[0], cut[2], cut[3]) categors = data_catg[target_current] target_current_true = targeter[categors[category]] self.samples.append((path_current, target_current_true)) # __getitem__ and __len__ inherited from ImageFolder def build_dataset(is_train, args): transform = build_transform(is_train, args) if args.data_set == 'CIFAR': dataset = datasets.CIFAR100(args.data_path, train=is_train, transform=transform, download=True) nb_classes = 100 elif args.data_set == 'IMNET': root = os.path.join(args.data_path, 'train' if is_train else 'val') dataset = datasets.ImageFolder(root, transform=transform) nb_classes = 1000 elif args.data_set == 'INAT': dataset = INatDataset(args.data_path, train=is_train, year=2018, category=args.inat_category, transform=transform) nb_classes = dataset.nb_classes elif args.data_set == 'INAT19': dataset = INatDataset(args.data_path, train=is_train, year=2019, category=args.inat_category, transform=transform) nb_classes = dataset.nb_classes return dataset, nb_classes def build_transform(is_train, args): resize_im = args.input_size > 32 if is_train: # this should always dispatch to transforms_imagenet_train transform = create_transform( input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation=args.train_interpolation, re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, ) if not resize_im: # replace RandomResizedCropAndInterpolation with # RandomCrop transform.transforms[0] = transforms.RandomCrop( args.input_size, padding=4) return transform t = [] if resize_im: size = int((256 / 224) * args.input_size) t.append( transforms.Resize(size, interpolation=3), # to maintain same ratio w.r.t. 224 images ) t.append(transforms.CenterCrop(args.input_size)) t.append(transforms.ToTensor()) t.append(transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD)) return transforms.Compose(t)
SPECIAL_DEVICES={ "chuangmi.plug.212a01":{ "device_type": ['switch','sensor'], "mapping": {"switch": {"switch_status": {"siid": 2, "piid": 1}, "temperature": {"siid": 2, "piid": 6}, "working_time": {"siid": 2, "piid": 7}}, "power_consumption": {"power_consumption": {"siid": 5, "piid": 1}, "electric_current": {"siid": 5, "piid": 2}, "voltage": {"siid": 5, "piid": 3}, "electric_power": {"siid": 5, "piid": 6}}}, "params": {"switch": {"switch_status": {"power_on": True, "power_off": False}, "main": True}, "power_consumption": {"electric_power":{"value_ratio": 0.01, "unit": "W"}}} }, "xiaomi.wifispeaker.x08c": { "device_type": ['media_player'], "mapping":{"speaker": {"volume": {"siid": 4, "piid": 1}, "mute": {"siid": 4, "piid": 2}, "playing_state": {"siid": 2, "piid": 1},"mp_sound_mode":{"siid":3,"aiid":1}}, "a_l": {"play_control_pause": {"siid": 2, "aiid": 1}, "play_control_play": {"siid": 2, "aiid": 2}, "play_control_next": {"siid": 2, "aiid": 3}, "play_control_previous": {"siid": 2, "aiid": 4}, "intelligent_speaker_play_text": {"siid": 3, "aiid": 1}, "intelligent_speaker_wake_up": {"siid": 3, "aiid": 2}, "intelligent_speaker_play_radio": {"siid": 3, "aiid": 3}, "intelligent_speaker_play_music": {"siid": 3, "aiid": 4}, "intelligent_speaker_execute_text_directive": {"siid": 3, "aiid": 5}}}, "params": {"speaker": {"volume": {"value_range": [5, 100, 5]}, "main": True, "mp_source":{"\u64ad\u653e\u79c1\u4eba\u7535\u53f0":{"siid":3,"aiid":3},"\u64ad\u653e\u97f3\u4e50":{"siid":3,"aiid":4},"\u505c\u6b62\u95f9\u949f":{"siid":6,"aiid":1}},"mp_sound_mode":{"\u4f60\u597d":0},"playing_state": {"pause": 0, "playing": 1}}} }, "lumi.sensor_motion.v2": { "device_type":['sensor'], "mapping":{"motion":{"key":"device_log","type":"prop"}}, "params":{"event_based":True} }, "cuco.plug.cp2":{ "device_type": ['switch'], "mapping": {"switch": {"switch_status": {"siid": 2, "piid": 1}}}, "params": {"switch": {"switch_status": {"power_on": True, "power_off": False}, "main": True}} }, "degree.lunar.smh013": { "device_type": ['switch', 'sensor'], "mapping": {"sleep_monitor":{"sleep_state":{"siid":2,"piid":1},"realtime_heart_rate":{"siid":4,"piid":10},"realtime_breath_rate":{"siid":4,"piid":11},"realtime_sleepstage":{"siid":4,"piid":12}},"switch":{"switch_status":{"siid":4,"piid":15}}}, "params": {"sleep_monitor":{"sleep_state":{"access":5,"format":"uint8","unit":None,"value_list":{"Out of Bed":0,"Awake":1,"Light Sleep":3,"Deep Sleep":4,"Rapid Eye Movement":2}},"realtime_heart_rate":{"unit":"bpm"},"realtime_breath_rate":{"unit":"/min"},"main":True},"switch":{"switch_status":{"power_on":True,"power_off":False}}} }, "hhcc.plantmonitor.v1": { "device_type": ['sensor'], "mapping": {"plant_monitor":{"temperature":{"siid":3,"piid":2},"relative_humidity":{"siid":2,"piid":1},"soil_ec":{"siid":2,"piid":2},"illumination":{"siid":2,"piid":3}}}, "params": {"plant_monitor": {"temperature": {"access": 5, "format": "float", "unit": "celsius"}, "relative_humidity": {"access": 5, "format": "float", "unit": "percentage", "value_range": [0, 100, 1]}, "soil_ec": {"access": 5, "format": "uint16", "unit": "µS/cm", "value_range": [0, 5000, 1]}, "illumination": {"access": 5, "format": "float", "unit": "lux", "value_range": [0, 10000, 1]}, "main": True}} }, "zhimi.heater.na1": { "device_type": ['climate', 'switch', 'light', 'lock'], "mapping": {"heater": {"fault": {"siid": 2, "piid": 1}, "switch_status": {"siid": 2, "piid": 2}, "speed": {"siid": 2, "piid": 3}, "horizontal_swing": {"siid": 2, "piid": 4}}, "indicator_light": {"brightness": {"siid": 6, "piid": 1}}, "physical_controls_locked": {"physical_controls_locked": {"siid": 7, "piid": 1}}, "switch": {"switch_status":{"siid":3,"piid":1}}, "switch_2": {"switch_status":{"siid":8,"piid":3}}}, "params": {"heater": {"switch_status": {"power_on": True, "power_off": False}, "fault": {"No faults": 0}, "horizontal_swing":{"off":0,"on":1}, "speed": {"High": 1, "Low": 2}, "main": True},"switch":{"switch_status":{"power_on":True,"power_off":False}}, "indicator_light": {"brightness": {"value_range": [0, 2, 1]}}, "physical_controls_locked": {"enabled": False}, "switch_2":{"switch_status":{"power_on": True,"power_off": False}}} }, } LOCK_PRM = { "device_type": ['sensor'], "mapping":'{"door":{"key":7,"type":"event"},"lock":{"key":11,"type":"event"}}', "params":'{"event_based":true}' }
SPECIAL_DEVICES={ "chuangmi.plug.212a01":{ "device_type": ['switch','sensor'], "mapping": {"switch": {"switch_status": {"siid": 2, "piid": 1}, "temperature": {"siid": 2, "piid": 6}, "working_time": {"siid": 2, "piid": 7}}, "power_consumption": {"power_consumption": {"siid": 5, "piid": 1}, "electric_current": {"siid": 5, "piid": 2}, "voltage": {"siid": 5, "piid": 3}, "electric_power": {"siid": 5, "piid": 6}}}, "params": {"switch": {"switch_status": {"power_on": True, "power_off": False}, "main": True}, "power_consumption": {"electric_power":{"value_ratio": 0.01, "unit": "W"}}} }, "xiaomi.wifispeaker.x08c": { "device_type": ['media_player'], "mapping":{"speaker": {"volume": {"siid": 4, "piid": 1}, "mute": {"siid": 4, "piid": 2}, "playing_state": {"siid": 2, "piid": 1},"mp_sound_mode":{"siid":3,"aiid":1}}, "a_l": {"play_control_pause": {"siid": 2, "aiid": 1}, "play_control_play": {"siid": 2, "aiid": 2}, "play_control_next": {"siid": 2, "aiid": 3}, "play_control_previous": {"siid": 2, "aiid": 4}, "intelligent_speaker_play_text": {"siid": 3, "aiid": 1}, "intelligent_speaker_wake_up": {"siid": 3, "aiid": 2}, "intelligent_speaker_play_radio": {"siid": 3, "aiid": 3}, "intelligent_speaker_play_music": {"siid": 3, "aiid": 4}, "intelligent_speaker_execute_text_directive": {"siid": 3, "aiid": 5}}}, "params": {"speaker": {"volume": {"value_range": [5, 100, 5]}, "main": True, "mp_source":{"\u64ad\u653e\u79c1\u4eba\u7535\u53f0":{"siid":3,"aiid":3},"\u64ad\u653e\u97f3\u4e50":{"siid":3,"aiid":4},"\u505c\u6b62\u95f9\u949f":{"siid":6,"aiid":1}},"mp_sound_mode":{"\u4f60\u597d":0},"playing_state": {"pause": 0, "playing": 1}}} }, "lumi.sensor_motion.v2": { "device_type":['sensor'], "mapping":{"motion":{"key":"device_log","type":"prop"}}, "params":{"event_based":True} }, "cuco.plug.cp2":{ "device_type": ['switch'], "mapping": {"switch": {"switch_status": {"siid": 2, "piid": 1}}}, "params": {"switch": {"switch_status": {"power_on": True, "power_off": False}, "main": True}} }, "degree.lunar.smh013": { "device_type": ['switch', 'sensor'], "mapping": {"sleep_monitor":{"sleep_state":{"siid":2,"piid":1},"realtime_heart_rate":{"siid":4,"piid":10},"realtime_breath_rate":{"siid":4,"piid":11},"realtime_sleepstage":{"siid":4,"piid":12}},"switch":{"switch_status":{"siid":4,"piid":15}}}, "params": {"sleep_monitor":{"sleep_state":{"access":5,"format":"uint8","unit":None,"value_list":{"Out of Bed":0,"Awake":1,"Light Sleep":3,"Deep Sleep":4,"Rapid Eye Movement":2}},"realtime_heart_rate":{"unit":"bpm"},"realtime_breath_rate":{"unit":"/min"},"main":True},"switch":{"switch_status":{"power_on":True,"power_off":False}}} }, "hhcc.plantmonitor.v1": { "device_type": ['sensor'], "mapping": {"plant_monitor":{"temperature":{"siid":3,"piid":2},"relative_humidity":{"siid":2,"piid":1},"soil_ec":{"siid":2,"piid":2},"illumination":{"siid":2,"piid":3}}}, "params": {"plant_monitor": {"temperature": {"access": 5, "format": "float", "unit": "celsius"}, "relative_humidity": {"access": 5, "format": "float", "unit": "percentage", "value_range": [0, 100, 1]}, "soil_ec": {"access": 5, "format": "uint16", "unit": "µS/cm", "value_range": [0, 5000, 1]}, "illumination": {"access": 5, "format": "float", "unit": "lux", "value_range": [0, 10000, 1]}, "main": True}} }, "zhimi.heater.na1": { "device_type": ['climate', 'switch', 'light', 'lock'], "mapping": {"heater": {"fault": {"siid": 2, "piid": 1}, "switch_status": {"siid": 2, "piid": 2}, "speed": {"siid": 2, "piid": 3}, "horizontal_swing": {"siid": 2, "piid": 4}}, "indicator_light": {"brightness": {"siid": 6, "piid": 1}}, "physical_controls_locked": {"physical_controls_locked": {"siid": 7, "piid": 1}}, "switch": {"switch_status":{"siid":3,"piid":1}}, "switch_2": {"switch_status":{"siid":8,"piid":3}}}, "params": {"heater": {"switch_status": {"power_on": True, "power_off": False}, "fault": {"No faults": 0}, "horizontal_swing":{"off":0,"on":1}, "speed": {"High": 1, "Low": 2}, "main": True},"switch":{"switch_status":{"power_on":True,"power_off":False}}, "indicator_light": {"brightness": {"value_range": [0, 2, 1]}}, "physical_controls_locked": {"enabled": False}, "switch_2":{"switch_status":{"power_on": True,"power_off": False}}} }, } LOCK_PRM = { "device_type": ['sensor'], "mapping":'{"door":{"key":7,"type":"event"},"lock":{"key":11,"type":"event"}}', "params":'{"event_based":true}' }
from flask import Blueprint, request, render_template, session, redirect, url_for from flask.wrappers import Response from loguru import logger from src.utils.common.data_helper import load_data from src.utils.common.plotly_helper import PlotlyHelper from src.utils.common.project_report_helper import ProjectReports import numpy as np from src.eda.eda_helper import EDA from pandas_profiling import ProfileReport from src.constants.constants import TWO_D_GRAPH_TYPES, TWO_D_GRAPH_TYPES_2 import plotly.figure_factory as ff import json import plotly from src.utils.common.common_helper import immutable_multi_dict_to_str, get_numeric_categorical_columns import os from from_root import from_root import pandas as pd app_eda = Blueprint('eda', __name__) @app_eda.route('/eda/<action>') def eda(action): try: if 'pid' in session: df = load_data() if df is not None: if action == "data-summary": ProjectReports.insert_record_eda('Redirect To Data Summary') summary = EDA.five_point_summary(df) data = summary.to_html() dtypes = EDA.data_dtype_info(df) return render_template('eda/5point.html', data=data, dtypes=dtypes.to_html(), count=len(df), column_count=df.shape[1]) # elif action == "profiler": # ProjectReports.insert_record_eda('Redirect To Profile Report') # return render_template('eda/profiler.html', action=action) elif action == "show": ProjectReports.insert_record_eda('Redirect To Show Dataset') data = EDA.get_no_records(df, 100) data = data.to_html() topselected = True bottomSelected = False selectedCount = 100 return render_template('eda/showdataset.html', data=data, length=len(df), bottomSelected=bottomSelected, topselected=topselected, action=action, selectedCount=selectedCount, columns=df.columns) elif action == "missing": ProjectReports.insert_record_eda('Redirect To Missing Value') df = EDA.missing_cells_table(df) if df is not None: graphJSON = PlotlyHelper.barplot(df, x='Column', y='Missing values') pie_graphJSON = PlotlyHelper.pieplot(df, names='Column', values='Missing values', title='Missing Values') data = df.drop('Column', axis=1) data = data.to_html() return render_template('eda/missing_values.html', action=action, data=data, barplot=graphJSON, pieplot=pie_graphJSON, contain_missing=True) else: return render_template('eda/missing_values.html', action=action, contain_missing=False) elif action == "outlier": ProjectReports.insert_record_eda('Redirect To Outlier') df = EDA.z_score_outlier_detection(df) graphJSON = PlotlyHelper.barplot(df, x='Features', y='Total outliers') pie_graphJSON = PlotlyHelper.pieplot( df.sort_values(by='Total outliers', ascending=False).loc[: 10 if len(df) > 10 else len(df)-1, :], names='Features', values='Total outliers', title='Top 10 Outliers') data = df.to_html() return render_template('eda/outliers.html', data=data, method='zscore', action=action, barplot=graphJSON, pieplot=pie_graphJSON) elif action == "correlation": ProjectReports.insert_record_eda('Redirect To Correlation') pearson_corr = EDA.correlation_report(df, 'pearson') persion_data = list(np.around(np.array(pearson_corr.values), 2)) fig = ff.create_annotated_heatmap(persion_data, x=list(pearson_corr.columns), y=list(pearson_corr.columns), colorscale='Viridis') graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) return render_template('eda/correlation.html', data=graphJSON, columns=list(pearson_corr.columns), action=action, method='pearson') elif action == "plots": ProjectReports.insert_record_eda('Plots') num_cols, cat_cols = get_numeric_categorical_columns(df) if len(cat_cols) == 0: graph_type_list = TWO_D_GRAPH_TYPES_2 else: graph_type_list = TWO_D_GRAPH_TYPES return render_template('eda/plots.html', columns=list(df.columns), x_list=list(df.columns), y_list=num_cols, graphs_2d=graph_type_list, action=action, x_column="", y_column="") else: return render_template('eda/help.html') else: return redirect('/') else: return redirect(url_for('/')) except Exception as e: ProjectReports.insert_record_eda(e) logger.error(e) return render_template('500.html', exception=e) @app_eda.route('/eda/<action>', methods=['POST']) def eda_post(action): try: if 'pid' in session: df = load_data() if df is not None: graphJSON = None if action == "show": range = request.form['range'] optradio = request.form['optradio'] columns_for_list = df.columns columns = request.form.getlist('columns') input_str = immutable_multi_dict_to_str(request.form) ProjectReports.insert_record_eda('Show', input=input_str) if len(columns) > 0: df = df.loc[:, columns] data = EDA.get_no_records(df, int(range), optradio) data = data.to_html() topselected = True if optradio == 'top' else False bottomSelected = True if optradio == 'bottom' else False return render_template('eda/showdataset.html', data=data, length=len(df), bottomSelected=bottomSelected, topselected=topselected, action=action, selectedCount=range, columns=columns_for_list) # elif action == "profiler": # ProjectReports.insert_record_eda('Download Profile Report') # # pr = ProfileReport(df, explorative=True, minimal=True, # correlations={"cramers": {"calculate": False}}) # # report_path = os.path.join(from_root(), "artifacts", f"{session.get("id")}_report.html") # pr.to_file(report_path) # with open(report_path) as fp: # content = fp.read() # # return Response( # content, # mimetype="text/csv", # headers={"Content-disposition": "attachment; filename=report.html"}) elif action == "correlation": method = request.form['method'] columns = request.form.getlist('columns') input_str = immutable_multi_dict_to_str(request.form, True) ProjectReports.insert_record_eda('Redirect To Correlation', input=input_str) if method is not None: # df=df.loc[:,columns] _corr = EDA.correlation_report(df, method) if len(columns) == 0: columns = _corr.columns _corr = _corr.loc[:, columns] _data = list(np.around(np.array(_corr.values), 2)) fig = ff.create_annotated_heatmap(_data, x=list(_corr.columns), y=list(_corr.index), colorscale='Viridis') # fig = ff.create_annotated_heatmap(_data, colorscale='Viridis') graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) return render_template('eda/correlation.html', data=graphJSON, columns=list(df.select_dtypes(exclude='object').columns), action=action, method=method) else: return render_template('eda/help.html') elif action == "outlier": method = request.form['method'] print(method) lower = 25 upper = 75 if method == "iqr": lower = request.form['lower'] upper = request.form['upper'] df = EDA.outlier_detection_iqr(df, int(lower), int(upper)) print(df) else: df = EDA.z_score_outlier_detection(df) print('missed') input_str = immutable_multi_dict_to_str(request.form, True) ProjectReports.insert_record_eda('Redirect To Outlier', input=input_str) graphJSON = PlotlyHelper.barplot(df, x='Features', y='Total outliers') pie_graphJSON = PlotlyHelper.pieplot( df.sort_values(by='Total outliers', ascending=False).loc[: 10 if len(df) > 10 else len(df)-1,:], names='Features', values='Total outliers', title='Top 10 Outliers') data = df.to_html() return render_template('eda/outliers.html', data=data, method=method, action=action, lower=lower, upper=upper, barplot=graphJSON, pieplot=pie_graphJSON) elif action == "plots": """All Polots for all kind of features????""" selected_graph_type = request.form['graph'] input_str = immutable_multi_dict_to_str(request.form) ProjectReports.insert_record_eda('Plot', input=input_str) num_cols, cat_cols = get_numeric_categorical_columns(df) if len(cat_cols) == 0: graph_type_list = TWO_D_GRAPH_TYPES_2 else: graph_type_list = TWO_D_GRAPH_TYPES if selected_graph_type == "Scatter Plot": x_column = request.form['xcolumn'] y_column = request.form['ycolumn'] graphJSON = PlotlyHelper.scatterplot(df, x=x_column, y=y_column, title='Scatter Plot') elif selected_graph_type == "Pie Chart": x_column = request.form['xcolumn'] new_df = df.groupby(x_column).count() temp_df = pd.DataFrame() temp_df[x_column] = list(new_df.index) temp_df['Count'] = list(new_df.iloc[:, 0]) graphJSON = PlotlyHelper.pieplot(temp_df, names=x_column, values='Count', title='Pie Chart') elif selected_graph_type == "Bar Graph": x_column = request.form['xcolumn'] new_df = df.groupby(x_column).count() temp_df = pd.DataFrame() temp_df[x_column] = list(new_df.index) temp_df['Count'] = list(new_df.iloc[:, 0]) graphJSON = PlotlyHelper.barplot(temp_df, x=x_column, y='Count') elif selected_graph_type == "Histogram": x_column = request.form['xcolumn'] graphJSON = PlotlyHelper.histogram(df, x=x_column) elif selected_graph_type == "Line Chart": x_column = request.form['xcolumn'] y_column = request.form['ycolumn'] graphJSON = PlotlyHelper.line(df, x=x_column, y=y_column) elif selected_graph_type == "Box Plot": x_column = request.form['xcolumn'] y_column = request.form['ycolumn'] graphJSON = PlotlyHelper.boxplot(df, x=x_column, y=y_column) elif selected_graph_type == "Dist Plot": x_column = request.form['xcolumn'] y_column = request.form['ycolumn'] hist_data = [] category_list = list(df[y_column].unique()) for category in category_list: hist_data.append(list(df[df[y_column] == category][x_column])) graphJSON = PlotlyHelper.create_distplot(hist_data, category_list) elif selected_graph_type == "Heat Map": graphJSON = PlotlyHelper.heatmap(df) return render_template('eda/plots.html', selected_graph_type=selected_graph_type, columns=list(df.columns), graphs_2d=graph_type_list, action=action, graphJSON=graphJSON) else: return render_template('eda/help.html') else: """Manage This""" pass else: return redirect(url_for('/')) except Exception as e: ProjectReports.insert_record_eda(e) return render_template('500.html', exception=e) @app_eda.route('/x_y_columns', methods=['GET', 'POST']) def x_y_columns(): try: if 'pid' in session: graph_selected = request.args.get('graph_selected') df = load_data() if df is not None: num_cols, cat_cols = get_numeric_categorical_columns(df) if graph_selected == "Bar Graph": return render_template('eda/x_y_columns.html', x_list=list(cat_cols), graph_selected=graph_selected) elif graph_selected == "Histogram": return render_template('eda/x_y_columns.html', x_list=list(df.columns), y_list=[], graph_selected=graph_selected) elif graph_selected == "Scatter Plot": return render_template('eda/x_y_columns.html', x_list=list(num_cols), y_list=list(num_cols), graph_selected=graph_selected) elif graph_selected == "Pie Chart": return render_template('eda/x_y_columns.html', x_list=list(cat_cols), graph_selected=graph_selected) elif graph_selected == "Line Chart": return render_template('eda/x_y_columns.html', x_list=list(num_cols), y_list=list(num_cols), graph_selected=graph_selected) elif graph_selected == "Box Plot": return render_template('eda/x_y_columns.html', x_list=list(cat_cols), y_list=list(num_cols), graph_selected=graph_selected) elif graph_selected == "Dist Plot": return render_template('eda/x_y_columns.html', x_list=list(num_cols), y_list=list(cat_cols), graph_selected=graph_selected) elif graph_selected == "Heat Map": return render_template('eda/x_y_columns.html', graph_selected=graph_selected) else: return redirect(url_for('/eda/help')) else: """Manage This""" pass else: return redirect(url_for('/')) except Exception as e: ProjectReports.insert_record_eda(e) return render_template('500.html', exception=e)
from flask import Blueprint, request, render_template, session, redirect, url_for from flask.wrappers import Response from loguru import logger from src.utils.common.data_helper import load_data from src.utils.common.plotly_helper import PlotlyHelper from src.utils.common.project_report_helper import ProjectReports import numpy as np from src.eda.eda_helper import EDA from pandas_profiling import ProfileReport from src.constants.constants import TWO_D_GRAPH_TYPES, TWO_D_GRAPH_TYPES_2 import plotly.figure_factory as ff import json import plotly from src.utils.common.common_helper import immutable_multi_dict_to_str, get_numeric_categorical_columns import os from from_root import from_root import pandas as pd app_eda = Blueprint('eda', __name__) @app_eda.route('/eda/<action>') def eda(action): try: if 'pid' in session: df = load_data() if df is not None: if action == "data-summary": ProjectReports.insert_record_eda('Redirect To Data Summary') summary = EDA.five_point_summary(df) data = summary.to_html() dtypes = EDA.data_dtype_info(df) return render_template('eda/5point.html', data=data, dtypes=dtypes.to_html(), count=len(df), column_count=df.shape[1]) # elif action == "profiler": # ProjectReports.insert_record_eda('Redirect To Profile Report') # return render_template('eda/profiler.html', action=action) elif action == "show": ProjectReports.insert_record_eda('Redirect To Show Dataset') data = EDA.get_no_records(df, 100) data = data.to_html() topselected = True bottomSelected = False selectedCount = 100 return render_template('eda/showdataset.html', data=data, length=len(df), bottomSelected=bottomSelected, topselected=topselected, action=action, selectedCount=selectedCount, columns=df.columns) elif action == "missing": ProjectReports.insert_record_eda('Redirect To Missing Value') df = EDA.missing_cells_table(df) if df is not None: graphJSON = PlotlyHelper.barplot(df, x='Column', y='Missing values') pie_graphJSON = PlotlyHelper.pieplot(df, names='Column', values='Missing values', title='Missing Values') data = df.drop('Column', axis=1) data = data.to_html() return render_template('eda/missing_values.html', action=action, data=data, barplot=graphJSON, pieplot=pie_graphJSON, contain_missing=True) else: return render_template('eda/missing_values.html', action=action, contain_missing=False) elif action == "outlier": ProjectReports.insert_record_eda('Redirect To Outlier') df = EDA.z_score_outlier_detection(df) graphJSON = PlotlyHelper.barplot(df, x='Features', y='Total outliers') pie_graphJSON = PlotlyHelper.pieplot( df.sort_values(by='Total outliers', ascending=False).loc[: 10 if len(df) > 10 else len(df)-1, :], names='Features', values='Total outliers', title='Top 10 Outliers') data = df.to_html() return render_template('eda/outliers.html', data=data, method='zscore', action=action, barplot=graphJSON, pieplot=pie_graphJSON) elif action == "correlation": ProjectReports.insert_record_eda('Redirect To Correlation') pearson_corr = EDA.correlation_report(df, 'pearson') persion_data = list(np.around(np.array(pearson_corr.values), 2)) fig = ff.create_annotated_heatmap(persion_data, x=list(pearson_corr.columns), y=list(pearson_corr.columns), colorscale='Viridis') graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) return render_template('eda/correlation.html', data=graphJSON, columns=list(pearson_corr.columns), action=action, method='pearson') elif action == "plots": ProjectReports.insert_record_eda('Plots') num_cols, cat_cols = get_numeric_categorical_columns(df) if len(cat_cols) == 0: graph_type_list = TWO_D_GRAPH_TYPES_2 else: graph_type_list = TWO_D_GRAPH_TYPES return render_template('eda/plots.html', columns=list(df.columns), x_list=list(df.columns), y_list=num_cols, graphs_2d=graph_type_list, action=action, x_column="", y_column="") else: return render_template('eda/help.html') else: return redirect('/') else: return redirect(url_for('/')) except Exception as e: ProjectReports.insert_record_eda(e) logger.error(e) return render_template('500.html', exception=e) @app_eda.route('/eda/<action>', methods=['POST']) def eda_post(action): try: if 'pid' in session: df = load_data() if df is not None: graphJSON = None if action == "show": range = request.form['range'] optradio = request.form['optradio'] columns_for_list = df.columns columns = request.form.getlist('columns') input_str = immutable_multi_dict_to_str(request.form) ProjectReports.insert_record_eda('Show', input=input_str) if len(columns) > 0: df = df.loc[:, columns] data = EDA.get_no_records(df, int(range), optradio) data = data.to_html() topselected = True if optradio == 'top' else False bottomSelected = True if optradio == 'bottom' else False return render_template('eda/showdataset.html', data=data, length=len(df), bottomSelected=bottomSelected, topselected=topselected, action=action, selectedCount=range, columns=columns_for_list) # elif action == "profiler": # ProjectReports.insert_record_eda('Download Profile Report') # # pr = ProfileReport(df, explorative=True, minimal=True, # correlations={"cramers": {"calculate": False}}) # # report_path = os.path.join(from_root(), "artifacts", f"{session.get('id')}_report.html") # pr.to_file(report_path) # with open(report_path) as fp: # content = fp.read() # # return Response( # content, # mimetype="text/csv", # headers={"Content-disposition": "attachment; filename=report.html"}) elif action == "correlation": method = request.form['method'] columns = request.form.getlist('columns') input_str = immutable_multi_dict_to_str(request.form, True) ProjectReports.insert_record_eda('Redirect To Correlation', input=input_str) if method is not None: # df=df.loc[:,columns] _corr = EDA.correlation_report(df, method) if len(columns) == 0: columns = _corr.columns _corr = _corr.loc[:, columns] _data = list(np.around(np.array(_corr.values), 2)) fig = ff.create_annotated_heatmap(_data, x=list(_corr.columns), y=list(_corr.index), colorscale='Viridis') # fig = ff.create_annotated_heatmap(_data, colorscale='Viridis') graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) return render_template('eda/correlation.html', data=graphJSON, columns=list(df.select_dtypes(exclude='object').columns), action=action, method=method) else: return render_template('eda/help.html') elif action == "outlier": method = request.form['method'] print(method) lower = 25 upper = 75 if method == "iqr": lower = request.form['lower'] upper = request.form['upper'] df = EDA.outlier_detection_iqr(df, int(lower), int(upper)) print(df) else: df = EDA.z_score_outlier_detection(df) print('missed') input_str = immutable_multi_dict_to_str(request.form, True) ProjectReports.insert_record_eda('Redirect To Outlier', input=input_str) graphJSON = PlotlyHelper.barplot(df, x='Features', y='Total outliers') pie_graphJSON = PlotlyHelper.pieplot( df.sort_values(by='Total outliers', ascending=False).loc[: 10 if len(df) > 10 else len(df)-1,:], names='Features', values='Total outliers', title='Top 10 Outliers') data = df.to_html() return render_template('eda/outliers.html', data=data, method=method, action=action, lower=lower, upper=upper, barplot=graphJSON, pieplot=pie_graphJSON) elif action == "plots": """All Polots for all kind of features????""" selected_graph_type = request.form['graph'] input_str = immutable_multi_dict_to_str(request.form) ProjectReports.insert_record_eda('Plot', input=input_str) num_cols, cat_cols = get_numeric_categorical_columns(df) if len(cat_cols) == 0: graph_type_list = TWO_D_GRAPH_TYPES_2 else: graph_type_list = TWO_D_GRAPH_TYPES if selected_graph_type == "Scatter Plot": x_column = request.form['xcolumn'] y_column = request.form['ycolumn'] graphJSON = PlotlyHelper.scatterplot(df, x=x_column, y=y_column, title='Scatter Plot') elif selected_graph_type == "Pie Chart": x_column = request.form['xcolumn'] new_df = df.groupby(x_column).count() temp_df = pd.DataFrame() temp_df[x_column] = list(new_df.index) temp_df['Count'] = list(new_df.iloc[:, 0]) graphJSON = PlotlyHelper.pieplot(temp_df, names=x_column, values='Count', title='Pie Chart') elif selected_graph_type == "Bar Graph": x_column = request.form['xcolumn'] new_df = df.groupby(x_column).count() temp_df = pd.DataFrame() temp_df[x_column] = list(new_df.index) temp_df['Count'] = list(new_df.iloc[:, 0]) graphJSON = PlotlyHelper.barplot(temp_df, x=x_column, y='Count') elif selected_graph_type == "Histogram": x_column = request.form['xcolumn'] graphJSON = PlotlyHelper.histogram(df, x=x_column) elif selected_graph_type == "Line Chart": x_column = request.form['xcolumn'] y_column = request.form['ycolumn'] graphJSON = PlotlyHelper.line(df, x=x_column, y=y_column) elif selected_graph_type == "Box Plot": x_column = request.form['xcolumn'] y_column = request.form['ycolumn'] graphJSON = PlotlyHelper.boxplot(df, x=x_column, y=y_column) elif selected_graph_type == "Dist Plot": x_column = request.form['xcolumn'] y_column = request.form['ycolumn'] hist_data = [] category_list = list(df[y_column].unique()) for category in category_list: hist_data.append(list(df[df[y_column] == category][x_column])) graphJSON = PlotlyHelper.create_distplot(hist_data, category_list) elif selected_graph_type == "Heat Map": graphJSON = PlotlyHelper.heatmap(df) return render_template('eda/plots.html', selected_graph_type=selected_graph_type, columns=list(df.columns), graphs_2d=graph_type_list, action=action, graphJSON=graphJSON) else: return render_template('eda/help.html') else: """Manage This""" pass else: return redirect(url_for('/')) except Exception as e: ProjectReports.insert_record_eda(e) return render_template('500.html', exception=e) @app_eda.route('/x_y_columns', methods=['GET', 'POST']) def x_y_columns(): try: if 'pid' in session: graph_selected = request.args.get('graph_selected') df = load_data() if df is not None: num_cols, cat_cols = get_numeric_categorical_columns(df) if graph_selected == "Bar Graph": return render_template('eda/x_y_columns.html', x_list=list(cat_cols), graph_selected=graph_selected) elif graph_selected == "Histogram": return render_template('eda/x_y_columns.html', x_list=list(df.columns), y_list=[], graph_selected=graph_selected) elif graph_selected == "Scatter Plot": return render_template('eda/x_y_columns.html', x_list=list(num_cols), y_list=list(num_cols), graph_selected=graph_selected) elif graph_selected == "Pie Chart": return render_template('eda/x_y_columns.html', x_list=list(cat_cols), graph_selected=graph_selected) elif graph_selected == "Line Chart": return render_template('eda/x_y_columns.html', x_list=list(num_cols), y_list=list(num_cols), graph_selected=graph_selected) elif graph_selected == "Box Plot": return render_template('eda/x_y_columns.html', x_list=list(cat_cols), y_list=list(num_cols), graph_selected=graph_selected) elif graph_selected == "Dist Plot": return render_template('eda/x_y_columns.html', x_list=list(num_cols), y_list=list(cat_cols), graph_selected=graph_selected) elif graph_selected == "Heat Map": return render_template('eda/x_y_columns.html', graph_selected=graph_selected) else: return redirect(url_for('/eda/help')) else: """Manage This""" pass else: return redirect(url_for('/')) except Exception as e: ProjectReports.insert_record_eda(e) return render_template('500.html', exception=e)
''' This module is used to download the data from several feeds in the public KoDa API. Supported companies: - dintur - Västernorrlands län: Only GTFSStatic - dt - Dalatrafik - klt - Kalmar länstrafik - krono - Kronobergs Länstrafik: Only GTFSStatic - otraf - Östgötatrafiken - sj - SJ + Snälltåget + Tågab: Only GTFSStatic - skane - Skånetrafiken - sl - Stockholm län: All feeds without VehiclePositions - ul - Uppsala län - varm - Värmlandstrafik+Karlstadbuss - vt - Västtrafik: Only GTFSStatic - xt - X-trafik Supported feeds: - VehiclePositions - TripUpdates - ServiceAlerts Supported date format: YYYY-MM-DD and YYYY_MM_DD ''' import gzip import json import tarfile import warnings import datetime import contextlib import requests import numpy as np import ey from google.protobuf import json_format import pandas as pd from joblib import Parallel, delayed import tqdm from .. import config from . import gtfs_realtime_pb2 def _is_json(series: pd.Series) -> bool: try: return isinstance(series[0][0], dict) except TypeError: return False def unpack_jsons(df: pd.DataFrame) -> pd.DataFrame: keys_to_sanitise = [] for k in list(df.keys()): # If the content is a json, unpack and remove if df[k].dtype == np.dtype('O') and _is_json(df[k]): keys_to_sanitise.append(k) if keys_to_sanitise: indexes = [] unpacked = {k: [] for k in keys_to_sanitise} for ix in df.index: for k in keys_to_sanitise: this_unpack = pd.json_normalize(df[k][ix]) unpacked[k].append(this_unpack) indexes.extend(ix for _ in range(len(this_unpack))) df.drop(keys_to_sanitise, axis='columns', inplace=True) unpacked_series = [] for k in keys_to_sanitise: this_df = pd.concat(unpacked[k], axis='index').reset_index(drop=True) this_df.rename(columns={curr_name: '_'.join((k, curr_name)) for curr_name in this_df.keys()}, inplace=True) unpacked_series.append(this_df) repeated = df.iloc[indexes].reset_index(drop=True) df = pd.concat([repeated] + unpacked_series, axis='columns') for k in df.keys(): if df[k].dtype == np.dtype('O') and _is_json(df[k]): warnings.warn(RuntimeWarning(f'There are extra json in column {k}')) return df def _get_data_path(company: str, feed: str, date: str, hour: (int, str)) -> str: return f'{config.CACHE_DIR}/{company}_{feed}_{date.replace('-', '_')}_{hour}.feather' def _parse_gtfs(gtfsrt: bytes) -> pd.DataFrame: # Read in to a FeedMessage class, of the GTFS-RT format msg = gtfs_realtime_pb2.FeedMessage() pbfile = gzip.decompress(gtfsrt) msg.ParseFromString(pbfile) msg_json = json_format.MessageToJson(msg) msg_dict = json.loads(msg_json) df = pd.json_normalize(msg_dict.get('entity', dict()), sep='_') df = unpack_jsons(df) df.reset_index(drop=True, inplace=True) return df def normalize_keys(df: pd.DataFrame) -> None: """Reformat the name of the keys to a consistent format, according to GTFS""" renames = {'tripUpdate_trip_tripId': 'trip_id', 'tripUpdate_trip_startDate': 'start_date', 'tripUpdate_trip_directionId': 'direction_id', 'tripUpdate_trip_routeId': 'route_id', 'tripUpdate_trip_scheduleRelationship': 'schedule_relationship', 'tripUpdate_trip_startTime': 'start_time', 'tripUpdate_timestamp': 'timestamp', 'tripUpdate_vehicle_id': 'vehicle_id', 'stopSequence': 'stop_sequence', 'stopId': 'stop_id', 'scheduleRelationship': 'schedule_relationship2', 'vehicle_trip_tripId': 'trip_id', 'vehicle_trip_scheduleRelationship': 'schedule_relationship', 'vehicle_timestamp': 'timestamp', 'vehicle_vehicle_id': 'vehicle_id', 'vehicle_trip_startTime': 'start_time', 'vehicle_trip_startDate': 'start_date', 'vehicle_trip_routeId': 'route_id', 'vehicle_trip_directionId': 'direction_id', 'tripUpdate_stopTimeUpdate_stopSequence': 'stop_sequence', 'tripUpdate_stopTimeUpdate_stopId': 'stop_id', 'tripUpdate_stopTimeUpdate_arrival_delay': 'arrival_delay', 'tripUpdate_stopTimeUpdate_arrival_time': 'arrival_time', 'tripUpdate_stopTimeUpdate_departure_delay': 'departure_delay', 'tripUpdate_stopTimeUpdate_departure_time': 'departure_time', 'tripUpdate_stopTimeUpdate_arrival_uncertainty': 'arrival_uncertainty', 'tripUpdate_stopTimeUpdate_departure_uncertainty': 'departure_uncertainty', 'alert_activePeriod_start': 'period_start', 'alert_activePeriod_end': 'period_end', 'alert_informedEntity_routeId': 'route_id', 'alert_informedEntity_stopId': 'stop_id', 'alert_informedEntity_trip_tripId': 'trip_id', 'alert_informedEntity_trip_scheduleRelationship': 'schedule_relationship', 'alert_headerText_translation_text': 'header_text', 'alert_descriptionText_translation_text': 'description_text', } df.rename(columns=renames, inplace=True) def sanitise_array(df: pd.DataFrame) -> None: normalize_keys(df) # Remove columns and rows with all NaNs df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True) # Remove old indexes df.drop(columns='level_0', inplace=True, errors='ignore') # Remove duplicated entries, ignoring timpestamps and index keys = list(df.keys()) with contextlib.suppress(ValueError): keys.remove('timestamp') keys.remove('index') # These may be updated in the database, so ignore as well keys.remove('arrival_delay') keys.remove('arrival_time') keys.remove('departure_delay') keys.remove('departure_time') keys.remove('arrival_uncertainty') keys.remove('departure_uncertainty') df.drop_duplicates(subset=keys, inplace=True, keep='last') def download_file(task): url = task.inputs['url'] output = task.outputs['file'] with open(output, 'wb') as f_out: with requests.get(url, stream=True) as req: for chunk in req.iter_content(chunk_size=128): f_out.write(chunk) def get_data(date: str, hour: (int, str), feed: str, company: str, output_file: (str, None) = None) -> None: if output_file is None: output_file = _get_data_path(company, feed, date, hour) print('Getting', output_file) # admit both _ and - date = date.replace('_', '-') data_date = datetime.date.fromisoformat(date) # ------------------------------------------------------------------------ # Create data dir # ------------------------------------------------------------------------ ey.shell('mkdir [o:datafolder:data]') # ------------------------------------------------------------------------ # Download data # ------------------------------------------------------------------------ if config.API_VERSION == 1: koda_url = f"https://koda.linkoping-ri.se/KoDa/api/v0.1?company={company}&feed={feed}&date={date}" else: koda_url = f'https://koda.linkoping-ri.se/KoDa/api/v2/gtfs-rt/{company}/{feed}?date={date}&hour={hour}&key={config.API_KEY}' out_path = f'{config.CACHE_DIR}/' + f'{company}-{feed}-{date}.bz2'.lower() download = ey.func(download_file, inputs={'url': koda_url}, outputs={'file': out_path}) # Check the file: with open(download.outputs['file'], 'rb') as f: start = f.read(10) if b'error' in start: msg = start + f.read(70) msg = msg.strip(b'{}" ') raise ValueError('API returned the following error message:', msg) # Select the list of files to extract: tar_file_name = download.outputs['file'] # ------------------------------------------------------------------------ # GTFS to file # ------------------------------------------------------------------------ def merge_files(task): tar = tarfile.open(tar_file_name) _prefix = f'mnt/kodashare/KoDa_NiFi_data/{company}/{feed}/{data_date.year}/' \ f'{str(data_date.month).zfill(2)}/{str(data_date.day).zfill(2)}/{str(hour).zfill(2)}/' gzfiles = [name for name in tar.getnames() if name.startswith(_prefix) and 'Duplicate' not in name] if len(gzfiles) == 0: # File does not contain data. Save an empty file. pd.DataFrame().reset_index().to_feather(task.outputs['outfile']) return # Extract each file and pass it to the parsing function parsed_files = Parallel(n_jobs=config.N_CPU, verbose=0)( delayed(_parse_gtfs)(tar.extractfile(gtfsfile).read()) for gtfsfile in gzfiles) tar.close() merged_df = pd.concat(parsed_files) # Force casts: castings = dict() for k in merged_df.keys(): if 'timestamp' in k: # Timestamps should be ints, not strings castings[k] = np.int64 elif k == 'id': castings[k] = np.int64 merged_df.dropna(how='all', inplace=True) # Remove rows of only NaNs merged_df = merged_df.astype(castings) # Remove dots from column names rename = dict((k, k.replace('.', '_')) for k in merged_df.keys() if '.' in k) merged_df.rename(columns=rename, inplace=True) # Clean up duplicates, fix keys, etc sanitise_array(merged_df) if merged_df.empty: # Feather does not support a DF without columns, so add a dummy one merged_df['_'] = np.zeros(len(merged_df), dtype=np.bool_) # Save to file merged_df.reset_index(inplace=True) merged_df.to_feather(task.outputs['outfile'], compression='zstd', compression_level=9) ey.func(merge_files, outputs={'outfile': output_file}) def get_range(start_date, end_date, start_hour, end_hour, feed, company) -> None: warnings.warn(DeprecationWarning('Use get_data_range instead')) date_range = pd.date_range(start=start_date, end=end_date) hour_range = range(start_hour, end_hour + 1) for date in tqdm.tqdm(date_range): print("Date: ", date.strftime("%Y-%m-%d")) for hour in tqdm.tqdm(hour_range, leave=False, desc='Hours for ' + date.strftime("%Y-%m-%d")): get_data(f'{date.year:0>4}-{date.month:0>2}-{date.day:0>2}', hour, feed, company)
''' This module is used to download the data from several feeds in the public KoDa API. Supported companies: - dintur - Västernorrlands län: Only GTFSStatic - dt - Dalatrafik - klt - Kalmar länstrafik - krono - Kronobergs Länstrafik: Only GTFSStatic - otraf - Östgötatrafiken - sj - SJ + Snälltåget + Tågab: Only GTFSStatic - skane - Skånetrafiken - sl - Stockholm län: All feeds without VehiclePositions - ul - Uppsala län - varm - Värmlandstrafik+Karlstadbuss - vt - Västtrafik: Only GTFSStatic - xt - X-trafik Supported feeds: - VehiclePositions - TripUpdates - ServiceAlerts Supported date format: YYYY-MM-DD and YYYY_MM_DD ''' import gzip import json import tarfile import warnings import datetime import contextlib import requests import numpy as np import ey from google.protobuf import json_format import pandas as pd from joblib import Parallel, delayed import tqdm from .. import config from . import gtfs_realtime_pb2 def _is_json(series: pd.Series) -> bool: try: return isinstance(series[0][0], dict) except TypeError: return False def unpack_jsons(df: pd.DataFrame) -> pd.DataFrame: keys_to_sanitise = [] for k in list(df.keys()): # If the content is a json, unpack and remove if df[k].dtype == np.dtype('O') and _is_json(df[k]): keys_to_sanitise.append(k) if keys_to_sanitise: indexes = [] unpacked = {k: [] for k in keys_to_sanitise} for ix in df.index: for k in keys_to_sanitise: this_unpack = pd.json_normalize(df[k][ix]) unpacked[k].append(this_unpack) indexes.extend(ix for _ in range(len(this_unpack))) df.drop(keys_to_sanitise, axis='columns', inplace=True) unpacked_series = [] for k in keys_to_sanitise: this_df = pd.concat(unpacked[k], axis='index').reset_index(drop=True) this_df.rename(columns={curr_name: '_'.join((k, curr_name)) for curr_name in this_df.keys()}, inplace=True) unpacked_series.append(this_df) repeated = df.iloc[indexes].reset_index(drop=True) df = pd.concat([repeated] + unpacked_series, axis='columns') for k in df.keys(): if df[k].dtype == np.dtype('O') and _is_json(df[k]): warnings.warn(RuntimeWarning(f'There are extra json in column {k}')) return df def _get_data_path(company: str, feed: str, date: str, hour: (int, str)) -> str: return f'{config.CACHE_DIR}/{company}_{feed}_{date.replace("-", "_")}_{hour}.feather' def _parse_gtfs(gtfsrt: bytes) -> pd.DataFrame: # Read in to a FeedMessage class, of the GTFS-RT format msg = gtfs_realtime_pb2.FeedMessage() pbfile = gzip.decompress(gtfsrt) msg.ParseFromString(pbfile) msg_json = json_format.MessageToJson(msg) msg_dict = json.loads(msg_json) df = pd.json_normalize(msg_dict.get('entity', dict()), sep='_') df = unpack_jsons(df) df.reset_index(drop=True, inplace=True) return df def normalize_keys(df: pd.DataFrame) -> None: """Reformat the name of the keys to a consistent format, according to GTFS""" renames = {'tripUpdate_trip_tripId': 'trip_id', 'tripUpdate_trip_startDate': 'start_date', 'tripUpdate_trip_directionId': 'direction_id', 'tripUpdate_trip_routeId': 'route_id', 'tripUpdate_trip_scheduleRelationship': 'schedule_relationship', 'tripUpdate_trip_startTime': 'start_time', 'tripUpdate_timestamp': 'timestamp', 'tripUpdate_vehicle_id': 'vehicle_id', 'stopSequence': 'stop_sequence', 'stopId': 'stop_id', 'scheduleRelationship': 'schedule_relationship2', 'vehicle_trip_tripId': 'trip_id', 'vehicle_trip_scheduleRelationship': 'schedule_relationship', 'vehicle_timestamp': 'timestamp', 'vehicle_vehicle_id': 'vehicle_id', 'vehicle_trip_startTime': 'start_time', 'vehicle_trip_startDate': 'start_date', 'vehicle_trip_routeId': 'route_id', 'vehicle_trip_directionId': 'direction_id', 'tripUpdate_stopTimeUpdate_stopSequence': 'stop_sequence', 'tripUpdate_stopTimeUpdate_stopId': 'stop_id', 'tripUpdate_stopTimeUpdate_arrival_delay': 'arrival_delay', 'tripUpdate_stopTimeUpdate_arrival_time': 'arrival_time', 'tripUpdate_stopTimeUpdate_departure_delay': 'departure_delay', 'tripUpdate_stopTimeUpdate_departure_time': 'departure_time', 'tripUpdate_stopTimeUpdate_arrival_uncertainty': 'arrival_uncertainty', 'tripUpdate_stopTimeUpdate_departure_uncertainty': 'departure_uncertainty', 'alert_activePeriod_start': 'period_start', 'alert_activePeriod_end': 'period_end', 'alert_informedEntity_routeId': 'route_id', 'alert_informedEntity_stopId': 'stop_id', 'alert_informedEntity_trip_tripId': 'trip_id', 'alert_informedEntity_trip_scheduleRelationship': 'schedule_relationship', 'alert_headerText_translation_text': 'header_text', 'alert_descriptionText_translation_text': 'description_text', } df.rename(columns=renames, inplace=True) def sanitise_array(df: pd.DataFrame) -> None: normalize_keys(df) # Remove columns and rows with all NaNs df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True) # Remove old indexes df.drop(columns='level_0', inplace=True, errors='ignore') # Remove duplicated entries, ignoring timpestamps and index keys = list(df.keys()) with contextlib.suppress(ValueError): keys.remove('timestamp') keys.remove('index') # These may be updated in the database, so ignore as well keys.remove('arrival_delay') keys.remove('arrival_time') keys.remove('departure_delay') keys.remove('departure_time') keys.remove('arrival_uncertainty') keys.remove('departure_uncertainty') df.drop_duplicates(subset=keys, inplace=True, keep='last') def download_file(task): url = task.inputs['url'] output = task.outputs['file'] with open(output, 'wb') as f_out: with requests.get(url, stream=True) as req: for chunk in req.iter_content(chunk_size=128): f_out.write(chunk) def get_data(date: str, hour: (int, str), feed: str, company: str, output_file: (str, None) = None) -> None: if output_file is None: output_file = _get_data_path(company, feed, date, hour) print('Getting', output_file) # admit both _ and - date = date.replace('_', '-') data_date = datetime.date.fromisoformat(date) # ------------------------------------------------------------------------ # Create data dir # ------------------------------------------------------------------------ ey.shell('mkdir [o:datafolder:data]') # ------------------------------------------------------------------------ # Download data # ------------------------------------------------------------------------ if config.API_VERSION == 1: koda_url = f"https://koda.linkoping-ri.se/KoDa/api/v0.1?company={company}&feed={feed}&date={date}" else: koda_url = f'https://koda.linkoping-ri.se/KoDa/api/v2/gtfs-rt/{company}/{feed}?date={date}&hour={hour}&key={config.API_KEY}' out_path = f'{config.CACHE_DIR}/' + f'{company}-{feed}-{date}.bz2'.lower() download = ey.func(download_file, inputs={'url': koda_url}, outputs={'file': out_path}) # Check the file: with open(download.outputs['file'], 'rb') as f: start = f.read(10) if b'error' in start: msg = start + f.read(70) msg = msg.strip(b'{}" ') raise ValueError('API returned the following error message:', msg) # Select the list of files to extract: tar_file_name = download.outputs['file'] # ------------------------------------------------------------------------ # GTFS to file # ------------------------------------------------------------------------ def merge_files(task): tar = tarfile.open(tar_file_name) _prefix = f'mnt/kodashare/KoDa_NiFi_data/{company}/{feed}/{data_date.year}/' \ f'{str(data_date.month).zfill(2)}/{str(data_date.day).zfill(2)}/{str(hour).zfill(2)}/' gzfiles = [name for name in tar.getnames() if name.startswith(_prefix) and 'Duplicate' not in name] if len(gzfiles) == 0: # File does not contain data. Save an empty file. pd.DataFrame().reset_index().to_feather(task.outputs['outfile']) return # Extract each file and pass it to the parsing function parsed_files = Parallel(n_jobs=config.N_CPU, verbose=0)( delayed(_parse_gtfs)(tar.extractfile(gtfsfile).read()) for gtfsfile in gzfiles) tar.close() merged_df = pd.concat(parsed_files) # Force casts: castings = dict() for k in merged_df.keys(): if 'timestamp' in k: # Timestamps should be ints, not strings castings[k] = np.int64 elif k == 'id': castings[k] = np.int64 merged_df.dropna(how='all', inplace=True) # Remove rows of only NaNs merged_df = merged_df.astype(castings) # Remove dots from column names rename = dict((k, k.replace('.', '_')) for k in merged_df.keys() if '.' in k) merged_df.rename(columns=rename, inplace=True) # Clean up duplicates, fix keys, etc sanitise_array(merged_df) if merged_df.empty: # Feather does not support a DF without columns, so add a dummy one merged_df['_'] = np.zeros(len(merged_df), dtype=np.bool_) # Save to file merged_df.reset_index(inplace=True) merged_df.to_feather(task.outputs['outfile'], compression='zstd', compression_level=9) ey.func(merge_files, outputs={'outfile': output_file}) def get_range(start_date, end_date, start_hour, end_hour, feed, company) -> None: warnings.warn(DeprecationWarning('Use get_data_range instead')) date_range = pd.date_range(start=start_date, end=end_date) hour_range = range(start_hour, end_hour + 1) for date in tqdm.tqdm(date_range): print("Date: ", date.strftime("%Y-%m-%d")) for hour in tqdm.tqdm(hour_range, leave=False, desc='Hours for ' + date.strftime("%Y-%m-%d")): get_data(f'{date.year:0>4}-{date.month:0>2}-{date.day:0>2}', hour, feed, company)
#!/usr/bin/env python # Copyright The PyTorch Lightning team. # # 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 import re from typing import List from pl_bolts import __homepage__, __version__, _PROJECT_ROOT _PATH_BADGES = os.path.join('.', 'docs', 'source', '_images', 'badges') # badge to download _DEFAULT_BADGES = ( 'Conda', 'DockerHub', 'codecov', 'ReadTheDocs', 'Slack', 'Discourse status', 'license', ) def _load_requirements(path_dir: str, file_name: str = 'requirements.txt', comment_char: str = '#') -> List[str]: """Load requirements from a file >>> _load_requirements(_PROJECT_ROOT) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ['torch...', 'pytorch-lightning...'...] """ with open(os.path.join(path_dir, file_name), 'r') as file: lines = [ln.strip() for ln in file.readlines()] reqs = [] for ln in lines: # filer all comments if comment_char in ln: ln = ln[:ln.index(comment_char)].strip() # skip directly installed dependencies if ln.startswith('http'): continue if ln: # if requirement is not empty reqs.append(ln) return reqs def _load_readme_description(path_dir: str, homepage: str = __homepage__, ver: str = __version__) -> str: """Load readme as decribtion >>> _load_readme_description(_PROJECT_ROOT) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE '<div align="center">...' """ path_readme = os.path.join(path_dir, "README.md") text = open(path_readme, encoding="utf-8").read() # drop images from readme text = text.replace('![PT to PL](docs/source/_images/general/pl_quick_start_full_compressed.gif)', '') # https://github.com/PyTorchLightning/pytorch-lightning/raw/master/docs/source/_images/lightning_module/pt_to_pl.png github_source_url = os.path.join(homepage, "raw", ver) # replace relative repository path to absolute link to the release # do not replace all "docs" as in the readme we reger some other sources with particular path to docs text = text.replace("docs/source/_images/", f"{os.path.join(github_source_url, "docs/source/_images/")}") # readthedocs badge text = text.replace('badge/?version=stable', f'badge/?version={ver}') text = text.replace('lightning-bolts.readthedocs.io/en/stable/', f'lightning-bolts.readthedocs.io/en/{ver}') # codecov badge text = text.replace('/branch/master/graph/badge.svg', f'/release/{ver}/graph/badge.svg') # replace github badges for release ones text = text.replace('badge.svg?branch=master&event=push', f'badge.svg?tag={ver}') skip_begin = r'<!-- following section will be skipped from PyPI description -->' skip_end = r'<!-- end skipping PyPI description -->' # todo: wrap content as commented description text = re.sub(rf"{skip_begin}.+?{skip_end}", '<!-- -->', text, flags=re.IGNORECASE + re.DOTALL) # # https://github.com/Borda/pytorch-lightning/releases/download/1.1.0a6/codecov_badge.png # github_release_url = os.path.join(homepage, "releases", "download", ver) # # download badge and replace url with local file # text = _parse_for_badge(text, github_release_url) return text
#!/usr/bin/env python # Copyright The PyTorch Lightning team. # # 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 import re from typing import List from pl_bolts import __homepage__, __version__, _PROJECT_ROOT _PATH_BADGES = os.path.join('.', 'docs', 'source', '_images', 'badges') # badge to download _DEFAULT_BADGES = ( 'Conda', 'DockerHub', 'codecov', 'ReadTheDocs', 'Slack', 'Discourse status', 'license', ) def _load_requirements(path_dir: str, file_name: str = 'requirements.txt', comment_char: str = '#') -> List[str]: """Load requirements from a file >>> _load_requirements(_PROJECT_ROOT) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ['torch...', 'pytorch-lightning...'...] """ with open(os.path.join(path_dir, file_name), 'r') as file: lines = [ln.strip() for ln in file.readlines()] reqs = [] for ln in lines: # filer all comments if comment_char in ln: ln = ln[:ln.index(comment_char)].strip() # skip directly installed dependencies if ln.startswith('http'): continue if ln: # if requirement is not empty reqs.append(ln) return reqs def _load_readme_description(path_dir: str, homepage: str = __homepage__, ver: str = __version__) -> str: """Load readme as decribtion >>> _load_readme_description(_PROJECT_ROOT) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE '<div align="center">...' """ path_readme = os.path.join(path_dir, "README.md") text = open(path_readme, encoding="utf-8").read() # drop images from readme text = text.replace('![PT to PL](docs/source/_images/general/pl_quick_start_full_compressed.gif)', '') # https://github.com/PyTorchLightning/pytorch-lightning/raw/master/docs/source/_images/lightning_module/pt_to_pl.png github_source_url = os.path.join(homepage, "raw", ver) # replace relative repository path to absolute link to the release # do not replace all "docs" as in the readme we reger some other sources with particular path to docs text = text.replace("docs/source/_images/", f"{os.path.join(github_source_url, 'docs/source/_images/')}") # readthedocs badge text = text.replace('badge/?version=stable', f'badge/?version={ver}') text = text.replace('lightning-bolts.readthedocs.io/en/stable/', f'lightning-bolts.readthedocs.io/en/{ver}') # codecov badge text = text.replace('/branch/master/graph/badge.svg', f'/release/{ver}/graph/badge.svg') # replace github badges for release ones text = text.replace('badge.svg?branch=master&event=push', f'badge.svg?tag={ver}') skip_begin = r'<!-- following section will be skipped from PyPI description -->' skip_end = r'<!-- end skipping PyPI description -->' # todo: wrap content as commented description text = re.sub(rf"{skip_begin}.+?{skip_end}", '<!-- -->', text, flags=re.IGNORECASE + re.DOTALL) # # https://github.com/Borda/pytorch-lightning/releases/download/1.1.0a6/codecov_badge.png # github_release_url = os.path.join(homepage, "releases", "download", ver) # # download badge and replace url with local file # text = _parse_for_badge(text, github_release_url) return text
import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity import pathlib import logging from copy import copy import numpy as np class Geomatch: def __init__(self, standard_db=False, # порядок колонок имеет значение т.к. определяет порядок фильтрации множеств match_columns=['region', 'settlement', 'municipality'], threshold=None, debug=False, skip_dead_end_fields=0, filter_by_prev=True ): self.current_directory = str(pathlib.Path(__file__).parent.resolve()) if type(standard_db) is pd.core.frame.DataFrame: self.standard = standard_db.reset_index(drop=True) elif type(standard_db) is str: self.standard = pd.read_csv(pathlib.Path(f'{standard_db}'), compression='zip') else: self.standard = pd.read_csv(pathlib.Path(f'{self.current_directory}/standard.zip'), compression='zip') self.standard = self.standard.fillna('') # здесь можно задать threshold срабатывания для полей если не задано то threshold = 0 if threshold is not None: self.threshold = threshold else: self.threshold = {} if debug: logging.basicConfig(filename='debug.log', format='%(asctime)s - %(levelname)s \n%(message)s', level=logging.DEBUG) self.skip_dead_end_fields = skip_dead_end_fields self.vectorizers = {} self.vectors = {} self.ids = {} self.keys = {} self.field_ids = {} self.filter_ids = None self.match_columns = match_columns # self.standard = self.standard # [self.match_columns] self.filter_by_prev = filter_by_prev # todo: протестировать другие варианты # инициализируем tfidf по каждой колонке for field in self.match_columns: self.ids[field] = self.standard.reset_index().groupby(field)['index'].apply(list).to_dict() self.keys[field] = list(self.ids[field].keys()) self.field_ids[field] = list(self.ids[field].values()) self.field_ids[field] = {value: k for k, v in enumerate(self.field_ids[field]) for value in self.field_ids[field][k]} self.vectorizers[field] = TfidfVectorizer(ngram_range=(1, 4), analyzer='char_wb') self.vectors[field] = self.vectorizers[field].fit_transform(self.keys[field]) # print(self.standard.groupby(field)['index'].apply(list).to_dict()) # print(len(self.ids[field])) def get_output(self, scores, field, top_n=1): out = [] if scores is None: out = [[{'name': '', 'score': 0, 'ids': set()}]] else: for score in scores: row = [] for i in (-score).argsort()[:top_n]: id = i if self.filter_ids: id = self.get_filter_ids(field)[i] curr_key = self.keys[field][id] ids = self.ids[field][curr_key] row.append({ 'id': id, 'name': curr_key, 'score': score[i], 'ids': set(ids) }) out.append(row) return out def get_filter_ids(self, field): return np.array(list({self.field_ids[field][i] for i in self.filter_ids})) def find_similar_records(self, data, field): vec = self.vectorizers[field].transform(data).toarray() vectors = self.vectors[field] if self.filter_ids: vectors = vectors[self.get_filter_ids(field), :] out = cosine_similarity( vec, vectors ) return out def return_matched_rows(self, ids, max_rows=1): if ids: selected_record = list(ids)[0] return dict(self.standard.iloc[selected_record]) else: return {i: '' for i in self.match_columns} def find_in_field(self, address_field, field, top_n=5): scores = None if address_field != '': scores = self.find_similar_records([address_field], field) return self.get_output(scores, field, top_n) def find_in_fields_by_step(self, address_dict): if type(address_dict) is list: address_dict = self.__to_list_of_dict__(address_dict) out = {} self.filter_ids = None for field in self.match_columns: if field in address_dict: out[field] = self.find_in_field(address_dict[field], field) if self.filter_by_prev: self.filter_ids = out[field][0][0]['ids'] return self.__to_dict_of_list__(out) def find_in_fields_by_intersection(self, address_dict): if type(address_dict) is list: address_dict = self.__to_list_of_dict__(address_dict) out = {} for field in self.match_columns: if field in address_dict: out[field] = self.find_in_field(address_dict[field], field) return self.__to_dict_of_list__(out) def check_threshold(self, field, score): if field in self.threshold: threshold = self.threshold[field] else: threshold = 0 return score > threshold def filter_by_field_intersection(self, search_results): results = [] for search_result in search_results: ids = [] skip_dead_end_fields = 0 curr_query = { 'ids': [] } for field in search_result: if self.check_threshold(field, search_result[field][0]['score']): test_ids = copy(ids) test_ids.append(search_result[field][0]['ids']) search_result_field = search_result[field][0] # здесь происходит проверка на тупиковые множества if len(set.intersection(*test_ids)) > 0 or self.skip_dead_end_fields <= skip_dead_end_fields: ids = test_ids else: skip_dead_end_fields += 1 logging.debug(f'action: SKIP_DEAD_END_FIELD \n' f'field: {field} \n' f'name: {search_result_field['name']} \n' f'score: {search_result_field['score']}\n' f'ids: {search_result_field['ids']}\n') logging.debug(f'action: INFO \n' f'field: {field} \n' f'name: {search_result_field['name']} \n' f'score: {search_result_field['score']}\n' f'ids: {search_result_field['ids']}\n') # curr_query[f'{field}_name'] = search_result_field['name'] # curr_query[f'{field}_score'] = search_result_field['score'] if len(ids) > 0: curr_query['ids'] = set.intersection(*ids) curr_query['results'] = len(curr_query['ids']) curr_query['skiped_dead_end_fields'] = skip_dead_end_fields results.append(curr_query) return results def output_data(self, intersections): results = [] for row in intersections: result = self.return_matched_rows(row['ids']) if 'results' in row: result['results_count'] = row['results'] if 'skiped_dead_end_fields' in row: result['skiped_dead_end_fields'] = row['skiped_dead_end_fields'] results.append(result) return results def __extract_result(self, row): return self.process_address(row.to_dict()) def process_df(self, df): return df.apply(self.__extract_result, axis=1, result_type="expand") def process_address(self, address_dict): matches = self.find_in_fields_by_step(address_dict) intersections = self.filter_by_field_intersection(matches) results = self.output_data(intersections) return results[0] def __to_dict_of_list__(self, dict_of_list): return [dict(zip(dict_of_list, t)) for t in zip(*dict_of_list.values())] def __to_list_of_dict__(self, list_of_dict): return {k: [dic[k] for dic in list_of_dict] for k in list_of_dict[0]} def __call__(self, input_data): if isinstance(input_data, pd.DataFrame): return self.process_df(input_data) elif isinstance(input_data, pd.Series): return self.process_address(input_data.to_dict()) else: return self.process_address(input_data)
import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity import pathlib import logging from copy import copy import numpy as np class Geomatch: def __init__(self, standard_db=False, # порядок колонок имеет значение т.к. определяет порядок фильтрации множеств match_columns=['region', 'settlement', 'municipality'], threshold=None, debug=False, skip_dead_end_fields=0, filter_by_prev=True ): self.current_directory = str(pathlib.Path(__file__).parent.resolve()) if type(standard_db) is pd.core.frame.DataFrame: self.standard = standard_db.reset_index(drop=True) elif type(standard_db) is str: self.standard = pd.read_csv(pathlib.Path(f'{standard_db}'), compression='zip') else: self.standard = pd.read_csv(pathlib.Path(f'{self.current_directory}/standard.zip'), compression='zip') self.standard = self.standard.fillna('') # здесь можно задать threshold срабатывания для полей если не задано то threshold = 0 if threshold is not None: self.threshold = threshold else: self.threshold = {} if debug: logging.basicConfig(filename='debug.log', format='%(asctime)s - %(levelname)s \n%(message)s', level=logging.DEBUG) self.skip_dead_end_fields = skip_dead_end_fields self.vectorizers = {} self.vectors = {} self.ids = {} self.keys = {} self.field_ids = {} self.filter_ids = None self.match_columns = match_columns # self.standard = self.standard # [self.match_columns] self.filter_by_prev = filter_by_prev # todo: протестировать другие варианты # инициализируем tfidf по каждой колонке for field in self.match_columns: self.ids[field] = self.standard.reset_index().groupby(field)['index'].apply(list).to_dict() self.keys[field] = list(self.ids[field].keys()) self.field_ids[field] = list(self.ids[field].values()) self.field_ids[field] = {value: k for k, v in enumerate(self.field_ids[field]) for value in self.field_ids[field][k]} self.vectorizers[field] = TfidfVectorizer(ngram_range=(1, 4), analyzer='char_wb') self.vectors[field] = self.vectorizers[field].fit_transform(self.keys[field]) # print(self.standard.groupby(field)['index'].apply(list).to_dict()) # print(len(self.ids[field])) def get_output(self, scores, field, top_n=1): out = [] if scores is None: out = [[{'name': '', 'score': 0, 'ids': set()}]] else: for score in scores: row = [] for i in (-score).argsort()[:top_n]: id = i if self.filter_ids: id = self.get_filter_ids(field)[i] curr_key = self.keys[field][id] ids = self.ids[field][curr_key] row.append({ 'id': id, 'name': curr_key, 'score': score[i], 'ids': set(ids) }) out.append(row) return out def get_filter_ids(self, field): return np.array(list({self.field_ids[field][i] for i in self.filter_ids})) def find_similar_records(self, data, field): vec = self.vectorizers[field].transform(data).toarray() vectors = self.vectors[field] if self.filter_ids: vectors = vectors[self.get_filter_ids(field), :] out = cosine_similarity( vec, vectors ) return out def return_matched_rows(self, ids, max_rows=1): if ids: selected_record = list(ids)[0] return dict(self.standard.iloc[selected_record]) else: return {i: '' for i in self.match_columns} def find_in_field(self, address_field, field, top_n=5): scores = None if address_field != '': scores = self.find_similar_records([address_field], field) return self.get_output(scores, field, top_n) def find_in_fields_by_step(self, address_dict): if type(address_dict) is list: address_dict = self.__to_list_of_dict__(address_dict) out = {} self.filter_ids = None for field in self.match_columns: if field in address_dict: out[field] = self.find_in_field(address_dict[field], field) if self.filter_by_prev: self.filter_ids = out[field][0][0]['ids'] return self.__to_dict_of_list__(out) def find_in_fields_by_intersection(self, address_dict): if type(address_dict) is list: address_dict = self.__to_list_of_dict__(address_dict) out = {} for field in self.match_columns: if field in address_dict: out[field] = self.find_in_field(address_dict[field], field) return self.__to_dict_of_list__(out) def check_threshold(self, field, score): if field in self.threshold: threshold = self.threshold[field] else: threshold = 0 return score > threshold def filter_by_field_intersection(self, search_results): results = [] for search_result in search_results: ids = [] skip_dead_end_fields = 0 curr_query = { 'ids': [] } for field in search_result: if self.check_threshold(field, search_result[field][0]['score']): test_ids = copy(ids) test_ids.append(search_result[field][0]['ids']) search_result_field = search_result[field][0] # здесь происходит проверка на тупиковые множества if len(set.intersection(*test_ids)) > 0 or self.skip_dead_end_fields <= skip_dead_end_fields: ids = test_ids else: skip_dead_end_fields += 1 logging.debug(f'action: SKIP_DEAD_END_FIELD \n' f'field: {field} \n' f'name: {search_result_field["name"]} \n' f'score: {search_result_field["score"]}\n' f'ids: {search_result_field["ids"]}\n') logging.debug(f'action: INFO \n' f'field: {field} \n' f'name: {search_result_field["name"]} \n' f'score: {search_result_field["score"]}\n' f'ids: {search_result_field["ids"]}\n') # curr_query[f'{field}_name'] = search_result_field['name'] # curr_query[f'{field}_score'] = search_result_field['score'] if len(ids) > 0: curr_query['ids'] = set.intersection(*ids) curr_query['results'] = len(curr_query['ids']) curr_query['skiped_dead_end_fields'] = skip_dead_end_fields results.append(curr_query) return results def output_data(self, intersections): results = [] for row in intersections: result = self.return_matched_rows(row['ids']) if 'results' in row: result['results_count'] = row['results'] if 'skiped_dead_end_fields' in row: result['skiped_dead_end_fields'] = row['skiped_dead_end_fields'] results.append(result) return results def __extract_result(self, row): return self.process_address(row.to_dict()) def process_df(self, df): return df.apply(self.__extract_result, axis=1, result_type="expand") def process_address(self, address_dict): matches = self.find_in_fields_by_step(address_dict) intersections = self.filter_by_field_intersection(matches) results = self.output_data(intersections) return results[0] def __to_dict_of_list__(self, dict_of_list): return [dict(zip(dict_of_list, t)) for t in zip(*dict_of_list.values())] def __to_list_of_dict__(self, list_of_dict): return {k: [dic[k] for dic in list_of_dict] for k in list_of_dict[0]} def __call__(self, input_data): if isinstance(input_data, pd.DataFrame): return self.process_df(input_data) elif isinstance(input_data, pd.Series): return self.process_address(input_data.to_dict()) else: return self.process_address(input_data)
import unittest import requests_mock from response_operations_social_ui import create_app from response_operations_social_ui.common import uaa class TestUaa(unittest.TestCase): def setUp(self): self.app = create_app('TestingConfig') def test_get_uaa_public_key_with_config_set(self): with self.app.app_context(): self.assertEqual("Test", uaa.get_uaa_public_key()) @requests_mock.mock() def test_get_uaa_public_key_with_no_config_set(self, mock_request): mock_request.get(f'{self.app.config['UAA_SERVICE_URL']}/token_key', json={'value': 'Test'}) self.app.config["UAA_PUBLIC_KEY"] = None with self.app.app_context(): self.assertEqual("Test", uaa.get_uaa_public_key()) @requests_mock.mock() def test_get_uaa_public_key_server_error_response(self, mock_request): mock_request.get(f'{self.app.config['UAA_SERVICE_URL']}/token_key', status_code=500) self.app.config["UAA_PUBLIC_KEY"] = None with self.app.app_context(), self.assertLogs('', 'ERROR') as logs: uaa.get_uaa_public_key() self.assertIn( f'Error during request to get public key from {self.app.config['UAA_SERVICE_URL']}/token_key', str(logs)) @requests_mock.mock() def test_get_uaa_public_key_no_value_key(self, mock_request): mock_request.get(f'{self.app.config['UAA_SERVICE_URL']}/token_key', json={'notvalue': 'text'}) self.app.config["UAA_PUBLIC_KEY"] = None with self.app.app_context(), self.assertLogs('', 'ERROR') as logs: uaa.get_uaa_public_key() self.assertIn( f'No public key returned by UAA {self.app.config['UAA_SERVICE_URL']}/token_key', str(logs))
import unittest import requests_mock from response_operations_social_ui import create_app from response_operations_social_ui.common import uaa class TestUaa(unittest.TestCase): def setUp(self): self.app = create_app('TestingConfig') def test_get_uaa_public_key_with_config_set(self): with self.app.app_context(): self.assertEqual("Test", uaa.get_uaa_public_key()) @requests_mock.mock() def test_get_uaa_public_key_with_no_config_set(self, mock_request): mock_request.get(f'{self.app.config["UAA_SERVICE_URL"]}/token_key', json={'value': 'Test'}) self.app.config["UAA_PUBLIC_KEY"] = None with self.app.app_context(): self.assertEqual("Test", uaa.get_uaa_public_key()) @requests_mock.mock() def test_get_uaa_public_key_server_error_response(self, mock_request): mock_request.get(f'{self.app.config["UAA_SERVICE_URL"]}/token_key', status_code=500) self.app.config["UAA_PUBLIC_KEY"] = None with self.app.app_context(), self.assertLogs('', 'ERROR') as logs: uaa.get_uaa_public_key() self.assertIn( f'Error during request to get public key from {self.app.config["UAA_SERVICE_URL"]}/token_key', str(logs)) @requests_mock.mock() def test_get_uaa_public_key_no_value_key(self, mock_request): mock_request.get(f'{self.app.config["UAA_SERVICE_URL"]}/token_key', json={'notvalue': 'text'}) self.app.config["UAA_PUBLIC_KEY"] = None with self.app.app_context(), self.assertLogs('', 'ERROR') as logs: uaa.get_uaa_public_key() self.assertIn( f'No public key returned by UAA {self.app.config["UAA_SERVICE_URL"]}/token_key', str(logs))
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.backend.codegen.protobuf.target_types import ( ProtobufDependenciesField, ProtobufGrpcToggleField, ) from pants.backend.codegen.utils import find_python_runtime_library_or_raise_error from pants.backend.python.dependency_inference.module_mapper import ThirdPartyPythonModuleMapping from pants.backend.python.goals import lockfile from pants.backend.python.goals.lockfile import GeneratePythonLockfile from pants.backend.python.subsystems.python_tool_base import PythonToolRequirementsBase from pants.backend.python.subsystems.setup import PythonSetup from pants.backend.python.target_types import PythonResolveField from pants.core.goals.generate_lockfiles import GenerateToolLockfileSentinel from pants.engine.addresses import Address from pants.engine.rules import Get, collect_rules, rule from pants.engine.target import InjectDependenciesRequest, InjectedDependencies, WrappedTarget from pants.engine.unions import UnionRule from pants.option.option_types import BoolOption from pants.option.subsystem import Subsystem from pants.util.docutil import doc_url, git_url class PythonProtobufSubsystem(Subsystem): options_scope = "python-protobuf" help = f"Options related to the Protobuf Python backend.\n\nSee {doc_url("protobuf")}." mypy_plugin = BoolOption( "--mypy-plugin", default=False, help=( "Use the `mypy-protobuf` plugin (https://github.com/dropbox/mypy-protobuf) to " "also generate .pyi type stubs." ), ) infer_runtime_dependency = BoolOption( "--infer-runtime-dependency", default=True, help=( "If True, will add a dependency on a `python_requirement` target exposing the " "`protobuf` module (usually from the `protobuf` requirement). If the `protobuf_source` " "target sets `grpc=True`, will also add a dependency on the `python_requirement` " "target exposing the `grpcio` module.\n\n" "If `[python].enable_resolves` is set, Pants will only infer dependencies on " "`python_requirement` targets that use the same resolve as the particular " "`protobuf_source` / `protobuf_sources` target uses, which is set via its " "`python_resolve` field.\n\n" "Unless this option is disabled, Pants will error if no relevant target is found or " "if more than one is found which causes ambiguity." ), advanced=True, ) class PythonProtobufMypyPlugin(PythonToolRequirementsBase): options_scope = "mypy-protobuf" help = "Configuration of the mypy-protobuf type stub generation plugin." default_version = "mypy-protobuf==2.10" register_interpreter_constraints = True default_interpreter_constraints = ["CPython>=3.7,<4"] register_lockfile = True default_lockfile_resource = ("pants.backend.codegen.protobuf.python", "mypy_protobuf.lock") default_lockfile_path = "src/python/pants/backend/codegen/protobuf/python/mypy_protobuf.lock" default_lockfile_url = git_url(default_lockfile_path) class MypyProtobufLockfileSentinel(GenerateToolLockfileSentinel): resolve_name = PythonProtobufMypyPlugin.options_scope @rule def setup_mypy_protobuf_lockfile( _: MypyProtobufLockfileSentinel, mypy_protobuf: PythonProtobufMypyPlugin, python_setup: PythonSetup, ) -> GeneratePythonLockfile: return GeneratePythonLockfile.from_tool( mypy_protobuf, use_pex=python_setup.generate_lockfiles_with_pex ) class InjectPythonProtobufDependencies(InjectDependenciesRequest): inject_for = ProtobufDependenciesField @rule async def inject_dependencies( request: InjectPythonProtobufDependencies, python_protobuf: PythonProtobufSubsystem, python_setup: PythonSetup, # TODO(#12946): Make this a lazy Get once possible. module_mapping: ThirdPartyPythonModuleMapping, ) -> InjectedDependencies: if not python_protobuf.infer_runtime_dependency: return InjectedDependencies() wrapped_tgt = await Get(WrappedTarget, Address, request.dependencies_field.address) tgt = wrapped_tgt.target resolve = tgt.get(PythonResolveField).normalized_value(python_setup) result = [ find_python_runtime_library_or_raise_error( module_mapping, request.dependencies_field.address, "google.protobuf", resolve=resolve, resolves_enabled=python_setup.enable_resolves, recommended_requirement_name="protobuf", recommended_requirement_url="https://pypi.org/project/protobuf/", disable_inference_option=f"[{python_protobuf.options_scope}].infer_runtime_dependency", ) ] if wrapped_tgt.target.get(ProtobufGrpcToggleField).value: result.append( find_python_runtime_library_or_raise_error( module_mapping, request.dependencies_field.address, # Note that the library is called `grpcio`, but the module is `grpc`. "grpc", resolve=resolve, resolves_enabled=python_setup.enable_resolves, recommended_requirement_name="grpcio", recommended_requirement_url="https://pypi.org/project/grpcio/", disable_inference_option=f"[{python_protobuf.options_scope}].infer_runtime_dependency", ) ) return InjectedDependencies(result) def rules(): return [ *collect_rules(), *lockfile.rules(), UnionRule(InjectDependenciesRequest, InjectPythonProtobufDependencies), UnionRule(GenerateToolLockfileSentinel, MypyProtobufLockfileSentinel), ]
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.backend.codegen.protobuf.target_types import ( ProtobufDependenciesField, ProtobufGrpcToggleField, ) from pants.backend.codegen.utils import find_python_runtime_library_or_raise_error from pants.backend.python.dependency_inference.module_mapper import ThirdPartyPythonModuleMapping from pants.backend.python.goals import lockfile from pants.backend.python.goals.lockfile import GeneratePythonLockfile from pants.backend.python.subsystems.python_tool_base import PythonToolRequirementsBase from pants.backend.python.subsystems.setup import PythonSetup from pants.backend.python.target_types import PythonResolveField from pants.core.goals.generate_lockfiles import GenerateToolLockfileSentinel from pants.engine.addresses import Address from pants.engine.rules import Get, collect_rules, rule from pants.engine.target import InjectDependenciesRequest, InjectedDependencies, WrappedTarget from pants.engine.unions import UnionRule from pants.option.option_types import BoolOption from pants.option.subsystem import Subsystem from pants.util.docutil import doc_url, git_url class PythonProtobufSubsystem(Subsystem): options_scope = "python-protobuf" help = f"Options related to the Protobuf Python backend.\n\nSee {doc_url('protobuf')}." mypy_plugin = BoolOption( "--mypy-plugin", default=False, help=( "Use the `mypy-protobuf` plugin (https://github.com/dropbox/mypy-protobuf) to " "also generate .pyi type stubs." ), ) infer_runtime_dependency = BoolOption( "--infer-runtime-dependency", default=True, help=( "If True, will add a dependency on a `python_requirement` target exposing the " "`protobuf` module (usually from the `protobuf` requirement). If the `protobuf_source` " "target sets `grpc=True`, will also add a dependency on the `python_requirement` " "target exposing the `grpcio` module.\n\n" "If `[python].enable_resolves` is set, Pants will only infer dependencies on " "`python_requirement` targets that use the same resolve as the particular " "`protobuf_source` / `protobuf_sources` target uses, which is set via its " "`python_resolve` field.\n\n" "Unless this option is disabled, Pants will error if no relevant target is found or " "if more than one is found which causes ambiguity." ), advanced=True, ) class PythonProtobufMypyPlugin(PythonToolRequirementsBase): options_scope = "mypy-protobuf" help = "Configuration of the mypy-protobuf type stub generation plugin." default_version = "mypy-protobuf==2.10" register_interpreter_constraints = True default_interpreter_constraints = ["CPython>=3.7,<4"] register_lockfile = True default_lockfile_resource = ("pants.backend.codegen.protobuf.python", "mypy_protobuf.lock") default_lockfile_path = "src/python/pants/backend/codegen/protobuf/python/mypy_protobuf.lock" default_lockfile_url = git_url(default_lockfile_path) class MypyProtobufLockfileSentinel(GenerateToolLockfileSentinel): resolve_name = PythonProtobufMypyPlugin.options_scope @rule def setup_mypy_protobuf_lockfile( _: MypyProtobufLockfileSentinel, mypy_protobuf: PythonProtobufMypyPlugin, python_setup: PythonSetup, ) -> GeneratePythonLockfile: return GeneratePythonLockfile.from_tool( mypy_protobuf, use_pex=python_setup.generate_lockfiles_with_pex ) class InjectPythonProtobufDependencies(InjectDependenciesRequest): inject_for = ProtobufDependenciesField @rule async def inject_dependencies( request: InjectPythonProtobufDependencies, python_protobuf: PythonProtobufSubsystem, python_setup: PythonSetup, # TODO(#12946): Make this a lazy Get once possible. module_mapping: ThirdPartyPythonModuleMapping, ) -> InjectedDependencies: if not python_protobuf.infer_runtime_dependency: return InjectedDependencies() wrapped_tgt = await Get(WrappedTarget, Address, request.dependencies_field.address) tgt = wrapped_tgt.target resolve = tgt.get(PythonResolveField).normalized_value(python_setup) result = [ find_python_runtime_library_or_raise_error( module_mapping, request.dependencies_field.address, "google.protobuf", resolve=resolve, resolves_enabled=python_setup.enable_resolves, recommended_requirement_name="protobuf", recommended_requirement_url="https://pypi.org/project/protobuf/", disable_inference_option=f"[{python_protobuf.options_scope}].infer_runtime_dependency", ) ] if wrapped_tgt.target.get(ProtobufGrpcToggleField).value: result.append( find_python_runtime_library_or_raise_error( module_mapping, request.dependencies_field.address, # Note that the library is called `grpcio`, but the module is `grpc`. "grpc", resolve=resolve, resolves_enabled=python_setup.enable_resolves, recommended_requirement_name="grpcio", recommended_requirement_url="https://pypi.org/project/grpcio/", disable_inference_option=f"[{python_protobuf.options_scope}].infer_runtime_dependency", ) ) return InjectedDependencies(result) def rules(): return [ *collect_rules(), *lockfile.rules(), UnionRule(InjectDependenciesRequest, InjectPythonProtobufDependencies), UnionRule(GenerateToolLockfileSentinel, MypyProtobufLockfileSentinel), ]
import numpy as np import pytest from eelbrain import Dataset, Factor from eelbrain._design import permute, random_factor, complement def test_random_factor(): """Test the design module for creating an experiemnt design""" ds = permute(( ('A', '123456'), ('Bin', '01'), ('B', 'abcdef'), )) n = ds.n_cases rand = random_factor(('1', '2', '3'), n, 'rand') nv = (rand == '1').sum() assert nv == (rand == '2').sum(), "overall balancing" assert nv == (rand == '3').sum(), "overall balancing" # test urn kwarg randu = random_factor(('1', '2', '3'), n, urn=[rand]) assert (rand == randu).sum() == 0, "`urn` arg failed" nv = (randu == '1').sum() assert nv == 24, "random value assignment" assert nv == (randu == '2').sum(), "overall balancing" assert nv == (randu == '3').sum(), "overall balancing" # test sub kwarg sub = ds['Bin'] == '1' subrand = random_factor(('1', '2', '3'), n, urn=[rand], sub=sub) assert np.all(rand != randu), "`urn` arg failed with `sub` arg" subc = (sub == False) assert np.all(subrand[subc] == ''), "values outside of sub are not ''" nv = (subrand == '1').sum() assert nv == 12, "random value assignment with `sub` arg" assert nv == (subrand == '2').sum(), "sub balancing" assert nv == (subrand == '3').sum(), "sub balancing" def test_complement(): """Test design.complement()""" ds = Dataset() ds['A'] = Factor('abcabc') ds['B'] = Factor('bcabca') ds['C'] = Factor('cabcab') # underspecified with pytest.raises(ValueError): complement(['A'], ds=ds) # correct comp = complement(['A', 'B'], ds=ds) assert np.all(comp == ds['C']), f"Complement yielded {comp} instead of {ds["C"]}" # overspecified with pytest.raises(ValueError): complement(['A', 'B', 'C'], ds=ds)
import numpy as np import pytest from eelbrain import Dataset, Factor from eelbrain._design import permute, random_factor, complement def test_random_factor(): """Test the design module for creating an experiemnt design""" ds = permute(( ('A', '123456'), ('Bin', '01'), ('B', 'abcdef'), )) n = ds.n_cases rand = random_factor(('1', '2', '3'), n, 'rand') nv = (rand == '1').sum() assert nv == (rand == '2').sum(), "overall balancing" assert nv == (rand == '3').sum(), "overall balancing" # test urn kwarg randu = random_factor(('1', '2', '3'), n, urn=[rand]) assert (rand == randu).sum() == 0, "`urn` arg failed" nv = (randu == '1').sum() assert nv == 24, "random value assignment" assert nv == (randu == '2').sum(), "overall balancing" assert nv == (randu == '3').sum(), "overall balancing" # test sub kwarg sub = ds['Bin'] == '1' subrand = random_factor(('1', '2', '3'), n, urn=[rand], sub=sub) assert np.all(rand != randu), "`urn` arg failed with `sub` arg" subc = (sub == False) assert np.all(subrand[subc] == ''), "values outside of sub are not ''" nv = (subrand == '1').sum() assert nv == 12, "random value assignment with `sub` arg" assert nv == (subrand == '2').sum(), "sub balancing" assert nv == (subrand == '3').sum(), "sub balancing" def test_complement(): """Test design.complement()""" ds = Dataset() ds['A'] = Factor('abcabc') ds['B'] = Factor('bcabca') ds['C'] = Factor('cabcab') # underspecified with pytest.raises(ValueError): complement(['A'], ds=ds) # correct comp = complement(['A', 'B'], ds=ds) assert np.all(comp == ds['C']), f"Complement yielded {comp} instead of {ds['C']}" # overspecified with pytest.raises(ValueError): complement(['A', 'B', 'C'], ds=ds)
import datetime import numpy as np import modin.pandas as pd import pytest from sklearn.exceptions import NotFittedError from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error from testfixtures import LogCapture import greykite.common.constants as cst from greykite.algo.forecast.silverkite.forecast_silverkite import SilverkiteForecast from greykite.common.data_loader import DataLoader from greykite.common.features.timeseries_features import convert_date_to_continuous_time from greykite.common.python_utils import assert_equal from greykite.common.testing_utils import daily_data_reg from greykite.common.testing_utils import generate_df_for_tests from greykite.common.testing_utils import generate_df_with_reg_for_tests from greykite.sklearn.estimator.base_silverkite_estimator import BaseSilverkiteEstimator from greykite.sklearn.estimator.testing_utils import params_components @pytest.fixture def params(): autoreg_dict = { "lag_dict": {"orders": [7]}, "agg_lag_dict": { "orders_list": [[7, 7 * 2, 7 * 3]], "interval_list": [(7, 7 * 2)]}, "series_na_fill_func": lambda s: s.bfill().ffill()} uncertainty_dict = { "uncertainty_method": "simple_conditional_residuals", "params": { "conditional_cols": ["dow"], "quantiles": [0.025, 0.975], "quantile_estimation_method": "normal_fit", "sample_size_thresh": 5, "small_sample_size_method": "std_quantiles", "small_sample_size_quantile": 0.98}} return { "origin_for_time_vars": convert_date_to_continuous_time(datetime.datetime(2018, 1, 3)), "extra_pred_cols": ["ct1", "regressor1", "regressor2"], "train_test_thresh": None, "training_fraction": None, "fit_algorithm": "sgd", "fit_algorithm_params": {"alpha": 0.1}, "daily_event_df_dict": None, "changepoints_dict": None, "fs_components_df": pd.DataFrame({ "name": ["tow"], "period": [7.0], "order": [3], "seas_names": [None]}), "autoreg_dict": autoreg_dict, "min_admissible_value": None, "max_admissible_value": None, "uncertainty_dict": uncertainty_dict } @pytest.fixture def daily_data(): return generate_df_for_tests( freq="D", periods=1000, train_start_date=datetime.datetime(2018, 1, 1), conti_year_origin=2018) @pytest.fixture def daily_data_with_reg(): return daily_data_reg() @pytest.fixture def X(): periods = 11 return pd.DataFrame({ cst.TIME_COL: pd.date_range("2018-01-01", periods=periods, freq="D"), cst.VALUE_COL: np.arange(1, periods + 1) }) @pytest.fixture def df_pt(): """fetches the Peyton Manning pageview data""" dl = DataLoader() return dl.load_peyton_manning() def test_init(params): """Checks if parameters are passed to BaseSilverkiteEstimator correctly""" coverage = 0.95 uncertainty_dict = { "uncertainty_method": "simple_conditional_residuals", "params": { "conditional_cols": ["dow"], "quantiles": [0.025, 0.975], "quantile_estimation_method": "normal_fit", "sample_size_thresh": 5, "small_sample_size_method": "std_quantiles", "small_sample_size_quantile": 0.98}} model = BaseSilverkiteEstimator( score_func=mean_squared_error, coverage=coverage, null_model_params=None, uncertainty_dict=uncertainty_dict) assert model.score_func == mean_squared_error assert model.coverage == coverage assert model.null_model_params is None assert model.uncertainty_dict == uncertainty_dict assert model.model_dict is None assert model.pred_cols is None assert model.feature_cols is None assert model.df is None assert model.coef_ is None def test_null_model(X): """Checks null model""" model = BaseSilverkiteEstimator(null_model_params={ "strategy": "quantile", "constant": None, "quantile": 0.8}) model.fit(X) y = np.repeat(2.0, X.shape[0]) null_score = model.null_model.score(X, y=y) assert null_score == mean_squared_error(y, np.repeat(9.0, X.shape[0])) # tests if different score function gets propagated to null model model = BaseSilverkiteEstimator( score_func=mean_absolute_error, null_model_params={"strategy": "quantile", "constant": None, "quantile": 0.8}) model.fit(X) y = np.repeat(2.0, X.shape[0]) null_score = model.null_model.score(X, y=y) assert null_score == mean_absolute_error(y, np.repeat(9.0, X.shape[0])) # checks that `df` is set assert_equal(X, model.df) def test_fit_predict(daily_data): """Checks fit and predict function with null model""" model = BaseSilverkiteEstimator(null_model_params={"strategy": "mean"}) train_df = daily_data["train_df"] test_df = daily_data["test_df"] assert model.last_predicted_X_ is None assert model.cached_predictions_ is None with pytest.raises( NotFittedError, match="Call `fit` before calling `predict`."): model.predict(train_df) # Every subclass `fit` follows these steps model.fit( train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) # Checks that `df` is set, but other variables aren't assert_equal(model.df, train_df) assert model.pred_cols is None assert model.feature_cols is None assert model.coef_ is None with pytest.raises(ValueError, match="Must set `self.model_dict` before calling this function."): model.finish_fit() silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL, origin_for_time_vars=None, extra_pred_cols=None, train_test_thresh=None, training_fraction=None, fit_algorithm="linear", fit_algorithm_params=None, daily_event_df_dict=None, changepoints_dict=None, fs_components_df=pd.DataFrame({ "name": ["tod", "tow", "conti_year"], "period": [24.0, 7.0, 1.0], "order": [3, 3, 5], "seas_names": ["daily", "weekly", "yearly"]}), autoreg_dict=None, min_admissible_value=None, max_admissible_value=None, uncertainty_dict=None ) with pytest.raises( NotFittedError, match="Subclass must call `finish_fit` inside the `fit` method."): model.predict(train_df) assert model.last_predicted_X_ is not None # attempted prediction assert model.cached_predictions_ is None model.finish_fit() # Checks that other variables are set assert_equal(model.pred_cols, model.model_dict["pred_cols"]) assert_equal(model.feature_cols, model.model_dict["x_mat"].columns) assert_equal(model.coef_, pd.DataFrame( model.model_dict["ml_model"].coef_, index=model.feature_cols)) # Predicts on a new dataset with LogCapture(cst.LOGGER_NAME) as log_capture: predicted = model.predict(test_df) assert_equal(model.last_predicted_X_, test_df) assert_equal(model.cached_predictions_, predicted) log_capture.check() # no log messages (not using cached predictions) # Uses cached predictions with LogCapture(cst.LOGGER_NAME) as log_capture: assert_equal(model.predict(test_df), predicted) log_capture.check( (cst.LOGGER_NAME, "DEBUG", "Returning cached predictions.") ) # Predicts on a different dataset with LogCapture(cst.LOGGER_NAME) as log_capture: predicted = model.predict(train_df) assert_equal(model.last_predicted_X_, train_df) assert_equal(model.cached_predictions_, predicted) log_capture.check() # no log messages (not using cached predictions) # .fit() clears the cached result model.fit(train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) assert model.last_predicted_X_ is None assert model.cached_predictions_ is None def test_score_function(daily_data_with_reg): """Checks score function without null model, with regressors""" model = BaseSilverkiteEstimator() train_df = daily_data_with_reg["train_df"] test_df = daily_data_with_reg["test_df"] # every subclass `fit` follows these steps model.fit( X=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL, origin_for_time_vars=None, extra_pred_cols=["ct1", "regressor1", "regressor2"], train_test_thresh=None, training_fraction=None, fit_algorithm="linear", fit_algorithm_params=None, daily_event_df_dict=None, changepoints_dict=None, fs_components_df=pd.DataFrame({ "name": ["tod", "tow", "conti_year"], "period": [24.0, 7.0, 1.0], "order": [3, 3, 5], "seas_names": ["daily", "weekly", "yearly"]}), autoreg_dict=None, min_admissible_value=None, max_admissible_value=None, uncertainty_dict=None ) model.finish_fit() score = model.score(test_df, test_df[cst.VALUE_COL]) pred_df = model.predict(test_df) assert list(pred_df.columns) == [cst.TIME_COL, cst.PREDICTED_COL] assert score == pytest.approx(mean_squared_error( pred_df[cst.PREDICTED_COL], test_df[cst.VALUE_COL])) assert score == pytest.approx(4.6, rel=1e-1) def test_set_uncertainty_dict(daily_data): """Tests __set_uncertainty_dict""" train_df = daily_data["train_df"] # both provided coverage = 0.95 uncertainty_dict = { "uncertainty_method": "simple_conditional_residuals", "params": { "conditional_cols": ["dow_hr"], "quantiles": [0.025, 0.975], "quantile_estimation_method": "normal_fit", "sample_size_thresh": 20, "small_sample_size_method": "std_quantiles", "small_sample_size_quantile": 0.98}} model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=uncertainty_dict) model.fit(train_df) expected_dict = uncertainty_dict assert_equal(model.uncertainty_dict, expected_dict) assert_equal(model.coverage, coverage) # only coverage provided coverage = 0.90 uncertainty_dict = None model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=uncertainty_dict) model.fit(train_df) expected_dict = { "uncertainty_method": "simple_conditional_residuals", "params": { "conditional_cols": ["dow_hr"], "quantiles": [0.05, 0.95], "quantile_estimation_method": "normal_fit", "sample_size_thresh": 5, "small_sample_size_method": "std_quantiles", "small_sample_size_quantile": 0.98}} assert_equal(model.uncertainty_dict, expected_dict) assert_equal(model.coverage, coverage) # both missing coverage = None uncertainty_dict = None model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=uncertainty_dict) model.fit(train_df) expected_dict = None assert_equal(model.uncertainty_dict, expected_dict) assert_equal(model.coverage, None) # only uncertainty provided coverage = None uncertainty_dict = { "uncertainty_method": "simple_conditional_residuals", "params": { "conditional_cols": ["dow_hr"], "quantiles": [0.05, 0.95], "quantile_estimation_method": "normal_fit", "sample_size_thresh": 5, "small_sample_size_method": "std_quantiles", "small_sample_size_quantile": 0.98}} model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=uncertainty_dict) model.fit(train_df) expected_dict = uncertainty_dict assert_equal(model.uncertainty_dict, expected_dict) assert_equal(model.coverage, 0.90) def test_summary(daily_data): """Checks summary function returns without error""" model = BaseSilverkiteEstimator() train_df = daily_data["train_df"] model.summary() model.fit( train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) model.summary() def test_silverkite_with_components_daily_data(): """Tests get_components, plot_components, plot_trend, plot_seasonalities with daily data and missing input values. """ daily_data = generate_df_with_reg_for_tests( freq="D", periods=20, train_start_date=datetime.datetime(2018, 1, 1), conti_year_origin=2018) train_df = daily_data["train_df"].copy() train_df.loc[[2, 4, 7], cst.VALUE_COL] = np.nan # creates missing values params_daily = params_components() # SilverkiteEstimator parameters # converts into parameters for `forecast_silverkite` coverage = params_daily.pop("coverage") # removes daily seasonality terms params_daily["fs_components_df"] = pd.DataFrame({ "name": ["tow", "ct1"], "period": [7.0, 1.0], "order": [4, 5], "seas_names": ["weekly", "yearly"]}) model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=params_daily["uncertainty_dict"]) with pytest.raises( NotFittedError, match="Call `fit` before calling `plot_components`."): model.plot_components() with pytest.warns(Warning): # suppress warnings from conf_interval.py and sklearn # a subclass's fit() method will have these steps model.fit( X=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL, **params_daily) model.finish_fit() # Tests plot_components with pytest.warns(Warning) as record: title = "Custom component plot" model._set_silverkite_diagnostics_params() fig = model.plot_components(names=["trend", "YEARLY_SEASONALITY", "DUMMY"], title=title) expected_rows = 3 assert len(fig.data) == expected_rows + 1 # includes changepoints assert [fig.data[i].name for i in range(expected_rows)] == \ [cst.VALUE_COL, "trend", "YEARLY_SEASONALITY"] assert fig.layout.xaxis.title["text"] == cst.TIME_COL assert fig.layout.xaxis2.title["text"] == cst.TIME_COL assert fig.layout.xaxis3.title["text"] == "Time of year" assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.yaxis2.title["text"] == "trend" assert fig.layout.yaxis3.title["text"] == "yearly" assert fig.layout.title["text"] == title assert f"The following components have not been specified in the model: " \ f"{{"DUMMY"}}, plotting the rest." in record[0].message.args[0] # Missing component error with pytest.raises( ValueError, match="None of the provided components have been specified in the model."): model.plot_components(names=["DUMMY"]) # Tests plot_trend title = "Custom trend plot" fig = model.plot_trend(title=title) expected_rows = 2 assert len(fig.data) == expected_rows + 1 # includes changepoints assert [fig.data[i].name for i in range(expected_rows)] == [cst.VALUE_COL, "trend"] assert fig.layout.xaxis.title["text"] == cst.TIME_COL assert fig.layout.xaxis2.title["text"] == cst.TIME_COL assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.yaxis2.title["text"] == "trend" assert fig.layout.title["text"] == title # Tests plot_seasonalities with pytest.warns(Warning): # suppresses the warning on seasonalities removed title = "Custom seasonality plot" fig = model.plot_seasonalities(title=title) expected_rows = 3 assert len(fig.data) == expected_rows assert [fig.data[i].name for i in range(expected_rows)] == \ [cst.VALUE_COL, "WEEKLY_SEASONALITY", "YEARLY_SEASONALITY"] assert fig.layout.xaxis.title["text"] == cst.TIME_COL assert fig.layout.xaxis2.title["text"] == "Day of week" assert fig.layout.xaxis3.title["text"] == "Time of year" assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.yaxis2.title["text"] == "weekly" assert fig.layout.yaxis3.title["text"] == "yearly" assert fig.layout.title["text"] == title # Component plot error if `fit_algorithm` is "rf" or "gradient_boosting" params_daily["fit_algorithm"] = "rf" model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=params_daily["uncertainty_dict"]) with pytest.warns(Warning): # suppress warnings from conf_interval.py and sklearn # a subclass's fit() method will have these steps model.fit( X=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) model.model_dict = silverkite.forecast( df=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL, **params_daily) model.finish_fit() assert model.coef_ is None with pytest.raises( NotImplementedError, match="Component plot has only been implemented for additive linear models."): model.plot_components() with pytest.raises( NotImplementedError, match="Component plot has only been implemented for additive linear models."): model.plot_trend() with pytest.raises( NotImplementedError, match="Component plot has only been implemented for additive linear models."): model.plot_seasonalities() def test_silverkite_with_components_hourly_data(): """Tests get_components, plot_components, plot_trend, plot_seasonalities with hourly data """ hourly_data = generate_df_with_reg_for_tests( freq="H", periods=24 * 4, train_start_date=datetime.datetime(2018, 1, 1), conti_year_origin=2018) train_df = hourly_data.get("train_df").copy() params_hourly = params_components() # converts into parameters for `forecast_silverkite` coverage = params_hourly.pop("coverage") model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=params_hourly["uncertainty_dict"]) model.fit( X=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL, **params_hourly) model.finish_fit() # Test plot_components with pytest.warns(Warning) as record: title = "Custom component plot" fig = model.plot_components(names=["trend", "DAILY_SEASONALITY", "DUMMY"], title=title) expected_rows = 3 + 1 # includes changepoints assert len(fig.data) == expected_rows assert [fig.data[i].name for i in range(expected_rows)] == \ [cst.VALUE_COL, "trend", "DAILY_SEASONALITY", "trend change point"] assert fig.layout.xaxis.title["text"] == cst.TIME_COL assert fig.layout.xaxis2.title["text"] == cst.TIME_COL assert fig.layout.xaxis3.title["text"] == "Hour of day" assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.yaxis2.title["text"] == "trend" assert fig.layout.yaxis3.title["text"] == "daily" assert fig.layout.title["text"] == title assert f"The following components have not been specified in the model: " \ f"{{"DUMMY"}}, plotting the rest." in record[0].message.args[0] # Test plot_trend title = "Custom trend plot" fig = model.plot_trend(title=title) expected_rows = 2 assert len(fig.data) == expected_rows + 1 # includes changepoints assert [fig.data[i].name for i in range(expected_rows)] == [cst.VALUE_COL, "trend"] assert fig.layout.xaxis.title["text"] == cst.TIME_COL assert fig.layout.xaxis2.title["text"] == cst.TIME_COL assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.yaxis2.title["text"] == "trend" assert fig.layout.title["text"] == title # Test plot_seasonalities with pytest.warns(Warning): # suppresses the warning on seasonalities removed title = "Custom seasonality plot" fig = model.plot_seasonalities(title=title) expected_rows = 4 assert len(fig.data) == expected_rows assert [fig.data[i].name for i in range(expected_rows)] == \ [cst.VALUE_COL, "DAILY_SEASONALITY", "WEEKLY_SEASONALITY", "YEARLY_SEASONALITY"] assert fig.layout.xaxis.title["text"] == cst.TIME_COL assert fig.layout.xaxis2.title["text"] == "Hour of day" assert fig.layout.xaxis3.title["text"] == "Day of week" assert fig.layout.xaxis4.title["text"] == "Time of year" assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.yaxis2.title["text"] == "daily" assert fig.layout.yaxis3.title["text"] == "weekly" assert fig.layout.yaxis4.title["text"] == "yearly" assert fig.layout.title["text"] == title def test_plot_trend_changepoint_detection(df_pt): model = BaseSilverkiteEstimator() model.fit( X=df_pt, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) params = { "changepoints_dict": {"method": "auto"}} silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=df_pt, time_col=cst.TIME_COL, value_col=cst.VALUE_COL, **params) model.finish_fit() fig = model.plot_trend_changepoint_detection() assert fig is not None assert fig.layout.title["text"] == "Timeseries Plot with detected trend change points" assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.xaxis.title["text"] == "Dates" # tests given parameters fig = model.plot_trend_changepoint_detection( dict(trend_change=False)) assert fig is not None assert fig.layout.title["text"] == "Timeseries Plot" assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.xaxis.title["text"] == "Dates" def test_model_summary(df_pt): model = BaseSilverkiteEstimator() model.fit( X=df_pt.iloc[:100], # speeds up time_col=cst.TIME_COL, value_col=cst.VALUE_COL) params = { "fit_algorithm": "linear", "training_fraction": 0.8} silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=df_pt.iloc[:100], time_col=cst.TIME_COL, value_col=cst.VALUE_COL, **params) model.finish_fit() summary = model.summary() summary.__str__() summary.__repr__() assert summary is not None def test_pred_category(df_pt): model = BaseSilverkiteEstimator() # property is not available without fitting. with pytest.raises( NotFittedError, match="Must fit before getting predictor category."): print(model.pred_category) model.fit( X=df_pt.iloc[:100], # speeds up time_col=cst.TIME_COL, value_col=cst.VALUE_COL) params = { "fit_algorithm": "linear", "training_fraction": 0.8, "extra_pred_cols": ["ct1", "x", "x:ct1"]} df_pt["x"] = np.random.randn(df_pt.shape[0]) silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=df_pt.iloc[:100], time_col=cst.TIME_COL, value_col=cst.VALUE_COL, **params) model.extra_pred_cols = ["ct1", "x", "x:ct1"] # set in subclass initialization # _pred_category is None before trying to access pred_category assert model._pred_category is None model.finish_fit() pred_category = model.pred_category # _pred_category is updated after trying to access pred_category assert model._pred_category is not None assert pred_category["intercept"] == ["Intercept"] assert pred_category["time_features"] == ["ct1", "x:ct1"] assert pred_category["event_features"] == [] assert pred_category["trend_features"] == ["ct1", "x:ct1"] assert pred_category["seasonality_features"] == ["sin1_tod_daily", "cos1_tod_daily", "sin2_tod_daily", "cos2_tod_daily", "sin3_tod_daily", "cos3_tod_daily", "sin1_tow_weekly", "cos1_tow_weekly", "sin2_tow_weekly", "cos2_tow_weekly", "sin3_tow_weekly", "cos3_tow_weekly", "sin1_toy_yearly", "cos1_toy_yearly", "sin2_toy_yearly", "cos2_toy_yearly", "sin3_toy_yearly", "cos3_toy_yearly", "sin4_toy_yearly", "cos4_toy_yearly", "sin5_toy_yearly", "cos5_toy_yearly"] assert pred_category["lag_features"] == [] assert pred_category["regressor_features"] == ["x", "x:ct1"] assert pred_category["interaction_features"] == ["x:ct1"]
import datetime import numpy as np import modin.pandas as pd import pytest from sklearn.exceptions import NotFittedError from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error from testfixtures import LogCapture import greykite.common.constants as cst from greykite.algo.forecast.silverkite.forecast_silverkite import SilverkiteForecast from greykite.common.data_loader import DataLoader from greykite.common.features.timeseries_features import convert_date_to_continuous_time from greykite.common.python_utils import assert_equal from greykite.common.testing_utils import daily_data_reg from greykite.common.testing_utils import generate_df_for_tests from greykite.common.testing_utils import generate_df_with_reg_for_tests from greykite.sklearn.estimator.base_silverkite_estimator import BaseSilverkiteEstimator from greykite.sklearn.estimator.testing_utils import params_components @pytest.fixture def params(): autoreg_dict = { "lag_dict": {"orders": [7]}, "agg_lag_dict": { "orders_list": [[7, 7 * 2, 7 * 3]], "interval_list": [(7, 7 * 2)]}, "series_na_fill_func": lambda s: s.bfill().ffill()} uncertainty_dict = { "uncertainty_method": "simple_conditional_residuals", "params": { "conditional_cols": ["dow"], "quantiles": [0.025, 0.975], "quantile_estimation_method": "normal_fit", "sample_size_thresh": 5, "small_sample_size_method": "std_quantiles", "small_sample_size_quantile": 0.98}} return { "origin_for_time_vars": convert_date_to_continuous_time(datetime.datetime(2018, 1, 3)), "extra_pred_cols": ["ct1", "regressor1", "regressor2"], "train_test_thresh": None, "training_fraction": None, "fit_algorithm": "sgd", "fit_algorithm_params": {"alpha": 0.1}, "daily_event_df_dict": None, "changepoints_dict": None, "fs_components_df": pd.DataFrame({ "name": ["tow"], "period": [7.0], "order": [3], "seas_names": [None]}), "autoreg_dict": autoreg_dict, "min_admissible_value": None, "max_admissible_value": None, "uncertainty_dict": uncertainty_dict } @pytest.fixture def daily_data(): return generate_df_for_tests( freq="D", periods=1000, train_start_date=datetime.datetime(2018, 1, 1), conti_year_origin=2018) @pytest.fixture def daily_data_with_reg(): return daily_data_reg() @pytest.fixture def X(): periods = 11 return pd.DataFrame({ cst.TIME_COL: pd.date_range("2018-01-01", periods=periods, freq="D"), cst.VALUE_COL: np.arange(1, periods + 1) }) @pytest.fixture def df_pt(): """fetches the Peyton Manning pageview data""" dl = DataLoader() return dl.load_peyton_manning() def test_init(params): """Checks if parameters are passed to BaseSilverkiteEstimator correctly""" coverage = 0.95 uncertainty_dict = { "uncertainty_method": "simple_conditional_residuals", "params": { "conditional_cols": ["dow"], "quantiles": [0.025, 0.975], "quantile_estimation_method": "normal_fit", "sample_size_thresh": 5, "small_sample_size_method": "std_quantiles", "small_sample_size_quantile": 0.98}} model = BaseSilverkiteEstimator( score_func=mean_squared_error, coverage=coverage, null_model_params=None, uncertainty_dict=uncertainty_dict) assert model.score_func == mean_squared_error assert model.coverage == coverage assert model.null_model_params is None assert model.uncertainty_dict == uncertainty_dict assert model.model_dict is None assert model.pred_cols is None assert model.feature_cols is None assert model.df is None assert model.coef_ is None def test_null_model(X): """Checks null model""" model = BaseSilverkiteEstimator(null_model_params={ "strategy": "quantile", "constant": None, "quantile": 0.8}) model.fit(X) y = np.repeat(2.0, X.shape[0]) null_score = model.null_model.score(X, y=y) assert null_score == mean_squared_error(y, np.repeat(9.0, X.shape[0])) # tests if different score function gets propagated to null model model = BaseSilverkiteEstimator( score_func=mean_absolute_error, null_model_params={"strategy": "quantile", "constant": None, "quantile": 0.8}) model.fit(X) y = np.repeat(2.0, X.shape[0]) null_score = model.null_model.score(X, y=y) assert null_score == mean_absolute_error(y, np.repeat(9.0, X.shape[0])) # checks that `df` is set assert_equal(X, model.df) def test_fit_predict(daily_data): """Checks fit and predict function with null model""" model = BaseSilverkiteEstimator(null_model_params={"strategy": "mean"}) train_df = daily_data["train_df"] test_df = daily_data["test_df"] assert model.last_predicted_X_ is None assert model.cached_predictions_ is None with pytest.raises( NotFittedError, match="Call `fit` before calling `predict`."): model.predict(train_df) # Every subclass `fit` follows these steps model.fit( train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) # Checks that `df` is set, but other variables aren't assert_equal(model.df, train_df) assert model.pred_cols is None assert model.feature_cols is None assert model.coef_ is None with pytest.raises(ValueError, match="Must set `self.model_dict` before calling this function."): model.finish_fit() silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL, origin_for_time_vars=None, extra_pred_cols=None, train_test_thresh=None, training_fraction=None, fit_algorithm="linear", fit_algorithm_params=None, daily_event_df_dict=None, changepoints_dict=None, fs_components_df=pd.DataFrame({ "name": ["tod", "tow", "conti_year"], "period": [24.0, 7.0, 1.0], "order": [3, 3, 5], "seas_names": ["daily", "weekly", "yearly"]}), autoreg_dict=None, min_admissible_value=None, max_admissible_value=None, uncertainty_dict=None ) with pytest.raises( NotFittedError, match="Subclass must call `finish_fit` inside the `fit` method."): model.predict(train_df) assert model.last_predicted_X_ is not None # attempted prediction assert model.cached_predictions_ is None model.finish_fit() # Checks that other variables are set assert_equal(model.pred_cols, model.model_dict["pred_cols"]) assert_equal(model.feature_cols, model.model_dict["x_mat"].columns) assert_equal(model.coef_, pd.DataFrame( model.model_dict["ml_model"].coef_, index=model.feature_cols)) # Predicts on a new dataset with LogCapture(cst.LOGGER_NAME) as log_capture: predicted = model.predict(test_df) assert_equal(model.last_predicted_X_, test_df) assert_equal(model.cached_predictions_, predicted) log_capture.check() # no log messages (not using cached predictions) # Uses cached predictions with LogCapture(cst.LOGGER_NAME) as log_capture: assert_equal(model.predict(test_df), predicted) log_capture.check( (cst.LOGGER_NAME, "DEBUG", "Returning cached predictions.") ) # Predicts on a different dataset with LogCapture(cst.LOGGER_NAME) as log_capture: predicted = model.predict(train_df) assert_equal(model.last_predicted_X_, train_df) assert_equal(model.cached_predictions_, predicted) log_capture.check() # no log messages (not using cached predictions) # .fit() clears the cached result model.fit(train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) assert model.last_predicted_X_ is None assert model.cached_predictions_ is None def test_score_function(daily_data_with_reg): """Checks score function without null model, with regressors""" model = BaseSilverkiteEstimator() train_df = daily_data_with_reg["train_df"] test_df = daily_data_with_reg["test_df"] # every subclass `fit` follows these steps model.fit( X=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL, origin_for_time_vars=None, extra_pred_cols=["ct1", "regressor1", "regressor2"], train_test_thresh=None, training_fraction=None, fit_algorithm="linear", fit_algorithm_params=None, daily_event_df_dict=None, changepoints_dict=None, fs_components_df=pd.DataFrame({ "name": ["tod", "tow", "conti_year"], "period": [24.0, 7.0, 1.0], "order": [3, 3, 5], "seas_names": ["daily", "weekly", "yearly"]}), autoreg_dict=None, min_admissible_value=None, max_admissible_value=None, uncertainty_dict=None ) model.finish_fit() score = model.score(test_df, test_df[cst.VALUE_COL]) pred_df = model.predict(test_df) assert list(pred_df.columns) == [cst.TIME_COL, cst.PREDICTED_COL] assert score == pytest.approx(mean_squared_error( pred_df[cst.PREDICTED_COL], test_df[cst.VALUE_COL])) assert score == pytest.approx(4.6, rel=1e-1) def test_set_uncertainty_dict(daily_data): """Tests __set_uncertainty_dict""" train_df = daily_data["train_df"] # both provided coverage = 0.95 uncertainty_dict = { "uncertainty_method": "simple_conditional_residuals", "params": { "conditional_cols": ["dow_hr"], "quantiles": [0.025, 0.975], "quantile_estimation_method": "normal_fit", "sample_size_thresh": 20, "small_sample_size_method": "std_quantiles", "small_sample_size_quantile": 0.98}} model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=uncertainty_dict) model.fit(train_df) expected_dict = uncertainty_dict assert_equal(model.uncertainty_dict, expected_dict) assert_equal(model.coverage, coverage) # only coverage provided coverage = 0.90 uncertainty_dict = None model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=uncertainty_dict) model.fit(train_df) expected_dict = { "uncertainty_method": "simple_conditional_residuals", "params": { "conditional_cols": ["dow_hr"], "quantiles": [0.05, 0.95], "quantile_estimation_method": "normal_fit", "sample_size_thresh": 5, "small_sample_size_method": "std_quantiles", "small_sample_size_quantile": 0.98}} assert_equal(model.uncertainty_dict, expected_dict) assert_equal(model.coverage, coverage) # both missing coverage = None uncertainty_dict = None model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=uncertainty_dict) model.fit(train_df) expected_dict = None assert_equal(model.uncertainty_dict, expected_dict) assert_equal(model.coverage, None) # only uncertainty provided coverage = None uncertainty_dict = { "uncertainty_method": "simple_conditional_residuals", "params": { "conditional_cols": ["dow_hr"], "quantiles": [0.05, 0.95], "quantile_estimation_method": "normal_fit", "sample_size_thresh": 5, "small_sample_size_method": "std_quantiles", "small_sample_size_quantile": 0.98}} model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=uncertainty_dict) model.fit(train_df) expected_dict = uncertainty_dict assert_equal(model.uncertainty_dict, expected_dict) assert_equal(model.coverage, 0.90) def test_summary(daily_data): """Checks summary function returns without error""" model = BaseSilverkiteEstimator() train_df = daily_data["train_df"] model.summary() model.fit( train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) model.summary() def test_silverkite_with_components_daily_data(): """Tests get_components, plot_components, plot_trend, plot_seasonalities with daily data and missing input values. """ daily_data = generate_df_with_reg_for_tests( freq="D", periods=20, train_start_date=datetime.datetime(2018, 1, 1), conti_year_origin=2018) train_df = daily_data["train_df"].copy() train_df.loc[[2, 4, 7], cst.VALUE_COL] = np.nan # creates missing values params_daily = params_components() # SilverkiteEstimator parameters # converts into parameters for `forecast_silverkite` coverage = params_daily.pop("coverage") # removes daily seasonality terms params_daily["fs_components_df"] = pd.DataFrame({ "name": ["tow", "ct1"], "period": [7.0, 1.0], "order": [4, 5], "seas_names": ["weekly", "yearly"]}) model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=params_daily["uncertainty_dict"]) with pytest.raises( NotFittedError, match="Call `fit` before calling `plot_components`."): model.plot_components() with pytest.warns(Warning): # suppress warnings from conf_interval.py and sklearn # a subclass's fit() method will have these steps model.fit( X=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL, **params_daily) model.finish_fit() # Tests plot_components with pytest.warns(Warning) as record: title = "Custom component plot" model._set_silverkite_diagnostics_params() fig = model.plot_components(names=["trend", "YEARLY_SEASONALITY", "DUMMY"], title=title) expected_rows = 3 assert len(fig.data) == expected_rows + 1 # includes changepoints assert [fig.data[i].name for i in range(expected_rows)] == \ [cst.VALUE_COL, "trend", "YEARLY_SEASONALITY"] assert fig.layout.xaxis.title["text"] == cst.TIME_COL assert fig.layout.xaxis2.title["text"] == cst.TIME_COL assert fig.layout.xaxis3.title["text"] == "Time of year" assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.yaxis2.title["text"] == "trend" assert fig.layout.yaxis3.title["text"] == "yearly" assert fig.layout.title["text"] == title assert f"The following components have not been specified in the model: " \ f"{{'DUMMY'}}, plotting the rest." in record[0].message.args[0] # Missing component error with pytest.raises( ValueError, match="None of the provided components have been specified in the model."): model.plot_components(names=["DUMMY"]) # Tests plot_trend title = "Custom trend plot" fig = model.plot_trend(title=title) expected_rows = 2 assert len(fig.data) == expected_rows + 1 # includes changepoints assert [fig.data[i].name for i in range(expected_rows)] == [cst.VALUE_COL, "trend"] assert fig.layout.xaxis.title["text"] == cst.TIME_COL assert fig.layout.xaxis2.title["text"] == cst.TIME_COL assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.yaxis2.title["text"] == "trend" assert fig.layout.title["text"] == title # Tests plot_seasonalities with pytest.warns(Warning): # suppresses the warning on seasonalities removed title = "Custom seasonality plot" fig = model.plot_seasonalities(title=title) expected_rows = 3 assert len(fig.data) == expected_rows assert [fig.data[i].name for i in range(expected_rows)] == \ [cst.VALUE_COL, "WEEKLY_SEASONALITY", "YEARLY_SEASONALITY"] assert fig.layout.xaxis.title["text"] == cst.TIME_COL assert fig.layout.xaxis2.title["text"] == "Day of week" assert fig.layout.xaxis3.title["text"] == "Time of year" assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.yaxis2.title["text"] == "weekly" assert fig.layout.yaxis3.title["text"] == "yearly" assert fig.layout.title["text"] == title # Component plot error if `fit_algorithm` is "rf" or "gradient_boosting" params_daily["fit_algorithm"] = "rf" model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=params_daily["uncertainty_dict"]) with pytest.warns(Warning): # suppress warnings from conf_interval.py and sklearn # a subclass's fit() method will have these steps model.fit( X=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) model.model_dict = silverkite.forecast( df=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL, **params_daily) model.finish_fit() assert model.coef_ is None with pytest.raises( NotImplementedError, match="Component plot has only been implemented for additive linear models."): model.plot_components() with pytest.raises( NotImplementedError, match="Component plot has only been implemented for additive linear models."): model.plot_trend() with pytest.raises( NotImplementedError, match="Component plot has only been implemented for additive linear models."): model.plot_seasonalities() def test_silverkite_with_components_hourly_data(): """Tests get_components, plot_components, plot_trend, plot_seasonalities with hourly data """ hourly_data = generate_df_with_reg_for_tests( freq="H", periods=24 * 4, train_start_date=datetime.datetime(2018, 1, 1), conti_year_origin=2018) train_df = hourly_data.get("train_df").copy() params_hourly = params_components() # converts into parameters for `forecast_silverkite` coverage = params_hourly.pop("coverage") model = BaseSilverkiteEstimator( coverage=coverage, uncertainty_dict=params_hourly["uncertainty_dict"]) model.fit( X=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL, **params_hourly) model.finish_fit() # Test plot_components with pytest.warns(Warning) as record: title = "Custom component plot" fig = model.plot_components(names=["trend", "DAILY_SEASONALITY", "DUMMY"], title=title) expected_rows = 3 + 1 # includes changepoints assert len(fig.data) == expected_rows assert [fig.data[i].name for i in range(expected_rows)] == \ [cst.VALUE_COL, "trend", "DAILY_SEASONALITY", "trend change point"] assert fig.layout.xaxis.title["text"] == cst.TIME_COL assert fig.layout.xaxis2.title["text"] == cst.TIME_COL assert fig.layout.xaxis3.title["text"] == "Hour of day" assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.yaxis2.title["text"] == "trend" assert fig.layout.yaxis3.title["text"] == "daily" assert fig.layout.title["text"] == title assert f"The following components have not been specified in the model: " \ f"{{'DUMMY'}}, plotting the rest." in record[0].message.args[0] # Test plot_trend title = "Custom trend plot" fig = model.plot_trend(title=title) expected_rows = 2 assert len(fig.data) == expected_rows + 1 # includes changepoints assert [fig.data[i].name for i in range(expected_rows)] == [cst.VALUE_COL, "trend"] assert fig.layout.xaxis.title["text"] == cst.TIME_COL assert fig.layout.xaxis2.title["text"] == cst.TIME_COL assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.yaxis2.title["text"] == "trend" assert fig.layout.title["text"] == title # Test plot_seasonalities with pytest.warns(Warning): # suppresses the warning on seasonalities removed title = "Custom seasonality plot" fig = model.plot_seasonalities(title=title) expected_rows = 4 assert len(fig.data) == expected_rows assert [fig.data[i].name for i in range(expected_rows)] == \ [cst.VALUE_COL, "DAILY_SEASONALITY", "WEEKLY_SEASONALITY", "YEARLY_SEASONALITY"] assert fig.layout.xaxis.title["text"] == cst.TIME_COL assert fig.layout.xaxis2.title["text"] == "Hour of day" assert fig.layout.xaxis3.title["text"] == "Day of week" assert fig.layout.xaxis4.title["text"] == "Time of year" assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.yaxis2.title["text"] == "daily" assert fig.layout.yaxis3.title["text"] == "weekly" assert fig.layout.yaxis4.title["text"] == "yearly" assert fig.layout.title["text"] == title def test_plot_trend_changepoint_detection(df_pt): model = BaseSilverkiteEstimator() model.fit( X=df_pt, time_col=cst.TIME_COL, value_col=cst.VALUE_COL) params = { "changepoints_dict": {"method": "auto"}} silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=df_pt, time_col=cst.TIME_COL, value_col=cst.VALUE_COL, **params) model.finish_fit() fig = model.plot_trend_changepoint_detection() assert fig is not None assert fig.layout.title["text"] == "Timeseries Plot with detected trend change points" assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.xaxis.title["text"] == "Dates" # tests given parameters fig = model.plot_trend_changepoint_detection( dict(trend_change=False)) assert fig is not None assert fig.layout.title["text"] == "Timeseries Plot" assert fig.layout.yaxis.title["text"] == cst.VALUE_COL assert fig.layout.xaxis.title["text"] == "Dates" def test_model_summary(df_pt): model = BaseSilverkiteEstimator() model.fit( X=df_pt.iloc[:100], # speeds up time_col=cst.TIME_COL, value_col=cst.VALUE_COL) params = { "fit_algorithm": "linear", "training_fraction": 0.8} silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=df_pt.iloc[:100], time_col=cst.TIME_COL, value_col=cst.VALUE_COL, **params) model.finish_fit() summary = model.summary() summary.__str__() summary.__repr__() assert summary is not None def test_pred_category(df_pt): model = BaseSilverkiteEstimator() # property is not available without fitting. with pytest.raises( NotFittedError, match="Must fit before getting predictor category."): print(model.pred_category) model.fit( X=df_pt.iloc[:100], # speeds up time_col=cst.TIME_COL, value_col=cst.VALUE_COL) params = { "fit_algorithm": "linear", "training_fraction": 0.8, "extra_pred_cols": ["ct1", "x", "x:ct1"]} df_pt["x"] = np.random.randn(df_pt.shape[0]) silverkite = SilverkiteForecast() model.model_dict = silverkite.forecast( df=df_pt.iloc[:100], time_col=cst.TIME_COL, value_col=cst.VALUE_COL, **params) model.extra_pred_cols = ["ct1", "x", "x:ct1"] # set in subclass initialization # _pred_category is None before trying to access pred_category assert model._pred_category is None model.finish_fit() pred_category = model.pred_category # _pred_category is updated after trying to access pred_category assert model._pred_category is not None assert pred_category["intercept"] == ["Intercept"] assert pred_category["time_features"] == ["ct1", "x:ct1"] assert pred_category["event_features"] == [] assert pred_category["trend_features"] == ["ct1", "x:ct1"] assert pred_category["seasonality_features"] == ["sin1_tod_daily", "cos1_tod_daily", "sin2_tod_daily", "cos2_tod_daily", "sin3_tod_daily", "cos3_tod_daily", "sin1_tow_weekly", "cos1_tow_weekly", "sin2_tow_weekly", "cos2_tow_weekly", "sin3_tow_weekly", "cos3_tow_weekly", "sin1_toy_yearly", "cos1_toy_yearly", "sin2_toy_yearly", "cos2_toy_yearly", "sin3_toy_yearly", "cos3_toy_yearly", "sin4_toy_yearly", "cos4_toy_yearly", "sin5_toy_yearly", "cos5_toy_yearly"] assert pred_category["lag_features"] == [] assert pred_category["regressor_features"] == ["x", "x:ct1"] assert pred_category["interaction_features"] == ["x:ct1"]
#!/usr/bin/env python # coding: utf-8 # # 🏁 Wrap-up quiz # # **This quiz requires some programming to be answered.** # # Open the dataset `house_prices.csv` with the following command: # In[2]: import pandas as pd ames_housing = pd.read_csv("../datasets/house_prices.csv", na_values="?") target_name = "SalePrice" data = ames_housing.drop(columns=target_name) target = ames_housing[target_name] # `ames_housing` is a pandas dataframe. The column "SalePrice" contains the # target variable. Note that we instructed pandas to treat the character "?" as a # marker for cells with missing values also known as "null" values. # # To simplify this exercise, we will only used the numerical features defined # below: # In[3]: numerical_features = [ "LotFrontage", "LotArea", "MasVnrArea", "BsmtFinSF1", "BsmtFinSF2", "BsmtUnfSF", "TotalBsmtSF", "1stFlrSF", "2ndFlrSF", "LowQualFinSF", "GrLivArea", "BedroomAbvGr", "KitchenAbvGr", "TotRmsAbvGrd", "Fireplaces", "GarageCars", "GarageArea", "WoodDeckSF", "OpenPorchSF", "EnclosedPorch", "3SsnPorch", "ScreenPorch", "PoolArea", "MiscVal", ] data_numerical = data[numerical_features] # Start by fitting a linear regression (`sklearn.linear_model.LinearRegression`). # Use a 10-fold cross-validation and pass the argument `return_estimator=True` in # `sklearn.model_selection.cross_validate` to access all fitted estimators fitted # on each fold. As we saw in the previous notebooks, you will have to use a # `sklearn.preprocessing.StandardScaler` to scale the data before passing it to # the regressor. Also, some missing data are present in the different columns. # You can use a `sklearn.impute.SimpleImputer` with the default parameters to # impute missing data. # In[4]: from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer from sklearn.linear_model import LinearRegression from sklearn.model_selection import cross_validate model = make_pipeline(StandardScaler(), SimpleImputer(), LinearRegression()) cv_result = cross_validate(model, data_numerical, target, cv=10, return_estimator=True) # In[15]: import numpy as np cv_result['estimator'] for idx, pipeline in enumerate(cv_result["estimator"]): print( f"Fold #{idx} - features selected are: " f"{np.argsort(pipeline[-1].coef_)[-2:]}" f"\n and weights are {np.max(abs(pipeline[-1].coef_))}" ) # # Question 1 # What is the order of magnitude of the extremum weight values over all the features: # # - a) 1e4 # - b) 1e6 # - c) 1e18 # # _Select a single answer_ # # +++ # # Repeat the same experiment by fitting a ridge regressor # (`sklearn.linear_model.Ridge`) with the default parameter. # In[16]: from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer from sklearn.linear_model import Ridge from sklearn.model_selection import cross_validate model = make_pipeline(StandardScaler(), SimpleImputer(), Ridge()) cv_result = cross_validate(model, data_numerical, target, cv=10, return_estimator=True) # In[17]: import numpy as np cv_result['estimator'] for idx, pipeline in enumerate(cv_result["estimator"]): print( f"Fold #{idx} - features selected are: " f"{np.argsort(pipeline[-1].coef_)[-2:]}" f"\n and weights are {np.max(abs(pipeline[-1].coef_))}" ) # # Question 2 # What magnitude of the extremum weight values for all features? # # - a) 1e4 # - b) 1e6 # - c) 1e18 # # _Select a single answer_ # ``` # +++ # # Question 3 # What are the two most important features used by the ridge regressor? You can # make a box-plot of the coefficients across all folds to get a good insight. # # - a) `"MiscVal"` and `"BsmtFinSF1"` # - b) `"GarageCars"` and `"GrLivArea"` # - c) `"TotalBsmtSF"` and `"GarageCars"` # # _Select a single answer_ # ``` # In[23]: import pandas as pd weights = pd.DataFrame( [np.abs(est[-1].coef_) for est in cv_result["estimator"]], columns=data[numerical_features].columns) import matplotlib.pyplot as plt color = {"whiskers": "black", "medians": "black", "caps": "black"} weights.plot.box(color=color, vert=False) _ = plt.title("Value of linear regression coefficients") # +++ # # Remove the feature `"GarageArea"` from the dataset and repeat the previous # experiment. # In[30]: numerical_features_wo_garage = [ "LotFrontage", "LotArea", "MasVnrArea", "BsmtFinSF1", "BsmtFinSF2", "BsmtUnfSF", "TotalBsmtSF", "1stFlrSF", "2ndFlrSF", "LowQualFinSF", "GrLivArea", "BedroomAbvGr", "KitchenAbvGr", "TotRmsAbvGrd", "Fireplaces", "GarageCars", "WoodDeckSF", "OpenPorchSF", "EnclosedPorch", "3SsnPorch", "ScreenPorch", "PoolArea", "MiscVal", ] data_wo_garage_numerical = data[numerical_features_wo_garage] cv_result = cross_validate(model, data_wo_garage_numerical, target, cv=10, return_estimator=True) weights = pd.DataFrame( [np.abs(est[-1].coef_) for est in cv_result["estimator"]], columns=data_wo_garage_numerical.columns) import matplotlib.pyplot as plt color = {"whiskers": "black", "medians": "black", "caps": "black"} weights.plot.box(color=color, vert=False) _ = plt.title("Value of linear regression coefficients") # # Question 4 # What is the impact on the weights of removing `"GarageArea"` from the dataset? # # - a) None # - b) Change completely the order of the feature importance # - c) The variability of the most important feature reduced # # _Select a single answer_ # ``` # # +++ # # Question 5 # What is the reason for observing the previous impact on the most important # weight? # # - a) Both features are correlated and are carrying similar information # - b) Removing a feature reduce the noise in the dataset # - c) Just some random effects # # _Select a single answer_ # ``` # +++ # # Now, we will search for the regularization strength that will maximize the # statistical performance of our predictive model. Fit a # [`sklearn.linear_model.RidgeCV`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RidgeCV.html) # instead of a `Ridge` regressor pass `alphas=np.logspace(-1, 3, num=30)` to # explore the effect of changing the regularization strength. # In[31]: from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer from sklearn.linear_model import RidgeCV from sklearn.model_selection import cross_validate import numpy as np import pandas as pd model = make_pipeline(StandardScaler(), SimpleImputer(), RidgeCV(alphas=np.logspace(-1, 3, num=30))) cv_result = cross_validate(model, data_numerical, target, cv=10, return_estimator=True) weights = pd.DataFrame( [np.abs(est[-1].coef_) for est in cv_result["estimator"]], columns=data_numerical.columns) import matplotlib.pyplot as plt color = {"whiskers": "black", "medians": "black", "caps": "black"} weights.plot.box(color=color, vert=False) _ = plt.title("Value of linear regression coefficients") # # Question 6 # Are there major differences regarding the most important weights? # # - a) Yes, the weights order is completely different # - b) No, the weights order is very similar # # _Select a single answer_ # ``` # # +++ # Check the parameter `alpha_` (the regularization strength) for the different # ridge regressors obtained on each fold. # In[34]: cv_result [np.abs(est[-1].alpha_) for est in cv_result["estimator"]] # # Question 7 # In which range does `alpha_` fall into for most folds? # # - a) between 0.1 and 1 # - b) between 1 and 10 # - c) between 10 and 100 # - d) between 100 and 1000 # # _Select a single answer_ # ``` # +++ # # Now, we will tackle a classification problem instead of a regression problem. # Load the Adult Census dataset with the following snippet of code and we will # work only with **numerical features**. # In[35]: adult_census = pd.read_csv("../datasets/adult-census.csv") target = adult_census["class"] data = adult_census.select_dtypes(["integer", "floating"]) data = data.drop(columns=["education-num"]) # In[36]: data.info() # # Question 8 # How many numerical features are present in the dataset? # # - a) 3 # - b) 4 # - c) 5 # # _Select a single answer_ # # # Question 9 # Are there missing values in this dataset? # # - a) Yes # - b) No # # _Select a single answer_ # # Hint: you can use `df.info()` to get information regarding each column. # ``` # +++ # # Fit a `sklearn.linear_model.LogisticRegression` classifier using a 10-fold # cross-validation to assess the performance. Since we are dealing with a linear # model, do not forget to scale the data with a `StandardScaler` before training # the model. # In[48]: from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_validate model = make_pipeline(StandardScaler(), LogisticRegression()) cv_result = cross_validate(model, data, target, cv=10, return_estimator=True) cv_result print(f'Score is {cv_result['test_score'].mean():0.2f} +/- {cv_result['test_score'].std():0.2f}') # In[45]: target.value_counts() # In[46]: from sklearn.dummy import DummyClassifier class_to_predict = " <=50K" low_revenue_clf = DummyClassifier(strategy="constant", constant=class_to_predict) low_revenue_clf.fit(data, target) score = low_revenue_clf.score(data, target) print(f"Accuracy of a model predicting only low revenue: {score:.3f}") # # Question 10 # On average, how much better/worse/similar is the logistic regression to a dummy # classifier that would predict the most frequent class? # # - a) Worse than a dummy classifier by ~4% # - b) Similar to a dummy classifier # - c) Better than a dummy classifier by ~4% # # _Select a single answer_ # ``` # # +++ # In[62]: weights = pd.DataFrame( np.array([np.abs(est[-1].coef_) for est in cv_result["estimator"]]).reshape(10,-1), columns=data.columns) import matplotlib.pyplot as plt color = {"whiskers": "black", "medians": "black", "caps": "black"} weights.plot.box(color=color, vert=False) _ = plt.title("Value of linear regression coefficients") # # Question 11 # What is the most important feature seen by the logistic regression? # # - a) `"age"` # - b) `"capital-gain"` # - c) `"capital-loss"` # - d) `"hours-per-week"` # # _Select a single answer_ # ``` # +++ # # Now, we will work with **both numerical and categorical features**. You can # load Adult Census with the following snippet: # In[63]: adult_census = pd.read_csv("../datasets/adult-census.csv") target = adult_census["class"] data = adult_census.drop(columns=["class", "education-num"]) # In[64]: data.info() # # Question 12 # Are there missing values in this dataset? # # - a) Yes # - b) No # # _Select a single answer_ # # Hint: you can use `df.info()` to get information regarding each column. # ``` # +++ # # Create a predictive model where the categorical data should be one-hot encoded, # the numerical data should be scaled, and the predictor used should be a # logistic regression classifier. # In[65]: from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_validate from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder from sklearn.compose import make_column_selector as selector categorical_columns_selector = selector(dtype_include=object) categorical_columns = categorical_columns_selector(data) numerical_columns_selector = selector(dtype_exclude=object) numerical_columns = numerical_columns_selector(data) preprocessor = ColumnTransformer(transformers=[ ("num-preprocessor", StandardScaler(), numerical_columns), ("cat-preprocessor", OneHotEncoder(handle_unknown='ignore'), categorical_columns) ]) model = make_pipeline(preprocessor, LogisticRegression()) cv_result = cross_validate(model, data, target, cv=10, return_estimator=True) cv_result print(f'Score is {cv_result['test_score'].mean():0.2f} +/- {cv_result['test_score'].std():0.2f}') # # Question 13 # On average, what is the improvement of using the categorical features? # # - a) It gives similar results # - b) It improves the statistical performance by 2.5% # - c) it improves the statistical performance by 5% # - d) it improves the statistical performance by 7.5% # - e) it improves the statistical performance by 10% # # _Select a single answer_ # ``` # +++ # # For the following questions, you can use the following snippet to get the # feature names after the preprocessing performed. # In[67]: preprocessor # In[68]: preprocessor.fit(data) feature_names = (preprocessor.named_transformers_["cat-preprocessor"] .get_feature_names(categorical_columns)).tolist() feature_names += numerical_columns # There is as many feature names as coefficients in the last step of your # predictive pipeline. # In[138]: for cv in cv_result['estimator']: print(np.argmax(cv[-1].coef_[0])) print(np.argsort(cv[-1].coef_[0])[-2:]) print([feature_names[i] for i in np.argsort(cv[-1].coef_[0])[-2:]]) feature_names[23] # # Question 14 # What are the two most important features used by the logistic regressor? # # - a) `"hours-per-week"` and `"native-country_Columbia"` # - b) `"workclass_?"` and `"naitive_country_?"` # - c) `"capital-gain"` and `"education_Doctorate"` # # _Select a single answer_ # ``` # # +++ # # Question 15 # What is the effect of decreasing the `C` parameter on the coefficients? # # - a) shrinking the magnitude of the weights towards zeros # - b) increasing the magnitude of the weights # - c) reducing the weights' variance # - d) increasing the weights' variance # - e) it has no influence on the weights' variance # # _Select several answers_ # ``` # In[ ]:
#!/usr/bin/env python # coding: utf-8 # # 🏁 Wrap-up quiz # # **This quiz requires some programming to be answered.** # # Open the dataset `house_prices.csv` with the following command: # In[2]: import pandas as pd ames_housing = pd.read_csv("../datasets/house_prices.csv", na_values="?") target_name = "SalePrice" data = ames_housing.drop(columns=target_name) target = ames_housing[target_name] # `ames_housing` is a pandas dataframe. The column "SalePrice" contains the # target variable. Note that we instructed pandas to treat the character "?" as a # marker for cells with missing values also known as "null" values. # # To simplify this exercise, we will only used the numerical features defined # below: # In[3]: numerical_features = [ "LotFrontage", "LotArea", "MasVnrArea", "BsmtFinSF1", "BsmtFinSF2", "BsmtUnfSF", "TotalBsmtSF", "1stFlrSF", "2ndFlrSF", "LowQualFinSF", "GrLivArea", "BedroomAbvGr", "KitchenAbvGr", "TotRmsAbvGrd", "Fireplaces", "GarageCars", "GarageArea", "WoodDeckSF", "OpenPorchSF", "EnclosedPorch", "3SsnPorch", "ScreenPorch", "PoolArea", "MiscVal", ] data_numerical = data[numerical_features] # Start by fitting a linear regression (`sklearn.linear_model.LinearRegression`). # Use a 10-fold cross-validation and pass the argument `return_estimator=True` in # `sklearn.model_selection.cross_validate` to access all fitted estimators fitted # on each fold. As we saw in the previous notebooks, you will have to use a # `sklearn.preprocessing.StandardScaler` to scale the data before passing it to # the regressor. Also, some missing data are present in the different columns. # You can use a `sklearn.impute.SimpleImputer` with the default parameters to # impute missing data. # In[4]: from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer from sklearn.linear_model import LinearRegression from sklearn.model_selection import cross_validate model = make_pipeline(StandardScaler(), SimpleImputer(), LinearRegression()) cv_result = cross_validate(model, data_numerical, target, cv=10, return_estimator=True) # In[15]: import numpy as np cv_result['estimator'] for idx, pipeline in enumerate(cv_result["estimator"]): print( f"Fold #{idx} - features selected are: " f"{np.argsort(pipeline[-1].coef_)[-2:]}" f"\n and weights are {np.max(abs(pipeline[-1].coef_))}" ) # # Question 1 # What is the order of magnitude of the extremum weight values over all the features: # # - a) 1e4 # - b) 1e6 # - c) 1e18 # # _Select a single answer_ # # +++ # # Repeat the same experiment by fitting a ridge regressor # (`sklearn.linear_model.Ridge`) with the default parameter. # In[16]: from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer from sklearn.linear_model import Ridge from sklearn.model_selection import cross_validate model = make_pipeline(StandardScaler(), SimpleImputer(), Ridge()) cv_result = cross_validate(model, data_numerical, target, cv=10, return_estimator=True) # In[17]: import numpy as np cv_result['estimator'] for idx, pipeline in enumerate(cv_result["estimator"]): print( f"Fold #{idx} - features selected are: " f"{np.argsort(pipeline[-1].coef_)[-2:]}" f"\n and weights are {np.max(abs(pipeline[-1].coef_))}" ) # # Question 2 # What magnitude of the extremum weight values for all features? # # - a) 1e4 # - b) 1e6 # - c) 1e18 # # _Select a single answer_ # ``` # +++ # # Question 3 # What are the two most important features used by the ridge regressor? You can # make a box-plot of the coefficients across all folds to get a good insight. # # - a) `"MiscVal"` and `"BsmtFinSF1"` # - b) `"GarageCars"` and `"GrLivArea"` # - c) `"TotalBsmtSF"` and `"GarageCars"` # # _Select a single answer_ # ``` # In[23]: import pandas as pd weights = pd.DataFrame( [np.abs(est[-1].coef_) for est in cv_result["estimator"]], columns=data[numerical_features].columns) import matplotlib.pyplot as plt color = {"whiskers": "black", "medians": "black", "caps": "black"} weights.plot.box(color=color, vert=False) _ = plt.title("Value of linear regression coefficients") # +++ # # Remove the feature `"GarageArea"` from the dataset and repeat the previous # experiment. # In[30]: numerical_features_wo_garage = [ "LotFrontage", "LotArea", "MasVnrArea", "BsmtFinSF1", "BsmtFinSF2", "BsmtUnfSF", "TotalBsmtSF", "1stFlrSF", "2ndFlrSF", "LowQualFinSF", "GrLivArea", "BedroomAbvGr", "KitchenAbvGr", "TotRmsAbvGrd", "Fireplaces", "GarageCars", "WoodDeckSF", "OpenPorchSF", "EnclosedPorch", "3SsnPorch", "ScreenPorch", "PoolArea", "MiscVal", ] data_wo_garage_numerical = data[numerical_features_wo_garage] cv_result = cross_validate(model, data_wo_garage_numerical, target, cv=10, return_estimator=True) weights = pd.DataFrame( [np.abs(est[-1].coef_) for est in cv_result["estimator"]], columns=data_wo_garage_numerical.columns) import matplotlib.pyplot as plt color = {"whiskers": "black", "medians": "black", "caps": "black"} weights.plot.box(color=color, vert=False) _ = plt.title("Value of linear regression coefficients") # # Question 4 # What is the impact on the weights of removing `"GarageArea"` from the dataset? # # - a) None # - b) Change completely the order of the feature importance # - c) The variability of the most important feature reduced # # _Select a single answer_ # ``` # # +++ # # Question 5 # What is the reason for observing the previous impact on the most important # weight? # # - a) Both features are correlated and are carrying similar information # - b) Removing a feature reduce the noise in the dataset # - c) Just some random effects # # _Select a single answer_ # ``` # +++ # # Now, we will search for the regularization strength that will maximize the # statistical performance of our predictive model. Fit a # [`sklearn.linear_model.RidgeCV`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RidgeCV.html) # instead of a `Ridge` regressor pass `alphas=np.logspace(-1, 3, num=30)` to # explore the effect of changing the regularization strength. # In[31]: from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer from sklearn.linear_model import RidgeCV from sklearn.model_selection import cross_validate import numpy as np import pandas as pd model = make_pipeline(StandardScaler(), SimpleImputer(), RidgeCV(alphas=np.logspace(-1, 3, num=30))) cv_result = cross_validate(model, data_numerical, target, cv=10, return_estimator=True) weights = pd.DataFrame( [np.abs(est[-1].coef_) for est in cv_result["estimator"]], columns=data_numerical.columns) import matplotlib.pyplot as plt color = {"whiskers": "black", "medians": "black", "caps": "black"} weights.plot.box(color=color, vert=False) _ = plt.title("Value of linear regression coefficients") # # Question 6 # Are there major differences regarding the most important weights? # # - a) Yes, the weights order is completely different # - b) No, the weights order is very similar # # _Select a single answer_ # ``` # # +++ # Check the parameter `alpha_` (the regularization strength) for the different # ridge regressors obtained on each fold. # In[34]: cv_result [np.abs(est[-1].alpha_) for est in cv_result["estimator"]] # # Question 7 # In which range does `alpha_` fall into for most folds? # # - a) between 0.1 and 1 # - b) between 1 and 10 # - c) between 10 and 100 # - d) between 100 and 1000 # # _Select a single answer_ # ``` # +++ # # Now, we will tackle a classification problem instead of a regression problem. # Load the Adult Census dataset with the following snippet of code and we will # work only with **numerical features**. # In[35]: adult_census = pd.read_csv("../datasets/adult-census.csv") target = adult_census["class"] data = adult_census.select_dtypes(["integer", "floating"]) data = data.drop(columns=["education-num"]) # In[36]: data.info() # # Question 8 # How many numerical features are present in the dataset? # # - a) 3 # - b) 4 # - c) 5 # # _Select a single answer_ # # # Question 9 # Are there missing values in this dataset? # # - a) Yes # - b) No # # _Select a single answer_ # # Hint: you can use `df.info()` to get information regarding each column. # ``` # +++ # # Fit a `sklearn.linear_model.LogisticRegression` classifier using a 10-fold # cross-validation to assess the performance. Since we are dealing with a linear # model, do not forget to scale the data with a `StandardScaler` before training # the model. # In[48]: from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_validate model = make_pipeline(StandardScaler(), LogisticRegression()) cv_result = cross_validate(model, data, target, cv=10, return_estimator=True) cv_result print(f'Score is {cv_result["test_score"].mean():0.2f} +/- {cv_result["test_score"].std():0.2f}') # In[45]: target.value_counts() # In[46]: from sklearn.dummy import DummyClassifier class_to_predict = " <=50K" low_revenue_clf = DummyClassifier(strategy="constant", constant=class_to_predict) low_revenue_clf.fit(data, target) score = low_revenue_clf.score(data, target) print(f"Accuracy of a model predicting only low revenue: {score:.3f}") # # Question 10 # On average, how much better/worse/similar is the logistic regression to a dummy # classifier that would predict the most frequent class? # # - a) Worse than a dummy classifier by ~4% # - b) Similar to a dummy classifier # - c) Better than a dummy classifier by ~4% # # _Select a single answer_ # ``` # # +++ # In[62]: weights = pd.DataFrame( np.array([np.abs(est[-1].coef_) for est in cv_result["estimator"]]).reshape(10,-1), columns=data.columns) import matplotlib.pyplot as plt color = {"whiskers": "black", "medians": "black", "caps": "black"} weights.plot.box(color=color, vert=False) _ = plt.title("Value of linear regression coefficients") # # Question 11 # What is the most important feature seen by the logistic regression? # # - a) `"age"` # - b) `"capital-gain"` # - c) `"capital-loss"` # - d) `"hours-per-week"` # # _Select a single answer_ # ``` # +++ # # Now, we will work with **both numerical and categorical features**. You can # load Adult Census with the following snippet: # In[63]: adult_census = pd.read_csv("../datasets/adult-census.csv") target = adult_census["class"] data = adult_census.drop(columns=["class", "education-num"]) # In[64]: data.info() # # Question 12 # Are there missing values in this dataset? # # - a) Yes # - b) No # # _Select a single answer_ # # Hint: you can use `df.info()` to get information regarding each column. # ``` # +++ # # Create a predictive model where the categorical data should be one-hot encoded, # the numerical data should be scaled, and the predictor used should be a # logistic regression classifier. # In[65]: from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_validate from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder from sklearn.compose import make_column_selector as selector categorical_columns_selector = selector(dtype_include=object) categorical_columns = categorical_columns_selector(data) numerical_columns_selector = selector(dtype_exclude=object) numerical_columns = numerical_columns_selector(data) preprocessor = ColumnTransformer(transformers=[ ("num-preprocessor", StandardScaler(), numerical_columns), ("cat-preprocessor", OneHotEncoder(handle_unknown='ignore'), categorical_columns) ]) model = make_pipeline(preprocessor, LogisticRegression()) cv_result = cross_validate(model, data, target, cv=10, return_estimator=True) cv_result print(f'Score is {cv_result["test_score"].mean():0.2f} +/- {cv_result["test_score"].std():0.2f}') # # Question 13 # On average, what is the improvement of using the categorical features? # # - a) It gives similar results # - b) It improves the statistical performance by 2.5% # - c) it improves the statistical performance by 5% # - d) it improves the statistical performance by 7.5% # - e) it improves the statistical performance by 10% # # _Select a single answer_ # ``` # +++ # # For the following questions, you can use the following snippet to get the # feature names after the preprocessing performed. # In[67]: preprocessor # In[68]: preprocessor.fit(data) feature_names = (preprocessor.named_transformers_["cat-preprocessor"] .get_feature_names(categorical_columns)).tolist() feature_names += numerical_columns # There is as many feature names as coefficients in the last step of your # predictive pipeline. # In[138]: for cv in cv_result['estimator']: print(np.argmax(cv[-1].coef_[0])) print(np.argsort(cv[-1].coef_[0])[-2:]) print([feature_names[i] for i in np.argsort(cv[-1].coef_[0])[-2:]]) feature_names[23] # # Question 14 # What are the two most important features used by the logistic regressor? # # - a) `"hours-per-week"` and `"native-country_Columbia"` # - b) `"workclass_?"` and `"naitive_country_?"` # - c) `"capital-gain"` and `"education_Doctorate"` # # _Select a single answer_ # ``` # # +++ # # Question 15 # What is the effect of decreasing the `C` parameter on the coefficients? # # - a) shrinking the magnitude of the weights towards zeros # - b) increasing the magnitude of the weights # - c) reducing the weights' variance # - d) increasing the weights' variance # - e) it has no influence on the weights' variance # # _Select several answers_ # ``` # In[ ]:
from Bio import SeqIO from Bio import AlignIO import sys import argparse parser = argparse.ArgumentParser(description='Clean up coding consensus.') parser.add_argument("--alignment_with_ref", action="store", type=str, dest="alignment") parser.add_argument("--output_seq", action="store", type=str, dest="output_seq") parser.add_argument("--polish_round", action="store", type=str, dest="round") parser.add_argument("--name", action="store", type=str, dest="name") args = parser.parse_args() round_name = '' if args.round: round_name = f" round_name={args.round}" def trim_trailing_gaps(alignment): start_position = 0 end_position = 0 for col in range(alignment.get_alignment_length()): if not "-" in alignment[:, col]: start_position = col break for col in range(alignment.get_alignment_length()): end_index = col+1 if not "-" in alignment[:, -end_index]: end_position = col break print(f"\nTrimming trailing gaps in alignment.\nAlignment now from {start_position} to {alignment.get_alignment_length()-end_position}.\n") if end_position == 0: return alignment[:,start_position:] else: return alignment[:,start_position:-end_position] def remove_gaps(aln): untrimmed_alignment = AlignIO.read(aln, "fasta") trimmed = trim_trailing_gaps(untrimmed_alignment) print(f"Reading in {aln}.\n\nGaps found:") cns_string = "" for i in range(len(trimmed[0])): col = trimmed[:,i] if len(set(col))>1 and '-' in col: print(f"Position {i+1}:\tReference:\t{col[0]}\tConsensus:\t{col[1]}") if col[0] == '-': pass else: cns_string += 'N' else: cns_string+= col[1] return trimmed[1].id, cns_string #the rule is to replace a gap in the query with 'N' and to force delete a base that causes a gap in the reference with open(args.output_seq, "w") as fw: cns_id, new_consensus = remove_gaps(args.alignment) fw.write(f">{args.name} accession={cns_id.split(":")[0]}{round_name} length={len(new_consensus)}\n{new_consensus.upper()}\n")
from Bio import SeqIO from Bio import AlignIO import sys import argparse parser = argparse.ArgumentParser(description='Clean up coding consensus.') parser.add_argument("--alignment_with_ref", action="store", type=str, dest="alignment") parser.add_argument("--output_seq", action="store", type=str, dest="output_seq") parser.add_argument("--polish_round", action="store", type=str, dest="round") parser.add_argument("--name", action="store", type=str, dest="name") args = parser.parse_args() round_name = '' if args.round: round_name = f" round_name={args.round}" def trim_trailing_gaps(alignment): start_position = 0 end_position = 0 for col in range(alignment.get_alignment_length()): if not "-" in alignment[:, col]: start_position = col break for col in range(alignment.get_alignment_length()): end_index = col+1 if not "-" in alignment[:, -end_index]: end_position = col break print(f"\nTrimming trailing gaps in alignment.\nAlignment now from {start_position} to {alignment.get_alignment_length()-end_position}.\n") if end_position == 0: return alignment[:,start_position:] else: return alignment[:,start_position:-end_position] def remove_gaps(aln): untrimmed_alignment = AlignIO.read(aln, "fasta") trimmed = trim_trailing_gaps(untrimmed_alignment) print(f"Reading in {aln}.\n\nGaps found:") cns_string = "" for i in range(len(trimmed[0])): col = trimmed[:,i] if len(set(col))>1 and '-' in col: print(f"Position {i+1}:\tReference:\t{col[0]}\tConsensus:\t{col[1]}") if col[0] == '-': pass else: cns_string += 'N' else: cns_string+= col[1] return trimmed[1].id, cns_string #the rule is to replace a gap in the query with 'N' and to force delete a base that causes a gap in the reference with open(args.output_seq, "w") as fw: cns_id, new_consensus = remove_gaps(args.alignment) fw.write(f">{args.name} accession={cns_id.split(':')[0]}{round_name} length={len(new_consensus)}\n{new_consensus.upper()}\n")
import datetime import html import textwrap import bs4 import jikanpy import requests from innexiaBot import DEV_USERS, OWNER_ID, DRAGONS, dispatcher from innexiaBot.modules.disable import DisableAbleCommandHandler from telegram import (InlineKeyboardButton, InlineKeyboardMarkup, ParseMode, Update) from telegram.ext import CallbackContext, CallbackQueryHandler, run_async info_btn = "More Information" kaizoku_btn = "Kaizoku ☠️" kayo_btn = "Kayo 🏴‍☠️" prequel_btn = "⬅️ Prequel" sequel_btn = "Sequel ➡️" close_btn = "Close ❌" def shorten(description, info='anilist.co'): msg = "" if len(description) > 700: description = description[0:500] + '....' msg += f"\n*Description*: _{description}_[Read More]({info})" else: msg += f"\n*Description*:_{description}_" return msg #time formatter from uniborg def t(milliseconds: int) -> str: """Inputs time in milliseconds, to get beautified time, as string""" seconds, milliseconds = divmod(int(milliseconds), 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ((str(days) + " Days, ") if days else "") + \ ((str(hours) + " Hours, ") if hours else "") + \ ((str(minutes) + " Minutes, ") if minutes else "") + \ ((str(seconds) + " Seconds, ") if seconds else "") + \ ((str(milliseconds) + " ms, ") if milliseconds else "") return tmp[:-2] airing_query = ''' query ($id: Int,$search: String) { Media (id: $id, type: ANIME,search: $search) { id episodes title { romaji english native } nextAiringEpisode { airingAt timeUntilAiring episode } } } ''' fav_query = """ query ($id: Int) { Media (id: $id, type: ANIME) { id title { romaji english native } } } """ anime_query = ''' query ($id: Int,$search: String) { Media (id: $id, type: ANIME,search: $search) { id title { romaji english native } description (asHtml: false) startDate{ year } episodes season type format status duration siteUrl studios{ nodes{ name } } trailer{ id site thumbnail } averageScore genres bannerImage } } ''' character_query = """ query ($query: String) { Character (search: $query) { id name { first last full } siteUrl image { large } description } } """ manga_query = """ query ($id: Int,$search: String) { Media (id: $id, type: MANGA,search: $search) { id title { romaji english native } description (asHtml: false) startDate{ year } type format status siteUrl averageScore genres bannerImage } } """ url = 'https://graphql.anilist.co' @run_async def airing(update: Update, context: CallbackContext): message = update.effective_message search_str = message.text.split(' ', 1) if len(search_str) == 1: update.effective_message.reply_text( 'Tell Anime Name :) ( /airing <anime name>)') return variables = {'search': search_str[1]} response = requests.post( url, json={ 'query': airing_query, 'variables': variables }).json()['data']['Media'] msg = f"*Name*: *{response["title"]["romaji"]}*(`{response["title"]["native"]}`)\n*ID*: `{response["id"]}`" if response['nextAiringEpisode']: time = response['nextAiringEpisode']['timeUntilAiring'] * 1000 time = t(time) msg += f"\n*Episode*: `{response["nextAiringEpisode"]["episode"]}`\n*Airing In*: `{time}`" else: msg += f"\n*Episode*:{response["episodes"]}\n*Status*: `N/A`" update.effective_message.reply_text(msg, parse_mode=ParseMode.MARKDOWN) @run_async def anime(update: Update, context: CallbackContext): message = update.effective_message search = message.text.split(' ', 1) if len(search) == 1: update.effective_message.reply_text('Format : /anime < anime name >') return else: search = search[1] variables = {'search': search} json = requests.post( url, json={ 'query': anime_query, 'variables': variables }).json() if 'errors' in json.keys(): update.effective_message.reply_text('Anime not found') return if json: json = json['data']['Media'] msg = f"*{json["title"]["romaji"]}*(`{json["title"]["native"]}`)\n*Type*: {json["format"]}\n*Status*: {json["status"]}\n*Episodes*: {json.get("episodes", "N/A")}\n*Duration*: {json.get("duration", "N/A")} Per Ep.\n*Score*: {json["averageScore"]}\n*Genres*: `" for x in json['genres']: msg += f"{x}, " msg = msg[:-2] + '`\n' msg += "*Studios*: `" for x in json['studios']['nodes']: msg += f"{x["name"]}, " msg = msg[:-2] + '`\n' info = json.get('siteUrl') trailer = json.get('trailer', None) anime_id = json['id'] if trailer: trailer_id = trailer.get('id', None) site = trailer.get('site', None) if site == "youtube": trailer = 'https://youtu.be/' + trailer_id description = json.get('description', 'N/A').replace('<i>', '').replace( '</i>', '').replace('<br>', '') msg += shorten(description, info) image = json.get('bannerImage', None) if trailer: buttons = [[ InlineKeyboardButton("More Info", url=info), InlineKeyboardButton("Trailer 🎬", url=trailer) ]] else: buttons = [[InlineKeyboardButton("More Info", url=info)]] if image: try: update.effective_message.reply_photo( photo=image, caption=msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) except: msg += f" [〽️]({image})" update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) else: update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) @run_async def character(update: Update, context: CallbackContext): message = update.effective_message search = message.text.split(' ', 1) if len(search) == 1: update.effective_message.reply_text( 'Format : /character < character name >') return search = search[1] variables = {'query': search} json = requests.post( url, json={ 'query': character_query, 'variables': variables }).json() if 'errors' in json.keys(): update.effective_message.reply_text('Character not found') return if json: json = json['data']['Character'] msg = f"*{json.get("name").get("full")}*(`{json.get("name").get("native")}`)\n" description = f"{json["description"]}" site_url = json.get('siteUrl') msg += shorten(description, site_url) image = json.get('image', None) if image: image = image.get('large') update.effective_message.reply_photo( photo=image, caption=msg.replace('<b>', '</b>'), parse_mode=ParseMode.MARKDOWN) else: update.effective_message.reply_text( msg.replace('<b>', '</b>'), parse_mode=ParseMode.MARKDOWN) @run_async def manga(update: Update, context: CallbackContext): message = update.effective_message search = message.text.split(' ', 1) if len(search) == 1: update.effective_message.reply_text('Format : /manga < manga name >') return search = search[1] variables = {'search': search} json = requests.post( url, json={ 'query': manga_query, 'variables': variables }).json() msg = '' if 'errors' in json.keys(): update.effective_message.reply_text('Manga not found') return if json: json = json['data']['Media'] title, title_native = json['title'].get('romaji', False), json['title'].get( 'native', False) start_date, status, score = json['startDate'].get( 'year', False), json.get('status', False), json.get('averageScore', False) if title: msg += f"*{title}*" if title_native: msg += f"(`{title_native}`)" if start_date: msg += f"\n*Start Date* - `{start_date}`" if status: msg += f"\n*Status* - `{status}`" if score: msg += f"\n*Score* - `{score}`" msg += '\n*Genres* - ' for x in json.get('genres', []): msg += f"{x}, " msg = msg[:-2] info = json['siteUrl'] buttons = [[InlineKeyboardButton("More Info", url=info)]] image = json.get("bannerImage", False) msg += f"_{json.get("description", None)}_" if image: try: update.effective_message.reply_photo( photo=image, caption=msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) except: msg += f" [〽️]({image})" update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) else: update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) @run_async def user(update: Update, context: CallbackContext): message = update.effective_message args = message.text.strip().split(" ", 1) try: search_query = args[1] except: if message.reply_to_message: search_query = message.reply_to_message.text else: update.effective_message.reply_text("Format : /user <username>") return jikan = jikanpy.jikan.Jikan() try: user = jikan.user(search_query) except jikanpy.APIException: update.effective_message.reply_text("Username not found.") return progress_message = update.effective_message.reply_text("Searching.... ") date_format = "%Y-%m-%d" if user['image_url'] is None: img = "https://cdn.myanimelist.net/images/questionmark_50.gif" else: img = user['image_url'] try: user_birthday = datetime.datetime.fromisoformat(user['birthday']) user_birthday_formatted = user_birthday.strftime(date_format) except: user_birthday_formatted = "Unknown" user_joined_date = datetime.datetime.fromisoformat(user['joined']) user_joined_date_formatted = user_joined_date.strftime(date_format) for entity in user: if user[entity] is None: user[entity] = "Unknown" about = user['about'].split(" ", 60) try: about.pop(60) except IndexError: pass about_string = ' '.join(about) about_string = about_string.replace("<br>", "").strip().replace("\r\n", "\n") caption = "" caption += textwrap.dedent(f""" *Username*: [{user['username']}]({user['url']}) *Gender*: `{user['gender']}` *Birthday*: `{user_birthday_formatted}` *Joined*: `{user_joined_date_formatted}` *Days wasted watching anime*: `{user['anime_stats']['days_watched']}` *Days wasted reading manga*: `{user['manga_stats']['days_read']}` """) caption += f"*About*: {about_string}" buttons = [[InlineKeyboardButton(info_btn, url=user['url'])], [ InlineKeyboardButton( close_btn, callback_data=f"anime_close, {message.from_user.id}") ]] update.effective_message.reply_photo( photo=img, caption=caption, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=False) progress_message.delete() @run_async def upcoming(update: Update, context: CallbackContext): jikan = jikanpy.jikan.Jikan() upcoming = jikan.top('anime', page=1, subtype="upcoming") upcoming_list = [entry['title'] for entry in upcoming['top']] upcoming_message = "" for entry_num in range(len(upcoming_list)): if entry_num == 10: break upcoming_message += f"{entry_num + 1}. {upcoming_list[entry_num]}\n" update.effective_message.reply_text(upcoming_message) def button(update: Update, context: CallbackContext): bot = context.bot query = update.callback_query message = query.message data = query.data.split(", ") query_type = data[0] original_user_id = int(data[1]) user_and_admin_list = [original_user_id, OWNER_ID] + DRAGONS + DEV_USERS bot.answer_callback_query(query.id) if query_type == "anime_close": if query.from_user.id in user_and_admin_list: message.delete() else: query.answer("You are not allowed to use this.") elif query_type in ('anime_anime', 'anime_manga'): mal_id = data[2] if query.from_user.id == original_user_id: message.delete() progress_message = bot.sendMessage(message.chat.id, "Searching.... ") caption, buttons, image = get_anime_manga(mal_id, query_type, original_user_id) bot.sendPhoto( message.chat.id, photo=image, caption=caption, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=False) progress_message.delete() else: query.answer("You are not allowed to use this.") def site_search(update: Update, context: CallbackContext, site: str): message = update.effective_message args = message.text.strip().split(" ", 1) more_results = True try: search_query = args[1] except IndexError: message.reply_text("Give something to search") return if site == "kaizoku": search_url = f"https://animekaizoku.com/?s={search_query}" html_text = requests.get(search_url).text soup = bs4.BeautifulSoup(html_text, "html.parser") search_result = soup.find_all("h2", {'class': "post-title"}) if search_result: result = f"<b>Search results for</b> <code>{html.escape(search_query)}</code> <b>on</b> <code>AnimeKaizoku</code>: \n" for entry in search_result: post_link = "https://animekaizoku.com/" + entry.a['href'] post_name = html.escape(entry.text) result += f"• <a href='{post_link}'>{post_name}</a>\n" else: more_results = False result = f"<b>No result found for</b> <code>{html.escape(search_query)}</code> <b>on</b> <code>AnimeKaizoku</code>" elif site == "kayo": search_url = f"https://animekayo.com/?s={search_query}" html_text = requests.get(search_url).text soup = bs4.BeautifulSoup(html_text, "html.parser") search_result = soup.find_all("h2", {'class': "title"}) result = f"<b>Search results for</b> <code>{html.escape(search_query)}</code> <b>on</b> <code>AnimeKayo</code>: \n" for entry in search_result: if entry.text.strip() == "Nothing Found": result = f"<b>No result found for</b> <code>{html.escape(search_query)}</code> <b>on</b> <code>AnimeKayo</code>" more_results = False break post_link = entry.a['href'] post_name = html.escape(entry.text.strip()) result += f"• <a href='{post_link}'>{post_name}</a>\n" buttons = [[InlineKeyboardButton("See all results", url=search_url)]] if more_results: message.reply_text( result, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) else: message.reply_text( result, parse_mode=ParseMode.HTML, disable_web_page_preview=True) @run_async def kaizoku(update: Update, context: CallbackContext): site_search(update, context, "kaizoku") @run_async def kayo(update: Update, context: CallbackContext): site_search(update, context, "kayo") __help__ = """ Get information about anime, manga or characters from [AniList](anilist.co). *Available commands:* • `/anime <anime>`*:* returns information about the anime. • `/character <character>`*:* returns information about the character. • `/manga <manga>`*:* returns information about the manga. • `/user <user>`*:* returns information about a MyAnimeList user. • `/upcoming`*:* returns a list of new anime in the upcoming seasons. • `/kaizoku <anime>`*:* search an anime on animekaizoku.com • `/kayo <anime>`*:* search an anime on animekayo.com • `/airing <anime>`*:* returns anime airing info. • /whatanime - reply to gif or video """ ANIME_HANDLER = DisableAbleCommandHandler("anime", anime) AIRING_HANDLER = DisableAbleCommandHandler("airing", airing) CHARACTER_HANDLER = DisableAbleCommandHandler("character", character) MANGA_HANDLER = DisableAbleCommandHandler("manga", manga) USER_HANDLER = DisableAbleCommandHandler("user", user) UPCOMING_HANDLER = DisableAbleCommandHandler("upcoming", upcoming) KAIZOKU_SEARCH_HANDLER = DisableAbleCommandHandler("kaizoku", kaizoku) KAYO_SEARCH_HANDLER = DisableAbleCommandHandler("kayo", kayo) BUTTON_HANDLER = CallbackQueryHandler(button, pattern='anime_.*') dispatcher.add_handler(BUTTON_HANDLER) dispatcher.add_handler(ANIME_HANDLER) dispatcher.add_handler(CHARACTER_HANDLER) dispatcher.add_handler(MANGA_HANDLER) dispatcher.add_handler(AIRING_HANDLER) dispatcher.add_handler(USER_HANDLER) dispatcher.add_handler(KAIZOKU_SEARCH_HANDLER) dispatcher.add_handler(KAYO_SEARCH_HANDLER) dispatcher.add_handler(UPCOMING_HANDLER) __mod_name__ = "Anime" __command_list__ = [ "anime", "manga", "character", "user", "upcoming", "kaizoku", "airing", "kayo" ] __handlers__ = [ ANIME_HANDLER, CHARACTER_HANDLER, MANGA_HANDLER, USER_HANDLER, UPCOMING_HANDLER, KAIZOKU_SEARCH_HANDLER, KAYO_SEARCH_HANDLER, BUTTON_HANDLER, AIRING_HANDLER ]
import datetime import html import textwrap import bs4 import jikanpy import requests from innexiaBot import DEV_USERS, OWNER_ID, DRAGONS, dispatcher from innexiaBot.modules.disable import DisableAbleCommandHandler from telegram import (InlineKeyboardButton, InlineKeyboardMarkup, ParseMode, Update) from telegram.ext import CallbackContext, CallbackQueryHandler, run_async info_btn = "More Information" kaizoku_btn = "Kaizoku ☠️" kayo_btn = "Kayo 🏴‍☠️" prequel_btn = "⬅️ Prequel" sequel_btn = "Sequel ➡️" close_btn = "Close ❌" def shorten(description, info='anilist.co'): msg = "" if len(description) > 700: description = description[0:500] + '....' msg += f"\n*Description*: _{description}_[Read More]({info})" else: msg += f"\n*Description*:_{description}_" return msg #time formatter from uniborg def t(milliseconds: int) -> str: """Inputs time in milliseconds, to get beautified time, as string""" seconds, milliseconds = divmod(int(milliseconds), 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ((str(days) + " Days, ") if days else "") + \ ((str(hours) + " Hours, ") if hours else "") + \ ((str(minutes) + " Minutes, ") if minutes else "") + \ ((str(seconds) + " Seconds, ") if seconds else "") + \ ((str(milliseconds) + " ms, ") if milliseconds else "") return tmp[:-2] airing_query = ''' query ($id: Int,$search: String) { Media (id: $id, type: ANIME,search: $search) { id episodes title { romaji english native } nextAiringEpisode { airingAt timeUntilAiring episode } } } ''' fav_query = """ query ($id: Int) { Media (id: $id, type: ANIME) { id title { romaji english native } } } """ anime_query = ''' query ($id: Int,$search: String) { Media (id: $id, type: ANIME,search: $search) { id title { romaji english native } description (asHtml: false) startDate{ year } episodes season type format status duration siteUrl studios{ nodes{ name } } trailer{ id site thumbnail } averageScore genres bannerImage } } ''' character_query = """ query ($query: String) { Character (search: $query) { id name { first last full } siteUrl image { large } description } } """ manga_query = """ query ($id: Int,$search: String) { Media (id: $id, type: MANGA,search: $search) { id title { romaji english native } description (asHtml: false) startDate{ year } type format status siteUrl averageScore genres bannerImage } } """ url = 'https://graphql.anilist.co' @run_async def airing(update: Update, context: CallbackContext): message = update.effective_message search_str = message.text.split(' ', 1) if len(search_str) == 1: update.effective_message.reply_text( 'Tell Anime Name :) ( /airing <anime name>)') return variables = {'search': search_str[1]} response = requests.post( url, json={ 'query': airing_query, 'variables': variables }).json()['data']['Media'] msg = f"*Name*: *{response['title']['romaji']}*(`{response['title']['native']}`)\n*ID*: `{response['id']}`" if response['nextAiringEpisode']: time = response['nextAiringEpisode']['timeUntilAiring'] * 1000 time = t(time) msg += f"\n*Episode*: `{response['nextAiringEpisode']['episode']}`\n*Airing In*: `{time}`" else: msg += f"\n*Episode*:{response['episodes']}\n*Status*: `N/A`" update.effective_message.reply_text(msg, parse_mode=ParseMode.MARKDOWN) @run_async def anime(update: Update, context: CallbackContext): message = update.effective_message search = message.text.split(' ', 1) if len(search) == 1: update.effective_message.reply_text('Format : /anime < anime name >') return else: search = search[1] variables = {'search': search} json = requests.post( url, json={ 'query': anime_query, 'variables': variables }).json() if 'errors' in json.keys(): update.effective_message.reply_text('Anime not found') return if json: json = json['data']['Media'] msg = f"*{json['title']['romaji']}*(`{json['title']['native']}`)\n*Type*: {json['format']}\n*Status*: {json['status']}\n*Episodes*: {json.get('episodes', 'N/A')}\n*Duration*: {json.get('duration', 'N/A')} Per Ep.\n*Score*: {json['averageScore']}\n*Genres*: `" for x in json['genres']: msg += f"{x}, " msg = msg[:-2] + '`\n' msg += "*Studios*: `" for x in json['studios']['nodes']: msg += f"{x['name']}, " msg = msg[:-2] + '`\n' info = json.get('siteUrl') trailer = json.get('trailer', None) anime_id = json['id'] if trailer: trailer_id = trailer.get('id', None) site = trailer.get('site', None) if site == "youtube": trailer = 'https://youtu.be/' + trailer_id description = json.get('description', 'N/A').replace('<i>', '').replace( '</i>', '').replace('<br>', '') msg += shorten(description, info) image = json.get('bannerImage', None) if trailer: buttons = [[ InlineKeyboardButton("More Info", url=info), InlineKeyboardButton("Trailer 🎬", url=trailer) ]] else: buttons = [[InlineKeyboardButton("More Info", url=info)]] if image: try: update.effective_message.reply_photo( photo=image, caption=msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) except: msg += f" [〽️]({image})" update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) else: update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) @run_async def character(update: Update, context: CallbackContext): message = update.effective_message search = message.text.split(' ', 1) if len(search) == 1: update.effective_message.reply_text( 'Format : /character < character name >') return search = search[1] variables = {'query': search} json = requests.post( url, json={ 'query': character_query, 'variables': variables }).json() if 'errors' in json.keys(): update.effective_message.reply_text('Character not found') return if json: json = json['data']['Character'] msg = f"*{json.get('name').get('full')}*(`{json.get('name').get('native')}`)\n" description = f"{json['description']}" site_url = json.get('siteUrl') msg += shorten(description, site_url) image = json.get('image', None) if image: image = image.get('large') update.effective_message.reply_photo( photo=image, caption=msg.replace('<b>', '</b>'), parse_mode=ParseMode.MARKDOWN) else: update.effective_message.reply_text( msg.replace('<b>', '</b>'), parse_mode=ParseMode.MARKDOWN) @run_async def manga(update: Update, context: CallbackContext): message = update.effective_message search = message.text.split(' ', 1) if len(search) == 1: update.effective_message.reply_text('Format : /manga < manga name >') return search = search[1] variables = {'search': search} json = requests.post( url, json={ 'query': manga_query, 'variables': variables }).json() msg = '' if 'errors' in json.keys(): update.effective_message.reply_text('Manga not found') return if json: json = json['data']['Media'] title, title_native = json['title'].get('romaji', False), json['title'].get( 'native', False) start_date, status, score = json['startDate'].get( 'year', False), json.get('status', False), json.get('averageScore', False) if title: msg += f"*{title}*" if title_native: msg += f"(`{title_native}`)" if start_date: msg += f"\n*Start Date* - `{start_date}`" if status: msg += f"\n*Status* - `{status}`" if score: msg += f"\n*Score* - `{score}`" msg += '\n*Genres* - ' for x in json.get('genres', []): msg += f"{x}, " msg = msg[:-2] info = json['siteUrl'] buttons = [[InlineKeyboardButton("More Info", url=info)]] image = json.get("bannerImage", False) msg += f"_{json.get('description', None)}_" if image: try: update.effective_message.reply_photo( photo=image, caption=msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) except: msg += f" [〽️]({image})" update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) else: update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) @run_async def user(update: Update, context: CallbackContext): message = update.effective_message args = message.text.strip().split(" ", 1) try: search_query = args[1] except: if message.reply_to_message: search_query = message.reply_to_message.text else: update.effective_message.reply_text("Format : /user <username>") return jikan = jikanpy.jikan.Jikan() try: user = jikan.user(search_query) except jikanpy.APIException: update.effective_message.reply_text("Username not found.") return progress_message = update.effective_message.reply_text("Searching.... ") date_format = "%Y-%m-%d" if user['image_url'] is None: img = "https://cdn.myanimelist.net/images/questionmark_50.gif" else: img = user['image_url'] try: user_birthday = datetime.datetime.fromisoformat(user['birthday']) user_birthday_formatted = user_birthday.strftime(date_format) except: user_birthday_formatted = "Unknown" user_joined_date = datetime.datetime.fromisoformat(user['joined']) user_joined_date_formatted = user_joined_date.strftime(date_format) for entity in user: if user[entity] is None: user[entity] = "Unknown" about = user['about'].split(" ", 60) try: about.pop(60) except IndexError: pass about_string = ' '.join(about) about_string = about_string.replace("<br>", "").strip().replace("\r\n", "\n") caption = "" caption += textwrap.dedent(f""" *Username*: [{user['username']}]({user['url']}) *Gender*: `{user['gender']}` *Birthday*: `{user_birthday_formatted}` *Joined*: `{user_joined_date_formatted}` *Days wasted watching anime*: `{user['anime_stats']['days_watched']}` *Days wasted reading manga*: `{user['manga_stats']['days_read']}` """) caption += f"*About*: {about_string}" buttons = [[InlineKeyboardButton(info_btn, url=user['url'])], [ InlineKeyboardButton( close_btn, callback_data=f"anime_close, {message.from_user.id}") ]] update.effective_message.reply_photo( photo=img, caption=caption, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=False) progress_message.delete() @run_async def upcoming(update: Update, context: CallbackContext): jikan = jikanpy.jikan.Jikan() upcoming = jikan.top('anime', page=1, subtype="upcoming") upcoming_list = [entry['title'] for entry in upcoming['top']] upcoming_message = "" for entry_num in range(len(upcoming_list)): if entry_num == 10: break upcoming_message += f"{entry_num + 1}. {upcoming_list[entry_num]}\n" update.effective_message.reply_text(upcoming_message) def button(update: Update, context: CallbackContext): bot = context.bot query = update.callback_query message = query.message data = query.data.split(", ") query_type = data[0] original_user_id = int(data[1]) user_and_admin_list = [original_user_id, OWNER_ID] + DRAGONS + DEV_USERS bot.answer_callback_query(query.id) if query_type == "anime_close": if query.from_user.id in user_and_admin_list: message.delete() else: query.answer("You are not allowed to use this.") elif query_type in ('anime_anime', 'anime_manga'): mal_id = data[2] if query.from_user.id == original_user_id: message.delete() progress_message = bot.sendMessage(message.chat.id, "Searching.... ") caption, buttons, image = get_anime_manga(mal_id, query_type, original_user_id) bot.sendPhoto( message.chat.id, photo=image, caption=caption, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=False) progress_message.delete() else: query.answer("You are not allowed to use this.") def site_search(update: Update, context: CallbackContext, site: str): message = update.effective_message args = message.text.strip().split(" ", 1) more_results = True try: search_query = args[1] except IndexError: message.reply_text("Give something to search") return if site == "kaizoku": search_url = f"https://animekaizoku.com/?s={search_query}" html_text = requests.get(search_url).text soup = bs4.BeautifulSoup(html_text, "html.parser") search_result = soup.find_all("h2", {'class': "post-title"}) if search_result: result = f"<b>Search results for</b> <code>{html.escape(search_query)}</code> <b>on</b> <code>AnimeKaizoku</code>: \n" for entry in search_result: post_link = "https://animekaizoku.com/" + entry.a['href'] post_name = html.escape(entry.text) result += f"• <a href='{post_link}'>{post_name}</a>\n" else: more_results = False result = f"<b>No result found for</b> <code>{html.escape(search_query)}</code> <b>on</b> <code>AnimeKaizoku</code>" elif site == "kayo": search_url = f"https://animekayo.com/?s={search_query}" html_text = requests.get(search_url).text soup = bs4.BeautifulSoup(html_text, "html.parser") search_result = soup.find_all("h2", {'class': "title"}) result = f"<b>Search results for</b> <code>{html.escape(search_query)}</code> <b>on</b> <code>AnimeKayo</code>: \n" for entry in search_result: if entry.text.strip() == "Nothing Found": result = f"<b>No result found for</b> <code>{html.escape(search_query)}</code> <b>on</b> <code>AnimeKayo</code>" more_results = False break post_link = entry.a['href'] post_name = html.escape(entry.text.strip()) result += f"• <a href='{post_link}'>{post_name}</a>\n" buttons = [[InlineKeyboardButton("See all results", url=search_url)]] if more_results: message.reply_text( result, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) else: message.reply_text( result, parse_mode=ParseMode.HTML, disable_web_page_preview=True) @run_async def kaizoku(update: Update, context: CallbackContext): site_search(update, context, "kaizoku") @run_async def kayo(update: Update, context: CallbackContext): site_search(update, context, "kayo") __help__ = """ Get information about anime, manga or characters from [AniList](anilist.co). *Available commands:* • `/anime <anime>`*:* returns information about the anime. • `/character <character>`*:* returns information about the character. • `/manga <manga>`*:* returns information about the manga. • `/user <user>`*:* returns information about a MyAnimeList user. • `/upcoming`*:* returns a list of new anime in the upcoming seasons. • `/kaizoku <anime>`*:* search an anime on animekaizoku.com • `/kayo <anime>`*:* search an anime on animekayo.com • `/airing <anime>`*:* returns anime airing info. • /whatanime - reply to gif or video """ ANIME_HANDLER = DisableAbleCommandHandler("anime", anime) AIRING_HANDLER = DisableAbleCommandHandler("airing", airing) CHARACTER_HANDLER = DisableAbleCommandHandler("character", character) MANGA_HANDLER = DisableAbleCommandHandler("manga", manga) USER_HANDLER = DisableAbleCommandHandler("user", user) UPCOMING_HANDLER = DisableAbleCommandHandler("upcoming", upcoming) KAIZOKU_SEARCH_HANDLER = DisableAbleCommandHandler("kaizoku", kaizoku) KAYO_SEARCH_HANDLER = DisableAbleCommandHandler("kayo", kayo) BUTTON_HANDLER = CallbackQueryHandler(button, pattern='anime_.*') dispatcher.add_handler(BUTTON_HANDLER) dispatcher.add_handler(ANIME_HANDLER) dispatcher.add_handler(CHARACTER_HANDLER) dispatcher.add_handler(MANGA_HANDLER) dispatcher.add_handler(AIRING_HANDLER) dispatcher.add_handler(USER_HANDLER) dispatcher.add_handler(KAIZOKU_SEARCH_HANDLER) dispatcher.add_handler(KAYO_SEARCH_HANDLER) dispatcher.add_handler(UPCOMING_HANDLER) __mod_name__ = "Anime" __command_list__ = [ "anime", "manga", "character", "user", "upcoming", "kaizoku", "airing", "kayo" ] __handlers__ = [ ANIME_HANDLER, CHARACTER_HANDLER, MANGA_HANDLER, USER_HANDLER, UPCOMING_HANDLER, KAIZOKU_SEARCH_HANDLER, KAYO_SEARCH_HANDLER, BUTTON_HANDLER, AIRING_HANDLER ]
import os, sys import unittest import tempfile from openmmforcefields.utils import get_data_filename from openmmforcefields.generators import GAFFTemplateGenerator from openmmforcefields.generators import SMIRNOFFTemplateGenerator import logging _logger = logging.getLogger("openmmforcefields.tests.test_template_generators") CI = ('TRAVIS' in os.environ) ################################################################################ # Tests ################################################################################ class TestGAFFTemplateGenerator(unittest.TestCase): TEMPLATE_GENERATOR = GAFFTemplateGenerator amber_forcefields = ['amber/protein.ff14SB.xml', 'amber/tip3p_standard.xml', 'amber/tip3p_HFE_multivalent.xml'] def filter_molecules(self, molecules): """ Filter molecules to speed up tests, especially on travis. Parameters ---------- molecules : list of openff.toolkit.topology.Molecule The input list of molecules to be filtered Returns ------- molecules : list of openff.toolkit.topology.Molecule The filtered list of molecules to be filtered """ # TODO: Eliminate molecules without fully-specified stereochemistry # Select some small molecules for fast testing MAX_ATOMS = 40 molecules = [ molecule for molecule in molecules if molecule.n_atoms < MAX_ATOMS ] # Cut down number of tests for travis import os MAX_MOLECULES = 10 if not CI else 3 molecules = molecules[:MAX_MOLECULES] return molecules def setUp(self): # TODO: Harmonize with test_system_generator.py infrastructure # Read test molecules from openff.toolkit.topology import Molecule filename = get_data_filename("minidrugbank/MiniDrugBank-without-unspecified-stereochemistry.sdf") molecules = Molecule.from_file(filename, allow_undefined_stereo=True) # Filter molecules as appropriate self.molecules = self.filter_molecules(molecules) # Suppress DEBUG logging from various packages import logging for name in ['parmed', 'matplotlib']: logging.getLogger(name).setLevel(logging.WARNING) def test_version(self): """Test version""" for forcefield in GAFFTemplateGenerator.INSTALLED_FORCEFIELDS: generator = GAFFTemplateGenerator(forcefield=forcefield) import re result = re.match('^gaff-(?P<major_version>\d+)\.(?P<minor_version>\d+)$', forcefield) assert generator.forcefield == forcefield assert generator.gaff_version == result['major_version'] + '.' + result['minor_version'] assert generator.gaff_major_version == result['major_version'] assert generator.gaff_minor_version == result['minor_version'] assert generator.gaff_dat_filename.endswith(forcefield + '.dat') assert os.path.exists(generator.gaff_dat_filename) assert generator.gaff_xml_filename.endswith(forcefield + '.xml') assert os.path.exists(generator.gaff_xml_filename) def test_create(self): """Test template generator creation""" # Create an empty generator generator = self.TEMPLATE_GENERATOR() # Create a generator that knows about a few molecules generator = self.TEMPLATE_GENERATOR(molecules=self.molecules) # Create a generator that also has a database cache with tempfile.TemporaryDirectory() as tmpdirname: cache = os.path.join(tmpdirname, 'db.json') # Create a new database file generator = self.TEMPLATE_GENERATOR(molecules=self.molecules, cache=cache) del generator # Reopen it (with cache still empty) generator = self.TEMPLATE_GENERATOR(molecules=self.molecules, cache=cache) del generator def test_add_molecules(self): """Test that molecules can be added to template generator after its creation""" # Create a generator that does not know about any molecules generator = self.TEMPLATE_GENERATOR() # Create a ForceField from openmm.app import ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Check that parameterizing a molecule fails molecule = self.molecules[0] from openmm.app import NoCutoff try: # This should fail with an exception openmm_topology = molecule.to_topology().to_openmm() system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) except ValueError as e: # Exception 'No template found...' is expected assert str(e).startswith('No template found') # Now add the molecule to the generator and ensure parameterization passes generator.add_molecules(molecule) openmm_topology = molecule.to_topology().to_openmm() try: system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) except Exception as e: print(forcefield._atomTypes.keys()) from openmm.app import PDBFile PDBFile.writeFile(openmm_topology, molecule.conformers[0]) raise e assert system.getNumParticles() == molecule.n_atoms # Add multiple molecules, including repeats generator.add_molecules(self.molecules) # Ensure all molecules can be parameterized for molecule in self.molecules: openmm_topology = molecule.to_topology().to_openmm() system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert system.getNumParticles() == molecule.n_atoms def charges_from_system(self, system): """Extract dimensionless partial charges from a System Parameters ---------- system : openmm.System The System from which partial charges are to be extracted Returns ------- charges : np.array of shape [n_particles] The dimensionless partial charges (implicitly in units of elementary_charge) """ import numpy as np from openmm import unit system_charges = list() forces = { force.__class__.__name__ : force for force in system.getForces() } for particle_index in range(system.getNumParticles()): charge, sigma, epsilon = forces['NonbondedForce'].getParticleParameters(particle_index) system_charges.append(charge / unit.elementary_charge) system_charges = np.array(system_charges) return system_charges def charges_are_equal(self, system, molecule): """Return True if partial charges are equal Parameters ---------- system : openmm.System The System from which partial charges are to be extracted molecule : openmmforcefield.topology.Molecule The Molecule from which partial charges are to be extracted Returns ------- result : bool True if the partial charges are equal, False if not """ assert system.getNumParticles() == molecule.n_particles system_charges = self.charges_from_system(system) from openmm import unit molecule_charges = molecule.partial_charges / unit.elementary_charge import numpy as np result = np.allclose(system_charges, molecule_charges) if not result: _logger.debug('Charges are not equal') _logger.debug(f'system charges : {system_charges}') _logger.debug(f'molecule charges: {molecule_charges}') return result def test_charge(self): """Test that charges are nonzero after charging if the molecule does not contain user charges""" # Create a generator that does not know about any molecules generator = self.TEMPLATE_GENERATOR() # Create a ForceField from openmm.app import ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Check that parameterizing a molecule using user-provided charges produces expected charges import numpy as np from openmm import unit molecule = self.molecules[0] # Ensure partial charges are initially zero assert (molecule.partial_charges is None) or np.all(molecule.partial_charges / unit.elementary_charge == 0) # Add the molecule generator.add_molecules(molecule) # Create the System from openmm.app import NoCutoff openmm_topology = molecule.to_topology().to_openmm() system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) # Ensure charges are no longer zero assert not np.all(self.charges_from_system(system) == 0), "System has zero charges despite molecule not being charged" def test_charge_from_molecules(self): """Test that user-specified partial charges are used if requested""" # Create a generator that does not know about any molecules generator = self.TEMPLATE_GENERATOR() # Create a ForceField from openmm.app import ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Check that parameterizing a molecule using user-provided charges produces expected charges import numpy as np from openmm import unit molecule = self.molecules[0] charges = np.random.random([molecule.n_particles]) total_charge = molecule.total_charge if type(total_charge) is unit.Quantity: # Handle openforcefield >= 0.7.0 total_charge /= unit.elementary_charge charges += (total_charge - charges.sum()) / molecule.n_particles molecule.partial_charges = unit.Quantity(charges, unit.elementary_charge) assert (molecule.partial_charges is not None) and not np.all(molecule.partial_charges / unit.elementary_charge == 0) # Add the molecule generator.add_molecules(molecule) # Create the System from openmm.app import NoCutoff openmm_topology = molecule.to_topology().to_openmm() system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert self.charges_are_equal(system, molecule) def test_debug_ffxml(self): """Test that debug ffxml file is created when requested""" with tempfile.TemporaryDirectory() as tmpdirname: debug_ffxml_filename = os.path.join(tmpdirname, 'molecule.ffxml') cache = os.path.join(tmpdirname, 'db.json') # Create a generator that only knows about one molecule molecule = self.molecules[0] generator = self.TEMPLATE_GENERATOR(molecules=molecule, cache=cache) # Create a ForceField from openmm.app import ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Ensure no file is created from openmm.app import NoCutoff openmm_topology = molecule.to_topology().to_openmm() system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert not os.path.exists(debug_ffxml_filename) # Enable debug file output creation forcefield = ForceField() forcefield.registerTemplateGenerator(generator.generator) generator.debug_ffxml_filename = debug_ffxml_filename # Ensure that an ffxml file is created system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert os.path.exists(debug_ffxml_filename) # Ensure we can use that file to create a new force field forcefield_from_ffxml = ForceField() if hasattr(generator, 'gaff_xml_filename'): forcefield_from_ffxml.loadFile(generator.gaff_xml_filename) forcefield_from_ffxml.loadFile(debug_ffxml_filename) system2 = forcefield_from_ffxml.createSystem(openmm_topology, nonbondedMethod=NoCutoff) # TODO: Test that systems are equivalent assert system.getNumParticles() == system2.getNumParticles() def test_cache(self): """Test template generator cache capability""" from openmm.app import ForceField, NoCutoff with tempfile.TemporaryDirectory() as tmpdirname: # Create a generator that also has a database cache cache = os.path.join(tmpdirname, 'db.json') generator = self.TEMPLATE_GENERATOR(molecules=self.molecules, cache=cache) # Create a ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Parameterize the molecules for molecule in self.molecules: openmm_topology = molecule.to_topology().to_openmm() forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) # Check database contents def check_cache(generator, n_expected): """ Check database contains number of expected records Parameters ---------- generator : SmallMoleculeTemplateGenerator The generator whose cache should be examined n_expected : int Number of expected records """ from tinydb import TinyDB db = TinyDB(generator._cache) table = db.table(generator._database_table_name) db_entries = table.all() db.close() n_entries = len(db_entries) assert (n_entries == n_expected), \ "Expected {} entries but database has {}\n db contents: {}".format(n_expected, n_entries, db_entries) check_cache(generator, len(self.molecules)) # Clean up, forcing closure of database del forcefield, generator # Create a generator that also uses the database cache but has no molecules print('Creating new generator with just cache...') generator = self.TEMPLATE_GENERATOR(cache=cache) # Check database still contains the molecules we expect check_cache(generator, len(self.molecules)) # Create a ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Parameterize the molecules; this should succeed for molecule in self.molecules: openmm_topology = molecule.to_topology().to_openmm() forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) def test_add_solvent(self): """Test using openmm.app.Modeller to add solvent to a small molecule parameterized by template generator""" # Select a molecule to add solvent around from openmm.app import NoCutoff, Modeller from openmm import unit molecule = self.molecules[0] openmm_topology = molecule.to_topology().to_openmm() openmm_positions = molecule.conformers[0] # Try adding solvent without residue template generator; this will fail from openmm.app import ForceField forcefield = ForceField('tip3p.xml') # Add solvent to a system containing a small molecule modeller = Modeller(openmm_topology, openmm_positions) try: modeller.addSolvent(forcefield, model='tip3p', padding=6.0*unit.angstroms) except ValueError as e: pass # Create a generator that knows about a few molecules generator = self.TEMPLATE_GENERATOR(molecules=self.molecules) # Add to the forcefield object forcefield.registerTemplateGenerator(generator.generator) # Add solvent to a system containing a small molecule # This should succeed modeller.addSolvent(forcefield, model='tip3p', padding=6.0*unit.angstroms) def test_jacs_ligands(self): """Use template generator to parameterize the Schrodinger JACS set of ligands""" from openmm.app import ForceField, NoCutoff jacs_systems = { #'bace' : { 'prefix' : 'Bace' }, #'cdk2' : { 'prefix' : 'CDK2' }, 'jnk1' : { 'prefix' : 'Jnk1' }, 'mcl1' : { 'prefix' : 'MCL1' }, #'p38' : { 'prefix' : 'p38' }, 'ptp1b' : { 'prefix' : 'PTP1B' }, 'thrombin' : { 'prefix' : 'Thrombin' }, #'tyk2' : { 'prefix' : 'Tyk2' }, } for system_name in jacs_systems: prefix = jacs_systems[system_name]['prefix'] # Load molecules ligand_sdf_filename = get_data_filename(os.path.join('perses_jacs_systems', system_name, prefix + '_ligands.sdf')) print(f'Reading molecules from {ligand_sdf_filename} ...') from openff.toolkit.topology import Molecule molecules = Molecule.from_file(ligand_sdf_filename, allow_undefined_stereo=True) # Ensure this is a list try: nmolecules = len(molecules) except TypeError: molecules = [molecules] print(f'Read {len(molecules)} molecules from {ligand_sdf_filename}') #molecules = self.filter_molecules(molecules) MAX_MOLECULES = len(molecules) if not CI else 3 molecules = molecules[:MAX_MOLECULES] print(f'{len(molecules)} molecules remain after filtering') # Create template generator with local cache cache = os.path.join(get_data_filename(os.path.join('perses_jacs_systems', system_name)), 'cache.json') generator = self.TEMPLATE_GENERATOR(molecules=molecules, cache=cache) # Create a ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Parameterize all molecules print(f'Caching all molecules for {system_name} at {cache} ...') n_success = 0 n_failure = 0 for molecule in molecules: openmm_topology = molecule.to_topology().to_openmm() try: forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) n_success += 1 except Exception as e: n_failure += 1 print(e) print(f'{n_failure}/{n_success+n_failure} ligands failed to parameterize for {system_name}') def test_jacs_complexes(self): """Use template generator to parameterize the Schrodinger JACS set of complexes""" # TODO: Uncomment working systems when we have cleaned up the input files jacs_systems = { #'bace' : { 'prefix' : 'Bace' }, #'cdk2' : { 'prefix' : 'CDK2' }, #'jnk1' : { 'prefix' : 'Jnk1' }, 'mcl1' : { 'prefix' : 'MCL1' }, #'p38' : { 'prefix' : 'p38' }, #'ptp1b' : { 'prefix' : 'PTP1B' }, #'thrombin' : { 'prefix' : 'Thrombin' }, #'tyk2' : { 'prefix' : 'Tyk2' }, } for system_name in jacs_systems: prefix = jacs_systems[system_name]['prefix'] # Read molecules ligand_sdf_filename = get_data_filename(os.path.join('perses_jacs_systems', system_name, prefix + '_ligands.sdf')) print(f'Reading molecules from {ligand_sdf_filename} ...') from openff.toolkit.topology import Molecule molecules = Molecule.from_file(ligand_sdf_filename, allow_undefined_stereo=True) try: nmolecules = len(molecules) except TypeError: molecules = [molecules] print(f'Read {len(molecules)} molecules from {ligand_sdf_filename}') # Read ParmEd Structures import parmed from openmm import unit protein_pdb_filename = get_data_filename(os.path.join('perses_jacs_systems', system_name, prefix + '_protein.pdb')) from openmm.app import PDBFile print(f'Reading protein from {protein_pdb_filename} ...') #protein_structure = parmed.load_file(protein_pdb_filename) # NOTE: This mis-interprets distorted geometry and sequentially-numbered residues that span chain breaks pdbfile = PDBFile(protein_pdb_filename) protein_structure = parmed.openmm.load_topology(pdbfile.topology, xyz=pdbfile.positions.value_in_unit(unit.angstroms)) ligand_structures = parmed.load_file(ligand_sdf_filename) try: nmolecules = len(ligand_structures) except TypeError: ligand_structures = [ligand_structures] assert len(ligand_structures) == len(molecules) # Filter molecules MAX_MOLECULES = 6 if not CI else 3 molecules = molecules[:MAX_MOLECULES] ligand_structures = ligand_structures[:MAX_MOLECULES] print(f'{len(molecules)} molecules remain after filtering') # Create complexes complex_structures = [ (protein_structure + ligand_structure) for ligand_structure in ligand_structures ] # Create template generator with local cache cache = os.path.join(get_data_filename(os.path.join('perses_jacs_systems', system_name)), 'cache.json') generator = self.TEMPLATE_GENERATOR(molecules=molecules, cache=cache) # Create a ForceField from openmm.app import ForceField forcefield = ForceField(*self.amber_forcefields) # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Parameterize all complexes print(f'Caching all molecules for {system_name} at {cache} ...') for ligand_index, complex_structure in enumerate(complex_structures): openmm_topology = complex_structure.topology molecule = molecules[ligand_index] # Delete hydrogens from terminal protein residues # TODO: Fix the input files so we don't need to do this from openmm import app modeller = app.Modeller(complex_structure.topology, complex_structure.positions) residues = [residue for residue in modeller.topology.residues() if residue.name != 'UNL'] termini_ids = [residues[0].id, residues[-1].id] #hs = [atom for atom in modeller.topology.atoms() if atom.element.symbol in ['H'] and atom.residue.name != 'UNL'] hs = [atom for atom in modeller.topology.atoms() if atom.element.symbol in ['H'] and atom.residue.id in termini_ids] modeller.delete(hs) from openmm.app import PDBFile modeller.addHydrogens(forcefield) # Parameterize protein:ligand complex in vacuum print(f' Parameterizing {system_name} : {molecule.to_smiles()} in vacuum...') from openmm.app import NoCutoff forcefield.createSystem(modeller.topology, nonbondedMethod=NoCutoff) # Parameterize protein:ligand complex in solvent print(f' Parameterizing {system_name} : {molecule.to_smiles()} in explicit solvent...') from openmm.app import PME modeller.addSolvent(forcefield, padding=0*unit.angstroms, ionicStrength=300*unit.millimolar) forcefield.createSystem(modeller.topology, nonbondedMethod=PME) def test_parameterize(self): """Test parameterizing molecules with template generator for all supported force fields""" # Test all supported small molecule force fields for small_molecule_forcefield in self.TEMPLATE_GENERATOR.INSTALLED_FORCEFIELDS: print(f'Testing {small_molecule_forcefield}') # Create a generator that knows about a few molecules # TODO: Should the generator also load the appropriate force field files into the ForceField object? generator = self.TEMPLATE_GENERATOR(molecules=self.molecules, forcefield=small_molecule_forcefield) # Check that we have loaded the right force field assert generator.forcefield == small_molecule_forcefield # Create a ForceField with the appropriate small molecule force field from openmm.app import ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Parameterize some molecules from openmm.app import NoCutoff from openmmforcefields.utils import Timer for molecule in self.molecules: openmm_topology = molecule.to_topology().to_openmm() with Timer() as t1: system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert system.getNumParticles() == molecule.n_atoms # Molecule should now be cached with Timer() as t2: system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert system.getNumParticles() == molecule.n_atoms assert (t2.interval() < t1.interval()) def test_multiple_registration(self): """Test registering the template generator with multiple force fields""" generator = self.TEMPLATE_GENERATOR(molecules=self.molecules) from openmm.app import ForceField NUM_FORCEFIELDS = 2 # number of force fields to test forcefields = list() for index in range(NUM_FORCEFIELDS): forcefield = ForceField() forcefield.registerTemplateGenerator(generator.generator) forcefields.append(forcefield) # Parameterize a molecule in each force field instance molecule = self.molecules[0] openmm_topology = molecule.to_topology().to_openmm() from openmm.app import NoCutoff for forcefield in forcefields: system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert system.getNumParticles() == molecule.n_atoms class TestSMIRNOFFTemplateGenerator(TestGAFFTemplateGenerator): TEMPLATE_GENERATOR = SMIRNOFFTemplateGenerator @staticmethod def compute_energy(system, positions): """Compute potential energy and Force components for an OpenMM system. Parameters ---------- system : openmm.System The System object positions : openmm.unit.Quantity of shape (nparticles,3) with units compatible with nanometers The positions for which energy is to be computed Returns ------- openmm_energy : dict of str : openmm.unit.Quantity openmm_energy['total'] is the total potential energy openmm_energy['components'][forcename] is the potential energy for the specified component force openmm_forces : dict of str : openmm.unit.Quantity openmm_forces['total'] is the total force openmm_forces['components'][forcename] is the force for the specified component force """ import copy system = copy.deepcopy(system) for index, force in enumerate(system.getForces()): force.setForceGroup(index) import openmm platform = openmm.Platform.getPlatformByName('Reference') integrator = openmm.VerletIntegrator(0.001) context = openmm.Context(system, integrator, platform) context.setPositions(positions) openmm_energy = { 'total' : context.getState(getEnergy=True).getPotentialEnergy(), 'components' : { system.getForce(index).__class__.__name__ : context.getState(getEnergy=True, groups=(1 << index)).getPotentialEnergy() for index in range(system.getNumForces()) }, } openmm_forces = { 'total' : context.getState(getForces=True).getForces(asNumpy=True), 'components' : { system.getForce(index).__class__.__name__ : context.getState(getForces=True, groups=(1 << index)).getForces(asNumpy=True) for index in range(system.getNumForces()) }, } del context, integrator return openmm_energy, openmm_forces @classmethod def compare_energies(cls, molecule, openmm_system, smirnoff_system): """Compare energies between Open Force Field Initiative and OpenMM ForceField objects The OpenMM System object created internally by the SMIRNOFFTemplateGenerator is used to avoid any issues with stochasticity of partial charges due to conformer generation. Parameters ---------- molecule : openff.toolkit.topology.Molecule The Molecule object to compare energy components (including positions) openmm_system : openmm.System System generated by OpenMM ForceField smirnoff_system : openmm.System System generated by SMIRNOFF engine """ # Compute energies openmm_energy, openmm_forces = cls.compute_energy(openmm_system, molecule.conformers[0]) smirnoff_energy, smirnoff_forces = cls.compute_energy(smirnoff_system, molecule.conformers[0]) from openmm import unit def write_xml(filename, system): import openmm with open(filename, 'w') as outfile: print(f'Writing {filename}...') outfile.write(openmm.XmlSerializer.serialize(system)) # Compare energies ENERGY_DEVIATION_TOLERANCE = 1.0e-2 * unit.kilocalories_per_mole delta = (openmm_energy['total'] - smirnoff_energy['total']) if abs(delta) > ENERGY_DEVIATION_TOLERANCE: # Show breakdown by components print('Energy components:') print(f"{"component":24} {"OpenMM (kcal/mol)":>20} {"SMIRNOFF (kcal/mol)":>20}") for key in openmm_energy['components'].keys(): openmm_component_energy = openmm_energy['components'][key] smirnoff_component_energy = smirnoff_energy['components'][key] print(f'{key:24} {(openmm_component_energy/unit.kilocalories_per_mole):20.3f} {(smirnoff_component_energy/unit.kilocalories_per_mole):20.3f} kcal/mol') print(f'{'TOTAL':24} {(openmm_energy['total']/unit.kilocalories_per_mole):20.3f} {(smirnoff_energy['total']/unit.kilocalories_per_mole):20.3f} kcal/mol') write_xml('system-smirnoff.xml', smirnoff_system) write_xml('openmm-smirnoff.xml', openmm_system) raise Exception(f'Energy deviation for {molecule.to_smiles()} ({delta/unit.kilocalories_per_mole} kcal/mol) exceeds threshold ({ENERGY_DEVIATION_TOLERANCE})') # Compare forces import numpy as np def norm(x): N = x.shape[0] return np.sqrt((1.0/N) * (x**2).sum()) def relative_deviation(x, y): if norm(y) > 0: return norm(x-y) / norm(y) else: return 0 RELATIVE_FORCE_DEVIATION_TOLERANCE = 1.0e-5 relative_force_deviation = relative_deviation(openmm_forces['total'], smirnoff_forces['total']) if relative_force_deviation > RELATIVE_FORCE_DEVIATION_TOLERANCE: # Show breakdown by components print('Force components:') print(f"{"component":24} {"relative deviation":>24}") for key in openmm_energy['components'].keys(): print(f"{key:24} {relative_deviation(openmm_forces["components"][key], smirnoff_forces["components"][key]):24.10f}") print(f'{'TOTAL':24} {relative_force_deviation:24.10f}') write_xml('system-smirnoff.xml', smirnoff_system) write_xml('openmm-smirnoff.xml', openmm_system) raise Exception(f'Relative force deviation for {molecule.to_smiles()} ({relative_force_deviation}) exceeds threshold ({RELATIVE_FORCE_DEVIATION_TOLERANCE})') def propagate_dynamics(self, molecule, system): """Run a few steps of dynamics to generate a perturbed configuration. Parameters ---------- molecule : openff.toolkit.topology.Molecule molecule.conformers[0] is used as initial positions system : openmm.System System object for dynamics Returns ------- new_molecule : openff.toolkit.topology.Molecule new_molecule.conformers[0] has updated positions """ # Run some dynamics import openmm from openmm import unit temperature = 300 * unit.kelvin collision_rate = 1.0 / unit.picoseconds timestep = 1.0 * unit.femtoseconds nsteps = 100 integrator = openmm.LangevinIntegrator(temperature, collision_rate, timestep) platform = openmm.Platform.getPlatformByName('Reference') context = openmm.Context(system, integrator, platform) context.setPositions(molecule.conformers[0]) integrator.step(nsteps) # Copy the molecule, storing new conformer import copy new_molecule = copy.deepcopy(molecule) new_molecule.conformers[0] = context.getState(getPositions=True).getPositions(asNumpy=True) # Clean up del context, integrator return new_molecule def test_INSTALLED_FORCEFIELDS(self): """Test INSTALLED_FORCEFIELDS contains expected force fields""" assert 'openff-1.1.0' in SMIRNOFFTemplateGenerator.INSTALLED_FORCEFIELDS assert 'smirnoff99Frosst-1.1.0' in SMIRNOFFTemplateGenerator.INSTALLED_FORCEFIELDS assert 'openff_unconstrained-1.1.0' not in SMIRNOFFTemplateGenerator.INSTALLED_FORCEFIELDS def test_energies(self): """Test potential energies match between openff-toolkit and OpenMM ForceField""" # DEBUG from openff.toolkit.topology import Molecule molecule = Molecule.from_smiles('C=O') molecule.generate_conformers(n_conformers=1) from openmm import unit molecule.conformers[0][0,0] += 0.1*unit.angstroms self.molecules.insert(0, molecule) # Test all supported SMIRNOFF force fields for small_molecule_forcefield in SMIRNOFFTemplateGenerator.INSTALLED_FORCEFIELDS: print(f'Testing energies for {small_molecule_forcefield}...') # Create a generator that knows about a few molecules # TODO: Should the generator also load the appropriate force field files into the ForceField object? generator = SMIRNOFFTemplateGenerator(molecules=self.molecules, forcefield=small_molecule_forcefield) # Create a ForceField import openmm openmm_forcefield = openmm.app.ForceField() # Register the template generator openmm_forcefield.registerTemplateGenerator(generator.generator) # Parameterize some molecules for molecule in self.molecules: # Create OpenMM System using OpenMM app from openmm.app import NoCutoff openmm_system = openmm_forcefield.createSystem(molecule.to_topology().to_openmm(), removeCMMotion=False, onbondedMethod=NoCutoff) # Retrieve System generated by the SMIRNOFF typing engine smirnoff_system = generator.get_openmm_system(molecule) # Compare energies and forces self.compare_energies(molecule, openmm_system, smirnoff_system) # Run some dynamics molecule = self.propagate_dynamics(molecule, smirnoff_system) # Compare energies again self.compare_energies(molecule, openmm_system, smirnoff_system) def test_partial_charges_are_none(self): """Test parameterizing a small molecule with `partial_charges=None` instead of zeros (happens frequently in OFFTK>=0.7.0)""" from openff.toolkit.topology import Molecule molecule = Molecule.from_smiles('C=O') molecule.generate_conformers(n_conformers=1) #molecule._partial_charges = None assert (molecule.partial_charges is None) or np.all(molecule.partial_charges / unit.elementary_charge == 0) # Test all supported SMIRNOFF force fields for small_molecule_forcefield in SMIRNOFFTemplateGenerator.INSTALLED_FORCEFIELDS: print(f'Testing energies for {small_molecule_forcefield}...') # Create a generator that knows about a few molecules # TODO: Should the generator also load the appropriate force field files into the ForceField object? generator = SMIRNOFFTemplateGenerator(molecules=[molecule], forcefield=small_molecule_forcefield) # Create a ForceField import openmm openmm_forcefield = openmm.app.ForceField() # Register the template generator openmm_forcefield.registerTemplateGenerator(generator.generator) # Create OpenMM System using OpenMM app from openmm.app import NoCutoff openmm_system = openmm_forcefield.createSystem(molecule.to_topology().to_openmm(), removeCMMotion=False, onbondedMethod=NoCutoff) smirnoff_system = generator.get_openmm_system(molecule) def test_version(self): """Test version""" for forcefield in SMIRNOFFTemplateGenerator.INSTALLED_FORCEFIELDS: generator = SMIRNOFFTemplateGenerator(forcefield=forcefield) assert generator.forcefield == forcefield assert generator.smirnoff_filename.endswith(forcefield + '.offxml') assert os.path.exists(generator.smirnoff_filename)
import os, sys import unittest import tempfile from openmmforcefields.utils import get_data_filename from openmmforcefields.generators import GAFFTemplateGenerator from openmmforcefields.generators import SMIRNOFFTemplateGenerator import logging _logger = logging.getLogger("openmmforcefields.tests.test_template_generators") CI = ('TRAVIS' in os.environ) ################################################################################ # Tests ################################################################################ class TestGAFFTemplateGenerator(unittest.TestCase): TEMPLATE_GENERATOR = GAFFTemplateGenerator amber_forcefields = ['amber/protein.ff14SB.xml', 'amber/tip3p_standard.xml', 'amber/tip3p_HFE_multivalent.xml'] def filter_molecules(self, molecules): """ Filter molecules to speed up tests, especially on travis. Parameters ---------- molecules : list of openff.toolkit.topology.Molecule The input list of molecules to be filtered Returns ------- molecules : list of openff.toolkit.topology.Molecule The filtered list of molecules to be filtered """ # TODO: Eliminate molecules without fully-specified stereochemistry # Select some small molecules for fast testing MAX_ATOMS = 40 molecules = [ molecule for molecule in molecules if molecule.n_atoms < MAX_ATOMS ] # Cut down number of tests for travis import os MAX_MOLECULES = 10 if not CI else 3 molecules = molecules[:MAX_MOLECULES] return molecules def setUp(self): # TODO: Harmonize with test_system_generator.py infrastructure # Read test molecules from openff.toolkit.topology import Molecule filename = get_data_filename("minidrugbank/MiniDrugBank-without-unspecified-stereochemistry.sdf") molecules = Molecule.from_file(filename, allow_undefined_stereo=True) # Filter molecules as appropriate self.molecules = self.filter_molecules(molecules) # Suppress DEBUG logging from various packages import logging for name in ['parmed', 'matplotlib']: logging.getLogger(name).setLevel(logging.WARNING) def test_version(self): """Test version""" for forcefield in GAFFTemplateGenerator.INSTALLED_FORCEFIELDS: generator = GAFFTemplateGenerator(forcefield=forcefield) import re result = re.match('^gaff-(?P<major_version>\d+)\.(?P<minor_version>\d+)$', forcefield) assert generator.forcefield == forcefield assert generator.gaff_version == result['major_version'] + '.' + result['minor_version'] assert generator.gaff_major_version == result['major_version'] assert generator.gaff_minor_version == result['minor_version'] assert generator.gaff_dat_filename.endswith(forcefield + '.dat') assert os.path.exists(generator.gaff_dat_filename) assert generator.gaff_xml_filename.endswith(forcefield + '.xml') assert os.path.exists(generator.gaff_xml_filename) def test_create(self): """Test template generator creation""" # Create an empty generator generator = self.TEMPLATE_GENERATOR() # Create a generator that knows about a few molecules generator = self.TEMPLATE_GENERATOR(molecules=self.molecules) # Create a generator that also has a database cache with tempfile.TemporaryDirectory() as tmpdirname: cache = os.path.join(tmpdirname, 'db.json') # Create a new database file generator = self.TEMPLATE_GENERATOR(molecules=self.molecules, cache=cache) del generator # Reopen it (with cache still empty) generator = self.TEMPLATE_GENERATOR(molecules=self.molecules, cache=cache) del generator def test_add_molecules(self): """Test that molecules can be added to template generator after its creation""" # Create a generator that does not know about any molecules generator = self.TEMPLATE_GENERATOR() # Create a ForceField from openmm.app import ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Check that parameterizing a molecule fails molecule = self.molecules[0] from openmm.app import NoCutoff try: # This should fail with an exception openmm_topology = molecule.to_topology().to_openmm() system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) except ValueError as e: # Exception 'No template found...' is expected assert str(e).startswith('No template found') # Now add the molecule to the generator and ensure parameterization passes generator.add_molecules(molecule) openmm_topology = molecule.to_topology().to_openmm() try: system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) except Exception as e: print(forcefield._atomTypes.keys()) from openmm.app import PDBFile PDBFile.writeFile(openmm_topology, molecule.conformers[0]) raise e assert system.getNumParticles() == molecule.n_atoms # Add multiple molecules, including repeats generator.add_molecules(self.molecules) # Ensure all molecules can be parameterized for molecule in self.molecules: openmm_topology = molecule.to_topology().to_openmm() system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert system.getNumParticles() == molecule.n_atoms def charges_from_system(self, system): """Extract dimensionless partial charges from a System Parameters ---------- system : openmm.System The System from which partial charges are to be extracted Returns ------- charges : np.array of shape [n_particles] The dimensionless partial charges (implicitly in units of elementary_charge) """ import numpy as np from openmm import unit system_charges = list() forces = { force.__class__.__name__ : force for force in system.getForces() } for particle_index in range(system.getNumParticles()): charge, sigma, epsilon = forces['NonbondedForce'].getParticleParameters(particle_index) system_charges.append(charge / unit.elementary_charge) system_charges = np.array(system_charges) return system_charges def charges_are_equal(self, system, molecule): """Return True if partial charges are equal Parameters ---------- system : openmm.System The System from which partial charges are to be extracted molecule : openmmforcefield.topology.Molecule The Molecule from which partial charges are to be extracted Returns ------- result : bool True if the partial charges are equal, False if not """ assert system.getNumParticles() == molecule.n_particles system_charges = self.charges_from_system(system) from openmm import unit molecule_charges = molecule.partial_charges / unit.elementary_charge import numpy as np result = np.allclose(system_charges, molecule_charges) if not result: _logger.debug('Charges are not equal') _logger.debug(f'system charges : {system_charges}') _logger.debug(f'molecule charges: {molecule_charges}') return result def test_charge(self): """Test that charges are nonzero after charging if the molecule does not contain user charges""" # Create a generator that does not know about any molecules generator = self.TEMPLATE_GENERATOR() # Create a ForceField from openmm.app import ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Check that parameterizing a molecule using user-provided charges produces expected charges import numpy as np from openmm import unit molecule = self.molecules[0] # Ensure partial charges are initially zero assert (molecule.partial_charges is None) or np.all(molecule.partial_charges / unit.elementary_charge == 0) # Add the molecule generator.add_molecules(molecule) # Create the System from openmm.app import NoCutoff openmm_topology = molecule.to_topology().to_openmm() system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) # Ensure charges are no longer zero assert not np.all(self.charges_from_system(system) == 0), "System has zero charges despite molecule not being charged" def test_charge_from_molecules(self): """Test that user-specified partial charges are used if requested""" # Create a generator that does not know about any molecules generator = self.TEMPLATE_GENERATOR() # Create a ForceField from openmm.app import ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Check that parameterizing a molecule using user-provided charges produces expected charges import numpy as np from openmm import unit molecule = self.molecules[0] charges = np.random.random([molecule.n_particles]) total_charge = molecule.total_charge if type(total_charge) is unit.Quantity: # Handle openforcefield >= 0.7.0 total_charge /= unit.elementary_charge charges += (total_charge - charges.sum()) / molecule.n_particles molecule.partial_charges = unit.Quantity(charges, unit.elementary_charge) assert (molecule.partial_charges is not None) and not np.all(molecule.partial_charges / unit.elementary_charge == 0) # Add the molecule generator.add_molecules(molecule) # Create the System from openmm.app import NoCutoff openmm_topology = molecule.to_topology().to_openmm() system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert self.charges_are_equal(system, molecule) def test_debug_ffxml(self): """Test that debug ffxml file is created when requested""" with tempfile.TemporaryDirectory() as tmpdirname: debug_ffxml_filename = os.path.join(tmpdirname, 'molecule.ffxml') cache = os.path.join(tmpdirname, 'db.json') # Create a generator that only knows about one molecule molecule = self.molecules[0] generator = self.TEMPLATE_GENERATOR(molecules=molecule, cache=cache) # Create a ForceField from openmm.app import ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Ensure no file is created from openmm.app import NoCutoff openmm_topology = molecule.to_topology().to_openmm() system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert not os.path.exists(debug_ffxml_filename) # Enable debug file output creation forcefield = ForceField() forcefield.registerTemplateGenerator(generator.generator) generator.debug_ffxml_filename = debug_ffxml_filename # Ensure that an ffxml file is created system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert os.path.exists(debug_ffxml_filename) # Ensure we can use that file to create a new force field forcefield_from_ffxml = ForceField() if hasattr(generator, 'gaff_xml_filename'): forcefield_from_ffxml.loadFile(generator.gaff_xml_filename) forcefield_from_ffxml.loadFile(debug_ffxml_filename) system2 = forcefield_from_ffxml.createSystem(openmm_topology, nonbondedMethod=NoCutoff) # TODO: Test that systems are equivalent assert system.getNumParticles() == system2.getNumParticles() def test_cache(self): """Test template generator cache capability""" from openmm.app import ForceField, NoCutoff with tempfile.TemporaryDirectory() as tmpdirname: # Create a generator that also has a database cache cache = os.path.join(tmpdirname, 'db.json') generator = self.TEMPLATE_GENERATOR(molecules=self.molecules, cache=cache) # Create a ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Parameterize the molecules for molecule in self.molecules: openmm_topology = molecule.to_topology().to_openmm() forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) # Check database contents def check_cache(generator, n_expected): """ Check database contains number of expected records Parameters ---------- generator : SmallMoleculeTemplateGenerator The generator whose cache should be examined n_expected : int Number of expected records """ from tinydb import TinyDB db = TinyDB(generator._cache) table = db.table(generator._database_table_name) db_entries = table.all() db.close() n_entries = len(db_entries) assert (n_entries == n_expected), \ "Expected {} entries but database has {}\n db contents: {}".format(n_expected, n_entries, db_entries) check_cache(generator, len(self.molecules)) # Clean up, forcing closure of database del forcefield, generator # Create a generator that also uses the database cache but has no molecules print('Creating new generator with just cache...') generator = self.TEMPLATE_GENERATOR(cache=cache) # Check database still contains the molecules we expect check_cache(generator, len(self.molecules)) # Create a ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Parameterize the molecules; this should succeed for molecule in self.molecules: openmm_topology = molecule.to_topology().to_openmm() forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) def test_add_solvent(self): """Test using openmm.app.Modeller to add solvent to a small molecule parameterized by template generator""" # Select a molecule to add solvent around from openmm.app import NoCutoff, Modeller from openmm import unit molecule = self.molecules[0] openmm_topology = molecule.to_topology().to_openmm() openmm_positions = molecule.conformers[0] # Try adding solvent without residue template generator; this will fail from openmm.app import ForceField forcefield = ForceField('tip3p.xml') # Add solvent to a system containing a small molecule modeller = Modeller(openmm_topology, openmm_positions) try: modeller.addSolvent(forcefield, model='tip3p', padding=6.0*unit.angstroms) except ValueError as e: pass # Create a generator that knows about a few molecules generator = self.TEMPLATE_GENERATOR(molecules=self.molecules) # Add to the forcefield object forcefield.registerTemplateGenerator(generator.generator) # Add solvent to a system containing a small molecule # This should succeed modeller.addSolvent(forcefield, model='tip3p', padding=6.0*unit.angstroms) def test_jacs_ligands(self): """Use template generator to parameterize the Schrodinger JACS set of ligands""" from openmm.app import ForceField, NoCutoff jacs_systems = { #'bace' : { 'prefix' : 'Bace' }, #'cdk2' : { 'prefix' : 'CDK2' }, 'jnk1' : { 'prefix' : 'Jnk1' }, 'mcl1' : { 'prefix' : 'MCL1' }, #'p38' : { 'prefix' : 'p38' }, 'ptp1b' : { 'prefix' : 'PTP1B' }, 'thrombin' : { 'prefix' : 'Thrombin' }, #'tyk2' : { 'prefix' : 'Tyk2' }, } for system_name in jacs_systems: prefix = jacs_systems[system_name]['prefix'] # Load molecules ligand_sdf_filename = get_data_filename(os.path.join('perses_jacs_systems', system_name, prefix + '_ligands.sdf')) print(f'Reading molecules from {ligand_sdf_filename} ...') from openff.toolkit.topology import Molecule molecules = Molecule.from_file(ligand_sdf_filename, allow_undefined_stereo=True) # Ensure this is a list try: nmolecules = len(molecules) except TypeError: molecules = [molecules] print(f'Read {len(molecules)} molecules from {ligand_sdf_filename}') #molecules = self.filter_molecules(molecules) MAX_MOLECULES = len(molecules) if not CI else 3 molecules = molecules[:MAX_MOLECULES] print(f'{len(molecules)} molecules remain after filtering') # Create template generator with local cache cache = os.path.join(get_data_filename(os.path.join('perses_jacs_systems', system_name)), 'cache.json') generator = self.TEMPLATE_GENERATOR(molecules=molecules, cache=cache) # Create a ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Parameterize all molecules print(f'Caching all molecules for {system_name} at {cache} ...') n_success = 0 n_failure = 0 for molecule in molecules: openmm_topology = molecule.to_topology().to_openmm() try: forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) n_success += 1 except Exception as e: n_failure += 1 print(e) print(f'{n_failure}/{n_success+n_failure} ligands failed to parameterize for {system_name}') def test_jacs_complexes(self): """Use template generator to parameterize the Schrodinger JACS set of complexes""" # TODO: Uncomment working systems when we have cleaned up the input files jacs_systems = { #'bace' : { 'prefix' : 'Bace' }, #'cdk2' : { 'prefix' : 'CDK2' }, #'jnk1' : { 'prefix' : 'Jnk1' }, 'mcl1' : { 'prefix' : 'MCL1' }, #'p38' : { 'prefix' : 'p38' }, #'ptp1b' : { 'prefix' : 'PTP1B' }, #'thrombin' : { 'prefix' : 'Thrombin' }, #'tyk2' : { 'prefix' : 'Tyk2' }, } for system_name in jacs_systems: prefix = jacs_systems[system_name]['prefix'] # Read molecules ligand_sdf_filename = get_data_filename(os.path.join('perses_jacs_systems', system_name, prefix + '_ligands.sdf')) print(f'Reading molecules from {ligand_sdf_filename} ...') from openff.toolkit.topology import Molecule molecules = Molecule.from_file(ligand_sdf_filename, allow_undefined_stereo=True) try: nmolecules = len(molecules) except TypeError: molecules = [molecules] print(f'Read {len(molecules)} molecules from {ligand_sdf_filename}') # Read ParmEd Structures import parmed from openmm import unit protein_pdb_filename = get_data_filename(os.path.join('perses_jacs_systems', system_name, prefix + '_protein.pdb')) from openmm.app import PDBFile print(f'Reading protein from {protein_pdb_filename} ...') #protein_structure = parmed.load_file(protein_pdb_filename) # NOTE: This mis-interprets distorted geometry and sequentially-numbered residues that span chain breaks pdbfile = PDBFile(protein_pdb_filename) protein_structure = parmed.openmm.load_topology(pdbfile.topology, xyz=pdbfile.positions.value_in_unit(unit.angstroms)) ligand_structures = parmed.load_file(ligand_sdf_filename) try: nmolecules = len(ligand_structures) except TypeError: ligand_structures = [ligand_structures] assert len(ligand_structures) == len(molecules) # Filter molecules MAX_MOLECULES = 6 if not CI else 3 molecules = molecules[:MAX_MOLECULES] ligand_structures = ligand_structures[:MAX_MOLECULES] print(f'{len(molecules)} molecules remain after filtering') # Create complexes complex_structures = [ (protein_structure + ligand_structure) for ligand_structure in ligand_structures ] # Create template generator with local cache cache = os.path.join(get_data_filename(os.path.join('perses_jacs_systems', system_name)), 'cache.json') generator = self.TEMPLATE_GENERATOR(molecules=molecules, cache=cache) # Create a ForceField from openmm.app import ForceField forcefield = ForceField(*self.amber_forcefields) # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Parameterize all complexes print(f'Caching all molecules for {system_name} at {cache} ...') for ligand_index, complex_structure in enumerate(complex_structures): openmm_topology = complex_structure.topology molecule = molecules[ligand_index] # Delete hydrogens from terminal protein residues # TODO: Fix the input files so we don't need to do this from openmm import app modeller = app.Modeller(complex_structure.topology, complex_structure.positions) residues = [residue for residue in modeller.topology.residues() if residue.name != 'UNL'] termini_ids = [residues[0].id, residues[-1].id] #hs = [atom for atom in modeller.topology.atoms() if atom.element.symbol in ['H'] and atom.residue.name != 'UNL'] hs = [atom for atom in modeller.topology.atoms() if atom.element.symbol in ['H'] and atom.residue.id in termini_ids] modeller.delete(hs) from openmm.app import PDBFile modeller.addHydrogens(forcefield) # Parameterize protein:ligand complex in vacuum print(f' Parameterizing {system_name} : {molecule.to_smiles()} in vacuum...') from openmm.app import NoCutoff forcefield.createSystem(modeller.topology, nonbondedMethod=NoCutoff) # Parameterize protein:ligand complex in solvent print(f' Parameterizing {system_name} : {molecule.to_smiles()} in explicit solvent...') from openmm.app import PME modeller.addSolvent(forcefield, padding=0*unit.angstroms, ionicStrength=300*unit.millimolar) forcefield.createSystem(modeller.topology, nonbondedMethod=PME) def test_parameterize(self): """Test parameterizing molecules with template generator for all supported force fields""" # Test all supported small molecule force fields for small_molecule_forcefield in self.TEMPLATE_GENERATOR.INSTALLED_FORCEFIELDS: print(f'Testing {small_molecule_forcefield}') # Create a generator that knows about a few molecules # TODO: Should the generator also load the appropriate force field files into the ForceField object? generator = self.TEMPLATE_GENERATOR(molecules=self.molecules, forcefield=small_molecule_forcefield) # Check that we have loaded the right force field assert generator.forcefield == small_molecule_forcefield # Create a ForceField with the appropriate small molecule force field from openmm.app import ForceField forcefield = ForceField() # Register the template generator forcefield.registerTemplateGenerator(generator.generator) # Parameterize some molecules from openmm.app import NoCutoff from openmmforcefields.utils import Timer for molecule in self.molecules: openmm_topology = molecule.to_topology().to_openmm() with Timer() as t1: system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert system.getNumParticles() == molecule.n_atoms # Molecule should now be cached with Timer() as t2: system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert system.getNumParticles() == molecule.n_atoms assert (t2.interval() < t1.interval()) def test_multiple_registration(self): """Test registering the template generator with multiple force fields""" generator = self.TEMPLATE_GENERATOR(molecules=self.molecules) from openmm.app import ForceField NUM_FORCEFIELDS = 2 # number of force fields to test forcefields = list() for index in range(NUM_FORCEFIELDS): forcefield = ForceField() forcefield.registerTemplateGenerator(generator.generator) forcefields.append(forcefield) # Parameterize a molecule in each force field instance molecule = self.molecules[0] openmm_topology = molecule.to_topology().to_openmm() from openmm.app import NoCutoff for forcefield in forcefields: system = forcefield.createSystem(openmm_topology, nonbondedMethod=NoCutoff) assert system.getNumParticles() == molecule.n_atoms class TestSMIRNOFFTemplateGenerator(TestGAFFTemplateGenerator): TEMPLATE_GENERATOR = SMIRNOFFTemplateGenerator @staticmethod def compute_energy(system, positions): """Compute potential energy and Force components for an OpenMM system. Parameters ---------- system : openmm.System The System object positions : openmm.unit.Quantity of shape (nparticles,3) with units compatible with nanometers The positions for which energy is to be computed Returns ------- openmm_energy : dict of str : openmm.unit.Quantity openmm_energy['total'] is the total potential energy openmm_energy['components'][forcename] is the potential energy for the specified component force openmm_forces : dict of str : openmm.unit.Quantity openmm_forces['total'] is the total force openmm_forces['components'][forcename] is the force for the specified component force """ import copy system = copy.deepcopy(system) for index, force in enumerate(system.getForces()): force.setForceGroup(index) import openmm platform = openmm.Platform.getPlatformByName('Reference') integrator = openmm.VerletIntegrator(0.001) context = openmm.Context(system, integrator, platform) context.setPositions(positions) openmm_energy = { 'total' : context.getState(getEnergy=True).getPotentialEnergy(), 'components' : { system.getForce(index).__class__.__name__ : context.getState(getEnergy=True, groups=(1 << index)).getPotentialEnergy() for index in range(system.getNumForces()) }, } openmm_forces = { 'total' : context.getState(getForces=True).getForces(asNumpy=True), 'components' : { system.getForce(index).__class__.__name__ : context.getState(getForces=True, groups=(1 << index)).getForces(asNumpy=True) for index in range(system.getNumForces()) }, } del context, integrator return openmm_energy, openmm_forces @classmethod def compare_energies(cls, molecule, openmm_system, smirnoff_system): """Compare energies between Open Force Field Initiative and OpenMM ForceField objects The OpenMM System object created internally by the SMIRNOFFTemplateGenerator is used to avoid any issues with stochasticity of partial charges due to conformer generation. Parameters ---------- molecule : openff.toolkit.topology.Molecule The Molecule object to compare energy components (including positions) openmm_system : openmm.System System generated by OpenMM ForceField smirnoff_system : openmm.System System generated by SMIRNOFF engine """ # Compute energies openmm_energy, openmm_forces = cls.compute_energy(openmm_system, molecule.conformers[0]) smirnoff_energy, smirnoff_forces = cls.compute_energy(smirnoff_system, molecule.conformers[0]) from openmm import unit def write_xml(filename, system): import openmm with open(filename, 'w') as outfile: print(f'Writing {filename}...') outfile.write(openmm.XmlSerializer.serialize(system)) # Compare energies ENERGY_DEVIATION_TOLERANCE = 1.0e-2 * unit.kilocalories_per_mole delta = (openmm_energy['total'] - smirnoff_energy['total']) if abs(delta) > ENERGY_DEVIATION_TOLERANCE: # Show breakdown by components print('Energy components:') print(f"{'component':24} {'OpenMM (kcal/mol)':>20} {'SMIRNOFF (kcal/mol)':>20}") for key in openmm_energy['components'].keys(): openmm_component_energy = openmm_energy['components'][key] smirnoff_component_energy = smirnoff_energy['components'][key] print(f'{key:24} {(openmm_component_energy/unit.kilocalories_per_mole):20.3f} {(smirnoff_component_energy/unit.kilocalories_per_mole):20.3f} kcal/mol') print(f'{"TOTAL":24} {(openmm_energy["total"]/unit.kilocalories_per_mole):20.3f} {(smirnoff_energy["total"]/unit.kilocalories_per_mole):20.3f} kcal/mol') write_xml('system-smirnoff.xml', smirnoff_system) write_xml('openmm-smirnoff.xml', openmm_system) raise Exception(f'Energy deviation for {molecule.to_smiles()} ({delta/unit.kilocalories_per_mole} kcal/mol) exceeds threshold ({ENERGY_DEVIATION_TOLERANCE})') # Compare forces import numpy as np def norm(x): N = x.shape[0] return np.sqrt((1.0/N) * (x**2).sum()) def relative_deviation(x, y): if norm(y) > 0: return norm(x-y) / norm(y) else: return 0 RELATIVE_FORCE_DEVIATION_TOLERANCE = 1.0e-5 relative_force_deviation = relative_deviation(openmm_forces['total'], smirnoff_forces['total']) if relative_force_deviation > RELATIVE_FORCE_DEVIATION_TOLERANCE: # Show breakdown by components print('Force components:') print(f"{'component':24} {'relative deviation':>24}") for key in openmm_energy['components'].keys(): print(f"{key:24} {relative_deviation(openmm_forces['components'][key], smirnoff_forces['components'][key]):24.10f}") print(f'{"TOTAL":24} {relative_force_deviation:24.10f}') write_xml('system-smirnoff.xml', smirnoff_system) write_xml('openmm-smirnoff.xml', openmm_system) raise Exception(f'Relative force deviation for {molecule.to_smiles()} ({relative_force_deviation}) exceeds threshold ({RELATIVE_FORCE_DEVIATION_TOLERANCE})') def propagate_dynamics(self, molecule, system): """Run a few steps of dynamics to generate a perturbed configuration. Parameters ---------- molecule : openff.toolkit.topology.Molecule molecule.conformers[0] is used as initial positions system : openmm.System System object for dynamics Returns ------- new_molecule : openff.toolkit.topology.Molecule new_molecule.conformers[0] has updated positions """ # Run some dynamics import openmm from openmm import unit temperature = 300 * unit.kelvin collision_rate = 1.0 / unit.picoseconds timestep = 1.0 * unit.femtoseconds nsteps = 100 integrator = openmm.LangevinIntegrator(temperature, collision_rate, timestep) platform = openmm.Platform.getPlatformByName('Reference') context = openmm.Context(system, integrator, platform) context.setPositions(molecule.conformers[0]) integrator.step(nsteps) # Copy the molecule, storing new conformer import copy new_molecule = copy.deepcopy(molecule) new_molecule.conformers[0] = context.getState(getPositions=True).getPositions(asNumpy=True) # Clean up del context, integrator return new_molecule def test_INSTALLED_FORCEFIELDS(self): """Test INSTALLED_FORCEFIELDS contains expected force fields""" assert 'openff-1.1.0' in SMIRNOFFTemplateGenerator.INSTALLED_FORCEFIELDS assert 'smirnoff99Frosst-1.1.0' in SMIRNOFFTemplateGenerator.INSTALLED_FORCEFIELDS assert 'openff_unconstrained-1.1.0' not in SMIRNOFFTemplateGenerator.INSTALLED_FORCEFIELDS def test_energies(self): """Test potential energies match between openff-toolkit and OpenMM ForceField""" # DEBUG from openff.toolkit.topology import Molecule molecule = Molecule.from_smiles('C=O') molecule.generate_conformers(n_conformers=1) from openmm import unit molecule.conformers[0][0,0] += 0.1*unit.angstroms self.molecules.insert(0, molecule) # Test all supported SMIRNOFF force fields for small_molecule_forcefield in SMIRNOFFTemplateGenerator.INSTALLED_FORCEFIELDS: print(f'Testing energies for {small_molecule_forcefield}...') # Create a generator that knows about a few molecules # TODO: Should the generator also load the appropriate force field files into the ForceField object? generator = SMIRNOFFTemplateGenerator(molecules=self.molecules, forcefield=small_molecule_forcefield) # Create a ForceField import openmm openmm_forcefield = openmm.app.ForceField() # Register the template generator openmm_forcefield.registerTemplateGenerator(generator.generator) # Parameterize some molecules for molecule in self.molecules: # Create OpenMM System using OpenMM app from openmm.app import NoCutoff openmm_system = openmm_forcefield.createSystem(molecule.to_topology().to_openmm(), removeCMMotion=False, onbondedMethod=NoCutoff) # Retrieve System generated by the SMIRNOFF typing engine smirnoff_system = generator.get_openmm_system(molecule) # Compare energies and forces self.compare_energies(molecule, openmm_system, smirnoff_system) # Run some dynamics molecule = self.propagate_dynamics(molecule, smirnoff_system) # Compare energies again self.compare_energies(molecule, openmm_system, smirnoff_system) def test_partial_charges_are_none(self): """Test parameterizing a small molecule with `partial_charges=None` instead of zeros (happens frequently in OFFTK>=0.7.0)""" from openff.toolkit.topology import Molecule molecule = Molecule.from_smiles('C=O') molecule.generate_conformers(n_conformers=1) #molecule._partial_charges = None assert (molecule.partial_charges is None) or np.all(molecule.partial_charges / unit.elementary_charge == 0) # Test all supported SMIRNOFF force fields for small_molecule_forcefield in SMIRNOFFTemplateGenerator.INSTALLED_FORCEFIELDS: print(f'Testing energies for {small_molecule_forcefield}...') # Create a generator that knows about a few molecules # TODO: Should the generator also load the appropriate force field files into the ForceField object? generator = SMIRNOFFTemplateGenerator(molecules=[molecule], forcefield=small_molecule_forcefield) # Create a ForceField import openmm openmm_forcefield = openmm.app.ForceField() # Register the template generator openmm_forcefield.registerTemplateGenerator(generator.generator) # Create OpenMM System using OpenMM app from openmm.app import NoCutoff openmm_system = openmm_forcefield.createSystem(molecule.to_topology().to_openmm(), removeCMMotion=False, onbondedMethod=NoCutoff) smirnoff_system = generator.get_openmm_system(molecule) def test_version(self): """Test version""" for forcefield in SMIRNOFFTemplateGenerator.INSTALLED_FORCEFIELDS: generator = SMIRNOFFTemplateGenerator(forcefield=forcefield) assert generator.forcefield == forcefield assert generator.smirnoff_filename.endswith(forcefield + '.offxml') assert os.path.exists(generator.smirnoff_filename)
import logging import os from functools import wraps from discord_webhook import DiscordEmbed from rcon.recorded_commands import RecordedRcon from rcon.player_history import ( save_player, save_start_player_session, save_end_player_session, safe_save_player_action, get_player, _get_set_player, ) from rcon.game_logs import on_connected, on_disconnected, on_camera, on_chat from rcon.models import enter_session, PlayerSteamID, SteamInfo, enter_session from rcon.discord import send_to_discord_audit, dict_to_discord from rcon.steam_utils import ( get_player_bans, STEAM_KEY, get_steam_profile, update_db_player_info, ) from rcon.discord import send_to_discord_audit from rcon.user_config import CameraConfig from rcon.discord import get_prepared_discord_hooks, send_to_discord_audit from rcon.map_recorder import VoteMap from rcon.user_config import VoteMapConfig from rcon.workers import temporary_broadcast, temporary_welcome logger = logging.getLogger(__name__) @on_chat def count_vote(rcon: RecordedRcon, struct_log): config = VoteMapConfig() if not config.get_vote_enabled(): return v = VoteMap() if vote := v.is_vote(struct_log.get("sub_content")): logger.debug("Vote chat detected: %s", struct_log["message"]) map_name = v.register_vote( struct_log["player"], struct_log["timestamp_ms"] / 1000, vote ) try: temporary_broadcast( rcon, config.get_votemap_thank_you_text().format( player_name=struct_log["player"], map_name=map_name ), 5 ) except Exception: logger.warning("Unable to output thank you message") v.apply_with_retry(nb_retry=2) MAX_DAYS_SINCE_BAN = os.getenv("BAN_ON_VAC_HISTORY_DAYS", 0) AUTO_BAN_REASON = os.getenv( "BAN_ON_VAC_HISTORY_REASON", "VAC ban history ({DAYS_SINCE_LAST_BAN} days ago)" ) MAX_GAME_BAN_THRESHOLD = os.getenv("MAX_GAME_BAN_THRESHOLD", 0) def ban_if_blacklisted(rcon: RecordedRcon, steam_id_64, name): with enter_session() as sess: player = get_player(sess, steam_id_64) if not player: logger.error("Can't check blacklist, player not found %s", steam_id_64) return if player.blacklist and player.blacklist.is_blacklisted: try: logger.info( "Player %s was banned due blacklist, reason: %s", str(name), player.blacklist.reason, ) rcon.do_perma_ban( player=name, reason=player.blacklist.reason, by=f"BLACKLIST: {player.blacklist.by}", ) safe_save_player_action( rcon=rcon, player_name=name, action_type="PERMABAN", reason=player.blacklist.reason, by=f"BLACKLIST: {player.blacklist.by}", steam_id_64=steam_id_64, ) try: send_to_discord_audit( f"`BLACKLIST` -> {dict_to_discord(dict(player=name, reason=player.blacklist.reason))}", "BLACKLIST", ) except: logger.error("Unable to send blacklist to audit log") except: send_to_discord_audit( "Failed to apply ban on blacklisted players, please check the logs and report the error", "ERROR", ) def should_ban(bans, max_game_bans, max_days_since_ban): try: days_since_last_ban = int(bans["DaysSinceLastBan"]) number_of_game_bans = int(bans.get("NumberOfGameBans", 0)) except ValueError: # In case DaysSinceLastBan can be null return has_a_ban = bans.get("VACBanned") == True or number_of_game_bans >= max_game_bans if days_since_last_ban <= 0: return False if days_since_last_ban <= max_days_since_ban and has_a_ban: return True return False def ban_if_has_vac_bans(rcon: RecordedRcon, steam_id_64, name): try: max_days_since_ban = int(MAX_DAYS_SINCE_BAN) max_game_bans = ( float("inf") if int(MAX_GAME_BAN_THRESHOLD) <= 0 else int(MAX_GAME_BAN_THRESHOLD) ) except ValueError: # No proper value is given logger.error( "Invalid value given for environment variable BAN_ON_VAC_HISTORY_DAYS or MAX_GAME_BAN_THRESHOLD" ) return if max_days_since_ban <= 0: return # Feature is disabled with enter_session() as sess: player = get_player(sess, steam_id_64) if not player: logger.error("Can't check VAC history, player not found %s", steam_id_64) return bans = get_player_bans(steam_id_64) if not bans or not isinstance(bans, dict): logger.warning( "Can't fetch Bans for player %s, received %s", steam_id_64, bans ) # Player couldn't be fetched properly (logged by get_player_bans) return if should_ban(bans, max_game_bans, max_days_since_ban): reason = AUTO_BAN_REASON.format( DAYS_SINCE_LAST_BAN=bans.get("DaysSinceLastBan"), MAX_DAYS_SINCE_BAN=str(max_days_since_ban), ) logger.info( "Player %s was banned due VAC history, last ban: %s days ago", str(player), bans.get("DaysSinceLastBan"), ) rcon.do_perma_ban(player=name, reason=reason, by="VAC BOT") try: audit_params = dict( player=name, steam_id_64=player.steam_id_64, reason=reason, days_since_last_ban=bans.get("DaysSinceLastBan"), vac_banned=bans.get("VACBanned"), number_of_game_bans=bans.get("NumberOfGameBans"), ) send_to_discord_audit( f"`VAC/GAME BAN` -> {dict_to_discord(audit_params)}", "AUTOBAN" ) except: logger.exception("Unable to send vac ban to audit log") def inject_steam_id_64(func): @wraps(func) def wrapper(rcon, struct_log): try: name = struct_log["player"] info = rcon.get_player_info(name) steam_id_64 = info.get("steam_id_64") except KeyError: logger.exception("Unable to inject steamid %s", struct_log) raise if not steam_id_64: logger.warning("Can't get player steam_id for %s", name) return return func(rcon, struct_log, steam_id_64) return wrapper @on_connected @inject_steam_id_64 def handle_on_connect(rcon, struct_log, steam_id_64): timestamp = int(struct_log["timestamp_ms"]) / 1000 save_player( struct_log["player"], steam_id_64, timestamp=int(struct_log["timestamp_ms"]) / 1000, ) save_start_player_session(steam_id_64, timestamp=timestamp) ban_if_blacklisted(rcon, steam_id_64, struct_log["player"]) ban_if_has_vac_bans(rcon, steam_id_64, struct_log["player"]) @on_disconnected @inject_steam_id_64 def handle_on_disconnect(rcon, struct_log, steam_id_64): save_end_player_session(steam_id_64, struct_log["timestamp_ms"] / 1000) @on_connected @inject_steam_id_64 def update_player_steaminfo_on_connect(rcon, struct_log, steam_id_64): if not steam_id_64: logger.error( "Can't update steam info, no steam id available for %s", struct_log.get("player"), ) return profile = get_steam_profile(steam_id_64) if not profile: logger.error( "Can't update steam info, no steam profile returned for %s", struct_log.get("player"), ) logger.info("Updating steam profile for player %s", struct_log["player"]) with enter_session() as sess: player = _get_set_player( sess, player_name=struct_log["player"], steam_id_64=steam_id_64 ) update_db_player_info(player, profile) sess.commit() @on_camera def notify_camera(rcon: RecordedRcon, struct_log): send_to_discord_audit(message=struct_log["message"], by=struct_log["player"]) try: if hooks := get_prepared_discord_hooks("camera"): embeded = DiscordEmbed( title=f'{struct_log['player']} - {struct_log['steam_id_64_1']}', description=struct_log["sub_content"], color=242424, ) for h in hooks: h.add_embed(embeded) h.execute() except Exception: logger.exception("Unable to forward to hooks") config = CameraConfig() if config.is_broadcast(): temporary_broadcast(rcon, struct_log["message"], 60) if config.is_welcome(): temporary_welcome(rcon, struct_log["message"], 60)
import logging import os from functools import wraps from discord_webhook import DiscordEmbed from rcon.recorded_commands import RecordedRcon from rcon.player_history import ( save_player, save_start_player_session, save_end_player_session, safe_save_player_action, get_player, _get_set_player, ) from rcon.game_logs import on_connected, on_disconnected, on_camera, on_chat from rcon.models import enter_session, PlayerSteamID, SteamInfo, enter_session from rcon.discord import send_to_discord_audit, dict_to_discord from rcon.steam_utils import ( get_player_bans, STEAM_KEY, get_steam_profile, update_db_player_info, ) from rcon.discord import send_to_discord_audit from rcon.user_config import CameraConfig from rcon.discord import get_prepared_discord_hooks, send_to_discord_audit from rcon.map_recorder import VoteMap from rcon.user_config import VoteMapConfig from rcon.workers import temporary_broadcast, temporary_welcome logger = logging.getLogger(__name__) @on_chat def count_vote(rcon: RecordedRcon, struct_log): config = VoteMapConfig() if not config.get_vote_enabled(): return v = VoteMap() if vote := v.is_vote(struct_log.get("sub_content")): logger.debug("Vote chat detected: %s", struct_log["message"]) map_name = v.register_vote( struct_log["player"], struct_log["timestamp_ms"] / 1000, vote ) try: temporary_broadcast( rcon, config.get_votemap_thank_you_text().format( player_name=struct_log["player"], map_name=map_name ), 5 ) except Exception: logger.warning("Unable to output thank you message") v.apply_with_retry(nb_retry=2) MAX_DAYS_SINCE_BAN = os.getenv("BAN_ON_VAC_HISTORY_DAYS", 0) AUTO_BAN_REASON = os.getenv( "BAN_ON_VAC_HISTORY_REASON", "VAC ban history ({DAYS_SINCE_LAST_BAN} days ago)" ) MAX_GAME_BAN_THRESHOLD = os.getenv("MAX_GAME_BAN_THRESHOLD", 0) def ban_if_blacklisted(rcon: RecordedRcon, steam_id_64, name): with enter_session() as sess: player = get_player(sess, steam_id_64) if not player: logger.error("Can't check blacklist, player not found %s", steam_id_64) return if player.blacklist and player.blacklist.is_blacklisted: try: logger.info( "Player %s was banned due blacklist, reason: %s", str(name), player.blacklist.reason, ) rcon.do_perma_ban( player=name, reason=player.blacklist.reason, by=f"BLACKLIST: {player.blacklist.by}", ) safe_save_player_action( rcon=rcon, player_name=name, action_type="PERMABAN", reason=player.blacklist.reason, by=f"BLACKLIST: {player.blacklist.by}", steam_id_64=steam_id_64, ) try: send_to_discord_audit( f"`BLACKLIST` -> {dict_to_discord(dict(player=name, reason=player.blacklist.reason))}", "BLACKLIST", ) except: logger.error("Unable to send blacklist to audit log") except: send_to_discord_audit( "Failed to apply ban on blacklisted players, please check the logs and report the error", "ERROR", ) def should_ban(bans, max_game_bans, max_days_since_ban): try: days_since_last_ban = int(bans["DaysSinceLastBan"]) number_of_game_bans = int(bans.get("NumberOfGameBans", 0)) except ValueError: # In case DaysSinceLastBan can be null return has_a_ban = bans.get("VACBanned") == True or number_of_game_bans >= max_game_bans if days_since_last_ban <= 0: return False if days_since_last_ban <= max_days_since_ban and has_a_ban: return True return False def ban_if_has_vac_bans(rcon: RecordedRcon, steam_id_64, name): try: max_days_since_ban = int(MAX_DAYS_SINCE_BAN) max_game_bans = ( float("inf") if int(MAX_GAME_BAN_THRESHOLD) <= 0 else int(MAX_GAME_BAN_THRESHOLD) ) except ValueError: # No proper value is given logger.error( "Invalid value given for environment variable BAN_ON_VAC_HISTORY_DAYS or MAX_GAME_BAN_THRESHOLD" ) return if max_days_since_ban <= 0: return # Feature is disabled with enter_session() as sess: player = get_player(sess, steam_id_64) if not player: logger.error("Can't check VAC history, player not found %s", steam_id_64) return bans = get_player_bans(steam_id_64) if not bans or not isinstance(bans, dict): logger.warning( "Can't fetch Bans for player %s, received %s", steam_id_64, bans ) # Player couldn't be fetched properly (logged by get_player_bans) return if should_ban(bans, max_game_bans, max_days_since_ban): reason = AUTO_BAN_REASON.format( DAYS_SINCE_LAST_BAN=bans.get("DaysSinceLastBan"), MAX_DAYS_SINCE_BAN=str(max_days_since_ban), ) logger.info( "Player %s was banned due VAC history, last ban: %s days ago", str(player), bans.get("DaysSinceLastBan"), ) rcon.do_perma_ban(player=name, reason=reason, by="VAC BOT") try: audit_params = dict( player=name, steam_id_64=player.steam_id_64, reason=reason, days_since_last_ban=bans.get("DaysSinceLastBan"), vac_banned=bans.get("VACBanned"), number_of_game_bans=bans.get("NumberOfGameBans"), ) send_to_discord_audit( f"`VAC/GAME BAN` -> {dict_to_discord(audit_params)}", "AUTOBAN" ) except: logger.exception("Unable to send vac ban to audit log") def inject_steam_id_64(func): @wraps(func) def wrapper(rcon, struct_log): try: name = struct_log["player"] info = rcon.get_player_info(name) steam_id_64 = info.get("steam_id_64") except KeyError: logger.exception("Unable to inject steamid %s", struct_log) raise if not steam_id_64: logger.warning("Can't get player steam_id for %s", name) return return func(rcon, struct_log, steam_id_64) return wrapper @on_connected @inject_steam_id_64 def handle_on_connect(rcon, struct_log, steam_id_64): timestamp = int(struct_log["timestamp_ms"]) / 1000 save_player( struct_log["player"], steam_id_64, timestamp=int(struct_log["timestamp_ms"]) / 1000, ) save_start_player_session(steam_id_64, timestamp=timestamp) ban_if_blacklisted(rcon, steam_id_64, struct_log["player"]) ban_if_has_vac_bans(rcon, steam_id_64, struct_log["player"]) @on_disconnected @inject_steam_id_64 def handle_on_disconnect(rcon, struct_log, steam_id_64): save_end_player_session(steam_id_64, struct_log["timestamp_ms"] / 1000) @on_connected @inject_steam_id_64 def update_player_steaminfo_on_connect(rcon, struct_log, steam_id_64): if not steam_id_64: logger.error( "Can't update steam info, no steam id available for %s", struct_log.get("player"), ) return profile = get_steam_profile(steam_id_64) if not profile: logger.error( "Can't update steam info, no steam profile returned for %s", struct_log.get("player"), ) logger.info("Updating steam profile for player %s", struct_log["player"]) with enter_session() as sess: player = _get_set_player( sess, player_name=struct_log["player"], steam_id_64=steam_id_64 ) update_db_player_info(player, profile) sess.commit() @on_camera def notify_camera(rcon: RecordedRcon, struct_log): send_to_discord_audit(message=struct_log["message"], by=struct_log["player"]) try: if hooks := get_prepared_discord_hooks("camera"): embeded = DiscordEmbed( title=f'{struct_log["player"]} - {struct_log["steam_id_64_1"]}', description=struct_log["sub_content"], color=242424, ) for h in hooks: h.add_embed(embeded) h.execute() except Exception: logger.exception("Unable to forward to hooks") config = CameraConfig() if config.is_broadcast(): temporary_broadcast(rcon, struct_log["message"], 60) if config.is_welcome(): temporary_welcome(rcon, struct_log["message"], 60)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://github.com/FerryYoungFan/SimpleTextMontage # 之前我不知道 Montage 是什么 # 其实用反向 Alpha-blend 也可以,不过我不想这么做,因为懒,而且我是没大阅读 doc… from PIL import Image from PIL import ImageDraw, ImageFont from argparse import ArgumentParser, FileType from math import ceil from sys import stdout, stderr from logging import getLogger, WARNING, INFO, DEBUG log = getLogger('MontagePY') log.setLevel(INFO) URL = 'https://github.com/FerryYoungFan/SimpleTextMontage' SUPPORTED_ENCODERS = "png webp pdf bmp dib gif ico jpeg ppm xbm tiff tga".split(';') log.debug(f'Supproted encoders {SUPPORTED_ENCODERS}') app = ArgumentParser(prog='montage', description='Simple montage graph generator', epilog=f'by duangsuse, see also {URL}') app.add_argument('image', type=str, nargs='+', help='Images (path) for input') app.add_argument('--convert', type=str, metavar='coding', help='Convert image color coding (RGBA)', default='RGBA') app.add_argument('--output-format', type=str, metavar='encoder', help=f'Python pillow image encoder type in [{','.join(SUPPORTED_ENCODERS)}]', default='png', choices=SUPPORTED_ENCODERS) app.add_argument('-o', type=FileType('w'), nargs='?', metavar='opath', help='Output to file directly (Text)', default=None) app.add_argument('--output-fmtstr', type=str, metavar='opathfmt', help='Output filename format like out_@_#.png', default='Mon@.png') app.add_argument('--text', type=str, help='Text to be embeeded', default='#') app.add_argument('--grayscale', help='Use grayscale and text output', default=False, action='store_true') app.add_argument('--text-grayscale', type=str, nargs='+', metavar='gray-texts', help=f'Character for grayscale picking', default=". * % #".split(' ')) app.add_argument('--scale', type=float, metavar='ratio', help='Text-image scale ratio X.Y', default=1.0) app.add_argument('--scaleXY', '-sxy', type=int, nargs=2, metavar=('x', 'y'), help='Size skip of collecting X/Y (override)', default=None) app.add_argument('-fnt', '--font', type=str, nargs='?', metavar='fpath', help='Font TTF/OTF glyph path, if like `:name`, treat as font(TrueType/FreeType) name, not path') app.add_argument('-fntsz', '--font-size', type=int, metavar='size', help='Font size (avaliable for fonts by :name)', default=16) app.add_argument('--preview', type=str, metavar='cmd', help='Preview command (don\'t do save)') app.add_argument('--preview!', dest='do_preview', action='store_true') app.add_argument('--print-render-src', help='Print Render source', default=False, action='store_true') def iterable(xs_): try: return iter(xs_) except TypeError: return None def repeat(n, x, skip=1): assert n >= 0, 'n must not negtive' while n !=0: yield x n -= skip # 此类会接受参数: # + --convert 颜色系统 # + --text 内嵌文字,grayscale 模式无效 # + --text-grayscale 按灰色深度从小到大排列的字符取样 # + --scale 生成综合块 (w,h) 大小(skip), --scaleXY 区间缩放 # + --font 文字字体, --font-size 字体大小 # # 提供 generate(img) -> img; generate_grayscale(img) -> str 方法 class Montage (object): def __init__(self, colorspace: str, text: str, text_grayscale: str, scale=1.0, skipXY = None, font=None, fontsz=16): self.space = colorspace self.text = text; self.graytexts = text_grayscale self.ratio = scale self.skipXY = skipXY self.font = font if type(font) is ImageFont else Montage.cfg_read_font(font,fontsz) self.log = getLogger('Montage') # Load font fmtstr, when :name do search, else read file @staticmethod def cfg_read_font(fnt: str, sz): if fnt is None: return ImageFont.load_default() elif len(fnt) !=0 and fnt[0] == ':': try: return ImageFont.truetype(fnt[1:], sz) except OSError: return ImageFont.FreeTypeFont(fnt[1:], size=sz) else: return ImageFont.load_path(fnt) # Not efficient but usable Lum @staticmethod def grayscale(rgb_a): if len(rgb_a) ==3: r,g,b = rgb_a; a=1.0 elif len(rgb_a) ==4: r,g,b,a = rgb_a return (0.2126 * r + 0.7152 * g + 0.0722 * b) *a @staticmethod def icsum(xs_s, is_atom=lambda o: not iterable(o)): accum = 0 for x in xs_s: accum += (x if is_atom(x) else Montage.icsum(x)) return accum # 就不用拜会 numpy 了 @staticmethod def caverage(ts): # (a, b, c), (a1, b1, c1) -> map(/2) (a+a1, b+b1 c+c1) assert len(ts) is not 0 dims = list(); dims.extend(repeat(len(ts[0]), 0)) for di in range(0, len(dims)): dims[di] = [t[di] for t in ts] # dims_0 = a_0, b_0, c_0, ... return [divmod(Montage.icsum(dim), len(dim))[0] for dim in dims] @staticmethod def points2D(xs, ys): for x in xs: # 1, 2, 3, ... for y in ys: # 0, 4, 8, ... yield (x, y) # (1, 0), (1, 4), (1, 8), (2, 0)... @staticmethod def coord(img: Image): return (img.width, img.height) # 为了达到 self.ratio 的缩放比,需要多少 skip? 已经放弃 def ratio_skip(self, img, coerc=ceil) -> (int,int): if self.skipXY is not None: assert len(self.skipXY) == 2 return self.skipXY sca = self.ratio w, h = [img.width, img.height] nw, nh = [sca*w, sca*h]; dw, dh = [nw-w, nh-h] return (coerc(sca/w), coerc(sca/w)) RGBA_0 = (0xFF, 0xFF, 0xFF, 0) # 将图像切分为块的 color average,很慢,懒得用并行处理 # 其实就是平均插值缩放图像,不过我自己实现了个 def clippy(self, img: Image, sxy: (int, int), cmapper: callable=None) -> Image: sx, sy = sxy self.log.info('Scale', (sx, sy)) rangx = range (0, img.width, sx) rangy = range (0, img.height, sy) width, height = list(map(len, (rangx, rangy))) #print(rangx,width, rangy,height) cblk = Image.new(self.space, (width,height), Montage.RGBA_0) nx, ny = (0, 0) for x in rangx: hline = [i for i in range (x, x+sx)] for y in rangy: # generate blk vline = [i for i in range (y, y+sy)] block = [] for p in Montage.points2D(hline, vline): try: block.append(img.getpixel(p)) except IndexError: pass coloravg = Montage.caverage(block) # 本块均色 #self.log.debug((hline, vline), block, coloravg, (nx,ny)) cblk.putpixel((nx, ny), tuple(coloravg) if cmapper==None else cmapper(tuple(coloravg))) ny += 1 nx += 1; ny = 0 return cblk # 生成彩色蒙太奇,虽然低性能但是不着急(很稳,删除) def generate_cmap(self, img: Image) -> (Image, list): skips = self.ratio_skip(img) if skips != (1,1): img = self.clippy(img, skips) fntsz = self.font.getsize(self.text) clipf = self.clippy(img, fntsz) coord = (clipf.width, clipf.height) print('TextXY', fntsz, 'Clipped', coord, file=stderr) monsrc = [] for ix, iy in Montage.points2D( range(0, coord[0]), range(0, coord[1]) ): monsrc.append(( (ix*fntsz[0], iy*fntsz[1]), clipf.getpixel((ix,iy)))) return clipf, (Montage.coord(img), monsrc) def generate(self, img: Image) -> Image: cord, src = self.generate_cmap(img)[1] montage = Image.new(self.space, cord, Montage.RGBA_0) draw = ImageDraw.Draw(montage) for p, c in src: draw.text(p, self.text, font=self.font, fill=c) return montage def selectGsChar(self, avg, cr): graytexts = self.graytexts txtlen = len(graytexts) i = int(cr-avg) % txtlen return ord(graytexts[i]) # 生成 ASCII Art def generate_grayscale(self, img: Image) -> str: scaled = self.clippy(img, self.ratio_skip(img)) scaled.show() co = Montage.coord(scaled) vline, hline = (range (0,co[0]), range (0,co[1])) gray = [Montage.grayscale(scaled.getpixel(p)) for p in Montage.points2D(hline, vline)] ts = bytearray(len(gray)) avg = 0; ac = 1 for n in hline: i = (co[0]*n) for m in vline: c = gray[i+m] avg = divmod((avg + c), ac)[0]; ac += 1 ts[i+m] = self.selectGsChar(avg, c) ts[i] = ord('\n') return ts # 此应用主函数处理参数: # + image [...] 遍历生成目标图像 # + --output-format save(...) 格式 # + --output-fmtstr save(...) 文件名,@ 表示输入名、# 表示输入序号 # + --grayscale 指示使用 generate_grayscale # + -o 指示 grayscale 模式的输出文件 def main(args): cfg = app.parse_args(args) txt, tgs = [cfg.text, cfg.text_grayscale] montage = Montage(cfg.convert, txt, tgs, scale=cfg.scale, skipXY=cfg.scaleXY, font=cfg.font, fontsz=cfg.font_size) tout = cfg.o for i, img in enumerate(cfg.image[1:len(cfg.image)]): ofname = solve_opathfmt(cfg.output_fmtstr, img, str(i+1)) img = Image.open(img).convert(cfg.convert) print('Image', (img.width, img.height), 'Scale', cfg.scaleXY, file=stderr) if cfg.grayscale: textmon = montage.generate_grayscale(img) write_or_createw(textmon, tout, ofname) continue elif cfg.print_render_src: avgscale, monsrc = montage.generate_cmap(img) avgscale.show(title=ofname) print('Image (w, h)', monsrc[0]) for p, c in (monsrc[1]): for t in ['#', sharpcolor(c), ' ']: stdout.write(t) print(p[0],p[1], sep=':') continue mon = montage.generate(img) if cfg.preview is not None or cfg.do_preview: mon.show(title=ofname, command=cfg.preview) continue mon.save(ofname, cfg.output_format) if tout is not None: tout.close() def sharpcolor(cvs): return ''.join(map(lambda i: hex(i)[2:], cvs)) # Write to non-null of or create nf & write def write_or_createw(o, of, nf: str, p=lambda f: f.writable(), mode='w+'): if of is not None and p(of): return of.buffer.write(o) else: with open(nf, mode) as out: return out.buffer.write(o) # @=ifname; #=output_no def solve_opathfmt(fmt: str, ifname, ofno) -> str: oat, osharp = list(map(ord, "@#")) return fmt.translate({oat: ifname, osharp: ofno}) from sys import argv if __name__ == '__main__': main(argv)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://github.com/FerryYoungFan/SimpleTextMontage # 之前我不知道 Montage 是什么 # 其实用反向 Alpha-blend 也可以,不过我不想这么做,因为懒,而且我是没大阅读 doc… from PIL import Image from PIL import ImageDraw, ImageFont from argparse import ArgumentParser, FileType from math import ceil from sys import stdout, stderr from logging import getLogger, WARNING, INFO, DEBUG log = getLogger('MontagePY') log.setLevel(INFO) URL = 'https://github.com/FerryYoungFan/SimpleTextMontage' SUPPORTED_ENCODERS = "png webp pdf bmp dib gif ico jpeg ppm xbm tiff tga".split(';') log.debug(f'Supproted encoders {SUPPORTED_ENCODERS}') app = ArgumentParser(prog='montage', description='Simple montage graph generator', epilog=f'by duangsuse, see also {URL}') app.add_argument('image', type=str, nargs='+', help='Images (path) for input') app.add_argument('--convert', type=str, metavar='coding', help='Convert image color coding (RGBA)', default='RGBA') app.add_argument('--output-format', type=str, metavar='encoder', help=f'Python pillow image encoder type in [{",".join(SUPPORTED_ENCODERS)}]', default='png', choices=SUPPORTED_ENCODERS) app.add_argument('-o', type=FileType('w'), nargs='?', metavar='opath', help='Output to file directly (Text)', default=None) app.add_argument('--output-fmtstr', type=str, metavar='opathfmt', help='Output filename format like out_@_#.png', default='Mon@.png') app.add_argument('--text', type=str, help='Text to be embeeded', default='#') app.add_argument('--grayscale', help='Use grayscale and text output', default=False, action='store_true') app.add_argument('--text-grayscale', type=str, nargs='+', metavar='gray-texts', help=f'Character for grayscale picking', default=". * % #".split(' ')) app.add_argument('--scale', type=float, metavar='ratio', help='Text-image scale ratio X.Y', default=1.0) app.add_argument('--scaleXY', '-sxy', type=int, nargs=2, metavar=('x', 'y'), help='Size skip of collecting X/Y (override)', default=None) app.add_argument('-fnt', '--font', type=str, nargs='?', metavar='fpath', help='Font TTF/OTF glyph path, if like `:name`, treat as font(TrueType/FreeType) name, not path') app.add_argument('-fntsz', '--font-size', type=int, metavar='size', help='Font size (avaliable for fonts by :name)', default=16) app.add_argument('--preview', type=str, metavar='cmd', help='Preview command (don\'t do save)') app.add_argument('--preview!', dest='do_preview', action='store_true') app.add_argument('--print-render-src', help='Print Render source', default=False, action='store_true') def iterable(xs_): try: return iter(xs_) except TypeError: return None def repeat(n, x, skip=1): assert n >= 0, 'n must not negtive' while n !=0: yield x n -= skip # 此类会接受参数: # + --convert 颜色系统 # + --text 内嵌文字,grayscale 模式无效 # + --text-grayscale 按灰色深度从小到大排列的字符取样 # + --scale 生成综合块 (w,h) 大小(skip), --scaleXY 区间缩放 # + --font 文字字体, --font-size 字体大小 # # 提供 generate(img) -> img; generate_grayscale(img) -> str 方法 class Montage (object): def __init__(self, colorspace: str, text: str, text_grayscale: str, scale=1.0, skipXY = None, font=None, fontsz=16): self.space = colorspace self.text = text; self.graytexts = text_grayscale self.ratio = scale self.skipXY = skipXY self.font = font if type(font) is ImageFont else Montage.cfg_read_font(font,fontsz) self.log = getLogger('Montage') # Load font fmtstr, when :name do search, else read file @staticmethod def cfg_read_font(fnt: str, sz): if fnt is None: return ImageFont.load_default() elif len(fnt) !=0 and fnt[0] == ':': try: return ImageFont.truetype(fnt[1:], sz) except OSError: return ImageFont.FreeTypeFont(fnt[1:], size=sz) else: return ImageFont.load_path(fnt) # Not efficient but usable Lum @staticmethod def grayscale(rgb_a): if len(rgb_a) ==3: r,g,b = rgb_a; a=1.0 elif len(rgb_a) ==4: r,g,b,a = rgb_a return (0.2126 * r + 0.7152 * g + 0.0722 * b) *a @staticmethod def icsum(xs_s, is_atom=lambda o: not iterable(o)): accum = 0 for x in xs_s: accum += (x if is_atom(x) else Montage.icsum(x)) return accum # 就不用拜会 numpy 了 @staticmethod def caverage(ts): # (a, b, c), (a1, b1, c1) -> map(/2) (a+a1, b+b1 c+c1) assert len(ts) is not 0 dims = list(); dims.extend(repeat(len(ts[0]), 0)) for di in range(0, len(dims)): dims[di] = [t[di] for t in ts] # dims_0 = a_0, b_0, c_0, ... return [divmod(Montage.icsum(dim), len(dim))[0] for dim in dims] @staticmethod def points2D(xs, ys): for x in xs: # 1, 2, 3, ... for y in ys: # 0, 4, 8, ... yield (x, y) # (1, 0), (1, 4), (1, 8), (2, 0)... @staticmethod def coord(img: Image): return (img.width, img.height) # 为了达到 self.ratio 的缩放比,需要多少 skip? 已经放弃 def ratio_skip(self, img, coerc=ceil) -> (int,int): if self.skipXY is not None: assert len(self.skipXY) == 2 return self.skipXY sca = self.ratio w, h = [img.width, img.height] nw, nh = [sca*w, sca*h]; dw, dh = [nw-w, nh-h] return (coerc(sca/w), coerc(sca/w)) RGBA_0 = (0xFF, 0xFF, 0xFF, 0) # 将图像切分为块的 color average,很慢,懒得用并行处理 # 其实就是平均插值缩放图像,不过我自己实现了个 def clippy(self, img: Image, sxy: (int, int), cmapper: callable=None) -> Image: sx, sy = sxy self.log.info('Scale', (sx, sy)) rangx = range (0, img.width, sx) rangy = range (0, img.height, sy) width, height = list(map(len, (rangx, rangy))) #print(rangx,width, rangy,height) cblk = Image.new(self.space, (width,height), Montage.RGBA_0) nx, ny = (0, 0) for x in rangx: hline = [i for i in range (x, x+sx)] for y in rangy: # generate blk vline = [i for i in range (y, y+sy)] block = [] for p in Montage.points2D(hline, vline): try: block.append(img.getpixel(p)) except IndexError: pass coloravg = Montage.caverage(block) # 本块均色 #self.log.debug((hline, vline), block, coloravg, (nx,ny)) cblk.putpixel((nx, ny), tuple(coloravg) if cmapper==None else cmapper(tuple(coloravg))) ny += 1 nx += 1; ny = 0 return cblk # 生成彩色蒙太奇,虽然低性能但是不着急(很稳,删除) def generate_cmap(self, img: Image) -> (Image, list): skips = self.ratio_skip(img) if skips != (1,1): img = self.clippy(img, skips) fntsz = self.font.getsize(self.text) clipf = self.clippy(img, fntsz) coord = (clipf.width, clipf.height) print('TextXY', fntsz, 'Clipped', coord, file=stderr) monsrc = [] for ix, iy in Montage.points2D( range(0, coord[0]), range(0, coord[1]) ): monsrc.append(( (ix*fntsz[0], iy*fntsz[1]), clipf.getpixel((ix,iy)))) return clipf, (Montage.coord(img), monsrc) def generate(self, img: Image) -> Image: cord, src = self.generate_cmap(img)[1] montage = Image.new(self.space, cord, Montage.RGBA_0) draw = ImageDraw.Draw(montage) for p, c in src: draw.text(p, self.text, font=self.font, fill=c) return montage def selectGsChar(self, avg, cr): graytexts = self.graytexts txtlen = len(graytexts) i = int(cr-avg) % txtlen return ord(graytexts[i]) # 生成 ASCII Art def generate_grayscale(self, img: Image) -> str: scaled = self.clippy(img, self.ratio_skip(img)) scaled.show() co = Montage.coord(scaled) vline, hline = (range (0,co[0]), range (0,co[1])) gray = [Montage.grayscale(scaled.getpixel(p)) for p in Montage.points2D(hline, vline)] ts = bytearray(len(gray)) avg = 0; ac = 1 for n in hline: i = (co[0]*n) for m in vline: c = gray[i+m] avg = divmod((avg + c), ac)[0]; ac += 1 ts[i+m] = self.selectGsChar(avg, c) ts[i] = ord('\n') return ts # 此应用主函数处理参数: # + image [...] 遍历生成目标图像 # + --output-format save(...) 格式 # + --output-fmtstr save(...) 文件名,@ 表示输入名、# 表示输入序号 # + --grayscale 指示使用 generate_grayscale # + -o 指示 grayscale 模式的输出文件 def main(args): cfg = app.parse_args(args) txt, tgs = [cfg.text, cfg.text_grayscale] montage = Montage(cfg.convert, txt, tgs, scale=cfg.scale, skipXY=cfg.scaleXY, font=cfg.font, fontsz=cfg.font_size) tout = cfg.o for i, img in enumerate(cfg.image[1:len(cfg.image)]): ofname = solve_opathfmt(cfg.output_fmtstr, img, str(i+1)) img = Image.open(img).convert(cfg.convert) print('Image', (img.width, img.height), 'Scale', cfg.scaleXY, file=stderr) if cfg.grayscale: textmon = montage.generate_grayscale(img) write_or_createw(textmon, tout, ofname) continue elif cfg.print_render_src: avgscale, monsrc = montage.generate_cmap(img) avgscale.show(title=ofname) print('Image (w, h)', monsrc[0]) for p, c in (monsrc[1]): for t in ['#', sharpcolor(c), ' ']: stdout.write(t) print(p[0],p[1], sep=':') continue mon = montage.generate(img) if cfg.preview is not None or cfg.do_preview: mon.show(title=ofname, command=cfg.preview) continue mon.save(ofname, cfg.output_format) if tout is not None: tout.close() def sharpcolor(cvs): return ''.join(map(lambda i: hex(i)[2:], cvs)) # Write to non-null of or create nf & write def write_or_createw(o, of, nf: str, p=lambda f: f.writable(), mode='w+'): if of is not None and p(of): return of.buffer.write(o) else: with open(nf, mode) as out: return out.buffer.write(o) # @=ifname; #=output_no def solve_opathfmt(fmt: str, ifname, ofno) -> str: oat, osharp = list(map(ord, "@#")) return fmt.translate({oat: ifname, osharp: ofno}) from sys import argv if __name__ == '__main__': main(argv)
from collections import OrderedDict import h5py import json from datetime import datetime import hashlib import urllib import base64 import logging from pathlib import Path import re from typing import List import numpy as np import requests # for HTTP requests from .docstream import MappedH5Generator from .model import Mapping, Issue from .util import IssueCollectorMixin logger = logging.getLogger("splash_ingest") can_debug = logger.isEnabledFor(logging.DEBUG) class ScicatCommError(Exception): def __init__(self, message): self.message = message class ScicatIngestor(IssueCollectorMixin): # settables host = "localhost:3000" baseurl = "http://" + host + "/api/v3/" # timeouts = (4, 8) # we are hitting a transmission timeout... timeouts = None # we are hitting a transmission timeout... sslVerify = True # do not check certificate username = "ingestor" # default username password = "aman" # default password delete_existing = False # You should see a nice, but abbreviated table here with the logbook contents. token = None # store token here settables = ['host', 'baseurl', 'timeouts', 'sslVerify', 'username', 'password', 'token', "job_id"] pid = 0 # gets set if you search for something entries = None # gets set if you search for something datasetType = "RawDatasets" datasetTypes = ["RawDatasets", "DerivedDatasets", "Proposals"] job_id = "0" test = False def __init__(self, dataset_id, issues: List[Issue], **kwargs): self.dataset_id = dataset_id self.stage = "scicat" self._issues = issues # nothing to do for key, value in kwargs.items(): assert key in self.settables, f"key {key} is not a valid input argument" setattr(self, key, value) logger.info(f"Starting ingestor talking to scicat at: {self.baseurl}") if self.baseurl[-1] != "/": self.baseurl = self.baseurl + "/" logger.info(f"Baseurl corrected to: {self.baseurl}") def _get_token(self, username=None, password=None): if username is None: username = self.username if password is None: password = self.password """logs in using the provided username / password combination and receives token for further communication use""" logger.info(f"{self.job_id} Getting new token for user {username}") response = requests.post( self.baseurl + "Users/login", json={"username": username, "password": password}, timeout=self.timeouts, stream=False, verify=self.sslVerify, ) if not response.ok: logger.error(f'{self.job_id} ** Error received: {response}') err = response.json()["error"] logger.error(f'{self.job_id} {err['name']}, {err['statusCode']}: {err['message']}') self.add_error(f'error getting token {err['name']}, {err['statusCode']}: {err['message']}') return None data = response.json() # print("Response:", data) token = data["id"] # not sure if semantically correct logger.info(f"{self.job_id} token: {token}") self.token = token # store new token return token def _send_to_scicat(self, url, dataDict=None, cmd="post"): """ sends a command to the SciCat API server using url and token, returns the response JSON Get token with the getToken method""" if cmd == "post": response = requests.post( url, params={"access_token": self.token}, json=dataDict, timeout=self.timeouts, stream=False, verify=self.sslVerify, ) elif cmd == "delete": response = requests.delete( url, params={"access_token": self.token}, timeout=self.timeouts, stream=False, verify=self.sslVerify, ) elif cmd == "get": response = requests.get( url, params={"access_token": self.token}, json=dataDict, timeout=self.timeouts, stream=False, verify=self.sslVerify, ) elif cmd == "patch": response = requests.patch( url, params={"access_token": self.token}, json=dataDict, timeout=self.timeouts, stream=False, verify=self.sslVerify, ) return response def _get_file_size(self, pathobj): filesize = pathobj.lstat().st_size return filesize def _get_checksum(self, pathobj): with open(pathobj) as file_to_check: # pipe contents of the file through return hashlib.md5(file_to_check.read()).hexdigest() def ingest_run(self, filepath, run_start, descriptor_doc, event_sample=None, thumbnails=None): logger.info(f"{self.job_id} Scicat ingestion started for {filepath} and uid {self.dataset_id}") # get token try: self.token = self._get_token(username=self.username, password=self.password) except Exception as e: self.add_error("Could not generate token. Exiting.", e) return if not self.token: self.add_error("could not create token, exiting") return logger.info(f"{self.job_id} Ingesting file {filepath}") try: projected_start_doc = project_start_doc(run_start, "app") except Exception as e: self.add_error("error projecting start document. Exiting.", e) return if can_debug: logger.debug(f"{self.job_id} projected start doc: {json.dumps(projected_start_doc)}") access_controls = calculate_access_controls(self.username, projected_start_doc) logger.info(f"Access controls for {filepath} access_groups: {access_controls.get("accessroups")} "\ f"owner_group: {access_controls.get("owner_group")}") try: self._create_sample( projected_start_doc, access_controls.get("access_groups"), access_controls.get("owner_group")) except Exception as e: self.add_error(f"Error creating sample for {filepath}. Continuing without sample.", e) try: scientific_metadata = self._extract_scientific_metadata(descriptor_doc, event_sample, run_start=run_start) except Exception as e: self.add_error(f"Error getting scientific metadata. Continuing without.", e) try: self._create_raw_dataset( projected_start_doc, scientific_metadata, access_controls.get("access_groups"), access_controls.get("owner_group"), filepath, thumbnails) except Exception as e: self.add_error("Error creating raw data set.", e) def _create_sample(self, projected_start_doc, access_groups, owner_group): sample = { "sampleId": projected_start_doc.get('sample_id'), "owner": projected_start_doc.get('pi_name'), "description": projected_start_doc.get('sample_name'), "createdAt": datetime.isoformat(datetime.utcnow()) + "Z", "sampleCharacteristics": {}, "isPublished": False, "ownerGroup": owner_group, "accessGroups": access_groups, "createdBy": self.username, "updatedBy": self.username, "updatedAt": datetime.isoformat(datetime.utcnow()) + "Z" } sample_url = f'{self.baseurl}Samples' resp = self._send_to_scicat(sample_url, sample) if not resp.ok: # can happen if sample id is a duplicate, but we can't tell that from the response err = resp.json()["error"] raise ScicatCommError(f"Error creating Sample {err}") def _get_field(self, field_name: str, projected_dict: dict, default_val): "some fields are required by scicat but we don't want to blow up, rather provide a default value" if projected_dict.get(field_name): return projected_dict.get(field_name) else: self.add_warning(f"missing field {field_name} defaulting to {str(default_val)}") return default_val def _create_raw_dataset(self, projected_start_doc, scientific_metadata, access_groups, owner_group, filepath, thumbnails): # model for the raw datasets as defined in the RawDatasets, required fields: # pid # owner # contactEmail # sourceFolder # creationTime # type creation_time_raw = self._get_field('collection_date', projected_start_doc, [datetime.now()]) creation_time = (datetime.isoformat(datetime.fromtimestamp(creation_time_raw[0])) + "Z") data = { "pid": self.dataset_id, "owner": self._get_field('pi_name', projected_start_doc, "unavailable"), "contactEmail": self._get_field('experimenter_email', projected_start_doc, "unavailable"), "createdBy": self.username, "updatedBy": self.username, "creationLocation": self._get_field('beamline', projected_start_doc, 'unkown'), "updatedAt": datetime.isoformat(datetime.utcnow()) + "Z", "createdAt": datetime.isoformat(datetime.utcnow()) + "Z", "creationTime": creation_time, "datasetName": filepath.stem, "type": "raw", "instrumentId": projected_start_doc.get('instrument_name'), "ownerGroup": owner_group, "accessGroups": access_groups, "proposalId": projected_start_doc.get('proposal'), "dataFormat": "DX", "principalInvestigator": self._get_field('pi_name', projected_start_doc, "unknown"), "sourceFolder": filepath.parent.as_posix(), "size": self._get_file_size(filepath), "scientificMetadata": scientific_metadata, "sampleId": projected_start_doc.get('sample_id'), "isPublished": False, "description": build_search_terms(projected_start_doc) } encoded_data = json.loads(json.dumps(data, cls=NPArrayEncoder)) # create dataset raw_dataset_url = self.baseurl + "RawDataSets/replaceOrCreate" resp = self._send_to_scicat(raw_dataset_url, encoded_data) if not resp.ok: err = resp.json()["error"] raise ScicatCommError(f"Error creating raw dataset {err}") new_pid = resp.json().get('pid') logger.info(f"{self.job_id} new dataset created {new_pid}") # upload thumbnail if thumbnails: for thumbnail in thumbnails: if thumbnail.exists(): logger.info(f"Uploading thumbnail {thumbnail}") resp = self._addThumbnail( new_pid, thumbnail, datasetType="RawDatasets", owner_group=owner_group, access_groups=access_groups) logger.info(f"Thumnail written {thumbnail}") if resp.ok: logger.info(f"{self.job_id} thumbnail created for {new_pid}") else: err = resp.json()["error"] raise ScicatCommError(f"Error creating datablock. {err}", ) elif not thumbnail.exists(): logger.info(f"Thumbnail {thumbnail} does not exist") else: logger.info("Thumbnails not specified") datasetType = "RawDatasets" dataBlock = { # "id": npid, "size": self._get_file_size(filepath), "dataFileList": [ { "path": str(filepath.name), "size": self._get_file_size(filepath), "time": self._get_file_mod_time(filepath), "chk": "", # do not do remote: getFileChecksumFromPathObj(filename) "uid": str( filepath.stat().st_uid ), # not implemented on windows: filename.owner(), "gid": str(filepath.stat().st_gid), "perm": str(filepath.stat().st_mode), } ], "ownerGroup": owner_group, "accessGroups": access_groups, "createdBy": self.username, "updatedBy": self.username, "datasetId": new_pid, "updatedAt": datetime.isoformat(datetime.utcnow()) + "Z", "createdAt": datetime.isoformat(datetime.utcnow()) + "Z", } url = self.baseurl + f"{datasetType}/{urllib.parse.quote_plus(new_pid)}/origdatablocks" logger.info(f"{self.job_id} sending to {url} accessGroups: {access_groups}, ownerGroup: {owner_group}") logger.info(f"datablock: {json.dumps(dataBlock)}") resp = self._send_to_scicat(url, dataBlock) if not resp.ok: err = resp.json()["error"] raise ScicatCommError(f"Error creating datablock. {err}") logger.info(f"{self.job_id} origdatablock sent for {new_pid}") @staticmethod def _extract_scientific_metadata(descriptor, event_page, run_start=None): return_dict = {k.replace(":", "/"): v for k, v in descriptor['configuration']['all']['data'].items()} if event_page: return_dict['data_sample'] = event_page if run_start: return_dict['run_start_uid'] = run_start['uid'] return OrderedDict(sorted(return_dict.items())) @staticmethod def _get_file_mod_time(pathobj): # may only work on WindowsPath objects... # timestamp = pathobj.lstat().st_mtime return str(datetime.fromtimestamp(pathobj.lstat().st_mtime)) def _addThumbnail(self, datasetId=None, filename=None, datasetType="RawDatasets", owner_group=None, access_groups=None): def encodeImageToThumbnail(filename, imType='jpg'): logging.info(f"Creating thumbnail for dataset: {filename}") header = "data:image/{imType};base64,".format(imType=imType) with open(filename, 'rb') as f: data = f.read() dataBytes = base64.b64encode(data) dataStr = dataBytes.decode('UTF-8') return header + dataStr dataBlock = { "caption": filename.stem, "thumbnail": encodeImageToThumbnail(filename), "datasetId": datasetId, "ownerGroup": owner_group, "accessGroups": access_groups } logging.info(f"Adding thumbnail for dataset: {datasetId}") url = self.baseurl + f"{datasetType}/{urllib.parse.quote_plus(datasetId)}/attachments" logging.debug(url) resp = requests.post( url, params={"access_token": self.token}, timeout=self.timeouts, stream=False, json=dataBlock, verify=self.sslVerify) return resp class NPArrayEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() return json.JSONEncoder.default(self, obj) def gen_ev_docs(scm: ScicatIngestor, filename: str, mapping_file: str): with open(mapping_file, 'r') as json_file: data = json.load(json_file) map = Mapping(**data) with h5py.File(filename, 'r') as h5_file: ingestor = MappedH5Generator( [], map, h5_file, 'root', thumbs_root='/home/dylan/data/beamlines/als832/thumbs', data_groups=['als832']) descriptor = None start_doc = None for name, doc in ingestor.generate_docstream(): if 'start' in name: start_doc = doc continue if 'descriptor' in name: descriptor = doc continue else: continue scm.ingest_run(Path(filename), start_doc, descriptor_doc=descriptor, thumbnail=ingestor.thumbnails[0]) def calculate_access_controls(username, projected_start_doc): # make an access grop list that includes the name of the proposal and the name of the beamline access_groups = [] # set owner_group to username so that at least someone has access in case no proposal number is found owner_group = username if projected_start_doc.get('beamline'): access_groups.append(projected_start_doc.get('beamline')) # username lets the user see the Dataset in order to ingest objects after the Dataset access_groups.append(username) # temporary mapping while beamline controls process request to match beamline name with what comes # from ALSHub if projected_start_doc.get('beamline') =="bl832": access_groups.append("8.3.2") if projected_start_doc.get('proposal') and projected_start_doc.get('proposal') != 'None': owner_group = projected_start_doc.get('proposal') # this is a bit of a kludge. Add 8.3.2 into the access groups so that staff will be able to see it return {"owner_group": owner_group, "access_groups": access_groups} def project_start_doc(start_doc, intent): found_projection = None projection = {} for projection in start_doc.get('projections'): configuration = projection.get('configuration') if configuration is None: continue if configuration.get('intent') == intent: if found_projection: raise Exception(f"Found more than one projection matching intent: {intent}") found_projection = projection if not found_projection: raise Exception(f"Could not find a projection matching intent: {intent}") projected_doc = {} for field, value in found_projection['projection'].items(): if value['location'] == "start": projected_doc[field] = start_doc.get(value['field']) return projected_doc def build_search_terms(projected_start): ''' exctract search terms from sample name to provide something pleasing to search on ''' terms = re.split('[^a-zA-Z0-9]', projected_start.get('sample_name')) description = [term.lower() for term in terms if len(term) > 0] return ' '.join(description) # return " ".join(re.sub(r'[^A-Za-z0-9 ]+', ' ', projected_start.get('sample_name')).split()); if __name__ == "__main__": ch = logging.StreamHandler() # ch.setLevel(logging.INFO) # root_logger.addHandler(ch) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) logger.setLevel(logging.DEBUG) can_debug = logger.isEnabledFor(logging.DEBUG) can_info = logger.isEnabledFor(logging.INFO) issues = [] scm = ScicatIngestor(password="23ljlkw", issues=issues) gen_ev_docs(scm, '/home/dylan/data/beamlines/als832/20210421_091523_test3.h5', './mappings/832Mapping.json')
from collections import OrderedDict import h5py import json from datetime import datetime import hashlib import urllib import base64 import logging from pathlib import Path import re from typing import List import numpy as np import requests # for HTTP requests from .docstream import MappedH5Generator from .model import Mapping, Issue from .util import IssueCollectorMixin logger = logging.getLogger("splash_ingest") can_debug = logger.isEnabledFor(logging.DEBUG) class ScicatCommError(Exception): def __init__(self, message): self.message = message class ScicatIngestor(IssueCollectorMixin): # settables host = "localhost:3000" baseurl = "http://" + host + "/api/v3/" # timeouts = (4, 8) # we are hitting a transmission timeout... timeouts = None # we are hitting a transmission timeout... sslVerify = True # do not check certificate username = "ingestor" # default username password = "aman" # default password delete_existing = False # You should see a nice, but abbreviated table here with the logbook contents. token = None # store token here settables = ['host', 'baseurl', 'timeouts', 'sslVerify', 'username', 'password', 'token', "job_id"] pid = 0 # gets set if you search for something entries = None # gets set if you search for something datasetType = "RawDatasets" datasetTypes = ["RawDatasets", "DerivedDatasets", "Proposals"] job_id = "0" test = False def __init__(self, dataset_id, issues: List[Issue], **kwargs): self.dataset_id = dataset_id self.stage = "scicat" self._issues = issues # nothing to do for key, value in kwargs.items(): assert key in self.settables, f"key {key} is not a valid input argument" setattr(self, key, value) logger.info(f"Starting ingestor talking to scicat at: {self.baseurl}") if self.baseurl[-1] != "/": self.baseurl = self.baseurl + "/" logger.info(f"Baseurl corrected to: {self.baseurl}") def _get_token(self, username=None, password=None): if username is None: username = self.username if password is None: password = self.password """logs in using the provided username / password combination and receives token for further communication use""" logger.info(f"{self.job_id} Getting new token for user {username}") response = requests.post( self.baseurl + "Users/login", json={"username": username, "password": password}, timeout=self.timeouts, stream=False, verify=self.sslVerify, ) if not response.ok: logger.error(f'{self.job_id} ** Error received: {response}') err = response.json()["error"] logger.error(f'{self.job_id} {err["name"]}, {err["statusCode"]}: {err["message"]}') self.add_error(f'error getting token {err["name"]}, {err["statusCode"]}: {err["message"]}') return None data = response.json() # print("Response:", data) token = data["id"] # not sure if semantically correct logger.info(f"{self.job_id} token: {token}") self.token = token # store new token return token def _send_to_scicat(self, url, dataDict=None, cmd="post"): """ sends a command to the SciCat API server using url and token, returns the response JSON Get token with the getToken method""" if cmd == "post": response = requests.post( url, params={"access_token": self.token}, json=dataDict, timeout=self.timeouts, stream=False, verify=self.sslVerify, ) elif cmd == "delete": response = requests.delete( url, params={"access_token": self.token}, timeout=self.timeouts, stream=False, verify=self.sslVerify, ) elif cmd == "get": response = requests.get( url, params={"access_token": self.token}, json=dataDict, timeout=self.timeouts, stream=False, verify=self.sslVerify, ) elif cmd == "patch": response = requests.patch( url, params={"access_token": self.token}, json=dataDict, timeout=self.timeouts, stream=False, verify=self.sslVerify, ) return response def _get_file_size(self, pathobj): filesize = pathobj.lstat().st_size return filesize def _get_checksum(self, pathobj): with open(pathobj) as file_to_check: # pipe contents of the file through return hashlib.md5(file_to_check.read()).hexdigest() def ingest_run(self, filepath, run_start, descriptor_doc, event_sample=None, thumbnails=None): logger.info(f"{self.job_id} Scicat ingestion started for {filepath} and uid {self.dataset_id}") # get token try: self.token = self._get_token(username=self.username, password=self.password) except Exception as e: self.add_error("Could not generate token. Exiting.", e) return if not self.token: self.add_error("could not create token, exiting") return logger.info(f"{self.job_id} Ingesting file {filepath}") try: projected_start_doc = project_start_doc(run_start, "app") except Exception as e: self.add_error("error projecting start document. Exiting.", e) return if can_debug: logger.debug(f"{self.job_id} projected start doc: {json.dumps(projected_start_doc)}") access_controls = calculate_access_controls(self.username, projected_start_doc) logger.info(f"Access controls for {filepath} access_groups: {access_controls.get('accessroups')} "\ f"owner_group: {access_controls.get('owner_group')}") try: self._create_sample( projected_start_doc, access_controls.get("access_groups"), access_controls.get("owner_group")) except Exception as e: self.add_error(f"Error creating sample for {filepath}. Continuing without sample.", e) try: scientific_metadata = self._extract_scientific_metadata(descriptor_doc, event_sample, run_start=run_start) except Exception as e: self.add_error(f"Error getting scientific metadata. Continuing without.", e) try: self._create_raw_dataset( projected_start_doc, scientific_metadata, access_controls.get("access_groups"), access_controls.get("owner_group"), filepath, thumbnails) except Exception as e: self.add_error("Error creating raw data set.", e) def _create_sample(self, projected_start_doc, access_groups, owner_group): sample = { "sampleId": projected_start_doc.get('sample_id'), "owner": projected_start_doc.get('pi_name'), "description": projected_start_doc.get('sample_name'), "createdAt": datetime.isoformat(datetime.utcnow()) + "Z", "sampleCharacteristics": {}, "isPublished": False, "ownerGroup": owner_group, "accessGroups": access_groups, "createdBy": self.username, "updatedBy": self.username, "updatedAt": datetime.isoformat(datetime.utcnow()) + "Z" } sample_url = f'{self.baseurl}Samples' resp = self._send_to_scicat(sample_url, sample) if not resp.ok: # can happen if sample id is a duplicate, but we can't tell that from the response err = resp.json()["error"] raise ScicatCommError(f"Error creating Sample {err}") def _get_field(self, field_name: str, projected_dict: dict, default_val): "some fields are required by scicat but we don't want to blow up, rather provide a default value" if projected_dict.get(field_name): return projected_dict.get(field_name) else: self.add_warning(f"missing field {field_name} defaulting to {str(default_val)}") return default_val def _create_raw_dataset(self, projected_start_doc, scientific_metadata, access_groups, owner_group, filepath, thumbnails): # model for the raw datasets as defined in the RawDatasets, required fields: # pid # owner # contactEmail # sourceFolder # creationTime # type creation_time_raw = self._get_field('collection_date', projected_start_doc, [datetime.now()]) creation_time = (datetime.isoformat(datetime.fromtimestamp(creation_time_raw[0])) + "Z") data = { "pid": self.dataset_id, "owner": self._get_field('pi_name', projected_start_doc, "unavailable"), "contactEmail": self._get_field('experimenter_email', projected_start_doc, "unavailable"), "createdBy": self.username, "updatedBy": self.username, "creationLocation": self._get_field('beamline', projected_start_doc, 'unkown'), "updatedAt": datetime.isoformat(datetime.utcnow()) + "Z", "createdAt": datetime.isoformat(datetime.utcnow()) + "Z", "creationTime": creation_time, "datasetName": filepath.stem, "type": "raw", "instrumentId": projected_start_doc.get('instrument_name'), "ownerGroup": owner_group, "accessGroups": access_groups, "proposalId": projected_start_doc.get('proposal'), "dataFormat": "DX", "principalInvestigator": self._get_field('pi_name', projected_start_doc, "unknown"), "sourceFolder": filepath.parent.as_posix(), "size": self._get_file_size(filepath), "scientificMetadata": scientific_metadata, "sampleId": projected_start_doc.get('sample_id'), "isPublished": False, "description": build_search_terms(projected_start_doc) } encoded_data = json.loads(json.dumps(data, cls=NPArrayEncoder)) # create dataset raw_dataset_url = self.baseurl + "RawDataSets/replaceOrCreate" resp = self._send_to_scicat(raw_dataset_url, encoded_data) if not resp.ok: err = resp.json()["error"] raise ScicatCommError(f"Error creating raw dataset {err}") new_pid = resp.json().get('pid') logger.info(f"{self.job_id} new dataset created {new_pid}") # upload thumbnail if thumbnails: for thumbnail in thumbnails: if thumbnail.exists(): logger.info(f"Uploading thumbnail {thumbnail}") resp = self._addThumbnail( new_pid, thumbnail, datasetType="RawDatasets", owner_group=owner_group, access_groups=access_groups) logger.info(f"Thumnail written {thumbnail}") if resp.ok: logger.info(f"{self.job_id} thumbnail created for {new_pid}") else: err = resp.json()["error"] raise ScicatCommError(f"Error creating datablock. {err}", ) elif not thumbnail.exists(): logger.info(f"Thumbnail {thumbnail} does not exist") else: logger.info("Thumbnails not specified") datasetType = "RawDatasets" dataBlock = { # "id": npid, "size": self._get_file_size(filepath), "dataFileList": [ { "path": str(filepath.name), "size": self._get_file_size(filepath), "time": self._get_file_mod_time(filepath), "chk": "", # do not do remote: getFileChecksumFromPathObj(filename) "uid": str( filepath.stat().st_uid ), # not implemented on windows: filename.owner(), "gid": str(filepath.stat().st_gid), "perm": str(filepath.stat().st_mode), } ], "ownerGroup": owner_group, "accessGroups": access_groups, "createdBy": self.username, "updatedBy": self.username, "datasetId": new_pid, "updatedAt": datetime.isoformat(datetime.utcnow()) + "Z", "createdAt": datetime.isoformat(datetime.utcnow()) + "Z", } url = self.baseurl + f"{datasetType}/{urllib.parse.quote_plus(new_pid)}/origdatablocks" logger.info(f"{self.job_id} sending to {url} accessGroups: {access_groups}, ownerGroup: {owner_group}") logger.info(f"datablock: {json.dumps(dataBlock)}") resp = self._send_to_scicat(url, dataBlock) if not resp.ok: err = resp.json()["error"] raise ScicatCommError(f"Error creating datablock. {err}") logger.info(f"{self.job_id} origdatablock sent for {new_pid}") @staticmethod def _extract_scientific_metadata(descriptor, event_page, run_start=None): return_dict = {k.replace(":", "/"): v for k, v in descriptor['configuration']['all']['data'].items()} if event_page: return_dict['data_sample'] = event_page if run_start: return_dict['run_start_uid'] = run_start['uid'] return OrderedDict(sorted(return_dict.items())) @staticmethod def _get_file_mod_time(pathobj): # may only work on WindowsPath objects... # timestamp = pathobj.lstat().st_mtime return str(datetime.fromtimestamp(pathobj.lstat().st_mtime)) def _addThumbnail(self, datasetId=None, filename=None, datasetType="RawDatasets", owner_group=None, access_groups=None): def encodeImageToThumbnail(filename, imType='jpg'): logging.info(f"Creating thumbnail for dataset: {filename}") header = "data:image/{imType};base64,".format(imType=imType) with open(filename, 'rb') as f: data = f.read() dataBytes = base64.b64encode(data) dataStr = dataBytes.decode('UTF-8') return header + dataStr dataBlock = { "caption": filename.stem, "thumbnail": encodeImageToThumbnail(filename), "datasetId": datasetId, "ownerGroup": owner_group, "accessGroups": access_groups } logging.info(f"Adding thumbnail for dataset: {datasetId}") url = self.baseurl + f"{datasetType}/{urllib.parse.quote_plus(datasetId)}/attachments" logging.debug(url) resp = requests.post( url, params={"access_token": self.token}, timeout=self.timeouts, stream=False, json=dataBlock, verify=self.sslVerify) return resp class NPArrayEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() return json.JSONEncoder.default(self, obj) def gen_ev_docs(scm: ScicatIngestor, filename: str, mapping_file: str): with open(mapping_file, 'r') as json_file: data = json.load(json_file) map = Mapping(**data) with h5py.File(filename, 'r') as h5_file: ingestor = MappedH5Generator( [], map, h5_file, 'root', thumbs_root='/home/dylan/data/beamlines/als832/thumbs', data_groups=['als832']) descriptor = None start_doc = None for name, doc in ingestor.generate_docstream(): if 'start' in name: start_doc = doc continue if 'descriptor' in name: descriptor = doc continue else: continue scm.ingest_run(Path(filename), start_doc, descriptor_doc=descriptor, thumbnail=ingestor.thumbnails[0]) def calculate_access_controls(username, projected_start_doc): # make an access grop list that includes the name of the proposal and the name of the beamline access_groups = [] # set owner_group to username so that at least someone has access in case no proposal number is found owner_group = username if projected_start_doc.get('beamline'): access_groups.append(projected_start_doc.get('beamline')) # username lets the user see the Dataset in order to ingest objects after the Dataset access_groups.append(username) # temporary mapping while beamline controls process request to match beamline name with what comes # from ALSHub if projected_start_doc.get('beamline') =="bl832": access_groups.append("8.3.2") if projected_start_doc.get('proposal') and projected_start_doc.get('proposal') != 'None': owner_group = projected_start_doc.get('proposal') # this is a bit of a kludge. Add 8.3.2 into the access groups so that staff will be able to see it return {"owner_group": owner_group, "access_groups": access_groups} def project_start_doc(start_doc, intent): found_projection = None projection = {} for projection in start_doc.get('projections'): configuration = projection.get('configuration') if configuration is None: continue if configuration.get('intent') == intent: if found_projection: raise Exception(f"Found more than one projection matching intent: {intent}") found_projection = projection if not found_projection: raise Exception(f"Could not find a projection matching intent: {intent}") projected_doc = {} for field, value in found_projection['projection'].items(): if value['location'] == "start": projected_doc[field] = start_doc.get(value['field']) return projected_doc def build_search_terms(projected_start): ''' exctract search terms from sample name to provide something pleasing to search on ''' terms = re.split('[^a-zA-Z0-9]', projected_start.get('sample_name')) description = [term.lower() for term in terms if len(term) > 0] return ' '.join(description) # return " ".join(re.sub(r'[^A-Za-z0-9 ]+', ' ', projected_start.get('sample_name')).split()); if __name__ == "__main__": ch = logging.StreamHandler() # ch.setLevel(logging.INFO) # root_logger.addHandler(ch) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) logger.setLevel(logging.DEBUG) can_debug = logger.isEnabledFor(logging.DEBUG) can_info = logger.isEnabledFor(logging.INFO) issues = [] scm = ScicatIngestor(password="23ljlkw", issues=issues) gen_ev_docs(scm, '/home/dylan/data/beamlines/als832/20210421_091523_test3.h5', './mappings/832Mapping.json')
import subprocess from collections import defaultdict from util import database, toolchain, bitdiff, progress with database.transact() as db: for device_name, device in db.items(): progress(device_name) package, pinout = next(iter(device['pins'].items())) goe_names = [name for name in device['globals'] if name.startswith("GOE")] goe_mux_range = range(*device['ranges']['goe_muxes']) assert len(goe_mux_range) % len(goe_names) == 0 goe_mux_size = len(goe_mux_range) // len(goe_names) for goe_index, goe_name in enumerate(goe_names): device['globals'][goe_name]['mux'] = { 'fuses': list(range(goe_mux_range.start + goe_mux_size * goe_index, goe_mux_range.start + goe_mux_size * (goe_index + 1))), 'values': {} } goe_muxes = {name: device['globals'][name]['mux'] for name in goe_names} def run_pads(pad_names): ports = [] cells = [] pins = {} used_pads = set(pad_names) for n, pad_name in enumerate(pad_names): for other_macrocell_name, other_macrocell in device['macrocells'].items(): if (other_macrocell['pad'] not in used_pads and other_macrocell['pad'] in pinout): used_pads.add(other_macrocell['pad']) break else: assert False ports += [f"input OE{n}", f"output O{n}"] cells += [f"wire Q{n}; DFFAS dff{n}(1'b0, O{n}, 1'b0, Q{n}); ", f"TRI t{n}(Q{n}, OE{n}, O{n}); "] pins.update({ f"O{n}": pinout[other_macrocell['pad']], f"OE{n}": pinout[pad_name], }) return toolchain.run( f"module top({", ".join(ports)}); " f"{" ".join(cells)} " f"endmodule", pins, f"{device_name}-{package}") # So, GOE mux feedback inputs. Where do I start... # This CUPL works and does what I expect: # # Name top; # Device f1502tqfp44; # PIN = OEA; # PIN = OEB; # PIN = Y0; # PIN = Y1; # PIN = I0; # PIN = I1; # [Y1..Y0] = [I1..I0].io; # [Y1..Y0].oe = !OEA & !OEB; # PROPERTY ATMEL {JTAG=OFF}; # PROPERTY ATMEL {Global_OE=Y0}; # # This Verilog, which produces EDIF -completely equivalent in every aspect-, does not: # # //OPT: -strategy JTAG off # //OPT: -strategy Global_OE Y0 # module top(input I0,I1, input OEA,OEB, output Y0,Y1); # wire OE; AND2I2 a1(OEA,OEB,OE); # wire OEL; LATCH l(.EN(1'b1), .D(OE), .Q(OEL)); # TRI t1(I0,OEL,Y0); # TRI t2(I1,OEL,Y1); # endmodule # # It looks like, for some completely incomprehensible reason, with TT2 input, the fitter # generates a latch for the buried node that is always enabled, which lets it use # the buried node for GOE, even though there's no latch in the input netlist, and also # it's useless. Whether this latch is present or not in the EDIF, EDIF input will never # cause buried nodes to be used for GOE. def run_fb(macrocell_idx, macrocell_name): for other1_macrocell_name, other1_macrocell in device['macrocells'].items(): if other1_macrocell_name != macrocell_name: break else: assert False for other2_macrocell_name, other2_macrocell in device['macrocells'].items(): if (other2_macrocell_name != macrocell_name and other2_macrocell_name != other1_macrocell_name): break else: assert False pins = [ f"OEA+:{pinout["C1"]}", f"OEB+:{pinout["C2"]}", f"Y0+:{pinout[device["macrocells"][other1_macrocell_name]["pad"]]}", f"Y1+:{pinout[device["macrocells"][other2_macrocell_name]["pad"]]}" ] return toolchain.run(f""" #$ PINS 4 {' '.join(pins)} #$ PROPERTY ATMEL Global_OE = Y0 #$ PROPERTY ATMEL OE_node = {str(601 + macrocell_idx)} .i 2 .o 4 .type f .ilb OEA OEB .ob Y0 Y0.OE Y1 Y1.OE .phase 1111 .p 2 -- 0000 00 0101 .e """, None, f"{device_name}-{package}", strategy={'logic_doubling':'on'}, format='tt') def has_mux_value(node_name, fuses): for mux_name, mux in goe_muxes.items(): gnd_value = (1 << len(mux['fuses'])) - 1 value = sum(fuses[fuse] << n_fuse for n_fuse, fuse in enumerate(mux['fuses'])) if value == gnd_value: continue if node_name in mux['values']: assert mux['values'][node_name] == value return True return False def add_mux_value(node_name, fuses, *, reserved=()): for mux_name, mux in goe_muxes.items(): if mux_name in reserved: continue gnd_value = (1 << len(mux['fuses'])) - 1 value = sum(fuses[fuse] << n_fuse for n_fuse, fuse in enumerate(mux['fuses'])) if value == gnd_value: continue assert node_name not in mux['values'], \ f"GOE mux {mux_name} already has a value for {node_name}" mux['values'][node_name] = value return mux_name assert False, f"all GOE muxes unprogrammed" worklist = {'C1', 'C2', 'E1'} for macrocell in device['macrocells'].values(): worklist.add(macrocell['pad']) depth = 0 pad_muxes = defaultdict(lambda: set()) mux_pads = defaultdict(lambda: set()) while worklist: progress(3) updates = [] for pad in sorted(worklist): if pad not in pinout: continue progress(2) reserved_muxes = [] reserved_pads = [] if depth > 0: for _, pad_mux_name in zip(range(depth), sorted(pad_muxes[pad])): reserved_muxes.append(pad_mux_name) for other_pad in sorted(mux_pads[pad_mux_name]): if other_pad == pad or other_pad in reserved_pads: continue if pad_muxes[other_pad].intersection(pad_muxes[pad]) != {pad_mux_name}: continue reserved_pads.append(other_pad) break if len(reserved_pads) != len(reserved_muxes): continue try: fuses = run_pads((pad, *reserved_pads)) except subprocess.CalledProcessError as err: if err.returncode != 250: raise # Design constrained so that inability to use GOE is a total failure. continue mux_name = add_mux_value(f"{pad}_PAD", fuses, reserved=reserved_muxes) updates.append((pad, mux_name)) worklist.clear() for pad, mux_name in updates: worklist.add(pad) pad_muxes[pad].add(mux_name) mux_pads[mux_name].add(pad) depth += 1 for macrocell_idx, (macrocell_name, macrocell) in enumerate(device['macrocells'].items()): progress(1) fuses = run_fb(macrocell_idx, macrocell_name) if fuses[macrocell['fb_mux']['fuses'][0]] != macrocell['fb_mux']['values']['sync']: # Cannot constrain design by using AS with CUPL (fitter always rejects), so instead # verify that the only cell that should have sync feedback, has it. continue if has_mux_value(f"{macrocell["pad"]}_PAD", fuses): # Due to a fitter bug, if a combinatorial node that is not itself a legal GOE # driver is constrained using OE_node, and the pad of the macrocell where the node # is placed, conversely, is a legal GOE driver, a miscompilation happens: # the fitter legalizes the node by inserting an always-transparent latch and # setting fb_mux to sync. # # Hardware testing and celestial rituals demonstrate that this is a miscompilation # (i.e. the GOE driver is not affected by fb_mux setting); the legalized node is # ignored, and GOE is driven simply by the pad. # # To account for this bug, ignore any FB mux drivers if a PAD mux driver exists # that refers to the same macrocell. continue add_mux_value(f"{macrocell_name}_FB", fuses) for mux_name, mux in goe_muxes.items(): # Each GOE mux has exactly one fuse which is never used by the fitter. Hardware testing # and celestial rituals demonstrate that this fuse drives the GOE network low. assert len(mux['values']) == len(mux['fuses']) - 1, \ f"GOE mux {mux_name} should have exactly one unused value" # Setting the mux to all-ones (erased state) has the exact same result, so call the GND # with all-ones "GND1" and the GND with one fuse set to 0 "GND0". erased_value = (1 << len(mux['fuses'])) - 1 mux['values']['GND1'] = erased_value for n_fuse in range(len(mux['fuses'])): value = erased_value ^ (1 << n_fuse) if value not in mux['values'].values(): mux['values']['GND0'] = value
import subprocess from collections import defaultdict from util import database, toolchain, bitdiff, progress with database.transact() as db: for device_name, device in db.items(): progress(device_name) package, pinout = next(iter(device['pins'].items())) goe_names = [name for name in device['globals'] if name.startswith("GOE")] goe_mux_range = range(*device['ranges']['goe_muxes']) assert len(goe_mux_range) % len(goe_names) == 0 goe_mux_size = len(goe_mux_range) // len(goe_names) for goe_index, goe_name in enumerate(goe_names): device['globals'][goe_name]['mux'] = { 'fuses': list(range(goe_mux_range.start + goe_mux_size * goe_index, goe_mux_range.start + goe_mux_size * (goe_index + 1))), 'values': {} } goe_muxes = {name: device['globals'][name]['mux'] for name in goe_names} def run_pads(pad_names): ports = [] cells = [] pins = {} used_pads = set(pad_names) for n, pad_name in enumerate(pad_names): for other_macrocell_name, other_macrocell in device['macrocells'].items(): if (other_macrocell['pad'] not in used_pads and other_macrocell['pad'] in pinout): used_pads.add(other_macrocell['pad']) break else: assert False ports += [f"input OE{n}", f"output O{n}"] cells += [f"wire Q{n}; DFFAS dff{n}(1'b0, O{n}, 1'b0, Q{n}); ", f"TRI t{n}(Q{n}, OE{n}, O{n}); "] pins.update({ f"O{n}": pinout[other_macrocell['pad']], f"OE{n}": pinout[pad_name], }) return toolchain.run( f"module top({', '.join(ports)}); " f"{' '.join(cells)} " f"endmodule", pins, f"{device_name}-{package}") # So, GOE mux feedback inputs. Where do I start... # This CUPL works and does what I expect: # # Name top; # Device f1502tqfp44; # PIN = OEA; # PIN = OEB; # PIN = Y0; # PIN = Y1; # PIN = I0; # PIN = I1; # [Y1..Y0] = [I1..I0].io; # [Y1..Y0].oe = !OEA & !OEB; # PROPERTY ATMEL {JTAG=OFF}; # PROPERTY ATMEL {Global_OE=Y0}; # # This Verilog, which produces EDIF -completely equivalent in every aspect-, does not: # # //OPT: -strategy JTAG off # //OPT: -strategy Global_OE Y0 # module top(input I0,I1, input OEA,OEB, output Y0,Y1); # wire OE; AND2I2 a1(OEA,OEB,OE); # wire OEL; LATCH l(.EN(1'b1), .D(OE), .Q(OEL)); # TRI t1(I0,OEL,Y0); # TRI t2(I1,OEL,Y1); # endmodule # # It looks like, for some completely incomprehensible reason, with TT2 input, the fitter # generates a latch for the buried node that is always enabled, which lets it use # the buried node for GOE, even though there's no latch in the input netlist, and also # it's useless. Whether this latch is present or not in the EDIF, EDIF input will never # cause buried nodes to be used for GOE. def run_fb(macrocell_idx, macrocell_name): for other1_macrocell_name, other1_macrocell in device['macrocells'].items(): if other1_macrocell_name != macrocell_name: break else: assert False for other2_macrocell_name, other2_macrocell in device['macrocells'].items(): if (other2_macrocell_name != macrocell_name and other2_macrocell_name != other1_macrocell_name): break else: assert False pins = [ f"OEA+:{pinout['C1']}", f"OEB+:{pinout['C2']}", f"Y0+:{pinout[device['macrocells'][other1_macrocell_name]['pad']]}", f"Y1+:{pinout[device['macrocells'][other2_macrocell_name]['pad']]}" ] return toolchain.run(f""" #$ PINS 4 {' '.join(pins)} #$ PROPERTY ATMEL Global_OE = Y0 #$ PROPERTY ATMEL OE_node = {str(601 + macrocell_idx)} .i 2 .o 4 .type f .ilb OEA OEB .ob Y0 Y0.OE Y1 Y1.OE .phase 1111 .p 2 -- 0000 00 0101 .e """, None, f"{device_name}-{package}", strategy={'logic_doubling':'on'}, format='tt') def has_mux_value(node_name, fuses): for mux_name, mux in goe_muxes.items(): gnd_value = (1 << len(mux['fuses'])) - 1 value = sum(fuses[fuse] << n_fuse for n_fuse, fuse in enumerate(mux['fuses'])) if value == gnd_value: continue if node_name in mux['values']: assert mux['values'][node_name] == value return True return False def add_mux_value(node_name, fuses, *, reserved=()): for mux_name, mux in goe_muxes.items(): if mux_name in reserved: continue gnd_value = (1 << len(mux['fuses'])) - 1 value = sum(fuses[fuse] << n_fuse for n_fuse, fuse in enumerate(mux['fuses'])) if value == gnd_value: continue assert node_name not in mux['values'], \ f"GOE mux {mux_name} already has a value for {node_name}" mux['values'][node_name] = value return mux_name assert False, f"all GOE muxes unprogrammed" worklist = {'C1', 'C2', 'E1'} for macrocell in device['macrocells'].values(): worklist.add(macrocell['pad']) depth = 0 pad_muxes = defaultdict(lambda: set()) mux_pads = defaultdict(lambda: set()) while worklist: progress(3) updates = [] for pad in sorted(worklist): if pad not in pinout: continue progress(2) reserved_muxes = [] reserved_pads = [] if depth > 0: for _, pad_mux_name in zip(range(depth), sorted(pad_muxes[pad])): reserved_muxes.append(pad_mux_name) for other_pad in sorted(mux_pads[pad_mux_name]): if other_pad == pad or other_pad in reserved_pads: continue if pad_muxes[other_pad].intersection(pad_muxes[pad]) != {pad_mux_name}: continue reserved_pads.append(other_pad) break if len(reserved_pads) != len(reserved_muxes): continue try: fuses = run_pads((pad, *reserved_pads)) except subprocess.CalledProcessError as err: if err.returncode != 250: raise # Design constrained so that inability to use GOE is a total failure. continue mux_name = add_mux_value(f"{pad}_PAD", fuses, reserved=reserved_muxes) updates.append((pad, mux_name)) worklist.clear() for pad, mux_name in updates: worklist.add(pad) pad_muxes[pad].add(mux_name) mux_pads[mux_name].add(pad) depth += 1 for macrocell_idx, (macrocell_name, macrocell) in enumerate(device['macrocells'].items()): progress(1) fuses = run_fb(macrocell_idx, macrocell_name) if fuses[macrocell['fb_mux']['fuses'][0]] != macrocell['fb_mux']['values']['sync']: # Cannot constrain design by using AS with CUPL (fitter always rejects), so instead # verify that the only cell that should have sync feedback, has it. continue if has_mux_value(f"{macrocell['pad']}_PAD", fuses): # Due to a fitter bug, if a combinatorial node that is not itself a legal GOE # driver is constrained using OE_node, and the pad of the macrocell where the node # is placed, conversely, is a legal GOE driver, a miscompilation happens: # the fitter legalizes the node by inserting an always-transparent latch and # setting fb_mux to sync. # # Hardware testing and celestial rituals demonstrate that this is a miscompilation # (i.e. the GOE driver is not affected by fb_mux setting); the legalized node is # ignored, and GOE is driven simply by the pad. # # To account for this bug, ignore any FB mux drivers if a PAD mux driver exists # that refers to the same macrocell. continue add_mux_value(f"{macrocell_name}_FB", fuses) for mux_name, mux in goe_muxes.items(): # Each GOE mux has exactly one fuse which is never used by the fitter. Hardware testing # and celestial rituals demonstrate that this fuse drives the GOE network low. assert len(mux['values']) == len(mux['fuses']) - 1, \ f"GOE mux {mux_name} should have exactly one unused value" # Setting the mux to all-ones (erased state) has the exact same result, so call the GND # with all-ones "GND1" and the GND with one fuse set to 0 "GND0". erased_value = (1 << len(mux['fuses'])) - 1 mux['values']['GND1'] = erased_value for n_fuse in range(len(mux['fuses'])): value = erased_value ^ (1 << n_fuse) if value not in mux['values'].values(): mux['values']['GND0'] = value
# -*- coding: utf-8 -*- # # Copyright (C) 2021 CESNET. # # OARepo-Communities is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """OArepo module that adds support for communities""" import click import sqlalchemy from flask.cli import with_appcontext from invenio_access import any_user from invenio_db import db from oarepo_ui.proxy import current_oarepo_ui from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.attributes import flag_modified from invenio_access.permissions import Need from oarepo_communities.api import OARepoCommunity from oarepo_communities.errors import OARepoCommunityCreateError from oarepo_communities.models import OAREPO_COMMUNITIES_TYPES, OARepoCommunityModel from oarepo_communities.permissions import community_record_owner from oarepo_communities.proxies import current_oarepo_communities @click.group() def communities(): """Management commands for OARepo Communities.""" @communities.command('list') @with_appcontext def list_communities(): """List all OARepo communities.""" comm = OARepoCommunityModel.query.all() for c in comm: click.secho(f'- {c.id} - ', fg='yellow', nl=False) click.secho(f'{c.title} ', fg='green', nl=False) click.secho(c.json.get('description', '')) @communities.command('create') @with_appcontext @click.argument('community-id') # Community PID that will be part of community URLs @click.argument('title') @click.option('--description', help='Community description') @click.option('--policy', help='Curation policy') @click.option('--logo-path', help='Path to the community logo file') @click.option('--ctype', help='Type of a community', default='other') def create(community_id, description, policy, title, ctype, logo_path): """Create a new community and associated community roles.""" topts = [t[0] for t in OAREPO_COMMUNITIES_TYPES] if ctype not in topts: click.secho(f'Invalid Community type {ctype}. Choices: {topts}', fg='red') exit(3) comm_data = { "curation_policy": policy, "id": community_id, "description": description, # TODO: "logo": "data/community-logos/ecfunded.jpg" } comm = None try: comm = OARepoCommunity.create( comm_data, id_=community_id, title=title, ctype=ctype ) except IntegrityError: click.secho(f'Community {community_id} already exists', fg='red') exit(4) except OARepoCommunityCreateError as e: click.secho(e, fg='red') exit(5) for role_name, actions in current_oarepo_communities.default_action_matrix.items(): role = OARepoCommunity.get_role(comm, role_name) if not role and role_name in ['author', 'any']: if role_name == 'author': role = community_record_owner else: role = any_user _allow_actions(community=comm, actions=[a[len('community-'):] for a in actions], role=role, system=True if isinstance(role, Need) else False) db.session.commit() click.secho(f'Created community: {comm} with roles {[r.name for r in comm.roles]}', fg='green') @communities.group('actions') def community_actions(): """Management commands for OARepo Communities actions.""" def _validate_role(community, role): role = OARepoCommunity.get_role(community, role) if not role: click.secho(f'Role {role} does not exist', fg='red') exit(4) return role def _validate_community(community): _community = None try: _community = OARepoCommunity.get_community(community) except sqlalchemy.orm.exc.NoResultFound: click.secho(f'Community {community} does not exist', fg='red') exit(3) return _community def _validate_actions(actions): if not actions: exit(0) def _action_valid(action): if f'community-{action}' in current_oarepo_communities.allowed_actions: return True click.secho(f'Action {action} not allowed', fg='red') actions = [a for a in actions if _action_valid(a)] return actions def _validate_facets(index_name, facets): index = current_oarepo_ui.facets.get(index_name, None) if not index: click.secho(f'Index {index_name} not found in facets config', fg='red') exit(4) for fac in facets: if not fac in index['aggs'].keys(): click.secho(f'Facet {fac} not in {index_name} facets', fg='red') exit(5) def _allow_actions(community, actions, role, system=False): with db.session.begin_nested(): for action in actions: _action = f'community-{action}' ar = community.allow_action(role, _action, system) click.secho(f'Added role action: {ar.action} {ar.need}', fg='green') db.session.commit() def _deny_actions(community, actions, role, system=False): with db.session.begin_nested(): for action in actions: _action = f'community-{action}' click.secho(f'Removing role action: {_action}', fg='green') community.deny_action(role, _action, system) db.session.commit() @community_actions.command('list') @with_appcontext @click.option('-c', '--community', help='List allowed and available actions in a community') def list_actions(community=None): """List all available community actions.""" click.secho('Available actions:', fg='green') for action in current_oarepo_communities.allowed_actions: _action = action[len('community-'):] click.secho(f'- {_action}') community = OARepoCommunity.get_community(community) if community: click.secho('\nAvailable community roles:', fg='green') for role in {r.name.split(':')[-1] for r in community.roles}.union({'any', 'author'}): click.secho(f'- {role}') click.secho('\nAllowed community role actions:', fg='green') ars, sars = community.actions for ar in ars: for action, roles in ar.items(): click.secho(f'- {action[len('community-'):]}: ', nl=False, fg='yellow') click.secho(', '.join([r.need.value.split(':')[-1] for r in roles])) click.secho('\nAllowed system role actions:', fg='green') for ar in sars: for action, roles in ar.items(): click.secho(f'- {action[len('community-'):]}: ', nl=False, fg='yellow') click.secho(', '.join([r.need.value.split('-')[-1] for r in roles])) @community_actions.command('allow') @with_appcontext @click.argument('community') @click.argument('role') @click.argument('actions', nargs=-1) def allow_actions(community, role, actions): """Allow actions to the given role.""" actions = _validate_actions(actions) community = OARepoCommunity.get_community(community) if role == 'any': # Allow actions for anonymous users _allow_actions(community, actions, any_user, system=True) elif role == 'author': # Allow actions for record owners _allow_actions(community, actions, community_record_owner, system=True) else: role = _validate_role(community, role) _allow_actions(community, actions, role) @community_actions.command('deny') @with_appcontext @click.argument('community') @click.argument('role') @click.argument('actions', nargs=-1) def deny_actions(community, role, actions): """Deny actions on the given role.""" actions = _validate_actions(actions) community = OARepoCommunity.get_community(community) if role == 'any': # Allow actions for anonymous users _deny_actions(community, actions, any_user, system=True) elif role == 'author': # Allow actions for record owners _deny_actions(community, actions, community_record_owner, system=True) else: role = _validate_role(community, role) _deny_actions(community, actions, role) db.session.commit() @communities.group('facets') def community_facets(): """Management commands for OARepo Communities facets.""" @community_facets.command('list') @with_appcontext @click.option('-c', '--community', help='List configured facets for community REST endpoints.') def list_facets(community=None): """List all available community facets.""" community = OARepoCommunity.get_community(community) if community: click.secho(f'\nAvailable community {community.title} facets on indices:', fg='green') else: click.secho('\nAvailable facets on indices:', fg='green') for index_name, aggs in current_oarepo_communities.facets.items(): click.secho(f'\nIndex: {index_name}', fg='yellow') for agg in aggs: is_excluded = False if community: excluded_aggs = community.excluded_facets.get(index_name, []) if agg in excluded_aggs: is_excluded = True click.secho(f'{'x' if is_excluded else '-'} {agg}', fg=f'{'red' if is_excluded else ''}') @community_facets.command('exclude') @with_appcontext @click.argument('community') @click.argument('index_name') @click.argument('facets', nargs=-1) def exclude(community, index_name, facets): """Exclude some facets on a given index for a given community.""" community = OARepoCommunity.get_community(community) _validate_facets(index_name=index_name, facets=facets) with db.session.begin_nested(): community.json.setdefault('excluded_facets', {}) community.json['excluded_facets'] = {index_name: facets} flag_modified(community, 'json') db.session.add(community) db.session.commit() click.secho(f'Excluded: {','.join(facets)} on index {index_name} for {community.title}', fg='green')
# -*- coding: utf-8 -*- # # Copyright (C) 2021 CESNET. # # OARepo-Communities is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """OArepo module that adds support for communities""" import click import sqlalchemy from flask.cli import with_appcontext from invenio_access import any_user from invenio_db import db from oarepo_ui.proxy import current_oarepo_ui from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.attributes import flag_modified from invenio_access.permissions import Need from oarepo_communities.api import OARepoCommunity from oarepo_communities.errors import OARepoCommunityCreateError from oarepo_communities.models import OAREPO_COMMUNITIES_TYPES, OARepoCommunityModel from oarepo_communities.permissions import community_record_owner from oarepo_communities.proxies import current_oarepo_communities @click.group() def communities(): """Management commands for OARepo Communities.""" @communities.command('list') @with_appcontext def list_communities(): """List all OARepo communities.""" comm = OARepoCommunityModel.query.all() for c in comm: click.secho(f'- {c.id} - ', fg='yellow', nl=False) click.secho(f'{c.title} ', fg='green', nl=False) click.secho(c.json.get('description', '')) @communities.command('create') @with_appcontext @click.argument('community-id') # Community PID that will be part of community URLs @click.argument('title') @click.option('--description', help='Community description') @click.option('--policy', help='Curation policy') @click.option('--logo-path', help='Path to the community logo file') @click.option('--ctype', help='Type of a community', default='other') def create(community_id, description, policy, title, ctype, logo_path): """Create a new community and associated community roles.""" topts = [t[0] for t in OAREPO_COMMUNITIES_TYPES] if ctype not in topts: click.secho(f'Invalid Community type {ctype}. Choices: {topts}', fg='red') exit(3) comm_data = { "curation_policy": policy, "id": community_id, "description": description, # TODO: "logo": "data/community-logos/ecfunded.jpg" } comm = None try: comm = OARepoCommunity.create( comm_data, id_=community_id, title=title, ctype=ctype ) except IntegrityError: click.secho(f'Community {community_id} already exists', fg='red') exit(4) except OARepoCommunityCreateError as e: click.secho(e, fg='red') exit(5) for role_name, actions in current_oarepo_communities.default_action_matrix.items(): role = OARepoCommunity.get_role(comm, role_name) if not role and role_name in ['author', 'any']: if role_name == 'author': role = community_record_owner else: role = any_user _allow_actions(community=comm, actions=[a[len('community-'):] for a in actions], role=role, system=True if isinstance(role, Need) else False) db.session.commit() click.secho(f'Created community: {comm} with roles {[r.name for r in comm.roles]}', fg='green') @communities.group('actions') def community_actions(): """Management commands for OARepo Communities actions.""" def _validate_role(community, role): role = OARepoCommunity.get_role(community, role) if not role: click.secho(f'Role {role} does not exist', fg='red') exit(4) return role def _validate_community(community): _community = None try: _community = OARepoCommunity.get_community(community) except sqlalchemy.orm.exc.NoResultFound: click.secho(f'Community {community} does not exist', fg='red') exit(3) return _community def _validate_actions(actions): if not actions: exit(0) def _action_valid(action): if f'community-{action}' in current_oarepo_communities.allowed_actions: return True click.secho(f'Action {action} not allowed', fg='red') actions = [a for a in actions if _action_valid(a)] return actions def _validate_facets(index_name, facets): index = current_oarepo_ui.facets.get(index_name, None) if not index: click.secho(f'Index {index_name} not found in facets config', fg='red') exit(4) for fac in facets: if not fac in index['aggs'].keys(): click.secho(f'Facet {fac} not in {index_name} facets', fg='red') exit(5) def _allow_actions(community, actions, role, system=False): with db.session.begin_nested(): for action in actions: _action = f'community-{action}' ar = community.allow_action(role, _action, system) click.secho(f'Added role action: {ar.action} {ar.need}', fg='green') db.session.commit() def _deny_actions(community, actions, role, system=False): with db.session.begin_nested(): for action in actions: _action = f'community-{action}' click.secho(f'Removing role action: {_action}', fg='green') community.deny_action(role, _action, system) db.session.commit() @community_actions.command('list') @with_appcontext @click.option('-c', '--community', help='List allowed and available actions in a community') def list_actions(community=None): """List all available community actions.""" click.secho('Available actions:', fg='green') for action in current_oarepo_communities.allowed_actions: _action = action[len('community-'):] click.secho(f'- {_action}') community = OARepoCommunity.get_community(community) if community: click.secho('\nAvailable community roles:', fg='green') for role in {r.name.split(':')[-1] for r in community.roles}.union({'any', 'author'}): click.secho(f'- {role}') click.secho('\nAllowed community role actions:', fg='green') ars, sars = community.actions for ar in ars: for action, roles in ar.items(): click.secho(f'- {action[len("community-"):]}: ', nl=False, fg='yellow') click.secho(', '.join([r.need.value.split(':')[-1] for r in roles])) click.secho('\nAllowed system role actions:', fg='green') for ar in sars: for action, roles in ar.items(): click.secho(f'- {action[len("community-"):]}: ', nl=False, fg='yellow') click.secho(', '.join([r.need.value.split('-')[-1] for r in roles])) @community_actions.command('allow') @with_appcontext @click.argument('community') @click.argument('role') @click.argument('actions', nargs=-1) def allow_actions(community, role, actions): """Allow actions to the given role.""" actions = _validate_actions(actions) community = OARepoCommunity.get_community(community) if role == 'any': # Allow actions for anonymous users _allow_actions(community, actions, any_user, system=True) elif role == 'author': # Allow actions for record owners _allow_actions(community, actions, community_record_owner, system=True) else: role = _validate_role(community, role) _allow_actions(community, actions, role) @community_actions.command('deny') @with_appcontext @click.argument('community') @click.argument('role') @click.argument('actions', nargs=-1) def deny_actions(community, role, actions): """Deny actions on the given role.""" actions = _validate_actions(actions) community = OARepoCommunity.get_community(community) if role == 'any': # Allow actions for anonymous users _deny_actions(community, actions, any_user, system=True) elif role == 'author': # Allow actions for record owners _deny_actions(community, actions, community_record_owner, system=True) else: role = _validate_role(community, role) _deny_actions(community, actions, role) db.session.commit() @communities.group('facets') def community_facets(): """Management commands for OARepo Communities facets.""" @community_facets.command('list') @with_appcontext @click.option('-c', '--community', help='List configured facets for community REST endpoints.') def list_facets(community=None): """List all available community facets.""" community = OARepoCommunity.get_community(community) if community: click.secho(f'\nAvailable community {community.title} facets on indices:', fg='green') else: click.secho('\nAvailable facets on indices:', fg='green') for index_name, aggs in current_oarepo_communities.facets.items(): click.secho(f'\nIndex: {index_name}', fg='yellow') for agg in aggs: is_excluded = False if community: excluded_aggs = community.excluded_facets.get(index_name, []) if agg in excluded_aggs: is_excluded = True click.secho(f'{"x" if is_excluded else "-"} {agg}', fg=f'{"red" if is_excluded else ""}') @community_facets.command('exclude') @with_appcontext @click.argument('community') @click.argument('index_name') @click.argument('facets', nargs=-1) def exclude(community, index_name, facets): """Exclude some facets on a given index for a given community.""" community = OARepoCommunity.get_community(community) _validate_facets(index_name=index_name, facets=facets) with db.session.begin_nested(): community.json.setdefault('excluded_facets', {}) community.json['excluded_facets'] = {index_name: facets} flag_modified(community, 'json') db.session.add(community) db.session.commit() click.secho(f'Excluded: {",".join(facets)} on index {index_name} for {community.title}', fg='green')
#! /usr/bin/env pipenv run -- python3 import click @click.command() @click.option('--version', '-v', flag_value=True, help="Show Viper version") @click.argument('args', nargs=-1) def app(version, args): if version: click.echo('Viper 0.0.1') elif args: click.echo(f"I know I'm supposed to compile '{args[0]}', but I wont 😜") click.echo(f"arguments = [{", ".join(args)}]") else: ctx = click.get_current_context() click.echo(ctx.get_help()) ctx.exit() if __name__ == "__main__": app()
#! /usr/bin/env pipenv run -- python3 import click @click.command() @click.option('--version', '-v', flag_value=True, help="Show Viper version") @click.argument('args', nargs=-1) def app(version, args): if version: click.echo('Viper 0.0.1') elif args: click.echo(f"I know I'm supposed to compile '{args[0]}', but I wont 😜") click.echo(f"arguments = [{', '.join(args)}]") else: ctx = click.get_current_context() click.echo(ctx.get_help()) ctx.exit() if __name__ == "__main__": app()
import csv import math from pathlib import Path from typing import List, Dict, Tuple import xmltodict from celery import current_app as current_celery_app from celery import shared_task from fiftyone import Dataset, Sample, Polyline, Polylines from fiftyone.core.metadata import ImageMetadata from app.models.schemas import Task from conf.configs import conf def create_celery() -> current_celery_app: """ Create a celery app run: celery -A app.main.celery worker --loglevel=INFO -P threads """ celery_app = current_celery_app celery_app.conf.broker_url = ( f"redis://{conf.redis_host}:{conf.redis_port}/{conf.redis_db}" ) celery_app.conf.result_backend = ( conf.mongo_uri + "/" + conf.fiftyone_database_name ) celery_app.conf.task_serializer = "pickle" celery_app.conf.result_serializer = "pickle" celery_app.conf.event_serializer = "json" celery_app.conf.accept_content = [ "application/json", "application/x-python-serialize", ] celery_app.conf.result_accept_content = [ "application/json", "application/x-python-serialize", ] return celery_app @shared_task(name="load_task_data") def load_task_data(task: Task) -> None: """ load task data :type task: Task return: None """ base_path = Path(conf.base_path) sample_pool: Dict[str, Sample] = {} for d in task.datas: prd_data_dir = base_path / Path(d.data_dir) / "annotations" gt_data_dir = base_path / Path(d.data_dir) / "groundtruth" _get_samples(base_path, prd_data_dir, f"pd_{d.name}", sample_pool) _get_samples(base_path, gt_data_dir, f"gt_{d.name}", sample_pool) # Create dataset dataset = Dataset(task.tid) dataset.add_samples(sample_pool.values()) dataset.persistent = True def _get_samples(base_path: Path, labels_dir: Path, dataset_name, sample_pool,) -> None: """ get annotation from voc xml file :type base_path: Path return: dict """ tsv_file = labels_dir / "index.tsv" with tsv_file.open() as fd: rd = csv.reader(fd, delimiter="\t", quotechar='"') for row in rd: img_path = Path(row[0]) annotation = _get_annotation(base_path, row[1]) if img_path.name in sample_pool: sample = sample_pool[img_path.name] else: sample = Sample(filepath=base_path / img_path) for k, v in annotation.get("ck", {}).items(): sample[k] = v sample_pool[img_path.name] = sample _set_metadata(annotation, sample) # if object is empty, skip if "object" not in annotation: continue _add_detections(annotation, dataset_name, sample) def _get_annotation( base_path: Path, annotation_path: str, ) -> dict: """ get annotation from voc xml file :type base_path: Path :type annotation_path: str return: dict """ annotation_file = base_path / annotation_path with annotation_file.open("r", encoding="utf-8") as ad: return xmltodict.parse(ad.read()).get("annotation") def _set_metadata( annotation: dict, sample: Sample, ) -> Sample: """ set metadata to sample :type annotation: dict :type sample: Sample return: sample """ size = annotation["size"] width = int(size["width"]) height = int(size["height"]) depth = int(size["depth"]) metadata = ImageMetadata( width=width, height=height, num_channels=depth, ) sample["metadata"] = metadata return sample def _add_detections( annotation: dict, ymir_data_name: str, sample: Sample, ) -> Sample: """ add detections to sample :type annotation: dict :type ymir_data_name: str :type sample: Sample return: sample """ voc_objects = [] if isinstance(annotation["object"], dict): voc_objects.append(annotation["object"]) elif isinstance(annotation["object"], list): voc_objects = annotation["object"] else: raise ValueError(f"Invalid object type: {type(annotation["object"])}") polylines = _build_polylines(voc_objects, sample["metadata"]["width"], sample["metadata"]["height"]) sample[ymir_data_name] = Polylines(polylines=polylines) return sample def _build_polylines(voc_objects: list, width: int, height: int) -> List[Polyline]: polylines = [] for obj in voc_objects: label = obj["name"] points = _get_points_from_bndbox(obj["bndbox"], width, height) polyline = Polyline( label=label, points=[points], confidence=obj.get("confidence"), closed=True ) for k, v in obj.get("tag", {}).items(): polyline[k] = v polylines.append(polyline) return polylines def _get_points_from_bndbox(bndbox: Dict, width: int, height: int) -> list: # raise error if parameter not exist xmin, ymin = float(bndbox["xmin"]), float(bndbox["ymin"]) xmax, ymax = float(bndbox["xmax"]), float(bndbox["ymax"]) angle = float(bndbox.get("rotate_angle", 0)) * math.pi cx, cy = (xmin + xmax) / 2, (ymin + ymax) / 2 half_w, half_h = (xmax - xmin) / 2, (ymax - ymin) / 2 p0x, p0y = _rotate_point(cx, cy, cx - half_w, cy - half_h, -angle, width, height) p1x, p1y = _rotate_point(cx, cy, cx + half_w, cy - half_h, -angle, width, height) p2x, p2y = _rotate_point(cx, cy, cx + half_w, cy + half_h, -angle, width, height) p3x, p3y = _rotate_point(cx, cy, cx - half_w, cy + half_h, -angle, width, height) return [(p0x, p0y), (p1x, p1y), (p2x, p2y), (p3x, p3y)] def _rotate_point(cx: float, cy: float, xp: float, yp: float, theta: float, width: int, height: int) -> Tuple[float, float]: xoff = xp - cx yoff = yp - cy cos_theta = math.cos(theta) sin_theta = math.sin(theta) resx = cos_theta * xoff + sin_theta * yoff resy = - sin_theta * xoff + cos_theta * yoff return (cx + resx) / width, (cy + resy) / height
import csv import math from pathlib import Path from typing import List, Dict, Tuple import xmltodict from celery import current_app as current_celery_app from celery import shared_task from fiftyone import Dataset, Sample, Polyline, Polylines from fiftyone.core.metadata import ImageMetadata from app.models.schemas import Task from conf.configs import conf def create_celery() -> current_celery_app: """ Create a celery app run: celery -A app.main.celery worker --loglevel=INFO -P threads """ celery_app = current_celery_app celery_app.conf.broker_url = ( f"redis://{conf.redis_host}:{conf.redis_port}/{conf.redis_db}" ) celery_app.conf.result_backend = ( conf.mongo_uri + "/" + conf.fiftyone_database_name ) celery_app.conf.task_serializer = "pickle" celery_app.conf.result_serializer = "pickle" celery_app.conf.event_serializer = "json" celery_app.conf.accept_content = [ "application/json", "application/x-python-serialize", ] celery_app.conf.result_accept_content = [ "application/json", "application/x-python-serialize", ] return celery_app @shared_task(name="load_task_data") def load_task_data(task: Task) -> None: """ load task data :type task: Task return: None """ base_path = Path(conf.base_path) sample_pool: Dict[str, Sample] = {} for d in task.datas: prd_data_dir = base_path / Path(d.data_dir) / "annotations" gt_data_dir = base_path / Path(d.data_dir) / "groundtruth" _get_samples(base_path, prd_data_dir, f"pd_{d.name}", sample_pool) _get_samples(base_path, gt_data_dir, f"gt_{d.name}", sample_pool) # Create dataset dataset = Dataset(task.tid) dataset.add_samples(sample_pool.values()) dataset.persistent = True def _get_samples(base_path: Path, labels_dir: Path, dataset_name, sample_pool,) -> None: """ get annotation from voc xml file :type base_path: Path return: dict """ tsv_file = labels_dir / "index.tsv" with tsv_file.open() as fd: rd = csv.reader(fd, delimiter="\t", quotechar='"') for row in rd: img_path = Path(row[0]) annotation = _get_annotation(base_path, row[1]) if img_path.name in sample_pool: sample = sample_pool[img_path.name] else: sample = Sample(filepath=base_path / img_path) for k, v in annotation.get("ck", {}).items(): sample[k] = v sample_pool[img_path.name] = sample _set_metadata(annotation, sample) # if object is empty, skip if "object" not in annotation: continue _add_detections(annotation, dataset_name, sample) def _get_annotation( base_path: Path, annotation_path: str, ) -> dict: """ get annotation from voc xml file :type base_path: Path :type annotation_path: str return: dict """ annotation_file = base_path / annotation_path with annotation_file.open("r", encoding="utf-8") as ad: return xmltodict.parse(ad.read()).get("annotation") def _set_metadata( annotation: dict, sample: Sample, ) -> Sample: """ set metadata to sample :type annotation: dict :type sample: Sample return: sample """ size = annotation["size"] width = int(size["width"]) height = int(size["height"]) depth = int(size["depth"]) metadata = ImageMetadata( width=width, height=height, num_channels=depth, ) sample["metadata"] = metadata return sample def _add_detections( annotation: dict, ymir_data_name: str, sample: Sample, ) -> Sample: """ add detections to sample :type annotation: dict :type ymir_data_name: str :type sample: Sample return: sample """ voc_objects = [] if isinstance(annotation["object"], dict): voc_objects.append(annotation["object"]) elif isinstance(annotation["object"], list): voc_objects = annotation["object"] else: raise ValueError(f"Invalid object type: {type(annotation['object'])}") polylines = _build_polylines(voc_objects, sample["metadata"]["width"], sample["metadata"]["height"]) sample[ymir_data_name] = Polylines(polylines=polylines) return sample def _build_polylines(voc_objects: list, width: int, height: int) -> List[Polyline]: polylines = [] for obj in voc_objects: label = obj["name"] points = _get_points_from_bndbox(obj["bndbox"], width, height) polyline = Polyline( label=label, points=[points], confidence=obj.get("confidence"), closed=True ) for k, v in obj.get("tag", {}).items(): polyline[k] = v polylines.append(polyline) return polylines def _get_points_from_bndbox(bndbox: Dict, width: int, height: int) -> list: # raise error if parameter not exist xmin, ymin = float(bndbox["xmin"]), float(bndbox["ymin"]) xmax, ymax = float(bndbox["xmax"]), float(bndbox["ymax"]) angle = float(bndbox.get("rotate_angle", 0)) * math.pi cx, cy = (xmin + xmax) / 2, (ymin + ymax) / 2 half_w, half_h = (xmax - xmin) / 2, (ymax - ymin) / 2 p0x, p0y = _rotate_point(cx, cy, cx - half_w, cy - half_h, -angle, width, height) p1x, p1y = _rotate_point(cx, cy, cx + half_w, cy - half_h, -angle, width, height) p2x, p2y = _rotate_point(cx, cy, cx + half_w, cy + half_h, -angle, width, height) p3x, p3y = _rotate_point(cx, cy, cx - half_w, cy + half_h, -angle, width, height) return [(p0x, p0y), (p1x, p1y), (p2x, p2y), (p3x, p3y)] def _rotate_point(cx: float, cy: float, xp: float, yp: float, theta: float, width: int, height: int) -> Tuple[float, float]: xoff = xp - cx yoff = yp - cy cos_theta = math.cos(theta) sin_theta = math.sin(theta) resx = cos_theta * xoff + sin_theta * yoff resy = - sin_theta * xoff + cos_theta * yoff return (cx + resx) / width, (cy + resy) / height
import json import hashlib import os import time import requests import binascii from web3 import Web3 import offlineOpen import offlineClose providerAddr = 'https://http-mainnet-node.huobichain.com' w3 = Web3(Web3.HTTPProvider(providerAddr)) FPABIFILE = "./abi/FuturePerpetual.json" FPADDR = '0x917e091cc000012bbd58afFa8E6DbB96fa06cb0a' with open(FPABIFILE) as fp: fpabi = json.loads(fp.read()) FPHANDLER = w3.eth.contract(abi=fpabi, address=FPADDR) MUL = 20 USDTDEC = 1e18 openUrl = 'https://openoracle_prod_heco.dfuture.com/dev/web/sendOpenPosition' closeUrl = 'https://openoracle_prod_heco.dfuture.com/dev/web/sendClosePosition' ack = '8967778135e4754' ask = 'f195e1be47b962625626' #use your root root = '' # use your address pk and sk pk = '' sk = '' def doOpen(user, usersk, sym, amount, dire, total, deadline, gasfee): openpara = getOpenPara(user, sym, amount, dire, 0, int(total/MUL*USDTDEC), deadline, gasfee) args = offlineOpen.toArgs(openpara, usersk) openpara['approvedUsdt'] = str(openpara['approvedUsdt']) openpara['v'] = args[0] print(f'{'*'*10}{hex(args[1])}, {hex(args[2])}') openpara['r'] = '0x'+hex(args[1])[2:].rjust(64,'0') openpara['s'] = '0x'+hex(args[2])[2:].rjust(64,'0') print(f'{'*'*10}{openpara['r']}, {openpara['s']}') openpara['accessKey'] = '123' print(f'{openpara}') header = getHeader() r = requests.post(url=openUrl,data=json.dumps(openpara),headers = header) print(f'post res {r.text}') res = json.loads(r.text) print(type(res), res) if res['success']: trxReceipt = w3.eth.waitForTransactionReceipt(res['data']['txHash']) print(f'res: {trxReceipt}') return trxReceipt['status'] print(res) return False def getHeader(): header = {} header["Content-Type"] = "application/json" header["accessKey"] = ack header["accessTime"] = str(int(time.time()*1000)) md5org = "&".join(list(header.values())[1:])+"&"+ask header["token"] = hashlib.md5(md5org.encode()).hexdigest() print(f"header is {md5org} {header}") return header def doClose(user, usersk, symbol, amount, ac, deadline, gasfee): closepara = getClosePara(user, symbol, amount, ac, deadline, gasfee) args = offlineClose.toArgs(closepara, usersk) closepara['v'] = args[0] closepara['r'] = '0x'+hex(args[1])[2:].rjust(64,'0') closepara['s'] = '0x'+hex(args[2])[2:].rjust(64,'0') closepara['accessKey'] = '123' print(f'{closepara}') header = getHeader() r = requests.post(url=closeUrl,data=json.dumps(closepara),headers=header) res = json.loads(r.text) print(type(res), res) if res['success']: trxReceipt = w3.eth.waitForTransactionReceipt(res['data']['txHash']) print(f'res: {trxReceipt}') return trxReceipt['status'] print(res) return False def getClosePara(user, symbol, amount, ac, deadline, gasfee): sym = binascii.hexlify(symbol.encode()).decode() para = { 'symbol': '0x'+sym.ljust(64, '0'), 'amount': amount, 'acceptablePrice': ac, 'deadline': deadline, 'maker': user, 'gasLevel': gasfee, 'couponId': '24273', 'couponAmount': '1' } return para def getOpenPara(user, symbol, amount, direction, ac, ap, deadline, gasfee): sym = binascii.hexlify(symbol.encode()).decode() para = { 'symbol': '0x'+sym.ljust(64, '0'), 'amount': amount, 'direction': direction, 'acceptablePrice': ac, 'approvedUsdt': ap, 'parent': root, 'withDiscount': True, 'deadline': deadline, 'maker': user, 'gasLevel': gasfee, 'couponId': '24271', 'couponAmount': '1' } return para def getNonce(user): nonce = FPHANDLER.functions.queryNonce(user).call() nonce+=1 ts = nonce << (256-64) ts += int(time.time()+300) print(f'nonce {nonce}, {ts}') return ts def openallPosition(user, usersk, sym, dire): total = 100 # 交易金额U,决定了杠杆倍数 amount = 2 # 交易多少手 gasfee = 10 ts = getNonce(user) doOpen(user, usersk, sym, amount, dire, total, ts, gasfee) time.sleep(10) ts = getNonce(user) doClose(user, usersk, sym, amount, 0, ts, gasfee) if __name__ == '__main__': dire = 1 openallPosition(pk, sk, 'btc', dire)
import json import hashlib import os import time import requests import binascii from web3 import Web3 import offlineOpen import offlineClose providerAddr = 'https://http-mainnet-node.huobichain.com' w3 = Web3(Web3.HTTPProvider(providerAddr)) FPABIFILE = "./abi/FuturePerpetual.json" FPADDR = '0x917e091cc000012bbd58afFa8E6DbB96fa06cb0a' with open(FPABIFILE) as fp: fpabi = json.loads(fp.read()) FPHANDLER = w3.eth.contract(abi=fpabi, address=FPADDR) MUL = 20 USDTDEC = 1e18 openUrl = 'https://openoracle_prod_heco.dfuture.com/dev/web/sendOpenPosition' closeUrl = 'https://openoracle_prod_heco.dfuture.com/dev/web/sendClosePosition' ack = '8967778135e4754' ask = 'f195e1be47b962625626' #use your root root = '' # use your address pk and sk pk = '' sk = '' def doOpen(user, usersk, sym, amount, dire, total, deadline, gasfee): openpara = getOpenPara(user, sym, amount, dire, 0, int(total/MUL*USDTDEC), deadline, gasfee) args = offlineOpen.toArgs(openpara, usersk) openpara['approvedUsdt'] = str(openpara['approvedUsdt']) openpara['v'] = args[0] print(f'{"*"*10}{hex(args[1])}, {hex(args[2])}') openpara['r'] = '0x'+hex(args[1])[2:].rjust(64,'0') openpara['s'] = '0x'+hex(args[2])[2:].rjust(64,'0') print(f'{"*"*10}{openpara["r"]}, {openpara["s"]}') openpara['accessKey'] = '123' print(f'{openpara}') header = getHeader() r = requests.post(url=openUrl,data=json.dumps(openpara),headers = header) print(f'post res {r.text}') res = json.loads(r.text) print(type(res), res) if res['success']: trxReceipt = w3.eth.waitForTransactionReceipt(res['data']['txHash']) print(f'res: {trxReceipt}') return trxReceipt['status'] print(res) return False def getHeader(): header = {} header["Content-Type"] = "application/json" header["accessKey"] = ack header["accessTime"] = str(int(time.time()*1000)) md5org = "&".join(list(header.values())[1:])+"&"+ask header["token"] = hashlib.md5(md5org.encode()).hexdigest() print(f"header is {md5org} {header}") return header def doClose(user, usersk, symbol, amount, ac, deadline, gasfee): closepara = getClosePara(user, symbol, amount, ac, deadline, gasfee) args = offlineClose.toArgs(closepara, usersk) closepara['v'] = args[0] closepara['r'] = '0x'+hex(args[1])[2:].rjust(64,'0') closepara['s'] = '0x'+hex(args[2])[2:].rjust(64,'0') closepara['accessKey'] = '123' print(f'{closepara}') header = getHeader() r = requests.post(url=closeUrl,data=json.dumps(closepara),headers=header) res = json.loads(r.text) print(type(res), res) if res['success']: trxReceipt = w3.eth.waitForTransactionReceipt(res['data']['txHash']) print(f'res: {trxReceipt}') return trxReceipt['status'] print(res) return False def getClosePara(user, symbol, amount, ac, deadline, gasfee): sym = binascii.hexlify(symbol.encode()).decode() para = { 'symbol': '0x'+sym.ljust(64, '0'), 'amount': amount, 'acceptablePrice': ac, 'deadline': deadline, 'maker': user, 'gasLevel': gasfee, 'couponId': '24273', 'couponAmount': '1' } return para def getOpenPara(user, symbol, amount, direction, ac, ap, deadline, gasfee): sym = binascii.hexlify(symbol.encode()).decode() para = { 'symbol': '0x'+sym.ljust(64, '0'), 'amount': amount, 'direction': direction, 'acceptablePrice': ac, 'approvedUsdt': ap, 'parent': root, 'withDiscount': True, 'deadline': deadline, 'maker': user, 'gasLevel': gasfee, 'couponId': '24271', 'couponAmount': '1' } return para def getNonce(user): nonce = FPHANDLER.functions.queryNonce(user).call() nonce+=1 ts = nonce << (256-64) ts += int(time.time()+300) print(f'nonce {nonce}, {ts}') return ts def openallPosition(user, usersk, sym, dire): total = 100 # 交易金额U,决定了杠杆倍数 amount = 2 # 交易多少手 gasfee = 10 ts = getNonce(user) doOpen(user, usersk, sym, amount, dire, total, ts, gasfee) time.sleep(10) ts = getNonce(user) doClose(user, usersk, sym, amount, 0, ts, gasfee) if __name__ == '__main__': dire = 1 openallPosition(pk, sk, 'btc', dire)
#!/usr/bin/env python import syslog import signal import bme680 import sys from paho.mqtt import client as mqtt_client from time import sleep from threading import Event sensor = bme680.BME680(bme680.I2C_ADDR_PRIMARY) exit = Event() # These oversampling settings can be tweaked to # change the balance between accuracy and noise in # the data. sensor.set_humidity_oversample(bme680.OS_2X) sensor.set_pressure_oversample(bme680.OS_4X) sensor.set_temperature_oversample(bme680.OS_8X) sensor.set_filter(bme680.FILTER_SIZE_3) # MQTT Setup broker = 'mqtt.yayoi.co.uk' port = 1883 topic = "domoticz/in" client_id = 'weatherpi' # Domoticz sensor setup TempIDX = "659" BaroIDX = "656" def connect_mqtt(): def on_connect(client, userdata, flags, rc): if rc == 0: syslog.syslog("BME680 connected to MQTT Broker!") else: syslog.syslog(f"BME680 failed to connect tp MQTTbroker, return code {rc}") # Set Connecting Client ID client = mqtt_client.Client(client_id) # client.username_pw_set(username, password) client.on_connect = on_connect client.connect(broker, port) return client def termHandler(signal, frame): syslog.syslog("Received SIGTERM") exit.set() def main(): try: mqttclient = connect_mqtt() signal.signal(signal.SIGTERM,termHandler) mqttclient.loop_start() while not exit.is_set(): if sensor.get_sensor_data(): baro_stat = 0 if (30 <= sensor.data.humidity <= 70) and (20 <= sensor.data.temperature <= 26): hum_stat = 1 elif sensor.data.humidity > 70: hum_stat = 3 elif sensor.data.humidity < 30: hum_stat = 2 else: hum_stat=0 mqttclient.publish(topic, f"{{ \"idx\": {TempIDX}, \"command\": \"udevice\", \"nvalue\": 0, \"svalue\": \"{sensor.data.temperature};{sensor.data.humidity};{hum_stat}\" }}") mqttclient.publish(topic, f"{{ \"idx\": {BaroIDX}, \"command\": \"udevice\", \"nvalue\": 0, \"svalue\": \"{sensor.data.pressure};{baro_stat}\" }}") exit.wait(300) syslog.syslog("Terminating cleanly") mqttclient.loop_stop() mqttclient.disconnect() sys.exit(0) except Exception as E: syslog.syslog(f"BME680 error: {E}") mqttclient.loop_stop() mqttclient.disconnect() sys.exit(1) if __name__ == "__main__": main()
#!/usr/bin/env python import syslog import signal import bme680 import sys from paho.mqtt import client as mqtt_client from time import sleep from threading import Event sensor = bme680.BME680(bme680.I2C_ADDR_PRIMARY) exit = Event() # These oversampling settings can be tweaked to # change the balance between accuracy and noise in # the data. sensor.set_humidity_oversample(bme680.OS_2X) sensor.set_pressure_oversample(bme680.OS_4X) sensor.set_temperature_oversample(bme680.OS_8X) sensor.set_filter(bme680.FILTER_SIZE_3) # MQTT Setup broker = 'mqtt.yayoi.co.uk' port = 1883 topic = "domoticz/in" client_id = 'weatherpi' # Domoticz sensor setup TempIDX = "659" BaroIDX = "656" def connect_mqtt(): def on_connect(client, userdata, flags, rc): if rc == 0: syslog.syslog("BME680 connected to MQTT Broker!") else: syslog.syslog(f"BME680 failed to connect tp MQTTbroker, return code {rc}") # Set Connecting Client ID client = mqtt_client.Client(client_id) # client.username_pw_set(username, password) client.on_connect = on_connect client.connect(broker, port) return client def termHandler(signal, frame): syslog.syslog("Received SIGTERM") exit.set() def main(): try: mqttclient = connect_mqtt() signal.signal(signal.SIGTERM,termHandler) mqttclient.loop_start() while not exit.is_set(): if sensor.get_sensor_data(): baro_stat = 0 if (30 <= sensor.data.humidity <= 70) and (20 <= sensor.data.temperature <= 26): hum_stat = 1 elif sensor.data.humidity > 70: hum_stat = 3 elif sensor.data.humidity < 30: hum_stat = 2 else: hum_stat=0 mqttclient.publish(topic, f"{{ \"idx\": {TempIDX}, \"command\": \"udevice\", \"nvalue\": 0, \"svalue\": \"{sensor.data.temperature};{sensor.data.humidity};{hum_stat}\" }}") mqttclient.publish(topic, f"{{ \"idx\": {BaroIDX}, \"command\": \"udevice\", \"nvalue\": 0, \"svalue\": \"{sensor.data.pressure};{baro_stat}\" }}") exit.wait(300) syslog.syslog("Terminating cleanly") mqttclient.loop_stop() mqttclient.disconnect() sys.exit(0) except Exception as E: syslog.syslog(f"BME680 error: {E}") mqttclient.loop_stop() mqttclient.disconnect() sys.exit(1) if __name__ == "__main__": main()
from crawl import main as crawl from util import get_params from util.elastic import Elastic import os import wget BASICS = 'https://datasets.imdbws.com/title.basics.tsv.gz' RATINGS = 'https://datasets.imdbws.com/title.ratings.tsv.gz' EPISODES = 'https://datasets.imdbws.com/title.episode.tsv.gz' def main(): elastic = Elastic() config = get_params() path = config['crawler']['path'] # download imdb files wget.download(BASICS, out=path) wget.download(RATINGS, out=path) wget.download(EPISODES, out=path) # crawl movies and add to elastic crawl() elastic.insert_elastic() # remove files os.remove(f"{config["crawler"]["path"]}/title.basics.tsv.gz") os.remove(f"{config["crawler"]["path"]}/title.ratings.tsv.gz") os.remove(f"{config["crawler"]["path"]}/title.episode.tsv.gz") if __name__ == '__main__': main()
from crawl import main as crawl from util import get_params from util.elastic import Elastic import os import wget BASICS = 'https://datasets.imdbws.com/title.basics.tsv.gz' RATINGS = 'https://datasets.imdbws.com/title.ratings.tsv.gz' EPISODES = 'https://datasets.imdbws.com/title.episode.tsv.gz' def main(): elastic = Elastic() config = get_params() path = config['crawler']['path'] # download imdb files wget.download(BASICS, out=path) wget.download(RATINGS, out=path) wget.download(EPISODES, out=path) # crawl movies and add to elastic crawl() elastic.insert_elastic() # remove files os.remove(f"{config['crawler']['path']}/title.basics.tsv.gz") os.remove(f"{config['crawler']['path']}/title.ratings.tsv.gz") os.remove(f"{config['crawler']['path']}/title.episode.tsv.gz") if __name__ == '__main__': main()
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pathlib import Path from pants.testutil.pants_run_integration_test import PantsRunIntegrationTest class MypyIntegrationTest(PantsRunIntegrationTest): cmdline = ["--backend-packages=pants.contrib.mypy", "lint"] @classmethod def target(cls, name): return f"contrib/mypy/examples/src/python/simple:{name}" def test_valid_type_hints(self): result = self.run_pants([*self.cmdline, self.target("valid")]) self.assert_success(result) def test_invalid_type_hints(self): result = self.run_pants([*self.cmdline, self.target("invalid")]) self.assert_failure(result) class MypyPluginIntegrationTest(PantsRunIntegrationTest): example_dir = Path("contrib/mypy/examples/src/python/mypy_plugin") @classmethod def cmdline(cls, *, include_requirements): cmd = [ "--backend-packages=pants.contrib.mypy", f'--mypy-config={cls.example_dir / 'mypy.ini'}', "lint.mypy", ] if include_requirements: cmd.append("--include-requirements") return cmd @classmethod def target(cls, name): return f"{cls.example_dir}:{name}" def test_valid_library_use_include_requirements(self): result = self.run_pants([*self.cmdline(include_requirements=True), self.target("valid")]) self.assert_success(result) def test_invalid_library_use_include_requirements(self): result = self.run_pants([*self.cmdline(include_requirements=True), self.target("invalid")]) self.assert_failure(result) def test_valid_library_use_exclude_requirements(self): # The target is valid, but we fail to include the mypy plugin and type information needed via # requirements and so the check fails. result = self.run_pants([*self.cmdline(include_requirements=False), self.target("valid")]) self.assert_failure(result)
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pathlib import Path from pants.testutil.pants_run_integration_test import PantsRunIntegrationTest class MypyIntegrationTest(PantsRunIntegrationTest): cmdline = ["--backend-packages=pants.contrib.mypy", "lint"] @classmethod def target(cls, name): return f"contrib/mypy/examples/src/python/simple:{name}" def test_valid_type_hints(self): result = self.run_pants([*self.cmdline, self.target("valid")]) self.assert_success(result) def test_invalid_type_hints(self): result = self.run_pants([*self.cmdline, self.target("invalid")]) self.assert_failure(result) class MypyPluginIntegrationTest(PantsRunIntegrationTest): example_dir = Path("contrib/mypy/examples/src/python/mypy_plugin") @classmethod def cmdline(cls, *, include_requirements): cmd = [ "--backend-packages=pants.contrib.mypy", f'--mypy-config={cls.example_dir / "mypy.ini"}', "lint.mypy", ] if include_requirements: cmd.append("--include-requirements") return cmd @classmethod def target(cls, name): return f"{cls.example_dir}:{name}" def test_valid_library_use_include_requirements(self): result = self.run_pants([*self.cmdline(include_requirements=True), self.target("valid")]) self.assert_success(result) def test_invalid_library_use_include_requirements(self): result = self.run_pants([*self.cmdline(include_requirements=True), self.target("invalid")]) self.assert_failure(result) def test_valid_library_use_exclude_requirements(self): # The target is valid, but we fail to include the mypy plugin and type information needed via # requirements and so the check fails. result = self.run_pants([*self.cmdline(include_requirements=False), self.target("valid")]) self.assert_failure(result)
import torchvision from fastai.vision import * from fastai.callbacks import SaveModelCallback import librosa import h5py # ***************************************************************************************** just_test = True # skip training and use a saved model sample_length = 5 # time window length in seconds SR = 22050 # spectrogram config n_fft = 2048 hop_length = 512 n_mels = 128 # Meta data paths train_csv_path = Path("data/mp3/train.csv") # change for training in a Kaggle Notebook test_csv_path = Path("data/mp3/test.csv") # change for training in a Kaggle Notebook # Data paths hdf_file_path = Path( "data/spectrograms_full.hdf5" ) # change for training in a Kaggle Notebook test_data_path = Path( "data/mp3/example_test_audio" ) # change for training in a Kaggle Notebook # train config load_saved_model = False saved_model_path = Path("models/bestmodel.pth") # ***************************************************************************************** # set variables for reproducibility torch.manual_seed(10) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False np.random.seed(22) def preprocess_data() -> pd.DataFrame: print("Start preprocessing") cache_data_path = Path("data/data.csv") if cache_data_path.exists(): print("Finished preprocessing") return pd.read_csv(cache_data_path) train_data_dict = {"x": [], "y": []} with h5py.File(hdf_file_path, "r") as file: for bird_name in file.keys(): for file_name in file[bird_name].keys(): shape = file[f"{bird_name}/{file_name}"].shape for i in range(shape[0]): train_data_dict["x"].append(f"{bird_name}/{file_name}_{i}") train_data_dict["y"].append(bird_name) df = pd.DataFrame(data=train_data_dict) df.to_csv(cache_data_path) print("Finished preprocessing") return df class CustomImageList(ImageList): def open(self, fn): path, i = self._split_path(fn) with h5py.File(hdf_file_path, "r") as file: mel_spec = file[path][i] return np.repeat( np.expand_dims(mel_spec, axis=0), repeats=3, axis=0 ).astype(np.float32) def _split_path(self, path: str) -> Tuple[str, int]: splits = path.split("_") path = Path("_".join(splits[:-1])) return "/".join(path.parts[-2:]), int(splits[-1]) class DataBunchCallback(Callback): def __init__(self, data: DataBunch): self.data = data def on_epoch_end(self, **kwargs: Any) -> None: self.data.save("models/data_save.pkl") """ class CustomMelSpec(torch.nn.Module): def __init__(self): super(CustomMelSpec, self).__init__() def forward(self, x): return torchaudio.functional.spectrogram(x, pad=0, window) """ def initialize_learner(df: pd.DataFrame) -> Learner: src = ( CustomImageList.from_df(df, ".", cols="x") .split_by_rand_pct(valid_pct=0.2) .label_from_df(cols="y") ) print("Create DataBunch") data = src.databunch(num_workers=8, bs=64) print("Normalize data") data.normalize() os.environ["TORCH_HOME"] = "models/pretrained" resnet34 = torchvision.models.resnet34(pretrained=True) learn = Learner(data, resnet34, metrics=accuracy) if load_saved_model and saved_model_path.exists(): learn.load(saved_model_path) learn.loss_func = torch.nn.functional.cross_entropy return learn def train(df: pd.DataFrame) -> Learner: print("Start training") learn = initialize_learner(df) callbacks = [SaveModelCallback(learn, monitor="accuracy"), DataBunchCallback(data)] learn.fit_one_cycle(8, callbacks=callbacks) learn.unfreeze() learn.fit_one_cycle(2, callbacks=callbacks) print("Finished training") return learn def process_file(file_name: Path) -> Tuple[List[List[float]], int]: try: data, SR = librosa.load(file_name) except ZeroDivisionError: data = [] SR = 22050 # remove leading and trailing zeros from the audio file data = np.trim_zeros(data) # number of samples that can be produces from this file samples = math.ceil((len(data) / SR) / sample_length) window_length = SR * sample_length result = [] if len(data) < window_length: return result, SR for i in range(samples): # Divide the audio file into sample of length # sampel_length. If there are data left at the # end the last window will overlap with the # previous one. start = i * window_length end = (i + 1) * window_length if end < data.size: sample = data[start:end] else: sample = data[data.size - window_length : data.size] result.append(sample) return result, SR def create_spectrogram(data: List[float], sr: int) -> np.ndarray: mel_spec = librosa.feature.melspectrogram( data, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels, ) # type: np.ndarray return mel_spec.astype(np.float32) def create_spectrograms(file_name: Path) -> List[np.ndarray]: data, SR = process_file(file_name) specs = [] for i, x in enumerate(data): specs.append(create_spectrogram(x, SR)) return specs def prediction_on_test_set(learn: Learner): test_df = pd.read_csv(test_csv_path) for index, row in test_df.iterrows(): path = test_data_path.joinpath(f"{row["audio_id"]}.mp3") specs = create_spectrograms(path) # TODO make predictions on spectrograms if __name__ == "__main__": train_df = preprocess_data() if not just_test: learn = train(train_df) else: learn = initialize_learner(train_df) prediction_on_test_set(learn)
import torchvision from fastai.vision import * from fastai.callbacks import SaveModelCallback import librosa import h5py # ***************************************************************************************** just_test = True # skip training and use a saved model sample_length = 5 # time window length in seconds SR = 22050 # spectrogram config n_fft = 2048 hop_length = 512 n_mels = 128 # Meta data paths train_csv_path = Path("data/mp3/train.csv") # change for training in a Kaggle Notebook test_csv_path = Path("data/mp3/test.csv") # change for training in a Kaggle Notebook # Data paths hdf_file_path = Path( "data/spectrograms_full.hdf5" ) # change for training in a Kaggle Notebook test_data_path = Path( "data/mp3/example_test_audio" ) # change for training in a Kaggle Notebook # train config load_saved_model = False saved_model_path = Path("models/bestmodel.pth") # ***************************************************************************************** # set variables for reproducibility torch.manual_seed(10) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False np.random.seed(22) def preprocess_data() -> pd.DataFrame: print("Start preprocessing") cache_data_path = Path("data/data.csv") if cache_data_path.exists(): print("Finished preprocessing") return pd.read_csv(cache_data_path) train_data_dict = {"x": [], "y": []} with h5py.File(hdf_file_path, "r") as file: for bird_name in file.keys(): for file_name in file[bird_name].keys(): shape = file[f"{bird_name}/{file_name}"].shape for i in range(shape[0]): train_data_dict["x"].append(f"{bird_name}/{file_name}_{i}") train_data_dict["y"].append(bird_name) df = pd.DataFrame(data=train_data_dict) df.to_csv(cache_data_path) print("Finished preprocessing") return df class CustomImageList(ImageList): def open(self, fn): path, i = self._split_path(fn) with h5py.File(hdf_file_path, "r") as file: mel_spec = file[path][i] return np.repeat( np.expand_dims(mel_spec, axis=0), repeats=3, axis=0 ).astype(np.float32) def _split_path(self, path: str) -> Tuple[str, int]: splits = path.split("_") path = Path("_".join(splits[:-1])) return "/".join(path.parts[-2:]), int(splits[-1]) class DataBunchCallback(Callback): def __init__(self, data: DataBunch): self.data = data def on_epoch_end(self, **kwargs: Any) -> None: self.data.save("models/data_save.pkl") """ class CustomMelSpec(torch.nn.Module): def __init__(self): super(CustomMelSpec, self).__init__() def forward(self, x): return torchaudio.functional.spectrogram(x, pad=0, window) """ def initialize_learner(df: pd.DataFrame) -> Learner: src = ( CustomImageList.from_df(df, ".", cols="x") .split_by_rand_pct(valid_pct=0.2) .label_from_df(cols="y") ) print("Create DataBunch") data = src.databunch(num_workers=8, bs=64) print("Normalize data") data.normalize() os.environ["TORCH_HOME"] = "models/pretrained" resnet34 = torchvision.models.resnet34(pretrained=True) learn = Learner(data, resnet34, metrics=accuracy) if load_saved_model and saved_model_path.exists(): learn.load(saved_model_path) learn.loss_func = torch.nn.functional.cross_entropy return learn def train(df: pd.DataFrame) -> Learner: print("Start training") learn = initialize_learner(df) callbacks = [SaveModelCallback(learn, monitor="accuracy"), DataBunchCallback(data)] learn.fit_one_cycle(8, callbacks=callbacks) learn.unfreeze() learn.fit_one_cycle(2, callbacks=callbacks) print("Finished training") return learn def process_file(file_name: Path) -> Tuple[List[List[float]], int]: try: data, SR = librosa.load(file_name) except ZeroDivisionError: data = [] SR = 22050 # remove leading and trailing zeros from the audio file data = np.trim_zeros(data) # number of samples that can be produces from this file samples = math.ceil((len(data) / SR) / sample_length) window_length = SR * sample_length result = [] if len(data) < window_length: return result, SR for i in range(samples): # Divide the audio file into sample of length # sampel_length. If there are data left at the # end the last window will overlap with the # previous one. start = i * window_length end = (i + 1) * window_length if end < data.size: sample = data[start:end] else: sample = data[data.size - window_length : data.size] result.append(sample) return result, SR def create_spectrogram(data: List[float], sr: int) -> np.ndarray: mel_spec = librosa.feature.melspectrogram( data, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels, ) # type: np.ndarray return mel_spec.astype(np.float32) def create_spectrograms(file_name: Path) -> List[np.ndarray]: data, SR = process_file(file_name) specs = [] for i, x in enumerate(data): specs.append(create_spectrogram(x, SR)) return specs def prediction_on_test_set(learn: Learner): test_df = pd.read_csv(test_csv_path) for index, row in test_df.iterrows(): path = test_data_path.joinpath(f"{row['audio_id']}.mp3") specs = create_spectrograms(path) # TODO make predictions on spectrograms if __name__ == "__main__": train_df = preprocess_data() if not just_test: learn = train(train_df) else: learn = initialize_learner(train_df) prediction_on_test_set(learn)
import sys import os import tempfile import pandas as pd import craft.config as config def finemap(data_dfs, index_df, file_dir, n_causal_snps): """ Runs Finemap and LDStore on each SNP locus. Finemap(v1.3.1) was created by Christian Brenner (http://www.christianbenner.com/) and uses summary statistics for finemapping. **INPUT** 1. Master file 2. Z file (dataset, uncompressed) The dataset.z file is a space-delimited text file and contains the GWAS summary statistics one SNP per line. It contains the mandatory column names in the following order. `rsid` contains the SNP identifiers. The identifier can be a rsID number or a combination of chromosome name and genomic position (e.g. XXX:yyy) `chromosome` contains the chromosome names. The chromosome names can be chosen freely with precomputed SNP correlations (e.g. 'X', '0X' or 'chrX') `position` contains the base pair position for each SNP `allele1` contains the "first" allele of the SNPs. In SNPTEST this corresponds to 'allele_A', whereas BOLT-LMM uses 'ALLELE1' `allele2` contains the "second" allele of the SNPs. In SNPTEST this corresponds to 'allele_B', whereas BOLT-LMM uses 'ALLELE0' `maf` contains the minor allele frequencies `beta` contains the estimated effect sizes as given by GWAS software `se` contains the standard errors of effect sizes as given by GWAS software 3. LD file Generated using LDstore, assuming PLINK input files (.bed, .bim, .fam). Other input options (support for BGEN input data, optional K file) are described at Christian Brenner's website and are not used here. **OUTPUT** """ with tempfile.TemporaryDirectory() as tempdir: # make an empty master file master = pd.DataFrame(columns=['z','ld','snp','config','cred','log', 'n_samples']) ld_store_executable = os.path.join(config.ldstore_dir, "ldstore") master_file = os.path.join(tempdir, "master_file") master = open(master_file, "w") master.write("z;ld;snp;config;cred;log;n_samples\n") # need to take in index_df region definitions. index_count = 0 for data in data_dfs: # set the PLINK basename based on chromosome in file chr = index_df.at[index_count, 'chromosome'] index = index_df.at[index_count, 'rsid'] # set filenames in tempdir with index SNP rsid (as unique identifier for input and output files) z_file = os.path.join(tempdir, index + ".z") plink_basename = os.path.join(config.plink_basename_dir, f"chr{chr}_ld_panel") bcor_file = os.path.join(tempdir, index + ".bcor") variant_file = os.path.join(file_dir, index + "_variant.txt") ld_file = os.path.join(file_dir, index + ".ld") snp_file = os.path.join(file_dir, index + ".snp") config_file = os.path.join(file_dir, index + ".config") cred_file = os.path.join(file_dir, index + ".cred") log_file = os.path.join(file_dir, index + ".log") # define region size [need to give index df as well and identify matching row based on rsid] region_start_cm = index_df.at[index_count, 'region_start_cm'] region_end_cm = index_df.at[index_count, 'region_end_cm'] # make a Z file order = ['rsid','chromosome','position','allele1','allele2','maf', 'beta', 'se'] data = data[order] data.to_csv(z_file, sep=' ', index=False, float_format='%g') # order of SNPs in LD file must correspond to order in Z file variants = data[['rsid','position','chromosome','allele1','allele2']] variants.to_csv(variant_file, sep=' ', index=False, header=['RSID','position','chromosome','A_allele','B_allele'], float_format='%g') # make an LD file (bcor) cmd = (ld_store_executable + " --bplink " + plink_basename + f" --bcor {bcor_file} --incl-range {region_start_cm}-{region_end_cm} --n-threads 1") os.system(cmd) # make an LD file matrix for our rsids in locus (matrix) cmd = (ld_store_executable + f" --bcor {bcor_file}_1 --matrix {ld_file} --incl-variants {variant_file}") os.system(cmd) # append row to master file master.write(f"{z_file};{ld_file};{snp_file};{config_file};{cred_file};{log_file};{index_df.at[index_count, "all_total"]}\n") # increment index count to bring in new region definition. index_count+=1 # Write completed master file out for use master.close() # run finemap (tell it data files are in temp directory) if n_causal_snps: cmd = (f"{config.finemap_dir}" + "/finemap_v1.3.1_x86_64" + f" --sss --in-files {master_file} --log --n-causal-snps {n_causal_snps}") os.system(cmd) else: cmd = (f"{config.finemap_dir}" + "/finemap_v1.3.1_x86_64" + f" --sss --in-files {master_file} --log") os.system(cmd) return 0
import sys import os import tempfile import pandas as pd import craft.config as config def finemap(data_dfs, index_df, file_dir, n_causal_snps): """ Runs Finemap and LDStore on each SNP locus. Finemap(v1.3.1) was created by Christian Brenner (http://www.christianbenner.com/) and uses summary statistics for finemapping. **INPUT** 1. Master file 2. Z file (dataset, uncompressed) The dataset.z file is a space-delimited text file and contains the GWAS summary statistics one SNP per line. It contains the mandatory column names in the following order. `rsid` contains the SNP identifiers. The identifier can be a rsID number or a combination of chromosome name and genomic position (e.g. XXX:yyy) `chromosome` contains the chromosome names. The chromosome names can be chosen freely with precomputed SNP correlations (e.g. 'X', '0X' or 'chrX') `position` contains the base pair position for each SNP `allele1` contains the "first" allele of the SNPs. In SNPTEST this corresponds to 'allele_A', whereas BOLT-LMM uses 'ALLELE1' `allele2` contains the "second" allele of the SNPs. In SNPTEST this corresponds to 'allele_B', whereas BOLT-LMM uses 'ALLELE0' `maf` contains the minor allele frequencies `beta` contains the estimated effect sizes as given by GWAS software `se` contains the standard errors of effect sizes as given by GWAS software 3. LD file Generated using LDstore, assuming PLINK input files (.bed, .bim, .fam). Other input options (support for BGEN input data, optional K file) are described at Christian Brenner's website and are not used here. **OUTPUT** """ with tempfile.TemporaryDirectory() as tempdir: # make an empty master file master = pd.DataFrame(columns=['z','ld','snp','config','cred','log', 'n_samples']) ld_store_executable = os.path.join(config.ldstore_dir, "ldstore") master_file = os.path.join(tempdir, "master_file") master = open(master_file, "w") master.write("z;ld;snp;config;cred;log;n_samples\n") # need to take in index_df region definitions. index_count = 0 for data in data_dfs: # set the PLINK basename based on chromosome in file chr = index_df.at[index_count, 'chromosome'] index = index_df.at[index_count, 'rsid'] # set filenames in tempdir with index SNP rsid (as unique identifier for input and output files) z_file = os.path.join(tempdir, index + ".z") plink_basename = os.path.join(config.plink_basename_dir, f"chr{chr}_ld_panel") bcor_file = os.path.join(tempdir, index + ".bcor") variant_file = os.path.join(file_dir, index + "_variant.txt") ld_file = os.path.join(file_dir, index + ".ld") snp_file = os.path.join(file_dir, index + ".snp") config_file = os.path.join(file_dir, index + ".config") cred_file = os.path.join(file_dir, index + ".cred") log_file = os.path.join(file_dir, index + ".log") # define region size [need to give index df as well and identify matching row based on rsid] region_start_cm = index_df.at[index_count, 'region_start_cm'] region_end_cm = index_df.at[index_count, 'region_end_cm'] # make a Z file order = ['rsid','chromosome','position','allele1','allele2','maf', 'beta', 'se'] data = data[order] data.to_csv(z_file, sep=' ', index=False, float_format='%g') # order of SNPs in LD file must correspond to order in Z file variants = data[['rsid','position','chromosome','allele1','allele2']] variants.to_csv(variant_file, sep=' ', index=False, header=['RSID','position','chromosome','A_allele','B_allele'], float_format='%g') # make an LD file (bcor) cmd = (ld_store_executable + " --bplink " + plink_basename + f" --bcor {bcor_file} --incl-range {region_start_cm}-{region_end_cm} --n-threads 1") os.system(cmd) # make an LD file matrix for our rsids in locus (matrix) cmd = (ld_store_executable + f" --bcor {bcor_file}_1 --matrix {ld_file} --incl-variants {variant_file}") os.system(cmd) # append row to master file master.write(f"{z_file};{ld_file};{snp_file};{config_file};{cred_file};{log_file};{index_df.at[index_count, 'all_total']}\n") # increment index count to bring in new region definition. index_count+=1 # Write completed master file out for use master.close() # run finemap (tell it data files are in temp directory) if n_causal_snps: cmd = (f"{config.finemap_dir}" + "/finemap_v1.3.1_x86_64" + f" --sss --in-files {master_file} --log --n-causal-snps {n_causal_snps}") os.system(cmd) else: cmd = (f"{config.finemap_dir}" + "/finemap_v1.3.1_x86_64" + f" --sss --in-files {master_file} --log") os.system(cmd) return 0
from discord import File, Member from discord.ext import commands from leveling.utils import get_user_data, get_rank from easy_pil import Editor, Canvas, load_image_async, Font class Level(commands.Cog): def __init__(self, bot) -> None: self.bot = bot @commands.command() async def rank(self, ctx, member: Member = None): if not member: member = ctx.author user_data = await get_user_data(self.bot.db, member.id, ctx.guild.id) # rank = await get_rank(self.bot.db, member.id, ctx.guild.id) # in case of using rank next_level_xp = (user_data["level"] + 1) * 100 current_level_xp = user_data["level"] * 100 xp_need = next_level_xp - current_level_xp xp_have = user_data["xp"] - current_level_xp percentage = (xp_need / 100) * xp_have ## Rank card background = Editor("leveling/assets/bg.png") profile = await load_image_async(str(member.avatar_url)) profile = Editor(profile).resize((150, 150)).circle_image() poppins = Font().poppins(size=40) poppins_small = Font().poppins(size=30) square = Canvas((500, 500), "#06FFBF") square = Editor(square) square.rotate(30, expand=True) background.paste(square.image, (600, -250)) background.paste(profile.image, (30, 30)) background.rectangle((30, 220), width=650, height=40, fill="white", radius=20) background.bar( (30, 220), max_width=650, height=40, percentage=percentage, fill="#FF56B2", radius=20, ) background.text((200, 40), str(member), font=poppins, color="white") background.rectangle((200, 100), width=350, height=2, fill="#17F3F6") background.text( (200, 130), f"Level : {user_data["level"]}" + f" XP : {user_data["xp"]} / {(user_data["level"] + 1) * 100}", font=poppins_small, color="white", ) file = File(fp=background.image_bytes, filename="card.png") await ctx.send(file=file) def setup(bot): bot.add_cog(Level(bot))
from discord import File, Member from discord.ext import commands from leveling.utils import get_user_data, get_rank from easy_pil import Editor, Canvas, load_image_async, Font class Level(commands.Cog): def __init__(self, bot) -> None: self.bot = bot @commands.command() async def rank(self, ctx, member: Member = None): if not member: member = ctx.author user_data = await get_user_data(self.bot.db, member.id, ctx.guild.id) # rank = await get_rank(self.bot.db, member.id, ctx.guild.id) # in case of using rank next_level_xp = (user_data["level"] + 1) * 100 current_level_xp = user_data["level"] * 100 xp_need = next_level_xp - current_level_xp xp_have = user_data["xp"] - current_level_xp percentage = (xp_need / 100) * xp_have ## Rank card background = Editor("leveling/assets/bg.png") profile = await load_image_async(str(member.avatar_url)) profile = Editor(profile).resize((150, 150)).circle_image() poppins = Font().poppins(size=40) poppins_small = Font().poppins(size=30) square = Canvas((500, 500), "#06FFBF") square = Editor(square) square.rotate(30, expand=True) background.paste(square.image, (600, -250)) background.paste(profile.image, (30, 30)) background.rectangle((30, 220), width=650, height=40, fill="white", radius=20) background.bar( (30, 220), max_width=650, height=40, percentage=percentage, fill="#FF56B2", radius=20, ) background.text((200, 40), str(member), font=poppins, color="white") background.rectangle((200, 100), width=350, height=2, fill="#17F3F6") background.text( (200, 130), f"Level : {user_data['level']}" + f" XP : {user_data['xp']} / {(user_data['level'] + 1) * 100}", font=poppins_small, color="white", ) file = File(fp=background.image_bytes, filename="card.png") await ctx.send(file=file) def setup(bot): bot.add_cog(Level(bot))
#!/usr/bin/env python3 # # installation.py r""" .. extensions:: sphinx_toolbox.installation Configuration -------------- .. confval:: conda_channels :type: :class:`~typing.List`\[:class:`str`\] :required: False :default: ``[]`` The conda channels required to install the library from Anaconda. An alternative to setting it within the :rst:dir:`installation` directive. Usage ------- .. rst:directive:: .. installation:: name Adds a series of tabs providing installation instructions for the project from a number of sources. The directive takes a single required argument -- the name of the project. If the project uses a different name on PyPI and/or Anaconda, the ``:pypi-name:`` and ``:conda-name:`` options can be used to set the name for those repositories. .. rst:directive:option:: pypi :type: flag Flag to indicate the project can be installed from PyPI. .. rst:directive:option:: pypi-name: name :type: string The name of the project on PyPI. .. rst:directive:option:: conda :type: flag Flag to indicate the project can be installed with Conda. .. rst:directive:option:: conda-name: name :type: string The name of the project on Conda. .. rst:directive:option:: conda-channels: channels :type: comma separated strings Comma-separated list of required Conda channels. This can also be set via the :confval:`conda_channels` option. .. rst:directive:option:: github :type: flag Flag to indicate the project can be installed from GitHub. To use this option add the following to your ``conf.py``: .. code-block:: python extensions = [ ... 'sphinx_toolbox.github', ] github_username = '<your username>' github_repository = '<your repository>' See :mod:`sphinx_toolbox.github` for more information. .. latex:vspace:: 5px **Example** .. rest-example:: .. installation:: sphinx-toolbox :pypi: :anaconda: :conda-channels: domdfcoding,conda-forge :github: .. latex:clearpage:: .. rst:directive:: extensions Shows instructions on how to enable a Sphinx extension. The directive takes a single argument -- the name of the extension. .. rst:directive:option:: import-name :type: string The name used to import the extension, if different from the name of the extension. .. rst:directive:option:: no-preamble :type: flag Disables the preamble text. .. rst:directive:option:: no-postamble :type: flag Disables the postamble text. .. rst:directive:option:: first :type: flag Puts the entry for extension before its dependencies. By default is is placed at the end. .. versionadded:: 0.4.0 .. latex:vspace:: 10px **Example** .. rest-example:: .. extensions:: sphinx-toolbox :import-name: sphinx_toolbox sphinx.ext.viewcode sphinx_tabs.tabs sphinx-prompt .. latex:clearpage:: API Reference -------------- """ # noqa: D400 # # Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk> # # 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. # # stdlib import inspect import re import warnings from typing import Any, Callable, Dict, List, Optional, Tuple # 3rd party import dict2css import sphinx.environment from docutils import nodes from docutils.parsers.rst import directives from docutils.statemachine import ViewList from domdf_python_tools.paths import PathPlus from domdf_python_tools.stringlist import StringList from domdf_python_tools.words import word_join from sphinx.application import Sphinx from sphinx.config import Config from sphinx.environment import BuildEnvironment from sphinx.util.docutils import SphinxDirective # this package from sphinx_toolbox import _css from sphinx_toolbox.utils import OptionSpec, Purger, SphinxExtMetadata, flag, metadata_add_version __all__ = [ "InstallationDirective", "ExtensionsDirective", "make_installation_instructions", "Sources", "sources", "pypi_installation", "conda_installation", "github_installation", "installation_node_purger", "extensions_node_purger", "copy_asset_files", "setup", ] class _Purger(Purger): def purge_nodes(self, app: Sphinx, env: BuildEnvironment, docname: str) -> None: # pragma: no cover """ Remove all redundant nodes. :param app: The Sphinx application. :param env: The Sphinx build environment. :param docname: The name of the document to remove nodes for. """ if not hasattr(env, self.attr_name): return setattr(env, self.attr_name, []) installation_node_purger = _Purger("all_installation_node_nodes") extensions_node_purger = Purger("all_extensions_node_nodes") class Sources(List[Tuple[str, str, Callable, Callable, Optional[Dict[str, Callable]]]]): """ Class to store functions that provide installation instructions for different sources. The syntax of each entry is: .. code-block:: python (option_name, source_name, getter_function, validator_function, extra_options) * ``option_name`` -- a string to use in the directive to specify the source to use, * ``source_name`` -- a string to use in the tabs to indicate the installation source, * ``getter_function`` -- the function that returns the installation instructions, * ``validator_function`` -- a function to validate the option value provided by the user, * ``extra_options`` -- a mapping of additional options for the directive that are used by the getter_function. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) _args = ["options", "env"] _directive_name = "installation" def register( self, option_name: str, source_name: str, validator: Callable = directives.unchanged, extra_options: Optional[Dict[str, Callable]] = None, ) -> Callable: """ Decorator to register a function. The function must have the following signature: .. code-block:: python def function( options: Dict[str, Any], # Mapping of option names to values. env: sphinx.environment.BuildEnvironment, # The Sphinx build environment. ) -> List[str]: ... :param option_name: A string to use in the directive to specify the source to use. :param source_name: A string to use in tabbed installation instructions to represent this source. :param validator: A function to validate the option value provided by the user. :default validator: :func:`docutils.parsers.rst.directives.unchanged` :param extra_options: An optional mapping of extra option names to validator functions. :default extra_options: ``{}`` :return: The registered function. :raises: :exc:`SyntaxError` if the decorated function does not take the correct arguments. """ def _decorator(function: Callable) -> Callable: signature = inspect.signature(function) if list(signature.parameters.keys()) != self._args: raise SyntaxError( # pragma: no cover "The decorated function must take only the following arguments: " f"{word_join(self._args, use_repr=True, oxford=True)}" ) self.append((option_name, source_name, function, validator, extra_options or {})) setattr(function, f"_{self._directive_name}_registered", True) return function return _decorator #: Instance of :class:`~.Sources`. sources: Sources = Sources() # pypi_name: The name of the project on PyPI. @sources.register("pypi", "PyPI", flag, {"pypi-name": directives.unchanged}) def pypi_installation( options: Dict[str, Any], env: sphinx.environment.BuildEnvironment, ) -> List[str]: """ Source to provide instructions for installing from PyPI. :param options: Mapping of option names to values. :param env: The Sphinx build environment. """ if "pypi-name" in options: pypi_name = options["pypi-name"] elif "project_name" in options: pypi_name = options["project_name"] else: raise ValueError("No PyPI project name supplied for the PyPI installation instructions.") return [".. prompt:: bash", '', f" python3 -m pip install {pypi_name} --user"] # conda_name: The name of the project on PyPI. @sources.register( "anaconda", "Anaconda", flag, {"conda-name": directives.unchanged, "conda-channels": directives.unchanged}, ) def conda_installation( options: Dict[str, Any], env: sphinx.environment.BuildEnvironment, ) -> List[str]: """ Source to provide instructions for installing from Anaconda. :param options: Mapping of option names to values. :param env: The Sphinx build environment. """ if "conda-name" in options: conda_name = options["conda-name"] elif "pypi-name" in options: conda_name = options["pypi-name"] elif "project_name" in options: conda_name = options["project_name"] else: raise ValueError("No username supplied for the Anaconda installation instructions.") lines: StringList = StringList() lines.indent_type = " " if "conda-channels" in options: channels = str(options["conda-channels"]).split(',') else: channels = env.config.conda_channels if channels: lines.append("First add the required channels\n\n.. prompt:: bash\n") with lines.with_indent_size(lines.indent_size + 1): for channel in channels: lines.append(f"conda config --add channels https://conda.anaconda.org/{channel.strip()}") lines.append("\nThen install") if lines: lines.blankline(ensure_single=True) lines.append(f".. prompt:: bash") lines.blankline(ensure_single=True) with lines.with_indent_size(lines.indent_size + 1): lines.append(f"conda install {conda_name}") lines.blankline(ensure_single=True) return list(lines) @sources.register("github", "GitHub", flag) def github_installation( options: Dict[str, Any], env: sphinx.environment.BuildEnvironment, ) -> List[str]: """ Source to provide instructions for installing from GitHub. :param options: Mapping of option names to values. :param env: The Sphinx build environment. """ if "sphinx_toolbox.github" not in env.app.extensions: raise ValueError( "The 'sphinx_toolbox.github' extension is required for the " ":github: option but it is not enabled!" ) username = getattr(env.config, "github_username", None) if username is None: raise ValueError("'github_username' has not been set in 'conf.py'!") repository = getattr(env.config, "github_repository", None) if repository is None: raise ValueError("'github_repository' has not been set in 'conf.py'!") return [ ".. prompt:: bash", '', f" python3 -m pip install git+https://github.com/{username}/{repository}@master --user" ] class InstallationDirective(SphinxDirective): """ Directive to show installation instructions. """ has_content: bool = True optional_arguments: int = 1 # The name of the project; can be overridden for each source # Registered sources option_spec: OptionSpec = { # type: ignore source[0].lower(): source[3] for source in sources # pylint: disable=not-an-iterable } # Extra options for registered sources for source in sources: # pylint: disable=not-an-iterable if source[4] is not None: option_spec.update(source[4]) # type: ignore options: Dict[str, Any] """ Mapping of option names to values. The options are as follows: * **pypi**: Flag to indicate the project can be installed from PyPI. * **pypi-name**: The name of the project on PyPI. * **conda**: Flag to indicate the project can be installed with Conda. * **conda-name**: The name of the project on Conda. * **conda-channels**: Comma-separated list of required Conda channels. * **github**: Flag to indicate the project can be installed from GitHub. The GitHub username and repository are configured in ``conf.py`` and are available in ``env.config``. """ def run_html(self) -> List[nodes.Node]: """ Generate output for ``HTML`` builders. """ targetid = f'installation-{self.env.new_serialno('sphinx-toolbox installation'):d}' targetnode = nodes.target('', '', ids=[targetid]) content = make_installation_instructions(self.options, self.env) view = ViewList(content) installation_node = nodes.paragraph(rawsource=content) # type: ignore self.state.nested_parse(view, self.content_offset, installation_node) # type: ignore installation_node_purger.add_node(self.env, installation_node, targetnode, self.lineno) return [targetnode, installation_node] def run_generic(self) -> List[nodes.Node]: """ Generate generic reStructuredText output. """ targetid = f'installation-{self.env.new_serialno('sphinx-toolbox installation'):d}' targetnode = nodes.target('', '', ids=[targetid]) tabs: Dict[str, List[str]] = _get_installation_instructions(self.options, self.env) if not tabs: warnings.warn("No installation source specified. No installation instructions will be shown.") return [] nodes_to_return: List[nodes.Node] = [targetnode] for tab_name, tab_content in tabs.items(): section_id = re.sub(r'\W+', '_', tab_name) section = nodes.section(ids=[f"{targetid}-{section_id}"]) section += nodes.title(tab_name, tab_name) nodes_to_return.append(section) installation_node_purger.add_node(self.env, section, targetnode, self.lineno) view = ViewList(tab_content) paragraph_node = nodes.paragraph(rawsource=tab_content) # type: ignore self.state.nested_parse(view, self.content_offset, paragraph_node) # type: ignore nodes_to_return.append(paragraph_node) installation_node_purger.add_node(self.env, paragraph_node, targetnode, self.lineno) return nodes_to_return def run(self) -> List[nodes.Node]: """ Create the installation node. """ assert self.env.app.builder is not None if self.arguments: self.options["project_name"] = self.arguments[0] if self.env.app.builder.format.lower() == "html": return self.run_html() else: return self.run_generic() def make_installation_instructions(options: Dict[str, Any], env: BuildEnvironment) -> List[str]: """ Make the content of an installation node. :param options: :param env: The Sphinx build environment. """ tabs: Dict[str, List[str]] = _get_installation_instructions(options, env) if not tabs: warnings.warn("No installation source specified. No installation instructions will be shown.") return [] content = StringList([".. tabs::", '']) content.set_indent_type(" ") for tab_name, tab_content in tabs.items(): with content.with_indent_size(1): content.append(f".. tab:: {tab_name}") content.blankline(ensure_single=True) with content.with_indent_size(2): content.extend([f"{line}" if line else '' for line in tab_content]) return list(content) def _get_installation_instructions(options: Dict[str, Any], env: BuildEnvironment) -> Dict[str, List[str]]: """ Returns a mapping of tab/section names to their content. :param options: :param env: The Sphinx build environment. """ tabs: Dict[str, List[str]] = {} for option_name, source_name, getter_function, validator_function, extra_options in sources: if option_name in options: tabs[f"from {source_name}"] = getter_function(options, env) return tabs class ExtensionsDirective(SphinxDirective): """ Directive to show instructions for enabling the extension. """ has_content: bool = True # Other required extensions, one per line optional_arguments: int = 1 # The name of the project option_spec: OptionSpec = { # type: ignore "import-name": directives.unchanged_required, # If different to project name "no-preamble": flag, "no-postamble": flag, "first": flag, } def run(self) -> List[nodes.Node]: """ Create the extensions node. """ extensions = list(self.content) first = self.options.get("first", False) if "import-name" in self.options and first: extensions.insert(0, self.options["import-name"]) elif "import-name" in self.options: extensions.append(self.options["import-name"]) elif first: extensions.insert(0, self.arguments[0]) else: extensions.append(self.arguments[0]) targetid = f'extensions-{self.env.new_serialno('sphinx-toolbox extensions'):d}' targetnode = nodes.target('', '', ids=[targetid]) top_text = [ ".. latex:vspace:: 10px", ".. rst-class:: sphinx-toolbox-extensions", '', f" Enable ``{self.arguments[0]}`` by adding the following", f" to the ``extensions`` variable in your ``conf.py``:", ] bottom_text = ( "For more information see " "https://www.sphinx-doc.org/en/master/usage/extensions#third-party-extensions ." ) if "no-preamble" in self.options: content = [] else: content = [*top_text, ''] content.append(".. code-block:: python", ) if "no-postamble" not in self.options: content.append(" :class: sphinx-toolbox-extensions") content.extend([ '', " extensions = [", " ...", ]) for extension in extensions: content.append(f" {extension!r},") content.extend([" ]", '']) if "no-postamble" not in self.options: content.extend([bottom_text, '']) extensions_node = nodes.paragraph(rawsource=content) # type: ignore self.state.nested_parse(ViewList(content), self.content_offset, extensions_node) # type: ignore extensions_node_purger.add_node(self.env, extensions_node, targetnode, self.lineno) return [targetnode, extensions_node] def copy_asset_files(app: Sphinx, exception: Optional[Exception] = None): """ Copy additional stylesheets into the HTML build directory. .. versionadded:: 1.2.0 :param app: The Sphinx application. :param exception: Any exception which occurred and caused Sphinx to abort. """ if exception: # pragma: no cover return if app.builder is None or app.builder.format.lower() != "html": return static_dir = PathPlus(app.outdir) / "_static" static_dir.maybe_make(parents=True) dict2css.dump(_css.installation_styles, static_dir / "sphinx_toolbox_installation.css", minify=True) (static_dir / "sphinx_toolbox_installation.js").write_lines([ "// Based on https://github.com/executablebooks/sphinx-tabs/blob/master/sphinx_tabs/static/tabs.js", "// Copyright (c) 2017 djungelorm", "// MIT Licensed", '', "function deselectTabset(target) {", " const parent = target.parentNode;", " const grandparent = parent.parentNode;", '', ' if (parent.parentNode.parentNode.getAttribute("id").startsWith("installation")) {', '', " // Hide all tabs in current tablist, but not nested", " Array.from(parent.children).forEach(t => {", ' if (t.getAttribute("name") !== target.getAttribute("name")) {', ' t.setAttribute("aria-selected", "false");', " }", " });", '', " // Hide all associated panels", " Array.from(grandparent.children).slice(1).forEach(p => { // Skip tablist", ' if (p.getAttribute("name") !== target.getAttribute("name")) {', ' p.setAttribute("hidden", "false")', " }", " });", " }", '', " else {", " // Hide all tabs in current tablist, but not nested", " Array.from(parent.children).forEach(t => {", ' t.setAttribute("aria-selected", "false");', " });", '', " // Hide all associated panels", " Array.from(grandparent.children).slice(1).forEach(p => { // Skip tablist", ' p.setAttribute("hidden", "true")', " });", " }", '', '}', '', "// Compatibility with sphinx-tabs 2.1.0 and later", "function deselectTabList(tab) {deselectTabset(tab)}", '', ]) def _on_config_inited(app: Sphinx, config: Config): app.add_css_file("sphinx_toolbox_installation.css") app.add_js_file("sphinx_toolbox_installation.js") @metadata_add_version def setup(app: Sphinx) -> SphinxExtMetadata: """ Setup :mod:`sphinx_toolbox.installation`. .. versionadded:: 0.7.0 :param app: The Sphinx application. """ if "sphinx_inline_tabs" not in getattr(app, "extensions", ()): app.setup_extension("sphinx_tabs.tabs") app.setup_extension("sphinx-prompt") app.setup_extension("sphinx_toolbox._css") app.setup_extension("sphinx_toolbox.latex") app.add_config_value("conda_channels", [], "env", types=[list]) # Instructions for installing a python package app.add_directive("installation", InstallationDirective) app.connect("env-get-outdated", installation_node_purger.get_outdated_docnames) # app.connect("env-purge-doc", installation_node_purger.purge_nodes) # Instructions for enabling a sphinx extension app.add_directive("extensions", ExtensionsDirective) app.connect("env-purge-doc", extensions_node_purger.purge_nodes) # Ensure this happens after tabs.js has been added app.connect("config-inited", _on_config_inited, priority=510) app.connect("build-finished", copy_asset_files) return {"parallel_read_safe": True}
#!/usr/bin/env python3 # # installation.py r""" .. extensions:: sphinx_toolbox.installation Configuration -------------- .. confval:: conda_channels :type: :class:`~typing.List`\[:class:`str`\] :required: False :default: ``[]`` The conda channels required to install the library from Anaconda. An alternative to setting it within the :rst:dir:`installation` directive. Usage ------- .. rst:directive:: .. installation:: name Adds a series of tabs providing installation instructions for the project from a number of sources. The directive takes a single required argument -- the name of the project. If the project uses a different name on PyPI and/or Anaconda, the ``:pypi-name:`` and ``:conda-name:`` options can be used to set the name for those repositories. .. rst:directive:option:: pypi :type: flag Flag to indicate the project can be installed from PyPI. .. rst:directive:option:: pypi-name: name :type: string The name of the project on PyPI. .. rst:directive:option:: conda :type: flag Flag to indicate the project can be installed with Conda. .. rst:directive:option:: conda-name: name :type: string The name of the project on Conda. .. rst:directive:option:: conda-channels: channels :type: comma separated strings Comma-separated list of required Conda channels. This can also be set via the :confval:`conda_channels` option. .. rst:directive:option:: github :type: flag Flag to indicate the project can be installed from GitHub. To use this option add the following to your ``conf.py``: .. code-block:: python extensions = [ ... 'sphinx_toolbox.github', ] github_username = '<your username>' github_repository = '<your repository>' See :mod:`sphinx_toolbox.github` for more information. .. latex:vspace:: 5px **Example** .. rest-example:: .. installation:: sphinx-toolbox :pypi: :anaconda: :conda-channels: domdfcoding,conda-forge :github: .. latex:clearpage:: .. rst:directive:: extensions Shows instructions on how to enable a Sphinx extension. The directive takes a single argument -- the name of the extension. .. rst:directive:option:: import-name :type: string The name used to import the extension, if different from the name of the extension. .. rst:directive:option:: no-preamble :type: flag Disables the preamble text. .. rst:directive:option:: no-postamble :type: flag Disables the postamble text. .. rst:directive:option:: first :type: flag Puts the entry for extension before its dependencies. By default is is placed at the end. .. versionadded:: 0.4.0 .. latex:vspace:: 10px **Example** .. rest-example:: .. extensions:: sphinx-toolbox :import-name: sphinx_toolbox sphinx.ext.viewcode sphinx_tabs.tabs sphinx-prompt .. latex:clearpage:: API Reference -------------- """ # noqa: D400 # # Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk> # # 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. # # stdlib import inspect import re import warnings from typing import Any, Callable, Dict, List, Optional, Tuple # 3rd party import dict2css import sphinx.environment from docutils import nodes from docutils.parsers.rst import directives from docutils.statemachine import ViewList from domdf_python_tools.paths import PathPlus from domdf_python_tools.stringlist import StringList from domdf_python_tools.words import word_join from sphinx.application import Sphinx from sphinx.config import Config from sphinx.environment import BuildEnvironment from sphinx.util.docutils import SphinxDirective # this package from sphinx_toolbox import _css from sphinx_toolbox.utils import OptionSpec, Purger, SphinxExtMetadata, flag, metadata_add_version __all__ = [ "InstallationDirective", "ExtensionsDirective", "make_installation_instructions", "Sources", "sources", "pypi_installation", "conda_installation", "github_installation", "installation_node_purger", "extensions_node_purger", "copy_asset_files", "setup", ] class _Purger(Purger): def purge_nodes(self, app: Sphinx, env: BuildEnvironment, docname: str) -> None: # pragma: no cover """ Remove all redundant nodes. :param app: The Sphinx application. :param env: The Sphinx build environment. :param docname: The name of the document to remove nodes for. """ if not hasattr(env, self.attr_name): return setattr(env, self.attr_name, []) installation_node_purger = _Purger("all_installation_node_nodes") extensions_node_purger = Purger("all_extensions_node_nodes") class Sources(List[Tuple[str, str, Callable, Callable, Optional[Dict[str, Callable]]]]): """ Class to store functions that provide installation instructions for different sources. The syntax of each entry is: .. code-block:: python (option_name, source_name, getter_function, validator_function, extra_options) * ``option_name`` -- a string to use in the directive to specify the source to use, * ``source_name`` -- a string to use in the tabs to indicate the installation source, * ``getter_function`` -- the function that returns the installation instructions, * ``validator_function`` -- a function to validate the option value provided by the user, * ``extra_options`` -- a mapping of additional options for the directive that are used by the getter_function. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) _args = ["options", "env"] _directive_name = "installation" def register( self, option_name: str, source_name: str, validator: Callable = directives.unchanged, extra_options: Optional[Dict[str, Callable]] = None, ) -> Callable: """ Decorator to register a function. The function must have the following signature: .. code-block:: python def function( options: Dict[str, Any], # Mapping of option names to values. env: sphinx.environment.BuildEnvironment, # The Sphinx build environment. ) -> List[str]: ... :param option_name: A string to use in the directive to specify the source to use. :param source_name: A string to use in tabbed installation instructions to represent this source. :param validator: A function to validate the option value provided by the user. :default validator: :func:`docutils.parsers.rst.directives.unchanged` :param extra_options: An optional mapping of extra option names to validator functions. :default extra_options: ``{}`` :return: The registered function. :raises: :exc:`SyntaxError` if the decorated function does not take the correct arguments. """ def _decorator(function: Callable) -> Callable: signature = inspect.signature(function) if list(signature.parameters.keys()) != self._args: raise SyntaxError( # pragma: no cover "The decorated function must take only the following arguments: " f"{word_join(self._args, use_repr=True, oxford=True)}" ) self.append((option_name, source_name, function, validator, extra_options or {})) setattr(function, f"_{self._directive_name}_registered", True) return function return _decorator #: Instance of :class:`~.Sources`. sources: Sources = Sources() # pypi_name: The name of the project on PyPI. @sources.register("pypi", "PyPI", flag, {"pypi-name": directives.unchanged}) def pypi_installation( options: Dict[str, Any], env: sphinx.environment.BuildEnvironment, ) -> List[str]: """ Source to provide instructions for installing from PyPI. :param options: Mapping of option names to values. :param env: The Sphinx build environment. """ if "pypi-name" in options: pypi_name = options["pypi-name"] elif "project_name" in options: pypi_name = options["project_name"] else: raise ValueError("No PyPI project name supplied for the PyPI installation instructions.") return [".. prompt:: bash", '', f" python3 -m pip install {pypi_name} --user"] # conda_name: The name of the project on PyPI. @sources.register( "anaconda", "Anaconda", flag, {"conda-name": directives.unchanged, "conda-channels": directives.unchanged}, ) def conda_installation( options: Dict[str, Any], env: sphinx.environment.BuildEnvironment, ) -> List[str]: """ Source to provide instructions for installing from Anaconda. :param options: Mapping of option names to values. :param env: The Sphinx build environment. """ if "conda-name" in options: conda_name = options["conda-name"] elif "pypi-name" in options: conda_name = options["pypi-name"] elif "project_name" in options: conda_name = options["project_name"] else: raise ValueError("No username supplied for the Anaconda installation instructions.") lines: StringList = StringList() lines.indent_type = " " if "conda-channels" in options: channels = str(options["conda-channels"]).split(',') else: channels = env.config.conda_channels if channels: lines.append("First add the required channels\n\n.. prompt:: bash\n") with lines.with_indent_size(lines.indent_size + 1): for channel in channels: lines.append(f"conda config --add channels https://conda.anaconda.org/{channel.strip()}") lines.append("\nThen install") if lines: lines.blankline(ensure_single=True) lines.append(f".. prompt:: bash") lines.blankline(ensure_single=True) with lines.with_indent_size(lines.indent_size + 1): lines.append(f"conda install {conda_name}") lines.blankline(ensure_single=True) return list(lines) @sources.register("github", "GitHub", flag) def github_installation( options: Dict[str, Any], env: sphinx.environment.BuildEnvironment, ) -> List[str]: """ Source to provide instructions for installing from GitHub. :param options: Mapping of option names to values. :param env: The Sphinx build environment. """ if "sphinx_toolbox.github" not in env.app.extensions: raise ValueError( "The 'sphinx_toolbox.github' extension is required for the " ":github: option but it is not enabled!" ) username = getattr(env.config, "github_username", None) if username is None: raise ValueError("'github_username' has not been set in 'conf.py'!") repository = getattr(env.config, "github_repository", None) if repository is None: raise ValueError("'github_repository' has not been set in 'conf.py'!") return [ ".. prompt:: bash", '', f" python3 -m pip install git+https://github.com/{username}/{repository}@master --user" ] class InstallationDirective(SphinxDirective): """ Directive to show installation instructions. """ has_content: bool = True optional_arguments: int = 1 # The name of the project; can be overridden for each source # Registered sources option_spec: OptionSpec = { # type: ignore source[0].lower(): source[3] for source in sources # pylint: disable=not-an-iterable } # Extra options for registered sources for source in sources: # pylint: disable=not-an-iterable if source[4] is not None: option_spec.update(source[4]) # type: ignore options: Dict[str, Any] """ Mapping of option names to values. The options are as follows: * **pypi**: Flag to indicate the project can be installed from PyPI. * **pypi-name**: The name of the project on PyPI. * **conda**: Flag to indicate the project can be installed with Conda. * **conda-name**: The name of the project on Conda. * **conda-channels**: Comma-separated list of required Conda channels. * **github**: Flag to indicate the project can be installed from GitHub. The GitHub username and repository are configured in ``conf.py`` and are available in ``env.config``. """ def run_html(self) -> List[nodes.Node]: """ Generate output for ``HTML`` builders. """ targetid = f'installation-{self.env.new_serialno("sphinx-toolbox installation"):d}' targetnode = nodes.target('', '', ids=[targetid]) content = make_installation_instructions(self.options, self.env) view = ViewList(content) installation_node = nodes.paragraph(rawsource=content) # type: ignore self.state.nested_parse(view, self.content_offset, installation_node) # type: ignore installation_node_purger.add_node(self.env, installation_node, targetnode, self.lineno) return [targetnode, installation_node] def run_generic(self) -> List[nodes.Node]: """ Generate generic reStructuredText output. """ targetid = f'installation-{self.env.new_serialno("sphinx-toolbox installation"):d}' targetnode = nodes.target('', '', ids=[targetid]) tabs: Dict[str, List[str]] = _get_installation_instructions(self.options, self.env) if not tabs: warnings.warn("No installation source specified. No installation instructions will be shown.") return [] nodes_to_return: List[nodes.Node] = [targetnode] for tab_name, tab_content in tabs.items(): section_id = re.sub(r'\W+', '_', tab_name) section = nodes.section(ids=[f"{targetid}-{section_id}"]) section += nodes.title(tab_name, tab_name) nodes_to_return.append(section) installation_node_purger.add_node(self.env, section, targetnode, self.lineno) view = ViewList(tab_content) paragraph_node = nodes.paragraph(rawsource=tab_content) # type: ignore self.state.nested_parse(view, self.content_offset, paragraph_node) # type: ignore nodes_to_return.append(paragraph_node) installation_node_purger.add_node(self.env, paragraph_node, targetnode, self.lineno) return nodes_to_return def run(self) -> List[nodes.Node]: """ Create the installation node. """ assert self.env.app.builder is not None if self.arguments: self.options["project_name"] = self.arguments[0] if self.env.app.builder.format.lower() == "html": return self.run_html() else: return self.run_generic() def make_installation_instructions(options: Dict[str, Any], env: BuildEnvironment) -> List[str]: """ Make the content of an installation node. :param options: :param env: The Sphinx build environment. """ tabs: Dict[str, List[str]] = _get_installation_instructions(options, env) if not tabs: warnings.warn("No installation source specified. No installation instructions will be shown.") return [] content = StringList([".. tabs::", '']) content.set_indent_type(" ") for tab_name, tab_content in tabs.items(): with content.with_indent_size(1): content.append(f".. tab:: {tab_name}") content.blankline(ensure_single=True) with content.with_indent_size(2): content.extend([f"{line}" if line else '' for line in tab_content]) return list(content) def _get_installation_instructions(options: Dict[str, Any], env: BuildEnvironment) -> Dict[str, List[str]]: """ Returns a mapping of tab/section names to their content. :param options: :param env: The Sphinx build environment. """ tabs: Dict[str, List[str]] = {} for option_name, source_name, getter_function, validator_function, extra_options in sources: if option_name in options: tabs[f"from {source_name}"] = getter_function(options, env) return tabs class ExtensionsDirective(SphinxDirective): """ Directive to show instructions for enabling the extension. """ has_content: bool = True # Other required extensions, one per line optional_arguments: int = 1 # The name of the project option_spec: OptionSpec = { # type: ignore "import-name": directives.unchanged_required, # If different to project name "no-preamble": flag, "no-postamble": flag, "first": flag, } def run(self) -> List[nodes.Node]: """ Create the extensions node. """ extensions = list(self.content) first = self.options.get("first", False) if "import-name" in self.options and first: extensions.insert(0, self.options["import-name"]) elif "import-name" in self.options: extensions.append(self.options["import-name"]) elif first: extensions.insert(0, self.arguments[0]) else: extensions.append(self.arguments[0]) targetid = f'extensions-{self.env.new_serialno("sphinx-toolbox extensions"):d}' targetnode = nodes.target('', '', ids=[targetid]) top_text = [ ".. latex:vspace:: 10px", ".. rst-class:: sphinx-toolbox-extensions", '', f" Enable ``{self.arguments[0]}`` by adding the following", f" to the ``extensions`` variable in your ``conf.py``:", ] bottom_text = ( "For more information see " "https://www.sphinx-doc.org/en/master/usage/extensions#third-party-extensions ." ) if "no-preamble" in self.options: content = [] else: content = [*top_text, ''] content.append(".. code-block:: python", ) if "no-postamble" not in self.options: content.append(" :class: sphinx-toolbox-extensions") content.extend([ '', " extensions = [", " ...", ]) for extension in extensions: content.append(f" {extension!r},") content.extend([" ]", '']) if "no-postamble" not in self.options: content.extend([bottom_text, '']) extensions_node = nodes.paragraph(rawsource=content) # type: ignore self.state.nested_parse(ViewList(content), self.content_offset, extensions_node) # type: ignore extensions_node_purger.add_node(self.env, extensions_node, targetnode, self.lineno) return [targetnode, extensions_node] def copy_asset_files(app: Sphinx, exception: Optional[Exception] = None): """ Copy additional stylesheets into the HTML build directory. .. versionadded:: 1.2.0 :param app: The Sphinx application. :param exception: Any exception which occurred and caused Sphinx to abort. """ if exception: # pragma: no cover return if app.builder is None or app.builder.format.lower() != "html": return static_dir = PathPlus(app.outdir) / "_static" static_dir.maybe_make(parents=True) dict2css.dump(_css.installation_styles, static_dir / "sphinx_toolbox_installation.css", minify=True) (static_dir / "sphinx_toolbox_installation.js").write_lines([ "// Based on https://github.com/executablebooks/sphinx-tabs/blob/master/sphinx_tabs/static/tabs.js", "// Copyright (c) 2017 djungelorm", "// MIT Licensed", '', "function deselectTabset(target) {", " const parent = target.parentNode;", " const grandparent = parent.parentNode;", '', ' if (parent.parentNode.parentNode.getAttribute("id").startsWith("installation")) {', '', " // Hide all tabs in current tablist, but not nested", " Array.from(parent.children).forEach(t => {", ' if (t.getAttribute("name") !== target.getAttribute("name")) {', ' t.setAttribute("aria-selected", "false");', " }", " });", '', " // Hide all associated panels", " Array.from(grandparent.children).slice(1).forEach(p => { // Skip tablist", ' if (p.getAttribute("name") !== target.getAttribute("name")) {', ' p.setAttribute("hidden", "false")', " }", " });", " }", '', " else {", " // Hide all tabs in current tablist, but not nested", " Array.from(parent.children).forEach(t => {", ' t.setAttribute("aria-selected", "false");', " });", '', " // Hide all associated panels", " Array.from(grandparent.children).slice(1).forEach(p => { // Skip tablist", ' p.setAttribute("hidden", "true")', " });", " }", '', '}', '', "// Compatibility with sphinx-tabs 2.1.0 and later", "function deselectTabList(tab) {deselectTabset(tab)}", '', ]) def _on_config_inited(app: Sphinx, config: Config): app.add_css_file("sphinx_toolbox_installation.css") app.add_js_file("sphinx_toolbox_installation.js") @metadata_add_version def setup(app: Sphinx) -> SphinxExtMetadata: """ Setup :mod:`sphinx_toolbox.installation`. .. versionadded:: 0.7.0 :param app: The Sphinx application. """ if "sphinx_inline_tabs" not in getattr(app, "extensions", ()): app.setup_extension("sphinx_tabs.tabs") app.setup_extension("sphinx-prompt") app.setup_extension("sphinx_toolbox._css") app.setup_extension("sphinx_toolbox.latex") app.add_config_value("conda_channels", [], "env", types=[list]) # Instructions for installing a python package app.add_directive("installation", InstallationDirective) app.connect("env-get-outdated", installation_node_purger.get_outdated_docnames) # app.connect("env-purge-doc", installation_node_purger.purge_nodes) # Instructions for enabling a sphinx extension app.add_directive("extensions", ExtensionsDirective) app.connect("env-purge-doc", extensions_node_purger.purge_nodes) # Ensure this happens after tabs.js has been added app.connect("config-inited", _on_config_inited, priority=510) app.connect("build-finished", copy_asset_files) return {"parallel_read_safe": True}
""" Saturn-specific override of ``dask.distributed.deploy.SpecCluster`` See https://distributed.dask.org/en/latest/_modules/distributed/deploy/spec.html for details on the parent class. """ import os import json import logging import warnings import weakref from distutils.version import LooseVersion from typing import Any, Dict, List, Optional from urllib.parse import urljoin import requests from distributed import Client, SpecCluster from distributed.security import Security from tornado.ioloop import PeriodicCallback from .backoff import ExpBackoff from .external import _security, ExternalConnection # noqa # pylint: disable=unused-import from .plugins import SaturnSetup from .settings import Settings DEFAULT_WAIT_TIMEOUT_SECONDS = 1200 log = logging.getLogger("dask-saturn") if log.level == logging.NOTSET: logging.basicConfig() log.setLevel(logging.INFO) class SaturnCluster(SpecCluster): """ Create a ``SaturnCluster``, an extension of ``distributed.SpecCluster`` specific to Saturn Cloud. :param n_workers: Number of workers to provision for the cluster. :param cluster_url: URL for the "cluster" service running in kubernetes. This component of a ``Dask`` cluster in kubernetes knows how to create pods for workers and the scheduler. :param worker_size: A string with the size to use for each worker. A list of valid sizes and their details can be obtained with ``dask_saturn.describe_sizes()``. If no size is provided, this will default to the size configured for Jupyter in your Saturn Cloud project. :param worker_is_spot: Flag to indicate if workers should be started on Spot Instances nodes. Added in dask-saturn 0.1.0, Saturn 2020.08.28. :param scheduler_size: A string with the size to use for the scheduler. A list of valid sizes and their details can be obtained with ``dask_saturn.describe_sizes()``. If no size is provided, this will default to the size configured for Jupyter in your Saturn Cloud project. :param nprocs: The number of ``dask-worker`` processes run on each host in a distributed cluster. :param nthreads: The number of threads available to each ``dask-worker`` process. :param scheduler_service_wait_timeout: The maximum amout of time, in seconds, that ``SaturnCluster`` will wait for the scheduler to respond before deciding that the scheduler is taking too long. By default, this is set to 1200 (20 minutes). Setting it to a lower value will help you catch problems earlier, but may also lead to false positives if you don't give the cluster enough to time to start up. :param shutdown_on_close: Whether or not the cluster should be automatically destroyed when its calling process is destroyed. Set this parameter to ``True`` if you want your cluster to shutdown when the work is done. By default, this is ``False`` if the cluster is attached to a Jupyter server, deployment, or job. If the cluster is attached to a Prefect Cloud flow run, this option is always set to ``True``. Note: ``autoclose`` is accepted as an alias for now, but will be removed in the future. """ # pylint: disable=unused-argument,super-init-not-called,too-many-instance-attributes _sizes = None _instances = weakref.WeakSet() def __init__( self, *args, n_workers: Optional[int] = None, cluster_url: Optional[str] = None, worker_size: Optional[str] = None, worker_is_spot: Optional[bool] = None, scheduler_size: Optional[str] = None, nprocs: Optional[int] = None, nthreads: Optional[int] = None, scheduler_service_wait_timeout: int = DEFAULT_WAIT_TIMEOUT_SECONDS, shutdown_on_close: bool = False, **kwargs, ): if "external_connection" in kwargs: raise RuntimeError( "Passing external_connection as a key word argument is no longer supported. " "Instead, set the env vars: ``SATURN_TOKEN`` and ``SATURN_BASE_URL`` " "as indicated in the Saturn Cloud UI. If those env vars are set, an external " "connection will be automatically set up." ) if "autoclose" in kwargs: warnings.warn( "``autoclose`` has been deprecated and will be removed in a future version. " "Please use ``shutdown_on_close`` instead.", category=FutureWarning, ) shutdown_on_close = kwargs.pop("autoclose") self.settings = Settings() if self.settings.is_prefect: # defaults to True if related to prefect, else defaults to False shutdown_on_close = True if cluster_url is None: self._start( n_workers=n_workers, worker_size=worker_size, worker_is_spot=worker_is_spot, scheduler_size=scheduler_size, nprocs=nprocs, nthreads=nthreads, scheduler_service_wait_timeout=scheduler_service_wait_timeout, ) else: self.cluster_url = cluster_url if cluster_url.endswith("/") else cluster_url + "/" self.dask_cluster_id = self.cluster_url.rstrip("/").split("/")[-1] info = self._get_info() self._name = self.dask_cluster_id self._dashboard_link = info["dashboard_link"] self._scheduler_address = info["scheduler_address"] self.loop = None self.periodic_callbacks: Dict[str, PeriodicCallback] = {} self.shutdown_on_close = shutdown_on_close self._adaptive = None self._instances.add(self) if self.settings.is_external: self.security = _security(self.settings, self.dask_cluster_id) else: self.security = Security() try: self.register_default_plugin() except Exception as e: # pylint: disable=broad-except log.warning( f"Registering default plugin failed: {e} Hint: you might " "have a different dask-saturn version on your dask cluster." ) def __await__(self): async def _(): pass return _().__await__() @classmethod def reset( cls, n_workers: Optional[int] = None, worker_size: Optional[str] = None, worker_is_spot: Optional[bool] = None, scheduler_size: Optional[str] = None, nprocs: Optional[int] = None, nthreads: Optional[int] = None, ) -> "SaturnCluster": """Return a SaturnCluster Destroy existing Dask cluster attached to the Jupyter Notebook or Custom Deployment and recreate it with the given configuration. For documentation on this method's parameters, see ``help(SaturnCluster)``. """ log.info("Resetting cluster.") settings = Settings() url = urljoin(settings.url, "api/dask_clusters/reset") cluster_config = { "n_workers": n_workers, "worker_size": worker_size, "worker_is_spot": worker_is_spot, "scheduler_size": scheduler_size, "nprocs": nprocs, "nthreads": nthreads, } # only send kwargs that are explicity set by user cluster_config = {k: v for k, v in cluster_config.items() if v is not None} response = requests.post(url, data=json.dumps(cluster_config), headers=settings.headers) if not response.ok: raise ValueError(response.json()["message"]) return cls(**cluster_config) @property def status(self) -> Optional[str]: """ Status of the cluster """ if self.cluster_url is None: return "closed" url = urljoin(self.cluster_url, "status") response = requests.get(url, headers=self.settings.headers) if not response.ok: return self._get_pod_status() return response.json()["status"] def _get_pod_status(self) -> Optional[str]: """ Status of the KubeCluster pod. """ response = requests.get(self.cluster_url[:-1], headers=self.settings.headers) if response.ok: return response.json()["status"] else: return None @property def _supports_scaling(self) -> bool: """ Property required by ``SpecCluster``, which describes whether the cluster can be scaled after it's created. """ return True @property def scheduler_address(self) -> str: """ Address for the Dask schduler. """ return self._scheduler_address @property def dashboard_link(self) -> str: """ Link to the Dask dashboard. This is customized to be inside of a Saturn project. """ return self._dashboard_link @property def scheduler_info(self) -> Dict[str, Any]: """ Information about the scheduler. Raises a ValueError if the scheduler is in a bad state. """ url = urljoin(self.cluster_url, "scheduler_info") response = requests.get(url, headers=self.settings.headers) if not response.ok: if self._get_pod_status() in ["error", "closed", "stopped"]: for pc in self.periodic_callbacks.values(): pc.stop() raise ValueError("Cluster is not running.") raise ValueError(response.json()["message"]) try: from distributed.objects import SchedulerInfo # pylint: disable=import-outside-toplevel return SchedulerInfo(response.json()) except ImportError: pass return response.json() # pylint: disable=invalid-overridden-method def _start( self, n_workers: Optional[int] = None, worker_size: Optional[str] = None, worker_is_spot: Optional[bool] = None, scheduler_size: Optional[str] = None, nprocs: Optional[int] = None, nthreads: Optional[int] = None, scheduler_service_wait_timeout: int = DEFAULT_WAIT_TIMEOUT_SECONDS, ) -> None: """ Start a cluster that has already been defined for the project. For documentation on this method's parameters, see ``help(SaturnCluster)``. """ url = urljoin(self.settings.url, "api/dask_clusters") url_query = "" if self.settings.is_external: url_query = "?is_external=true" self.cluster_url: Optional[str] = None self._validate_sizes(worker_size, scheduler_size) cluster_config = { "n_workers": n_workers, "worker_size": worker_size, "worker_is_spot": worker_is_spot, "scheduler_size": scheduler_size, "nprocs": nprocs, "nthreads": nthreads, } if self.settings.SATURN_VERSION >= LooseVersion("2021.08.16"): cluster_config["prefectcloudflowrun_id"] = os.environ.get( "PREFECT__CONTEXT__FLOW_RUN_ID" ) # only send kwargs that are explicitly set by user cluster_config = {k: v for k, v in cluster_config.items() if v is not None} expBackoff = ExpBackoff(wait_timeout=scheduler_service_wait_timeout) logged_warnings: Dict[str, bool] = {} while self.cluster_url is None: response = requests.post( url + url_query, data=json.dumps(cluster_config), headers=self.settings.headers, ) if not response.ok: raise ValueError(response.json()["message"]) data = response.json() for warning in data.get("warnings", []): if not logged_warnings.get(warning): logged_warnings[warning] = True log.warning(warning) if data["status"] == "error": raise ValueError(" ".join(data["errors"])) elif data["status"] == "ready": self.dask_cluster_id = data["id"] self.cluster_url = f"{url}/{self.dask_cluster_id}/" log.info("Cluster is ready") break else: log.info(f"Starting cluster. Status: {data["status"]}") if self.cluster_url is None: if not expBackoff.wait(): raise ValueError( "Retry in a few minutes. Check status in Saturn User Interface" ) def register_default_plugin(self): """Register the default SaturnSetup plugin to all workers.""" log.info("Registering default plugins") outputs = {} with Client(self) as client: output = client.register_worker_plugin(SaturnSetup()) outputs.update(output) output_statuses = [v["status"] for v in outputs.values()] if "OK" in output_statuses: log.info("Success!") elif "repeat" in output_statuses: log.info("Success!") elif len(output_statuses) == 0: log.warning("No workers started up.") else: log.warning("Registering default plugins failed. Please check logs for more info.") def _get_info(self) -> Dict[str, Any]: url = urljoin(self.cluster_url, "info") if self.settings.is_external: url += "?is_external=true" response = requests.get(url, headers=self.settings.headers) if not response.ok: raise ValueError(response.json()["message"]) return response.json() def scale(self, n: int) -> None: """ Scale cluster to have ``n`` workers :param n: number of workers to scale to. """ url = urljoin(self.cluster_url, "scale") response = requests.post(url, json.dumps({"n": n}), headers=self.settings.headers) if not response.ok: raise ValueError(response.json()["message"]) def adapt(self, minimum: int, maximum: int) -> None: """Adapt cluster to have between ``minimum`` and ``maximum`` workers""" url = urljoin(self.cluster_url, "adapt") response = requests.post( url, json.dumps({"minimum": minimum, "maximum": maximum}), headers=self.settings.headers, ) if not response.ok: raise ValueError(response.json()["message"]) def close(self) -> None: """ Defines what should be done when closing the cluster. """ url = urljoin(self.cluster_url, "close") response = requests.post(url, headers=self.settings.headers) if not response.ok: raise ValueError(response.json()["message"]) for pc in self.periodic_callbacks.values(): pc.stop() @property def asynchronous(self) -> bool: """ Whether or not the cluster's ``_start`` method is synchronous. ``SaturnCluster`` uses a synchronous ``_start()`` because it has to be called in the class constructor, which is intended to be used interactively in a notebook. """ return False def __enter__(self) -> "SaturnCluster": """ magic method used to allow the use of ``SaturnCluster`` with a context manager. .. code-block:: python with SaturnCluster() as cluster: """ return self def __exit__(self, typ, value, traceback) -> None: """ magic method that defines what should be done when exiting a context manager's context. in other words at the end of this .. code-block:: python with SaturnCluster() as cluster: """ if self.shutdown_on_close: self.close() # pylint: disable=access-member-before-definition def _validate_sizes( self, worker_size: Optional[str] = None, scheduler_size: Optional[str] = None, ): """Validate the options provided""" if self._sizes is None: self._sizes = list_sizes() errors = [] if worker_size is not None: if worker_size not in self._sizes: errors.append( f"Proposed worker_size: {worker_size} is not a valid option. " f"Options are: {self._sizes}." ) if scheduler_size is not None: if scheduler_size not in self._sizes: errors.append( f"Proposed scheduler_size: {scheduler_size} is not a valid option. " f"Options are: {self._sizes}." ) if len(errors) > 0: raise ValueError(" ".join(errors)) @classmethod def from_name(cls, name: str): """Create an instance of this class to represent an existing cluster by name.""" log.warning( "Only one dask cluster can be associated with a particular resource, so " f"user provided name: {name} will not be used." ) return cls() def _options() -> Dict[str, Any]: settings = Settings() url = urljoin(settings.url, "api/dask_clusters/info") response = requests.get(url, headers=settings.headers) if not response.ok: raise ValueError(response.json()["message"]) return response.json()["server_options"] def list_sizes() -> List[str]: """Return a list of valid size options for worker_size and scheduler size.""" return [size["name"] for size in _options()["size"]] def describe_sizes() -> Dict[str, str]: """Return a dict of size options with a description.""" return {size["name"]: size["display"] for size in _options()["size"]}
""" Saturn-specific override of ``dask.distributed.deploy.SpecCluster`` See https://distributed.dask.org/en/latest/_modules/distributed/deploy/spec.html for details on the parent class. """ import os import json import logging import warnings import weakref from distutils.version import LooseVersion from typing import Any, Dict, List, Optional from urllib.parse import urljoin import requests from distributed import Client, SpecCluster from distributed.security import Security from tornado.ioloop import PeriodicCallback from .backoff import ExpBackoff from .external import _security, ExternalConnection # noqa # pylint: disable=unused-import from .plugins import SaturnSetup from .settings import Settings DEFAULT_WAIT_TIMEOUT_SECONDS = 1200 log = logging.getLogger("dask-saturn") if log.level == logging.NOTSET: logging.basicConfig() log.setLevel(logging.INFO) class SaturnCluster(SpecCluster): """ Create a ``SaturnCluster``, an extension of ``distributed.SpecCluster`` specific to Saturn Cloud. :param n_workers: Number of workers to provision for the cluster. :param cluster_url: URL for the "cluster" service running in kubernetes. This component of a ``Dask`` cluster in kubernetes knows how to create pods for workers and the scheduler. :param worker_size: A string with the size to use for each worker. A list of valid sizes and their details can be obtained with ``dask_saturn.describe_sizes()``. If no size is provided, this will default to the size configured for Jupyter in your Saturn Cloud project. :param worker_is_spot: Flag to indicate if workers should be started on Spot Instances nodes. Added in dask-saturn 0.1.0, Saturn 2020.08.28. :param scheduler_size: A string with the size to use for the scheduler. A list of valid sizes and their details can be obtained with ``dask_saturn.describe_sizes()``. If no size is provided, this will default to the size configured for Jupyter in your Saturn Cloud project. :param nprocs: The number of ``dask-worker`` processes run on each host in a distributed cluster. :param nthreads: The number of threads available to each ``dask-worker`` process. :param scheduler_service_wait_timeout: The maximum amout of time, in seconds, that ``SaturnCluster`` will wait for the scheduler to respond before deciding that the scheduler is taking too long. By default, this is set to 1200 (20 minutes). Setting it to a lower value will help you catch problems earlier, but may also lead to false positives if you don't give the cluster enough to time to start up. :param shutdown_on_close: Whether or not the cluster should be automatically destroyed when its calling process is destroyed. Set this parameter to ``True`` if you want your cluster to shutdown when the work is done. By default, this is ``False`` if the cluster is attached to a Jupyter server, deployment, or job. If the cluster is attached to a Prefect Cloud flow run, this option is always set to ``True``. Note: ``autoclose`` is accepted as an alias for now, but will be removed in the future. """ # pylint: disable=unused-argument,super-init-not-called,too-many-instance-attributes _sizes = None _instances = weakref.WeakSet() def __init__( self, *args, n_workers: Optional[int] = None, cluster_url: Optional[str] = None, worker_size: Optional[str] = None, worker_is_spot: Optional[bool] = None, scheduler_size: Optional[str] = None, nprocs: Optional[int] = None, nthreads: Optional[int] = None, scheduler_service_wait_timeout: int = DEFAULT_WAIT_TIMEOUT_SECONDS, shutdown_on_close: bool = False, **kwargs, ): if "external_connection" in kwargs: raise RuntimeError( "Passing external_connection as a key word argument is no longer supported. " "Instead, set the env vars: ``SATURN_TOKEN`` and ``SATURN_BASE_URL`` " "as indicated in the Saturn Cloud UI. If those env vars are set, an external " "connection will be automatically set up." ) if "autoclose" in kwargs: warnings.warn( "``autoclose`` has been deprecated and will be removed in a future version. " "Please use ``shutdown_on_close`` instead.", category=FutureWarning, ) shutdown_on_close = kwargs.pop("autoclose") self.settings = Settings() if self.settings.is_prefect: # defaults to True if related to prefect, else defaults to False shutdown_on_close = True if cluster_url is None: self._start( n_workers=n_workers, worker_size=worker_size, worker_is_spot=worker_is_spot, scheduler_size=scheduler_size, nprocs=nprocs, nthreads=nthreads, scheduler_service_wait_timeout=scheduler_service_wait_timeout, ) else: self.cluster_url = cluster_url if cluster_url.endswith("/") else cluster_url + "/" self.dask_cluster_id = self.cluster_url.rstrip("/").split("/")[-1] info = self._get_info() self._name = self.dask_cluster_id self._dashboard_link = info["dashboard_link"] self._scheduler_address = info["scheduler_address"] self.loop = None self.periodic_callbacks: Dict[str, PeriodicCallback] = {} self.shutdown_on_close = shutdown_on_close self._adaptive = None self._instances.add(self) if self.settings.is_external: self.security = _security(self.settings, self.dask_cluster_id) else: self.security = Security() try: self.register_default_plugin() except Exception as e: # pylint: disable=broad-except log.warning( f"Registering default plugin failed: {e} Hint: you might " "have a different dask-saturn version on your dask cluster." ) def __await__(self): async def _(): pass return _().__await__() @classmethod def reset( cls, n_workers: Optional[int] = None, worker_size: Optional[str] = None, worker_is_spot: Optional[bool] = None, scheduler_size: Optional[str] = None, nprocs: Optional[int] = None, nthreads: Optional[int] = None, ) -> "SaturnCluster": """Return a SaturnCluster Destroy existing Dask cluster attached to the Jupyter Notebook or Custom Deployment and recreate it with the given configuration. For documentation on this method's parameters, see ``help(SaturnCluster)``. """ log.info("Resetting cluster.") settings = Settings() url = urljoin(settings.url, "api/dask_clusters/reset") cluster_config = { "n_workers": n_workers, "worker_size": worker_size, "worker_is_spot": worker_is_spot, "scheduler_size": scheduler_size, "nprocs": nprocs, "nthreads": nthreads, } # only send kwargs that are explicity set by user cluster_config = {k: v for k, v in cluster_config.items() if v is not None} response = requests.post(url, data=json.dumps(cluster_config), headers=settings.headers) if not response.ok: raise ValueError(response.json()["message"]) return cls(**cluster_config) @property def status(self) -> Optional[str]: """ Status of the cluster """ if self.cluster_url is None: return "closed" url = urljoin(self.cluster_url, "status") response = requests.get(url, headers=self.settings.headers) if not response.ok: return self._get_pod_status() return response.json()["status"] def _get_pod_status(self) -> Optional[str]: """ Status of the KubeCluster pod. """ response = requests.get(self.cluster_url[:-1], headers=self.settings.headers) if response.ok: return response.json()["status"] else: return None @property def _supports_scaling(self) -> bool: """ Property required by ``SpecCluster``, which describes whether the cluster can be scaled after it's created. """ return True @property def scheduler_address(self) -> str: """ Address for the Dask schduler. """ return self._scheduler_address @property def dashboard_link(self) -> str: """ Link to the Dask dashboard. This is customized to be inside of a Saturn project. """ return self._dashboard_link @property def scheduler_info(self) -> Dict[str, Any]: """ Information about the scheduler. Raises a ValueError if the scheduler is in a bad state. """ url = urljoin(self.cluster_url, "scheduler_info") response = requests.get(url, headers=self.settings.headers) if not response.ok: if self._get_pod_status() in ["error", "closed", "stopped"]: for pc in self.periodic_callbacks.values(): pc.stop() raise ValueError("Cluster is not running.") raise ValueError(response.json()["message"]) try: from distributed.objects import SchedulerInfo # pylint: disable=import-outside-toplevel return SchedulerInfo(response.json()) except ImportError: pass return response.json() # pylint: disable=invalid-overridden-method def _start( self, n_workers: Optional[int] = None, worker_size: Optional[str] = None, worker_is_spot: Optional[bool] = None, scheduler_size: Optional[str] = None, nprocs: Optional[int] = None, nthreads: Optional[int] = None, scheduler_service_wait_timeout: int = DEFAULT_WAIT_TIMEOUT_SECONDS, ) -> None: """ Start a cluster that has already been defined for the project. For documentation on this method's parameters, see ``help(SaturnCluster)``. """ url = urljoin(self.settings.url, "api/dask_clusters") url_query = "" if self.settings.is_external: url_query = "?is_external=true" self.cluster_url: Optional[str] = None self._validate_sizes(worker_size, scheduler_size) cluster_config = { "n_workers": n_workers, "worker_size": worker_size, "worker_is_spot": worker_is_spot, "scheduler_size": scheduler_size, "nprocs": nprocs, "nthreads": nthreads, } if self.settings.SATURN_VERSION >= LooseVersion("2021.08.16"): cluster_config["prefectcloudflowrun_id"] = os.environ.get( "PREFECT__CONTEXT__FLOW_RUN_ID" ) # only send kwargs that are explicitly set by user cluster_config = {k: v for k, v in cluster_config.items() if v is not None} expBackoff = ExpBackoff(wait_timeout=scheduler_service_wait_timeout) logged_warnings: Dict[str, bool] = {} while self.cluster_url is None: response = requests.post( url + url_query, data=json.dumps(cluster_config), headers=self.settings.headers, ) if not response.ok: raise ValueError(response.json()["message"]) data = response.json() for warning in data.get("warnings", []): if not logged_warnings.get(warning): logged_warnings[warning] = True log.warning(warning) if data["status"] == "error": raise ValueError(" ".join(data["errors"])) elif data["status"] == "ready": self.dask_cluster_id = data["id"] self.cluster_url = f"{url}/{self.dask_cluster_id}/" log.info("Cluster is ready") break else: log.info(f"Starting cluster. Status: {data['status']}") if self.cluster_url is None: if not expBackoff.wait(): raise ValueError( "Retry in a few minutes. Check status in Saturn User Interface" ) def register_default_plugin(self): """Register the default SaturnSetup plugin to all workers.""" log.info("Registering default plugins") outputs = {} with Client(self) as client: output = client.register_worker_plugin(SaturnSetup()) outputs.update(output) output_statuses = [v["status"] for v in outputs.values()] if "OK" in output_statuses: log.info("Success!") elif "repeat" in output_statuses: log.info("Success!") elif len(output_statuses) == 0: log.warning("No workers started up.") else: log.warning("Registering default plugins failed. Please check logs for more info.") def _get_info(self) -> Dict[str, Any]: url = urljoin(self.cluster_url, "info") if self.settings.is_external: url += "?is_external=true" response = requests.get(url, headers=self.settings.headers) if not response.ok: raise ValueError(response.json()["message"]) return response.json() def scale(self, n: int) -> None: """ Scale cluster to have ``n`` workers :param n: number of workers to scale to. """ url = urljoin(self.cluster_url, "scale") response = requests.post(url, json.dumps({"n": n}), headers=self.settings.headers) if not response.ok: raise ValueError(response.json()["message"]) def adapt(self, minimum: int, maximum: int) -> None: """Adapt cluster to have between ``minimum`` and ``maximum`` workers""" url = urljoin(self.cluster_url, "adapt") response = requests.post( url, json.dumps({"minimum": minimum, "maximum": maximum}), headers=self.settings.headers, ) if not response.ok: raise ValueError(response.json()["message"]) def close(self) -> None: """ Defines what should be done when closing the cluster. """ url = urljoin(self.cluster_url, "close") response = requests.post(url, headers=self.settings.headers) if not response.ok: raise ValueError(response.json()["message"]) for pc in self.periodic_callbacks.values(): pc.stop() @property def asynchronous(self) -> bool: """ Whether or not the cluster's ``_start`` method is synchronous. ``SaturnCluster`` uses a synchronous ``_start()`` because it has to be called in the class constructor, which is intended to be used interactively in a notebook. """ return False def __enter__(self) -> "SaturnCluster": """ magic method used to allow the use of ``SaturnCluster`` with a context manager. .. code-block:: python with SaturnCluster() as cluster: """ return self def __exit__(self, typ, value, traceback) -> None: """ magic method that defines what should be done when exiting a context manager's context. in other words at the end of this .. code-block:: python with SaturnCluster() as cluster: """ if self.shutdown_on_close: self.close() # pylint: disable=access-member-before-definition def _validate_sizes( self, worker_size: Optional[str] = None, scheduler_size: Optional[str] = None, ): """Validate the options provided""" if self._sizes is None: self._sizes = list_sizes() errors = [] if worker_size is not None: if worker_size not in self._sizes: errors.append( f"Proposed worker_size: {worker_size} is not a valid option. " f"Options are: {self._sizes}." ) if scheduler_size is not None: if scheduler_size not in self._sizes: errors.append( f"Proposed scheduler_size: {scheduler_size} is not a valid option. " f"Options are: {self._sizes}." ) if len(errors) > 0: raise ValueError(" ".join(errors)) @classmethod def from_name(cls, name: str): """Create an instance of this class to represent an existing cluster by name.""" log.warning( "Only one dask cluster can be associated with a particular resource, so " f"user provided name: {name} will not be used." ) return cls() def _options() -> Dict[str, Any]: settings = Settings() url = urljoin(settings.url, "api/dask_clusters/info") response = requests.get(url, headers=settings.headers) if not response.ok: raise ValueError(response.json()["message"]) return response.json()["server_options"] def list_sizes() -> List[str]: """Return a list of valid size options for worker_size and scheduler size.""" return [size["name"] for size in _options()["size"]] def describe_sizes() -> Dict[str, str]: """Return a dict of size options with a description.""" return {size["name"]: size["display"] for size in _options()["size"]}
"""Blueprint models.""" from __future__ import annotations import asyncio import logging import pathlib import shutil from typing import Any from awesomeversion import AwesomeVersion import voluptuous as vol from voluptuous.humanize import humanize_error from homeassistant import loader from homeassistant.const import ( CONF_DEFAULT, CONF_DOMAIN, CONF_NAME, CONF_PATH, __version__, ) from homeassistant.core import DOMAIN as HA_DOMAIN, HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.util import yaml from .const import ( BLUEPRINT_FOLDER, CONF_BLUEPRINT, CONF_HOMEASSISTANT, CONF_INPUT, CONF_MIN_VERSION, CONF_SOURCE_URL, CONF_USE_BLUEPRINT, DOMAIN, ) from .errors import ( BlueprintException, FailedToLoad, FileAlreadyExists, InvalidBlueprint, InvalidBlueprintInputs, MissingInput, ) from .schemas import BLUEPRINT_INSTANCE_FIELDS, BLUEPRINT_SCHEMA class Blueprint: """Blueprint of a configuration structure.""" def __init__( self, data: dict, *, path: str | None = None, expected_domain: str | None = None, ) -> None: """Initialize a blueprint.""" try: data = self.data = BLUEPRINT_SCHEMA(data) except vol.Invalid as err: raise InvalidBlueprint(expected_domain, path, data, err) from err # In future, we will treat this as "incorrect" and allow to recover from this data_domain = data[CONF_BLUEPRINT][CONF_DOMAIN] if expected_domain is not None and data_domain != expected_domain: raise InvalidBlueprint( expected_domain, path or self.name, data, f"Found incorrect blueprint type {data_domain}, expected {expected_domain}", ) self.domain = data_domain missing = yaml.extract_inputs(data) - set(data[CONF_BLUEPRINT][CONF_INPUT]) if missing: raise InvalidBlueprint( data_domain, path or self.name, data, f"Missing input definition for {", ".join(missing)}", ) @property def name(self) -> str: """Return blueprint name.""" return self.data[CONF_BLUEPRINT][CONF_NAME] @property def inputs(self) -> dict: """Return blueprint inputs.""" return self.data[CONF_BLUEPRINT][CONF_INPUT] @property def metadata(self) -> dict: """Return blueprint metadata.""" return self.data[CONF_BLUEPRINT] def update_metadata(self, *, source_url: str | None = None) -> None: """Update metadata.""" if source_url is not None: self.data[CONF_BLUEPRINT][CONF_SOURCE_URL] = source_url def yaml(self) -> str: """Dump blueprint as YAML.""" return yaml.dump(self.data) @callback def validate(self) -> list[str] | None: """Test if the Home Assistant installation supports this blueprint. Return list of errors if not valid. """ errors = [] metadata = self.metadata min_version = metadata.get(CONF_HOMEASSISTANT, {}).get(CONF_MIN_VERSION) if min_version is not None and AwesomeVersion(__version__) < AwesomeVersion( min_version ): errors.append(f"Requires at least Home Assistant {min_version}") return errors or None class BlueprintInputs: """Inputs for a blueprint.""" def __init__( self, blueprint: Blueprint, config_with_inputs: dict[str, Any] ) -> None: """Instantiate a blueprint inputs object.""" self.blueprint = blueprint self.config_with_inputs = config_with_inputs @property def inputs(self): """Return the inputs.""" return self.config_with_inputs[CONF_USE_BLUEPRINT][CONF_INPUT] @property def inputs_with_default(self): """Return the inputs and fallback to defaults.""" no_input = set(self.blueprint.inputs) - set(self.inputs) inputs_with_default = dict(self.inputs) for inp in no_input: blueprint_input = self.blueprint.inputs[inp] if isinstance(blueprint_input, dict) and CONF_DEFAULT in blueprint_input: inputs_with_default[inp] = blueprint_input[CONF_DEFAULT] return inputs_with_default def validate(self) -> None: """Validate the inputs.""" missing = set(self.blueprint.inputs) - set(self.inputs_with_default) if missing: raise MissingInput(self.blueprint.domain, self.blueprint.name, missing) # In future we can see if entities are correct domain, areas exist etc # using the new selector helper. @callback def async_substitute(self) -> dict: """Get the blueprint value with the inputs substituted.""" processed = yaml.substitute(self.blueprint.data, self.inputs_with_default) combined = {**processed, **self.config_with_inputs} # From config_with_inputs combined.pop(CONF_USE_BLUEPRINT) # From blueprint combined.pop(CONF_BLUEPRINT) return combined class DomainBlueprints: """Blueprints for a specific domain.""" def __init__( self, hass: HomeAssistant, domain: str, logger: logging.Logger, ) -> None: """Initialize a domain blueprints instance.""" self.hass = hass self.domain = domain self.logger = logger self._blueprints = {} self._load_lock = asyncio.Lock() hass.data.setdefault(DOMAIN, {})[domain] = self @property def blueprint_folder(self) -> pathlib.Path: """Return the blueprint folder.""" return pathlib.Path(self.hass.config.path(BLUEPRINT_FOLDER, self.domain)) @callback def async_reset_cache(self) -> None: """Reset the blueprint cache.""" self._blueprints = {} def _load_blueprint(self, blueprint_path) -> Blueprint: """Load a blueprint.""" try: blueprint_data = yaml.load_yaml(self.blueprint_folder / blueprint_path) except FileNotFoundError as err: raise FailedToLoad( self.domain, blueprint_path, FileNotFoundError(f"Unable to find {blueprint_path}"), ) from err except HomeAssistantError as err: raise FailedToLoad(self.domain, blueprint_path, err) from err return Blueprint( blueprint_data, expected_domain=self.domain, path=blueprint_path ) def _load_blueprints(self) -> dict[str, Blueprint | BlueprintException]: """Load all the blueprints.""" blueprint_folder = pathlib.Path( self.hass.config.path(BLUEPRINT_FOLDER, self.domain) ) results = {} for blueprint_path in blueprint_folder.glob("**/*.yaml"): blueprint_path = str(blueprint_path.relative_to(blueprint_folder)) if self._blueprints.get(blueprint_path) is None: try: self._blueprints[blueprint_path] = self._load_blueprint( blueprint_path ) except BlueprintException as err: self._blueprints[blueprint_path] = None results[blueprint_path] = err continue results[blueprint_path] = self._blueprints[blueprint_path] return results async def async_get_blueprints( self, ) -> dict[str, Blueprint | BlueprintException]: """Get all the blueprints.""" async with self._load_lock: return await self.hass.async_add_executor_job(self._load_blueprints) async def async_get_blueprint(self, blueprint_path: str) -> Blueprint: """Get a blueprint.""" def load_from_cache(): """Load blueprint from cache.""" blueprint = self._blueprints[blueprint_path] if blueprint is None: raise FailedToLoad( self.domain, blueprint_path, FileNotFoundError(f"Unable to find {blueprint_path}"), ) return blueprint if blueprint_path in self._blueprints: return load_from_cache() async with self._load_lock: # Check it again if blueprint_path in self._blueprints: return load_from_cache() try: blueprint = await self.hass.async_add_executor_job( self._load_blueprint, blueprint_path ) except Exception: self._blueprints[blueprint_path] = None raise self._blueprints[blueprint_path] = blueprint return blueprint async def async_inputs_from_config( self, config_with_blueprint: dict ) -> BlueprintInputs: """Process a blueprint config.""" try: config_with_blueprint = BLUEPRINT_INSTANCE_FIELDS(config_with_blueprint) except vol.Invalid as err: raise InvalidBlueprintInputs( self.domain, humanize_error(config_with_blueprint, err) ) from err bp_conf = config_with_blueprint[CONF_USE_BLUEPRINT] blueprint = await self.async_get_blueprint(bp_conf[CONF_PATH]) inputs = BlueprintInputs(blueprint, config_with_blueprint) inputs.validate() return inputs async def async_remove_blueprint(self, blueprint_path: str) -> None: """Remove a blueprint file.""" path = self.blueprint_folder / blueprint_path await self.hass.async_add_executor_job(path.unlink) self._blueprints[blueprint_path] = None def _create_file(self, blueprint: Blueprint, blueprint_path: str) -> None: """Create blueprint file.""" path = pathlib.Path( self.hass.config.path(BLUEPRINT_FOLDER, self.domain, blueprint_path) ) if path.exists(): raise FileAlreadyExists(self.domain, blueprint_path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(blueprint.yaml()) async def async_add_blueprint( self, blueprint: Blueprint, blueprint_path: str ) -> None: """Add a blueprint.""" if not blueprint_path.endswith(".yaml"): blueprint_path = f"{blueprint_path}.yaml" await self.hass.async_add_executor_job( self._create_file, blueprint, blueprint_path ) self._blueprints[blueprint_path] = blueprint async def async_populate(self) -> None: """Create folder if it doesn't exist and populate with examples.""" integration = await loader.async_get_integration(self.hass, self.domain) def populate(): if self.blueprint_folder.exists(): return shutil.copytree( integration.file_path / BLUEPRINT_FOLDER, self.blueprint_folder / HA_DOMAIN, ) await self.hass.async_add_executor_job(populate)
"""Blueprint models.""" from __future__ import annotations import asyncio import logging import pathlib import shutil from typing import Any from awesomeversion import AwesomeVersion import voluptuous as vol from voluptuous.humanize import humanize_error from homeassistant import loader from homeassistant.const import ( CONF_DEFAULT, CONF_DOMAIN, CONF_NAME, CONF_PATH, __version__, ) from homeassistant.core import DOMAIN as HA_DOMAIN, HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.util import yaml from .const import ( BLUEPRINT_FOLDER, CONF_BLUEPRINT, CONF_HOMEASSISTANT, CONF_INPUT, CONF_MIN_VERSION, CONF_SOURCE_URL, CONF_USE_BLUEPRINT, DOMAIN, ) from .errors import ( BlueprintException, FailedToLoad, FileAlreadyExists, InvalidBlueprint, InvalidBlueprintInputs, MissingInput, ) from .schemas import BLUEPRINT_INSTANCE_FIELDS, BLUEPRINT_SCHEMA class Blueprint: """Blueprint of a configuration structure.""" def __init__( self, data: dict, *, path: str | None = None, expected_domain: str | None = None, ) -> None: """Initialize a blueprint.""" try: data = self.data = BLUEPRINT_SCHEMA(data) except vol.Invalid as err: raise InvalidBlueprint(expected_domain, path, data, err) from err # In future, we will treat this as "incorrect" and allow to recover from this data_domain = data[CONF_BLUEPRINT][CONF_DOMAIN] if expected_domain is not None and data_domain != expected_domain: raise InvalidBlueprint( expected_domain, path or self.name, data, f"Found incorrect blueprint type {data_domain}, expected {expected_domain}", ) self.domain = data_domain missing = yaml.extract_inputs(data) - set(data[CONF_BLUEPRINT][CONF_INPUT]) if missing: raise InvalidBlueprint( data_domain, path or self.name, data, f"Missing input definition for {', '.join(missing)}", ) @property def name(self) -> str: """Return blueprint name.""" return self.data[CONF_BLUEPRINT][CONF_NAME] @property def inputs(self) -> dict: """Return blueprint inputs.""" return self.data[CONF_BLUEPRINT][CONF_INPUT] @property def metadata(self) -> dict: """Return blueprint metadata.""" return self.data[CONF_BLUEPRINT] def update_metadata(self, *, source_url: str | None = None) -> None: """Update metadata.""" if source_url is not None: self.data[CONF_BLUEPRINT][CONF_SOURCE_URL] = source_url def yaml(self) -> str: """Dump blueprint as YAML.""" return yaml.dump(self.data) @callback def validate(self) -> list[str] | None: """Test if the Home Assistant installation supports this blueprint. Return list of errors if not valid. """ errors = [] metadata = self.metadata min_version = metadata.get(CONF_HOMEASSISTANT, {}).get(CONF_MIN_VERSION) if min_version is not None and AwesomeVersion(__version__) < AwesomeVersion( min_version ): errors.append(f"Requires at least Home Assistant {min_version}") return errors or None class BlueprintInputs: """Inputs for a blueprint.""" def __init__( self, blueprint: Blueprint, config_with_inputs: dict[str, Any] ) -> None: """Instantiate a blueprint inputs object.""" self.blueprint = blueprint self.config_with_inputs = config_with_inputs @property def inputs(self): """Return the inputs.""" return self.config_with_inputs[CONF_USE_BLUEPRINT][CONF_INPUT] @property def inputs_with_default(self): """Return the inputs and fallback to defaults.""" no_input = set(self.blueprint.inputs) - set(self.inputs) inputs_with_default = dict(self.inputs) for inp in no_input: blueprint_input = self.blueprint.inputs[inp] if isinstance(blueprint_input, dict) and CONF_DEFAULT in blueprint_input: inputs_with_default[inp] = blueprint_input[CONF_DEFAULT] return inputs_with_default def validate(self) -> None: """Validate the inputs.""" missing = set(self.blueprint.inputs) - set(self.inputs_with_default) if missing: raise MissingInput(self.blueprint.domain, self.blueprint.name, missing) # In future we can see if entities are correct domain, areas exist etc # using the new selector helper. @callback def async_substitute(self) -> dict: """Get the blueprint value with the inputs substituted.""" processed = yaml.substitute(self.blueprint.data, self.inputs_with_default) combined = {**processed, **self.config_with_inputs} # From config_with_inputs combined.pop(CONF_USE_BLUEPRINT) # From blueprint combined.pop(CONF_BLUEPRINT) return combined class DomainBlueprints: """Blueprints for a specific domain.""" def __init__( self, hass: HomeAssistant, domain: str, logger: logging.Logger, ) -> None: """Initialize a domain blueprints instance.""" self.hass = hass self.domain = domain self.logger = logger self._blueprints = {} self._load_lock = asyncio.Lock() hass.data.setdefault(DOMAIN, {})[domain] = self @property def blueprint_folder(self) -> pathlib.Path: """Return the blueprint folder.""" return pathlib.Path(self.hass.config.path(BLUEPRINT_FOLDER, self.domain)) @callback def async_reset_cache(self) -> None: """Reset the blueprint cache.""" self._blueprints = {} def _load_blueprint(self, blueprint_path) -> Blueprint: """Load a blueprint.""" try: blueprint_data = yaml.load_yaml(self.blueprint_folder / blueprint_path) except FileNotFoundError as err: raise FailedToLoad( self.domain, blueprint_path, FileNotFoundError(f"Unable to find {blueprint_path}"), ) from err except HomeAssistantError as err: raise FailedToLoad(self.domain, blueprint_path, err) from err return Blueprint( blueprint_data, expected_domain=self.domain, path=blueprint_path ) def _load_blueprints(self) -> dict[str, Blueprint | BlueprintException]: """Load all the blueprints.""" blueprint_folder = pathlib.Path( self.hass.config.path(BLUEPRINT_FOLDER, self.domain) ) results = {} for blueprint_path in blueprint_folder.glob("**/*.yaml"): blueprint_path = str(blueprint_path.relative_to(blueprint_folder)) if self._blueprints.get(blueprint_path) is None: try: self._blueprints[blueprint_path] = self._load_blueprint( blueprint_path ) except BlueprintException as err: self._blueprints[blueprint_path] = None results[blueprint_path] = err continue results[blueprint_path] = self._blueprints[blueprint_path] return results async def async_get_blueprints( self, ) -> dict[str, Blueprint | BlueprintException]: """Get all the blueprints.""" async with self._load_lock: return await self.hass.async_add_executor_job(self._load_blueprints) async def async_get_blueprint(self, blueprint_path: str) -> Blueprint: """Get a blueprint.""" def load_from_cache(): """Load blueprint from cache.""" blueprint = self._blueprints[blueprint_path] if blueprint is None: raise FailedToLoad( self.domain, blueprint_path, FileNotFoundError(f"Unable to find {blueprint_path}"), ) return blueprint if blueprint_path in self._blueprints: return load_from_cache() async with self._load_lock: # Check it again if blueprint_path in self._blueprints: return load_from_cache() try: blueprint = await self.hass.async_add_executor_job( self._load_blueprint, blueprint_path ) except Exception: self._blueprints[blueprint_path] = None raise self._blueprints[blueprint_path] = blueprint return blueprint async def async_inputs_from_config( self, config_with_blueprint: dict ) -> BlueprintInputs: """Process a blueprint config.""" try: config_with_blueprint = BLUEPRINT_INSTANCE_FIELDS(config_with_blueprint) except vol.Invalid as err: raise InvalidBlueprintInputs( self.domain, humanize_error(config_with_blueprint, err) ) from err bp_conf = config_with_blueprint[CONF_USE_BLUEPRINT] blueprint = await self.async_get_blueprint(bp_conf[CONF_PATH]) inputs = BlueprintInputs(blueprint, config_with_blueprint) inputs.validate() return inputs async def async_remove_blueprint(self, blueprint_path: str) -> None: """Remove a blueprint file.""" path = self.blueprint_folder / blueprint_path await self.hass.async_add_executor_job(path.unlink) self._blueprints[blueprint_path] = None def _create_file(self, blueprint: Blueprint, blueprint_path: str) -> None: """Create blueprint file.""" path = pathlib.Path( self.hass.config.path(BLUEPRINT_FOLDER, self.domain, blueprint_path) ) if path.exists(): raise FileAlreadyExists(self.domain, blueprint_path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(blueprint.yaml()) async def async_add_blueprint( self, blueprint: Blueprint, blueprint_path: str ) -> None: """Add a blueprint.""" if not blueprint_path.endswith(".yaml"): blueprint_path = f"{blueprint_path}.yaml" await self.hass.async_add_executor_job( self._create_file, blueprint, blueprint_path ) self._blueprints[blueprint_path] = blueprint async def async_populate(self) -> None: """Create folder if it doesn't exist and populate with examples.""" integration = await loader.async_get_integration(self.hass, self.domain) def populate(): if self.blueprint_folder.exists(): return shutil.copytree( integration.file_path / BLUEPRINT_FOLDER, self.blueprint_folder / HA_DOMAIN, ) await self.hass.async_add_executor_job(populate)
#!/usr/local/bin/env python #============================================================================================= # MODULE DOCSTRING #============================================================================================= """ Test custom integrators. """ #============================================================================================= # GLOBAL IMPORTS #============================================================================================= import copy import inspect import pymbar from unittest import TestCase import numpy as np try: import openmm from openmm import unit except ImportError: # OpenMM < 7.6 from simtk import unit from simtk import openmm from openmmtools import integrators, testsystems from openmmtools.integrators import (ThermostatedIntegrator, AlchemicalNonequilibriumLangevinIntegrator, GHMCIntegrator, NoseHooverChainVelocityVerletIntegrator) #============================================================================================= # CONSTANTS #============================================================================================= kB = unit.BOLTZMANN_CONSTANT_kB * unit.AVOGADRO_CONSTANT_NA #============================================================================================= # UTILITY SUBROUTINES #============================================================================================= def get_all_custom_integrators(only_thermostated=False): """Return all CustomIntegrators in integrators. Parameters ---------- only_thermostated : bool If True, only the CustomIntegrators inheriting from ThermostatedIntegrator are returned. Returns ------- custom_integrators : list of tuples A list of tuples ('IntegratorName', IntegratorClass) """ predicate = lambda x: (inspect.isclass(x) and issubclass(x, openmm.CustomIntegrator) and x != integrators.ThermostatedIntegrator) if only_thermostated: old_predicate = predicate # Avoid infinite recursion. predicate = lambda x: old_predicate(x) and issubclass(x, integrators.ThermostatedIntegrator) custom_integrators = inspect.getmembers(integrators, predicate=predicate) return custom_integrators def check_stability(integrator, test, platform=None, nsteps=100, temperature=300.0*unit.kelvin): """ Check that the simulation does not explode over a number integration steps. Parameters ---------- integrator : openmm.Integrator The integrator to test. test : testsystem The testsystem to test. """ kT = kB * temperature # Create Context and initialize positions. if platform: context = openmm.Context(test.system, integrator, platform) else: context = openmm.Context(test.system, integrator) context.setPositions(test.positions) context.setVelocitiesToTemperature(temperature) # TODO: Make deterministic. # Set integrator temperature if hasattr(integrator, 'setTemperature'): integrator.setTemperature(temperature) # Take a number of steps. integrator.step(nsteps) # Check that simulation has not exploded. state = context.getState(getEnergy=True) potential = state.getPotentialEnergy() / kT if np.isnan(potential): raise Exception("Potential energy for integrator %s became NaN." % integrator.__doc__) del context def check_integrator_temperature(integrator, temperature, has_changed): """Check integrator temperature has has_kT_changed variables.""" kT = (temperature * integrators.kB) temperature = temperature / unit.kelvin assert np.isclose(integrator.getTemperature() / unit.kelvin, temperature) assert np.isclose(integrator.getGlobalVariableByName('kT'), kT.value_in_unit_system(unit.md_unit_system)) assert np.isclose(integrator.kT.value_in_unit_system(unit.md_unit_system), kT.value_in_unit_system(unit.md_unit_system)) has_kT_changed = False if 'has_kT_changed' in integrator.global_variable_names: has_kT_changed = integrator.getGlobalVariableByName('has_kT_changed') if has_kT_changed is not False: assert has_kT_changed == has_changed def check_integrator_temperature_getter_setter(integrator): """Check that temperature setter/getter works correctly. Parameters ---------- integrator : ThermostatedIntegrator An integrator just created and already bound to a context. """ # The variable has_kT_changed is initialized correctly. temperature = integrator.getTemperature() check_integrator_temperature(integrator, temperature, 1) # At the first step step, the temperature-dependent constants are computed. integrator.step(1) check_integrator_temperature(integrator, temperature, 0) # Setting temperature update kT and has_kT_changed. temperature += 100*unit.kelvin integrator.setTemperature(temperature) check_integrator_temperature(integrator, temperature, 1) # At the next step, temperature-dependent constants are recomputed. integrator.step(1) check_integrator_temperature(integrator, temperature, 0) #============================================================================================= # TESTS #============================================================================================= def test_stabilities(): """ Test integrators for stability over a short number of steps. """ ts = testsystems # shortcut test_cases = {'harmonic oscillator': ts.HarmonicOscillator(), 'alanine dipeptide in implicit solvent': ts.AlanineDipeptideImplicit()} custom_integrators = get_all_custom_integrators() for test_name, test in test_cases.items(): for integrator_name, integrator_class in custom_integrators: integrator = integrator_class() # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. integrator.__doc__ = integrator_name check_stability.description = ("Testing {} for stability over a short number of " "integration steps of a {}.").format(integrator_name, test_name) yield check_stability, integrator, test def test_integrator_decorators(): integrator = integrators.HMCIntegrator(timestep=0.05 * unit.femtoseconds) testsystem = testsystems.IdealGas() nsteps = 25 context = openmm.Context(testsystem.system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(300 * unit.kelvin) integrator.step(nsteps) assert integrator.n_accept == nsteps assert integrator.n_trials == nsteps assert integrator.acceptance_rate == 1.0 def test_nose_hoover_integrator(): """ Test Nose-Hoover thermostat by ensuring that a short run conserves the system and bath energy to a reasonable tolerance. Also test that the target temperature is rougly matched (+- 10 K). """ temperature = 298*unit.kelvin testsystem = testsystems.WaterBox() num_dof = 3*testsystem.system.getNumParticles() - testsystem.system.getNumConstraints() integrator = NoseHooverChainVelocityVerletIntegrator(testsystem.system, temperature) # Create Context and initialize positions. context = openmm.Context(testsystem.system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) integrator.step(200) # Short equilibration energies = [] temperatures = [] for n in range(100): integrator.step(1) state = context.getState(getEnergy=True) # temperature kinE = state.getKineticEnergy() temp = (2.0 * kinE / (num_dof * unit.MOLAR_GAS_CONSTANT_R)).value_in_unit(unit.kelvin) temperatures.append(temp) # total energy KE = kinE.value_in_unit(unit.kilojoules_per_mole) PE = state.getPotentialEnergy().value_in_unit(unit.kilojoules_per_mole) bathKE = integrator.getGlobalVariableByName('bathKE') bathPE = integrator.getGlobalVariableByName('bathPE') conserved = KE + PE + bathKE + bathPE energies.append(conserved) # Compute maximum deviation from the mean for conserved energies meanenergies = np.mean(energies) maxdeviation = np.amax(np.abs(energies - meanenergies)/meanenergies) assert maxdeviation < 1e-3 # Coarse check for target temperature mean_temperature = np.mean(temperatures) assert abs(mean_temperature - temperature.value_in_unit(unit.kelvin)) < 10.0, mean_temperature def test_pretty_formatting(): """ Test pretty-printing and pretty-formatting of integrators. """ custom_integrators = get_all_custom_integrators() for integrator_name, integrator_class in custom_integrators: integrator = integrator_class() # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. if hasattr(integrator, 'pretty_format'): # Check formatting as text text = integrator.pretty_format() # Check formatting as text with highlighted steps text = integrator.pretty_format(step_types_to_highlight=[5]) # Check list format lines = integrator.pretty_format(as_list=True) msg = "integrator.pretty_format(as_list=True) has %d lines while integrator has %d steps" % (len(lines), integrator.getNumComputations()) assert len(lines) == integrator.getNumComputations(), msg def test_update_context_state_calls(): """ Ensure that all integrators only call addUpdateContextState() once. """ custom_integrators = get_all_custom_integrators() for integrator_name, integrator_class in custom_integrators: integrator = integrator_class() # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. num_force_update = 0 for i in range(integrator.getNumComputations()): step_type, target, expr = integrator.getComputationStep(i) if step_type == 5: num_force_update += 1 msg = "Integrator '%s' has %d calls to addUpdateContextState(), while there should be only one." % (integrator_name, num_force_update) if hasattr(integrator, 'pretty_format'): msg += '\n' + integrator.pretty_format(step_types_to_highlight=[5]) assert num_force_update == 1, msg def test_vvvr_shadow_work_accumulation(): """When `measure_shadow_work==True`, assert that global `shadow_work` is initialized to zero and reaches a nonzero value after integrating a few dozen steps.""" # test `measure_shadow_work=True` --> accumulation of a nonzero value in global `shadow_work` testsystem = testsystems.HarmonicOscillator() system, topology = testsystem.system, testsystem.topology temperature = 298.0 * unit.kelvin integrator = integrators.VVVRIntegrator(temperature, measure_shadow_work=True) context = openmm.Context(system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) assert(integrator.get_shadow_work(dimensionless=True) == 0), "Shadow work should initially be zero." assert(integrator.get_shadow_work() / unit.kilojoules_per_mole == 0), "integrator.get_shadow_work() should have units of energy." assert(integrator.shadow_work / unit.kilojoules_per_mole == 0), "integrator.shadow_work should have units of energy." integrator.step(25) assert(integrator.get_shadow_work(dimensionless=True) != 0), "integrator.get_shadow_work() should be nonzero after dynamics" integrator = integrators.VVVRIntegrator(temperature) context = openmm.Context(system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) integrator.step(25) del context, integrator def test_baoab_heat_accumulation(): """When `measure_heat==True`, assert that global `heat` is initialized to zero and reaches a nonzero value after integrating a few dozen steps.""" # test `measure_shadow_work=True` --> accumulation of a nonzero value in global `shadow_work` testsystem = testsystems.HarmonicOscillator() system, topology = testsystem.system, testsystem.topology temperature = 298.0 * unit.kelvin integrator = integrators.BAOABIntegrator(temperature, measure_heat=True) context = openmm.Context(system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) assert(integrator.get_heat(dimensionless=True) == 0), "Heat should initially be zero." assert(integrator.get_heat() / unit.kilojoules_per_mole == 0), "integrator.get_heat() should have units of energy." assert(integrator.heat / unit.kilojoules_per_mole == 0), "integrator.heat should have units of energy." integrator.step(25) assert(integrator.get_heat(dimensionless=True) != 0), "integrator.get_heat() should be nonzero after dynamics" integrator = integrators.VVVRIntegrator(temperature) context = openmm.Context(system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) integrator.step(25) del context, integrator def test_external_protocol_work_accumulation(): """When `measure_protocol_work==True`, assert that global `protocol_work` is initialized to zero and reaches a zero value after integrating a few dozen steps without perturbation. By default (`measure_protocol_work=False`), assert that there is no global name for `protocol_work`.""" testsystem = testsystems.HarmonicOscillator() system, topology = testsystem.system, testsystem.topology temperature = 298.0 * unit.kelvin integrator = integrators.ExternalPerturbationLangevinIntegrator(splitting="O V R V O", temperature=temperature) context = openmm.Context(system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) # Check that initial step accumulates no protocol work assert(integrator.get_protocol_work(dimensionless=True) == 0), "Protocol work should be 0 initially" assert(integrator.get_protocol_work() / unit.kilojoules_per_mole == 0), "Protocol work should have units of energy" integrator.step(1) assert(integrator.get_protocol_work(dimensionless=True) == 0), "There should be no protocol work." # Check that a single step accumulates protocol work pe_1 = context.getState(getEnergy=True).getPotentialEnergy() perturbed_K=99.0 * unit.kilocalories_per_mole / unit.angstroms**2 context.setParameter('testsystems_HarmonicOscillator_K', perturbed_K) pe_2 = context.getState(getEnergy=True).getPotentialEnergy() integrator.step(1) assert (integrator.get_protocol_work(dimensionless=True) != 0), "There should be protocol work after perturbing." assert (integrator.protocol_work == (pe_2 - pe_1)), "The potential energy difference should be equal to protocol work." del context, integrator integrator = integrators.VVVRIntegrator(temperature) context = openmm.Context(system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) integrator.step(25) del context, integrator class TestExternalPerturbationLangevinIntegrator(TestCase): def create_system(self, testsystem, parameter_name, parameter_initial, temperature = 298.0 * unit.kelvin, platform_name='Reference'): """ Create an example system to be used by other tests """ system, topology = testsystem.system, testsystem.topology integrator = integrators.ExternalPerturbationLangevinIntegrator(splitting="O V R V O", temperature=temperature) # Create the context platform = openmm.Platform.getPlatformByName(platform_name) if platform_name in ['CPU', 'CUDA']: try: platform.setPropertyDefaultValue('DeterministicForces', 'true') except Exception as e: mm_min_version = '7.2.0' if platform_name == 'CPU' and openmm.version.short_version < mm_min_version: print("Deterministic CPU forces not present in versions of OpenMM prior to {}".format(mm_min_version)) else: raise e context = openmm.Context(system, integrator, platform) context.setParameter(parameter_name, parameter_initial) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) return context, integrator def run_ncmc(self, context, integrator, temperature, nsteps, parameter_name, parameter_initial, parameter_final): """ A simple example of NCMC to be used with unit tests. The protocol work should be reset each time this command is called. Returns ------- external_protocol_work: float the protocol work calculated with context.getState() integrator_protocol_work: float the protocol work calculated inside the integrator. """ kT = kB * temperature external_protocol_work = 0.0 integrator.step(1) for step in range(nsteps): lambda_value = float(step + 1) / float(nsteps) parameter_value = parameter_initial * (1 - lambda_value) + parameter_final * lambda_value initial_energy = context.getState(getEnergy=True).getPotentialEnergy() context.setParameter(parameter_name, parameter_value) final_energy = context.getState(getEnergy=True).getPotentialEnergy() external_protocol_work += (final_energy - initial_energy) / kT integrator.step(1) integrator_protocol_work = integrator.get_protocol_work(dimensionless=True) return external_protocol_work, integrator_protocol_work def test_initial_protocol_work(self): """ Ensure the protocol work is initially zero and remains zero after a number of integrator steps. """ try: from openmm import app except ImportError: # OpenMM < 7.6 from simtk.openmm import app parameter_name = 'lambda_electrostatics' temperature = 298.0 * unit.kelvin parameter_initial = 1.0 platform_name = 'CPU' nonbonded_method = 'CutoffPeriodic' # Create the system testsystem = testsystems.AlchemicalWaterBox(nonbondedMethod=getattr(app, nonbonded_method)) testsystem.system.addForce(openmm.MonteCarloBarostat(1 * unit.atmospheres, temperature, 2)) context, integrator = self.create_system(testsystem, parameter_name, parameter_initial, temperature, platform_name) assert (integrator.get_protocol_work(dimensionless=True) == 0) integrator.step(5) assert np.allclose(integrator.get_protocol_work(dimensionless=True), 0) def test_reset_protocol_work(self): """ Make sure the protocol work that is accumulated internally by the langevin integrator matches the protocol is correctly reset with the reset_protocol_work() command. """ try: from openmm import app except ImportError: # OpenMM < 7.6 from simtk.openmm import app parameter_name = 'lambda_electrostatics' temperature = 298.0 * unit.kelvin parameter_initial = 1.0 parameter_final = 0.0 platform_name = 'CPU' nonbonded_method = 'CutoffPeriodic' # Creating the test system with a high frequency barostat. testsystem = testsystems.AlchemicalAlanineDipeptide(nonbondedMethod=getattr(app, nonbonded_method)) context, integrator = self.create_system(testsystem, parameter_name, parameter_initial, temperature, platform_name) # Number of NCMC steps nsteps = 20 niterations = 3 # Running several rounds of configuration updates and NCMC for i in range(niterations): integrator.step(5) # Reseting the protocol work inside the integrator integrator.reset_protocol_work() integrator.reset() external_protocol_work, integrator_protocol_work = self.run_ncmc(context, integrator, temperature, nsteps, parameter_name, parameter_initial, parameter_final) assert abs(external_protocol_work - integrator_protocol_work) < 1.E-5 def test_ncmc_update_parameters_in_context(self): """ Testing that the protocol work is correctly calculated in cases when the parameters are updated using context.updateParametersInContext() and the integrator is a compound integrator. The NCMC scheme tested below is based on the one used by the saltswap and protons code-bases. """ try: from openmm import app except ImportError: # OpenMM < 7.6 from simtk.openmm import app from openmmtools.constants import kB size = 20.0 temperature = 298.0 * unit.kelvin kT = kB * temperature nonbonded_method = 'CutoffPeriodic' platform_name = 'CPU' timestep = 1. * unit.femtoseconds collision_rate = 90. / unit.picoseconds wbox = testsystems.WaterBox(box_edge=size*unit.angstrom, cutoff=9.*unit.angstrom, nonbondedMethod=getattr(app, nonbonded_method)) integrator = integrators.ExternalPerturbationLangevinIntegrator(splitting="V R O R V", temperature=temperature, timestep=timestep, collision_rate=collision_rate) # Create context platform = openmm.Platform.getPlatformByName(platform_name) context = openmm.Context(wbox.system, integrator, platform) context.setPositions(wbox.positions) context.setPositions(wbox.positions) context.setVelocitiesToTemperature(temperature) def switchoff(force, context, frac=0.9): force.setParticleParameters(0, charge=-0.834 * frac, sigma=0.3150752406575124*frac, epsilon=0.635968 * frac) force.setParticleParameters(1, charge=0.417 * frac, sigma=0, epsilon=1 * frac) force.setParticleParameters(2, charge=0.417 * frac, sigma=0, epsilon=1 * frac) force.updateParametersInContext(context) def switchon(force, context): force.setParticleParameters(0, charge=-0.834, sigma=0.3150752406575124, epsilon=0.635968) force.setParticleParameters(1, charge=0.417, sigma=0, epsilon=1) force.setParticleParameters(2, charge=0.417, sigma=0, epsilon=1) force.updateParametersInContext(context) force = wbox.system.getForce(2) # Non-bonded force. # Number of NCMC steps nsteps = 20 niterations = 3 for i in range(niterations): external_protocol_work = 0.0 integrator.reset_protocol_work() integrator.step(1) for step in range(nsteps): fraction = float(step + 1) / float(nsteps) initial_energy = context.getState(getEnergy=True).getPotentialEnergy() switchoff(force, context, frac=fraction) final_energy = context.getState(getEnergy=True).getPotentialEnergy() external_protocol_work += (final_energy - initial_energy) / kT integrator.step(1) integrator_protocol_work = integrator.get_protocol_work(dimensionless=True) assert abs(external_protocol_work - integrator_protocol_work) < 1.E-5 # Return to unperturbed state switchon(force, context) def test_protocol_work_accumulation_harmonic_oscillator(self): """Testing protocol work accumulation for ExternalPerturbationLangevinIntegrator with HarmonicOscillator """ testsystem = testsystems.HarmonicOscillator() parameter_name = 'testsystems_HarmonicOscillator_x0' parameter_initial = 0.0 * unit.angstroms parameter_final = 10.0 * unit.angstroms for platform_name in ['Reference', 'CPU']: self.compare_external_protocol_work_accumulation(testsystem, parameter_name, parameter_initial, parameter_final, platform_name=platform_name) def test_protocol_work_accumulation_waterbox(self): """Testing protocol work accumulation for ExternalPerturbationLangevinIntegrator with AlchemicalWaterBox """ try: from openmm import app except ImportError: # OpenMM < 7.6 from simtk.openmm import app parameter_name = 'lambda_electrostatics' parameter_initial = 1.0 parameter_final = 0.0 platform_names = [ openmm.Platform.getPlatform(index).getName() for index in range(openmm.Platform.getNumPlatforms()) ] for nonbonded_method in ['CutoffPeriodic']: testsystem = testsystems.AlchemicalWaterBox(nonbondedMethod=getattr(app, nonbonded_method), box_edge=12.0*unit.angstroms, cutoff=5.0*unit.angstroms) for platform_name in platform_names: name = '%s %s %s' % (testsystem.name, nonbonded_method, platform_name) self.compare_external_protocol_work_accumulation(testsystem, parameter_name, parameter_initial, parameter_final, platform_name=platform_name, name=name) def test_protocol_work_accumulation_waterbox_barostat(self, temperature=300*unit.kelvin): """ Testing protocol work accumulation for ExternalPerturbationLangevinIntegrator with AlchemicalWaterBox with barostat. For brevity, only using CutoffPeriodic as the non-bonded method. """ try: from openmm import app except ImportError: # OpenMM < 7.6 from simtk.openmm import app parameter_name = 'lambda_electrostatics' parameter_initial = 1.0 parameter_final = 0.0 platform_names = [ openmm.Platform.getPlatform(index).getName() for index in range(openmm.Platform.getNumPlatforms()) ] nonbonded_method = 'CutoffPeriodic' testsystem = testsystems.AlchemicalWaterBox(nonbondedMethod=getattr(app, nonbonded_method), box_edge=12.0*unit.angstroms, cutoff=5.0*unit.angstroms) # Adding the barostat with a high frequency testsystem.system.addForce(openmm.MonteCarloBarostat(1*unit.atmospheres, temperature, 2)) for platform_name in platform_names: name = '%s %s %s' % (testsystem.name, nonbonded_method, platform_name) self.compare_external_protocol_work_accumulation(testsystem, parameter_name, parameter_initial, parameter_final, platform_name=platform_name, name=name) def compare_external_protocol_work_accumulation(self, testsystem, parameter_name, parameter_initial, parameter_final, platform_name='Reference', name=None): """Compare external work accumulation between Reference and CPU platforms. """ if name is None: name = testsystem.name from openmmtools.constants import kB temperature = 298.0 * unit.kelvin kT = kB * temperature context, integrator = self.create_system(testsystem, parameter_name, parameter_initial, temperature=temperature, platform_name='Reference') external_protocol_work = 0.0 nsteps = 20 integrator.step(1) for step in range(nsteps): lambda_value = float(step+1) / float(nsteps) parameter_value = parameter_initial * (1-lambda_value) + parameter_final * lambda_value initial_energy = context.getState(getEnergy=True).getPotentialEnergy() context.setParameter(parameter_name, parameter_value) final_energy = context.getState(getEnergy=True).getPotentialEnergy() external_protocol_work += (final_energy - initial_energy) / kT integrator.step(1) integrator_protocol_work = integrator.get_protocol_work(dimensionless=True) message = '\n' message += 'protocol work discrepancy noted for %s on platform %s\n' % (name, platform_name) message += 'step %5d : external %16e kT | integrator %16e kT | difference %16e kT' % (step, external_protocol_work, integrator_protocol_work, external_protocol_work - integrator_protocol_work) self.assertAlmostEqual(external_protocol_work, integrator_protocol_work, msg=message) del context, integrator def test_temperature_getter_setter(): """Test that temperature setter and getter modify integrator variables.""" temperature = 350*unit.kelvin test = testsystems.HarmonicOscillator() custom_integrators = get_all_custom_integrators() thermostated_integrators = dict(get_all_custom_integrators(only_thermostated=True)) for integrator_name, integrator_class in custom_integrators: # If this is not a ThermostatedIntegrator, the interface should not be added. if integrator_name not in thermostated_integrators: integrator = integrator_class() # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. assert ThermostatedIntegrator.is_thermostated(integrator) is False assert ThermostatedIntegrator.restore_interface(integrator) is False assert not hasattr(integrator, 'getTemperature') continue # Test original integrator. check_integrator_temperature_getter_setter.description = ('Test temperature setter and ' 'getter of {}').format(integrator_name) integrator = integrator_class(temperature=temperature) # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. context = openmm.Context(test.system, integrator) context.setPositions(test.positions) # Integrator temperature is initialized correctly. check_integrator_temperature(integrator, temperature, 1) yield check_integrator_temperature_getter_setter, integrator del context # Test Context integrator wrapper. check_integrator_temperature_getter_setter.description = ('Test temperature wrapper ' 'of {}').format(integrator_name) integrator = integrator_class() # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. context = openmm.Context(test.system, integrator) context.setPositions(test.positions) integrator = context.getIntegrator() # Setter and getter should be added successfully. assert ThermostatedIntegrator.is_thermostated(integrator) is True assert ThermostatedIntegrator.restore_interface(integrator) is True assert isinstance(integrator, integrator_class) yield check_integrator_temperature_getter_setter, integrator del context def test_restorable_integrator_copy(): """Check that ThermostatedIntegrator copies the correct class and attributes.""" thermostated_integrators = get_all_custom_integrators(only_thermostated=True) for integrator_name, integrator_class in thermostated_integrators: integrator = integrator_class() # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. integrator_copied = copy.deepcopy(integrator) assert isinstance(integrator_copied, integrator_class) assert set(integrator_copied.__dict__.keys()) == set(integrator.__dict__.keys()) def run_alchemical_langevin_integrator(nsteps=0, splitting="O { V R H R V } O"): """Check that the AlchemicalLangevinSplittingIntegrator reproduces the analytical free energy difference for a harmonic oscillator deformation, using BAR. Up to 6*sigma is tolerated for error. The total work (protocol work + shadow work) is used. """ #max deviation from the calculated free energy NSIGMA_MAX = 6 n_iterations = 200 # number of forward and reverse protocols # These are the alchemical functions that will be used to control the system temperature = 298.0 * unit.kelvin sigma = 1.0 * unit.angstrom # stddev of harmonic oscillator kT = kB * temperature # thermal energy beta = 1.0 / kT # inverse thermal energy K = kT / sigma**2 # spring constant corresponding to sigma mass = 39.948 * unit.amu period = unit.sqrt(mass/K) # period of harmonic oscillator timestep = period / 20.0 collision_rate = 1.0 / period dF_analytical = 1.0 parameters = dict() parameters['testsystems_HarmonicOscillator_x0'] = (0 * sigma, 2 * sigma) parameters['testsystems_HarmonicOscillator_U0'] = (0 * kT, 1 * kT) alchemical_functions = { 'forward' : { name : '(1-lambda)*%f + lambda*%f' % (value[0].value_in_unit_system(unit.md_unit_system), value[1].value_in_unit_system(unit.md_unit_system)) for (name, value) in parameters.items() }, 'reverse' : { name : '(1-lambda)*%f + lambda*%f' % (value[1].value_in_unit_system(unit.md_unit_system), value[0].value_in_unit_system(unit.md_unit_system)) for (name, value) in parameters.items() }, } # Create harmonic oscillator testsystem testsystem = testsystems.HarmonicOscillator(K=K, mass=mass) system = testsystem.system positions = testsystem.positions # Get equilibrium samples from initial and final states burn_in = 5 * 20 # 5 periods thinning = 5 * 20 # 5 periods # Collect forward and reverse work values directions = ['forward', 'reverse'] work = { direction : np.zeros([n_iterations], np.float64) for direction in directions } platform = openmm.Platform.getPlatformByName("Reference") for direction in directions: positions = testsystem.positions # Create equilibrium and nonequilibrium integrators equilibrium_integrator = GHMCIntegrator(temperature=temperature, collision_rate=collision_rate, timestep=timestep) nonequilibrium_integrator = AlchemicalNonequilibriumLangevinIntegrator(temperature=temperature, collision_rate=collision_rate, timestep=timestep, alchemical_functions=alchemical_functions[direction], splitting=splitting, nsteps_neq=nsteps, measure_shadow_work=True) # Create compound integrator compound_integrator = openmm.CompoundIntegrator() compound_integrator.addIntegrator(equilibrium_integrator) compound_integrator.addIntegrator(nonequilibrium_integrator) # Create Context context = openmm.Context(system, compound_integrator, platform) context.setPositions(positions) # Collect work samples for iteration in range(n_iterations): # # Generate equilibrium sample # compound_integrator.setCurrentIntegrator(0) equilibrium_integrator.reset() compound_integrator.step(thinning) # # Generate nonequilibrium work sample # compound_integrator.setCurrentIntegrator(1) nonequilibrium_integrator.reset() # Check initial conditions after reset current_lambda = nonequilibrium_integrator.getGlobalVariableByName('lambda') assert current_lambda == 0.0, 'initial lambda should be 0.0 (was %f)' % current_lambda current_step = nonequilibrium_integrator.getGlobalVariableByName('step') assert current_step == 0.0, 'initial step should be 0 (was %f)' % current_step compound_integrator.step(max(1, nsteps)) # need to execute at least one step work[direction][iteration] = nonequilibrium_integrator.get_total_work(dimensionless=True) # Check final conditions before reset current_lambda = nonequilibrium_integrator.getGlobalVariableByName('lambda') assert current_lambda == 1.0, 'final lambda should be 1.0 (was %f) for splitting %s' % (current_lambda, splitting) current_step = nonequilibrium_integrator.getGlobalVariableByName('step') assert int(current_step) == max(1,nsteps), 'final step should be %d (was %f) for splitting %s' % (max(1,nsteps), current_step, splitting) nonequilibrium_integrator.reset() # Clean up del context del compound_integrator dF, ddF = pymbar.BAR(work['forward'], work['reverse']) nsigma = np.abs(dF - dF_analytical) / ddF print("analytical DeltaF: {:12.4f}, DeltaF: {:12.4f}, dDeltaF: {:12.4f}, nsigma: {:12.1f}".format(dF_analytical, dF, ddF, nsigma)) if nsigma > NSIGMA_MAX: raise Exception("The free energy difference for the nonequilibrium switching for splitting '%s' and %d steps is not zero within statistical error." % (splitting, nsteps)) def test_periodic_langevin_integrator(splitting="H V R O R V H", ncycles=40, nsteps_neq=1000, nsteps_eq=1000, write_trajectory=False): """ Test PeriodicNonequilibriumIntegrator Parameters ---------- integrator_flavor : openmmtools.integrator.PeriodicNonequilibriumIntegrator (or subclass) integrator to run ncycles : int, optional, default=40 number of cycles nsteps_neq : int, optional, default=1000 number of forward/backward annealing steps nsteps_eq : int, optional, default=1000 number of equilibration steps to run at endstates before annealing write_trajectory : bool, optional, default=True If True, will generate a PDB file that contains the harmonic oscillator trajectory """ #max deviation from the calculated free energy NSIGMA_MAX = 6 # These are the alchemical functions that will be used to control the system temperature = 298.0 * unit.kelvin sigma = 1.0 * unit.angstrom # stddev of harmonic oscillator kT = kB * temperature # thermal energy beta = 1.0 / kT # inverse thermal energy K = kT / sigma**2 # spring constant corresponding to sigma mass = 39.948 * unit.amu period = unit.sqrt(mass/K) # period of harmonic oscillator timestep = period / 20.0 collision_rate = 1.0 / period dF_analytical = 5.0 parameters = dict() displacement = 10 * sigma parameters['testsystems_HarmonicOscillator_x0'] = (0 * sigma, displacement) parameters['testsystems_HarmonicOscillator_U0'] = (0 * kT, 5 * kT) integrator_kwargs = {'temperature':temperature, 'collision_rate': collision_rate, 'timestep': timestep, 'measure_shadow_work': False, 'measure_heat': False} alchemical_functions = { name : '(1-lambda)*%f + lambda*%f' % (value[0].value_in_unit_system(unit.md_unit_system), value[1].value_in_unit_system(unit.md_unit_system)) for (name, value) in parameters.items() } # Create harmonic oscillator testsystem testsystem = testsystems.HarmonicOscillator(K=K, mass=mass) system = testsystem.system positions = testsystem.positions topology = testsystem.topology # Create integrator from openmmtools.integrators import PeriodicNonequilibriumIntegrator integrator = PeriodicNonequilibriumIntegrator(alchemical_functions=alchemical_functions, splitting=splitting, nsteps_eq=nsteps_eq, nsteps_neq=nsteps_neq, **integrator_kwargs) platform = openmm.Platform.getPlatformByName("Reference") context = openmm.Context(system, integrator, platform) context.setPositions(positions) nsteps_per_cycle = nsteps_eq + nsteps_neq + nsteps_eq + nsteps_neq assert integrator.getGlobalVariableByName("n_steps_per_cycle") == nsteps_per_cycle if write_trajectory: try: from openmm.app import PDBFile except ImportError: # OpenMM < 7.6 from simtk.openmm.app import PDBFile filename = 'neq-trajectory.pdb' print(f'Writing trajectory to {filename}') with open(filename, 'wt') as outfile: # Write reference import copy pos1 = copy.deepcopy(positions) pos2 = copy.deepcopy(positions) pos2[0,0] += displacement PDBFile.writeModel(topology, pos1, outfile) PDBFile.writeModel(topology, pos2, outfile) interval = 10 PDBFile.writeModel(topology, positions, outfile, modelIndex=0) for step in range(0,2*nsteps_per_cycle,interval): integrator.step(interval) positions = context.getState(getPositions=True).getPositions(asNumpy=True) PDBFile.writeModel(topology, positions, outfile, modelIndex=step) PDBFile.writeModel(topology, pos1, outfile) PDBFile.writeModel(topology, pos2, outfile) # Reset the integrator integrator.reset() step = 0 for cycle in range(2): # eq (0) for i in range(nsteps_eq): integrator.step(1) step += 1 assert integrator.getGlobalVariableByName("step") == (step % nsteps_per_cycle) assert np.isclose(integrator.getGlobalVariableByName("lambda"), 0.0) # neq (0 -> 1) for i in range(nsteps_neq): integrator.step(1) step += 1 assert integrator.getGlobalVariableByName("step") == (step % nsteps_per_cycle) assert np.isclose(integrator.getGlobalVariableByName("lambda"), (i+1)/nsteps_neq), f'{step} {integrator.getGlobalVariableByName('lambda')}' # eq (1) for i in range(nsteps_eq): integrator.step(1) step += 1 assert integrator.getGlobalVariableByName("step") == (step % nsteps_per_cycle) assert np.isclose(integrator.getGlobalVariableByName("lambda"), 1.0) # neq (1 -> 0) for i in range(nsteps_neq): integrator.step(1) step += 1 assert integrator.getGlobalVariableByName("step") == (step % nsteps_per_cycle) assert np.isclose(integrator.getGlobalVariableByName("lambda"), 1 - (i+1)/nsteps_neq) assert np.isclose(integrator.getGlobalVariableByName("lambda"), 0.0) # Reset the integrator integrator.reset() forward_works, reverse_works = list(), list() for _ in range(ncycles): # Equilibrium (lambda = 0) integrator.step(nsteps_eq) # Forward (0 -> 1) initial_work = integrator.get_protocol_work(dimensionless=True) integrator.step(nsteps_neq) final_work = integrator.get_protocol_work(dimensionless=True) forward_work = final_work - initial_work forward_works.append(forward_work) # Equilibrium (lambda = 1) integrator.step(nsteps_eq) # Reverse work (1 -> 0) initial_work = integrator.get_protocol_work(dimensionless=True) integrator.step(nsteps_neq) final_work = integrator.get_protocol_work(dimensionless=True) reverse_work = final_work - initial_work reverse_works.append(reverse_work) print(np.array(forward_works).std()) print(np.array(reverse_works).std()) dF, ddF = pymbar.BAR(np.array(forward_works), np.array(reverse_works)) nsigma = np.abs(dF - dF_analytical) / ddF assert np.isclose(integrator.getGlobalVariableByName("lambda"), 0.0) print("analytical DeltaF: {:12.4f}, DeltaF: {:12.4f}, dDeltaF: {:12.4f}, nsigma: {:12.1f}".format(dF_analytical, dF, ddF, nsigma)) if nsigma > NSIGMA_MAX: raise Exception(f"The free energy difference for the nonequilibrium switching for splitting {splitting} is not zero within statistical error.") # Clean up del context del integrator def test_alchemical_langevin_integrator(): for splitting in ["O V R H R V O", "H R V O V R H", "O { V R H R V } O"]: for nsteps in [0, 1, 10]: run_alchemical_langevin_integrator(splitting=splitting, nsteps=nsteps) if __name__=="__main__": test_alchemical_langevin_integrator()
#!/usr/local/bin/env python #============================================================================================= # MODULE DOCSTRING #============================================================================================= """ Test custom integrators. """ #============================================================================================= # GLOBAL IMPORTS #============================================================================================= import copy import inspect import pymbar from unittest import TestCase import numpy as np try: import openmm from openmm import unit except ImportError: # OpenMM < 7.6 from simtk import unit from simtk import openmm from openmmtools import integrators, testsystems from openmmtools.integrators import (ThermostatedIntegrator, AlchemicalNonequilibriumLangevinIntegrator, GHMCIntegrator, NoseHooverChainVelocityVerletIntegrator) #============================================================================================= # CONSTANTS #============================================================================================= kB = unit.BOLTZMANN_CONSTANT_kB * unit.AVOGADRO_CONSTANT_NA #============================================================================================= # UTILITY SUBROUTINES #============================================================================================= def get_all_custom_integrators(only_thermostated=False): """Return all CustomIntegrators in integrators. Parameters ---------- only_thermostated : bool If True, only the CustomIntegrators inheriting from ThermostatedIntegrator are returned. Returns ------- custom_integrators : list of tuples A list of tuples ('IntegratorName', IntegratorClass) """ predicate = lambda x: (inspect.isclass(x) and issubclass(x, openmm.CustomIntegrator) and x != integrators.ThermostatedIntegrator) if only_thermostated: old_predicate = predicate # Avoid infinite recursion. predicate = lambda x: old_predicate(x) and issubclass(x, integrators.ThermostatedIntegrator) custom_integrators = inspect.getmembers(integrators, predicate=predicate) return custom_integrators def check_stability(integrator, test, platform=None, nsteps=100, temperature=300.0*unit.kelvin): """ Check that the simulation does not explode over a number integration steps. Parameters ---------- integrator : openmm.Integrator The integrator to test. test : testsystem The testsystem to test. """ kT = kB * temperature # Create Context and initialize positions. if platform: context = openmm.Context(test.system, integrator, platform) else: context = openmm.Context(test.system, integrator) context.setPositions(test.positions) context.setVelocitiesToTemperature(temperature) # TODO: Make deterministic. # Set integrator temperature if hasattr(integrator, 'setTemperature'): integrator.setTemperature(temperature) # Take a number of steps. integrator.step(nsteps) # Check that simulation has not exploded. state = context.getState(getEnergy=True) potential = state.getPotentialEnergy() / kT if np.isnan(potential): raise Exception("Potential energy for integrator %s became NaN." % integrator.__doc__) del context def check_integrator_temperature(integrator, temperature, has_changed): """Check integrator temperature has has_kT_changed variables.""" kT = (temperature * integrators.kB) temperature = temperature / unit.kelvin assert np.isclose(integrator.getTemperature() / unit.kelvin, temperature) assert np.isclose(integrator.getGlobalVariableByName('kT'), kT.value_in_unit_system(unit.md_unit_system)) assert np.isclose(integrator.kT.value_in_unit_system(unit.md_unit_system), kT.value_in_unit_system(unit.md_unit_system)) has_kT_changed = False if 'has_kT_changed' in integrator.global_variable_names: has_kT_changed = integrator.getGlobalVariableByName('has_kT_changed') if has_kT_changed is not False: assert has_kT_changed == has_changed def check_integrator_temperature_getter_setter(integrator): """Check that temperature setter/getter works correctly. Parameters ---------- integrator : ThermostatedIntegrator An integrator just created and already bound to a context. """ # The variable has_kT_changed is initialized correctly. temperature = integrator.getTemperature() check_integrator_temperature(integrator, temperature, 1) # At the first step step, the temperature-dependent constants are computed. integrator.step(1) check_integrator_temperature(integrator, temperature, 0) # Setting temperature update kT and has_kT_changed. temperature += 100*unit.kelvin integrator.setTemperature(temperature) check_integrator_temperature(integrator, temperature, 1) # At the next step, temperature-dependent constants are recomputed. integrator.step(1) check_integrator_temperature(integrator, temperature, 0) #============================================================================================= # TESTS #============================================================================================= def test_stabilities(): """ Test integrators for stability over a short number of steps. """ ts = testsystems # shortcut test_cases = {'harmonic oscillator': ts.HarmonicOscillator(), 'alanine dipeptide in implicit solvent': ts.AlanineDipeptideImplicit()} custom_integrators = get_all_custom_integrators() for test_name, test in test_cases.items(): for integrator_name, integrator_class in custom_integrators: integrator = integrator_class() # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. integrator.__doc__ = integrator_name check_stability.description = ("Testing {} for stability over a short number of " "integration steps of a {}.").format(integrator_name, test_name) yield check_stability, integrator, test def test_integrator_decorators(): integrator = integrators.HMCIntegrator(timestep=0.05 * unit.femtoseconds) testsystem = testsystems.IdealGas() nsteps = 25 context = openmm.Context(testsystem.system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(300 * unit.kelvin) integrator.step(nsteps) assert integrator.n_accept == nsteps assert integrator.n_trials == nsteps assert integrator.acceptance_rate == 1.0 def test_nose_hoover_integrator(): """ Test Nose-Hoover thermostat by ensuring that a short run conserves the system and bath energy to a reasonable tolerance. Also test that the target temperature is rougly matched (+- 10 K). """ temperature = 298*unit.kelvin testsystem = testsystems.WaterBox() num_dof = 3*testsystem.system.getNumParticles() - testsystem.system.getNumConstraints() integrator = NoseHooverChainVelocityVerletIntegrator(testsystem.system, temperature) # Create Context and initialize positions. context = openmm.Context(testsystem.system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) integrator.step(200) # Short equilibration energies = [] temperatures = [] for n in range(100): integrator.step(1) state = context.getState(getEnergy=True) # temperature kinE = state.getKineticEnergy() temp = (2.0 * kinE / (num_dof * unit.MOLAR_GAS_CONSTANT_R)).value_in_unit(unit.kelvin) temperatures.append(temp) # total energy KE = kinE.value_in_unit(unit.kilojoules_per_mole) PE = state.getPotentialEnergy().value_in_unit(unit.kilojoules_per_mole) bathKE = integrator.getGlobalVariableByName('bathKE') bathPE = integrator.getGlobalVariableByName('bathPE') conserved = KE + PE + bathKE + bathPE energies.append(conserved) # Compute maximum deviation from the mean for conserved energies meanenergies = np.mean(energies) maxdeviation = np.amax(np.abs(energies - meanenergies)/meanenergies) assert maxdeviation < 1e-3 # Coarse check for target temperature mean_temperature = np.mean(temperatures) assert abs(mean_temperature - temperature.value_in_unit(unit.kelvin)) < 10.0, mean_temperature def test_pretty_formatting(): """ Test pretty-printing and pretty-formatting of integrators. """ custom_integrators = get_all_custom_integrators() for integrator_name, integrator_class in custom_integrators: integrator = integrator_class() # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. if hasattr(integrator, 'pretty_format'): # Check formatting as text text = integrator.pretty_format() # Check formatting as text with highlighted steps text = integrator.pretty_format(step_types_to_highlight=[5]) # Check list format lines = integrator.pretty_format(as_list=True) msg = "integrator.pretty_format(as_list=True) has %d lines while integrator has %d steps" % (len(lines), integrator.getNumComputations()) assert len(lines) == integrator.getNumComputations(), msg def test_update_context_state_calls(): """ Ensure that all integrators only call addUpdateContextState() once. """ custom_integrators = get_all_custom_integrators() for integrator_name, integrator_class in custom_integrators: integrator = integrator_class() # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. num_force_update = 0 for i in range(integrator.getNumComputations()): step_type, target, expr = integrator.getComputationStep(i) if step_type == 5: num_force_update += 1 msg = "Integrator '%s' has %d calls to addUpdateContextState(), while there should be only one." % (integrator_name, num_force_update) if hasattr(integrator, 'pretty_format'): msg += '\n' + integrator.pretty_format(step_types_to_highlight=[5]) assert num_force_update == 1, msg def test_vvvr_shadow_work_accumulation(): """When `measure_shadow_work==True`, assert that global `shadow_work` is initialized to zero and reaches a nonzero value after integrating a few dozen steps.""" # test `measure_shadow_work=True` --> accumulation of a nonzero value in global `shadow_work` testsystem = testsystems.HarmonicOscillator() system, topology = testsystem.system, testsystem.topology temperature = 298.0 * unit.kelvin integrator = integrators.VVVRIntegrator(temperature, measure_shadow_work=True) context = openmm.Context(system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) assert(integrator.get_shadow_work(dimensionless=True) == 0), "Shadow work should initially be zero." assert(integrator.get_shadow_work() / unit.kilojoules_per_mole == 0), "integrator.get_shadow_work() should have units of energy." assert(integrator.shadow_work / unit.kilojoules_per_mole == 0), "integrator.shadow_work should have units of energy." integrator.step(25) assert(integrator.get_shadow_work(dimensionless=True) != 0), "integrator.get_shadow_work() should be nonzero after dynamics" integrator = integrators.VVVRIntegrator(temperature) context = openmm.Context(system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) integrator.step(25) del context, integrator def test_baoab_heat_accumulation(): """When `measure_heat==True`, assert that global `heat` is initialized to zero and reaches a nonzero value after integrating a few dozen steps.""" # test `measure_shadow_work=True` --> accumulation of a nonzero value in global `shadow_work` testsystem = testsystems.HarmonicOscillator() system, topology = testsystem.system, testsystem.topology temperature = 298.0 * unit.kelvin integrator = integrators.BAOABIntegrator(temperature, measure_heat=True) context = openmm.Context(system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) assert(integrator.get_heat(dimensionless=True) == 0), "Heat should initially be zero." assert(integrator.get_heat() / unit.kilojoules_per_mole == 0), "integrator.get_heat() should have units of energy." assert(integrator.heat / unit.kilojoules_per_mole == 0), "integrator.heat should have units of energy." integrator.step(25) assert(integrator.get_heat(dimensionless=True) != 0), "integrator.get_heat() should be nonzero after dynamics" integrator = integrators.VVVRIntegrator(temperature) context = openmm.Context(system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) integrator.step(25) del context, integrator def test_external_protocol_work_accumulation(): """When `measure_protocol_work==True`, assert that global `protocol_work` is initialized to zero and reaches a zero value after integrating a few dozen steps without perturbation. By default (`measure_protocol_work=False`), assert that there is no global name for `protocol_work`.""" testsystem = testsystems.HarmonicOscillator() system, topology = testsystem.system, testsystem.topology temperature = 298.0 * unit.kelvin integrator = integrators.ExternalPerturbationLangevinIntegrator(splitting="O V R V O", temperature=temperature) context = openmm.Context(system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) # Check that initial step accumulates no protocol work assert(integrator.get_protocol_work(dimensionless=True) == 0), "Protocol work should be 0 initially" assert(integrator.get_protocol_work() / unit.kilojoules_per_mole == 0), "Protocol work should have units of energy" integrator.step(1) assert(integrator.get_protocol_work(dimensionless=True) == 0), "There should be no protocol work." # Check that a single step accumulates protocol work pe_1 = context.getState(getEnergy=True).getPotentialEnergy() perturbed_K=99.0 * unit.kilocalories_per_mole / unit.angstroms**2 context.setParameter('testsystems_HarmonicOscillator_K', perturbed_K) pe_2 = context.getState(getEnergy=True).getPotentialEnergy() integrator.step(1) assert (integrator.get_protocol_work(dimensionless=True) != 0), "There should be protocol work after perturbing." assert (integrator.protocol_work == (pe_2 - pe_1)), "The potential energy difference should be equal to protocol work." del context, integrator integrator = integrators.VVVRIntegrator(temperature) context = openmm.Context(system, integrator) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) integrator.step(25) del context, integrator class TestExternalPerturbationLangevinIntegrator(TestCase): def create_system(self, testsystem, parameter_name, parameter_initial, temperature = 298.0 * unit.kelvin, platform_name='Reference'): """ Create an example system to be used by other tests """ system, topology = testsystem.system, testsystem.topology integrator = integrators.ExternalPerturbationLangevinIntegrator(splitting="O V R V O", temperature=temperature) # Create the context platform = openmm.Platform.getPlatformByName(platform_name) if platform_name in ['CPU', 'CUDA']: try: platform.setPropertyDefaultValue('DeterministicForces', 'true') except Exception as e: mm_min_version = '7.2.0' if platform_name == 'CPU' and openmm.version.short_version < mm_min_version: print("Deterministic CPU forces not present in versions of OpenMM prior to {}".format(mm_min_version)) else: raise e context = openmm.Context(system, integrator, platform) context.setParameter(parameter_name, parameter_initial) context.setPositions(testsystem.positions) context.setVelocitiesToTemperature(temperature) return context, integrator def run_ncmc(self, context, integrator, temperature, nsteps, parameter_name, parameter_initial, parameter_final): """ A simple example of NCMC to be used with unit tests. The protocol work should be reset each time this command is called. Returns ------- external_protocol_work: float the protocol work calculated with context.getState() integrator_protocol_work: float the protocol work calculated inside the integrator. """ kT = kB * temperature external_protocol_work = 0.0 integrator.step(1) for step in range(nsteps): lambda_value = float(step + 1) / float(nsteps) parameter_value = parameter_initial * (1 - lambda_value) + parameter_final * lambda_value initial_energy = context.getState(getEnergy=True).getPotentialEnergy() context.setParameter(parameter_name, parameter_value) final_energy = context.getState(getEnergy=True).getPotentialEnergy() external_protocol_work += (final_energy - initial_energy) / kT integrator.step(1) integrator_protocol_work = integrator.get_protocol_work(dimensionless=True) return external_protocol_work, integrator_protocol_work def test_initial_protocol_work(self): """ Ensure the protocol work is initially zero and remains zero after a number of integrator steps. """ try: from openmm import app except ImportError: # OpenMM < 7.6 from simtk.openmm import app parameter_name = 'lambda_electrostatics' temperature = 298.0 * unit.kelvin parameter_initial = 1.0 platform_name = 'CPU' nonbonded_method = 'CutoffPeriodic' # Create the system testsystem = testsystems.AlchemicalWaterBox(nonbondedMethod=getattr(app, nonbonded_method)) testsystem.system.addForce(openmm.MonteCarloBarostat(1 * unit.atmospheres, temperature, 2)) context, integrator = self.create_system(testsystem, parameter_name, parameter_initial, temperature, platform_name) assert (integrator.get_protocol_work(dimensionless=True) == 0) integrator.step(5) assert np.allclose(integrator.get_protocol_work(dimensionless=True), 0) def test_reset_protocol_work(self): """ Make sure the protocol work that is accumulated internally by the langevin integrator matches the protocol is correctly reset with the reset_protocol_work() command. """ try: from openmm import app except ImportError: # OpenMM < 7.6 from simtk.openmm import app parameter_name = 'lambda_electrostatics' temperature = 298.0 * unit.kelvin parameter_initial = 1.0 parameter_final = 0.0 platform_name = 'CPU' nonbonded_method = 'CutoffPeriodic' # Creating the test system with a high frequency barostat. testsystem = testsystems.AlchemicalAlanineDipeptide(nonbondedMethod=getattr(app, nonbonded_method)) context, integrator = self.create_system(testsystem, parameter_name, parameter_initial, temperature, platform_name) # Number of NCMC steps nsteps = 20 niterations = 3 # Running several rounds of configuration updates and NCMC for i in range(niterations): integrator.step(5) # Reseting the protocol work inside the integrator integrator.reset_protocol_work() integrator.reset() external_protocol_work, integrator_protocol_work = self.run_ncmc(context, integrator, temperature, nsteps, parameter_name, parameter_initial, parameter_final) assert abs(external_protocol_work - integrator_protocol_work) < 1.E-5 def test_ncmc_update_parameters_in_context(self): """ Testing that the protocol work is correctly calculated in cases when the parameters are updated using context.updateParametersInContext() and the integrator is a compound integrator. The NCMC scheme tested below is based on the one used by the saltswap and protons code-bases. """ try: from openmm import app except ImportError: # OpenMM < 7.6 from simtk.openmm import app from openmmtools.constants import kB size = 20.0 temperature = 298.0 * unit.kelvin kT = kB * temperature nonbonded_method = 'CutoffPeriodic' platform_name = 'CPU' timestep = 1. * unit.femtoseconds collision_rate = 90. / unit.picoseconds wbox = testsystems.WaterBox(box_edge=size*unit.angstrom, cutoff=9.*unit.angstrom, nonbondedMethod=getattr(app, nonbonded_method)) integrator = integrators.ExternalPerturbationLangevinIntegrator(splitting="V R O R V", temperature=temperature, timestep=timestep, collision_rate=collision_rate) # Create context platform = openmm.Platform.getPlatformByName(platform_name) context = openmm.Context(wbox.system, integrator, platform) context.setPositions(wbox.positions) context.setPositions(wbox.positions) context.setVelocitiesToTemperature(temperature) def switchoff(force, context, frac=0.9): force.setParticleParameters(0, charge=-0.834 * frac, sigma=0.3150752406575124*frac, epsilon=0.635968 * frac) force.setParticleParameters(1, charge=0.417 * frac, sigma=0, epsilon=1 * frac) force.setParticleParameters(2, charge=0.417 * frac, sigma=0, epsilon=1 * frac) force.updateParametersInContext(context) def switchon(force, context): force.setParticleParameters(0, charge=-0.834, sigma=0.3150752406575124, epsilon=0.635968) force.setParticleParameters(1, charge=0.417, sigma=0, epsilon=1) force.setParticleParameters(2, charge=0.417, sigma=0, epsilon=1) force.updateParametersInContext(context) force = wbox.system.getForce(2) # Non-bonded force. # Number of NCMC steps nsteps = 20 niterations = 3 for i in range(niterations): external_protocol_work = 0.0 integrator.reset_protocol_work() integrator.step(1) for step in range(nsteps): fraction = float(step + 1) / float(nsteps) initial_energy = context.getState(getEnergy=True).getPotentialEnergy() switchoff(force, context, frac=fraction) final_energy = context.getState(getEnergy=True).getPotentialEnergy() external_protocol_work += (final_energy - initial_energy) / kT integrator.step(1) integrator_protocol_work = integrator.get_protocol_work(dimensionless=True) assert abs(external_protocol_work - integrator_protocol_work) < 1.E-5 # Return to unperturbed state switchon(force, context) def test_protocol_work_accumulation_harmonic_oscillator(self): """Testing protocol work accumulation for ExternalPerturbationLangevinIntegrator with HarmonicOscillator """ testsystem = testsystems.HarmonicOscillator() parameter_name = 'testsystems_HarmonicOscillator_x0' parameter_initial = 0.0 * unit.angstroms parameter_final = 10.0 * unit.angstroms for platform_name in ['Reference', 'CPU']: self.compare_external_protocol_work_accumulation(testsystem, parameter_name, parameter_initial, parameter_final, platform_name=platform_name) def test_protocol_work_accumulation_waterbox(self): """Testing protocol work accumulation for ExternalPerturbationLangevinIntegrator with AlchemicalWaterBox """ try: from openmm import app except ImportError: # OpenMM < 7.6 from simtk.openmm import app parameter_name = 'lambda_electrostatics' parameter_initial = 1.0 parameter_final = 0.0 platform_names = [ openmm.Platform.getPlatform(index).getName() for index in range(openmm.Platform.getNumPlatforms()) ] for nonbonded_method in ['CutoffPeriodic']: testsystem = testsystems.AlchemicalWaterBox(nonbondedMethod=getattr(app, nonbonded_method), box_edge=12.0*unit.angstroms, cutoff=5.0*unit.angstroms) for platform_name in platform_names: name = '%s %s %s' % (testsystem.name, nonbonded_method, platform_name) self.compare_external_protocol_work_accumulation(testsystem, parameter_name, parameter_initial, parameter_final, platform_name=platform_name, name=name) def test_protocol_work_accumulation_waterbox_barostat(self, temperature=300*unit.kelvin): """ Testing protocol work accumulation for ExternalPerturbationLangevinIntegrator with AlchemicalWaterBox with barostat. For brevity, only using CutoffPeriodic as the non-bonded method. """ try: from openmm import app except ImportError: # OpenMM < 7.6 from simtk.openmm import app parameter_name = 'lambda_electrostatics' parameter_initial = 1.0 parameter_final = 0.0 platform_names = [ openmm.Platform.getPlatform(index).getName() for index in range(openmm.Platform.getNumPlatforms()) ] nonbonded_method = 'CutoffPeriodic' testsystem = testsystems.AlchemicalWaterBox(nonbondedMethod=getattr(app, nonbonded_method), box_edge=12.0*unit.angstroms, cutoff=5.0*unit.angstroms) # Adding the barostat with a high frequency testsystem.system.addForce(openmm.MonteCarloBarostat(1*unit.atmospheres, temperature, 2)) for platform_name in platform_names: name = '%s %s %s' % (testsystem.name, nonbonded_method, platform_name) self.compare_external_protocol_work_accumulation(testsystem, parameter_name, parameter_initial, parameter_final, platform_name=platform_name, name=name) def compare_external_protocol_work_accumulation(self, testsystem, parameter_name, parameter_initial, parameter_final, platform_name='Reference', name=None): """Compare external work accumulation between Reference and CPU platforms. """ if name is None: name = testsystem.name from openmmtools.constants import kB temperature = 298.0 * unit.kelvin kT = kB * temperature context, integrator = self.create_system(testsystem, parameter_name, parameter_initial, temperature=temperature, platform_name='Reference') external_protocol_work = 0.0 nsteps = 20 integrator.step(1) for step in range(nsteps): lambda_value = float(step+1) / float(nsteps) parameter_value = parameter_initial * (1-lambda_value) + parameter_final * lambda_value initial_energy = context.getState(getEnergy=True).getPotentialEnergy() context.setParameter(parameter_name, parameter_value) final_energy = context.getState(getEnergy=True).getPotentialEnergy() external_protocol_work += (final_energy - initial_energy) / kT integrator.step(1) integrator_protocol_work = integrator.get_protocol_work(dimensionless=True) message = '\n' message += 'protocol work discrepancy noted for %s on platform %s\n' % (name, platform_name) message += 'step %5d : external %16e kT | integrator %16e kT | difference %16e kT' % (step, external_protocol_work, integrator_protocol_work, external_protocol_work - integrator_protocol_work) self.assertAlmostEqual(external_protocol_work, integrator_protocol_work, msg=message) del context, integrator def test_temperature_getter_setter(): """Test that temperature setter and getter modify integrator variables.""" temperature = 350*unit.kelvin test = testsystems.HarmonicOscillator() custom_integrators = get_all_custom_integrators() thermostated_integrators = dict(get_all_custom_integrators(only_thermostated=True)) for integrator_name, integrator_class in custom_integrators: # If this is not a ThermostatedIntegrator, the interface should not be added. if integrator_name not in thermostated_integrators: integrator = integrator_class() # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. assert ThermostatedIntegrator.is_thermostated(integrator) is False assert ThermostatedIntegrator.restore_interface(integrator) is False assert not hasattr(integrator, 'getTemperature') continue # Test original integrator. check_integrator_temperature_getter_setter.description = ('Test temperature setter and ' 'getter of {}').format(integrator_name) integrator = integrator_class(temperature=temperature) # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. context = openmm.Context(test.system, integrator) context.setPositions(test.positions) # Integrator temperature is initialized correctly. check_integrator_temperature(integrator, temperature, 1) yield check_integrator_temperature_getter_setter, integrator del context # Test Context integrator wrapper. check_integrator_temperature_getter_setter.description = ('Test temperature wrapper ' 'of {}').format(integrator_name) integrator = integrator_class() # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. context = openmm.Context(test.system, integrator) context.setPositions(test.positions) integrator = context.getIntegrator() # Setter and getter should be added successfully. assert ThermostatedIntegrator.is_thermostated(integrator) is True assert ThermostatedIntegrator.restore_interface(integrator) is True assert isinstance(integrator, integrator_class) yield check_integrator_temperature_getter_setter, integrator del context def test_restorable_integrator_copy(): """Check that ThermostatedIntegrator copies the correct class and attributes.""" thermostated_integrators = get_all_custom_integrators(only_thermostated=True) for integrator_name, integrator_class in thermostated_integrators: integrator = integrator_class() # NoseHooverChainVelocityVerletIntegrator will print a severe warning here, # because it is being initialized without a system. That's OK. integrator_copied = copy.deepcopy(integrator) assert isinstance(integrator_copied, integrator_class) assert set(integrator_copied.__dict__.keys()) == set(integrator.__dict__.keys()) def run_alchemical_langevin_integrator(nsteps=0, splitting="O { V R H R V } O"): """Check that the AlchemicalLangevinSplittingIntegrator reproduces the analytical free energy difference for a harmonic oscillator deformation, using BAR. Up to 6*sigma is tolerated for error. The total work (protocol work + shadow work) is used. """ #max deviation from the calculated free energy NSIGMA_MAX = 6 n_iterations = 200 # number of forward and reverse protocols # These are the alchemical functions that will be used to control the system temperature = 298.0 * unit.kelvin sigma = 1.0 * unit.angstrom # stddev of harmonic oscillator kT = kB * temperature # thermal energy beta = 1.0 / kT # inverse thermal energy K = kT / sigma**2 # spring constant corresponding to sigma mass = 39.948 * unit.amu period = unit.sqrt(mass/K) # period of harmonic oscillator timestep = period / 20.0 collision_rate = 1.0 / period dF_analytical = 1.0 parameters = dict() parameters['testsystems_HarmonicOscillator_x0'] = (0 * sigma, 2 * sigma) parameters['testsystems_HarmonicOscillator_U0'] = (0 * kT, 1 * kT) alchemical_functions = { 'forward' : { name : '(1-lambda)*%f + lambda*%f' % (value[0].value_in_unit_system(unit.md_unit_system), value[1].value_in_unit_system(unit.md_unit_system)) for (name, value) in parameters.items() }, 'reverse' : { name : '(1-lambda)*%f + lambda*%f' % (value[1].value_in_unit_system(unit.md_unit_system), value[0].value_in_unit_system(unit.md_unit_system)) for (name, value) in parameters.items() }, } # Create harmonic oscillator testsystem testsystem = testsystems.HarmonicOscillator(K=K, mass=mass) system = testsystem.system positions = testsystem.positions # Get equilibrium samples from initial and final states burn_in = 5 * 20 # 5 periods thinning = 5 * 20 # 5 periods # Collect forward and reverse work values directions = ['forward', 'reverse'] work = { direction : np.zeros([n_iterations], np.float64) for direction in directions } platform = openmm.Platform.getPlatformByName("Reference") for direction in directions: positions = testsystem.positions # Create equilibrium and nonequilibrium integrators equilibrium_integrator = GHMCIntegrator(temperature=temperature, collision_rate=collision_rate, timestep=timestep) nonequilibrium_integrator = AlchemicalNonequilibriumLangevinIntegrator(temperature=temperature, collision_rate=collision_rate, timestep=timestep, alchemical_functions=alchemical_functions[direction], splitting=splitting, nsteps_neq=nsteps, measure_shadow_work=True) # Create compound integrator compound_integrator = openmm.CompoundIntegrator() compound_integrator.addIntegrator(equilibrium_integrator) compound_integrator.addIntegrator(nonequilibrium_integrator) # Create Context context = openmm.Context(system, compound_integrator, platform) context.setPositions(positions) # Collect work samples for iteration in range(n_iterations): # # Generate equilibrium sample # compound_integrator.setCurrentIntegrator(0) equilibrium_integrator.reset() compound_integrator.step(thinning) # # Generate nonequilibrium work sample # compound_integrator.setCurrentIntegrator(1) nonequilibrium_integrator.reset() # Check initial conditions after reset current_lambda = nonequilibrium_integrator.getGlobalVariableByName('lambda') assert current_lambda == 0.0, 'initial lambda should be 0.0 (was %f)' % current_lambda current_step = nonequilibrium_integrator.getGlobalVariableByName('step') assert current_step == 0.0, 'initial step should be 0 (was %f)' % current_step compound_integrator.step(max(1, nsteps)) # need to execute at least one step work[direction][iteration] = nonequilibrium_integrator.get_total_work(dimensionless=True) # Check final conditions before reset current_lambda = nonequilibrium_integrator.getGlobalVariableByName('lambda') assert current_lambda == 1.0, 'final lambda should be 1.0 (was %f) for splitting %s' % (current_lambda, splitting) current_step = nonequilibrium_integrator.getGlobalVariableByName('step') assert int(current_step) == max(1,nsteps), 'final step should be %d (was %f) for splitting %s' % (max(1,nsteps), current_step, splitting) nonequilibrium_integrator.reset() # Clean up del context del compound_integrator dF, ddF = pymbar.BAR(work['forward'], work['reverse']) nsigma = np.abs(dF - dF_analytical) / ddF print("analytical DeltaF: {:12.4f}, DeltaF: {:12.4f}, dDeltaF: {:12.4f}, nsigma: {:12.1f}".format(dF_analytical, dF, ddF, nsigma)) if nsigma > NSIGMA_MAX: raise Exception("The free energy difference for the nonequilibrium switching for splitting '%s' and %d steps is not zero within statistical error." % (splitting, nsteps)) def test_periodic_langevin_integrator(splitting="H V R O R V H", ncycles=40, nsteps_neq=1000, nsteps_eq=1000, write_trajectory=False): """ Test PeriodicNonequilibriumIntegrator Parameters ---------- integrator_flavor : openmmtools.integrator.PeriodicNonequilibriumIntegrator (or subclass) integrator to run ncycles : int, optional, default=40 number of cycles nsteps_neq : int, optional, default=1000 number of forward/backward annealing steps nsteps_eq : int, optional, default=1000 number of equilibration steps to run at endstates before annealing write_trajectory : bool, optional, default=True If True, will generate a PDB file that contains the harmonic oscillator trajectory """ #max deviation from the calculated free energy NSIGMA_MAX = 6 # These are the alchemical functions that will be used to control the system temperature = 298.0 * unit.kelvin sigma = 1.0 * unit.angstrom # stddev of harmonic oscillator kT = kB * temperature # thermal energy beta = 1.0 / kT # inverse thermal energy K = kT / sigma**2 # spring constant corresponding to sigma mass = 39.948 * unit.amu period = unit.sqrt(mass/K) # period of harmonic oscillator timestep = period / 20.0 collision_rate = 1.0 / period dF_analytical = 5.0 parameters = dict() displacement = 10 * sigma parameters['testsystems_HarmonicOscillator_x0'] = (0 * sigma, displacement) parameters['testsystems_HarmonicOscillator_U0'] = (0 * kT, 5 * kT) integrator_kwargs = {'temperature':temperature, 'collision_rate': collision_rate, 'timestep': timestep, 'measure_shadow_work': False, 'measure_heat': False} alchemical_functions = { name : '(1-lambda)*%f + lambda*%f' % (value[0].value_in_unit_system(unit.md_unit_system), value[1].value_in_unit_system(unit.md_unit_system)) for (name, value) in parameters.items() } # Create harmonic oscillator testsystem testsystem = testsystems.HarmonicOscillator(K=K, mass=mass) system = testsystem.system positions = testsystem.positions topology = testsystem.topology # Create integrator from openmmtools.integrators import PeriodicNonequilibriumIntegrator integrator = PeriodicNonequilibriumIntegrator(alchemical_functions=alchemical_functions, splitting=splitting, nsteps_eq=nsteps_eq, nsteps_neq=nsteps_neq, **integrator_kwargs) platform = openmm.Platform.getPlatformByName("Reference") context = openmm.Context(system, integrator, platform) context.setPositions(positions) nsteps_per_cycle = nsteps_eq + nsteps_neq + nsteps_eq + nsteps_neq assert integrator.getGlobalVariableByName("n_steps_per_cycle") == nsteps_per_cycle if write_trajectory: try: from openmm.app import PDBFile except ImportError: # OpenMM < 7.6 from simtk.openmm.app import PDBFile filename = 'neq-trajectory.pdb' print(f'Writing trajectory to {filename}') with open(filename, 'wt') as outfile: # Write reference import copy pos1 = copy.deepcopy(positions) pos2 = copy.deepcopy(positions) pos2[0,0] += displacement PDBFile.writeModel(topology, pos1, outfile) PDBFile.writeModel(topology, pos2, outfile) interval = 10 PDBFile.writeModel(topology, positions, outfile, modelIndex=0) for step in range(0,2*nsteps_per_cycle,interval): integrator.step(interval) positions = context.getState(getPositions=True).getPositions(asNumpy=True) PDBFile.writeModel(topology, positions, outfile, modelIndex=step) PDBFile.writeModel(topology, pos1, outfile) PDBFile.writeModel(topology, pos2, outfile) # Reset the integrator integrator.reset() step = 0 for cycle in range(2): # eq (0) for i in range(nsteps_eq): integrator.step(1) step += 1 assert integrator.getGlobalVariableByName("step") == (step % nsteps_per_cycle) assert np.isclose(integrator.getGlobalVariableByName("lambda"), 0.0) # neq (0 -> 1) for i in range(nsteps_neq): integrator.step(1) step += 1 assert integrator.getGlobalVariableByName("step") == (step % nsteps_per_cycle) assert np.isclose(integrator.getGlobalVariableByName("lambda"), (i+1)/nsteps_neq), f'{step} {integrator.getGlobalVariableByName("lambda")}' # eq (1) for i in range(nsteps_eq): integrator.step(1) step += 1 assert integrator.getGlobalVariableByName("step") == (step % nsteps_per_cycle) assert np.isclose(integrator.getGlobalVariableByName("lambda"), 1.0) # neq (1 -> 0) for i in range(nsteps_neq): integrator.step(1) step += 1 assert integrator.getGlobalVariableByName("step") == (step % nsteps_per_cycle) assert np.isclose(integrator.getGlobalVariableByName("lambda"), 1 - (i+1)/nsteps_neq) assert np.isclose(integrator.getGlobalVariableByName("lambda"), 0.0) # Reset the integrator integrator.reset() forward_works, reverse_works = list(), list() for _ in range(ncycles): # Equilibrium (lambda = 0) integrator.step(nsteps_eq) # Forward (0 -> 1) initial_work = integrator.get_protocol_work(dimensionless=True) integrator.step(nsteps_neq) final_work = integrator.get_protocol_work(dimensionless=True) forward_work = final_work - initial_work forward_works.append(forward_work) # Equilibrium (lambda = 1) integrator.step(nsteps_eq) # Reverse work (1 -> 0) initial_work = integrator.get_protocol_work(dimensionless=True) integrator.step(nsteps_neq) final_work = integrator.get_protocol_work(dimensionless=True) reverse_work = final_work - initial_work reverse_works.append(reverse_work) print(np.array(forward_works).std()) print(np.array(reverse_works).std()) dF, ddF = pymbar.BAR(np.array(forward_works), np.array(reverse_works)) nsigma = np.abs(dF - dF_analytical) / ddF assert np.isclose(integrator.getGlobalVariableByName("lambda"), 0.0) print("analytical DeltaF: {:12.4f}, DeltaF: {:12.4f}, dDeltaF: {:12.4f}, nsigma: {:12.1f}".format(dF_analytical, dF, ddF, nsigma)) if nsigma > NSIGMA_MAX: raise Exception(f"The free energy difference for the nonequilibrium switching for splitting {splitting} is not zero within statistical error.") # Clean up del context del integrator def test_alchemical_langevin_integrator(): for splitting in ["O V R H R V O", "H R V O V R H", "O { V R H R V } O"]: for nsteps in [0, 1, 10]: run_alchemical_langevin_integrator(splitting=splitting, nsteps=nsteps) if __name__=="__main__": test_alchemical_langevin_integrator()
# MIT License # # Copyright (c) 2018-2020 Red Hat, Inc. # # 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 github import gitlab import pytest from flexmock import flexmock from ogr.abstract import CommitStatus from ogr.services.gitlab import GitlabProject from packit_service.worker.reporting import StatusReporter @pytest.mark.parametrize( ( "project,commit_sha," "pr_id,pr_object," "state,description,check_name,url," "needs_pr_flags,uid" ), [ pytest.param( flexmock(), "7654321", "11", flexmock(), CommitStatus.success, "We made it!", "packit/pr-rpm-build", "https://api.packit.dev/build/111/logs", False, None, id="GitHub PR", ), pytest.param( flexmock(), "7654321", None, flexmock(), CommitStatus.failure, "We made it!", "packit/branch-rpm-build", "https://api.packit.dev/build/112/logs", False, None, id="branch push", ), pytest.param( flexmock(), "7654321", None, flexmock(head_commit="1234567"), CommitStatus.pending, "We made it!", "packit/pagure-rpm-build", "https://api.packit.dev/build/113/logs", False, None, id="Pagure PR, not head commit", ), pytest.param( flexmock(), "7654321", None, flexmock(head_commit="7654321"), CommitStatus.error, "We made it!", "packit/pagure-rpm-build", "https://api.packit.dev/build/114/logs", True, "8d8d0d428ccee1112042f6d06f6b334a", id="Pagure PR, head commit", ), ], ) def test_set_status( project, commit_sha, pr_id, pr_object, state, description, check_name, url, needs_pr_flags, uid, ): reporter = StatusReporter(project, commit_sha, pr_id) project.should_receive("set_commit_status").with_args( commit_sha, state, url, description, check_name, trim=True ).once() if pr_id is not None: project.should_receive("get_pr").with_args(pr_id).once().and_return(pr_object) if needs_pr_flags: pr_object.should_receive("set_flag").with_args( check_name, description, url, state, uid ) reporter.set_status(state, description, check_name, url) @pytest.mark.parametrize( ("commit_sha,pr_id,pr_object," "state,description,check_name,url,"), [ pytest.param( "7654321", None, None, CommitStatus.success, "We made it!", "packit/pr-rpm-build", "https://api.packit.dev/build/111/logs", id="Gitlab branch", ), pytest.param( "7654321", 1, flexmock(source_project=flexmock()), CommitStatus.success, "We made it!", "packit/pr-rpm-build", "https://api.packit.dev/build/111/logs", id="Gitlab PR", ), ], ) def test_set_status_gitlab( commit_sha, pr_id, pr_object, state, description, check_name, url, ): project = GitlabProject(None, None, None) reporter = StatusReporter(project, commit_sha, pr_id) act_upon = flexmock(pr_object.source_project) if pr_id else flexmock(GitlabProject) act_upon.should_receive("set_commit_status").with_args( commit_sha, state, url, description, check_name, trim=True ).once() if pr_id is not None: flexmock(GitlabProject).should_receive("get_pr").with_args(pr_id).and_return( pr_object ) reporter.set_status(state, description, check_name, url) @pytest.mark.parametrize( ( "project,commit_sha," "pr_id,has_pr_id,pr_object," "state,description,check_name,url," "exception_mock" ), [ pytest.param( flexmock(), "7654321", "11", True, flexmock(), CommitStatus.success, "We made it!", "packit/pr-rpm-build", "https://api.packit.dev/build/111/logs", (github.GithubException, (None, None), dict()), id="GitHub PR", ), pytest.param( flexmock(), "7654321", None, False, flexmock(), CommitStatus.failure, "We made it!", "packit/branch-rpm-build", "https://api.packit.dev/build/112/logs", (gitlab.exceptions.GitlabCreateError, (), {"response_code": 403}), id="branch push", ), ], ) def test_commit_comment_instead_of_status( project, commit_sha, pr_id, has_pr_id, pr_object, state, description, check_name, url, exception_mock, ): reporter = StatusReporter(project, commit_sha, pr_id) exception, exception_args, exception_kwargs = exception_mock project.should_receive("set_commit_status").with_args( commit_sha, state, url, description, check_name, trim=True ).and_raise(exception, *exception_args, **exception_kwargs).once() project.should_receive("commit_comment").with_args( commit=commit_sha, body="\n".join( [ f"- name: {check_name}", f"- state: {state.name}", f"- url: {url if url else "not provided"}", ] ) + f"\n\n{description}", ) if has_pr_id: project.should_receive("get_pr").with_args(pr_id).once().and_return(pr_object) reporter.set_status(state, description, check_name, url) @pytest.mark.parametrize( "project,commit_sha,pr_id,state,check_names,url,result", [ ( flexmock(), "7654321", "11", CommitStatus.success, "packit/pr-rpm-build", "https://api.packit.dev/build/111/logs", "SUCCESS", ), ( flexmock(), "deadbeef", None, CommitStatus.failure, "packit/branch-build", "https://api.packit.dev/build/111/logs", "FAILURE", ), ], ) def test_report_status_by_comment( project, commit_sha, pr_id, state, check_names, url, result, ): reporter = StatusReporter(project, commit_sha, pr_id) comment_body = "\n".join( ( "| Job | Result |", "| ------------- | ------------ |", f"| [{check_names}]({url}) | {result} |", ) ) if pr_id: project.should_receive("get_pr").with_args(pr_id=pr_id).and_return( flexmock().should_receive("comment").with_args(body=comment_body).mock() ).once() else: project.should_receive("commit_comment").with_args( commit=commit_sha, body=comment_body, ).once() reporter.report_status_by_comment(state, url, check_names)
# MIT License # # Copyright (c) 2018-2020 Red Hat, Inc. # # 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 github import gitlab import pytest from flexmock import flexmock from ogr.abstract import CommitStatus from ogr.services.gitlab import GitlabProject from packit_service.worker.reporting import StatusReporter @pytest.mark.parametrize( ( "project,commit_sha," "pr_id,pr_object," "state,description,check_name,url," "needs_pr_flags,uid" ), [ pytest.param( flexmock(), "7654321", "11", flexmock(), CommitStatus.success, "We made it!", "packit/pr-rpm-build", "https://api.packit.dev/build/111/logs", False, None, id="GitHub PR", ), pytest.param( flexmock(), "7654321", None, flexmock(), CommitStatus.failure, "We made it!", "packit/branch-rpm-build", "https://api.packit.dev/build/112/logs", False, None, id="branch push", ), pytest.param( flexmock(), "7654321", None, flexmock(head_commit="1234567"), CommitStatus.pending, "We made it!", "packit/pagure-rpm-build", "https://api.packit.dev/build/113/logs", False, None, id="Pagure PR, not head commit", ), pytest.param( flexmock(), "7654321", None, flexmock(head_commit="7654321"), CommitStatus.error, "We made it!", "packit/pagure-rpm-build", "https://api.packit.dev/build/114/logs", True, "8d8d0d428ccee1112042f6d06f6b334a", id="Pagure PR, head commit", ), ], ) def test_set_status( project, commit_sha, pr_id, pr_object, state, description, check_name, url, needs_pr_flags, uid, ): reporter = StatusReporter(project, commit_sha, pr_id) project.should_receive("set_commit_status").with_args( commit_sha, state, url, description, check_name, trim=True ).once() if pr_id is not None: project.should_receive("get_pr").with_args(pr_id).once().and_return(pr_object) if needs_pr_flags: pr_object.should_receive("set_flag").with_args( check_name, description, url, state, uid ) reporter.set_status(state, description, check_name, url) @pytest.mark.parametrize( ("commit_sha,pr_id,pr_object," "state,description,check_name,url,"), [ pytest.param( "7654321", None, None, CommitStatus.success, "We made it!", "packit/pr-rpm-build", "https://api.packit.dev/build/111/logs", id="Gitlab branch", ), pytest.param( "7654321", 1, flexmock(source_project=flexmock()), CommitStatus.success, "We made it!", "packit/pr-rpm-build", "https://api.packit.dev/build/111/logs", id="Gitlab PR", ), ], ) def test_set_status_gitlab( commit_sha, pr_id, pr_object, state, description, check_name, url, ): project = GitlabProject(None, None, None) reporter = StatusReporter(project, commit_sha, pr_id) act_upon = flexmock(pr_object.source_project) if pr_id else flexmock(GitlabProject) act_upon.should_receive("set_commit_status").with_args( commit_sha, state, url, description, check_name, trim=True ).once() if pr_id is not None: flexmock(GitlabProject).should_receive("get_pr").with_args(pr_id).and_return( pr_object ) reporter.set_status(state, description, check_name, url) @pytest.mark.parametrize( ( "project,commit_sha," "pr_id,has_pr_id,pr_object," "state,description,check_name,url," "exception_mock" ), [ pytest.param( flexmock(), "7654321", "11", True, flexmock(), CommitStatus.success, "We made it!", "packit/pr-rpm-build", "https://api.packit.dev/build/111/logs", (github.GithubException, (None, None), dict()), id="GitHub PR", ), pytest.param( flexmock(), "7654321", None, False, flexmock(), CommitStatus.failure, "We made it!", "packit/branch-rpm-build", "https://api.packit.dev/build/112/logs", (gitlab.exceptions.GitlabCreateError, (), {"response_code": 403}), id="branch push", ), ], ) def test_commit_comment_instead_of_status( project, commit_sha, pr_id, has_pr_id, pr_object, state, description, check_name, url, exception_mock, ): reporter = StatusReporter(project, commit_sha, pr_id) exception, exception_args, exception_kwargs = exception_mock project.should_receive("set_commit_status").with_args( commit_sha, state, url, description, check_name, trim=True ).and_raise(exception, *exception_args, **exception_kwargs).once() project.should_receive("commit_comment").with_args( commit=commit_sha, body="\n".join( [ f"- name: {check_name}", f"- state: {state.name}", f"- url: {url if url else 'not provided'}", ] ) + f"\n\n{description}", ) if has_pr_id: project.should_receive("get_pr").with_args(pr_id).once().and_return(pr_object) reporter.set_status(state, description, check_name, url) @pytest.mark.parametrize( "project,commit_sha,pr_id,state,check_names,url,result", [ ( flexmock(), "7654321", "11", CommitStatus.success, "packit/pr-rpm-build", "https://api.packit.dev/build/111/logs", "SUCCESS", ), ( flexmock(), "deadbeef", None, CommitStatus.failure, "packit/branch-build", "https://api.packit.dev/build/111/logs", "FAILURE", ), ], ) def test_report_status_by_comment( project, commit_sha, pr_id, state, check_names, url, result, ): reporter = StatusReporter(project, commit_sha, pr_id) comment_body = "\n".join( ( "| Job | Result |", "| ------------- | ------------ |", f"| [{check_names}]({url}) | {result} |", ) ) if pr_id: project.should_receive("get_pr").with_args(pr_id=pr_id).and_return( flexmock().should_receive("comment").with_args(body=comment_body).mock() ).once() else: project.should_receive("commit_comment").with_args( commit=commit_sha, body=comment_body, ).once() reporter.report_status_by_comment(state, url, check_names)
import dataclasses import docker import logging import os import shutil import homepose.libs.enviroment import homepose.libs.utils class DNSMasqInstallError(Exception): default_message = 'DNSMasq installation failed!' def __init__(self, msg=default_message, *args, **kwargs): super().__init__(msg, *args, **kwargs) @dataclasses.dataclass class HomeposeNetworking(): enviroment: homepose.libs.enviroment.HomeposeDeployEnviroment = dataclasses.field(init=False, default_factory=homepose.libs.enviroment.HomeposeDeployEnviroment) host_ip_address: str = dataclasses.field(init=False, default='') __additional_gateways: dict = dataclasses.field(init=False, default_factory=dict) __hosts_file_contents: str = dataclasses.field(init=False, default='') __reverse_proxy_location_template: str = dataclasses.field(init=False, default='') def __post_init__(self): for line in os.popen('ip a show ${HOMEPOSE_ETHERNET_INTERFACE}').readlines(): if 'inet ' and 'scope global dynamic' in line: self.host_ip_address = line.strip()[5:line.find('/')-4] os.environ.setdefault('HOMEPOSE_IP_ADDRESS', self.host_ip_address) os.environ.setdefault('HOSTNAME', os.popen('hostname').read().rstrip()) break with open(homepose.libs.vars.HOSTS_TARGET_FILE_PATH, 'r') as current_hosts_file: self.__hosts_file_contents = current_hosts_file.read() with open(f'{self.enviroment['TEMPLATES_FOLDER']}/configs/rproxy.location', 'r') as rproxy_location_template: self.__reverse_proxy_location_template = rproxy_location_template.read() def configure_dns(self): dnsmasq_install_result = os.popen('yes | apt-get install avahi-daemon').readlines() if 'E:' in dnsmasq_install_result[-1]: raise DNSMasqInstallError() shutil.copyfile(f'{self.enviroment['GENERATED_FOLDER']}/configs/dnsmasq.conf', homepose.libs.vars.DNSMASQ_CONF_TARGET_FILE_PATH) os.system('systemctl restart dnsmasq.service') def add_gateway(self, address: str, name: str): if address != self.host_ip_address: self.__additional_gateways[name] = address def broadcast_gateways(self, services_list: list): gateways_entries = [ f'{additional_gateway_address} {additional_gateway_name}\n' for additional_gateway_name, additional_gateway_address in self.__additional_gateways.items() ] + [ f'{self.host_ip_address} {service_name}\n' for service_name in services_list ] new_hosts_file_contents = self.__hosts_file_contents for entry in gateways_entries: if entry not in self.__hosts_file_contents: new_hosts_file_contents += entry current_hosts_file = open(homepose.libs.vars.HOSTS_TARGET_FILE_PATH, 'w') current_hosts_file.truncate(0) current_hosts_file.write(new_hosts_file_contents) current_hosts_file.close()
import dataclasses import docker import logging import os import shutil import homepose.libs.enviroment import homepose.libs.utils class DNSMasqInstallError(Exception): default_message = 'DNSMasq installation failed!' def __init__(self, msg=default_message, *args, **kwargs): super().__init__(msg, *args, **kwargs) @dataclasses.dataclass class HomeposeNetworking(): enviroment: homepose.libs.enviroment.HomeposeDeployEnviroment = dataclasses.field(init=False, default_factory=homepose.libs.enviroment.HomeposeDeployEnviroment) host_ip_address: str = dataclasses.field(init=False, default='') __additional_gateways: dict = dataclasses.field(init=False, default_factory=dict) __hosts_file_contents: str = dataclasses.field(init=False, default='') __reverse_proxy_location_template: str = dataclasses.field(init=False, default='') def __post_init__(self): for line in os.popen('ip a show ${HOMEPOSE_ETHERNET_INTERFACE}').readlines(): if 'inet ' and 'scope global dynamic' in line: self.host_ip_address = line.strip()[5:line.find('/')-4] os.environ.setdefault('HOMEPOSE_IP_ADDRESS', self.host_ip_address) os.environ.setdefault('HOSTNAME', os.popen('hostname').read().rstrip()) break with open(homepose.libs.vars.HOSTS_TARGET_FILE_PATH, 'r') as current_hosts_file: self.__hosts_file_contents = current_hosts_file.read() with open(f'{self.enviroment["TEMPLATES_FOLDER"]}/configs/rproxy.location', 'r') as rproxy_location_template: self.__reverse_proxy_location_template = rproxy_location_template.read() def configure_dns(self): dnsmasq_install_result = os.popen('yes | apt-get install avahi-daemon').readlines() if 'E:' in dnsmasq_install_result[-1]: raise DNSMasqInstallError() shutil.copyfile(f'{self.enviroment["GENERATED_FOLDER"]}/configs/dnsmasq.conf', homepose.libs.vars.DNSMASQ_CONF_TARGET_FILE_PATH) os.system('systemctl restart dnsmasq.service') def add_gateway(self, address: str, name: str): if address != self.host_ip_address: self.__additional_gateways[name] = address def broadcast_gateways(self, services_list: list): gateways_entries = [ f'{additional_gateway_address} {additional_gateway_name}\n' for additional_gateway_name, additional_gateway_address in self.__additional_gateways.items() ] + [ f'{self.host_ip_address} {service_name}\n' for service_name in services_list ] new_hosts_file_contents = self.__hosts_file_contents for entry in gateways_entries: if entry not in self.__hosts_file_contents: new_hosts_file_contents += entry current_hosts_file = open(homepose.libs.vars.HOSTS_TARGET_FILE_PATH, 'w') current_hosts_file.truncate(0) current_hosts_file.write(new_hosts_file_contents) current_hosts_file.close()
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2020 James 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 asyncio from datetime import datetime from typing import TYPE_CHECKING, Awaitable, Callable, Optional, Tuple, Union from .abc import BaseChannel if TYPE_CHECKING: from .clan import Clan from .group import Group from .image import Image from .protobufs.steammessages_chat import ( CChatRoomIncomingChatMessageNotification as GroupMessageNotification, CChatRoomState, CUserChatRoomState, ) from .state import ConnectionState from .trade import TradeOffer from .user import User __all__ = ( "DMChannel", "GroupChannel", "ClanChannel", ) class DMChannel(BaseChannel): """Represents the channel a DM is sent in. Attributes ---------- participant: :class:`~steam.User` The recipient of any messages sent. """ __slots__ = ("participant",) def __init__(self, state: "ConnectionState", participant: "User"): self._state = state self.participant = participant self.clan = None self.group = None def __repr__(self): return f"<DMChannel participant={self.participant!r}>" def _get_message_endpoint(self): return self.participant._get_message_endpoint() def _get_image_endpoint(self): return self.participant._get_image_endpoint() async def send( self, content: Optional[str] = None, *, trade: Optional["TradeOffer"] = None, image: Optional["Image"] = None ) -> None: await self.participant.send(content=content, trade=trade, image=image) def typing(self) -> "TypingContextManager": """Send a typing indicator continuously to the channel while in the context manager. .. note:: This only works in DMs. Usage: :: async with ctx.channel.typing(): # do your expensive operations # or with ctx.channel.typing(): # do your expensive operations """ return TypingContextManager(self.participant) async def trigger_typing(self) -> None: """Send a typing indicator to the channel once. .. note:: This only works in DMs. """ await self._state.send_user_typing(self.participant) # this is basically straight from d.py def _typing_done_callback(future: asyncio.Future): # just retrieve any exception and call it a day try: future.exception() except (asyncio.CancelledError, Exception): pass class TypingContextManager: __slots__ = ("participant", "task", "_state") def __init__(self, participant: "User"): self._state = participant._state self.participant = participant async def send_typing(self): while 1: await self._state.send_user_typing(self.participant) await asyncio.sleep(5) def __enter__(self): self.task = asyncio.create_task(self.send_typing()) return self.task.add_done_callback(_typing_done_callback) def __exit__(self, exc_type, exc, tb): self.task.cancel() async def __aenter__(self): return self.__enter__() async def __aexit__(self, exc_type, exc, tb): self.task.cancel() _MessageEndpointReturnType = Tuple[Tuple[int, int], Callable[[Tuple[int, int]], Awaitable[None]]] class _GroupChannel(BaseChannel): __slots__ = ("id", "joined_at", "name") def __init__(self, state: "ConnectionState", channel): super().__init__() self._state = state self.id = int(channel.chat_id) self.joined_at: Optional[datetime] if hasattr(channel, "chat_name"): split = channel.chat_name.split(" | ", 1) self.name = split[1] if len(split) != 1 else split[0] else: self.name = None if hasattr(channel, "time_joined"): self.joined_at = datetime.utcfromtimestamp(int(channel.time_joined)) else: self.joined_at = None def typing(self): raise NotImplementedError async def trigger_typing(self): raise NotImplementedError def __repr__(self): attrs = ("id", "group") resolved = [f"{attr}={getattr(self, attr)!r}" for attr in attrs] return f"<GroupChannel {" ".join(resolved)}>" def _get_message_endpoint(self) -> _MessageEndpointReturnType: return (self.id, self.group.id), self._state.send_group_message def _get_image_endpoint(self) -> _MessageEndpointReturnType: return (self.id, self.group.id), self._state.http.send_group_image class GroupChannel(_GroupChannel): """Represents a group channel. Attributes ---------- id: :class:`int` The ID of the channel. name: Optional[:class:`str`] The name of the channel, this could be the same as the :attr:`~steam.Group.name` if it's the main channel. group: :class:`~steam.Group` The group to which messages are sent. joined_at: Optional[:class:`datetime.datetime`] The time the client joined the chat. """ def __init__( self, state: "ConnectionState", group: "Group", channel: Union["GroupMessageNotification", "CChatRoomState"] ): super().__init__(state, channel) self.group = group class ClanChannel(_GroupChannel): # they're basically the same thing """Represents a group channel. Attributes ---------- id: :class:`int` The ID of the channel. name: Optional[:class:`str`] The name of the channel, this could be the same as the :attr:`~steam.Clan.name` if it's the main channel. clan: :class:`~steam.Clan` The clan to which messages are sent. joined_at: Optional[:class:`datetime.datetime`] The time the client joined the chat. """ def __init__( self, state: "ConnectionState", clan: "Clan", channel: Union["GroupMessageNotification", "CUserChatRoomState"] ): super().__init__(state, channel) self.clan = clan def __repr__(self): attrs = ("id", "clan") resolved = [f"{attr}={getattr(self, attr)!r}" for attr in attrs] return f"<ClanChannel {" ".join(resolved)}>" def _get_message_endpoint(self) -> _MessageEndpointReturnType: return (self.id, self.clan.chat_id), self._state.send_group_message def _get_image_endpoint(self) -> _MessageEndpointReturnType: return (self.id, self.clan.chat_id), self._state.http.send_group_image
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2020 James 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 asyncio from datetime import datetime from typing import TYPE_CHECKING, Awaitable, Callable, Optional, Tuple, Union from .abc import BaseChannel if TYPE_CHECKING: from .clan import Clan from .group import Group from .image import Image from .protobufs.steammessages_chat import ( CChatRoomIncomingChatMessageNotification as GroupMessageNotification, CChatRoomState, CUserChatRoomState, ) from .state import ConnectionState from .trade import TradeOffer from .user import User __all__ = ( "DMChannel", "GroupChannel", "ClanChannel", ) class DMChannel(BaseChannel): """Represents the channel a DM is sent in. Attributes ---------- participant: :class:`~steam.User` The recipient of any messages sent. """ __slots__ = ("participant",) def __init__(self, state: "ConnectionState", participant: "User"): self._state = state self.participant = participant self.clan = None self.group = None def __repr__(self): return f"<DMChannel participant={self.participant!r}>" def _get_message_endpoint(self): return self.participant._get_message_endpoint() def _get_image_endpoint(self): return self.participant._get_image_endpoint() async def send( self, content: Optional[str] = None, *, trade: Optional["TradeOffer"] = None, image: Optional["Image"] = None ) -> None: await self.participant.send(content=content, trade=trade, image=image) def typing(self) -> "TypingContextManager": """Send a typing indicator continuously to the channel while in the context manager. .. note:: This only works in DMs. Usage: :: async with ctx.channel.typing(): # do your expensive operations # or with ctx.channel.typing(): # do your expensive operations """ return TypingContextManager(self.participant) async def trigger_typing(self) -> None: """Send a typing indicator to the channel once. .. note:: This only works in DMs. """ await self._state.send_user_typing(self.participant) # this is basically straight from d.py def _typing_done_callback(future: asyncio.Future): # just retrieve any exception and call it a day try: future.exception() except (asyncio.CancelledError, Exception): pass class TypingContextManager: __slots__ = ("participant", "task", "_state") def __init__(self, participant: "User"): self._state = participant._state self.participant = participant async def send_typing(self): while 1: await self._state.send_user_typing(self.participant) await asyncio.sleep(5) def __enter__(self): self.task = asyncio.create_task(self.send_typing()) return self.task.add_done_callback(_typing_done_callback) def __exit__(self, exc_type, exc, tb): self.task.cancel() async def __aenter__(self): return self.__enter__() async def __aexit__(self, exc_type, exc, tb): self.task.cancel() _MessageEndpointReturnType = Tuple[Tuple[int, int], Callable[[Tuple[int, int]], Awaitable[None]]] class _GroupChannel(BaseChannel): __slots__ = ("id", "joined_at", "name") def __init__(self, state: "ConnectionState", channel): super().__init__() self._state = state self.id = int(channel.chat_id) self.joined_at: Optional[datetime] if hasattr(channel, "chat_name"): split = channel.chat_name.split(" | ", 1) self.name = split[1] if len(split) != 1 else split[0] else: self.name = None if hasattr(channel, "time_joined"): self.joined_at = datetime.utcfromtimestamp(int(channel.time_joined)) else: self.joined_at = None def typing(self): raise NotImplementedError async def trigger_typing(self): raise NotImplementedError def __repr__(self): attrs = ("id", "group") resolved = [f"{attr}={getattr(self, attr)!r}" for attr in attrs] return f"<GroupChannel {' '.join(resolved)}>" def _get_message_endpoint(self) -> _MessageEndpointReturnType: return (self.id, self.group.id), self._state.send_group_message def _get_image_endpoint(self) -> _MessageEndpointReturnType: return (self.id, self.group.id), self._state.http.send_group_image class GroupChannel(_GroupChannel): """Represents a group channel. Attributes ---------- id: :class:`int` The ID of the channel. name: Optional[:class:`str`] The name of the channel, this could be the same as the :attr:`~steam.Group.name` if it's the main channel. group: :class:`~steam.Group` The group to which messages are sent. joined_at: Optional[:class:`datetime.datetime`] The time the client joined the chat. """ def __init__( self, state: "ConnectionState", group: "Group", channel: Union["GroupMessageNotification", "CChatRoomState"] ): super().__init__(state, channel) self.group = group class ClanChannel(_GroupChannel): # they're basically the same thing """Represents a group channel. Attributes ---------- id: :class:`int` The ID of the channel. name: Optional[:class:`str`] The name of the channel, this could be the same as the :attr:`~steam.Clan.name` if it's the main channel. clan: :class:`~steam.Clan` The clan to which messages are sent. joined_at: Optional[:class:`datetime.datetime`] The time the client joined the chat. """ def __init__( self, state: "ConnectionState", clan: "Clan", channel: Union["GroupMessageNotification", "CUserChatRoomState"] ): super().__init__(state, channel) self.clan = clan def __repr__(self): attrs = ("id", "clan") resolved = [f"{attr}={getattr(self, attr)!r}" for attr in attrs] return f"<ClanChannel {' '.join(resolved)}>" def _get_message_endpoint(self) -> _MessageEndpointReturnType: return (self.id, self.clan.chat_id), self._state.send_group_message def _get_image_endpoint(self) -> _MessageEndpointReturnType: return (self.id, self.clan.chat_id), self._state.http.send_group_image
from django.contrib.contenttypes.models import ContentType from django.db.models import Prefetch from django.db.models.expressions import RawSQL from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse from circuits.models import Provider from circuits.tables import ProviderTable from dcim.filtersets import InterfaceFilterSet from dcim.models import Interface, Site from dcim.tables import SiteTable from netbox.views import generic from utilities.utils import count_related from virtualization.filtersets import VMInterfaceFilterSet from virtualization.models import VMInterface from . import filtersets, forms, tables from .constants import * from .models import * from .models import ASN from .utils import add_requested_prefixes, add_available_ipaddresses, add_available_vlans # # VRFs # class VRFListView(generic.ObjectListView): queryset = VRF.objects.all() filterset = filtersets.VRFFilterSet filterset_form = forms.VRFFilterForm table = tables.VRFTable class VRFView(generic.ObjectView): queryset = VRF.objects.all() def get_extra_context(self, request, instance): prefix_count = Prefix.objects.restrict(request.user, 'view').filter(vrf=instance).count() ipaddress_count = IPAddress.objects.restrict(request.user, 'view').filter(vrf=instance).count() import_targets_table = tables.RouteTargetTable( instance.import_targets.prefetch_related('tenant'), orderable=False ) export_targets_table = tables.RouteTargetTable( instance.export_targets.prefetch_related('tenant'), orderable=False ) return { 'prefix_count': prefix_count, 'ipaddress_count': ipaddress_count, 'import_targets_table': import_targets_table, 'export_targets_table': export_targets_table, } class VRFEditView(generic.ObjectEditView): queryset = VRF.objects.all() form = forms.VRFForm class VRFDeleteView(generic.ObjectDeleteView): queryset = VRF.objects.all() class VRFBulkImportView(generic.BulkImportView): queryset = VRF.objects.all() model_form = forms.VRFCSVForm table = tables.VRFTable class VRFBulkEditView(generic.BulkEditView): queryset = VRF.objects.prefetch_related('tenant') filterset = filtersets.VRFFilterSet table = tables.VRFTable form = forms.VRFBulkEditForm class VRFBulkDeleteView(generic.BulkDeleteView): queryset = VRF.objects.prefetch_related('tenant') filterset = filtersets.VRFFilterSet table = tables.VRFTable # # Route targets # class RouteTargetListView(generic.ObjectListView): queryset = RouteTarget.objects.all() filterset = filtersets.RouteTargetFilterSet filterset_form = forms.RouteTargetFilterForm table = tables.RouteTargetTable class RouteTargetView(generic.ObjectView): queryset = RouteTarget.objects.all() def get_extra_context(self, request, instance): importing_vrfs_table = tables.VRFTable( instance.importing_vrfs.prefetch_related('tenant'), orderable=False ) exporting_vrfs_table = tables.VRFTable( instance.exporting_vrfs.prefetch_related('tenant'), orderable=False ) return { 'importing_vrfs_table': importing_vrfs_table, 'exporting_vrfs_table': exporting_vrfs_table, } class RouteTargetEditView(generic.ObjectEditView): queryset = RouteTarget.objects.all() form = forms.RouteTargetForm class RouteTargetDeleteView(generic.ObjectDeleteView): queryset = RouteTarget.objects.all() class RouteTargetBulkImportView(generic.BulkImportView): queryset = RouteTarget.objects.all() model_form = forms.RouteTargetCSVForm table = tables.RouteTargetTable class RouteTargetBulkEditView(generic.BulkEditView): queryset = RouteTarget.objects.prefetch_related('tenant') filterset = filtersets.RouteTargetFilterSet table = tables.RouteTargetTable form = forms.RouteTargetBulkEditForm class RouteTargetBulkDeleteView(generic.BulkDeleteView): queryset = RouteTarget.objects.prefetch_related('tenant') filterset = filtersets.RouteTargetFilterSet table = tables.RouteTargetTable # # RIRs # class RIRListView(generic.ObjectListView): queryset = RIR.objects.annotate( aggregate_count=count_related(Aggregate, 'rir') ) filterset = filtersets.RIRFilterSet filterset_form = forms.RIRFilterForm table = tables.RIRTable class RIRView(generic.ObjectView): queryset = RIR.objects.all() def get_extra_context(self, request, instance): aggregates = Aggregate.objects.restrict(request.user, 'view').filter(rir=instance).annotate( child_count=RawSQL('SELECT COUNT(*) FROM ipam_prefix WHERE ipam_prefix.prefix <<= ipam_aggregate.prefix', ()) ) aggregates_table = tables.AggregateTable(aggregates, user=request.user, exclude=('rir', 'utilization')) aggregates_table.configure(request) return { 'aggregates_table': aggregates_table, } class RIREditView(generic.ObjectEditView): queryset = RIR.objects.all() form = forms.RIRForm class RIRDeleteView(generic.ObjectDeleteView): queryset = RIR.objects.all() class RIRBulkImportView(generic.BulkImportView): queryset = RIR.objects.all() model_form = forms.RIRCSVForm table = tables.RIRTable class RIRBulkEditView(generic.BulkEditView): queryset = RIR.objects.annotate( aggregate_count=count_related(Aggregate, 'rir') ) filterset = filtersets.RIRFilterSet table = tables.RIRTable form = forms.RIRBulkEditForm class RIRBulkDeleteView(generic.BulkDeleteView): queryset = RIR.objects.annotate( aggregate_count=count_related(Aggregate, 'rir') ) filterset = filtersets.RIRFilterSet table = tables.RIRTable # # ASNs # class ASNListView(generic.ObjectListView): queryset = ASN.objects.annotate( site_count=count_related(Site, 'asns'), provider_count=count_related(Provider, 'asns') ) filterset = filtersets.ASNFilterSet filterset_form = forms.ASNFilterForm table = tables.ASNTable class ASNView(generic.ObjectView): queryset = ASN.objects.all() def get_extra_context(self, request, instance): # Gather assigned Sites sites = instance.sites.restrict(request.user, 'view') sites_table = SiteTable(sites, user=request.user) sites_table.configure(request) # Gather assigned Providers providers = instance.providers.restrict(request.user, 'view') providers_table = ProviderTable(providers, user=request.user) providers_table.configure(request) return { 'sites_table': sites_table, 'sites_count': sites.count(), 'providers_table': providers_table, 'providers_count': providers.count(), } class ASNEditView(generic.ObjectEditView): queryset = ASN.objects.all() form = forms.ASNForm class ASNDeleteView(generic.ObjectDeleteView): queryset = ASN.objects.all() class ASNBulkImportView(generic.BulkImportView): queryset = ASN.objects.all() model_form = forms.ASNCSVForm table = tables.ASNTable class ASNBulkEditView(generic.BulkEditView): queryset = ASN.objects.annotate( site_count=count_related(Site, 'asns') ) filterset = filtersets.ASNFilterSet table = tables.ASNTable form = forms.ASNBulkEditForm class ASNBulkDeleteView(generic.BulkDeleteView): queryset = ASN.objects.annotate( site_count=count_related(Site, 'asns') ) filterset = filtersets.ASNFilterSet table = tables.ASNTable # # Aggregates # class AggregateListView(generic.ObjectListView): queryset = Aggregate.objects.annotate( child_count=RawSQL('SELECT COUNT(*) FROM ipam_prefix WHERE ipam_prefix.prefix <<= ipam_aggregate.prefix', ()) ) filterset = filtersets.AggregateFilterSet filterset_form = forms.AggregateFilterForm table = tables.AggregateTable class AggregateView(generic.ObjectView): queryset = Aggregate.objects.all() class AggregatePrefixesView(generic.ObjectChildrenView): queryset = Aggregate.objects.all() child_model = Prefix table = tables.PrefixTable filterset = filtersets.PrefixFilterSet template_name = 'ipam/aggregate/prefixes.html' def get_children(self, request, parent): return Prefix.objects.restrict(request.user, 'view').filter( prefix__net_contained_or_equal=str(parent.prefix) ).prefetch_related('site', 'role', 'tenant', 'vlan') def prep_table_data(self, request, queryset, parent): # Determine whether to show assigned prefixes, available prefixes, or both show_available = bool(request.GET.get('show_available', 'true') == 'true') show_assigned = bool(request.GET.get('show_assigned', 'true') == 'true') return add_requested_prefixes(parent.prefix, queryset, show_available, show_assigned) def get_extra_context(self, request, instance): return { 'bulk_querystring': f'within={instance.prefix}', 'active_tab': 'prefixes', 'first_available_prefix': instance.get_first_available_prefix(), 'show_available': bool(request.GET.get('show_available', 'true') == 'true'), 'show_assigned': bool(request.GET.get('show_assigned', 'true') == 'true'), } class AggregateEditView(generic.ObjectEditView): queryset = Aggregate.objects.all() form = forms.AggregateForm class AggregateDeleteView(generic.ObjectDeleteView): queryset = Aggregate.objects.all() class AggregateBulkImportView(generic.BulkImportView): queryset = Aggregate.objects.all() model_form = forms.AggregateCSVForm table = tables.AggregateTable class AggregateBulkEditView(generic.BulkEditView): queryset = Aggregate.objects.prefetch_related('rir') filterset = filtersets.AggregateFilterSet table = tables.AggregateTable form = forms.AggregateBulkEditForm class AggregateBulkDeleteView(generic.BulkDeleteView): queryset = Aggregate.objects.prefetch_related('rir') filterset = filtersets.AggregateFilterSet table = tables.AggregateTable # # Prefix/VLAN roles # class RoleListView(generic.ObjectListView): queryset = Role.objects.annotate( prefix_count=count_related(Prefix, 'role'), iprange_count=count_related(IPRange, 'role'), vlan_count=count_related(VLAN, 'role') ) filterset = filtersets.RoleFilterSet filterset_form = forms.RoleFilterForm table = tables.RoleTable class RoleView(generic.ObjectView): queryset = Role.objects.all() def get_extra_context(self, request, instance): prefixes = Prefix.objects.restrict(request.user, 'view').filter( role=instance ) prefixes_table = tables.PrefixTable(prefixes, user=request.user, exclude=('role', 'utilization')) prefixes_table.configure(request) return { 'prefixes_table': prefixes_table, } class RoleEditView(generic.ObjectEditView): queryset = Role.objects.all() form = forms.RoleForm class RoleDeleteView(generic.ObjectDeleteView): queryset = Role.objects.all() class RoleBulkImportView(generic.BulkImportView): queryset = Role.objects.all() model_form = forms.RoleCSVForm table = tables.RoleTable class RoleBulkEditView(generic.BulkEditView): queryset = Role.objects.all() filterset = filtersets.RoleFilterSet table = tables.RoleTable form = forms.RoleBulkEditForm class RoleBulkDeleteView(generic.BulkDeleteView): queryset = Role.objects.all() table = tables.RoleTable # # Prefixes # class PrefixListView(generic.ObjectListView): queryset = Prefix.objects.all() filterset = filtersets.PrefixFilterSet filterset_form = forms.PrefixFilterForm table = tables.PrefixTable template_name = 'ipam/prefix_list.html' class PrefixView(generic.ObjectView): queryset = Prefix.objects.prefetch_related('vrf', 'site__region', 'tenant__group', 'vlan__group', 'role') def get_extra_context(self, request, instance): try: aggregate = Aggregate.objects.restrict(request.user, 'view').get( prefix__net_contains_or_equals=str(instance.prefix) ) except Aggregate.DoesNotExist: aggregate = None # Parent prefixes table parent_prefixes = Prefix.objects.restrict(request.user, 'view').filter( Q(vrf=instance.vrf) | Q(vrf__isnull=True) ).filter( prefix__net_contains=str(instance.prefix) ).prefetch_related( 'site', 'role', 'tenant' ) parent_prefix_table = tables.PrefixTable( list(parent_prefixes), exclude=('vrf', 'utilization'), orderable=False ) # Duplicate prefixes table duplicate_prefixes = Prefix.objects.restrict(request.user, 'view').filter( vrf=instance.vrf, prefix=str(instance.prefix) ).exclude( pk=instance.pk ).prefetch_related( 'site', 'role' ) duplicate_prefix_table = tables.PrefixTable( list(duplicate_prefixes), exclude=('vrf', 'utilization'), orderable=False ) return { 'aggregate': aggregate, 'parent_prefix_table': parent_prefix_table, 'duplicate_prefix_table': duplicate_prefix_table, } class PrefixPrefixesView(generic.ObjectChildrenView): queryset = Prefix.objects.all() child_model = Prefix table = tables.PrefixTable filterset = filtersets.PrefixFilterSet template_name = 'ipam/prefix/prefixes.html' def get_children(self, request, parent): return parent.get_child_prefixes().restrict(request.user, 'view').prefetch_related( 'site', 'vrf', 'vlan', 'role', 'tenant', ) def prep_table_data(self, request, queryset, parent): # Determine whether to show assigned prefixes, available prefixes, or both show_available = bool(request.GET.get('show_available', 'true') == 'true') show_assigned = bool(request.GET.get('show_assigned', 'true') == 'true') return add_requested_prefixes(parent.prefix, queryset, show_available, show_assigned) def get_extra_context(self, request, instance): return { 'bulk_querystring': f"vrf_id={instance.vrf.pk if instance.vrf else "0"}&within={instance.prefix}", 'active_tab': 'prefixes', 'first_available_prefix': instance.get_first_available_prefix(), 'show_available': bool(request.GET.get('show_available', 'true') == 'true'), 'show_assigned': bool(request.GET.get('show_assigned', 'true') == 'true'), } class PrefixIPRangesView(generic.ObjectChildrenView): queryset = Prefix.objects.all() child_model = IPRange table = tables.IPRangeTable filterset = filtersets.IPRangeFilterSet template_name = 'ipam/prefix/ip_ranges.html' def get_children(self, request, parent): return parent.get_child_ranges().restrict(request.user, 'view').prefetch_related( 'vrf', 'role', 'tenant', ) def get_extra_context(self, request, instance): return { 'bulk_querystring': f"vrf_id={instance.vrf.pk if instance.vrf else "0"}&parent={instance.prefix}", 'active_tab': 'ip-ranges', 'first_available_ip': instance.get_first_available_ip(), } class PrefixIPAddressesView(generic.ObjectChildrenView): queryset = Prefix.objects.all() child_model = IPAddress table = tables.IPAddressTable filterset = filtersets.IPAddressFilterSet template_name = 'ipam/prefix/ip_addresses.html' def get_children(self, request, parent): return parent.get_child_ips().restrict(request.user, 'view').prefetch_related('vrf', 'tenant') def prep_table_data(self, request, queryset, parent): show_available = bool(request.GET.get('show_available', 'true') == 'true') if show_available: return add_available_ipaddresses(parent.prefix, queryset, parent.is_pool) return queryset def get_extra_context(self, request, instance): return { 'bulk_querystring': f"vrf_id={instance.vrf.pk if instance.vrf else "0"}&parent={instance.prefix}", 'active_tab': 'ip-addresses', 'first_available_ip': instance.get_first_available_ip(), } class PrefixEditView(generic.ObjectEditView): queryset = Prefix.objects.all() form = forms.PrefixForm class PrefixDeleteView(generic.ObjectDeleteView): queryset = Prefix.objects.all() class PrefixBulkImportView(generic.BulkImportView): queryset = Prefix.objects.all() model_form = forms.PrefixCSVForm table = tables.PrefixTable class PrefixBulkEditView(generic.BulkEditView): queryset = Prefix.objects.prefetch_related('site', 'vrf__tenant', 'tenant', 'vlan', 'role') filterset = filtersets.PrefixFilterSet table = tables.PrefixTable form = forms.PrefixBulkEditForm class PrefixBulkDeleteView(generic.BulkDeleteView): queryset = Prefix.objects.prefetch_related('site', 'vrf__tenant', 'tenant', 'vlan', 'role') filterset = filtersets.PrefixFilterSet table = tables.PrefixTable # # IP Ranges # class IPRangeListView(generic.ObjectListView): queryset = IPRange.objects.all() filterset = filtersets.IPRangeFilterSet filterset_form = forms.IPRangeFilterForm table = tables.IPRangeTable class IPRangeView(generic.ObjectView): queryset = IPRange.objects.all() class IPRangeIPAddressesView(generic.ObjectChildrenView): queryset = IPRange.objects.all() child_model = IPAddress table = tables.IPAddressTable filterset = filtersets.IPAddressFilterSet template_name = 'ipam/iprange/ip_addresses.html' def get_children(self, request, parent): return parent.get_child_ips().restrict(request.user, 'view').prefetch_related( 'vrf', 'role', 'tenant', ) def get_extra_context(self, request, instance): return { 'active_tab': 'ip-addresses', } class IPRangeEditView(generic.ObjectEditView): queryset = IPRange.objects.all() form = forms.IPRangeForm class IPRangeDeleteView(generic.ObjectDeleteView): queryset = IPRange.objects.all() class IPRangeBulkImportView(generic.BulkImportView): queryset = IPRange.objects.all() model_form = forms.IPRangeCSVForm table = tables.IPRangeTable class IPRangeBulkEditView(generic.BulkEditView): queryset = IPRange.objects.prefetch_related('vrf', 'tenant') filterset = filtersets.IPRangeFilterSet table = tables.IPRangeTable form = forms.IPRangeBulkEditForm class IPRangeBulkDeleteView(generic.BulkDeleteView): queryset = IPRange.objects.prefetch_related('vrf', 'tenant') filterset = filtersets.IPRangeFilterSet table = tables.IPRangeTable # # IP addresses # class IPAddressListView(generic.ObjectListView): queryset = IPAddress.objects.all() filterset = filtersets.IPAddressFilterSet filterset_form = forms.IPAddressFilterForm table = tables.IPAddressTable class IPAddressView(generic.ObjectView): queryset = IPAddress.objects.prefetch_related('vrf__tenant', 'tenant') def get_extra_context(self, request, instance): # Parent prefixes table parent_prefixes = Prefix.objects.restrict(request.user, 'view').filter( vrf=instance.vrf, prefix__net_contains_or_equals=str(instance.address.ip) ).prefetch_related( 'site', 'role' ) parent_prefixes_table = tables.PrefixTable( list(parent_prefixes), exclude=('vrf', 'utilization'), orderable=False ) # Duplicate IPs table duplicate_ips = IPAddress.objects.restrict(request.user, 'view').filter( vrf=instance.vrf, address=str(instance.address) ).exclude( pk=instance.pk ).prefetch_related( 'nat_inside' ) # Exclude anycast IPs if this IP is anycast if instance.role == IPAddressRoleChoices.ROLE_ANYCAST: duplicate_ips = duplicate_ips.exclude(role=IPAddressRoleChoices.ROLE_ANYCAST) # Limit to a maximum of 10 duplicates displayed here duplicate_ips_table = tables.IPAddressTable(duplicate_ips[:10], orderable=False) # Related IP table related_ips = IPAddress.objects.restrict(request.user, 'view').exclude( address=str(instance.address) ).filter( vrf=instance.vrf, address__net_contained_or_equal=str(instance.address) ) related_ips_table = tables.IPAddressTable(related_ips, orderable=False) related_ips_table.configure(request) return { 'parent_prefixes_table': parent_prefixes_table, 'duplicate_ips_table': duplicate_ips_table, 'more_duplicate_ips': duplicate_ips.count() > 10, 'related_ips_table': related_ips_table, } class IPAddressEditView(generic.ObjectEditView): queryset = IPAddress.objects.all() form = forms.IPAddressForm template_name = 'ipam/ipaddress_edit.html' def alter_object(self, obj, request, url_args, url_kwargs): if 'interface' in request.GET: try: obj.assigned_object = Interface.objects.get(pk=request.GET['interface']) except (ValueError, Interface.DoesNotExist): pass elif 'vminterface' in request.GET: try: obj.assigned_object = VMInterface.objects.get(pk=request.GET['vminterface']) except (ValueError, VMInterface.DoesNotExist): pass elif 'fhrpgroup' in request.GET: try: obj.assigned_object = FHRPGroup.objects.get(pk=request.GET['fhrpgroup']) except (ValueError, FHRPGroup.DoesNotExist): pass return obj # TODO: Standardize or remove this view class IPAddressAssignView(generic.ObjectView): """ Search for IPAddresses to be assigned to an Interface. """ queryset = IPAddress.objects.all() def dispatch(self, request, *args, **kwargs): # Redirect user if an interface has not been provided if 'interface' not in request.GET and 'vminterface' not in request.GET: return redirect('ipam:ipaddress_add') return super().dispatch(request, *args, **kwargs) def get(self, request): form = forms.IPAddressAssignForm() return render(request, 'ipam/ipaddress_assign.html', { 'form': form, 'return_url': request.GET.get('return_url', ''), }) def post(self, request): form = forms.IPAddressAssignForm(request.POST) table = None if form.is_valid(): addresses = self.queryset.prefetch_related('vrf', 'tenant') # Limit to 100 results addresses = filtersets.IPAddressFilterSet(request.POST, addresses).qs[:100] table = tables.IPAddressAssignTable(addresses) return render(request, 'ipam/ipaddress_assign.html', { 'form': form, 'table': table, 'return_url': request.GET.get('return_url'), }) class IPAddressDeleteView(generic.ObjectDeleteView): queryset = IPAddress.objects.all() class IPAddressBulkCreateView(generic.BulkCreateView): queryset = IPAddress.objects.all() form = forms.IPAddressBulkCreateForm model_form = forms.IPAddressBulkAddForm pattern_target = 'address' template_name = 'ipam/ipaddress_bulk_add.html' class IPAddressBulkImportView(generic.BulkImportView): queryset = IPAddress.objects.all() model_form = forms.IPAddressCSVForm table = tables.IPAddressTable class IPAddressBulkEditView(generic.BulkEditView): queryset = IPAddress.objects.prefetch_related('vrf__tenant', 'tenant') filterset = filtersets.IPAddressFilterSet table = tables.IPAddressTable form = forms.IPAddressBulkEditForm class IPAddressBulkDeleteView(generic.BulkDeleteView): queryset = IPAddress.objects.prefetch_related('vrf__tenant', 'tenant') filterset = filtersets.IPAddressFilterSet table = tables.IPAddressTable # # VLAN groups # class VLANGroupListView(generic.ObjectListView): queryset = VLANGroup.objects.annotate( vlan_count=count_related(VLAN, 'group') ) filterset = filtersets.VLANGroupFilterSet filterset_form = forms.VLANGroupFilterForm table = tables.VLANGroupTable class VLANGroupView(generic.ObjectView): queryset = VLANGroup.objects.all() def get_extra_context(self, request, instance): vlans = VLAN.objects.restrict(request.user, 'view').filter(group=instance).prefetch_related( Prefetch('prefixes', queryset=Prefix.objects.restrict(request.user)) ).order_by('vid') vlans_count = vlans.count() vlans = add_available_vlans(vlans, vlan_group=instance) vlans_table = tables.VLANTable(vlans, user=request.user, exclude=('group',)) if request.user.has_perm('ipam.change_vlan') or request.user.has_perm('ipam.delete_vlan'): vlans_table.columns.show('pk') vlans_table.configure(request) # Compile permissions list for rendering the object table permissions = { 'add': request.user.has_perm('ipam.add_vlan'), 'change': request.user.has_perm('ipam.change_vlan'), 'delete': request.user.has_perm('ipam.delete_vlan'), } return { 'vlans_count': vlans_count, 'vlans_table': vlans_table, 'permissions': permissions, } class VLANGroupEditView(generic.ObjectEditView): queryset = VLANGroup.objects.all() form = forms.VLANGroupForm class VLANGroupDeleteView(generic.ObjectDeleteView): queryset = VLANGroup.objects.all() class VLANGroupBulkImportView(generic.BulkImportView): queryset = VLANGroup.objects.all() model_form = forms.VLANGroupCSVForm table = tables.VLANGroupTable class VLANGroupBulkEditView(generic.BulkEditView): queryset = VLANGroup.objects.annotate( vlan_count=count_related(VLAN, 'group') ) filterset = filtersets.VLANGroupFilterSet table = tables.VLANGroupTable form = forms.VLANGroupBulkEditForm class VLANGroupBulkDeleteView(generic.BulkDeleteView): queryset = VLANGroup.objects.annotate( vlan_count=count_related(VLAN, 'group') ) filterset = filtersets.VLANGroupFilterSet table = tables.VLANGroupTable # # FHRP groups # class FHRPGroupListView(generic.ObjectListView): queryset = FHRPGroup.objects.annotate( member_count=count_related(FHRPGroupAssignment, 'group') ) filterset = filtersets.FHRPGroupFilterSet filterset_form = forms.FHRPGroupFilterForm table = tables.FHRPGroupTable class FHRPGroupView(generic.ObjectView): queryset = FHRPGroup.objects.all() def get_extra_context(self, request, instance): # Get assigned IP addresses ipaddress_table = tables.AssignedIPAddressesTable( data=instance.ip_addresses.restrict(request.user, 'view').prefetch_related('vrf', 'tenant'), orderable=False ) # Get assigned interfaces members_table = tables.FHRPGroupAssignmentTable( data=FHRPGroupAssignment.objects.restrict(request.user, 'view').filter(group=instance), orderable=False ) members_table.columns.hide('group') return { 'ipaddress_table': ipaddress_table, 'members_table': members_table, 'member_count': FHRPGroupAssignment.objects.filter(group=instance).count(), } class FHRPGroupEditView(generic.ObjectEditView): queryset = FHRPGroup.objects.all() form = forms.FHRPGroupForm template_name = 'ipam/fhrpgroup_edit.html' def get_return_url(self, request, obj=None): return_url = super().get_return_url(request, obj) # If we're redirecting the user to the FHRPGroupAssignment creation form, # initialize the group field with the FHRPGroup we just saved. if return_url.startswith(reverse('ipam:fhrpgroupassignment_add')): return_url += f'&group={obj.pk}' return return_url class FHRPGroupDeleteView(generic.ObjectDeleteView): queryset = FHRPGroup.objects.all() class FHRPGroupBulkImportView(generic.BulkImportView): queryset = FHRPGroup.objects.all() model_form = forms.FHRPGroupCSVForm table = tables.FHRPGroupTable class FHRPGroupBulkEditView(generic.BulkEditView): queryset = FHRPGroup.objects.all() filterset = filtersets.FHRPGroupFilterSet table = tables.FHRPGroupTable form = forms.FHRPGroupBulkEditForm class FHRPGroupBulkDeleteView(generic.BulkDeleteView): queryset = FHRPGroup.objects.all() filterset = filtersets.FHRPGroupFilterSet table = tables.FHRPGroupTable # # FHRP group assignments # class FHRPGroupAssignmentEditView(generic.ObjectEditView): queryset = FHRPGroupAssignment.objects.all() form = forms.FHRPGroupAssignmentForm template_name = 'ipam/fhrpgroupassignment_edit.html' def alter_object(self, instance, request, args, kwargs): if not instance.pk: # Assign the interface based on URL kwargs content_type = get_object_or_404(ContentType, pk=request.GET.get('interface_type')) instance.interface = get_object_or_404(content_type.model_class(), pk=request.GET.get('interface_id')) return instance class FHRPGroupAssignmentDeleteView(generic.ObjectDeleteView): queryset = FHRPGroupAssignment.objects.all() # # VLANs # class VLANListView(generic.ObjectListView): queryset = VLAN.objects.all() filterset = filtersets.VLANFilterSet filterset_form = forms.VLANFilterForm table = tables.VLANTable class VLANView(generic.ObjectView): queryset = VLAN.objects.prefetch_related('site__region', 'tenant__group', 'role') def get_extra_context(self, request, instance): prefixes = Prefix.objects.restrict(request.user, 'view').filter(vlan=instance).prefetch_related( 'vrf', 'site', 'role' ) prefix_table = tables.PrefixTable(list(prefixes), exclude=('vlan', 'utilization'), orderable=False) return { 'prefix_table': prefix_table, } class VLANInterfacesView(generic.ObjectChildrenView): queryset = VLAN.objects.all() child_model = Interface table = tables.VLANDevicesTable filterset = InterfaceFilterSet template_name = 'ipam/vlan/interfaces.html' def get_children(self, request, parent): return parent.get_interfaces().restrict(request.user, 'view') def get_extra_context(self, request, instance): return { 'active_tab': 'interfaces', } class VLANVMInterfacesView(generic.ObjectChildrenView): queryset = VLAN.objects.all() child_model = VMInterface table = tables.VLANVirtualMachinesTable filterset = VMInterfaceFilterSet template_name = 'ipam/vlan/vminterfaces.html' def get_children(self, request, parent): return parent.get_vminterfaces().restrict(request.user, 'view') def get_extra_context(self, request, instance): return { 'active_tab': 'vminterfaces', } class VLANEditView(generic.ObjectEditView): queryset = VLAN.objects.all() form = forms.VLANForm template_name = 'ipam/vlan_edit.html' class VLANDeleteView(generic.ObjectDeleteView): queryset = VLAN.objects.all() class VLANBulkImportView(generic.BulkImportView): queryset = VLAN.objects.all() model_form = forms.VLANCSVForm table = tables.VLANTable class VLANBulkEditView(generic.BulkEditView): queryset = VLAN.objects.prefetch_related('site', 'group', 'tenant', 'role') filterset = filtersets.VLANFilterSet table = tables.VLANTable form = forms.VLANBulkEditForm class VLANBulkDeleteView(generic.BulkDeleteView): queryset = VLAN.objects.prefetch_related('site', 'group', 'tenant', 'role') filterset = filtersets.VLANFilterSet table = tables.VLANTable # # Service templates # class ServiceTemplateListView(generic.ObjectListView): queryset = ServiceTemplate.objects.all() filterset = filtersets.ServiceTemplateFilterSet filterset_form = forms.ServiceTemplateFilterForm table = tables.ServiceTemplateTable class ServiceTemplateView(generic.ObjectView): queryset = ServiceTemplate.objects.all() class ServiceTemplateEditView(generic.ObjectEditView): queryset = ServiceTemplate.objects.all() form = forms.ServiceTemplateForm class ServiceTemplateDeleteView(generic.ObjectDeleteView): queryset = ServiceTemplate.objects.all() class ServiceTemplateBulkImportView(generic.BulkImportView): queryset = ServiceTemplate.objects.all() model_form = forms.ServiceTemplateCSVForm table = tables.ServiceTemplateTable class ServiceTemplateBulkEditView(generic.BulkEditView): queryset = ServiceTemplate.objects.all() filterset = filtersets.ServiceTemplateFilterSet table = tables.ServiceTemplateTable form = forms.ServiceTemplateBulkEditForm class ServiceTemplateBulkDeleteView(generic.BulkDeleteView): queryset = ServiceTemplate.objects.all() filterset = filtersets.ServiceTemplateFilterSet table = tables.ServiceTemplateTable # # Services # class ServiceListView(generic.ObjectListView): queryset = Service.objects.all() filterset = filtersets.ServiceFilterSet filterset_form = forms.ServiceFilterForm table = tables.ServiceTable class ServiceView(generic.ObjectView): queryset = Service.objects.prefetch_related('ipaddresses') class ServiceCreateView(generic.ObjectEditView): queryset = Service.objects.all() form = forms.ServiceCreateForm template_name = 'ipam/service_create.html' class ServiceEditView(generic.ObjectEditView): queryset = Service.objects.prefetch_related('ipaddresses') form = forms.ServiceForm template_name = 'ipam/service_edit.html' class ServiceDeleteView(generic.ObjectDeleteView): queryset = Service.objects.all() class ServiceBulkImportView(generic.BulkImportView): queryset = Service.objects.all() model_form = forms.ServiceCSVForm table = tables.ServiceTable class ServiceBulkEditView(generic.BulkEditView): queryset = Service.objects.prefetch_related('device', 'virtual_machine') filterset = filtersets.ServiceFilterSet table = tables.ServiceTable form = forms.ServiceBulkEditForm class ServiceBulkDeleteView(generic.BulkDeleteView): queryset = Service.objects.prefetch_related('device', 'virtual_machine') filterset = filtersets.ServiceFilterSet table = tables.ServiceTable
from django.contrib.contenttypes.models import ContentType from django.db.models import Prefetch from django.db.models.expressions import RawSQL from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse from circuits.models import Provider from circuits.tables import ProviderTable from dcim.filtersets import InterfaceFilterSet from dcim.models import Interface, Site from dcim.tables import SiteTable from netbox.views import generic from utilities.utils import count_related from virtualization.filtersets import VMInterfaceFilterSet from virtualization.models import VMInterface from . import filtersets, forms, tables from .constants import * from .models import * from .models import ASN from .utils import add_requested_prefixes, add_available_ipaddresses, add_available_vlans # # VRFs # class VRFListView(generic.ObjectListView): queryset = VRF.objects.all() filterset = filtersets.VRFFilterSet filterset_form = forms.VRFFilterForm table = tables.VRFTable class VRFView(generic.ObjectView): queryset = VRF.objects.all() def get_extra_context(self, request, instance): prefix_count = Prefix.objects.restrict(request.user, 'view').filter(vrf=instance).count() ipaddress_count = IPAddress.objects.restrict(request.user, 'view').filter(vrf=instance).count() import_targets_table = tables.RouteTargetTable( instance.import_targets.prefetch_related('tenant'), orderable=False ) export_targets_table = tables.RouteTargetTable( instance.export_targets.prefetch_related('tenant'), orderable=False ) return { 'prefix_count': prefix_count, 'ipaddress_count': ipaddress_count, 'import_targets_table': import_targets_table, 'export_targets_table': export_targets_table, } class VRFEditView(generic.ObjectEditView): queryset = VRF.objects.all() form = forms.VRFForm class VRFDeleteView(generic.ObjectDeleteView): queryset = VRF.objects.all() class VRFBulkImportView(generic.BulkImportView): queryset = VRF.objects.all() model_form = forms.VRFCSVForm table = tables.VRFTable class VRFBulkEditView(generic.BulkEditView): queryset = VRF.objects.prefetch_related('tenant') filterset = filtersets.VRFFilterSet table = tables.VRFTable form = forms.VRFBulkEditForm class VRFBulkDeleteView(generic.BulkDeleteView): queryset = VRF.objects.prefetch_related('tenant') filterset = filtersets.VRFFilterSet table = tables.VRFTable # # Route targets # class RouteTargetListView(generic.ObjectListView): queryset = RouteTarget.objects.all() filterset = filtersets.RouteTargetFilterSet filterset_form = forms.RouteTargetFilterForm table = tables.RouteTargetTable class RouteTargetView(generic.ObjectView): queryset = RouteTarget.objects.all() def get_extra_context(self, request, instance): importing_vrfs_table = tables.VRFTable( instance.importing_vrfs.prefetch_related('tenant'), orderable=False ) exporting_vrfs_table = tables.VRFTable( instance.exporting_vrfs.prefetch_related('tenant'), orderable=False ) return { 'importing_vrfs_table': importing_vrfs_table, 'exporting_vrfs_table': exporting_vrfs_table, } class RouteTargetEditView(generic.ObjectEditView): queryset = RouteTarget.objects.all() form = forms.RouteTargetForm class RouteTargetDeleteView(generic.ObjectDeleteView): queryset = RouteTarget.objects.all() class RouteTargetBulkImportView(generic.BulkImportView): queryset = RouteTarget.objects.all() model_form = forms.RouteTargetCSVForm table = tables.RouteTargetTable class RouteTargetBulkEditView(generic.BulkEditView): queryset = RouteTarget.objects.prefetch_related('tenant') filterset = filtersets.RouteTargetFilterSet table = tables.RouteTargetTable form = forms.RouteTargetBulkEditForm class RouteTargetBulkDeleteView(generic.BulkDeleteView): queryset = RouteTarget.objects.prefetch_related('tenant') filterset = filtersets.RouteTargetFilterSet table = tables.RouteTargetTable # # RIRs # class RIRListView(generic.ObjectListView): queryset = RIR.objects.annotate( aggregate_count=count_related(Aggregate, 'rir') ) filterset = filtersets.RIRFilterSet filterset_form = forms.RIRFilterForm table = tables.RIRTable class RIRView(generic.ObjectView): queryset = RIR.objects.all() def get_extra_context(self, request, instance): aggregates = Aggregate.objects.restrict(request.user, 'view').filter(rir=instance).annotate( child_count=RawSQL('SELECT COUNT(*) FROM ipam_prefix WHERE ipam_prefix.prefix <<= ipam_aggregate.prefix', ()) ) aggregates_table = tables.AggregateTable(aggregates, user=request.user, exclude=('rir', 'utilization')) aggregates_table.configure(request) return { 'aggregates_table': aggregates_table, } class RIREditView(generic.ObjectEditView): queryset = RIR.objects.all() form = forms.RIRForm class RIRDeleteView(generic.ObjectDeleteView): queryset = RIR.objects.all() class RIRBulkImportView(generic.BulkImportView): queryset = RIR.objects.all() model_form = forms.RIRCSVForm table = tables.RIRTable class RIRBulkEditView(generic.BulkEditView): queryset = RIR.objects.annotate( aggregate_count=count_related(Aggregate, 'rir') ) filterset = filtersets.RIRFilterSet table = tables.RIRTable form = forms.RIRBulkEditForm class RIRBulkDeleteView(generic.BulkDeleteView): queryset = RIR.objects.annotate( aggregate_count=count_related(Aggregate, 'rir') ) filterset = filtersets.RIRFilterSet table = tables.RIRTable # # ASNs # class ASNListView(generic.ObjectListView): queryset = ASN.objects.annotate( site_count=count_related(Site, 'asns'), provider_count=count_related(Provider, 'asns') ) filterset = filtersets.ASNFilterSet filterset_form = forms.ASNFilterForm table = tables.ASNTable class ASNView(generic.ObjectView): queryset = ASN.objects.all() def get_extra_context(self, request, instance): # Gather assigned Sites sites = instance.sites.restrict(request.user, 'view') sites_table = SiteTable(sites, user=request.user) sites_table.configure(request) # Gather assigned Providers providers = instance.providers.restrict(request.user, 'view') providers_table = ProviderTable(providers, user=request.user) providers_table.configure(request) return { 'sites_table': sites_table, 'sites_count': sites.count(), 'providers_table': providers_table, 'providers_count': providers.count(), } class ASNEditView(generic.ObjectEditView): queryset = ASN.objects.all() form = forms.ASNForm class ASNDeleteView(generic.ObjectDeleteView): queryset = ASN.objects.all() class ASNBulkImportView(generic.BulkImportView): queryset = ASN.objects.all() model_form = forms.ASNCSVForm table = tables.ASNTable class ASNBulkEditView(generic.BulkEditView): queryset = ASN.objects.annotate( site_count=count_related(Site, 'asns') ) filterset = filtersets.ASNFilterSet table = tables.ASNTable form = forms.ASNBulkEditForm class ASNBulkDeleteView(generic.BulkDeleteView): queryset = ASN.objects.annotate( site_count=count_related(Site, 'asns') ) filterset = filtersets.ASNFilterSet table = tables.ASNTable # # Aggregates # class AggregateListView(generic.ObjectListView): queryset = Aggregate.objects.annotate( child_count=RawSQL('SELECT COUNT(*) FROM ipam_prefix WHERE ipam_prefix.prefix <<= ipam_aggregate.prefix', ()) ) filterset = filtersets.AggregateFilterSet filterset_form = forms.AggregateFilterForm table = tables.AggregateTable class AggregateView(generic.ObjectView): queryset = Aggregate.objects.all() class AggregatePrefixesView(generic.ObjectChildrenView): queryset = Aggregate.objects.all() child_model = Prefix table = tables.PrefixTable filterset = filtersets.PrefixFilterSet template_name = 'ipam/aggregate/prefixes.html' def get_children(self, request, parent): return Prefix.objects.restrict(request.user, 'view').filter( prefix__net_contained_or_equal=str(parent.prefix) ).prefetch_related('site', 'role', 'tenant', 'vlan') def prep_table_data(self, request, queryset, parent): # Determine whether to show assigned prefixes, available prefixes, or both show_available = bool(request.GET.get('show_available', 'true') == 'true') show_assigned = bool(request.GET.get('show_assigned', 'true') == 'true') return add_requested_prefixes(parent.prefix, queryset, show_available, show_assigned) def get_extra_context(self, request, instance): return { 'bulk_querystring': f'within={instance.prefix}', 'active_tab': 'prefixes', 'first_available_prefix': instance.get_first_available_prefix(), 'show_available': bool(request.GET.get('show_available', 'true') == 'true'), 'show_assigned': bool(request.GET.get('show_assigned', 'true') == 'true'), } class AggregateEditView(generic.ObjectEditView): queryset = Aggregate.objects.all() form = forms.AggregateForm class AggregateDeleteView(generic.ObjectDeleteView): queryset = Aggregate.objects.all() class AggregateBulkImportView(generic.BulkImportView): queryset = Aggregate.objects.all() model_form = forms.AggregateCSVForm table = tables.AggregateTable class AggregateBulkEditView(generic.BulkEditView): queryset = Aggregate.objects.prefetch_related('rir') filterset = filtersets.AggregateFilterSet table = tables.AggregateTable form = forms.AggregateBulkEditForm class AggregateBulkDeleteView(generic.BulkDeleteView): queryset = Aggregate.objects.prefetch_related('rir') filterset = filtersets.AggregateFilterSet table = tables.AggregateTable # # Prefix/VLAN roles # class RoleListView(generic.ObjectListView): queryset = Role.objects.annotate( prefix_count=count_related(Prefix, 'role'), iprange_count=count_related(IPRange, 'role'), vlan_count=count_related(VLAN, 'role') ) filterset = filtersets.RoleFilterSet filterset_form = forms.RoleFilterForm table = tables.RoleTable class RoleView(generic.ObjectView): queryset = Role.objects.all() def get_extra_context(self, request, instance): prefixes = Prefix.objects.restrict(request.user, 'view').filter( role=instance ) prefixes_table = tables.PrefixTable(prefixes, user=request.user, exclude=('role', 'utilization')) prefixes_table.configure(request) return { 'prefixes_table': prefixes_table, } class RoleEditView(generic.ObjectEditView): queryset = Role.objects.all() form = forms.RoleForm class RoleDeleteView(generic.ObjectDeleteView): queryset = Role.objects.all() class RoleBulkImportView(generic.BulkImportView): queryset = Role.objects.all() model_form = forms.RoleCSVForm table = tables.RoleTable class RoleBulkEditView(generic.BulkEditView): queryset = Role.objects.all() filterset = filtersets.RoleFilterSet table = tables.RoleTable form = forms.RoleBulkEditForm class RoleBulkDeleteView(generic.BulkDeleteView): queryset = Role.objects.all() table = tables.RoleTable # # Prefixes # class PrefixListView(generic.ObjectListView): queryset = Prefix.objects.all() filterset = filtersets.PrefixFilterSet filterset_form = forms.PrefixFilterForm table = tables.PrefixTable template_name = 'ipam/prefix_list.html' class PrefixView(generic.ObjectView): queryset = Prefix.objects.prefetch_related('vrf', 'site__region', 'tenant__group', 'vlan__group', 'role') def get_extra_context(self, request, instance): try: aggregate = Aggregate.objects.restrict(request.user, 'view').get( prefix__net_contains_or_equals=str(instance.prefix) ) except Aggregate.DoesNotExist: aggregate = None # Parent prefixes table parent_prefixes = Prefix.objects.restrict(request.user, 'view').filter( Q(vrf=instance.vrf) | Q(vrf__isnull=True) ).filter( prefix__net_contains=str(instance.prefix) ).prefetch_related( 'site', 'role', 'tenant' ) parent_prefix_table = tables.PrefixTable( list(parent_prefixes), exclude=('vrf', 'utilization'), orderable=False ) # Duplicate prefixes table duplicate_prefixes = Prefix.objects.restrict(request.user, 'view').filter( vrf=instance.vrf, prefix=str(instance.prefix) ).exclude( pk=instance.pk ).prefetch_related( 'site', 'role' ) duplicate_prefix_table = tables.PrefixTable( list(duplicate_prefixes), exclude=('vrf', 'utilization'), orderable=False ) return { 'aggregate': aggregate, 'parent_prefix_table': parent_prefix_table, 'duplicate_prefix_table': duplicate_prefix_table, } class PrefixPrefixesView(generic.ObjectChildrenView): queryset = Prefix.objects.all() child_model = Prefix table = tables.PrefixTable filterset = filtersets.PrefixFilterSet template_name = 'ipam/prefix/prefixes.html' def get_children(self, request, parent): return parent.get_child_prefixes().restrict(request.user, 'view').prefetch_related( 'site', 'vrf', 'vlan', 'role', 'tenant', ) def prep_table_data(self, request, queryset, parent): # Determine whether to show assigned prefixes, available prefixes, or both show_available = bool(request.GET.get('show_available', 'true') == 'true') show_assigned = bool(request.GET.get('show_assigned', 'true') == 'true') return add_requested_prefixes(parent.prefix, queryset, show_available, show_assigned) def get_extra_context(self, request, instance): return { 'bulk_querystring': f"vrf_id={instance.vrf.pk if instance.vrf else '0'}&within={instance.prefix}", 'active_tab': 'prefixes', 'first_available_prefix': instance.get_first_available_prefix(), 'show_available': bool(request.GET.get('show_available', 'true') == 'true'), 'show_assigned': bool(request.GET.get('show_assigned', 'true') == 'true'), } class PrefixIPRangesView(generic.ObjectChildrenView): queryset = Prefix.objects.all() child_model = IPRange table = tables.IPRangeTable filterset = filtersets.IPRangeFilterSet template_name = 'ipam/prefix/ip_ranges.html' def get_children(self, request, parent): return parent.get_child_ranges().restrict(request.user, 'view').prefetch_related( 'vrf', 'role', 'tenant', ) def get_extra_context(self, request, instance): return { 'bulk_querystring': f"vrf_id={instance.vrf.pk if instance.vrf else '0'}&parent={instance.prefix}", 'active_tab': 'ip-ranges', 'first_available_ip': instance.get_first_available_ip(), } class PrefixIPAddressesView(generic.ObjectChildrenView): queryset = Prefix.objects.all() child_model = IPAddress table = tables.IPAddressTable filterset = filtersets.IPAddressFilterSet template_name = 'ipam/prefix/ip_addresses.html' def get_children(self, request, parent): return parent.get_child_ips().restrict(request.user, 'view').prefetch_related('vrf', 'tenant') def prep_table_data(self, request, queryset, parent): show_available = bool(request.GET.get('show_available', 'true') == 'true') if show_available: return add_available_ipaddresses(parent.prefix, queryset, parent.is_pool) return queryset def get_extra_context(self, request, instance): return { 'bulk_querystring': f"vrf_id={instance.vrf.pk if instance.vrf else '0'}&parent={instance.prefix}", 'active_tab': 'ip-addresses', 'first_available_ip': instance.get_first_available_ip(), } class PrefixEditView(generic.ObjectEditView): queryset = Prefix.objects.all() form = forms.PrefixForm class PrefixDeleteView(generic.ObjectDeleteView): queryset = Prefix.objects.all() class PrefixBulkImportView(generic.BulkImportView): queryset = Prefix.objects.all() model_form = forms.PrefixCSVForm table = tables.PrefixTable class PrefixBulkEditView(generic.BulkEditView): queryset = Prefix.objects.prefetch_related('site', 'vrf__tenant', 'tenant', 'vlan', 'role') filterset = filtersets.PrefixFilterSet table = tables.PrefixTable form = forms.PrefixBulkEditForm class PrefixBulkDeleteView(generic.BulkDeleteView): queryset = Prefix.objects.prefetch_related('site', 'vrf__tenant', 'tenant', 'vlan', 'role') filterset = filtersets.PrefixFilterSet table = tables.PrefixTable # # IP Ranges # class IPRangeListView(generic.ObjectListView): queryset = IPRange.objects.all() filterset = filtersets.IPRangeFilterSet filterset_form = forms.IPRangeFilterForm table = tables.IPRangeTable class IPRangeView(generic.ObjectView): queryset = IPRange.objects.all() class IPRangeIPAddressesView(generic.ObjectChildrenView): queryset = IPRange.objects.all() child_model = IPAddress table = tables.IPAddressTable filterset = filtersets.IPAddressFilterSet template_name = 'ipam/iprange/ip_addresses.html' def get_children(self, request, parent): return parent.get_child_ips().restrict(request.user, 'view').prefetch_related( 'vrf', 'role', 'tenant', ) def get_extra_context(self, request, instance): return { 'active_tab': 'ip-addresses', } class IPRangeEditView(generic.ObjectEditView): queryset = IPRange.objects.all() form = forms.IPRangeForm class IPRangeDeleteView(generic.ObjectDeleteView): queryset = IPRange.objects.all() class IPRangeBulkImportView(generic.BulkImportView): queryset = IPRange.objects.all() model_form = forms.IPRangeCSVForm table = tables.IPRangeTable class IPRangeBulkEditView(generic.BulkEditView): queryset = IPRange.objects.prefetch_related('vrf', 'tenant') filterset = filtersets.IPRangeFilterSet table = tables.IPRangeTable form = forms.IPRangeBulkEditForm class IPRangeBulkDeleteView(generic.BulkDeleteView): queryset = IPRange.objects.prefetch_related('vrf', 'tenant') filterset = filtersets.IPRangeFilterSet table = tables.IPRangeTable # # IP addresses # class IPAddressListView(generic.ObjectListView): queryset = IPAddress.objects.all() filterset = filtersets.IPAddressFilterSet filterset_form = forms.IPAddressFilterForm table = tables.IPAddressTable class IPAddressView(generic.ObjectView): queryset = IPAddress.objects.prefetch_related('vrf__tenant', 'tenant') def get_extra_context(self, request, instance): # Parent prefixes table parent_prefixes = Prefix.objects.restrict(request.user, 'view').filter( vrf=instance.vrf, prefix__net_contains_or_equals=str(instance.address.ip) ).prefetch_related( 'site', 'role' ) parent_prefixes_table = tables.PrefixTable( list(parent_prefixes), exclude=('vrf', 'utilization'), orderable=False ) # Duplicate IPs table duplicate_ips = IPAddress.objects.restrict(request.user, 'view').filter( vrf=instance.vrf, address=str(instance.address) ).exclude( pk=instance.pk ).prefetch_related( 'nat_inside' ) # Exclude anycast IPs if this IP is anycast if instance.role == IPAddressRoleChoices.ROLE_ANYCAST: duplicate_ips = duplicate_ips.exclude(role=IPAddressRoleChoices.ROLE_ANYCAST) # Limit to a maximum of 10 duplicates displayed here duplicate_ips_table = tables.IPAddressTable(duplicate_ips[:10], orderable=False) # Related IP table related_ips = IPAddress.objects.restrict(request.user, 'view').exclude( address=str(instance.address) ).filter( vrf=instance.vrf, address__net_contained_or_equal=str(instance.address) ) related_ips_table = tables.IPAddressTable(related_ips, orderable=False) related_ips_table.configure(request) return { 'parent_prefixes_table': parent_prefixes_table, 'duplicate_ips_table': duplicate_ips_table, 'more_duplicate_ips': duplicate_ips.count() > 10, 'related_ips_table': related_ips_table, } class IPAddressEditView(generic.ObjectEditView): queryset = IPAddress.objects.all() form = forms.IPAddressForm template_name = 'ipam/ipaddress_edit.html' def alter_object(self, obj, request, url_args, url_kwargs): if 'interface' in request.GET: try: obj.assigned_object = Interface.objects.get(pk=request.GET['interface']) except (ValueError, Interface.DoesNotExist): pass elif 'vminterface' in request.GET: try: obj.assigned_object = VMInterface.objects.get(pk=request.GET['vminterface']) except (ValueError, VMInterface.DoesNotExist): pass elif 'fhrpgroup' in request.GET: try: obj.assigned_object = FHRPGroup.objects.get(pk=request.GET['fhrpgroup']) except (ValueError, FHRPGroup.DoesNotExist): pass return obj # TODO: Standardize or remove this view class IPAddressAssignView(generic.ObjectView): """ Search for IPAddresses to be assigned to an Interface. """ queryset = IPAddress.objects.all() def dispatch(self, request, *args, **kwargs): # Redirect user if an interface has not been provided if 'interface' not in request.GET and 'vminterface' not in request.GET: return redirect('ipam:ipaddress_add') return super().dispatch(request, *args, **kwargs) def get(self, request): form = forms.IPAddressAssignForm() return render(request, 'ipam/ipaddress_assign.html', { 'form': form, 'return_url': request.GET.get('return_url', ''), }) def post(self, request): form = forms.IPAddressAssignForm(request.POST) table = None if form.is_valid(): addresses = self.queryset.prefetch_related('vrf', 'tenant') # Limit to 100 results addresses = filtersets.IPAddressFilterSet(request.POST, addresses).qs[:100] table = tables.IPAddressAssignTable(addresses) return render(request, 'ipam/ipaddress_assign.html', { 'form': form, 'table': table, 'return_url': request.GET.get('return_url'), }) class IPAddressDeleteView(generic.ObjectDeleteView): queryset = IPAddress.objects.all() class IPAddressBulkCreateView(generic.BulkCreateView): queryset = IPAddress.objects.all() form = forms.IPAddressBulkCreateForm model_form = forms.IPAddressBulkAddForm pattern_target = 'address' template_name = 'ipam/ipaddress_bulk_add.html' class IPAddressBulkImportView(generic.BulkImportView): queryset = IPAddress.objects.all() model_form = forms.IPAddressCSVForm table = tables.IPAddressTable class IPAddressBulkEditView(generic.BulkEditView): queryset = IPAddress.objects.prefetch_related('vrf__tenant', 'tenant') filterset = filtersets.IPAddressFilterSet table = tables.IPAddressTable form = forms.IPAddressBulkEditForm class IPAddressBulkDeleteView(generic.BulkDeleteView): queryset = IPAddress.objects.prefetch_related('vrf__tenant', 'tenant') filterset = filtersets.IPAddressFilterSet table = tables.IPAddressTable # # VLAN groups # class VLANGroupListView(generic.ObjectListView): queryset = VLANGroup.objects.annotate( vlan_count=count_related(VLAN, 'group') ) filterset = filtersets.VLANGroupFilterSet filterset_form = forms.VLANGroupFilterForm table = tables.VLANGroupTable class VLANGroupView(generic.ObjectView): queryset = VLANGroup.objects.all() def get_extra_context(self, request, instance): vlans = VLAN.objects.restrict(request.user, 'view').filter(group=instance).prefetch_related( Prefetch('prefixes', queryset=Prefix.objects.restrict(request.user)) ).order_by('vid') vlans_count = vlans.count() vlans = add_available_vlans(vlans, vlan_group=instance) vlans_table = tables.VLANTable(vlans, user=request.user, exclude=('group',)) if request.user.has_perm('ipam.change_vlan') or request.user.has_perm('ipam.delete_vlan'): vlans_table.columns.show('pk') vlans_table.configure(request) # Compile permissions list for rendering the object table permissions = { 'add': request.user.has_perm('ipam.add_vlan'), 'change': request.user.has_perm('ipam.change_vlan'), 'delete': request.user.has_perm('ipam.delete_vlan'), } return { 'vlans_count': vlans_count, 'vlans_table': vlans_table, 'permissions': permissions, } class VLANGroupEditView(generic.ObjectEditView): queryset = VLANGroup.objects.all() form = forms.VLANGroupForm class VLANGroupDeleteView(generic.ObjectDeleteView): queryset = VLANGroup.objects.all() class VLANGroupBulkImportView(generic.BulkImportView): queryset = VLANGroup.objects.all() model_form = forms.VLANGroupCSVForm table = tables.VLANGroupTable class VLANGroupBulkEditView(generic.BulkEditView): queryset = VLANGroup.objects.annotate( vlan_count=count_related(VLAN, 'group') ) filterset = filtersets.VLANGroupFilterSet table = tables.VLANGroupTable form = forms.VLANGroupBulkEditForm class VLANGroupBulkDeleteView(generic.BulkDeleteView): queryset = VLANGroup.objects.annotate( vlan_count=count_related(VLAN, 'group') ) filterset = filtersets.VLANGroupFilterSet table = tables.VLANGroupTable # # FHRP groups # class FHRPGroupListView(generic.ObjectListView): queryset = FHRPGroup.objects.annotate( member_count=count_related(FHRPGroupAssignment, 'group') ) filterset = filtersets.FHRPGroupFilterSet filterset_form = forms.FHRPGroupFilterForm table = tables.FHRPGroupTable class FHRPGroupView(generic.ObjectView): queryset = FHRPGroup.objects.all() def get_extra_context(self, request, instance): # Get assigned IP addresses ipaddress_table = tables.AssignedIPAddressesTable( data=instance.ip_addresses.restrict(request.user, 'view').prefetch_related('vrf', 'tenant'), orderable=False ) # Get assigned interfaces members_table = tables.FHRPGroupAssignmentTable( data=FHRPGroupAssignment.objects.restrict(request.user, 'view').filter(group=instance), orderable=False ) members_table.columns.hide('group') return { 'ipaddress_table': ipaddress_table, 'members_table': members_table, 'member_count': FHRPGroupAssignment.objects.filter(group=instance).count(), } class FHRPGroupEditView(generic.ObjectEditView): queryset = FHRPGroup.objects.all() form = forms.FHRPGroupForm template_name = 'ipam/fhrpgroup_edit.html' def get_return_url(self, request, obj=None): return_url = super().get_return_url(request, obj) # If we're redirecting the user to the FHRPGroupAssignment creation form, # initialize the group field with the FHRPGroup we just saved. if return_url.startswith(reverse('ipam:fhrpgroupassignment_add')): return_url += f'&group={obj.pk}' return return_url class FHRPGroupDeleteView(generic.ObjectDeleteView): queryset = FHRPGroup.objects.all() class FHRPGroupBulkImportView(generic.BulkImportView): queryset = FHRPGroup.objects.all() model_form = forms.FHRPGroupCSVForm table = tables.FHRPGroupTable class FHRPGroupBulkEditView(generic.BulkEditView): queryset = FHRPGroup.objects.all() filterset = filtersets.FHRPGroupFilterSet table = tables.FHRPGroupTable form = forms.FHRPGroupBulkEditForm class FHRPGroupBulkDeleteView(generic.BulkDeleteView): queryset = FHRPGroup.objects.all() filterset = filtersets.FHRPGroupFilterSet table = tables.FHRPGroupTable # # FHRP group assignments # class FHRPGroupAssignmentEditView(generic.ObjectEditView): queryset = FHRPGroupAssignment.objects.all() form = forms.FHRPGroupAssignmentForm template_name = 'ipam/fhrpgroupassignment_edit.html' def alter_object(self, instance, request, args, kwargs): if not instance.pk: # Assign the interface based on URL kwargs content_type = get_object_or_404(ContentType, pk=request.GET.get('interface_type')) instance.interface = get_object_or_404(content_type.model_class(), pk=request.GET.get('interface_id')) return instance class FHRPGroupAssignmentDeleteView(generic.ObjectDeleteView): queryset = FHRPGroupAssignment.objects.all() # # VLANs # class VLANListView(generic.ObjectListView): queryset = VLAN.objects.all() filterset = filtersets.VLANFilterSet filterset_form = forms.VLANFilterForm table = tables.VLANTable class VLANView(generic.ObjectView): queryset = VLAN.objects.prefetch_related('site__region', 'tenant__group', 'role') def get_extra_context(self, request, instance): prefixes = Prefix.objects.restrict(request.user, 'view').filter(vlan=instance).prefetch_related( 'vrf', 'site', 'role' ) prefix_table = tables.PrefixTable(list(prefixes), exclude=('vlan', 'utilization'), orderable=False) return { 'prefix_table': prefix_table, } class VLANInterfacesView(generic.ObjectChildrenView): queryset = VLAN.objects.all() child_model = Interface table = tables.VLANDevicesTable filterset = InterfaceFilterSet template_name = 'ipam/vlan/interfaces.html' def get_children(self, request, parent): return parent.get_interfaces().restrict(request.user, 'view') def get_extra_context(self, request, instance): return { 'active_tab': 'interfaces', } class VLANVMInterfacesView(generic.ObjectChildrenView): queryset = VLAN.objects.all() child_model = VMInterface table = tables.VLANVirtualMachinesTable filterset = VMInterfaceFilterSet template_name = 'ipam/vlan/vminterfaces.html' def get_children(self, request, parent): return parent.get_vminterfaces().restrict(request.user, 'view') def get_extra_context(self, request, instance): return { 'active_tab': 'vminterfaces', } class VLANEditView(generic.ObjectEditView): queryset = VLAN.objects.all() form = forms.VLANForm template_name = 'ipam/vlan_edit.html' class VLANDeleteView(generic.ObjectDeleteView): queryset = VLAN.objects.all() class VLANBulkImportView(generic.BulkImportView): queryset = VLAN.objects.all() model_form = forms.VLANCSVForm table = tables.VLANTable class VLANBulkEditView(generic.BulkEditView): queryset = VLAN.objects.prefetch_related('site', 'group', 'tenant', 'role') filterset = filtersets.VLANFilterSet table = tables.VLANTable form = forms.VLANBulkEditForm class VLANBulkDeleteView(generic.BulkDeleteView): queryset = VLAN.objects.prefetch_related('site', 'group', 'tenant', 'role') filterset = filtersets.VLANFilterSet table = tables.VLANTable # # Service templates # class ServiceTemplateListView(generic.ObjectListView): queryset = ServiceTemplate.objects.all() filterset = filtersets.ServiceTemplateFilterSet filterset_form = forms.ServiceTemplateFilterForm table = tables.ServiceTemplateTable class ServiceTemplateView(generic.ObjectView): queryset = ServiceTemplate.objects.all() class ServiceTemplateEditView(generic.ObjectEditView): queryset = ServiceTemplate.objects.all() form = forms.ServiceTemplateForm class ServiceTemplateDeleteView(generic.ObjectDeleteView): queryset = ServiceTemplate.objects.all() class ServiceTemplateBulkImportView(generic.BulkImportView): queryset = ServiceTemplate.objects.all() model_form = forms.ServiceTemplateCSVForm table = tables.ServiceTemplateTable class ServiceTemplateBulkEditView(generic.BulkEditView): queryset = ServiceTemplate.objects.all() filterset = filtersets.ServiceTemplateFilterSet table = tables.ServiceTemplateTable form = forms.ServiceTemplateBulkEditForm class ServiceTemplateBulkDeleteView(generic.BulkDeleteView): queryset = ServiceTemplate.objects.all() filterset = filtersets.ServiceTemplateFilterSet table = tables.ServiceTemplateTable # # Services # class ServiceListView(generic.ObjectListView): queryset = Service.objects.all() filterset = filtersets.ServiceFilterSet filterset_form = forms.ServiceFilterForm table = tables.ServiceTable class ServiceView(generic.ObjectView): queryset = Service.objects.prefetch_related('ipaddresses') class ServiceCreateView(generic.ObjectEditView): queryset = Service.objects.all() form = forms.ServiceCreateForm template_name = 'ipam/service_create.html' class ServiceEditView(generic.ObjectEditView): queryset = Service.objects.prefetch_related('ipaddresses') form = forms.ServiceForm template_name = 'ipam/service_edit.html' class ServiceDeleteView(generic.ObjectDeleteView): queryset = Service.objects.all() class ServiceBulkImportView(generic.BulkImportView): queryset = Service.objects.all() model_form = forms.ServiceCSVForm table = tables.ServiceTable class ServiceBulkEditView(generic.BulkEditView): queryset = Service.objects.prefetch_related('device', 'virtual_machine') filterset = filtersets.ServiceFilterSet table = tables.ServiceTable form = forms.ServiceBulkEditForm class ServiceBulkDeleteView(generic.BulkDeleteView): queryset = Service.objects.prefetch_related('device', 'virtual_machine') filterset = filtersets.ServiceFilterSet table = tables.ServiceTable
import collections from datetime import timedelta import functools import gc import json import operator import pickle import re from textwrap import dedent from typing import ( TYPE_CHECKING, Any, Callable, Dict, FrozenSet, Hashable, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) import warnings import weakref import numpy as np from pandas._config import config from pandas._libs import Timestamp, lib from pandas._typing import ( Axis, FilePathOrBuffer, FrameOrSeries, JSONSerializable, Label, Level, Renamer, TimedeltaConvertibleTypes, TimestampConvertibleTypes, ValueKeyFunc, ) from pandas.compat import set_function_name from pandas.compat._optional import import_optional_dependency from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import ( Appender, Substitution, doc, rewrite_axis_style_signature, ) from pandas.util._validators import ( validate_bool_kwarg, validate_fillna_kwargs, validate_percentile, ) from pandas.core.dtypes.common import ( ensure_int64, ensure_object, ensure_str, is_bool, is_bool_dtype, is_datetime64_any_dtype, is_datetime64tz_dtype, is_dict_like, is_extension_array_dtype, is_float, is_list_like, is_number, is_numeric_dtype, is_object_dtype, is_re_compilable, is_scalar, is_timedelta64_dtype, pandas_dtype, ) from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries from pandas.core.dtypes.inference import is_hashable from pandas.core.dtypes.missing import isna, notna import pandas as pd from pandas.core import missing, nanops import pandas.core.algorithms as algos from pandas.core.base import PandasObject, SelectionMixin import pandas.core.common as com from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.indexes.api import ( Index, InvalidIndexError, MultiIndex, RangeIndex, ensure_index, ) from pandas.core.indexes.datetimes import DatetimeIndex from pandas.core.indexes.period import Period, PeriodIndex import pandas.core.indexing as indexing from pandas.core.internals import BlockManager from pandas.core.missing import find_valid_index from pandas.core.ops import _align_method_FRAME from pandas.io.formats import format as fmt from pandas.io.formats.format import DataFrameFormatter, format_percentiles from pandas.io.formats.printing import pprint_thing from pandas.tseries.frequencies import to_offset from pandas.tseries.offsets import Tick if TYPE_CHECKING: from pandas.core.resample import Resampler # goal is to be able to define the docs close to function, while still being # able to share _shared_docs: Dict[str, str] = dict() _shared_doc_kwargs = dict( axes="keywords for axes", klass="Series/DataFrame", axes_single_arg="int or labels for object", args_transpose="axes to permute (int or label for object)", optional_by=""" by : str or list of str Name or list of names to sort by""", ) def _single_replace(self, to_replace, method, inplace, limit): """ Replaces values in a Series using the fill method specified when no replacement value is given in the replace method """ if self.ndim != 1: raise TypeError( f"cannot replace {to_replace} with method {method} on a " f"{type(self).__name__}" ) orig_dtype = self.dtype result = self if inplace else self.copy() fill_f = missing.get_fill_func(method) mask = missing.mask_missing(result.values, to_replace) values = fill_f(result.values, limit=limit, mask=mask) if values.dtype == orig_dtype and inplace: return result = pd.Series(values, index=self.index, dtype=self.dtype).__finalize__(self) if inplace: self._update_inplace(result) return return result bool_t = bool # Need alias because NDFrame has def bool: class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin): """ N-dimensional analogue of DataFrame. Store multi-dimensional in a size-mutable, labeled data structure Parameters ---------- data : BlockManager axes : list copy : bool, default False """ _internal_names: List[str] = [ "_mgr", "_cacher", "_item_cache", "_cache", "_is_copy", "_subtyp", "_name", "_index", "_default_kind", "_default_fill_value", "_metadata", "__array_struct__", "__array_interface__", ] _internal_names_set: Set[str] = set(_internal_names) _accessors: Set[str] = set() _deprecations: FrozenSet[str] = frozenset(["get_values"]) _metadata: List[str] = [] _is_copy = None _mgr: BlockManager _attrs: Dict[Optional[Hashable], Any] _typ: str # ---------------------------------------------------------------------- # Constructors def __init__( self, data: BlockManager, copy: bool = False, attrs: Optional[Mapping[Optional[Hashable], Any]] = None, ): # copy kwarg is retained for mypy compat, is not used object.__setattr__(self, "_is_copy", None) object.__setattr__(self, "_mgr", data) object.__setattr__(self, "_item_cache", {}) if attrs is None: attrs = {} else: attrs = dict(attrs) object.__setattr__(self, "_attrs", attrs) @classmethod def _init_mgr(cls, mgr, axes, dtype=None, copy: bool = False) -> BlockManager: """ passed a manager and a axes dict """ for a, axe in axes.items(): if axe is not None: axe = ensure_index(axe) bm_axis = cls._get_block_manager_axis(a) mgr = mgr.reindex_axis(axe, axis=bm_axis, copy=False) # make a copy if explicitly requested if copy: mgr = mgr.copy() if dtype is not None: # avoid further copies if we can if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype: mgr = mgr.astype(dtype=dtype) return mgr # ---------------------------------------------------------------------- @property def attrs(self) -> Dict[Optional[Hashable], Any]: """ Dictionary of global attributes on this object. .. warning:: attrs is experimental and may change without warning. """ if self._attrs is None: self._attrs = {} return self._attrs @attrs.setter def attrs(self, value: Mapping[Optional[Hashable], Any]) -> None: self._attrs = dict(value) @classmethod def _validate_dtype(cls, dtype): """ validate the passed dtype """ if dtype is not None: dtype = pandas_dtype(dtype) # a compound dtype if dtype.kind == "V": raise NotImplementedError( "compound dtypes are not implemented " f"in the {cls.__name__} constructor" ) return dtype # ---------------------------------------------------------------------- # Construction @property def _constructor(self: FrameOrSeries) -> Type[FrameOrSeries]: """ Used when a manipulation result has the same dimensions as the original. """ raise AbstractMethodError(self) @property def _constructor_sliced(self): """ Used when a manipulation result has one lower dimension(s) as the original, such as DataFrame single columns slicing. """ raise AbstractMethodError(self) @property def _constructor_expanddim(self): """ Used when a manipulation result has one higher dimension as the original, such as Series.to_frame() """ raise NotImplementedError # ---------------------------------------------------------------------- # Internals @property def _data(self): # GH#33054 retained because some downstream packages uses this, # e.g. fastparquet return self._mgr # ---------------------------------------------------------------------- # Axis _stat_axis_number = 0 _stat_axis_name = "index" _ix = None _AXIS_ORDERS: List[str] _AXIS_TO_AXIS_NUMBER: Dict[Axis, int] = {0: 0, "index": 0, "rows": 0} _AXIS_REVERSED: bool _info_axis_number: int _info_axis_name: str _AXIS_LEN: int @property def _AXIS_NUMBERS(self) -> Dict[str, int]: """.. deprecated:: 1.1.0""" warnings.warn( "_AXIS_NUMBERS has been deprecated.", FutureWarning, stacklevel=3, ) return {"index": 0} @property def _AXIS_NAMES(self) -> Dict[int, str]: """.. deprecated:: 1.1.0""" warnings.warn( "_AXIS_NAMES has been deprecated.", FutureWarning, stacklevel=3, ) return {0: "index"} def _construct_axes_dict(self, axes=None, **kwargs): """Return an axes dictionary for myself.""" d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)} d.update(kwargs) return d @classmethod def _construct_axes_from_arguments( cls, args, kwargs, require_all: bool = False, sentinel=None ): """ Construct and returns axes if supplied in args/kwargs. If require_all, raise if all axis arguments are not supplied return a tuple of (axes, kwargs). sentinel specifies the default parameter when an axis is not supplied; useful to distinguish when a user explicitly passes None in scenarios where None has special meaning. """ # construct the args args = list(args) for a in cls._AXIS_ORDERS: # look for a argument by position if a not in kwargs: try: kwargs[a] = args.pop(0) except IndexError as err: if require_all: raise TypeError( "not enough/duplicate arguments specified!" ) from err axes = {a: kwargs.pop(a, sentinel) for a in cls._AXIS_ORDERS} return axes, kwargs @classmethod def _get_axis_number(cls, axis: Axis) -> int: try: return cls._AXIS_TO_AXIS_NUMBER[axis] except KeyError: raise ValueError(f"No axis named {axis} for object type {cls.__name__}") @classmethod def _get_axis_name(cls, axis: Axis) -> str: axis_number = cls._get_axis_number(axis) return cls._AXIS_ORDERS[axis_number] def _get_axis(self, axis: Axis) -> Index: axis_number = self._get_axis_number(axis) assert axis_number in {0, 1} return self.index if axis_number == 0 else self.columns @classmethod def _get_block_manager_axis(cls, axis: Axis) -> int: """Map the axis to the block_manager axis.""" axis = cls._get_axis_number(axis) if cls._AXIS_REVERSED: m = cls._AXIS_LEN - 1 return m - axis return axis def _get_axis_resolvers(self, axis: str) -> Dict[str, ABCSeries]: # index or columns axis_index = getattr(self, axis) d = dict() prefix = axis[0] for i, name in enumerate(axis_index.names): if name is not None: key = level = name else: # prefix with 'i' or 'c' depending on the input axis # e.g., you must do ilevel_0 for the 0th level of an unnamed # multiiindex key = f"{prefix}level_{i}" level = i level_values = axis_index.get_level_values(level) s = level_values.to_series() s.index = axis_index d[key] = s # put the index/columns itself in the dict if isinstance(axis_index, MultiIndex): dindex = axis_index else: dindex = axis_index.to_series() d[axis] = dindex return d def _get_index_resolvers(self) -> Dict[str, ABCSeries]: from pandas.core.computation.parsing import clean_column_name d: Dict[str, ABCSeries] = {} for axis_name in self._AXIS_ORDERS: d.update(self._get_axis_resolvers(axis_name)) return {clean_column_name(k): v for k, v in d.items() if not isinstance(k, int)} def _get_cleaned_column_resolvers(self) -> Dict[str, ABCSeries]: """ Return the special character free column resolvers of a dataframe. Column names with special characters are 'cleaned up' so that they can be referred to by backtick quoting. Used in :meth:`DataFrame.eval`. """ from pandas.core.computation.parsing import clean_column_name if isinstance(self, ABCSeries): return {clean_column_name(self.name): self} return { clean_column_name(k): v for k, v in self.items() if not isinstance(k, int) } @property def _info_axis(self) -> Index: return getattr(self, self._info_axis_name) @property def _stat_axis(self) -> Index: return getattr(self, self._stat_axis_name) @property def shape(self) -> Tuple[int, ...]: """ Return a tuple of axis dimensions """ return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS) @property def axes(self) -> List[Index]: """ Return index label(s) of the internal NDFrame """ # we do it this way because if we have reversed axes, then # the block manager shows then reversed return [self._get_axis(a) for a in self._AXIS_ORDERS] @property def ndim(self) -> int: """ Return an int representing the number of axes / array dimensions. Return 1 if Series. Otherwise return 2 if DataFrame. See Also -------- ndarray.ndim : Number of array dimensions. Examples -------- >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3}) >>> s.ndim 1 >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}) >>> df.ndim 2 """ return self._mgr.ndim @property def size(self) -> int: """ Return an int representing the number of elements in this object. Return the number of rows if Series. Otherwise return the number of rows times number of columns if DataFrame. See Also -------- ndarray.size : Number of elements in the array. Examples -------- >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3}) >>> s.size 3 >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}) >>> df.size 4 """ return np.prod(self.shape) @property def _selected_obj(self: FrameOrSeries) -> FrameOrSeries: """ internal compat with SelectionMixin """ return self @property def _obj_with_exclusions(self: FrameOrSeries) -> FrameOrSeries: """ internal compat with SelectionMixin """ return self def set_axis(self, labels, axis: Axis = 0, inplace: bool = False): """ Assign desired index to given axis. Indexes for%(extended_summary_sub)s row labels can be changed by assigning a list-like or Index. Parameters ---------- labels : list-like, Index The values for the new index. axis : %(axes_single_arg)s, default 0 The axis to update. The value 0 identifies the rows%(axis_description_sub)s. inplace : bool, default False Whether to return a new %(klass)s instance. Returns ------- renamed : %(klass)s or None An object of type %(klass)s if inplace=False, None otherwise. See Also -------- %(klass)s.rename_axis : Alter the name of the index%(see_also_sub)s. """ if inplace: setattr(self, self._get_axis_name(axis), labels) else: obj = self.copy() obj.set_axis(labels, axis=axis, inplace=True) return obj def _set_axis(self, axis: int, labels: Index) -> None: labels = ensure_index(labels) self._mgr.set_axis(axis, labels) self._clear_item_cache() def swapaxes(self: FrameOrSeries, axis1, axis2, copy=True) -> FrameOrSeries: """ Interchange axes and swap values axes appropriately. Returns ------- y : same as input """ i = self._get_axis_number(axis1) j = self._get_axis_number(axis2) if i == j: if copy: return self.copy() return self mapping = {i: j, j: i} new_axes = (self._get_axis(mapping.get(k, k)) for k in range(self._AXIS_LEN)) new_values = self.values.swapaxes(i, j) if copy: new_values = new_values.copy() # ignore needed because of NDFrame constructor is different than # DataFrame/Series constructors. return self._constructor(new_values, *new_axes).__finalize__( # type: ignore self, method="swapaxes" ) def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries: """ Return DataFrame with requested index / column level(s) removed. .. versionadded:: 0.24.0 Parameters ---------- level : int, str, or list-like If a string is given, must be the name of a level If list-like, elements must be names or positional indexes of levels. axis : {0 or 'index', 1 or 'columns'}, default 0 Axis along which the level(s) is removed: * 0 or 'index': remove level(s) in column. * 1 or 'columns': remove level(s) in row. Returns ------- DataFrame DataFrame with requested index / column level(s) removed. Examples -------- >>> df = pd.DataFrame([ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12] ... ]).set_index([0, 1]).rename_axis(['a', 'b']) >>> df.columns = pd.MultiIndex.from_tuples([ ... ('c', 'e'), ('d', 'f') ... ], names=['level_1', 'level_2']) >>> df level_1 c d level_2 e f a b 1 2 3 4 5 6 7 8 9 10 11 12 >>> df.droplevel('a') level_1 c d level_2 e f b 2 3 4 6 7 8 10 11 12 >>> df.droplevel('level_2', axis=1) level_1 c d a b 1 2 3 4 5 6 7 8 9 10 11 12 """ labels = self._get_axis(axis) new_labels = labels.droplevel(level) result = self.set_axis(new_labels, axis=axis, inplace=False) return result def pop(self: FrameOrSeries, item) -> FrameOrSeries: """ Return item and drop from frame. Raise KeyError if not found. Parameters ---------- item : str Label of column to be popped. Returns ------- Series Examples -------- >>> df = pd.DataFrame([('falcon', 'bird', 389.0), ... ('parrot', 'bird', 24.0), ... ('lion', 'mammal', 80.5), ... ('monkey', 'mammal', np.nan)], ... columns=('name', 'class', 'max_speed')) >>> df name class max_speed 0 falcon bird 389.0 1 parrot bird 24.0 2 lion mammal 80.5 3 monkey mammal NaN >>> df.pop('class') 0 bird 1 bird 2 mammal 3 mammal Name: class, dtype: object >>> df name max_speed 0 falcon 389.0 1 parrot 24.0 2 lion 80.5 3 monkey NaN """ result = self[item] del self[item] if self.ndim == 2: result._reset_cacher() return result def squeeze(self, axis=None): """ Squeeze 1 dimensional axis objects into scalars. Series or DataFrames with a single element are squeezed to a scalar. DataFrames with a single column or a single row are squeezed to a Series. Otherwise the object is unchanged. This method is most useful when you don't know if your object is a Series or DataFrame, but you do know it has just a single column. In that case you can safely call `squeeze` to ensure you have a Series. Parameters ---------- axis : {0 or 'index', 1 or 'columns', None}, default None A specific axis to squeeze. By default, all length-1 axes are squeezed. Returns ------- DataFrame, Series, or scalar The projection after squeezing `axis` or all the axes. See Also -------- Series.iloc : Integer-location based indexing for selecting scalars. DataFrame.iloc : Integer-location based indexing for selecting Series. Series.to_frame : Inverse of DataFrame.squeeze for a single-column DataFrame. Examples -------- >>> primes = pd.Series([2, 3, 5, 7]) Slicing might produce a Series with a single value: >>> even_primes = primes[primes % 2 == 0] >>> even_primes 0 2 dtype: int64 >>> even_primes.squeeze() 2 Squeezing objects with more than one value in every axis does nothing: >>> odd_primes = primes[primes % 2 == 1] >>> odd_primes 1 3 2 5 3 7 dtype: int64 >>> odd_primes.squeeze() 1 3 2 5 3 7 dtype: int64 Squeezing is even more effective when used with DataFrames. >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) >>> df a b 0 1 2 1 3 4 Slicing a single column will produce a DataFrame with the columns having only one value: >>> df_a = df[['a']] >>> df_a a 0 1 1 3 So the columns can be squeezed down, resulting in a Series: >>> df_a.squeeze('columns') 0 1 1 3 Name: a, dtype: int64 Slicing a single row from a single column will produce a single scalar DataFrame: >>> df_0a = df.loc[df.index < 1, ['a']] >>> df_0a a 0 1 Squeezing the rows produces a single scalar Series: >>> df_0a.squeeze('rows') a 1 Name: 0, dtype: int64 Squeezing all axes will project directly into a scalar: >>> df_0a.squeeze() 1 """ axis = range(self._AXIS_LEN) if axis is None else (self._get_axis_number(axis),) return self.iloc[ tuple( 0 if i in axis and len(a) == 1 else slice(None) for i, a in enumerate(self.axes) ) ] # ---------------------------------------------------------------------- # Rename def rename( self: FrameOrSeries, mapper: Optional[Renamer] = None, *, index: Optional[Renamer] = None, columns: Optional[Renamer] = None, axis: Optional[Axis] = None, copy: bool = True, inplace: bool = False, level: Optional[Level] = None, errors: str = "ignore", ) -> Optional[FrameOrSeries]: """ Alter axes input function or functions. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don't throw an error. Alternatively, change ``Series.name`` with a scalar value (Series only). Parameters ---------- %(axes)s : scalar, list-like, dict-like or function, optional Scalar or list-like will alter the ``Series.name`` attribute, and raise on DataFrame. dict-like or functions are transformations to apply to that axis' values copy : bool, default True Also copy underlying data. inplace : bool, default False Whether to return a new %(klass)s. If True then value of copy is ignored. level : int or level name, default None In case of a MultiIndex, only rename labels in the specified level. errors : {'ignore', 'raise'}, default 'ignore' If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`, or `columns` contains labels that are not present in the Index being transformed. If 'ignore', existing keys will be renamed and extra keys will be ignored. Returns ------- renamed : %(klass)s (new object) Raises ------ KeyError If any of the labels is not found in the selected axis and "errors='raise'". See Also -------- NDFrame.rename_axis Examples -------- >>> s = pd.Series([1, 2, 3]) >>> s 0 1 1 2 2 3 dtype: int64 >>> s.rename("my_name") # scalar, changes Series.name 0 1 1 2 2 3 Name: my_name, dtype: int64 >>> s.rename(lambda x: x ** 2) # function, changes labels 0 1 1 2 4 3 dtype: int64 >>> s.rename({1: 3, 2: 5}) # mapping, changes labels 0 1 3 2 5 3 dtype: int64 Since ``DataFrame`` doesn't have a ``.name`` attribute, only mapping-type arguments are allowed. >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) >>> df.rename(2) Traceback (most recent call last): ... TypeError: 'int' object is not callable ``DataFrame.rename`` supports two calling conventions * ``(index=index_mapper, columns=columns_mapper, ...)`` * ``(mapper, axis={'index', 'columns'}, ...)`` We *highly* recommend using keyword arguments to clarify your intent. >>> df.rename(index=str, columns={"A": "a", "B": "c"}) a c 0 1 4 1 2 5 2 3 6 >>> df.rename(index=str, columns={"A": "a", "C": "c"}) a B 0 1 4 1 2 5 2 3 6 Using axis-style parameters >>> df.rename(str.lower, axis='columns') a b 0 1 4 1 2 5 2 3 6 >>> df.rename({1: 2, 2: 4}, axis='index') A B 0 1 4 2 2 5 4 3 6 See the :ref:`user guide <basics.rename>` for more. """ if mapper is None and index is None and columns is None: raise TypeError("must pass an index to rename") if index is not None or columns is not None: if axis is not None: raise TypeError( "Cannot specify both 'axis' and any of 'index' or 'columns'" ) elif mapper is not None: raise TypeError( "Cannot specify both 'mapper' and any of 'index' or 'columns'" ) else: # use the mapper argument if axis and self._get_axis_number(axis) == 1: columns = mapper else: index = mapper result = self if inplace else self.copy(deep=copy) for axis_no, replacements in enumerate((index, columns)): if replacements is None: continue ax = self._get_axis(axis_no) f = com.get_rename_function(replacements) if level is not None: level = ax._get_level_number(level) # GH 13473 if not callable(replacements): indexer = ax.get_indexer_for(replacements) if errors == "raise" and len(indexer[indexer == -1]): missing_labels = [ label for index, label in enumerate(replacements) if indexer[index] == -1 ] raise KeyError(f"{missing_labels} not found in axis") new_index = ax._transform_index(f, level) result.set_axis(new_index, axis=axis_no, inplace=True) result._clear_item_cache() if inplace: self._update_inplace(result) return None else: return result.__finalize__(self, method="rename") @rewrite_axis_style_signature("mapper", [("copy", True), ("inplace", False)]) def rename_axis(self, mapper=lib.no_default, **kwargs): """ Set the name of the axis for the index or columns. Parameters ---------- mapper : scalar, list-like, optional Value to set the axis name attribute. index, columns : scalar, list-like, dict-like or function, optional A scalar, list-like, dict-like or functions transformations to apply to that axis' values. Note that the ``columns`` parameter is not allowed if the object is a Series. This parameter only apply for DataFrame type objects. Use either ``mapper`` and ``axis`` to specify the axis to target with ``mapper``, or ``index`` and/or ``columns``. .. versionchanged:: 0.24.0 axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to rename. copy : bool, default True Also copy underlying data. inplace : bool, default False Modifies the object directly, instead of creating a new Series or DataFrame. Returns ------- Series, DataFrame, or None The same type as the caller or None if `inplace` is True. See Also -------- Series.rename : Alter Series index labels or name. DataFrame.rename : Alter DataFrame index labels or name. Index.rename : Set new names on index. Notes ----- ``DataFrame.rename_axis`` supports two calling conventions * ``(index=index_mapper, columns=columns_mapper, ...)`` * ``(mapper, axis={'index', 'columns'}, ...)`` The first calling convention will only modify the names of the index and/or the names of the Index object that is the columns. In this case, the parameter ``copy`` is ignored. The second calling convention will modify the names of the the corresponding index if mapper is a list or a scalar. However, if mapper is dict-like or a function, it will use the deprecated behavior of modifying the axis *labels*. We *highly* recommend using keyword arguments to clarify your intent. Examples -------- **Series** >>> s = pd.Series(["dog", "cat", "monkey"]) >>> s 0 dog 1 cat 2 monkey dtype: object >>> s.rename_axis("animal") animal 0 dog 1 cat 2 monkey dtype: object **DataFrame** >>> df = pd.DataFrame({"num_legs": [4, 4, 2], ... "num_arms": [0, 0, 2]}, ... ["dog", "cat", "monkey"]) >>> df num_legs num_arms dog 4 0 cat 4 0 monkey 2 2 >>> df = df.rename_axis("animal") >>> df num_legs num_arms animal dog 4 0 cat 4 0 monkey 2 2 >>> df = df.rename_axis("limbs", axis="columns") >>> df limbs num_legs num_arms animal dog 4 0 cat 4 0 monkey 2 2 **MultiIndex** >>> df.index = pd.MultiIndex.from_product([['mammal'], ... ['dog', 'cat', 'monkey']], ... names=['type', 'name']) >>> df limbs num_legs num_arms type name mammal dog 4 0 cat 4 0 monkey 2 2 >>> df.rename_axis(index={'type': 'class'}) limbs num_legs num_arms class name mammal dog 4 0 cat 4 0 monkey 2 2 >>> df.rename_axis(columns=str.upper) LIMBS num_legs num_arms type name mammal dog 4 0 cat 4 0 monkey 2 2 """ axes, kwargs = self._construct_axes_from_arguments( (), kwargs, sentinel=lib.no_default ) copy = kwargs.pop("copy", True) inplace = kwargs.pop("inplace", False) axis = kwargs.pop("axis", 0) if axis is not None: axis = self._get_axis_number(axis) if kwargs: raise TypeError( "rename_axis() got an unexpected keyword " f'argument "{list(kwargs.keys())[0]}"' ) inplace = validate_bool_kwarg(inplace, "inplace") if mapper is not lib.no_default: # Use v0.23 behavior if a scalar or list non_mapper = is_scalar(mapper) or ( is_list_like(mapper) and not is_dict_like(mapper) ) if non_mapper: return self._set_axis_name(mapper, axis=axis, inplace=inplace) else: raise ValueError("Use `.rename` to alter labels with a mapper.") else: # Use new behavior. Means that index and/or columns # is specified result = self if inplace else self.copy(deep=copy) for axis in range(self._AXIS_LEN): v = axes.get(self._get_axis_name(axis)) if v is lib.no_default: continue non_mapper = is_scalar(v) or (is_list_like(v) and not is_dict_like(v)) if non_mapper: newnames = v else: f = com.get_rename_function(v) curnames = self._get_axis(axis).names newnames = [f(name) for name in curnames] result._set_axis_name(newnames, axis=axis, inplace=True) if not inplace: return result def _set_axis_name(self, name, axis=0, inplace=False): """ Set the name(s) of the axis. Parameters ---------- name : str or list of str Name(s) to set. axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to set the label. The value 0 or 'index' specifies index, and the value 1 or 'columns' specifies columns. inplace : bool, default False If `True`, do operation inplace and return None. Returns ------- Series, DataFrame, or None The same type as the caller or `None` if `inplace` is `True`. See Also -------- DataFrame.rename : Alter the axis labels of :class:`DataFrame`. Series.rename : Alter the index labels or set the index name of :class:`Series`. Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`. Examples -------- >>> df = pd.DataFrame({"num_legs": [4, 4, 2]}, ... ["dog", "cat", "monkey"]) >>> df num_legs dog 4 cat 4 monkey 2 >>> df._set_axis_name("animal") num_legs animal dog 4 cat 4 monkey 2 >>> df.index = pd.MultiIndex.from_product( ... [["mammal"], ['dog', 'cat', 'monkey']]) >>> df._set_axis_name(["type", "name"]) num_legs type name mammal dog 4 cat 4 monkey 2 """ axis = self._get_axis_number(axis) idx = self._get_axis(axis).set_names(name) inplace = validate_bool_kwarg(inplace, "inplace") renamed = self if inplace else self.copy() renamed.set_axis(idx, axis=axis, inplace=True) if not inplace: return renamed # ---------------------------------------------------------------------- # Comparison Methods def _indexed_same(self, other) -> bool: return all( self._get_axis(a).equals(other._get_axis(a)) for a in self._AXIS_ORDERS ) def equals(self, other): """ Test whether two objects contain the same elements. This function allows two Series or DataFrames to be compared against each other to see if they have the same shape and elements. NaNs in the same location are considered equal. The column headers do not need to have the same type, but the elements within the columns must be the same dtype. Parameters ---------- other : Series or DataFrame The other Series or DataFrame to be compared with the first. Returns ------- bool True if all elements are the same in both objects, False otherwise. See Also -------- Series.eq : Compare two Series objects of the same length and return a Series where each element is True if the element in each Series is equal, False otherwise. DataFrame.eq : Compare two DataFrame objects of the same shape and return a DataFrame where each element is True if the respective element in each DataFrame is equal, False otherwise. testing.assert_series_equal : Raises an AssertionError if left and right are not equal. Provides an easy interface to ignore inequality in dtypes, indexes and precision among others. testing.assert_frame_equal : Like assert_series_equal, but targets DataFrames. numpy.array_equal : Return True if two arrays have the same shape and elements, False otherwise. Notes ----- This function requires that the elements have the same dtype as their respective elements in the other Series or DataFrame. However, the column labels do not need to have the same type, as long as they are still considered equal. Examples -------- >>> df = pd.DataFrame({1: [10], 2: [20]}) >>> df 1 2 0 10 20 DataFrames df and exactly_equal have the same types and values for their elements and column labels, which will return True. >>> exactly_equal = pd.DataFrame({1: [10], 2: [20]}) >>> exactly_equal 1 2 0 10 20 >>> df.equals(exactly_equal) True DataFrames df and different_column_type have the same element types and values, but have different types for the column labels, which will still return True. >>> different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]}) >>> different_column_type 1.0 2.0 0 10 20 >>> df.equals(different_column_type) True DataFrames df and different_data_type have different types for the same values for their elements, and will return False even though their column labels are the same values and types. >>> different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]}) >>> different_data_type 1 2 0 10.0 20.0 >>> df.equals(different_data_type) False """ if not isinstance(other, self._constructor): return False return self._mgr.equals(other._mgr) # ------------------------------------------------------------------------- # Unary Methods def __neg__(self): values = self._values if is_bool_dtype(values): arr = operator.inv(values) elif ( is_numeric_dtype(values) or is_timedelta64_dtype(values) or is_object_dtype(values) ): arr = operator.neg(values) else: raise TypeError(f"Unary negative expects numeric dtype, not {values.dtype}") return self.__array_wrap__(arr) def __pos__(self): values = self._values if is_bool_dtype(values): arr = values elif ( is_numeric_dtype(values) or is_timedelta64_dtype(values) or is_object_dtype(values) ): arr = operator.pos(values) else: raise TypeError(f"Unary plus expects numeric dtype, not {values.dtype}") return self.__array_wrap__(arr) def __invert__(self): if not self.size: # inv fails with 0 len return self new_data = self._mgr.apply(operator.invert) result = self._constructor(new_data).__finalize__(self, method="__invert__") return result def __nonzero__(self): raise ValueError( f"The truth value of a {type(self).__name__} is ambiguous. " "Use a.empty, a.bool(), a.item(), a.any() or a.all()." ) __bool__ = __nonzero__ def bool(self): """ Return the bool of a single element PandasObject. This must be a boolean scalar value, either True or False. Raise a ValueError if the PandasObject does not have exactly 1 element, or that element is not boolean Returns ------- bool Same single boolean value converted to bool type. """ v = self.squeeze() if isinstance(v, (bool, np.bool_)): return bool(v) elif is_scalar(v): raise ValueError( "bool cannot act on a non-boolean single element " f"{type(self).__name__}" ) self.__nonzero__() def __abs__(self: FrameOrSeries) -> FrameOrSeries: return self.abs() def __round__(self: FrameOrSeries, decimals: int = 0) -> FrameOrSeries: return self.round(decimals) # ------------------------------------------------------------------------- # Label or Level Combination Helpers # # A collection of helper methods for DataFrame/Series operations that # accept a combination of column/index labels and levels. All such # operations should utilize/extend these methods when possible so that we # have consistent precedence and validation logic throughout the library. def _is_level_reference(self, key, axis=0): """ Test whether a key is a level reference for a given axis. To be considered a level reference, `key` must be a string that: - (axis=0): Matches the name of an index level and does NOT match a column label. - (axis=1): Matches the name of a column level and does NOT match an index label. Parameters ---------- key : str Potential level name for the given axis axis : int, default 0 Axis that levels are associated with (0 for index, 1 for columns) Returns ------- is_level : bool """ axis = self._get_axis_number(axis) return ( key is not None and is_hashable(key) and key in self.axes[axis].names and not self._is_label_reference(key, axis=axis) ) def _is_label_reference(self, key, axis=0) -> bool_t: """ Test whether a key is a label reference for a given axis. To be considered a label reference, `key` must be a string that: - (axis=0): Matches a column label - (axis=1): Matches an index label Parameters ---------- key: str Potential label name axis: int, default 0 Axis perpendicular to the axis that labels are associated with (0 means search for column labels, 1 means search for index labels) Returns ------- is_label: bool """ axis = self._get_axis_number(axis) other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis) return ( key is not None and is_hashable(key) and any(key in self.axes[ax] for ax in other_axes) ) def _is_label_or_level_reference(self, key: str, axis: int = 0) -> bool_t: """ Test whether a key is a label or level reference for a given axis. To be considered either a label or a level reference, `key` must be a string that: - (axis=0): Matches a column label or an index level - (axis=1): Matches an index label or a column level Parameters ---------- key: str Potential label or level name axis: int, default 0 Axis that levels are associated with (0 for index, 1 for columns) Returns ------- is_label_or_level: bool """ return self._is_level_reference(key, axis=axis) or self._is_label_reference( key, axis=axis ) def _check_label_or_level_ambiguity(self, key, axis: int = 0) -> None: """ Check whether `key` is ambiguous. By ambiguous, we mean that it matches both a level of the input `axis` and a label of the other axis. Parameters ---------- key: str or object Label or level name. axis: int, default 0 Axis that levels are associated with (0 for index, 1 for columns). Raises ------ ValueError: `key` is ambiguous """ axis = self._get_axis_number(axis) other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis) if ( key is not None and is_hashable(key) and key in self.axes[axis].names and any(key in self.axes[ax] for ax in other_axes) ): # Build an informative and grammatical warning level_article, level_type = ( ("an", "index") if axis == 0 else ("a", "column") ) label_article, label_type = ( ("a", "column") if axis == 0 else ("an", "index") ) msg = ( f"'{key}' is both {level_article} {level_type} level and " f"{label_article} {label_type} label, which is ambiguous." ) raise ValueError(msg) def _get_label_or_level_values(self, key: str, axis: int = 0) -> np.ndarray: """ Return a 1-D array of values associated with `key`, a label or level from the given `axis`. Retrieval logic: - (axis=0): Return column values if `key` matches a column label. Otherwise return index level values if `key` matches an index level. - (axis=1): Return row values if `key` matches an index label. Otherwise return column level values if 'key' matches a column level Parameters ---------- key: str Label or level name. axis: int, default 0 Axis that levels are associated with (0 for index, 1 for columns) Returns ------- values: np.ndarray Raises ------ KeyError if `key` matches neither a label nor a level ValueError if `key` matches multiple labels FutureWarning if `key` is ambiguous. This will become an ambiguity error in a future version """ axis = self._get_axis_number(axis) other_axes = [ax for ax in range(self._AXIS_LEN) if ax != axis] if self._is_label_reference(key, axis=axis): self._check_label_or_level_ambiguity(key, axis=axis) values = self.xs(key, axis=other_axes[0])._values elif self._is_level_reference(key, axis=axis): values = self.axes[axis].get_level_values(key)._values else: raise KeyError(key) # Check for duplicates if values.ndim > 1: if other_axes and isinstance(self._get_axis(other_axes[0]), MultiIndex): multi_message = ( "\n" "For a multi-index, the label must be a " "tuple with elements corresponding to each level." ) else: multi_message = "" label_axis_name = "column" if axis == 0 else "index" raise ValueError( ( f"The {label_axis_name} label '{key}' " f"is not unique.{multi_message}" ) ) return values def _drop_labels_or_levels(self, keys, axis: int = 0): """ Drop labels and/or levels for the given `axis`. For each key in `keys`: - (axis=0): If key matches a column label then drop the column. Otherwise if key matches an index level then drop the level. - (axis=1): If key matches an index label then drop the row. Otherwise if key matches a column level then drop the level. Parameters ---------- keys: str or list of str labels or levels to drop axis: int, default 0 Axis that levels are associated with (0 for index, 1 for columns) Returns ------- dropped: DataFrame Raises ------ ValueError if any `keys` match neither a label nor a level """ axis = self._get_axis_number(axis) # Validate keys keys = com.maybe_make_list(keys) invalid_keys = [ k for k in keys if not self._is_label_or_level_reference(k, axis=axis) ] if invalid_keys: raise ValueError( ( "The following keys are not valid labels or " f"levels for axis {axis}: {invalid_keys}" ) ) # Compute levels and labels to drop levels_to_drop = [k for k in keys if self._is_level_reference(k, axis=axis)] labels_to_drop = [k for k in keys if not self._is_level_reference(k, axis=axis)] # Perform copy upfront and then use inplace operations below. # This ensures that we always perform exactly one copy. # ``copy`` and/or ``inplace`` options could be added in the future. dropped = self.copy() if axis == 0: # Handle dropping index levels if levels_to_drop: dropped.reset_index(levels_to_drop, drop=True, inplace=True) # Handle dropping columns labels if labels_to_drop: dropped.drop(labels_to_drop, axis=1, inplace=True) else: # Handle dropping column levels if levels_to_drop: if isinstance(dropped.columns, MultiIndex): # Drop the specified levels from the MultiIndex dropped.columns = dropped.columns.droplevel(levels_to_drop) else: # Drop the last level of Index by replacing with # a RangeIndex dropped.columns = RangeIndex(dropped.columns.size) # Handle dropping index labels if labels_to_drop: dropped.drop(labels_to_drop, axis=0, inplace=True) return dropped # ---------------------------------------------------------------------- # Iteration def __hash__(self): raise TypeError( f"{repr(type(self).__name__)} objects are mutable, " f"thus they cannot be hashed" ) def __iter__(self): """ Iterate over info axis. Returns ------- iterator Info axis as iterator. """ return iter(self._info_axis) # can we get a better explanation of this? def keys(self): """ Get the 'info axis' (see Indexing for more). This is index for Series, columns for DataFrame. Returns ------- Index Info axis. """ return self._info_axis def items(self): """ Iterate over (label, values) on info axis This is index for Series and columns for DataFrame. Returns ------- Generator """ for h in self._info_axis: yield h, self[h] @doc(items) def iteritems(self): return self.items() def __len__(self) -> int: """Returns length of info axis""" return len(self._info_axis) def __contains__(self, key) -> bool_t: """True if the key is in the info axis""" return key in self._info_axis @property def empty(self) -> bool_t: """ Indicator whether DataFrame is empty. True if DataFrame is entirely empty (no items), meaning any of the axes are of length 0. Returns ------- bool If DataFrame is empty, return True, if not return False. See Also -------- Series.dropna : Return series without null values. DataFrame.dropna : Return DataFrame with labels on given axis omitted where (all or any) data are missing. Notes ----- If DataFrame contains only NaNs, it is still not considered empty. See the example below. Examples -------- An example of an actual empty DataFrame. Notice the index is empty: >>> df_empty = pd.DataFrame({'A' : []}) >>> df_empty Empty DataFrame Columns: [A] Index: [] >>> df_empty.empty True If we only have NaNs in our DataFrame, it is not considered empty! We will need to drop the NaNs to make the DataFrame empty: >>> df = pd.DataFrame({'A' : [np.nan]}) >>> df A 0 NaN >>> df.empty False >>> df.dropna().empty True """ return any(len(self._get_axis(a)) == 0 for a in self._AXIS_ORDERS) # ---------------------------------------------------------------------- # Array Interface # This is also set in IndexOpsMixin # GH#23114 Ensure ndarray.__op__(DataFrame) returns NotImplemented __array_priority__ = 1000 def __array__(self, dtype=None) -> np.ndarray: return np.asarray(self._values, dtype=dtype) def __array_wrap__(self, result, context=None): result = lib.item_from_zerodim(result) if is_scalar(result): # e.g. we get here with np.ptp(series) # ptp also requires the item_from_zerodim return result d = self._construct_axes_dict(self._AXIS_ORDERS, copy=False) return self._constructor(result, **d).__finalize__( self, method="__array_wrap__" ) # ideally we would define this to avoid the getattr checks, but # is slower # @property # def __array_interface__(self): # """ provide numpy array interface method """ # values = self.values # return dict(typestr=values.dtype.str,shape=values.shape,data=values) # ---------------------------------------------------------------------- # Picklability def __getstate__(self) -> Dict[str, Any]: meta = {k: getattr(self, k, None) for k in self._metadata} return dict( _mgr=self._mgr, _typ=self._typ, _metadata=self._metadata, attrs=self.attrs, **meta, ) def __setstate__(self, state): if isinstance(state, BlockManager): self._mgr = state elif isinstance(state, dict): if "_data" in state and "_mgr" not in state: # compat for older pickles state["_mgr"] = state.pop("_data") typ = state.get("_typ") if typ is not None: attrs = state.get("_attrs", {}) object.__setattr__(self, "_attrs", attrs) # set in the order of internal names # to avoid definitional recursion # e.g. say fill_value needing _mgr to be # defined meta = set(self._internal_names + self._metadata) for k in list(meta): if k in state: v = state[k] object.__setattr__(self, k, v) for k, v in state.items(): if k not in meta: object.__setattr__(self, k, v) else: raise NotImplementedError("Pre-0.12 pickles are no longer supported") elif len(state) == 2: raise NotImplementedError("Pre-0.12 pickles are no longer supported") self._item_cache = {} # ---------------------------------------------------------------------- # Rendering Methods def __repr__(self) -> str: # string representation based upon iterating over self # (since, by definition, `PandasContainers` are iterable) prepr = f"[{",".join(map(pprint_thing, self))}]" return f"{type(self).__name__}({prepr})" def _repr_latex_(self): """ Returns a LaTeX representation for a particular object. Mainly for use with nbconvert (jupyter notebook conversion to pdf). """ if config.get_option("display.latex.repr"): return self.to_latex() else: return None def _repr_data_resource_(self): """ Not a real Jupyter special repr method, but we use the same naming convention. """ if config.get_option("display.html.table_schema"): data = self.head(config.get_option("display.max_rows")) payload = json.loads( data.to_json(orient="table"), object_pairs_hook=collections.OrderedDict ) return payload # ---------------------------------------------------------------------- # I/O Methods _shared_docs[ "to_markdown" ] = """ Print %(klass)s in Markdown-friendly format. .. versionadded:: 1.0.0 Parameters ---------- buf : str, Path or StringIO-like, optional, default None Buffer to write to. If None, the output is returned as a string. mode : str, optional Mode in which file is opened. **kwargs These parameters will be passed to `tabulate`. Returns ------- str %(klass)s in Markdown-friendly format. """ @doc(klass="object") def to_excel( self, excel_writer, sheet_name="Sheet1", na_rep="", float_format=None, columns=None, header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None, merge_cells=True, encoding=None, inf_rep="inf", verbose=True, freeze_panes=None, ) -> None: """ Write {klass} to an Excel sheet. To write a single {klass} to an Excel .xlsx file it is only necessary to specify a target file name. To write to multiple sheets it is necessary to create an `ExcelWriter` object with a target file name, and specify a sheet in the file to write to. Multiple sheets may be written to by specifying unique `sheet_name`. With all data written to the file it is necessary to save the changes. Note that creating an `ExcelWriter` object with a file name that already exists will result in the contents of the existing file being erased. Parameters ---------- excel_writer : str or ExcelWriter object File path or existing ExcelWriter. sheet_name : str, default 'Sheet1' Name of sheet which will contain DataFrame. na_rep : str, default '' Missing data representation. float_format : str, optional Format string for floating point numbers. For example ``float_format="%.2f"`` will format 0.1234 to 0.12. columns : sequence or list of str, optional Columns to write. header : bool or list of str, default True Write out the column names. If a list of string is given it is assumed to be aliases for the column names. index : bool, default True Write row names (index). index_label : str or sequence, optional Column label for index column(s) if desired. If not specified, and `header` and `index` are True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. startrow : int, default 0 Upper left cell row to dump data frame. startcol : int, default 0 Upper left cell column to dump data frame. engine : str, optional Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and ``io.excel.xlsm.writer``. merge_cells : bool, default True Write MultiIndex and Hierarchical Rows as merged cells. encoding : str, optional Encoding of the resulting excel file. Only necessary for xlwt, other writers support unicode natively. inf_rep : str, default 'inf' Representation for infinity (there is no native representation for infinity in Excel). verbose : bool, default True Display more information in the error logs. freeze_panes : tuple of int (length 2), optional Specifies the one-based bottommost row and rightmost column that is to be frozen. See Also -------- to_csv : Write DataFrame to a comma-separated values (csv) file. ExcelWriter : Class for writing DataFrame objects into excel sheets. read_excel : Read an Excel file into a pandas DataFrame. read_csv : Read a comma-separated values (csv) file into DataFrame. Notes ----- For compatibility with :meth:`~DataFrame.to_csv`, to_excel serializes lists and dicts to strings before writing. Once a workbook has been saved it is not possible write further data without rewriting the whole workbook. Examples -------- Create, write to and save a workbook: >>> df1 = pd.DataFrame([['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']) >>> df1.to_excel("output.xlsx") # doctest: +SKIP To specify the sheet name: >>> df1.to_excel("output.xlsx", ... sheet_name='Sheet_name_1') # doctest: +SKIP If you wish to write to more than one sheet in the workbook, it is necessary to specify an ExcelWriter object: >>> df2 = df1.copy() >>> with pd.ExcelWriter('output.xlsx') as writer: # doctest: +SKIP ... df1.to_excel(writer, sheet_name='Sheet_name_1') ... df2.to_excel(writer, sheet_name='Sheet_name_2') ExcelWriter can also be used to append to an existing Excel file: >>> with pd.ExcelWriter('output.xlsx', ... mode='a') as writer: # doctest: +SKIP ... df.to_excel(writer, sheet_name='Sheet_name_3') To set the library that is used to write the Excel file, you can pass the `engine` keyword (the default engine is automatically chosen depending on the file extension): >>> df1.to_excel('output1.xlsx', engine='xlsxwriter') # doctest: +SKIP """ df = self if isinstance(self, ABCDataFrame) else self.to_frame() from pandas.io.formats.excel import ExcelFormatter formatter = ExcelFormatter( df, na_rep=na_rep, cols=columns, header=header, float_format=float_format, index=index, index_label=index_label, merge_cells=merge_cells, inf_rep=inf_rep, ) formatter.write( excel_writer, sheet_name=sheet_name, startrow=startrow, startcol=startcol, freeze_panes=freeze_panes, engine=engine, ) def to_json( self, path_or_buf: Optional[FilePathOrBuffer] = None, orient: Optional[str] = None, date_format: Optional[str] = None, double_precision: int = 10, force_ascii: bool_t = True, date_unit: str = "ms", default_handler: Optional[Callable[[Any], JSONSerializable]] = None, lines: bool_t = False, compression: Optional[str] = "infer", index: bool_t = True, indent: Optional[int] = None, ) -> Optional[str]: """ Convert the object to a JSON string. Note NaN's and None will be converted to null and datetime objects will be converted to UNIX timestamps. Parameters ---------- path_or_buf : str or file handle, optional File path or object. If not specified, the result is returned as a string. orient : str Indication of expected JSON string format. * Series: - default is 'index' - allowed values are: {'split','records','index','table'}. * DataFrame: - default is 'columns' - allowed values are: {'split', 'records', 'index', 'columns', 'values', 'table'}. * The format of the JSON string: - 'split' : dict like {'index' -> [index], 'columns' -> [columns], 'data' -> [values]} - 'records' : list like [{column -> value}, ... , {column -> value}] - 'index' : dict like {index -> {column -> value}} - 'columns' : dict like {column -> {index -> value}} - 'values' : just the values array - 'table' : dict like {'schema': {schema}, 'data': {data}} Describing the data, where data component is like ``orient='records'``. .. versionchanged:: 0.20.0 date_format : {None, 'epoch', 'iso'} Type of date conversion. 'epoch' = epoch milliseconds, 'iso' = ISO8601. The default depends on the `orient`. For ``orient='table'``, the default is 'iso'. For all other orients, the default is 'epoch'. double_precision : int, default 10 The number of decimal places to use when encoding floating point values. force_ascii : bool, default True Force encoded string to be ASCII. date_unit : str, default 'ms' (milliseconds) The time unit to encode to, governs timestamp and ISO8601 precision. One of 's', 'ms', 'us', 'ns' for second, millisecond, microsecond, and nanosecond respectively. default_handler : callable, default None Handler to call if object cannot otherwise be converted to a suitable format for JSON. Should receive a single argument which is the object to convert and return a serialisable object. lines : bool, default False If 'orient' is 'records' write out line delimited json format. Will throw ValueError if incorrect 'orient' since others are not list like. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None} A string representing the compression to use in the output file, only used when the first argument is a filename. By default, the compression is inferred from the filename. .. versionchanged:: 0.24.0 'infer' option added and set to default index : bool, default True Whether to include the index values in the JSON string. Not including the index (``index=False``) is only supported when orient is 'split' or 'table'. .. versionadded:: 0.23.0 indent : int, optional Length of whitespace used to indent each record. .. versionadded:: 1.0.0 Returns ------- None or str If path_or_buf is None, returns the resulting json format as a string. Otherwise returns None. See Also -------- read_json : Convert a JSON string to pandas object. Notes ----- The behavior of ``indent=0`` varies from the stdlib, which does not indent the output but does insert newlines. Currently, ``indent=0`` and the default ``indent=None`` are equivalent in pandas, though this may change in a future release. Examples -------- >>> import json >>> df = pd.DataFrame( ... [["a", "b"], ["c", "d"]], ... index=["row 1", "row 2"], ... columns=["col 1", "col 2"], ... ) >>> result = df.to_json(orient="split") >>> parsed = json.loads(result) >>> json.dumps(parsed, indent=4) # doctest: +SKIP { "columns": [ "col 1", "col 2" ], "index": [ "row 1", "row 2" ], "data": [ [ "a", "b" ], [ "c", "d" ] ] } Encoding/decoding a Dataframe using ``'records'`` formatted JSON. Note that index labels are not preserved with this encoding. >>> result = df.to_json(orient="records") >>> parsed = json.loads(result) >>> json.dumps(parsed, indent=4) # doctest: +SKIP [ { "col 1": "a", "col 2": "b" }, { "col 1": "c", "col 2": "d" } ] Encoding/decoding a Dataframe using ``'index'`` formatted JSON: >>> result = df.to_json(orient="index") >>> parsed = json.loads(result) >>> json.dumps(parsed, indent=4) # doctest: +SKIP { "row 1": { "col 1": "a", "col 2": "b" }, "row 2": { "col 1": "c", "col 2": "d" } } Encoding/decoding a Dataframe using ``'columns'`` formatted JSON: >>> result = df.to_json(orient="columns") >>> parsed = json.loads(result) >>> json.dumps(parsed, indent=4) # doctest: +SKIP { "col 1": { "row 1": "a", "row 2": "c" }, "col 2": { "row 1": "b", "row 2": "d" } } Encoding/decoding a Dataframe using ``'values'`` formatted JSON: >>> result = df.to_json(orient="values") >>> parsed = json.loads(result) >>> json.dumps(parsed, indent=4) # doctest: +SKIP [ [ "a", "b" ], [ "c", "d" ] ] Encoding with Table Schema: >>> result = df.to_json(orient="table") >>> parsed = json.loads(result) >>> json.dumps(parsed, indent=4) # doctest: +SKIP { "schema": { "fields": [ { "name": "index", "type": "string" }, { "name": "col 1", "type": "string" }, { "name": "col 2", "type": "string" } ], "primaryKey": [ "index" ], "pandas_version": "0.20.0" }, "data": [ { "index": "row 1", "col 1": "a", "col 2": "b" }, { "index": "row 2", "col 1": "c", "col 2": "d" } ] } """ from pandas.io import json if date_format is None and orient == "table": date_format = "iso" elif date_format is None: date_format = "epoch" config.is_nonnegative_int(indent) indent = indent or 0 return json.to_json( path_or_buf=path_or_buf, obj=self, orient=orient, date_format=date_format, double_precision=double_precision, force_ascii=force_ascii, date_unit=date_unit, default_handler=default_handler, lines=lines, compression=compression, index=index, indent=indent, ) def to_hdf( self, path_or_buf, key: str, mode: str = "a", complevel: Optional[int] = None, complib: Optional[str] = None, append: bool_t = False, format: Optional[str] = None, index: bool_t = True, min_itemsize: Optional[Union[int, Dict[str, int]]] = None, nan_rep=None, dropna: Optional[bool_t] = None, data_columns: Optional[Union[bool_t, List[str]]] = None, errors: str = "strict", encoding: str = "UTF-8", ) -> None: """ Write the contained data to an HDF5 file using HDFStore. Hierarchical Data Format (HDF) is self-describing, allowing an application to interpret the structure and contents of a file with no outside information. One HDF file can hold a mix of related objects which can be accessed as a group or as individual objects. In order to add another DataFrame or Series to an existing HDF file please use append mode and a different a key. For more information see the :ref:`user guide <io.hdf5>`. Parameters ---------- path_or_buf : str or pandas.HDFStore File path or HDFStore object. key : str Identifier for the group in the store. mode : {'a', 'w', 'r+'}, default 'a' Mode to open file: - 'w': write, a new file is created (an existing file with the same name would be deleted). - 'a': append, an existing file is opened for reading and writing, and if the file does not exist it is created. - 'r+': similar to 'a', but the file must already exist. complevel : {0-9}, optional Specifies a compression level for data. A value of 0 disables compression. complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib' Specifies the compression library to be used. As of v0.20.2 these additional compressors for Blosc are supported (default if no compressor specified: 'blosc:blosclz'): {'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy', 'blosc:zlib', 'blosc:zstd'}. Specifying a compression library which is not available issues a ValueError. append : bool, default False For Table formats, append the input data to the existing. format : {'fixed', 'table', None}, default 'fixed' Possible values: - 'fixed': Fixed format. Fast writing/reading. Not-appendable, nor searchable. - 'table': Table format. Write as a PyTables Table structure which may perform worse but allow more flexible operations like searching / selecting subsets of the data. - If None, pd.get_option('io.hdf.default_format') is checked, followed by fallback to "fixed" errors : str, default 'strict' Specifies how encoding and decoding errors are to be handled. See the errors argument for :func:`open` for a full list of options. encoding : str, default "UTF-8" min_itemsize : dict or int, optional Map column names to minimum string sizes for columns. nan_rep : Any, optional How to represent null values as str. Not allowed with append=True. data_columns : list of columns or True, optional List of columns to create as indexed data columns for on-disk queries, or True to use all columns. By default only the axes of the object are indexed. See :ref:`io.hdf5-query-data-columns`. Applicable only to format='table'. See Also -------- DataFrame.read_hdf : Read from HDF file. DataFrame.to_parquet : Write a DataFrame to the binary parquet format. DataFrame.to_sql : Write to a sql table. DataFrame.to_feather : Write out feather-format for DataFrames. DataFrame.to_csv : Write out to a csv file. Examples -------- >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, ... index=['a', 'b', 'c']) >>> df.to_hdf('data.h5', key='df', mode='w') We can add another object to the same file: >>> s = pd.Series([1, 2, 3, 4]) >>> s.to_hdf('data.h5', key='s') Reading from HDF file: >>> pd.read_hdf('data.h5', 'df') A B a 1 4 b 2 5 c 3 6 >>> pd.read_hdf('data.h5', 's') 0 1 1 2 2 3 3 4 dtype: int64 Deleting file with data: >>> import os >>> os.remove('data.h5') """ from pandas.io import pytables pytables.to_hdf( path_or_buf, key, self, mode=mode, complevel=complevel, complib=complib, append=append, format=format, index=index, min_itemsize=min_itemsize, nan_rep=nan_rep, dropna=dropna, data_columns=data_columns, errors=errors, encoding=encoding, ) def to_sql( self, name: str, con, schema=None, if_exists: str = "fail", index: bool_t = True, index_label=None, chunksize=None, dtype=None, method=None, ) -> None: """ Write records stored in a DataFrame to a SQL database. Databases supported by SQLAlchemy [1]_ are supported. Tables can be newly created, appended to, or overwritten. Parameters ---------- name : str Name of SQL table. con : sqlalchemy.engine.Engine or sqlite3.Connection Using SQLAlchemy makes it possible to use any DB supported by that library. Legacy support is provided for sqlite3.Connection objects. The user is responsible for engine disposal and connection closure for the SQLAlchemy connectable See `here \ <https://docs.sqlalchemy.org/en/13/core/connections.html>`_. schema : str, optional Specify the schema (if database flavor supports this). If None, use default schema. if_exists : {'fail', 'replace', 'append'}, default 'fail' How to behave if the table already exists. * fail: Raise a ValueError. * replace: Drop the table before inserting new values. * append: Insert new values to the existing table. index : bool, default True Write DataFrame index as a column. Uses `index_label` as the column name in the table. index_label : str or sequence, default None Column label for index column(s). If None is given (default) and `index` is True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. chunksize : int, optional Specify the number of rows in each batch to be written at a time. By default, all rows will be written at once. dtype : dict or scalar, optional Specifying the datatype for columns. If a dictionary is used, the keys should be the column names and the values should be the SQLAlchemy types or strings for the sqlite3 legacy mode. If a scalar is provided, it will be applied to all columns. method : {None, 'multi', callable}, optional Controls the SQL insertion clause used: * None : Uses standard SQL ``INSERT`` clause (one per row). * 'multi': Pass multiple values in a single ``INSERT`` clause. * callable with signature ``(pd_table, conn, keys, data_iter)``. Details and a sample callable implementation can be found in the section :ref:`insert method <io.sql.method>`. .. versionadded:: 0.24.0 Raises ------ ValueError When the table already exists and `if_exists` is 'fail' (the default). See Also -------- read_sql : Read a DataFrame from a table. Notes ----- Timezone aware datetime columns will be written as ``Timestamp with timezone`` type with SQLAlchemy if supported by the database. Otherwise, the datetimes will be stored as timezone unaware timestamps local to the original timezone. .. versionadded:: 0.24.0 References ---------- .. [1] https://docs.sqlalchemy.org .. [2] https://www.python.org/dev/peps/pep-0249/ Examples -------- Create an in-memory SQLite database. >>> from sqlalchemy import create_engine >>> engine = create_engine('sqlite://', echo=False) Create a table from scratch with 3 rows. >>> df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']}) >>> df name 0 User 1 1 User 2 2 User 3 >>> df.to_sql('users', con=engine) >>> engine.execute("SELECT * FROM users").fetchall() [(0, 'User 1'), (1, 'User 2'), (2, 'User 3')] >>> df1 = pd.DataFrame({'name' : ['User 4', 'User 5']}) >>> df1.to_sql('users', con=engine, if_exists='append') >>> engine.execute("SELECT * FROM users").fetchall() [(0, 'User 1'), (1, 'User 2'), (2, 'User 3'), (0, 'User 4'), (1, 'User 5')] Overwrite the table with just ``df1``. >>> df1.to_sql('users', con=engine, if_exists='replace', ... index_label='id') >>> engine.execute("SELECT * FROM users").fetchall() [(0, 'User 4'), (1, 'User 5')] Specify the dtype (especially useful for integers with missing values). Notice that while pandas is forced to store the data as floating point, the database supports nullable integers. When fetching the data with Python, we get back integer scalars. >>> df = pd.DataFrame({"A": [1, None, 2]}) >>> df A 0 1.0 1 NaN 2 2.0 >>> from sqlalchemy.types import Integer >>> df.to_sql('integers', con=engine, index=False, ... dtype={"A": Integer()}) >>> engine.execute("SELECT * FROM integers").fetchall() [(1,), (None,), (2,)] """ from pandas.io import sql sql.to_sql( self, name, con, schema=schema, if_exists=if_exists, index=index, index_label=index_label, chunksize=chunksize, dtype=dtype, method=method, ) def to_pickle( self, path, compression: Optional[str] = "infer", protocol: int = pickle.HIGHEST_PROTOCOL, ) -> None: """ Pickle (serialize) object to file. Parameters ---------- path : str File path where the pickled object will be stored. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, \ default 'infer' A string representing the compression to use in the output file. By default, infers from the file extension in specified path. protocol : int Int which indicates which protocol should be used by the pickler, default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible values are 0, 1, 2, 3, 4. A negative value for the protocol parameter is equivalent to setting its value to HIGHEST_PROTOCOL. .. [1] https://docs.python.org/3/library/pickle.html. See Also -------- read_pickle : Load pickled pandas object (or any object) from file. DataFrame.to_hdf : Write DataFrame to an HDF5 file. DataFrame.to_sql : Write DataFrame to a SQL database. DataFrame.to_parquet : Write a DataFrame to the binary parquet format. Examples -------- >>> original_df = pd.DataFrame({"foo": range(5), "bar": range(5, 10)}) >>> original_df foo bar 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9 >>> original_df.to_pickle("./dummy.pkl") >>> unpickled_df = pd.read_pickle("./dummy.pkl") >>> unpickled_df foo bar 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9 >>> import os >>> os.remove("./dummy.pkl") """ from pandas.io.pickle import to_pickle to_pickle(self, path, compression=compression, protocol=protocol) def to_clipboard( self, excel: bool_t = True, sep: Optional[str] = None, **kwargs ) -> None: r""" Copy object to the system clipboard. Write a text representation of object to the system clipboard. This can be pasted into Excel, for example. Parameters ---------- excel : bool, default True Produce output in a csv format for easy pasting into excel. - True, use the provided separator for csv pasting. - False, write a string representation of the object to the clipboard. sep : str, default ``'\t'`` Field delimiter. **kwargs These parameters will be passed to DataFrame.to_csv. See Also -------- DataFrame.to_csv : Write a DataFrame to a comma-separated values (csv) file. read_clipboard : Read text from clipboard and pass to read_table. Notes ----- Requirements for your platform. - Linux : `xclip`, or `xsel` (with `PyQt4` modules) - Windows : none - OS X : none Examples -------- Copy the contents of a DataFrame to the clipboard. >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C']) >>> df.to_clipboard(sep=',') # doctest: +SKIP ... # Wrote the following to the system clipboard: ... # ,A,B,C ... # 0,1,2,3 ... # 1,4,5,6 We can omit the index by passing the keyword `index` and setting it to false. >>> df.to_clipboard(sep=',', index=False) # doctest: +SKIP ... # Wrote the following to the system clipboard: ... # A,B,C ... # 1,2,3 ... # 4,5,6 """ from pandas.io import clipboards clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs) def to_xarray(self): """ Return an xarray object from the pandas object. Returns ------- xarray.DataArray or xarray.Dataset Data in the pandas structure converted to Dataset if the object is a DataFrame, or a DataArray if the object is a Series. See Also -------- DataFrame.to_hdf : Write DataFrame to an HDF5 file. DataFrame.to_parquet : Write a DataFrame to the binary parquet format. Notes ----- See the `xarray docs <https://xarray.pydata.org/en/stable/>`__ Examples -------- >>> df = pd.DataFrame([('falcon', 'bird', 389.0, 2), ... ('parrot', 'bird', 24.0, 2), ... ('lion', 'mammal', 80.5, 4), ... ('monkey', 'mammal', np.nan, 4)], ... columns=['name', 'class', 'max_speed', ... 'num_legs']) >>> df name class max_speed num_legs 0 falcon bird 389.0 2 1 parrot bird 24.0 2 2 lion mammal 80.5 4 3 monkey mammal NaN 4 >>> df.to_xarray() <xarray.Dataset> Dimensions: (index: 4) Coordinates: * index (index) int64 0 1 2 3 Data variables: name (index) object 'falcon' 'parrot' 'lion' 'monkey' class (index) object 'bird' 'bird' 'mammal' 'mammal' max_speed (index) float64 389.0 24.0 80.5 nan num_legs (index) int64 2 2 4 4 >>> df['max_speed'].to_xarray() <xarray.DataArray 'max_speed' (index: 4)> array([389. , 24. , 80.5, nan]) Coordinates: * index (index) int64 0 1 2 3 >>> dates = pd.to_datetime(['2018-01-01', '2018-01-01', ... '2018-01-02', '2018-01-02']) >>> df_multiindex = pd.DataFrame({'date': dates, ... 'animal': ['falcon', 'parrot', ... 'falcon', 'parrot'], ... 'speed': [350, 18, 361, 15]}) >>> df_multiindex = df_multiindex.set_index(['date', 'animal']) >>> df_multiindex speed date animal 2018-01-01 falcon 350 parrot 18 2018-01-02 falcon 361 parrot 15 >>> df_multiindex.to_xarray() <xarray.Dataset> Dimensions: (animal: 2, date: 2) Coordinates: * date (date) datetime64[ns] 2018-01-01 2018-01-02 * animal (animal) object 'falcon' 'parrot' Data variables: speed (date, animal) int64 350 18 361 15 """ xarray = import_optional_dependency("xarray") if self.ndim == 1: return xarray.DataArray.from_series(self) else: return xarray.Dataset.from_dataframe(self) @Substitution(returns=fmt.return_docstring) def to_latex( self, buf=None, columns=None, col_space=None, header=True, index=True, na_rep="NaN", formatters=None, float_format=None, sparsify=None, index_names=True, bold_rows=False, column_format=None, longtable=None, escape=None, encoding=None, decimal=".", multicolumn=None, multicolumn_format=None, multirow=None, caption=None, label=None, ): r""" Render object to a LaTeX tabular, longtable, or nested table/tabular. Requires ``\usepackage{booktabs}``. The output can be copy/pasted into a main LaTeX document or read from an external file with ``\input{table.tex}``. .. versionchanged:: 0.20.2 Added to Series. .. versionchanged:: 1.0.0 Added caption and label arguments. Parameters ---------- buf : str, Path or StringIO-like, optional, default None Buffer to write to. If None, the output is returned as a string. columns : list of label, optional The subset of columns to write. Writes all columns by default. col_space : int, optional The minimum width of each column. header : bool or list of str, default True Write out the column names. If a list of strings is given, it is assumed to be aliases for the column names. index : bool, default True Write row names (index). na_rep : str, default 'NaN' Missing data representation. formatters : list of functions or dict of {str: function}, optional Formatter functions to apply to columns' elements by position or name. The result of each function must be a unicode string. List must be of length equal to the number of columns. float_format : one-parameter function or str, optional, default None Formatter for floating point numbers. For example ``float_format="%%.2f"`` and ``float_format="{:0.2f}".format`` will both result in 0.1234 being formatted as 0.12. sparsify : bool, optional Set to False for a DataFrame with a hierarchical index to print every multiindex key at each row. By default, the value will be read from the config module. index_names : bool, default True Prints the names of the indexes. bold_rows : bool, default False Make the row labels bold in the output. column_format : str, optional The columns format as specified in `LaTeX table format <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g. 'rcl' for 3 columns. By default, 'l' will be used for all columns except columns of numbers, which default to 'r'. longtable : bool, optional By default, the value will be read from the pandas config module. Use a longtable environment instead of tabular. Requires adding a \usepackage{longtable} to your LaTeX preamble. escape : bool, optional By default, the value will be read from the pandas config module. When set to False prevents from escaping latex special characters in column names. encoding : str, optional A string representing the encoding to use in the output file, defaults to 'utf-8'. decimal : str, default '.' Character recognized as decimal separator, e.g. ',' in Europe. multicolumn : bool, default True Use \multicolumn to enhance MultiIndex columns. The default will be read from the config module. multicolumn_format : str, default 'l' The alignment for multicolumns, similar to `column_format` The default will be read from the config module. multirow : bool, default False Use \multirow to enhance MultiIndex rows. Requires adding a \usepackage{multirow} to your LaTeX preamble. Will print centered labels (instead of top-aligned) across the contained rows, separating groups via clines. The default will be read from the pandas config module. caption : str, optional The LaTeX caption to be placed inside ``\caption{}`` in the output. .. versionadded:: 1.0.0 label : str, optional The LaTeX label to be placed inside ``\label{}`` in the output. This is used with ``\ref{}`` in the main ``.tex`` file. .. versionadded:: 1.0.0 %(returns)s See Also -------- DataFrame.to_string : Render a DataFrame to a console-friendly tabular output. DataFrame.to_html : Render a DataFrame as an HTML table. Examples -------- >>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'], ... 'mask': ['red', 'purple'], ... 'weapon': ['sai', 'bo staff']}) >>> print(df.to_latex(index=False)) # doctest: +NORMALIZE_WHITESPACE \begin{tabular}{lll} \toprule name & mask & weapon \\ \midrule Raphael & red & sai \\ Donatello & purple & bo staff \\ \bottomrule \end{tabular} """ # Get defaults from the pandas config if self.ndim == 1: self = self.to_frame() if longtable is None: longtable = config.get_option("display.latex.longtable") if escape is None: escape = config.get_option("display.latex.escape") if multicolumn is None: multicolumn = config.get_option("display.latex.multicolumn") if multicolumn_format is None: multicolumn_format = config.get_option("display.latex.multicolumn_format") if multirow is None: multirow = config.get_option("display.latex.multirow") formatter = DataFrameFormatter( self, columns=columns, col_space=col_space, na_rep=na_rep, header=header, index=index, formatters=formatters, float_format=float_format, bold_rows=bold_rows, sparsify=sparsify, index_names=index_names, escape=escape, decimal=decimal, ) return formatter.to_latex( buf=buf, column_format=column_format, longtable=longtable, encoding=encoding, multicolumn=multicolumn, multicolumn_format=multicolumn_format, multirow=multirow, caption=caption, label=label, ) def to_csv( self, path_or_buf: Optional[FilePathOrBuffer] = None, sep: str = ",", na_rep: str = "", float_format: Optional[str] = None, columns: Optional[Sequence[Label]] = None, header: Union[bool_t, List[str]] = True, index: bool_t = True, index_label: Optional[Union[bool_t, str, Sequence[Label]]] = None, mode: str = "w", encoding: Optional[str] = None, compression: Optional[Union[str, Mapping[str, str]]] = "infer", quoting: Optional[int] = None, quotechar: str = '"', line_terminator: Optional[str] = None, chunksize: Optional[int] = None, date_format: Optional[str] = None, doublequote: bool_t = True, escapechar: Optional[str] = None, decimal: Optional[str] = ".", ) -> Optional[str]: r""" Write object to a comma-separated values (csv) file. .. versionchanged:: 0.24.0 The order of arguments for Series was changed. Parameters ---------- path_or_buf : str or file handle, default None File path or object, if None is provided the result is returned as a string. If a file object is passed it should be opened with `newline=''`, disabling universal newlines. .. versionchanged:: 0.24.0 Was previously named "path" for Series. sep : str, default ',' String of length 1. Field delimiter for the output file. na_rep : str, default '' Missing data representation. float_format : str, default None Format string for floating point numbers. columns : sequence, optional Columns to write. header : bool or list of str, default True Write out the column names. If a list of strings is given it is assumed to be aliases for the column names. .. versionchanged:: 0.24.0 Previously defaulted to False for Series. index : bool, default True Write row names (index). index_label : str or sequence, or False, default None Column label for index column(s) if desired. If None is given, and `header` and `index` are True, then the index names are used. A sequence should be given if the object uses MultiIndex. If False do not print fields for index names. Use index_label=False for easier importing in R. mode : str Python write mode, default 'w'. encoding : str, optional A string representing the encoding to use in the output file, defaults to 'utf-8'. compression : str or dict, default 'infer' If str, represents compression mode. If dict, value at 'method' is the compression mode. Compression mode may be any of the following possible values: {'infer', 'gzip', 'bz2', 'zip', 'xz', None}. If compression mode is 'infer' and `path_or_buf` is path-like, then detect compression mode from the following extensions: '.gz', '.bz2', '.zip' or '.xz'. (otherwise no compression). If dict given and mode is one of {'zip', 'gzip', 'bz2'}, or inferred as one of the above, other entries passed as additional compression options. .. versionchanged:: 1.0.0 May now be a dict with key 'method' as compression mode and other entries as additional compression options if compression mode is 'zip'. .. versionchanged:: 1.1.0 Passing compression options as keys in dict is supported for compression modes 'gzip' and 'bz2' as well as 'zip'. quoting : optional constant from csv module Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format` then floats are converted to strings and thus csv.QUOTE_NONNUMERIC will treat them as non-numeric. quotechar : str, default '\"' String of length 1. Character used to quote fields. line_terminator : str, optional The newline character or character sequence to use in the output file. Defaults to `os.linesep`, which depends on the OS in which this method is called ('\n' for linux, '\r\n' for Windows, i.e.). .. versionchanged:: 0.24.0 chunksize : int or None Rows to write at a time. date_format : str, default None Format string for datetime objects. doublequote : bool, default True Control quoting of `quotechar` inside a field. escapechar : str, default None String of length 1. Character used to escape `sep` and `quotechar` when appropriate. decimal : str, default '.' Character recognized as decimal separator. E.g. use ',' for European data. Returns ------- None or str If path_or_buf is None, returns the resulting csv format as a string. Otherwise returns None. See Also -------- read_csv : Load a CSV file into a DataFrame. to_excel : Write DataFrame to an Excel file. Examples -------- >>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'], ... 'mask': ['red', 'purple'], ... 'weapon': ['sai', 'bo staff']}) >>> df.to_csv(index=False) 'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n' Create 'out.zip' containing 'out.csv' >>> compression_opts = dict(method='zip', ... archive_name='out.csv') # doctest: +SKIP >>> df.to_csv('out.zip', index=False, ... compression=compression_opts) # doctest: +SKIP """ df = self if isinstance(self, ABCDataFrame) else self.to_frame() from pandas.io.formats.csvs import CSVFormatter formatter = CSVFormatter( df, path_or_buf, line_terminator=line_terminator, sep=sep, encoding=encoding, compression=compression, quoting=quoting, na_rep=na_rep, float_format=float_format, cols=columns, header=header, index=index, index_label=index_label, mode=mode, chunksize=chunksize, quotechar=quotechar, date_format=date_format, doublequote=doublequote, escapechar=escapechar, decimal=decimal, ) formatter.save() if path_or_buf is None: return formatter.path_or_buf.getvalue() return None # ---------------------------------------------------------------------- # Lookup Caching def _set_as_cached(self, item, cacher) -> None: """ Set the _cacher attribute on the calling object with a weakref to cacher. """ self._cacher = (item, weakref.ref(cacher)) def _reset_cacher(self) -> None: """ Reset the cacher. """ if hasattr(self, "_cacher"): del self._cacher def _maybe_cache_changed(self, item, value) -> None: """ The object has called back to us saying maybe it has changed. """ loc = self._info_axis.get_loc(item) self._mgr.iset(loc, value) @property def _is_cached(self) -> bool_t: """Return boolean indicating if self is cached or not.""" return getattr(self, "_cacher", None) is not None def _get_cacher(self): """return my cacher or None""" cacher = getattr(self, "_cacher", None) if cacher is not None: cacher = cacher[1]() return cacher def _maybe_update_cacher( self, clear: bool_t = False, verify_is_copy: bool_t = True ) -> None: """ See if we need to update our parent cacher if clear, then clear our cache. Parameters ---------- clear : bool, default False Clear the item cache. verify_is_copy : bool, default True Provide is_copy checks. """ cacher = getattr(self, "_cacher", None) if cacher is not None: ref = cacher[1]() # we are trying to reference a dead referant, hence # a copy if ref is None: del self._cacher else: if len(self) == len(ref): # otherwise, either self or ref has swapped in new arrays ref._maybe_cache_changed(cacher[0], self) if verify_is_copy: self._check_setitem_copy(stacklevel=5, t="referant") if clear: self._clear_item_cache() def _clear_item_cache(self) -> None: self._item_cache.clear() # ---------------------------------------------------------------------- # Indexing Methods def take( self: FrameOrSeries, indices, axis=0, is_copy: Optional[bool_t] = None, **kwargs ) -> FrameOrSeries: """ Return the elements in the given *positional* indices along an axis. This means that we are not indexing according to actual values in the index attribute of the object. We are indexing according to the actual position of the element in the object. Parameters ---------- indices : array-like An array of ints indicating which positions to take. axis : {0 or 'index', 1 or 'columns', None}, default 0 The axis on which to select elements. ``0`` means that we are selecting rows, ``1`` means that we are selecting columns. is_copy : bool Before pandas 1.0, ``is_copy=False`` can be specified to ensure that the return value is an actual copy. Starting with pandas 1.0, ``take`` always returns a copy, and the keyword is therefore deprecated. .. deprecated:: 1.0.0 **kwargs For compatibility with :meth:`numpy.take`. Has no effect on the output. Returns ------- taken : same type as caller An array-like containing the elements taken from the object. See Also -------- DataFrame.loc : Select a subset of a DataFrame by labels. DataFrame.iloc : Select a subset of a DataFrame by positions. numpy.take : Take elements from an array along an axis. Examples -------- >>> df = pd.DataFrame([('falcon', 'bird', 389.0), ... ('parrot', 'bird', 24.0), ... ('lion', 'mammal', 80.5), ... ('monkey', 'mammal', np.nan)], ... columns=['name', 'class', 'max_speed'], ... index=[0, 2, 3, 1]) >>> df name class max_speed 0 falcon bird 389.0 2 parrot bird 24.0 3 lion mammal 80.5 1 monkey mammal NaN Take elements at positions 0 and 3 along the axis 0 (default). Note how the actual indices selected (0 and 1) do not correspond to our selected indices 0 and 3. That's because we are selecting the 0th and 3rd rows, not rows whose indices equal 0 and 3. >>> df.take([0, 3]) name class max_speed 0 falcon bird 389.0 1 monkey mammal NaN Take elements at indices 1 and 2 along the axis 1 (column selection). >>> df.take([1, 2], axis=1) class max_speed 0 bird 389.0 2 bird 24.0 3 mammal 80.5 1 mammal NaN We may take elements using negative integers for positive indices, starting from the end of the object, just like with Python lists. >>> df.take([-1, -2]) name class max_speed 1 monkey mammal NaN 3 lion mammal 80.5 """ if is_copy is not None: warnings.warn( "is_copy is deprecated and will be removed in a future version. " "'take' always returns a copy, so there is no need to specify this.", FutureWarning, stacklevel=2, ) nv.validate_take(tuple(), kwargs) new_data = self._mgr.take( indices, axis=self._get_block_manager_axis(axis), verify=True ) return self._constructor(new_data).__finalize__(self, method="take") def _take_with_is_copy(self: FrameOrSeries, indices, axis=0) -> FrameOrSeries: """ Internal version of the `take` method that sets the `_is_copy` attribute to keep track of the parent dataframe (using in indexing for the SettingWithCopyWarning). See the docstring of `take` for full explanation of the parameters. """ result = self.take(indices=indices, axis=axis) # Maybe set copy if we didn't actually change the index. if not result._get_axis(axis).equals(self._get_axis(axis)): result._set_is_copy(self) return result def xs(self, key, axis=0, level=None, drop_level: bool_t = True): """ Return cross-section from the Series/DataFrame. This method takes a `key` argument to select data at a particular level of a MultiIndex. Parameters ---------- key : label or tuple of label Label contained in the index, or partially in a MultiIndex. axis : {0 or 'index', 1 or 'columns'}, default 0 Axis to retrieve cross-section on. level : object, defaults to first n levels (n=1 or len(key)) In case of a key partially contained in a MultiIndex, indicate which levels are used. Levels can be referred by label or position. drop_level : bool, default True If False, returns object with same levels as self. Returns ------- Series or DataFrame Cross-section from the original Series or DataFrame corresponding to the selected index levels. See Also -------- DataFrame.loc : Access a group of rows and columns by label(s) or a boolean array. DataFrame.iloc : Purely integer-location based indexing for selection by position. Notes ----- `xs` can not be used to set values. MultiIndex Slicers is a generic way to get/set values on any level or levels. It is a superset of `xs` functionality, see :ref:`MultiIndex Slicers <advanced.mi_slicers>`. Examples -------- >>> d = {'num_legs': [4, 4, 2, 2], ... 'num_wings': [0, 0, 2, 2], ... 'class': ['mammal', 'mammal', 'mammal', 'bird'], ... 'animal': ['cat', 'dog', 'bat', 'penguin'], ... 'locomotion': ['walks', 'walks', 'flies', 'walks']} >>> df = pd.DataFrame(data=d) >>> df = df.set_index(['class', 'animal', 'locomotion']) >>> df num_legs num_wings class animal locomotion mammal cat walks 4 0 dog walks 4 0 bat flies 2 2 bird penguin walks 2 2 Get values at specified index >>> df.xs('mammal') num_legs num_wings animal locomotion cat walks 4 0 dog walks 4 0 bat flies 2 2 Get values at several indexes >>> df.xs(('mammal', 'dog')) num_legs num_wings locomotion walks 4 0 Get values at specified index and level >>> df.xs('cat', level=1) num_legs num_wings class locomotion mammal walks 4 0 Get values at several indexes and levels >>> df.xs(('bird', 'walks'), ... level=[0, 'locomotion']) num_legs num_wings animal penguin 2 2 Get values at specified column and axis >>> df.xs('num_wings', axis=1) class animal locomotion mammal cat walks 0 dog walks 0 bat flies 2 bird penguin walks 2 Name: num_wings, dtype: int64 """ axis = self._get_axis_number(axis) labels = self._get_axis(axis) if level is not None: if not isinstance(labels, MultiIndex): raise TypeError("Index must be a MultiIndex") loc, new_ax = labels.get_loc_level(key, level=level, drop_level=drop_level) # create the tuple of the indexer _indexer = [slice(None)] * self.ndim _indexer[axis] = loc indexer = tuple(_indexer) result = self.iloc[indexer] setattr(result, result._get_axis_name(axis), new_ax) return result if axis == 1: return self[key] index = self.index if isinstance(index, MultiIndex): loc, new_index = self.index.get_loc_level(key, drop_level=drop_level) else: loc = self.index.get_loc(key) if isinstance(loc, np.ndarray): if loc.dtype == np.bool_: (inds,) = loc.nonzero() return self._take_with_is_copy(inds, axis=axis) else: return self._take_with_is_copy(loc, axis=axis) if not is_scalar(loc): new_index = self.index[loc] if is_scalar(loc): # In this case loc should be an integer if self.ndim == 1: # if we encounter an array-like and we only have 1 dim # that means that their are list/ndarrays inside the Series! # so just return them (GH 6394) return self._values[loc] new_values = self._mgr.fast_xs(loc) result = self._constructor_sliced( new_values, index=self.columns, name=self.index[loc], dtype=new_values.dtype, ) else: result = self.iloc[loc] result.index = new_index # this could be a view # but only in a single-dtyped view sliceable case result._set_is_copy(self, copy=not result._is_view) return result def __getitem__(self, item): raise AbstractMethodError(self) def _get_item_cache(self, item): """Return the cached item, item represents a label indexer.""" cache = self._item_cache res = cache.get(item) if res is None: # All places that call _get_item_cache have unique columns, # pending resolution of GH#33047 loc = self.columns.get_loc(item) values = self._mgr.iget(loc) res = self._box_col_values(values, loc) cache[item] = res res._set_as_cached(item, self) # for a chain res._is_copy = self._is_copy return res def _slice(self: FrameOrSeries, slobj: slice, axis=0) -> FrameOrSeries: """ Construct a slice of this container. Slicing with this method is *always* positional. """ assert isinstance(slobj, slice), type(slobj) axis = self._get_block_manager_axis(axis) result = self._constructor(self._mgr.get_slice(slobj, axis=axis)) result = result.__finalize__(self) # this could be a view # but only in a single-dtyped view sliceable case is_copy = axis != 0 or result._is_view result._set_is_copy(self, copy=is_copy) return result def _iset_item(self, loc: int, value) -> None: self._mgr.iset(loc, value) self._clear_item_cache() def _set_item(self, key, value) -> None: try: loc = self._info_axis.get_loc(key) except KeyError: # This item wasn't present, just insert at end self._mgr.insert(len(self._info_axis), key, value) return NDFrame._iset_item(self, loc, value) def _set_is_copy(self, ref, copy: bool_t = True) -> None: if not copy: self._is_copy = None else: assert ref is not None self._is_copy = weakref.ref(ref) def _check_is_chained_assignment_possible(self) -> bool_t: """ Check if we are a view, have a cacher, and are of mixed type. If so, then force a setitem_copy check. Should be called just near setting a value Will return a boolean if it we are a view and are cached, but a single-dtype meaning that the cacher should be updated following setting. """ if self._is_view and self._is_cached: ref = self._get_cacher() if ref is not None and ref._is_mixed_type: self._check_setitem_copy(stacklevel=4, t="referant", force=True) return True elif self._is_copy: self._check_setitem_copy(stacklevel=4, t="referant") return False def _check_setitem_copy(self, stacklevel=4, t="setting", force=False): """ Parameters ---------- stacklevel : int, default 4 the level to show of the stack when the error is output t : str, the type of setting error force : bool, default False If True, then force showing an error. validate if we are doing a setitem on a chained copy. If you call this function, be sure to set the stacklevel such that the user will see the error *at the level of setting* It is technically possible to figure out that we are setting on a copy even WITH a multi-dtyped pandas object. In other words, some blocks may be views while other are not. Currently _is_view will ALWAYS return False for multi-blocks to avoid having to handle this case. df = DataFrame(np.arange(0,9), columns=['count']) df['group'] = 'b' # This technically need not raise SettingWithCopy if both are view # (which is not # generally guaranteed but is usually True. However, # this is in general not a good practice and we recommend using .loc. df.iloc[0:5]['group'] = 'a' """ # return early if the check is not needed if not (force or self._is_copy): return value = config.get_option("mode.chained_assignment") if value is None: return # see if the copy is not actually referred; if so, then dissolve # the copy weakref if self._is_copy is not None and not isinstance(self._is_copy, str): r = self._is_copy() if not gc.get_referents(r) or r.shape == self.shape: self._is_copy = None return # a custom message if isinstance(self._is_copy, str): t = self._is_copy elif t == "referant": t = ( "\n" "A value is trying to be set on a copy of a slice from a " "DataFrame\n\n" "See the caveats in the documentation: " "https://pandas.pydata.org/pandas-docs/stable/user_guide/" "indexing.html#returning-a-view-versus-a-copy" ) else: t = ( "\n" "A value is trying to be set on a copy of a slice from a " "DataFrame.\n" "Try using .loc[row_indexer,col_indexer] = value " "instead\n\nSee the caveats in the documentation: " "https://pandas.pydata.org/pandas-docs/stable/user_guide/" "indexing.html#returning-a-view-versus-a-copy" ) if value == "raise": raise com.SettingWithCopyError(t) elif value == "warn": warnings.warn(t, com.SettingWithCopyWarning, stacklevel=stacklevel) def __delitem__(self, key) -> None: """ Delete item """ deleted = False maybe_shortcut = False if self.ndim == 2 and isinstance(self.columns, MultiIndex): try: maybe_shortcut = key not in self.columns._engine except TypeError: pass if maybe_shortcut: # Allow shorthand to delete all columns whose first len(key) # elements match key: if not isinstance(key, tuple): key = (key,) for col in self.columns: if isinstance(col, tuple) and col[: len(key)] == key: del self[col] deleted = True if not deleted: # If the above loop ran and didn't delete anything because # there was no match, this call should raise the appropriate # exception: loc = self.axes[-1].get_loc(key) self._mgr.idelete(loc) # delete from the caches try: del self._item_cache[key] except KeyError: pass # ---------------------------------------------------------------------- # Unsorted def get(self, key, default=None): """ Get item from object for given key (ex: DataFrame column). Returns default value if not found. Parameters ---------- key : object Returns ------- value : same type as items contained in object """ try: return self[key] except (KeyError, ValueError, IndexError): return default @property def _is_view(self) -> bool_t: """Return boolean indicating if self is view of another array """ return self._mgr.is_view def reindex_like( self: FrameOrSeries, other, method: Optional[str] = None, copy: bool_t = True, limit=None, tolerance=None, ) -> FrameOrSeries: """ Return an object with matching indices as other object. Conform the object to the same index on all axes. Optional filling logic, placing NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False. Parameters ---------- other : Object of the same data type Its row and column indices are used to define the new indices of this object. method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'} Method to use for filling holes in reindexed DataFrame. Please note: this is only applicable to DataFrames/Series with a monotonically increasing/decreasing index. * None (default): don't fill gaps * pad / ffill: propagate last valid observation forward to next valid * backfill / bfill: use next valid observation to fill gap * nearest: use nearest valid observations to fill gap. copy : bool, default True Return a new object, even if the passed indexes are the same. limit : int, default None Maximum number of consecutive labels to fill for inexact matches. tolerance : optional Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations most satisfy the equation ``abs(index[indexer] - target) <= tolerance``. Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the index's type. Returns ------- Series or DataFrame Same type as caller, but with changed indices on each axis. See Also -------- DataFrame.set_index : Set row labels. DataFrame.reset_index : Remove row labels or move them to new columns. DataFrame.reindex : Change to new indices or expand indices. Notes ----- Same as calling ``.reindex(index=other.index, columns=other.columns,...)``. Examples -------- >>> df1 = pd.DataFrame([[24.3, 75.7, 'high'], ... [31, 87.8, 'high'], ... [22, 71.6, 'medium'], ... [35, 95, 'medium']], ... columns=['temp_celsius', 'temp_fahrenheit', ... 'windspeed'], ... index=pd.date_range(start='2014-02-12', ... end='2014-02-15', freq='D')) >>> df1 temp_celsius temp_fahrenheit windspeed 2014-02-12 24.3 75.7 high 2014-02-13 31.0 87.8 high 2014-02-14 22.0 71.6 medium 2014-02-15 35.0 95.0 medium >>> df2 = pd.DataFrame([[28, 'low'], ... [30, 'low'], ... [35.1, 'medium']], ... columns=['temp_celsius', 'windspeed'], ... index=pd.DatetimeIndex(['2014-02-12', '2014-02-13', ... '2014-02-15'])) >>> df2 temp_celsius windspeed 2014-02-12 28.0 low 2014-02-13 30.0 low 2014-02-15 35.1 medium >>> df2.reindex_like(df1) temp_celsius temp_fahrenheit windspeed 2014-02-12 28.0 NaN low 2014-02-13 30.0 NaN low 2014-02-14 NaN NaN NaN 2014-02-15 35.1 NaN medium """ d = other._construct_axes_dict( axes=self._AXIS_ORDERS, method=method, copy=copy, limit=limit, tolerance=tolerance, ) return self.reindex(**d) def drop( self, labels=None, axis=0, index=None, columns=None, level=None, inplace: bool_t = False, errors: str = "raise", ): inplace = validate_bool_kwarg(inplace, "inplace") if labels is not None: if index is not None or columns is not None: raise ValueError("Cannot specify both 'labels' and 'index'/'columns'") axis_name = self._get_axis_name(axis) axes = {axis_name: labels} elif index is not None or columns is not None: axes, _ = self._construct_axes_from_arguments((index, columns), {}) else: raise ValueError( "Need to specify at least one of 'labels', 'index' or 'columns'" ) obj = self for axis, labels in axes.items(): if labels is not None: obj = obj._drop_axis(labels, axis, level=level, errors=errors) if inplace: self._update_inplace(obj) else: return obj def _drop_axis( self: FrameOrSeries, labels, axis, level=None, errors: str = "raise" ) -> FrameOrSeries: """ Drop labels from specified axis. Used in the ``drop`` method internally. Parameters ---------- labels : single label or list-like axis : int or axis name level : int or level name, default None For MultiIndex errors : {'ignore', 'raise'}, default 'raise' If 'ignore', suppress error and existing labels are dropped. """ axis = self._get_axis_number(axis) axis_name = self._get_axis_name(axis) axis = self._get_axis(axis) if axis.is_unique: if level is not None: if not isinstance(axis, MultiIndex): raise AssertionError("axis must be a MultiIndex") new_axis = axis.drop(labels, level=level, errors=errors) else: new_axis = axis.drop(labels, errors=errors) result = self.reindex(**{axis_name: new_axis}) # Case for non-unique axis else: labels = ensure_object(com.index_labels_to_array(labels)) if level is not None: if not isinstance(axis, MultiIndex): raise AssertionError("axis must be a MultiIndex") indexer = ~axis.get_level_values(level).isin(labels) # GH 18561 MultiIndex.drop should raise if label is absent if errors == "raise" and indexer.all(): raise KeyError(f"{labels} not found in axis") else: indexer = ~axis.isin(labels) # Check if label doesn't exist along axis labels_missing = (axis.get_indexer_for(labels) == -1).any() if errors == "raise" and labels_missing: raise KeyError(f"{labels} not found in axis") slicer = [slice(None)] * self.ndim slicer[self._get_axis_number(axis_name)] = indexer result = self.loc[tuple(slicer)] return result def _update_inplace(self, result, verify_is_copy: bool_t = True) -> None: """ Replace self internals with result. Parameters ---------- result : same type as self verify_is_copy : bool, default True Provide is_copy checks. """ # NOTE: This does *not* call __finalize__ and that's an explicit # decision that we may revisit in the future. self._reset_cache() self._clear_item_cache() self._mgr = result._mgr self._maybe_update_cacher(verify_is_copy=verify_is_copy) def add_prefix(self: FrameOrSeries, prefix: str) -> FrameOrSeries: """ Prefix labels with string `prefix`. For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed. Parameters ---------- prefix : str The string to add before each label. Returns ------- Series or DataFrame New Series or DataFrame with updated labels. See Also -------- Series.add_suffix: Suffix row labels with string `suffix`. DataFrame.add_suffix: Suffix column labels with string `suffix`. Examples -------- >>> s = pd.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.add_prefix('item_') item_0 1 item_1 2 item_2 3 item_3 4 dtype: int64 >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]}) >>> df A B 0 1 3 1 2 4 2 3 5 3 4 6 >>> df.add_prefix('col_') col_A col_B 0 1 3 1 2 4 2 3 5 3 4 6 """ f = functools.partial("{prefix}{}".format, prefix=prefix) mapper = {self._info_axis_name: f} return self.rename(**mapper) # type: ignore def add_suffix(self: FrameOrSeries, suffix: str) -> FrameOrSeries: """ Suffix labels with string `suffix`. For Series, the row labels are suffixed. For DataFrame, the column labels are suffixed. Parameters ---------- suffix : str The string to add after each label. Returns ------- Series or DataFrame New Series or DataFrame with updated labels. See Also -------- Series.add_prefix: Prefix row labels with string `prefix`. DataFrame.add_prefix: Prefix column labels with string `prefix`. Examples -------- >>> s = pd.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.add_suffix('_item') 0_item 1 1_item 2 2_item 3 3_item 4 dtype: int64 >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]}) >>> df A B 0 1 3 1 2 4 2 3 5 3 4 6 >>> df.add_suffix('_col') A_col B_col 0 1 3 1 2 4 2 3 5 3 4 6 """ f = functools.partial("{}{suffix}".format, suffix=suffix) mapper = {self._info_axis_name: f} return self.rename(**mapper) # type: ignore def sort_values( self, axis=0, ascending=True, inplace: bool_t = False, kind: str = "quicksort", na_position: str = "last", ignore_index: bool_t = False, key: ValueKeyFunc = None, ): """ Sort by the values along either axis. Parameters ----------%(optional_by)s axis : %(axes_single_arg)s, default 0 Axis to be sorted. ascending : bool or list of bool, default True Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by. inplace : bool, default False If True, perform operation in-place. kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort' Choice of sorting algorithm. See also ndarray.np.sort for more information. `mergesort` is the only stable algorithm. For DataFrames, this option is only applied when sorting on a single column or label. na_position : {'first', 'last'}, default 'last' Puts NaNs at the beginning if `first`; `last` puts NaNs at the end. ignore_index : bool, default False If True, the resulting axis will be labeled 0, 1, …, n - 1. .. versionadded:: 1.0.0 key : callable, optional Apply the key function to the values before sorting. This is similar to the `key` argument in the builtin :meth:`sorted` function, with the notable difference that this `key` function should be *vectorized*. It should expect a ``Series`` and return a Series with the same shape as the input. It will be applied to each column in `by` independently. .. versionadded:: 1.1.0 Returns ------- DataFrame or None DataFrame with sorted values if inplace=False, None otherwise. See Also -------- DataFrame.sort_index : Sort a DataFrame by the index. Series.sort_values : Similar method for a Series. Examples -------- >>> df = pd.DataFrame({ ... 'col1': ['A', 'A', 'B', np.nan, 'D', 'C'], ... 'col2': [2, 1, 9, 8, 7, 4], ... 'col3': [0, 1, 9, 4, 2, 3], ... 'col4': ['a', 'B', 'c', 'D', 'e', 'F'] ... }) >>> df col1 col2 col3 col4 0 A 2 0 a 1 A 1 1 B 2 B 9 9 c 3 NaN 8 4 D 4 D 7 2 e 5 C 4 3 F Sort by col1 >>> df.sort_values(by=['col1']) col1 col2 col3 col4 0 A 2 0 a 1 A 1 1 B 2 B 9 9 c 5 C 4 3 F 4 D 7 2 e 3 NaN 8 4 D Sort by multiple columns >>> df.sort_values(by=['col1', 'col2']) col1 col2 col3 col4 1 A 1 1 B 0 A 2 0 a 2 B 9 9 c 5 C 4 3 F 4 D 7 2 e 3 NaN 8 4 D Sort Descending >>> df.sort_values(by='col1', ascending=False) col1 col2 col3 col4 4 D 7 2 e 5 C 4 3 F 2 B 9 9 c 0 A 2 0 a 1 A 1 1 B 3 NaN 8 4 D Putting NAs first >>> df.sort_values(by='col1', ascending=False, na_position='first') col1 col2 col3 col4 3 NaN 8 4 D 4 D 7 2 e 5 C 4 3 F 2 B 9 9 c 0 A 2 0 a 1 A 1 1 B Sorting with a key function >>> df.sort_values(by='col4', key=lambda col: col.str.lower()) col1 col2 col3 col4 0 A 2 0 a 1 A 1 1 B 2 B 9 9 c 3 NaN 8 4 D 4 D 7 2 e 5 C 4 3 F """ raise AbstractMethodError(self) def reindex(self: FrameOrSeries, *args, **kwargs) -> FrameOrSeries: """ Conform %(klass)s to new index with optional filling logic. Places NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and ``copy=False``. Parameters ---------- %(optional_labels)s %(axes)s : array-like, optional New labels / index to conform to, should be specified using keywords. Preferably an Index object to avoid duplicating data. %(optional_axis)s method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'} Method to use for filling holes in reindexed DataFrame. Please note: this is only applicable to DataFrames/Series with a monotonically increasing/decreasing index. * None (default): don't fill gaps * pad / ffill: Propagate last valid observation forward to next valid. * backfill / bfill: Use next valid observation to fill gap. * nearest: Use nearest valid observations to fill gap. copy : bool, default True Return a new object, even if the passed indexes are the same. level : int or name Broadcast across a level, matching Index values on the passed MultiIndex level. fill_value : scalar, default np.NaN Value to use for missing values. Defaults to NaN, but can be any "compatible" value. limit : int, default None Maximum number of consecutive elements to forward or backward fill. tolerance : optional Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations most satisfy the equation ``abs(index[indexer] - target) <= tolerance``. Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the index's type. Returns ------- %(klass)s with changed index. See Also -------- DataFrame.set_index : Set row labels. DataFrame.reset_index : Remove row labels or move them to new columns. DataFrame.reindex_like : Change to same indices as other DataFrame. Examples -------- ``DataFrame.reindex`` supports two calling conventions * ``(index=index_labels, columns=column_labels, ...)`` * ``(labels, axis={'index', 'columns'}, ...)`` We *highly* recommend using keyword arguments to clarify your intent. Create a dataframe with some fictional data. >>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror'] >>> df = pd.DataFrame({'http_status': [200, 200, 404, 404, 301], ... 'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]}, ... index=index) >>> df http_status response_time Firefox 200 0.04 Chrome 200 0.02 Safari 404 0.07 IE10 404 0.08 Konqueror 301 1.00 Create a new index and reindex the dataframe. By default values in the new index that do not have corresponding records in the dataframe are assigned ``NaN``. >>> new_index = ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10', ... 'Chrome'] >>> df.reindex(new_index) http_status response_time Safari 404.0 0.07 Iceweasel NaN NaN Comodo Dragon NaN NaN IE10 404.0 0.08 Chrome 200.0 0.02 We can fill in the missing values by passing a value to the keyword ``fill_value``. Because the index is not monotonically increasing or decreasing, we cannot use arguments to the keyword ``method`` to fill the ``NaN`` values. >>> df.reindex(new_index, fill_value=0) http_status response_time Safari 404 0.07 Iceweasel 0 0.00 Comodo Dragon 0 0.00 IE10 404 0.08 Chrome 200 0.02 >>> df.reindex(new_index, fill_value='missing') http_status response_time Safari 404 0.07 Iceweasel missing missing Comodo Dragon missing missing IE10 404 0.08 Chrome 200 0.02 We can also reindex the columns. >>> df.reindex(columns=['http_status', 'user_agent']) http_status user_agent Firefox 200 NaN Chrome 200 NaN Safari 404 NaN IE10 404 NaN Konqueror 301 NaN Or we can use "axis-style" keyword arguments >>> df.reindex(['http_status', 'user_agent'], axis="columns") http_status user_agent Firefox 200 NaN Chrome 200 NaN Safari 404 NaN IE10 404 NaN Konqueror 301 NaN To further illustrate the filling functionality in ``reindex``, we will create a dataframe with a monotonically increasing index (for example, a sequence of dates). >>> date_index = pd.date_range('1/1/2010', periods=6, freq='D') >>> df2 = pd.DataFrame({"prices": [100, 101, np.nan, 100, 89, 88]}, ... index=date_index) >>> df2 prices 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0 Suppose we decide to expand the dataframe to cover a wider date range. >>> date_index2 = pd.date_range('12/29/2009', periods=10, freq='D') >>> df2.reindex(date_index2) prices 2009-12-29 NaN 2009-12-30 NaN 2009-12-31 NaN 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0 2010-01-07 NaN The index entries that did not have a value in the original data frame (for example, '2009-12-29') are by default filled with ``NaN``. If desired, we can fill in the missing values using one of several options. For example, to back-propagate the last valid value to fill the ``NaN`` values, pass ``bfill`` as an argument to the ``method`` keyword. >>> df2.reindex(date_index2, method='bfill') prices 2009-12-29 100.0 2009-12-30 100.0 2009-12-31 100.0 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0 2010-01-07 NaN Please note that the ``NaN`` value present in the original dataframe (at index value 2010-01-03) will not be filled by any of the value propagation schemes. This is because filling while reindexing does not look at dataframe values, but only compares the original and desired indexes. If you do want to fill in the ``NaN`` values present in the original dataframe, use the ``fillna()`` method. See the :ref:`user guide <basics.reindexing>` for more. """ # TODO: Decide if we care about having different examples for different # kinds # construct the args axes, kwargs = self._construct_axes_from_arguments(args, kwargs) method = missing.clean_reindex_fill_method(kwargs.pop("method", None)) level = kwargs.pop("level", None) copy = kwargs.pop("copy", True) limit = kwargs.pop("limit", None) tolerance = kwargs.pop("tolerance", None) fill_value = kwargs.pop("fill_value", None) # Series.reindex doesn't use / need the axis kwarg # We pop and ignore it here, to make writing Series/Frame generic code # easier kwargs.pop("axis", None) if kwargs: raise TypeError( "reindex() got an unexpected keyword " f'argument "{list(kwargs.keys())[0]}"' ) self._consolidate_inplace() # if all axes that are requested to reindex are equal, then only copy # if indicated must have index names equal here as well as values if all( self._get_axis(axis).identical(ax) for axis, ax in axes.items() if ax is not None ): if copy: return self.copy() return self # check if we are a multi reindex if self._needs_reindex_multi(axes, method, level): return self._reindex_multi(axes, copy, fill_value) # perform the reindex on the axes return self._reindex_axes( axes, level, limit, tolerance, method, fill_value, copy ).__finalize__(self, method="reindex") def _reindex_axes( self: FrameOrSeries, axes, level, limit, tolerance, method, fill_value, copy ) -> FrameOrSeries: """Perform the reindex for all the axes.""" obj = self for a in self._AXIS_ORDERS: labels = axes[a] if labels is None: continue ax = self._get_axis(a) new_index, indexer = ax.reindex( labels, level=level, limit=limit, tolerance=tolerance, method=method ) axis = self._get_axis_number(a) obj = obj._reindex_with_indexers( {axis: [new_index, indexer]}, fill_value=fill_value, copy=copy, allow_dups=False, ) return obj def _needs_reindex_multi(self, axes, method, level) -> bool_t: """Check if we do need a multi reindex.""" return ( (com.count_not_none(*axes.values()) == self._AXIS_LEN) and method is None and level is None and not self._is_mixed_type ) def _reindex_multi(self, axes, copy, fill_value): raise AbstractMethodError(self) def _reindex_with_indexers( self: FrameOrSeries, reindexers, fill_value=None, copy: bool_t = False, allow_dups: bool_t = False, ) -> FrameOrSeries: """allow_dups indicates an internal call here """ # reindex doing multiple operations on different axes if indicated new_data = self._mgr for axis in sorted(reindexers.keys()): index, indexer = reindexers[axis] baxis = self._get_block_manager_axis(axis) if index is None: continue index = ensure_index(index) if indexer is not None: indexer = ensure_int64(indexer) # TODO: speed up on homogeneous DataFrame objects new_data = new_data.reindex_indexer( index, indexer, axis=baxis, fill_value=fill_value, allow_dups=allow_dups, copy=copy, ) # If we've made a copy once, no need to make another one copy = False if copy and new_data is self._mgr: new_data = new_data.copy() return self._constructor(new_data).__finalize__(self) def filter( self: FrameOrSeries, items=None, like: Optional[str] = None, regex: Optional[str] = None, axis=None, ) -> FrameOrSeries: """ Subset the dataframe rows or columns according to the specified index labels. Note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index. Parameters ---------- items : list-like Keep labels from axis which are in items. like : str Keep labels from axis for which "like in label == True". regex : str (regular expression) Keep labels from axis for which re.search(regex, label) == True. axis : {0 or ‘index’, 1 or ‘columns’, None}, default None The axis to filter on, expressed either as an index (int) or axis name (str). By default this is the info axis, 'index' for Series, 'columns' for DataFrame. Returns ------- same type as input object See Also -------- DataFrame.loc : Access a group of rows and columns by label(s) or a boolean array. Notes ----- The ``items``, ``like``, and ``regex`` parameters are enforced to be mutually exclusive. ``axis`` defaults to the info axis that is used when indexing with ``[]``. Examples -------- >>> df = pd.DataFrame(np.array(([1, 2, 3], [4, 5, 6])), ... index=['mouse', 'rabbit'], ... columns=['one', 'two', 'three']) >>> df one two three mouse 1 2 3 rabbit 4 5 6 >>> # select columns by name >>> df.filter(items=['one', 'three']) one three mouse 1 3 rabbit 4 6 >>> # select columns by regular expression >>> df.filter(regex='e$', axis=1) one three mouse 1 3 rabbit 4 6 >>> # select rows containing 'bbi' >>> df.filter(like='bbi', axis=0) one two three rabbit 4 5 6 """ nkw = com.count_not_none(items, like, regex) if nkw > 1: raise TypeError( "Keyword arguments `items`, `like`, or `regex` " "are mutually exclusive" ) if axis is None: axis = self._info_axis_name labels = self._get_axis(axis) if items is not None: name = self._get_axis_name(axis) return self.reindex(**{name: [r for r in items if r in labels]}) elif like: def f(x): return like in ensure_str(x) values = labels.map(f) return self.loc(axis=axis)[values] elif regex: def f(x): return matcher.search(ensure_str(x)) is not None matcher = re.compile(regex) values = labels.map(f) return self.loc(axis=axis)[values] else: raise TypeError("Must pass either `items`, `like`, or `regex`") def head(self: FrameOrSeries, n: int = 5) -> FrameOrSeries: """ Return the first `n` rows. This function returns the first `n` rows for the object based on position. It is useful for quickly testing if your object has the right type of data in it. For negative values of `n`, this function returns all rows except the last `n` rows, equivalent to ``df[:-n]``. Parameters ---------- n : int, default 5 Number of rows to select. Returns ------- same type as caller The first `n` rows of the caller object. See Also -------- DataFrame.tail: Returns the last `n` rows. Examples -------- >>> df = pd.DataFrame({'animal': ['alligator', 'bee', 'falcon', 'lion', ... 'monkey', 'parrot', 'shark', 'whale', 'zebra']}) >>> df animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey 5 parrot 6 shark 7 whale 8 zebra Viewing the first 5 lines >>> df.head() animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey Viewing the first `n` lines (three in this case) >>> df.head(3) animal 0 alligator 1 bee 2 falcon For negative values of `n` >>> df.head(-3) animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey 5 parrot """ return self.iloc[:n] def tail(self: FrameOrSeries, n: int = 5) -> FrameOrSeries: """ Return the last `n` rows. This function returns last `n` rows from the object based on position. It is useful for quickly verifying data, for example, after sorting or appending rows. For negative values of `n`, this function returns all rows except the first `n` rows, equivalent to ``df[n:]``. Parameters ---------- n : int, default 5 Number of rows to select. Returns ------- type of caller The last `n` rows of the caller object. See Also -------- DataFrame.head : The first `n` rows of the caller object. Examples -------- >>> df = pd.DataFrame({'animal': ['alligator', 'bee', 'falcon', 'lion', ... 'monkey', 'parrot', 'shark', 'whale', 'zebra']}) >>> df animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey 5 parrot 6 shark 7 whale 8 zebra Viewing the last 5 lines >>> df.tail() animal 4 monkey 5 parrot 6 shark 7 whale 8 zebra Viewing the last `n` lines (three in this case) >>> df.tail(3) animal 6 shark 7 whale 8 zebra For negative values of `n` >>> df.tail(-3) animal 3 lion 4 monkey 5 parrot 6 shark 7 whale 8 zebra """ if n == 0: return self.iloc[0:0] return self.iloc[-n:] def sample( self: FrameOrSeries, n=None, frac=None, replace=False, weights=None, random_state=None, axis=None, ) -> FrameOrSeries: """ Return a random sample of items from an axis of object. You can use `random_state` for reproducibility. Parameters ---------- n : int, optional Number of items from axis to return. Cannot be used with `frac`. Default = 1 if `frac` = None. frac : float, optional Fraction of axis items to return. Cannot be used with `n`. replace : bool, default False Allow or disallow sampling of the same row more than once. weights : str or ndarray-like, optional Default 'None' results in equal probability weighting. If passed a Series, will align with target object on index. Index values in weights not found in sampled object will be ignored and index values in sampled object not in weights will be assigned weights of zero. If called on a DataFrame, will accept the name of a column when axis = 0. Unless weights are a Series, weights must be same length as axis being sampled. If weights do not sum to 1, they will be normalized to sum to 1. Missing values in the weights column will be treated as zero. Infinite values not allowed. random_state : int, array-like, BitGenerator, np.random.RandomState, optional If int, array-like, or BitGenerator (NumPy>=1.17), seed for random number generator If np.random.RandomState, use as numpy RandomState object. ..versionchanged:: 1.1.0 array-like and BitGenerator (for NumPy>=1.17) object now passed to np.random.RandomState() as seed axis : {0 or ‘index’, 1 or ‘columns’, None}, default None Axis to sample. Accepts axis number or name. Default is stat axis for given data type (0 for Series and DataFrames). Returns ------- Series or DataFrame A new object of same type as caller containing `n` items randomly sampled from the caller object. See Also -------- numpy.random.choice: Generates a random sample from a given 1-D numpy array. Notes ----- If `frac` > 1, `replacement` should be set to `True`. Examples -------- >>> df = pd.DataFrame({'num_legs': [2, 4, 8, 0], ... 'num_wings': [2, 0, 0, 0], ... 'num_specimen_seen': [10, 2, 1, 8]}, ... index=['falcon', 'dog', 'spider', 'fish']) >>> df num_legs num_wings num_specimen_seen falcon 2 2 10 dog 4 0 2 spider 8 0 1 fish 0 0 8 Extract 3 random elements from the ``Series`` ``df['num_legs']``: Note that we use `random_state` to ensure the reproducibility of the examples. >>> df['num_legs'].sample(n=3, random_state=1) fish 0 spider 8 falcon 2 Name: num_legs, dtype: int64 A random 50% sample of the ``DataFrame`` with replacement: >>> df.sample(frac=0.5, replace=True, random_state=1) num_legs num_wings num_specimen_seen dog 4 0 2 fish 0 0 8 An upsample sample of the ``DataFrame`` with replacement: Note that `replace` parameter has to be `True` for `frac` parameter > 1. >>> df.sample(frac=2, replace=True, random_state=1) num_legs num_wings num_specimen_seen dog 4 0 2 fish 0 0 8 falcon 2 2 10 falcon 2 2 10 fish 0 0 8 dog 4 0 2 fish 0 0 8 dog 4 0 2 Using a DataFrame column as weights. Rows with larger value in the `num_specimen_seen` column are more likely to be sampled. >>> df.sample(n=2, weights='num_specimen_seen', random_state=1) num_legs num_wings num_specimen_seen falcon 2 2 10 fish 0 0 8 """ if axis is None: axis = self._stat_axis_number axis = self._get_axis_number(axis) axis_length = self.shape[axis] # Process random_state argument rs = com.random_state(random_state) # Check weights for compliance if weights is not None: # If a series, align with frame if isinstance(weights, ABCSeries): weights = weights.reindex(self.axes[axis]) # Strings acceptable if a dataframe and axis = 0 if isinstance(weights, str): if isinstance(self, ABCDataFrame): if axis == 0: try: weights = self[weights] except KeyError as err: raise KeyError( "String passed to weights not a valid column" ) from err else: raise ValueError( "Strings can only be passed to " "weights when sampling from rows on " "a DataFrame" ) else: raise ValueError( "Strings cannot be passed as weights " "when sampling from a Series." ) weights = pd.Series(weights, dtype="float64") if len(weights) != axis_length: raise ValueError( "Weights and axis to be sampled must be of same length" ) if (weights == np.inf).any() or (weights == -np.inf).any(): raise ValueError("weight vector may not include `inf` values") if (weights < 0).any(): raise ValueError("weight vector many not include negative values") # If has nan, set to zero. weights = weights.fillna(0) # Renormalize if don't sum to 1 if weights.sum() != 1: if weights.sum() != 0: weights = weights / weights.sum() else: raise ValueError("Invalid weights: weights sum to zero") weights = weights._values # If no frac or n, default to n=1. if n is None and frac is None: n = 1 elif frac is not None and frac > 1 and not replace: raise ValueError( "Replace has to be set to `True` when " "upsampling the population `frac` > 1." ) elif n is not None and frac is None and n % 1 != 0: raise ValueError("Only integers accepted as `n` values") elif n is None and frac is not None: n = int(round(frac * axis_length)) elif n is not None and frac is not None: raise ValueError("Please enter a value for `frac` OR `n`, not both") # Check for negative sizes if n < 0: raise ValueError( "A negative number of rows requested. Please provide positive value." ) locs = rs.choice(axis_length, size=n, replace=replace, p=weights) return self.take(locs, axis=axis) _shared_docs[ "pipe" ] = r""" Apply func(self, \*args, \*\*kwargs). Parameters ---------- func : function Function to apply to the %(klass)s. ``args``, and ``kwargs`` are passed into ``func``. Alternatively a ``(callable, data_keyword)`` tuple where ``data_keyword`` is a string indicating the keyword of ``callable`` that expects the %(klass)s. args : iterable, optional Positional arguments passed into ``func``. kwargs : mapping, optional A dictionary of keyword arguments passed into ``func``. Returns ------- object : the return type of ``func``. See Also -------- DataFrame.apply : Apply a function along input axis of DataFrame. DataFrame.applymap : Apply a function elementwise on a whole DataFrame. Series.map : Apply a mapping correspondence on a :class:`~pandas.Series`. Notes ----- Use ``.pipe`` when chaining together functions that expect Series, DataFrames or GroupBy objects. Instead of writing >>> func(g(h(df), arg1=a), arg2=b, arg3=c) # doctest: +SKIP You can write >>> (df.pipe(h) ... .pipe(g, arg1=a) ... .pipe(func, arg2=b, arg3=c) ... ) # doctest: +SKIP If you have a function that takes the data as (say) the second argument, pass a tuple indicating which keyword expects the data. For example, suppose ``f`` takes its data as ``arg2``: >>> (df.pipe(h) ... .pipe(g, arg1=a) ... .pipe((func, 'arg2'), arg1=a, arg3=c) ... ) # doctest: +SKIP """ @Appender(_shared_docs["pipe"] % _shared_doc_kwargs) def pipe(self, func, *args, **kwargs): return com.pipe(self, func, *args, **kwargs) _shared_docs["aggregate"] = dedent( """ Aggregate using one or more operations over the specified axis. %(versionadded)s Parameters ---------- func : function, str, list or dict Function to use for aggregating the data. If a function, must either work when passed a %(klass)s or when passed to %(klass)s.apply. Accepted combinations are: - function - string function name - list of functions and/or function names, e.g. ``[np.sum, 'mean']`` - dict of axis labels -> functions, function names or list of such. %(axis)s *args Positional arguments to pass to `func`. **kwargs Keyword arguments to pass to `func`. Returns ------- scalar, Series or DataFrame The return can be: * scalar : when Series.agg is called with single function * Series : when DataFrame.agg is called with a single function * DataFrame : when DataFrame.agg is called with several functions Return scalar, Series or DataFrame. %(see_also)s Notes ----- `agg` is an alias for `aggregate`. Use the alias. A passed user-defined-function will be passed a Series for evaluation. %(examples)s""" ) _shared_docs[ "transform" ] = """ Call ``func`` on self producing a %(klass)s with transformed values. Produced %(klass)s will have same axis length as self. Parameters ---------- func : function, str, list or dict Function to use for transforming the data. If a function, must either work when passed a %(klass)s or when passed to %(klass)s.apply. Accepted combinations are: - function - string function name - list of functions and/or function names, e.g. ``[np.exp. 'sqrt']`` - dict of axis labels -> functions, function names or list of such. %(axis)s *args Positional arguments to pass to `func`. **kwargs Keyword arguments to pass to `func`. Returns ------- %(klass)s A %(klass)s that must have the same length as self. Raises ------ ValueError : If the returned %(klass)s has a different length than self. See Also -------- %(klass)s.agg : Only perform aggregating type operations. %(klass)s.apply : Invoke function on a %(klass)s. Examples -------- >>> df = pd.DataFrame({'A': range(3), 'B': range(1, 4)}) >>> df A B 0 0 1 1 1 2 2 2 3 >>> df.transform(lambda x: x + 1) A B 0 1 2 1 2 3 2 3 4 Even though the resulting %(klass)s must have the same length as the input %(klass)s, it is possible to provide several input functions: >>> s = pd.Series(range(3)) >>> s 0 0 1 1 2 2 dtype: int64 >>> s.transform([np.sqrt, np.exp]) sqrt exp 0 0.000000 1.000000 1 1.000000 2.718282 2 1.414214 7.389056 """ # ---------------------------------------------------------------------- # Attribute access def __finalize__( self: FrameOrSeries, other, method: Optional[str] = None, **kwargs ) -> FrameOrSeries: """ Propagate metadata from other to self. Parameters ---------- other : the object from which to get the attributes that we are going to propagate method : str, optional A passed method name providing context on where ``__finalize__`` was called. .. warning: The value passed as `method` are not currently considered stable across pandas releases. """ if isinstance(other, NDFrame): for name in other.attrs: self.attrs[name] = other.attrs[name] # For subclasses using _metadata. for name in self._metadata: assert isinstance(name, str) object.__setattr__(self, name, getattr(other, name, None)) return self def __getattr__(self, name: str): """ After regular attribute access, try looking up the name This allows simpler access to columns for interactive use. """ # Note: obj.x will always call obj.__getattribute__('x') prior to # calling obj.__getattr__('x'). if ( name in self._internal_names_set or name in self._metadata or name in self._accessors ): return object.__getattribute__(self, name) else: if self._info_axis._can_hold_identifiers_and_holds_name(name): return self[name] return object.__getattribute__(self, name) def __setattr__(self, name: str, value) -> None: """ After regular attribute access, try setting the name This allows simpler access to columns for interactive use. """ # first try regular attribute access via __getattribute__, so that # e.g. ``obj.x`` and ``obj.x = 4`` will always reference/modify # the same attribute. try: object.__getattribute__(self, name) return object.__setattr__(self, name, value) except AttributeError: pass # if this fails, go on to more involved attribute setting # (note that this matches __getattr__, above). if name in self._internal_names_set: object.__setattr__(self, name, value) elif name in self._metadata: object.__setattr__(self, name, value) else: try: existing = getattr(self, name) if isinstance(existing, Index): object.__setattr__(self, name, value) elif name in self._info_axis: self[name] = value else: object.__setattr__(self, name, value) except (AttributeError, TypeError): if isinstance(self, ABCDataFrame) and (is_list_like(value)): warnings.warn( "Pandas doesn't allow columns to be " "created via a new attribute name - see " "https://pandas.pydata.org/pandas-docs/" "stable/indexing.html#attribute-access", stacklevel=2, ) object.__setattr__(self, name, value) def _dir_additions(self): """ add the string-like attributes from the info_axis. If info_axis is a MultiIndex, it's first level values are used. """ additions = { c for c in self._info_axis.unique(level=0)[:100] if isinstance(c, str) and c.isidentifier() } return super()._dir_additions().union(additions) # ---------------------------------------------------------------------- # Consolidation of internals def _protect_consolidate(self, f): """ Consolidate _mgr -- if the blocks have changed, then clear the cache """ blocks_before = len(self._mgr.blocks) result = f() if len(self._mgr.blocks) != blocks_before: self._clear_item_cache() return result def _consolidate_inplace(self) -> None: """Consolidate data in place and return None""" def f(): self._mgr = self._mgr.consolidate() self._protect_consolidate(f) def _consolidate(self, inplace: bool_t = False): """ Compute NDFrame with "consolidated" internals (data of each dtype grouped together in a single ndarray). Parameters ---------- inplace : bool, default False If False return new object, otherwise modify existing object. Returns ------- consolidated : same type as caller """ inplace = validate_bool_kwarg(inplace, "inplace") if inplace: self._consolidate_inplace() else: f = lambda: self._mgr.consolidate() cons_data = self._protect_consolidate(f) return self._constructor(cons_data).__finalize__(self) @property def _is_mixed_type(self) -> bool_t: f = lambda: self._mgr.is_mixed_type return self._protect_consolidate(f) @property def _is_numeric_mixed_type(self) -> bool_t: f = lambda: self._mgr.is_numeric_mixed_type return self._protect_consolidate(f) def _check_inplace_setting(self, value) -> bool_t: """ check whether we allow in-place setting with this type of value """ if self._is_mixed_type: if not self._is_numeric_mixed_type: # allow an actual np.nan thru if is_float(value) and np.isnan(value): return True raise TypeError( "Cannot do inplace boolean setting on " "mixed-types with a non np.nan value" ) return True def _get_numeric_data(self): return self._constructor(self._mgr.get_numeric_data()).__finalize__(self) def _get_bool_data(self): return self._constructor(self._mgr.get_bool_data()).__finalize__(self) # ---------------------------------------------------------------------- # Internal Interface Methods @property def values(self) -> np.ndarray: """ Return a Numpy representation of the DataFrame. .. warning:: We recommend using :meth:`DataFrame.to_numpy` instead. Only the values in the DataFrame will be returned, the axes labels will be removed. Returns ------- numpy.ndarray The values of the DataFrame. See Also -------- DataFrame.to_numpy : Recommended alternative to this method. DataFrame.index : Retrieve the index labels. DataFrame.columns : Retrieving the column names. Notes ----- The dtype will be a lower-common-denominator dtype (implicit upcasting); that is to say if the dtypes (even of numeric types) are mixed, the one that accommodates all will be chosen. Use this with care if you are not dealing with the blocks. e.g. If the dtypes are float16 and float32, dtype will be upcast to float32. If dtypes are int32 and uint8, dtype will be upcast to int32. By :func:`numpy.find_common_type` convention, mixing int64 and uint64 will result in a float64 dtype. Examples -------- A DataFrame where all columns are the same type (e.g., int64) results in an array of the same type. >>> df = pd.DataFrame({'age': [ 3, 29], ... 'height': [94, 170], ... 'weight': [31, 115]}) >>> df age height weight 0 3 94 31 1 29 170 115 >>> df.dtypes age int64 height int64 weight int64 dtype: object >>> df.values array([[ 3, 94, 31], [ 29, 170, 115]]) A DataFrame with mixed type columns(e.g., str/object, int64, float32) results in an ndarray of the broadest type that accommodates these mixed types (e.g., object). >>> df2 = pd.DataFrame([('parrot', 24.0, 'second'), ... ('lion', 80.5, 1), ... ('monkey', np.nan, None)], ... columns=('name', 'max_speed', 'rank')) >>> df2.dtypes name object max_speed float64 rank object dtype: object >>> df2.values array([['parrot', 24.0, 'second'], ['lion', 80.5, 1], ['monkey', nan, None]], dtype=object) """ return self._mgr.as_array(transpose=self._AXIS_REVERSED) @property def _values(self) -> np.ndarray: """internal implementation""" return self.values @property def dtypes(self): """ Return the dtypes in the DataFrame. This returns a Series with the data type of each column. The result's index is the original DataFrame's columns. Columns with mixed types are stored with the ``object`` dtype. See :ref:`the User Guide <basics.dtypes>` for more. Returns ------- pandas.Series The data type of each column. Examples -------- >>> df = pd.DataFrame({'float': [1.0], ... 'int': [1], ... 'datetime': [pd.Timestamp('20180310')], ... 'string': ['foo']}) >>> df.dtypes float float64 int int64 datetime datetime64[ns] string object dtype: object """ from pandas import Series return Series(self._mgr.get_dtypes(), index=self._info_axis, dtype=np.object_) def _to_dict_of_blocks(self, copy: bool_t = True): """ Return a dict of dtype -> Constructor Types that each is a homogeneous dtype. Internal ONLY """ return { k: self._constructor(v).__finalize__(self) for k, v, in self._mgr.to_dict(copy=copy).items() } def astype( self: FrameOrSeries, dtype, copy: bool_t = True, errors: str = "raise" ) -> FrameOrSeries: """ Cast a pandas object to a specified dtype ``dtype``. Parameters ---------- dtype : data type, or dict of column name -> data type Use a numpy.dtype or Python type to cast entire pandas object to the same type. Alternatively, use {col: dtype, ...}, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame's columns to column-specific types. copy : bool, default True Return a copy when ``copy=True`` (be very careful setting ``copy=False`` as changes to values then may propagate to other pandas objects). errors : {'raise', 'ignore'}, default 'raise' Control raising of exceptions on invalid data for provided dtype. - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress exceptions. On error return original object. Returns ------- casted : same type as caller See Also -------- to_datetime : Convert argument to datetime. to_timedelta : Convert argument to timedelta. to_numeric : Convert argument to a numeric type. numpy.ndarray.astype : Cast a numpy array to a specified type. Examples -------- Create a DataFrame: >>> d = {'col1': [1, 2], 'col2': [3, 4]} >>> df = pd.DataFrame(data=d) >>> df.dtypes col1 int64 col2 int64 dtype: object Cast all columns to int32: >>> df.astype('int32').dtypes col1 int32 col2 int32 dtype: object Cast col1 to int32 using a dictionary: >>> df.astype({'col1': 'int32'}).dtypes col1 int32 col2 int64 dtype: object Create a series: >>> ser = pd.Series([1, 2], dtype='int32') >>> ser 0 1 1 2 dtype: int32 >>> ser.astype('int64') 0 1 1 2 dtype: int64 Convert to categorical type: >>> ser.astype('category') 0 1 1 2 dtype: category Categories (2, int64): [1, 2] Convert to ordered categorical type with custom ordering: >>> cat_dtype = pd.api.types.CategoricalDtype( ... categories=[2, 1], ordered=True) >>> ser.astype(cat_dtype) 0 1 1 2 dtype: category Categories (2, int64): [2 < 1] Note that using ``copy=False`` and changing data on a new pandas object may propagate changes: >>> s1 = pd.Series([1, 2]) >>> s2 = s1.astype('int64', copy=False) >>> s2[0] = 10 >>> s1 # note that s1[0] has changed too 0 10 1 2 dtype: int64 Create a series of dates: >>> ser_date = pd.Series(pd.date_range('20200101', periods=3)) >>> ser_date 0 2020-01-01 1 2020-01-02 2 2020-01-03 dtype: datetime64[ns] Datetimes are localized to UTC first before converting to the specified timezone: >>> ser_date.astype('datetime64[ns, US/Eastern]') 0 2019-12-31 19:00:00-05:00 1 2020-01-01 19:00:00-05:00 2 2020-01-02 19:00:00-05:00 dtype: datetime64[ns, US/Eastern] """ if is_dict_like(dtype): if self.ndim == 1: # i.e. Series if len(dtype) > 1 or self.name not in dtype: raise KeyError( "Only the Series name can be used for " "the key in Series dtype mappings." ) new_type = dtype[self.name] return self.astype(new_type, copy, errors) for col_name in dtype.keys(): if col_name not in self: raise KeyError( "Only a column name can be used for the " "key in a dtype mappings argument." ) results = [] for col_name, col in self.items(): if col_name in dtype: results.append( col.astype(dtype=dtype[col_name], copy=copy, errors=errors) ) else: results.append(col.copy() if copy else col) elif is_extension_array_dtype(dtype) and self.ndim > 1: # GH 18099/22869: columnwise conversion to extension dtype # GH 24704: use iloc to handle duplicate column names results = [ self.iloc[:, i].astype(dtype, copy=copy) for i in range(len(self.columns)) ] else: # else, only a single dtype is given new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors,) return self._constructor(new_data).__finalize__(self, method="astype") # GH 19920: retain column metadata after concat result = pd.concat(results, axis=1, copy=False) result.columns = self.columns return result def copy(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: """ Make a copy of this object's indices and data. When ``deep=True`` (default), a new object will be created with a copy of the calling object's data and indices. Modifications to the data or indices of the copy will not be reflected in the original object (see notes below). When ``deep=False``, a new object will be created without copying the calling object's data or index (only references to the data and index are copied). Any changes to the data of the original will be reflected in the shallow copy (and vice versa). Parameters ---------- deep : bool, default True Make a deep copy, including a copy of the data and the indices. With ``deep=False`` neither the indices nor the data are copied. Returns ------- copy : Series or DataFrame Object type matches caller. Notes ----- When ``deep=True``, data is copied but actual Python objects will not be copied recursively, only the reference to the object. This is in contrast to `copy.deepcopy` in the Standard Library, which recursively copies object data (see examples below). While ``Index`` objects are copied when ``deep=True``, the underlying numpy array is not copied for performance reasons. Since ``Index`` is immutable, the underlying data can be safely shared and a copy is not needed. Examples -------- >>> s = pd.Series([1, 2], index=["a", "b"]) >>> s a 1 b 2 dtype: int64 >>> s_copy = s.copy() >>> s_copy a 1 b 2 dtype: int64 **Shallow copy versus default (deep) copy:** >>> s = pd.Series([1, 2], index=["a", "b"]) >>> deep = s.copy() >>> shallow = s.copy(deep=False) Shallow copy shares data and index with original. >>> s is shallow False >>> s.values is shallow.values and s.index is shallow.index True Deep copy has own copy of data and index. >>> s is deep False >>> s.values is deep.values or s.index is deep.index False Updates to the data shared by shallow copy and original is reflected in both; deep copy remains unchanged. >>> s[0] = 3 >>> shallow[1] = 4 >>> s a 3 b 4 dtype: int64 >>> shallow a 3 b 4 dtype: int64 >>> deep a 1 b 2 dtype: int64 Note that when copying an object containing Python objects, a deep copy will copy the data, but will not do so recursively. Updating a nested data object will be reflected in the deep copy. >>> s = pd.Series([[1, 2], [3, 4]]) >>> deep = s.copy() >>> s[0][0] = 10 >>> s 0 [10, 2] 1 [3, 4] dtype: object >>> deep 0 [10, 2] 1 [3, 4] dtype: object """ data = self._mgr.copy(deep=deep) self._clear_item_cache() return self._constructor(data).__finalize__(self, method="copy") def __copy__(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: return self.copy(deep=deep) def __deepcopy__(self: FrameOrSeries, memo=None) -> FrameOrSeries: """ Parameters ---------- memo, default None Standard signature. Unused """ return self.copy(deep=True) def _convert( self: FrameOrSeries, datetime: bool_t = False, numeric: bool_t = False, timedelta: bool_t = False, coerce: bool_t = False, ) -> FrameOrSeries: """ Attempt to infer better dtype for object columns Parameters ---------- datetime : bool, default False If True, convert to date where possible. numeric : bool, default False If True, attempt to convert to numbers (including strings), with unconvertible values becoming NaN. timedelta : bool, default False If True, convert to timedelta where possible. coerce : bool, default False If True, force conversion with unconvertible values converted to nulls (NaN or NaT). Returns ------- converted : same as input object """ validate_bool_kwarg(datetime, "datetime") validate_bool_kwarg(numeric, "numeric") validate_bool_kwarg(timedelta, "timedelta") validate_bool_kwarg(coerce, "coerce") return self._constructor( self._mgr.convert( datetime=datetime, numeric=numeric, timedelta=timedelta, coerce=coerce, copy=True, ) ).__finalize__(self) def infer_objects(self: FrameOrSeries) -> FrameOrSeries: """ Attempt to infer better dtypes for object columns. Attempts soft conversion of object-dtyped columns, leaving non-object and unconvertible columns unchanged. The inference rules are the same as during normal Series/DataFrame construction. Returns ------- converted : same type as input object See Also -------- to_datetime : Convert argument to datetime. to_timedelta : Convert argument to timedelta. to_numeric : Convert argument to numeric type. convert_dtypes : Convert argument to best possible dtype. Examples -------- >>> df = pd.DataFrame({"A": ["a", 1, 2, 3]}) >>> df = df.iloc[1:] >>> df A 1 1 2 2 3 3 >>> df.dtypes A object dtype: object >>> df.infer_objects().dtypes A int64 dtype: object """ # numeric=False necessary to only soft convert; # python objects will still be converted to # native numpy numeric types return self._constructor( self._mgr.convert( datetime=True, numeric=False, timedelta=True, coerce=False, copy=True ) ).__finalize__(self, method="infer_objects") def convert_dtypes( self: FrameOrSeries, infer_objects: bool_t = True, convert_string: bool_t = True, convert_integer: bool_t = True, convert_boolean: bool_t = True, ) -> FrameOrSeries: """ Convert columns to best possible dtypes using dtypes supporting ``pd.NA``. .. versionadded:: 1.0.0 Parameters ---------- infer_objects : bool, default True Whether object dtypes should be converted to the best possible types. convert_string : bool, default True Whether object dtypes should be converted to ``StringDtype()``. convert_integer : bool, default True Whether, if possible, conversion can be done to integer extension types. convert_boolean : bool, defaults True Whether object dtypes should be converted to ``BooleanDtypes()``. Returns ------- Series or DataFrame Copy of input object with new dtype. See Also -------- infer_objects : Infer dtypes of objects. to_datetime : Convert argument to datetime. to_timedelta : Convert argument to timedelta. to_numeric : Convert argument to a numeric type. Notes ----- By default, ``convert_dtypes`` will attempt to convert a Series (or each Series in a DataFrame) to dtypes that support ``pd.NA``. By using the options ``convert_string``, ``convert_integer``, and ``convert_boolean``, it is possible to turn off individual conversions to ``StringDtype``, the integer extension types or ``BooleanDtype``, respectively. For object-dtyped columns, if ``infer_objects`` is ``True``, use the inference rules as during normal Series/DataFrame construction. Then, if possible, convert to ``StringDtype``, ``BooleanDtype`` or an appropriate integer extension type, otherwise leave as ``object``. If the dtype is integer, convert to an appropriate integer extension type. If the dtype is numeric, and consists of all integers, convert to an appropriate integer extension type. In the future, as new dtypes are added that support ``pd.NA``, the results of this method will change to support those new dtypes. Examples -------- >>> df = pd.DataFrame( ... { ... "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")), ... "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")), ... "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")), ... "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")), ... "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")), ... "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")), ... } ... ) Start with a DataFrame with default dtypes. >>> df a b c d e f 0 1 x True h 10.0 NaN 1 2 y False i NaN 100.5 2 3 z NaN NaN 20.0 200.0 >>> df.dtypes a int32 b object c object d object e float64 f float64 dtype: object Convert the DataFrame to use best possible dtypes. >>> dfn = df.convert_dtypes() >>> dfn a b c d e f 0 1 x True h 10 NaN 1 2 y False i <NA> 100.5 2 3 z <NA> <NA> 20 200.0 >>> dfn.dtypes a Int32 b string c boolean d string e Int64 f float64 dtype: object Start with a Series of strings and missing data represented by ``np.nan``. >>> s = pd.Series(["a", "b", np.nan]) >>> s 0 a 1 b 2 NaN dtype: object Obtain a Series with dtype ``StringDtype``. >>> s.convert_dtypes() 0 a 1 b 2 <NA> dtype: string """ if self.ndim == 1: return self._convert_dtypes( infer_objects, convert_string, convert_integer, convert_boolean ) else: results = [ col._convert_dtypes( infer_objects, convert_string, convert_integer, convert_boolean ) for col_name, col in self.items() ] result = pd.concat(results, axis=1, copy=False) return result # ---------------------------------------------------------------------- # Filling NA's @doc(**_shared_doc_kwargs) def fillna( self: FrameOrSeries, value=None, method=None, axis=None, inplace: bool_t = False, limit=None, downcast=None, ) -> Optional[FrameOrSeries]: """ Fill NA/NaN values using the specified method. Parameters ---------- value : scalar, dict, Series, or DataFrame Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of values specifying which value to use for each index (for a Series) or column (for a DataFrame). Values not in the dict/Series/DataFrame will not be filled. This value cannot be a list. method : {{'backfill', 'bfill', 'pad', 'ffill', None}}, default None Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use next valid observation to fill gap. axis : {axes_single_arg} Axis along which to fill missing values. inplace : bool, default False If True, fill in-place. Note: this will modify any other views on this object (e.g., a no-copy slice for a column in a DataFrame). limit : int, default None If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None. downcast : dict, default is None A dict of item->dtype of what to downcast if possible, or the string 'infer' which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible). Returns ------- {klass} or None Object with missing values filled or None if ``inplace=True``. See Also -------- interpolate : Fill NaN values using interpolation. reindex : Conform object to new index. asfreq : Convert TimeSeries to specified frequency. Examples -------- >>> df = pd.DataFrame([[np.nan, 2, np.nan, 0], ... [3, 4, np.nan, 1], ... [np.nan, np.nan, np.nan, 5], ... [np.nan, 3, np.nan, 4]], ... columns=list('ABCD')) >>> df A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 2 NaN NaN NaN 5 3 NaN 3.0 NaN 4 Replace all NaN elements with 0s. >>> df.fillna(0) A B C D 0 0.0 2.0 0.0 0 1 3.0 4.0 0.0 1 2 0.0 0.0 0.0 5 3 0.0 3.0 0.0 4 We can also propagate non-null values forward or backward. >>> df.fillna(method='ffill') A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 2 3.0 4.0 NaN 5 3 3.0 3.0 NaN 4 Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1, 2, and 3 respectively. >>> values = {{'A': 0, 'B': 1, 'C': 2, 'D': 3}} >>> df.fillna(value=values) A B C D 0 0.0 2.0 2.0 0 1 3.0 4.0 2.0 1 2 0.0 1.0 2.0 5 3 0.0 3.0 2.0 4 Only replace the first NaN element. >>> df.fillna(value=values, limit=1) A B C D 0 0.0 2.0 2.0 0 1 3.0 4.0 NaN 1 2 NaN 1.0 NaN 5 3 NaN 3.0 NaN 4 """ inplace = validate_bool_kwarg(inplace, "inplace") value, method = validate_fillna_kwargs(value, method) # set the default here, so functions examining the signaure # can detect if something was set (e.g. in groupby) (GH9221) if axis is None: axis = 0 axis = self._get_axis_number(axis) if value is None: if self._is_mixed_type and axis == 1: if inplace: raise NotImplementedError() result = self.T.fillna(method=method, limit=limit).T # need to downcast here because of all of the transposes result._mgr = result._mgr.downcast() return result new_data = self._mgr.interpolate( method=method, axis=axis, limit=limit, inplace=inplace, coerce=True, downcast=downcast, ) else: if self.ndim == 1: if isinstance(value, (dict, ABCSeries)): value = create_series_with_explicit_dtype( value, dtype_if_empty=object ) value = value.reindex(self.index, copy=False) value = value._values elif not is_list_like(value): pass else: raise TypeError( '"value" parameter must be a scalar, dict ' "or Series, but you passed a " f'"{type(value).__name__}"' ) new_data = self._mgr.fillna( value=value, limit=limit, inplace=inplace, downcast=downcast ) elif isinstance(value, (dict, ABCSeries)): if axis == 1: raise NotImplementedError( "Currently only can fill " "with dict/Series column " "by column" ) result = self if inplace else self.copy() for k, v in value.items(): if k not in result: continue obj = result[k] obj.fillna(v, limit=limit, inplace=True, downcast=downcast) return result if not inplace else None elif not is_list_like(value): new_data = self._mgr.fillna( value=value, limit=limit, inplace=inplace, downcast=downcast ) elif isinstance(value, ABCDataFrame) and self.ndim == 2: new_data = self.where(self.notna(), value)._data else: raise ValueError(f"invalid fill value with a {type(value)}") result = self._constructor(new_data) if inplace: return self._update_inplace(result) else: return result.__finalize__(self, method="fillna") def ffill( self: FrameOrSeries, axis=None, inplace: bool_t = False, limit=None, downcast=None, ) -> Optional[FrameOrSeries]: """ Synonym for :meth:`DataFrame.fillna` with ``method='ffill'``. Returns ------- %(klass)s or None Object with missing values filled or None if ``inplace=True``. """ return self.fillna( method="ffill", axis=axis, inplace=inplace, limit=limit, downcast=downcast ) def bfill( self: FrameOrSeries, axis=None, inplace: bool_t = False, limit=None, downcast=None, ) -> Optional[FrameOrSeries]: """ Synonym for :meth:`DataFrame.fillna` with ``method='bfill'``. Returns ------- %(klass)s or None Object with missing values filled or None if ``inplace=True``. """ return self.fillna( method="bfill", axis=axis, inplace=inplace, limit=limit, downcast=downcast ) @doc(klass=_shared_doc_kwargs["klass"]) def replace( self, to_replace=None, value=None, inplace=False, limit=None, regex=False, method="pad", ): """ Replace values given in `to_replace` with `value`. Values of the {klass} are replaced with other values dynamically. This differs from updating with ``.loc`` or ``.iloc``, which require you to specify a location to update with some value. Parameters ---------- to_replace : str, regex, list, dict, Series, int, float, or None How to find the values that will be replaced. * numeric, str or regex: - numeric: numeric values equal to `to_replace` will be replaced with `value` - str: string exactly matching `to_replace` will be replaced with `value` - regex: regexs matching `to_replace` will be replaced with `value` * list of str, regex, or numeric: - First, if `to_replace` and `value` are both lists, they **must** be the same length. - Second, if ``regex=True`` then all of the strings in **both** lists will be interpreted as regexs otherwise they will match directly. This doesn't matter much for `value` since there are only a few possible substitution regexes you can use. - str, regex and numeric rules apply as above. * dict: - Dicts can be used to specify different replacement values for different existing values. For example, ``{{'a': 'b', 'y': 'z'}}`` replaces the value 'a' with 'b' and 'y' with 'z'. To use a dict in this way the `value` parameter should be `None`. - For a DataFrame a dict can specify that different values should be replaced in different columns. For example, ``{{'a': 1, 'b': 'z'}}`` looks for the value 1 in column 'a' and the value 'z' in column 'b' and replaces these values with whatever is specified in `value`. The `value` parameter should not be ``None`` in this case. You can treat this as a special case of passing two lists except that you are specifying the column to search in. - For a DataFrame nested dictionaries, e.g., ``{{'a': {{'b': np.nan}}}}``, are read as follows: look in column 'a' for the value 'b' and replace it with NaN. The `value` parameter should be ``None`` to use a nested dict in this way. You can nest regular expressions as well. Note that column names (the top-level dictionary keys in a nested dictionary) **cannot** be regular expressions. * None: - This means that the `regex` argument must be a string, compiled regular expression, or list, dict, ndarray or Series of such elements. If `value` is also ``None`` then this **must** be a nested dictionary or Series. See the examples section for examples of each of these. value : scalar, dict, list, str, regex, default None Value to replace any values matching `to_replace` with. For a DataFrame a dict of values can be used to specify which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed. inplace : bool, default False If True, in place. Note: this will modify any other views on this object (e.g. a column from a DataFrame). Returns the caller if this is True. limit : int, default None Maximum size gap to forward or backward fill. regex : bool or same types as `to_replace`, default False Whether to interpret `to_replace` and/or `value` as regular expressions. If this is ``True`` then `to_replace` *must* be a string. Alternatively, this could be a regular expression or a list, dict, or array of regular expressions in which case `to_replace` must be ``None``. method : {{'pad', 'ffill', 'bfill', `None`}} The method to use when for replacement, when `to_replace` is a scalar, list or tuple and `value` is ``None``. .. versionchanged:: 0.23.0 Added to DataFrame. Returns ------- {klass} Object after replacement. Raises ------ AssertionError * If `regex` is not a ``bool`` and `to_replace` is not ``None``. TypeError * If `to_replace` is not a scalar, array-like, ``dict``, or ``None`` * If `to_replace` is a ``dict`` and `value` is not a ``list``, ``dict``, ``ndarray``, or ``Series`` * If `to_replace` is ``None`` and `regex` is not compilable into a regular expression or is a list, dict, ndarray, or Series. * When replacing multiple ``bool`` or ``datetime64`` objects and the arguments to `to_replace` does not match the type of the value being replaced ValueError * If a ``list`` or an ``ndarray`` is passed to `to_replace` and `value` but they are not the same length. See Also -------- {klass}.fillna : Fill NA values. {klass}.where : Replace values based on boolean condition. Series.str.replace : Simple string replacement. Notes ----- * Regex substitution is performed under the hood with ``re.sub``. The rules for substitution for ``re.sub`` are the same. * Regular expressions will only substitute on strings, meaning you cannot provide, for example, a regular expression matching floating point numbers and expect the columns in your frame that have a numeric dtype to be matched. However, if those floating point numbers *are* strings, then you can do this. * This method has *a lot* of options. You are encouraged to experiment and play with this method to gain intuition about how it works. * When dict is used as the `to_replace` value, it is like key(s) in the dict are the to_replace part and value(s) in the dict are the value parameter. Examples -------- **Scalar `to_replace` and `value`** >>> s = pd.Series([0, 1, 2, 3, 4]) >>> s.replace(0, 5) 0 5 1 1 2 2 3 3 4 4 dtype: int64 >>> df = pd.DataFrame({{'A': [0, 1, 2, 3, 4], ... 'B': [5, 6, 7, 8, 9], ... 'C': ['a', 'b', 'c', 'd', 'e']}}) >>> df.replace(0, 5) A B C 0 5 5 a 1 1 6 b 2 2 7 c 3 3 8 d 4 4 9 e **List-like `to_replace`** >>> df.replace([0, 1, 2, 3], 4) A B C 0 4 5 a 1 4 6 b 2 4 7 c 3 4 8 d 4 4 9 e >>> df.replace([0, 1, 2, 3], [4, 3, 2, 1]) A B C 0 4 5 a 1 3 6 b 2 2 7 c 3 1 8 d 4 4 9 e >>> s.replace([1, 2], method='bfill') 0 0 1 3 2 3 3 3 4 4 dtype: int64 **dict-like `to_replace`** >>> df.replace({{0: 10, 1: 100}}) A B C 0 10 5 a 1 100 6 b 2 2 7 c 3 3 8 d 4 4 9 e >>> df.replace({{'A': 0, 'B': 5}}, 100) A B C 0 100 100 a 1 1 6 b 2 2 7 c 3 3 8 d 4 4 9 e >>> df.replace({{'A': {{0: 100, 4: 400}}}}) A B C 0 100 5 a 1 1 6 b 2 2 7 c 3 3 8 d 4 400 9 e **Regular expression `to_replace`** >>> df = pd.DataFrame({{'A': ['bat', 'foo', 'bait'], ... 'B': ['abc', 'bar', 'xyz']}}) >>> df.replace(to_replace=r'^ba.$', value='new', regex=True) A B 0 new abc 1 foo new 2 bait xyz >>> df.replace({{'A': r'^ba.$'}}, {{'A': 'new'}}, regex=True) A B 0 new abc 1 foo bar 2 bait xyz >>> df.replace(regex=r'^ba.$', value='new') A B 0 new abc 1 foo new 2 bait xyz >>> df.replace(regex={{r'^ba.$': 'new', 'foo': 'xyz'}}) A B 0 new abc 1 xyz new 2 bait xyz >>> df.replace(regex=[r'^ba.$', 'foo'], value='new') A B 0 new abc 1 new new 2 bait xyz Note that when replacing multiple ``bool`` or ``datetime64`` objects, the data types in the `to_replace` parameter must match the data type of the value being replaced: >>> df = pd.DataFrame({{'A': [True, False, True], ... 'B': [False, True, False]}}) >>> df.replace({{'a string': 'new value', True: False}}) # raises Traceback (most recent call last): ... TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str' This raises a ``TypeError`` because one of the ``dict`` keys is not of the correct type for replacement. Compare the behavior of ``s.replace({{'a': None}})`` and ``s.replace('a', None)`` to understand the peculiarities of the `to_replace` parameter: >>> s = pd.Series([10, 'a', 'a', 'b', 'a']) When one uses a dict as the `to_replace` value, it is like the value(s) in the dict are equal to the `value` parameter. ``s.replace({{'a': None}})`` is equivalent to ``s.replace(to_replace={{'a': None}}, value=None, method=None)``: >>> s.replace({{'a': None}}) 0 10 1 None 2 None 3 b 4 None dtype: object When ``value=None`` and `to_replace` is a scalar, list or tuple, `replace` uses the method parameter (default 'pad') to do the replacement. So this is why the 'a' values are being replaced by 10 in rows 1 and 2 and 'b' in row 4 in this case. The command ``s.replace('a', None)`` is actually equivalent to ``s.replace(to_replace='a', value=None, method='pad')``: >>> s.replace('a', None) 0 10 1 10 2 10 3 b 4 b dtype: object """ if not ( is_scalar(to_replace) or is_re_compilable(to_replace) or is_list_like(to_replace) ): raise TypeError( "Expecting 'to_replace' to be either a scalar, array-like, " "dict or None, got invalid type " f"{repr(type(to_replace).__name__)}" ) inplace = validate_bool_kwarg(inplace, "inplace") if not is_bool(regex) and to_replace is not None: raise AssertionError("'to_replace' must be 'None' if 'regex' is not a bool") if value is None: # passing a single value that is scalar like # when value is None (GH5319), for compat if not is_dict_like(to_replace) and not is_dict_like(regex): to_replace = [to_replace] if isinstance(to_replace, (tuple, list)): if isinstance(self, ABCDataFrame): return self.apply( _single_replace, args=(to_replace, method, inplace, limit) ) return _single_replace(self, to_replace, method, inplace, limit) if not is_dict_like(to_replace): if not is_dict_like(regex): raise TypeError( 'If "to_replace" and "value" are both None ' 'and "to_replace" is not a list, then ' "regex must be a mapping" ) to_replace = regex regex = True items = list(to_replace.items()) keys, values = zip(*items) if items else ([], []) are_mappings = [is_dict_like(v) for v in values] if any(are_mappings): if not all(are_mappings): raise TypeError( "If a nested mapping is passed, all values " "of the top level mapping must be mappings" ) # passed a nested dict/Series to_rep_dict = {} value_dict = {} for k, v in items: keys, values = list(zip(*v.items())) or ([], []) to_rep_dict[k] = list(keys) value_dict[k] = list(values) to_replace, value = to_rep_dict, value_dict else: to_replace, value = keys, values return self.replace( to_replace, value, inplace=inplace, limit=limit, regex=regex ) else: # need a non-zero len on all axes if not self.size: return self if is_dict_like(to_replace): if is_dict_like(value): # {'A' : NA} -> {'A' : 0} # Note: Checking below for `in foo.keys()` instead of # `in foo`is needed for when we have a Series and not dict mapping = { col: (to_replace[col], value[col]) for col in to_replace.keys() if col in value.keys() and col in self } return self._replace_columnwise(mapping, inplace, regex) # {'A': NA} -> 0 elif not is_list_like(value): # Operate column-wise if self.ndim == 1: raise ValueError( "Series.replace cannot use dict-like to_replace " "and non-None value" ) mapping = { col: (to_rep, value) for col, to_rep in to_replace.items() } return self._replace_columnwise(mapping, inplace, regex) else: raise TypeError("value argument must be scalar, dict, or Series") elif is_list_like(to_replace): # [NA, ''] -> [0, 'missing'] if is_list_like(value): if len(to_replace) != len(value): raise ValueError( f"Replacement lists must match in length. " f"Expecting {len(to_replace)} got {len(value)} " ) new_data = self._mgr.replace_list( src_list=to_replace, dest_list=value, inplace=inplace, regex=regex, ) else: # [NA, ''] -> 0 new_data = self._mgr.replace( to_replace=to_replace, value=value, inplace=inplace, regex=regex ) elif to_replace is None: if not ( is_re_compilable(regex) or is_list_like(regex) or is_dict_like(regex) ): raise TypeError( f"'regex' must be a string or a compiled regular expression " f"or a list or dict of strings or regular expressions, " f"you passed a {repr(type(regex).__name__)}" ) return self.replace( regex, value, inplace=inplace, limit=limit, regex=True ) else: # dest iterable dict-like if is_dict_like(value): # NA -> {'A' : 0, 'B' : -1} # Operate column-wise if self.ndim == 1: raise ValueError( "Series.replace cannot use dict-value and " "non-None to_replace" ) mapping = {col: (to_replace, val) for col, val in value.items()} return self._replace_columnwise(mapping, inplace, regex) elif not is_list_like(value): # NA -> 0 new_data = self._mgr.replace( to_replace=to_replace, value=value, inplace=inplace, regex=regex ) else: raise TypeError( f'Invalid "to_replace" type: {repr(type(to_replace).__name__)}' ) result = self._constructor(new_data) if inplace: return self._update_inplace(result) else: return result.__finalize__(self, method="replace") _shared_docs[ "interpolate" ] = """ Please note that only ``method='linear'`` is supported for DataFrame/Series with a MultiIndex. Parameters ---------- method : str, default 'linear' Interpolation technique to use. One of: * 'linear': Ignore the index and treat the values as equally spaced. This is the only method supported on MultiIndexes. * 'time': Works on daily and higher resolution data to interpolate given length of interval. * 'index', 'values': use the actual numerical values of the index. * 'pad': Fill in NaNs using existing values. * 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'spline', 'barycentric', 'polynomial': Passed to `scipy.interpolate.interp1d`. These methods use the numerical values of the index. Both 'polynomial' and 'spline' require that you also specify an `order` (int), e.g. ``df.interpolate(method='polynomial', order=5)``. * 'krogh', 'piecewise_polynomial', 'spline', 'pchip', 'akima', 'cubicspline': Wrappers around the SciPy interpolation methods of similar names. See `Notes`. * 'from_derivatives': Refers to `scipy.interpolate.BPoly.from_derivatives` which replaces 'piecewise_polynomial' interpolation method in scipy 0.18. axis : {0 or 'index', 1 or 'columns', None}, default None Axis to interpolate along. limit : int, optional Maximum number of consecutive NaNs to fill. Must be greater than 0. inplace : bool, default False Update the data in place if possible. limit_direction : {'forward', 'backward', 'both'}, default 'forward' If limit is specified, consecutive NaNs will be filled in this direction. limit_area : {`None`, 'inside', 'outside'}, default None If limit is specified, consecutive NaNs will be filled with this restriction. * ``None``: No fill restriction. * 'inside': Only fill NaNs surrounded by valid values (interpolate). * 'outside': Only fill NaNs outside valid values (extrapolate). .. versionadded:: 0.23.0 downcast : optional, 'infer' or None, defaults to None Downcast dtypes if possible. **kwargs Keyword arguments to pass on to the interpolating function. Returns ------- Series or DataFrame Returns the same object type as the caller, interpolated at some or all ``NaN`` values. See Also -------- fillna : Fill missing values using different methods. scipy.interpolate.Akima1DInterpolator : Piecewise cubic polynomials (Akima interpolator). scipy.interpolate.BPoly.from_derivatives : Piecewise polynomial in the Bernstein basis. scipy.interpolate.interp1d : Interpolate a 1-D function. scipy.interpolate.KroghInterpolator : Interpolate polynomial (Krogh interpolator). scipy.interpolate.PchipInterpolator : PCHIP 1-d monotonic cubic interpolation. scipy.interpolate.CubicSpline : Cubic spline data interpolator. Notes ----- The 'krogh', 'piecewise_polynomial', 'spline', 'pchip' and 'akima' methods are wrappers around the respective SciPy implementations of similar names. These use the actual numerical values of the index. For more information on their behavior, see the `SciPy documentation <https://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation>`__ and `SciPy tutorial <https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html>`__. Examples -------- Filling in ``NaN`` in a :class:`~pandas.Series` via linear interpolation. >>> s = pd.Series([0, 1, np.nan, 3]) >>> s 0 0.0 1 1.0 2 NaN 3 3.0 dtype: float64 >>> s.interpolate() 0 0.0 1 1.0 2 2.0 3 3.0 dtype: float64 Filling in ``NaN`` in a Series by padding, but filling at most two consecutive ``NaN`` at a time. >>> s = pd.Series([np.nan, "single_one", np.nan, ... "fill_two_more", np.nan, np.nan, np.nan, ... 4.71, np.nan]) >>> s 0 NaN 1 single_one 2 NaN 3 fill_two_more 4 NaN 5 NaN 6 NaN 7 4.71 8 NaN dtype: object >>> s.interpolate(method='pad', limit=2) 0 NaN 1 single_one 2 single_one 3 fill_two_more 4 fill_two_more 5 fill_two_more 6 NaN 7 4.71 8 4.71 dtype: object Filling in ``NaN`` in a Series via polynomial interpolation or splines: Both 'polynomial' and 'spline' methods require that you also specify an ``order`` (int). >>> s = pd.Series([0, 2, np.nan, 8]) >>> s.interpolate(method='polynomial', order=2) 0 0.000000 1 2.000000 2 4.666667 3 8.000000 dtype: float64 Fill the DataFrame forward (that is, going down) along each column using linear interpolation. Note how the last entry in column 'a' is interpolated differently, because there is no entry after it to use for interpolation. Note how the first entry in column 'b' remains ``NaN``, because there is no entry before it to use for interpolation. >>> df = pd.DataFrame([(0.0, np.nan, -1.0, 1.0), ... (np.nan, 2.0, np.nan, np.nan), ... (2.0, 3.0, np.nan, 9.0), ... (np.nan, 4.0, -4.0, 16.0)], ... columns=list('abcd')) >>> df a b c d 0 0.0 NaN -1.0 1.0 1 NaN 2.0 NaN NaN 2 2.0 3.0 NaN 9.0 3 NaN 4.0 -4.0 16.0 >>> df.interpolate(method='linear', limit_direction='forward', axis=0) a b c d 0 0.0 NaN -1.0 1.0 1 1.0 2.0 -2.0 5.0 2 2.0 3.0 -3.0 9.0 3 2.0 4.0 -4.0 16.0 Using polynomial interpolation. >>> df['d'].interpolate(method='polynomial', order=2) 0 1.0 1 4.0 2 9.0 3 16.0 Name: d, dtype: float64 """ @Appender(_shared_docs["interpolate"] % _shared_doc_kwargs) def interpolate( self, method="linear", axis=0, limit=None, inplace=False, limit_direction="forward", limit_area=None, downcast=None, **kwargs, ): """ Interpolate values according to different methods. """ inplace = validate_bool_kwarg(inplace, "inplace") axis = self._get_axis_number(axis) if axis == 0: df = self else: df = self.T if isinstance(df.index, MultiIndex) and method != "linear": raise ValueError( "Only `method=linear` interpolation is supported on MultiIndexes." ) if df.ndim == 2 and np.all(df.dtypes == np.dtype(object)): raise TypeError( "Cannot interpolate with all object-dtype columns " "in the DataFrame. Try setting at least one " "column to a numeric dtype." ) # create/use the index if method == "linear": # prior default index = np.arange(len(df.index)) else: index = df.index methods = {"index", "values", "nearest", "time"} is_numeric_or_datetime = ( is_numeric_dtype(index.dtype) or is_datetime64_any_dtype(index.dtype) or is_timedelta64_dtype(index.dtype) ) if method not in methods and not is_numeric_or_datetime: raise ValueError( "Index column must be numeric or datetime type when " f"using {method} method other than linear. " "Try setting a numeric or datetime index column before " "interpolating." ) if isna(index).any(): raise NotImplementedError( "Interpolation with NaNs in the index " "has not been implemented. Try filling " "those NaNs before interpolating." ) data = df._mgr new_data = data.interpolate( method=method, axis=self._info_axis_number, index=index, limit=limit, limit_direction=limit_direction, limit_area=limit_area, inplace=inplace, downcast=downcast, **kwargs, ) result = self._constructor(new_data) if axis == 1: result = result.T if inplace: return self._update_inplace(result) else: return result.__finalize__(self, method="interpolate") # ---------------------------------------------------------------------- # Timeseries methods Methods def asof(self, where, subset=None): """ Return the last row(s) without any NaNs before `where`. The last row (for each element in `where`, if list) without any NaN is taken. In case of a :class:`~pandas.DataFrame`, the last row without NaN considering only the subset of columns (if not `None`) If there is no good value, NaN is returned for a Series or a Series of NaN values for a DataFrame Parameters ---------- where : date or array-like of dates Date(s) before which the last row(s) are returned. subset : str or array-like of str, default `None` For DataFrame, if not `None`, only use these columns to check for NaNs. Returns ------- scalar, Series, or DataFrame The return can be: * scalar : when `self` is a Series and `where` is a scalar * Series: when `self` is a Series and `where` is an array-like, or when `self` is a DataFrame and `where` is a scalar * DataFrame : when `self` is a DataFrame and `where` is an array-like Return scalar, Series, or DataFrame. See Also -------- merge_asof : Perform an asof merge. Similar to left join. Notes ----- Dates are assumed to be sorted. Raises if this is not the case. Examples -------- A Series and a scalar `where`. >>> s = pd.Series([1, 2, np.nan, 4], index=[10, 20, 30, 40]) >>> s 10 1.0 20 2.0 30 NaN 40 4.0 dtype: float64 >>> s.asof(20) 2.0 For a sequence `where`, a Series is returned. The first value is NaN, because the first element of `where` is before the first index value. >>> s.asof([5, 20]) 5 NaN 20 2.0 dtype: float64 Missing values are not considered. The following is ``2.0``, not NaN, even though NaN is at the index location for ``30``. >>> s.asof(30) 2.0 Take all columns into consideration >>> df = pd.DataFrame({'a': [10, 20, 30, 40, 50], ... 'b': [None, None, None, None, 500]}, ... index=pd.DatetimeIndex(['2018-02-27 09:01:00', ... '2018-02-27 09:02:00', ... '2018-02-27 09:03:00', ... '2018-02-27 09:04:00', ... '2018-02-27 09:05:00'])) >>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30', ... '2018-02-27 09:04:30'])) a b 2018-02-27 09:03:30 NaN NaN 2018-02-27 09:04:30 NaN NaN Take a single column into consideration >>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30', ... '2018-02-27 09:04:30']), ... subset=['a']) a b 2018-02-27 09:03:30 30.0 NaN 2018-02-27 09:04:30 40.0 NaN """ if isinstance(where, str): where = Timestamp(where) if not self.index.is_monotonic: raise ValueError("asof requires a sorted index") is_series = isinstance(self, ABCSeries) if is_series: if subset is not None: raise ValueError("subset is not valid for Series") else: if subset is None: subset = self.columns if not is_list_like(subset): subset = [subset] is_list = is_list_like(where) if not is_list: start = self.index[0] if isinstance(self.index, PeriodIndex): where = Period(where, freq=self.index.freq) if where < start: if not is_series: return self._constructor_sliced( index=self.columns, name=where, dtype=np.float64 ) return np.nan # It's always much faster to use a *while* loop here for # Series than pre-computing all the NAs. However a # *while* loop is extremely expensive for DataFrame # so we later pre-compute all the NAs and use the same # code path whether *where* is a scalar or list. # See PR: https://github.com/pandas-dev/pandas/pull/14476 if is_series: loc = self.index.searchsorted(where, side="right") if loc > 0: loc -= 1 values = self._values while loc > 0 and isna(values[loc]): loc -= 1 return values[loc] if not isinstance(where, Index): where = Index(where) if is_list else Index([where]) nulls = self.isna() if is_series else self[subset].isna().any(1) if nulls.all(): if is_series: return self._constructor(np.nan, index=where, name=self.name) elif is_list: return self._constructor(np.nan, index=where, columns=self.columns) else: return self._constructor_sliced( np.nan, index=self.columns, name=where[0] ) locs = self.index.asof_locs(where, ~(nulls._values)) # mask the missing missing = locs == -1 data = self.take(locs) data.index = where data.loc[missing] = np.nan return data if is_list else data.iloc[-1] # ---------------------------------------------------------------------- # Action Methods _shared_docs[ "isna" ] = """ Detect missing values. Return a boolean same-sized object indicating if the values are NA. NA values, such as None or :attr:`numpy.NaN`, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings ``''`` or :attr:`numpy.inf` are not considered NA values (unless you set ``pandas.options.mode.use_inf_as_na = True``). Returns ------- %(klass)s Mask of bool values for each element in %(klass)s that indicates whether an element is not an NA value. See Also -------- %(klass)s.isnull : Alias of isna. %(klass)s.notna : Boolean inverse of isna. %(klass)s.dropna : Omit axes labels with missing values. isna : Top-level isna. Examples -------- Show which entries in a DataFrame are NA. >>> df = pd.DataFrame({'age': [5, 6, np.NaN], ... 'born': [pd.NaT, pd.Timestamp('1939-05-27'), ... pd.Timestamp('1940-04-25')], ... 'name': ['Alfred', 'Batman', ''], ... 'toy': [None, 'Batmobile', 'Joker']}) >>> df age born name toy 0 5.0 NaT Alfred None 1 6.0 1939-05-27 Batman Batmobile 2 NaN 1940-04-25 Joker >>> df.isna() age born name toy 0 False True False True 1 False False False False 2 True False False False Show which entries in a Series are NA. >>> ser = pd.Series([5, 6, np.NaN]) >>> ser 0 5.0 1 6.0 2 NaN dtype: float64 >>> ser.isna() 0 False 1 False 2 True dtype: bool """ @Appender(_shared_docs["isna"] % _shared_doc_kwargs) def isna(self: FrameOrSeries) -> FrameOrSeries: return isna(self).__finalize__(self, method="isna") @Appender(_shared_docs["isna"] % _shared_doc_kwargs) def isnull(self: FrameOrSeries) -> FrameOrSeries: return isna(self).__finalize__(self, method="isnull") _shared_docs[ "notna" ] = """ Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to True. Characters such as empty strings ``''`` or :attr:`numpy.inf` are not considered NA values (unless you set ``pandas.options.mode.use_inf_as_na = True``). NA values, such as None or :attr:`numpy.NaN`, get mapped to False values. Returns ------- %(klass)s Mask of bool values for each element in %(klass)s that indicates whether an element is not an NA value. See Also -------- %(klass)s.notnull : Alias of notna. %(klass)s.isna : Boolean inverse of notna. %(klass)s.dropna : Omit axes labels with missing values. notna : Top-level notna. Examples -------- Show which entries in a DataFrame are not NA. >>> df = pd.DataFrame({'age': [5, 6, np.NaN], ... 'born': [pd.NaT, pd.Timestamp('1939-05-27'), ... pd.Timestamp('1940-04-25')], ... 'name': ['Alfred', 'Batman', ''], ... 'toy': [None, 'Batmobile', 'Joker']}) >>> df age born name toy 0 5.0 NaT Alfred None 1 6.0 1939-05-27 Batman Batmobile 2 NaN 1940-04-25 Joker >>> df.notna() age born name toy 0 True False True False 1 True True True True 2 False True True True Show which entries in a Series are not NA. >>> ser = pd.Series([5, 6, np.NaN]) >>> ser 0 5.0 1 6.0 2 NaN dtype: float64 >>> ser.notna() 0 True 1 True 2 False dtype: bool """ @Appender(_shared_docs["notna"] % _shared_doc_kwargs) def notna(self: FrameOrSeries) -> FrameOrSeries: return notna(self).__finalize__(self, method="notna") @Appender(_shared_docs["notna"] % _shared_doc_kwargs) def notnull(self: FrameOrSeries) -> FrameOrSeries: return notna(self).__finalize__(self, method="notnull") def _clip_with_scalar(self, lower, upper, inplace: bool_t = False): if (lower is not None and np.any(isna(lower))) or ( upper is not None and np.any(isna(upper)) ): raise ValueError("Cannot use an NA value as a clip threshold") result = self mask = isna(self._values) with np.errstate(all="ignore"): if upper is not None: subset = self.to_numpy() <= upper result = result.where(subset, upper, axis=None, inplace=False) if lower is not None: subset = self.to_numpy() >= lower result = result.where(subset, lower, axis=None, inplace=False) if np.any(mask): result[mask] = np.nan if inplace: return self._update_inplace(result) else: return result def _clip_with_one_bound(self, threshold, method, axis, inplace): if axis is not None: axis = self._get_axis_number(axis) # method is self.le for upper bound and self.ge for lower bound if is_scalar(threshold) and is_number(threshold): if method.__name__ == "le": return self._clip_with_scalar(None, threshold, inplace=inplace) return self._clip_with_scalar(threshold, None, inplace=inplace) subset = method(threshold, axis=axis) | isna(self) # GH #15390 # In order for where method to work, the threshold must # be transformed to NDFrame from other array like structure. if (not isinstance(threshold, ABCSeries)) and is_list_like(threshold): if isinstance(self, ABCSeries): threshold = self._constructor(threshold, index=self.index) else: threshold = _align_method_FRAME(self, threshold, axis, flex=None)[1] return self.where(subset, threshold, axis=axis, inplace=inplace) def clip( self: FrameOrSeries, lower=None, upper=None, axis=None, inplace: bool_t = False, *args, **kwargs, ) -> FrameOrSeries: """ Trim values at input threshold(s). Assigns values outside boundary to boundary values. Thresholds can be singular values or array like, and in the latter case the clipping is performed element-wise in the specified axis. Parameters ---------- lower : float or array_like, default None Minimum threshold value. All values below this threshold will be set to it. upper : float or array_like, default None Maximum threshold value. All values above this threshold will be set to it. axis : int or str axis name, optional Align object with lower and upper along the given axis. inplace : bool, default False Whether to perform the operation in place on the data. *args, **kwargs Additional keywords have no effect but might be accepted for compatibility with numpy. Returns ------- Series or DataFrame Same type as calling object with the values outside the clip boundaries replaced. See Also -------- Series.clip : Trim values at input threshold in series. DataFrame.clip : Trim values at input threshold in dataframe. numpy.clip : Clip (limit) the values in an array. Examples -------- >>> data = {'col_0': [9, -3, 0, -1, 5], 'col_1': [-2, -7, 6, 8, -5]} >>> df = pd.DataFrame(data) >>> df col_0 col_1 0 9 -2 1 -3 -7 2 0 6 3 -1 8 4 5 -5 Clips per column using lower and upper thresholds: >>> df.clip(-4, 6) col_0 col_1 0 6 -2 1 -3 -4 2 0 6 3 -1 6 4 5 -4 Clips using specific lower and upper thresholds per column element: >>> t = pd.Series([2, -4, -1, 6, 3]) >>> t 0 2 1 -4 2 -1 3 6 4 3 dtype: int64 >>> df.clip(t, t + 4, axis=0) col_0 col_1 0 6 2 1 -3 -4 2 0 3 3 6 8 4 5 3 """ inplace = validate_bool_kwarg(inplace, "inplace") axis = nv.validate_clip_with_axis(axis, args, kwargs) if axis is not None: axis = self._get_axis_number(axis) # GH 17276 # numpy doesn't like NaN as a clip value # so ignore # GH 19992 # numpy doesn't drop a list-like bound containing NaN if not is_list_like(lower) and np.any(isna(lower)): lower = None if not is_list_like(upper) and np.any(isna(upper)): upper = None # GH 2747 (arguments were reversed) if lower is not None and upper is not None: if is_scalar(lower) and is_scalar(upper): lower, upper = min(lower, upper), max(lower, upper) # fast-path for scalars if (lower is None or (is_scalar(lower) and is_number(lower))) and ( upper is None or (is_scalar(upper) and is_number(upper)) ): return self._clip_with_scalar(lower, upper, inplace=inplace) result = self if lower is not None: result = result._clip_with_one_bound( lower, method=self.ge, axis=axis, inplace=inplace ) if upper is not None: if inplace: result = self result = result._clip_with_one_bound( upper, method=self.le, axis=axis, inplace=inplace ) return result _shared_docs[ "groupby" ] = """ Group %(klass)s using a mapper or by a Series of columns. A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Parameters ---------- by : mapping, function, label, or list of labels Used to determine the groups for the groupby. If ``by`` is a function, it's called on each value of the object's index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series' values are first aligned; see ``.align()`` method). If an ndarray is passed, the values are used as-is determine the groups. A label or list of labels may be passed to group by the columns in ``self``. Notice that a tuple is interpreted as a (single) key. axis : {0 or 'index', 1 or 'columns'}, default 0 Split along rows (0) or columns (1). level : int, level name, or sequence of such, default None If the axis is a MultiIndex (hierarchical), group by a particular level or levels. as_index : bool, default True For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively "SQL-style" grouped output. sort : bool, default True Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group. group_keys : bool, default True When calling apply, add group keys to index to identify pieces. squeeze : bool, default False Reduce the dimensionality of the return type if possible, otherwise return a consistent type. .. deprecated:: 1.1.0 observed : bool, default False This only applies if any of the groupers are Categoricals. If True: only show observed values for categorical groupers. If False: show all values for categorical groupers. .. versionadded:: 0.23.0 dropna : bool, default True If True, and if group keys contain NA values, NA values together with row/column will be dropped. If False, NA values will also be treated as the key in groups .. versionadded:: 1.1.0 Returns ------- %(klass)sGroupBy Returns a groupby object that contains information about the groups. See Also -------- resample : Convenience method for frequency conversion and resampling of time series. Notes ----- See the `user guide <https://pandas.pydata.org/pandas-docs/stable/groupby.html>`_ for more. """ def asfreq( self: FrameOrSeries, freq, method=None, how: Optional[str] = None, normalize: bool_t = False, fill_value=None, ) -> FrameOrSeries: """ Convert TimeSeries to specified frequency. Optionally provide filling method to pad/backfill missing values. Returns the original data conformed to a new index with the specified frequency. ``resample`` is more appropriate if an operation, such as summarization, is necessary to represent the data at the new frequency. Parameters ---------- freq : DateOffset or str Frequency DateOffset or string. method : {'backfill'/'bfill', 'pad'/'ffill'}, default None Method to use for filling holes in reindexed Series (note this does not fill NaNs that already were present): * 'pad' / 'ffill': propagate last valid observation forward to next valid * 'backfill' / 'bfill': use NEXT valid observation to fill. how : {'start', 'end'}, default end For PeriodIndex only (see PeriodIndex.asfreq). normalize : bool, default False Whether to reset output index to midnight. fill_value : scalar, optional Value to use for missing values, applied during upsampling (note this does not fill NaNs that already were present). Returns ------- Same type as caller Object converted to the specified frequency. See Also -------- reindex : Conform DataFrame to new index with optional filling logic. Notes ----- To learn more about the frequency strings, please see `this link <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__. Examples -------- Start by creating a series with 4 one minute timestamps. >>> index = pd.date_range('1/1/2000', periods=4, freq='T') >>> series = pd.Series([0.0, None, 2.0, 3.0], index=index) >>> df = pd.DataFrame({'s':series}) >>> df s 2000-01-01 00:00:00 0.0 2000-01-01 00:01:00 NaN 2000-01-01 00:02:00 2.0 2000-01-01 00:03:00 3.0 Upsample the series into 30 second bins. >>> df.asfreq(freq='30S') s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 NaN 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 NaN 2000-01-01 00:03:00 3.0 Upsample again, providing a ``fill value``. >>> df.asfreq(freq='30S', fill_value=9.0) s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 9.0 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 9.0 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 9.0 2000-01-01 00:03:00 3.0 Upsample again, providing a ``method``. >>> df.asfreq(freq='30S', method='bfill') s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 2.0 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 3.0 2000-01-01 00:03:00 3.0 """ from pandas.core.resample import asfreq return asfreq( self, freq, method=method, how=how, normalize=normalize, fill_value=fill_value, ) def at_time( self: FrameOrSeries, time, asof: bool_t = False, axis=None ) -> FrameOrSeries: """ Select values at particular time of day (e.g., 9:30AM). Parameters ---------- time : datetime.time or str axis : {0 or 'index', 1 or 'columns'}, default 0 .. versionadded:: 0.24.0 Returns ------- Series or DataFrame Raises ------ TypeError If the index is not a :class:`DatetimeIndex` See Also -------- between_time : Select values between particular times of the day. first : Select initial periods of time series based on a date offset. last : Select final periods of time series based on a date offset. DatetimeIndex.indexer_at_time : Get just the index locations for values at particular time of the day. Examples -------- >>> i = pd.date_range('2018-04-09', periods=4, freq='12H') >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i) >>> ts A 2018-04-09 00:00:00 1 2018-04-09 12:00:00 2 2018-04-10 00:00:00 3 2018-04-10 12:00:00 4 >>> ts.at_time('12:00') A 2018-04-09 12:00:00 2 2018-04-10 12:00:00 4 """ if axis is None: axis = self._stat_axis_number axis = self._get_axis_number(axis) index = self._get_axis(axis) if not isinstance(index, DatetimeIndex): raise TypeError("Index must be DatetimeIndex") indexer = index.indexer_at_time(time, asof=asof) return self._take_with_is_copy(indexer, axis=axis) def between_time( self: FrameOrSeries, start_time, end_time, include_start: bool_t = True, include_end: bool_t = True, axis=None, ) -> FrameOrSeries: """ Select values between particular times of the day (e.g., 9:00-9:30 AM). By setting ``start_time`` to be later than ``end_time``, you can get the times that are *not* between the two times. Parameters ---------- start_time : datetime.time or str Initial time as a time filter limit. end_time : datetime.time or str End time as a time filter limit. include_start : bool, default True Whether the start time needs to be included in the result. include_end : bool, default True Whether the end time needs to be included in the result. axis : {0 or 'index', 1 or 'columns'}, default 0 Determine range time on index or columns value. .. versionadded:: 0.24.0 Returns ------- Series or DataFrame Data from the original object filtered to the specified dates range. Raises ------ TypeError If the index is not a :class:`DatetimeIndex` See Also -------- at_time : Select values at a particular time of the day. first : Select initial periods of time series based on a date offset. last : Select final periods of time series based on a date offset. DatetimeIndex.indexer_between_time : Get just the index locations for values between particular times of the day. Examples -------- >>> i = pd.date_range('2018-04-09', periods=4, freq='1D20min') >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i) >>> ts A 2018-04-09 00:00:00 1 2018-04-10 00:20:00 2 2018-04-11 00:40:00 3 2018-04-12 01:00:00 4 >>> ts.between_time('0:15', '0:45') A 2018-04-10 00:20:00 2 2018-04-11 00:40:00 3 You get the times that are *not* between two times by setting ``start_time`` later than ``end_time``: >>> ts.between_time('0:45', '0:15') A 2018-04-09 00:00:00 1 2018-04-12 01:00:00 4 """ if axis is None: axis = self._stat_axis_number axis = self._get_axis_number(axis) index = self._get_axis(axis) if not isinstance(index, DatetimeIndex): raise TypeError("Index must be DatetimeIndex") indexer = index.indexer_between_time( start_time, end_time, include_start=include_start, include_end=include_end, ) return self._take_with_is_copy(indexer, axis=axis) def resample( self, rule, axis=0, closed: Optional[str] = None, label: Optional[str] = None, convention: str = "start", kind: Optional[str] = None, loffset=None, base: Optional[int] = None, on=None, level=None, origin: Union[str, TimestampConvertibleTypes] = "start_day", offset: Optional[TimedeltaConvertibleTypes] = None, ) -> "Resampler": """ Resample time-series data. Convenience method for frequency conversion and resampling of time series. Object must have a datetime-like index (`DatetimeIndex`, `PeriodIndex`, or `TimedeltaIndex`), or pass datetime-like values to the `on` or `level` keyword. Parameters ---------- rule : DateOffset, Timedelta or str The offset string or object representing target conversion. axis : {0 or 'index', 1 or 'columns'}, default 0 Which axis to use for up- or down-sampling. For `Series` this will default to 0, i.e. along the rows. Must be `DatetimeIndex`, `TimedeltaIndex` or `PeriodIndex`. closed : {'right', 'left'}, default None Which side of bin interval is closed. The default is 'left' for all frequency offsets except for 'M', 'A', 'Q', 'BM', 'BA', 'BQ', and 'W' which all have a default of 'right'. label : {'right', 'left'}, default None Which bin edge label to label bucket with. The default is 'left' for all frequency offsets except for 'M', 'A', 'Q', 'BM', 'BA', 'BQ', and 'W' which all have a default of 'right'. convention : {'start', 'end', 's', 'e'}, default 'start' For `PeriodIndex` only, controls whether to use the start or end of `rule`. kind : {'timestamp', 'period'}, optional, default None Pass 'timestamp' to convert the resulting index to a `DateTimeIndex` or 'period' to convert it to a `PeriodIndex`. By default the input representation is retained. loffset : timedelta, default None Adjust the resampled time labels. .. deprecated:: 1.1.0 You should add the loffset to the `df.index` after the resample. See below. base : int, default 0 For frequencies that evenly subdivide 1 day, the "origin" of the aggregated intervals. For example, for '5min' frequency, base could range from 0 through 4. Defaults to 0. .. deprecated:: 1.1.0 The new arguments that you should use are 'offset' or 'origin'. on : str, optional For a DataFrame, column to use instead of index for resampling. Column must be datetime-like. level : str or int, optional For a MultiIndex, level (name or number) to use for resampling. `level` must be datetime-like. origin : {'epoch', 'start', 'start_day'}, Timestamp or str, default 'start_day' The timestamp on which to adjust the grouping. The timezone of origin must match the timezone of the index. If a timestamp is not used, these values are also supported: - 'epoch': `origin` is 1970-01-01 - 'start': `origin` is the first value of the timeseries - 'start_day': `origin` is the first day at midnight of the timeseries .. versionadded:: 1.1.0 offset : Timedelta or str, default is None An offset timedelta added to the origin. .. versionadded:: 1.1.0 Returns ------- Resampler object See Also -------- groupby : Group by mapping, function, label, or list of labels. Series.resample : Resample a Series. DataFrame.resample: Resample a DataFrame. Notes ----- See the `user guide <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling>`_ for more. To learn more about the offset strings, please see `this link <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects>`__. Examples -------- Start by creating a series with 9 one minute timestamps. >>> index = pd.date_range('1/1/2000', periods=9, freq='T') >>> series = pd.Series(range(9), index=index) >>> series 2000-01-01 00:00:00 0 2000-01-01 00:01:00 1 2000-01-01 00:02:00 2 2000-01-01 00:03:00 3 2000-01-01 00:04:00 4 2000-01-01 00:05:00 5 2000-01-01 00:06:00 6 2000-01-01 00:07:00 7 2000-01-01 00:08:00 8 Freq: T, dtype: int64 Downsample the series into 3 minute bins and sum the values of the timestamps falling into a bin. >>> series.resample('3T').sum() 2000-01-01 00:00:00 3 2000-01-01 00:03:00 12 2000-01-01 00:06:00 21 Freq: 3T, dtype: int64 Downsample the series into 3 minute bins as above, but label each bin using the right edge instead of the left. Please note that the value in the bucket used as the label is not included in the bucket, which it labels. For example, in the original series the bucket ``2000-01-01 00:03:00`` contains the value 3, but the summed value in the resampled bucket with the label ``2000-01-01 00:03:00`` does not include 3 (if it did, the summed value would be 6, not 3). To include this value close the right side of the bin interval as illustrated in the example below this one. >>> series.resample('3T', label='right').sum() 2000-01-01 00:03:00 3 2000-01-01 00:06:00 12 2000-01-01 00:09:00 21 Freq: 3T, dtype: int64 Downsample the series into 3 minute bins as above, but close the right side of the bin interval. >>> series.resample('3T', label='right', closed='right').sum() 2000-01-01 00:00:00 0 2000-01-01 00:03:00 6 2000-01-01 00:06:00 15 2000-01-01 00:09:00 15 Freq: 3T, dtype: int64 Upsample the series into 30 second bins. >>> series.resample('30S').asfreq()[0:5] # Select first 5 rows 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 1.0 2000-01-01 00:01:30 NaN 2000-01-01 00:02:00 2.0 Freq: 30S, dtype: float64 Upsample the series into 30 second bins and fill the ``NaN`` values using the ``pad`` method. >>> series.resample('30S').pad()[0:5] 2000-01-01 00:00:00 0 2000-01-01 00:00:30 0 2000-01-01 00:01:00 1 2000-01-01 00:01:30 1 2000-01-01 00:02:00 2 Freq: 30S, dtype: int64 Upsample the series into 30 second bins and fill the ``NaN`` values using the ``bfill`` method. >>> series.resample('30S').bfill()[0:5] 2000-01-01 00:00:00 0 2000-01-01 00:00:30 1 2000-01-01 00:01:00 1 2000-01-01 00:01:30 2 2000-01-01 00:02:00 2 Freq: 30S, dtype: int64 Pass a custom function via ``apply`` >>> def custom_resampler(array_like): ... return np.sum(array_like) + 5 ... >>> series.resample('3T').apply(custom_resampler) 2000-01-01 00:00:00 8 2000-01-01 00:03:00 17 2000-01-01 00:06:00 26 Freq: 3T, dtype: int64 For a Series with a PeriodIndex, the keyword `convention` can be used to control whether to use the start or end of `rule`. Resample a year by quarter using 'start' `convention`. Values are assigned to the first quarter of the period. >>> s = pd.Series([1, 2], index=pd.period_range('2012-01-01', ... freq='A', ... periods=2)) >>> s 2012 1 2013 2 Freq: A-DEC, dtype: int64 >>> s.resample('Q', convention='start').asfreq() 2012Q1 1.0 2012Q2 NaN 2012Q3 NaN 2012Q4 NaN 2013Q1 2.0 2013Q2 NaN 2013Q3 NaN 2013Q4 NaN Freq: Q-DEC, dtype: float64 Resample quarters by month using 'end' `convention`. Values are assigned to the last month of the period. >>> q = pd.Series([1, 2, 3, 4], index=pd.period_range('2018-01-01', ... freq='Q', ... periods=4)) >>> q 2018Q1 1 2018Q2 2 2018Q3 3 2018Q4 4 Freq: Q-DEC, dtype: int64 >>> q.resample('M', convention='end').asfreq() 2018-03 1.0 2018-04 NaN 2018-05 NaN 2018-06 2.0 2018-07 NaN 2018-08 NaN 2018-09 3.0 2018-10 NaN 2018-11 NaN 2018-12 4.0 Freq: M, dtype: float64 For DataFrame objects, the keyword `on` can be used to specify the column instead of the index for resampling. >>> d = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19], ... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]}) >>> df = pd.DataFrame(d) >>> df['week_starting'] = pd.date_range('01/01/2018', ... periods=8, ... freq='W') >>> df price volume week_starting 0 10 50 2018-01-07 1 11 60 2018-01-14 2 9 40 2018-01-21 3 13 100 2018-01-28 4 14 50 2018-02-04 5 18 100 2018-02-11 6 17 40 2018-02-18 7 19 50 2018-02-25 >>> df.resample('M', on='week_starting').mean() price volume week_starting 2018-01-31 10.75 62.5 2018-02-28 17.00 60.0 For a DataFrame with MultiIndex, the keyword `level` can be used to specify on which level the resampling needs to take place. >>> days = pd.date_range('1/1/2000', periods=4, freq='D') >>> d2 = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19], ... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]}) >>> df2 = pd.DataFrame(d2, ... index=pd.MultiIndex.from_product([days, ... ['morning', ... 'afternoon']] ... )) >>> df2 price volume 2000-01-01 morning 10 50 afternoon 11 60 2000-01-02 morning 9 40 afternoon 13 100 2000-01-03 morning 14 50 afternoon 18 100 2000-01-04 morning 17 40 afternoon 19 50 >>> df2.resample('D', level=0).sum() price volume 2000-01-01 21 110 2000-01-02 22 140 2000-01-03 32 150 2000-01-04 36 90 If you want to adjust the start of the bins based on a fixed timestamp: >>> start, end = '2000-10-01 23:30:00', '2000-10-02 00:30:00' >>> rng = pd.date_range(start, end, freq='7min') >>> ts = pd.Series(np.arange(len(rng)) * 3, index=rng) >>> ts 2000-10-01 23:30:00 0 2000-10-01 23:37:00 3 2000-10-01 23:44:00 6 2000-10-01 23:51:00 9 2000-10-01 23:58:00 12 2000-10-02 00:05:00 15 2000-10-02 00:12:00 18 2000-10-02 00:19:00 21 2000-10-02 00:26:00 24 Freq: 7T, dtype: int64 >>> ts.resample('17min').sum() 2000-10-01 23:14:00 0 2000-10-01 23:31:00 9 2000-10-01 23:48:00 21 2000-10-02 00:05:00 54 2000-10-02 00:22:00 24 Freq: 17T, dtype: int64 >>> ts.resample('17min', origin='epoch').sum() 2000-10-01 23:18:00 0 2000-10-01 23:35:00 18 2000-10-01 23:52:00 27 2000-10-02 00:09:00 39 2000-10-02 00:26:00 24 Freq: 17T, dtype: int64 >>> ts.resample('17min', origin='2000-01-01').sum() 2000-10-01 23:24:00 3 2000-10-01 23:41:00 15 2000-10-01 23:58:00 45 2000-10-02 00:15:00 45 Freq: 17T, dtype: int64 If you want to adjust the start of the bins with an `offset` Timedelta, the two following lines are equivalent: >>> ts.resample('17min', origin='start').sum() 2000-10-01 23:30:00 9 2000-10-01 23:47:00 21 2000-10-02 00:04:00 54 2000-10-02 00:21:00 24 Freq: 17T, dtype: int64 >>> ts.resample('17min', offset='23h30min').sum() 2000-10-01 23:30:00 9 2000-10-01 23:47:00 21 2000-10-02 00:04:00 54 2000-10-02 00:21:00 24 Freq: 17T, dtype: int64 To replace the use of the deprecated `base` argument, you can now use `offset`, in this example it is equivalent to have `base=2`: >>> ts.resample('17min', offset='2min').sum() 2000-10-01 23:16:00 0 2000-10-01 23:33:00 9 2000-10-01 23:50:00 36 2000-10-02 00:07:00 39 2000-10-02 00:24:00 24 Freq: 17T, dtype: int64 To replace the use of the deprecated `loffset` argument: >>> from pandas.tseries.frequencies import to_offset >>> loffset = '19min' >>> ts_out = ts.resample('17min').sum() >>> ts_out.index = ts_out.index + to_offset(loffset) >>> ts_out 2000-10-01 23:33:00 0 2000-10-01 23:50:00 9 2000-10-02 00:07:00 21 2000-10-02 00:24:00 54 2000-10-02 00:41:00 24 Freq: 17T, dtype: int64 """ from pandas.core.resample import get_resampler axis = self._get_axis_number(axis) return get_resampler( self, freq=rule, label=label, closed=closed, axis=axis, kind=kind, loffset=loffset, convention=convention, base=base, key=on, level=level, origin=origin, offset=offset, ) def first(self: FrameOrSeries, offset) -> FrameOrSeries: """ Select initial periods of time series data based on a date offset. When having a DataFrame with dates as index, this function can select the first few rows based on a date offset. Parameters ---------- offset : str, DateOffset or dateutil.relativedelta The offset length of the data that will be selected. For instance, '1M' will display all the rows having their index within the first month. Returns ------- Series or DataFrame A subset of the caller. Raises ------ TypeError If the index is not a :class:`DatetimeIndex` See Also -------- last : Select final periods of time series based on a date offset. at_time : Select values at a particular time of the day. between_time : Select values between particular times of the day. Examples -------- >>> i = pd.date_range('2018-04-09', periods=4, freq='2D') >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i) >>> ts A 2018-04-09 1 2018-04-11 2 2018-04-13 3 2018-04-15 4 Get the rows for the first 3 days: >>> ts.first('3D') A 2018-04-09 1 2018-04-11 2 Notice the data for 3 first calendar days were returned, not the first 3 days observed in the dataset, and therefore data for 2018-04-13 was not returned. """ if not isinstance(self.index, DatetimeIndex): raise TypeError("'first' only supports a DatetimeIndex index") if len(self.index) == 0: return self offset = to_offset(offset) end_date = end = self.index[0] + offset # Tick-like, e.g. 3 weeks if isinstance(offset, Tick): if end_date in self.index: end = self.index.searchsorted(end_date, side="left") return self.iloc[:end] return self.loc[:end] def last(self: FrameOrSeries, offset) -> FrameOrSeries: """ Select final periods of time series data based on a date offset. When having a DataFrame with dates as index, this function can select the last few rows based on a date offset. Parameters ---------- offset : str, DateOffset, dateutil.relativedelta The offset length of the data that will be selected. For instance, '3D' will display all the rows having their index within the last 3 days. Returns ------- Series or DataFrame A subset of the caller. Raises ------ TypeError If the index is not a :class:`DatetimeIndex` See Also -------- first : Select initial periods of time series based on a date offset. at_time : Select values at a particular time of the day. between_time : Select values between particular times of the day. Examples -------- >>> i = pd.date_range('2018-04-09', periods=4, freq='2D') >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i) >>> ts A 2018-04-09 1 2018-04-11 2 2018-04-13 3 2018-04-15 4 Get the rows for the last 3 days: >>> ts.last('3D') A 2018-04-13 3 2018-04-15 4 Notice the data for 3 last calendar days were returned, not the last 3 observed days in the dataset, and therefore data for 2018-04-11 was not returned. """ if not isinstance(self.index, DatetimeIndex): raise TypeError("'last' only supports a DatetimeIndex index") if len(self.index) == 0: return self offset = to_offset(offset) start_date = self.index[-1] - offset start = self.index.searchsorted(start_date, side="right") return self.iloc[start:] def rank( self: FrameOrSeries, axis=0, method: str = "average", numeric_only: Optional[bool_t] = None, na_option: str = "keep", ascending: bool_t = True, pct: bool_t = False, ) -> FrameOrSeries: """ Compute numerical data ranks (1 through n) along axis. By default, equal values are assigned a rank that is the average of the ranks of those values. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 Index to direct ranking. method : {'average', 'min', 'max', 'first', 'dense'}, default 'average' How to rank the group of records that have the same value (i.e. ties): * average: average rank of the group * min: lowest rank in the group * max: highest rank in the group * first: ranks assigned in order they appear in the array * dense: like 'min', but rank always increases by 1 between groups. numeric_only : bool, optional For DataFrame objects, rank only numeric columns if set to True. na_option : {'keep', 'top', 'bottom'}, default 'keep' How to rank NaN values: * keep: assign NaN rank to NaN values * top: assign smallest rank to NaN values if ascending * bottom: assign highest rank to NaN values if ascending. ascending : bool, default True Whether or not the elements should be ranked in ascending order. pct : bool, default False Whether or not to display the returned rankings in percentile form. Returns ------- same type as caller Return a Series or DataFrame with data ranks as values. See Also -------- core.groupby.GroupBy.rank : Rank of values within each group. Examples -------- >>> df = pd.DataFrame(data={'Animal': ['cat', 'penguin', 'dog', ... 'spider', 'snake'], ... 'Number_legs': [4, 2, 4, 8, np.nan]}) >>> df Animal Number_legs 0 cat 4.0 1 penguin 2.0 2 dog 4.0 3 spider 8.0 4 snake NaN The following example shows how the method behaves with the above parameters: * default_rank: this is the default behaviour obtained without using any parameter. * max_rank: setting ``method = 'max'`` the records that have the same values are ranked using the highest rank (e.g.: since 'cat' and 'dog' are both in the 2nd and 3rd position, rank 3 is assigned.) * NA_bottom: choosing ``na_option = 'bottom'``, if there are records with NaN values they are placed at the bottom of the ranking. * pct_rank: when setting ``pct = True``, the ranking is expressed as percentile rank. >>> df['default_rank'] = df['Number_legs'].rank() >>> df['max_rank'] = df['Number_legs'].rank(method='max') >>> df['NA_bottom'] = df['Number_legs'].rank(na_option='bottom') >>> df['pct_rank'] = df['Number_legs'].rank(pct=True) >>> df Animal Number_legs default_rank max_rank NA_bottom pct_rank 0 cat 4.0 2.5 3.0 2.5 0.625 1 penguin 2.0 1.0 1.0 1.0 0.250 2 dog 4.0 2.5 3.0 2.5 0.625 3 spider 8.0 4.0 4.0 4.0 1.000 4 snake NaN NaN NaN 5.0 NaN """ axis = self._get_axis_number(axis) if na_option not in {"keep", "top", "bottom"}: msg = "na_option must be one of 'keep', 'top', or 'bottom'" raise ValueError(msg) def ranker(data): ranks = algos.rank( data.values, axis=axis, method=method, ascending=ascending, na_option=na_option, pct=pct, ) ranks = self._constructor(ranks, **data._construct_axes_dict()) return ranks.__finalize__(self, method="rank") # if numeric_only is None, and we can't get anything, we try with # numeric_only=True if numeric_only is None: try: return ranker(self) except TypeError: numeric_only = True if numeric_only: data = self._get_numeric_data() else: data = self return ranker(data) @doc(**_shared_doc_kwargs) def align( self, other, join="outer", axis=None, level=None, copy=True, fill_value=None, method=None, limit=None, fill_axis=0, broadcast_axis=None, ): """ Align two objects on their axes with the specified join method. Join method is specified for each axis Index. Parameters ---------- other : DataFrame or Series join : {{'outer', 'inner', 'left', 'right'}}, default 'outer' axis : allowed axis of the other object, default None Align on index (0), columns (1), or both (None). level : int or level name, default None Broadcast across a level, matching Index values on the passed MultiIndex level. copy : bool, default True Always returns new objects. If copy=False and no reindexing is required then original objects are returned. fill_value : scalar, default np.NaN Value to use for missing values. Defaults to NaN, but can be any "compatible" value. method : {{'backfill', 'bfill', 'pad', 'ffill', None}}, default None Method to use for filling holes in reindexed Series: - pad / ffill: propagate last valid observation forward to next valid. - backfill / bfill: use NEXT valid observation to fill gap. limit : int, default None If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None. fill_axis : {axes_single_arg}, default 0 Filling axis, method and limit. broadcast_axis : {axes_single_arg}, default None Broadcast values along this axis, if aligning two objects of different dimensions. Returns ------- (left, right) : ({klass}, type of other) Aligned objects. """ method = missing.clean_fill_method(method) if broadcast_axis == 1 and self.ndim != other.ndim: if isinstance(self, ABCSeries): # this means other is a DataFrame, and we need to broadcast # self cons = self._constructor_expanddim df = cons( {c: self for c in other.columns}, **other._construct_axes_dict() ) return df._align_frame( other, join=join, axis=axis, level=level, copy=copy, fill_value=fill_value, method=method, limit=limit, fill_axis=fill_axis, ) elif isinstance(other, ABCSeries): # this means self is a DataFrame, and we need to broadcast # other cons = other._constructor_expanddim df = cons( {c: other for c in self.columns}, **self._construct_axes_dict() ) return self._align_frame( df, join=join, axis=axis, level=level, copy=copy, fill_value=fill_value, method=method, limit=limit, fill_axis=fill_axis, ) if axis is not None: axis = self._get_axis_number(axis) if isinstance(other, ABCDataFrame): return self._align_frame( other, join=join, axis=axis, level=level, copy=copy, fill_value=fill_value, method=method, limit=limit, fill_axis=fill_axis, ) elif isinstance(other, ABCSeries): return self._align_series( other, join=join, axis=axis, level=level, copy=copy, fill_value=fill_value, method=method, limit=limit, fill_axis=fill_axis, ) else: # pragma: no cover raise TypeError(f"unsupported type: {type(other)}") def _align_frame( self, other, join="outer", axis=None, level=None, copy: bool_t = True, fill_value=None, method=None, limit=None, fill_axis=0, ): # defaults join_index, join_columns = None, None ilidx, iridx = None, None clidx, cridx = None, None is_series = isinstance(self, ABCSeries) if axis is None or axis == 0: if not self.index.equals(other.index): join_index, ilidx, iridx = self.index.join( other.index, how=join, level=level, return_indexers=True ) if axis is None or axis == 1: if not is_series and not self.columns.equals(other.columns): join_columns, clidx, cridx = self.columns.join( other.columns, how=join, level=level, return_indexers=True ) if is_series: reindexers = {0: [join_index, ilidx]} else: reindexers = {0: [join_index, ilidx], 1: [join_columns, clidx]} left = self._reindex_with_indexers( reindexers, copy=copy, fill_value=fill_value, allow_dups=True ) # other must be always DataFrame right = other._reindex_with_indexers( {0: [join_index, iridx], 1: [join_columns, cridx]}, copy=copy, fill_value=fill_value, allow_dups=True, ) if method is not None: _left = left.fillna(method=method, axis=fill_axis, limit=limit) assert _left is not None # needed for mypy left = _left right = right.fillna(method=method, axis=fill_axis, limit=limit) # if DatetimeIndex have different tz, convert to UTC if is_datetime64tz_dtype(left.index.dtype): if left.index.tz != right.index.tz: if join_index is not None: left.index = join_index right.index = join_index return ( left.__finalize__(self), right.__finalize__(other), ) def _align_series( self, other, join="outer", axis=None, level=None, copy: bool_t = True, fill_value=None, method=None, limit=None, fill_axis=0, ): is_series = isinstance(self, ABCSeries) # series/series compat, other must always be a Series if is_series: if axis: raise ValueError("cannot align series to a series other than axis 0") # equal if self.index.equals(other.index): join_index, lidx, ridx = None, None, None else: join_index, lidx, ridx = self.index.join( other.index, how=join, level=level, return_indexers=True ) left = self._reindex_indexer(join_index, lidx, copy) right = other._reindex_indexer(join_index, ridx, copy) else: # one has > 1 ndim fdata = self._mgr if axis == 0: join_index = self.index lidx, ridx = None, None if not self.index.equals(other.index): join_index, lidx, ridx = self.index.join( other.index, how=join, level=level, return_indexers=True ) if lidx is not None: fdata = fdata.reindex_indexer(join_index, lidx, axis=1) elif axis == 1: join_index = self.columns lidx, ridx = None, None if not self.columns.equals(other.index): join_index, lidx, ridx = self.columns.join( other.index, how=join, level=level, return_indexers=True ) if lidx is not None: fdata = fdata.reindex_indexer(join_index, lidx, axis=0) else: raise ValueError("Must specify axis=0 or 1") if copy and fdata is self._mgr: fdata = fdata.copy() left = self._constructor(fdata) if ridx is None: right = other else: right = other.reindex(join_index, level=level) # fill fill_na = notna(fill_value) or (method is not None) if fill_na: left = left.fillna(fill_value, method=method, limit=limit, axis=fill_axis) right = right.fillna(fill_value, method=method, limit=limit) # if DatetimeIndex have different tz, convert to UTC if is_series or (not is_series and axis == 0): if is_datetime64tz_dtype(left.index.dtype): if left.index.tz != right.index.tz: if join_index is not None: left.index = join_index right.index = join_index return ( left.__finalize__(self), right.__finalize__(other), ) def _where( self, cond, other=np.nan, inplace=False, axis=None, level=None, errors="raise", try_cast=False, ): """ Equivalent to public method `where`, except that `other` is not applied as a function even if callable. Used in __setitem__. """ inplace = validate_bool_kwarg(inplace, "inplace") # align the cond to same shape as myself cond = com.apply_if_callable(cond, self) if isinstance(cond, NDFrame): cond, _ = cond.align(self, join="right", broadcast_axis=1) else: if not hasattr(cond, "shape"): cond = np.asanyarray(cond) if cond.shape != self.shape: raise ValueError("Array conditional must be same shape as self") cond = self._constructor(cond, **self._construct_axes_dict()) # make sure we are boolean fill_value = bool(inplace) cond = cond.fillna(fill_value) msg = "Boolean array expected for the condition, not {dtype}" if not isinstance(cond, ABCDataFrame): # This is a single-dimensional object. if not is_bool_dtype(cond): raise ValueError(msg.format(dtype=cond.dtype)) elif not cond.empty: for dt in cond.dtypes: if not is_bool_dtype(dt): raise ValueError(msg.format(dtype=dt)) else: # GH#21947 we have an empty DataFrame, could be object-dtype cond = cond.astype(bool) cond = -cond if inplace else cond # try to align with other try_quick = True if isinstance(other, NDFrame): # align with me if other.ndim <= self.ndim: _, other = self.align( other, join="left", axis=axis, level=level, fill_value=np.nan ) # if we are NOT aligned, raise as we cannot where index if axis is None and not all( other._get_axis(i).equals(ax) for i, ax in enumerate(self.axes) ): raise InvalidIndexError # slice me out of the other else: raise NotImplementedError( "cannot align with a higher dimensional NDFrame" ) if isinstance(other, np.ndarray): if other.shape != self.shape: if self.ndim == 1: icond = cond._values # GH 2745 / GH 4192 # treat like a scalar if len(other) == 1: other = other[0] # GH 3235 # match True cond to other elif len(cond[icond]) == len(other): # try to not change dtype at first (if try_quick) if try_quick: new_other = np.asarray(self) new_other = new_other.copy() new_other[icond] = other other = new_other else: raise ValueError( "Length of replacements must equal series length" ) else: raise ValueError( "other must be the same shape as self when an ndarray" ) # we are the same shape, so create an actual object for alignment else: other = self._constructor(other, **self._construct_axes_dict()) if axis is None: axis = 0 if self.ndim == getattr(other, "ndim", 0): align = True else: align = self._get_axis_number(axis) == 1 if align and isinstance(other, NDFrame): other = other.reindex(self._info_axis, axis=self._info_axis_number) if isinstance(cond, NDFrame): cond = cond.reindex(self._info_axis, axis=self._info_axis_number) block_axis = self._get_block_manager_axis(axis) if inplace: # we may have different type blocks come out of putmask, so # reconstruct the block manager self._check_inplace_setting(other) new_data = self._mgr.putmask( mask=cond, new=other, align=align, axis=block_axis, ) result = self._constructor(new_data) return self._update_inplace(result) else: new_data = self._mgr.where( other=other, cond=cond, align=align, errors=errors, try_cast=try_cast, axis=block_axis, ) result = self._constructor(new_data) return result.__finalize__(self) _shared_docs[ "where" ] = """ Replace values where the condition is %(cond_rev)s. Parameters ---------- cond : bool %(klass)s, array-like, or callable Where `cond` is %(cond)s, keep the original value. Where %(cond_rev)s, replace with corresponding value from `other`. If `cond` is callable, it is computed on the %(klass)s and should return boolean %(klass)s or array. The callable must not change input %(klass)s (though pandas doesn't check it). other : scalar, %(klass)s, or callable Entries where `cond` is %(cond_rev)s are replaced with corresponding value from `other`. If other is callable, it is computed on the %(klass)s and should return scalar or %(klass)s. The callable must not change input %(klass)s (though pandas doesn't check it). inplace : bool, default False Whether to perform the operation in place on the data. axis : int, default None Alignment axis if needed. level : int, default None Alignment level if needed. errors : str, {'raise', 'ignore'}, default 'raise' Note that currently this parameter won't affect the results and will always coerce to a suitable dtype. - 'raise' : allow exceptions to be raised. - 'ignore' : suppress exceptions. On error return original object. try_cast : bool, default False Try to cast the result back to the input type (if possible). Returns ------- Same type as caller See Also -------- :func:`DataFrame.%(name_other)s` : Return an object of same shape as self. Notes ----- The %(name)s method is an application of the if-then idiom. For each element in the calling DataFrame, if ``cond`` is ``%(cond)s`` the element is used; otherwise the corresponding element from the DataFrame ``other`` is used. The signature for :func:`DataFrame.where` differs from :func:`numpy.where`. Roughly ``df1.where(m, df2)`` is equivalent to ``np.where(m, df1, df2)``. For further details and examples see the ``%(name)s`` documentation in :ref:`indexing <indexing.where_mask>`. Examples -------- >>> s = pd.Series(range(5)) >>> s.where(s > 0) 0 NaN 1 1.0 2 2.0 3 3.0 4 4.0 dtype: float64 >>> s.mask(s > 0) 0 0.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 >>> s.where(s > 1, 10) 0 10 1 10 2 2 3 3 4 4 dtype: int64 >>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B']) >>> df A B 0 0 1 1 2 3 2 4 5 3 6 7 4 8 9 >>> m = df %% 3 == 0 >>> df.where(m, -df) A B 0 0 -1 1 -2 3 2 -4 -5 3 6 -7 4 -8 9 >>> df.where(m, -df) == np.where(m, df, -df) A B 0 True True 1 True True 2 True True 3 True True 4 True True >>> df.where(m, -df) == df.mask(~m, -df) A B 0 True True 1 True True 2 True True 3 True True 4 True True """ @Appender( _shared_docs["where"] % dict( _shared_doc_kwargs, cond="True", cond_rev="False", name="where", name_other="mask", ) ) def where( self, cond, other=np.nan, inplace=False, axis=None, level=None, errors="raise", try_cast=False, ): other = com.apply_if_callable(other, self) return self._where( cond, other, inplace, axis, level, errors=errors, try_cast=try_cast ) @Appender( _shared_docs["where"] % dict( _shared_doc_kwargs, cond="False", cond_rev="True", name="mask", name_other="where", ) ) def mask( self, cond, other=np.nan, inplace=False, axis=None, level=None, errors="raise", try_cast=False, ): inplace = validate_bool_kwarg(inplace, "inplace") cond = com.apply_if_callable(cond, self) # see gh-21891 if not hasattr(cond, "__invert__"): cond = np.array(cond) return self.where( ~cond, other=other, inplace=inplace, axis=axis, level=level, try_cast=try_cast, errors=errors, ) @doc(klass=_shared_doc_kwargs["klass"]) def shift( self: FrameOrSeries, periods=1, freq=None, axis=0, fill_value=None ) -> FrameOrSeries: """ Shift index by desired number of periods with an optional time `freq`. When `freq` is not passed, shift the index without realigning the data. If `freq` is passed (in this case, the index must be date or datetime, or it will raise a `NotImplementedError`), the index will be increased using the periods and the `freq`. Parameters ---------- periods : int Number of periods to shift. Can be positive or negative. freq : DateOffset, tseries.offsets, timedelta, or str, optional Offset to use from the tseries module or time rule (e.g. 'EOM'). If `freq` is specified then the index values are shifted but the data is not realigned. That is, use `freq` if you would like to extend the index when shifting and preserve the original data. axis : {{0 or 'index', 1 or 'columns', None}}, default None Shift direction. fill_value : object, optional The scalar value to use for newly introduced missing values. the default depends on the dtype of `self`. For numeric data, ``np.nan`` is used. For datetime, timedelta, or period data, etc. :attr:`NaT` is used. For extension dtypes, ``self.dtype.na_value`` is used. .. versionchanged:: 0.24.0 Returns ------- {klass} Copy of input object, shifted. See Also -------- Index.shift : Shift values of Index. DatetimeIndex.shift : Shift values of DatetimeIndex. PeriodIndex.shift : Shift values of PeriodIndex. tshift : Shift the time index, using the index's frequency if available. Examples -------- >>> df = pd.DataFrame({{'Col1': [10, 20, 15, 30, 45], ... 'Col2': [13, 23, 18, 33, 48], ... 'Col3': [17, 27, 22, 37, 52]}}) >>> df.shift(periods=3) Col1 Col2 Col3 0 NaN NaN NaN 1 NaN NaN NaN 2 NaN NaN NaN 3 10.0 13.0 17.0 4 20.0 23.0 27.0 >>> df.shift(periods=1, axis='columns') Col1 Col2 Col3 0 NaN 10.0 13.0 1 NaN 20.0 23.0 2 NaN 15.0 18.0 3 NaN 30.0 33.0 4 NaN 45.0 48.0 >>> df.shift(periods=3, fill_value=0) Col1 Col2 Col3 0 0 0 0 1 0 0 0 2 0 0 0 3 10 13 17 4 20 23 27 """ if periods == 0: return self.copy() block_axis = self._get_block_manager_axis(axis) if freq is None: new_data = self._mgr.shift( periods=periods, axis=block_axis, fill_value=fill_value ) else: return self.tshift(periods, freq) return self._constructor(new_data).__finalize__(self, method="shift") def slice_shift(self: FrameOrSeries, periods: int = 1, axis=0) -> FrameOrSeries: """ Equivalent to `shift` without copying data. The shifted data will not include the dropped periods and the shifted axis will be smaller than the original. Parameters ---------- periods : int Number of periods to move, can be positive or negative. Returns ------- shifted : same type as caller Notes ----- While the `slice_shift` is faster than `shift`, you may pay for it later during alignment. """ if periods == 0: return self if periods > 0: vslicer = slice(None, -periods) islicer = slice(periods, None) else: vslicer = slice(-periods, None) islicer = slice(None, periods) new_obj = self._slice(vslicer, axis=axis) shifted_axis = self._get_axis(axis)[islicer] new_obj.set_axis(shifted_axis, axis=axis, inplace=True) return new_obj.__finalize__(self, method="slice_shift") def tshift( self: FrameOrSeries, periods: int = 1, freq=None, axis: Axis = 0 ) -> FrameOrSeries: """ Shift the time index, using the index's frequency if available. Parameters ---------- periods : int Number of periods to move, can be positive or negative. freq : DateOffset, timedelta, or str, default None Increment to use from the tseries module or time rule expressed as a string (e.g. 'EOM'). axis : {0 or ‘index’, 1 or ‘columns’, None}, default 0 Corresponds to the axis that contains the Index. Returns ------- shifted : Series/DataFrame Notes ----- If freq is not specified then tries to use the freq or inferred_freq attributes of the index. If neither of those attributes exist, a ValueError is thrown """ index = self._get_axis(axis) if freq is None: freq = getattr(index, "freq", None) if freq is None: freq = getattr(index, "inferred_freq", None) if freq is None: msg = "Freq was not given and was not set in the index" raise ValueError(msg) if periods == 0: return self if isinstance(freq, str): freq = to_offset(freq) axis = self._get_axis_number(axis) if isinstance(index, PeriodIndex): orig_freq = to_offset(index.freq) if freq != orig_freq: assert orig_freq is not None # for mypy raise ValueError( f"Given freq {freq.rule_code} does not match " f"PeriodIndex freq {orig_freq.rule_code}" ) new_ax = index.shift(periods) else: new_ax = index.shift(periods, freq) result = self.copy() result.set_axis(new_ax, axis, inplace=True) return result.__finalize__(self, method="tshift") def truncate( self: FrameOrSeries, before=None, after=None, axis=None, copy: bool_t = True ) -> FrameOrSeries: """ Truncate a Series or DataFrame before and after some index value. This is a useful shorthand for boolean indexing based on index values above or below certain thresholds. Parameters ---------- before : date, str, int Truncate all rows before this index value. after : date, str, int Truncate all rows after this index value. axis : {0 or 'index', 1 or 'columns'}, optional Axis to truncate. Truncates the index (rows) by default. copy : bool, default is True, Return a copy of the truncated section. Returns ------- type of caller The truncated Series or DataFrame. See Also -------- DataFrame.loc : Select a subset of a DataFrame by label. DataFrame.iloc : Select a subset of a DataFrame by position. Notes ----- If the index being truncated contains only datetime values, `before` and `after` may be specified as strings instead of Timestamps. Examples -------- >>> df = pd.DataFrame({'A': ['a', 'b', 'c', 'd', 'e'], ... 'B': ['f', 'g', 'h', 'i', 'j'], ... 'C': ['k', 'l', 'm', 'n', 'o']}, ... index=[1, 2, 3, 4, 5]) >>> df A B C 1 a f k 2 b g l 3 c h m 4 d i n 5 e j o >>> df.truncate(before=2, after=4) A B C 2 b g l 3 c h m 4 d i n The columns of a DataFrame can be truncated. >>> df.truncate(before="A", after="B", axis="columns") A B 1 a f 2 b g 3 c h 4 d i 5 e j For Series, only rows can be truncated. >>> df['A'].truncate(before=2, after=4) 2 b 3 c 4 d Name: A, dtype: object The index values in ``truncate`` can be datetimes or string dates. >>> dates = pd.date_range('2016-01-01', '2016-02-01', freq='s') >>> df = pd.DataFrame(index=dates, data={'A': 1}) >>> df.tail() A 2016-01-31 23:59:56 1 2016-01-31 23:59:57 1 2016-01-31 23:59:58 1 2016-01-31 23:59:59 1 2016-02-01 00:00:00 1 >>> df.truncate(before=pd.Timestamp('2016-01-05'), ... after=pd.Timestamp('2016-01-10')).tail() A 2016-01-09 23:59:56 1 2016-01-09 23:59:57 1 2016-01-09 23:59:58 1 2016-01-09 23:59:59 1 2016-01-10 00:00:00 1 Because the index is a DatetimeIndex containing only dates, we can specify `before` and `after` as strings. They will be coerced to Timestamps before truncation. >>> df.truncate('2016-01-05', '2016-01-10').tail() A 2016-01-09 23:59:56 1 2016-01-09 23:59:57 1 2016-01-09 23:59:58 1 2016-01-09 23:59:59 1 2016-01-10 00:00:00 1 Note that ``truncate`` assumes a 0 value for any unspecified time component (midnight). This differs from partial string slicing, which returns any partially matching dates. >>> df.loc['2016-01-05':'2016-01-10', :].tail() A 2016-01-10 23:59:55 1 2016-01-10 23:59:56 1 2016-01-10 23:59:57 1 2016-01-10 23:59:58 1 2016-01-10 23:59:59 1 """ if axis is None: axis = self._stat_axis_number axis = self._get_axis_number(axis) ax = self._get_axis(axis) # GH 17935 # Check that index is sorted if not ax.is_monotonic_increasing and not ax.is_monotonic_decreasing: raise ValueError("truncate requires a sorted index") # if we have a date index, convert to dates, otherwise # treat like a slice if ax.is_all_dates: from pandas.core.tools.datetimes import to_datetime before = to_datetime(before) after = to_datetime(after) if before is not None and after is not None: if before > after: raise ValueError(f"Truncate: {after} must be after {before}") if ax.is_monotonic_decreasing: before, after = after, before slicer = [slice(None, None)] * self._AXIS_LEN slicer[axis] = slice(before, after) result = self.loc[tuple(slicer)] if isinstance(ax, MultiIndex): setattr(result, self._get_axis_name(axis), ax.truncate(before, after)) if copy: result = result.copy() return result def tz_convert( self: FrameOrSeries, tz, axis=0, level=None, copy: bool_t = True ) -> FrameOrSeries: """ Convert tz-aware axis to target time zone. Parameters ---------- tz : str or tzinfo object axis : the axis to convert level : int, str, default None If axis is a MultiIndex, convert a specific level. Otherwise must be None. copy : bool, default True Also make a copy of the underlying data. Returns ------- %(klass)s Object with time zone converted axis. Raises ------ TypeError If the axis is tz-naive. """ axis = self._get_axis_number(axis) ax = self._get_axis(axis) def _tz_convert(ax, tz): if not hasattr(ax, "tz_convert"): if len(ax) > 0: ax_name = self._get_axis_name(axis) raise TypeError( f"{ax_name} is not a valid DatetimeIndex or PeriodIndex" ) else: ax = DatetimeIndex([], tz=tz) else: ax = ax.tz_convert(tz) return ax # if a level is given it must be a MultiIndex level or # equivalent to the axis name if isinstance(ax, MultiIndex): level = ax._get_level_number(level) new_level = _tz_convert(ax.levels[level], tz) ax = ax.set_levels(new_level, level=level) else: if level not in (None, 0, ax.name): raise ValueError(f"The level {level} is not valid") ax = _tz_convert(ax, tz) result = self.copy(deep=copy) result = result.set_axis(ax, axis=axis, inplace=False) return result.__finalize__(self, method="tz_convert") def tz_localize( self: FrameOrSeries, tz, axis=0, level=None, copy: bool_t = True, ambiguous="raise", nonexistent: str = "raise", ) -> FrameOrSeries: """ Localize tz-naive index of a Series or DataFrame to target time zone. This operation localizes the Index. To localize the values in a timezone-naive Series, use :meth:`Series.dt.tz_localize`. Parameters ---------- tz : str or tzinfo axis : the axis to localize level : int, str, default None If axis ia a MultiIndex, localize a specific level. Otherwise must be None. copy : bool, default True Also make a copy of the underlying data. ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise' When clocks moved backward due to DST, ambiguous times may arise. For example in Central European Time (UTC+01), when going from 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the `ambiguous` parameter dictates how ambiguous times should be handled. - 'infer' will attempt to infer fall dst-transition hours based on order - bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times) - 'NaT' will return NaT where there are ambiguous times - 'raise' will raise an AmbiguousTimeError if there are ambiguous times. nonexistent : str, default 'raise' A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST. Valid values are: - 'shift_forward' will shift the nonexistent time forward to the closest existing time - 'shift_backward' will shift the nonexistent time backward to the closest existing time - 'NaT' will return NaT where there are nonexistent times - timedelta objects will shift nonexistent times by the timedelta - 'raise' will raise an NonExistentTimeError if there are nonexistent times. .. versionadded:: 0.24.0 Returns ------- Series or DataFrame Same type as the input. Raises ------ TypeError If the TimeSeries is tz-aware and tz is not None. Examples -------- Localize local times: >>> s = pd.Series([1], ... index=pd.DatetimeIndex(['2018-09-15 01:30:00'])) >>> s.tz_localize('CET') 2018-09-15 01:30:00+02:00 1 dtype: int64 Be careful with DST changes. When there is sequential data, pandas can infer the DST time: >>> s = pd.Series(range(7), ... index=pd.DatetimeIndex(['2018-10-28 01:30:00', ... '2018-10-28 02:00:00', ... '2018-10-28 02:30:00', ... '2018-10-28 02:00:00', ... '2018-10-28 02:30:00', ... '2018-10-28 03:00:00', ... '2018-10-28 03:30:00'])) >>> s.tz_localize('CET', ambiguous='infer') 2018-10-28 01:30:00+02:00 0 2018-10-28 02:00:00+02:00 1 2018-10-28 02:30:00+02:00 2 2018-10-28 02:00:00+01:00 3 2018-10-28 02:30:00+01:00 4 2018-10-28 03:00:00+01:00 5 2018-10-28 03:30:00+01:00 6 dtype: int64 In some cases, inferring the DST is impossible. In such cases, you can pass an ndarray to the ambiguous parameter to set the DST explicitly >>> s = pd.Series(range(3), ... index=pd.DatetimeIndex(['2018-10-28 01:20:00', ... '2018-10-28 02:36:00', ... '2018-10-28 03:46:00'])) >>> s.tz_localize('CET', ambiguous=np.array([True, True, False])) 2018-10-28 01:20:00+02:00 0 2018-10-28 02:36:00+02:00 1 2018-10-28 03:46:00+01:00 2 dtype: int64 If the DST transition causes nonexistent times, you can shift these dates forward or backwards with a timedelta object or `'shift_forward'` or `'shift_backwards'`. >>> s = pd.Series(range(2), ... index=pd.DatetimeIndex(['2015-03-29 02:30:00', ... '2015-03-29 03:30:00'])) >>> s.tz_localize('Europe/Warsaw', nonexistent='shift_forward') 2015-03-29 03:00:00+02:00 0 2015-03-29 03:30:00+02:00 1 dtype: int64 >>> s.tz_localize('Europe/Warsaw', nonexistent='shift_backward') 2015-03-29 01:59:59.999999999+01:00 0 2015-03-29 03:30:00+02:00 1 dtype: int64 >>> s.tz_localize('Europe/Warsaw', nonexistent=pd.Timedelta('1H')) 2015-03-29 03:30:00+02:00 0 2015-03-29 03:30:00+02:00 1 dtype: int64 """ nonexistent_options = ("raise", "NaT", "shift_forward", "shift_backward") if nonexistent not in nonexistent_options and not isinstance( nonexistent, timedelta ): raise ValueError( "The nonexistent argument must be one of 'raise', " "'NaT', 'shift_forward', 'shift_backward' or " "a timedelta object" ) axis = self._get_axis_number(axis) ax = self._get_axis(axis) def _tz_localize(ax, tz, ambiguous, nonexistent): if not hasattr(ax, "tz_localize"): if len(ax) > 0: ax_name = self._get_axis_name(axis) raise TypeError( f"{ax_name} is not a valid DatetimeIndex or PeriodIndex" ) else: ax = DatetimeIndex([], tz=tz) else: ax = ax.tz_localize(tz, ambiguous=ambiguous, nonexistent=nonexistent) return ax # if a level is given it must be a MultiIndex level or # equivalent to the axis name if isinstance(ax, MultiIndex): level = ax._get_level_number(level) new_level = _tz_localize(ax.levels[level], tz, ambiguous, nonexistent) ax = ax.set_levels(new_level, level=level) else: if level not in (None, 0, ax.name): raise ValueError(f"The level {level} is not valid") ax = _tz_localize(ax, tz, ambiguous, nonexistent) result = self.copy(deep=copy) result = result.set_axis(ax, axis=axis, inplace=False) return result.__finalize__(self, method="tz_localize") # ---------------------------------------------------------------------- # Numeric Methods def abs(self: FrameOrSeries) -> FrameOrSeries: """ Return a Series/DataFrame with absolute numeric value of each element. This function only applies to elements that are all numeric. Returns ------- abs Series/DataFrame containing the absolute value of each element. See Also -------- numpy.absolute : Calculate the absolute value element-wise. Notes ----- For ``complex`` inputs, ``1.2 + 1j``, the absolute value is :math:`\\sqrt{ a^2 + b^2 }`. Examples -------- Absolute numeric values in a Series. >>> s = pd.Series([-1.10, 2, -3.33, 4]) >>> s.abs() 0 1.10 1 2.00 2 3.33 3 4.00 dtype: float64 Absolute numeric values in a Series with complex numbers. >>> s = pd.Series([1.2 + 1j]) >>> s.abs() 0 1.56205 dtype: float64 Absolute numeric values in a Series with a Timedelta element. >>> s = pd.Series([pd.Timedelta('1 days')]) >>> s.abs() 0 1 days dtype: timedelta64[ns] Select rows with data closest to certain value using argsort (from `StackOverflow <https://stackoverflow.com/a/17758115>`__). >>> df = pd.DataFrame({ ... 'a': [4, 5, 6, 7], ... 'b': [10, 20, 30, 40], ... 'c': [100, 50, -30, -50] ... }) >>> df a b c 0 4 10 100 1 5 20 50 2 6 30 -30 3 7 40 -50 >>> df.loc[(df.c - 43).abs().argsort()] a b c 1 5 20 50 0 4 10 100 2 6 30 -30 3 7 40 -50 """ return np.abs(self) def describe( self: FrameOrSeries, percentiles=None, include=None, exclude=None ) -> FrameOrSeries: """ Generate descriptive statistics. Descriptive statistics include those that summarize the central tendency, dispersion and shape of a dataset's distribution, excluding ``NaN`` values. Analyzes both numeric and object series, as well as ``DataFrame`` column sets of mixed data types. The output will vary depending on what is provided. Refer to the notes below for more detail. Parameters ---------- percentiles : list-like of numbers, optional The percentiles to include in the output. All should fall between 0 and 1. The default is ``[.25, .5, .75]``, which returns the 25th, 50th, and 75th percentiles. include : 'all', list-like of dtypes or None (default), optional A white list of data types to include in the result. Ignored for ``Series``. Here are the options: - 'all' : All columns of the input will be included in the output. - A list-like of dtypes : Limits the results to the provided data types. To limit the result to numeric types submit ``numpy.number``. To limit it instead to object columns submit the ``numpy.object`` data type. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To select pandas categorical columns, use ``'category'`` - None (default) : The result will include all numeric columns. exclude : list-like of dtypes or None (default), optional, A black list of data types to omit from the result. Ignored for ``Series``. Here are the options: - A list-like of dtypes : Excludes the provided data types from the result. To exclude numeric types submit ``numpy.number``. To exclude object columns submit the data type ``numpy.object``. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To exclude pandas categorical columns, use ``'category'`` - None (default) : The result will exclude nothing. Returns ------- Series or DataFrame Summary statistics of the Series or Dataframe provided. See Also -------- DataFrame.count: Count number of non-NA/null observations. DataFrame.max: Maximum of the values in the object. DataFrame.min: Minimum of the values in the object. DataFrame.mean: Mean of the values. DataFrame.std: Standard deviation of the observations. DataFrame.select_dtypes: Subset of a DataFrame including/excluding columns based on their dtype. Notes ----- For numeric data, the result's index will include ``count``, ``mean``, ``std``, ``min``, ``max`` as well as lower, ``50`` and upper percentiles. By default the lower percentile is ``25`` and the upper percentile is ``75``. The ``50`` percentile is the same as the median. For object data (e.g. strings or timestamps), the result's index will include ``count``, ``unique``, ``top``, and ``freq``. The ``top`` is the most common value. The ``freq`` is the most common value's frequency. Timestamps also include the ``first`` and ``last`` items. If multiple object values have the highest count, then the ``count`` and ``top`` results will be arbitrarily chosen from among those with the highest count. For mixed data types provided via a ``DataFrame``, the default is to return only an analysis of numeric columns. If the dataframe consists only of object and categorical data without any numeric columns, the default is to return an analysis of both the object and categorical columns. If ``include='all'`` is provided as an option, the result will include a union of attributes of each type. The `include` and `exclude` parameters can be used to limit which columns in a ``DataFrame`` are analyzed for the output. The parameters are ignored when analyzing a ``Series``. Examples -------- Describing a numeric ``Series``. >>> s = pd.Series([1, 2, 3]) >>> s.describe() count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 dtype: float64 Describing a categorical ``Series``. >>> s = pd.Series(['a', 'a', 'b', 'c']) >>> s.describe() count 4 unique 3 top a freq 2 dtype: object Describing a timestamp ``Series``. >>> s = pd.Series([ ... np.datetime64("2000-01-01"), ... np.datetime64("2010-01-01"), ... np.datetime64("2010-01-01") ... ]) >>> s.describe() count 3 mean 2006-09-01 08:00:00 min 2000-01-01 00:00:00 25% 2004-12-31 12:00:00 50% 2010-01-01 00:00:00 75% 2010-01-01 00:00:00 max 2010-01-01 00:00:00 dtype: object Describing a ``DataFrame``. By default only numeric fields are returned. >>> df = pd.DataFrame({'categorical': pd.Categorical(['d','e','f']), ... 'numeric': [1, 2, 3], ... 'object': ['a', 'b', 'c'] ... }) >>> df.describe() numeric count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Describing all columns of a ``DataFrame`` regardless of data type. >>> df.describe(include='all') # doctest: +SKIP categorical numeric object count 3 3.0 3 unique 3 NaN 3 top f NaN a freq 1 NaN 1 mean NaN 2.0 NaN std NaN 1.0 NaN min NaN 1.0 NaN 25% NaN 1.5 NaN 50% NaN 2.0 NaN 75% NaN 2.5 NaN max NaN 3.0 NaN Describing a column from a ``DataFrame`` by accessing it as an attribute. >>> df.numeric.describe() count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Name: numeric, dtype: float64 Including only numeric columns in a ``DataFrame`` description. >>> df.describe(include=[np.number]) numeric count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Including only string columns in a ``DataFrame`` description. >>> df.describe(include=[np.object]) # doctest: +SKIP object count 3 unique 3 top a freq 1 Including only categorical columns from a ``DataFrame`` description. >>> df.describe(include=['category']) categorical count 3 unique 3 top f freq 1 Excluding numeric columns from a ``DataFrame`` description. >>> df.describe(exclude=[np.number]) # doctest: +SKIP categorical object count 3 3 unique 3 3 top f a freq 1 1 Excluding object columns from a ``DataFrame`` description. >>> df.describe(exclude=[np.object]) # doctest: +SKIP categorical numeric count 3 3.0 unique 3 NaN top f NaN freq 1 NaN mean NaN 2.0 std NaN 1.0 min NaN 1.0 25% NaN 1.5 50% NaN 2.0 75% NaN 2.5 max NaN 3.0 """ if self.ndim == 2 and self.columns.size == 0: raise ValueError("Cannot describe a DataFrame without columns") if percentiles is not None: # explicit conversion of `percentiles` to list percentiles = list(percentiles) # get them all to be in [0, 1] validate_percentile(percentiles) # median should always be included if 0.5 not in percentiles: percentiles.append(0.5) percentiles = np.asarray(percentiles) else: percentiles = np.array([0.25, 0.5, 0.75]) # sort and check for duplicates unique_pcts = np.unique(percentiles) if len(unique_pcts) < len(percentiles): raise ValueError("percentiles cannot contain duplicates") percentiles = unique_pcts formatted_percentiles = format_percentiles(percentiles) def describe_numeric_1d(series): stat_index = ( ["count", "mean", "std", "min"] + formatted_percentiles + ["max"] ) d = ( [series.count(), series.mean(), series.std(), series.min()] + series.quantile(percentiles).tolist() + [series.max()] ) return pd.Series(d, index=stat_index, name=series.name) def describe_categorical_1d(data): names = ["count", "unique"] objcounts = data.value_counts() count_unique = len(objcounts[objcounts != 0]) result = [data.count(), count_unique] dtype = None if result[1] > 0: top, freq = objcounts.index[0], objcounts.iloc[0] names += ["top", "freq"] result += [top, freq] # If the DataFrame is empty, set 'top' and 'freq' to None # to maintain output shape consistency else: names += ["top", "freq"] result += [np.nan, np.nan] dtype = "object" return pd.Series(result, index=names, name=data.name, dtype=dtype) def describe_timestamp_1d(data): # GH-30164 stat_index = ["count", "mean", "min"] + formatted_percentiles + ["max"] d = ( [data.count(), data.mean(), data.min()] + data.quantile(percentiles).tolist() + [data.max()] ) return pd.Series(d, index=stat_index, name=data.name) def describe_1d(data): if is_bool_dtype(data.dtype): return describe_categorical_1d(data) elif is_numeric_dtype(data): return describe_numeric_1d(data) elif is_datetime64_any_dtype(data.dtype): return describe_timestamp_1d(data) elif is_timedelta64_dtype(data.dtype): return describe_numeric_1d(data) else: return describe_categorical_1d(data) if self.ndim == 1: return describe_1d(self) elif (include is None) and (exclude is None): # when some numerics are found, keep only numerics data = self.select_dtypes(include=[np.number]) if len(data.columns) == 0: data = self elif include == "all": if exclude is not None: msg = "exclude must be None when include is 'all'" raise ValueError(msg) data = self else: data = self.select_dtypes(include=include, exclude=exclude) ldesc = [describe_1d(s) for _, s in data.items()] # set a convenient order for rows names: List[Label] = [] ldesc_indexes = sorted((x.index for x in ldesc), key=len) for idxnames in ldesc_indexes: for name in idxnames: if name not in names: names.append(name) d = pd.concat([x.reindex(names, copy=False) for x in ldesc], axis=1, sort=False) d.columns = data.columns.copy() return d _shared_docs[ "pct_change" ] = """ Percentage change between the current and a prior element. Computes the percentage change from the immediately previous row by default. This is useful in comparing the percentage of change in a time series of elements. Parameters ---------- periods : int, default 1 Periods to shift for forming percent change. fill_method : str, default 'pad' How to handle NAs before computing percent changes. limit : int, default None The number of consecutive NAs to fill before stopping. freq : DateOffset, timedelta, or str, optional Increment to use from time series API (e.g. 'M' or BDay()). **kwargs Additional keyword arguments are passed into `DataFrame.shift` or `Series.shift`. Returns ------- chg : Series or DataFrame The same type as the calling object. See Also -------- Series.diff : Compute the difference of two elements in a Series. DataFrame.diff : Compute the difference of two elements in a DataFrame. Series.shift : Shift the index by some number of periods. DataFrame.shift : Shift the index by some number of periods. Examples -------- **Series** >>> s = pd.Series([90, 91, 85]) >>> s 0 90 1 91 2 85 dtype: int64 >>> s.pct_change() 0 NaN 1 0.011111 2 -0.065934 dtype: float64 >>> s.pct_change(periods=2) 0 NaN 1 NaN 2 -0.055556 dtype: float64 See the percentage change in a Series where filling NAs with last valid observation forward to next valid. >>> s = pd.Series([90, 91, None, 85]) >>> s 0 90.0 1 91.0 2 NaN 3 85.0 dtype: float64 >>> s.pct_change(fill_method='ffill') 0 NaN 1 0.011111 2 0.000000 3 -0.065934 dtype: float64 **DataFrame** Percentage change in French franc, Deutsche Mark, and Italian lira from 1980-01-01 to 1980-03-01. >>> df = pd.DataFrame({ ... 'FR': [4.0405, 4.0963, 4.3149], ... 'GR': [1.7246, 1.7482, 1.8519], ... 'IT': [804.74, 810.01, 860.13]}, ... index=['1980-01-01', '1980-02-01', '1980-03-01']) >>> df FR GR IT 1980-01-01 4.0405 1.7246 804.74 1980-02-01 4.0963 1.7482 810.01 1980-03-01 4.3149 1.8519 860.13 >>> df.pct_change() FR GR IT 1980-01-01 NaN NaN NaN 1980-02-01 0.013810 0.013684 0.006549 1980-03-01 0.053365 0.059318 0.061876 Percentage of change in GOOG and APPL stock volume. Shows computing the percentage change between columns. >>> df = pd.DataFrame({ ... '2016': [1769950, 30586265], ... '2015': [1500923, 40912316], ... '2014': [1371819, 41403351]}, ... index=['GOOG', 'APPL']) >>> df 2016 2015 2014 GOOG 1769950 1500923 1371819 APPL 30586265 40912316 41403351 >>> df.pct_change(axis='columns') 2016 2015 2014 GOOG NaN -0.151997 -0.086016 APPL NaN 0.337604 0.012002 """ @Appender(_shared_docs["pct_change"] % _shared_doc_kwargs) def pct_change( self: FrameOrSeries, periods=1, fill_method="pad", limit=None, freq=None, **kwargs, ) -> FrameOrSeries: # TODO: Not sure if above is correct - need someone to confirm. axis = self._get_axis_number(kwargs.pop("axis", self._stat_axis_name)) if fill_method is None: data = self else: _data = self.fillna(method=fill_method, axis=axis, limit=limit) assert _data is not None # needed for mypy data = _data rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1 if freq is not None: # Shift method is implemented differently when freq is not None # We want to restore the original index rs = rs.loc[~rs.index.duplicated()] rs = rs.reindex_like(data) return rs def _agg_by_level(self, name, axis=0, level=0, skipna=True, **kwargs): if axis is None: raise ValueError("Must specify 'axis' when aggregating by level.") grouped = self.groupby(level=level, axis=axis, sort=False) if hasattr(grouped, name) and skipna: return getattr(grouped, name)(**kwargs) axis = self._get_axis_number(axis) method = getattr(type(self), name) applyf = lambda x: method(x, axis=axis, skipna=skipna, **kwargs) return grouped.aggregate(applyf) @classmethod def _add_numeric_operations(cls): """ Add the operations to the cls; evaluate the doc strings again """ axis_descr, name1, name2 = _doc_parms(cls) cls.any = _make_logical_function( cls, "any", name1=name1, name2=name2, axis_descr=axis_descr, desc=_any_desc, func=nanops.nanany, see_also=_any_see_also, examples=_any_examples, empty_value=False, ) cls.all = _make_logical_function( cls, "all", name1=name1, name2=name2, axis_descr=axis_descr, desc=_all_desc, func=nanops.nanall, see_also=_all_see_also, examples=_all_examples, empty_value=True, ) @Substitution( desc="Return the mean absolute deviation of the values " "for the requested axis.", name1=name1, name2=name2, axis_descr=axis_descr, min_count="", see_also="", examples="", ) @Appender(_num_doc_mad) def mad(self, axis=None, skipna=None, level=None): if skipna is None: skipna = True if axis is None: axis = self._stat_axis_number if level is not None: return self._agg_by_level("mad", axis=axis, level=level, skipna=skipna) data = self._get_numeric_data() if axis == 0: demeaned = data - data.mean(axis=0) else: demeaned = data.sub(data.mean(axis=1), axis=0) return np.abs(demeaned).mean(axis=axis, skipna=skipna) cls.mad = mad cls.sem = _make_stat_function_ddof( cls, "sem", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return unbiased standard error of the mean over requested " "axis.\n\nNormalized by N-1 by default. This can be changed " "using the ddof argument", func=nanops.nansem, ) cls.var = _make_stat_function_ddof( cls, "var", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return unbiased variance over requested axis.\n\nNormalized by " "N-1 by default. This can be changed using the ddof argument", func=nanops.nanvar, ) cls.std = _make_stat_function_ddof( cls, "std", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return sample standard deviation over requested axis." "\n\nNormalized by N-1 by default. This can be changed using the " "ddof argument", func=nanops.nanstd, ) cls.cummin = _make_cum_function( cls, "cummin", name1=name1, name2=name2, axis_descr=axis_descr, desc="minimum", accum_func=np.minimum.accumulate, accum_func_name="min", examples=_cummin_examples, ) cls.cumsum = _make_cum_function( cls, "cumsum", name1=name1, name2=name2, axis_descr=axis_descr, desc="sum", accum_func=np.cumsum, accum_func_name="sum", examples=_cumsum_examples, ) cls.cumprod = _make_cum_function( cls, "cumprod", name1=name1, name2=name2, axis_descr=axis_descr, desc="product", accum_func=np.cumprod, accum_func_name="prod", examples=_cumprod_examples, ) cls.cummax = _make_cum_function( cls, "cummax", name1=name1, name2=name2, axis_descr=axis_descr, desc="maximum", accum_func=np.maximum.accumulate, accum_func_name="max", examples=_cummax_examples, ) cls.sum = _make_min_count_stat_function( cls, "sum", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return the sum of the values for the requested axis.\n\n" "This is equivalent to the method ``numpy.sum``.", func=nanops.nansum, see_also=_stat_func_see_also, examples=_sum_examples, ) cls.mean = _make_stat_function( cls, "mean", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return the mean of the values for the requested axis.", func=nanops.nanmean, ) cls.skew = _make_stat_function( cls, "skew", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return unbiased skew over requested axis.\n\nNormalized by N-1.", func=nanops.nanskew, ) cls.kurt = _make_stat_function( cls, "kurt", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return unbiased kurtosis over requested axis.\n\n" "Kurtosis obtained using Fisher's definition of\n" "kurtosis (kurtosis of normal == 0.0). Normalized " "by N-1.", func=nanops.nankurt, ) cls.kurtosis = cls.kurt cls.prod = _make_min_count_stat_function( cls, "prod", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return the product of the values for the requested axis.", func=nanops.nanprod, examples=_prod_examples, ) cls.product = cls.prod cls.median = _make_stat_function( cls, "median", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return the median of the values for the requested axis.", func=nanops.nanmedian, ) cls.max = _make_stat_function( cls, "max", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return the maximum of the values for the requested axis.\n\n" "If you want the *index* of the maximum, use ``idxmax``. This is" "the equivalent of the ``numpy.ndarray`` method ``argmax``.", func=nanops.nanmax, see_also=_stat_func_see_also, examples=_max_examples, ) cls.min = _make_stat_function( cls, "min", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return the minimum of the values for the requested axis.\n\n" "If you want the *index* of the minimum, use ``idxmin``. This is" "the equivalent of the ``numpy.ndarray`` method ``argmin``.", func=nanops.nanmin, see_also=_stat_func_see_also, examples=_min_examples, ) @classmethod def _add_series_or_dataframe_operations(cls): """ Add the series or dataframe only operations to the cls; evaluate the doc strings again. """ from pandas.core.window import EWM, Expanding, Rolling, Window @doc(Rolling) def rolling( self, window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None, ): axis = self._get_axis_number(axis) if win_type is not None: return Window( self, window=window, min_periods=min_periods, center=center, win_type=win_type, on=on, axis=axis, closed=closed, ) return Rolling( self, window=window, min_periods=min_periods, center=center, win_type=win_type, on=on, axis=axis, closed=closed, ) cls.rolling = rolling @doc(Expanding) def expanding(self, min_periods=1, center=False, axis=0): axis = self._get_axis_number(axis) return Expanding(self, min_periods=min_periods, center=center, axis=axis) cls.expanding = expanding @doc(EWM) def ewm( self, com=None, span=None, halflife=None, alpha=None, min_periods=0, adjust=True, ignore_na=False, axis=0, ): axis = self._get_axis_number(axis) return EWM( self, com=com, span=span, halflife=halflife, alpha=alpha, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na, axis=axis, ) cls.ewm = ewm @Appender(_shared_docs["transform"] % dict(axis="", **_shared_doc_kwargs)) def transform(self, func, *args, **kwargs): result = self.agg(func, *args, **kwargs) if is_scalar(result) or len(result) != len(self): raise ValueError("transforms cannot produce aggregated results") return result # ---------------------------------------------------------------------- # Misc methods _shared_docs[ "valid_index" ] = """ Return index for %(position)s non-NA/null value. Returns ------- scalar : type of index Notes ----- If all elements are non-NA/null, returns None. Also returns None for empty %(klass)s. """ def _find_valid_index(self, how: str): """ Retrieves the index of the first valid value. Parameters ---------- how : {'first', 'last'} Use this parameter to change between the first or last valid index. Returns ------- idx_first_valid : type of index """ idxpos = find_valid_index(self._values, how) if idxpos is None: return None return self.index[idxpos] @Appender( _shared_docs["valid_index"] % {"position": "first", "klass": "Series/DataFrame"} ) def first_valid_index(self): return self._find_valid_index("first") @Appender( _shared_docs["valid_index"] % {"position": "last", "klass": "Series/DataFrame"} ) def last_valid_index(self): return self._find_valid_index("last") def _doc_parms(cls): """Return a tuple of the doc parms.""" axis_descr = ( f"{{{", ".join(f"{a} ({i})' for i, a in enumerate(cls._AXIS_ORDERS))}}}" ) name = cls._constructor_sliced.__name__ if cls._AXIS_LEN > 1 else "scalar" name2 = cls.__name__ return axis_descr, name, name2 _num_doc = """ %(desc)s Parameters ---------- axis : %(axis_descr)s Axis for the function to be applied on. skipna : bool, default True Exclude NA/null values when computing the result. level : int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a %(name1)s. numeric_only : bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. %(min_count)s\ **kwargs Additional keyword arguments to be passed to the function. Returns ------- %(name1)s or %(name2)s (if level specified)\ %(see_also)s\ %(examples)s """ _num_doc_mad = """ %(desc)s Parameters ---------- axis : %(axis_descr)s Axis for the function to be applied on. skipna : bool, default None Exclude NA/null values when computing the result. level : int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a %(name1)s. Returns ------- %(name1)s or %(name2)s (if level specified)\ %(see_also)s\ %(examples)s """ _num_ddof_doc = """ %(desc)s Parameters ---------- axis : %(axis_descr)s skipna : bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. level : int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a %(name1)s. ddof : int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. numeric_only : bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. Returns ------- %(name1)s or %(name2)s (if level specified)\n""" _bool_doc = """ %(desc)s Parameters ---------- axis : {0 or 'index', 1 or 'columns', None}, default 0 Indicate which axis or axes should be reduced. * 0 / 'index' : reduce the index, return a Series whose index is the original column labels. * 1 / 'columns' : reduce the columns, return a Series whose index is the original index. * None : reduce all axes, return a scalar. bool_only : bool, default None Include only boolean columns. If None, will attempt to use everything, then use only boolean data. Not implemented for Series. skipna : bool, default True Exclude NA/null values. If the entire row/column is NA and skipna is True, then the result will be %(empty_value)s, as for an empty row/column. If skipna is False, then NA are treated as True, because these are not equal to zero. level : int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a %(name1)s. **kwargs : any, default None Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- %(name1)s or %(name2)s If level is specified, then, %(name2)s is returned; otherwise, %(name1)s is returned. %(see_also)s %(examples)s""" _all_desc = """\ Return whether all elements are True, potentially over an axis. Returns True unless there at least one element within a series or along a Dataframe axis that is False or equivalent (e.g. zero or empty).""" _all_examples = """\ Examples -------- **Series** >>> pd.Series([True, True]).all() True >>> pd.Series([True, False]).all() False >>> pd.Series([]).all() True >>> pd.Series([np.nan]).all() True >>> pd.Series([np.nan]).all(skipna=False) True **DataFrames** Create a dataframe from a dictionary. >>> df = pd.DataFrame({'col1': [True, True], 'col2': [True, False]}) >>> df col1 col2 0 True True 1 True False Default behaviour checks if column-wise values all return True. >>> df.all() col1 True col2 False dtype: bool Specify ``axis='columns'`` to check if row-wise values all return True. >>> df.all(axis='columns') 0 True 1 False dtype: bool Or ``axis=None`` for whether every value is True. >>> df.all(axis=None) False """ _all_see_also = """\ See Also -------- Series.all : Return True if all elements are True. DataFrame.any : Return True if one (or more) elements are True. """ _cnum_doc = """ Return cumulative %(desc)s over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative %(desc)s. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The index or the name of the axis. 0 is equivalent to None or 'index'. skipna : bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. *args, **kwargs Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- %(name1)s or %(name2)s Return cumulative %(desc)s of %(name1)s or %(name2)s. See Also -------- core.window.Expanding.%(accum_func_name)s : Similar functionality but ignores ``NaN`` values. %(name2)s.%(accum_func_name)s : Return the %(desc)s over %(name2)s axis. %(name2)s.cummax : Return cumulative maximum over %(name2)s axis. %(name2)s.cummin : Return cumulative minimum over %(name2)s axis. %(name2)s.cumsum : Return cumulative sum over %(name2)s axis. %(name2)s.cumprod : Return cumulative product over %(name2)s axis. %(examples)s""" _cummin_examples = """\ Examples -------- **Series** >>> s = pd.Series([2, np.nan, 5, -1, 0]) >>> s 0 2.0 1 NaN 2 5.0 3 -1.0 4 0.0 dtype: float64 By default, NA values are ignored. >>> s.cummin() 0 2.0 1 NaN 2 2.0 3 -1.0 4 -1.0 dtype: float64 To include NA values in the operation, use ``skipna=False`` >>> s.cummin(skipna=False) 0 2.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 **DataFrame** >>> df = pd.DataFrame([[2.0, 1.0], ... [3.0, np.nan], ... [1.0, 0.0]], ... columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the minimum in each column. This is equivalent to ``axis=None`` or ``axis='index'``. >>> df.cummin() A B 0 2.0 1.0 1 2.0 NaN 2 1.0 0.0 To iterate over columns and find the minimum in each row, use ``axis=1`` >>> df.cummin(axis=1) A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 """ _cumsum_examples = """\ Examples -------- **Series** >>> s = pd.Series([2, np.nan, 5, -1, 0]) >>> s 0 2.0 1 NaN 2 5.0 3 -1.0 4 0.0 dtype: float64 By default, NA values are ignored. >>> s.cumsum() 0 2.0 1 NaN 2 7.0 3 6.0 4 6.0 dtype: float64 To include NA values in the operation, use ``skipna=False`` >>> s.cumsum(skipna=False) 0 2.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 **DataFrame** >>> df = pd.DataFrame([[2.0, 1.0], ... [3.0, np.nan], ... [1.0, 0.0]], ... columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the sum in each column. This is equivalent to ``axis=None`` or ``axis='index'``. >>> df.cumsum() A B 0 2.0 1.0 1 5.0 NaN 2 6.0 1.0 To iterate over columns and find the sum in each row, use ``axis=1`` >>> df.cumsum(axis=1) A B 0 2.0 3.0 1 3.0 NaN 2 1.0 1.0 """ _cumprod_examples = """\ Examples -------- **Series** >>> s = pd.Series([2, np.nan, 5, -1, 0]) >>> s 0 2.0 1 NaN 2 5.0 3 -1.0 4 0.0 dtype: float64 By default, NA values are ignored. >>> s.cumprod() 0 2.0 1 NaN 2 10.0 3 -10.0 4 -0.0 dtype: float64 To include NA values in the operation, use ``skipna=False`` >>> s.cumprod(skipna=False) 0 2.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 **DataFrame** >>> df = pd.DataFrame([[2.0, 1.0], ... [3.0, np.nan], ... [1.0, 0.0]], ... columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the product in each column. This is equivalent to ``axis=None`` or ``axis='index'``. >>> df.cumprod() A B 0 2.0 1.0 1 6.0 NaN 2 6.0 0.0 To iterate over columns and find the product in each row, use ``axis=1`` >>> df.cumprod(axis=1) A B 0 2.0 2.0 1 3.0 NaN 2 1.0 0.0 """ _cummax_examples = """\ Examples -------- **Series** >>> s = pd.Series([2, np.nan, 5, -1, 0]) >>> s 0 2.0 1 NaN 2 5.0 3 -1.0 4 0.0 dtype: float64 By default, NA values are ignored. >>> s.cummax() 0 2.0 1 NaN 2 5.0 3 5.0 4 5.0 dtype: float64 To include NA values in the operation, use ``skipna=False`` >>> s.cummax(skipna=False) 0 2.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 **DataFrame** >>> df = pd.DataFrame([[2.0, 1.0], ... [3.0, np.nan], ... [1.0, 0.0]], ... columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the maximum in each column. This is equivalent to ``axis=None`` or ``axis='index'``. >>> df.cummax() A B 0 2.0 1.0 1 3.0 NaN 2 3.0 1.0 To iterate over columns and find the maximum in each row, use ``axis=1`` >>> df.cummax(axis=1) A B 0 2.0 2.0 1 3.0 NaN 2 1.0 1.0 """ _any_see_also = """\ See Also -------- numpy.any : Numpy version of this method. Series.any : Return whether any element is True. Series.all : Return whether all elements are True. DataFrame.any : Return whether any element is True over requested axis. DataFrame.all : Return whether all elements are True over requested axis. """ _any_desc = """\ Return whether any element is True, potentially over an axis. Returns False unless there at least one element within a series or along a Dataframe axis that is True or equivalent (e.g. non-zero or non-empty).""" _any_examples = """\ Examples -------- **Series** For Series input, the output is a scalar indicating whether any element is True. >>> pd.Series([False, False]).any() False >>> pd.Series([True, False]).any() True >>> pd.Series([]).any() False >>> pd.Series([np.nan]).any() False >>> pd.Series([np.nan]).any(skipna=False) True **DataFrame** Whether each column contains at least one True element (the default). >>> df = pd.DataFrame({"A": [1, 2], "B": [0, 2], "C": [0, 0]}) >>> df A B C 0 1 0 0 1 2 2 0 >>> df.any() A True B True C False dtype: bool Aggregating over the columns. >>> df = pd.DataFrame({"A": [True, False], "B": [1, 2]}) >>> df A B 0 True 1 1 False 2 >>> df.any(axis='columns') 0 True 1 True dtype: bool >>> df = pd.DataFrame({"A": [True, False], "B": [1, 0]}) >>> df A B 0 True 1 1 False 0 >>> df.any(axis='columns') 0 True 1 False dtype: bool Aggregating over the entire DataFrame with ``axis=None``. >>> df.any(axis=None) True `any` for an empty DataFrame is an empty Series. >>> pd.DataFrame([]).any() Series([], dtype: bool) """ _shared_docs[ "stat_func_example" ] = """ Examples -------- >>> idx = pd.MultiIndex.from_arrays([ ... ['warm', 'warm', 'cold', 'cold'], ... ['dog', 'falcon', 'fish', 'spider']], ... names=['blooded', 'animal']) >>> s = pd.Series([4, 2, 0, 8], name='legs', index=idx) >>> s blooded animal warm dog 4 falcon 2 cold fish 0 spider 8 Name: legs, dtype: int64 >>> s.{stat_func}() {default_output} {verb} using level names, as well as indices. >>> s.{stat_func}(level='blooded') blooded warm {level_output_0} cold {level_output_1} Name: legs, dtype: int64 >>> s.{stat_func}(level=0) blooded warm {level_output_0} cold {level_output_1} Name: legs, dtype: int64""" _sum_examples = _shared_docs["stat_func_example"].format( stat_func="sum", verb="Sum", default_output=14, level_output_0=6, level_output_1=8 ) _sum_examples += """ By default, the sum of an empty or all-NA Series is ``0``. >>> pd.Series([]).sum() # min_count=0 is the default 0.0 This can be controlled with the ``min_count`` parameter. For example, if you'd like the sum of an empty series to be NaN, pass ``min_count=1``. >>> pd.Series([]).sum(min_count=1) nan Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and empty series identically. >>> pd.Series([np.nan]).sum() 0.0 >>> pd.Series([np.nan]).sum(min_count=1) nan""" _max_examples = _shared_docs["stat_func_example"].format( stat_func="max", verb="Max", default_output=8, level_output_0=4, level_output_1=8 ) _min_examples = _shared_docs["stat_func_example"].format( stat_func="min", verb="Min", default_output=0, level_output_0=2, level_output_1=0 ) _stat_func_see_also = """ See Also -------- Series.sum : Return the sum. Series.min : Return the minimum. Series.max : Return the maximum. Series.idxmin : Return the index of the minimum. Series.idxmax : Return the index of the maximum. DataFrame.sum : Return the sum over the requested axis. DataFrame.min : Return the minimum over the requested axis. DataFrame.max : Return the maximum over the requested axis. DataFrame.idxmin : Return the index of the minimum over the requested axis. DataFrame.idxmax : Return the index of the maximum over the requested axis.""" _prod_examples = """ Examples -------- By default, the product of an empty or all-NA Series is ``1`` >>> pd.Series([]).prod() 1.0 This can be controlled with the ``min_count`` parameter >>> pd.Series([]).prod(min_count=1) nan Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and empty series identically. >>> pd.Series([np.nan]).prod() 1.0 >>> pd.Series([np.nan]).prod(min_count=1) nan""" _min_count_stub = """\ min_count : int, default 0 The required number of valid values to perform the operation. If fewer than ``min_count`` non-NA values are present the result will be NA. .. versionadded:: 0.22.0 Added with the default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1. """ def _make_min_count_stat_function( cls, name: str, name1: str, name2: str, axis_descr: str, desc: str, func: Callable, see_also: str = "", examples: str = "", ) -> Callable: @Substitution( desc=desc, name1=name1, name2=name2, axis_descr=axis_descr, min_count=_min_count_stub, see_also=see_also, examples=examples, ) @Appender(_num_doc) def stat_func( self, axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs, ): if name == "sum": nv.validate_sum(tuple(), kwargs) elif name == "prod": nv.validate_prod(tuple(), kwargs) else: nv.validate_stat_func(tuple(), kwargs, fname=name) if skipna is None: skipna = True if axis is None: axis = self._stat_axis_number if level is not None: return self._agg_by_level( name, axis=axis, level=level, skipna=skipna, min_count=min_count ) return self._reduce( func, name=name, axis=axis, skipna=skipna, numeric_only=numeric_only, min_count=min_count, ) return set_function_name(stat_func, name, cls) def _make_stat_function( cls, name: str, name1: str, name2: str, axis_descr: str, desc: str, func: Callable, see_also: str = "", examples: str = "", ) -> Callable: @Substitution( desc=desc, name1=name1, name2=name2, axis_descr=axis_descr, min_count="", see_also=see_also, examples=examples, ) @Appender(_num_doc) def stat_func( self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs ): if name == "median": nv.validate_median(tuple(), kwargs) else: nv.validate_stat_func(tuple(), kwargs, fname=name) if skipna is None: skipna = True if axis is None: axis = self._stat_axis_number if level is not None: return self._agg_by_level(name, axis=axis, level=level, skipna=skipna) return self._reduce( func, name=name, axis=axis, skipna=skipna, numeric_only=numeric_only ) return set_function_name(stat_func, name, cls) def _make_stat_function_ddof( cls, name: str, name1: str, name2: str, axis_descr: str, desc: str, func: Callable ) -> Callable: @Substitution(desc=desc, name1=name1, name2=name2, axis_descr=axis_descr) @Appender(_num_ddof_doc) def stat_func( self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs ): nv.validate_stat_ddof_func(tuple(), kwargs, fname=name) if skipna is None: skipna = True if axis is None: axis = self._stat_axis_number if level is not None: return self._agg_by_level( name, axis=axis, level=level, skipna=skipna, ddof=ddof ) return self._reduce( func, name, axis=axis, numeric_only=numeric_only, skipna=skipna, ddof=ddof ) return set_function_name(stat_func, name, cls) def _make_cum_function( cls, name: str, name1: str, name2: str, axis_descr: str, desc: str, accum_func: Callable, accum_func_name: str, examples: str, ) -> Callable: @Substitution( desc=desc, name1=name1, name2=name2, axis_descr=axis_descr, accum_func_name=accum_func_name, examples=examples, ) @Appender(_cnum_doc) def cum_func(self, axis=None, skipna=True, *args, **kwargs): skipna = nv.validate_cum_func_with_skipna(skipna, args, kwargs, name) if axis is None: axis = self._stat_axis_number else: axis = self._get_axis_number(axis) if axis == 1: return cum_func(self.T, axis=0, skipna=skipna, *args, **kwargs).T def block_accum_func(blk_values): values = blk_values.T if hasattr(blk_values, "T") else blk_values result = nanops.na_accum_func(values, accum_func, skipna=skipna) result = result.T if hasattr(result, "T") else result return result result = self._mgr.apply(block_accum_func) return self._constructor(result).__finalize__(self, method=name) return set_function_name(cum_func, name, cls) def _make_logical_function( cls, name: str, name1: str, name2: str, axis_descr: str, desc: str, func: Callable, see_also: str, examples: str, empty_value: bool, ) -> Callable: @Substitution( desc=desc, name1=name1, name2=name2, axis_descr=axis_descr, see_also=see_also, examples=examples, empty_value=empty_value, ) @Appender(_bool_doc) def logical_func(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): nv.validate_logical_func(tuple(), kwargs, fname=name) if level is not None: if bool_only is not None: raise NotImplementedError( "Option bool_only is not implemented with option level." ) return self._agg_by_level(name, axis=axis, level=level, skipna=skipna) return self._reduce( func, name=name, axis=axis, skipna=skipna, numeric_only=bool_only, filter_type="bool", ) return set_function_name(logical_func, name, cls)
import collections from datetime import timedelta import functools import gc import json import operator import pickle import re from textwrap import dedent from typing import ( TYPE_CHECKING, Any, Callable, Dict, FrozenSet, Hashable, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) import warnings import weakref import numpy as np from pandas._config import config from pandas._libs import Timestamp, lib from pandas._typing import ( Axis, FilePathOrBuffer, FrameOrSeries, JSONSerializable, Label, Level, Renamer, TimedeltaConvertibleTypes, TimestampConvertibleTypes, ValueKeyFunc, ) from pandas.compat import set_function_name from pandas.compat._optional import import_optional_dependency from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import ( Appender, Substitution, doc, rewrite_axis_style_signature, ) from pandas.util._validators import ( validate_bool_kwarg, validate_fillna_kwargs, validate_percentile, ) from pandas.core.dtypes.common import ( ensure_int64, ensure_object, ensure_str, is_bool, is_bool_dtype, is_datetime64_any_dtype, is_datetime64tz_dtype, is_dict_like, is_extension_array_dtype, is_float, is_list_like, is_number, is_numeric_dtype, is_object_dtype, is_re_compilable, is_scalar, is_timedelta64_dtype, pandas_dtype, ) from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries from pandas.core.dtypes.inference import is_hashable from pandas.core.dtypes.missing import isna, notna import pandas as pd from pandas.core import missing, nanops import pandas.core.algorithms as algos from pandas.core.base import PandasObject, SelectionMixin import pandas.core.common as com from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.indexes.api import ( Index, InvalidIndexError, MultiIndex, RangeIndex, ensure_index, ) from pandas.core.indexes.datetimes import DatetimeIndex from pandas.core.indexes.period import Period, PeriodIndex import pandas.core.indexing as indexing from pandas.core.internals import BlockManager from pandas.core.missing import find_valid_index from pandas.core.ops import _align_method_FRAME from pandas.io.formats import format as fmt from pandas.io.formats.format import DataFrameFormatter, format_percentiles from pandas.io.formats.printing import pprint_thing from pandas.tseries.frequencies import to_offset from pandas.tseries.offsets import Tick if TYPE_CHECKING: from pandas.core.resample import Resampler # goal is to be able to define the docs close to function, while still being # able to share _shared_docs: Dict[str, str] = dict() _shared_doc_kwargs = dict( axes="keywords for axes", klass="Series/DataFrame", axes_single_arg="int or labels for object", args_transpose="axes to permute (int or label for object)", optional_by=""" by : str or list of str Name or list of names to sort by""", ) def _single_replace(self, to_replace, method, inplace, limit): """ Replaces values in a Series using the fill method specified when no replacement value is given in the replace method """ if self.ndim != 1: raise TypeError( f"cannot replace {to_replace} with method {method} on a " f"{type(self).__name__}" ) orig_dtype = self.dtype result = self if inplace else self.copy() fill_f = missing.get_fill_func(method) mask = missing.mask_missing(result.values, to_replace) values = fill_f(result.values, limit=limit, mask=mask) if values.dtype == orig_dtype and inplace: return result = pd.Series(values, index=self.index, dtype=self.dtype).__finalize__(self) if inplace: self._update_inplace(result) return return result bool_t = bool # Need alias because NDFrame has def bool: class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin): """ N-dimensional analogue of DataFrame. Store multi-dimensional in a size-mutable, labeled data structure Parameters ---------- data : BlockManager axes : list copy : bool, default False """ _internal_names: List[str] = [ "_mgr", "_cacher", "_item_cache", "_cache", "_is_copy", "_subtyp", "_name", "_index", "_default_kind", "_default_fill_value", "_metadata", "__array_struct__", "__array_interface__", ] _internal_names_set: Set[str] = set(_internal_names) _accessors: Set[str] = set() _deprecations: FrozenSet[str] = frozenset(["get_values"]) _metadata: List[str] = [] _is_copy = None _mgr: BlockManager _attrs: Dict[Optional[Hashable], Any] _typ: str # ---------------------------------------------------------------------- # Constructors def __init__( self, data: BlockManager, copy: bool = False, attrs: Optional[Mapping[Optional[Hashable], Any]] = None, ): # copy kwarg is retained for mypy compat, is not used object.__setattr__(self, "_is_copy", None) object.__setattr__(self, "_mgr", data) object.__setattr__(self, "_item_cache", {}) if attrs is None: attrs = {} else: attrs = dict(attrs) object.__setattr__(self, "_attrs", attrs) @classmethod def _init_mgr(cls, mgr, axes, dtype=None, copy: bool = False) -> BlockManager: """ passed a manager and a axes dict """ for a, axe in axes.items(): if axe is not None: axe = ensure_index(axe) bm_axis = cls._get_block_manager_axis(a) mgr = mgr.reindex_axis(axe, axis=bm_axis, copy=False) # make a copy if explicitly requested if copy: mgr = mgr.copy() if dtype is not None: # avoid further copies if we can if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype: mgr = mgr.astype(dtype=dtype) return mgr # ---------------------------------------------------------------------- @property def attrs(self) -> Dict[Optional[Hashable], Any]: """ Dictionary of global attributes on this object. .. warning:: attrs is experimental and may change without warning. """ if self._attrs is None: self._attrs = {} return self._attrs @attrs.setter def attrs(self, value: Mapping[Optional[Hashable], Any]) -> None: self._attrs = dict(value) @classmethod def _validate_dtype(cls, dtype): """ validate the passed dtype """ if dtype is not None: dtype = pandas_dtype(dtype) # a compound dtype if dtype.kind == "V": raise NotImplementedError( "compound dtypes are not implemented " f"in the {cls.__name__} constructor" ) return dtype # ---------------------------------------------------------------------- # Construction @property def _constructor(self: FrameOrSeries) -> Type[FrameOrSeries]: """ Used when a manipulation result has the same dimensions as the original. """ raise AbstractMethodError(self) @property def _constructor_sliced(self): """ Used when a manipulation result has one lower dimension(s) as the original, such as DataFrame single columns slicing. """ raise AbstractMethodError(self) @property def _constructor_expanddim(self): """ Used when a manipulation result has one higher dimension as the original, such as Series.to_frame() """ raise NotImplementedError # ---------------------------------------------------------------------- # Internals @property def _data(self): # GH#33054 retained because some downstream packages uses this, # e.g. fastparquet return self._mgr # ---------------------------------------------------------------------- # Axis _stat_axis_number = 0 _stat_axis_name = "index" _ix = None _AXIS_ORDERS: List[str] _AXIS_TO_AXIS_NUMBER: Dict[Axis, int] = {0: 0, "index": 0, "rows": 0} _AXIS_REVERSED: bool _info_axis_number: int _info_axis_name: str _AXIS_LEN: int @property def _AXIS_NUMBERS(self) -> Dict[str, int]: """.. deprecated:: 1.1.0""" warnings.warn( "_AXIS_NUMBERS has been deprecated.", FutureWarning, stacklevel=3, ) return {"index": 0} @property def _AXIS_NAMES(self) -> Dict[int, str]: """.. deprecated:: 1.1.0""" warnings.warn( "_AXIS_NAMES has been deprecated.", FutureWarning, stacklevel=3, ) return {0: "index"} def _construct_axes_dict(self, axes=None, **kwargs): """Return an axes dictionary for myself.""" d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)} d.update(kwargs) return d @classmethod def _construct_axes_from_arguments( cls, args, kwargs, require_all: bool = False, sentinel=None ): """ Construct and returns axes if supplied in args/kwargs. If require_all, raise if all axis arguments are not supplied return a tuple of (axes, kwargs). sentinel specifies the default parameter when an axis is not supplied; useful to distinguish when a user explicitly passes None in scenarios where None has special meaning. """ # construct the args args = list(args) for a in cls._AXIS_ORDERS: # look for a argument by position if a not in kwargs: try: kwargs[a] = args.pop(0) except IndexError as err: if require_all: raise TypeError( "not enough/duplicate arguments specified!" ) from err axes = {a: kwargs.pop(a, sentinel) for a in cls._AXIS_ORDERS} return axes, kwargs @classmethod def _get_axis_number(cls, axis: Axis) -> int: try: return cls._AXIS_TO_AXIS_NUMBER[axis] except KeyError: raise ValueError(f"No axis named {axis} for object type {cls.__name__}") @classmethod def _get_axis_name(cls, axis: Axis) -> str: axis_number = cls._get_axis_number(axis) return cls._AXIS_ORDERS[axis_number] def _get_axis(self, axis: Axis) -> Index: axis_number = self._get_axis_number(axis) assert axis_number in {0, 1} return self.index if axis_number == 0 else self.columns @classmethod def _get_block_manager_axis(cls, axis: Axis) -> int: """Map the axis to the block_manager axis.""" axis = cls._get_axis_number(axis) if cls._AXIS_REVERSED: m = cls._AXIS_LEN - 1 return m - axis return axis def _get_axis_resolvers(self, axis: str) -> Dict[str, ABCSeries]: # index or columns axis_index = getattr(self, axis) d = dict() prefix = axis[0] for i, name in enumerate(axis_index.names): if name is not None: key = level = name else: # prefix with 'i' or 'c' depending on the input axis # e.g., you must do ilevel_0 for the 0th level of an unnamed # multiiindex key = f"{prefix}level_{i}" level = i level_values = axis_index.get_level_values(level) s = level_values.to_series() s.index = axis_index d[key] = s # put the index/columns itself in the dict if isinstance(axis_index, MultiIndex): dindex = axis_index else: dindex = axis_index.to_series() d[axis] = dindex return d def _get_index_resolvers(self) -> Dict[str, ABCSeries]: from pandas.core.computation.parsing import clean_column_name d: Dict[str, ABCSeries] = {} for axis_name in self._AXIS_ORDERS: d.update(self._get_axis_resolvers(axis_name)) return {clean_column_name(k): v for k, v in d.items() if not isinstance(k, int)} def _get_cleaned_column_resolvers(self) -> Dict[str, ABCSeries]: """ Return the special character free column resolvers of a dataframe. Column names with special characters are 'cleaned up' so that they can be referred to by backtick quoting. Used in :meth:`DataFrame.eval`. """ from pandas.core.computation.parsing import clean_column_name if isinstance(self, ABCSeries): return {clean_column_name(self.name): self} return { clean_column_name(k): v for k, v in self.items() if not isinstance(k, int) } @property def _info_axis(self) -> Index: return getattr(self, self._info_axis_name) @property def _stat_axis(self) -> Index: return getattr(self, self._stat_axis_name) @property def shape(self) -> Tuple[int, ...]: """ Return a tuple of axis dimensions """ return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS) @property def axes(self) -> List[Index]: """ Return index label(s) of the internal NDFrame """ # we do it this way because if we have reversed axes, then # the block manager shows then reversed return [self._get_axis(a) for a in self._AXIS_ORDERS] @property def ndim(self) -> int: """ Return an int representing the number of axes / array dimensions. Return 1 if Series. Otherwise return 2 if DataFrame. See Also -------- ndarray.ndim : Number of array dimensions. Examples -------- >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3}) >>> s.ndim 1 >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}) >>> df.ndim 2 """ return self._mgr.ndim @property def size(self) -> int: """ Return an int representing the number of elements in this object. Return the number of rows if Series. Otherwise return the number of rows times number of columns if DataFrame. See Also -------- ndarray.size : Number of elements in the array. Examples -------- >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3}) >>> s.size 3 >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}) >>> df.size 4 """ return np.prod(self.shape) @property def _selected_obj(self: FrameOrSeries) -> FrameOrSeries: """ internal compat with SelectionMixin """ return self @property def _obj_with_exclusions(self: FrameOrSeries) -> FrameOrSeries: """ internal compat with SelectionMixin """ return self def set_axis(self, labels, axis: Axis = 0, inplace: bool = False): """ Assign desired index to given axis. Indexes for%(extended_summary_sub)s row labels can be changed by assigning a list-like or Index. Parameters ---------- labels : list-like, Index The values for the new index. axis : %(axes_single_arg)s, default 0 The axis to update. The value 0 identifies the rows%(axis_description_sub)s. inplace : bool, default False Whether to return a new %(klass)s instance. Returns ------- renamed : %(klass)s or None An object of type %(klass)s if inplace=False, None otherwise. See Also -------- %(klass)s.rename_axis : Alter the name of the index%(see_also_sub)s. """ if inplace: setattr(self, self._get_axis_name(axis), labels) else: obj = self.copy() obj.set_axis(labels, axis=axis, inplace=True) return obj def _set_axis(self, axis: int, labels: Index) -> None: labels = ensure_index(labels) self._mgr.set_axis(axis, labels) self._clear_item_cache() def swapaxes(self: FrameOrSeries, axis1, axis2, copy=True) -> FrameOrSeries: """ Interchange axes and swap values axes appropriately. Returns ------- y : same as input """ i = self._get_axis_number(axis1) j = self._get_axis_number(axis2) if i == j: if copy: return self.copy() return self mapping = {i: j, j: i} new_axes = (self._get_axis(mapping.get(k, k)) for k in range(self._AXIS_LEN)) new_values = self.values.swapaxes(i, j) if copy: new_values = new_values.copy() # ignore needed because of NDFrame constructor is different than # DataFrame/Series constructors. return self._constructor(new_values, *new_axes).__finalize__( # type: ignore self, method="swapaxes" ) def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries: """ Return DataFrame with requested index / column level(s) removed. .. versionadded:: 0.24.0 Parameters ---------- level : int, str, or list-like If a string is given, must be the name of a level If list-like, elements must be names or positional indexes of levels. axis : {0 or 'index', 1 or 'columns'}, default 0 Axis along which the level(s) is removed: * 0 or 'index': remove level(s) in column. * 1 or 'columns': remove level(s) in row. Returns ------- DataFrame DataFrame with requested index / column level(s) removed. Examples -------- >>> df = pd.DataFrame([ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12] ... ]).set_index([0, 1]).rename_axis(['a', 'b']) >>> df.columns = pd.MultiIndex.from_tuples([ ... ('c', 'e'), ('d', 'f') ... ], names=['level_1', 'level_2']) >>> df level_1 c d level_2 e f a b 1 2 3 4 5 6 7 8 9 10 11 12 >>> df.droplevel('a') level_1 c d level_2 e f b 2 3 4 6 7 8 10 11 12 >>> df.droplevel('level_2', axis=1) level_1 c d a b 1 2 3 4 5 6 7 8 9 10 11 12 """ labels = self._get_axis(axis) new_labels = labels.droplevel(level) result = self.set_axis(new_labels, axis=axis, inplace=False) return result def pop(self: FrameOrSeries, item) -> FrameOrSeries: """ Return item and drop from frame. Raise KeyError if not found. Parameters ---------- item : str Label of column to be popped. Returns ------- Series Examples -------- >>> df = pd.DataFrame([('falcon', 'bird', 389.0), ... ('parrot', 'bird', 24.0), ... ('lion', 'mammal', 80.5), ... ('monkey', 'mammal', np.nan)], ... columns=('name', 'class', 'max_speed')) >>> df name class max_speed 0 falcon bird 389.0 1 parrot bird 24.0 2 lion mammal 80.5 3 monkey mammal NaN >>> df.pop('class') 0 bird 1 bird 2 mammal 3 mammal Name: class, dtype: object >>> df name max_speed 0 falcon 389.0 1 parrot 24.0 2 lion 80.5 3 monkey NaN """ result = self[item] del self[item] if self.ndim == 2: result._reset_cacher() return result def squeeze(self, axis=None): """ Squeeze 1 dimensional axis objects into scalars. Series or DataFrames with a single element are squeezed to a scalar. DataFrames with a single column or a single row are squeezed to a Series. Otherwise the object is unchanged. This method is most useful when you don't know if your object is a Series or DataFrame, but you do know it has just a single column. In that case you can safely call `squeeze` to ensure you have a Series. Parameters ---------- axis : {0 or 'index', 1 or 'columns', None}, default None A specific axis to squeeze. By default, all length-1 axes are squeezed. Returns ------- DataFrame, Series, or scalar The projection after squeezing `axis` or all the axes. See Also -------- Series.iloc : Integer-location based indexing for selecting scalars. DataFrame.iloc : Integer-location based indexing for selecting Series. Series.to_frame : Inverse of DataFrame.squeeze for a single-column DataFrame. Examples -------- >>> primes = pd.Series([2, 3, 5, 7]) Slicing might produce a Series with a single value: >>> even_primes = primes[primes % 2 == 0] >>> even_primes 0 2 dtype: int64 >>> even_primes.squeeze() 2 Squeezing objects with more than one value in every axis does nothing: >>> odd_primes = primes[primes % 2 == 1] >>> odd_primes 1 3 2 5 3 7 dtype: int64 >>> odd_primes.squeeze() 1 3 2 5 3 7 dtype: int64 Squeezing is even more effective when used with DataFrames. >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) >>> df a b 0 1 2 1 3 4 Slicing a single column will produce a DataFrame with the columns having only one value: >>> df_a = df[['a']] >>> df_a a 0 1 1 3 So the columns can be squeezed down, resulting in a Series: >>> df_a.squeeze('columns') 0 1 1 3 Name: a, dtype: int64 Slicing a single row from a single column will produce a single scalar DataFrame: >>> df_0a = df.loc[df.index < 1, ['a']] >>> df_0a a 0 1 Squeezing the rows produces a single scalar Series: >>> df_0a.squeeze('rows') a 1 Name: 0, dtype: int64 Squeezing all axes will project directly into a scalar: >>> df_0a.squeeze() 1 """ axis = range(self._AXIS_LEN) if axis is None else (self._get_axis_number(axis),) return self.iloc[ tuple( 0 if i in axis and len(a) == 1 else slice(None) for i, a in enumerate(self.axes) ) ] # ---------------------------------------------------------------------- # Rename def rename( self: FrameOrSeries, mapper: Optional[Renamer] = None, *, index: Optional[Renamer] = None, columns: Optional[Renamer] = None, axis: Optional[Axis] = None, copy: bool = True, inplace: bool = False, level: Optional[Level] = None, errors: str = "ignore", ) -> Optional[FrameOrSeries]: """ Alter axes input function or functions. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don't throw an error. Alternatively, change ``Series.name`` with a scalar value (Series only). Parameters ---------- %(axes)s : scalar, list-like, dict-like or function, optional Scalar or list-like will alter the ``Series.name`` attribute, and raise on DataFrame. dict-like or functions are transformations to apply to that axis' values copy : bool, default True Also copy underlying data. inplace : bool, default False Whether to return a new %(klass)s. If True then value of copy is ignored. level : int or level name, default None In case of a MultiIndex, only rename labels in the specified level. errors : {'ignore', 'raise'}, default 'ignore' If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`, or `columns` contains labels that are not present in the Index being transformed. If 'ignore', existing keys will be renamed and extra keys will be ignored. Returns ------- renamed : %(klass)s (new object) Raises ------ KeyError If any of the labels is not found in the selected axis and "errors='raise'". See Also -------- NDFrame.rename_axis Examples -------- >>> s = pd.Series([1, 2, 3]) >>> s 0 1 1 2 2 3 dtype: int64 >>> s.rename("my_name") # scalar, changes Series.name 0 1 1 2 2 3 Name: my_name, dtype: int64 >>> s.rename(lambda x: x ** 2) # function, changes labels 0 1 1 2 4 3 dtype: int64 >>> s.rename({1: 3, 2: 5}) # mapping, changes labels 0 1 3 2 5 3 dtype: int64 Since ``DataFrame`` doesn't have a ``.name`` attribute, only mapping-type arguments are allowed. >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) >>> df.rename(2) Traceback (most recent call last): ... TypeError: 'int' object is not callable ``DataFrame.rename`` supports two calling conventions * ``(index=index_mapper, columns=columns_mapper, ...)`` * ``(mapper, axis={'index', 'columns'}, ...)`` We *highly* recommend using keyword arguments to clarify your intent. >>> df.rename(index=str, columns={"A": "a", "B": "c"}) a c 0 1 4 1 2 5 2 3 6 >>> df.rename(index=str, columns={"A": "a", "C": "c"}) a B 0 1 4 1 2 5 2 3 6 Using axis-style parameters >>> df.rename(str.lower, axis='columns') a b 0 1 4 1 2 5 2 3 6 >>> df.rename({1: 2, 2: 4}, axis='index') A B 0 1 4 2 2 5 4 3 6 See the :ref:`user guide <basics.rename>` for more. """ if mapper is None and index is None and columns is None: raise TypeError("must pass an index to rename") if index is not None or columns is not None: if axis is not None: raise TypeError( "Cannot specify both 'axis' and any of 'index' or 'columns'" ) elif mapper is not None: raise TypeError( "Cannot specify both 'mapper' and any of 'index' or 'columns'" ) else: # use the mapper argument if axis and self._get_axis_number(axis) == 1: columns = mapper else: index = mapper result = self if inplace else self.copy(deep=copy) for axis_no, replacements in enumerate((index, columns)): if replacements is None: continue ax = self._get_axis(axis_no) f = com.get_rename_function(replacements) if level is not None: level = ax._get_level_number(level) # GH 13473 if not callable(replacements): indexer = ax.get_indexer_for(replacements) if errors == "raise" and len(indexer[indexer == -1]): missing_labels = [ label for index, label in enumerate(replacements) if indexer[index] == -1 ] raise KeyError(f"{missing_labels} not found in axis") new_index = ax._transform_index(f, level) result.set_axis(new_index, axis=axis_no, inplace=True) result._clear_item_cache() if inplace: self._update_inplace(result) return None else: return result.__finalize__(self, method="rename") @rewrite_axis_style_signature("mapper", [("copy", True), ("inplace", False)]) def rename_axis(self, mapper=lib.no_default, **kwargs): """ Set the name of the axis for the index or columns. Parameters ---------- mapper : scalar, list-like, optional Value to set the axis name attribute. index, columns : scalar, list-like, dict-like or function, optional A scalar, list-like, dict-like or functions transformations to apply to that axis' values. Note that the ``columns`` parameter is not allowed if the object is a Series. This parameter only apply for DataFrame type objects. Use either ``mapper`` and ``axis`` to specify the axis to target with ``mapper``, or ``index`` and/or ``columns``. .. versionchanged:: 0.24.0 axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to rename. copy : bool, default True Also copy underlying data. inplace : bool, default False Modifies the object directly, instead of creating a new Series or DataFrame. Returns ------- Series, DataFrame, or None The same type as the caller or None if `inplace` is True. See Also -------- Series.rename : Alter Series index labels or name. DataFrame.rename : Alter DataFrame index labels or name. Index.rename : Set new names on index. Notes ----- ``DataFrame.rename_axis`` supports two calling conventions * ``(index=index_mapper, columns=columns_mapper, ...)`` * ``(mapper, axis={'index', 'columns'}, ...)`` The first calling convention will only modify the names of the index and/or the names of the Index object that is the columns. In this case, the parameter ``copy`` is ignored. The second calling convention will modify the names of the the corresponding index if mapper is a list or a scalar. However, if mapper is dict-like or a function, it will use the deprecated behavior of modifying the axis *labels*. We *highly* recommend using keyword arguments to clarify your intent. Examples -------- **Series** >>> s = pd.Series(["dog", "cat", "monkey"]) >>> s 0 dog 1 cat 2 monkey dtype: object >>> s.rename_axis("animal") animal 0 dog 1 cat 2 monkey dtype: object **DataFrame** >>> df = pd.DataFrame({"num_legs": [4, 4, 2], ... "num_arms": [0, 0, 2]}, ... ["dog", "cat", "monkey"]) >>> df num_legs num_arms dog 4 0 cat 4 0 monkey 2 2 >>> df = df.rename_axis("animal") >>> df num_legs num_arms animal dog 4 0 cat 4 0 monkey 2 2 >>> df = df.rename_axis("limbs", axis="columns") >>> df limbs num_legs num_arms animal dog 4 0 cat 4 0 monkey 2 2 **MultiIndex** >>> df.index = pd.MultiIndex.from_product([['mammal'], ... ['dog', 'cat', 'monkey']], ... names=['type', 'name']) >>> df limbs num_legs num_arms type name mammal dog 4 0 cat 4 0 monkey 2 2 >>> df.rename_axis(index={'type': 'class'}) limbs num_legs num_arms class name mammal dog 4 0 cat 4 0 monkey 2 2 >>> df.rename_axis(columns=str.upper) LIMBS num_legs num_arms type name mammal dog 4 0 cat 4 0 monkey 2 2 """ axes, kwargs = self._construct_axes_from_arguments( (), kwargs, sentinel=lib.no_default ) copy = kwargs.pop("copy", True) inplace = kwargs.pop("inplace", False) axis = kwargs.pop("axis", 0) if axis is not None: axis = self._get_axis_number(axis) if kwargs: raise TypeError( "rename_axis() got an unexpected keyword " f'argument "{list(kwargs.keys())[0]}"' ) inplace = validate_bool_kwarg(inplace, "inplace") if mapper is not lib.no_default: # Use v0.23 behavior if a scalar or list non_mapper = is_scalar(mapper) or ( is_list_like(mapper) and not is_dict_like(mapper) ) if non_mapper: return self._set_axis_name(mapper, axis=axis, inplace=inplace) else: raise ValueError("Use `.rename` to alter labels with a mapper.") else: # Use new behavior. Means that index and/or columns # is specified result = self if inplace else self.copy(deep=copy) for axis in range(self._AXIS_LEN): v = axes.get(self._get_axis_name(axis)) if v is lib.no_default: continue non_mapper = is_scalar(v) or (is_list_like(v) and not is_dict_like(v)) if non_mapper: newnames = v else: f = com.get_rename_function(v) curnames = self._get_axis(axis).names newnames = [f(name) for name in curnames] result._set_axis_name(newnames, axis=axis, inplace=True) if not inplace: return result def _set_axis_name(self, name, axis=0, inplace=False): """ Set the name(s) of the axis. Parameters ---------- name : str or list of str Name(s) to set. axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to set the label. The value 0 or 'index' specifies index, and the value 1 or 'columns' specifies columns. inplace : bool, default False If `True`, do operation inplace and return None. Returns ------- Series, DataFrame, or None The same type as the caller or `None` if `inplace` is `True`. See Also -------- DataFrame.rename : Alter the axis labels of :class:`DataFrame`. Series.rename : Alter the index labels or set the index name of :class:`Series`. Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`. Examples -------- >>> df = pd.DataFrame({"num_legs": [4, 4, 2]}, ... ["dog", "cat", "monkey"]) >>> df num_legs dog 4 cat 4 monkey 2 >>> df._set_axis_name("animal") num_legs animal dog 4 cat 4 monkey 2 >>> df.index = pd.MultiIndex.from_product( ... [["mammal"], ['dog', 'cat', 'monkey']]) >>> df._set_axis_name(["type", "name"]) num_legs type name mammal dog 4 cat 4 monkey 2 """ axis = self._get_axis_number(axis) idx = self._get_axis(axis).set_names(name) inplace = validate_bool_kwarg(inplace, "inplace") renamed = self if inplace else self.copy() renamed.set_axis(idx, axis=axis, inplace=True) if not inplace: return renamed # ---------------------------------------------------------------------- # Comparison Methods def _indexed_same(self, other) -> bool: return all( self._get_axis(a).equals(other._get_axis(a)) for a in self._AXIS_ORDERS ) def equals(self, other): """ Test whether two objects contain the same elements. This function allows two Series or DataFrames to be compared against each other to see if they have the same shape and elements. NaNs in the same location are considered equal. The column headers do not need to have the same type, but the elements within the columns must be the same dtype. Parameters ---------- other : Series or DataFrame The other Series or DataFrame to be compared with the first. Returns ------- bool True if all elements are the same in both objects, False otherwise. See Also -------- Series.eq : Compare two Series objects of the same length and return a Series where each element is True if the element in each Series is equal, False otherwise. DataFrame.eq : Compare two DataFrame objects of the same shape and return a DataFrame where each element is True if the respective element in each DataFrame is equal, False otherwise. testing.assert_series_equal : Raises an AssertionError if left and right are not equal. Provides an easy interface to ignore inequality in dtypes, indexes and precision among others. testing.assert_frame_equal : Like assert_series_equal, but targets DataFrames. numpy.array_equal : Return True if two arrays have the same shape and elements, False otherwise. Notes ----- This function requires that the elements have the same dtype as their respective elements in the other Series or DataFrame. However, the column labels do not need to have the same type, as long as they are still considered equal. Examples -------- >>> df = pd.DataFrame({1: [10], 2: [20]}) >>> df 1 2 0 10 20 DataFrames df and exactly_equal have the same types and values for their elements and column labels, which will return True. >>> exactly_equal = pd.DataFrame({1: [10], 2: [20]}) >>> exactly_equal 1 2 0 10 20 >>> df.equals(exactly_equal) True DataFrames df and different_column_type have the same element types and values, but have different types for the column labels, which will still return True. >>> different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]}) >>> different_column_type 1.0 2.0 0 10 20 >>> df.equals(different_column_type) True DataFrames df and different_data_type have different types for the same values for their elements, and will return False even though their column labels are the same values and types. >>> different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]}) >>> different_data_type 1 2 0 10.0 20.0 >>> df.equals(different_data_type) False """ if not isinstance(other, self._constructor): return False return self._mgr.equals(other._mgr) # ------------------------------------------------------------------------- # Unary Methods def __neg__(self): values = self._values if is_bool_dtype(values): arr = operator.inv(values) elif ( is_numeric_dtype(values) or is_timedelta64_dtype(values) or is_object_dtype(values) ): arr = operator.neg(values) else: raise TypeError(f"Unary negative expects numeric dtype, not {values.dtype}") return self.__array_wrap__(arr) def __pos__(self): values = self._values if is_bool_dtype(values): arr = values elif ( is_numeric_dtype(values) or is_timedelta64_dtype(values) or is_object_dtype(values) ): arr = operator.pos(values) else: raise TypeError(f"Unary plus expects numeric dtype, not {values.dtype}") return self.__array_wrap__(arr) def __invert__(self): if not self.size: # inv fails with 0 len return self new_data = self._mgr.apply(operator.invert) result = self._constructor(new_data).__finalize__(self, method="__invert__") return result def __nonzero__(self): raise ValueError( f"The truth value of a {type(self).__name__} is ambiguous. " "Use a.empty, a.bool(), a.item(), a.any() or a.all()." ) __bool__ = __nonzero__ def bool(self): """ Return the bool of a single element PandasObject. This must be a boolean scalar value, either True or False. Raise a ValueError if the PandasObject does not have exactly 1 element, or that element is not boolean Returns ------- bool Same single boolean value converted to bool type. """ v = self.squeeze() if isinstance(v, (bool, np.bool_)): return bool(v) elif is_scalar(v): raise ValueError( "bool cannot act on a non-boolean single element " f"{type(self).__name__}" ) self.__nonzero__() def __abs__(self: FrameOrSeries) -> FrameOrSeries: return self.abs() def __round__(self: FrameOrSeries, decimals: int = 0) -> FrameOrSeries: return self.round(decimals) # ------------------------------------------------------------------------- # Label or Level Combination Helpers # # A collection of helper methods for DataFrame/Series operations that # accept a combination of column/index labels and levels. All such # operations should utilize/extend these methods when possible so that we # have consistent precedence and validation logic throughout the library. def _is_level_reference(self, key, axis=0): """ Test whether a key is a level reference for a given axis. To be considered a level reference, `key` must be a string that: - (axis=0): Matches the name of an index level and does NOT match a column label. - (axis=1): Matches the name of a column level and does NOT match an index label. Parameters ---------- key : str Potential level name for the given axis axis : int, default 0 Axis that levels are associated with (0 for index, 1 for columns) Returns ------- is_level : bool """ axis = self._get_axis_number(axis) return ( key is not None and is_hashable(key) and key in self.axes[axis].names and not self._is_label_reference(key, axis=axis) ) def _is_label_reference(self, key, axis=0) -> bool_t: """ Test whether a key is a label reference for a given axis. To be considered a label reference, `key` must be a string that: - (axis=0): Matches a column label - (axis=1): Matches an index label Parameters ---------- key: str Potential label name axis: int, default 0 Axis perpendicular to the axis that labels are associated with (0 means search for column labels, 1 means search for index labels) Returns ------- is_label: bool """ axis = self._get_axis_number(axis) other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis) return ( key is not None and is_hashable(key) and any(key in self.axes[ax] for ax in other_axes) ) def _is_label_or_level_reference(self, key: str, axis: int = 0) -> bool_t: """ Test whether a key is a label or level reference for a given axis. To be considered either a label or a level reference, `key` must be a string that: - (axis=0): Matches a column label or an index level - (axis=1): Matches an index label or a column level Parameters ---------- key: str Potential label or level name axis: int, default 0 Axis that levels are associated with (0 for index, 1 for columns) Returns ------- is_label_or_level: bool """ return self._is_level_reference(key, axis=axis) or self._is_label_reference( key, axis=axis ) def _check_label_or_level_ambiguity(self, key, axis: int = 0) -> None: """ Check whether `key` is ambiguous. By ambiguous, we mean that it matches both a level of the input `axis` and a label of the other axis. Parameters ---------- key: str or object Label or level name. axis: int, default 0 Axis that levels are associated with (0 for index, 1 for columns). Raises ------ ValueError: `key` is ambiguous """ axis = self._get_axis_number(axis) other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis) if ( key is not None and is_hashable(key) and key in self.axes[axis].names and any(key in self.axes[ax] for ax in other_axes) ): # Build an informative and grammatical warning level_article, level_type = ( ("an", "index") if axis == 0 else ("a", "column") ) label_article, label_type = ( ("a", "column") if axis == 0 else ("an", "index") ) msg = ( f"'{key}' is both {level_article} {level_type} level and " f"{label_article} {label_type} label, which is ambiguous." ) raise ValueError(msg) def _get_label_or_level_values(self, key: str, axis: int = 0) -> np.ndarray: """ Return a 1-D array of values associated with `key`, a label or level from the given `axis`. Retrieval logic: - (axis=0): Return column values if `key` matches a column label. Otherwise return index level values if `key` matches an index level. - (axis=1): Return row values if `key` matches an index label. Otherwise return column level values if 'key' matches a column level Parameters ---------- key: str Label or level name. axis: int, default 0 Axis that levels are associated with (0 for index, 1 for columns) Returns ------- values: np.ndarray Raises ------ KeyError if `key` matches neither a label nor a level ValueError if `key` matches multiple labels FutureWarning if `key` is ambiguous. This will become an ambiguity error in a future version """ axis = self._get_axis_number(axis) other_axes = [ax for ax in range(self._AXIS_LEN) if ax != axis] if self._is_label_reference(key, axis=axis): self._check_label_or_level_ambiguity(key, axis=axis) values = self.xs(key, axis=other_axes[0])._values elif self._is_level_reference(key, axis=axis): values = self.axes[axis].get_level_values(key)._values else: raise KeyError(key) # Check for duplicates if values.ndim > 1: if other_axes and isinstance(self._get_axis(other_axes[0]), MultiIndex): multi_message = ( "\n" "For a multi-index, the label must be a " "tuple with elements corresponding to each level." ) else: multi_message = "" label_axis_name = "column" if axis == 0 else "index" raise ValueError( ( f"The {label_axis_name} label '{key}' " f"is not unique.{multi_message}" ) ) return values def _drop_labels_or_levels(self, keys, axis: int = 0): """ Drop labels and/or levels for the given `axis`. For each key in `keys`: - (axis=0): If key matches a column label then drop the column. Otherwise if key matches an index level then drop the level. - (axis=1): If key matches an index label then drop the row. Otherwise if key matches a column level then drop the level. Parameters ---------- keys: str or list of str labels or levels to drop axis: int, default 0 Axis that levels are associated with (0 for index, 1 for columns) Returns ------- dropped: DataFrame Raises ------ ValueError if any `keys` match neither a label nor a level """ axis = self._get_axis_number(axis) # Validate keys keys = com.maybe_make_list(keys) invalid_keys = [ k for k in keys if not self._is_label_or_level_reference(k, axis=axis) ] if invalid_keys: raise ValueError( ( "The following keys are not valid labels or " f"levels for axis {axis}: {invalid_keys}" ) ) # Compute levels and labels to drop levels_to_drop = [k for k in keys if self._is_level_reference(k, axis=axis)] labels_to_drop = [k for k in keys if not self._is_level_reference(k, axis=axis)] # Perform copy upfront and then use inplace operations below. # This ensures that we always perform exactly one copy. # ``copy`` and/or ``inplace`` options could be added in the future. dropped = self.copy() if axis == 0: # Handle dropping index levels if levels_to_drop: dropped.reset_index(levels_to_drop, drop=True, inplace=True) # Handle dropping columns labels if labels_to_drop: dropped.drop(labels_to_drop, axis=1, inplace=True) else: # Handle dropping column levels if levels_to_drop: if isinstance(dropped.columns, MultiIndex): # Drop the specified levels from the MultiIndex dropped.columns = dropped.columns.droplevel(levels_to_drop) else: # Drop the last level of Index by replacing with # a RangeIndex dropped.columns = RangeIndex(dropped.columns.size) # Handle dropping index labels if labels_to_drop: dropped.drop(labels_to_drop, axis=0, inplace=True) return dropped # ---------------------------------------------------------------------- # Iteration def __hash__(self): raise TypeError( f"{repr(type(self).__name__)} objects are mutable, " f"thus they cannot be hashed" ) def __iter__(self): """ Iterate over info axis. Returns ------- iterator Info axis as iterator. """ return iter(self._info_axis) # can we get a better explanation of this? def keys(self): """ Get the 'info axis' (see Indexing for more). This is index for Series, columns for DataFrame. Returns ------- Index Info axis. """ return self._info_axis def items(self): """ Iterate over (label, values) on info axis This is index for Series and columns for DataFrame. Returns ------- Generator """ for h in self._info_axis: yield h, self[h] @doc(items) def iteritems(self): return self.items() def __len__(self) -> int: """Returns length of info axis""" return len(self._info_axis) def __contains__(self, key) -> bool_t: """True if the key is in the info axis""" return key in self._info_axis @property def empty(self) -> bool_t: """ Indicator whether DataFrame is empty. True if DataFrame is entirely empty (no items), meaning any of the axes are of length 0. Returns ------- bool If DataFrame is empty, return True, if not return False. See Also -------- Series.dropna : Return series without null values. DataFrame.dropna : Return DataFrame with labels on given axis omitted where (all or any) data are missing. Notes ----- If DataFrame contains only NaNs, it is still not considered empty. See the example below. Examples -------- An example of an actual empty DataFrame. Notice the index is empty: >>> df_empty = pd.DataFrame({'A' : []}) >>> df_empty Empty DataFrame Columns: [A] Index: [] >>> df_empty.empty True If we only have NaNs in our DataFrame, it is not considered empty! We will need to drop the NaNs to make the DataFrame empty: >>> df = pd.DataFrame({'A' : [np.nan]}) >>> df A 0 NaN >>> df.empty False >>> df.dropna().empty True """ return any(len(self._get_axis(a)) == 0 for a in self._AXIS_ORDERS) # ---------------------------------------------------------------------- # Array Interface # This is also set in IndexOpsMixin # GH#23114 Ensure ndarray.__op__(DataFrame) returns NotImplemented __array_priority__ = 1000 def __array__(self, dtype=None) -> np.ndarray: return np.asarray(self._values, dtype=dtype) def __array_wrap__(self, result, context=None): result = lib.item_from_zerodim(result) if is_scalar(result): # e.g. we get here with np.ptp(series) # ptp also requires the item_from_zerodim return result d = self._construct_axes_dict(self._AXIS_ORDERS, copy=False) return self._constructor(result, **d).__finalize__( self, method="__array_wrap__" ) # ideally we would define this to avoid the getattr checks, but # is slower # @property # def __array_interface__(self): # """ provide numpy array interface method """ # values = self.values # return dict(typestr=values.dtype.str,shape=values.shape,data=values) # ---------------------------------------------------------------------- # Picklability def __getstate__(self) -> Dict[str, Any]: meta = {k: getattr(self, k, None) for k in self._metadata} return dict( _mgr=self._mgr, _typ=self._typ, _metadata=self._metadata, attrs=self.attrs, **meta, ) def __setstate__(self, state): if isinstance(state, BlockManager): self._mgr = state elif isinstance(state, dict): if "_data" in state and "_mgr" not in state: # compat for older pickles state["_mgr"] = state.pop("_data") typ = state.get("_typ") if typ is not None: attrs = state.get("_attrs", {}) object.__setattr__(self, "_attrs", attrs) # set in the order of internal names # to avoid definitional recursion # e.g. say fill_value needing _mgr to be # defined meta = set(self._internal_names + self._metadata) for k in list(meta): if k in state: v = state[k] object.__setattr__(self, k, v) for k, v in state.items(): if k not in meta: object.__setattr__(self, k, v) else: raise NotImplementedError("Pre-0.12 pickles are no longer supported") elif len(state) == 2: raise NotImplementedError("Pre-0.12 pickles are no longer supported") self._item_cache = {} # ---------------------------------------------------------------------- # Rendering Methods def __repr__(self) -> str: # string representation based upon iterating over self # (since, by definition, `PandasContainers` are iterable) prepr = f"[{','.join(map(pprint_thing, self))}]" return f"{type(self).__name__}({prepr})" def _repr_latex_(self): """ Returns a LaTeX representation for a particular object. Mainly for use with nbconvert (jupyter notebook conversion to pdf). """ if config.get_option("display.latex.repr"): return self.to_latex() else: return None def _repr_data_resource_(self): """ Not a real Jupyter special repr method, but we use the same naming convention. """ if config.get_option("display.html.table_schema"): data = self.head(config.get_option("display.max_rows")) payload = json.loads( data.to_json(orient="table"), object_pairs_hook=collections.OrderedDict ) return payload # ---------------------------------------------------------------------- # I/O Methods _shared_docs[ "to_markdown" ] = """ Print %(klass)s in Markdown-friendly format. .. versionadded:: 1.0.0 Parameters ---------- buf : str, Path or StringIO-like, optional, default None Buffer to write to. If None, the output is returned as a string. mode : str, optional Mode in which file is opened. **kwargs These parameters will be passed to `tabulate`. Returns ------- str %(klass)s in Markdown-friendly format. """ @doc(klass="object") def to_excel( self, excel_writer, sheet_name="Sheet1", na_rep="", float_format=None, columns=None, header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None, merge_cells=True, encoding=None, inf_rep="inf", verbose=True, freeze_panes=None, ) -> None: """ Write {klass} to an Excel sheet. To write a single {klass} to an Excel .xlsx file it is only necessary to specify a target file name. To write to multiple sheets it is necessary to create an `ExcelWriter` object with a target file name, and specify a sheet in the file to write to. Multiple sheets may be written to by specifying unique `sheet_name`. With all data written to the file it is necessary to save the changes. Note that creating an `ExcelWriter` object with a file name that already exists will result in the contents of the existing file being erased. Parameters ---------- excel_writer : str or ExcelWriter object File path or existing ExcelWriter. sheet_name : str, default 'Sheet1' Name of sheet which will contain DataFrame. na_rep : str, default '' Missing data representation. float_format : str, optional Format string for floating point numbers. For example ``float_format="%.2f"`` will format 0.1234 to 0.12. columns : sequence or list of str, optional Columns to write. header : bool or list of str, default True Write out the column names. If a list of string is given it is assumed to be aliases for the column names. index : bool, default True Write row names (index). index_label : str or sequence, optional Column label for index column(s) if desired. If not specified, and `header` and `index` are True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. startrow : int, default 0 Upper left cell row to dump data frame. startcol : int, default 0 Upper left cell column to dump data frame. engine : str, optional Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and ``io.excel.xlsm.writer``. merge_cells : bool, default True Write MultiIndex and Hierarchical Rows as merged cells. encoding : str, optional Encoding of the resulting excel file. Only necessary for xlwt, other writers support unicode natively. inf_rep : str, default 'inf' Representation for infinity (there is no native representation for infinity in Excel). verbose : bool, default True Display more information in the error logs. freeze_panes : tuple of int (length 2), optional Specifies the one-based bottommost row and rightmost column that is to be frozen. See Also -------- to_csv : Write DataFrame to a comma-separated values (csv) file. ExcelWriter : Class for writing DataFrame objects into excel sheets. read_excel : Read an Excel file into a pandas DataFrame. read_csv : Read a comma-separated values (csv) file into DataFrame. Notes ----- For compatibility with :meth:`~DataFrame.to_csv`, to_excel serializes lists and dicts to strings before writing. Once a workbook has been saved it is not possible write further data without rewriting the whole workbook. Examples -------- Create, write to and save a workbook: >>> df1 = pd.DataFrame([['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']) >>> df1.to_excel("output.xlsx") # doctest: +SKIP To specify the sheet name: >>> df1.to_excel("output.xlsx", ... sheet_name='Sheet_name_1') # doctest: +SKIP If you wish to write to more than one sheet in the workbook, it is necessary to specify an ExcelWriter object: >>> df2 = df1.copy() >>> with pd.ExcelWriter('output.xlsx') as writer: # doctest: +SKIP ... df1.to_excel(writer, sheet_name='Sheet_name_1') ... df2.to_excel(writer, sheet_name='Sheet_name_2') ExcelWriter can also be used to append to an existing Excel file: >>> with pd.ExcelWriter('output.xlsx', ... mode='a') as writer: # doctest: +SKIP ... df.to_excel(writer, sheet_name='Sheet_name_3') To set the library that is used to write the Excel file, you can pass the `engine` keyword (the default engine is automatically chosen depending on the file extension): >>> df1.to_excel('output1.xlsx', engine='xlsxwriter') # doctest: +SKIP """ df = self if isinstance(self, ABCDataFrame) else self.to_frame() from pandas.io.formats.excel import ExcelFormatter formatter = ExcelFormatter( df, na_rep=na_rep, cols=columns, header=header, float_format=float_format, index=index, index_label=index_label, merge_cells=merge_cells, inf_rep=inf_rep, ) formatter.write( excel_writer, sheet_name=sheet_name, startrow=startrow, startcol=startcol, freeze_panes=freeze_panes, engine=engine, ) def to_json( self, path_or_buf: Optional[FilePathOrBuffer] = None, orient: Optional[str] = None, date_format: Optional[str] = None, double_precision: int = 10, force_ascii: bool_t = True, date_unit: str = "ms", default_handler: Optional[Callable[[Any], JSONSerializable]] = None, lines: bool_t = False, compression: Optional[str] = "infer", index: bool_t = True, indent: Optional[int] = None, ) -> Optional[str]: """ Convert the object to a JSON string. Note NaN's and None will be converted to null and datetime objects will be converted to UNIX timestamps. Parameters ---------- path_or_buf : str or file handle, optional File path or object. If not specified, the result is returned as a string. orient : str Indication of expected JSON string format. * Series: - default is 'index' - allowed values are: {'split','records','index','table'}. * DataFrame: - default is 'columns' - allowed values are: {'split', 'records', 'index', 'columns', 'values', 'table'}. * The format of the JSON string: - 'split' : dict like {'index' -> [index], 'columns' -> [columns], 'data' -> [values]} - 'records' : list like [{column -> value}, ... , {column -> value}] - 'index' : dict like {index -> {column -> value}} - 'columns' : dict like {column -> {index -> value}} - 'values' : just the values array - 'table' : dict like {'schema': {schema}, 'data': {data}} Describing the data, where data component is like ``orient='records'``. .. versionchanged:: 0.20.0 date_format : {None, 'epoch', 'iso'} Type of date conversion. 'epoch' = epoch milliseconds, 'iso' = ISO8601. The default depends on the `orient`. For ``orient='table'``, the default is 'iso'. For all other orients, the default is 'epoch'. double_precision : int, default 10 The number of decimal places to use when encoding floating point values. force_ascii : bool, default True Force encoded string to be ASCII. date_unit : str, default 'ms' (milliseconds) The time unit to encode to, governs timestamp and ISO8601 precision. One of 's', 'ms', 'us', 'ns' for second, millisecond, microsecond, and nanosecond respectively. default_handler : callable, default None Handler to call if object cannot otherwise be converted to a suitable format for JSON. Should receive a single argument which is the object to convert and return a serialisable object. lines : bool, default False If 'orient' is 'records' write out line delimited json format. Will throw ValueError if incorrect 'orient' since others are not list like. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None} A string representing the compression to use in the output file, only used when the first argument is a filename. By default, the compression is inferred from the filename. .. versionchanged:: 0.24.0 'infer' option added and set to default index : bool, default True Whether to include the index values in the JSON string. Not including the index (``index=False``) is only supported when orient is 'split' or 'table'. .. versionadded:: 0.23.0 indent : int, optional Length of whitespace used to indent each record. .. versionadded:: 1.0.0 Returns ------- None or str If path_or_buf is None, returns the resulting json format as a string. Otherwise returns None. See Also -------- read_json : Convert a JSON string to pandas object. Notes ----- The behavior of ``indent=0`` varies from the stdlib, which does not indent the output but does insert newlines. Currently, ``indent=0`` and the default ``indent=None`` are equivalent in pandas, though this may change in a future release. Examples -------- >>> import json >>> df = pd.DataFrame( ... [["a", "b"], ["c", "d"]], ... index=["row 1", "row 2"], ... columns=["col 1", "col 2"], ... ) >>> result = df.to_json(orient="split") >>> parsed = json.loads(result) >>> json.dumps(parsed, indent=4) # doctest: +SKIP { "columns": [ "col 1", "col 2" ], "index": [ "row 1", "row 2" ], "data": [ [ "a", "b" ], [ "c", "d" ] ] } Encoding/decoding a Dataframe using ``'records'`` formatted JSON. Note that index labels are not preserved with this encoding. >>> result = df.to_json(orient="records") >>> parsed = json.loads(result) >>> json.dumps(parsed, indent=4) # doctest: +SKIP [ { "col 1": "a", "col 2": "b" }, { "col 1": "c", "col 2": "d" } ] Encoding/decoding a Dataframe using ``'index'`` formatted JSON: >>> result = df.to_json(orient="index") >>> parsed = json.loads(result) >>> json.dumps(parsed, indent=4) # doctest: +SKIP { "row 1": { "col 1": "a", "col 2": "b" }, "row 2": { "col 1": "c", "col 2": "d" } } Encoding/decoding a Dataframe using ``'columns'`` formatted JSON: >>> result = df.to_json(orient="columns") >>> parsed = json.loads(result) >>> json.dumps(parsed, indent=4) # doctest: +SKIP { "col 1": { "row 1": "a", "row 2": "c" }, "col 2": { "row 1": "b", "row 2": "d" } } Encoding/decoding a Dataframe using ``'values'`` formatted JSON: >>> result = df.to_json(orient="values") >>> parsed = json.loads(result) >>> json.dumps(parsed, indent=4) # doctest: +SKIP [ [ "a", "b" ], [ "c", "d" ] ] Encoding with Table Schema: >>> result = df.to_json(orient="table") >>> parsed = json.loads(result) >>> json.dumps(parsed, indent=4) # doctest: +SKIP { "schema": { "fields": [ { "name": "index", "type": "string" }, { "name": "col 1", "type": "string" }, { "name": "col 2", "type": "string" } ], "primaryKey": [ "index" ], "pandas_version": "0.20.0" }, "data": [ { "index": "row 1", "col 1": "a", "col 2": "b" }, { "index": "row 2", "col 1": "c", "col 2": "d" } ] } """ from pandas.io import json if date_format is None and orient == "table": date_format = "iso" elif date_format is None: date_format = "epoch" config.is_nonnegative_int(indent) indent = indent or 0 return json.to_json( path_or_buf=path_or_buf, obj=self, orient=orient, date_format=date_format, double_precision=double_precision, force_ascii=force_ascii, date_unit=date_unit, default_handler=default_handler, lines=lines, compression=compression, index=index, indent=indent, ) def to_hdf( self, path_or_buf, key: str, mode: str = "a", complevel: Optional[int] = None, complib: Optional[str] = None, append: bool_t = False, format: Optional[str] = None, index: bool_t = True, min_itemsize: Optional[Union[int, Dict[str, int]]] = None, nan_rep=None, dropna: Optional[bool_t] = None, data_columns: Optional[Union[bool_t, List[str]]] = None, errors: str = "strict", encoding: str = "UTF-8", ) -> None: """ Write the contained data to an HDF5 file using HDFStore. Hierarchical Data Format (HDF) is self-describing, allowing an application to interpret the structure and contents of a file with no outside information. One HDF file can hold a mix of related objects which can be accessed as a group or as individual objects. In order to add another DataFrame or Series to an existing HDF file please use append mode and a different a key. For more information see the :ref:`user guide <io.hdf5>`. Parameters ---------- path_or_buf : str or pandas.HDFStore File path or HDFStore object. key : str Identifier for the group in the store. mode : {'a', 'w', 'r+'}, default 'a' Mode to open file: - 'w': write, a new file is created (an existing file with the same name would be deleted). - 'a': append, an existing file is opened for reading and writing, and if the file does not exist it is created. - 'r+': similar to 'a', but the file must already exist. complevel : {0-9}, optional Specifies a compression level for data. A value of 0 disables compression. complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib' Specifies the compression library to be used. As of v0.20.2 these additional compressors for Blosc are supported (default if no compressor specified: 'blosc:blosclz'): {'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy', 'blosc:zlib', 'blosc:zstd'}. Specifying a compression library which is not available issues a ValueError. append : bool, default False For Table formats, append the input data to the existing. format : {'fixed', 'table', None}, default 'fixed' Possible values: - 'fixed': Fixed format. Fast writing/reading. Not-appendable, nor searchable. - 'table': Table format. Write as a PyTables Table structure which may perform worse but allow more flexible operations like searching / selecting subsets of the data. - If None, pd.get_option('io.hdf.default_format') is checked, followed by fallback to "fixed" errors : str, default 'strict' Specifies how encoding and decoding errors are to be handled. See the errors argument for :func:`open` for a full list of options. encoding : str, default "UTF-8" min_itemsize : dict or int, optional Map column names to minimum string sizes for columns. nan_rep : Any, optional How to represent null values as str. Not allowed with append=True. data_columns : list of columns or True, optional List of columns to create as indexed data columns for on-disk queries, or True to use all columns. By default only the axes of the object are indexed. See :ref:`io.hdf5-query-data-columns`. Applicable only to format='table'. See Also -------- DataFrame.read_hdf : Read from HDF file. DataFrame.to_parquet : Write a DataFrame to the binary parquet format. DataFrame.to_sql : Write to a sql table. DataFrame.to_feather : Write out feather-format for DataFrames. DataFrame.to_csv : Write out to a csv file. Examples -------- >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, ... index=['a', 'b', 'c']) >>> df.to_hdf('data.h5', key='df', mode='w') We can add another object to the same file: >>> s = pd.Series([1, 2, 3, 4]) >>> s.to_hdf('data.h5', key='s') Reading from HDF file: >>> pd.read_hdf('data.h5', 'df') A B a 1 4 b 2 5 c 3 6 >>> pd.read_hdf('data.h5', 's') 0 1 1 2 2 3 3 4 dtype: int64 Deleting file with data: >>> import os >>> os.remove('data.h5') """ from pandas.io import pytables pytables.to_hdf( path_or_buf, key, self, mode=mode, complevel=complevel, complib=complib, append=append, format=format, index=index, min_itemsize=min_itemsize, nan_rep=nan_rep, dropna=dropna, data_columns=data_columns, errors=errors, encoding=encoding, ) def to_sql( self, name: str, con, schema=None, if_exists: str = "fail", index: bool_t = True, index_label=None, chunksize=None, dtype=None, method=None, ) -> None: """ Write records stored in a DataFrame to a SQL database. Databases supported by SQLAlchemy [1]_ are supported. Tables can be newly created, appended to, or overwritten. Parameters ---------- name : str Name of SQL table. con : sqlalchemy.engine.Engine or sqlite3.Connection Using SQLAlchemy makes it possible to use any DB supported by that library. Legacy support is provided for sqlite3.Connection objects. The user is responsible for engine disposal and connection closure for the SQLAlchemy connectable See `here \ <https://docs.sqlalchemy.org/en/13/core/connections.html>`_. schema : str, optional Specify the schema (if database flavor supports this). If None, use default schema. if_exists : {'fail', 'replace', 'append'}, default 'fail' How to behave if the table already exists. * fail: Raise a ValueError. * replace: Drop the table before inserting new values. * append: Insert new values to the existing table. index : bool, default True Write DataFrame index as a column. Uses `index_label` as the column name in the table. index_label : str or sequence, default None Column label for index column(s). If None is given (default) and `index` is True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. chunksize : int, optional Specify the number of rows in each batch to be written at a time. By default, all rows will be written at once. dtype : dict or scalar, optional Specifying the datatype for columns. If a dictionary is used, the keys should be the column names and the values should be the SQLAlchemy types or strings for the sqlite3 legacy mode. If a scalar is provided, it will be applied to all columns. method : {None, 'multi', callable}, optional Controls the SQL insertion clause used: * None : Uses standard SQL ``INSERT`` clause (one per row). * 'multi': Pass multiple values in a single ``INSERT`` clause. * callable with signature ``(pd_table, conn, keys, data_iter)``. Details and a sample callable implementation can be found in the section :ref:`insert method <io.sql.method>`. .. versionadded:: 0.24.0 Raises ------ ValueError When the table already exists and `if_exists` is 'fail' (the default). See Also -------- read_sql : Read a DataFrame from a table. Notes ----- Timezone aware datetime columns will be written as ``Timestamp with timezone`` type with SQLAlchemy if supported by the database. Otherwise, the datetimes will be stored as timezone unaware timestamps local to the original timezone. .. versionadded:: 0.24.0 References ---------- .. [1] https://docs.sqlalchemy.org .. [2] https://www.python.org/dev/peps/pep-0249/ Examples -------- Create an in-memory SQLite database. >>> from sqlalchemy import create_engine >>> engine = create_engine('sqlite://', echo=False) Create a table from scratch with 3 rows. >>> df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']}) >>> df name 0 User 1 1 User 2 2 User 3 >>> df.to_sql('users', con=engine) >>> engine.execute("SELECT * FROM users").fetchall() [(0, 'User 1'), (1, 'User 2'), (2, 'User 3')] >>> df1 = pd.DataFrame({'name' : ['User 4', 'User 5']}) >>> df1.to_sql('users', con=engine, if_exists='append') >>> engine.execute("SELECT * FROM users").fetchall() [(0, 'User 1'), (1, 'User 2'), (2, 'User 3'), (0, 'User 4'), (1, 'User 5')] Overwrite the table with just ``df1``. >>> df1.to_sql('users', con=engine, if_exists='replace', ... index_label='id') >>> engine.execute("SELECT * FROM users").fetchall() [(0, 'User 4'), (1, 'User 5')] Specify the dtype (especially useful for integers with missing values). Notice that while pandas is forced to store the data as floating point, the database supports nullable integers. When fetching the data with Python, we get back integer scalars. >>> df = pd.DataFrame({"A": [1, None, 2]}) >>> df A 0 1.0 1 NaN 2 2.0 >>> from sqlalchemy.types import Integer >>> df.to_sql('integers', con=engine, index=False, ... dtype={"A": Integer()}) >>> engine.execute("SELECT * FROM integers").fetchall() [(1,), (None,), (2,)] """ from pandas.io import sql sql.to_sql( self, name, con, schema=schema, if_exists=if_exists, index=index, index_label=index_label, chunksize=chunksize, dtype=dtype, method=method, ) def to_pickle( self, path, compression: Optional[str] = "infer", protocol: int = pickle.HIGHEST_PROTOCOL, ) -> None: """ Pickle (serialize) object to file. Parameters ---------- path : str File path where the pickled object will be stored. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, \ default 'infer' A string representing the compression to use in the output file. By default, infers from the file extension in specified path. protocol : int Int which indicates which protocol should be used by the pickler, default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible values are 0, 1, 2, 3, 4. A negative value for the protocol parameter is equivalent to setting its value to HIGHEST_PROTOCOL. .. [1] https://docs.python.org/3/library/pickle.html. See Also -------- read_pickle : Load pickled pandas object (or any object) from file. DataFrame.to_hdf : Write DataFrame to an HDF5 file. DataFrame.to_sql : Write DataFrame to a SQL database. DataFrame.to_parquet : Write a DataFrame to the binary parquet format. Examples -------- >>> original_df = pd.DataFrame({"foo": range(5), "bar": range(5, 10)}) >>> original_df foo bar 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9 >>> original_df.to_pickle("./dummy.pkl") >>> unpickled_df = pd.read_pickle("./dummy.pkl") >>> unpickled_df foo bar 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9 >>> import os >>> os.remove("./dummy.pkl") """ from pandas.io.pickle import to_pickle to_pickle(self, path, compression=compression, protocol=protocol) def to_clipboard( self, excel: bool_t = True, sep: Optional[str] = None, **kwargs ) -> None: r""" Copy object to the system clipboard. Write a text representation of object to the system clipboard. This can be pasted into Excel, for example. Parameters ---------- excel : bool, default True Produce output in a csv format for easy pasting into excel. - True, use the provided separator for csv pasting. - False, write a string representation of the object to the clipboard. sep : str, default ``'\t'`` Field delimiter. **kwargs These parameters will be passed to DataFrame.to_csv. See Also -------- DataFrame.to_csv : Write a DataFrame to a comma-separated values (csv) file. read_clipboard : Read text from clipboard and pass to read_table. Notes ----- Requirements for your platform. - Linux : `xclip`, or `xsel` (with `PyQt4` modules) - Windows : none - OS X : none Examples -------- Copy the contents of a DataFrame to the clipboard. >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C']) >>> df.to_clipboard(sep=',') # doctest: +SKIP ... # Wrote the following to the system clipboard: ... # ,A,B,C ... # 0,1,2,3 ... # 1,4,5,6 We can omit the index by passing the keyword `index` and setting it to false. >>> df.to_clipboard(sep=',', index=False) # doctest: +SKIP ... # Wrote the following to the system clipboard: ... # A,B,C ... # 1,2,3 ... # 4,5,6 """ from pandas.io import clipboards clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs) def to_xarray(self): """ Return an xarray object from the pandas object. Returns ------- xarray.DataArray or xarray.Dataset Data in the pandas structure converted to Dataset if the object is a DataFrame, or a DataArray if the object is a Series. See Also -------- DataFrame.to_hdf : Write DataFrame to an HDF5 file. DataFrame.to_parquet : Write a DataFrame to the binary parquet format. Notes ----- See the `xarray docs <https://xarray.pydata.org/en/stable/>`__ Examples -------- >>> df = pd.DataFrame([('falcon', 'bird', 389.0, 2), ... ('parrot', 'bird', 24.0, 2), ... ('lion', 'mammal', 80.5, 4), ... ('monkey', 'mammal', np.nan, 4)], ... columns=['name', 'class', 'max_speed', ... 'num_legs']) >>> df name class max_speed num_legs 0 falcon bird 389.0 2 1 parrot bird 24.0 2 2 lion mammal 80.5 4 3 monkey mammal NaN 4 >>> df.to_xarray() <xarray.Dataset> Dimensions: (index: 4) Coordinates: * index (index) int64 0 1 2 3 Data variables: name (index) object 'falcon' 'parrot' 'lion' 'monkey' class (index) object 'bird' 'bird' 'mammal' 'mammal' max_speed (index) float64 389.0 24.0 80.5 nan num_legs (index) int64 2 2 4 4 >>> df['max_speed'].to_xarray() <xarray.DataArray 'max_speed' (index: 4)> array([389. , 24. , 80.5, nan]) Coordinates: * index (index) int64 0 1 2 3 >>> dates = pd.to_datetime(['2018-01-01', '2018-01-01', ... '2018-01-02', '2018-01-02']) >>> df_multiindex = pd.DataFrame({'date': dates, ... 'animal': ['falcon', 'parrot', ... 'falcon', 'parrot'], ... 'speed': [350, 18, 361, 15]}) >>> df_multiindex = df_multiindex.set_index(['date', 'animal']) >>> df_multiindex speed date animal 2018-01-01 falcon 350 parrot 18 2018-01-02 falcon 361 parrot 15 >>> df_multiindex.to_xarray() <xarray.Dataset> Dimensions: (animal: 2, date: 2) Coordinates: * date (date) datetime64[ns] 2018-01-01 2018-01-02 * animal (animal) object 'falcon' 'parrot' Data variables: speed (date, animal) int64 350 18 361 15 """ xarray = import_optional_dependency("xarray") if self.ndim == 1: return xarray.DataArray.from_series(self) else: return xarray.Dataset.from_dataframe(self) @Substitution(returns=fmt.return_docstring) def to_latex( self, buf=None, columns=None, col_space=None, header=True, index=True, na_rep="NaN", formatters=None, float_format=None, sparsify=None, index_names=True, bold_rows=False, column_format=None, longtable=None, escape=None, encoding=None, decimal=".", multicolumn=None, multicolumn_format=None, multirow=None, caption=None, label=None, ): r""" Render object to a LaTeX tabular, longtable, or nested table/tabular. Requires ``\usepackage{booktabs}``. The output can be copy/pasted into a main LaTeX document or read from an external file with ``\input{table.tex}``. .. versionchanged:: 0.20.2 Added to Series. .. versionchanged:: 1.0.0 Added caption and label arguments. Parameters ---------- buf : str, Path or StringIO-like, optional, default None Buffer to write to. If None, the output is returned as a string. columns : list of label, optional The subset of columns to write. Writes all columns by default. col_space : int, optional The minimum width of each column. header : bool or list of str, default True Write out the column names. If a list of strings is given, it is assumed to be aliases for the column names. index : bool, default True Write row names (index). na_rep : str, default 'NaN' Missing data representation. formatters : list of functions or dict of {str: function}, optional Formatter functions to apply to columns' elements by position or name. The result of each function must be a unicode string. List must be of length equal to the number of columns. float_format : one-parameter function or str, optional, default None Formatter for floating point numbers. For example ``float_format="%%.2f"`` and ``float_format="{:0.2f}".format`` will both result in 0.1234 being formatted as 0.12. sparsify : bool, optional Set to False for a DataFrame with a hierarchical index to print every multiindex key at each row. By default, the value will be read from the config module. index_names : bool, default True Prints the names of the indexes. bold_rows : bool, default False Make the row labels bold in the output. column_format : str, optional The columns format as specified in `LaTeX table format <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g. 'rcl' for 3 columns. By default, 'l' will be used for all columns except columns of numbers, which default to 'r'. longtable : bool, optional By default, the value will be read from the pandas config module. Use a longtable environment instead of tabular. Requires adding a \usepackage{longtable} to your LaTeX preamble. escape : bool, optional By default, the value will be read from the pandas config module. When set to False prevents from escaping latex special characters in column names. encoding : str, optional A string representing the encoding to use in the output file, defaults to 'utf-8'. decimal : str, default '.' Character recognized as decimal separator, e.g. ',' in Europe. multicolumn : bool, default True Use \multicolumn to enhance MultiIndex columns. The default will be read from the config module. multicolumn_format : str, default 'l' The alignment for multicolumns, similar to `column_format` The default will be read from the config module. multirow : bool, default False Use \multirow to enhance MultiIndex rows. Requires adding a \usepackage{multirow} to your LaTeX preamble. Will print centered labels (instead of top-aligned) across the contained rows, separating groups via clines. The default will be read from the pandas config module. caption : str, optional The LaTeX caption to be placed inside ``\caption{}`` in the output. .. versionadded:: 1.0.0 label : str, optional The LaTeX label to be placed inside ``\label{}`` in the output. This is used with ``\ref{}`` in the main ``.tex`` file. .. versionadded:: 1.0.0 %(returns)s See Also -------- DataFrame.to_string : Render a DataFrame to a console-friendly tabular output. DataFrame.to_html : Render a DataFrame as an HTML table. Examples -------- >>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'], ... 'mask': ['red', 'purple'], ... 'weapon': ['sai', 'bo staff']}) >>> print(df.to_latex(index=False)) # doctest: +NORMALIZE_WHITESPACE \begin{tabular}{lll} \toprule name & mask & weapon \\ \midrule Raphael & red & sai \\ Donatello & purple & bo staff \\ \bottomrule \end{tabular} """ # Get defaults from the pandas config if self.ndim == 1: self = self.to_frame() if longtable is None: longtable = config.get_option("display.latex.longtable") if escape is None: escape = config.get_option("display.latex.escape") if multicolumn is None: multicolumn = config.get_option("display.latex.multicolumn") if multicolumn_format is None: multicolumn_format = config.get_option("display.latex.multicolumn_format") if multirow is None: multirow = config.get_option("display.latex.multirow") formatter = DataFrameFormatter( self, columns=columns, col_space=col_space, na_rep=na_rep, header=header, index=index, formatters=formatters, float_format=float_format, bold_rows=bold_rows, sparsify=sparsify, index_names=index_names, escape=escape, decimal=decimal, ) return formatter.to_latex( buf=buf, column_format=column_format, longtable=longtable, encoding=encoding, multicolumn=multicolumn, multicolumn_format=multicolumn_format, multirow=multirow, caption=caption, label=label, ) def to_csv( self, path_or_buf: Optional[FilePathOrBuffer] = None, sep: str = ",", na_rep: str = "", float_format: Optional[str] = None, columns: Optional[Sequence[Label]] = None, header: Union[bool_t, List[str]] = True, index: bool_t = True, index_label: Optional[Union[bool_t, str, Sequence[Label]]] = None, mode: str = "w", encoding: Optional[str] = None, compression: Optional[Union[str, Mapping[str, str]]] = "infer", quoting: Optional[int] = None, quotechar: str = '"', line_terminator: Optional[str] = None, chunksize: Optional[int] = None, date_format: Optional[str] = None, doublequote: bool_t = True, escapechar: Optional[str] = None, decimal: Optional[str] = ".", ) -> Optional[str]: r""" Write object to a comma-separated values (csv) file. .. versionchanged:: 0.24.0 The order of arguments for Series was changed. Parameters ---------- path_or_buf : str or file handle, default None File path or object, if None is provided the result is returned as a string. If a file object is passed it should be opened with `newline=''`, disabling universal newlines. .. versionchanged:: 0.24.0 Was previously named "path" for Series. sep : str, default ',' String of length 1. Field delimiter for the output file. na_rep : str, default '' Missing data representation. float_format : str, default None Format string for floating point numbers. columns : sequence, optional Columns to write. header : bool or list of str, default True Write out the column names. If a list of strings is given it is assumed to be aliases for the column names. .. versionchanged:: 0.24.0 Previously defaulted to False for Series. index : bool, default True Write row names (index). index_label : str or sequence, or False, default None Column label for index column(s) if desired. If None is given, and `header` and `index` are True, then the index names are used. A sequence should be given if the object uses MultiIndex. If False do not print fields for index names. Use index_label=False for easier importing in R. mode : str Python write mode, default 'w'. encoding : str, optional A string representing the encoding to use in the output file, defaults to 'utf-8'. compression : str or dict, default 'infer' If str, represents compression mode. If dict, value at 'method' is the compression mode. Compression mode may be any of the following possible values: {'infer', 'gzip', 'bz2', 'zip', 'xz', None}. If compression mode is 'infer' and `path_or_buf` is path-like, then detect compression mode from the following extensions: '.gz', '.bz2', '.zip' or '.xz'. (otherwise no compression). If dict given and mode is one of {'zip', 'gzip', 'bz2'}, or inferred as one of the above, other entries passed as additional compression options. .. versionchanged:: 1.0.0 May now be a dict with key 'method' as compression mode and other entries as additional compression options if compression mode is 'zip'. .. versionchanged:: 1.1.0 Passing compression options as keys in dict is supported for compression modes 'gzip' and 'bz2' as well as 'zip'. quoting : optional constant from csv module Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format` then floats are converted to strings and thus csv.QUOTE_NONNUMERIC will treat them as non-numeric. quotechar : str, default '\"' String of length 1. Character used to quote fields. line_terminator : str, optional The newline character or character sequence to use in the output file. Defaults to `os.linesep`, which depends on the OS in which this method is called ('\n' for linux, '\r\n' for Windows, i.e.). .. versionchanged:: 0.24.0 chunksize : int or None Rows to write at a time. date_format : str, default None Format string for datetime objects. doublequote : bool, default True Control quoting of `quotechar` inside a field. escapechar : str, default None String of length 1. Character used to escape `sep` and `quotechar` when appropriate. decimal : str, default '.' Character recognized as decimal separator. E.g. use ',' for European data. Returns ------- None or str If path_or_buf is None, returns the resulting csv format as a string. Otherwise returns None. See Also -------- read_csv : Load a CSV file into a DataFrame. to_excel : Write DataFrame to an Excel file. Examples -------- >>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'], ... 'mask': ['red', 'purple'], ... 'weapon': ['sai', 'bo staff']}) >>> df.to_csv(index=False) 'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n' Create 'out.zip' containing 'out.csv' >>> compression_opts = dict(method='zip', ... archive_name='out.csv') # doctest: +SKIP >>> df.to_csv('out.zip', index=False, ... compression=compression_opts) # doctest: +SKIP """ df = self if isinstance(self, ABCDataFrame) else self.to_frame() from pandas.io.formats.csvs import CSVFormatter formatter = CSVFormatter( df, path_or_buf, line_terminator=line_terminator, sep=sep, encoding=encoding, compression=compression, quoting=quoting, na_rep=na_rep, float_format=float_format, cols=columns, header=header, index=index, index_label=index_label, mode=mode, chunksize=chunksize, quotechar=quotechar, date_format=date_format, doublequote=doublequote, escapechar=escapechar, decimal=decimal, ) formatter.save() if path_or_buf is None: return formatter.path_or_buf.getvalue() return None # ---------------------------------------------------------------------- # Lookup Caching def _set_as_cached(self, item, cacher) -> None: """ Set the _cacher attribute on the calling object with a weakref to cacher. """ self._cacher = (item, weakref.ref(cacher)) def _reset_cacher(self) -> None: """ Reset the cacher. """ if hasattr(self, "_cacher"): del self._cacher def _maybe_cache_changed(self, item, value) -> None: """ The object has called back to us saying maybe it has changed. """ loc = self._info_axis.get_loc(item) self._mgr.iset(loc, value) @property def _is_cached(self) -> bool_t: """Return boolean indicating if self is cached or not.""" return getattr(self, "_cacher", None) is not None def _get_cacher(self): """return my cacher or None""" cacher = getattr(self, "_cacher", None) if cacher is not None: cacher = cacher[1]() return cacher def _maybe_update_cacher( self, clear: bool_t = False, verify_is_copy: bool_t = True ) -> None: """ See if we need to update our parent cacher if clear, then clear our cache. Parameters ---------- clear : bool, default False Clear the item cache. verify_is_copy : bool, default True Provide is_copy checks. """ cacher = getattr(self, "_cacher", None) if cacher is not None: ref = cacher[1]() # we are trying to reference a dead referant, hence # a copy if ref is None: del self._cacher else: if len(self) == len(ref): # otherwise, either self or ref has swapped in new arrays ref._maybe_cache_changed(cacher[0], self) if verify_is_copy: self._check_setitem_copy(stacklevel=5, t="referant") if clear: self._clear_item_cache() def _clear_item_cache(self) -> None: self._item_cache.clear() # ---------------------------------------------------------------------- # Indexing Methods def take( self: FrameOrSeries, indices, axis=0, is_copy: Optional[bool_t] = None, **kwargs ) -> FrameOrSeries: """ Return the elements in the given *positional* indices along an axis. This means that we are not indexing according to actual values in the index attribute of the object. We are indexing according to the actual position of the element in the object. Parameters ---------- indices : array-like An array of ints indicating which positions to take. axis : {0 or 'index', 1 or 'columns', None}, default 0 The axis on which to select elements. ``0`` means that we are selecting rows, ``1`` means that we are selecting columns. is_copy : bool Before pandas 1.0, ``is_copy=False`` can be specified to ensure that the return value is an actual copy. Starting with pandas 1.0, ``take`` always returns a copy, and the keyword is therefore deprecated. .. deprecated:: 1.0.0 **kwargs For compatibility with :meth:`numpy.take`. Has no effect on the output. Returns ------- taken : same type as caller An array-like containing the elements taken from the object. See Also -------- DataFrame.loc : Select a subset of a DataFrame by labels. DataFrame.iloc : Select a subset of a DataFrame by positions. numpy.take : Take elements from an array along an axis. Examples -------- >>> df = pd.DataFrame([('falcon', 'bird', 389.0), ... ('parrot', 'bird', 24.0), ... ('lion', 'mammal', 80.5), ... ('monkey', 'mammal', np.nan)], ... columns=['name', 'class', 'max_speed'], ... index=[0, 2, 3, 1]) >>> df name class max_speed 0 falcon bird 389.0 2 parrot bird 24.0 3 lion mammal 80.5 1 monkey mammal NaN Take elements at positions 0 and 3 along the axis 0 (default). Note how the actual indices selected (0 and 1) do not correspond to our selected indices 0 and 3. That's because we are selecting the 0th and 3rd rows, not rows whose indices equal 0 and 3. >>> df.take([0, 3]) name class max_speed 0 falcon bird 389.0 1 monkey mammal NaN Take elements at indices 1 and 2 along the axis 1 (column selection). >>> df.take([1, 2], axis=1) class max_speed 0 bird 389.0 2 bird 24.0 3 mammal 80.5 1 mammal NaN We may take elements using negative integers for positive indices, starting from the end of the object, just like with Python lists. >>> df.take([-1, -2]) name class max_speed 1 monkey mammal NaN 3 lion mammal 80.5 """ if is_copy is not None: warnings.warn( "is_copy is deprecated and will be removed in a future version. " "'take' always returns a copy, so there is no need to specify this.", FutureWarning, stacklevel=2, ) nv.validate_take(tuple(), kwargs) new_data = self._mgr.take( indices, axis=self._get_block_manager_axis(axis), verify=True ) return self._constructor(new_data).__finalize__(self, method="take") def _take_with_is_copy(self: FrameOrSeries, indices, axis=0) -> FrameOrSeries: """ Internal version of the `take` method that sets the `_is_copy` attribute to keep track of the parent dataframe (using in indexing for the SettingWithCopyWarning). See the docstring of `take` for full explanation of the parameters. """ result = self.take(indices=indices, axis=axis) # Maybe set copy if we didn't actually change the index. if not result._get_axis(axis).equals(self._get_axis(axis)): result._set_is_copy(self) return result def xs(self, key, axis=0, level=None, drop_level: bool_t = True): """ Return cross-section from the Series/DataFrame. This method takes a `key` argument to select data at a particular level of a MultiIndex. Parameters ---------- key : label or tuple of label Label contained in the index, or partially in a MultiIndex. axis : {0 or 'index', 1 or 'columns'}, default 0 Axis to retrieve cross-section on. level : object, defaults to first n levels (n=1 or len(key)) In case of a key partially contained in a MultiIndex, indicate which levels are used. Levels can be referred by label or position. drop_level : bool, default True If False, returns object with same levels as self. Returns ------- Series or DataFrame Cross-section from the original Series or DataFrame corresponding to the selected index levels. See Also -------- DataFrame.loc : Access a group of rows and columns by label(s) or a boolean array. DataFrame.iloc : Purely integer-location based indexing for selection by position. Notes ----- `xs` can not be used to set values. MultiIndex Slicers is a generic way to get/set values on any level or levels. It is a superset of `xs` functionality, see :ref:`MultiIndex Slicers <advanced.mi_slicers>`. Examples -------- >>> d = {'num_legs': [4, 4, 2, 2], ... 'num_wings': [0, 0, 2, 2], ... 'class': ['mammal', 'mammal', 'mammal', 'bird'], ... 'animal': ['cat', 'dog', 'bat', 'penguin'], ... 'locomotion': ['walks', 'walks', 'flies', 'walks']} >>> df = pd.DataFrame(data=d) >>> df = df.set_index(['class', 'animal', 'locomotion']) >>> df num_legs num_wings class animal locomotion mammal cat walks 4 0 dog walks 4 0 bat flies 2 2 bird penguin walks 2 2 Get values at specified index >>> df.xs('mammal') num_legs num_wings animal locomotion cat walks 4 0 dog walks 4 0 bat flies 2 2 Get values at several indexes >>> df.xs(('mammal', 'dog')) num_legs num_wings locomotion walks 4 0 Get values at specified index and level >>> df.xs('cat', level=1) num_legs num_wings class locomotion mammal walks 4 0 Get values at several indexes and levels >>> df.xs(('bird', 'walks'), ... level=[0, 'locomotion']) num_legs num_wings animal penguin 2 2 Get values at specified column and axis >>> df.xs('num_wings', axis=1) class animal locomotion mammal cat walks 0 dog walks 0 bat flies 2 bird penguin walks 2 Name: num_wings, dtype: int64 """ axis = self._get_axis_number(axis) labels = self._get_axis(axis) if level is not None: if not isinstance(labels, MultiIndex): raise TypeError("Index must be a MultiIndex") loc, new_ax = labels.get_loc_level(key, level=level, drop_level=drop_level) # create the tuple of the indexer _indexer = [slice(None)] * self.ndim _indexer[axis] = loc indexer = tuple(_indexer) result = self.iloc[indexer] setattr(result, result._get_axis_name(axis), new_ax) return result if axis == 1: return self[key] index = self.index if isinstance(index, MultiIndex): loc, new_index = self.index.get_loc_level(key, drop_level=drop_level) else: loc = self.index.get_loc(key) if isinstance(loc, np.ndarray): if loc.dtype == np.bool_: (inds,) = loc.nonzero() return self._take_with_is_copy(inds, axis=axis) else: return self._take_with_is_copy(loc, axis=axis) if not is_scalar(loc): new_index = self.index[loc] if is_scalar(loc): # In this case loc should be an integer if self.ndim == 1: # if we encounter an array-like and we only have 1 dim # that means that their are list/ndarrays inside the Series! # so just return them (GH 6394) return self._values[loc] new_values = self._mgr.fast_xs(loc) result = self._constructor_sliced( new_values, index=self.columns, name=self.index[loc], dtype=new_values.dtype, ) else: result = self.iloc[loc] result.index = new_index # this could be a view # but only in a single-dtyped view sliceable case result._set_is_copy(self, copy=not result._is_view) return result def __getitem__(self, item): raise AbstractMethodError(self) def _get_item_cache(self, item): """Return the cached item, item represents a label indexer.""" cache = self._item_cache res = cache.get(item) if res is None: # All places that call _get_item_cache have unique columns, # pending resolution of GH#33047 loc = self.columns.get_loc(item) values = self._mgr.iget(loc) res = self._box_col_values(values, loc) cache[item] = res res._set_as_cached(item, self) # for a chain res._is_copy = self._is_copy return res def _slice(self: FrameOrSeries, slobj: slice, axis=0) -> FrameOrSeries: """ Construct a slice of this container. Slicing with this method is *always* positional. """ assert isinstance(slobj, slice), type(slobj) axis = self._get_block_manager_axis(axis) result = self._constructor(self._mgr.get_slice(slobj, axis=axis)) result = result.__finalize__(self) # this could be a view # but only in a single-dtyped view sliceable case is_copy = axis != 0 or result._is_view result._set_is_copy(self, copy=is_copy) return result def _iset_item(self, loc: int, value) -> None: self._mgr.iset(loc, value) self._clear_item_cache() def _set_item(self, key, value) -> None: try: loc = self._info_axis.get_loc(key) except KeyError: # This item wasn't present, just insert at end self._mgr.insert(len(self._info_axis), key, value) return NDFrame._iset_item(self, loc, value) def _set_is_copy(self, ref, copy: bool_t = True) -> None: if not copy: self._is_copy = None else: assert ref is not None self._is_copy = weakref.ref(ref) def _check_is_chained_assignment_possible(self) -> bool_t: """ Check if we are a view, have a cacher, and are of mixed type. If so, then force a setitem_copy check. Should be called just near setting a value Will return a boolean if it we are a view and are cached, but a single-dtype meaning that the cacher should be updated following setting. """ if self._is_view and self._is_cached: ref = self._get_cacher() if ref is not None and ref._is_mixed_type: self._check_setitem_copy(stacklevel=4, t="referant", force=True) return True elif self._is_copy: self._check_setitem_copy(stacklevel=4, t="referant") return False def _check_setitem_copy(self, stacklevel=4, t="setting", force=False): """ Parameters ---------- stacklevel : int, default 4 the level to show of the stack when the error is output t : str, the type of setting error force : bool, default False If True, then force showing an error. validate if we are doing a setitem on a chained copy. If you call this function, be sure to set the stacklevel such that the user will see the error *at the level of setting* It is technically possible to figure out that we are setting on a copy even WITH a multi-dtyped pandas object. In other words, some blocks may be views while other are not. Currently _is_view will ALWAYS return False for multi-blocks to avoid having to handle this case. df = DataFrame(np.arange(0,9), columns=['count']) df['group'] = 'b' # This technically need not raise SettingWithCopy if both are view # (which is not # generally guaranteed but is usually True. However, # this is in general not a good practice and we recommend using .loc. df.iloc[0:5]['group'] = 'a' """ # return early if the check is not needed if not (force or self._is_copy): return value = config.get_option("mode.chained_assignment") if value is None: return # see if the copy is not actually referred; if so, then dissolve # the copy weakref if self._is_copy is not None and not isinstance(self._is_copy, str): r = self._is_copy() if not gc.get_referents(r) or r.shape == self.shape: self._is_copy = None return # a custom message if isinstance(self._is_copy, str): t = self._is_copy elif t == "referant": t = ( "\n" "A value is trying to be set on a copy of a slice from a " "DataFrame\n\n" "See the caveats in the documentation: " "https://pandas.pydata.org/pandas-docs/stable/user_guide/" "indexing.html#returning-a-view-versus-a-copy" ) else: t = ( "\n" "A value is trying to be set on a copy of a slice from a " "DataFrame.\n" "Try using .loc[row_indexer,col_indexer] = value " "instead\n\nSee the caveats in the documentation: " "https://pandas.pydata.org/pandas-docs/stable/user_guide/" "indexing.html#returning-a-view-versus-a-copy" ) if value == "raise": raise com.SettingWithCopyError(t) elif value == "warn": warnings.warn(t, com.SettingWithCopyWarning, stacklevel=stacklevel) def __delitem__(self, key) -> None: """ Delete item """ deleted = False maybe_shortcut = False if self.ndim == 2 and isinstance(self.columns, MultiIndex): try: maybe_shortcut = key not in self.columns._engine except TypeError: pass if maybe_shortcut: # Allow shorthand to delete all columns whose first len(key) # elements match key: if not isinstance(key, tuple): key = (key,) for col in self.columns: if isinstance(col, tuple) and col[: len(key)] == key: del self[col] deleted = True if not deleted: # If the above loop ran and didn't delete anything because # there was no match, this call should raise the appropriate # exception: loc = self.axes[-1].get_loc(key) self._mgr.idelete(loc) # delete from the caches try: del self._item_cache[key] except KeyError: pass # ---------------------------------------------------------------------- # Unsorted def get(self, key, default=None): """ Get item from object for given key (ex: DataFrame column). Returns default value if not found. Parameters ---------- key : object Returns ------- value : same type as items contained in object """ try: return self[key] except (KeyError, ValueError, IndexError): return default @property def _is_view(self) -> bool_t: """Return boolean indicating if self is view of another array """ return self._mgr.is_view def reindex_like( self: FrameOrSeries, other, method: Optional[str] = None, copy: bool_t = True, limit=None, tolerance=None, ) -> FrameOrSeries: """ Return an object with matching indices as other object. Conform the object to the same index on all axes. Optional filling logic, placing NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False. Parameters ---------- other : Object of the same data type Its row and column indices are used to define the new indices of this object. method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'} Method to use for filling holes in reindexed DataFrame. Please note: this is only applicable to DataFrames/Series with a monotonically increasing/decreasing index. * None (default): don't fill gaps * pad / ffill: propagate last valid observation forward to next valid * backfill / bfill: use next valid observation to fill gap * nearest: use nearest valid observations to fill gap. copy : bool, default True Return a new object, even if the passed indexes are the same. limit : int, default None Maximum number of consecutive labels to fill for inexact matches. tolerance : optional Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations most satisfy the equation ``abs(index[indexer] - target) <= tolerance``. Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the index's type. Returns ------- Series or DataFrame Same type as caller, but with changed indices on each axis. See Also -------- DataFrame.set_index : Set row labels. DataFrame.reset_index : Remove row labels or move them to new columns. DataFrame.reindex : Change to new indices or expand indices. Notes ----- Same as calling ``.reindex(index=other.index, columns=other.columns,...)``. Examples -------- >>> df1 = pd.DataFrame([[24.3, 75.7, 'high'], ... [31, 87.8, 'high'], ... [22, 71.6, 'medium'], ... [35, 95, 'medium']], ... columns=['temp_celsius', 'temp_fahrenheit', ... 'windspeed'], ... index=pd.date_range(start='2014-02-12', ... end='2014-02-15', freq='D')) >>> df1 temp_celsius temp_fahrenheit windspeed 2014-02-12 24.3 75.7 high 2014-02-13 31.0 87.8 high 2014-02-14 22.0 71.6 medium 2014-02-15 35.0 95.0 medium >>> df2 = pd.DataFrame([[28, 'low'], ... [30, 'low'], ... [35.1, 'medium']], ... columns=['temp_celsius', 'windspeed'], ... index=pd.DatetimeIndex(['2014-02-12', '2014-02-13', ... '2014-02-15'])) >>> df2 temp_celsius windspeed 2014-02-12 28.0 low 2014-02-13 30.0 low 2014-02-15 35.1 medium >>> df2.reindex_like(df1) temp_celsius temp_fahrenheit windspeed 2014-02-12 28.0 NaN low 2014-02-13 30.0 NaN low 2014-02-14 NaN NaN NaN 2014-02-15 35.1 NaN medium """ d = other._construct_axes_dict( axes=self._AXIS_ORDERS, method=method, copy=copy, limit=limit, tolerance=tolerance, ) return self.reindex(**d) def drop( self, labels=None, axis=0, index=None, columns=None, level=None, inplace: bool_t = False, errors: str = "raise", ): inplace = validate_bool_kwarg(inplace, "inplace") if labels is not None: if index is not None or columns is not None: raise ValueError("Cannot specify both 'labels' and 'index'/'columns'") axis_name = self._get_axis_name(axis) axes = {axis_name: labels} elif index is not None or columns is not None: axes, _ = self._construct_axes_from_arguments((index, columns), {}) else: raise ValueError( "Need to specify at least one of 'labels', 'index' or 'columns'" ) obj = self for axis, labels in axes.items(): if labels is not None: obj = obj._drop_axis(labels, axis, level=level, errors=errors) if inplace: self._update_inplace(obj) else: return obj def _drop_axis( self: FrameOrSeries, labels, axis, level=None, errors: str = "raise" ) -> FrameOrSeries: """ Drop labels from specified axis. Used in the ``drop`` method internally. Parameters ---------- labels : single label or list-like axis : int or axis name level : int or level name, default None For MultiIndex errors : {'ignore', 'raise'}, default 'raise' If 'ignore', suppress error and existing labels are dropped. """ axis = self._get_axis_number(axis) axis_name = self._get_axis_name(axis) axis = self._get_axis(axis) if axis.is_unique: if level is not None: if not isinstance(axis, MultiIndex): raise AssertionError("axis must be a MultiIndex") new_axis = axis.drop(labels, level=level, errors=errors) else: new_axis = axis.drop(labels, errors=errors) result = self.reindex(**{axis_name: new_axis}) # Case for non-unique axis else: labels = ensure_object(com.index_labels_to_array(labels)) if level is not None: if not isinstance(axis, MultiIndex): raise AssertionError("axis must be a MultiIndex") indexer = ~axis.get_level_values(level).isin(labels) # GH 18561 MultiIndex.drop should raise if label is absent if errors == "raise" and indexer.all(): raise KeyError(f"{labels} not found in axis") else: indexer = ~axis.isin(labels) # Check if label doesn't exist along axis labels_missing = (axis.get_indexer_for(labels) == -1).any() if errors == "raise" and labels_missing: raise KeyError(f"{labels} not found in axis") slicer = [slice(None)] * self.ndim slicer[self._get_axis_number(axis_name)] = indexer result = self.loc[tuple(slicer)] return result def _update_inplace(self, result, verify_is_copy: bool_t = True) -> None: """ Replace self internals with result. Parameters ---------- result : same type as self verify_is_copy : bool, default True Provide is_copy checks. """ # NOTE: This does *not* call __finalize__ and that's an explicit # decision that we may revisit in the future. self._reset_cache() self._clear_item_cache() self._mgr = result._mgr self._maybe_update_cacher(verify_is_copy=verify_is_copy) def add_prefix(self: FrameOrSeries, prefix: str) -> FrameOrSeries: """ Prefix labels with string `prefix`. For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed. Parameters ---------- prefix : str The string to add before each label. Returns ------- Series or DataFrame New Series or DataFrame with updated labels. See Also -------- Series.add_suffix: Suffix row labels with string `suffix`. DataFrame.add_suffix: Suffix column labels with string `suffix`. Examples -------- >>> s = pd.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.add_prefix('item_') item_0 1 item_1 2 item_2 3 item_3 4 dtype: int64 >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]}) >>> df A B 0 1 3 1 2 4 2 3 5 3 4 6 >>> df.add_prefix('col_') col_A col_B 0 1 3 1 2 4 2 3 5 3 4 6 """ f = functools.partial("{prefix}{}".format, prefix=prefix) mapper = {self._info_axis_name: f} return self.rename(**mapper) # type: ignore def add_suffix(self: FrameOrSeries, suffix: str) -> FrameOrSeries: """ Suffix labels with string `suffix`. For Series, the row labels are suffixed. For DataFrame, the column labels are suffixed. Parameters ---------- suffix : str The string to add after each label. Returns ------- Series or DataFrame New Series or DataFrame with updated labels. See Also -------- Series.add_prefix: Prefix row labels with string `prefix`. DataFrame.add_prefix: Prefix column labels with string `prefix`. Examples -------- >>> s = pd.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.add_suffix('_item') 0_item 1 1_item 2 2_item 3 3_item 4 dtype: int64 >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]}) >>> df A B 0 1 3 1 2 4 2 3 5 3 4 6 >>> df.add_suffix('_col') A_col B_col 0 1 3 1 2 4 2 3 5 3 4 6 """ f = functools.partial("{}{suffix}".format, suffix=suffix) mapper = {self._info_axis_name: f} return self.rename(**mapper) # type: ignore def sort_values( self, axis=0, ascending=True, inplace: bool_t = False, kind: str = "quicksort", na_position: str = "last", ignore_index: bool_t = False, key: ValueKeyFunc = None, ): """ Sort by the values along either axis. Parameters ----------%(optional_by)s axis : %(axes_single_arg)s, default 0 Axis to be sorted. ascending : bool or list of bool, default True Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by. inplace : bool, default False If True, perform operation in-place. kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort' Choice of sorting algorithm. See also ndarray.np.sort for more information. `mergesort` is the only stable algorithm. For DataFrames, this option is only applied when sorting on a single column or label. na_position : {'first', 'last'}, default 'last' Puts NaNs at the beginning if `first`; `last` puts NaNs at the end. ignore_index : bool, default False If True, the resulting axis will be labeled 0, 1, …, n - 1. .. versionadded:: 1.0.0 key : callable, optional Apply the key function to the values before sorting. This is similar to the `key` argument in the builtin :meth:`sorted` function, with the notable difference that this `key` function should be *vectorized*. It should expect a ``Series`` and return a Series with the same shape as the input. It will be applied to each column in `by` independently. .. versionadded:: 1.1.0 Returns ------- DataFrame or None DataFrame with sorted values if inplace=False, None otherwise. See Also -------- DataFrame.sort_index : Sort a DataFrame by the index. Series.sort_values : Similar method for a Series. Examples -------- >>> df = pd.DataFrame({ ... 'col1': ['A', 'A', 'B', np.nan, 'D', 'C'], ... 'col2': [2, 1, 9, 8, 7, 4], ... 'col3': [0, 1, 9, 4, 2, 3], ... 'col4': ['a', 'B', 'c', 'D', 'e', 'F'] ... }) >>> df col1 col2 col3 col4 0 A 2 0 a 1 A 1 1 B 2 B 9 9 c 3 NaN 8 4 D 4 D 7 2 e 5 C 4 3 F Sort by col1 >>> df.sort_values(by=['col1']) col1 col2 col3 col4 0 A 2 0 a 1 A 1 1 B 2 B 9 9 c 5 C 4 3 F 4 D 7 2 e 3 NaN 8 4 D Sort by multiple columns >>> df.sort_values(by=['col1', 'col2']) col1 col2 col3 col4 1 A 1 1 B 0 A 2 0 a 2 B 9 9 c 5 C 4 3 F 4 D 7 2 e 3 NaN 8 4 D Sort Descending >>> df.sort_values(by='col1', ascending=False) col1 col2 col3 col4 4 D 7 2 e 5 C 4 3 F 2 B 9 9 c 0 A 2 0 a 1 A 1 1 B 3 NaN 8 4 D Putting NAs first >>> df.sort_values(by='col1', ascending=False, na_position='first') col1 col2 col3 col4 3 NaN 8 4 D 4 D 7 2 e 5 C 4 3 F 2 B 9 9 c 0 A 2 0 a 1 A 1 1 B Sorting with a key function >>> df.sort_values(by='col4', key=lambda col: col.str.lower()) col1 col2 col3 col4 0 A 2 0 a 1 A 1 1 B 2 B 9 9 c 3 NaN 8 4 D 4 D 7 2 e 5 C 4 3 F """ raise AbstractMethodError(self) def reindex(self: FrameOrSeries, *args, **kwargs) -> FrameOrSeries: """ Conform %(klass)s to new index with optional filling logic. Places NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and ``copy=False``. Parameters ---------- %(optional_labels)s %(axes)s : array-like, optional New labels / index to conform to, should be specified using keywords. Preferably an Index object to avoid duplicating data. %(optional_axis)s method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'} Method to use for filling holes in reindexed DataFrame. Please note: this is only applicable to DataFrames/Series with a monotonically increasing/decreasing index. * None (default): don't fill gaps * pad / ffill: Propagate last valid observation forward to next valid. * backfill / bfill: Use next valid observation to fill gap. * nearest: Use nearest valid observations to fill gap. copy : bool, default True Return a new object, even if the passed indexes are the same. level : int or name Broadcast across a level, matching Index values on the passed MultiIndex level. fill_value : scalar, default np.NaN Value to use for missing values. Defaults to NaN, but can be any "compatible" value. limit : int, default None Maximum number of consecutive elements to forward or backward fill. tolerance : optional Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations most satisfy the equation ``abs(index[indexer] - target) <= tolerance``. Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the index's type. Returns ------- %(klass)s with changed index. See Also -------- DataFrame.set_index : Set row labels. DataFrame.reset_index : Remove row labels or move them to new columns. DataFrame.reindex_like : Change to same indices as other DataFrame. Examples -------- ``DataFrame.reindex`` supports two calling conventions * ``(index=index_labels, columns=column_labels, ...)`` * ``(labels, axis={'index', 'columns'}, ...)`` We *highly* recommend using keyword arguments to clarify your intent. Create a dataframe with some fictional data. >>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror'] >>> df = pd.DataFrame({'http_status': [200, 200, 404, 404, 301], ... 'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]}, ... index=index) >>> df http_status response_time Firefox 200 0.04 Chrome 200 0.02 Safari 404 0.07 IE10 404 0.08 Konqueror 301 1.00 Create a new index and reindex the dataframe. By default values in the new index that do not have corresponding records in the dataframe are assigned ``NaN``. >>> new_index = ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10', ... 'Chrome'] >>> df.reindex(new_index) http_status response_time Safari 404.0 0.07 Iceweasel NaN NaN Comodo Dragon NaN NaN IE10 404.0 0.08 Chrome 200.0 0.02 We can fill in the missing values by passing a value to the keyword ``fill_value``. Because the index is not monotonically increasing or decreasing, we cannot use arguments to the keyword ``method`` to fill the ``NaN`` values. >>> df.reindex(new_index, fill_value=0) http_status response_time Safari 404 0.07 Iceweasel 0 0.00 Comodo Dragon 0 0.00 IE10 404 0.08 Chrome 200 0.02 >>> df.reindex(new_index, fill_value='missing') http_status response_time Safari 404 0.07 Iceweasel missing missing Comodo Dragon missing missing IE10 404 0.08 Chrome 200 0.02 We can also reindex the columns. >>> df.reindex(columns=['http_status', 'user_agent']) http_status user_agent Firefox 200 NaN Chrome 200 NaN Safari 404 NaN IE10 404 NaN Konqueror 301 NaN Or we can use "axis-style" keyword arguments >>> df.reindex(['http_status', 'user_agent'], axis="columns") http_status user_agent Firefox 200 NaN Chrome 200 NaN Safari 404 NaN IE10 404 NaN Konqueror 301 NaN To further illustrate the filling functionality in ``reindex``, we will create a dataframe with a monotonically increasing index (for example, a sequence of dates). >>> date_index = pd.date_range('1/1/2010', periods=6, freq='D') >>> df2 = pd.DataFrame({"prices": [100, 101, np.nan, 100, 89, 88]}, ... index=date_index) >>> df2 prices 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0 Suppose we decide to expand the dataframe to cover a wider date range. >>> date_index2 = pd.date_range('12/29/2009', periods=10, freq='D') >>> df2.reindex(date_index2) prices 2009-12-29 NaN 2009-12-30 NaN 2009-12-31 NaN 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0 2010-01-07 NaN The index entries that did not have a value in the original data frame (for example, '2009-12-29') are by default filled with ``NaN``. If desired, we can fill in the missing values using one of several options. For example, to back-propagate the last valid value to fill the ``NaN`` values, pass ``bfill`` as an argument to the ``method`` keyword. >>> df2.reindex(date_index2, method='bfill') prices 2009-12-29 100.0 2009-12-30 100.0 2009-12-31 100.0 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0 2010-01-07 NaN Please note that the ``NaN`` value present in the original dataframe (at index value 2010-01-03) will not be filled by any of the value propagation schemes. This is because filling while reindexing does not look at dataframe values, but only compares the original and desired indexes. If you do want to fill in the ``NaN`` values present in the original dataframe, use the ``fillna()`` method. See the :ref:`user guide <basics.reindexing>` for more. """ # TODO: Decide if we care about having different examples for different # kinds # construct the args axes, kwargs = self._construct_axes_from_arguments(args, kwargs) method = missing.clean_reindex_fill_method(kwargs.pop("method", None)) level = kwargs.pop("level", None) copy = kwargs.pop("copy", True) limit = kwargs.pop("limit", None) tolerance = kwargs.pop("tolerance", None) fill_value = kwargs.pop("fill_value", None) # Series.reindex doesn't use / need the axis kwarg # We pop and ignore it here, to make writing Series/Frame generic code # easier kwargs.pop("axis", None) if kwargs: raise TypeError( "reindex() got an unexpected keyword " f'argument "{list(kwargs.keys())[0]}"' ) self._consolidate_inplace() # if all axes that are requested to reindex are equal, then only copy # if indicated must have index names equal here as well as values if all( self._get_axis(axis).identical(ax) for axis, ax in axes.items() if ax is not None ): if copy: return self.copy() return self # check if we are a multi reindex if self._needs_reindex_multi(axes, method, level): return self._reindex_multi(axes, copy, fill_value) # perform the reindex on the axes return self._reindex_axes( axes, level, limit, tolerance, method, fill_value, copy ).__finalize__(self, method="reindex") def _reindex_axes( self: FrameOrSeries, axes, level, limit, tolerance, method, fill_value, copy ) -> FrameOrSeries: """Perform the reindex for all the axes.""" obj = self for a in self._AXIS_ORDERS: labels = axes[a] if labels is None: continue ax = self._get_axis(a) new_index, indexer = ax.reindex( labels, level=level, limit=limit, tolerance=tolerance, method=method ) axis = self._get_axis_number(a) obj = obj._reindex_with_indexers( {axis: [new_index, indexer]}, fill_value=fill_value, copy=copy, allow_dups=False, ) return obj def _needs_reindex_multi(self, axes, method, level) -> bool_t: """Check if we do need a multi reindex.""" return ( (com.count_not_none(*axes.values()) == self._AXIS_LEN) and method is None and level is None and not self._is_mixed_type ) def _reindex_multi(self, axes, copy, fill_value): raise AbstractMethodError(self) def _reindex_with_indexers( self: FrameOrSeries, reindexers, fill_value=None, copy: bool_t = False, allow_dups: bool_t = False, ) -> FrameOrSeries: """allow_dups indicates an internal call here """ # reindex doing multiple operations on different axes if indicated new_data = self._mgr for axis in sorted(reindexers.keys()): index, indexer = reindexers[axis] baxis = self._get_block_manager_axis(axis) if index is None: continue index = ensure_index(index) if indexer is not None: indexer = ensure_int64(indexer) # TODO: speed up on homogeneous DataFrame objects new_data = new_data.reindex_indexer( index, indexer, axis=baxis, fill_value=fill_value, allow_dups=allow_dups, copy=copy, ) # If we've made a copy once, no need to make another one copy = False if copy and new_data is self._mgr: new_data = new_data.copy() return self._constructor(new_data).__finalize__(self) def filter( self: FrameOrSeries, items=None, like: Optional[str] = None, regex: Optional[str] = None, axis=None, ) -> FrameOrSeries: """ Subset the dataframe rows or columns according to the specified index labels. Note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index. Parameters ---------- items : list-like Keep labels from axis which are in items. like : str Keep labels from axis for which "like in label == True". regex : str (regular expression) Keep labels from axis for which re.search(regex, label) == True. axis : {0 or ‘index’, 1 or ‘columns’, None}, default None The axis to filter on, expressed either as an index (int) or axis name (str). By default this is the info axis, 'index' for Series, 'columns' for DataFrame. Returns ------- same type as input object See Also -------- DataFrame.loc : Access a group of rows and columns by label(s) or a boolean array. Notes ----- The ``items``, ``like``, and ``regex`` parameters are enforced to be mutually exclusive. ``axis`` defaults to the info axis that is used when indexing with ``[]``. Examples -------- >>> df = pd.DataFrame(np.array(([1, 2, 3], [4, 5, 6])), ... index=['mouse', 'rabbit'], ... columns=['one', 'two', 'three']) >>> df one two three mouse 1 2 3 rabbit 4 5 6 >>> # select columns by name >>> df.filter(items=['one', 'three']) one three mouse 1 3 rabbit 4 6 >>> # select columns by regular expression >>> df.filter(regex='e$', axis=1) one three mouse 1 3 rabbit 4 6 >>> # select rows containing 'bbi' >>> df.filter(like='bbi', axis=0) one two three rabbit 4 5 6 """ nkw = com.count_not_none(items, like, regex) if nkw > 1: raise TypeError( "Keyword arguments `items`, `like`, or `regex` " "are mutually exclusive" ) if axis is None: axis = self._info_axis_name labels = self._get_axis(axis) if items is not None: name = self._get_axis_name(axis) return self.reindex(**{name: [r for r in items if r in labels]}) elif like: def f(x): return like in ensure_str(x) values = labels.map(f) return self.loc(axis=axis)[values] elif regex: def f(x): return matcher.search(ensure_str(x)) is not None matcher = re.compile(regex) values = labels.map(f) return self.loc(axis=axis)[values] else: raise TypeError("Must pass either `items`, `like`, or `regex`") def head(self: FrameOrSeries, n: int = 5) -> FrameOrSeries: """ Return the first `n` rows. This function returns the first `n` rows for the object based on position. It is useful for quickly testing if your object has the right type of data in it. For negative values of `n`, this function returns all rows except the last `n` rows, equivalent to ``df[:-n]``. Parameters ---------- n : int, default 5 Number of rows to select. Returns ------- same type as caller The first `n` rows of the caller object. See Also -------- DataFrame.tail: Returns the last `n` rows. Examples -------- >>> df = pd.DataFrame({'animal': ['alligator', 'bee', 'falcon', 'lion', ... 'monkey', 'parrot', 'shark', 'whale', 'zebra']}) >>> df animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey 5 parrot 6 shark 7 whale 8 zebra Viewing the first 5 lines >>> df.head() animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey Viewing the first `n` lines (three in this case) >>> df.head(3) animal 0 alligator 1 bee 2 falcon For negative values of `n` >>> df.head(-3) animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey 5 parrot """ return self.iloc[:n] def tail(self: FrameOrSeries, n: int = 5) -> FrameOrSeries: """ Return the last `n` rows. This function returns last `n` rows from the object based on position. It is useful for quickly verifying data, for example, after sorting or appending rows. For negative values of `n`, this function returns all rows except the first `n` rows, equivalent to ``df[n:]``. Parameters ---------- n : int, default 5 Number of rows to select. Returns ------- type of caller The last `n` rows of the caller object. See Also -------- DataFrame.head : The first `n` rows of the caller object. Examples -------- >>> df = pd.DataFrame({'animal': ['alligator', 'bee', 'falcon', 'lion', ... 'monkey', 'parrot', 'shark', 'whale', 'zebra']}) >>> df animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey 5 parrot 6 shark 7 whale 8 zebra Viewing the last 5 lines >>> df.tail() animal 4 monkey 5 parrot 6 shark 7 whale 8 zebra Viewing the last `n` lines (three in this case) >>> df.tail(3) animal 6 shark 7 whale 8 zebra For negative values of `n` >>> df.tail(-3) animal 3 lion 4 monkey 5 parrot 6 shark 7 whale 8 zebra """ if n == 0: return self.iloc[0:0] return self.iloc[-n:] def sample( self: FrameOrSeries, n=None, frac=None, replace=False, weights=None, random_state=None, axis=None, ) -> FrameOrSeries: """ Return a random sample of items from an axis of object. You can use `random_state` for reproducibility. Parameters ---------- n : int, optional Number of items from axis to return. Cannot be used with `frac`. Default = 1 if `frac` = None. frac : float, optional Fraction of axis items to return. Cannot be used with `n`. replace : bool, default False Allow or disallow sampling of the same row more than once. weights : str or ndarray-like, optional Default 'None' results in equal probability weighting. If passed a Series, will align with target object on index. Index values in weights not found in sampled object will be ignored and index values in sampled object not in weights will be assigned weights of zero. If called on a DataFrame, will accept the name of a column when axis = 0. Unless weights are a Series, weights must be same length as axis being sampled. If weights do not sum to 1, they will be normalized to sum to 1. Missing values in the weights column will be treated as zero. Infinite values not allowed. random_state : int, array-like, BitGenerator, np.random.RandomState, optional If int, array-like, or BitGenerator (NumPy>=1.17), seed for random number generator If np.random.RandomState, use as numpy RandomState object. ..versionchanged:: 1.1.0 array-like and BitGenerator (for NumPy>=1.17) object now passed to np.random.RandomState() as seed axis : {0 or ‘index’, 1 or ‘columns’, None}, default None Axis to sample. Accepts axis number or name. Default is stat axis for given data type (0 for Series and DataFrames). Returns ------- Series or DataFrame A new object of same type as caller containing `n` items randomly sampled from the caller object. See Also -------- numpy.random.choice: Generates a random sample from a given 1-D numpy array. Notes ----- If `frac` > 1, `replacement` should be set to `True`. Examples -------- >>> df = pd.DataFrame({'num_legs': [2, 4, 8, 0], ... 'num_wings': [2, 0, 0, 0], ... 'num_specimen_seen': [10, 2, 1, 8]}, ... index=['falcon', 'dog', 'spider', 'fish']) >>> df num_legs num_wings num_specimen_seen falcon 2 2 10 dog 4 0 2 spider 8 0 1 fish 0 0 8 Extract 3 random elements from the ``Series`` ``df['num_legs']``: Note that we use `random_state` to ensure the reproducibility of the examples. >>> df['num_legs'].sample(n=3, random_state=1) fish 0 spider 8 falcon 2 Name: num_legs, dtype: int64 A random 50% sample of the ``DataFrame`` with replacement: >>> df.sample(frac=0.5, replace=True, random_state=1) num_legs num_wings num_specimen_seen dog 4 0 2 fish 0 0 8 An upsample sample of the ``DataFrame`` with replacement: Note that `replace` parameter has to be `True` for `frac` parameter > 1. >>> df.sample(frac=2, replace=True, random_state=1) num_legs num_wings num_specimen_seen dog 4 0 2 fish 0 0 8 falcon 2 2 10 falcon 2 2 10 fish 0 0 8 dog 4 0 2 fish 0 0 8 dog 4 0 2 Using a DataFrame column as weights. Rows with larger value in the `num_specimen_seen` column are more likely to be sampled. >>> df.sample(n=2, weights='num_specimen_seen', random_state=1) num_legs num_wings num_specimen_seen falcon 2 2 10 fish 0 0 8 """ if axis is None: axis = self._stat_axis_number axis = self._get_axis_number(axis) axis_length = self.shape[axis] # Process random_state argument rs = com.random_state(random_state) # Check weights for compliance if weights is not None: # If a series, align with frame if isinstance(weights, ABCSeries): weights = weights.reindex(self.axes[axis]) # Strings acceptable if a dataframe and axis = 0 if isinstance(weights, str): if isinstance(self, ABCDataFrame): if axis == 0: try: weights = self[weights] except KeyError as err: raise KeyError( "String passed to weights not a valid column" ) from err else: raise ValueError( "Strings can only be passed to " "weights when sampling from rows on " "a DataFrame" ) else: raise ValueError( "Strings cannot be passed as weights " "when sampling from a Series." ) weights = pd.Series(weights, dtype="float64") if len(weights) != axis_length: raise ValueError( "Weights and axis to be sampled must be of same length" ) if (weights == np.inf).any() or (weights == -np.inf).any(): raise ValueError("weight vector may not include `inf` values") if (weights < 0).any(): raise ValueError("weight vector many not include negative values") # If has nan, set to zero. weights = weights.fillna(0) # Renormalize if don't sum to 1 if weights.sum() != 1: if weights.sum() != 0: weights = weights / weights.sum() else: raise ValueError("Invalid weights: weights sum to zero") weights = weights._values # If no frac or n, default to n=1. if n is None and frac is None: n = 1 elif frac is not None and frac > 1 and not replace: raise ValueError( "Replace has to be set to `True` when " "upsampling the population `frac` > 1." ) elif n is not None and frac is None and n % 1 != 0: raise ValueError("Only integers accepted as `n` values") elif n is None and frac is not None: n = int(round(frac * axis_length)) elif n is not None and frac is not None: raise ValueError("Please enter a value for `frac` OR `n`, not both") # Check for negative sizes if n < 0: raise ValueError( "A negative number of rows requested. Please provide positive value." ) locs = rs.choice(axis_length, size=n, replace=replace, p=weights) return self.take(locs, axis=axis) _shared_docs[ "pipe" ] = r""" Apply func(self, \*args, \*\*kwargs). Parameters ---------- func : function Function to apply to the %(klass)s. ``args``, and ``kwargs`` are passed into ``func``. Alternatively a ``(callable, data_keyword)`` tuple where ``data_keyword`` is a string indicating the keyword of ``callable`` that expects the %(klass)s. args : iterable, optional Positional arguments passed into ``func``. kwargs : mapping, optional A dictionary of keyword arguments passed into ``func``. Returns ------- object : the return type of ``func``. See Also -------- DataFrame.apply : Apply a function along input axis of DataFrame. DataFrame.applymap : Apply a function elementwise on a whole DataFrame. Series.map : Apply a mapping correspondence on a :class:`~pandas.Series`. Notes ----- Use ``.pipe`` when chaining together functions that expect Series, DataFrames or GroupBy objects. Instead of writing >>> func(g(h(df), arg1=a), arg2=b, arg3=c) # doctest: +SKIP You can write >>> (df.pipe(h) ... .pipe(g, arg1=a) ... .pipe(func, arg2=b, arg3=c) ... ) # doctest: +SKIP If you have a function that takes the data as (say) the second argument, pass a tuple indicating which keyword expects the data. For example, suppose ``f`` takes its data as ``arg2``: >>> (df.pipe(h) ... .pipe(g, arg1=a) ... .pipe((func, 'arg2'), arg1=a, arg3=c) ... ) # doctest: +SKIP """ @Appender(_shared_docs["pipe"] % _shared_doc_kwargs) def pipe(self, func, *args, **kwargs): return com.pipe(self, func, *args, **kwargs) _shared_docs["aggregate"] = dedent( """ Aggregate using one or more operations over the specified axis. %(versionadded)s Parameters ---------- func : function, str, list or dict Function to use for aggregating the data. If a function, must either work when passed a %(klass)s or when passed to %(klass)s.apply. Accepted combinations are: - function - string function name - list of functions and/or function names, e.g. ``[np.sum, 'mean']`` - dict of axis labels -> functions, function names or list of such. %(axis)s *args Positional arguments to pass to `func`. **kwargs Keyword arguments to pass to `func`. Returns ------- scalar, Series or DataFrame The return can be: * scalar : when Series.agg is called with single function * Series : when DataFrame.agg is called with a single function * DataFrame : when DataFrame.agg is called with several functions Return scalar, Series or DataFrame. %(see_also)s Notes ----- `agg` is an alias for `aggregate`. Use the alias. A passed user-defined-function will be passed a Series for evaluation. %(examples)s""" ) _shared_docs[ "transform" ] = """ Call ``func`` on self producing a %(klass)s with transformed values. Produced %(klass)s will have same axis length as self. Parameters ---------- func : function, str, list or dict Function to use for transforming the data. If a function, must either work when passed a %(klass)s or when passed to %(klass)s.apply. Accepted combinations are: - function - string function name - list of functions and/or function names, e.g. ``[np.exp. 'sqrt']`` - dict of axis labels -> functions, function names or list of such. %(axis)s *args Positional arguments to pass to `func`. **kwargs Keyword arguments to pass to `func`. Returns ------- %(klass)s A %(klass)s that must have the same length as self. Raises ------ ValueError : If the returned %(klass)s has a different length than self. See Also -------- %(klass)s.agg : Only perform aggregating type operations. %(klass)s.apply : Invoke function on a %(klass)s. Examples -------- >>> df = pd.DataFrame({'A': range(3), 'B': range(1, 4)}) >>> df A B 0 0 1 1 1 2 2 2 3 >>> df.transform(lambda x: x + 1) A B 0 1 2 1 2 3 2 3 4 Even though the resulting %(klass)s must have the same length as the input %(klass)s, it is possible to provide several input functions: >>> s = pd.Series(range(3)) >>> s 0 0 1 1 2 2 dtype: int64 >>> s.transform([np.sqrt, np.exp]) sqrt exp 0 0.000000 1.000000 1 1.000000 2.718282 2 1.414214 7.389056 """ # ---------------------------------------------------------------------- # Attribute access def __finalize__( self: FrameOrSeries, other, method: Optional[str] = None, **kwargs ) -> FrameOrSeries: """ Propagate metadata from other to self. Parameters ---------- other : the object from which to get the attributes that we are going to propagate method : str, optional A passed method name providing context on where ``__finalize__`` was called. .. warning: The value passed as `method` are not currently considered stable across pandas releases. """ if isinstance(other, NDFrame): for name in other.attrs: self.attrs[name] = other.attrs[name] # For subclasses using _metadata. for name in self._metadata: assert isinstance(name, str) object.__setattr__(self, name, getattr(other, name, None)) return self def __getattr__(self, name: str): """ After regular attribute access, try looking up the name This allows simpler access to columns for interactive use. """ # Note: obj.x will always call obj.__getattribute__('x') prior to # calling obj.__getattr__('x'). if ( name in self._internal_names_set or name in self._metadata or name in self._accessors ): return object.__getattribute__(self, name) else: if self._info_axis._can_hold_identifiers_and_holds_name(name): return self[name] return object.__getattribute__(self, name) def __setattr__(self, name: str, value) -> None: """ After regular attribute access, try setting the name This allows simpler access to columns for interactive use. """ # first try regular attribute access via __getattribute__, so that # e.g. ``obj.x`` and ``obj.x = 4`` will always reference/modify # the same attribute. try: object.__getattribute__(self, name) return object.__setattr__(self, name, value) except AttributeError: pass # if this fails, go on to more involved attribute setting # (note that this matches __getattr__, above). if name in self._internal_names_set: object.__setattr__(self, name, value) elif name in self._metadata: object.__setattr__(self, name, value) else: try: existing = getattr(self, name) if isinstance(existing, Index): object.__setattr__(self, name, value) elif name in self._info_axis: self[name] = value else: object.__setattr__(self, name, value) except (AttributeError, TypeError): if isinstance(self, ABCDataFrame) and (is_list_like(value)): warnings.warn( "Pandas doesn't allow columns to be " "created via a new attribute name - see " "https://pandas.pydata.org/pandas-docs/" "stable/indexing.html#attribute-access", stacklevel=2, ) object.__setattr__(self, name, value) def _dir_additions(self): """ add the string-like attributes from the info_axis. If info_axis is a MultiIndex, it's first level values are used. """ additions = { c for c in self._info_axis.unique(level=0)[:100] if isinstance(c, str) and c.isidentifier() } return super()._dir_additions().union(additions) # ---------------------------------------------------------------------- # Consolidation of internals def _protect_consolidate(self, f): """ Consolidate _mgr -- if the blocks have changed, then clear the cache """ blocks_before = len(self._mgr.blocks) result = f() if len(self._mgr.blocks) != blocks_before: self._clear_item_cache() return result def _consolidate_inplace(self) -> None: """Consolidate data in place and return None""" def f(): self._mgr = self._mgr.consolidate() self._protect_consolidate(f) def _consolidate(self, inplace: bool_t = False): """ Compute NDFrame with "consolidated" internals (data of each dtype grouped together in a single ndarray). Parameters ---------- inplace : bool, default False If False return new object, otherwise modify existing object. Returns ------- consolidated : same type as caller """ inplace = validate_bool_kwarg(inplace, "inplace") if inplace: self._consolidate_inplace() else: f = lambda: self._mgr.consolidate() cons_data = self._protect_consolidate(f) return self._constructor(cons_data).__finalize__(self) @property def _is_mixed_type(self) -> bool_t: f = lambda: self._mgr.is_mixed_type return self._protect_consolidate(f) @property def _is_numeric_mixed_type(self) -> bool_t: f = lambda: self._mgr.is_numeric_mixed_type return self._protect_consolidate(f) def _check_inplace_setting(self, value) -> bool_t: """ check whether we allow in-place setting with this type of value """ if self._is_mixed_type: if not self._is_numeric_mixed_type: # allow an actual np.nan thru if is_float(value) and np.isnan(value): return True raise TypeError( "Cannot do inplace boolean setting on " "mixed-types with a non np.nan value" ) return True def _get_numeric_data(self): return self._constructor(self._mgr.get_numeric_data()).__finalize__(self) def _get_bool_data(self): return self._constructor(self._mgr.get_bool_data()).__finalize__(self) # ---------------------------------------------------------------------- # Internal Interface Methods @property def values(self) -> np.ndarray: """ Return a Numpy representation of the DataFrame. .. warning:: We recommend using :meth:`DataFrame.to_numpy` instead. Only the values in the DataFrame will be returned, the axes labels will be removed. Returns ------- numpy.ndarray The values of the DataFrame. See Also -------- DataFrame.to_numpy : Recommended alternative to this method. DataFrame.index : Retrieve the index labels. DataFrame.columns : Retrieving the column names. Notes ----- The dtype will be a lower-common-denominator dtype (implicit upcasting); that is to say if the dtypes (even of numeric types) are mixed, the one that accommodates all will be chosen. Use this with care if you are not dealing with the blocks. e.g. If the dtypes are float16 and float32, dtype will be upcast to float32. If dtypes are int32 and uint8, dtype will be upcast to int32. By :func:`numpy.find_common_type` convention, mixing int64 and uint64 will result in a float64 dtype. Examples -------- A DataFrame where all columns are the same type (e.g., int64) results in an array of the same type. >>> df = pd.DataFrame({'age': [ 3, 29], ... 'height': [94, 170], ... 'weight': [31, 115]}) >>> df age height weight 0 3 94 31 1 29 170 115 >>> df.dtypes age int64 height int64 weight int64 dtype: object >>> df.values array([[ 3, 94, 31], [ 29, 170, 115]]) A DataFrame with mixed type columns(e.g., str/object, int64, float32) results in an ndarray of the broadest type that accommodates these mixed types (e.g., object). >>> df2 = pd.DataFrame([('parrot', 24.0, 'second'), ... ('lion', 80.5, 1), ... ('monkey', np.nan, None)], ... columns=('name', 'max_speed', 'rank')) >>> df2.dtypes name object max_speed float64 rank object dtype: object >>> df2.values array([['parrot', 24.0, 'second'], ['lion', 80.5, 1], ['monkey', nan, None]], dtype=object) """ return self._mgr.as_array(transpose=self._AXIS_REVERSED) @property def _values(self) -> np.ndarray: """internal implementation""" return self.values @property def dtypes(self): """ Return the dtypes in the DataFrame. This returns a Series with the data type of each column. The result's index is the original DataFrame's columns. Columns with mixed types are stored with the ``object`` dtype. See :ref:`the User Guide <basics.dtypes>` for more. Returns ------- pandas.Series The data type of each column. Examples -------- >>> df = pd.DataFrame({'float': [1.0], ... 'int': [1], ... 'datetime': [pd.Timestamp('20180310')], ... 'string': ['foo']}) >>> df.dtypes float float64 int int64 datetime datetime64[ns] string object dtype: object """ from pandas import Series return Series(self._mgr.get_dtypes(), index=self._info_axis, dtype=np.object_) def _to_dict_of_blocks(self, copy: bool_t = True): """ Return a dict of dtype -> Constructor Types that each is a homogeneous dtype. Internal ONLY """ return { k: self._constructor(v).__finalize__(self) for k, v, in self._mgr.to_dict(copy=copy).items() } def astype( self: FrameOrSeries, dtype, copy: bool_t = True, errors: str = "raise" ) -> FrameOrSeries: """ Cast a pandas object to a specified dtype ``dtype``. Parameters ---------- dtype : data type, or dict of column name -> data type Use a numpy.dtype or Python type to cast entire pandas object to the same type. Alternatively, use {col: dtype, ...}, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame's columns to column-specific types. copy : bool, default True Return a copy when ``copy=True`` (be very careful setting ``copy=False`` as changes to values then may propagate to other pandas objects). errors : {'raise', 'ignore'}, default 'raise' Control raising of exceptions on invalid data for provided dtype. - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress exceptions. On error return original object. Returns ------- casted : same type as caller See Also -------- to_datetime : Convert argument to datetime. to_timedelta : Convert argument to timedelta. to_numeric : Convert argument to a numeric type. numpy.ndarray.astype : Cast a numpy array to a specified type. Examples -------- Create a DataFrame: >>> d = {'col1': [1, 2], 'col2': [3, 4]} >>> df = pd.DataFrame(data=d) >>> df.dtypes col1 int64 col2 int64 dtype: object Cast all columns to int32: >>> df.astype('int32').dtypes col1 int32 col2 int32 dtype: object Cast col1 to int32 using a dictionary: >>> df.astype({'col1': 'int32'}).dtypes col1 int32 col2 int64 dtype: object Create a series: >>> ser = pd.Series([1, 2], dtype='int32') >>> ser 0 1 1 2 dtype: int32 >>> ser.astype('int64') 0 1 1 2 dtype: int64 Convert to categorical type: >>> ser.astype('category') 0 1 1 2 dtype: category Categories (2, int64): [1, 2] Convert to ordered categorical type with custom ordering: >>> cat_dtype = pd.api.types.CategoricalDtype( ... categories=[2, 1], ordered=True) >>> ser.astype(cat_dtype) 0 1 1 2 dtype: category Categories (2, int64): [2 < 1] Note that using ``copy=False`` and changing data on a new pandas object may propagate changes: >>> s1 = pd.Series([1, 2]) >>> s2 = s1.astype('int64', copy=False) >>> s2[0] = 10 >>> s1 # note that s1[0] has changed too 0 10 1 2 dtype: int64 Create a series of dates: >>> ser_date = pd.Series(pd.date_range('20200101', periods=3)) >>> ser_date 0 2020-01-01 1 2020-01-02 2 2020-01-03 dtype: datetime64[ns] Datetimes are localized to UTC first before converting to the specified timezone: >>> ser_date.astype('datetime64[ns, US/Eastern]') 0 2019-12-31 19:00:00-05:00 1 2020-01-01 19:00:00-05:00 2 2020-01-02 19:00:00-05:00 dtype: datetime64[ns, US/Eastern] """ if is_dict_like(dtype): if self.ndim == 1: # i.e. Series if len(dtype) > 1 or self.name not in dtype: raise KeyError( "Only the Series name can be used for " "the key in Series dtype mappings." ) new_type = dtype[self.name] return self.astype(new_type, copy, errors) for col_name in dtype.keys(): if col_name not in self: raise KeyError( "Only a column name can be used for the " "key in a dtype mappings argument." ) results = [] for col_name, col in self.items(): if col_name in dtype: results.append( col.astype(dtype=dtype[col_name], copy=copy, errors=errors) ) else: results.append(col.copy() if copy else col) elif is_extension_array_dtype(dtype) and self.ndim > 1: # GH 18099/22869: columnwise conversion to extension dtype # GH 24704: use iloc to handle duplicate column names results = [ self.iloc[:, i].astype(dtype, copy=copy) for i in range(len(self.columns)) ] else: # else, only a single dtype is given new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors,) return self._constructor(new_data).__finalize__(self, method="astype") # GH 19920: retain column metadata after concat result = pd.concat(results, axis=1, copy=False) result.columns = self.columns return result def copy(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: """ Make a copy of this object's indices and data. When ``deep=True`` (default), a new object will be created with a copy of the calling object's data and indices. Modifications to the data or indices of the copy will not be reflected in the original object (see notes below). When ``deep=False``, a new object will be created without copying the calling object's data or index (only references to the data and index are copied). Any changes to the data of the original will be reflected in the shallow copy (and vice versa). Parameters ---------- deep : bool, default True Make a deep copy, including a copy of the data and the indices. With ``deep=False`` neither the indices nor the data are copied. Returns ------- copy : Series or DataFrame Object type matches caller. Notes ----- When ``deep=True``, data is copied but actual Python objects will not be copied recursively, only the reference to the object. This is in contrast to `copy.deepcopy` in the Standard Library, which recursively copies object data (see examples below). While ``Index`` objects are copied when ``deep=True``, the underlying numpy array is not copied for performance reasons. Since ``Index`` is immutable, the underlying data can be safely shared and a copy is not needed. Examples -------- >>> s = pd.Series([1, 2], index=["a", "b"]) >>> s a 1 b 2 dtype: int64 >>> s_copy = s.copy() >>> s_copy a 1 b 2 dtype: int64 **Shallow copy versus default (deep) copy:** >>> s = pd.Series([1, 2], index=["a", "b"]) >>> deep = s.copy() >>> shallow = s.copy(deep=False) Shallow copy shares data and index with original. >>> s is shallow False >>> s.values is shallow.values and s.index is shallow.index True Deep copy has own copy of data and index. >>> s is deep False >>> s.values is deep.values or s.index is deep.index False Updates to the data shared by shallow copy and original is reflected in both; deep copy remains unchanged. >>> s[0] = 3 >>> shallow[1] = 4 >>> s a 3 b 4 dtype: int64 >>> shallow a 3 b 4 dtype: int64 >>> deep a 1 b 2 dtype: int64 Note that when copying an object containing Python objects, a deep copy will copy the data, but will not do so recursively. Updating a nested data object will be reflected in the deep copy. >>> s = pd.Series([[1, 2], [3, 4]]) >>> deep = s.copy() >>> s[0][0] = 10 >>> s 0 [10, 2] 1 [3, 4] dtype: object >>> deep 0 [10, 2] 1 [3, 4] dtype: object """ data = self._mgr.copy(deep=deep) self._clear_item_cache() return self._constructor(data).__finalize__(self, method="copy") def __copy__(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: return self.copy(deep=deep) def __deepcopy__(self: FrameOrSeries, memo=None) -> FrameOrSeries: """ Parameters ---------- memo, default None Standard signature. Unused """ return self.copy(deep=True) def _convert( self: FrameOrSeries, datetime: bool_t = False, numeric: bool_t = False, timedelta: bool_t = False, coerce: bool_t = False, ) -> FrameOrSeries: """ Attempt to infer better dtype for object columns Parameters ---------- datetime : bool, default False If True, convert to date where possible. numeric : bool, default False If True, attempt to convert to numbers (including strings), with unconvertible values becoming NaN. timedelta : bool, default False If True, convert to timedelta where possible. coerce : bool, default False If True, force conversion with unconvertible values converted to nulls (NaN or NaT). Returns ------- converted : same as input object """ validate_bool_kwarg(datetime, "datetime") validate_bool_kwarg(numeric, "numeric") validate_bool_kwarg(timedelta, "timedelta") validate_bool_kwarg(coerce, "coerce") return self._constructor( self._mgr.convert( datetime=datetime, numeric=numeric, timedelta=timedelta, coerce=coerce, copy=True, ) ).__finalize__(self) def infer_objects(self: FrameOrSeries) -> FrameOrSeries: """ Attempt to infer better dtypes for object columns. Attempts soft conversion of object-dtyped columns, leaving non-object and unconvertible columns unchanged. The inference rules are the same as during normal Series/DataFrame construction. Returns ------- converted : same type as input object See Also -------- to_datetime : Convert argument to datetime. to_timedelta : Convert argument to timedelta. to_numeric : Convert argument to numeric type. convert_dtypes : Convert argument to best possible dtype. Examples -------- >>> df = pd.DataFrame({"A": ["a", 1, 2, 3]}) >>> df = df.iloc[1:] >>> df A 1 1 2 2 3 3 >>> df.dtypes A object dtype: object >>> df.infer_objects().dtypes A int64 dtype: object """ # numeric=False necessary to only soft convert; # python objects will still be converted to # native numpy numeric types return self._constructor( self._mgr.convert( datetime=True, numeric=False, timedelta=True, coerce=False, copy=True ) ).__finalize__(self, method="infer_objects") def convert_dtypes( self: FrameOrSeries, infer_objects: bool_t = True, convert_string: bool_t = True, convert_integer: bool_t = True, convert_boolean: bool_t = True, ) -> FrameOrSeries: """ Convert columns to best possible dtypes using dtypes supporting ``pd.NA``. .. versionadded:: 1.0.0 Parameters ---------- infer_objects : bool, default True Whether object dtypes should be converted to the best possible types. convert_string : bool, default True Whether object dtypes should be converted to ``StringDtype()``. convert_integer : bool, default True Whether, if possible, conversion can be done to integer extension types. convert_boolean : bool, defaults True Whether object dtypes should be converted to ``BooleanDtypes()``. Returns ------- Series or DataFrame Copy of input object with new dtype. See Also -------- infer_objects : Infer dtypes of objects. to_datetime : Convert argument to datetime. to_timedelta : Convert argument to timedelta. to_numeric : Convert argument to a numeric type. Notes ----- By default, ``convert_dtypes`` will attempt to convert a Series (or each Series in a DataFrame) to dtypes that support ``pd.NA``. By using the options ``convert_string``, ``convert_integer``, and ``convert_boolean``, it is possible to turn off individual conversions to ``StringDtype``, the integer extension types or ``BooleanDtype``, respectively. For object-dtyped columns, if ``infer_objects`` is ``True``, use the inference rules as during normal Series/DataFrame construction. Then, if possible, convert to ``StringDtype``, ``BooleanDtype`` or an appropriate integer extension type, otherwise leave as ``object``. If the dtype is integer, convert to an appropriate integer extension type. If the dtype is numeric, and consists of all integers, convert to an appropriate integer extension type. In the future, as new dtypes are added that support ``pd.NA``, the results of this method will change to support those new dtypes. Examples -------- >>> df = pd.DataFrame( ... { ... "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")), ... "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")), ... "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")), ... "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")), ... "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")), ... "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")), ... } ... ) Start with a DataFrame with default dtypes. >>> df a b c d e f 0 1 x True h 10.0 NaN 1 2 y False i NaN 100.5 2 3 z NaN NaN 20.0 200.0 >>> df.dtypes a int32 b object c object d object e float64 f float64 dtype: object Convert the DataFrame to use best possible dtypes. >>> dfn = df.convert_dtypes() >>> dfn a b c d e f 0 1 x True h 10 NaN 1 2 y False i <NA> 100.5 2 3 z <NA> <NA> 20 200.0 >>> dfn.dtypes a Int32 b string c boolean d string e Int64 f float64 dtype: object Start with a Series of strings and missing data represented by ``np.nan``. >>> s = pd.Series(["a", "b", np.nan]) >>> s 0 a 1 b 2 NaN dtype: object Obtain a Series with dtype ``StringDtype``. >>> s.convert_dtypes() 0 a 1 b 2 <NA> dtype: string """ if self.ndim == 1: return self._convert_dtypes( infer_objects, convert_string, convert_integer, convert_boolean ) else: results = [ col._convert_dtypes( infer_objects, convert_string, convert_integer, convert_boolean ) for col_name, col in self.items() ] result = pd.concat(results, axis=1, copy=False) return result # ---------------------------------------------------------------------- # Filling NA's @doc(**_shared_doc_kwargs) def fillna( self: FrameOrSeries, value=None, method=None, axis=None, inplace: bool_t = False, limit=None, downcast=None, ) -> Optional[FrameOrSeries]: """ Fill NA/NaN values using the specified method. Parameters ---------- value : scalar, dict, Series, or DataFrame Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of values specifying which value to use for each index (for a Series) or column (for a DataFrame). Values not in the dict/Series/DataFrame will not be filled. This value cannot be a list. method : {{'backfill', 'bfill', 'pad', 'ffill', None}}, default None Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use next valid observation to fill gap. axis : {axes_single_arg} Axis along which to fill missing values. inplace : bool, default False If True, fill in-place. Note: this will modify any other views on this object (e.g., a no-copy slice for a column in a DataFrame). limit : int, default None If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None. downcast : dict, default is None A dict of item->dtype of what to downcast if possible, or the string 'infer' which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible). Returns ------- {klass} or None Object with missing values filled or None if ``inplace=True``. See Also -------- interpolate : Fill NaN values using interpolation. reindex : Conform object to new index. asfreq : Convert TimeSeries to specified frequency. Examples -------- >>> df = pd.DataFrame([[np.nan, 2, np.nan, 0], ... [3, 4, np.nan, 1], ... [np.nan, np.nan, np.nan, 5], ... [np.nan, 3, np.nan, 4]], ... columns=list('ABCD')) >>> df A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 2 NaN NaN NaN 5 3 NaN 3.0 NaN 4 Replace all NaN elements with 0s. >>> df.fillna(0) A B C D 0 0.0 2.0 0.0 0 1 3.0 4.0 0.0 1 2 0.0 0.0 0.0 5 3 0.0 3.0 0.0 4 We can also propagate non-null values forward or backward. >>> df.fillna(method='ffill') A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 2 3.0 4.0 NaN 5 3 3.0 3.0 NaN 4 Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1, 2, and 3 respectively. >>> values = {{'A': 0, 'B': 1, 'C': 2, 'D': 3}} >>> df.fillna(value=values) A B C D 0 0.0 2.0 2.0 0 1 3.0 4.0 2.0 1 2 0.0 1.0 2.0 5 3 0.0 3.0 2.0 4 Only replace the first NaN element. >>> df.fillna(value=values, limit=1) A B C D 0 0.0 2.0 2.0 0 1 3.0 4.0 NaN 1 2 NaN 1.0 NaN 5 3 NaN 3.0 NaN 4 """ inplace = validate_bool_kwarg(inplace, "inplace") value, method = validate_fillna_kwargs(value, method) # set the default here, so functions examining the signaure # can detect if something was set (e.g. in groupby) (GH9221) if axis is None: axis = 0 axis = self._get_axis_number(axis) if value is None: if self._is_mixed_type and axis == 1: if inplace: raise NotImplementedError() result = self.T.fillna(method=method, limit=limit).T # need to downcast here because of all of the transposes result._mgr = result._mgr.downcast() return result new_data = self._mgr.interpolate( method=method, axis=axis, limit=limit, inplace=inplace, coerce=True, downcast=downcast, ) else: if self.ndim == 1: if isinstance(value, (dict, ABCSeries)): value = create_series_with_explicit_dtype( value, dtype_if_empty=object ) value = value.reindex(self.index, copy=False) value = value._values elif not is_list_like(value): pass else: raise TypeError( '"value" parameter must be a scalar, dict ' "or Series, but you passed a " f'"{type(value).__name__}"' ) new_data = self._mgr.fillna( value=value, limit=limit, inplace=inplace, downcast=downcast ) elif isinstance(value, (dict, ABCSeries)): if axis == 1: raise NotImplementedError( "Currently only can fill " "with dict/Series column " "by column" ) result = self if inplace else self.copy() for k, v in value.items(): if k not in result: continue obj = result[k] obj.fillna(v, limit=limit, inplace=True, downcast=downcast) return result if not inplace else None elif not is_list_like(value): new_data = self._mgr.fillna( value=value, limit=limit, inplace=inplace, downcast=downcast ) elif isinstance(value, ABCDataFrame) and self.ndim == 2: new_data = self.where(self.notna(), value)._data else: raise ValueError(f"invalid fill value with a {type(value)}") result = self._constructor(new_data) if inplace: return self._update_inplace(result) else: return result.__finalize__(self, method="fillna") def ffill( self: FrameOrSeries, axis=None, inplace: bool_t = False, limit=None, downcast=None, ) -> Optional[FrameOrSeries]: """ Synonym for :meth:`DataFrame.fillna` with ``method='ffill'``. Returns ------- %(klass)s or None Object with missing values filled or None if ``inplace=True``. """ return self.fillna( method="ffill", axis=axis, inplace=inplace, limit=limit, downcast=downcast ) def bfill( self: FrameOrSeries, axis=None, inplace: bool_t = False, limit=None, downcast=None, ) -> Optional[FrameOrSeries]: """ Synonym for :meth:`DataFrame.fillna` with ``method='bfill'``. Returns ------- %(klass)s or None Object with missing values filled or None if ``inplace=True``. """ return self.fillna( method="bfill", axis=axis, inplace=inplace, limit=limit, downcast=downcast ) @doc(klass=_shared_doc_kwargs["klass"]) def replace( self, to_replace=None, value=None, inplace=False, limit=None, regex=False, method="pad", ): """ Replace values given in `to_replace` with `value`. Values of the {klass} are replaced with other values dynamically. This differs from updating with ``.loc`` or ``.iloc``, which require you to specify a location to update with some value. Parameters ---------- to_replace : str, regex, list, dict, Series, int, float, or None How to find the values that will be replaced. * numeric, str or regex: - numeric: numeric values equal to `to_replace` will be replaced with `value` - str: string exactly matching `to_replace` will be replaced with `value` - regex: regexs matching `to_replace` will be replaced with `value` * list of str, regex, or numeric: - First, if `to_replace` and `value` are both lists, they **must** be the same length. - Second, if ``regex=True`` then all of the strings in **both** lists will be interpreted as regexs otherwise they will match directly. This doesn't matter much for `value` since there are only a few possible substitution regexes you can use. - str, regex and numeric rules apply as above. * dict: - Dicts can be used to specify different replacement values for different existing values. For example, ``{{'a': 'b', 'y': 'z'}}`` replaces the value 'a' with 'b' and 'y' with 'z'. To use a dict in this way the `value` parameter should be `None`. - For a DataFrame a dict can specify that different values should be replaced in different columns. For example, ``{{'a': 1, 'b': 'z'}}`` looks for the value 1 in column 'a' and the value 'z' in column 'b' and replaces these values with whatever is specified in `value`. The `value` parameter should not be ``None`` in this case. You can treat this as a special case of passing two lists except that you are specifying the column to search in. - For a DataFrame nested dictionaries, e.g., ``{{'a': {{'b': np.nan}}}}``, are read as follows: look in column 'a' for the value 'b' and replace it with NaN. The `value` parameter should be ``None`` to use a nested dict in this way. You can nest regular expressions as well. Note that column names (the top-level dictionary keys in a nested dictionary) **cannot** be regular expressions. * None: - This means that the `regex` argument must be a string, compiled regular expression, or list, dict, ndarray or Series of such elements. If `value` is also ``None`` then this **must** be a nested dictionary or Series. See the examples section for examples of each of these. value : scalar, dict, list, str, regex, default None Value to replace any values matching `to_replace` with. For a DataFrame a dict of values can be used to specify which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed. inplace : bool, default False If True, in place. Note: this will modify any other views on this object (e.g. a column from a DataFrame). Returns the caller if this is True. limit : int, default None Maximum size gap to forward or backward fill. regex : bool or same types as `to_replace`, default False Whether to interpret `to_replace` and/or `value` as regular expressions. If this is ``True`` then `to_replace` *must* be a string. Alternatively, this could be a regular expression or a list, dict, or array of regular expressions in which case `to_replace` must be ``None``. method : {{'pad', 'ffill', 'bfill', `None`}} The method to use when for replacement, when `to_replace` is a scalar, list or tuple and `value` is ``None``. .. versionchanged:: 0.23.0 Added to DataFrame. Returns ------- {klass} Object after replacement. Raises ------ AssertionError * If `regex` is not a ``bool`` and `to_replace` is not ``None``. TypeError * If `to_replace` is not a scalar, array-like, ``dict``, or ``None`` * If `to_replace` is a ``dict`` and `value` is not a ``list``, ``dict``, ``ndarray``, or ``Series`` * If `to_replace` is ``None`` and `regex` is not compilable into a regular expression or is a list, dict, ndarray, or Series. * When replacing multiple ``bool`` or ``datetime64`` objects and the arguments to `to_replace` does not match the type of the value being replaced ValueError * If a ``list`` or an ``ndarray`` is passed to `to_replace` and `value` but they are not the same length. See Also -------- {klass}.fillna : Fill NA values. {klass}.where : Replace values based on boolean condition. Series.str.replace : Simple string replacement. Notes ----- * Regex substitution is performed under the hood with ``re.sub``. The rules for substitution for ``re.sub`` are the same. * Regular expressions will only substitute on strings, meaning you cannot provide, for example, a regular expression matching floating point numbers and expect the columns in your frame that have a numeric dtype to be matched. However, if those floating point numbers *are* strings, then you can do this. * This method has *a lot* of options. You are encouraged to experiment and play with this method to gain intuition about how it works. * When dict is used as the `to_replace` value, it is like key(s) in the dict are the to_replace part and value(s) in the dict are the value parameter. Examples -------- **Scalar `to_replace` and `value`** >>> s = pd.Series([0, 1, 2, 3, 4]) >>> s.replace(0, 5) 0 5 1 1 2 2 3 3 4 4 dtype: int64 >>> df = pd.DataFrame({{'A': [0, 1, 2, 3, 4], ... 'B': [5, 6, 7, 8, 9], ... 'C': ['a', 'b', 'c', 'd', 'e']}}) >>> df.replace(0, 5) A B C 0 5 5 a 1 1 6 b 2 2 7 c 3 3 8 d 4 4 9 e **List-like `to_replace`** >>> df.replace([0, 1, 2, 3], 4) A B C 0 4 5 a 1 4 6 b 2 4 7 c 3 4 8 d 4 4 9 e >>> df.replace([0, 1, 2, 3], [4, 3, 2, 1]) A B C 0 4 5 a 1 3 6 b 2 2 7 c 3 1 8 d 4 4 9 e >>> s.replace([1, 2], method='bfill') 0 0 1 3 2 3 3 3 4 4 dtype: int64 **dict-like `to_replace`** >>> df.replace({{0: 10, 1: 100}}) A B C 0 10 5 a 1 100 6 b 2 2 7 c 3 3 8 d 4 4 9 e >>> df.replace({{'A': 0, 'B': 5}}, 100) A B C 0 100 100 a 1 1 6 b 2 2 7 c 3 3 8 d 4 4 9 e >>> df.replace({{'A': {{0: 100, 4: 400}}}}) A B C 0 100 5 a 1 1 6 b 2 2 7 c 3 3 8 d 4 400 9 e **Regular expression `to_replace`** >>> df = pd.DataFrame({{'A': ['bat', 'foo', 'bait'], ... 'B': ['abc', 'bar', 'xyz']}}) >>> df.replace(to_replace=r'^ba.$', value='new', regex=True) A B 0 new abc 1 foo new 2 bait xyz >>> df.replace({{'A': r'^ba.$'}}, {{'A': 'new'}}, regex=True) A B 0 new abc 1 foo bar 2 bait xyz >>> df.replace(regex=r'^ba.$', value='new') A B 0 new abc 1 foo new 2 bait xyz >>> df.replace(regex={{r'^ba.$': 'new', 'foo': 'xyz'}}) A B 0 new abc 1 xyz new 2 bait xyz >>> df.replace(regex=[r'^ba.$', 'foo'], value='new') A B 0 new abc 1 new new 2 bait xyz Note that when replacing multiple ``bool`` or ``datetime64`` objects, the data types in the `to_replace` parameter must match the data type of the value being replaced: >>> df = pd.DataFrame({{'A': [True, False, True], ... 'B': [False, True, False]}}) >>> df.replace({{'a string': 'new value', True: False}}) # raises Traceback (most recent call last): ... TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str' This raises a ``TypeError`` because one of the ``dict`` keys is not of the correct type for replacement. Compare the behavior of ``s.replace({{'a': None}})`` and ``s.replace('a', None)`` to understand the peculiarities of the `to_replace` parameter: >>> s = pd.Series([10, 'a', 'a', 'b', 'a']) When one uses a dict as the `to_replace` value, it is like the value(s) in the dict are equal to the `value` parameter. ``s.replace({{'a': None}})`` is equivalent to ``s.replace(to_replace={{'a': None}}, value=None, method=None)``: >>> s.replace({{'a': None}}) 0 10 1 None 2 None 3 b 4 None dtype: object When ``value=None`` and `to_replace` is a scalar, list or tuple, `replace` uses the method parameter (default 'pad') to do the replacement. So this is why the 'a' values are being replaced by 10 in rows 1 and 2 and 'b' in row 4 in this case. The command ``s.replace('a', None)`` is actually equivalent to ``s.replace(to_replace='a', value=None, method='pad')``: >>> s.replace('a', None) 0 10 1 10 2 10 3 b 4 b dtype: object """ if not ( is_scalar(to_replace) or is_re_compilable(to_replace) or is_list_like(to_replace) ): raise TypeError( "Expecting 'to_replace' to be either a scalar, array-like, " "dict or None, got invalid type " f"{repr(type(to_replace).__name__)}" ) inplace = validate_bool_kwarg(inplace, "inplace") if not is_bool(regex) and to_replace is not None: raise AssertionError("'to_replace' must be 'None' if 'regex' is not a bool") if value is None: # passing a single value that is scalar like # when value is None (GH5319), for compat if not is_dict_like(to_replace) and not is_dict_like(regex): to_replace = [to_replace] if isinstance(to_replace, (tuple, list)): if isinstance(self, ABCDataFrame): return self.apply( _single_replace, args=(to_replace, method, inplace, limit) ) return _single_replace(self, to_replace, method, inplace, limit) if not is_dict_like(to_replace): if not is_dict_like(regex): raise TypeError( 'If "to_replace" and "value" are both None ' 'and "to_replace" is not a list, then ' "regex must be a mapping" ) to_replace = regex regex = True items = list(to_replace.items()) keys, values = zip(*items) if items else ([], []) are_mappings = [is_dict_like(v) for v in values] if any(are_mappings): if not all(are_mappings): raise TypeError( "If a nested mapping is passed, all values " "of the top level mapping must be mappings" ) # passed a nested dict/Series to_rep_dict = {} value_dict = {} for k, v in items: keys, values = list(zip(*v.items())) or ([], []) to_rep_dict[k] = list(keys) value_dict[k] = list(values) to_replace, value = to_rep_dict, value_dict else: to_replace, value = keys, values return self.replace( to_replace, value, inplace=inplace, limit=limit, regex=regex ) else: # need a non-zero len on all axes if not self.size: return self if is_dict_like(to_replace): if is_dict_like(value): # {'A' : NA} -> {'A' : 0} # Note: Checking below for `in foo.keys()` instead of # `in foo`is needed for when we have a Series and not dict mapping = { col: (to_replace[col], value[col]) for col in to_replace.keys() if col in value.keys() and col in self } return self._replace_columnwise(mapping, inplace, regex) # {'A': NA} -> 0 elif not is_list_like(value): # Operate column-wise if self.ndim == 1: raise ValueError( "Series.replace cannot use dict-like to_replace " "and non-None value" ) mapping = { col: (to_rep, value) for col, to_rep in to_replace.items() } return self._replace_columnwise(mapping, inplace, regex) else: raise TypeError("value argument must be scalar, dict, or Series") elif is_list_like(to_replace): # [NA, ''] -> [0, 'missing'] if is_list_like(value): if len(to_replace) != len(value): raise ValueError( f"Replacement lists must match in length. " f"Expecting {len(to_replace)} got {len(value)} " ) new_data = self._mgr.replace_list( src_list=to_replace, dest_list=value, inplace=inplace, regex=regex, ) else: # [NA, ''] -> 0 new_data = self._mgr.replace( to_replace=to_replace, value=value, inplace=inplace, regex=regex ) elif to_replace is None: if not ( is_re_compilable(regex) or is_list_like(regex) or is_dict_like(regex) ): raise TypeError( f"'regex' must be a string or a compiled regular expression " f"or a list or dict of strings or regular expressions, " f"you passed a {repr(type(regex).__name__)}" ) return self.replace( regex, value, inplace=inplace, limit=limit, regex=True ) else: # dest iterable dict-like if is_dict_like(value): # NA -> {'A' : 0, 'B' : -1} # Operate column-wise if self.ndim == 1: raise ValueError( "Series.replace cannot use dict-value and " "non-None to_replace" ) mapping = {col: (to_replace, val) for col, val in value.items()} return self._replace_columnwise(mapping, inplace, regex) elif not is_list_like(value): # NA -> 0 new_data = self._mgr.replace( to_replace=to_replace, value=value, inplace=inplace, regex=regex ) else: raise TypeError( f'Invalid "to_replace" type: {repr(type(to_replace).__name__)}' ) result = self._constructor(new_data) if inplace: return self._update_inplace(result) else: return result.__finalize__(self, method="replace") _shared_docs[ "interpolate" ] = """ Please note that only ``method='linear'`` is supported for DataFrame/Series with a MultiIndex. Parameters ---------- method : str, default 'linear' Interpolation technique to use. One of: * 'linear': Ignore the index and treat the values as equally spaced. This is the only method supported on MultiIndexes. * 'time': Works on daily and higher resolution data to interpolate given length of interval. * 'index', 'values': use the actual numerical values of the index. * 'pad': Fill in NaNs using existing values. * 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'spline', 'barycentric', 'polynomial': Passed to `scipy.interpolate.interp1d`. These methods use the numerical values of the index. Both 'polynomial' and 'spline' require that you also specify an `order` (int), e.g. ``df.interpolate(method='polynomial', order=5)``. * 'krogh', 'piecewise_polynomial', 'spline', 'pchip', 'akima', 'cubicspline': Wrappers around the SciPy interpolation methods of similar names. See `Notes`. * 'from_derivatives': Refers to `scipy.interpolate.BPoly.from_derivatives` which replaces 'piecewise_polynomial' interpolation method in scipy 0.18. axis : {0 or 'index', 1 or 'columns', None}, default None Axis to interpolate along. limit : int, optional Maximum number of consecutive NaNs to fill. Must be greater than 0. inplace : bool, default False Update the data in place if possible. limit_direction : {'forward', 'backward', 'both'}, default 'forward' If limit is specified, consecutive NaNs will be filled in this direction. limit_area : {`None`, 'inside', 'outside'}, default None If limit is specified, consecutive NaNs will be filled with this restriction. * ``None``: No fill restriction. * 'inside': Only fill NaNs surrounded by valid values (interpolate). * 'outside': Only fill NaNs outside valid values (extrapolate). .. versionadded:: 0.23.0 downcast : optional, 'infer' or None, defaults to None Downcast dtypes if possible. **kwargs Keyword arguments to pass on to the interpolating function. Returns ------- Series or DataFrame Returns the same object type as the caller, interpolated at some or all ``NaN`` values. See Also -------- fillna : Fill missing values using different methods. scipy.interpolate.Akima1DInterpolator : Piecewise cubic polynomials (Akima interpolator). scipy.interpolate.BPoly.from_derivatives : Piecewise polynomial in the Bernstein basis. scipy.interpolate.interp1d : Interpolate a 1-D function. scipy.interpolate.KroghInterpolator : Interpolate polynomial (Krogh interpolator). scipy.interpolate.PchipInterpolator : PCHIP 1-d monotonic cubic interpolation. scipy.interpolate.CubicSpline : Cubic spline data interpolator. Notes ----- The 'krogh', 'piecewise_polynomial', 'spline', 'pchip' and 'akima' methods are wrappers around the respective SciPy implementations of similar names. These use the actual numerical values of the index. For more information on their behavior, see the `SciPy documentation <https://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation>`__ and `SciPy tutorial <https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html>`__. Examples -------- Filling in ``NaN`` in a :class:`~pandas.Series` via linear interpolation. >>> s = pd.Series([0, 1, np.nan, 3]) >>> s 0 0.0 1 1.0 2 NaN 3 3.0 dtype: float64 >>> s.interpolate() 0 0.0 1 1.0 2 2.0 3 3.0 dtype: float64 Filling in ``NaN`` in a Series by padding, but filling at most two consecutive ``NaN`` at a time. >>> s = pd.Series([np.nan, "single_one", np.nan, ... "fill_two_more", np.nan, np.nan, np.nan, ... 4.71, np.nan]) >>> s 0 NaN 1 single_one 2 NaN 3 fill_two_more 4 NaN 5 NaN 6 NaN 7 4.71 8 NaN dtype: object >>> s.interpolate(method='pad', limit=2) 0 NaN 1 single_one 2 single_one 3 fill_two_more 4 fill_two_more 5 fill_two_more 6 NaN 7 4.71 8 4.71 dtype: object Filling in ``NaN`` in a Series via polynomial interpolation or splines: Both 'polynomial' and 'spline' methods require that you also specify an ``order`` (int). >>> s = pd.Series([0, 2, np.nan, 8]) >>> s.interpolate(method='polynomial', order=2) 0 0.000000 1 2.000000 2 4.666667 3 8.000000 dtype: float64 Fill the DataFrame forward (that is, going down) along each column using linear interpolation. Note how the last entry in column 'a' is interpolated differently, because there is no entry after it to use for interpolation. Note how the first entry in column 'b' remains ``NaN``, because there is no entry before it to use for interpolation. >>> df = pd.DataFrame([(0.0, np.nan, -1.0, 1.0), ... (np.nan, 2.0, np.nan, np.nan), ... (2.0, 3.0, np.nan, 9.0), ... (np.nan, 4.0, -4.0, 16.0)], ... columns=list('abcd')) >>> df a b c d 0 0.0 NaN -1.0 1.0 1 NaN 2.0 NaN NaN 2 2.0 3.0 NaN 9.0 3 NaN 4.0 -4.0 16.0 >>> df.interpolate(method='linear', limit_direction='forward', axis=0) a b c d 0 0.0 NaN -1.0 1.0 1 1.0 2.0 -2.0 5.0 2 2.0 3.0 -3.0 9.0 3 2.0 4.0 -4.0 16.0 Using polynomial interpolation. >>> df['d'].interpolate(method='polynomial', order=2) 0 1.0 1 4.0 2 9.0 3 16.0 Name: d, dtype: float64 """ @Appender(_shared_docs["interpolate"] % _shared_doc_kwargs) def interpolate( self, method="linear", axis=0, limit=None, inplace=False, limit_direction="forward", limit_area=None, downcast=None, **kwargs, ): """ Interpolate values according to different methods. """ inplace = validate_bool_kwarg(inplace, "inplace") axis = self._get_axis_number(axis) if axis == 0: df = self else: df = self.T if isinstance(df.index, MultiIndex) and method != "linear": raise ValueError( "Only `method=linear` interpolation is supported on MultiIndexes." ) if df.ndim == 2 and np.all(df.dtypes == np.dtype(object)): raise TypeError( "Cannot interpolate with all object-dtype columns " "in the DataFrame. Try setting at least one " "column to a numeric dtype." ) # create/use the index if method == "linear": # prior default index = np.arange(len(df.index)) else: index = df.index methods = {"index", "values", "nearest", "time"} is_numeric_or_datetime = ( is_numeric_dtype(index.dtype) or is_datetime64_any_dtype(index.dtype) or is_timedelta64_dtype(index.dtype) ) if method not in methods and not is_numeric_or_datetime: raise ValueError( "Index column must be numeric or datetime type when " f"using {method} method other than linear. " "Try setting a numeric or datetime index column before " "interpolating." ) if isna(index).any(): raise NotImplementedError( "Interpolation with NaNs in the index " "has not been implemented. Try filling " "those NaNs before interpolating." ) data = df._mgr new_data = data.interpolate( method=method, axis=self._info_axis_number, index=index, limit=limit, limit_direction=limit_direction, limit_area=limit_area, inplace=inplace, downcast=downcast, **kwargs, ) result = self._constructor(new_data) if axis == 1: result = result.T if inplace: return self._update_inplace(result) else: return result.__finalize__(self, method="interpolate") # ---------------------------------------------------------------------- # Timeseries methods Methods def asof(self, where, subset=None): """ Return the last row(s) without any NaNs before `where`. The last row (for each element in `where`, if list) without any NaN is taken. In case of a :class:`~pandas.DataFrame`, the last row without NaN considering only the subset of columns (if not `None`) If there is no good value, NaN is returned for a Series or a Series of NaN values for a DataFrame Parameters ---------- where : date or array-like of dates Date(s) before which the last row(s) are returned. subset : str or array-like of str, default `None` For DataFrame, if not `None`, only use these columns to check for NaNs. Returns ------- scalar, Series, or DataFrame The return can be: * scalar : when `self` is a Series and `where` is a scalar * Series: when `self` is a Series and `where` is an array-like, or when `self` is a DataFrame and `where` is a scalar * DataFrame : when `self` is a DataFrame and `where` is an array-like Return scalar, Series, or DataFrame. See Also -------- merge_asof : Perform an asof merge. Similar to left join. Notes ----- Dates are assumed to be sorted. Raises if this is not the case. Examples -------- A Series and a scalar `where`. >>> s = pd.Series([1, 2, np.nan, 4], index=[10, 20, 30, 40]) >>> s 10 1.0 20 2.0 30 NaN 40 4.0 dtype: float64 >>> s.asof(20) 2.0 For a sequence `where`, a Series is returned. The first value is NaN, because the first element of `where` is before the first index value. >>> s.asof([5, 20]) 5 NaN 20 2.0 dtype: float64 Missing values are not considered. The following is ``2.0``, not NaN, even though NaN is at the index location for ``30``. >>> s.asof(30) 2.0 Take all columns into consideration >>> df = pd.DataFrame({'a': [10, 20, 30, 40, 50], ... 'b': [None, None, None, None, 500]}, ... index=pd.DatetimeIndex(['2018-02-27 09:01:00', ... '2018-02-27 09:02:00', ... '2018-02-27 09:03:00', ... '2018-02-27 09:04:00', ... '2018-02-27 09:05:00'])) >>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30', ... '2018-02-27 09:04:30'])) a b 2018-02-27 09:03:30 NaN NaN 2018-02-27 09:04:30 NaN NaN Take a single column into consideration >>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30', ... '2018-02-27 09:04:30']), ... subset=['a']) a b 2018-02-27 09:03:30 30.0 NaN 2018-02-27 09:04:30 40.0 NaN """ if isinstance(where, str): where = Timestamp(where) if not self.index.is_monotonic: raise ValueError("asof requires a sorted index") is_series = isinstance(self, ABCSeries) if is_series: if subset is not None: raise ValueError("subset is not valid for Series") else: if subset is None: subset = self.columns if not is_list_like(subset): subset = [subset] is_list = is_list_like(where) if not is_list: start = self.index[0] if isinstance(self.index, PeriodIndex): where = Period(where, freq=self.index.freq) if where < start: if not is_series: return self._constructor_sliced( index=self.columns, name=where, dtype=np.float64 ) return np.nan # It's always much faster to use a *while* loop here for # Series than pre-computing all the NAs. However a # *while* loop is extremely expensive for DataFrame # so we later pre-compute all the NAs and use the same # code path whether *where* is a scalar or list. # See PR: https://github.com/pandas-dev/pandas/pull/14476 if is_series: loc = self.index.searchsorted(where, side="right") if loc > 0: loc -= 1 values = self._values while loc > 0 and isna(values[loc]): loc -= 1 return values[loc] if not isinstance(where, Index): where = Index(where) if is_list else Index([where]) nulls = self.isna() if is_series else self[subset].isna().any(1) if nulls.all(): if is_series: return self._constructor(np.nan, index=where, name=self.name) elif is_list: return self._constructor(np.nan, index=where, columns=self.columns) else: return self._constructor_sliced( np.nan, index=self.columns, name=where[0] ) locs = self.index.asof_locs(where, ~(nulls._values)) # mask the missing missing = locs == -1 data = self.take(locs) data.index = where data.loc[missing] = np.nan return data if is_list else data.iloc[-1] # ---------------------------------------------------------------------- # Action Methods _shared_docs[ "isna" ] = """ Detect missing values. Return a boolean same-sized object indicating if the values are NA. NA values, such as None or :attr:`numpy.NaN`, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings ``''`` or :attr:`numpy.inf` are not considered NA values (unless you set ``pandas.options.mode.use_inf_as_na = True``). Returns ------- %(klass)s Mask of bool values for each element in %(klass)s that indicates whether an element is not an NA value. See Also -------- %(klass)s.isnull : Alias of isna. %(klass)s.notna : Boolean inverse of isna. %(klass)s.dropna : Omit axes labels with missing values. isna : Top-level isna. Examples -------- Show which entries in a DataFrame are NA. >>> df = pd.DataFrame({'age': [5, 6, np.NaN], ... 'born': [pd.NaT, pd.Timestamp('1939-05-27'), ... pd.Timestamp('1940-04-25')], ... 'name': ['Alfred', 'Batman', ''], ... 'toy': [None, 'Batmobile', 'Joker']}) >>> df age born name toy 0 5.0 NaT Alfred None 1 6.0 1939-05-27 Batman Batmobile 2 NaN 1940-04-25 Joker >>> df.isna() age born name toy 0 False True False True 1 False False False False 2 True False False False Show which entries in a Series are NA. >>> ser = pd.Series([5, 6, np.NaN]) >>> ser 0 5.0 1 6.0 2 NaN dtype: float64 >>> ser.isna() 0 False 1 False 2 True dtype: bool """ @Appender(_shared_docs["isna"] % _shared_doc_kwargs) def isna(self: FrameOrSeries) -> FrameOrSeries: return isna(self).__finalize__(self, method="isna") @Appender(_shared_docs["isna"] % _shared_doc_kwargs) def isnull(self: FrameOrSeries) -> FrameOrSeries: return isna(self).__finalize__(self, method="isnull") _shared_docs[ "notna" ] = """ Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to True. Characters such as empty strings ``''`` or :attr:`numpy.inf` are not considered NA values (unless you set ``pandas.options.mode.use_inf_as_na = True``). NA values, such as None or :attr:`numpy.NaN`, get mapped to False values. Returns ------- %(klass)s Mask of bool values for each element in %(klass)s that indicates whether an element is not an NA value. See Also -------- %(klass)s.notnull : Alias of notna. %(klass)s.isna : Boolean inverse of notna. %(klass)s.dropna : Omit axes labels with missing values. notna : Top-level notna. Examples -------- Show which entries in a DataFrame are not NA. >>> df = pd.DataFrame({'age': [5, 6, np.NaN], ... 'born': [pd.NaT, pd.Timestamp('1939-05-27'), ... pd.Timestamp('1940-04-25')], ... 'name': ['Alfred', 'Batman', ''], ... 'toy': [None, 'Batmobile', 'Joker']}) >>> df age born name toy 0 5.0 NaT Alfred None 1 6.0 1939-05-27 Batman Batmobile 2 NaN 1940-04-25 Joker >>> df.notna() age born name toy 0 True False True False 1 True True True True 2 False True True True Show which entries in a Series are not NA. >>> ser = pd.Series([5, 6, np.NaN]) >>> ser 0 5.0 1 6.0 2 NaN dtype: float64 >>> ser.notna() 0 True 1 True 2 False dtype: bool """ @Appender(_shared_docs["notna"] % _shared_doc_kwargs) def notna(self: FrameOrSeries) -> FrameOrSeries: return notna(self).__finalize__(self, method="notna") @Appender(_shared_docs["notna"] % _shared_doc_kwargs) def notnull(self: FrameOrSeries) -> FrameOrSeries: return notna(self).__finalize__(self, method="notnull") def _clip_with_scalar(self, lower, upper, inplace: bool_t = False): if (lower is not None and np.any(isna(lower))) or ( upper is not None and np.any(isna(upper)) ): raise ValueError("Cannot use an NA value as a clip threshold") result = self mask = isna(self._values) with np.errstate(all="ignore"): if upper is not None: subset = self.to_numpy() <= upper result = result.where(subset, upper, axis=None, inplace=False) if lower is not None: subset = self.to_numpy() >= lower result = result.where(subset, lower, axis=None, inplace=False) if np.any(mask): result[mask] = np.nan if inplace: return self._update_inplace(result) else: return result def _clip_with_one_bound(self, threshold, method, axis, inplace): if axis is not None: axis = self._get_axis_number(axis) # method is self.le for upper bound and self.ge for lower bound if is_scalar(threshold) and is_number(threshold): if method.__name__ == "le": return self._clip_with_scalar(None, threshold, inplace=inplace) return self._clip_with_scalar(threshold, None, inplace=inplace) subset = method(threshold, axis=axis) | isna(self) # GH #15390 # In order for where method to work, the threshold must # be transformed to NDFrame from other array like structure. if (not isinstance(threshold, ABCSeries)) and is_list_like(threshold): if isinstance(self, ABCSeries): threshold = self._constructor(threshold, index=self.index) else: threshold = _align_method_FRAME(self, threshold, axis, flex=None)[1] return self.where(subset, threshold, axis=axis, inplace=inplace) def clip( self: FrameOrSeries, lower=None, upper=None, axis=None, inplace: bool_t = False, *args, **kwargs, ) -> FrameOrSeries: """ Trim values at input threshold(s). Assigns values outside boundary to boundary values. Thresholds can be singular values or array like, and in the latter case the clipping is performed element-wise in the specified axis. Parameters ---------- lower : float or array_like, default None Minimum threshold value. All values below this threshold will be set to it. upper : float or array_like, default None Maximum threshold value. All values above this threshold will be set to it. axis : int or str axis name, optional Align object with lower and upper along the given axis. inplace : bool, default False Whether to perform the operation in place on the data. *args, **kwargs Additional keywords have no effect but might be accepted for compatibility with numpy. Returns ------- Series or DataFrame Same type as calling object with the values outside the clip boundaries replaced. See Also -------- Series.clip : Trim values at input threshold in series. DataFrame.clip : Trim values at input threshold in dataframe. numpy.clip : Clip (limit) the values in an array. Examples -------- >>> data = {'col_0': [9, -3, 0, -1, 5], 'col_1': [-2, -7, 6, 8, -5]} >>> df = pd.DataFrame(data) >>> df col_0 col_1 0 9 -2 1 -3 -7 2 0 6 3 -1 8 4 5 -5 Clips per column using lower and upper thresholds: >>> df.clip(-4, 6) col_0 col_1 0 6 -2 1 -3 -4 2 0 6 3 -1 6 4 5 -4 Clips using specific lower and upper thresholds per column element: >>> t = pd.Series([2, -4, -1, 6, 3]) >>> t 0 2 1 -4 2 -1 3 6 4 3 dtype: int64 >>> df.clip(t, t + 4, axis=0) col_0 col_1 0 6 2 1 -3 -4 2 0 3 3 6 8 4 5 3 """ inplace = validate_bool_kwarg(inplace, "inplace") axis = nv.validate_clip_with_axis(axis, args, kwargs) if axis is not None: axis = self._get_axis_number(axis) # GH 17276 # numpy doesn't like NaN as a clip value # so ignore # GH 19992 # numpy doesn't drop a list-like bound containing NaN if not is_list_like(lower) and np.any(isna(lower)): lower = None if not is_list_like(upper) and np.any(isna(upper)): upper = None # GH 2747 (arguments were reversed) if lower is not None and upper is not None: if is_scalar(lower) and is_scalar(upper): lower, upper = min(lower, upper), max(lower, upper) # fast-path for scalars if (lower is None or (is_scalar(lower) and is_number(lower))) and ( upper is None or (is_scalar(upper) and is_number(upper)) ): return self._clip_with_scalar(lower, upper, inplace=inplace) result = self if lower is not None: result = result._clip_with_one_bound( lower, method=self.ge, axis=axis, inplace=inplace ) if upper is not None: if inplace: result = self result = result._clip_with_one_bound( upper, method=self.le, axis=axis, inplace=inplace ) return result _shared_docs[ "groupby" ] = """ Group %(klass)s using a mapper or by a Series of columns. A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Parameters ---------- by : mapping, function, label, or list of labels Used to determine the groups for the groupby. If ``by`` is a function, it's called on each value of the object's index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series' values are first aligned; see ``.align()`` method). If an ndarray is passed, the values are used as-is determine the groups. A label or list of labels may be passed to group by the columns in ``self``. Notice that a tuple is interpreted as a (single) key. axis : {0 or 'index', 1 or 'columns'}, default 0 Split along rows (0) or columns (1). level : int, level name, or sequence of such, default None If the axis is a MultiIndex (hierarchical), group by a particular level or levels. as_index : bool, default True For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively "SQL-style" grouped output. sort : bool, default True Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group. group_keys : bool, default True When calling apply, add group keys to index to identify pieces. squeeze : bool, default False Reduce the dimensionality of the return type if possible, otherwise return a consistent type. .. deprecated:: 1.1.0 observed : bool, default False This only applies if any of the groupers are Categoricals. If True: only show observed values for categorical groupers. If False: show all values for categorical groupers. .. versionadded:: 0.23.0 dropna : bool, default True If True, and if group keys contain NA values, NA values together with row/column will be dropped. If False, NA values will also be treated as the key in groups .. versionadded:: 1.1.0 Returns ------- %(klass)sGroupBy Returns a groupby object that contains information about the groups. See Also -------- resample : Convenience method for frequency conversion and resampling of time series. Notes ----- See the `user guide <https://pandas.pydata.org/pandas-docs/stable/groupby.html>`_ for more. """ def asfreq( self: FrameOrSeries, freq, method=None, how: Optional[str] = None, normalize: bool_t = False, fill_value=None, ) -> FrameOrSeries: """ Convert TimeSeries to specified frequency. Optionally provide filling method to pad/backfill missing values. Returns the original data conformed to a new index with the specified frequency. ``resample`` is more appropriate if an operation, such as summarization, is necessary to represent the data at the new frequency. Parameters ---------- freq : DateOffset or str Frequency DateOffset or string. method : {'backfill'/'bfill', 'pad'/'ffill'}, default None Method to use for filling holes in reindexed Series (note this does not fill NaNs that already were present): * 'pad' / 'ffill': propagate last valid observation forward to next valid * 'backfill' / 'bfill': use NEXT valid observation to fill. how : {'start', 'end'}, default end For PeriodIndex only (see PeriodIndex.asfreq). normalize : bool, default False Whether to reset output index to midnight. fill_value : scalar, optional Value to use for missing values, applied during upsampling (note this does not fill NaNs that already were present). Returns ------- Same type as caller Object converted to the specified frequency. See Also -------- reindex : Conform DataFrame to new index with optional filling logic. Notes ----- To learn more about the frequency strings, please see `this link <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__. Examples -------- Start by creating a series with 4 one minute timestamps. >>> index = pd.date_range('1/1/2000', periods=4, freq='T') >>> series = pd.Series([0.0, None, 2.0, 3.0], index=index) >>> df = pd.DataFrame({'s':series}) >>> df s 2000-01-01 00:00:00 0.0 2000-01-01 00:01:00 NaN 2000-01-01 00:02:00 2.0 2000-01-01 00:03:00 3.0 Upsample the series into 30 second bins. >>> df.asfreq(freq='30S') s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 NaN 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 NaN 2000-01-01 00:03:00 3.0 Upsample again, providing a ``fill value``. >>> df.asfreq(freq='30S', fill_value=9.0) s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 9.0 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 9.0 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 9.0 2000-01-01 00:03:00 3.0 Upsample again, providing a ``method``. >>> df.asfreq(freq='30S', method='bfill') s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 2.0 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 3.0 2000-01-01 00:03:00 3.0 """ from pandas.core.resample import asfreq return asfreq( self, freq, method=method, how=how, normalize=normalize, fill_value=fill_value, ) def at_time( self: FrameOrSeries, time, asof: bool_t = False, axis=None ) -> FrameOrSeries: """ Select values at particular time of day (e.g., 9:30AM). Parameters ---------- time : datetime.time or str axis : {0 or 'index', 1 or 'columns'}, default 0 .. versionadded:: 0.24.0 Returns ------- Series or DataFrame Raises ------ TypeError If the index is not a :class:`DatetimeIndex` See Also -------- between_time : Select values between particular times of the day. first : Select initial periods of time series based on a date offset. last : Select final periods of time series based on a date offset. DatetimeIndex.indexer_at_time : Get just the index locations for values at particular time of the day. Examples -------- >>> i = pd.date_range('2018-04-09', periods=4, freq='12H') >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i) >>> ts A 2018-04-09 00:00:00 1 2018-04-09 12:00:00 2 2018-04-10 00:00:00 3 2018-04-10 12:00:00 4 >>> ts.at_time('12:00') A 2018-04-09 12:00:00 2 2018-04-10 12:00:00 4 """ if axis is None: axis = self._stat_axis_number axis = self._get_axis_number(axis) index = self._get_axis(axis) if not isinstance(index, DatetimeIndex): raise TypeError("Index must be DatetimeIndex") indexer = index.indexer_at_time(time, asof=asof) return self._take_with_is_copy(indexer, axis=axis) def between_time( self: FrameOrSeries, start_time, end_time, include_start: bool_t = True, include_end: bool_t = True, axis=None, ) -> FrameOrSeries: """ Select values between particular times of the day (e.g., 9:00-9:30 AM). By setting ``start_time`` to be later than ``end_time``, you can get the times that are *not* between the two times. Parameters ---------- start_time : datetime.time or str Initial time as a time filter limit. end_time : datetime.time or str End time as a time filter limit. include_start : bool, default True Whether the start time needs to be included in the result. include_end : bool, default True Whether the end time needs to be included in the result. axis : {0 or 'index', 1 or 'columns'}, default 0 Determine range time on index or columns value. .. versionadded:: 0.24.0 Returns ------- Series or DataFrame Data from the original object filtered to the specified dates range. Raises ------ TypeError If the index is not a :class:`DatetimeIndex` See Also -------- at_time : Select values at a particular time of the day. first : Select initial periods of time series based on a date offset. last : Select final periods of time series based on a date offset. DatetimeIndex.indexer_between_time : Get just the index locations for values between particular times of the day. Examples -------- >>> i = pd.date_range('2018-04-09', periods=4, freq='1D20min') >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i) >>> ts A 2018-04-09 00:00:00 1 2018-04-10 00:20:00 2 2018-04-11 00:40:00 3 2018-04-12 01:00:00 4 >>> ts.between_time('0:15', '0:45') A 2018-04-10 00:20:00 2 2018-04-11 00:40:00 3 You get the times that are *not* between two times by setting ``start_time`` later than ``end_time``: >>> ts.between_time('0:45', '0:15') A 2018-04-09 00:00:00 1 2018-04-12 01:00:00 4 """ if axis is None: axis = self._stat_axis_number axis = self._get_axis_number(axis) index = self._get_axis(axis) if not isinstance(index, DatetimeIndex): raise TypeError("Index must be DatetimeIndex") indexer = index.indexer_between_time( start_time, end_time, include_start=include_start, include_end=include_end, ) return self._take_with_is_copy(indexer, axis=axis) def resample( self, rule, axis=0, closed: Optional[str] = None, label: Optional[str] = None, convention: str = "start", kind: Optional[str] = None, loffset=None, base: Optional[int] = None, on=None, level=None, origin: Union[str, TimestampConvertibleTypes] = "start_day", offset: Optional[TimedeltaConvertibleTypes] = None, ) -> "Resampler": """ Resample time-series data. Convenience method for frequency conversion and resampling of time series. Object must have a datetime-like index (`DatetimeIndex`, `PeriodIndex`, or `TimedeltaIndex`), or pass datetime-like values to the `on` or `level` keyword. Parameters ---------- rule : DateOffset, Timedelta or str The offset string or object representing target conversion. axis : {0 or 'index', 1 or 'columns'}, default 0 Which axis to use for up- or down-sampling. For `Series` this will default to 0, i.e. along the rows. Must be `DatetimeIndex`, `TimedeltaIndex` or `PeriodIndex`. closed : {'right', 'left'}, default None Which side of bin interval is closed. The default is 'left' for all frequency offsets except for 'M', 'A', 'Q', 'BM', 'BA', 'BQ', and 'W' which all have a default of 'right'. label : {'right', 'left'}, default None Which bin edge label to label bucket with. The default is 'left' for all frequency offsets except for 'M', 'A', 'Q', 'BM', 'BA', 'BQ', and 'W' which all have a default of 'right'. convention : {'start', 'end', 's', 'e'}, default 'start' For `PeriodIndex` only, controls whether to use the start or end of `rule`. kind : {'timestamp', 'period'}, optional, default None Pass 'timestamp' to convert the resulting index to a `DateTimeIndex` or 'period' to convert it to a `PeriodIndex`. By default the input representation is retained. loffset : timedelta, default None Adjust the resampled time labels. .. deprecated:: 1.1.0 You should add the loffset to the `df.index` after the resample. See below. base : int, default 0 For frequencies that evenly subdivide 1 day, the "origin" of the aggregated intervals. For example, for '5min' frequency, base could range from 0 through 4. Defaults to 0. .. deprecated:: 1.1.0 The new arguments that you should use are 'offset' or 'origin'. on : str, optional For a DataFrame, column to use instead of index for resampling. Column must be datetime-like. level : str or int, optional For a MultiIndex, level (name or number) to use for resampling. `level` must be datetime-like. origin : {'epoch', 'start', 'start_day'}, Timestamp or str, default 'start_day' The timestamp on which to adjust the grouping. The timezone of origin must match the timezone of the index. If a timestamp is not used, these values are also supported: - 'epoch': `origin` is 1970-01-01 - 'start': `origin` is the first value of the timeseries - 'start_day': `origin` is the first day at midnight of the timeseries .. versionadded:: 1.1.0 offset : Timedelta or str, default is None An offset timedelta added to the origin. .. versionadded:: 1.1.0 Returns ------- Resampler object See Also -------- groupby : Group by mapping, function, label, or list of labels. Series.resample : Resample a Series. DataFrame.resample: Resample a DataFrame. Notes ----- See the `user guide <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling>`_ for more. To learn more about the offset strings, please see `this link <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects>`__. Examples -------- Start by creating a series with 9 one minute timestamps. >>> index = pd.date_range('1/1/2000', periods=9, freq='T') >>> series = pd.Series(range(9), index=index) >>> series 2000-01-01 00:00:00 0 2000-01-01 00:01:00 1 2000-01-01 00:02:00 2 2000-01-01 00:03:00 3 2000-01-01 00:04:00 4 2000-01-01 00:05:00 5 2000-01-01 00:06:00 6 2000-01-01 00:07:00 7 2000-01-01 00:08:00 8 Freq: T, dtype: int64 Downsample the series into 3 minute bins and sum the values of the timestamps falling into a bin. >>> series.resample('3T').sum() 2000-01-01 00:00:00 3 2000-01-01 00:03:00 12 2000-01-01 00:06:00 21 Freq: 3T, dtype: int64 Downsample the series into 3 minute bins as above, but label each bin using the right edge instead of the left. Please note that the value in the bucket used as the label is not included in the bucket, which it labels. For example, in the original series the bucket ``2000-01-01 00:03:00`` contains the value 3, but the summed value in the resampled bucket with the label ``2000-01-01 00:03:00`` does not include 3 (if it did, the summed value would be 6, not 3). To include this value close the right side of the bin interval as illustrated in the example below this one. >>> series.resample('3T', label='right').sum() 2000-01-01 00:03:00 3 2000-01-01 00:06:00 12 2000-01-01 00:09:00 21 Freq: 3T, dtype: int64 Downsample the series into 3 minute bins as above, but close the right side of the bin interval. >>> series.resample('3T', label='right', closed='right').sum() 2000-01-01 00:00:00 0 2000-01-01 00:03:00 6 2000-01-01 00:06:00 15 2000-01-01 00:09:00 15 Freq: 3T, dtype: int64 Upsample the series into 30 second bins. >>> series.resample('30S').asfreq()[0:5] # Select first 5 rows 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 1.0 2000-01-01 00:01:30 NaN 2000-01-01 00:02:00 2.0 Freq: 30S, dtype: float64 Upsample the series into 30 second bins and fill the ``NaN`` values using the ``pad`` method. >>> series.resample('30S').pad()[0:5] 2000-01-01 00:00:00 0 2000-01-01 00:00:30 0 2000-01-01 00:01:00 1 2000-01-01 00:01:30 1 2000-01-01 00:02:00 2 Freq: 30S, dtype: int64 Upsample the series into 30 second bins and fill the ``NaN`` values using the ``bfill`` method. >>> series.resample('30S').bfill()[0:5] 2000-01-01 00:00:00 0 2000-01-01 00:00:30 1 2000-01-01 00:01:00 1 2000-01-01 00:01:30 2 2000-01-01 00:02:00 2 Freq: 30S, dtype: int64 Pass a custom function via ``apply`` >>> def custom_resampler(array_like): ... return np.sum(array_like) + 5 ... >>> series.resample('3T').apply(custom_resampler) 2000-01-01 00:00:00 8 2000-01-01 00:03:00 17 2000-01-01 00:06:00 26 Freq: 3T, dtype: int64 For a Series with a PeriodIndex, the keyword `convention` can be used to control whether to use the start or end of `rule`. Resample a year by quarter using 'start' `convention`. Values are assigned to the first quarter of the period. >>> s = pd.Series([1, 2], index=pd.period_range('2012-01-01', ... freq='A', ... periods=2)) >>> s 2012 1 2013 2 Freq: A-DEC, dtype: int64 >>> s.resample('Q', convention='start').asfreq() 2012Q1 1.0 2012Q2 NaN 2012Q3 NaN 2012Q4 NaN 2013Q1 2.0 2013Q2 NaN 2013Q3 NaN 2013Q4 NaN Freq: Q-DEC, dtype: float64 Resample quarters by month using 'end' `convention`. Values are assigned to the last month of the period. >>> q = pd.Series([1, 2, 3, 4], index=pd.period_range('2018-01-01', ... freq='Q', ... periods=4)) >>> q 2018Q1 1 2018Q2 2 2018Q3 3 2018Q4 4 Freq: Q-DEC, dtype: int64 >>> q.resample('M', convention='end').asfreq() 2018-03 1.0 2018-04 NaN 2018-05 NaN 2018-06 2.0 2018-07 NaN 2018-08 NaN 2018-09 3.0 2018-10 NaN 2018-11 NaN 2018-12 4.0 Freq: M, dtype: float64 For DataFrame objects, the keyword `on` can be used to specify the column instead of the index for resampling. >>> d = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19], ... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]}) >>> df = pd.DataFrame(d) >>> df['week_starting'] = pd.date_range('01/01/2018', ... periods=8, ... freq='W') >>> df price volume week_starting 0 10 50 2018-01-07 1 11 60 2018-01-14 2 9 40 2018-01-21 3 13 100 2018-01-28 4 14 50 2018-02-04 5 18 100 2018-02-11 6 17 40 2018-02-18 7 19 50 2018-02-25 >>> df.resample('M', on='week_starting').mean() price volume week_starting 2018-01-31 10.75 62.5 2018-02-28 17.00 60.0 For a DataFrame with MultiIndex, the keyword `level` can be used to specify on which level the resampling needs to take place. >>> days = pd.date_range('1/1/2000', periods=4, freq='D') >>> d2 = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19], ... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]}) >>> df2 = pd.DataFrame(d2, ... index=pd.MultiIndex.from_product([days, ... ['morning', ... 'afternoon']] ... )) >>> df2 price volume 2000-01-01 morning 10 50 afternoon 11 60 2000-01-02 morning 9 40 afternoon 13 100 2000-01-03 morning 14 50 afternoon 18 100 2000-01-04 morning 17 40 afternoon 19 50 >>> df2.resample('D', level=0).sum() price volume 2000-01-01 21 110 2000-01-02 22 140 2000-01-03 32 150 2000-01-04 36 90 If you want to adjust the start of the bins based on a fixed timestamp: >>> start, end = '2000-10-01 23:30:00', '2000-10-02 00:30:00' >>> rng = pd.date_range(start, end, freq='7min') >>> ts = pd.Series(np.arange(len(rng)) * 3, index=rng) >>> ts 2000-10-01 23:30:00 0 2000-10-01 23:37:00 3 2000-10-01 23:44:00 6 2000-10-01 23:51:00 9 2000-10-01 23:58:00 12 2000-10-02 00:05:00 15 2000-10-02 00:12:00 18 2000-10-02 00:19:00 21 2000-10-02 00:26:00 24 Freq: 7T, dtype: int64 >>> ts.resample('17min').sum() 2000-10-01 23:14:00 0 2000-10-01 23:31:00 9 2000-10-01 23:48:00 21 2000-10-02 00:05:00 54 2000-10-02 00:22:00 24 Freq: 17T, dtype: int64 >>> ts.resample('17min', origin='epoch').sum() 2000-10-01 23:18:00 0 2000-10-01 23:35:00 18 2000-10-01 23:52:00 27 2000-10-02 00:09:00 39 2000-10-02 00:26:00 24 Freq: 17T, dtype: int64 >>> ts.resample('17min', origin='2000-01-01').sum() 2000-10-01 23:24:00 3 2000-10-01 23:41:00 15 2000-10-01 23:58:00 45 2000-10-02 00:15:00 45 Freq: 17T, dtype: int64 If you want to adjust the start of the bins with an `offset` Timedelta, the two following lines are equivalent: >>> ts.resample('17min', origin='start').sum() 2000-10-01 23:30:00 9 2000-10-01 23:47:00 21 2000-10-02 00:04:00 54 2000-10-02 00:21:00 24 Freq: 17T, dtype: int64 >>> ts.resample('17min', offset='23h30min').sum() 2000-10-01 23:30:00 9 2000-10-01 23:47:00 21 2000-10-02 00:04:00 54 2000-10-02 00:21:00 24 Freq: 17T, dtype: int64 To replace the use of the deprecated `base` argument, you can now use `offset`, in this example it is equivalent to have `base=2`: >>> ts.resample('17min', offset='2min').sum() 2000-10-01 23:16:00 0 2000-10-01 23:33:00 9 2000-10-01 23:50:00 36 2000-10-02 00:07:00 39 2000-10-02 00:24:00 24 Freq: 17T, dtype: int64 To replace the use of the deprecated `loffset` argument: >>> from pandas.tseries.frequencies import to_offset >>> loffset = '19min' >>> ts_out = ts.resample('17min').sum() >>> ts_out.index = ts_out.index + to_offset(loffset) >>> ts_out 2000-10-01 23:33:00 0 2000-10-01 23:50:00 9 2000-10-02 00:07:00 21 2000-10-02 00:24:00 54 2000-10-02 00:41:00 24 Freq: 17T, dtype: int64 """ from pandas.core.resample import get_resampler axis = self._get_axis_number(axis) return get_resampler( self, freq=rule, label=label, closed=closed, axis=axis, kind=kind, loffset=loffset, convention=convention, base=base, key=on, level=level, origin=origin, offset=offset, ) def first(self: FrameOrSeries, offset) -> FrameOrSeries: """ Select initial periods of time series data based on a date offset. When having a DataFrame with dates as index, this function can select the first few rows based on a date offset. Parameters ---------- offset : str, DateOffset or dateutil.relativedelta The offset length of the data that will be selected. For instance, '1M' will display all the rows having their index within the first month. Returns ------- Series or DataFrame A subset of the caller. Raises ------ TypeError If the index is not a :class:`DatetimeIndex` See Also -------- last : Select final periods of time series based on a date offset. at_time : Select values at a particular time of the day. between_time : Select values between particular times of the day. Examples -------- >>> i = pd.date_range('2018-04-09', periods=4, freq='2D') >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i) >>> ts A 2018-04-09 1 2018-04-11 2 2018-04-13 3 2018-04-15 4 Get the rows for the first 3 days: >>> ts.first('3D') A 2018-04-09 1 2018-04-11 2 Notice the data for 3 first calendar days were returned, not the first 3 days observed in the dataset, and therefore data for 2018-04-13 was not returned. """ if not isinstance(self.index, DatetimeIndex): raise TypeError("'first' only supports a DatetimeIndex index") if len(self.index) == 0: return self offset = to_offset(offset) end_date = end = self.index[0] + offset # Tick-like, e.g. 3 weeks if isinstance(offset, Tick): if end_date in self.index: end = self.index.searchsorted(end_date, side="left") return self.iloc[:end] return self.loc[:end] def last(self: FrameOrSeries, offset) -> FrameOrSeries: """ Select final periods of time series data based on a date offset. When having a DataFrame with dates as index, this function can select the last few rows based on a date offset. Parameters ---------- offset : str, DateOffset, dateutil.relativedelta The offset length of the data that will be selected. For instance, '3D' will display all the rows having their index within the last 3 days. Returns ------- Series or DataFrame A subset of the caller. Raises ------ TypeError If the index is not a :class:`DatetimeIndex` See Also -------- first : Select initial periods of time series based on a date offset. at_time : Select values at a particular time of the day. between_time : Select values between particular times of the day. Examples -------- >>> i = pd.date_range('2018-04-09', periods=4, freq='2D') >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i) >>> ts A 2018-04-09 1 2018-04-11 2 2018-04-13 3 2018-04-15 4 Get the rows for the last 3 days: >>> ts.last('3D') A 2018-04-13 3 2018-04-15 4 Notice the data for 3 last calendar days were returned, not the last 3 observed days in the dataset, and therefore data for 2018-04-11 was not returned. """ if not isinstance(self.index, DatetimeIndex): raise TypeError("'last' only supports a DatetimeIndex index") if len(self.index) == 0: return self offset = to_offset(offset) start_date = self.index[-1] - offset start = self.index.searchsorted(start_date, side="right") return self.iloc[start:] def rank( self: FrameOrSeries, axis=0, method: str = "average", numeric_only: Optional[bool_t] = None, na_option: str = "keep", ascending: bool_t = True, pct: bool_t = False, ) -> FrameOrSeries: """ Compute numerical data ranks (1 through n) along axis. By default, equal values are assigned a rank that is the average of the ranks of those values. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 Index to direct ranking. method : {'average', 'min', 'max', 'first', 'dense'}, default 'average' How to rank the group of records that have the same value (i.e. ties): * average: average rank of the group * min: lowest rank in the group * max: highest rank in the group * first: ranks assigned in order they appear in the array * dense: like 'min', but rank always increases by 1 between groups. numeric_only : bool, optional For DataFrame objects, rank only numeric columns if set to True. na_option : {'keep', 'top', 'bottom'}, default 'keep' How to rank NaN values: * keep: assign NaN rank to NaN values * top: assign smallest rank to NaN values if ascending * bottom: assign highest rank to NaN values if ascending. ascending : bool, default True Whether or not the elements should be ranked in ascending order. pct : bool, default False Whether or not to display the returned rankings in percentile form. Returns ------- same type as caller Return a Series or DataFrame with data ranks as values. See Also -------- core.groupby.GroupBy.rank : Rank of values within each group. Examples -------- >>> df = pd.DataFrame(data={'Animal': ['cat', 'penguin', 'dog', ... 'spider', 'snake'], ... 'Number_legs': [4, 2, 4, 8, np.nan]}) >>> df Animal Number_legs 0 cat 4.0 1 penguin 2.0 2 dog 4.0 3 spider 8.0 4 snake NaN The following example shows how the method behaves with the above parameters: * default_rank: this is the default behaviour obtained without using any parameter. * max_rank: setting ``method = 'max'`` the records that have the same values are ranked using the highest rank (e.g.: since 'cat' and 'dog' are both in the 2nd and 3rd position, rank 3 is assigned.) * NA_bottom: choosing ``na_option = 'bottom'``, if there are records with NaN values they are placed at the bottom of the ranking. * pct_rank: when setting ``pct = True``, the ranking is expressed as percentile rank. >>> df['default_rank'] = df['Number_legs'].rank() >>> df['max_rank'] = df['Number_legs'].rank(method='max') >>> df['NA_bottom'] = df['Number_legs'].rank(na_option='bottom') >>> df['pct_rank'] = df['Number_legs'].rank(pct=True) >>> df Animal Number_legs default_rank max_rank NA_bottom pct_rank 0 cat 4.0 2.5 3.0 2.5 0.625 1 penguin 2.0 1.0 1.0 1.0 0.250 2 dog 4.0 2.5 3.0 2.5 0.625 3 spider 8.0 4.0 4.0 4.0 1.000 4 snake NaN NaN NaN 5.0 NaN """ axis = self._get_axis_number(axis) if na_option not in {"keep", "top", "bottom"}: msg = "na_option must be one of 'keep', 'top', or 'bottom'" raise ValueError(msg) def ranker(data): ranks = algos.rank( data.values, axis=axis, method=method, ascending=ascending, na_option=na_option, pct=pct, ) ranks = self._constructor(ranks, **data._construct_axes_dict()) return ranks.__finalize__(self, method="rank") # if numeric_only is None, and we can't get anything, we try with # numeric_only=True if numeric_only is None: try: return ranker(self) except TypeError: numeric_only = True if numeric_only: data = self._get_numeric_data() else: data = self return ranker(data) @doc(**_shared_doc_kwargs) def align( self, other, join="outer", axis=None, level=None, copy=True, fill_value=None, method=None, limit=None, fill_axis=0, broadcast_axis=None, ): """ Align two objects on their axes with the specified join method. Join method is specified for each axis Index. Parameters ---------- other : DataFrame or Series join : {{'outer', 'inner', 'left', 'right'}}, default 'outer' axis : allowed axis of the other object, default None Align on index (0), columns (1), or both (None). level : int or level name, default None Broadcast across a level, matching Index values on the passed MultiIndex level. copy : bool, default True Always returns new objects. If copy=False and no reindexing is required then original objects are returned. fill_value : scalar, default np.NaN Value to use for missing values. Defaults to NaN, but can be any "compatible" value. method : {{'backfill', 'bfill', 'pad', 'ffill', None}}, default None Method to use for filling holes in reindexed Series: - pad / ffill: propagate last valid observation forward to next valid. - backfill / bfill: use NEXT valid observation to fill gap. limit : int, default None If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None. fill_axis : {axes_single_arg}, default 0 Filling axis, method and limit. broadcast_axis : {axes_single_arg}, default None Broadcast values along this axis, if aligning two objects of different dimensions. Returns ------- (left, right) : ({klass}, type of other) Aligned objects. """ method = missing.clean_fill_method(method) if broadcast_axis == 1 and self.ndim != other.ndim: if isinstance(self, ABCSeries): # this means other is a DataFrame, and we need to broadcast # self cons = self._constructor_expanddim df = cons( {c: self for c in other.columns}, **other._construct_axes_dict() ) return df._align_frame( other, join=join, axis=axis, level=level, copy=copy, fill_value=fill_value, method=method, limit=limit, fill_axis=fill_axis, ) elif isinstance(other, ABCSeries): # this means self is a DataFrame, and we need to broadcast # other cons = other._constructor_expanddim df = cons( {c: other for c in self.columns}, **self._construct_axes_dict() ) return self._align_frame( df, join=join, axis=axis, level=level, copy=copy, fill_value=fill_value, method=method, limit=limit, fill_axis=fill_axis, ) if axis is not None: axis = self._get_axis_number(axis) if isinstance(other, ABCDataFrame): return self._align_frame( other, join=join, axis=axis, level=level, copy=copy, fill_value=fill_value, method=method, limit=limit, fill_axis=fill_axis, ) elif isinstance(other, ABCSeries): return self._align_series( other, join=join, axis=axis, level=level, copy=copy, fill_value=fill_value, method=method, limit=limit, fill_axis=fill_axis, ) else: # pragma: no cover raise TypeError(f"unsupported type: {type(other)}") def _align_frame( self, other, join="outer", axis=None, level=None, copy: bool_t = True, fill_value=None, method=None, limit=None, fill_axis=0, ): # defaults join_index, join_columns = None, None ilidx, iridx = None, None clidx, cridx = None, None is_series = isinstance(self, ABCSeries) if axis is None or axis == 0: if not self.index.equals(other.index): join_index, ilidx, iridx = self.index.join( other.index, how=join, level=level, return_indexers=True ) if axis is None or axis == 1: if not is_series and not self.columns.equals(other.columns): join_columns, clidx, cridx = self.columns.join( other.columns, how=join, level=level, return_indexers=True ) if is_series: reindexers = {0: [join_index, ilidx]} else: reindexers = {0: [join_index, ilidx], 1: [join_columns, clidx]} left = self._reindex_with_indexers( reindexers, copy=copy, fill_value=fill_value, allow_dups=True ) # other must be always DataFrame right = other._reindex_with_indexers( {0: [join_index, iridx], 1: [join_columns, cridx]}, copy=copy, fill_value=fill_value, allow_dups=True, ) if method is not None: _left = left.fillna(method=method, axis=fill_axis, limit=limit) assert _left is not None # needed for mypy left = _left right = right.fillna(method=method, axis=fill_axis, limit=limit) # if DatetimeIndex have different tz, convert to UTC if is_datetime64tz_dtype(left.index.dtype): if left.index.tz != right.index.tz: if join_index is not None: left.index = join_index right.index = join_index return ( left.__finalize__(self), right.__finalize__(other), ) def _align_series( self, other, join="outer", axis=None, level=None, copy: bool_t = True, fill_value=None, method=None, limit=None, fill_axis=0, ): is_series = isinstance(self, ABCSeries) # series/series compat, other must always be a Series if is_series: if axis: raise ValueError("cannot align series to a series other than axis 0") # equal if self.index.equals(other.index): join_index, lidx, ridx = None, None, None else: join_index, lidx, ridx = self.index.join( other.index, how=join, level=level, return_indexers=True ) left = self._reindex_indexer(join_index, lidx, copy) right = other._reindex_indexer(join_index, ridx, copy) else: # one has > 1 ndim fdata = self._mgr if axis == 0: join_index = self.index lidx, ridx = None, None if not self.index.equals(other.index): join_index, lidx, ridx = self.index.join( other.index, how=join, level=level, return_indexers=True ) if lidx is not None: fdata = fdata.reindex_indexer(join_index, lidx, axis=1) elif axis == 1: join_index = self.columns lidx, ridx = None, None if not self.columns.equals(other.index): join_index, lidx, ridx = self.columns.join( other.index, how=join, level=level, return_indexers=True ) if lidx is not None: fdata = fdata.reindex_indexer(join_index, lidx, axis=0) else: raise ValueError("Must specify axis=0 or 1") if copy and fdata is self._mgr: fdata = fdata.copy() left = self._constructor(fdata) if ridx is None: right = other else: right = other.reindex(join_index, level=level) # fill fill_na = notna(fill_value) or (method is not None) if fill_na: left = left.fillna(fill_value, method=method, limit=limit, axis=fill_axis) right = right.fillna(fill_value, method=method, limit=limit) # if DatetimeIndex have different tz, convert to UTC if is_series or (not is_series and axis == 0): if is_datetime64tz_dtype(left.index.dtype): if left.index.tz != right.index.tz: if join_index is not None: left.index = join_index right.index = join_index return ( left.__finalize__(self), right.__finalize__(other), ) def _where( self, cond, other=np.nan, inplace=False, axis=None, level=None, errors="raise", try_cast=False, ): """ Equivalent to public method `where`, except that `other` is not applied as a function even if callable. Used in __setitem__. """ inplace = validate_bool_kwarg(inplace, "inplace") # align the cond to same shape as myself cond = com.apply_if_callable(cond, self) if isinstance(cond, NDFrame): cond, _ = cond.align(self, join="right", broadcast_axis=1) else: if not hasattr(cond, "shape"): cond = np.asanyarray(cond) if cond.shape != self.shape: raise ValueError("Array conditional must be same shape as self") cond = self._constructor(cond, **self._construct_axes_dict()) # make sure we are boolean fill_value = bool(inplace) cond = cond.fillna(fill_value) msg = "Boolean array expected for the condition, not {dtype}" if not isinstance(cond, ABCDataFrame): # This is a single-dimensional object. if not is_bool_dtype(cond): raise ValueError(msg.format(dtype=cond.dtype)) elif not cond.empty: for dt in cond.dtypes: if not is_bool_dtype(dt): raise ValueError(msg.format(dtype=dt)) else: # GH#21947 we have an empty DataFrame, could be object-dtype cond = cond.astype(bool) cond = -cond if inplace else cond # try to align with other try_quick = True if isinstance(other, NDFrame): # align with me if other.ndim <= self.ndim: _, other = self.align( other, join="left", axis=axis, level=level, fill_value=np.nan ) # if we are NOT aligned, raise as we cannot where index if axis is None and not all( other._get_axis(i).equals(ax) for i, ax in enumerate(self.axes) ): raise InvalidIndexError # slice me out of the other else: raise NotImplementedError( "cannot align with a higher dimensional NDFrame" ) if isinstance(other, np.ndarray): if other.shape != self.shape: if self.ndim == 1: icond = cond._values # GH 2745 / GH 4192 # treat like a scalar if len(other) == 1: other = other[0] # GH 3235 # match True cond to other elif len(cond[icond]) == len(other): # try to not change dtype at first (if try_quick) if try_quick: new_other = np.asarray(self) new_other = new_other.copy() new_other[icond] = other other = new_other else: raise ValueError( "Length of replacements must equal series length" ) else: raise ValueError( "other must be the same shape as self when an ndarray" ) # we are the same shape, so create an actual object for alignment else: other = self._constructor(other, **self._construct_axes_dict()) if axis is None: axis = 0 if self.ndim == getattr(other, "ndim", 0): align = True else: align = self._get_axis_number(axis) == 1 if align and isinstance(other, NDFrame): other = other.reindex(self._info_axis, axis=self._info_axis_number) if isinstance(cond, NDFrame): cond = cond.reindex(self._info_axis, axis=self._info_axis_number) block_axis = self._get_block_manager_axis(axis) if inplace: # we may have different type blocks come out of putmask, so # reconstruct the block manager self._check_inplace_setting(other) new_data = self._mgr.putmask( mask=cond, new=other, align=align, axis=block_axis, ) result = self._constructor(new_data) return self._update_inplace(result) else: new_data = self._mgr.where( other=other, cond=cond, align=align, errors=errors, try_cast=try_cast, axis=block_axis, ) result = self._constructor(new_data) return result.__finalize__(self) _shared_docs[ "where" ] = """ Replace values where the condition is %(cond_rev)s. Parameters ---------- cond : bool %(klass)s, array-like, or callable Where `cond` is %(cond)s, keep the original value. Where %(cond_rev)s, replace with corresponding value from `other`. If `cond` is callable, it is computed on the %(klass)s and should return boolean %(klass)s or array. The callable must not change input %(klass)s (though pandas doesn't check it). other : scalar, %(klass)s, or callable Entries where `cond` is %(cond_rev)s are replaced with corresponding value from `other`. If other is callable, it is computed on the %(klass)s and should return scalar or %(klass)s. The callable must not change input %(klass)s (though pandas doesn't check it). inplace : bool, default False Whether to perform the operation in place on the data. axis : int, default None Alignment axis if needed. level : int, default None Alignment level if needed. errors : str, {'raise', 'ignore'}, default 'raise' Note that currently this parameter won't affect the results and will always coerce to a suitable dtype. - 'raise' : allow exceptions to be raised. - 'ignore' : suppress exceptions. On error return original object. try_cast : bool, default False Try to cast the result back to the input type (if possible). Returns ------- Same type as caller See Also -------- :func:`DataFrame.%(name_other)s` : Return an object of same shape as self. Notes ----- The %(name)s method is an application of the if-then idiom. For each element in the calling DataFrame, if ``cond`` is ``%(cond)s`` the element is used; otherwise the corresponding element from the DataFrame ``other`` is used. The signature for :func:`DataFrame.where` differs from :func:`numpy.where`. Roughly ``df1.where(m, df2)`` is equivalent to ``np.where(m, df1, df2)``. For further details and examples see the ``%(name)s`` documentation in :ref:`indexing <indexing.where_mask>`. Examples -------- >>> s = pd.Series(range(5)) >>> s.where(s > 0) 0 NaN 1 1.0 2 2.0 3 3.0 4 4.0 dtype: float64 >>> s.mask(s > 0) 0 0.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 >>> s.where(s > 1, 10) 0 10 1 10 2 2 3 3 4 4 dtype: int64 >>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B']) >>> df A B 0 0 1 1 2 3 2 4 5 3 6 7 4 8 9 >>> m = df %% 3 == 0 >>> df.where(m, -df) A B 0 0 -1 1 -2 3 2 -4 -5 3 6 -7 4 -8 9 >>> df.where(m, -df) == np.where(m, df, -df) A B 0 True True 1 True True 2 True True 3 True True 4 True True >>> df.where(m, -df) == df.mask(~m, -df) A B 0 True True 1 True True 2 True True 3 True True 4 True True """ @Appender( _shared_docs["where"] % dict( _shared_doc_kwargs, cond="True", cond_rev="False", name="where", name_other="mask", ) ) def where( self, cond, other=np.nan, inplace=False, axis=None, level=None, errors="raise", try_cast=False, ): other = com.apply_if_callable(other, self) return self._where( cond, other, inplace, axis, level, errors=errors, try_cast=try_cast ) @Appender( _shared_docs["where"] % dict( _shared_doc_kwargs, cond="False", cond_rev="True", name="mask", name_other="where", ) ) def mask( self, cond, other=np.nan, inplace=False, axis=None, level=None, errors="raise", try_cast=False, ): inplace = validate_bool_kwarg(inplace, "inplace") cond = com.apply_if_callable(cond, self) # see gh-21891 if not hasattr(cond, "__invert__"): cond = np.array(cond) return self.where( ~cond, other=other, inplace=inplace, axis=axis, level=level, try_cast=try_cast, errors=errors, ) @doc(klass=_shared_doc_kwargs["klass"]) def shift( self: FrameOrSeries, periods=1, freq=None, axis=0, fill_value=None ) -> FrameOrSeries: """ Shift index by desired number of periods with an optional time `freq`. When `freq` is not passed, shift the index without realigning the data. If `freq` is passed (in this case, the index must be date or datetime, or it will raise a `NotImplementedError`), the index will be increased using the periods and the `freq`. Parameters ---------- periods : int Number of periods to shift. Can be positive or negative. freq : DateOffset, tseries.offsets, timedelta, or str, optional Offset to use from the tseries module or time rule (e.g. 'EOM'). If `freq` is specified then the index values are shifted but the data is not realigned. That is, use `freq` if you would like to extend the index when shifting and preserve the original data. axis : {{0 or 'index', 1 or 'columns', None}}, default None Shift direction. fill_value : object, optional The scalar value to use for newly introduced missing values. the default depends on the dtype of `self`. For numeric data, ``np.nan`` is used. For datetime, timedelta, or period data, etc. :attr:`NaT` is used. For extension dtypes, ``self.dtype.na_value`` is used. .. versionchanged:: 0.24.0 Returns ------- {klass} Copy of input object, shifted. See Also -------- Index.shift : Shift values of Index. DatetimeIndex.shift : Shift values of DatetimeIndex. PeriodIndex.shift : Shift values of PeriodIndex. tshift : Shift the time index, using the index's frequency if available. Examples -------- >>> df = pd.DataFrame({{'Col1': [10, 20, 15, 30, 45], ... 'Col2': [13, 23, 18, 33, 48], ... 'Col3': [17, 27, 22, 37, 52]}}) >>> df.shift(periods=3) Col1 Col2 Col3 0 NaN NaN NaN 1 NaN NaN NaN 2 NaN NaN NaN 3 10.0 13.0 17.0 4 20.0 23.0 27.0 >>> df.shift(periods=1, axis='columns') Col1 Col2 Col3 0 NaN 10.0 13.0 1 NaN 20.0 23.0 2 NaN 15.0 18.0 3 NaN 30.0 33.0 4 NaN 45.0 48.0 >>> df.shift(periods=3, fill_value=0) Col1 Col2 Col3 0 0 0 0 1 0 0 0 2 0 0 0 3 10 13 17 4 20 23 27 """ if periods == 0: return self.copy() block_axis = self._get_block_manager_axis(axis) if freq is None: new_data = self._mgr.shift( periods=periods, axis=block_axis, fill_value=fill_value ) else: return self.tshift(periods, freq) return self._constructor(new_data).__finalize__(self, method="shift") def slice_shift(self: FrameOrSeries, periods: int = 1, axis=0) -> FrameOrSeries: """ Equivalent to `shift` without copying data. The shifted data will not include the dropped periods and the shifted axis will be smaller than the original. Parameters ---------- periods : int Number of periods to move, can be positive or negative. Returns ------- shifted : same type as caller Notes ----- While the `slice_shift` is faster than `shift`, you may pay for it later during alignment. """ if periods == 0: return self if periods > 0: vslicer = slice(None, -periods) islicer = slice(periods, None) else: vslicer = slice(-periods, None) islicer = slice(None, periods) new_obj = self._slice(vslicer, axis=axis) shifted_axis = self._get_axis(axis)[islicer] new_obj.set_axis(shifted_axis, axis=axis, inplace=True) return new_obj.__finalize__(self, method="slice_shift") def tshift( self: FrameOrSeries, periods: int = 1, freq=None, axis: Axis = 0 ) -> FrameOrSeries: """ Shift the time index, using the index's frequency if available. Parameters ---------- periods : int Number of periods to move, can be positive or negative. freq : DateOffset, timedelta, or str, default None Increment to use from the tseries module or time rule expressed as a string (e.g. 'EOM'). axis : {0 or ‘index’, 1 or ‘columns’, None}, default 0 Corresponds to the axis that contains the Index. Returns ------- shifted : Series/DataFrame Notes ----- If freq is not specified then tries to use the freq or inferred_freq attributes of the index. If neither of those attributes exist, a ValueError is thrown """ index = self._get_axis(axis) if freq is None: freq = getattr(index, "freq", None) if freq is None: freq = getattr(index, "inferred_freq", None) if freq is None: msg = "Freq was not given and was not set in the index" raise ValueError(msg) if periods == 0: return self if isinstance(freq, str): freq = to_offset(freq) axis = self._get_axis_number(axis) if isinstance(index, PeriodIndex): orig_freq = to_offset(index.freq) if freq != orig_freq: assert orig_freq is not None # for mypy raise ValueError( f"Given freq {freq.rule_code} does not match " f"PeriodIndex freq {orig_freq.rule_code}" ) new_ax = index.shift(periods) else: new_ax = index.shift(periods, freq) result = self.copy() result.set_axis(new_ax, axis, inplace=True) return result.__finalize__(self, method="tshift") def truncate( self: FrameOrSeries, before=None, after=None, axis=None, copy: bool_t = True ) -> FrameOrSeries: """ Truncate a Series or DataFrame before and after some index value. This is a useful shorthand for boolean indexing based on index values above or below certain thresholds. Parameters ---------- before : date, str, int Truncate all rows before this index value. after : date, str, int Truncate all rows after this index value. axis : {0 or 'index', 1 or 'columns'}, optional Axis to truncate. Truncates the index (rows) by default. copy : bool, default is True, Return a copy of the truncated section. Returns ------- type of caller The truncated Series or DataFrame. See Also -------- DataFrame.loc : Select a subset of a DataFrame by label. DataFrame.iloc : Select a subset of a DataFrame by position. Notes ----- If the index being truncated contains only datetime values, `before` and `after` may be specified as strings instead of Timestamps. Examples -------- >>> df = pd.DataFrame({'A': ['a', 'b', 'c', 'd', 'e'], ... 'B': ['f', 'g', 'h', 'i', 'j'], ... 'C': ['k', 'l', 'm', 'n', 'o']}, ... index=[1, 2, 3, 4, 5]) >>> df A B C 1 a f k 2 b g l 3 c h m 4 d i n 5 e j o >>> df.truncate(before=2, after=4) A B C 2 b g l 3 c h m 4 d i n The columns of a DataFrame can be truncated. >>> df.truncate(before="A", after="B", axis="columns") A B 1 a f 2 b g 3 c h 4 d i 5 e j For Series, only rows can be truncated. >>> df['A'].truncate(before=2, after=4) 2 b 3 c 4 d Name: A, dtype: object The index values in ``truncate`` can be datetimes or string dates. >>> dates = pd.date_range('2016-01-01', '2016-02-01', freq='s') >>> df = pd.DataFrame(index=dates, data={'A': 1}) >>> df.tail() A 2016-01-31 23:59:56 1 2016-01-31 23:59:57 1 2016-01-31 23:59:58 1 2016-01-31 23:59:59 1 2016-02-01 00:00:00 1 >>> df.truncate(before=pd.Timestamp('2016-01-05'), ... after=pd.Timestamp('2016-01-10')).tail() A 2016-01-09 23:59:56 1 2016-01-09 23:59:57 1 2016-01-09 23:59:58 1 2016-01-09 23:59:59 1 2016-01-10 00:00:00 1 Because the index is a DatetimeIndex containing only dates, we can specify `before` and `after` as strings. They will be coerced to Timestamps before truncation. >>> df.truncate('2016-01-05', '2016-01-10').tail() A 2016-01-09 23:59:56 1 2016-01-09 23:59:57 1 2016-01-09 23:59:58 1 2016-01-09 23:59:59 1 2016-01-10 00:00:00 1 Note that ``truncate`` assumes a 0 value for any unspecified time component (midnight). This differs from partial string slicing, which returns any partially matching dates. >>> df.loc['2016-01-05':'2016-01-10', :].tail() A 2016-01-10 23:59:55 1 2016-01-10 23:59:56 1 2016-01-10 23:59:57 1 2016-01-10 23:59:58 1 2016-01-10 23:59:59 1 """ if axis is None: axis = self._stat_axis_number axis = self._get_axis_number(axis) ax = self._get_axis(axis) # GH 17935 # Check that index is sorted if not ax.is_monotonic_increasing and not ax.is_monotonic_decreasing: raise ValueError("truncate requires a sorted index") # if we have a date index, convert to dates, otherwise # treat like a slice if ax.is_all_dates: from pandas.core.tools.datetimes import to_datetime before = to_datetime(before) after = to_datetime(after) if before is not None and after is not None: if before > after: raise ValueError(f"Truncate: {after} must be after {before}") if ax.is_monotonic_decreasing: before, after = after, before slicer = [slice(None, None)] * self._AXIS_LEN slicer[axis] = slice(before, after) result = self.loc[tuple(slicer)] if isinstance(ax, MultiIndex): setattr(result, self._get_axis_name(axis), ax.truncate(before, after)) if copy: result = result.copy() return result def tz_convert( self: FrameOrSeries, tz, axis=0, level=None, copy: bool_t = True ) -> FrameOrSeries: """ Convert tz-aware axis to target time zone. Parameters ---------- tz : str or tzinfo object axis : the axis to convert level : int, str, default None If axis is a MultiIndex, convert a specific level. Otherwise must be None. copy : bool, default True Also make a copy of the underlying data. Returns ------- %(klass)s Object with time zone converted axis. Raises ------ TypeError If the axis is tz-naive. """ axis = self._get_axis_number(axis) ax = self._get_axis(axis) def _tz_convert(ax, tz): if not hasattr(ax, "tz_convert"): if len(ax) > 0: ax_name = self._get_axis_name(axis) raise TypeError( f"{ax_name} is not a valid DatetimeIndex or PeriodIndex" ) else: ax = DatetimeIndex([], tz=tz) else: ax = ax.tz_convert(tz) return ax # if a level is given it must be a MultiIndex level or # equivalent to the axis name if isinstance(ax, MultiIndex): level = ax._get_level_number(level) new_level = _tz_convert(ax.levels[level], tz) ax = ax.set_levels(new_level, level=level) else: if level not in (None, 0, ax.name): raise ValueError(f"The level {level} is not valid") ax = _tz_convert(ax, tz) result = self.copy(deep=copy) result = result.set_axis(ax, axis=axis, inplace=False) return result.__finalize__(self, method="tz_convert") def tz_localize( self: FrameOrSeries, tz, axis=0, level=None, copy: bool_t = True, ambiguous="raise", nonexistent: str = "raise", ) -> FrameOrSeries: """ Localize tz-naive index of a Series or DataFrame to target time zone. This operation localizes the Index. To localize the values in a timezone-naive Series, use :meth:`Series.dt.tz_localize`. Parameters ---------- tz : str or tzinfo axis : the axis to localize level : int, str, default None If axis ia a MultiIndex, localize a specific level. Otherwise must be None. copy : bool, default True Also make a copy of the underlying data. ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise' When clocks moved backward due to DST, ambiguous times may arise. For example in Central European Time (UTC+01), when going from 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the `ambiguous` parameter dictates how ambiguous times should be handled. - 'infer' will attempt to infer fall dst-transition hours based on order - bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times) - 'NaT' will return NaT where there are ambiguous times - 'raise' will raise an AmbiguousTimeError if there are ambiguous times. nonexistent : str, default 'raise' A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST. Valid values are: - 'shift_forward' will shift the nonexistent time forward to the closest existing time - 'shift_backward' will shift the nonexistent time backward to the closest existing time - 'NaT' will return NaT where there are nonexistent times - timedelta objects will shift nonexistent times by the timedelta - 'raise' will raise an NonExistentTimeError if there are nonexistent times. .. versionadded:: 0.24.0 Returns ------- Series or DataFrame Same type as the input. Raises ------ TypeError If the TimeSeries is tz-aware and tz is not None. Examples -------- Localize local times: >>> s = pd.Series([1], ... index=pd.DatetimeIndex(['2018-09-15 01:30:00'])) >>> s.tz_localize('CET') 2018-09-15 01:30:00+02:00 1 dtype: int64 Be careful with DST changes. When there is sequential data, pandas can infer the DST time: >>> s = pd.Series(range(7), ... index=pd.DatetimeIndex(['2018-10-28 01:30:00', ... '2018-10-28 02:00:00', ... '2018-10-28 02:30:00', ... '2018-10-28 02:00:00', ... '2018-10-28 02:30:00', ... '2018-10-28 03:00:00', ... '2018-10-28 03:30:00'])) >>> s.tz_localize('CET', ambiguous='infer') 2018-10-28 01:30:00+02:00 0 2018-10-28 02:00:00+02:00 1 2018-10-28 02:30:00+02:00 2 2018-10-28 02:00:00+01:00 3 2018-10-28 02:30:00+01:00 4 2018-10-28 03:00:00+01:00 5 2018-10-28 03:30:00+01:00 6 dtype: int64 In some cases, inferring the DST is impossible. In such cases, you can pass an ndarray to the ambiguous parameter to set the DST explicitly >>> s = pd.Series(range(3), ... index=pd.DatetimeIndex(['2018-10-28 01:20:00', ... '2018-10-28 02:36:00', ... '2018-10-28 03:46:00'])) >>> s.tz_localize('CET', ambiguous=np.array([True, True, False])) 2018-10-28 01:20:00+02:00 0 2018-10-28 02:36:00+02:00 1 2018-10-28 03:46:00+01:00 2 dtype: int64 If the DST transition causes nonexistent times, you can shift these dates forward or backwards with a timedelta object or `'shift_forward'` or `'shift_backwards'`. >>> s = pd.Series(range(2), ... index=pd.DatetimeIndex(['2015-03-29 02:30:00', ... '2015-03-29 03:30:00'])) >>> s.tz_localize('Europe/Warsaw', nonexistent='shift_forward') 2015-03-29 03:00:00+02:00 0 2015-03-29 03:30:00+02:00 1 dtype: int64 >>> s.tz_localize('Europe/Warsaw', nonexistent='shift_backward') 2015-03-29 01:59:59.999999999+01:00 0 2015-03-29 03:30:00+02:00 1 dtype: int64 >>> s.tz_localize('Europe/Warsaw', nonexistent=pd.Timedelta('1H')) 2015-03-29 03:30:00+02:00 0 2015-03-29 03:30:00+02:00 1 dtype: int64 """ nonexistent_options = ("raise", "NaT", "shift_forward", "shift_backward") if nonexistent not in nonexistent_options and not isinstance( nonexistent, timedelta ): raise ValueError( "The nonexistent argument must be one of 'raise', " "'NaT', 'shift_forward', 'shift_backward' or " "a timedelta object" ) axis = self._get_axis_number(axis) ax = self._get_axis(axis) def _tz_localize(ax, tz, ambiguous, nonexistent): if not hasattr(ax, "tz_localize"): if len(ax) > 0: ax_name = self._get_axis_name(axis) raise TypeError( f"{ax_name} is not a valid DatetimeIndex or PeriodIndex" ) else: ax = DatetimeIndex([], tz=tz) else: ax = ax.tz_localize(tz, ambiguous=ambiguous, nonexistent=nonexistent) return ax # if a level is given it must be a MultiIndex level or # equivalent to the axis name if isinstance(ax, MultiIndex): level = ax._get_level_number(level) new_level = _tz_localize(ax.levels[level], tz, ambiguous, nonexistent) ax = ax.set_levels(new_level, level=level) else: if level not in (None, 0, ax.name): raise ValueError(f"The level {level} is not valid") ax = _tz_localize(ax, tz, ambiguous, nonexistent) result = self.copy(deep=copy) result = result.set_axis(ax, axis=axis, inplace=False) return result.__finalize__(self, method="tz_localize") # ---------------------------------------------------------------------- # Numeric Methods def abs(self: FrameOrSeries) -> FrameOrSeries: """ Return a Series/DataFrame with absolute numeric value of each element. This function only applies to elements that are all numeric. Returns ------- abs Series/DataFrame containing the absolute value of each element. See Also -------- numpy.absolute : Calculate the absolute value element-wise. Notes ----- For ``complex`` inputs, ``1.2 + 1j``, the absolute value is :math:`\\sqrt{ a^2 + b^2 }`. Examples -------- Absolute numeric values in a Series. >>> s = pd.Series([-1.10, 2, -3.33, 4]) >>> s.abs() 0 1.10 1 2.00 2 3.33 3 4.00 dtype: float64 Absolute numeric values in a Series with complex numbers. >>> s = pd.Series([1.2 + 1j]) >>> s.abs() 0 1.56205 dtype: float64 Absolute numeric values in a Series with a Timedelta element. >>> s = pd.Series([pd.Timedelta('1 days')]) >>> s.abs() 0 1 days dtype: timedelta64[ns] Select rows with data closest to certain value using argsort (from `StackOverflow <https://stackoverflow.com/a/17758115>`__). >>> df = pd.DataFrame({ ... 'a': [4, 5, 6, 7], ... 'b': [10, 20, 30, 40], ... 'c': [100, 50, -30, -50] ... }) >>> df a b c 0 4 10 100 1 5 20 50 2 6 30 -30 3 7 40 -50 >>> df.loc[(df.c - 43).abs().argsort()] a b c 1 5 20 50 0 4 10 100 2 6 30 -30 3 7 40 -50 """ return np.abs(self) def describe( self: FrameOrSeries, percentiles=None, include=None, exclude=None ) -> FrameOrSeries: """ Generate descriptive statistics. Descriptive statistics include those that summarize the central tendency, dispersion and shape of a dataset's distribution, excluding ``NaN`` values. Analyzes both numeric and object series, as well as ``DataFrame`` column sets of mixed data types. The output will vary depending on what is provided. Refer to the notes below for more detail. Parameters ---------- percentiles : list-like of numbers, optional The percentiles to include in the output. All should fall between 0 and 1. The default is ``[.25, .5, .75]``, which returns the 25th, 50th, and 75th percentiles. include : 'all', list-like of dtypes or None (default), optional A white list of data types to include in the result. Ignored for ``Series``. Here are the options: - 'all' : All columns of the input will be included in the output. - A list-like of dtypes : Limits the results to the provided data types. To limit the result to numeric types submit ``numpy.number``. To limit it instead to object columns submit the ``numpy.object`` data type. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To select pandas categorical columns, use ``'category'`` - None (default) : The result will include all numeric columns. exclude : list-like of dtypes or None (default), optional, A black list of data types to omit from the result. Ignored for ``Series``. Here are the options: - A list-like of dtypes : Excludes the provided data types from the result. To exclude numeric types submit ``numpy.number``. To exclude object columns submit the data type ``numpy.object``. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To exclude pandas categorical columns, use ``'category'`` - None (default) : The result will exclude nothing. Returns ------- Series or DataFrame Summary statistics of the Series or Dataframe provided. See Also -------- DataFrame.count: Count number of non-NA/null observations. DataFrame.max: Maximum of the values in the object. DataFrame.min: Minimum of the values in the object. DataFrame.mean: Mean of the values. DataFrame.std: Standard deviation of the observations. DataFrame.select_dtypes: Subset of a DataFrame including/excluding columns based on their dtype. Notes ----- For numeric data, the result's index will include ``count``, ``mean``, ``std``, ``min``, ``max`` as well as lower, ``50`` and upper percentiles. By default the lower percentile is ``25`` and the upper percentile is ``75``. The ``50`` percentile is the same as the median. For object data (e.g. strings or timestamps), the result's index will include ``count``, ``unique``, ``top``, and ``freq``. The ``top`` is the most common value. The ``freq`` is the most common value's frequency. Timestamps also include the ``first`` and ``last`` items. If multiple object values have the highest count, then the ``count`` and ``top`` results will be arbitrarily chosen from among those with the highest count. For mixed data types provided via a ``DataFrame``, the default is to return only an analysis of numeric columns. If the dataframe consists only of object and categorical data without any numeric columns, the default is to return an analysis of both the object and categorical columns. If ``include='all'`` is provided as an option, the result will include a union of attributes of each type. The `include` and `exclude` parameters can be used to limit which columns in a ``DataFrame`` are analyzed for the output. The parameters are ignored when analyzing a ``Series``. Examples -------- Describing a numeric ``Series``. >>> s = pd.Series([1, 2, 3]) >>> s.describe() count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 dtype: float64 Describing a categorical ``Series``. >>> s = pd.Series(['a', 'a', 'b', 'c']) >>> s.describe() count 4 unique 3 top a freq 2 dtype: object Describing a timestamp ``Series``. >>> s = pd.Series([ ... np.datetime64("2000-01-01"), ... np.datetime64("2010-01-01"), ... np.datetime64("2010-01-01") ... ]) >>> s.describe() count 3 mean 2006-09-01 08:00:00 min 2000-01-01 00:00:00 25% 2004-12-31 12:00:00 50% 2010-01-01 00:00:00 75% 2010-01-01 00:00:00 max 2010-01-01 00:00:00 dtype: object Describing a ``DataFrame``. By default only numeric fields are returned. >>> df = pd.DataFrame({'categorical': pd.Categorical(['d','e','f']), ... 'numeric': [1, 2, 3], ... 'object': ['a', 'b', 'c'] ... }) >>> df.describe() numeric count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Describing all columns of a ``DataFrame`` regardless of data type. >>> df.describe(include='all') # doctest: +SKIP categorical numeric object count 3 3.0 3 unique 3 NaN 3 top f NaN a freq 1 NaN 1 mean NaN 2.0 NaN std NaN 1.0 NaN min NaN 1.0 NaN 25% NaN 1.5 NaN 50% NaN 2.0 NaN 75% NaN 2.5 NaN max NaN 3.0 NaN Describing a column from a ``DataFrame`` by accessing it as an attribute. >>> df.numeric.describe() count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Name: numeric, dtype: float64 Including only numeric columns in a ``DataFrame`` description. >>> df.describe(include=[np.number]) numeric count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Including only string columns in a ``DataFrame`` description. >>> df.describe(include=[np.object]) # doctest: +SKIP object count 3 unique 3 top a freq 1 Including only categorical columns from a ``DataFrame`` description. >>> df.describe(include=['category']) categorical count 3 unique 3 top f freq 1 Excluding numeric columns from a ``DataFrame`` description. >>> df.describe(exclude=[np.number]) # doctest: +SKIP categorical object count 3 3 unique 3 3 top f a freq 1 1 Excluding object columns from a ``DataFrame`` description. >>> df.describe(exclude=[np.object]) # doctest: +SKIP categorical numeric count 3 3.0 unique 3 NaN top f NaN freq 1 NaN mean NaN 2.0 std NaN 1.0 min NaN 1.0 25% NaN 1.5 50% NaN 2.0 75% NaN 2.5 max NaN 3.0 """ if self.ndim == 2 and self.columns.size == 0: raise ValueError("Cannot describe a DataFrame without columns") if percentiles is not None: # explicit conversion of `percentiles` to list percentiles = list(percentiles) # get them all to be in [0, 1] validate_percentile(percentiles) # median should always be included if 0.5 not in percentiles: percentiles.append(0.5) percentiles = np.asarray(percentiles) else: percentiles = np.array([0.25, 0.5, 0.75]) # sort and check for duplicates unique_pcts = np.unique(percentiles) if len(unique_pcts) < len(percentiles): raise ValueError("percentiles cannot contain duplicates") percentiles = unique_pcts formatted_percentiles = format_percentiles(percentiles) def describe_numeric_1d(series): stat_index = ( ["count", "mean", "std", "min"] + formatted_percentiles + ["max"] ) d = ( [series.count(), series.mean(), series.std(), series.min()] + series.quantile(percentiles).tolist() + [series.max()] ) return pd.Series(d, index=stat_index, name=series.name) def describe_categorical_1d(data): names = ["count", "unique"] objcounts = data.value_counts() count_unique = len(objcounts[objcounts != 0]) result = [data.count(), count_unique] dtype = None if result[1] > 0: top, freq = objcounts.index[0], objcounts.iloc[0] names += ["top", "freq"] result += [top, freq] # If the DataFrame is empty, set 'top' and 'freq' to None # to maintain output shape consistency else: names += ["top", "freq"] result += [np.nan, np.nan] dtype = "object" return pd.Series(result, index=names, name=data.name, dtype=dtype) def describe_timestamp_1d(data): # GH-30164 stat_index = ["count", "mean", "min"] + formatted_percentiles + ["max"] d = ( [data.count(), data.mean(), data.min()] + data.quantile(percentiles).tolist() + [data.max()] ) return pd.Series(d, index=stat_index, name=data.name) def describe_1d(data): if is_bool_dtype(data.dtype): return describe_categorical_1d(data) elif is_numeric_dtype(data): return describe_numeric_1d(data) elif is_datetime64_any_dtype(data.dtype): return describe_timestamp_1d(data) elif is_timedelta64_dtype(data.dtype): return describe_numeric_1d(data) else: return describe_categorical_1d(data) if self.ndim == 1: return describe_1d(self) elif (include is None) and (exclude is None): # when some numerics are found, keep only numerics data = self.select_dtypes(include=[np.number]) if len(data.columns) == 0: data = self elif include == "all": if exclude is not None: msg = "exclude must be None when include is 'all'" raise ValueError(msg) data = self else: data = self.select_dtypes(include=include, exclude=exclude) ldesc = [describe_1d(s) for _, s in data.items()] # set a convenient order for rows names: List[Label] = [] ldesc_indexes = sorted((x.index for x in ldesc), key=len) for idxnames in ldesc_indexes: for name in idxnames: if name not in names: names.append(name) d = pd.concat([x.reindex(names, copy=False) for x in ldesc], axis=1, sort=False) d.columns = data.columns.copy() return d _shared_docs[ "pct_change" ] = """ Percentage change between the current and a prior element. Computes the percentage change from the immediately previous row by default. This is useful in comparing the percentage of change in a time series of elements. Parameters ---------- periods : int, default 1 Periods to shift for forming percent change. fill_method : str, default 'pad' How to handle NAs before computing percent changes. limit : int, default None The number of consecutive NAs to fill before stopping. freq : DateOffset, timedelta, or str, optional Increment to use from time series API (e.g. 'M' or BDay()). **kwargs Additional keyword arguments are passed into `DataFrame.shift` or `Series.shift`. Returns ------- chg : Series or DataFrame The same type as the calling object. See Also -------- Series.diff : Compute the difference of two elements in a Series. DataFrame.diff : Compute the difference of two elements in a DataFrame. Series.shift : Shift the index by some number of periods. DataFrame.shift : Shift the index by some number of periods. Examples -------- **Series** >>> s = pd.Series([90, 91, 85]) >>> s 0 90 1 91 2 85 dtype: int64 >>> s.pct_change() 0 NaN 1 0.011111 2 -0.065934 dtype: float64 >>> s.pct_change(periods=2) 0 NaN 1 NaN 2 -0.055556 dtype: float64 See the percentage change in a Series where filling NAs with last valid observation forward to next valid. >>> s = pd.Series([90, 91, None, 85]) >>> s 0 90.0 1 91.0 2 NaN 3 85.0 dtype: float64 >>> s.pct_change(fill_method='ffill') 0 NaN 1 0.011111 2 0.000000 3 -0.065934 dtype: float64 **DataFrame** Percentage change in French franc, Deutsche Mark, and Italian lira from 1980-01-01 to 1980-03-01. >>> df = pd.DataFrame({ ... 'FR': [4.0405, 4.0963, 4.3149], ... 'GR': [1.7246, 1.7482, 1.8519], ... 'IT': [804.74, 810.01, 860.13]}, ... index=['1980-01-01', '1980-02-01', '1980-03-01']) >>> df FR GR IT 1980-01-01 4.0405 1.7246 804.74 1980-02-01 4.0963 1.7482 810.01 1980-03-01 4.3149 1.8519 860.13 >>> df.pct_change() FR GR IT 1980-01-01 NaN NaN NaN 1980-02-01 0.013810 0.013684 0.006549 1980-03-01 0.053365 0.059318 0.061876 Percentage of change in GOOG and APPL stock volume. Shows computing the percentage change between columns. >>> df = pd.DataFrame({ ... '2016': [1769950, 30586265], ... '2015': [1500923, 40912316], ... '2014': [1371819, 41403351]}, ... index=['GOOG', 'APPL']) >>> df 2016 2015 2014 GOOG 1769950 1500923 1371819 APPL 30586265 40912316 41403351 >>> df.pct_change(axis='columns') 2016 2015 2014 GOOG NaN -0.151997 -0.086016 APPL NaN 0.337604 0.012002 """ @Appender(_shared_docs["pct_change"] % _shared_doc_kwargs) def pct_change( self: FrameOrSeries, periods=1, fill_method="pad", limit=None, freq=None, **kwargs, ) -> FrameOrSeries: # TODO: Not sure if above is correct - need someone to confirm. axis = self._get_axis_number(kwargs.pop("axis", self._stat_axis_name)) if fill_method is None: data = self else: _data = self.fillna(method=fill_method, axis=axis, limit=limit) assert _data is not None # needed for mypy data = _data rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1 if freq is not None: # Shift method is implemented differently when freq is not None # We want to restore the original index rs = rs.loc[~rs.index.duplicated()] rs = rs.reindex_like(data) return rs def _agg_by_level(self, name, axis=0, level=0, skipna=True, **kwargs): if axis is None: raise ValueError("Must specify 'axis' when aggregating by level.") grouped = self.groupby(level=level, axis=axis, sort=False) if hasattr(grouped, name) and skipna: return getattr(grouped, name)(**kwargs) axis = self._get_axis_number(axis) method = getattr(type(self), name) applyf = lambda x: method(x, axis=axis, skipna=skipna, **kwargs) return grouped.aggregate(applyf) @classmethod def _add_numeric_operations(cls): """ Add the operations to the cls; evaluate the doc strings again """ axis_descr, name1, name2 = _doc_parms(cls) cls.any = _make_logical_function( cls, "any", name1=name1, name2=name2, axis_descr=axis_descr, desc=_any_desc, func=nanops.nanany, see_also=_any_see_also, examples=_any_examples, empty_value=False, ) cls.all = _make_logical_function( cls, "all", name1=name1, name2=name2, axis_descr=axis_descr, desc=_all_desc, func=nanops.nanall, see_also=_all_see_also, examples=_all_examples, empty_value=True, ) @Substitution( desc="Return the mean absolute deviation of the values " "for the requested axis.", name1=name1, name2=name2, axis_descr=axis_descr, min_count="", see_also="", examples="", ) @Appender(_num_doc_mad) def mad(self, axis=None, skipna=None, level=None): if skipna is None: skipna = True if axis is None: axis = self._stat_axis_number if level is not None: return self._agg_by_level("mad", axis=axis, level=level, skipna=skipna) data = self._get_numeric_data() if axis == 0: demeaned = data - data.mean(axis=0) else: demeaned = data.sub(data.mean(axis=1), axis=0) return np.abs(demeaned).mean(axis=axis, skipna=skipna) cls.mad = mad cls.sem = _make_stat_function_ddof( cls, "sem", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return unbiased standard error of the mean over requested " "axis.\n\nNormalized by N-1 by default. This can be changed " "using the ddof argument", func=nanops.nansem, ) cls.var = _make_stat_function_ddof( cls, "var", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return unbiased variance over requested axis.\n\nNormalized by " "N-1 by default. This can be changed using the ddof argument", func=nanops.nanvar, ) cls.std = _make_stat_function_ddof( cls, "std", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return sample standard deviation over requested axis." "\n\nNormalized by N-1 by default. This can be changed using the " "ddof argument", func=nanops.nanstd, ) cls.cummin = _make_cum_function( cls, "cummin", name1=name1, name2=name2, axis_descr=axis_descr, desc="minimum", accum_func=np.minimum.accumulate, accum_func_name="min", examples=_cummin_examples, ) cls.cumsum = _make_cum_function( cls, "cumsum", name1=name1, name2=name2, axis_descr=axis_descr, desc="sum", accum_func=np.cumsum, accum_func_name="sum", examples=_cumsum_examples, ) cls.cumprod = _make_cum_function( cls, "cumprod", name1=name1, name2=name2, axis_descr=axis_descr, desc="product", accum_func=np.cumprod, accum_func_name="prod", examples=_cumprod_examples, ) cls.cummax = _make_cum_function( cls, "cummax", name1=name1, name2=name2, axis_descr=axis_descr, desc="maximum", accum_func=np.maximum.accumulate, accum_func_name="max", examples=_cummax_examples, ) cls.sum = _make_min_count_stat_function( cls, "sum", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return the sum of the values for the requested axis.\n\n" "This is equivalent to the method ``numpy.sum``.", func=nanops.nansum, see_also=_stat_func_see_also, examples=_sum_examples, ) cls.mean = _make_stat_function( cls, "mean", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return the mean of the values for the requested axis.", func=nanops.nanmean, ) cls.skew = _make_stat_function( cls, "skew", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return unbiased skew over requested axis.\n\nNormalized by N-1.", func=nanops.nanskew, ) cls.kurt = _make_stat_function( cls, "kurt", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return unbiased kurtosis over requested axis.\n\n" "Kurtosis obtained using Fisher's definition of\n" "kurtosis (kurtosis of normal == 0.0). Normalized " "by N-1.", func=nanops.nankurt, ) cls.kurtosis = cls.kurt cls.prod = _make_min_count_stat_function( cls, "prod", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return the product of the values for the requested axis.", func=nanops.nanprod, examples=_prod_examples, ) cls.product = cls.prod cls.median = _make_stat_function( cls, "median", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return the median of the values for the requested axis.", func=nanops.nanmedian, ) cls.max = _make_stat_function( cls, "max", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return the maximum of the values for the requested axis.\n\n" "If you want the *index* of the maximum, use ``idxmax``. This is" "the equivalent of the ``numpy.ndarray`` method ``argmax``.", func=nanops.nanmax, see_also=_stat_func_see_also, examples=_max_examples, ) cls.min = _make_stat_function( cls, "min", name1=name1, name2=name2, axis_descr=axis_descr, desc="Return the minimum of the values for the requested axis.\n\n" "If you want the *index* of the minimum, use ``idxmin``. This is" "the equivalent of the ``numpy.ndarray`` method ``argmin``.", func=nanops.nanmin, see_also=_stat_func_see_also, examples=_min_examples, ) @classmethod def _add_series_or_dataframe_operations(cls): """ Add the series or dataframe only operations to the cls; evaluate the doc strings again. """ from pandas.core.window import EWM, Expanding, Rolling, Window @doc(Rolling) def rolling( self, window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None, ): axis = self._get_axis_number(axis) if win_type is not None: return Window( self, window=window, min_periods=min_periods, center=center, win_type=win_type, on=on, axis=axis, closed=closed, ) return Rolling( self, window=window, min_periods=min_periods, center=center, win_type=win_type, on=on, axis=axis, closed=closed, ) cls.rolling = rolling @doc(Expanding) def expanding(self, min_periods=1, center=False, axis=0): axis = self._get_axis_number(axis) return Expanding(self, min_periods=min_periods, center=center, axis=axis) cls.expanding = expanding @doc(EWM) def ewm( self, com=None, span=None, halflife=None, alpha=None, min_periods=0, adjust=True, ignore_na=False, axis=0, ): axis = self._get_axis_number(axis) return EWM( self, com=com, span=span, halflife=halflife, alpha=alpha, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na, axis=axis, ) cls.ewm = ewm @Appender(_shared_docs["transform"] % dict(axis="", **_shared_doc_kwargs)) def transform(self, func, *args, **kwargs): result = self.agg(func, *args, **kwargs) if is_scalar(result) or len(result) != len(self): raise ValueError("transforms cannot produce aggregated results") return result # ---------------------------------------------------------------------- # Misc methods _shared_docs[ "valid_index" ] = """ Return index for %(position)s non-NA/null value. Returns ------- scalar : type of index Notes ----- If all elements are non-NA/null, returns None. Also returns None for empty %(klass)s. """ def _find_valid_index(self, how: str): """ Retrieves the index of the first valid value. Parameters ---------- how : {'first', 'last'} Use this parameter to change between the first or last valid index. Returns ------- idx_first_valid : type of index """ idxpos = find_valid_index(self._values, how) if idxpos is None: return None return self.index[idxpos] @Appender( _shared_docs["valid_index"] % {"position": "first", "klass": "Series/DataFrame"} ) def first_valid_index(self): return self._find_valid_index("first") @Appender( _shared_docs["valid_index"] % {"position": "last", "klass": "Series/DataFrame"} ) def last_valid_index(self): return self._find_valid_index("last") def _doc_parms(cls): """Return a tuple of the doc parms.""" axis_descr = ( f"{{{', '.join(f'{a} ({i})' for i, a in enumerate(cls._AXIS_ORDERS))}}}" ) name = cls._constructor_sliced.__name__ if cls._AXIS_LEN > 1 else "scalar" name2 = cls.__name__ return axis_descr, name, name2 _num_doc = """ %(desc)s Parameters ---------- axis : %(axis_descr)s Axis for the function to be applied on. skipna : bool, default True Exclude NA/null values when computing the result. level : int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a %(name1)s. numeric_only : bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. %(min_count)s\ **kwargs Additional keyword arguments to be passed to the function. Returns ------- %(name1)s or %(name2)s (if level specified)\ %(see_also)s\ %(examples)s """ _num_doc_mad = """ %(desc)s Parameters ---------- axis : %(axis_descr)s Axis for the function to be applied on. skipna : bool, default None Exclude NA/null values when computing the result. level : int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a %(name1)s. Returns ------- %(name1)s or %(name2)s (if level specified)\ %(see_also)s\ %(examples)s """ _num_ddof_doc = """ %(desc)s Parameters ---------- axis : %(axis_descr)s skipna : bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. level : int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a %(name1)s. ddof : int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. numeric_only : bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. Returns ------- %(name1)s or %(name2)s (if level specified)\n""" _bool_doc = """ %(desc)s Parameters ---------- axis : {0 or 'index', 1 or 'columns', None}, default 0 Indicate which axis or axes should be reduced. * 0 / 'index' : reduce the index, return a Series whose index is the original column labels. * 1 / 'columns' : reduce the columns, return a Series whose index is the original index. * None : reduce all axes, return a scalar. bool_only : bool, default None Include only boolean columns. If None, will attempt to use everything, then use only boolean data. Not implemented for Series. skipna : bool, default True Exclude NA/null values. If the entire row/column is NA and skipna is True, then the result will be %(empty_value)s, as for an empty row/column. If skipna is False, then NA are treated as True, because these are not equal to zero. level : int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a %(name1)s. **kwargs : any, default None Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- %(name1)s or %(name2)s If level is specified, then, %(name2)s is returned; otherwise, %(name1)s is returned. %(see_also)s %(examples)s""" _all_desc = """\ Return whether all elements are True, potentially over an axis. Returns True unless there at least one element within a series or along a Dataframe axis that is False or equivalent (e.g. zero or empty).""" _all_examples = """\ Examples -------- **Series** >>> pd.Series([True, True]).all() True >>> pd.Series([True, False]).all() False >>> pd.Series([]).all() True >>> pd.Series([np.nan]).all() True >>> pd.Series([np.nan]).all(skipna=False) True **DataFrames** Create a dataframe from a dictionary. >>> df = pd.DataFrame({'col1': [True, True], 'col2': [True, False]}) >>> df col1 col2 0 True True 1 True False Default behaviour checks if column-wise values all return True. >>> df.all() col1 True col2 False dtype: bool Specify ``axis='columns'`` to check if row-wise values all return True. >>> df.all(axis='columns') 0 True 1 False dtype: bool Or ``axis=None`` for whether every value is True. >>> df.all(axis=None) False """ _all_see_also = """\ See Also -------- Series.all : Return True if all elements are True. DataFrame.any : Return True if one (or more) elements are True. """ _cnum_doc = """ Return cumulative %(desc)s over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative %(desc)s. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The index or the name of the axis. 0 is equivalent to None or 'index'. skipna : bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. *args, **kwargs Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- %(name1)s or %(name2)s Return cumulative %(desc)s of %(name1)s or %(name2)s. See Also -------- core.window.Expanding.%(accum_func_name)s : Similar functionality but ignores ``NaN`` values. %(name2)s.%(accum_func_name)s : Return the %(desc)s over %(name2)s axis. %(name2)s.cummax : Return cumulative maximum over %(name2)s axis. %(name2)s.cummin : Return cumulative minimum over %(name2)s axis. %(name2)s.cumsum : Return cumulative sum over %(name2)s axis. %(name2)s.cumprod : Return cumulative product over %(name2)s axis. %(examples)s""" _cummin_examples = """\ Examples -------- **Series** >>> s = pd.Series([2, np.nan, 5, -1, 0]) >>> s 0 2.0 1 NaN 2 5.0 3 -1.0 4 0.0 dtype: float64 By default, NA values are ignored. >>> s.cummin() 0 2.0 1 NaN 2 2.0 3 -1.0 4 -1.0 dtype: float64 To include NA values in the operation, use ``skipna=False`` >>> s.cummin(skipna=False) 0 2.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 **DataFrame** >>> df = pd.DataFrame([[2.0, 1.0], ... [3.0, np.nan], ... [1.0, 0.0]], ... columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the minimum in each column. This is equivalent to ``axis=None`` or ``axis='index'``. >>> df.cummin() A B 0 2.0 1.0 1 2.0 NaN 2 1.0 0.0 To iterate over columns and find the minimum in each row, use ``axis=1`` >>> df.cummin(axis=1) A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 """ _cumsum_examples = """\ Examples -------- **Series** >>> s = pd.Series([2, np.nan, 5, -1, 0]) >>> s 0 2.0 1 NaN 2 5.0 3 -1.0 4 0.0 dtype: float64 By default, NA values are ignored. >>> s.cumsum() 0 2.0 1 NaN 2 7.0 3 6.0 4 6.0 dtype: float64 To include NA values in the operation, use ``skipna=False`` >>> s.cumsum(skipna=False) 0 2.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 **DataFrame** >>> df = pd.DataFrame([[2.0, 1.0], ... [3.0, np.nan], ... [1.0, 0.0]], ... columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the sum in each column. This is equivalent to ``axis=None`` or ``axis='index'``. >>> df.cumsum() A B 0 2.0 1.0 1 5.0 NaN 2 6.0 1.0 To iterate over columns and find the sum in each row, use ``axis=1`` >>> df.cumsum(axis=1) A B 0 2.0 3.0 1 3.0 NaN 2 1.0 1.0 """ _cumprod_examples = """\ Examples -------- **Series** >>> s = pd.Series([2, np.nan, 5, -1, 0]) >>> s 0 2.0 1 NaN 2 5.0 3 -1.0 4 0.0 dtype: float64 By default, NA values are ignored. >>> s.cumprod() 0 2.0 1 NaN 2 10.0 3 -10.0 4 -0.0 dtype: float64 To include NA values in the operation, use ``skipna=False`` >>> s.cumprod(skipna=False) 0 2.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 **DataFrame** >>> df = pd.DataFrame([[2.0, 1.0], ... [3.0, np.nan], ... [1.0, 0.0]], ... columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the product in each column. This is equivalent to ``axis=None`` or ``axis='index'``. >>> df.cumprod() A B 0 2.0 1.0 1 6.0 NaN 2 6.0 0.0 To iterate over columns and find the product in each row, use ``axis=1`` >>> df.cumprod(axis=1) A B 0 2.0 2.0 1 3.0 NaN 2 1.0 0.0 """ _cummax_examples = """\ Examples -------- **Series** >>> s = pd.Series([2, np.nan, 5, -1, 0]) >>> s 0 2.0 1 NaN 2 5.0 3 -1.0 4 0.0 dtype: float64 By default, NA values are ignored. >>> s.cummax() 0 2.0 1 NaN 2 5.0 3 5.0 4 5.0 dtype: float64 To include NA values in the operation, use ``skipna=False`` >>> s.cummax(skipna=False) 0 2.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 **DataFrame** >>> df = pd.DataFrame([[2.0, 1.0], ... [3.0, np.nan], ... [1.0, 0.0]], ... columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the maximum in each column. This is equivalent to ``axis=None`` or ``axis='index'``. >>> df.cummax() A B 0 2.0 1.0 1 3.0 NaN 2 3.0 1.0 To iterate over columns and find the maximum in each row, use ``axis=1`` >>> df.cummax(axis=1) A B 0 2.0 2.0 1 3.0 NaN 2 1.0 1.0 """ _any_see_also = """\ See Also -------- numpy.any : Numpy version of this method. Series.any : Return whether any element is True. Series.all : Return whether all elements are True. DataFrame.any : Return whether any element is True over requested axis. DataFrame.all : Return whether all elements are True over requested axis. """ _any_desc = """\ Return whether any element is True, potentially over an axis. Returns False unless there at least one element within a series or along a Dataframe axis that is True or equivalent (e.g. non-zero or non-empty).""" _any_examples = """\ Examples -------- **Series** For Series input, the output is a scalar indicating whether any element is True. >>> pd.Series([False, False]).any() False >>> pd.Series([True, False]).any() True >>> pd.Series([]).any() False >>> pd.Series([np.nan]).any() False >>> pd.Series([np.nan]).any(skipna=False) True **DataFrame** Whether each column contains at least one True element (the default). >>> df = pd.DataFrame({"A": [1, 2], "B": [0, 2], "C": [0, 0]}) >>> df A B C 0 1 0 0 1 2 2 0 >>> df.any() A True B True C False dtype: bool Aggregating over the columns. >>> df = pd.DataFrame({"A": [True, False], "B": [1, 2]}) >>> df A B 0 True 1 1 False 2 >>> df.any(axis='columns') 0 True 1 True dtype: bool >>> df = pd.DataFrame({"A": [True, False], "B": [1, 0]}) >>> df A B 0 True 1 1 False 0 >>> df.any(axis='columns') 0 True 1 False dtype: bool Aggregating over the entire DataFrame with ``axis=None``. >>> df.any(axis=None) True `any` for an empty DataFrame is an empty Series. >>> pd.DataFrame([]).any() Series([], dtype: bool) """ _shared_docs[ "stat_func_example" ] = """ Examples -------- >>> idx = pd.MultiIndex.from_arrays([ ... ['warm', 'warm', 'cold', 'cold'], ... ['dog', 'falcon', 'fish', 'spider']], ... names=['blooded', 'animal']) >>> s = pd.Series([4, 2, 0, 8], name='legs', index=idx) >>> s blooded animal warm dog 4 falcon 2 cold fish 0 spider 8 Name: legs, dtype: int64 >>> s.{stat_func}() {default_output} {verb} using level names, as well as indices. >>> s.{stat_func}(level='blooded') blooded warm {level_output_0} cold {level_output_1} Name: legs, dtype: int64 >>> s.{stat_func}(level=0) blooded warm {level_output_0} cold {level_output_1} Name: legs, dtype: int64""" _sum_examples = _shared_docs["stat_func_example"].format( stat_func="sum", verb="Sum", default_output=14, level_output_0=6, level_output_1=8 ) _sum_examples += """ By default, the sum of an empty or all-NA Series is ``0``. >>> pd.Series([]).sum() # min_count=0 is the default 0.0 This can be controlled with the ``min_count`` parameter. For example, if you'd like the sum of an empty series to be NaN, pass ``min_count=1``. >>> pd.Series([]).sum(min_count=1) nan Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and empty series identically. >>> pd.Series([np.nan]).sum() 0.0 >>> pd.Series([np.nan]).sum(min_count=1) nan""" _max_examples = _shared_docs["stat_func_example"].format( stat_func="max", verb="Max", default_output=8, level_output_0=4, level_output_1=8 ) _min_examples = _shared_docs["stat_func_example"].format( stat_func="min", verb="Min", default_output=0, level_output_0=2, level_output_1=0 ) _stat_func_see_also = """ See Also -------- Series.sum : Return the sum. Series.min : Return the minimum. Series.max : Return the maximum. Series.idxmin : Return the index of the minimum. Series.idxmax : Return the index of the maximum. DataFrame.sum : Return the sum over the requested axis. DataFrame.min : Return the minimum over the requested axis. DataFrame.max : Return the maximum over the requested axis. DataFrame.idxmin : Return the index of the minimum over the requested axis. DataFrame.idxmax : Return the index of the maximum over the requested axis.""" _prod_examples = """ Examples -------- By default, the product of an empty or all-NA Series is ``1`` >>> pd.Series([]).prod() 1.0 This can be controlled with the ``min_count`` parameter >>> pd.Series([]).prod(min_count=1) nan Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and empty series identically. >>> pd.Series([np.nan]).prod() 1.0 >>> pd.Series([np.nan]).prod(min_count=1) nan""" _min_count_stub = """\ min_count : int, default 0 The required number of valid values to perform the operation. If fewer than ``min_count`` non-NA values are present the result will be NA. .. versionadded:: 0.22.0 Added with the default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1. """ def _make_min_count_stat_function( cls, name: str, name1: str, name2: str, axis_descr: str, desc: str, func: Callable, see_also: str = "", examples: str = "", ) -> Callable: @Substitution( desc=desc, name1=name1, name2=name2, axis_descr=axis_descr, min_count=_min_count_stub, see_also=see_also, examples=examples, ) @Appender(_num_doc) def stat_func( self, axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs, ): if name == "sum": nv.validate_sum(tuple(), kwargs) elif name == "prod": nv.validate_prod(tuple(), kwargs) else: nv.validate_stat_func(tuple(), kwargs, fname=name) if skipna is None: skipna = True if axis is None: axis = self._stat_axis_number if level is not None: return self._agg_by_level( name, axis=axis, level=level, skipna=skipna, min_count=min_count ) return self._reduce( func, name=name, axis=axis, skipna=skipna, numeric_only=numeric_only, min_count=min_count, ) return set_function_name(stat_func, name, cls) def _make_stat_function( cls, name: str, name1: str, name2: str, axis_descr: str, desc: str, func: Callable, see_also: str = "", examples: str = "", ) -> Callable: @Substitution( desc=desc, name1=name1, name2=name2, axis_descr=axis_descr, min_count="", see_also=see_also, examples=examples, ) @Appender(_num_doc) def stat_func( self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs ): if name == "median": nv.validate_median(tuple(), kwargs) else: nv.validate_stat_func(tuple(), kwargs, fname=name) if skipna is None: skipna = True if axis is None: axis = self._stat_axis_number if level is not None: return self._agg_by_level(name, axis=axis, level=level, skipna=skipna) return self._reduce( func, name=name, axis=axis, skipna=skipna, numeric_only=numeric_only ) return set_function_name(stat_func, name, cls) def _make_stat_function_ddof( cls, name: str, name1: str, name2: str, axis_descr: str, desc: str, func: Callable ) -> Callable: @Substitution(desc=desc, name1=name1, name2=name2, axis_descr=axis_descr) @Appender(_num_ddof_doc) def stat_func( self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs ): nv.validate_stat_ddof_func(tuple(), kwargs, fname=name) if skipna is None: skipna = True if axis is None: axis = self._stat_axis_number if level is not None: return self._agg_by_level( name, axis=axis, level=level, skipna=skipna, ddof=ddof ) return self._reduce( func, name, axis=axis, numeric_only=numeric_only, skipna=skipna, ddof=ddof ) return set_function_name(stat_func, name, cls) def _make_cum_function( cls, name: str, name1: str, name2: str, axis_descr: str, desc: str, accum_func: Callable, accum_func_name: str, examples: str, ) -> Callable: @Substitution( desc=desc, name1=name1, name2=name2, axis_descr=axis_descr, accum_func_name=accum_func_name, examples=examples, ) @Appender(_cnum_doc) def cum_func(self, axis=None, skipna=True, *args, **kwargs): skipna = nv.validate_cum_func_with_skipna(skipna, args, kwargs, name) if axis is None: axis = self._stat_axis_number else: axis = self._get_axis_number(axis) if axis == 1: return cum_func(self.T, axis=0, skipna=skipna, *args, **kwargs).T def block_accum_func(blk_values): values = blk_values.T if hasattr(blk_values, "T") else blk_values result = nanops.na_accum_func(values, accum_func, skipna=skipna) result = result.T if hasattr(result, "T") else result return result result = self._mgr.apply(block_accum_func) return self._constructor(result).__finalize__(self, method=name) return set_function_name(cum_func, name, cls) def _make_logical_function( cls, name: str, name1: str, name2: str, axis_descr: str, desc: str, func: Callable, see_also: str, examples: str, empty_value: bool, ) -> Callable: @Substitution( desc=desc, name1=name1, name2=name2, axis_descr=axis_descr, see_also=see_also, examples=examples, empty_value=empty_value, ) @Appender(_bool_doc) def logical_func(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): nv.validate_logical_func(tuple(), kwargs, fname=name) if level is not None: if bool_only is not None: raise NotImplementedError( "Option bool_only is not implemented with option level." ) return self._agg_by_level(name, axis=axis, level=level, skipna=skipna) return self._reduce( func, name=name, axis=axis, skipna=skipna, numeric_only=bool_only, filter_type="bool", ) return set_function_name(logical_func, name, cls)
from prettyprinter import pformat import inspect from functools import cached_property class PickleableState: def __init__(self, kwds): self.attrs = list(kwds.keys()) self.filename: str = kwds['format_filename'] self.frame: PickleableFrame = kwds['frame'] self.event: str = kwds['event'] self.arg: Any = kwds['arg'] self.f_locals: Dict = kwds['f_locals'] self.count: int = kwds['count'] self.function: str = kwds['function'] self.module: str = kwds['module'] self.lineno: int = kwds['lineno'] self.stdlib: bool = kwds['stdlib'] self.source: str = kwds['source'] def __str__(self): l = [] for attr in self.attrs: l.append(f"{attr}={getattr(self,attr,"None")}") s = "\n".join(l) return s def asdict(self): return self.__dict__ @property def indent(self): idt = '\u0020' + (len(PickleableState.stack)-1) return idt stack = [] @cached_property def format_call(self): symbol = "=>" PickleableState.stack.append(f"{self.module}.{self.function}") self.formatter1 = ( # default formatter f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" f"{self.indent}|{symbol}|{self.function}|{self.locals}" ) self.formatter2 = ( # indented formatter f"{self.indent}|{symbol}|{self.function}|{self.locals}|" f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" ) return self.formatter2 @cached_property def format_line(self): symbol = " " self.formatter1 = ( # default formatter f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" f"{self.indent} |{symbol}|{self.source}|" ) self.formatter2 = ( # indented formatter f"{self.indent} |{symbol}|{self.source}|" f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" ) return self.formatter2 @cached_property def format_return(self): symbol = "<=" self.formatter1 = ( # default formatter f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" f"{self.indent}|{symbol}|{self.function}|{self.arg}" ) self.formatter2 = ( # indented formatter f"{self.indent}|{symbol}|{self.function}|{self.arg}|" f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" ) if PickleableState.stack and PickleableState.stack[-1] == f"{self.module}.{self.function}": PickleableState.stack.pop() return self.formatter2 @cached_property def format_exception(self): symbol = " !" self.formatter1 = ( # default formatter f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" f"{self.indent}|{symbol}|{self.function}|{self.arg}" ) self.formatter2 = ( # indented formatter f"{self.indent}|{symbol}|{self.function}|{self.arg}|" f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" ) return self.formatter2 def make_pickleable_frame(frame): kwds = { "filename": frame.f_code.co_filename, "lineno": frame.f_lineno, "function": frame.f_code.co_name, "local_vars": frame.f_code.co_names, "code_context": getcodecontext(frame,frame.f_lineno)[0], "count": getcodecontext(frame,frame.f_lineno)[1], } return PickleableFrame(kwds) def make_pickleable_state(self) -> PickleableState: kwds = { "frame": pickleable_dispatch(self.frame), "event": self.event, "arg": pickleable_dispatch(self.arg), "f_locals": pickleable_dispatch(self.frame.f_locals), "count": self.count, "function": self.function, "module": self.module, "format_filename": self.format_filename, "lineno": self.lineno, "stdlib": self.stdlib, "source": self.source, } try: pickleable_state = PickleableState(**kwds) except: wf(stackprinter.format(sys.exc_info()),'logs/get_pickleable_state.log','a') raise SystemExit return pickleable_state def getcodecontext(frame,lineno,context=2): if context > 0: start = lineno - 1 - context//2 try: lines, lnum = inspect.findsource(frame) except OSError: lines = count = None else: start = max(0, min(start, len(lines) - context)) lines = lines[start:start+context] count = lineno - 1 - start else: lines = count = None return lines, count class PickleableFrame: def __init__(self, kwds): self.filename = kwds['filename'] self.lineno = kwds['lineno'] self.function = kwds['function'] self.local_vars = kwds['local_vars'] self.code_context = kwds['code_context'] self.count = kwds['count'] def __str__(self,color=False): return pformat(self.__dict__) f = inspect.currentframe() pf = make_pickleable_frame(f) kwds = dict( frame=pf, event='call', arg=None, f_locals={'a':12}, count=43, function="wefa", module="mod", format_filename="wetwfge", lineno=43, stdlib=False, source='f = inspect.currentframe()\n', ) pst = PickleableState(kwds) print(pst)
from prettyprinter import pformat import inspect from functools import cached_property class PickleableState: def __init__(self, kwds): self.attrs = list(kwds.keys()) self.filename: str = kwds['format_filename'] self.frame: PickleableFrame = kwds['frame'] self.event: str = kwds['event'] self.arg: Any = kwds['arg'] self.f_locals: Dict = kwds['f_locals'] self.count: int = kwds['count'] self.function: str = kwds['function'] self.module: str = kwds['module'] self.lineno: int = kwds['lineno'] self.stdlib: bool = kwds['stdlib'] self.source: str = kwds['source'] def __str__(self): l = [] for attr in self.attrs: l.append(f"{attr}={getattr(self,attr,'None')}") s = "\n".join(l) return s def asdict(self): return self.__dict__ @property def indent(self): idt = '\u0020' + (len(PickleableState.stack)-1) return idt stack = [] @cached_property def format_call(self): symbol = "=>" PickleableState.stack.append(f"{self.module}.{self.function}") self.formatter1 = ( # default formatter f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" f"{self.indent}|{symbol}|{self.function}|{self.locals}" ) self.formatter2 = ( # indented formatter f"{self.indent}|{symbol}|{self.function}|{self.locals}|" f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" ) return self.formatter2 @cached_property def format_line(self): symbol = " " self.formatter1 = ( # default formatter f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" f"{self.indent} |{symbol}|{self.source}|" ) self.formatter2 = ( # indented formatter f"{self.indent} |{symbol}|{self.source}|" f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" ) return self.formatter2 @cached_property def format_return(self): symbol = "<=" self.formatter1 = ( # default formatter f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" f"{self.indent}|{symbol}|{self.function}|{self.arg}" ) self.formatter2 = ( # indented formatter f"{self.indent}|{symbol}|{self.function}|{self.arg}|" f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" ) if PickleableState.stack and PickleableState.stack[-1] == f"{self.module}.{self.function}": PickleableState.stack.pop() return self.formatter2 @cached_property def format_exception(self): symbol = " !" self.formatter1 = ( # default formatter f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" f"{self.indent}|{symbol}|{self.function}|{self.arg}" ) self.formatter2 = ( # indented formatter f"{self.indent}|{symbol}|{self.function}|{self.arg}|" f"{self.count:>5}|{self.filename}:{self.lineno:<5}|{self.event:9}|" ) return self.formatter2 def make_pickleable_frame(frame): kwds = { "filename": frame.f_code.co_filename, "lineno": frame.f_lineno, "function": frame.f_code.co_name, "local_vars": frame.f_code.co_names, "code_context": getcodecontext(frame,frame.f_lineno)[0], "count": getcodecontext(frame,frame.f_lineno)[1], } return PickleableFrame(kwds) def make_pickleable_state(self) -> PickleableState: kwds = { "frame": pickleable_dispatch(self.frame), "event": self.event, "arg": pickleable_dispatch(self.arg), "f_locals": pickleable_dispatch(self.frame.f_locals), "count": self.count, "function": self.function, "module": self.module, "format_filename": self.format_filename, "lineno": self.lineno, "stdlib": self.stdlib, "source": self.source, } try: pickleable_state = PickleableState(**kwds) except: wf(stackprinter.format(sys.exc_info()),'logs/get_pickleable_state.log','a') raise SystemExit return pickleable_state def getcodecontext(frame,lineno,context=2): if context > 0: start = lineno - 1 - context//2 try: lines, lnum = inspect.findsource(frame) except OSError: lines = count = None else: start = max(0, min(start, len(lines) - context)) lines = lines[start:start+context] count = lineno - 1 - start else: lines = count = None return lines, count class PickleableFrame: def __init__(self, kwds): self.filename = kwds['filename'] self.lineno = kwds['lineno'] self.function = kwds['function'] self.local_vars = kwds['local_vars'] self.code_context = kwds['code_context'] self.count = kwds['count'] def __str__(self,color=False): return pformat(self.__dict__) f = inspect.currentframe() pf = make_pickleable_frame(f) kwds = dict( frame=pf, event='call', arg=None, f_locals={'a':12}, count=43, function="wefa", module="mod", format_filename="wetwfge", lineno=43, stdlib=False, source='f = inspect.currentframe()\n', ) pst = PickleableState(kwds) print(pst)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # "Testing Configurations" - a chapter of "The Fuzzing Book" # Web site: https://www.fuzzingbook.org/html/ConfigurationFuzzer.html # Last change: 2021-06-04 14:57:19+02:00 # # Copyright (c) 2021 CISPA Helmholtz Center for Information Security # Copyright (c) 2018-2020 Saarland University, authors, and contributors # # 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. r''' The Fuzzing Book - Testing Configurations This file can be _executed_ as a script, running all experiments: $ python ConfigurationFuzzer.py or _imported_ as a package, providing classes, functions, and constants: >>> from fuzzingbook.ConfigurationFuzzer import <identifier> but before you do so, _read_ it and _interact_ with it at: https://www.fuzzingbook.org/html/ConfigurationFuzzer.html This chapter provides two classes: * `OptionRunner` automatically extract command-line options from a Python program; * `OptionFuzzer` uses these to automatically test a Python program with a large variety of options. `OptionRunner` runs a program up to the point where it parses its arguments, and then extracts a grammar that describes its invocations: >>> autopep8_runner = OptionRunner("autopep8", "foo.py") The grammar can be extracted via the method `ebnf_grammar()`: >>> option_ebnf_grammar = autopep8_runner.ebnf_grammar() >>> print(option_ebnf_grammar) {'': ['()*'], '': [' -h', ' --help', ' --version', ' -v', ' --verbose', ' -d', ' --diff', ' -i', ' --in-place', ' --global-config ', ' --ignore-local-config', ' -r', ' --recursive', ' -j ', ' --jobs ', ' -p ', ' --pep8-passes ', ' -a', ' --aggressive', ' --experimental', ' --exclude ', ' --list-fixes', ' --ignore ', ' --select ', ' --max-line-length ', ' --line-range ', ' --range ', ' --indent-size ', ' --hang-closing', ' --exit-code'], '': [' foo.py'], '': ['+'], '': ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~'], '': [''], '': ['(-)?+'], '': ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], '': [''], '': [''], '': [''], '': ['']} The grammar can be immediately used for fuzzing. A `GrammarCoverageFuzzer` will ensure all options are covered: >>> from Grammars import convert_ebnf_grammar >>> fuzzer = GrammarCoverageFuzzer(convert_ebnf_grammar(option_ebnf_grammar)) >>> [fuzzer.fuzz() for i in range(3)] [' --pep8-passes 62 foo.py', ' --exit-code -j -95 --in-place -d --line-range 87 1 --list-fixes --range 3 0 --hang-closing --aggressive --experimental foo.py', ' --indent-size 4 --ignore 7_ -p -3 --jobs 9 --diff -i -a --ignore-local-config -h --select y -r --exclude Ig8> --max-line-length -43 --help --verbose --global-config AR --recursive --version -v --ignore m --select ~a|h< --global-config vx --exclude `q --ignore l --select J --select pLNOV --ignore Y{ --global-config ; --exclude f --select Hr --exclude - --select * --exclude )W --select c9+4 --select 0]s --ignore b6 --ignore k$? --select G --select BM --global-config \\1[ --exclude Z --exclude d --exclude #\' --global-config DU --select u --global-config QSz --ignore e!,t2F --global-config w. --exclude i --select n --exclude ETCj --exclude P: --ignore (& --exclude K3@ --select =/ --select Xo --exclude %" --select } --exclude 5 --ignore )^ --global-config 6 --exclude O!& --global-config B foo.py'] The `OptionFuzzer` class summarizes these steps. Its constructor takes an `OptionRunner` to automatically extract the grammar; it does the necessary steps to extract the grammar and fuzz with it. >>> autopep8_runner = OptionRunner("autopep8", "foo.py") >>> autopep8_fuzzer = OptionFuzzer(autopep8_runner) >>> [autopep8_fuzzer.fuzz() for i in range(3)] [' --indent-size 9 foo.py', ' -v --global-config F --range -0 -715382 --help --ignore-local-config -j -4 -a --exit-code -r --list-fixes --hang-closing --diff --version --select hZ --jobs 5 --pep8-passes -6 --line-range -9 5 --exclude k% --recursive -h -i --max-line-length 703 --aggressive -d --verbose --experimental --in-place -p -9 --ignore G --ignore 8U --global-config mKa --global-config 45[ --ignore & --global-config Yp --global-config .i) --select |7 --select `*l^SIy> --exclude C --global-config = --ignore xD --global-config bQ --select Tsq --select \\ --select cd~t --exclude ?V --global-config 1O:R --global-config g --global-config E$W --exclude MN --global-config ;v --select !2B#X --select / --global-config L9J_w3 --ignore \' --select uz( --exclude P@ --global-config ero --exclude H --global-config 0,fj --ignore } For more details, source, and documentation, see "The Fuzzing Book - Testing Configurations" at https://www.fuzzingbook.org/html/ConfigurationFuzzer.html ''' # Allow to use 'from . import <module>' when run as script (cf. PEP 366) if __name__ == '__main__' and __package__ is None: __package__ = 'fuzzingbook' # Testing Configurations # ====================== if __name__ == '__main__': print('# Testing Configurations') ## Synopsis ## -------- if __name__ == '__main__': print('\n## Synopsis') ## Configuration Options ## --------------------- if __name__ == '__main__': print('\n## Configuration Options') if __name__ == '__main__': import os os.system(f'grep --help') ## Options in Python ## ----------------- if __name__ == '__main__': print('\n## Options in Python') import argparse def process_numbers(args=[]): parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--sum', dest='accumulate', action='store_const', const=sum, help='sum the integers') group.add_argument('--min', dest='accumulate', action='store_const', const=min, help='compute the minimum') group.add_argument('--max', dest='accumulate', action='store_const', const=max, help='compute the maximum') args = parser.parse_args(args) print(args.accumulate(args.integers)) if __name__ == '__main__': process_numbers(["--min", "100", "200", "300"]) if __name__ == '__main__': process_numbers(["--sum", "1", "2", "3"]) if __name__ == '__main__': # We use the same fixed seed as the notebook to ensure consistency import random random.seed(2001) from .ExpectError import ExpectError if __name__ == '__main__': with ExpectError(print_traceback=False): process_numbers(["--sum", "--max", "1", "2", "3"]) ## A Grammar for Configurations ## ---------------------------- if __name__ == '__main__': print('\n## A Grammar for Configurations') from .Grammars import crange, srange, convert_ebnf_grammar, extend_grammar, is_valid_grammar from .Grammars import START_SYMBOL, new_symbol PROCESS_NUMBERS_EBNF_GRAMMAR = { "<start>": ["<operator> <integers>"], "<operator>": ["--sum", "--min", "--max"], "<integers>": ["<integer>", "<integers> <integer>"], "<integer>": ["<digit>+"], "<digit>": crange('0', '9') } assert is_valid_grammar(PROCESS_NUMBERS_EBNF_GRAMMAR) PROCESS_NUMBERS_GRAMMAR = convert_ebnf_grammar(PROCESS_NUMBERS_EBNF_GRAMMAR) from .GrammarCoverageFuzzer import GrammarCoverageFuzzer if __name__ == '__main__': f = GrammarCoverageFuzzer(PROCESS_NUMBERS_GRAMMAR, min_nonterminals=10) for i in range(3): print(f.fuzz()) if __name__ == '__main__': f = GrammarCoverageFuzzer(PROCESS_NUMBERS_GRAMMAR, min_nonterminals=10) for i in range(3): args = f.fuzz().split() print(args) process_numbers(args) ## Mining Configuration Options ## ---------------------------- if __name__ == '__main__': print('\n## Mining Configuration Options') ### Tracking Arguments if __name__ == '__main__': print('\n### Tracking Arguments') import sys import string def traceit(frame, event, arg): if event != "call": return method_name = frame.f_code.co_name if method_name != "add_argument": return locals = frame.f_locals print(method_name, locals) if __name__ == '__main__': sys.settrace(traceit) process_numbers(["--sum", "1", "2", "3"]) sys.settrace(None) def traceit(frame, event, arg): if event != "call": return method_name = frame.f_code.co_name if method_name != "add_argument": return locals = frame.f_locals print(locals['args']) if __name__ == '__main__': sys.settrace(traceit) process_numbers(["--sum", "1", "2", "3"]) sys.settrace(None) ### A Grammar Miner for Options and Arguments if __name__ == '__main__': print('\n### A Grammar Miner for Options and Arguments') class ParseInterrupt(Exception): pass class OptionGrammarMiner(object): def __init__(self, function, log=False): self.function = function self.log = log class OptionGrammarMiner(OptionGrammarMiner): OPTION_SYMBOL = "<option>" ARGUMENTS_SYMBOL = "<arguments>" def mine_ebnf_grammar(self): self.grammar = { START_SYMBOL: ["(" + self.OPTION_SYMBOL + ")*" + self.ARGUMENTS_SYMBOL], self.OPTION_SYMBOL: [], self.ARGUMENTS_SYMBOL: [] } self.current_group = self.OPTION_SYMBOL old_trace = sys.gettrace() sys.settrace(self.traceit) try: self.function() except ParseInterrupt: pass sys.settrace(old_trace) return self.grammar def mine_grammar(self): return convert_ebnf_grammar(self.mine_ebnf_grammar()) class OptionGrammarMiner(OptionGrammarMiner): def traceit(self, frame, event, arg): if event != "call": return if "self" not in frame.f_locals: return self_var = frame.f_locals["self"] method_name = frame.f_code.co_name if method_name == "add_argument": in_group = repr(type(self_var)).find("Group") >= 0 self.process_argument(frame.f_locals, in_group) elif method_name == "add_mutually_exclusive_group": self.add_group(frame.f_locals, exclusive=True) elif method_name == "add_argument_group": # self.add_group(frame.f_locals, exclusive=False) pass elif method_name == "parse_args": raise ParseInterrupt return None class OptionGrammarMiner(OptionGrammarMiner): def process_argument(self, locals, in_group): args = locals["args"] kwargs = locals["kwargs"] if self.log: print(args) print(kwargs) print() for arg in args: self.process_arg(arg, in_group, kwargs) class OptionGrammarMiner(OptionGrammarMiner): def process_arg(self, arg, in_group, kwargs): if arg.startswith('-'): if not in_group: target = self.OPTION_SYMBOL else: target = self.current_group metavar = None arg = " " + arg else: target = self.ARGUMENTS_SYMBOL metavar = arg arg = "" if "nargs" in kwargs: nargs = kwargs["nargs"] else: nargs = 1 param = self.add_parameter(kwargs, metavar) if param == "": nargs = 0 if isinstance(nargs, int): for i in range(nargs): arg += param else: assert nargs in "?+*" arg += '(' + param + ')' + nargs if target == self.OPTION_SYMBOL: self.grammar[target].append(arg) else: self.grammar[target].append(arg) import inspect class OptionGrammarMiner(OptionGrammarMiner): def add_parameter(self, kwargs, metavar): if "action" in kwargs: # No parameter return "" type_ = "str" if "type" in kwargs: given_type = kwargs["type"] # int types come as '<class int>' if inspect.isclass(given_type) and issubclass(given_type, int): type_ = "int" if metavar is None: if "metavar" in kwargs: metavar = kwargs["metavar"] else: metavar = type_ self.add_type_rule(type_) if metavar != type_: self.add_metavar_rule(metavar, type_) param = " <" + metavar + ">" return param class OptionGrammarMiner(OptionGrammarMiner): def add_type_rule(self, type_): if type_ == "int": self.add_int_rule() else: self.add_str_rule() def add_int_rule(self): self.grammar["<int>"] = ["(-)?<digit>+"] self.grammar["<digit>"] = crange('0', '9') def add_str_rule(self): self.grammar["<str>"] = ["<char>+"] self.grammar["<char>"] = srange( string.digits + string.ascii_letters + string.punctuation) def add_metavar_rule(self, metavar, type_): self.grammar["<" + metavar + ">"] = ["<" + type_ + ">"] class OptionGrammarMiner(OptionGrammarMiner): def add_group(self, locals, exclusive): kwargs = locals["kwargs"] if self.log: print(kwargs) required = kwargs.get("required", False) group = new_symbol(self.grammar, "<group>") if required and exclusive: group_expansion = group if required and not exclusive: group_expansion = group + "+" if not required and exclusive: group_expansion = group + "?" if not required and not exclusive: group_expansion = group + "*" self.grammar[START_SYMBOL][0] = group_expansion + \ self.grammar[START_SYMBOL][0] self.grammar[group] = [] self.current_group = group if __name__ == '__main__': miner = OptionGrammarMiner(process_numbers, log=True) process_numbers_grammar = miner.mine_ebnf_grammar() if __name__ == '__main__': process_numbers_grammar if __name__ == '__main__': process_numbers_grammar["<start>"] if __name__ == '__main__': process_numbers_grammar["<group>"] if __name__ == '__main__': process_numbers_grammar["<option>"] if __name__ == '__main__': process_numbers_grammar["<arguments>"] if __name__ == '__main__': process_numbers_grammar["<integers>"] if __name__ == '__main__': process_numbers_grammar["<int>"] if __name__ == '__main__': assert is_valid_grammar(process_numbers_grammar) if __name__ == '__main__': grammar = convert_ebnf_grammar(process_numbers_grammar) assert is_valid_grammar(grammar) if __name__ == '__main__': f = GrammarCoverageFuzzer(grammar) for i in range(10): print(f.fuzz()) ## Testing Autopep8 ## ---------------- if __name__ == '__main__': print('\n## Testing Autopep8') if __name__ == '__main__': import os os.system(f'autopep8 --help') ### Autopep8 Setup if __name__ == '__main__': print('\n### Autopep8 Setup') import os def find_executable(name): for path in os.get_exec_path(): qualified_name = os.path.join(path, name) if os.path.exists(qualified_name): return qualified_name return None if __name__ == '__main__': autopep8_executable = find_executable("autopep8") assert autopep8_executable is not None autopep8_executable def autopep8(): executable = find_executable("autopep8") # First line has to contain "/usr/bin/env python" or like first_line = open(executable).readline() assert first_line.find("python") >= 0 contents = open(executable).read() exec(contents) ### Mining an Autopep8 Grammar if __name__ == '__main__': print('\n### Mining an Autopep8 Grammar') if __name__ == '__main__': autopep8_miner = OptionGrammarMiner(autopep8) if __name__ == '__main__': autopep8_ebnf_grammar = autopep8_miner.mine_ebnf_grammar() if __name__ == '__main__': print(autopep8_ebnf_grammar["<option>"]) if __name__ == '__main__': autopep8_ebnf_grammar["<line>"] if __name__ == '__main__': autopep8_ebnf_grammar["<arguments>"] if __name__ == '__main__': autopep8_ebnf_grammar["<files>"] if __name__ == '__main__': autopep8_ebnf_grammar["<arguments>"] = [" <files>"] autopep8_ebnf_grammar["<files>"] = ["foo.py"] assert is_valid_grammar(autopep8_ebnf_grammar) ### Creating Autopep8 Options if __name__ == '__main__': print('\n### Creating Autopep8 Options') if __name__ == '__main__': autopep8_grammar = convert_ebnf_grammar(autopep8_ebnf_grammar) assert is_valid_grammar(autopep8_grammar) if __name__ == '__main__': f = GrammarCoverageFuzzer(autopep8_grammar, max_nonterminals=4) for i in range(20): print(f.fuzz()) def create_foo_py(): open("foo.py", "w").write(""" def twice(x = 2): return x + x """) if __name__ == '__main__': create_foo_py() if __name__ == '__main__': print(open("foo.py").read(), end="") if __name__ == '__main__': import os os.system(f'autopep8 foo.py') from .Fuzzer import ProgramRunner if __name__ == '__main__': f = GrammarCoverageFuzzer(autopep8_grammar, max_nonterminals=5) for i in range(20): invocation = "autopep8" + f.fuzz() print("$ " + invocation) args = invocation.split() autopep8 = ProgramRunner(args) result, outcome = autopep8.run() if result.stderr != "": print(result.stderr, end="") if __name__ == '__main__': print(open("foo.py").read(), end="") import os if __name__ == '__main__': os.remove("foo.py") ## Classes for Fuzzing Configuration Options ## ----------------------------------------- if __name__ == '__main__': print('\n## Classes for Fuzzing Configuration Options') class OptionRunner(ProgramRunner): def __init__(self, program, arguments=None): if isinstance(program, str): self.base_executable = program else: self.base_executable = program[0] self.find_contents() self.find_grammar() if arguments is not None: self.set_arguments(arguments) super().__init__(program) class OptionRunner(OptionRunner): def find_contents(self): self._executable = find_executable(self.base_executable) first_line = open(self._executable).readline() assert first_line.find("python") >= 0 self.contents = open(self._executable).read() def invoker(self): exec(self.contents) def executable(self): return self._executable class OptionRunner(OptionRunner): def find_grammar(self): miner = OptionGrammarMiner(self.invoker) self._ebnf_grammar = miner.mine_ebnf_grammar() def ebnf_grammar(self): return self._ebnf_grammar def grammar(self): return convert_ebnf_grammar(self._ebnf_grammar) from .Grammars import unreachable_nonterminals class OptionRunner(OptionRunner): def set_arguments(self, args): self._ebnf_grammar["<arguments>"] = [" " + args] # Delete rules for previous arguments for nonterminal in unreachable_nonterminals(self._ebnf_grammar): del self._ebnf_grammar[nonterminal] def set_invocation(self, program): self.program = program if __name__ == '__main__': autopep8_runner = OptionRunner("autopep8", "foo.py") if __name__ == '__main__': print(autopep8_runner.ebnf_grammar()["<option>"]) class OptionFuzzer(GrammarCoverageFuzzer): def __init__(self, runner, *args, **kwargs): assert issubclass(type(runner), OptionRunner) self.runner = runner grammar = runner.grammar() super().__init__(grammar, *args, **kwargs) class OptionFuzzer(OptionFuzzer): def run(self, runner=None, inp=""): if runner is None: runner = self.runner assert issubclass(type(runner), OptionRunner) invocation = runner.executable() + " " + self.fuzz() runner.set_invocation(invocation.split()) return runner.run(inp) ### Example: Autopep8 if __name__ == '__main__': print('\n### Example: Autopep8') if __name__ == '__main__': autopep8_fuzzer = OptionFuzzer(autopep8_runner, max_nonterminals=5) if __name__ == '__main__': for i in range(3): print(autopep8_fuzzer.fuzz()) if __name__ == '__main__': autopep8_fuzzer.run(autopep8_runner) ### Example: MyPy if __name__ == '__main__': print('\n### Example: MyPy') if __name__ == '__main__': assert find_executable("mypy") is not None if __name__ == '__main__': mypy_runner = OptionRunner("mypy", "foo.py") print(mypy_runner.ebnf_grammar()["<option>"]) if __name__ == '__main__': mypy_fuzzer = OptionFuzzer(mypy_runner, max_nonterminals=5) for i in range(10): print(mypy_fuzzer.fuzz()) ### Example: Notedown if __name__ == '__main__': print('\n### Example: Notedown') if __name__ == '__main__': assert find_executable("notedown") is not None if __name__ == '__main__': notedown_runner = OptionRunner("notedown") if __name__ == '__main__': print(notedown_runner.ebnf_grammar()["<option>"]) if __name__ == '__main__': notedown_fuzzer = OptionFuzzer(notedown_runner, max_nonterminals=5) for i in range(10): print(notedown_fuzzer.fuzz()) ## Combinatorial Testing ## --------------------- if __name__ == '__main__': print('\n## Combinatorial Testing') from itertools import combinations if __name__ == '__main__': option_list = notedown_runner.ebnf_grammar()["<option>"] pairs = list(combinations(option_list, 2)) if __name__ == '__main__': len(pairs) if __name__ == '__main__': print(pairs[:20]) def pairwise(option_list): return [option_1 + option_2 for (option_1, option_2) in combinations(option_list, 2)] if __name__ == '__main__': print(pairwise(option_list)[:20]) if __name__ == '__main__': notedown_grammar = notedown_runner.grammar() pairwise_notedown_grammar = extend_grammar(notedown_grammar) pairwise_notedown_grammar["<option>"] = pairwise(notedown_grammar["<option>"]) assert is_valid_grammar(pairwise_notedown_grammar) if __name__ == '__main__': notedown_fuzzer = GrammarCoverageFuzzer( pairwise_notedown_grammar, max_nonterminals=4) if __name__ == '__main__': for i in range(10): print(notedown_fuzzer.fuzz()) if __name__ == '__main__': for combination_length in range(1, 20): tuples = list(combinations(option_list, combination_length)) print(combination_length, len(tuples)) if __name__ == '__main__': len(autopep8_runner.ebnf_grammar()["<option>"]) if __name__ == '__main__': len(autopep8_runner.ebnf_grammar()["<option>"]) * \ (len(autopep8_runner.ebnf_grammar()["<option>"]) - 1) if __name__ == '__main__': len(mypy_runner.ebnf_grammar()["<option>"]) if __name__ == '__main__': len(mypy_runner.ebnf_grammar()["<option>"]) * \ (len(mypy_runner.ebnf_grammar()["<option>"]) - 1) ## Synopsis ## -------- if __name__ == '__main__': print('\n## Synopsis') if __name__ == '__main__': autopep8_runner = OptionRunner("autopep8", "foo.py") if __name__ == '__main__': option_ebnf_grammar = autopep8_runner.ebnf_grammar() print(option_ebnf_grammar) from .Grammars import convert_ebnf_grammar if __name__ == '__main__': fuzzer = GrammarCoverageFuzzer(convert_ebnf_grammar(option_ebnf_grammar)) [fuzzer.fuzz() for i in range(3)] if __name__ == '__main__': autopep8_runner = OptionRunner("autopep8", "foo.py") autopep8_fuzzer = OptionFuzzer(autopep8_runner) if __name__ == '__main__': [autopep8_fuzzer.fuzz() for i in range(3)] ## Lessons Learned ## --------------- if __name__ == '__main__': print('\n## Lessons Learned') ## Next Steps ## ---------- if __name__ == '__main__': print('\n## Next Steps') ## Background ## ---------- if __name__ == '__main__': print('\n## Background') ## Exercises ## --------- if __name__ == '__main__': print('\n## Exercises') ### Exercise 1: #ifdef Configuration Fuzzing if __name__ == '__main__': print('\n### Exercise 1: #ifdef Configuration Fuzzing') #### Part 1: Extract Preprocessor Variables if __name__ == '__main__': print('\n#### Part 1: Extract Preprocessor Variables') if __name__ == '__main__': filename = "xmlparse.c" open(filename, "w").write( """ #if defined(_WIN32) && !defined(LOAD_LIBRARY_SEARCH_SYSTEM32) # define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800 #endif #if !defined(HAVE_GETRANDOM) && !defined(HAVE_SYSCALL_GETRANDOM) \ && !defined(HAVE_ARC4RANDOM_BUF) && !defined(HAVE_ARC4RANDOM) \ && !defined(XML_DEV_URANDOM) \ && !defined(_WIN32) \ && !defined(XML_POOR_ENTROPY) # error #endif #if !defined(TIOCSWINSZ) || defined(__SCO__) || defined(__UNIXWARE__) #define USE_SYSV_ENVVARS /* COLUMNS/LINES vs. TERMCAP */ #endif #ifdef XML_UNICODE_WCHAR_T #define XML_T(x) (const wchar_t)x #define XML_L(x) L ## x #else #define XML_T(x) (const unsigned short)x #define XML_L(x) x #endif int fun(int x) { return XML_T(x); } """); import re if __name__ == '__main__': re_cpp_if_directive = re.compile(r"\s*#\s*(el)?if") re_cpp_identifier = re.compile(r"[a-zA-Z_$]+") def cpp_identifiers(lines): identifiers = set() for line in lines: if re_cpp_if_directive.match(line): identifiers |= set(re_cpp_identifier.findall(line)) # These are preprocessor keywords identifiers -= {"if", "ifdef", "ifndef", "defined"} return identifiers if __name__ == '__main__': cpp_ids = cpp_identifiers(open("xmlparse.c").readlines()) cpp_ids #### Part 2: Derive an Option Grammar if __name__ == '__main__': print('\n#### Part 2: Derive an Option Grammar') from .Grammars import new_symbol if __name__ == '__main__': cpp_grammar = { "<start>": ["cc -c<options> " + filename], "<options>": ["<option>", "<options><option>"], "<option>": [] } for id in cpp_ids: s = new_symbol(cpp_grammar, "<" + id + ">") cpp_grammar["<option>"].append(s) cpp_grammar[s] = [" -D" + id] cpp_grammar if __name__ == '__main__': assert is_valid_grammar(cpp_grammar) #### Part 3: C Preprocessor Configuration Fuzzing if __name__ == '__main__': print('\n#### Part 3: C Preprocessor Configuration Fuzzing') if __name__ == '__main__': g = GrammarCoverageFuzzer(cpp_grammar) g.fuzz() from .Fuzzer import ProgramRunner if __name__ == '__main__': for i in range(10): invocation = g.fuzz() print("$", invocation) # subprocess.call(invocation, shell=True) cc_runner = ProgramRunner(invocation.split(' ')) (result, outcome) = cc_runner.run() print(result.stderr, end="") if __name__ == '__main__': pairwise_cpp_grammar = extend_grammar(cpp_grammar) pairwise_cpp_grammar["<option>"] = pairwise(cpp_grammar["<option>"]) pairwise_cpp_grammar["<option>"][:10] if __name__ == '__main__': for i in range(10): invocation = g.fuzz() print("$", invocation) # subprocess.call(invocation, shell=True) cc_runner = ProgramRunner(invocation.split(' ')) (result, outcome) = cc_runner.run() print(result.stderr, end="") if __name__ == '__main__': os.remove("xmlparse.c") if __name__ == '__main__': if os.path.exists("xmlparse.o"): os.remove("xmlparse.o") ### Exercise 2: .ini Configuration Fuzzing if __name__ == '__main__': print('\n### Exercise 2: .ini Configuration Fuzzing') import configparser if __name__ == '__main__': config = configparser.ConfigParser() config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret['Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' with open('example.ini', 'w') as configfile: config.write(configfile) with open('example.ini') as configfile: print(configfile.read(), end="") if __name__ == '__main__': config = configparser.ConfigParser() config.read('example.ini') topsecret = config['topsecret.server.com'] topsecret['Port'] #### Part 1: Read Configuration if __name__ == '__main__': print('\n#### Part 1: Read Configuration') #### Part 2: Create a Configuration Grammar if __name__ == '__main__': print('\n#### Part 2: Create a Configuration Grammar') #### Part 3: Mine a Configuration Grammar if __name__ == '__main__': print('\n#### Part 3: Mine a Configuration Grammar') class TrackingConfigParser(configparser.ConfigParser): def __getitem__(self, key): print("Accessing", repr(key)) return super().__getitem__(key) if __name__ == '__main__': tracking_config_parser = TrackingConfigParser() tracking_config_parser.read('example.ini') section = tracking_config_parser['topsecret.server.com'] import os if __name__ == '__main__': os.remove("example.ini") ### Exercise 3: Extracting and Fuzzing C Command-Line Options if __name__ == '__main__': print('\n### Exercise 3: Extracting and Fuzzing C Command-Line Options') #### Part 1: Getopt Fuzzing if __name__ == '__main__': print('\n#### Part 1: Getopt Fuzzing') #### Part 2: Fuzzing Long Options in C if __name__ == '__main__': print('\n#### Part 2: Fuzzing Long Options in C') ### Exercise 4: Expansions in Context if __name__ == '__main__': print('\n### Exercise 4: Expansions in Context') if __name__ == '__main__': autopep8_runner.ebnf_grammar()["<line>"] if __name__ == '__main__': autopep8_runner.ebnf_grammar()["<int>"] if __name__ == '__main__': autopep8_runner.ebnf_grammar()["<digit>"]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # "Testing Configurations" - a chapter of "The Fuzzing Book" # Web site: https://www.fuzzingbook.org/html/ConfigurationFuzzer.html # Last change: 2021-06-04 14:57:19+02:00 # # Copyright (c) 2021 CISPA Helmholtz Center for Information Security # Copyright (c) 2018-2020 Saarland University, authors, and contributors # # 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. r''' The Fuzzing Book - Testing Configurations This file can be _executed_ as a script, running all experiments: $ python ConfigurationFuzzer.py or _imported_ as a package, providing classes, functions, and constants: >>> from fuzzingbook.ConfigurationFuzzer import <identifier> but before you do so, _read_ it and _interact_ with it at: https://www.fuzzingbook.org/html/ConfigurationFuzzer.html This chapter provides two classes: * `OptionRunner` automatically extract command-line options from a Python program; * `OptionFuzzer` uses these to automatically test a Python program with a large variety of options. `OptionRunner` runs a program up to the point where it parses its arguments, and then extracts a grammar that describes its invocations: >>> autopep8_runner = OptionRunner("autopep8", "foo.py") The grammar can be extracted via the method `ebnf_grammar()`: >>> option_ebnf_grammar = autopep8_runner.ebnf_grammar() >>> print(option_ebnf_grammar) {'': ['()*'], '': [' -h', ' --help', ' --version', ' -v', ' --verbose', ' -d', ' --diff', ' -i', ' --in-place', ' --global-config ', ' --ignore-local-config', ' -r', ' --recursive', ' -j ', ' --jobs ', ' -p ', ' --pep8-passes ', ' -a', ' --aggressive', ' --experimental', ' --exclude ', ' --list-fixes', ' --ignore ', ' --select ', ' --max-line-length ', ' --line-range ', ' --range ', ' --indent-size ', ' --hang-closing', ' --exit-code'], '': [' foo.py'], '': ['+'], '': ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~'], '': [''], '': ['(-)?+'], '': ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], '': [''], '': [''], '': [''], '': ['']} The grammar can be immediately used for fuzzing. A `GrammarCoverageFuzzer` will ensure all options are covered: >>> from Grammars import convert_ebnf_grammar >>> fuzzer = GrammarCoverageFuzzer(convert_ebnf_grammar(option_ebnf_grammar)) >>> [fuzzer.fuzz() for i in range(3)] [' --pep8-passes 62 foo.py', ' --exit-code -j -95 --in-place -d --line-range 87 1 --list-fixes --range 3 0 --hang-closing --aggressive --experimental foo.py', ' --indent-size 4 --ignore 7_ -p -3 --jobs 9 --diff -i -a --ignore-local-config -h --select y -r --exclude Ig8> --max-line-length -43 --help --verbose --global-config AR --recursive --version -v --ignore m --select ~a|h< --global-config vx --exclude `q --ignore l --select J --select pLNOV --ignore Y{ --global-config ; --exclude f --select Hr --exclude - --select * --exclude )W --select c9+4 --select 0]s --ignore b6 --ignore k$? --select G --select BM --global-config \\1[ --exclude Z --exclude d --exclude #\' --global-config DU --select u --global-config QSz --ignore e!,t2F --global-config w. --exclude i --select n --exclude ETCj --exclude P: --ignore (& --exclude K3@ --select =/ --select Xo --exclude %" --select } --exclude 5 --ignore )^ --global-config 6 --exclude O!& --global-config B foo.py'] The `OptionFuzzer` class summarizes these steps. Its constructor takes an `OptionRunner` to automatically extract the grammar; it does the necessary steps to extract the grammar and fuzz with it. >>> autopep8_runner = OptionRunner("autopep8", "foo.py") >>> autopep8_fuzzer = OptionFuzzer(autopep8_runner) >>> [autopep8_fuzzer.fuzz() for i in range(3)] [' --indent-size 9 foo.py', ' -v --global-config F --range -0 -715382 --help --ignore-local-config -j -4 -a --exit-code -r --list-fixes --hang-closing --diff --version --select hZ --jobs 5 --pep8-passes -6 --line-range -9 5 --exclude k% --recursive -h -i --max-line-length 703 --aggressive -d --verbose --experimental --in-place -p -9 --ignore G --ignore 8U --global-config mKa --global-config 45[ --ignore & --global-config Yp --global-config .i) --select |7 --select `*l^SIy> --exclude C --global-config = --ignore xD --global-config bQ --select Tsq --select \\ --select cd~t --exclude ?V --global-config 1O:R --global-config g --global-config E$W --exclude MN --global-config ;v --select !2B#X --select / --global-config L9J_w3 --ignore \' --select uz( --exclude P@ --global-config ero --exclude H --global-config 0,fj --ignore } For more details, source, and documentation, see "The Fuzzing Book - Testing Configurations" at https://www.fuzzingbook.org/html/ConfigurationFuzzer.html ''' # Allow to use 'from . import <module>' when run as script (cf. PEP 366) if __name__ == '__main__' and __package__ is None: __package__ = 'fuzzingbook' # Testing Configurations # ====================== if __name__ == '__main__': print('# Testing Configurations') ## Synopsis ## -------- if __name__ == '__main__': print('\n## Synopsis') ## Configuration Options ## --------------------- if __name__ == '__main__': print('\n## Configuration Options') if __name__ == '__main__': import os os.system(f'grep --help') ## Options in Python ## ----------------- if __name__ == '__main__': print('\n## Options in Python') import argparse def process_numbers(args=[]): parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--sum', dest='accumulate', action='store_const', const=sum, help='sum the integers') group.add_argument('--min', dest='accumulate', action='store_const', const=min, help='compute the minimum') group.add_argument('--max', dest='accumulate', action='store_const', const=max, help='compute the maximum') args = parser.parse_args(args) print(args.accumulate(args.integers)) if __name__ == '__main__': process_numbers(["--min", "100", "200", "300"]) if __name__ == '__main__': process_numbers(["--sum", "1", "2", "3"]) if __name__ == '__main__': # We use the same fixed seed as the notebook to ensure consistency import random random.seed(2001) from .ExpectError import ExpectError if __name__ == '__main__': with ExpectError(print_traceback=False): process_numbers(["--sum", "--max", "1", "2", "3"]) ## A Grammar for Configurations ## ---------------------------- if __name__ == '__main__': print('\n## A Grammar for Configurations') from .Grammars import crange, srange, convert_ebnf_grammar, extend_grammar, is_valid_grammar from .Grammars import START_SYMBOL, new_symbol PROCESS_NUMBERS_EBNF_GRAMMAR = { "<start>": ["<operator> <integers>"], "<operator>": ["--sum", "--min", "--max"], "<integers>": ["<integer>", "<integers> <integer>"], "<integer>": ["<digit>+"], "<digit>": crange('0', '9') } assert is_valid_grammar(PROCESS_NUMBERS_EBNF_GRAMMAR) PROCESS_NUMBERS_GRAMMAR = convert_ebnf_grammar(PROCESS_NUMBERS_EBNF_GRAMMAR) from .GrammarCoverageFuzzer import GrammarCoverageFuzzer if __name__ == '__main__': f = GrammarCoverageFuzzer(PROCESS_NUMBERS_GRAMMAR, min_nonterminals=10) for i in range(3): print(f.fuzz()) if __name__ == '__main__': f = GrammarCoverageFuzzer(PROCESS_NUMBERS_GRAMMAR, min_nonterminals=10) for i in range(3): args = f.fuzz().split() print(args) process_numbers(args) ## Mining Configuration Options ## ---------------------------- if __name__ == '__main__': print('\n## Mining Configuration Options') ### Tracking Arguments if __name__ == '__main__': print('\n### Tracking Arguments') import sys import string def traceit(frame, event, arg): if event != "call": return method_name = frame.f_code.co_name if method_name != "add_argument": return locals = frame.f_locals print(method_name, locals) if __name__ == '__main__': sys.settrace(traceit) process_numbers(["--sum", "1", "2", "3"]) sys.settrace(None) def traceit(frame, event, arg): if event != "call": return method_name = frame.f_code.co_name if method_name != "add_argument": return locals = frame.f_locals print(locals['args']) if __name__ == '__main__': sys.settrace(traceit) process_numbers(["--sum", "1", "2", "3"]) sys.settrace(None) ### A Grammar Miner for Options and Arguments if __name__ == '__main__': print('\n### A Grammar Miner for Options and Arguments') class ParseInterrupt(Exception): pass class OptionGrammarMiner(object): def __init__(self, function, log=False): self.function = function self.log = log class OptionGrammarMiner(OptionGrammarMiner): OPTION_SYMBOL = "<option>" ARGUMENTS_SYMBOL = "<arguments>" def mine_ebnf_grammar(self): self.grammar = { START_SYMBOL: ["(" + self.OPTION_SYMBOL + ")*" + self.ARGUMENTS_SYMBOL], self.OPTION_SYMBOL: [], self.ARGUMENTS_SYMBOL: [] } self.current_group = self.OPTION_SYMBOL old_trace = sys.gettrace() sys.settrace(self.traceit) try: self.function() except ParseInterrupt: pass sys.settrace(old_trace) return self.grammar def mine_grammar(self): return convert_ebnf_grammar(self.mine_ebnf_grammar()) class OptionGrammarMiner(OptionGrammarMiner): def traceit(self, frame, event, arg): if event != "call": return if "self" not in frame.f_locals: return self_var = frame.f_locals["self"] method_name = frame.f_code.co_name if method_name == "add_argument": in_group = repr(type(self_var)).find("Group") >= 0 self.process_argument(frame.f_locals, in_group) elif method_name == "add_mutually_exclusive_group": self.add_group(frame.f_locals, exclusive=True) elif method_name == "add_argument_group": # self.add_group(frame.f_locals, exclusive=False) pass elif method_name == "parse_args": raise ParseInterrupt return None class OptionGrammarMiner(OptionGrammarMiner): def process_argument(self, locals, in_group): args = locals["args"] kwargs = locals["kwargs"] if self.log: print(args) print(kwargs) print() for arg in args: self.process_arg(arg, in_group, kwargs) class OptionGrammarMiner(OptionGrammarMiner): def process_arg(self, arg, in_group, kwargs): if arg.startswith('-'): if not in_group: target = self.OPTION_SYMBOL else: target = self.current_group metavar = None arg = " " + arg else: target = self.ARGUMENTS_SYMBOL metavar = arg arg = "" if "nargs" in kwargs: nargs = kwargs["nargs"] else: nargs = 1 param = self.add_parameter(kwargs, metavar) if param == "": nargs = 0 if isinstance(nargs, int): for i in range(nargs): arg += param else: assert nargs in "?+*" arg += '(' + param + ')' + nargs if target == self.OPTION_SYMBOL: self.grammar[target].append(arg) else: self.grammar[target].append(arg) import inspect class OptionGrammarMiner(OptionGrammarMiner): def add_parameter(self, kwargs, metavar): if "action" in kwargs: # No parameter return "" type_ = "str" if "type" in kwargs: given_type = kwargs["type"] # int types come as '<class int>' if inspect.isclass(given_type) and issubclass(given_type, int): type_ = "int" if metavar is None: if "metavar" in kwargs: metavar = kwargs["metavar"] else: metavar = type_ self.add_type_rule(type_) if metavar != type_: self.add_metavar_rule(metavar, type_) param = " <" + metavar + ">" return param class OptionGrammarMiner(OptionGrammarMiner): def add_type_rule(self, type_): if type_ == "int": self.add_int_rule() else: self.add_str_rule() def add_int_rule(self): self.grammar["<int>"] = ["(-)?<digit>+"] self.grammar["<digit>"] = crange('0', '9') def add_str_rule(self): self.grammar["<str>"] = ["<char>+"] self.grammar["<char>"] = srange( string.digits + string.ascii_letters + string.punctuation) def add_metavar_rule(self, metavar, type_): self.grammar["<" + metavar + ">"] = ["<" + type_ + ">"] class OptionGrammarMiner(OptionGrammarMiner): def add_group(self, locals, exclusive): kwargs = locals["kwargs"] if self.log: print(kwargs) required = kwargs.get("required", False) group = new_symbol(self.grammar, "<group>") if required and exclusive: group_expansion = group if required and not exclusive: group_expansion = group + "+" if not required and exclusive: group_expansion = group + "?" if not required and not exclusive: group_expansion = group + "*" self.grammar[START_SYMBOL][0] = group_expansion + \ self.grammar[START_SYMBOL][0] self.grammar[group] = [] self.current_group = group if __name__ == '__main__': miner = OptionGrammarMiner(process_numbers, log=True) process_numbers_grammar = miner.mine_ebnf_grammar() if __name__ == '__main__': process_numbers_grammar if __name__ == '__main__': process_numbers_grammar["<start>"] if __name__ == '__main__': process_numbers_grammar["<group>"] if __name__ == '__main__': process_numbers_grammar["<option>"] if __name__ == '__main__': process_numbers_grammar["<arguments>"] if __name__ == '__main__': process_numbers_grammar["<integers>"] if __name__ == '__main__': process_numbers_grammar["<int>"] if __name__ == '__main__': assert is_valid_grammar(process_numbers_grammar) if __name__ == '__main__': grammar = convert_ebnf_grammar(process_numbers_grammar) assert is_valid_grammar(grammar) if __name__ == '__main__': f = GrammarCoverageFuzzer(grammar) for i in range(10): print(f.fuzz()) ## Testing Autopep8 ## ---------------- if __name__ == '__main__': print('\n## Testing Autopep8') if __name__ == '__main__': import os os.system(f'autopep8 --help') ### Autopep8 Setup if __name__ == '__main__': print('\n### Autopep8 Setup') import os def find_executable(name): for path in os.get_exec_path(): qualified_name = os.path.join(path, name) if os.path.exists(qualified_name): return qualified_name return None if __name__ == '__main__': autopep8_executable = find_executable("autopep8") assert autopep8_executable is not None autopep8_executable def autopep8(): executable = find_executable("autopep8") # First line has to contain "/usr/bin/env python" or like first_line = open(executable).readline() assert first_line.find("python") >= 0 contents = open(executable).read() exec(contents) ### Mining an Autopep8 Grammar if __name__ == '__main__': print('\n### Mining an Autopep8 Grammar') if __name__ == '__main__': autopep8_miner = OptionGrammarMiner(autopep8) if __name__ == '__main__': autopep8_ebnf_grammar = autopep8_miner.mine_ebnf_grammar() if __name__ == '__main__': print(autopep8_ebnf_grammar["<option>"]) if __name__ == '__main__': autopep8_ebnf_grammar["<line>"] if __name__ == '__main__': autopep8_ebnf_grammar["<arguments>"] if __name__ == '__main__': autopep8_ebnf_grammar["<files>"] if __name__ == '__main__': autopep8_ebnf_grammar["<arguments>"] = [" <files>"] autopep8_ebnf_grammar["<files>"] = ["foo.py"] assert is_valid_grammar(autopep8_ebnf_grammar) ### Creating Autopep8 Options if __name__ == '__main__': print('\n### Creating Autopep8 Options') if __name__ == '__main__': autopep8_grammar = convert_ebnf_grammar(autopep8_ebnf_grammar) assert is_valid_grammar(autopep8_grammar) if __name__ == '__main__': f = GrammarCoverageFuzzer(autopep8_grammar, max_nonterminals=4) for i in range(20): print(f.fuzz()) def create_foo_py(): open("foo.py", "w").write(""" def twice(x = 2): return x + x """) if __name__ == '__main__': create_foo_py() if __name__ == '__main__': print(open("foo.py").read(), end="") if __name__ == '__main__': import os os.system(f'autopep8 foo.py') from .Fuzzer import ProgramRunner if __name__ == '__main__': f = GrammarCoverageFuzzer(autopep8_grammar, max_nonterminals=5) for i in range(20): invocation = "autopep8" + f.fuzz() print("$ " + invocation) args = invocation.split() autopep8 = ProgramRunner(args) result, outcome = autopep8.run() if result.stderr != "": print(result.stderr, end="") if __name__ == '__main__': print(open("foo.py").read(), end="") import os if __name__ == '__main__': os.remove("foo.py") ## Classes for Fuzzing Configuration Options ## ----------------------------------------- if __name__ == '__main__': print('\n## Classes for Fuzzing Configuration Options') class OptionRunner(ProgramRunner): def __init__(self, program, arguments=None): if isinstance(program, str): self.base_executable = program else: self.base_executable = program[0] self.find_contents() self.find_grammar() if arguments is not None: self.set_arguments(arguments) super().__init__(program) class OptionRunner(OptionRunner): def find_contents(self): self._executable = find_executable(self.base_executable) first_line = open(self._executable).readline() assert first_line.find("python") >= 0 self.contents = open(self._executable).read() def invoker(self): exec(self.contents) def executable(self): return self._executable class OptionRunner(OptionRunner): def find_grammar(self): miner = OptionGrammarMiner(self.invoker) self._ebnf_grammar = miner.mine_ebnf_grammar() def ebnf_grammar(self): return self._ebnf_grammar def grammar(self): return convert_ebnf_grammar(self._ebnf_grammar) from .Grammars import unreachable_nonterminals class OptionRunner(OptionRunner): def set_arguments(self, args): self._ebnf_grammar["<arguments>"] = [" " + args] # Delete rules for previous arguments for nonterminal in unreachable_nonterminals(self._ebnf_grammar): del self._ebnf_grammar[nonterminal] def set_invocation(self, program): self.program = program if __name__ == '__main__': autopep8_runner = OptionRunner("autopep8", "foo.py") if __name__ == '__main__': print(autopep8_runner.ebnf_grammar()["<option>"]) class OptionFuzzer(GrammarCoverageFuzzer): def __init__(self, runner, *args, **kwargs): assert issubclass(type(runner), OptionRunner) self.runner = runner grammar = runner.grammar() super().__init__(grammar, *args, **kwargs) class OptionFuzzer(OptionFuzzer): def run(self, runner=None, inp=""): if runner is None: runner = self.runner assert issubclass(type(runner), OptionRunner) invocation = runner.executable() + " " + self.fuzz() runner.set_invocation(invocation.split()) return runner.run(inp) ### Example: Autopep8 if __name__ == '__main__': print('\n### Example: Autopep8') if __name__ == '__main__': autopep8_fuzzer = OptionFuzzer(autopep8_runner, max_nonterminals=5) if __name__ == '__main__': for i in range(3): print(autopep8_fuzzer.fuzz()) if __name__ == '__main__': autopep8_fuzzer.run(autopep8_runner) ### Example: MyPy if __name__ == '__main__': print('\n### Example: MyPy') if __name__ == '__main__': assert find_executable("mypy") is not None if __name__ == '__main__': mypy_runner = OptionRunner("mypy", "foo.py") print(mypy_runner.ebnf_grammar()["<option>"]) if __name__ == '__main__': mypy_fuzzer = OptionFuzzer(mypy_runner, max_nonterminals=5) for i in range(10): print(mypy_fuzzer.fuzz()) ### Example: Notedown if __name__ == '__main__': print('\n### Example: Notedown') if __name__ == '__main__': assert find_executable("notedown") is not None if __name__ == '__main__': notedown_runner = OptionRunner("notedown") if __name__ == '__main__': print(notedown_runner.ebnf_grammar()["<option>"]) if __name__ == '__main__': notedown_fuzzer = OptionFuzzer(notedown_runner, max_nonterminals=5) for i in range(10): print(notedown_fuzzer.fuzz()) ## Combinatorial Testing ## --------------------- if __name__ == '__main__': print('\n## Combinatorial Testing') from itertools import combinations if __name__ == '__main__': option_list = notedown_runner.ebnf_grammar()["<option>"] pairs = list(combinations(option_list, 2)) if __name__ == '__main__': len(pairs) if __name__ == '__main__': print(pairs[:20]) def pairwise(option_list): return [option_1 + option_2 for (option_1, option_2) in combinations(option_list, 2)] if __name__ == '__main__': print(pairwise(option_list)[:20]) if __name__ == '__main__': notedown_grammar = notedown_runner.grammar() pairwise_notedown_grammar = extend_grammar(notedown_grammar) pairwise_notedown_grammar["<option>"] = pairwise(notedown_grammar["<option>"]) assert is_valid_grammar(pairwise_notedown_grammar) if __name__ == '__main__': notedown_fuzzer = GrammarCoverageFuzzer( pairwise_notedown_grammar, max_nonterminals=4) if __name__ == '__main__': for i in range(10): print(notedown_fuzzer.fuzz()) if __name__ == '__main__': for combination_length in range(1, 20): tuples = list(combinations(option_list, combination_length)) print(combination_length, len(tuples)) if __name__ == '__main__': len(autopep8_runner.ebnf_grammar()["<option>"]) if __name__ == '__main__': len(autopep8_runner.ebnf_grammar()["<option>"]) * \ (len(autopep8_runner.ebnf_grammar()["<option>"]) - 1) if __name__ == '__main__': len(mypy_runner.ebnf_grammar()["<option>"]) if __name__ == '__main__': len(mypy_runner.ebnf_grammar()["<option>"]) * \ (len(mypy_runner.ebnf_grammar()["<option>"]) - 1) ## Synopsis ## -------- if __name__ == '__main__': print('\n## Synopsis') if __name__ == '__main__': autopep8_runner = OptionRunner("autopep8", "foo.py") if __name__ == '__main__': option_ebnf_grammar = autopep8_runner.ebnf_grammar() print(option_ebnf_grammar) from .Grammars import convert_ebnf_grammar if __name__ == '__main__': fuzzer = GrammarCoverageFuzzer(convert_ebnf_grammar(option_ebnf_grammar)) [fuzzer.fuzz() for i in range(3)] if __name__ == '__main__': autopep8_runner = OptionRunner("autopep8", "foo.py") autopep8_fuzzer = OptionFuzzer(autopep8_runner) if __name__ == '__main__': [autopep8_fuzzer.fuzz() for i in range(3)] ## Lessons Learned ## --------------- if __name__ == '__main__': print('\n## Lessons Learned') ## Next Steps ## ---------- if __name__ == '__main__': print('\n## Next Steps') ## Background ## ---------- if __name__ == '__main__': print('\n## Background') ## Exercises ## --------- if __name__ == '__main__': print('\n## Exercises') ### Exercise 1: #ifdef Configuration Fuzzing if __name__ == '__main__': print('\n### Exercise 1: #ifdef Configuration Fuzzing') #### Part 1: Extract Preprocessor Variables if __name__ == '__main__': print('\n#### Part 1: Extract Preprocessor Variables') if __name__ == '__main__': filename = "xmlparse.c" open(filename, "w").write( """ #if defined(_WIN32) && !defined(LOAD_LIBRARY_SEARCH_SYSTEM32) # define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800 #endif #if !defined(HAVE_GETRANDOM) && !defined(HAVE_SYSCALL_GETRANDOM) \ && !defined(HAVE_ARC4RANDOM_BUF) && !defined(HAVE_ARC4RANDOM) \ && !defined(XML_DEV_URANDOM) \ && !defined(_WIN32) \ && !defined(XML_POOR_ENTROPY) # error #endif #if !defined(TIOCSWINSZ) || defined(__SCO__) || defined(__UNIXWARE__) #define USE_SYSV_ENVVARS /* COLUMNS/LINES vs. TERMCAP */ #endif #ifdef XML_UNICODE_WCHAR_T #define XML_T(x) (const wchar_t)x #define XML_L(x) L ## x #else #define XML_T(x) (const unsigned short)x #define XML_L(x) x #endif int fun(int x) { return XML_T(x); } """); import re if __name__ == '__main__': re_cpp_if_directive = re.compile(r"\s*#\s*(el)?if") re_cpp_identifier = re.compile(r"[a-zA-Z_$]+") def cpp_identifiers(lines): identifiers = set() for line in lines: if re_cpp_if_directive.match(line): identifiers |= set(re_cpp_identifier.findall(line)) # These are preprocessor keywords identifiers -= {"if", "ifdef", "ifndef", "defined"} return identifiers if __name__ == '__main__': cpp_ids = cpp_identifiers(open("xmlparse.c").readlines()) cpp_ids #### Part 2: Derive an Option Grammar if __name__ == '__main__': print('\n#### Part 2: Derive an Option Grammar') from .Grammars import new_symbol if __name__ == '__main__': cpp_grammar = { "<start>": ["cc -c<options> " + filename], "<options>": ["<option>", "<options><option>"], "<option>": [] } for id in cpp_ids: s = new_symbol(cpp_grammar, "<" + id + ">") cpp_grammar["<option>"].append(s) cpp_grammar[s] = [" -D" + id] cpp_grammar if __name__ == '__main__': assert is_valid_grammar(cpp_grammar) #### Part 3: C Preprocessor Configuration Fuzzing if __name__ == '__main__': print('\n#### Part 3: C Preprocessor Configuration Fuzzing') if __name__ == '__main__': g = GrammarCoverageFuzzer(cpp_grammar) g.fuzz() from .Fuzzer import ProgramRunner if __name__ == '__main__': for i in range(10): invocation = g.fuzz() print("$", invocation) # subprocess.call(invocation, shell=True) cc_runner = ProgramRunner(invocation.split(' ')) (result, outcome) = cc_runner.run() print(result.stderr, end="") if __name__ == '__main__': pairwise_cpp_grammar = extend_grammar(cpp_grammar) pairwise_cpp_grammar["<option>"] = pairwise(cpp_grammar["<option>"]) pairwise_cpp_grammar["<option>"][:10] if __name__ == '__main__': for i in range(10): invocation = g.fuzz() print("$", invocation) # subprocess.call(invocation, shell=True) cc_runner = ProgramRunner(invocation.split(' ')) (result, outcome) = cc_runner.run() print(result.stderr, end="") if __name__ == '__main__': os.remove("xmlparse.c") if __name__ == '__main__': if os.path.exists("xmlparse.o"): os.remove("xmlparse.o") ### Exercise 2: .ini Configuration Fuzzing if __name__ == '__main__': print('\n### Exercise 2: .ini Configuration Fuzzing') import configparser if __name__ == '__main__': config = configparser.ConfigParser() config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret['Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' with open('example.ini', 'w') as configfile: config.write(configfile) with open('example.ini') as configfile: print(configfile.read(), end="") if __name__ == '__main__': config = configparser.ConfigParser() config.read('example.ini') topsecret = config['topsecret.server.com'] topsecret['Port'] #### Part 1: Read Configuration if __name__ == '__main__': print('\n#### Part 1: Read Configuration') #### Part 2: Create a Configuration Grammar if __name__ == '__main__': print('\n#### Part 2: Create a Configuration Grammar') #### Part 3: Mine a Configuration Grammar if __name__ == '__main__': print('\n#### Part 3: Mine a Configuration Grammar') class TrackingConfigParser(configparser.ConfigParser): def __getitem__(self, key): print("Accessing", repr(key)) return super().__getitem__(key) if __name__ == '__main__': tracking_config_parser = TrackingConfigParser() tracking_config_parser.read('example.ini') section = tracking_config_parser['topsecret.server.com'] import os if __name__ == '__main__': os.remove("example.ini") ### Exercise 3: Extracting and Fuzzing C Command-Line Options if __name__ == '__main__': print('\n### Exercise 3: Extracting and Fuzzing C Command-Line Options') #### Part 1: Getopt Fuzzing if __name__ == '__main__': print('\n#### Part 1: Getopt Fuzzing') #### Part 2: Fuzzing Long Options in C if __name__ == '__main__': print('\n#### Part 2: Fuzzing Long Options in C') ### Exercise 4: Expansions in Context if __name__ == '__main__': print('\n### Exercise 4: Expansions in Context') if __name__ == '__main__': autopep8_runner.ebnf_grammar()["<line>"] if __name__ == '__main__': autopep8_runner.ebnf_grammar()["<int>"] if __name__ == '__main__': autopep8_runner.ebnf_grammar()["<digit>"]
import socket import threading from sys import exit server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.connect(("127.0.0.1", 55556)) nickname = input('Pls Enter a nickname') def recive(): while True: try: message = server.recv(1024).decode("ascii") if message == "NICK": server.send(nickname.encode('ascii')) else: print(message) except: print('an error occurred') server.close() break def write(): while True: try: message = f'{nickname}: {input('')}' server.send(message.encode('ascii')) except: server.close() exit() recive_thread = threading.Thread(target=recive) recive_thread.start() write_thread = threading.Thread(target=write) write_thread.start()
import socket import threading from sys import exit server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.connect(("127.0.0.1", 55556)) nickname = input('Pls Enter a nickname') def recive(): while True: try: message = server.recv(1024).decode("ascii") if message == "NICK": server.send(nickname.encode('ascii')) else: print(message) except: print('an error occurred') server.close() break def write(): while True: try: message = f'{nickname}: {input("")}' server.send(message.encode('ascii')) except: server.close() exit() recive_thread = threading.Thread(target=recive) recive_thread.start() write_thread = threading.Thread(target=write) write_thread.start()
import json import os import platform import sys import threading import time from concurrent.futures import ThreadPoolExecutor import requests from pixivpy3 import * from altfe.interface.root import interRoot @interRoot.bind("biu", "LIB_CORE") class core_module_biu(interRoot): def __init__(self): self.ver = 201020 self.lowestConfVer = 5 self.place = "local" self.sysPlc = platform.system() self.apiType = "public" self.api = None self.apiAssist = None self.sets = self.loadConfig(self.getENV("rootPath") + "config.yml") self.pximgURL = "https://i.pximg.net" self.proxy = "" self.biuInfo = "" # 线程相关 self.lock = threading.Lock() self.pool_srh = ThreadPoolExecutor( max_workers=self.sets["biu"]["search"]["maxThreads"] ) self.STATUS = {"rate_search": {}, "rate_download": {}} # 暂时 self.sets["account"]["isToken"] = True self.sets["account"]["username"] = "1" self.sets["account"]["password"] = "1" self.auto() def __del__(self): self.pool_srh.shutdown(False) def auto(self): self.__prepConfig() # 加载配置项 self.__preCheck() # 运行前检测 self.proxy = self.__getSystemProxy() # 加载代理地址 self.biuInfo = self.__getBiuInfo() # 加载联网信息 self.__checkForUpdate() # 检测更新 if self.apiType != "byPassSni": self.__checkNetwork() # 检测网络是否可通 self.__login() # 登录 self.__setImageHost() # 设置图片服务器地址 self.__showRdyInfo() # 展示初始化完成信息 return self def __prepConfig(self): """ 加载 pixivbiu 的全局配置项。 """ if self.sets is None: self.STATIC.localMsger.red("读取配置文件失败,程序无法正常运行") input("按任意键退出...") sys.exit(0) if self.sets["sys"]["confVersion"] < self.lowestConfVer: self.STATIC.localMsger.red("配置文件版本过低,请使用新版本中的配置文件 (config.yml)") input("按任意键退出...") sys.exit(0) self.apiType = self.sets["sys"]["api"] def __preCheck(self): """ 进行运行前的检测,目前有如下功能: 1. 检测端口是否已被占用 """ # 检测端口是否被占用 if self.STATIC.util.isPortInUse(self.sets["sys"]["host"].split(":")[1]): self.STATIC.localMsger.red("现端口已被占用,请修改 config.yml 中 sys-host 配置项") input("按任意键退出...") sys.exit(0) def __getSystemProxy(self): """ 获取系统代理设置。 :return: """ if self.sets["biu"]["common"]["proxy"] == "no": return "" if self.apiType == "byPassSni" or self.sets["biu"]["common"]["proxy"] != "": return self.sets["biu"]["common"]["proxy"] url = self.STATIC.util.getSystemProxy(self.sysPlc) if url != "": self.STATIC.localMsger.msg(f"已启用系统代理地址: {url}") return url def __getBiuInfo(self): """ 获取联网 pixivbiu 相关信息。 """ try: return json.loads( requests.get("https://biu.tls.moe/d/biuinfo.json", timeout=6, verify=False).text ) except: return {"version": -1, "pApiURL": "public-api.secure.pixiv.net"} def __checkForUpdate(self): """ 检测是否有更新,仅本地版本号对比。 """ if self.biuInfo["version"] == -1: self.STATIC.localMsger.red("检测更新失败,可能是目标服务器过长时间未响应") elif self.ver < self.biuInfo["version"]: self.STATIC.localMsger.red(f"有新版本可用@{self.biuInfo["version"]}!访问 https://biu.tls.moe/ 即可下载") input("按任意键以继续使用旧版本...") def __checkNetwork(self): """ 检测网络是否可通。若不可通,则启用 bypass 模式。 """ self.STATIC.localMsger.msg("检测网络状态...") try: if self.proxy != "": requests.get( "https://pixiv.net/", proxies={"https": self.proxy}, timeout=3, verify=False ) else: requests.get("https://pixiv.net/", timeout=3, verify=False) except: self.STATIC.localMsger.msg("无法访问 Pixiv,启用 byPassSni API") self.apiType = "byPassSni" self.proxy = "" def __login(self, refreshToken=None, retry=True): """ 登录函数。 """ try: tokenFile = self.STATIC.file.ain( self.getENV("rootPath") + "usr/.token.json") if refreshToken is None else {"token": refreshToken} if self.sets["account"]["isToken"] and tokenFile: args = { "token": tokenFile["token"], } else: self.__loadAccountInfo() args = { "username": self.sets["account"]["username"], "password": self.sets["account"]["password"], } if self.apiType == "app" or self.apiType == "byPassSni": self.__loginAppAPI(**args) else: self.__loginPublicAPI(**args) except Exception as e: if retry is False: self.STATIC.localMsger.error(e) input("按任意键退出...") sys.exit(0) self.STATIC.localMsger.green("由于 Pixiv 禁止了账号密码登陆方式,暂时只能使用 Token 进行登录") if input("是否开始手动获取 Token 后继续使用? (y / n): ") != "y": input("按任意键退出...") sys.exit(0) self.STATIC.localMsger.msg("即将开始进行网络检测,此过程可以减少因网络问题导致的无法正常使用 PixivBiu 的概率", header="Login Helper") helper = self.COMMON.loginHelper() if helper.check_network() is False: self.STATIC.localMsger.red("您的网络无法正常进行 Pixiv Token 登陆,请调整后重试。") input("按任意键退出...") sys.exit(0) token = helper.login() if token is False: self.STATIC.localMsger.red("获取 Token 时出错,请重试。") input("按任意键退出...") sys.exit(0) self.STATIC.file.aout( self.getENV("rootPath") + "usr/.token.json", {"token": token, }, dRename=False, ) self.__login(retry=False) def __loadAccountInfo(self): """ 要求用户输入 Pixiv 邮箱、密码信息。 """ if ( self.sets["account"]["username"] == "" or self.sets["account"]["password"] == "" ): self.STATIC.localMsger.msg("请输入您 Pixiv 的邮箱、密码 (本程序不会记录)", header=False) self.sets["account"]["username"] = input(self.STATIC.localMsger.green("邮箱: ", header=False, out=False)) self.sets["account"]["password"] = input(self.STATIC.localMsger.green("密码: ", header=False, out=False)) self.__clear() return self.sets["account"]["username"], self.sets["account"]["password"] def __loginPublicAPI(self, username=None, password=None, token=None): """ public 模式登录。 """ _REQUESTS_KWARGS = {} if self.proxy != "": _REQUESTS_KWARGS = { "proxies": {"https": self.proxy, }, } self.api = PixivAPI(**_REQUESTS_KWARGS) self.apiAssist = AppPixivAPI(**_REQUESTS_KWARGS) if token is not None: try: self.api.auth(refresh_token=token) self.apiAssist.auth(refresh_token=token) except: account = self.__loadAccountInfo() self.api.login(*account) self.apiAssist.login(*account) else: self.api.login(username, password) self.apiAssist.login(username, password) if self.sets["account"]["isToken"]: self.STATIC.file.aout( self.getENV("rootPath") + "usr/.token.json", {"token": self.api.refresh_token, }, dRename=False, ) self.STATIC.localMsger.msg(f"{self.apiType} API 登陆成功") def __loginAppAPI(self, username=None, password=None, token=None): """ app 模式登录。 """ _REQUESTS_KWARGS = {} if self.proxy != "" and self.apiType != "byPassSni": _REQUESTS_KWARGS = { "proxies": {"https": self.proxy, }, } if self.apiType == "app": self.api = AppPixivAPI(**_REQUESTS_KWARGS) else: self.api = ByPassSniApi(**_REQUESTS_KWARGS) self.api.require_appapi_hosts(hostname=self.biuInfo["pApiURL"]) self.api.set_accept_language("zh-cn") if token is not None: try: self.api.auth(refresh_token=token) # self.STATIC.localMsger.msg("使用 Token 登陆") except: account = self.__loadAccountInfo() self.api.login(*account) else: self.api.login(username, password) if self.sets["account"]["isToken"]: self.STATIC.file.aout( self.getENV("rootPath") + "usr/.token.json", {"token": self.api.refresh_token, }, dRename=False, ) self.apiAssist = self.api self.STATIC.localMsger.msg(f"{self.apiType} API 登陆成功") def __showRdyInfo(self): """ 展示初始化成功消息。 """ if self.biuInfo["version"] == -1: des = self.STATIC.localMsger.red("检测更新失败", header=False, out=False) else: if self.ver >= int(self.biuInfo["version"]): des = "最新" else: des = self.STATIC.localMsger.red(f"有新版本可用@{self.biuInfo["version"]}", header=False, out=False) WORDS = "abcdefghij" version = str(self.ver) self.STATIC.localMsger.arr( self.STATIC.localMsger.msg("初始化完成", out=False), "------------", self.STATIC.localMsger.sign(" PixivBiu ", header=False, out=False), "-", ("运行", "%s (将地址输入现代浏览器即可使用)" % self.STATIC.localMsger.green("http://" + self.sets["sys"]["host"] + "/", header=False, out=False)), ("版本", "2.%s.%s%s (%s)" % (int(version[1:3]), int(version[3:5]), WORDS[int(version[-1])], des)), ("API 类型", self.apiType), ("图片服务器", self.pximgURL + "/"), ("下载保存路径", self.sets["biu"]["download"]["saveURI"].replace("{ROOTPATH}", "程序目录")), "-", self.STATIC.localMsger.sign(" Biu ", header=False, out=False), "------------" ) t = threading.Timer(60 * 20, self.__pro_refreshToken) t.setDaemon(True) t.start() def __pro_refreshToken(self): """ 子线程,每 20 分钟刷新一次 refresh token 并重新登录,以持久化登录状态。 :return: none """ helper = self.COMMON.loginHelper() while True: self.STATIC.localMsger.msg( "updating token at %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))) try: try: helper.check_network(silent=True, proxy_="") except: try: helper.check_network(silent=True, proxy_="auto") except: helper.check_network(silent=True, proxy_=self.proxy) token = helper.refresh(refresh_token=self.api.refresh_token) if token is not False: self.__login(refreshToken=token) except Exception as e: self.STATIC.localMsger.error(e, header=False) time.sleep(60 * 20) def updateStatus(self, type_, key, c): """ 线程池状态更新函数。 @type_(str): search || download @key(str): 线程的唯一 key @c(thread): 线程引用 """ if not key or c == []: return self.lock.acquire() if type_ == "search": self.STATUS["rate_search"][key] = c elif type_ == "download": self.STATUS["rate_download"][key] = c self.lock.release() def appWorksPurer(self, da): """ 格式化返回的图片信息。 """ for i in range(len(da)): total = views = 0 typer = "other" typea = { "illust": "illustration", "manga": "manga", "ugoira": "ugoira", } originalPic = None tags = [] c = da[i] if c["total_bookmarks"]: total = int(c["total_bookmarks"]) if c["total_view"]: views = int(c["total_view"]) if c["type"] in typea: typer = typea[c["type"]] for x in c["tags"]: tags.append(x["name"]) if "original_image_url" in c["meta_single_page"]: originalPic = c["meta_single_page"]["original_image_url"] else: originalPic = c["image_urls"]["large"] if "is_followed" in c["user"]: is_followed = c["user"]["is_followed"] is True else: is_followed = False r = { "id": int(c["id"]), "type": typer, "title": c["title"], "caption": c["caption"], "created_time": c["create_date"], "image_urls": { "small": c["image_urls"]["square_medium"], "medium": c["image_urls"]["medium"], "large": originalPic, }, "is_bookmarked": (c["is_bookmarked"] is True), "total_bookmarked": total, "total_viewed": views, "author": { "id": c["user"]["id"], "account": c["user"]["account"], "name": c["user"]["name"], "is_followed": is_followed, }, "tags": tags, "all": c.copy(), } da[i] = r def __setImageHost(self): """ 设置 pixiv 图片服务器地址。 """ if self.sets["biu"]["download"]["imageHost"] != "": self.pximgURL = self.sets["biu"]["download"]["imageHost"] if self.apiType == "byPassSni": self.pximgURL = "https://i.pixiv.re" def __clear(self): if os.name == "nt": os.system("cls") else: os.system("clear")
import json import os import platform import sys import threading import time from concurrent.futures import ThreadPoolExecutor import requests from pixivpy3 import * from altfe.interface.root import interRoot @interRoot.bind("biu", "LIB_CORE") class core_module_biu(interRoot): def __init__(self): self.ver = 201020 self.lowestConfVer = 5 self.place = "local" self.sysPlc = platform.system() self.apiType = "public" self.api = None self.apiAssist = None self.sets = self.loadConfig(self.getENV("rootPath") + "config.yml") self.pximgURL = "https://i.pximg.net" self.proxy = "" self.biuInfo = "" # 线程相关 self.lock = threading.Lock() self.pool_srh = ThreadPoolExecutor( max_workers=self.sets["biu"]["search"]["maxThreads"] ) self.STATUS = {"rate_search": {}, "rate_download": {}} # 暂时 self.sets["account"]["isToken"] = True self.sets["account"]["username"] = "1" self.sets["account"]["password"] = "1" self.auto() def __del__(self): self.pool_srh.shutdown(False) def auto(self): self.__prepConfig() # 加载配置项 self.__preCheck() # 运行前检测 self.proxy = self.__getSystemProxy() # 加载代理地址 self.biuInfo = self.__getBiuInfo() # 加载联网信息 self.__checkForUpdate() # 检测更新 if self.apiType != "byPassSni": self.__checkNetwork() # 检测网络是否可通 self.__login() # 登录 self.__setImageHost() # 设置图片服务器地址 self.__showRdyInfo() # 展示初始化完成信息 return self def __prepConfig(self): """ 加载 pixivbiu 的全局配置项。 """ if self.sets is None: self.STATIC.localMsger.red("读取配置文件失败,程序无法正常运行") input("按任意键退出...") sys.exit(0) if self.sets["sys"]["confVersion"] < self.lowestConfVer: self.STATIC.localMsger.red("配置文件版本过低,请使用新版本中的配置文件 (config.yml)") input("按任意键退出...") sys.exit(0) self.apiType = self.sets["sys"]["api"] def __preCheck(self): """ 进行运行前的检测,目前有如下功能: 1. 检测端口是否已被占用 """ # 检测端口是否被占用 if self.STATIC.util.isPortInUse(self.sets["sys"]["host"].split(":")[1]): self.STATIC.localMsger.red("现端口已被占用,请修改 config.yml 中 sys-host 配置项") input("按任意键退出...") sys.exit(0) def __getSystemProxy(self): """ 获取系统代理设置。 :return: """ if self.sets["biu"]["common"]["proxy"] == "no": return "" if self.apiType == "byPassSni" or self.sets["biu"]["common"]["proxy"] != "": return self.sets["biu"]["common"]["proxy"] url = self.STATIC.util.getSystemProxy(self.sysPlc) if url != "": self.STATIC.localMsger.msg(f"已启用系统代理地址: {url}") return url def __getBiuInfo(self): """ 获取联网 pixivbiu 相关信息。 """ try: return json.loads( requests.get("https://biu.tls.moe/d/biuinfo.json", timeout=6, verify=False).text ) except: return {"version": -1, "pApiURL": "public-api.secure.pixiv.net"} def __checkForUpdate(self): """ 检测是否有更新,仅本地版本号对比。 """ if self.biuInfo["version"] == -1: self.STATIC.localMsger.red("检测更新失败,可能是目标服务器过长时间未响应") elif self.ver < self.biuInfo["version"]: self.STATIC.localMsger.red(f"有新版本可用@{self.biuInfo['version']}!访问 https://biu.tls.moe/ 即可下载") input("按任意键以继续使用旧版本...") def __checkNetwork(self): """ 检测网络是否可通。若不可通,则启用 bypass 模式。 """ self.STATIC.localMsger.msg("检测网络状态...") try: if self.proxy != "": requests.get( "https://pixiv.net/", proxies={"https": self.proxy}, timeout=3, verify=False ) else: requests.get("https://pixiv.net/", timeout=3, verify=False) except: self.STATIC.localMsger.msg("无法访问 Pixiv,启用 byPassSni API") self.apiType = "byPassSni" self.proxy = "" def __login(self, refreshToken=None, retry=True): """ 登录函数。 """ try: tokenFile = self.STATIC.file.ain( self.getENV("rootPath") + "usr/.token.json") if refreshToken is None else {"token": refreshToken} if self.sets["account"]["isToken"] and tokenFile: args = { "token": tokenFile["token"], } else: self.__loadAccountInfo() args = { "username": self.sets["account"]["username"], "password": self.sets["account"]["password"], } if self.apiType == "app" or self.apiType == "byPassSni": self.__loginAppAPI(**args) else: self.__loginPublicAPI(**args) except Exception as e: if retry is False: self.STATIC.localMsger.error(e) input("按任意键退出...") sys.exit(0) self.STATIC.localMsger.green("由于 Pixiv 禁止了账号密码登陆方式,暂时只能使用 Token 进行登录") if input("是否开始手动获取 Token 后继续使用? (y / n): ") != "y": input("按任意键退出...") sys.exit(0) self.STATIC.localMsger.msg("即将开始进行网络检测,此过程可以减少因网络问题导致的无法正常使用 PixivBiu 的概率", header="Login Helper") helper = self.COMMON.loginHelper() if helper.check_network() is False: self.STATIC.localMsger.red("您的网络无法正常进行 Pixiv Token 登陆,请调整后重试。") input("按任意键退出...") sys.exit(0) token = helper.login() if token is False: self.STATIC.localMsger.red("获取 Token 时出错,请重试。") input("按任意键退出...") sys.exit(0) self.STATIC.file.aout( self.getENV("rootPath") + "usr/.token.json", {"token": token, }, dRename=False, ) self.__login(retry=False) def __loadAccountInfo(self): """ 要求用户输入 Pixiv 邮箱、密码信息。 """ if ( self.sets["account"]["username"] == "" or self.sets["account"]["password"] == "" ): self.STATIC.localMsger.msg("请输入您 Pixiv 的邮箱、密码 (本程序不会记录)", header=False) self.sets["account"]["username"] = input(self.STATIC.localMsger.green("邮箱: ", header=False, out=False)) self.sets["account"]["password"] = input(self.STATIC.localMsger.green("密码: ", header=False, out=False)) self.__clear() return self.sets["account"]["username"], self.sets["account"]["password"] def __loginPublicAPI(self, username=None, password=None, token=None): """ public 模式登录。 """ _REQUESTS_KWARGS = {} if self.proxy != "": _REQUESTS_KWARGS = { "proxies": {"https": self.proxy, }, } self.api = PixivAPI(**_REQUESTS_KWARGS) self.apiAssist = AppPixivAPI(**_REQUESTS_KWARGS) if token is not None: try: self.api.auth(refresh_token=token) self.apiAssist.auth(refresh_token=token) except: account = self.__loadAccountInfo() self.api.login(*account) self.apiAssist.login(*account) else: self.api.login(username, password) self.apiAssist.login(username, password) if self.sets["account"]["isToken"]: self.STATIC.file.aout( self.getENV("rootPath") + "usr/.token.json", {"token": self.api.refresh_token, }, dRename=False, ) self.STATIC.localMsger.msg(f"{self.apiType} API 登陆成功") def __loginAppAPI(self, username=None, password=None, token=None): """ app 模式登录。 """ _REQUESTS_KWARGS = {} if self.proxy != "" and self.apiType != "byPassSni": _REQUESTS_KWARGS = { "proxies": {"https": self.proxy, }, } if self.apiType == "app": self.api = AppPixivAPI(**_REQUESTS_KWARGS) else: self.api = ByPassSniApi(**_REQUESTS_KWARGS) self.api.require_appapi_hosts(hostname=self.biuInfo["pApiURL"]) self.api.set_accept_language("zh-cn") if token is not None: try: self.api.auth(refresh_token=token) # self.STATIC.localMsger.msg("使用 Token 登陆") except: account = self.__loadAccountInfo() self.api.login(*account) else: self.api.login(username, password) if self.sets["account"]["isToken"]: self.STATIC.file.aout( self.getENV("rootPath") + "usr/.token.json", {"token": self.api.refresh_token, }, dRename=False, ) self.apiAssist = self.api self.STATIC.localMsger.msg(f"{self.apiType} API 登陆成功") def __showRdyInfo(self): """ 展示初始化成功消息。 """ if self.biuInfo["version"] == -1: des = self.STATIC.localMsger.red("检测更新失败", header=False, out=False) else: if self.ver >= int(self.biuInfo["version"]): des = "最新" else: des = self.STATIC.localMsger.red(f"有新版本可用@{self.biuInfo['version']}", header=False, out=False) WORDS = "abcdefghij" version = str(self.ver) self.STATIC.localMsger.arr( self.STATIC.localMsger.msg("初始化完成", out=False), "------------", self.STATIC.localMsger.sign(" PixivBiu ", header=False, out=False), "-", ("运行", "%s (将地址输入现代浏览器即可使用)" % self.STATIC.localMsger.green("http://" + self.sets["sys"]["host"] + "/", header=False, out=False)), ("版本", "2.%s.%s%s (%s)" % (int(version[1:3]), int(version[3:5]), WORDS[int(version[-1])], des)), ("API 类型", self.apiType), ("图片服务器", self.pximgURL + "/"), ("下载保存路径", self.sets["biu"]["download"]["saveURI"].replace("{ROOTPATH}", "程序目录")), "-", self.STATIC.localMsger.sign(" Biu ", header=False, out=False), "------------" ) t = threading.Timer(60 * 20, self.__pro_refreshToken) t.setDaemon(True) t.start() def __pro_refreshToken(self): """ 子线程,每 20 分钟刷新一次 refresh token 并重新登录,以持久化登录状态。 :return: none """ helper = self.COMMON.loginHelper() while True: self.STATIC.localMsger.msg( "updating token at %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))) try: try: helper.check_network(silent=True, proxy_="") except: try: helper.check_network(silent=True, proxy_="auto") except: helper.check_network(silent=True, proxy_=self.proxy) token = helper.refresh(refresh_token=self.api.refresh_token) if token is not False: self.__login(refreshToken=token) except Exception as e: self.STATIC.localMsger.error(e, header=False) time.sleep(60 * 20) def updateStatus(self, type_, key, c): """ 线程池状态更新函数。 @type_(str): search || download @key(str): 线程的唯一 key @c(thread): 线程引用 """ if not key or c == []: return self.lock.acquire() if type_ == "search": self.STATUS["rate_search"][key] = c elif type_ == "download": self.STATUS["rate_download"][key] = c self.lock.release() def appWorksPurer(self, da): """ 格式化返回的图片信息。 """ for i in range(len(da)): total = views = 0 typer = "other" typea = { "illust": "illustration", "manga": "manga", "ugoira": "ugoira", } originalPic = None tags = [] c = da[i] if c["total_bookmarks"]: total = int(c["total_bookmarks"]) if c["total_view"]: views = int(c["total_view"]) if c["type"] in typea: typer = typea[c["type"]] for x in c["tags"]: tags.append(x["name"]) if "original_image_url" in c["meta_single_page"]: originalPic = c["meta_single_page"]["original_image_url"] else: originalPic = c["image_urls"]["large"] if "is_followed" in c["user"]: is_followed = c["user"]["is_followed"] is True else: is_followed = False r = { "id": int(c["id"]), "type": typer, "title": c["title"], "caption": c["caption"], "created_time": c["create_date"], "image_urls": { "small": c["image_urls"]["square_medium"], "medium": c["image_urls"]["medium"], "large": originalPic, }, "is_bookmarked": (c["is_bookmarked"] is True), "total_bookmarked": total, "total_viewed": views, "author": { "id": c["user"]["id"], "account": c["user"]["account"], "name": c["user"]["name"], "is_followed": is_followed, }, "tags": tags, "all": c.copy(), } da[i] = r def __setImageHost(self): """ 设置 pixiv 图片服务器地址。 """ if self.sets["biu"]["download"]["imageHost"] != "": self.pximgURL = self.sets["biu"]["download"]["imageHost"] if self.apiType == "byPassSni": self.pximgURL = "https://i.pixiv.re" def __clear(self): if os.name == "nt": os.system("cls") else: os.system("clear")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # This file is part of CbM (https://github.com/ec-jrc/cbm). # Author : Guido Lemoine, Konstantinos Anastasakis # Credits : GTCAP Team # Copyright : 2021 European Commission, Joint Research Centre # License : 3-Clause BSD import os import os.path import requests from os.path import join, normpath, isfile from cbm.utils import config def parcel_by_loc(aoi, year, lon, lat, ptype=None, geom=False, wgs84=False, debug=False): api_url, api_user, api_pass = config.credentials('api') requrl = """{}/query/parcelByLocation?aoi={}&year={}&lon={}&lat={}""" if geom is True: requrl = f"{requrl}&withGeometry=True" if ptype not in [None, '']: requrl = f"{requrl}&ptype={ptype}" if wgs84 is True: requrl = f"{requrl}&wgs84={wgs84}" # print(requrl.format(api_url, aoi, year, lon, lat)) response = requests.get(requrl.format(api_url, aoi, year, lon, lat), auth=(api_user, api_pass)) if debug: print(requrl.format(api_url, aoi, year, lon, lat), response) return response.content def parcel_by_id(aoi, year, pid, ptype=None, geom=False, wgs84=False, debug=False): api_url, api_user, api_pass = config.credentials('api') requrl = """{}/query/parcelById?aoi={}&year={}&pid={}""" if geom is True: requrl = f"{requrl}&withGeometry=True" if ptype not in [None, '']: requrl = f"{requrl}&ptype={ptype}" if wgs84 is True: requrl = f"{requrl}&wgs84={wgs84}" # print(requrl.format(api_url, aoi, year, pid)) response = requests.get(requrl.format(api_url, aoi, year, pid), auth=(api_user, api_pass)) if debug: print(requrl.format(api_url, aoi, year, pid), response) return response.content def parcel_by_polygon(aoi, year, polygon, ptype=None, geom=False, wgs84=False, only_ids=True, debug=False): api_url, api_user, api_pass = config.credentials('api') requrl = """{}/query/parcelsByPolygon?aoi={}&year={}&polygon={}""" if geom is True: requrl = f"{requrl}&withGeometry=True" if only_ids is True: requrl = f"{requrl}&only_ids=True" if ptype not in [None, '']: requrl = f"{requrl}&ptype={ptype}" if wgs84 is True: requrl = f"{requrl}&wgs84={wgs84}" response = requests.get(requrl.format(api_url, aoi, year, polygon), auth=(api_user, api_pass)) if debug: print(requrl.format(api_url, aoi, year, polygon), response) return response.content def parcel_ts(aoi, year, pid, tstype='s2', ptype=None, band='', debug=False): api_url, api_user, api_pass = config.credentials('api') requrl = """{}/query/parcelTimeSeries?aoi={}&year={}&pid={}&tstype={}""" if ptype not in [None, '']: requrl = f"{requrl}&ptype={ptype}" if band not in [None, '']: requrl = f"{requrl}&band={band}" response = requests.get(requrl.format(api_url, aoi, year, pid, tstype, band), auth=(api_user, api_pass)) if debug: print(requrl.format(api_url, aoi, year, pid, tstype, band), response) return response.content def cbl(lon, lat, start_date, end_date, bands=None, lut=None, chipsize=None): api_url, api_user, api_pass = config.credentials('api') requrl = """{}/query/chipsByLocation?lon={}&lat={}&start_date={}&end_date={}""" band = '_'.join(bands) if band is not None: requrl = f"{requrl}&band={band}" if chipsize is not None: requrl = f"{requrl}&chipsize={chipsize}" if lut != '': requrl = f"{requrl}&lut={lut}" # print(requrl.format(api_url, lon, lat, start_date, end_date)) response = requests.get(requrl.format(api_url, lon, lat, start_date, end_date), auth=(api_user, api_pass)) return response def rcbl(parcel, start_date, end_date, bands, chipsize, filespath, quiet=True): """Get parcel raw chip images from RESTful API by location""" import os import os.path import pandas as pd from osgeo import osr, ogr import time start = time.time() api_url, api_user, api_pass = config.credentials('api') for band in bands: requrl = """{}/query/rawChipByLocation?lon={}&lat={}&start_date={}&end_date={}""" if band is not None: requrl = f"{requrl}&band={band}" if chipsize is not None: requrl = f"{requrl}&chipsize={chipsize}" # Create a valid geometry from the returned JSON withGeometry geom = ogr.CreateGeometryFromJson(parcel.get('geom')[0]) source = osr.SpatialReference() source.ImportFromEPSG(parcel.get('srid')[0]) # Assign this projection to the geometry geom.AssignSpatialReference(source) target = osr.SpatialReference() target.ImportFromEPSG(4326) transform = osr.CoordinateTransformation(source, target) # And get the lon, lat for its centroid, so that we can center the chips # on the parcel centroid = geom.Centroid() centroid.Transform(transform) # Use pid for next request # pid = parcel['pid'][0] # cropname = parcel['cropname'][0] # Set up the rawChip request cen_x, cen_y = str(centroid.GetX()), str(centroid.GetY()) response = requests.get(requrl.format(api_url, cen_y, cen_x, start_date, end_date, band, chipsize), auth=(api_user, api_pass)) if not quiet: print("Request url:", requrl.format( api_url, cen_y, cen_x, start_date, end_date, band, chipsize)) print("Geom:", geom) print("Source:", source, ", Target:", target) print("Centroid", centroid) print("Response:", response) # Directly create a pandas DataFrame from the json response df = pd.read_json(response.content) os.makedirs(filespath, exist_ok=True) df_file = normpath(join(filespath, f'images_list.{band}.csv')) df.to_csv(df_file, index=True, header=True) # print(f"The response table is saved to: {df_file}") # Download the GeoTIFFs that were just created in the user cache for c in df.chips: url = f"{api_url}{c}" outf = normpath(join(filespath, c.split('/')[-1])) if not isfile(outf): res = requests.get(url, stream=True) if not quiet: print(f"Downloading {c.split("/")[-1]}") with open(outf, "wb") as handle: for chunk in res.iter_content(chunk_size=512): if chunk: # filter out keep-alive new chunks handle.write(chunk) if not quiet: print( f"Images for band '{band}', for the selected dates are downloaded.") if not quiet: print("\n------Total time------") print( f"Total time required for {len(bands)} bands: {time.time() - start} seconds.") def clouds(geom): import glob import json import rasterio from osgeo import osr from rasterstats import zonal_stats # Check whether our parcel is cloud free # We should have a list of GeoTIFFs ending with .SCL.tif tiflist = glob.glob('*.SCL.tif') for t in tiflist: with rasterio.open(t) as src: affine = src.transform CRS = src.crs data = src.read(1) # Reproject the parcel geometry in the image crs imageCRS = int(str(CRS).split(':')[-1]) # Cross check with the projection of the geometry # This needs to be done for each image, because the parcel could be in # a straddle between (UTM) zones geomCRS = int(geom.GetSpatialReference().GetAuthorityCode(None)) if geomCRS != imageCRS: target = osr.SpatialReference() target.ImportFromEPSG(imageCRS) source = osr.SpatialReference() source.ImportFromEPSG(geomCRS) transform = osr.CoordinateTransformation(source, target) geom.Transform(transform) # Format as a feature collection (with only 1 feature) # and extract the histogram features = {"type": "FeatureCollection", "features": [{"type": "feature", "geometry": json.loads(geom.ExportToJson()), "properties": {"pid": pid}}]} zs = zonal_stats(features, data, affine=affine, prefix="", nodata=0, categorical=True, geojson_out=True) # This has only one record properties = zs[0].get('properties') # pid was used as a dummy key to make sure the histogram # values are in 'properties' del properties['pid'] histogram = {int(float(k)): v for k, v in properties.items()} # print(t, histogram) def get_options(): api_url, api_user, api_pass = config.credentials('api') requrl = """{}/query/options""" response = requests.get(requrl.format(api_url), auth=(api_user, api_pass)) return response.content def background(lon, lat, chipsize=512, extend=512, tms='Google', bg_path='', debug=False): # aoi='undefined', year='', pid='0000', quiet=True): """Download the background image. Examples: background(lon, lat, 512, 512, 'Google', 'temp/test.tif', True) Arguments: lon, lat, longitude and latitude in decimal degrees (float). chipsize, size of the chip in pixels (int). extend, size of the chip in meters (float). tms, tile map server Google or Bing (str). bk_file, the name of the output file (str). """ # Get the api credentials api_url, api_user, api_pass = config.credentials('api') # The url to get the background image requrl = f"lon={lon}&lat={lat}&chipsize={chipsize}&extend={extend}" # print(f"{api_url}/query/backgroundByLocation?{requrl}&tms={tms}&iformat=tif") response = requests.get( f"{api_url}/query/backgroundByLocation?{requrl}&tms={tms}&iformat=tif", auth=(api_user, api_pass)) # print(response) # Try to get the image link from the html response try: img_url = response.content.decode("utf-8") # print(type(img_url), img_url) if img_url == '{}': if debug: print("Image not found...") print( f"{api_url}/query/backgroundByLocation?{requrl}&tms={tms}&iformat=tif", response) return response else: if debug: print( f"{api_url}/query/backgroundByLocation?{requrl}&tms={tms}&iformat=tif", response) res = requests.get(img_url, stream=True) image_name = img_url.split('/')[-1].lower() bg_file = normpath(join(bg_path, image_name)) with open(bg_file, "wb") as handle: for chunk in res.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks handle.write(chunk) return bg_file except AttributeError as err: return err
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # This file is part of CbM (https://github.com/ec-jrc/cbm). # Author : Guido Lemoine, Konstantinos Anastasakis # Credits : GTCAP Team # Copyright : 2021 European Commission, Joint Research Centre # License : 3-Clause BSD import os import os.path import requests from os.path import join, normpath, isfile from cbm.utils import config def parcel_by_loc(aoi, year, lon, lat, ptype=None, geom=False, wgs84=False, debug=False): api_url, api_user, api_pass = config.credentials('api') requrl = """{}/query/parcelByLocation?aoi={}&year={}&lon={}&lat={}""" if geom is True: requrl = f"{requrl}&withGeometry=True" if ptype not in [None, '']: requrl = f"{requrl}&ptype={ptype}" if wgs84 is True: requrl = f"{requrl}&wgs84={wgs84}" # print(requrl.format(api_url, aoi, year, lon, lat)) response = requests.get(requrl.format(api_url, aoi, year, lon, lat), auth=(api_user, api_pass)) if debug: print(requrl.format(api_url, aoi, year, lon, lat), response) return response.content def parcel_by_id(aoi, year, pid, ptype=None, geom=False, wgs84=False, debug=False): api_url, api_user, api_pass = config.credentials('api') requrl = """{}/query/parcelById?aoi={}&year={}&pid={}""" if geom is True: requrl = f"{requrl}&withGeometry=True" if ptype not in [None, '']: requrl = f"{requrl}&ptype={ptype}" if wgs84 is True: requrl = f"{requrl}&wgs84={wgs84}" # print(requrl.format(api_url, aoi, year, pid)) response = requests.get(requrl.format(api_url, aoi, year, pid), auth=(api_user, api_pass)) if debug: print(requrl.format(api_url, aoi, year, pid), response) return response.content def parcel_by_polygon(aoi, year, polygon, ptype=None, geom=False, wgs84=False, only_ids=True, debug=False): api_url, api_user, api_pass = config.credentials('api') requrl = """{}/query/parcelsByPolygon?aoi={}&year={}&polygon={}""" if geom is True: requrl = f"{requrl}&withGeometry=True" if only_ids is True: requrl = f"{requrl}&only_ids=True" if ptype not in [None, '']: requrl = f"{requrl}&ptype={ptype}" if wgs84 is True: requrl = f"{requrl}&wgs84={wgs84}" response = requests.get(requrl.format(api_url, aoi, year, polygon), auth=(api_user, api_pass)) if debug: print(requrl.format(api_url, aoi, year, polygon), response) return response.content def parcel_ts(aoi, year, pid, tstype='s2', ptype=None, band='', debug=False): api_url, api_user, api_pass = config.credentials('api') requrl = """{}/query/parcelTimeSeries?aoi={}&year={}&pid={}&tstype={}""" if ptype not in [None, '']: requrl = f"{requrl}&ptype={ptype}" if band not in [None, '']: requrl = f"{requrl}&band={band}" response = requests.get(requrl.format(api_url, aoi, year, pid, tstype, band), auth=(api_user, api_pass)) if debug: print(requrl.format(api_url, aoi, year, pid, tstype, band), response) return response.content def cbl(lon, lat, start_date, end_date, bands=None, lut=None, chipsize=None): api_url, api_user, api_pass = config.credentials('api') requrl = """{}/query/chipsByLocation?lon={}&lat={}&start_date={}&end_date={}""" band = '_'.join(bands) if band is not None: requrl = f"{requrl}&band={band}" if chipsize is not None: requrl = f"{requrl}&chipsize={chipsize}" if lut != '': requrl = f"{requrl}&lut={lut}" # print(requrl.format(api_url, lon, lat, start_date, end_date)) response = requests.get(requrl.format(api_url, lon, lat, start_date, end_date), auth=(api_user, api_pass)) return response def rcbl(parcel, start_date, end_date, bands, chipsize, filespath, quiet=True): """Get parcel raw chip images from RESTful API by location""" import os import os.path import pandas as pd from osgeo import osr, ogr import time start = time.time() api_url, api_user, api_pass = config.credentials('api') for band in bands: requrl = """{}/query/rawChipByLocation?lon={}&lat={}&start_date={}&end_date={}""" if band is not None: requrl = f"{requrl}&band={band}" if chipsize is not None: requrl = f"{requrl}&chipsize={chipsize}" # Create a valid geometry from the returned JSON withGeometry geom = ogr.CreateGeometryFromJson(parcel.get('geom')[0]) source = osr.SpatialReference() source.ImportFromEPSG(parcel.get('srid')[0]) # Assign this projection to the geometry geom.AssignSpatialReference(source) target = osr.SpatialReference() target.ImportFromEPSG(4326) transform = osr.CoordinateTransformation(source, target) # And get the lon, lat for its centroid, so that we can center the chips # on the parcel centroid = geom.Centroid() centroid.Transform(transform) # Use pid for next request # pid = parcel['pid'][0] # cropname = parcel['cropname'][0] # Set up the rawChip request cen_x, cen_y = str(centroid.GetX()), str(centroid.GetY()) response = requests.get(requrl.format(api_url, cen_y, cen_x, start_date, end_date, band, chipsize), auth=(api_user, api_pass)) if not quiet: print("Request url:", requrl.format( api_url, cen_y, cen_x, start_date, end_date, band, chipsize)) print("Geom:", geom) print("Source:", source, ", Target:", target) print("Centroid", centroid) print("Response:", response) # Directly create a pandas DataFrame from the json response df = pd.read_json(response.content) os.makedirs(filespath, exist_ok=True) df_file = normpath(join(filespath, f'images_list.{band}.csv')) df.to_csv(df_file, index=True, header=True) # print(f"The response table is saved to: {df_file}") # Download the GeoTIFFs that were just created in the user cache for c in df.chips: url = f"{api_url}{c}" outf = normpath(join(filespath, c.split('/')[-1])) if not isfile(outf): res = requests.get(url, stream=True) if not quiet: print(f"Downloading {c.split('/')[-1]}") with open(outf, "wb") as handle: for chunk in res.iter_content(chunk_size=512): if chunk: # filter out keep-alive new chunks handle.write(chunk) if not quiet: print( f"Images for band '{band}', for the selected dates are downloaded.") if not quiet: print("\n------Total time------") print( f"Total time required for {len(bands)} bands: {time.time() - start} seconds.") def clouds(geom): import glob import json import rasterio from osgeo import osr from rasterstats import zonal_stats # Check whether our parcel is cloud free # We should have a list of GeoTIFFs ending with .SCL.tif tiflist = glob.glob('*.SCL.tif') for t in tiflist: with rasterio.open(t) as src: affine = src.transform CRS = src.crs data = src.read(1) # Reproject the parcel geometry in the image crs imageCRS = int(str(CRS).split(':')[-1]) # Cross check with the projection of the geometry # This needs to be done for each image, because the parcel could be in # a straddle between (UTM) zones geomCRS = int(geom.GetSpatialReference().GetAuthorityCode(None)) if geomCRS != imageCRS: target = osr.SpatialReference() target.ImportFromEPSG(imageCRS) source = osr.SpatialReference() source.ImportFromEPSG(geomCRS) transform = osr.CoordinateTransformation(source, target) geom.Transform(transform) # Format as a feature collection (with only 1 feature) # and extract the histogram features = {"type": "FeatureCollection", "features": [{"type": "feature", "geometry": json.loads(geom.ExportToJson()), "properties": {"pid": pid}}]} zs = zonal_stats(features, data, affine=affine, prefix="", nodata=0, categorical=True, geojson_out=True) # This has only one record properties = zs[0].get('properties') # pid was used as a dummy key to make sure the histogram # values are in 'properties' del properties['pid'] histogram = {int(float(k)): v for k, v in properties.items()} # print(t, histogram) def get_options(): api_url, api_user, api_pass = config.credentials('api') requrl = """{}/query/options""" response = requests.get(requrl.format(api_url), auth=(api_user, api_pass)) return response.content def background(lon, lat, chipsize=512, extend=512, tms='Google', bg_path='', debug=False): # aoi='undefined', year='', pid='0000', quiet=True): """Download the background image. Examples: background(lon, lat, 512, 512, 'Google', 'temp/test.tif', True) Arguments: lon, lat, longitude and latitude in decimal degrees (float). chipsize, size of the chip in pixels (int). extend, size of the chip in meters (float). tms, tile map server Google or Bing (str). bk_file, the name of the output file (str). """ # Get the api credentials api_url, api_user, api_pass = config.credentials('api') # The url to get the background image requrl = f"lon={lon}&lat={lat}&chipsize={chipsize}&extend={extend}" # print(f"{api_url}/query/backgroundByLocation?{requrl}&tms={tms}&iformat=tif") response = requests.get( f"{api_url}/query/backgroundByLocation?{requrl}&tms={tms}&iformat=tif", auth=(api_user, api_pass)) # print(response) # Try to get the image link from the html response try: img_url = response.content.decode("utf-8") # print(type(img_url), img_url) if img_url == '{}': if debug: print("Image not found...") print( f"{api_url}/query/backgroundByLocation?{requrl}&tms={tms}&iformat=tif", response) return response else: if debug: print( f"{api_url}/query/backgroundByLocation?{requrl}&tms={tms}&iformat=tif", response) res = requests.get(img_url, stream=True) image_name = img_url.split('/')[-1].lower() bg_file = normpath(join(bg_path, image_name)) with open(bg_file, "wb") as handle: for chunk in res.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks handle.write(chunk) return bg_file except AttributeError as err: return err
import os import sys import glob import json import requests import time import ipaddress import socket import shutil import random import hashlib import base64 import re import copy from ast import literal_eval from pathlib import Path from itertools import chain import inspect import uuid from bs4 import BeautifulSoup import xml.etree.ElementTree as ET from pprint import pprint from configparser import ConfigParser import tldextract from urllib.parse import quote, unquote import urllib.parse import urllib3 from datetime import datetime from distutils.dir_util import copy_tree urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) ################# # Console colors W = '\033[1;0m' # white R = '\033[1;31m' # red G = '\033[1;32m' # green O = '\033[1;33m' # orange B = '\033[1;34m' # blue Y = '\033[1;93m' # yellow P = '\033[1;35m' # purple C = '\033[1;36m' # cyan GR = '\033[1;37m' # gray colors = [G, R, B, P, C, O, GR] info = '{0}[*]{1} '.format(B, W) ques = '{0}[?]{1} '.format(C, W) bad = '{0}[-]{1} '.format(R, W) good = '{0}[+]{1} '.format(G, W) # Define some path current_path = os.path.dirname(os.path.realpath(__file__)) ROOT_PATH = os.path.dirname(os.path.dirname(current_path)) DEAFULT_CONFIG_PATH = str(Path.home().joinpath( '.osmedeus/server.conf')) TEMPLATE_SERVER_CONFIG = os.path.join(current_path, 'template-server.conf') TEMPLATE_CLIENT_CONFIG = os.path.join(current_path, 'template-client.conf') # send request through Burp proxy for debug purpose PROXY = { 'http': 'http://127.0.0.1:8081', 'https': 'http://127.0.0.1:8081' } def print_added(text): print(f'{G} + {GR}' + str(text)) def print_missing(text): print(f'{R} + {GR}' + str(text)) def print_load(text): print(f'{GR}' + '-'*70) print(f'{GR}{' ':10}{GR}^{B}O{GR}^ {G}{text} {GR}^{B}O{GR}^') print(f'{GR}' + '-'*70) def print_block(text, tag='LOAD'): print(f'{GR}' + '-'*70) print(f'{GR}[{B}{tag}{GR}] {G}{text}') print(f'{GR}' + '-'*70) def print_banner(text): print_block(text, tag='RUN') def print_target(text): print('{2}---<---<--{1}@{2} Target: {0} {1}@{2}-->--->---'.format(text, P, G)) def print_info(text): print(info + text) def print_ques(text): print(ques + text) def print_good(text): print(good + text) def print_bad(text): print(bad + text) def print_line(): print(GR + '-' * 70) def get_perf_time(): return time.perf_counter() def print_elapsed(options): print_line() current_module = options.get('CURRENT_MODULE', '') elapsed = time.perf_counter() - options.get('start_time') print(f"{GR}[{G}ESTIMATED{GR}] {C}{current_module}{GR} module executed in {C}{elapsed:0.2f}{GR} seconds.") print_line() def print_debug(text, options=None): if not options: return if options.get('DEBUG', False) or options.get('debug', False): print(G + "#" * 20 + GR) print(text) print("#" * 20) def check_output(output): if output is None: return if os.path.isfile(output): if str(output) != '' and str(output) != "None": print('{1}--==[ Check the output: {2}{0}{1}'.format(output, G, P)) elif os.path.isdir(output) and not_empty_file(output): print('{1}--==[ Check the output: {2}{0}{1}'.format(output, G, P)) def random_sleep(min=2, max=5, fixed=None): if fixed: time.sleep(fixed) else: time.sleep(random.randint(min, max)) # checking connection on port def connection_check(target, port): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((target, int(port))) if result == 0: return True else: return False except Exception: return False ''' ### String utils ''' def loop_grep(currents, source): for current in currents: for i in range(len(current)): if current[:i+1].lower().strip() == source: return True return False def regex_strip(regex, string_in): real_regex = re.compile("{0}".format(regex)) result = re.sub(real_regex, "", string_in) return result def get_classes(class_name): return inspect.getmembers(sys.modules[class_name], inspect.isclass) def get_methods(class_object, prefix=None): methods = [attr for attr in dir(class_object) if inspect.ismethod( getattr(class_object, attr))] if not prefix: return methods return [m for m in methods if m.startswith(prefix)] def any_in(string_in, lists): return any(x in string_in for x in lists) def upper_dict_keys(options): final_options = {} for key in options.keys(): final_options[key.upper()] = options.get(key) return final_options def lower_dict_keys(options): final_options = {} for key in options.keys(): final_options[key.lower()] = options.get(key) return final_options # clean some dangerous string before pass it to eval function def safe_eval(base, inject_string, max_length=40): if len(inject_string) > max_length: return False if '.' in inject_string or ';' in inject_string: return False if '(' in inject_string or '}' in inject_string: return False if '%' in inject_string or '"' in inject_string: return False try: inject_string.encode('ascii') except: return False return base.format(inject_string) # Yield successive n-sized chunks from l def chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] # just make sure there is a path def clean_path(fpath): return os.path.normpath(fpath) def get_tld(string_in): try: result = tldextract.extract(string_in) return result.domain except: return string_in def get_uuid(): return uuid.uuid4().hex def strip_slash(string_in): if '/' in string_in: string_in = string_in.replace('/', '_') return string_in # gen checksum field def gen_checksum(string_in): if type(string_in) != str: string_in = str(string_in) checksum = hashlib.sha256("{0}".format(string_in).encode()).hexdigest() return checksum def gen_checksum_folder(folder): folders_string = ' '.join( [x for x in list_all(folder=folder, ext='*')]) return gen_checksum(folders_string) def gen_ts(): ts = int(time.time()) return ts def get_readable_time(): ts = int(time.time()) return str(datetime.utcfromtimestamp(ts).strftime('%Y.%m.%d')) + f"__{ts}" def copy_dir(dirA, dirB): if not_empty_dir(dirA): copy_tree(dirA, dirB) return dirB return False def remove_dir(directory): directory = os.path.normpath(directory) if os.path.isdir(directory): shutil.rmtree(directory) def move_dir(dirA, dirB): if not_empty_dir(dirA): shutil.move(dirA, dirB) return dirB def get_newest_folder(directory, raw=False): base = get_parent(directory) try: if not_empty_dir(base): real_directory = f'{directory}*' if raw: return sorted(glob.glob(real_directory), key=os.path.getmtime) return max(glob.glob(real_directory), key=os.path.getmtime) except: pass return False # @TODO check XXE here def is_xml(string_in, strict=True): if strict: # kind of prevent XXE if '<!ENTITY' in string_in or ' SYSTEM ' in string_in: return False try: tree = ET.fromstring(string_in) return True except: return False return False def isBase64(sb): try: if type(sb) == str: sb_bytes = bytes(sb, 'ascii') elif type(sb) == bytes: sb_bytes = sb else: raise ValueError("Argument must be string or bytes") return base64.b64encode(base64.b64decode(sb_bytes)) == sb_bytes except Exception: return False def is_json(string_in): try: json_object = json.loads(string_in) except: try: if type(literal_eval(string_in)) == dict: return True except: return False return True def isURL(string_in): if 'http' in string_in: return True return False def dict2json(dict_in): if type(dict_in) == dict: return json.dumps(dict_in) else: return dict_in # check if string is IP or not def valid_ip(string_in): try: ipaddress.ip_interface(str(string_in).strip()) return True except: return False # get IP of input string def resolve_input(string_in): if valid_ip(string_in): return string_in else: try: ip = socket.gethostbyname(get_domain(string_in)) return ip except: return False return False # just get main domain def get_domain(string_in): parsed = urllib.parse.urlparse(string_in) domain = parsed.netloc if parsed.netloc else parsed.path return domain # get workspace name from options or direct string to prevent LFI def get_workspace(options=None, workspace=None): if not workspace: raw_workspace = options.get('WORKSPACE') else: raw_workspace = workspace ws_name = os.path.basename(os.path.normpath(raw_workspace)) return ws_name def set_value(default, value): if value and value != '' and value != 'None': return value else: return default # parsing xml string def just_parse_xml(xml_string, get_dict=False): if is_xml(xml_string): root = ET.fromstring(xml_string) return root else: return False # duplicate dict without reference def just_copy(dict_in): return copy.deepcopy(dict_in) def absolute_path(raw_path): return str(Path(raw_path).expanduser()) def file_copy(src, dest): shutil.copyfile(absolute_path(src), absolute_path(dest)) def just_chain(g1, g2): return chain(g1, g2) def get_json(text): if is_json(text): if type(text) == dict: return text elif type(text) == str: try: return json.loads(text) except: return literal_eval(text) elif type(text) == dict: return text return False def get_enviroment(env_name, default_value=None): variable = str(os.getenv(env_name)) if variable == "None" and default_value is not None: return default_value return variable def get_query(url): return urllib.parse.urlparse(url).query def just_url_encode(string_in): return urllib.parse.quote(string_in) def just_url_decode(string_in): return urllib.parse.unquote(string_in) def just_b64_encode(string_in, encode_dict=False): if string_in: if encode_dict: if type(string_in) == dict: string_in = json.dumps(string_in) return base64.b64encode(string_in.encode()).decode() else: return base64.b64encode(string_in.encode()).decode() else: if type(string_in) != str: string_in = str(string_in) return base64.b64encode(string_in.encode()).decode() else: return string_in def just_b64_decode(string_in, get_dict=False): if not string_in: return '' elif isBase64(string_in): if get_dict: string_out = base64.b64decode(string_in.encode()).decode() if type(string_out) == dict: return string_out elif is_json(string_out): return json.loads(string_out) elif type(literal_eval(string_out.strip('"'))) == dict: return literal_eval(string_out.strip('"')) else: return string_out return base64.b64decode(string_in.encode()).decode() else: return string_in # just beatiful soup the xml or html def soup(content, content_type='xml'): soup = BeautifulSoup(content, content_type) return soup # join the request to def url_join(url_dict, full_url=False): raw = urllib.parse.urlparse('/') # ('scheme', 'netloc', 'path', 'params', 'query', 'fragment') if url_dict.get('scheme'): raw = raw._replace(scheme=url_dict.get('scheme')) if url_dict.get('netloc'): raw = raw._replace(netloc=url_dict.get('netloc')) if url_dict.get('path'): raw = raw._replace(path=url_dict.get('path')) if url_dict.get('query'): raw = raw._replace(query=url_dict.get('query')) if url_dict.get('fragment'): raw = raw._replace(fragment=url_dict.get('fragment')) final = raw.geturl() if full_url: return final host = url_parse(final).netloc.split(':')[0] url = final.split(url_dict.get('netloc'))[1] return host, url # parsing url def url_parse(string_in, get_dict=False): parsed = urllib.parse.urlparse(string_in) if not get_dict: return parsed else: parsed_dict = { 'scheme': parsed.scheme, 'netloc': parsed.netloc, 'path': parsed.path, 'params': parsed.params, 'query': parsed.query, 'fragment': parsed.fragment, } return parsed_dict # resolve list of commands def resolve_commands(options, commands): results = [] for raw_command in commands: command = just_copy(raw_command) for key, value in raw_command.items(): command[key] = replace_argument(options, str(value)) results.append(command) return results # resolve list of commands def resolve_command(options, raw_command): command = just_copy(raw_command) for key, value in raw_command.items(): command[key] = replace_argument(options, str(value)) return command def check_required(command): if not command.get('requirement') or command.get('requirement') == '': return True if not not_empty_file(command.get('requirement')): print_bad("Requirement not found: {0}".format(command.get('requirement'))) return False if not_empty_file(command.get('cleaned_output')): print_info("Post routine already done") return False return True # replace argument in the command def replace_argument(options, cmd): for key, value in options.items(): if key in cmd: cmd = cmd.replace('$' + str(key), str(value)) return cmd ''' ### End of string utils ''' ''' File utils ''' def get_parent(path): return os.path.dirname(path) def join_path(parent, child): parent = os.path.normpath(parent) child = os.path.normpath(child) return os.path.join(parent, child.strip('/')) def make_directory(directory, verbose=False): if directory and not os.path.exists(directory): if verbose: print_good('Make new directory: {0}'.format(directory)) os.makedirs(directory) def list_all(folder, ext='xml'): folder = os.path.normpath(folder) if os.path.isdir(folder): return glob.iglob(folder + '/**/*.{0}'.format(ext), recursive=True) return None def just_write(filename, data, is_json=False, uniq=False, verbose=False): if not filename or not data: return False filename = os.path.normpath(filename) try: if verbose: print_good("Writing {0}".format(filename)) if is_json: with open(filename, 'w+') as f: json.dump(data, f) else: with open(filename, 'w+') as f: f.write(data) return filename except: print_bad("Writing fail: {0}".format(filename)) return False def just_append(filename, data, is_json=False, uniq=False, verbose=False): if not filename or not data: return False filename = os.path.normpath(filename) try: if verbose: print_good("Writing {0}".format(filename)) if is_json: with open(filename, 'a+') as f: json.dump(data, f) else: with open(filename, 'a+') as f: f.write(data) return filename except: print_bad("Writing fail: {0}".format(filename)) return False # unique and clean up def clean_up(filename): if not filename: return False filename = os.path.normpath(filename) if os.path.isfile(filename): with open(filename, 'r') as f: data = f.readlines() real_data = list(set(data)) just_write(filename, "\n".join(real_data)) return True def unique_list(list_in): if type(list_in) != list: return False return list(set(list_in)) def just_append(filename, data, is_json=False): if not filename: return False filename = os.path.normpath(filename) try: # print_good("Writing {0}".format(filename)) if is_json: with open(filename, 'a+') as f: json.dump(data, f) else: with open(filename, 'a+') as f: f.write(data) return filename except: print_bad("Writing fail: {0}".format(filename)) return False def just_read_config(config_file, raw=False): if not not_empty_file(config_file): return False config = ConfigParser() config.read(config_file) if raw: return config sections = config.sections() options = {'CONFIG_PATH': config_file} for sec in sections: for key in config[sec]: options[key.upper()] = config.get(sec, key) # return options return options def not_empty_file(filepath): if not filepath: return False fpath = os.path.normpath(filepath) return os.path.isfile(fpath) and os.path.getsize(fpath) > 0 def not_empty_dir(dpath): if not dpath: return False dpath = os.path.normpath(dpath) if os.path.exists(dpath) and len(os.listdir(dpath)) > 0: return True return False def isFile(filepath): if os.path.isfile(filepath): return not_empty_file(filepath) else: return False def just_read(filename, get_json=False, get_list=False): if not filename: return False filename = os.path.normpath(filename) if os.path.isfile(filename): with open(filename, 'r') as f: data = f.read() if get_json and is_json(data): return json.loads(data) elif get_list: return data.splitlines() return data return False def strip_blank_line(filename, output): content = just_read(filename, get_list=True) if not content: return False output = os.path.normpath(output) with open(output, 'w+') as file: for line in content: if line.strip(): file.write(line + "\n") return output def get_ws(target): if not target: return False if os.path.isfile(target): return strip_slash(os.path.basename(target)) else: return strip_slash(target) def get_output_path(commands): output_list = [] for command in commands: if command.get('cleaned_output') and not_empty_file(command.get('cleaned_output')): output_list.append(command.get('cleaned_output')) elif command.get('output_path') and not_empty_file(command.get('output_path')): output_list.append(command.get('output_path')) return output_list def join_files(file_paths, output, uniq=True): if not file_paths and not output: return False if not uniq: with open(output, 'w') as outfile: for fname in file_paths: with open(fname) as infile: for line in infile: outfile.write(line) return output with open(output, 'w') as outfile: seen = set() for fname in file_paths: with open(fname) as infile: for line in infile: if line not in seen: outfile.write(line) seen.add(line) return output def is_done(options, final_output): if options.get('FORCED'): return False if not final_output: return False if type(final_output) == list: for report in final_output: if not not_empty_file(report): return False return True else: if not_empty_file(final_output): return True # -gobuster.txt def list_files(folder, pattern, empty_checked=True): if os.path.isfile(folder): folder = os.path.dirname(folder) folder = os.path.normpath(folder) if pattern: if pattern.startswith('**'): files = glob.iglob(folder + '/{0}'.format(pattern)) else: files = glob.iglob(folder + '/**{0}'.format(pattern)) if not empty_checked: return files return [f for f in files if not_empty_file(f)]
import os import sys import glob import json import requests import time import ipaddress import socket import shutil import random import hashlib import base64 import re import copy from ast import literal_eval from pathlib import Path from itertools import chain import inspect import uuid from bs4 import BeautifulSoup import xml.etree.ElementTree as ET from pprint import pprint from configparser import ConfigParser import tldextract from urllib.parse import quote, unquote import urllib.parse import urllib3 from datetime import datetime from distutils.dir_util import copy_tree urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) ################# # Console colors W = '\033[1;0m' # white R = '\033[1;31m' # red G = '\033[1;32m' # green O = '\033[1;33m' # orange B = '\033[1;34m' # blue Y = '\033[1;93m' # yellow P = '\033[1;35m' # purple C = '\033[1;36m' # cyan GR = '\033[1;37m' # gray colors = [G, R, B, P, C, O, GR] info = '{0}[*]{1} '.format(B, W) ques = '{0}[?]{1} '.format(C, W) bad = '{0}[-]{1} '.format(R, W) good = '{0}[+]{1} '.format(G, W) # Define some path current_path = os.path.dirname(os.path.realpath(__file__)) ROOT_PATH = os.path.dirname(os.path.dirname(current_path)) DEAFULT_CONFIG_PATH = str(Path.home().joinpath( '.osmedeus/server.conf')) TEMPLATE_SERVER_CONFIG = os.path.join(current_path, 'template-server.conf') TEMPLATE_CLIENT_CONFIG = os.path.join(current_path, 'template-client.conf') # send request through Burp proxy for debug purpose PROXY = { 'http': 'http://127.0.0.1:8081', 'https': 'http://127.0.0.1:8081' } def print_added(text): print(f'{G} + {GR}' + str(text)) def print_missing(text): print(f'{R} + {GR}' + str(text)) def print_load(text): print(f'{GR}' + '-'*70) print(f'{GR}{" ":10}{GR}^{B}O{GR}^ {G}{text} {GR}^{B}O{GR}^') print(f'{GR}' + '-'*70) def print_block(text, tag='LOAD'): print(f'{GR}' + '-'*70) print(f'{GR}[{B}{tag}{GR}] {G}{text}') print(f'{GR}' + '-'*70) def print_banner(text): print_block(text, tag='RUN') def print_target(text): print('{2}---<---<--{1}@{2} Target: {0} {1}@{2}-->--->---'.format(text, P, G)) def print_info(text): print(info + text) def print_ques(text): print(ques + text) def print_good(text): print(good + text) def print_bad(text): print(bad + text) def print_line(): print(GR + '-' * 70) def get_perf_time(): return time.perf_counter() def print_elapsed(options): print_line() current_module = options.get('CURRENT_MODULE', '') elapsed = time.perf_counter() - options.get('start_time') print(f"{GR}[{G}ESTIMATED{GR}] {C}{current_module}{GR} module executed in {C}{elapsed:0.2f}{GR} seconds.") print_line() def print_debug(text, options=None): if not options: return if options.get('DEBUG', False) or options.get('debug', False): print(G + "#" * 20 + GR) print(text) print("#" * 20) def check_output(output): if output is None: return if os.path.isfile(output): if str(output) != '' and str(output) != "None": print('{1}--==[ Check the output: {2}{0}{1}'.format(output, G, P)) elif os.path.isdir(output) and not_empty_file(output): print('{1}--==[ Check the output: {2}{0}{1}'.format(output, G, P)) def random_sleep(min=2, max=5, fixed=None): if fixed: time.sleep(fixed) else: time.sleep(random.randint(min, max)) # checking connection on port def connection_check(target, port): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((target, int(port))) if result == 0: return True else: return False except Exception: return False ''' ### String utils ''' def loop_grep(currents, source): for current in currents: for i in range(len(current)): if current[:i+1].lower().strip() == source: return True return False def regex_strip(regex, string_in): real_regex = re.compile("{0}".format(regex)) result = re.sub(real_regex, "", string_in) return result def get_classes(class_name): return inspect.getmembers(sys.modules[class_name], inspect.isclass) def get_methods(class_object, prefix=None): methods = [attr for attr in dir(class_object) if inspect.ismethod( getattr(class_object, attr))] if not prefix: return methods return [m for m in methods if m.startswith(prefix)] def any_in(string_in, lists): return any(x in string_in for x in lists) def upper_dict_keys(options): final_options = {} for key in options.keys(): final_options[key.upper()] = options.get(key) return final_options def lower_dict_keys(options): final_options = {} for key in options.keys(): final_options[key.lower()] = options.get(key) return final_options # clean some dangerous string before pass it to eval function def safe_eval(base, inject_string, max_length=40): if len(inject_string) > max_length: return False if '.' in inject_string or ';' in inject_string: return False if '(' in inject_string or '}' in inject_string: return False if '%' in inject_string or '"' in inject_string: return False try: inject_string.encode('ascii') except: return False return base.format(inject_string) # Yield successive n-sized chunks from l def chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] # just make sure there is a path def clean_path(fpath): return os.path.normpath(fpath) def get_tld(string_in): try: result = tldextract.extract(string_in) return result.domain except: return string_in def get_uuid(): return uuid.uuid4().hex def strip_slash(string_in): if '/' in string_in: string_in = string_in.replace('/', '_') return string_in # gen checksum field def gen_checksum(string_in): if type(string_in) != str: string_in = str(string_in) checksum = hashlib.sha256("{0}".format(string_in).encode()).hexdigest() return checksum def gen_checksum_folder(folder): folders_string = ' '.join( [x for x in list_all(folder=folder, ext='*')]) return gen_checksum(folders_string) def gen_ts(): ts = int(time.time()) return ts def get_readable_time(): ts = int(time.time()) return str(datetime.utcfromtimestamp(ts).strftime('%Y.%m.%d')) + f"__{ts}" def copy_dir(dirA, dirB): if not_empty_dir(dirA): copy_tree(dirA, dirB) return dirB return False def remove_dir(directory): directory = os.path.normpath(directory) if os.path.isdir(directory): shutil.rmtree(directory) def move_dir(dirA, dirB): if not_empty_dir(dirA): shutil.move(dirA, dirB) return dirB def get_newest_folder(directory, raw=False): base = get_parent(directory) try: if not_empty_dir(base): real_directory = f'{directory}*' if raw: return sorted(glob.glob(real_directory), key=os.path.getmtime) return max(glob.glob(real_directory), key=os.path.getmtime) except: pass return False # @TODO check XXE here def is_xml(string_in, strict=True): if strict: # kind of prevent XXE if '<!ENTITY' in string_in or ' SYSTEM ' in string_in: return False try: tree = ET.fromstring(string_in) return True except: return False return False def isBase64(sb): try: if type(sb) == str: sb_bytes = bytes(sb, 'ascii') elif type(sb) == bytes: sb_bytes = sb else: raise ValueError("Argument must be string or bytes") return base64.b64encode(base64.b64decode(sb_bytes)) == sb_bytes except Exception: return False def is_json(string_in): try: json_object = json.loads(string_in) except: try: if type(literal_eval(string_in)) == dict: return True except: return False return True def isURL(string_in): if 'http' in string_in: return True return False def dict2json(dict_in): if type(dict_in) == dict: return json.dumps(dict_in) else: return dict_in # check if string is IP or not def valid_ip(string_in): try: ipaddress.ip_interface(str(string_in).strip()) return True except: return False # get IP of input string def resolve_input(string_in): if valid_ip(string_in): return string_in else: try: ip = socket.gethostbyname(get_domain(string_in)) return ip except: return False return False # just get main domain def get_domain(string_in): parsed = urllib.parse.urlparse(string_in) domain = parsed.netloc if parsed.netloc else parsed.path return domain # get workspace name from options or direct string to prevent LFI def get_workspace(options=None, workspace=None): if not workspace: raw_workspace = options.get('WORKSPACE') else: raw_workspace = workspace ws_name = os.path.basename(os.path.normpath(raw_workspace)) return ws_name def set_value(default, value): if value and value != '' and value != 'None': return value else: return default # parsing xml string def just_parse_xml(xml_string, get_dict=False): if is_xml(xml_string): root = ET.fromstring(xml_string) return root else: return False # duplicate dict without reference def just_copy(dict_in): return copy.deepcopy(dict_in) def absolute_path(raw_path): return str(Path(raw_path).expanduser()) def file_copy(src, dest): shutil.copyfile(absolute_path(src), absolute_path(dest)) def just_chain(g1, g2): return chain(g1, g2) def get_json(text): if is_json(text): if type(text) == dict: return text elif type(text) == str: try: return json.loads(text) except: return literal_eval(text) elif type(text) == dict: return text return False def get_enviroment(env_name, default_value=None): variable = str(os.getenv(env_name)) if variable == "None" and default_value is not None: return default_value return variable def get_query(url): return urllib.parse.urlparse(url).query def just_url_encode(string_in): return urllib.parse.quote(string_in) def just_url_decode(string_in): return urllib.parse.unquote(string_in) def just_b64_encode(string_in, encode_dict=False): if string_in: if encode_dict: if type(string_in) == dict: string_in = json.dumps(string_in) return base64.b64encode(string_in.encode()).decode() else: return base64.b64encode(string_in.encode()).decode() else: if type(string_in) != str: string_in = str(string_in) return base64.b64encode(string_in.encode()).decode() else: return string_in def just_b64_decode(string_in, get_dict=False): if not string_in: return '' elif isBase64(string_in): if get_dict: string_out = base64.b64decode(string_in.encode()).decode() if type(string_out) == dict: return string_out elif is_json(string_out): return json.loads(string_out) elif type(literal_eval(string_out.strip('"'))) == dict: return literal_eval(string_out.strip('"')) else: return string_out return base64.b64decode(string_in.encode()).decode() else: return string_in # just beatiful soup the xml or html def soup(content, content_type='xml'): soup = BeautifulSoup(content, content_type) return soup # join the request to def url_join(url_dict, full_url=False): raw = urllib.parse.urlparse('/') # ('scheme', 'netloc', 'path', 'params', 'query', 'fragment') if url_dict.get('scheme'): raw = raw._replace(scheme=url_dict.get('scheme')) if url_dict.get('netloc'): raw = raw._replace(netloc=url_dict.get('netloc')) if url_dict.get('path'): raw = raw._replace(path=url_dict.get('path')) if url_dict.get('query'): raw = raw._replace(query=url_dict.get('query')) if url_dict.get('fragment'): raw = raw._replace(fragment=url_dict.get('fragment')) final = raw.geturl() if full_url: return final host = url_parse(final).netloc.split(':')[0] url = final.split(url_dict.get('netloc'))[1] return host, url # parsing url def url_parse(string_in, get_dict=False): parsed = urllib.parse.urlparse(string_in) if not get_dict: return parsed else: parsed_dict = { 'scheme': parsed.scheme, 'netloc': parsed.netloc, 'path': parsed.path, 'params': parsed.params, 'query': parsed.query, 'fragment': parsed.fragment, } return parsed_dict # resolve list of commands def resolve_commands(options, commands): results = [] for raw_command in commands: command = just_copy(raw_command) for key, value in raw_command.items(): command[key] = replace_argument(options, str(value)) results.append(command) return results # resolve list of commands def resolve_command(options, raw_command): command = just_copy(raw_command) for key, value in raw_command.items(): command[key] = replace_argument(options, str(value)) return command def check_required(command): if not command.get('requirement') or command.get('requirement') == '': return True if not not_empty_file(command.get('requirement')): print_bad("Requirement not found: {0}".format(command.get('requirement'))) return False if not_empty_file(command.get('cleaned_output')): print_info("Post routine already done") return False return True # replace argument in the command def replace_argument(options, cmd): for key, value in options.items(): if key in cmd: cmd = cmd.replace('$' + str(key), str(value)) return cmd ''' ### End of string utils ''' ''' File utils ''' def get_parent(path): return os.path.dirname(path) def join_path(parent, child): parent = os.path.normpath(parent) child = os.path.normpath(child) return os.path.join(parent, child.strip('/')) def make_directory(directory, verbose=False): if directory and not os.path.exists(directory): if verbose: print_good('Make new directory: {0}'.format(directory)) os.makedirs(directory) def list_all(folder, ext='xml'): folder = os.path.normpath(folder) if os.path.isdir(folder): return glob.iglob(folder + '/**/*.{0}'.format(ext), recursive=True) return None def just_write(filename, data, is_json=False, uniq=False, verbose=False): if not filename or not data: return False filename = os.path.normpath(filename) try: if verbose: print_good("Writing {0}".format(filename)) if is_json: with open(filename, 'w+') as f: json.dump(data, f) else: with open(filename, 'w+') as f: f.write(data) return filename except: print_bad("Writing fail: {0}".format(filename)) return False def just_append(filename, data, is_json=False, uniq=False, verbose=False): if not filename or not data: return False filename = os.path.normpath(filename) try: if verbose: print_good("Writing {0}".format(filename)) if is_json: with open(filename, 'a+') as f: json.dump(data, f) else: with open(filename, 'a+') as f: f.write(data) return filename except: print_bad("Writing fail: {0}".format(filename)) return False # unique and clean up def clean_up(filename): if not filename: return False filename = os.path.normpath(filename) if os.path.isfile(filename): with open(filename, 'r') as f: data = f.readlines() real_data = list(set(data)) just_write(filename, "\n".join(real_data)) return True def unique_list(list_in): if type(list_in) != list: return False return list(set(list_in)) def just_append(filename, data, is_json=False): if not filename: return False filename = os.path.normpath(filename) try: # print_good("Writing {0}".format(filename)) if is_json: with open(filename, 'a+') as f: json.dump(data, f) else: with open(filename, 'a+') as f: f.write(data) return filename except: print_bad("Writing fail: {0}".format(filename)) return False def just_read_config(config_file, raw=False): if not not_empty_file(config_file): return False config = ConfigParser() config.read(config_file) if raw: return config sections = config.sections() options = {'CONFIG_PATH': config_file} for sec in sections: for key in config[sec]: options[key.upper()] = config.get(sec, key) # return options return options def not_empty_file(filepath): if not filepath: return False fpath = os.path.normpath(filepath) return os.path.isfile(fpath) and os.path.getsize(fpath) > 0 def not_empty_dir(dpath): if not dpath: return False dpath = os.path.normpath(dpath) if os.path.exists(dpath) and len(os.listdir(dpath)) > 0: return True return False def isFile(filepath): if os.path.isfile(filepath): return not_empty_file(filepath) else: return False def just_read(filename, get_json=False, get_list=False): if not filename: return False filename = os.path.normpath(filename) if os.path.isfile(filename): with open(filename, 'r') as f: data = f.read() if get_json and is_json(data): return json.loads(data) elif get_list: return data.splitlines() return data return False def strip_blank_line(filename, output): content = just_read(filename, get_list=True) if not content: return False output = os.path.normpath(output) with open(output, 'w+') as file: for line in content: if line.strip(): file.write(line + "\n") return output def get_ws(target): if not target: return False if os.path.isfile(target): return strip_slash(os.path.basename(target)) else: return strip_slash(target) def get_output_path(commands): output_list = [] for command in commands: if command.get('cleaned_output') and not_empty_file(command.get('cleaned_output')): output_list.append(command.get('cleaned_output')) elif command.get('output_path') and not_empty_file(command.get('output_path')): output_list.append(command.get('output_path')) return output_list def join_files(file_paths, output, uniq=True): if not file_paths and not output: return False if not uniq: with open(output, 'w') as outfile: for fname in file_paths: with open(fname) as infile: for line in infile: outfile.write(line) return output with open(output, 'w') as outfile: seen = set() for fname in file_paths: with open(fname) as infile: for line in infile: if line not in seen: outfile.write(line) seen.add(line) return output def is_done(options, final_output): if options.get('FORCED'): return False if not final_output: return False if type(final_output) == list: for report in final_output: if not not_empty_file(report): return False return True else: if not_empty_file(final_output): return True # -gobuster.txt def list_files(folder, pattern, empty_checked=True): if os.path.isfile(folder): folder = os.path.dirname(folder) folder = os.path.normpath(folder) if pattern: if pattern.startswith('**'): files = glob.iglob(folder + '/{0}'.format(pattern)) else: files = glob.iglob(folder + '/**{0}'.format(pattern)) if not empty_checked: return files return [f for f in files if not_empty_file(f)]
from aiohttp import request from discord import Embed from discord.ext.commands import Cog, BucketType from discord.ext.commands import command, has_permissions, cooldown from discord.ext.commands.errors import MissingPermissions from random import choice, randint import logging class Fun(Cog): def __init__(self, bot): self.bot = bot self.log = logging.getLogger("gerfroniabot.fun") @Cog.listener() async def on_ready(self): if not self.bot.ready: self.bot.cogs_ready.ready_up("fun") self.log.info("Fun cog ready") @command(name="hallo", aliases=["hi"], brief="Grüße den Benutzer des Befehls") async def say_hello(self, ctx): """ Wird dieser Befehl aufgerufen, antwortet er mit einem von mehreren möglichen Grüßen und erwähnt den aufrufenden Benutzer. """ await ctx.send(f"{choice(("Hallo", "Hi", "Hey", "Huhu", "Servus"))} {ctx.author.mention}!") @command(name="würfel", aliases=["w"], brief="Wirf einen oder mehrere Würfel") @cooldown(3, 60.0, BucketType.user) async def roll_dice(self, ctx, num_of_dice: int, size_of_die: int): """ Dieser Befehl erwartet zwei Parameter: `num_of_dice`, die Anzahl der Würfel, die geworfen werden sollen (muss eine Ganzzahl größer 0 und kleiner 26 sein); `size_of_die`, die Anzahl der Seiten der Würfel (also die maximale Augenzahl; muss eine Ganzzahl größer 1 und kleiner 101 sein). Die Würfe werden in folgender Form ausgegeben: `n1 + n2 + n3 + ... = summe`. """ if num_of_dice < 1 or num_of_dice > 25: await ctx.send(":game_die: Ich kann nicht weniger als 1 oder mehr als 25 Würfel auf einmal werfen.") return if size_of_die < 2 or size_of_die > 100: await ctx.send(":game_die: Diese Würfelgröße wird nicht unterstützt.") return rolls = [randint(1, size_of_die) for i in range(num_of_dice)] await ctx.send(":game_die: " + " + ".join([str(r) for r in rolls]) + f" = {sum(rolls)}") @command(name="echo", aliases=["sag"], brief="Wiederhole, was geschrieben wurde") @has_permissions(manage_guild=True) async def echo_message(self, ctx, *, message): """ Löscht die Originalnachricht, mit der der Befehl aufgerufen wurde, und gibt ihren Text wieder (Echo). Dieser Befehl kann nur von Mitgliedern mit der Berechtigung "Server verwalten" verwendet werden. """ await ctx.message.delete() await ctx.send(message) @echo_message.error async def echo_message_error(self, ctx, exc): if isinstance(exc, MissingPermissions): await ctx.send("Du musst Verwaltungsrechte für den Server haben, um diesen Befehl benutzen zu können.") else: raise exc @command(name="fux", aliases=["fuchs"], brief="Zeige ein süßes Fuchsenbild") @cooldown(1, 60.0, BucketType.user) async def send_fox(self, ctx): """ Dieser Befehl antwortet mit einem zufällig ausgewählten Bild eines Fuchsen. Grüße gehen raus an die API: https://randomfox.ca/floof/. """ async with request("GET", "https://randomfox.ca/floof/") as response: if response.status == 200: data = await response.json() image_link = data["image"] embed = Embed(title=":fox_face: Zufallsfux", colour=ctx.author.colour) embed.set_image(url=image_link) await ctx.send(embed=embed) else: await ctx.send(":fox_face: Ich konnte leider keinen Zufallsfux generieren.") def setup(bot): bot.add_cog(Fun(bot))
from aiohttp import request from discord import Embed from discord.ext.commands import Cog, BucketType from discord.ext.commands import command, has_permissions, cooldown from discord.ext.commands.errors import MissingPermissions from random import choice, randint import logging class Fun(Cog): def __init__(self, bot): self.bot = bot self.log = logging.getLogger("gerfroniabot.fun") @Cog.listener() async def on_ready(self): if not self.bot.ready: self.bot.cogs_ready.ready_up("fun") self.log.info("Fun cog ready") @command(name="hallo", aliases=["hi"], brief="Grüße den Benutzer des Befehls") async def say_hello(self, ctx): """ Wird dieser Befehl aufgerufen, antwortet er mit einem von mehreren möglichen Grüßen und erwähnt den aufrufenden Benutzer. """ await ctx.send(f"{choice(('Hallo', 'Hi', 'Hey', 'Huhu', 'Servus'))} {ctx.author.mention}!") @command(name="würfel", aliases=["w"], brief="Wirf einen oder mehrere Würfel") @cooldown(3, 60.0, BucketType.user) async def roll_dice(self, ctx, num_of_dice: int, size_of_die: int): """ Dieser Befehl erwartet zwei Parameter: `num_of_dice`, die Anzahl der Würfel, die geworfen werden sollen (muss eine Ganzzahl größer 0 und kleiner 26 sein); `size_of_die`, die Anzahl der Seiten der Würfel (also die maximale Augenzahl; muss eine Ganzzahl größer 1 und kleiner 101 sein). Die Würfe werden in folgender Form ausgegeben: `n1 + n2 + n3 + ... = summe`. """ if num_of_dice < 1 or num_of_dice > 25: await ctx.send(":game_die: Ich kann nicht weniger als 1 oder mehr als 25 Würfel auf einmal werfen.") return if size_of_die < 2 or size_of_die > 100: await ctx.send(":game_die: Diese Würfelgröße wird nicht unterstützt.") return rolls = [randint(1, size_of_die) for i in range(num_of_dice)] await ctx.send(":game_die: " + " + ".join([str(r) for r in rolls]) + f" = {sum(rolls)}") @command(name="echo", aliases=["sag"], brief="Wiederhole, was geschrieben wurde") @has_permissions(manage_guild=True) async def echo_message(self, ctx, *, message): """ Löscht die Originalnachricht, mit der der Befehl aufgerufen wurde, und gibt ihren Text wieder (Echo). Dieser Befehl kann nur von Mitgliedern mit der Berechtigung "Server verwalten" verwendet werden. """ await ctx.message.delete() await ctx.send(message) @echo_message.error async def echo_message_error(self, ctx, exc): if isinstance(exc, MissingPermissions): await ctx.send("Du musst Verwaltungsrechte für den Server haben, um diesen Befehl benutzen zu können.") else: raise exc @command(name="fux", aliases=["fuchs"], brief="Zeige ein süßes Fuchsenbild") @cooldown(1, 60.0, BucketType.user) async def send_fox(self, ctx): """ Dieser Befehl antwortet mit einem zufällig ausgewählten Bild eines Fuchsen. Grüße gehen raus an die API: https://randomfox.ca/floof/. """ async with request("GET", "https://randomfox.ca/floof/") as response: if response.status == 200: data = await response.json() image_link = data["image"] embed = Embed(title=":fox_face: Zufallsfux", colour=ctx.author.colour) embed.set_image(url=image_link) await ctx.send(embed=embed) else: await ctx.send(":fox_face: Ich konnte leider keinen Zufallsfux generieren.") def setup(bot): bot.add_cog(Fun(bot))
#!/usr/bin/env python3 """ Contains the logic to create an instance of the server See also https://github.com/best-bet/thumbs-up-api """ import os from flask import Flask, g, jsonify, request from flask_cors import CORS from .api import projects, items, options from .database import connect_db def create_app(): """Create an instance of the Flask server""" app = Flask(__name__) # Grab FLASK_ENV and format it into a config name, then add that config to our app app.config.from_object(f"config.{str.capitalize(os.environ["FLASK_ENV"])}Config") # Create db connection db_session = connect_db(app) # Register blueprints app.register_blueprint(projects(db_session)) app.register_blueprint(items(db_session)) app.register_blueprint(options(db_session)) # Setup CORS headers to allow all domains CORS(app) @app.route("/") def root(): """possibly temporary route / debugging route""" return f"<div>app root</div>" # try to rate limit things the user wont need a lot of @app.after_request def inject_rate_limit_headers(response): try: requests, remaining, reset = map(int, g.view_limits) except (AttributeError, ValueError): return response else: h = response.headers h.add('X-RateLimit-Remaining', remaining) h.add('X-RateLimit-Limit', requests) h.add('X-RateLimit-Reset', reset) return response @app.errorhandler(404) def not_found(error=None): """404 - Resource not found.""" # Error response message = {"status": 404, "message": "Not Found: " + request.url} resp = jsonify(message) resp.status_code = 404 return resp return app
#!/usr/bin/env python3 """ Contains the logic to create an instance of the server See also https://github.com/best-bet/thumbs-up-api """ import os from flask import Flask, g, jsonify, request from flask_cors import CORS from .api import projects, items, options from .database import connect_db def create_app(): """Create an instance of the Flask server""" app = Flask(__name__) # Grab FLASK_ENV and format it into a config name, then add that config to our app app.config.from_object(f"config.{str.capitalize(os.environ['FLASK_ENV'])}Config") # Create db connection db_session = connect_db(app) # Register blueprints app.register_blueprint(projects(db_session)) app.register_blueprint(items(db_session)) app.register_blueprint(options(db_session)) # Setup CORS headers to allow all domains CORS(app) @app.route("/") def root(): """possibly temporary route / debugging route""" return f"<div>app root</div>" # try to rate limit things the user wont need a lot of @app.after_request def inject_rate_limit_headers(response): try: requests, remaining, reset = map(int, g.view_limits) except (AttributeError, ValueError): return response else: h = response.headers h.add('X-RateLimit-Remaining', remaining) h.add('X-RateLimit-Limit', requests) h.add('X-RateLimit-Reset', reset) return response @app.errorhandler(404) def not_found(error=None): """404 - Resource not found.""" # Error response message = {"status": 404, "message": "Not Found: " + request.url} resp = jsonify(message) resp.status_code = 404 return resp return app
#-- toolbar building blocks ------------------------------------------------- tool_nav = ( '<tool type="nav"/>' ) tool_insert = ( '<tool type="img" name="insert" tip="Insert row (Ctrl+Insert)" ' 'shortcut="ctrl,Insert" action="' '&lt;req_insert_row/&gt;' '"/>' ) tool_delete = ( '<tool type="img" name="delete" tip="Delete row (Ctrl+Delete)" ' 'shortcut="ctrl,Delete" action="' '&lt;req_delete_row/&gt;' '"/>' ) tool_formview = ( '<tool type="img" name="formview" tip="Form view (Ctrl+Enter)" ' 'shortcut="ctrl,Enter" action="' '&lt;req_formview/&gt;' '"/>' ) tool_selected = ( '<tool type="img" name="selected" tip="Item selected (Enter)" ' 'shortcut="normal,Enter" action="' '&lt;row_selected/&gt;' '"/>' ) tool_download = ( '<tool type="img" name="download" tip="Download as csv" ' 'action="' '&lt;download/&gt;' '"/>' ) #-- button row building blocks ---------------------------------------------- btn_ok = ( '<button btn_id="btn_ok" btn_label="Ok" btn_enabled="true" ' 'btn_validate="true" btn_default="true" lng="60" action="' '&lt;end_form state=&quot;completed&quot;/&gt;' '"/>' ) btn_can = ( '<button btn_id="btn_can" btn_label="Cancel" btn_enabled="true" ' 'btn_validate="false" btn_default="false" lng="60" action="' '&lt;end_form state=&quot;cancelled&quot;/&gt;' '"/>' ) btn_save = ( '<button btn_id="btn_save" btn_label="Save" btn_enabled="false" ' 'btn_validate="true" btn_default="false" lng="60" action="' '&lt;req_save/&gt;' '"/>' ) # btn_validate changed to "true" [2019-07-03] # if user presses 'Enter', check all fields are valid, even if nothing entered # if validation fails, user must press 'Esc' # reason - 'Enter' always returns 'state=completed' # if nothing entered, we want to return 'state=cancelled' # changed back to "false" [2019-11-26] # on selecting 'Add new <module>' (template=Setup_Form_Single), showing an error message # when pressing "Enter" on an empty form feels counter-intuitive # cannot remember why 'state=cancelled' was important # find an example, and try to find a solution for all scenarios btn_close = ( '<button btn_id="btn_close" btn_label="{close_text}" btn_enabled="true" ' 'btn_validate="false" btn_default="true" lng="60" action="' '&lt;case&gt;' '&lt;has_temp_data&gt;' # user changed field and pressed Enter '&lt;req_save/&gt;' '&lt;/has_temp_data&gt;' '&lt;btn_has_label btn_id=&quot;btn_close&quot; label=&quot;{close_text}&quot;&gt;' '&lt;{close_action}/&gt;' '&lt;/btn_has_label&gt;' '&lt;default&gt;' # label must be 'Cancel' - ask if ok to cancel '&lt;call method=&quot;on_req_cancel&quot;/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' ) btn_save_multi = ( '<button btn_id="btn_save" btn_label="More?" btn_enabled="false" ' 'btn_validate="true" btn_default="true" lng="60" action="' '&lt;case&gt;' '&lt;btn_has_label btn_id=&quot;btn_save&quot; label=&quot;More?&quot;&gt;' '&lt;do_navigate nav_type=&quot;last&quot;/&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_close&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;false&quot;/&gt;' '&lt;/change_button&gt;' '&lt;/btn_has_label&gt;' '&lt;default&gt;' '&lt;req_save/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' ) btn_close_multi = ( '<button btn_id="btn_close" btn_label="{close_text}" btn_enabled="true" ' 'btn_validate="false" btn_default="false" lng="60" action="' '&lt;case&gt;' '&lt;has_temp_data&gt;' # user changed field and pressed Enter '&lt;req_save/&gt;' '&lt;/has_temp_data&gt;' '&lt;btn_has_label btn_id=&quot;btn_close&quot; label=&quot;{close_text}&quot;&gt;' '&lt;{close_action}/&gt;' '&lt;/btn_has_label&gt;' '&lt;default&gt;' # label must be 'Cancel' - ask if ok to cancel '&lt;call method=&quot;on_req_cancel&quot;/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' ) #-- frame methods building blocks ------------------------------------------- on_clean = ( '<method name="on_clean" obj_name="[obj_name]" action="' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_close&quot; value=&quot;{close_text}&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_close&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;false&quot;/&gt;' '&lt;/change_button&gt;' '&lt;notify_obj_clean obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' ) on_clean_multi = ( # change 'Save' to 'More?' '<method name="on_clean" obj_name="[obj_name]" action="' '&lt;case&gt;' '&lt;obj_exists obj_name=&quot;[obj_name]&quot;&gt;' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_save&quot; value=&quot;More?&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;true&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_close&quot; value=&quot;{close_text}&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_save&quot;/&gt;' '&lt;/change_button&gt;' '&lt;/obj_exists&gt;' '&lt;default&gt;' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_close&quot; value=&quot;{close_text}&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_close&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_save&quot; value=&quot;More?&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;false&quot;/&gt;' '&lt;/change_button&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '&lt;notify_obj_clean obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' ) on_amend = ( '<method name="on_amend" obj_name="[obj_name]" action="' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_save&quot; value=&quot;Save&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;true&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_save&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_close&quot; value=&quot;Cancel&quot;/&gt;' '&lt;/change_button&gt;' '&lt;notify_obj_dirty obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' ) on_navigate = ( '<method name="on_navigate" action="' # user clicked in navigation bar '&lt;case&gt;' '&lt;data_changed&gt;' '&lt;ask title=&quot;Save changes?&quot; enter=&quot;No&quot; escape=&quot;Cancel&quot; ' 'question=&quot;Do you want to save changes to [obj_descr]?&quot;&gt;' '&lt;response ans=&quot;Yes&quot;&gt;' '&lt;req_save/&gt;' '&lt;do_navigate/&gt;' '&lt;call method=&quot;on_clean&quot;/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;No&quot;&gt;' '&lt;handle_restore/&gt;' '&lt;do_navigate/&gt;' '&lt;call method=&quot;on_clean&quot;/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;Cancel&quot;&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/data_changed&gt;' '&lt;default&gt;' '&lt;do_navigate/&gt;' '&lt;call method=&quot;on_clean&quot;/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' ) on_req_cancel = ( '<method name="on_req_cancel" action="' # press Esc or click 'Cancel' '&lt;case&gt;' '&lt;data_changed&gt;' '&lt;ask title=&quot;Cancel?&quot; enter=&quot;No&quot; escape=&quot;No&quot; ' 'question=&quot;Ok to undo changes to [obj_descr]?&quot;&gt;' '&lt;response ans=&quot;Yes&quot;&gt;' '&lt;handle_restore/&gt;' '{after_restore}' '&lt;/response&gt;' '&lt;response ans=&quot;No&quot;&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/data_changed&gt;' '{check_row_inserted}' '&lt;default&gt;' '{close_action}' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' ) on_req_close = ( '<method name="on_req_close" action="' # click [X] or press Shift+F4 '&lt;case&gt;' '&lt;data_changed&gt;' '&lt;ask title=&quot;Save changes?&quot; enter=&quot;No&quot; escape=&quot;Cancel&quot; ' 'question=&quot;Do you want to save changes to [obj_descr]?&quot;&gt;' '&lt;response ans=&quot;Yes&quot;&gt;' '&lt;req_save/&gt;' '&lt;parent_req_close/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;No&quot;&gt;' '&lt;handle_restore/&gt;' '&lt;parent_req_close/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;Cancel&quot;&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/data_changed&gt;' '&lt;default&gt;' '&lt;parent_req_close/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' ) do_save = ( '<method name="do_save" action="' # separate method so it can be over-ridden '&lt;save_obj obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' ) do_restore = ( '<method name="do_restore" action="' # separate method so it can be over-ridden '&lt;restore_obj obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' ) #---------------------------------------------------------------------------- class Form: # template for standard forms button_row = ( '<button_row>' f'{btn_ok}' f'{btn_can}' '</button_row>' ) frame_methods = ( '<frame_methods>' # this is the default, so not required # '<method name="on_req_cancel" action="' # press Esc or click 'Cancel' # '&lt;parent_req_cancel/&gt;' # '"/>' '<method name="on_req_close" action="' # click [X] or press Shift+F4 '&lt;parent_req_cancel/&gt;' # why not req_close (and so not required) ? # maybe to distinguish 'Ok' from Shift_F4 ?? '"/>' '</frame_methods>' ) #---------------------------------------------------------------------------- class Setup_Form_Single: # template for single setup e.g. params button_row = ( '<button_row>' f'{btn_save}' f'{btn_close.format(close_text='Close', close_action='parent_req_close')}' '</button_row>' ) on_req_cancel_args = { 'after_restore': '&lt;restart_frame/&gt;', 'check_row_inserted': '', 'close_action': '&lt;parent_req_cancel/&gt;' } frame_methods = ( '<frame_methods>' f'{on_clean.format(close_text='Close')}' f'{on_amend}' f'{on_req_cancel.format(**on_req_cancel_args)}' f'{on_req_close}' f'{do_save}' f'{do_restore}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Setup_Form: # template for setup-type forms # toolbar is only set up if form has a ctrl_grid - hardcoded in ht.form toolbar = ( '<toolbar>' f'{tool_nav}' f'{tool_insert}' f'{tool_delete}' '</toolbar>' ) button_row = ( '<button_row>' f'{btn_save_multi}' f'{btn_close_multi.format(close_text='Close', close_action='parent_req_close')}' '</button_row>' ) on_req_cancel_args = { 'after_restore': '&lt;restart_frame/&gt;', 'check_row_inserted': '&lt;row_inserted&gt;&lt;req_delete_row/&gt;&lt;/row_inserted&gt;', 'close_action': '&lt;parent_req_cancel/&gt;' } frame_methods = ( '<frame_methods>' '<method name="reset_buttons" action="' '&lt;case&gt;' '&lt;obj_exists obj_name=&quot;[obj_name]&quot;&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_save&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;true&quot;/&gt;' '&lt;/change_button&gt;' '&lt;/obj_exists&gt;' '&lt;default&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_close&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;false&quot;/&gt;' '&lt;/change_button&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' f'{on_clean_multi.format(close_text='Close')}' f'{on_amend}' f'{on_navigate}' f'{on_req_cancel.format(**on_req_cancel_args)}' f'{on_req_close}' f'{do_save}' f'{do_restore}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Query_Form: # template for query-type forms toolbar = ( '<toolbar>' f'{tool_nav}' f'{tool_download}' '</toolbar>' ) # changed parent_req_cancel to parent_req_close [2020-04-25] - implications? # reason - if called from bp.bpm.userTask, process waits until task 'completed' button_row = ( '<button_row>' '<button btn_id="btn_ok" btn_label="Ok" btn_enabled="true" ' 'btn_validate="true" btn_default="true" lng="60" action="' '&lt;parent_req_close/&gt;' '"/>' '</button_row>' ) frame_methods = ( '<frame_methods/>' ) #---------------------------------------------------------------------------- class Grid: # template for grids toolbar = ( '<toolbar>' f'{tool_nav}' f'{tool_insert}' f'{tool_delete}' f'{tool_download}' '</toolbar>' ) on_req_cancel_args = { 'after_restore': '', 'check_row_inserted': '&lt;row_inserted&gt;&lt;req_delete_row/&gt;&lt;/row_inserted&gt;', 'close_action': '&lt;parent_req_cancel/&gt;' } grid_methods = ( '<grid_methods>' '<method name="on_read" obj_name="[obj_name]" action="' '&lt;repos_row/&gt;' '"/>' '<method name="on_clean" obj_name="[obj_name]" action="' '&lt;notify_obj_clean obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' '<method name="on_amend" obj_name="[obj_name]" action="' '&lt;notify_obj_dirty obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' f'{on_req_close}' f'{on_req_cancel.format(**on_req_cancel_args)}' f'{do_save}' f'{do_restore}' '</grid_methods>' ) frame_methods = ( # is this needed? '<frame_methods>' f'{on_req_close}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Grid_Setup(Grid): # template for setup-type grids - added 'formview' toolbar = ( '<toolbar>' f'{tool_formview}' f'{tool_nav}' f'{tool_insert}' f'{tool_delete}' f'{tool_download}' '</toolbar>' ) #---------------------------------------------------------------------------- class Grid_Finrpt(Grid): # template for finrpt - only nav and download toolbar = ( '<toolbar>' f'{tool_nav}' f'{tool_download}' '</toolbar>' ) #---------------------------------------------------------------------------- class Grid_Lookup(Grid): # template for lookup-type grids - added 'selected' toolbar = ( '<toolbar>' f'{tool_selected}' f'{tool_formview}' f'{tool_nav}' f'{tool_insert}' f'{tool_delete}' f'{tool_download}' '</toolbar>' ) #---------------------------------------------------------------------------- class Grid_Frame: # template for a grid_frame button_row = ( '<button_row>' f'{btn_save}' f'{btn_close.format(close_text='Return', close_action='return_to_grid')}' '</button_row>' ) on_req_cancel_args = { 'after_restore': '&lt;restart_frame/&gt;', 'check_row_inserted': '&lt;row_inserted&gt;&lt;req_delete_row/&gt;&lt;/row_inserted&gt;', 'close_action': '&lt;return_to_grid/&gt;' } frame_methods = ( '<frame_methods>' f'{on_clean_multi.format(close_text='Return')}' f'{on_amend}' f'{on_navigate}' f'{on_req_cancel.format(**on_req_cancel_args)}' f'{on_req_close}' # called if grid_frame is active when user closes form f'{do_save}' f'{do_restore}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Grid_Frame_Grid_RO: # template for a grid_frame with r/o grid button_row = ( '<button_row>' f'{btn_save_multi}' f'{btn_close_multi.format(close_text='Close', close_action='move_off_grid')}' '</button_row>' ) on_req_cancel_args = { 'after_restore': '&lt;restart_frame/&gt;', 'check_row_inserted': '&lt;row_inserted&gt;&lt;req_delete_row/&gt;&lt;/row_inserted&gt;', 'close_action': '&lt;move_off_grid/&gt;' } frame_methods = ( '<frame_methods>' f'{on_clean_multi.format(close_text='Close')}' f'{on_amend}' f'{on_navigate}' f'{on_req_cancel.format(**on_req_cancel_args)}' f'{on_req_close}' # called if grid_frame is active when user closes form f'{do_save}' f'{do_restore}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Grid_Frame_With_Grid: # template for a grid_frame containing a grid - must save first button_row = ( '<button_row>' '<button btn_id="btn_close" btn_label="Return" btn_enabled="true" ' 'btn_validate="false" btn_default="true" lng="60" action="' '&lt;req_save/&gt;' '&lt;return_to_grid/&gt;' '"/>' '</button_row>' ) frame_methods = ( '<frame_methods>' f'{on_req_close}' # called if grid_frame is active when user closes form f'{do_save}' f'{do_restore}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Tree_Frame: # template for a tree_frame button_row = ( '<button_row>' f'{btn_save}' f'{btn_close.format(close_text='Return', close_action='call method=&quot;on_req_return&quot;')}' '</button_row>' ) on_req_cancel_args = { 'after_restore': '&lt;restart_frame/&gt;', 'check_row_inserted': '&lt;obj_exists obj_name=&quot;[obj_name]&quot;&gt;&lt;return_to_tree/&gt;&lt;/obj_exists&gt;', 'close_action': '&lt;delete_node/&gt;&lt;return_to_tree/&gt;' } frame_methods = ( '<frame_methods>' '<method name="on_read" obj_name="[obj_name]" action="' '&lt;case&gt;' '&lt;node_inserted&gt;' '&lt;raise_error head=&quot;Error&quot; body=&quot;Already exists&quot;/&gt;' '&lt;/node_inserted&gt;' '&lt;/case&gt;' '"/>' f'{on_clean.format(close_text='Return')}' f'{on_amend}' f'{on_req_cancel.format(**on_req_cancel_args)}' '<method name="on_req_return" action="' # click 'Return' '&lt;case&gt;' '&lt;data_changed&gt;' '&lt;ask title=&quot;Save changes?&quot; enter=&quot;No&quot; escape=&quot;Cancel&quot; ' 'question=&quot;Do you want to save changes to [obj_descr]?&quot;&gt;' '&lt;response ans=&quot;Yes&quot;&gt;' '&lt;req_save/&gt;' '&lt;return_to_tree/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;No&quot;&gt;' '&lt;handle_restore/&gt;' '&lt;return_to_tree/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;Cancel&quot;&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/data_changed&gt;' '&lt;default&gt;' '&lt;return_to_tree/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' f'{on_req_close}' f'{do_save}' f'{do_restore}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Transaction: # template for capturing transactions button_row = ( '<button_row>' '<button btn_id="btn_close" btn_label="Close" btn_enabled="true" ' 'btn_validate="true" btn_default="false" lng="60" action="' '&lt;case&gt;' '&lt;has_ctrl_grid&gt;' # if ctrl grid, restart grid '&lt;call method=&quot;on_req_cancel&quot;/&gt;' '&lt;/has_ctrl_grid&gt;' '&lt;default&gt;' '&lt;ask title=&quot;Saved&quot; enter=&quot;Yes&quot; escape=&quot;No&quot; ' 'question=&quot;Capture another?&quot;&gt;' '&lt;response ans=&quot;Yes&quot;&gt;' '&lt;init_obj obj_name=&quot;[obj_name]&quot;/&gt;' '&lt;restart_frame/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;No&quot;&gt;' '&lt;call method=&quot;on_req_close&quot;/&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' '<button btn_id="btn_post" btn_label="Post" btn_enabled="true" ' 'btn_validate="true" btn_default="true" lng="60" action="' '&lt;req_save/&gt;' '&lt;call method=&quot;do_post&quot;/&gt;' '&lt;case&gt;' "&lt;compare test=&quot;[['if', '', '[obj_name].posted', " "'=', '$True', '']]&quot;&gt;" # check 'post' successful '&lt;case&gt;' '&lt;has_ctrl_grid&gt;' # if ctrl grid, restart grid '&lt;ask title=&quot;Posted&quot; enter=&quot;Ok&quot; escape=&quot;Ok&quot; ' 'question=&quot;[tran_type] \'[tran_number]\' posted&quot;&gt;' '&lt;response ans=&quot;Ok&quot;&gt;' '&lt;restart_grid obj_name=&quot;grid_obj&quot;/&gt;' '&lt;call method=&quot;on_req_close&quot;/&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/has_ctrl_grid&gt;' '&lt;default&gt;' '&lt;ask title=&quot;Posted&quot; enter=&quot;Yes&quot; escape=&quot;No&quot; ' 'question=&quot;[tran_type] \'[tran_number]\' posted - capture another?&quot;&gt;' '&lt;response ans=&quot;Yes&quot;&gt;' '&lt;init_obj obj_name=&quot;[obj_name]&quot;/&gt;' '&lt;restart_frame/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;No&quot;&gt;' '&lt;call method=&quot;on_req_close&quot;/&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '&lt;/compare&gt;' '&lt;/case&gt;' '"/>' '</button_row>' ) frame_methods = ( '<frame_methods>' '<method name="on_start_transaction" action="' '&lt;case&gt;' '&lt;obj_exists obj_name=&quot;[obj_name]&quot;/&gt;' '&lt;no_tran_header/&gt;' '&lt;default&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_post&quot; state=&quot;false&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_close&quot; state=&quot;false&quot;/&gt;' '&lt;/change_button&gt;' '&lt;inline_form name=&quot;tran_header&quot;&gt;' '&lt;on_return&gt;' '&lt;return state=&quot;cancelled&quot;&gt;' '&lt;end_form state=&quot;cancelled&quot;/&gt;' '&lt;/return&gt;' '&lt;return state=&quot;completed&quot;&gt;' '&lt;case&gt;' '&lt;obj_exists obj_name=&quot;[obj_name]&quot;&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_post&quot; state=&quot;true&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_close&quot; state=&quot;true&quot;/&gt;' '&lt;/change_button&gt;' '&lt;restart_frame/&gt;' '&lt;/obj_exists&gt;' '&lt;default&gt;' '&lt;end_form state=&quot;cancelled&quot;/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '&lt;/return&gt;' '&lt;/on_return&gt;' '&lt;/inline_form&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' '<method name="on_req_cancel" action="' # press Esc or click 'Cancel' '&lt;parent_req_cancel/&gt;' '"/>' '<method name="on_req_close" action="' # click [X] or press Shift+F4 '&lt;parent_req_cancel/&gt;' '"/>' '<method name="do_save" action="' # separate method so it can be over-ridden '&lt;case&gt;' '&lt;no_tran_header&gt;' '&lt;save_obj obj_name=&quot;[obj_name]&quot;/&gt;' '&lt;/no_tran_header&gt;' '&lt;default&gt;' '&lt;save_obj obj_name=&quot;[obj_name]&quot; from_upd_on_save=&quot;true&quot;/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' '<method name="do_post" action="' # separate method so it can be over-ridden '&lt;post_obj obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' '</frame_methods>' ) #---------------------------------------------------------------------------- class Transaction_Header: # template for transaction header button_row = ( '<button_row>' # f'{btn_save}' '<button btn_id="btn_save" btn_label="Save" btn_enabled="false" ' 'btn_validate="true" btn_default="false" lng="60" action="' '&lt;req_save/&gt;' '&lt;case&gt;' '&lt;obj_exists obj_name=&quot;[obj_name]&quot;&gt;' '&lt;parent_req_close/&gt;' '&lt;/obj_exists&gt;' '&lt;/case&gt;' '"/>' # f'{btn_close.format(close_text='Ok', close_action='parent_req_close')}' '<button btn_id="btn_close" btn_label="Close" btn_enabled="true" ' 'btn_validate="false" btn_default="true" lng="60" action="' '&lt;case&gt;' '&lt;has_temp_data&gt;' # user changed field and pressed Enter '&lt;req_save/&gt;' '&lt;case&gt;' '&lt;obj_exists obj_name=&quot;[obj_name]&quot;&gt;' '&lt;parent_req_close/&gt;' '&lt;/obj_exists&gt;' '&lt;/case&gt;' '&lt;/has_temp_data&gt;' '&lt;btn_has_label btn_id=&quot;btn_close&quot; label=&quot;Close&quot;&gt;' '&lt;parent_req_close/&gt;' '&lt;/btn_has_label&gt;' '&lt;default&gt;' # label must be 'Cancel' - ask if ok to cancel '&lt;call method=&quot;on_req_cancel&quot;/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' '</button_row>' ) on_req_cancel_args = { 'after_restore': '&lt;restart_frame/&gt;', 'check_row_inserted': '', 'close_action': '&lt;parent_req_cancel/&gt;' } frame_methods = ( '<frame_methods>' f'{on_clean.format(close_text='Close')}' f'{on_amend}' f'{on_req_cancel.format(**on_req_cancel_args)}' f'{on_req_close}' f'{do_save}' f'{do_restore}' '</frame_methods>' )
#-- toolbar building blocks ------------------------------------------------- tool_nav = ( '<tool type="nav"/>' ) tool_insert = ( '<tool type="img" name="insert" tip="Insert row (Ctrl+Insert)" ' 'shortcut="ctrl,Insert" action="' '&lt;req_insert_row/&gt;' '"/>' ) tool_delete = ( '<tool type="img" name="delete" tip="Delete row (Ctrl+Delete)" ' 'shortcut="ctrl,Delete" action="' '&lt;req_delete_row/&gt;' '"/>' ) tool_formview = ( '<tool type="img" name="formview" tip="Form view (Ctrl+Enter)" ' 'shortcut="ctrl,Enter" action="' '&lt;req_formview/&gt;' '"/>' ) tool_selected = ( '<tool type="img" name="selected" tip="Item selected (Enter)" ' 'shortcut="normal,Enter" action="' '&lt;row_selected/&gt;' '"/>' ) tool_download = ( '<tool type="img" name="download" tip="Download as csv" ' 'action="' '&lt;download/&gt;' '"/>' ) #-- button row building blocks ---------------------------------------------- btn_ok = ( '<button btn_id="btn_ok" btn_label="Ok" btn_enabled="true" ' 'btn_validate="true" btn_default="true" lng="60" action="' '&lt;end_form state=&quot;completed&quot;/&gt;' '"/>' ) btn_can = ( '<button btn_id="btn_can" btn_label="Cancel" btn_enabled="true" ' 'btn_validate="false" btn_default="false" lng="60" action="' '&lt;end_form state=&quot;cancelled&quot;/&gt;' '"/>' ) btn_save = ( '<button btn_id="btn_save" btn_label="Save" btn_enabled="false" ' 'btn_validate="true" btn_default="false" lng="60" action="' '&lt;req_save/&gt;' '"/>' ) # btn_validate changed to "true" [2019-07-03] # if user presses 'Enter', check all fields are valid, even if nothing entered # if validation fails, user must press 'Esc' # reason - 'Enter' always returns 'state=completed' # if nothing entered, we want to return 'state=cancelled' # changed back to "false" [2019-11-26] # on selecting 'Add new <module>' (template=Setup_Form_Single), showing an error message # when pressing "Enter" on an empty form feels counter-intuitive # cannot remember why 'state=cancelled' was important # find an example, and try to find a solution for all scenarios btn_close = ( '<button btn_id="btn_close" btn_label="{close_text}" btn_enabled="true" ' 'btn_validate="false" btn_default="true" lng="60" action="' '&lt;case&gt;' '&lt;has_temp_data&gt;' # user changed field and pressed Enter '&lt;req_save/&gt;' '&lt;/has_temp_data&gt;' '&lt;btn_has_label btn_id=&quot;btn_close&quot; label=&quot;{close_text}&quot;&gt;' '&lt;{close_action}/&gt;' '&lt;/btn_has_label&gt;' '&lt;default&gt;' # label must be 'Cancel' - ask if ok to cancel '&lt;call method=&quot;on_req_cancel&quot;/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' ) btn_save_multi = ( '<button btn_id="btn_save" btn_label="More?" btn_enabled="false" ' 'btn_validate="true" btn_default="true" lng="60" action="' '&lt;case&gt;' '&lt;btn_has_label btn_id=&quot;btn_save&quot; label=&quot;More?&quot;&gt;' '&lt;do_navigate nav_type=&quot;last&quot;/&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_close&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;false&quot;/&gt;' '&lt;/change_button&gt;' '&lt;/btn_has_label&gt;' '&lt;default&gt;' '&lt;req_save/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' ) btn_close_multi = ( '<button btn_id="btn_close" btn_label="{close_text}" btn_enabled="true" ' 'btn_validate="false" btn_default="false" lng="60" action="' '&lt;case&gt;' '&lt;has_temp_data&gt;' # user changed field and pressed Enter '&lt;req_save/&gt;' '&lt;/has_temp_data&gt;' '&lt;btn_has_label btn_id=&quot;btn_close&quot; label=&quot;{close_text}&quot;&gt;' '&lt;{close_action}/&gt;' '&lt;/btn_has_label&gt;' '&lt;default&gt;' # label must be 'Cancel' - ask if ok to cancel '&lt;call method=&quot;on_req_cancel&quot;/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' ) #-- frame methods building blocks ------------------------------------------- on_clean = ( '<method name="on_clean" obj_name="[obj_name]" action="' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_close&quot; value=&quot;{close_text}&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_close&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;false&quot;/&gt;' '&lt;/change_button&gt;' '&lt;notify_obj_clean obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' ) on_clean_multi = ( # change 'Save' to 'More?' '<method name="on_clean" obj_name="[obj_name]" action="' '&lt;case&gt;' '&lt;obj_exists obj_name=&quot;[obj_name]&quot;&gt;' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_save&quot; value=&quot;More?&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;true&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_close&quot; value=&quot;{close_text}&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_save&quot;/&gt;' '&lt;/change_button&gt;' '&lt;/obj_exists&gt;' '&lt;default&gt;' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_close&quot; value=&quot;{close_text}&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_close&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_save&quot; value=&quot;More?&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;false&quot;/&gt;' '&lt;/change_button&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '&lt;notify_obj_clean obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' ) on_amend = ( '<method name="on_amend" obj_name="[obj_name]" action="' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_save&quot; value=&quot;Save&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;true&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_save&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_label btn_id=&quot;btn_close&quot; value=&quot;Cancel&quot;/&gt;' '&lt;/change_button&gt;' '&lt;notify_obj_dirty obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' ) on_navigate = ( '<method name="on_navigate" action="' # user clicked in navigation bar '&lt;case&gt;' '&lt;data_changed&gt;' '&lt;ask title=&quot;Save changes?&quot; enter=&quot;No&quot; escape=&quot;Cancel&quot; ' 'question=&quot;Do you want to save changes to [obj_descr]?&quot;&gt;' '&lt;response ans=&quot;Yes&quot;&gt;' '&lt;req_save/&gt;' '&lt;do_navigate/&gt;' '&lt;call method=&quot;on_clean&quot;/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;No&quot;&gt;' '&lt;handle_restore/&gt;' '&lt;do_navigate/&gt;' '&lt;call method=&quot;on_clean&quot;/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;Cancel&quot;&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/data_changed&gt;' '&lt;default&gt;' '&lt;do_navigate/&gt;' '&lt;call method=&quot;on_clean&quot;/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' ) on_req_cancel = ( '<method name="on_req_cancel" action="' # press Esc or click 'Cancel' '&lt;case&gt;' '&lt;data_changed&gt;' '&lt;ask title=&quot;Cancel?&quot; enter=&quot;No&quot; escape=&quot;No&quot; ' 'question=&quot;Ok to undo changes to [obj_descr]?&quot;&gt;' '&lt;response ans=&quot;Yes&quot;&gt;' '&lt;handle_restore/&gt;' '{after_restore}' '&lt;/response&gt;' '&lt;response ans=&quot;No&quot;&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/data_changed&gt;' '{check_row_inserted}' '&lt;default&gt;' '{close_action}' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' ) on_req_close = ( '<method name="on_req_close" action="' # click [X] or press Shift+F4 '&lt;case&gt;' '&lt;data_changed&gt;' '&lt;ask title=&quot;Save changes?&quot; enter=&quot;No&quot; escape=&quot;Cancel&quot; ' 'question=&quot;Do you want to save changes to [obj_descr]?&quot;&gt;' '&lt;response ans=&quot;Yes&quot;&gt;' '&lt;req_save/&gt;' '&lt;parent_req_close/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;No&quot;&gt;' '&lt;handle_restore/&gt;' '&lt;parent_req_close/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;Cancel&quot;&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/data_changed&gt;' '&lt;default&gt;' '&lt;parent_req_close/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' ) do_save = ( '<method name="do_save" action="' # separate method so it can be over-ridden '&lt;save_obj obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' ) do_restore = ( '<method name="do_restore" action="' # separate method so it can be over-ridden '&lt;restore_obj obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' ) #---------------------------------------------------------------------------- class Form: # template for standard forms button_row = ( '<button_row>' f'{btn_ok}' f'{btn_can}' '</button_row>' ) frame_methods = ( '<frame_methods>' # this is the default, so not required # '<method name="on_req_cancel" action="' # press Esc or click 'Cancel' # '&lt;parent_req_cancel/&gt;' # '"/>' '<method name="on_req_close" action="' # click [X] or press Shift+F4 '&lt;parent_req_cancel/&gt;' # why not req_close (and so not required) ? # maybe to distinguish 'Ok' from Shift_F4 ?? '"/>' '</frame_methods>' ) #---------------------------------------------------------------------------- class Setup_Form_Single: # template for single setup e.g. params button_row = ( '<button_row>' f'{btn_save}' f'{btn_close.format(close_text="Close", close_action="parent_req_close")}' '</button_row>' ) on_req_cancel_args = { 'after_restore': '&lt;restart_frame/&gt;', 'check_row_inserted': '', 'close_action': '&lt;parent_req_cancel/&gt;' } frame_methods = ( '<frame_methods>' f'{on_clean.format(close_text="Close")}' f'{on_amend}' f'{on_req_cancel.format(**on_req_cancel_args)}' f'{on_req_close}' f'{do_save}' f'{do_restore}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Setup_Form: # template for setup-type forms # toolbar is only set up if form has a ctrl_grid - hardcoded in ht.form toolbar = ( '<toolbar>' f'{tool_nav}' f'{tool_insert}' f'{tool_delete}' '</toolbar>' ) button_row = ( '<button_row>' f'{btn_save_multi}' f'{btn_close_multi.format(close_text="Close", close_action="parent_req_close")}' '</button_row>' ) on_req_cancel_args = { 'after_restore': '&lt;restart_frame/&gt;', 'check_row_inserted': '&lt;row_inserted&gt;&lt;req_delete_row/&gt;&lt;/row_inserted&gt;', 'close_action': '&lt;parent_req_cancel/&gt;' } frame_methods = ( '<frame_methods>' '<method name="reset_buttons" action="' '&lt;case&gt;' '&lt;obj_exists obj_name=&quot;[obj_name]&quot;&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_save&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;true&quot;/&gt;' '&lt;/change_button&gt;' '&lt;/obj_exists&gt;' '&lt;default&gt;' '&lt;change_button&gt;' '&lt;btn_dflt btn_id=&quot;btn_close&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_save&quot; state=&quot;false&quot;/&gt;' '&lt;/change_button&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' f'{on_clean_multi.format(close_text="Close")}' f'{on_amend}' f'{on_navigate}' f'{on_req_cancel.format(**on_req_cancel_args)}' f'{on_req_close}' f'{do_save}' f'{do_restore}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Query_Form: # template for query-type forms toolbar = ( '<toolbar>' f'{tool_nav}' f'{tool_download}' '</toolbar>' ) # changed parent_req_cancel to parent_req_close [2020-04-25] - implications? # reason - if called from bp.bpm.userTask, process waits until task 'completed' button_row = ( '<button_row>' '<button btn_id="btn_ok" btn_label="Ok" btn_enabled="true" ' 'btn_validate="true" btn_default="true" lng="60" action="' '&lt;parent_req_close/&gt;' '"/>' '</button_row>' ) frame_methods = ( '<frame_methods/>' ) #---------------------------------------------------------------------------- class Grid: # template for grids toolbar = ( '<toolbar>' f'{tool_nav}' f'{tool_insert}' f'{tool_delete}' f'{tool_download}' '</toolbar>' ) on_req_cancel_args = { 'after_restore': '', 'check_row_inserted': '&lt;row_inserted&gt;&lt;req_delete_row/&gt;&lt;/row_inserted&gt;', 'close_action': '&lt;parent_req_cancel/&gt;' } grid_methods = ( '<grid_methods>' '<method name="on_read" obj_name="[obj_name]" action="' '&lt;repos_row/&gt;' '"/>' '<method name="on_clean" obj_name="[obj_name]" action="' '&lt;notify_obj_clean obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' '<method name="on_amend" obj_name="[obj_name]" action="' '&lt;notify_obj_dirty obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' f'{on_req_close}' f'{on_req_cancel.format(**on_req_cancel_args)}' f'{do_save}' f'{do_restore}' '</grid_methods>' ) frame_methods = ( # is this needed? '<frame_methods>' f'{on_req_close}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Grid_Setup(Grid): # template for setup-type grids - added 'formview' toolbar = ( '<toolbar>' f'{tool_formview}' f'{tool_nav}' f'{tool_insert}' f'{tool_delete}' f'{tool_download}' '</toolbar>' ) #---------------------------------------------------------------------------- class Grid_Finrpt(Grid): # template for finrpt - only nav and download toolbar = ( '<toolbar>' f'{tool_nav}' f'{tool_download}' '</toolbar>' ) #---------------------------------------------------------------------------- class Grid_Lookup(Grid): # template for lookup-type grids - added 'selected' toolbar = ( '<toolbar>' f'{tool_selected}' f'{tool_formview}' f'{tool_nav}' f'{tool_insert}' f'{tool_delete}' f'{tool_download}' '</toolbar>' ) #---------------------------------------------------------------------------- class Grid_Frame: # template for a grid_frame button_row = ( '<button_row>' f'{btn_save}' f'{btn_close.format(close_text="Return", close_action="return_to_grid")}' '</button_row>' ) on_req_cancel_args = { 'after_restore': '&lt;restart_frame/&gt;', 'check_row_inserted': '&lt;row_inserted&gt;&lt;req_delete_row/&gt;&lt;/row_inserted&gt;', 'close_action': '&lt;return_to_grid/&gt;' } frame_methods = ( '<frame_methods>' f'{on_clean_multi.format(close_text="Return")}' f'{on_amend}' f'{on_navigate}' f'{on_req_cancel.format(**on_req_cancel_args)}' f'{on_req_close}' # called if grid_frame is active when user closes form f'{do_save}' f'{do_restore}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Grid_Frame_Grid_RO: # template for a grid_frame with r/o grid button_row = ( '<button_row>' f'{btn_save_multi}' f'{btn_close_multi.format(close_text="Close", close_action="move_off_grid")}' '</button_row>' ) on_req_cancel_args = { 'after_restore': '&lt;restart_frame/&gt;', 'check_row_inserted': '&lt;row_inserted&gt;&lt;req_delete_row/&gt;&lt;/row_inserted&gt;', 'close_action': '&lt;move_off_grid/&gt;' } frame_methods = ( '<frame_methods>' f'{on_clean_multi.format(close_text="Close")}' f'{on_amend}' f'{on_navigate}' f'{on_req_cancel.format(**on_req_cancel_args)}' f'{on_req_close}' # called if grid_frame is active when user closes form f'{do_save}' f'{do_restore}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Grid_Frame_With_Grid: # template for a grid_frame containing a grid - must save first button_row = ( '<button_row>' '<button btn_id="btn_close" btn_label="Return" btn_enabled="true" ' 'btn_validate="false" btn_default="true" lng="60" action="' '&lt;req_save/&gt;' '&lt;return_to_grid/&gt;' '"/>' '</button_row>' ) frame_methods = ( '<frame_methods>' f'{on_req_close}' # called if grid_frame is active when user closes form f'{do_save}' f'{do_restore}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Tree_Frame: # template for a tree_frame button_row = ( '<button_row>' f'{btn_save}' f'{btn_close.format(close_text="Return", close_action="call method=&quot;on_req_return&quot;")}' '</button_row>' ) on_req_cancel_args = { 'after_restore': '&lt;restart_frame/&gt;', 'check_row_inserted': '&lt;obj_exists obj_name=&quot;[obj_name]&quot;&gt;&lt;return_to_tree/&gt;&lt;/obj_exists&gt;', 'close_action': '&lt;delete_node/&gt;&lt;return_to_tree/&gt;' } frame_methods = ( '<frame_methods>' '<method name="on_read" obj_name="[obj_name]" action="' '&lt;case&gt;' '&lt;node_inserted&gt;' '&lt;raise_error head=&quot;Error&quot; body=&quot;Already exists&quot;/&gt;' '&lt;/node_inserted&gt;' '&lt;/case&gt;' '"/>' f'{on_clean.format(close_text="Return")}' f'{on_amend}' f'{on_req_cancel.format(**on_req_cancel_args)}' '<method name="on_req_return" action="' # click 'Return' '&lt;case&gt;' '&lt;data_changed&gt;' '&lt;ask title=&quot;Save changes?&quot; enter=&quot;No&quot; escape=&quot;Cancel&quot; ' 'question=&quot;Do you want to save changes to [obj_descr]?&quot;&gt;' '&lt;response ans=&quot;Yes&quot;&gt;' '&lt;req_save/&gt;' '&lt;return_to_tree/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;No&quot;&gt;' '&lt;handle_restore/&gt;' '&lt;return_to_tree/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;Cancel&quot;&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/data_changed&gt;' '&lt;default&gt;' '&lt;return_to_tree/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' f'{on_req_close}' f'{do_save}' f'{do_restore}' '</frame_methods>' ) #---------------------------------------------------------------------------- class Transaction: # template for capturing transactions button_row = ( '<button_row>' '<button btn_id="btn_close" btn_label="Close" btn_enabled="true" ' 'btn_validate="true" btn_default="false" lng="60" action="' '&lt;case&gt;' '&lt;has_ctrl_grid&gt;' # if ctrl grid, restart grid '&lt;call method=&quot;on_req_cancel&quot;/&gt;' '&lt;/has_ctrl_grid&gt;' '&lt;default&gt;' '&lt;ask title=&quot;Saved&quot; enter=&quot;Yes&quot; escape=&quot;No&quot; ' 'question=&quot;Capture another?&quot;&gt;' '&lt;response ans=&quot;Yes&quot;&gt;' '&lt;init_obj obj_name=&quot;[obj_name]&quot;/&gt;' '&lt;restart_frame/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;No&quot;&gt;' '&lt;call method=&quot;on_req_close&quot;/&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' '<button btn_id="btn_post" btn_label="Post" btn_enabled="true" ' 'btn_validate="true" btn_default="true" lng="60" action="' '&lt;req_save/&gt;' '&lt;call method=&quot;do_post&quot;/&gt;' '&lt;case&gt;' "&lt;compare test=&quot;[['if', '', '[obj_name].posted', " "'=', '$True', '']]&quot;&gt;" # check 'post' successful '&lt;case&gt;' '&lt;has_ctrl_grid&gt;' # if ctrl grid, restart grid '&lt;ask title=&quot;Posted&quot; enter=&quot;Ok&quot; escape=&quot;Ok&quot; ' 'question=&quot;[tran_type] \'[tran_number]\' posted&quot;&gt;' '&lt;response ans=&quot;Ok&quot;&gt;' '&lt;restart_grid obj_name=&quot;grid_obj&quot;/&gt;' '&lt;call method=&quot;on_req_close&quot;/&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/has_ctrl_grid&gt;' '&lt;default&gt;' '&lt;ask title=&quot;Posted&quot; enter=&quot;Yes&quot; escape=&quot;No&quot; ' 'question=&quot;[tran_type] \'[tran_number]\' posted - capture another?&quot;&gt;' '&lt;response ans=&quot;Yes&quot;&gt;' '&lt;init_obj obj_name=&quot;[obj_name]&quot;/&gt;' '&lt;restart_frame/&gt;' '&lt;/response&gt;' '&lt;response ans=&quot;No&quot;&gt;' '&lt;call method=&quot;on_req_close&quot;/&gt;' '&lt;/response&gt;' '&lt;/ask&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '&lt;/compare&gt;' '&lt;/case&gt;' '"/>' '</button_row>' ) frame_methods = ( '<frame_methods>' '<method name="on_start_transaction" action="' '&lt;case&gt;' '&lt;obj_exists obj_name=&quot;[obj_name]&quot;/&gt;' '&lt;no_tran_header/&gt;' '&lt;default&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_post&quot; state=&quot;false&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_close&quot; state=&quot;false&quot;/&gt;' '&lt;/change_button&gt;' '&lt;inline_form name=&quot;tran_header&quot;&gt;' '&lt;on_return&gt;' '&lt;return state=&quot;cancelled&quot;&gt;' '&lt;end_form state=&quot;cancelled&quot;/&gt;' '&lt;/return&gt;' '&lt;return state=&quot;completed&quot;&gt;' '&lt;case&gt;' '&lt;obj_exists obj_name=&quot;[obj_name]&quot;&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_post&quot; state=&quot;true&quot;/&gt;' '&lt;/change_button&gt;' '&lt;change_button&gt;' '&lt;btn_enabled btn_id=&quot;btn_close&quot; state=&quot;true&quot;/&gt;' '&lt;/change_button&gt;' '&lt;restart_frame/&gt;' '&lt;/obj_exists&gt;' '&lt;default&gt;' '&lt;end_form state=&quot;cancelled&quot;/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '&lt;/return&gt;' '&lt;/on_return&gt;' '&lt;/inline_form&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' '<method name="on_req_cancel" action="' # press Esc or click 'Cancel' '&lt;parent_req_cancel/&gt;' '"/>' '<method name="on_req_close" action="' # click [X] or press Shift+F4 '&lt;parent_req_cancel/&gt;' '"/>' '<method name="do_save" action="' # separate method so it can be over-ridden '&lt;case&gt;' '&lt;no_tran_header&gt;' '&lt;save_obj obj_name=&quot;[obj_name]&quot;/&gt;' '&lt;/no_tran_header&gt;' '&lt;default&gt;' '&lt;save_obj obj_name=&quot;[obj_name]&quot; from_upd_on_save=&quot;true&quot;/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' '<method name="do_post" action="' # separate method so it can be over-ridden '&lt;post_obj obj_name=&quot;[obj_name]&quot;/&gt;' '"/>' '</frame_methods>' ) #---------------------------------------------------------------------------- class Transaction_Header: # template for transaction header button_row = ( '<button_row>' # f'{btn_save}' '<button btn_id="btn_save" btn_label="Save" btn_enabled="false" ' 'btn_validate="true" btn_default="false" lng="60" action="' '&lt;req_save/&gt;' '&lt;case&gt;' '&lt;obj_exists obj_name=&quot;[obj_name]&quot;&gt;' '&lt;parent_req_close/&gt;' '&lt;/obj_exists&gt;' '&lt;/case&gt;' '"/>' # f'{btn_close.format(close_text="Ok", close_action="parent_req_close")}' '<button btn_id="btn_close" btn_label="Close" btn_enabled="true" ' 'btn_validate="false" btn_default="true" lng="60" action="' '&lt;case&gt;' '&lt;has_temp_data&gt;' # user changed field and pressed Enter '&lt;req_save/&gt;' '&lt;case&gt;' '&lt;obj_exists obj_name=&quot;[obj_name]&quot;&gt;' '&lt;parent_req_close/&gt;' '&lt;/obj_exists&gt;' '&lt;/case&gt;' '&lt;/has_temp_data&gt;' '&lt;btn_has_label btn_id=&quot;btn_close&quot; label=&quot;Close&quot;&gt;' '&lt;parent_req_close/&gt;' '&lt;/btn_has_label&gt;' '&lt;default&gt;' # label must be 'Cancel' - ask if ok to cancel '&lt;call method=&quot;on_req_cancel&quot;/&gt;' '&lt;/default&gt;' '&lt;/case&gt;' '"/>' '</button_row>' ) on_req_cancel_args = { 'after_restore': '&lt;restart_frame/&gt;', 'check_row_inserted': '', 'close_action': '&lt;parent_req_cancel/&gt;' } frame_methods = ( '<frame_methods>' f'{on_clean.format(close_text="Close")}' f'{on_amend}' f'{on_req_cancel.format(**on_req_cancel_args)}' f'{on_req_close}' f'{do_save}' f'{do_restore}' '</frame_methods>' )
from pathlib import Path from shutil import ExecError from typing import Any, Callable, Dict, List, Tuple, Union from experiment_server._participant_ordering import construct_participant_condition, ORDERING_BEHAVIOUR from experiment_server.utils import ExperimentServerConfigurationExcetion from loguru import logger from easydict import EasyDict as edict import json TOP_LEVEL_RESERVED_KEYS = ["step_name", "config", "repeat"] SECTIONS = ["main_configuration", "init_configuration", "final_configuration", "template_values", "order", "settings"] ALLOWED_SETTINGS = ["randomize_within_groups", "randomize_groups"] def get_sections(f: Union[str, Path]) -> Dict[str, str]: loaded_configurations = {} current_blob = None current_section = None with open(f) as fp: for line in fp.readlines(): stripped_line = line.strip() if stripped_line.startswith("//"): stripped_line = stripped_line.lstrip("//") if stripped_line in SECTIONS: # Lines starting with // are considered comments if current_blob is not None: loaded_configurations[current_section] = current_blob current_blob = "" current_section = stripped_line else: try: line = line.rstrip() if len(line) > 0: current_blob += line except TypeError: raise ExperimentServerConfigurationExcetion("The file should start with a section header.") loaded_configurations[current_section] = current_blob logger.info(f"Sections in configuration: {list(loaded_configurations.keys())}") return loaded_configurations def process_config_file(f: Union[str, Path], participant_id: int) -> List[Dict[str, Any]]: if participant_id < 1: raise ExperimentServerConfigurationExcetion(f"Participant id needs to be greater than 0, got {participant_id}") loaded_configurations = get_sections(f) if "template_values" in loaded_configurations: template_values = json.loads(loaded_configurations["template_values"]) else: template_values = {} # config = json.loads(_replace_template_values(loaded_configurations["init_configuration"], template_values)) if "order" in loaded_configurations: order = json.loads(loaded_configurations["order"]) else: order = [list(range(len(loaded_configurations)))] # TODO: expand repeat parameter if "settings" in loaded_configurations: settings = edict(json.loads(loaded_configurations["settings"])) else: settings = edict() settings.groups = settings.get("groups", ORDERING_BEHAVIOUR.as_is) settings.within_groups = settings.get("within_groups", ORDERING_BEHAVIOUR.as_is) logger.info(f"Settings used: \n {json.dumps(settings, indent=4)}") _raw_main_configuration = loaded_configurations["main_configuration"] _templated_main_configuration = _replace_template_values(_raw_main_configuration, template_values) try: main_configuration = json.loads(_templated_main_configuration) except Exception as e: logger.error("Raw main config: " + _raw_main_configuration) logger.error("Main config with template values passed: " + _templated_main_configuration) if isinstance(e, json.decoder.JSONDecodeError): raise ExperimentServerConfigurationExcetion("JSONDecodeError at position {}: `... {} ...`".format( e.pos, _templated_main_configuration[max(0, e.pos - 40):min(len(_templated_main_configuration), e.pos + 40)])) else: raise main_configuration = construct_participant_condition(main_configuration, participant_id, order=order, groups=settings.groups, within_groups=settings.within_groups) if "init_configuration" in loaded_configurations: init_configuration = json.loads(_replace_template_values(loaded_configurations["init_configuration"], template_values)) else: init_configuration = [] if "final_configuration" in loaded_configurations: final_configuration = json.loads(_replace_template_values(loaded_configurations["final_configuration"], template_values)) else: final_configuration = [] config = init_configuration + main_configuration + final_configuration for c in config: c["config"]["participant_id"] = participant_id c["config"]["step_name"] = c["step_name"] logger.info("Configuration loaded: \n" + "\n".join([f"{idx}: {json.dumps(c, indent=2)}" for idx, c in enumerate(config)])) return config def _replace_template_values(string, template_values): for k, v in template_values.items(): string = string.replace("{" + k + "}", json.dumps(v)) return string def verify_config(f: Union[str, Path], test_func:Callable[[List[Dict[str, Any]]], Tuple[bool, str]]=None) -> bool: import pandas as pd from tabulate import tabulate with logger.catch(reraise=False, message="Config verification failed"): config_steps = {} for participant_id in range(1,6): config = process_config_file(f, participant_id=participant_id) config_steps[participant_id] = {f"trial_{idx + 1}": c["step_name"] for idx, c in enumerate(config)} if test_func is not None: test_result, reason = test_func(config) assert test_result, f"test_func failed for {participant_id} with reason, {reason}" df = pd.DataFrame(config_steps) df.style.set_properties(**{'text-align': 'left'}).set_table_styles([ dict(selector='th', props=[('text-align', 'left')])]) logger.info(f"Ordering for 5 participants: \n\n{tabulate(df, headers="keys", tablefmt="fancy_grid")}\n") logger.info(f"Config file verification successful for {f}") return True return False
from pathlib import Path from shutil import ExecError from typing import Any, Callable, Dict, List, Tuple, Union from experiment_server._participant_ordering import construct_participant_condition, ORDERING_BEHAVIOUR from experiment_server.utils import ExperimentServerConfigurationExcetion from loguru import logger from easydict import EasyDict as edict import json TOP_LEVEL_RESERVED_KEYS = ["step_name", "config", "repeat"] SECTIONS = ["main_configuration", "init_configuration", "final_configuration", "template_values", "order", "settings"] ALLOWED_SETTINGS = ["randomize_within_groups", "randomize_groups"] def get_sections(f: Union[str, Path]) -> Dict[str, str]: loaded_configurations = {} current_blob = None current_section = None with open(f) as fp: for line in fp.readlines(): stripped_line = line.strip() if stripped_line.startswith("//"): stripped_line = stripped_line.lstrip("//") if stripped_line in SECTIONS: # Lines starting with // are considered comments if current_blob is not None: loaded_configurations[current_section] = current_blob current_blob = "" current_section = stripped_line else: try: line = line.rstrip() if len(line) > 0: current_blob += line except TypeError: raise ExperimentServerConfigurationExcetion("The file should start with a section header.") loaded_configurations[current_section] = current_blob logger.info(f"Sections in configuration: {list(loaded_configurations.keys())}") return loaded_configurations def process_config_file(f: Union[str, Path], participant_id: int) -> List[Dict[str, Any]]: if participant_id < 1: raise ExperimentServerConfigurationExcetion(f"Participant id needs to be greater than 0, got {participant_id}") loaded_configurations = get_sections(f) if "template_values" in loaded_configurations: template_values = json.loads(loaded_configurations["template_values"]) else: template_values = {} # config = json.loads(_replace_template_values(loaded_configurations["init_configuration"], template_values)) if "order" in loaded_configurations: order = json.loads(loaded_configurations["order"]) else: order = [list(range(len(loaded_configurations)))] # TODO: expand repeat parameter if "settings" in loaded_configurations: settings = edict(json.loads(loaded_configurations["settings"])) else: settings = edict() settings.groups = settings.get("groups", ORDERING_BEHAVIOUR.as_is) settings.within_groups = settings.get("within_groups", ORDERING_BEHAVIOUR.as_is) logger.info(f"Settings used: \n {json.dumps(settings, indent=4)}") _raw_main_configuration = loaded_configurations["main_configuration"] _templated_main_configuration = _replace_template_values(_raw_main_configuration, template_values) try: main_configuration = json.loads(_templated_main_configuration) except Exception as e: logger.error("Raw main config: " + _raw_main_configuration) logger.error("Main config with template values passed: " + _templated_main_configuration) if isinstance(e, json.decoder.JSONDecodeError): raise ExperimentServerConfigurationExcetion("JSONDecodeError at position {}: `... {} ...`".format( e.pos, _templated_main_configuration[max(0, e.pos - 40):min(len(_templated_main_configuration), e.pos + 40)])) else: raise main_configuration = construct_participant_condition(main_configuration, participant_id, order=order, groups=settings.groups, within_groups=settings.within_groups) if "init_configuration" in loaded_configurations: init_configuration = json.loads(_replace_template_values(loaded_configurations["init_configuration"], template_values)) else: init_configuration = [] if "final_configuration" in loaded_configurations: final_configuration = json.loads(_replace_template_values(loaded_configurations["final_configuration"], template_values)) else: final_configuration = [] config = init_configuration + main_configuration + final_configuration for c in config: c["config"]["participant_id"] = participant_id c["config"]["step_name"] = c["step_name"] logger.info("Configuration loaded: \n" + "\n".join([f"{idx}: {json.dumps(c, indent=2)}" for idx, c in enumerate(config)])) return config def _replace_template_values(string, template_values): for k, v in template_values.items(): string = string.replace("{" + k + "}", json.dumps(v)) return string def verify_config(f: Union[str, Path], test_func:Callable[[List[Dict[str, Any]]], Tuple[bool, str]]=None) -> bool: import pandas as pd from tabulate import tabulate with logger.catch(reraise=False, message="Config verification failed"): config_steps = {} for participant_id in range(1,6): config = process_config_file(f, participant_id=participant_id) config_steps[participant_id] = {f"trial_{idx + 1}": c["step_name"] for idx, c in enumerate(config)} if test_func is not None: test_result, reason = test_func(config) assert test_result, f"test_func failed for {participant_id} with reason, {reason}" df = pd.DataFrame(config_steps) df.style.set_properties(**{'text-align': 'left'}).set_table_styles([ dict(selector='th', props=[('text-align', 'left')])]) logger.info(f"Ordering for 5 participants: \n\n{tabulate(df, headers='keys', tablefmt='fancy_grid')}\n") logger.info(f"Config file verification successful for {f}") return True return False
"""Support for the Netatmo cameras.""" import logging import aiohttp import pyatmo import voluptuous as vol from homeassistant.components.camera import SUPPORT_STREAM, Camera from homeassistant.core import callback from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import ( ATTR_CAMERA_LIGHT_MODE, ATTR_PERSON, ATTR_PERSONS, ATTR_PSEUDO, CAMERA_LIGHT_MODES, DATA_CAMERAS, DATA_EVENTS, DATA_HANDLER, DATA_PERSONS, DOMAIN, EVENT_TYPE_LIGHT_MODE, EVENT_TYPE_OFF, EVENT_TYPE_ON, MANUFACTURER, MODELS, SERVICE_SET_CAMERA_LIGHT, SERVICE_SET_PERSON_AWAY, SERVICE_SET_PERSONS_HOME, SIGNAL_NAME, WEBHOOK_LIGHT_MODE, WEBHOOK_NACAMERA_CONNECTION, WEBHOOK_PUSH_TYPE, ) from .data_handler import CAMERA_DATA_CLASS_NAME from .netatmo_entity_base import NetatmoBase _LOGGER = logging.getLogger(__name__) DEFAULT_QUALITY = "high" async def async_setup_entry(hass, entry, async_add_entities): """Set up the Netatmo camera platform.""" if "access_camera" not in entry.data["token"]["scope"]: _LOGGER.info( "Cameras are currently not supported with this authentication method" ) data_handler = hass.data[DOMAIN][entry.entry_id][DATA_HANDLER] await data_handler.register_data_class( CAMERA_DATA_CLASS_NAME, CAMERA_DATA_CLASS_NAME, None ) data_class = data_handler.data.get(CAMERA_DATA_CLASS_NAME) if not data_class or not data_class.raw_data: raise PlatformNotReady all_cameras = [] for home in data_class.cameras.values(): for camera in home.values(): all_cameras.append(camera) entities = [ NetatmoCamera( data_handler, camera["id"], camera["type"], camera["home_id"], DEFAULT_QUALITY, ) for camera in all_cameras ] for person_id, person_data in data_handler.data[ CAMERA_DATA_CLASS_NAME ].persons.items(): hass.data[DOMAIN][DATA_PERSONS][person_id] = person_data.get(ATTR_PSEUDO) _LOGGER.debug("Adding cameras %s", entities) async_add_entities(entities, True) platform = entity_platform.async_get_current_platform() platform.async_register_entity_service( SERVICE_SET_PERSONS_HOME, {vol.Required(ATTR_PERSONS): vol.All(cv.ensure_list, [cv.string])}, "_service_set_persons_home", ) platform.async_register_entity_service( SERVICE_SET_PERSON_AWAY, {vol.Optional(ATTR_PERSON): cv.string}, "_service_set_person_away", ) platform.async_register_entity_service( SERVICE_SET_CAMERA_LIGHT, {vol.Required(ATTR_CAMERA_LIGHT_MODE): vol.In(CAMERA_LIGHT_MODES)}, "_service_set_camera_light", ) class NetatmoCamera(NetatmoBase, Camera): """Representation of a Netatmo camera.""" def __init__( self, data_handler, camera_id, camera_type, home_id, quality, ): """Set up for access to the Netatmo camera images.""" Camera.__init__(self) super().__init__(data_handler) self._data_classes.append( {"name": CAMERA_DATA_CLASS_NAME, SIGNAL_NAME: CAMERA_DATA_CLASS_NAME} ) self._id = camera_id self._home_id = home_id self._device_name = self._data.get_camera(camera_id=camera_id).get("name") self._attr_name = f"{MANUFACTURER} {self._device_name}" self._model = camera_type self._attr_unique_id = f"{self._id}-{self._model}" self._quality = quality self._vpnurl = None self._localurl = None self._status = None self._sd_status = None self._alim_status = None self._is_local = None self._light_state = None async def async_added_to_hass(self) -> None: """Entity created.""" await super().async_added_to_hass() for event_type in (EVENT_TYPE_LIGHT_MODE, EVENT_TYPE_OFF, EVENT_TYPE_ON): self._listeners.append( async_dispatcher_connect( self.hass, f"signal-{DOMAIN}-webhook-{event_type}", self.handle_event, ) ) self.hass.data[DOMAIN][DATA_CAMERAS][self._id] = self._device_name @callback def handle_event(self, event): """Handle webhook events.""" data = event["data"] if not data.get("camera_id"): return if data["home_id"] == self._home_id and data["camera_id"] == self._id: if data[WEBHOOK_PUSH_TYPE] in ["NACamera-off", "NACamera-disconnection"]: self.is_streaming = False self._status = "off" elif data[WEBHOOK_PUSH_TYPE] in [ "NACamera-on", WEBHOOK_NACAMERA_CONNECTION, ]: self.is_streaming = True self._status = "on" elif data[WEBHOOK_PUSH_TYPE] == WEBHOOK_LIGHT_MODE: self._light_state = data["sub_type"] self._attr_extra_state_attributes.update( {"light_state": self._light_state} ) self.async_write_ha_state() return async def async_camera_image(self): """Return a still image response from the camera.""" try: return await self._data.async_get_live_snapshot(camera_id=self._id) except ( aiohttp.ClientPayloadError, aiohttp.ContentTypeError, aiohttp.ServerDisconnectedError, aiohttp.ClientConnectorError, pyatmo.exceptions.ApiError, ) as err: _LOGGER.debug("Could not fetch live camera image (%s)", err) return None @property def available(self): """Return True if entity is available.""" return bool(self._alim_status == "on" or self._status == "disconnected") @property def supported_features(self): """Return supported features.""" return SUPPORT_STREAM @property def brand(self): """Return the camera brand.""" return MANUFACTURER @property def motion_detection_enabled(self): """Return the camera motion detection status.""" return bool(self._status == "on") @property def is_on(self): """Return true if on.""" return self.is_streaming async def async_turn_off(self): """Turn off camera.""" await self._data.async_set_state( home_id=self._home_id, camera_id=self._id, monitoring="off" ) async def async_turn_on(self): """Turn on camera.""" await self._data.async_set_state( home_id=self._home_id, camera_id=self._id, monitoring="on" ) async def stream_source(self): """Return the stream source.""" url = "{0}/live/files/{1}/index.m3u8" if self._localurl: return url.format(self._localurl, self._quality) return url.format(self._vpnurl, self._quality) @property def model(self): """Return the camera model.""" return MODELS[self._model] @callback def async_update_callback(self): """Update the entity's state.""" camera = self._data.get_camera(self._id) self._vpnurl, self._localurl = self._data.camera_urls(self._id) self._status = camera.get("status") self._sd_status = camera.get("sd_status") self._alim_status = camera.get("alim_status") self._is_local = camera.get("is_local") self.is_streaming = bool(self._status == "on") if self._model == "NACamera": # Smart Indoor Camera self.hass.data[DOMAIN][DATA_EVENTS][self._id] = self.process_events( self._data.events.get(self._id, {}) ) elif self._model == "NOC": # Smart Outdoor Camera self.hass.data[DOMAIN][DATA_EVENTS][self._id] = self.process_events( self._data.outdoor_events.get(self._id, {}) ) self._attr_extra_state_attributes.update( { "id": self._id, "status": self._status, "sd_status": self._sd_status, "alim_status": self._alim_status, "is_local": self._is_local, "vpn_url": self._vpnurl, "local_url": self._localurl, "light_state": self._light_state, } ) def process_events(self, events): """Add meta data to events.""" for event in events.values(): if "video_id" not in event: continue if self._is_local: event[ "media_url" ] = f"{self._localurl}/vod/{event["video_id"]}/files/{self._quality}/index.m3u8" else: event[ "media_url" ] = f"{self._vpnurl}/vod/{event["video_id"]}/files/{self._quality}/index.m3u8" return events async def _service_set_persons_home(self, **kwargs): """Service to change current home schedule.""" persons = kwargs.get(ATTR_PERSONS) person_ids = [] for person in persons: for pid, data in self._data.persons.items(): if data.get("pseudo") == person: person_ids.append(pid) await self._data.async_set_persons_home( person_ids=person_ids, home_id=self._home_id ) _LOGGER.debug("Set %s as at home", persons) async def _service_set_person_away(self, **kwargs): """Service to mark a person as away or set the home as empty.""" person = kwargs.get(ATTR_PERSON) person_id = None if person: for pid, data in self._data.persons.items(): if data.get("pseudo") == person: person_id = pid if person_id: await self._data.async_set_persons_away( person_id=person_id, home_id=self._home_id, ) _LOGGER.debug("Set %s as away", person) else: await self._data.async_set_persons_away( person_id=person_id, home_id=self._home_id, ) _LOGGER.debug("Set home as empty") async def _service_set_camera_light(self, **kwargs): """Service to set light mode.""" mode = kwargs.get(ATTR_CAMERA_LIGHT_MODE) _LOGGER.debug("Turn %s camera light for '%s'", mode, self.name) await self._data.async_set_state( home_id=self._home_id, camera_id=self._id, floodlight=mode, )
"""Support for the Netatmo cameras.""" import logging import aiohttp import pyatmo import voluptuous as vol from homeassistant.components.camera import SUPPORT_STREAM, Camera from homeassistant.core import callback from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import ( ATTR_CAMERA_LIGHT_MODE, ATTR_PERSON, ATTR_PERSONS, ATTR_PSEUDO, CAMERA_LIGHT_MODES, DATA_CAMERAS, DATA_EVENTS, DATA_HANDLER, DATA_PERSONS, DOMAIN, EVENT_TYPE_LIGHT_MODE, EVENT_TYPE_OFF, EVENT_TYPE_ON, MANUFACTURER, MODELS, SERVICE_SET_CAMERA_LIGHT, SERVICE_SET_PERSON_AWAY, SERVICE_SET_PERSONS_HOME, SIGNAL_NAME, WEBHOOK_LIGHT_MODE, WEBHOOK_NACAMERA_CONNECTION, WEBHOOK_PUSH_TYPE, ) from .data_handler import CAMERA_DATA_CLASS_NAME from .netatmo_entity_base import NetatmoBase _LOGGER = logging.getLogger(__name__) DEFAULT_QUALITY = "high" async def async_setup_entry(hass, entry, async_add_entities): """Set up the Netatmo camera platform.""" if "access_camera" not in entry.data["token"]["scope"]: _LOGGER.info( "Cameras are currently not supported with this authentication method" ) data_handler = hass.data[DOMAIN][entry.entry_id][DATA_HANDLER] await data_handler.register_data_class( CAMERA_DATA_CLASS_NAME, CAMERA_DATA_CLASS_NAME, None ) data_class = data_handler.data.get(CAMERA_DATA_CLASS_NAME) if not data_class or not data_class.raw_data: raise PlatformNotReady all_cameras = [] for home in data_class.cameras.values(): for camera in home.values(): all_cameras.append(camera) entities = [ NetatmoCamera( data_handler, camera["id"], camera["type"], camera["home_id"], DEFAULT_QUALITY, ) for camera in all_cameras ] for person_id, person_data in data_handler.data[ CAMERA_DATA_CLASS_NAME ].persons.items(): hass.data[DOMAIN][DATA_PERSONS][person_id] = person_data.get(ATTR_PSEUDO) _LOGGER.debug("Adding cameras %s", entities) async_add_entities(entities, True) platform = entity_platform.async_get_current_platform() platform.async_register_entity_service( SERVICE_SET_PERSONS_HOME, {vol.Required(ATTR_PERSONS): vol.All(cv.ensure_list, [cv.string])}, "_service_set_persons_home", ) platform.async_register_entity_service( SERVICE_SET_PERSON_AWAY, {vol.Optional(ATTR_PERSON): cv.string}, "_service_set_person_away", ) platform.async_register_entity_service( SERVICE_SET_CAMERA_LIGHT, {vol.Required(ATTR_CAMERA_LIGHT_MODE): vol.In(CAMERA_LIGHT_MODES)}, "_service_set_camera_light", ) class NetatmoCamera(NetatmoBase, Camera): """Representation of a Netatmo camera.""" def __init__( self, data_handler, camera_id, camera_type, home_id, quality, ): """Set up for access to the Netatmo camera images.""" Camera.__init__(self) super().__init__(data_handler) self._data_classes.append( {"name": CAMERA_DATA_CLASS_NAME, SIGNAL_NAME: CAMERA_DATA_CLASS_NAME} ) self._id = camera_id self._home_id = home_id self._device_name = self._data.get_camera(camera_id=camera_id).get("name") self._attr_name = f"{MANUFACTURER} {self._device_name}" self._model = camera_type self._attr_unique_id = f"{self._id}-{self._model}" self._quality = quality self._vpnurl = None self._localurl = None self._status = None self._sd_status = None self._alim_status = None self._is_local = None self._light_state = None async def async_added_to_hass(self) -> None: """Entity created.""" await super().async_added_to_hass() for event_type in (EVENT_TYPE_LIGHT_MODE, EVENT_TYPE_OFF, EVENT_TYPE_ON): self._listeners.append( async_dispatcher_connect( self.hass, f"signal-{DOMAIN}-webhook-{event_type}", self.handle_event, ) ) self.hass.data[DOMAIN][DATA_CAMERAS][self._id] = self._device_name @callback def handle_event(self, event): """Handle webhook events.""" data = event["data"] if not data.get("camera_id"): return if data["home_id"] == self._home_id and data["camera_id"] == self._id: if data[WEBHOOK_PUSH_TYPE] in ["NACamera-off", "NACamera-disconnection"]: self.is_streaming = False self._status = "off" elif data[WEBHOOK_PUSH_TYPE] in [ "NACamera-on", WEBHOOK_NACAMERA_CONNECTION, ]: self.is_streaming = True self._status = "on" elif data[WEBHOOK_PUSH_TYPE] == WEBHOOK_LIGHT_MODE: self._light_state = data["sub_type"] self._attr_extra_state_attributes.update( {"light_state": self._light_state} ) self.async_write_ha_state() return async def async_camera_image(self): """Return a still image response from the camera.""" try: return await self._data.async_get_live_snapshot(camera_id=self._id) except ( aiohttp.ClientPayloadError, aiohttp.ContentTypeError, aiohttp.ServerDisconnectedError, aiohttp.ClientConnectorError, pyatmo.exceptions.ApiError, ) as err: _LOGGER.debug("Could not fetch live camera image (%s)", err) return None @property def available(self): """Return True if entity is available.""" return bool(self._alim_status == "on" or self._status == "disconnected") @property def supported_features(self): """Return supported features.""" return SUPPORT_STREAM @property def brand(self): """Return the camera brand.""" return MANUFACTURER @property def motion_detection_enabled(self): """Return the camera motion detection status.""" return bool(self._status == "on") @property def is_on(self): """Return true if on.""" return self.is_streaming async def async_turn_off(self): """Turn off camera.""" await self._data.async_set_state( home_id=self._home_id, camera_id=self._id, monitoring="off" ) async def async_turn_on(self): """Turn on camera.""" await self._data.async_set_state( home_id=self._home_id, camera_id=self._id, monitoring="on" ) async def stream_source(self): """Return the stream source.""" url = "{0}/live/files/{1}/index.m3u8" if self._localurl: return url.format(self._localurl, self._quality) return url.format(self._vpnurl, self._quality) @property def model(self): """Return the camera model.""" return MODELS[self._model] @callback def async_update_callback(self): """Update the entity's state.""" camera = self._data.get_camera(self._id) self._vpnurl, self._localurl = self._data.camera_urls(self._id) self._status = camera.get("status") self._sd_status = camera.get("sd_status") self._alim_status = camera.get("alim_status") self._is_local = camera.get("is_local") self.is_streaming = bool(self._status == "on") if self._model == "NACamera": # Smart Indoor Camera self.hass.data[DOMAIN][DATA_EVENTS][self._id] = self.process_events( self._data.events.get(self._id, {}) ) elif self._model == "NOC": # Smart Outdoor Camera self.hass.data[DOMAIN][DATA_EVENTS][self._id] = self.process_events( self._data.outdoor_events.get(self._id, {}) ) self._attr_extra_state_attributes.update( { "id": self._id, "status": self._status, "sd_status": self._sd_status, "alim_status": self._alim_status, "is_local": self._is_local, "vpn_url": self._vpnurl, "local_url": self._localurl, "light_state": self._light_state, } ) def process_events(self, events): """Add meta data to events.""" for event in events.values(): if "video_id" not in event: continue if self._is_local: event[ "media_url" ] = f"{self._localurl}/vod/{event['video_id']}/files/{self._quality}/index.m3u8" else: event[ "media_url" ] = f"{self._vpnurl}/vod/{event['video_id']}/files/{self._quality}/index.m3u8" return events async def _service_set_persons_home(self, **kwargs): """Service to change current home schedule.""" persons = kwargs.get(ATTR_PERSONS) person_ids = [] for person in persons: for pid, data in self._data.persons.items(): if data.get("pseudo") == person: person_ids.append(pid) await self._data.async_set_persons_home( person_ids=person_ids, home_id=self._home_id ) _LOGGER.debug("Set %s as at home", persons) async def _service_set_person_away(self, **kwargs): """Service to mark a person as away or set the home as empty.""" person = kwargs.get(ATTR_PERSON) person_id = None if person: for pid, data in self._data.persons.items(): if data.get("pseudo") == person: person_id = pid if person_id: await self._data.async_set_persons_away( person_id=person_id, home_id=self._home_id, ) _LOGGER.debug("Set %s as away", person) else: await self._data.async_set_persons_away( person_id=person_id, home_id=self._home_id, ) _LOGGER.debug("Set home as empty") async def _service_set_camera_light(self, **kwargs): """Service to set light mode.""" mode = kwargs.get(ATTR_CAMERA_LIGHT_MODE) _LOGGER.debug("Turn %s camera light for '%s'", mode, self.name) await self._data.async_set_state( home_id=self._home_id, camera_id=self._id, floodlight=mode, )
import traceback from typing import Optional import aiosqlite import discord from discord.ext import commands import time import discordSuperUtils from discordSuperUtils import MusicManager from tools.database_tool import DataBaseTool import datetime from bot import MyBot from py_cord_components import ( Button, Interaction ) def parse_duration(duration: Optional[float]) -> str: return ( time.strftime("%H:%M:%S", time.gmtime(duration)) if duration != "LIVE" else duration ) # Custom Check Error class NoVoiceConncted(commands.CheckFailure): pass class BotAlreadyConncted(commands.CheckFailure): pass class InvalidIndex(commands.CheckFailure): pass # Custom Check Error class NoVoiceConncted(commands.CheckFailure): pass class BotAlreadyConncted(commands.CheckFailure): pass class InvalidIndex(commands.CheckFailure): pass # Custom Checks def ensure_voice_state(): async def predicate(ctx): if not ctx.author.voice or not ctx.author.voice.channel: raise commands.NoVoiceConncted() if ctx.voice_client: if ctx.voice_client.channel != ctx.author.voice.channel: raise commands.BotAlreadyConncted() return True return commands.check(predicate) # Format view count def parse_count(count): original_count = count count = float("{:.3g}".format(count)) magnitude = 0 matches = ["", "K", "M", "B", "T", "Qua", "Qui"] while abs(count) >= 1000: if magnitude >= 5: break magnitude += 1 count /= 1000.0 try: return "{}{}".format( "{:f}".format(count).rstrip("0").rstrip("."), matches[magnitude] ) except IndexError: return original_count # Index converter/validator def indexer(index: int): if index <= 0: raise InvalidIndex return index - 1 # Music commands class Musicsetup(commands.Cog, discordSuperUtils.CogManager.Cog, name="Musicsetup"): """ 뮤직관련 소스 """ def __init__(self, bot: MyBot): self.bot = bot self.music_stat = {} # self.client_secret = "" # spotify client_secret # self.client_id = "" # spotify client_id # Get your's from here https://developer.spotify.com/ self.MusicManager = MusicManager(self.bot, spotify_support=False) # self.MusicManager = MusicManager(bot, # client_id=self.client_id, # client_secret=self.client_secret, # spotify_support=True) # If using spotify support use this instead ^^^ self.ImageManager = discordSuperUtils.ImageManager() super().__init__() async def queue(self, ctx): try: if queue := await self.MusicManager.get_queue(ctx): if len(queue.queue) == 1: return ["대기열 비어있음"] return [ f"{x.title} Requester: {x.requester.display_name if x.requester else "Autoplay"}"for x in queue.queue ] except discordSuperUtils.QueueEmpty: return ["대기열 비어있음"] async def restart(self, ctx, interaction:Interaction): # This returns a player object # Extracting useful data from player object player = await self.MusicManager.now_playing(ctx) db = await aiosqlite.connect("db/db.sqlite") conn = await db.execute("SELECT * FROM music WHERE guild = ?", (ctx.guild.id,)) resp = await conn.fetchone() thumbnail = player.data["videoDetails"]["thumbnail"]["thumbnails"][-1]["url"] uploader = player.data["videoDetails"]["author"] url = player.url requester = player.requester.mention if player.requester else "Autoplay" embed = discord.Embed( colour=discord.Colour.random(), timestamp=datetime.datetime.now(datetime.timezone.utc), ) duration_played = round( await self.MusicManager.get_player_played_duration(ctx, player) ) embed.set_author(name=f"{player.title} upload by {uploader}",url=player.url) embed.add_field(name="노래요청자", value=requester) embed.add_field(name="현재 재생시간", value=parse_duration(duration_played)) embed.add_field(name="재생길이", value=parse_duration(player.duration)) embed.add_field(name="업로더", value=uploader) embed.add_field(name="URL", value=f"[유튜브]({url})") loop = (await self.MusicManager.get_queue(ctx)).loop if loop == discordSuperUtils.Loops.LOOP: loop_status = "🟢 단일곡 루프." elif loop == discordSuperUtils.Loops.QUEUE_LOOP: loop_status = "🟢 대기열 루프." else: loop_status = "🔴 비활성화" embed.add_field(name="루프모드", value=loop_status) shuffle = (await self.MusicManager.get_queue(ctx)).shuffle shuffle_status = "🟢 활성화" if shuffle else "🔴 비활성화" embed.add_field(name="셔플모드", value=shuffle_status) embed.set_image(url=thumbnail) embed.set_thumbnail(url=r"https://i.imgur.com/ufxvZ0j.gif") queue_resp = await self.queue(ctx) queue_res = "\n".join(queue_resp) await ( await ctx.channel.fetch_message(resp[2]) ).edit( content=f'** **\n**__대기열 목록__**:\n{queue_res}', embed=embed, ) # Play function async def play_cmd(self, ctx, query): db = await aiosqlite.connect("db/db.sqlite") conn = await db.execute("SELECT * FROM music WHERE guild = ?", (ctx.guild.id,)) resp = await conn.fetchone() async with ctx.typing(): player = await self.MusicManager.create_player(query, ctx.author) if player: if not ctx.voice_client or not ctx.voice_client.is_connected(): await self.MusicManager.join(ctx) await self.MusicManager.queue_add(players=player, ctx=ctx) if not await self.MusicManager.play(ctx): queue_resp = await self.queue(ctx) try: queue_res = "\n".join(queue_resp) except: queue_res = "대기열 없음" msg = await ctx.channel.fetch_message(resp[2]) await msg.edit( content=f'** **\n**__대기열 목록__**:\n{queue_res}', embed=msg.embeds[0], ) await ctx.send(f"`{player[0].title}`(을)를 대기열에 추가했어요.",delete_after=5) else: await ctx.send("✅",delete_after=5) else: await ctx.send("Query not found.",delete_after=5) def default_music_embed(self): em = discord.Embed( title="현재 아무 곡도 재생 중이지 않아요.", colour=discord.Colour.dark_purple() ) em.set_image(url="https://cdn.discordapp.com/attachments/921555509935480853/921555519578189834/c265877614d80026.png?width=400&height=144") em.set_footer(text="아래 버튼을 통해 조작하실 수 있어요!") em.add_field(name="루프모드",value="-",inline=False) em.add_field(name="셔플모드",value="-",inline=False) return em async def set_default(self,ctx=None): db = await aiosqlite.connect("db/db.sqlite") conn = await db.execute("SELECT * FROM music WHERE guild = ?", (ctx.guild.id,)) resp = await conn.fetchone() msg = await (self.bot.get_channel(resp[1])).fetch_message(resp[2]) await msg.edit( content="** **\n**__대기열 목록__**:\n음성채널에 접속한뒤 이 채널에 제목이나 URL을 입력해주세요.", embed=self.default_music_embed(), components=[ [ Button(emoji="⏯", custom_id="music_pr"), Button(emoji="⏹", custom_id="music_stop"), Button(emoji="⏮", custom_id="music_previous"), Button(emoji="⏭", custom_id="music_skip"), Button(emoji="🔀", custom_id="music_shuffle") ], [ Button(emoji="🔉", custom_id="music_volumedown"), Button(label="10%", emoji="🔈", disabled=True), Button(emoji="🔊", custom_id="music_volumeup"), Button(emoji="🔁", custom_id="music_queueloop"), Button(emoji="🔂", custom_id="music_oneloop") ], [ Button(label="새로고침", emoji="↩️", custom_id="music_restart"), Button(emoji="🤖", custom_id="music_auto"), Button(emoji="📥", custom_id="music_join"), Button(emoji="❎", custom_id="music_cancel", style=4) ] ] ) # DSU Error handler @discordSuperUtils.CogManager.event(discordSuperUtils.MusicManager) async def on_music_error(self, ctx, error): # sourcery skip: remove-redundant-fstring errors = { discordSuperUtils.NotPlaying: "지금 아무 음악도 재생중이지 않아요...", discordSuperUtils.NotConnected: f"저는 보이스채널에 접속해있지않아요!", discordSuperUtils.NotPaused: "음악이 멈추어져있지않아요!", discordSuperUtils.QueueEmpty: "대기열이 비어있어요!", discordSuperUtils.AlreadyConnected: "이미 보이스채널에 접속해있어요!", discordSuperUtils.SkipError: "스킵할 곡이 없어요!", discordSuperUtils.UserNotConnected: "요청자님이 음성채널에 접속해있지않아요!", discordSuperUtils.InvalidSkipIndex: "스킵될 값을 사용할수없어요!", } for error_type, response in errors.items(): if isinstance(error, error_type): await ctx.send(response,delete_after=5) break print("unexpected error") raise error # On music play event @discordSuperUtils.CogManager.event(discordSuperUtils.MusicManager) async def on_play(self, ctx, player): # This returns a player object db = await aiosqlite.connect("db/db.sqlite") conn = await db.execute("SELECT * FROM music WHERE guild = ?", (ctx.guild.id,)) resp = await conn.fetchone() # Extracting useful data from player object self.music_stat[ctx.guild.id] = "resume" thumbnail = player.data["videoDetails"]["thumbnail"]["thumbnails"][-1]["url"] uploader = player.data["videoDetails"]["author"] url = player.url requester = player.requester.mention if player.requester else "Autoplay" embed = discord.Embed( colour=discord.Colour.random(), timestamp=datetime.datetime.now(datetime.timezone.utc), ) duration_played = round( await self.MusicManager.get_player_played_duration(ctx, player) ) embed.set_author(name=f"{player.title} upload by {uploader}",url=player.url) embed.add_field(name="노래요청자", value=requester) embed.add_field(name="현재 재생시간", value=parse_duration(duration_played)) embed.add_field(name="재생길이", value=parse_duration(player.duration)) embed.add_field(name="업로더", value=uploader) embed.add_field(name="URL", value=f"[유튜브]({url})") loop = (await self.MusicManager.get_queue(ctx)).loop if loop == discordSuperUtils.Loops.LOOP: loop_status = "🟢 단일곡 루프." elif loop == discordSuperUtils.Loops.QUEUE_LOOP: loop_status = "🟢 대기열 루프." else: loop_status = "🔴 비활성화" embed.add_field(name="루프모드", value=loop_status) shuffle = (await self.MusicManager.get_queue(ctx)).shuffle shuffle_status = "🟢 활성화" if shuffle else "🔴 비활성화" embed.add_field(name="셔플모드", value=shuffle_status) embed.set_image(url=thumbnail) embed.set_thumbnail(url=r"https://i.imgur.com/ufxvZ0j.gif") queue_resp = await self.queue(ctx) queue_res = "\n".join(queue_resp) await ( await ctx.channel.fetch_message(resp[2]) ).edit( content=f'** **\n**__대기열 목록__**:\n{queue_res}', embed=embed, ) # On queue end event @discordSuperUtils.CogManager.event(discordSuperUtils.MusicManager) async def on_queue_end(self, ctx): print(f"The queue has ended in {ctx}") await self.set_default(ctx) self.music_stat[ctx.guild.id] = None # You could wait and check activity, etc... # On inactivity disconnect event @discordSuperUtils.CogManager.event(discordSuperUtils.MusicManager) async def on_inactivity_disconnect(self, ctx): print(f"I have left {ctx} due to inactivity") async def pause_resume(self, ctx): if self.music_stat[ctx.guild.id] == "pause": if await self.MusicManager.resume(ctx): self.music_stat[ctx.guild.id] = "resume" return {"type":True,"stat":"resume"} elif await self.MusicManager.pause(ctx): self.music_stat[ctx.guild.id] = "pause" return {"type":True,"stat":"pause"} async def volume(self, ctx, interaction:Interaction,type): if current_volume := await self.MusicManager.volume(ctx): if type == "down": volume = int(current_volume) - 5 if int(current_volume) == 5: return await interaction.send(content="최소 볼륨으로 더이상 낮출수없어요.",ephemeral=False,delete_after=5) else: if int(current_volume) == 100: return await interaction.send(content="100이상 올릴수없어요",ephemeral=False,delete_after=5) else: volume = int(current_volume) + 5 if await self.MusicManager.volume(ctx, volume): await interaction.edit_origin( components=[ [ Button(emoji="⏯",custom_id="music_pr"), Button(emoji="⏹", custom_id="music_stop"), Button(emoji="⏮", custom_id="music_previous"), Button(emoji="⏭", custom_id="music_skip"), Button(emoji="🔀", custom_id="music_shuffle") ], [ Button(emoji="🔉", custom_id="music_volumedown"), Button(label=f"{volume}%",emoji="🔈", custom_id="music_volumestat",disabled=True), Button(emoji="🔊", custom_id="music_volumeup"), Button(emoji="🔁", custom_id="music_queueloop"), Button(emoji="🔂", custom_id="music_oneloop") ], [ Button(label="새로고침", emoji="↩️", custom_id="music_restart"), Button(emoji="🤖", custom_id="music_auto"), Button(emoji="📥", custom_id="music_join"), Button(emoji="❎", custom_id="music_cancel", style=4) ] ] ) await interaction.send(content=f"다음 볼륨으로 설정했어요 - {current_volume}%",ephemeral=False,delete_after=5) async def loop(self, ctx,interaction:Interaction): is_loop = await self.MusicManager.loop(ctx) if is_loop is not None: await interaction.send(content=f"단일곡 루프모드를 {"🟢 활성화" if is_loop else "🔴 비활성화"}했어요.\n임베드에 반영되기까지 시간이 조금 걸려요.",ephemeral=False,delete_after=5) async def queueloop(self, ctx,interaction:Interaction): is_loop = await self.MusicManager.queueloop(ctx) if is_loop is not None: await interaction.send(content=f"대기열 루프모드를 {"🟢 활성화" if is_loop else "🔴 비활성화"}했어요.\n임베드에 반영되기까지 시간이 조금 걸려요.",ephemeral=False,delete_after=5) async def skip(self, ctx,interaction:Interaction, index: int = None): if queue := (await self.MusicManager.get_queue(ctx)): requester = (await self.MusicManager.now_playing(ctx)).requester # Checking if the song is autoplayed if requester is None: await interaction.send(content="자동재생중인 음악을 스킵했어요.",ephemeral=False,delete_after=5) await self.MusicManager.skip(ctx, index) # Checking if queue is empty and autoplay is disabled if not queue.queue and not queue.autoplay: await interaction.send(content="대기열의 마지막곡이여서 스킵할수없어요.",ephemeral=False,delete_after=5) else: skipped_player = await self.MusicManager.skip(ctx, index) await interaction.send(content="성공적으로 스킵했어요!",ephemeral=False,delete_after=5) if not skipped_player.requester: await ctx.send("Autoplaying next song.") async def previous(self, ctx,interaction:Interaction, index: int = None): if previous_player := await self.MusicManager.previous( ctx, index, no_autoplay=True ): await interaction.send(content=f"`{previous_player[0].title}`로 되돌렸어요!",ephemeral=False,delete_after=5) async def autoplay(self, ctx,interaction:Interaction): is_autoplay = await self.MusicManager.autoplay(ctx) if is_autoplay is not None: await interaction.send(content=f"대기열 자동재생 모드를 {"🟢 활성화" if is_autoplay else "🔴 비활성화"}했어요.\n임베드에 반영되기까지 시간이 조금 걸려요.",ephemeral=False,delete_after=5) async def shuffle(self, ctx,interaction:Interaction): is_shuffle = await self.MusicManager.shuffle(ctx) if is_shuffle is not None: await interaction.send(content=f"셔플모드를 {"🟢 활성화" if is_shuffle else "🔴 비활성화"}했어요.\n임베드에 반영되기까지 시간이 조금 걸려요.",ephemeral=False,delete_after=5) async def join(self, interaction:Interaction): try: user = self.bot.get_guild(interaction.guild_id).get_member(interaction.user.id) await user.voice.channel.connect() await interaction.send("정상적으로 채널에 접속했어요.",ephemeral=False,delete_after=5) except: print(str(traceback.format_exc())) await interaction.send("이미 접속된 상태에요.",ephemeral=False,delete_after=5) # async def playlists(self, interaction:Interaction): # user = interaction.user # user_playlists = await MusicManager.get_user_playlists(user) # # if not user_playlists: # await interaction.send(f"{user.mention}님의 즐겨찾기목록을 찾지 못했어요.",ephemeral=False,delete_after=5) # return # # formatted_playlists = [ # f"""**Title:** '{user_playlist.playlist.title}' # Total Songs: {len(user_playlist.playlist.songs)} # ID: `{user_playlist.id}`""" # for user_playlist in user_playlists # ] # # embeds = discordSuperUtils.generate_embeds( # formatted_playlists, # f"{user}님의 즐겨찾기목록", # f"{user.mention}님의 즐겨찾기 목록을 보여드려요.", # 15, # string_format="{}", # ) # # for embed in embeds: # embed.timestamp = datetime.datetime.utcnow() # # try: # await user.send(embed=embeds) # except discord.Forbidden: # await interaction.respond(content="개인DM이 차단되어있어 보내지 못했어요. DM차단을 해제해주세요.") # async def add(self, ctx, interaction:Interaction): # if player := await self.MusicManager.now_playing(ctx): # added_playlist = await MusicManager.add_playlist(ctx.author, player.url) # # if not added_playlist: # await interaction.respond("URL을 찾지못했어요.") # return # # await interaction.respond(f"다음 ID로 즐겨찾기를 등록했어요. `{added_playlist.id}`") topic = """ ⏯ 일시정지/이어재생 ⏹ 정지. ⏮ 이전곡. ⏭ 스킵. 🔁 대기열 루프모드. 🔂 단일곡 루프모드. 🔀 셔플모드. ❎ 대기열 초기화 및 음성채널 접속해제. 🔉 볼륨 다운. 🔊 볼륨 업. 🤖 대기열 자동재생. 📥 봇 접속. """ @commands.command(name="뮤직셋업") async def msetup(self,ctx): try: db = await aiosqlite.connect("db/db.sqlite") music_check = await DataBaseTool(db).check_db_music(ctx.guild) premium_cur = await db.execute("SELECT * FROM premium WHERE guild = ?",(ctx.guild.id,)) premium_resp = await premium_cur.fetchone() if premium_resp == None: em = discord.Embed(title="사용불가",colour=discord.Colour.random()) em.add_field(name="사유", value="프리미엄을 사용해주셔야해요!") if not music_check: return await ctx.reply("❎ 이미 설정되어있는것같아요!") else: channel = await ctx.guild.create_text_channel(name="music setup", topic=self.topic) await channel.send("https://cdn.discordapp.com/icons/856829534926143538/4df4eac52287d066ded88084d1b728eb.webp?size=160") msg = await channel.send(content="** **\n**__대기열 목록__**:\n음성채널에 접속한뒤 이 채널에 제목이나 URL을 입력해주세요.", embed=self.default_music_embed(), components=[ [ Button(emoji="⏯", custom_id="music_pr"), Button(emoji="⏹", custom_id="music_stop"), Button(emoji="⏮", custom_id="music_previous"), Button(emoji="⏭", custom_id="music_skip"), Button(emoji="🔀", custom_id="music_shuffle") ], [ Button(emoji="🔉", custom_id="music_volumedown"), Button(label="10%", emoji="🔈", disabled=True), Button(emoji="🔊", custom_id="music_volumeup"), Button(emoji="🔁", custom_id="music_queueloop"), Button(emoji="🔂", custom_id="music_oneloop") ], [ Button(label="새로고침", emoji="↩️", custom_id="music_restart"), Button(emoji="🤖", custom_id="music_auto"), Button(emoji="📥", custom_id="music_join"), Button(emoji="❎", custom_id="music_cancel", style=4) ] ] ) db = await aiosqlite.connect("db/db.sqlite") await DataBaseTool(db).add_music_data(ctx.guild,channel,msg) await ctx.send( f"성공적으로 뮤직채널({channel.mention})을 만들었어요!\n해당 채널의 이름과 위치는 마음껏 커스터마이징이 가능하답니다!") except: print(traceback.format_exc()) @commands.Cog.listener("on_message") async def music_message(self,message): if message.author.bot: return ctx = await self.bot.get_context(message) db = await aiosqlite.connect("db/db.sqlite") conn = await db.execute("SELECT * FROM music WHERE guild = ?",(message.guild.id,)) resp = await conn.fetchone() if not resp == None: if message.channel.id == resp[1]: await message.delete() await Musicsetup.play_cmd(self, ctx, message.content) @commands.Cog.listener(name="on_button_click") async def music_button_control(self,interaction:Interaction): ctx = await self.bot.get_context(interaction.message) db = await aiosqlite.connect("db/db.sqlite") conn = await db.execute("SELECT * FROM music WHERE guild = ?", (interaction.guild_id,)) resp = await conn.fetchone() if interaction.custom_id.startswith("music_") and interaction.message.id == resp[2]: if not interaction.user.voice or not interaction.user.voice.channel: return await interaction.send("음성채널에 접속해있지않아요!",ephemeral=False,delete_after=5) if interaction.custom_id == "music_cancel": if await self.MusicManager.leave(ctx): await self.set_default(ctx) await interaction.send(content="대기열을 초기화하고 접속을 해제했어요!",ephemeral=False,delete_after=5) elif interaction.custom_id == "music_pr": resp = await self.pause_resume(ctx) if resp['type']: if resp['stat'] == "resume": await interaction.send(content="이어서 재생할게요!",ephemeral=False,delete_after=5) else: await interaction.send(content="음악을 일시정지했어요.",ephemeral=False,delete_after=5) elif interaction.custom_id == "music_stop": await self.MusicManager.cleanup(voice_client=None, guild=ctx.guild) ctx.voice_client.stop() await interaction.send("음악을 정지했어요.",ephemeral=False,delete_after=5) elif interaction.custom_id == "music_skip": await self.skip(ctx,interaction) elif interaction.custom_id == "music_shuffle": await self.shuffle(ctx,interaction) elif interaction.custom_id == "music_volumedown": await self.volume(ctx,interaction,type="down") elif interaction.custom_id == "music_volumeup": await self.volume(ctx,interaction,type="up") elif interaction.custom_id == "music_queueloop": await self.queueloop(ctx,interaction) elif interaction.custom_id == "music_oneloop": await self.loop(ctx,interaction) elif interaction.custom_id == "music_previous": await self.previous(ctx,interaction) elif interaction.custom_id == "music_auto": await self.autoplay(ctx,interaction) elif interaction.custom_id == "music_join": await self.join(interaction) elif interaction.custom_id == "music_restart": await self.restart(ctx, interaction) def setup(bot): bot.add_cog(Musicsetup(bot))
import traceback from typing import Optional import aiosqlite import discord from discord.ext import commands import time import discordSuperUtils from discordSuperUtils import MusicManager from tools.database_tool import DataBaseTool import datetime from bot import MyBot from py_cord_components import ( Button, Interaction ) def parse_duration(duration: Optional[float]) -> str: return ( time.strftime("%H:%M:%S", time.gmtime(duration)) if duration != "LIVE" else duration ) # Custom Check Error class NoVoiceConncted(commands.CheckFailure): pass class BotAlreadyConncted(commands.CheckFailure): pass class InvalidIndex(commands.CheckFailure): pass # Custom Check Error class NoVoiceConncted(commands.CheckFailure): pass class BotAlreadyConncted(commands.CheckFailure): pass class InvalidIndex(commands.CheckFailure): pass # Custom Checks def ensure_voice_state(): async def predicate(ctx): if not ctx.author.voice or not ctx.author.voice.channel: raise commands.NoVoiceConncted() if ctx.voice_client: if ctx.voice_client.channel != ctx.author.voice.channel: raise commands.BotAlreadyConncted() return True return commands.check(predicate) # Format view count def parse_count(count): original_count = count count = float("{:.3g}".format(count)) magnitude = 0 matches = ["", "K", "M", "B", "T", "Qua", "Qui"] while abs(count) >= 1000: if magnitude >= 5: break magnitude += 1 count /= 1000.0 try: return "{}{}".format( "{:f}".format(count).rstrip("0").rstrip("."), matches[magnitude] ) except IndexError: return original_count # Index converter/validator def indexer(index: int): if index <= 0: raise InvalidIndex return index - 1 # Music commands class Musicsetup(commands.Cog, discordSuperUtils.CogManager.Cog, name="Musicsetup"): """ 뮤직관련 소스 """ def __init__(self, bot: MyBot): self.bot = bot self.music_stat = {} # self.client_secret = "" # spotify client_secret # self.client_id = "" # spotify client_id # Get your's from here https://developer.spotify.com/ self.MusicManager = MusicManager(self.bot, spotify_support=False) # self.MusicManager = MusicManager(bot, # client_id=self.client_id, # client_secret=self.client_secret, # spotify_support=True) # If using spotify support use this instead ^^^ self.ImageManager = discordSuperUtils.ImageManager() super().__init__() async def queue(self, ctx): try: if queue := await self.MusicManager.get_queue(ctx): if len(queue.queue) == 1: return ["대기열 비어있음"] return [ f"{x.title} Requester: {x.requester.display_name if x.requester else 'Autoplay'}"for x in queue.queue ] except discordSuperUtils.QueueEmpty: return ["대기열 비어있음"] async def restart(self, ctx, interaction:Interaction): # This returns a player object # Extracting useful data from player object player = await self.MusicManager.now_playing(ctx) db = await aiosqlite.connect("db/db.sqlite") conn = await db.execute("SELECT * FROM music WHERE guild = ?", (ctx.guild.id,)) resp = await conn.fetchone() thumbnail = player.data["videoDetails"]["thumbnail"]["thumbnails"][-1]["url"] uploader = player.data["videoDetails"]["author"] url = player.url requester = player.requester.mention if player.requester else "Autoplay" embed = discord.Embed( colour=discord.Colour.random(), timestamp=datetime.datetime.now(datetime.timezone.utc), ) duration_played = round( await self.MusicManager.get_player_played_duration(ctx, player) ) embed.set_author(name=f"{player.title} upload by {uploader}",url=player.url) embed.add_field(name="노래요청자", value=requester) embed.add_field(name="현재 재생시간", value=parse_duration(duration_played)) embed.add_field(name="재생길이", value=parse_duration(player.duration)) embed.add_field(name="업로더", value=uploader) embed.add_field(name="URL", value=f"[유튜브]({url})") loop = (await self.MusicManager.get_queue(ctx)).loop if loop == discordSuperUtils.Loops.LOOP: loop_status = "🟢 단일곡 루프." elif loop == discordSuperUtils.Loops.QUEUE_LOOP: loop_status = "🟢 대기열 루프." else: loop_status = "🔴 비활성화" embed.add_field(name="루프모드", value=loop_status) shuffle = (await self.MusicManager.get_queue(ctx)).shuffle shuffle_status = "🟢 활성화" if shuffle else "🔴 비활성화" embed.add_field(name="셔플모드", value=shuffle_status) embed.set_image(url=thumbnail) embed.set_thumbnail(url=r"https://i.imgur.com/ufxvZ0j.gif") queue_resp = await self.queue(ctx) queue_res = "\n".join(queue_resp) await ( await ctx.channel.fetch_message(resp[2]) ).edit( content=f'** **\n**__대기열 목록__**:\n{queue_res}', embed=embed, ) # Play function async def play_cmd(self, ctx, query): db = await aiosqlite.connect("db/db.sqlite") conn = await db.execute("SELECT * FROM music WHERE guild = ?", (ctx.guild.id,)) resp = await conn.fetchone() async with ctx.typing(): player = await self.MusicManager.create_player(query, ctx.author) if player: if not ctx.voice_client or not ctx.voice_client.is_connected(): await self.MusicManager.join(ctx) await self.MusicManager.queue_add(players=player, ctx=ctx) if not await self.MusicManager.play(ctx): queue_resp = await self.queue(ctx) try: queue_res = "\n".join(queue_resp) except: queue_res = "대기열 없음" msg = await ctx.channel.fetch_message(resp[2]) await msg.edit( content=f'** **\n**__대기열 목록__**:\n{queue_res}', embed=msg.embeds[0], ) await ctx.send(f"`{player[0].title}`(을)를 대기열에 추가했어요.",delete_after=5) else: await ctx.send("✅",delete_after=5) else: await ctx.send("Query not found.",delete_after=5) def default_music_embed(self): em = discord.Embed( title="현재 아무 곡도 재생 중이지 않아요.", colour=discord.Colour.dark_purple() ) em.set_image(url="https://cdn.discordapp.com/attachments/921555509935480853/921555519578189834/c265877614d80026.png?width=400&height=144") em.set_footer(text="아래 버튼을 통해 조작하실 수 있어요!") em.add_field(name="루프모드",value="-",inline=False) em.add_field(name="셔플모드",value="-",inline=False) return em async def set_default(self,ctx=None): db = await aiosqlite.connect("db/db.sqlite") conn = await db.execute("SELECT * FROM music WHERE guild = ?", (ctx.guild.id,)) resp = await conn.fetchone() msg = await (self.bot.get_channel(resp[1])).fetch_message(resp[2]) await msg.edit( content="** **\n**__대기열 목록__**:\n음성채널에 접속한뒤 이 채널에 제목이나 URL을 입력해주세요.", embed=self.default_music_embed(), components=[ [ Button(emoji="⏯", custom_id="music_pr"), Button(emoji="⏹", custom_id="music_stop"), Button(emoji="⏮", custom_id="music_previous"), Button(emoji="⏭", custom_id="music_skip"), Button(emoji="🔀", custom_id="music_shuffle") ], [ Button(emoji="🔉", custom_id="music_volumedown"), Button(label="10%", emoji="🔈", disabled=True), Button(emoji="🔊", custom_id="music_volumeup"), Button(emoji="🔁", custom_id="music_queueloop"), Button(emoji="🔂", custom_id="music_oneloop") ], [ Button(label="새로고침", emoji="↩️", custom_id="music_restart"), Button(emoji="🤖", custom_id="music_auto"), Button(emoji="📥", custom_id="music_join"), Button(emoji="❎", custom_id="music_cancel", style=4) ] ] ) # DSU Error handler @discordSuperUtils.CogManager.event(discordSuperUtils.MusicManager) async def on_music_error(self, ctx, error): # sourcery skip: remove-redundant-fstring errors = { discordSuperUtils.NotPlaying: "지금 아무 음악도 재생중이지 않아요...", discordSuperUtils.NotConnected: f"저는 보이스채널에 접속해있지않아요!", discordSuperUtils.NotPaused: "음악이 멈추어져있지않아요!", discordSuperUtils.QueueEmpty: "대기열이 비어있어요!", discordSuperUtils.AlreadyConnected: "이미 보이스채널에 접속해있어요!", discordSuperUtils.SkipError: "스킵할 곡이 없어요!", discordSuperUtils.UserNotConnected: "요청자님이 음성채널에 접속해있지않아요!", discordSuperUtils.InvalidSkipIndex: "스킵될 값을 사용할수없어요!", } for error_type, response in errors.items(): if isinstance(error, error_type): await ctx.send(response,delete_after=5) break print("unexpected error") raise error # On music play event @discordSuperUtils.CogManager.event(discordSuperUtils.MusicManager) async def on_play(self, ctx, player): # This returns a player object db = await aiosqlite.connect("db/db.sqlite") conn = await db.execute("SELECT * FROM music WHERE guild = ?", (ctx.guild.id,)) resp = await conn.fetchone() # Extracting useful data from player object self.music_stat[ctx.guild.id] = "resume" thumbnail = player.data["videoDetails"]["thumbnail"]["thumbnails"][-1]["url"] uploader = player.data["videoDetails"]["author"] url = player.url requester = player.requester.mention if player.requester else "Autoplay" embed = discord.Embed( colour=discord.Colour.random(), timestamp=datetime.datetime.now(datetime.timezone.utc), ) duration_played = round( await self.MusicManager.get_player_played_duration(ctx, player) ) embed.set_author(name=f"{player.title} upload by {uploader}",url=player.url) embed.add_field(name="노래요청자", value=requester) embed.add_field(name="현재 재생시간", value=parse_duration(duration_played)) embed.add_field(name="재생길이", value=parse_duration(player.duration)) embed.add_field(name="업로더", value=uploader) embed.add_field(name="URL", value=f"[유튜브]({url})") loop = (await self.MusicManager.get_queue(ctx)).loop if loop == discordSuperUtils.Loops.LOOP: loop_status = "🟢 단일곡 루프." elif loop == discordSuperUtils.Loops.QUEUE_LOOP: loop_status = "🟢 대기열 루프." else: loop_status = "🔴 비활성화" embed.add_field(name="루프모드", value=loop_status) shuffle = (await self.MusicManager.get_queue(ctx)).shuffle shuffle_status = "🟢 활성화" if shuffle else "🔴 비활성화" embed.add_field(name="셔플모드", value=shuffle_status) embed.set_image(url=thumbnail) embed.set_thumbnail(url=r"https://i.imgur.com/ufxvZ0j.gif") queue_resp = await self.queue(ctx) queue_res = "\n".join(queue_resp) await ( await ctx.channel.fetch_message(resp[2]) ).edit( content=f'** **\n**__대기열 목록__**:\n{queue_res}', embed=embed, ) # On queue end event @discordSuperUtils.CogManager.event(discordSuperUtils.MusicManager) async def on_queue_end(self, ctx): print(f"The queue has ended in {ctx}") await self.set_default(ctx) self.music_stat[ctx.guild.id] = None # You could wait and check activity, etc... # On inactivity disconnect event @discordSuperUtils.CogManager.event(discordSuperUtils.MusicManager) async def on_inactivity_disconnect(self, ctx): print(f"I have left {ctx} due to inactivity") async def pause_resume(self, ctx): if self.music_stat[ctx.guild.id] == "pause": if await self.MusicManager.resume(ctx): self.music_stat[ctx.guild.id] = "resume" return {"type":True,"stat":"resume"} elif await self.MusicManager.pause(ctx): self.music_stat[ctx.guild.id] = "pause" return {"type":True,"stat":"pause"} async def volume(self, ctx, interaction:Interaction,type): if current_volume := await self.MusicManager.volume(ctx): if type == "down": volume = int(current_volume) - 5 if int(current_volume) == 5: return await interaction.send(content="최소 볼륨으로 더이상 낮출수없어요.",ephemeral=False,delete_after=5) else: if int(current_volume) == 100: return await interaction.send(content="100이상 올릴수없어요",ephemeral=False,delete_after=5) else: volume = int(current_volume) + 5 if await self.MusicManager.volume(ctx, volume): await interaction.edit_origin( components=[ [ Button(emoji="⏯",custom_id="music_pr"), Button(emoji="⏹", custom_id="music_stop"), Button(emoji="⏮", custom_id="music_previous"), Button(emoji="⏭", custom_id="music_skip"), Button(emoji="🔀", custom_id="music_shuffle") ], [ Button(emoji="🔉", custom_id="music_volumedown"), Button(label=f"{volume}%",emoji="🔈", custom_id="music_volumestat",disabled=True), Button(emoji="🔊", custom_id="music_volumeup"), Button(emoji="🔁", custom_id="music_queueloop"), Button(emoji="🔂", custom_id="music_oneloop") ], [ Button(label="새로고침", emoji="↩️", custom_id="music_restart"), Button(emoji="🤖", custom_id="music_auto"), Button(emoji="📥", custom_id="music_join"), Button(emoji="❎", custom_id="music_cancel", style=4) ] ] ) await interaction.send(content=f"다음 볼륨으로 설정했어요 - {current_volume}%",ephemeral=False,delete_after=5) async def loop(self, ctx,interaction:Interaction): is_loop = await self.MusicManager.loop(ctx) if is_loop is not None: await interaction.send(content=f"단일곡 루프모드를 {'🟢 활성화' if is_loop else '🔴 비활성화'}했어요.\n임베드에 반영되기까지 시간이 조금 걸려요.",ephemeral=False,delete_after=5) async def queueloop(self, ctx,interaction:Interaction): is_loop = await self.MusicManager.queueloop(ctx) if is_loop is not None: await interaction.send(content=f"대기열 루프모드를 {'🟢 활성화' if is_loop else '🔴 비활성화'}했어요.\n임베드에 반영되기까지 시간이 조금 걸려요.",ephemeral=False,delete_after=5) async def skip(self, ctx,interaction:Interaction, index: int = None): if queue := (await self.MusicManager.get_queue(ctx)): requester = (await self.MusicManager.now_playing(ctx)).requester # Checking if the song is autoplayed if requester is None: await interaction.send(content="자동재생중인 음악을 스킵했어요.",ephemeral=False,delete_after=5) await self.MusicManager.skip(ctx, index) # Checking if queue is empty and autoplay is disabled if not queue.queue and not queue.autoplay: await interaction.send(content="대기열의 마지막곡이여서 스킵할수없어요.",ephemeral=False,delete_after=5) else: skipped_player = await self.MusicManager.skip(ctx, index) await interaction.send(content="성공적으로 스킵했어요!",ephemeral=False,delete_after=5) if not skipped_player.requester: await ctx.send("Autoplaying next song.") async def previous(self, ctx,interaction:Interaction, index: int = None): if previous_player := await self.MusicManager.previous( ctx, index, no_autoplay=True ): await interaction.send(content=f"`{previous_player[0].title}`로 되돌렸어요!",ephemeral=False,delete_after=5) async def autoplay(self, ctx,interaction:Interaction): is_autoplay = await self.MusicManager.autoplay(ctx) if is_autoplay is not None: await interaction.send(content=f"대기열 자동재생 모드를 {'🟢 활성화' if is_autoplay else '🔴 비활성화'}했어요.\n임베드에 반영되기까지 시간이 조금 걸려요.",ephemeral=False,delete_after=5) async def shuffle(self, ctx,interaction:Interaction): is_shuffle = await self.MusicManager.shuffle(ctx) if is_shuffle is not None: await interaction.send(content=f"셔플모드를 {'🟢 활성화' if is_shuffle else '🔴 비활성화'}했어요.\n임베드에 반영되기까지 시간이 조금 걸려요.",ephemeral=False,delete_after=5) async def join(self, interaction:Interaction): try: user = self.bot.get_guild(interaction.guild_id).get_member(interaction.user.id) await user.voice.channel.connect() await interaction.send("정상적으로 채널에 접속했어요.",ephemeral=False,delete_after=5) except: print(str(traceback.format_exc())) await interaction.send("이미 접속된 상태에요.",ephemeral=False,delete_after=5) # async def playlists(self, interaction:Interaction): # user = interaction.user # user_playlists = await MusicManager.get_user_playlists(user) # # if not user_playlists: # await interaction.send(f"{user.mention}님의 즐겨찾기목록을 찾지 못했어요.",ephemeral=False,delete_after=5) # return # # formatted_playlists = [ # f"""**Title:** '{user_playlist.playlist.title}' # Total Songs: {len(user_playlist.playlist.songs)} # ID: `{user_playlist.id}`""" # for user_playlist in user_playlists # ] # # embeds = discordSuperUtils.generate_embeds( # formatted_playlists, # f"{user}님의 즐겨찾기목록", # f"{user.mention}님의 즐겨찾기 목록을 보여드려요.", # 15, # string_format="{}", # ) # # for embed in embeds: # embed.timestamp = datetime.datetime.utcnow() # # try: # await user.send(embed=embeds) # except discord.Forbidden: # await interaction.respond(content="개인DM이 차단되어있어 보내지 못했어요. DM차단을 해제해주세요.") # async def add(self, ctx, interaction:Interaction): # if player := await self.MusicManager.now_playing(ctx): # added_playlist = await MusicManager.add_playlist(ctx.author, player.url) # # if not added_playlist: # await interaction.respond("URL을 찾지못했어요.") # return # # await interaction.respond(f"다음 ID로 즐겨찾기를 등록했어요. `{added_playlist.id}`") topic = """ ⏯ 일시정지/이어재생 ⏹ 정지. ⏮ 이전곡. ⏭ 스킵. 🔁 대기열 루프모드. 🔂 단일곡 루프모드. 🔀 셔플모드. ❎ 대기열 초기화 및 음성채널 접속해제. 🔉 볼륨 다운. 🔊 볼륨 업. 🤖 대기열 자동재생. 📥 봇 접속. """ @commands.command(name="뮤직셋업") async def msetup(self,ctx): try: db = await aiosqlite.connect("db/db.sqlite") music_check = await DataBaseTool(db).check_db_music(ctx.guild) premium_cur = await db.execute("SELECT * FROM premium WHERE guild = ?",(ctx.guild.id,)) premium_resp = await premium_cur.fetchone() if premium_resp == None: em = discord.Embed(title="사용불가",colour=discord.Colour.random()) em.add_field(name="사유", value="프리미엄을 사용해주셔야해요!") if not music_check: return await ctx.reply("❎ 이미 설정되어있는것같아요!") else: channel = await ctx.guild.create_text_channel(name="music setup", topic=self.topic) await channel.send("https://cdn.discordapp.com/icons/856829534926143538/4df4eac52287d066ded88084d1b728eb.webp?size=160") msg = await channel.send(content="** **\n**__대기열 목록__**:\n음성채널에 접속한뒤 이 채널에 제목이나 URL을 입력해주세요.", embed=self.default_music_embed(), components=[ [ Button(emoji="⏯", custom_id="music_pr"), Button(emoji="⏹", custom_id="music_stop"), Button(emoji="⏮", custom_id="music_previous"), Button(emoji="⏭", custom_id="music_skip"), Button(emoji="🔀", custom_id="music_shuffle") ], [ Button(emoji="🔉", custom_id="music_volumedown"), Button(label="10%", emoji="🔈", disabled=True), Button(emoji="🔊", custom_id="music_volumeup"), Button(emoji="🔁", custom_id="music_queueloop"), Button(emoji="🔂", custom_id="music_oneloop") ], [ Button(label="새로고침", emoji="↩️", custom_id="music_restart"), Button(emoji="🤖", custom_id="music_auto"), Button(emoji="📥", custom_id="music_join"), Button(emoji="❎", custom_id="music_cancel", style=4) ] ] ) db = await aiosqlite.connect("db/db.sqlite") await DataBaseTool(db).add_music_data(ctx.guild,channel,msg) await ctx.send( f"성공적으로 뮤직채널({channel.mention})을 만들었어요!\n해당 채널의 이름과 위치는 마음껏 커스터마이징이 가능하답니다!") except: print(traceback.format_exc()) @commands.Cog.listener("on_message") async def music_message(self,message): if message.author.bot: return ctx = await self.bot.get_context(message) db = await aiosqlite.connect("db/db.sqlite") conn = await db.execute("SELECT * FROM music WHERE guild = ?",(message.guild.id,)) resp = await conn.fetchone() if not resp == None: if message.channel.id == resp[1]: await message.delete() await Musicsetup.play_cmd(self, ctx, message.content) @commands.Cog.listener(name="on_button_click") async def music_button_control(self,interaction:Interaction): ctx = await self.bot.get_context(interaction.message) db = await aiosqlite.connect("db/db.sqlite") conn = await db.execute("SELECT * FROM music WHERE guild = ?", (interaction.guild_id,)) resp = await conn.fetchone() if interaction.custom_id.startswith("music_") and interaction.message.id == resp[2]: if not interaction.user.voice or not interaction.user.voice.channel: return await interaction.send("음성채널에 접속해있지않아요!",ephemeral=False,delete_after=5) if interaction.custom_id == "music_cancel": if await self.MusicManager.leave(ctx): await self.set_default(ctx) await interaction.send(content="대기열을 초기화하고 접속을 해제했어요!",ephemeral=False,delete_after=5) elif interaction.custom_id == "music_pr": resp = await self.pause_resume(ctx) if resp['type']: if resp['stat'] == "resume": await interaction.send(content="이어서 재생할게요!",ephemeral=False,delete_after=5) else: await interaction.send(content="음악을 일시정지했어요.",ephemeral=False,delete_after=5) elif interaction.custom_id == "music_stop": await self.MusicManager.cleanup(voice_client=None, guild=ctx.guild) ctx.voice_client.stop() await interaction.send("음악을 정지했어요.",ephemeral=False,delete_after=5) elif interaction.custom_id == "music_skip": await self.skip(ctx,interaction) elif interaction.custom_id == "music_shuffle": await self.shuffle(ctx,interaction) elif interaction.custom_id == "music_volumedown": await self.volume(ctx,interaction,type="down") elif interaction.custom_id == "music_volumeup": await self.volume(ctx,interaction,type="up") elif interaction.custom_id == "music_queueloop": await self.queueloop(ctx,interaction) elif interaction.custom_id == "music_oneloop": await self.loop(ctx,interaction) elif interaction.custom_id == "music_previous": await self.previous(ctx,interaction) elif interaction.custom_id == "music_auto": await self.autoplay(ctx,interaction) elif interaction.custom_id == "music_join": await self.join(interaction) elif interaction.custom_id == "music_restart": await self.restart(ctx, interaction) def setup(bot): bot.add_cog(Musicsetup(bot))
from django.db import models from django.contrib.auth.models import User import uuid class DevProfile(models.Model): """ DevProfile model for developers """ user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=254, blank=True) github_username = models.CharField(max_length=50, blank=True, null=True) twitter_username = models.CharField(max_length=50, blank=True, null=True) website = models.CharField(max_length=50, blank=True, null=True) bio = models.TextField(blank=True, null=True, default="") public_key = models.CharField(max_length=50, blank=True, null=True) private_key = models.CharField(max_length=50, blank=True, null=True) def __str__(self): """ String representation of the model """ return self.user.username def get_absolute_url(self): """ Returns the absolute url to the profile """ from django.urls import reverse return reverse('profile_view', kwargs={'username': self.user.username}) def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ return f"{self.first_name or self.user.username} {self.last_name or ""}" def to_json(self): """ Returns a json representation of the model """ return { 'id': self.id, 'first_name': self.first_name, 'last_name': self.last_name, 'email': self.email, 'bio': self.bio, 'github_username': self.github_username, 'twitter_username': self.twitter_username, 'website': self.website, } class DocumentationCategory(models.Model): """ DocumentCategory model """ name = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) slug = models.SlugField(max_length=50, unique=True) def __str__(self): return self.name class Meta: ordering = ["-name"] verbose_name = "Documentation Category" verbose_name_plural = "Documentation Categories" def to_json(self): return { 'id': self.id, 'name': self.name, 'description': self.description, } class Documentation(models.Model): """ Docs model """ title = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) content = models.TextField(blank=True, null=True) category = models.ForeignKey( DocumentationCategory, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, unique=True) def __str__(self): return self.title class Meta: ordering = ["-date"] def to_json(self): return { 'id': self.id, 'name': self.name, 'description': self.description, 'content': self.content, 'documentation_category': self.documentation_category.name, 'date': self.date.strftime("%b %d, %Y %H:%M:%S"), } class Bot(models.Model): """ Bot model """ name = models.CharField(max_length=50, unique=True) description = models.TextField(blank=True, null=True) user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner", blank=True, null=True) date = models.DateTimeField(auto_now=True) private_key = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ["-date"] def to_json(self): return { 'id': self.id, 'name': self.name, 'description': self.description, 'date': self.date.strftime("%b %d, %Y %H:%M:%S"), 'endpoint': self.endpoint, } class WebHook(models.Model): """ WebHook model """ REQUEST_TYPE_CHOICES = ( ('GET', 'GET'), ('POST', 'POST'), ) EVENT_TYPE = ( ('on_vit_mention', 'On Vit Mention'), ('on_comment_mention', 'On Comment Mention'), ('on_follow', 'On Follow'), ('on_message', 'On Message'), ) CONTENT_TYPE = ( ('application/json', 'application/json'), ('application/x-www-form-urlencoded', 'application/x-www-form-urlencoded'), ) name = models.CharField(max_length=50, unique=True) description = models.TextField(blank=True, null=True) bot = models.ForeignKey(Bot, on_delete=models.CASCADE, blank=True, null=True) payload_url = models.CharField(max_length=50) event_type = models.CharField(max_length=50, choices=EVENT_TYPE, blank=True, null=True) method = models.CharField(max_length=5, choices=REQUEST_TYPE_CHOICES, default='GET') content_type = models.CharField(max_length=50, choices=CONTENT_TYPE, default='application/json') date = models.DateTimeField(auto_now=True) required_authentication = models.BooleanField(default=False) def __str__(self): return self.name class Meta: ordering = ["-date"] def to_json(self): return { 'id': self.id, 'name': self.name, 'description': self.description, 'date': self.date.strftime("%b %d, %Y %H:%M:%S"), 'url': self.url, 'event_type': self.event_type, 'method': self.method, 'required_authentication': self.required_authentication, }
from django.db import models from django.contrib.auth.models import User import uuid class DevProfile(models.Model): """ DevProfile model for developers """ user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=254, blank=True) github_username = models.CharField(max_length=50, blank=True, null=True) twitter_username = models.CharField(max_length=50, blank=True, null=True) website = models.CharField(max_length=50, blank=True, null=True) bio = models.TextField(blank=True, null=True, default="") public_key = models.CharField(max_length=50, blank=True, null=True) private_key = models.CharField(max_length=50, blank=True, null=True) def __str__(self): """ String representation of the model """ return self.user.username def get_absolute_url(self): """ Returns the absolute url to the profile """ from django.urls import reverse return reverse('profile_view', kwargs={'username': self.user.username}) def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ return f"{self.first_name or self.user.username} {self.last_name or ''}" def to_json(self): """ Returns a json representation of the model """ return { 'id': self.id, 'first_name': self.first_name, 'last_name': self.last_name, 'email': self.email, 'bio': self.bio, 'github_username': self.github_username, 'twitter_username': self.twitter_username, 'website': self.website, } class DocumentationCategory(models.Model): """ DocumentCategory model """ name = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) slug = models.SlugField(max_length=50, unique=True) def __str__(self): return self.name class Meta: ordering = ["-name"] verbose_name = "Documentation Category" verbose_name_plural = "Documentation Categories" def to_json(self): return { 'id': self.id, 'name': self.name, 'description': self.description, } class Documentation(models.Model): """ Docs model """ title = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) content = models.TextField(blank=True, null=True) category = models.ForeignKey( DocumentationCategory, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, unique=True) def __str__(self): return self.title class Meta: ordering = ["-date"] def to_json(self): return { 'id': self.id, 'name': self.name, 'description': self.description, 'content': self.content, 'documentation_category': self.documentation_category.name, 'date': self.date.strftime("%b %d, %Y %H:%M:%S"), } class Bot(models.Model): """ Bot model """ name = models.CharField(max_length=50, unique=True) description = models.TextField(blank=True, null=True) user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner", blank=True, null=True) date = models.DateTimeField(auto_now=True) private_key = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ["-date"] def to_json(self): return { 'id': self.id, 'name': self.name, 'description': self.description, 'date': self.date.strftime("%b %d, %Y %H:%M:%S"), 'endpoint': self.endpoint, } class WebHook(models.Model): """ WebHook model """ REQUEST_TYPE_CHOICES = ( ('GET', 'GET'), ('POST', 'POST'), ) EVENT_TYPE = ( ('on_vit_mention', 'On Vit Mention'), ('on_comment_mention', 'On Comment Mention'), ('on_follow', 'On Follow'), ('on_message', 'On Message'), ) CONTENT_TYPE = ( ('application/json', 'application/json'), ('application/x-www-form-urlencoded', 'application/x-www-form-urlencoded'), ) name = models.CharField(max_length=50, unique=True) description = models.TextField(blank=True, null=True) bot = models.ForeignKey(Bot, on_delete=models.CASCADE, blank=True, null=True) payload_url = models.CharField(max_length=50) event_type = models.CharField(max_length=50, choices=EVENT_TYPE, blank=True, null=True) method = models.CharField(max_length=5, choices=REQUEST_TYPE_CHOICES, default='GET') content_type = models.CharField(max_length=50, choices=CONTENT_TYPE, default='application/json') date = models.DateTimeField(auto_now=True) required_authentication = models.BooleanField(default=False) def __str__(self): return self.name class Meta: ordering = ["-date"] def to_json(self): return { 'id': self.id, 'name': self.name, 'description': self.description, 'date': self.date.strftime("%b %d, %Y %H:%M:%S"), 'url': self.url, 'event_type': self.event_type, 'method': self.method, 'required_authentication': self.required_authentication, }
import os from typing import List, Dict, Generator, Tuple import pandas as pd import numpy as np from argparse import ArgumentParser from tqdm import tqdm from evaluate import evaluate, Metrics, match_arguments from common import Question, Role, QUESTION_FIELDS, Argument from decode_encode_answers import NO_RANGE, decode_qasrl def to_arg_roles(roles: List[Role]): return [(arg, role.question) for role in roles for arg in role.arguments] def build_all_arg_roles(sys_roles: List[Role], grt_roles: List[Role], sys_to_grt_matches: Dict[Argument, Argument]): grt_arg_roles = to_arg_roles(grt_roles) sys_arg_roles = to_arg_roles(sys_roles) grt_arg_roles = pd.DataFrame(grt_arg_roles, columns=["grt_arg", "grt_role"]) sys_arg_roles = pd.DataFrame(sys_arg_roles, columns=["sys_arg", "sys_role"]) # Dictionary mapping with None values sys_arg_roles['grt_arg'] = sys_arg_roles.sys_arg.apply(sys_to_grt_matches.get) all_arg_roles = pd.merge(sys_arg_roles, grt_arg_roles, on="grt_arg", how="outer") all_arg_roles.grt_arg.fillna(NO_RANGE, inplace=True) all_arg_roles.sys_arg.fillna(NO_RANGE, inplace=True) return all_arg_roles def filter_ids(df, row): return (df.qasrl_id == row.qasrl_id) & (df.verb_idx == row.verb_idx) def fill_answer(arg: Argument, tokens: List[str]): if arg == NO_RANGE: return NO_RANGE return " ".join(tokens[arg[0]: arg[1]]) def eval_datasets(grt_df, sys_df) -> Tuple[Metrics, Metrics, Metrics]: unlabelled_arg_counts = np.zeros(3, dtype=np.float32) labelled_arg_counts = np.zeros(3, dtype=np.float32) unlabelled_role_counts = np.zeros(3, dtype=np.float32) for key, sys_roles, grt_roles in yield_paired_predicates(sys_df, grt_df): local_arg, local_qna, local_role = evaluate(sys_roles, grt_roles) unlabelled_arg_counts += np.array(local_arg.as_tuple()) labelled_arg_counts += np.array(local_qna.as_tuple()) unlabelled_role_counts += np.array(local_role.as_tuple()) unlabelled_arg_counts = Metrics(*unlabelled_arg_counts) labelled_arg_counts = Metrics(*labelled_arg_counts) unlabelled_role_counts = Metrics(*unlabelled_role_counts) return unlabelled_arg_counts, labelled_arg_counts, unlabelled_role_counts def build_alignment(sys_df, grt_df, sent_map): all_matches = [] paired_predicates = tqdm(yield_paired_predicates(sys_df, grt_df), leave=False) for (qasrl_id, verb_idx), sys_roles, grt_roles in paired_predicates: tokens = sent_map[qasrl_id] grt_args = set(arg for role in grt_roles for arg in role.arguments) sys_args = set(arg for role in sys_roles for arg in role.arguments) sys_to_grt_arg, unmatched_sys_args, unmatched_grt_args = match_arguments(grt_args, sys_args) sys_roles_consolidated = [Role(role.question, set(arg for arg in role.arguments if arg in sys_to_grt_arg or arg in unmatched_sys_args) ) for role in sys_roles] # TODO: # Our consolidation of redundancies is based only on arguments and may remove questions # This is more common for the parser that predicts spans and their questions independently sys_roles_consolidated = [role for role in sys_roles_consolidated if role.arguments] all_args = build_all_arg_roles(sys_roles_consolidated, grt_roles, sys_to_grt_arg) all_args['qasrl_id'] = qasrl_id all_args['verb_idx'] = verb_idx all_args['grt_arg_text'] = all_args.grt_arg.apply(fill_answer, tokens=tokens) all_args['sys_arg_text'] = all_args.sys_arg.apply(fill_answer, tokens=tokens) all_matches.append(all_args) all_matches = pd.concat(all_matches) all_matches = all_matches[['grt_arg_text', 'sys_arg_text', 'grt_role', 'sys_role', 'grt_arg', 'sys_arg', 'qasrl_id', 'verb_idx']].copy() return all_matches def main(proposed_path: str, reference_path: str, sents_path=None): sys_df = decode_qasrl(pd.read_csv(proposed_path)) grt_df = decode_qasrl(pd.read_csv(reference_path)) unlabelled_arg, labelled_arg, unlabelled_role = eval_datasets(grt_df, sys_df) print("Metrics:\tPrecision\tRecall\tF1") print(f"Unlabelled Argument: {unlabelled_arg}") print(f"labelled Argument: {labelled_arg}") print(f"Unlabelled Role: {unlabelled_role}") print("Metrics:\tTP\tFP\tFN") print(f"Unlabelled Argument: {" ".join(str(t) for t in unlabelled_arg.as_tuple())}") print(f"labelled Argument: {" ".join(str(t) for t in labelled_arg.as_tuple())}") print(f"Unlabelled Role: {" ".join(str(t) for t in unlabelled_role.as_tuple())}") if sents_path is not None: sents = pd.read_csv(sents_path) sent_map = dict(zip(sents.qasrl_id, sents.tokens.apply(str.split))) align = build_alignment(sys_df, grt_df, sent_map) b1_dir, b1_name = os.path.split(proposed_path) b1 = os.path.splitext(b1_name)[0] b2 = os.path.splitext(os.path.basename(reference_path))[0] align_path = os.path.join(b1_dir, f"{b1}_{b2}.align.csv") print(align_path) align.sort_values(['qasrl_id','verb_idx', 'grt_role'], inplace=True) align.to_csv(align_path, encoding="utf-8", index=False) def yield_paired_predicates(sys_df: pd.DataFrame, grt_df: pd.DataFrame): predicate_ids = grt_df[['qasrl_id', 'verb_idx']].drop_duplicates() for idx, row in predicate_ids.iterrows(): sys_arg_roles = sys_df[filter_ids(sys_df, row)].copy() grt_arg_roles = grt_df[filter_ids(grt_df, row)].copy() sys_roles = list(yield_roles(sys_arg_roles)) grt_roles = list(yield_roles(grt_arg_roles)) yield (row.qasrl_id, row.verb_idx), sys_roles, grt_roles def question_from_row(row: pd.Series) -> Question: question_as_dict = {question_field: row[question_field] for question_field in QUESTION_FIELDS} question_as_dict['text'] = row.question return Question(**question_as_dict) def yield_roles(predicate_df: pd.DataFrame) -> Generator[Role, None, None]: for row_idx, role_row in predicate_df.iterrows(): question = question_from_row(role_row) arguments: List[Argument] = role_row.answer_range yield Role(question, tuple(arguments)) if __name__ == "__main__": ap = ArgumentParser() ap.add_argument("sys_path") ap.add_argument("ground_truth_path") ap.add_argument("-s","--sentences_path", required=False) args = ap.parse_args() main(args.sys_path, args.ground_truth_path, args.sentences_path)
import os from typing import List, Dict, Generator, Tuple import pandas as pd import numpy as np from argparse import ArgumentParser from tqdm import tqdm from evaluate import evaluate, Metrics, match_arguments from common import Question, Role, QUESTION_FIELDS, Argument from decode_encode_answers import NO_RANGE, decode_qasrl def to_arg_roles(roles: List[Role]): return [(arg, role.question) for role in roles for arg in role.arguments] def build_all_arg_roles(sys_roles: List[Role], grt_roles: List[Role], sys_to_grt_matches: Dict[Argument, Argument]): grt_arg_roles = to_arg_roles(grt_roles) sys_arg_roles = to_arg_roles(sys_roles) grt_arg_roles = pd.DataFrame(grt_arg_roles, columns=["grt_arg", "grt_role"]) sys_arg_roles = pd.DataFrame(sys_arg_roles, columns=["sys_arg", "sys_role"]) # Dictionary mapping with None values sys_arg_roles['grt_arg'] = sys_arg_roles.sys_arg.apply(sys_to_grt_matches.get) all_arg_roles = pd.merge(sys_arg_roles, grt_arg_roles, on="grt_arg", how="outer") all_arg_roles.grt_arg.fillna(NO_RANGE, inplace=True) all_arg_roles.sys_arg.fillna(NO_RANGE, inplace=True) return all_arg_roles def filter_ids(df, row): return (df.qasrl_id == row.qasrl_id) & (df.verb_idx == row.verb_idx) def fill_answer(arg: Argument, tokens: List[str]): if arg == NO_RANGE: return NO_RANGE return " ".join(tokens[arg[0]: arg[1]]) def eval_datasets(grt_df, sys_df) -> Tuple[Metrics, Metrics, Metrics]: unlabelled_arg_counts = np.zeros(3, dtype=np.float32) labelled_arg_counts = np.zeros(3, dtype=np.float32) unlabelled_role_counts = np.zeros(3, dtype=np.float32) for key, sys_roles, grt_roles in yield_paired_predicates(sys_df, grt_df): local_arg, local_qna, local_role = evaluate(sys_roles, grt_roles) unlabelled_arg_counts += np.array(local_arg.as_tuple()) labelled_arg_counts += np.array(local_qna.as_tuple()) unlabelled_role_counts += np.array(local_role.as_tuple()) unlabelled_arg_counts = Metrics(*unlabelled_arg_counts) labelled_arg_counts = Metrics(*labelled_arg_counts) unlabelled_role_counts = Metrics(*unlabelled_role_counts) return unlabelled_arg_counts, labelled_arg_counts, unlabelled_role_counts def build_alignment(sys_df, grt_df, sent_map): all_matches = [] paired_predicates = tqdm(yield_paired_predicates(sys_df, grt_df), leave=False) for (qasrl_id, verb_idx), sys_roles, grt_roles in paired_predicates: tokens = sent_map[qasrl_id] grt_args = set(arg for role in grt_roles for arg in role.arguments) sys_args = set(arg for role in sys_roles for arg in role.arguments) sys_to_grt_arg, unmatched_sys_args, unmatched_grt_args = match_arguments(grt_args, sys_args) sys_roles_consolidated = [Role(role.question, set(arg for arg in role.arguments if arg in sys_to_grt_arg or arg in unmatched_sys_args) ) for role in sys_roles] # TODO: # Our consolidation of redundancies is based only on arguments and may remove questions # This is more common for the parser that predicts spans and their questions independently sys_roles_consolidated = [role for role in sys_roles_consolidated if role.arguments] all_args = build_all_arg_roles(sys_roles_consolidated, grt_roles, sys_to_grt_arg) all_args['qasrl_id'] = qasrl_id all_args['verb_idx'] = verb_idx all_args['grt_arg_text'] = all_args.grt_arg.apply(fill_answer, tokens=tokens) all_args['sys_arg_text'] = all_args.sys_arg.apply(fill_answer, tokens=tokens) all_matches.append(all_args) all_matches = pd.concat(all_matches) all_matches = all_matches[['grt_arg_text', 'sys_arg_text', 'grt_role', 'sys_role', 'grt_arg', 'sys_arg', 'qasrl_id', 'verb_idx']].copy() return all_matches def main(proposed_path: str, reference_path: str, sents_path=None): sys_df = decode_qasrl(pd.read_csv(proposed_path)) grt_df = decode_qasrl(pd.read_csv(reference_path)) unlabelled_arg, labelled_arg, unlabelled_role = eval_datasets(grt_df, sys_df) print("Metrics:\tPrecision\tRecall\tF1") print(f"Unlabelled Argument: {unlabelled_arg}") print(f"labelled Argument: {labelled_arg}") print(f"Unlabelled Role: {unlabelled_role}") print("Metrics:\tTP\tFP\tFN") print(f"Unlabelled Argument: {' '.join(str(t) for t in unlabelled_arg.as_tuple())}") print(f"labelled Argument: {' '.join(str(t) for t in labelled_arg.as_tuple())}") print(f"Unlabelled Role: {' '.join(str(t) for t in unlabelled_role.as_tuple())}") if sents_path is not None: sents = pd.read_csv(sents_path) sent_map = dict(zip(sents.qasrl_id, sents.tokens.apply(str.split))) align = build_alignment(sys_df, grt_df, sent_map) b1_dir, b1_name = os.path.split(proposed_path) b1 = os.path.splitext(b1_name)[0] b2 = os.path.splitext(os.path.basename(reference_path))[0] align_path = os.path.join(b1_dir, f"{b1}_{b2}.align.csv") print(align_path) align.sort_values(['qasrl_id','verb_idx', 'grt_role'], inplace=True) align.to_csv(align_path, encoding="utf-8", index=False) def yield_paired_predicates(sys_df: pd.DataFrame, grt_df: pd.DataFrame): predicate_ids = grt_df[['qasrl_id', 'verb_idx']].drop_duplicates() for idx, row in predicate_ids.iterrows(): sys_arg_roles = sys_df[filter_ids(sys_df, row)].copy() grt_arg_roles = grt_df[filter_ids(grt_df, row)].copy() sys_roles = list(yield_roles(sys_arg_roles)) grt_roles = list(yield_roles(grt_arg_roles)) yield (row.qasrl_id, row.verb_idx), sys_roles, grt_roles def question_from_row(row: pd.Series) -> Question: question_as_dict = {question_field: row[question_field] for question_field in QUESTION_FIELDS} question_as_dict['text'] = row.question return Question(**question_as_dict) def yield_roles(predicate_df: pd.DataFrame) -> Generator[Role, None, None]: for row_idx, role_row in predicate_df.iterrows(): question = question_from_row(role_row) arguments: List[Argument] = role_row.answer_range yield Role(question, tuple(arguments)) if __name__ == "__main__": ap = ArgumentParser() ap.add_argument("sys_path") ap.add_argument("ground_truth_path") ap.add_argument("-s","--sentences_path", required=False) args = ap.parse_args() main(args.sys_path, args.ground_truth_path, args.sentences_path)
from plotly.subplots import make_subplots import plotly.graph_objs as go class WellLog: """Well log wrapper. Args: n_tracks (int): number of vertical tracks. shared_yaxes (bool): shared Y axes for all tracks? Other keyword arguments will be passed to plotly.make_subplots() Attributes: fig (plotly go.Figure object) """ def __init__(self, n_tracks, shared_yaxes=True, **kwargs): self.fig = make_subplots( rows=1, cols=n_tracks, subplot_titles=[f"{t + 1}:" for t in range(n_tracks)], shared_yaxes=shared_yaxes, **kwargs, ) def get_trace(self, name): """Get a dictionary containing the plotly graph object for the trace. Args: name (str): current name of the plotly graph object. Returns: dict containing key *'go'* containing the current plotly graph object, and other keys: *'track_no'* (int): zero-indexed track/column containing the trace. """ trace = None for tr in self.fig.data: if tr.name == name: trace = {"go": tr} if trace is None: raise KeyError( f"Could not find trace.name = '{name}" in {[t["name"] for t in self.fig.data]}" ) else: if trace["go"].yaxis == "y": trace["track_no"] = 0 else: trace["track_no"] = int(trace["go"].yaxis.replace("y", "")) - 1 return trace def add_trace(self, graph_obj, name=None, track_no=0, **kwargs): """Add a trace to the plotly figure. Args: graph_obj (plotly graph object) name (str) track_no (int): zero-indexed track/column number Other keyword arguments (e.g. "secondary_x") are passed through to plotly.go.Figure.add_trace. """ if name is None: name = graph_obj.name self.fig.add_trace(graph_obj, row=1, col=track_no + 1, **kwargs) def make_scatter(series, **kwargs): return go.Scatter(x=series.values, y=series.index, **kwargs) def make_composite_log( df, lines=(), log_tracks=(), lines_func=make_scatter, line_kwargs=None, ): """Make a composite well log from a pandas.DataFrame. Args: df (pandas.DataFrame): the index should be the depth. lines (list of lists): list of column names to plot as lines on the composite log. Each item should be a list of column names; each list refers to each track. So for example, for a composite log showing gamma in the first track and neutron and density in the second track, you would use: ``lines=[["GAMM"], ["NEUT", "RHO"]]``. log_tracks (list): list of tracks to set as log scale (zero-indexed, i.e. ``log_tracks=[0]`` would apply to left-most track; also allows negative indices so that ``log_tracks=[-1]`` would apply to the right-most track). lines_func (function): function which takes a pandas.Series and returns a plotly graph object e.g. ``go.Scatter`` line_kwargs (dict): dictionary which is passed also for each call to lines_func. Default is `{"mode": "lines", "line": {"width": 1}}` Returns: ``WellLog`` object with a plotly ``Figure`` as the ``fig`` attribute. """ if line_kwargs is None: line_kwargs = {"mode": "lines", "line": {"width": 1}} n_tracks = max([len(lines)]) columns = [] log = WellLog(n_tracks=n_tracks) for i, column_names in enumerate(lines): for column in column_names: log.add_trace( lines_func(df[column], name=column, **line_kwargs), track_no=i ) columns.append(column) data_range = df[columns].dropna(how="any") log.fig.update_yaxes(range=(max(data_range.index), min(data_range.index))) for track_no in log_tracks: if track_no < 0: track_no = n_tracks + track_no if track_no == 0: log.fig.update_layout(xaxis_type="log") else: log.fig.update_layout(**{f"xaxis{track_no + 1:.0f}_type": "log"}) log.fig.update_layout(template='plotly_white') return log
from plotly.subplots import make_subplots import plotly.graph_objs as go class WellLog: """Well log wrapper. Args: n_tracks (int): number of vertical tracks. shared_yaxes (bool): shared Y axes for all tracks? Other keyword arguments will be passed to plotly.make_subplots() Attributes: fig (plotly go.Figure object) """ def __init__(self, n_tracks, shared_yaxes=True, **kwargs): self.fig = make_subplots( rows=1, cols=n_tracks, subplot_titles=[f"{t + 1}:" for t in range(n_tracks)], shared_yaxes=shared_yaxes, **kwargs, ) def get_trace(self, name): """Get a dictionary containing the plotly graph object for the trace. Args: name (str): current name of the plotly graph object. Returns: dict containing key *'go'* containing the current plotly graph object, and other keys: *'track_no'* (int): zero-indexed track/column containing the trace. """ trace = None for tr in self.fig.data: if tr.name == name: trace = {"go": tr} if trace is None: raise KeyError( f"Could not find trace.name = '{name}' in {[t['name'] for t in self.fig.data]}" ) else: if trace["go"].yaxis == "y": trace["track_no"] = 0 else: trace["track_no"] = int(trace["go"].yaxis.replace("y", "")) - 1 return trace def add_trace(self, graph_obj, name=None, track_no=0, **kwargs): """Add a trace to the plotly figure. Args: graph_obj (plotly graph object) name (str) track_no (int): zero-indexed track/column number Other keyword arguments (e.g. "secondary_x") are passed through to plotly.go.Figure.add_trace. """ if name is None: name = graph_obj.name self.fig.add_trace(graph_obj, row=1, col=track_no + 1, **kwargs) def make_scatter(series, **kwargs): return go.Scatter(x=series.values, y=series.index, **kwargs) def make_composite_log( df, lines=(), log_tracks=(), lines_func=make_scatter, line_kwargs=None, ): """Make a composite well log from a pandas.DataFrame. Args: df (pandas.DataFrame): the index should be the depth. lines (list of lists): list of column names to plot as lines on the composite log. Each item should be a list of column names; each list refers to each track. So for example, for a composite log showing gamma in the first track and neutron and density in the second track, you would use: ``lines=[["GAMM"], ["NEUT", "RHO"]]``. log_tracks (list): list of tracks to set as log scale (zero-indexed, i.e. ``log_tracks=[0]`` would apply to left-most track; also allows negative indices so that ``log_tracks=[-1]`` would apply to the right-most track). lines_func (function): function which takes a pandas.Series and returns a plotly graph object e.g. ``go.Scatter`` line_kwargs (dict): dictionary which is passed also for each call to lines_func. Default is `{"mode": "lines", "line": {"width": 1}}` Returns: ``WellLog`` object with a plotly ``Figure`` as the ``fig`` attribute. """ if line_kwargs is None: line_kwargs = {"mode": "lines", "line": {"width": 1}} n_tracks = max([len(lines)]) columns = [] log = WellLog(n_tracks=n_tracks) for i, column_names in enumerate(lines): for column in column_names: log.add_trace( lines_func(df[column], name=column, **line_kwargs), track_no=i ) columns.append(column) data_range = df[columns].dropna(how="any") log.fig.update_yaxes(range=(max(data_range.index), min(data_range.index))) for track_no in log_tracks: if track_no < 0: track_no = n_tracks + track_no if track_no == 0: log.fig.update_layout(xaxis_type="log") else: log.fig.update_layout(**{f"xaxis{track_no + 1:.0f}_type": "log"}) log.fig.update_layout(template='plotly_white') return log
import json import boto3 from datetime import datetime as dt lambd = boto3.client('lambda') def lambda_handler(event, context): today = dt.fromtimestamp(event['timestamp']) prefix = event['prefix'] event['report']['img']['files'] = [] for query in event['queries']: if "HEATMAP" in query['query_name'].split("_"): query_name = query['query_name'] filename = f"{today.year}-{today.month}-{today.day}-{event["city"]}-{query_name}" png_key = prefix + "img/" + filename + ".png" task = { 'png_key': png_key, 'alert': query['related_alert'], 'CSVBucket': query['CSVBucket'], 'CSVKey': query['CSVKey'], } event['report']['img']['files'].append(task) event['task'] = task #################### Attention for Docker Test and AWS Production ################ lambd.invoke( FunctionName='generate-js-files', InvocationType='Event', Payload=json.dumps(event)) return event
import json import boto3 from datetime import datetime as dt lambd = boto3.client('lambda') def lambda_handler(event, context): today = dt.fromtimestamp(event['timestamp']) prefix = event['prefix'] event['report']['img']['files'] = [] for query in event['queries']: if "HEATMAP" in query['query_name'].split("_"): query_name = query['query_name'] filename = f"{today.year}-{today.month}-{today.day}-{event['city']}-{query_name}" png_key = prefix + "img/" + filename + ".png" task = { 'png_key': png_key, 'alert': query['related_alert'], 'CSVBucket': query['CSVBucket'], 'CSVKey': query['CSVKey'], } event['report']['img']['files'].append(task) event['task'] = task #################### Attention for Docker Test and AWS Production ################ lambd.invoke( FunctionName='generate-js-files', InvocationType='Event', Payload=json.dumps(event)) return event
from typing import Iterator, Optional, Any, Dict, Callable, Iterable from typing import Union, Tuple, List, Set, Pattern, Sequence from typing import NoReturn, TYPE_CHECKING, TypeVar, cast, overload from dataclasses import dataclass import random import itertools import functools from contextlib import contextmanager from copy import deepcopy from pathlib import Path import warnings from thinc.api import get_current_ops, Config, CupyOps, Optimizer import srsly import multiprocessing as mp from itertools import chain, cycle from timeit import default_timer as timer import traceback from . import ty from .tokens.underscore import Underscore from .vocab import Vocab, create_vocab from .pipe_analysis import validate_attrs, analyze_pipes, print_pipe_analysis from .training import Example, validate_examples from .training.initialize import init_vocab, init_tok2vec from .scorer import Scorer from .util import registry, SimpleFrozenList, _pipe, raise_error from .util import SimpleFrozenDict, combine_score_weights, CONFIG_SECTION_ORDER from .util import warn_if_jupyter_cupy from .lang.tokenizer_exceptions import URL_MATCH, BASE_EXCEPTIONS from .lang.punctuation import TOKENIZER_PREFIXES, TOKENIZER_SUFFIXES from .lang.punctuation import TOKENIZER_INFIXES from .tokens import Doc from .tokenizer import Tokenizer from .errors import Errors, Warnings from .schemas import ConfigSchema, ConfigSchemaNlp, ConfigSchemaInit from .schemas import ConfigSchemaPretrain, validate_init_settings from .git_info import GIT_VERSION from . import util from . import about from .lookups import load_lookups from .compat import Literal if TYPE_CHECKING: from .pipeline import Pipe # noqa: F401 # This is the base config will all settings (training etc.) DEFAULT_CONFIG_PATH = Path(__file__).parent / "default_config.cfg" DEFAULT_CONFIG = util.load_config(DEFAULT_CONFIG_PATH) # This is the base config for the [pretraining] block and currently not included # in the main config and only added via the 'init fill-config' command DEFAULT_CONFIG_PRETRAIN_PATH = Path(__file__).parent / "default_config_pretraining.cfg" # Type variable for contexts piped with documents _AnyContext = TypeVar("_AnyContext") class BaseDefaults: """Language data defaults, available via Language.Defaults. Can be overwritten by language subclasses by defining their own subclasses of Language.Defaults. """ config: Config = Config(section_order=CONFIG_SECTION_ORDER) tokenizer_exceptions: Dict[str, List[dict]] = BASE_EXCEPTIONS prefixes: Optional[Sequence[Union[str, Pattern]]] = TOKENIZER_PREFIXES suffixes: Optional[Sequence[Union[str, Pattern]]] = TOKENIZER_SUFFIXES infixes: Optional[Sequence[Union[str, Pattern]]] = TOKENIZER_INFIXES token_match: Optional[Callable] = None url_match: Optional[Callable] = URL_MATCH syntax_iterators: Dict[str, Callable] = {} lex_attr_getters: Dict[int, Callable[[str], Any]] = {} stop_words: Set[str] = set() writing_system = {"direction": "ltr", "has_case": True, "has_letters": True} @registry.tokenizers("spacy.Tokenizer.v1") def create_tokenizer() -> Callable[["Language"], Tokenizer]: """Registered function to create a tokenizer. Returns a factory that takes the nlp object and returns a Tokenizer instance using the language detaults. """ def tokenizer_factory(nlp: "Language") -> Tokenizer: prefixes = nlp.Defaults.prefixes suffixes = nlp.Defaults.suffixes infixes = nlp.Defaults.infixes prefix_search = util.compile_prefix_regex(prefixes).search if prefixes else None suffix_search = util.compile_suffix_regex(suffixes).search if suffixes else None infix_finditer = util.compile_infix_regex(infixes).finditer if infixes else None return Tokenizer( nlp.vocab, rules=nlp.Defaults.tokenizer_exceptions, prefix_search=prefix_search, suffix_search=suffix_search, infix_finditer=infix_finditer, token_match=nlp.Defaults.token_match, url_match=nlp.Defaults.url_match, ) return tokenizer_factory @registry.misc("spacy.LookupsDataLoader.v1") def load_lookups_data(lang, tables): util.logger.debug(f"Loading lookups from spacy-lookups-data: {tables}") lookups = load_lookups(lang=lang, tables=tables) return lookups class Language: """A text-processing pipeline. Usually you'll load this once per process, and pass the instance around your application. Defaults (class): Settings, data and factory methods for creating the `nlp` object and processing pipeline. lang (str): IETF language code, such as 'en'. DOCS: https://spacy.io/api/language """ Defaults = BaseDefaults lang: Optional[str] = None default_config = DEFAULT_CONFIG factories = SimpleFrozenDict(error=Errors.E957) _factory_meta: Dict[str, "FactoryMeta"] = {} # meta by factory def __init__( self, vocab: Union[Vocab, bool] = True, *, max_length: int = 10 ** 6, meta: Dict[str, Any] = {}, create_tokenizer: Optional[Callable[["Language"], Callable[[str], Doc]]] = None, batch_size: int = 1000, **kwargs, ) -> None: """Initialise a Language object. vocab (Vocab): A `Vocab` object. If `True`, a vocab is created. meta (dict): Custom meta data for the Language class. Is written to by models to add model meta data. max_length (int): Maximum number of characters in a single text. The current models may run out memory on extremely long texts, due to large internal allocations. You should segment these texts into meaningful units, e.g. paragraphs, subsections etc, before passing them to spaCy. Default maximum length is 1,000,000 charas (1mb). As a rule of thumb, if all pipeline components are enabled, spaCy's default models currently requires roughly 1GB of temporary memory per 100,000 characters in one text. create_tokenizer (Callable): Function that takes the nlp object and returns a tokenizer. batch_size (int): Default batch size for pipe and evaluate. DOCS: https://spacy.io/api/language#init """ # We're only calling this to import all factories provided via entry # points. The factory decorator applied to these functions takes care # of the rest. util.registry._entry_point_factories.get_all() self._config = DEFAULT_CONFIG.merge(self.default_config) self._meta = dict(meta) self._path = None self._optimizer: Optional[Optimizer] = None # Component meta and configs are only needed on the instance self._pipe_meta: Dict[str, "FactoryMeta"] = {} # meta by component self._pipe_configs: Dict[str, Config] = {} # config by component if not isinstance(vocab, Vocab) and vocab is not True: raise ValueError(Errors.E918.format(vocab=vocab, vocab_type=type(Vocab))) if vocab is True: vectors_name = meta.get("vectors", {}).get("name") vocab = create_vocab(self.lang, self.Defaults, vectors_name=vectors_name) else: if (self.lang and vocab.lang) and (self.lang != vocab.lang): raise ValueError(Errors.E150.format(nlp=self.lang, vocab=vocab.lang)) self.vocab: Vocab = vocab if self.lang is None: self.lang = self.vocab.lang self._components: List[Tuple[str, "Pipe"]] = [] self._disabled: Set[str] = set() self.max_length = max_length # Create the default tokenizer from the default config if not create_tokenizer: tokenizer_cfg = {"tokenizer": self._config["nlp"]["tokenizer"]} create_tokenizer = registry.resolve(tokenizer_cfg)["tokenizer"] self.tokenizer = create_tokenizer(self) self.batch_size = batch_size self.default_error_handler = raise_error def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) cls.default_config = DEFAULT_CONFIG.merge(cls.Defaults.config) cls.default_config["nlp"]["lang"] = cls.lang @property def path(self): return self._path @property def meta(self) -> Dict[str, Any]: """Custom meta data of the language class. If a model is loaded, this includes details from the model's meta.json. RETURNS (Dict[str, Any]): The meta. DOCS: https://spacy.io/api/language#meta """ spacy_version = util.get_minor_version_range(about.__version__) if self.vocab.lang: self._meta.setdefault("lang", self.vocab.lang) else: self._meta.setdefault("lang", self.lang) self._meta.setdefault("name", "pipeline") self._meta.setdefault("version", "0.0.0") self._meta.setdefault("spacy_version", spacy_version) self._meta.setdefault("description", "") self._meta.setdefault("author", "") self._meta.setdefault("email", "") self._meta.setdefault("url", "") self._meta.setdefault("license", "") self._meta.setdefault("spacy_git_version", GIT_VERSION) self._meta["vectors"] = { "width": self.vocab.vectors_length, "vectors": len(self.vocab.vectors), "keys": self.vocab.vectors.n_keys, "name": self.vocab.vectors.name, "mode": self.vocab.vectors.mode, } self._meta["labels"] = dict(self.pipe_labels) # TODO: Adding this back to prevent breaking people's code etc., but # we should consider removing it self._meta["pipeline"] = list(self.pipe_names) self._meta["components"] = list(self.component_names) self._meta["disabled"] = list(self.disabled) return self._meta @meta.setter def meta(self, value: Dict[str, Any]) -> None: self._meta = value @property def config(self) -> Config: """Trainable config for the current language instance. Includes the current pipeline components, as well as default training config. RETURNS (thinc.api.Config): The config. DOCS: https://spacy.io/api/language#config """ self._config.setdefault("nlp", {}) self._config.setdefault("training", {}) self._config["nlp"]["lang"] = self.lang # We're storing the filled config for each pipeline component and so # we can populate the config again later pipeline = {} score_weights = [] for pipe_name in self.component_names: pipe_meta = self.get_pipe_meta(pipe_name) pipe_config = self.get_pipe_config(pipe_name) pipeline[pipe_name] = {"factory": pipe_meta.factory, **pipe_config} if pipe_meta.default_score_weights: score_weights.append(pipe_meta.default_score_weights) self._config["nlp"]["pipeline"] = list(self.component_names) self._config["nlp"]["disabled"] = list(self.disabled) self._config["components"] = pipeline # We're merging the existing score weights back into the combined # weights to make sure we're preserving custom settings in the config # but also reflect updates (e.g. new components added) prev_weights = self._config["training"].get("score_weights", {}) combined_score_weights = combine_score_weights(score_weights, prev_weights) self._config["training"]["score_weights"] = combined_score_weights if not srsly.is_json_serializable(self._config): raise ValueError(Errors.E961.format(config=self._config)) return self._config @config.setter def config(self, value: Config) -> None: self._config = value @property def disabled(self) -> List[str]: """Get the names of all disabled components. RETURNS (List[str]): The disabled components. """ # Make sure the disabled components are returned in the order they # appear in the pipeline (which isn't guaranteed by the set) names = [name for name, _ in self._components if name in self._disabled] return SimpleFrozenList(names, error=Errors.E926.format(attr="disabled")) @property def factory_names(self) -> List[str]: """Get names of all available factories. RETURNS (List[str]): The factory names. """ names = list(self.factories.keys()) return SimpleFrozenList(names) @property def components(self) -> List[Tuple[str, "Pipe"]]: """Get all (name, component) tuples in the pipeline, including the currently disabled components. """ return SimpleFrozenList( self._components, error=Errors.E926.format(attr="components") ) @property def component_names(self) -> List[str]: """Get the names of the available pipeline components. Includes all active and inactive pipeline components. RETURNS (List[str]): List of component name strings, in order. """ names = [pipe_name for pipe_name, _ in self._components] return SimpleFrozenList(names, error=Errors.E926.format(attr="component_names")) @property def pipeline(self) -> List[Tuple[str, "Pipe"]]: """The processing pipeline consisting of (name, component) tuples. The components are called on the Doc in order as it passes through the pipeline. RETURNS (List[Tuple[str, Pipe]]): The pipeline. """ pipes = [(n, p) for n, p in self._components if n not in self._disabled] return SimpleFrozenList(pipes, error=Errors.E926.format(attr="pipeline")) @property def pipe_names(self) -> List[str]: """Get names of available active pipeline components. RETURNS (List[str]): List of component name strings, in order. """ names = [pipe_name for pipe_name, _ in self.pipeline] return SimpleFrozenList(names, error=Errors.E926.format(attr="pipe_names")) @property def pipe_factories(self) -> Dict[str, str]: """Get the component factories for the available pipeline components. RETURNS (Dict[str, str]): Factory names, keyed by component names. """ factories = {} for pipe_name, pipe in self._components: factories[pipe_name] = self.get_pipe_meta(pipe_name).factory return SimpleFrozenDict(factories) @property def pipe_labels(self) -> Dict[str, List[str]]: """Get the labels set by the pipeline components, if available (if the component exposes a labels property). RETURNS (Dict[str, List[str]]): Labels keyed by component name. """ labels = {} for name, pipe in self._components: if hasattr(pipe, "labels"): labels[name] = list(pipe.labels) return SimpleFrozenDict(labels) @classmethod def has_factory(cls, name: str) -> bool: """RETURNS (bool): Whether a factory of that name is registered.""" internal_name = cls.get_factory_name(name) return name in registry.factories or internal_name in registry.factories @classmethod def get_factory_name(cls, name: str) -> str: """Get the internal factory name based on the language subclass. name (str): The factory name. RETURNS (str): The internal factory name. """ if cls.lang is None: return name return f"{cls.lang}.{name}" @classmethod def get_factory_meta(cls, name: str) -> "FactoryMeta": """Get the meta information for a given factory name. name (str): The component factory name. RETURNS (FactoryMeta): The meta for the given factory name. """ internal_name = cls.get_factory_name(name) if internal_name in cls._factory_meta: return cls._factory_meta[internal_name] if name in cls._factory_meta: return cls._factory_meta[name] raise ValueError(Errors.E967.format(meta="factory", name=name)) @classmethod def set_factory_meta(cls, name: str, value: "FactoryMeta") -> None: """Set the meta information for a given factory name. name (str): The component factory name. value (FactoryMeta): The meta to set. """ cls._factory_meta[cls.get_factory_name(name)] = value def get_pipe_meta(self, name: str) -> "FactoryMeta": """Get the meta information for a given component name. name (str): The component name. RETURNS (FactoryMeta): The meta for the given component name. """ if name not in self._pipe_meta: raise ValueError(Errors.E967.format(meta="component", name=name)) return self._pipe_meta[name] def get_pipe_config(self, name: str) -> Config: """Get the config used to create a pipeline component. name (str): The component name. RETURNS (Config): The config used to create the pipeline component. """ if name not in self._pipe_configs: raise ValueError(Errors.E960.format(name=name)) pipe_config = self._pipe_configs[name] return pipe_config @classmethod def factory( cls, name: str, *, default_config: Dict[str, Any] = SimpleFrozenDict(), assigns: Iterable[str] = SimpleFrozenList(), requires: Iterable[str] = SimpleFrozenList(), retokenizes: bool = False, default_score_weights: Dict[str, Optional[float]] = SimpleFrozenDict(), func: Optional[Callable] = None, ) -> Callable: """Register a new pipeline component factory. Can be used as a decorator on a function or classmethod, or called as a function with the factory provided as the func keyword argument. To create a component and add it to the pipeline, you can use nlp.add_pipe(name). name (str): The name of the component factory. default_config (Dict[str, Any]): Default configuration, describing the default values of the factory arguments. assigns (Iterable[str]): Doc/Token attributes assigned by this component, e.g. "token.ent_id". Used for pipeline analysis. requires (Iterable[str]): Doc/Token attributes required by this component, e.g. "token.ent_id". Used for pipeline analysis. retokenizes (bool): Whether the component changes the tokenization. Used for pipeline analysis. default_score_weights (Dict[str, Optional[float]]): The scores to report during training, and their default weight towards the final score used to select the best model. Weights should sum to 1.0 per component and will be combined and normalized for the whole pipeline. If None, the score won't be shown in the logs or be weighted. func (Optional[Callable]): Factory function if not used as a decorator. DOCS: https://spacy.io/api/language#factory """ if not isinstance(name, str): raise ValueError(Errors.E963.format(decorator="factory")) if not isinstance(default_config, dict): err = Errors.E962.format( style="default config", name=name, cfg_type=type(default_config) ) raise ValueError(err) def add_factory(factory_func: Callable) -> Callable: internal_name = cls.get_factory_name(name) if internal_name in registry.factories: # We only check for the internal name here – it's okay if it's a # subclass and the base class has a factory of the same name. We # also only raise if the function is different to prevent raising # if module is reloaded. existing_func = registry.factories.get(internal_name) if not util.is_same_func(factory_func, existing_func): err = Errors.E004.format( name=name, func=existing_func, new_func=factory_func ) raise ValueError(err) arg_names = util.get_arg_names(factory_func) if "nlp" not in arg_names or "name" not in arg_names: raise ValueError(Errors.E964.format(name=name)) # Officially register the factory so we can later call # registry.resolve and refer to it in the config as # @factories = "spacy.Language.xyz". We use the class name here so # different classes can have different factories. registry.factories.register(internal_name, func=factory_func) factory_meta = FactoryMeta( factory=name, default_config=default_config, assigns=validate_attrs(assigns), requires=validate_attrs(requires), scores=list(default_score_weights.keys()), default_score_weights=default_score_weights, retokenizes=retokenizes, ) cls.set_factory_meta(name, factory_meta) # We're overwriting the class attr with a frozen dict to handle # backwards-compat (writing to Language.factories directly). This # wouldn't work with an instance property and just produce a # confusing error – here we can show a custom error cls.factories = SimpleFrozenDict( registry.factories.get_all(), error=Errors.E957 ) return factory_func if func is not None: # Support non-decorator use cases return add_factory(func) return add_factory @classmethod def component( cls, name: str, *, assigns: Iterable[str] = SimpleFrozenList(), requires: Iterable[str] = SimpleFrozenList(), retokenizes: bool = False, func: Optional["Pipe"] = None, ) -> Callable: """Register a new pipeline component. Can be used for stateless function components that don't require a separate factory. Can be used as a decorator on a function or classmethod, or called as a function with the factory provided as the func keyword argument. To create a component and add it to the pipeline, you can use nlp.add_pipe(name). name (str): The name of the component factory. assigns (Iterable[str]): Doc/Token attributes assigned by this component, e.g. "token.ent_id". Used for pipeline analysis. requires (Iterable[str]): Doc/Token attributes required by this component, e.g. "token.ent_id". Used for pipeline analysis. retokenizes (bool): Whether the component changes the tokenization. Used for pipeline analysis. func (Optional[Callable]): Factory function if not used as a decorator. DOCS: https://spacy.io/api/language#component """ if name is not None and not isinstance(name, str): raise ValueError(Errors.E963.format(decorator="component")) component_name = name if name is not None else util.get_object_name(func) def add_component(component_func: "Pipe") -> Callable: if isinstance(func, type): # function is a class raise ValueError(Errors.E965.format(name=component_name)) def factory_func(nlp, name: str) -> "Pipe": return component_func internal_name = cls.get_factory_name(name) if internal_name in registry.factories: # We only check for the internal name here – it's okay if it's a # subclass and the base class has a factory of the same name. We # also only raise if the function is different to prevent raising # if module is reloaded. It's hacky, but we need to check the # existing functure for a closure and whether that's identical # to the component function (because factory_func created above # will always be different, even for the same function) existing_func = registry.factories.get(internal_name) closure = existing_func.__closure__ wrapped = [c.cell_contents for c in closure][0] if closure else None if util.is_same_func(wrapped, component_func): factory_func = existing_func # noqa: F811 cls.factory( component_name, assigns=assigns, requires=requires, retokenizes=retokenizes, func=factory_func, ) return component_func if func is not None: # Support non-decorator use cases return add_component(func) return add_component def analyze_pipes( self, *, keys: List[str] = ["assigns", "requires", "scores", "retokenizes"], pretty: bool = False, ) -> Optional[Dict[str, Any]]: """Analyze the current pipeline components, print a summary of what they assign or require and check that all requirements are met. keys (List[str]): The meta values to display in the table. Corresponds to values in FactoryMeta, defined by @Language.factory decorator. pretty (bool): Pretty-print the results. RETURNS (dict): The data. """ analysis = analyze_pipes(self, keys=keys) if pretty: print_pipe_analysis(analysis, keys=keys) return analysis def get_pipe(self, name: str) -> "Pipe": """Get a pipeline component for a given component name. name (str): Name of pipeline component to get. RETURNS (callable): The pipeline component. DOCS: https://spacy.io/api/language#get_pipe """ for pipe_name, component in self._components: if pipe_name == name: return component raise KeyError(Errors.E001.format(name=name, opts=self.component_names)) def create_pipe( self, factory_name: str, name: Optional[str] = None, *, config: Dict[str, Any] = SimpleFrozenDict(), raw_config: Optional[Config] = None, validate: bool = True, ) -> "Pipe": """Create a pipeline component. Mostly used internally. To create and add a component to the pipeline, you can use nlp.add_pipe. factory_name (str): Name of component factory. name (Optional[str]): Optional name to assign to component instance. Defaults to factory name if not set. config (Dict[str, Any]): Config parameters to use for this component. Will be merged with default config, if available. raw_config (Optional[Config]): Internals: the non-interpolated config. validate (bool): Whether to validate the component config against the arguments and types expected by the factory. RETURNS (Pipe): The pipeline component. DOCS: https://spacy.io/api/language#create_pipe """ name = name if name is not None else factory_name if not isinstance(config, dict): err = Errors.E962.format(style="config", name=name, cfg_type=type(config)) raise ValueError(err) if not srsly.is_json_serializable(config): raise ValueError(Errors.E961.format(config=config)) if not self.has_factory(factory_name): err = Errors.E002.format( name=factory_name, opts=", ".join(self.factory_names), method="create_pipe", lang=util.get_object_name(self), lang_code=self.lang, ) raise ValueError(err) pipe_meta = self.get_factory_meta(factory_name) # This is unideal, but the alternative would mean you always need to # specify the full config settings, which is not really viable. if pipe_meta.default_config: config = Config(pipe_meta.default_config).merge(config) internal_name = self.get_factory_name(factory_name) # If the language-specific factory doesn't exist, try again with the # not-specific name if internal_name not in registry.factories: internal_name = factory_name # The name allows components to know their pipe name and use it in the # losses etc. (even if multiple instances of the same factory are used) config = {"nlp": self, "name": name, **config, "@factories": internal_name} # We need to create a top-level key because Thinc doesn't allow resolving # top-level references to registered functions. Also gives nicer errors. cfg = {factory_name: config} # We're calling the internal _fill here to avoid constructing the # registered functions twice resolved = registry.resolve(cfg, validate=validate) filled = registry.fill({"cfg": cfg[factory_name]}, validate=validate)["cfg"] filled = Config(filled) filled["factory"] = factory_name filled.pop("@factories", None) # Remove the extra values we added because we don't want to keep passing # them around, copying them etc. filled.pop("nlp", None) filled.pop("name", None) # Merge the final filled config with the raw config (including non- # interpolated variables) if raw_config: filled = filled.merge(raw_config) self._pipe_configs[name] = filled return resolved[factory_name] def create_pipe_from_source( self, source_name: str, source: "Language", *, name: str ) -> Tuple["Pipe", str]: """Create a pipeline component by copying it from an existing model. source_name (str): Name of the component in the source pipeline. source (Language): The source nlp object to copy from. name (str): Optional alternative name to use in current pipeline. RETURNS (Tuple[Callable, str]): The component and its factory name. """ # Check source type if not isinstance(source, Language): raise ValueError(Errors.E945.format(name=source_name, source=type(source))) # Check vectors, with faster checks first if ( self.vocab.vectors.shape != source.vocab.vectors.shape or self.vocab.vectors.key2row != source.vocab.vectors.key2row or self.vocab.vectors.to_bytes(exclude=["strings"]) != source.vocab.vectors.to_bytes(exclude=["strings"]) ): warnings.warn(Warnings.W113.format(name=source_name)) if source_name not in source.component_names: raise KeyError( Errors.E944.format( name=source_name, model=f"{source.meta["lang"]}_{source.meta["name"]}", opts=", ".join(source.component_names), ) ) pipe = source.get_pipe(source_name) # Make sure the source config is interpolated so we don't end up with # orphaned variables in our final config source_config = source.config.interpolate() pipe_config = util.copy_config(source_config["components"][source_name]) self._pipe_configs[name] = pipe_config if self.vocab.strings != source.vocab.strings: for s in source.vocab.strings: self.vocab.strings.add(s) return pipe, pipe_config["factory"] def add_pipe( self, factory_name: str, name: Optional[str] = None, *, before: Optional[Union[str, int]] = None, after: Optional[Union[str, int]] = None, first: Optional[bool] = None, last: Optional[bool] = None, source: Optional["Language"] = None, config: Dict[str, Any] = SimpleFrozenDict(), raw_config: Optional[Config] = None, validate: bool = True, ) -> "Pipe": """Add a component to the processing pipeline. Valid components are callables that take a `Doc` object, modify it and return it. Only one of before/after/first/last can be set. Default behaviour is "last". factory_name (str): Name of the component factory. name (str): Name of pipeline component. Overwrites existing component.name attribute if available. If no name is set and the component exposes no name attribute, component.__name__ is used. An error is raised if a name already exists in the pipeline. before (Union[str, int]): Name or index of the component to insert new component directly before. after (Union[str, int]): Name or index of the component to insert new component directly after. first (bool): If True, insert component first in the pipeline. last (bool): If True, insert component last in the pipeline. source (Language): Optional loaded nlp object to copy the pipeline component from. config (Dict[str, Any]): Config parameters to use for this component. Will be merged with default config, if available. raw_config (Optional[Config]): Internals: the non-interpolated config. validate (bool): Whether to validate the component config against the arguments and types expected by the factory. RETURNS (Pipe): The pipeline component. DOCS: https://spacy.io/api/language#add_pipe """ if not isinstance(factory_name, str): bad_val = repr(factory_name) err = Errors.E966.format(component=bad_val, name=name) raise ValueError(err) name = name if name is not None else factory_name if name in self.component_names: raise ValueError(Errors.E007.format(name=name, opts=self.component_names)) if source is not None: # We're loading the component from a model. After loading the # component, we know its real factory name pipe_component, factory_name = self.create_pipe_from_source( factory_name, source, name=name ) else: if not self.has_factory(factory_name): err = Errors.E002.format( name=factory_name, opts=", ".join(self.factory_names), method="add_pipe", lang=util.get_object_name(self), lang_code=self.lang, ) pipe_component = self.create_pipe( factory_name, name=name, config=config, raw_config=raw_config, validate=validate, ) pipe_index = self._get_pipe_index(before, after, first, last) self._pipe_meta[name] = self.get_factory_meta(factory_name) self._components.insert(pipe_index, (name, pipe_component)) return pipe_component def _get_pipe_index( self, before: Optional[Union[str, int]] = None, after: Optional[Union[str, int]] = None, first: Optional[bool] = None, last: Optional[bool] = None, ) -> int: """Determine where to insert a pipeline component based on the before/ after/first/last values. before (str): Name or index of the component to insert directly before. after (str): Name or index of component to insert directly after. first (bool): If True, insert component first in the pipeline. last (bool): If True, insert component last in the pipeline. RETURNS (int): The index of the new pipeline component. """ all_args = {"before": before, "after": after, "first": first, "last": last} if sum(arg is not None for arg in [before, after, first, last]) >= 2: raise ValueError( Errors.E006.format(args=all_args, opts=self.component_names) ) if last or not any(value is not None for value in [first, before, after]): return len(self._components) elif first: return 0 elif isinstance(before, str): if before not in self.component_names: raise ValueError( Errors.E001.format(name=before, opts=self.component_names) ) return self.component_names.index(before) elif isinstance(after, str): if after not in self.component_names: raise ValueError( Errors.E001.format(name=after, opts=self.component_names) ) return self.component_names.index(after) + 1 # We're only accepting indices referring to components that exist # (can't just do isinstance here because bools are instance of int, too) elif type(before) == int: if before >= len(self._components) or before < 0: err = Errors.E959.format( dir="before", idx=before, opts=self.component_names ) raise ValueError(err) return before elif type(after) == int: if after >= len(self._components) or after < 0: err = Errors.E959.format( dir="after", idx=after, opts=self.component_names ) raise ValueError(err) return after + 1 raise ValueError(Errors.E006.format(args=all_args, opts=self.component_names)) def has_pipe(self, name: str) -> bool: """Check if a component name is present in the pipeline. Equivalent to `name in nlp.pipe_names`. name (str): Name of the component. RETURNS (bool): Whether a component of the name exists in the pipeline. DOCS: https://spacy.io/api/language#has_pipe """ return name in self.pipe_names def replace_pipe( self, name: str, factory_name: str, *, config: Dict[str, Any] = SimpleFrozenDict(), validate: bool = True, ) -> "Pipe": """Replace a component in the pipeline. name (str): Name of the component to replace. factory_name (str): Factory name of replacement component. config (Optional[Dict[str, Any]]): Config parameters to use for this component. Will be merged with default config, if available. validate (bool): Whether to validate the component config against the arguments and types expected by the factory. RETURNS (Pipe): The new pipeline component. DOCS: https://spacy.io/api/language#replace_pipe """ if name not in self.component_names: raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names)) if hasattr(factory_name, "__call__"): err = Errors.E968.format(component=repr(factory_name), name=name) raise ValueError(err) # We need to delegate to Language.add_pipe here instead of just writing # to Language.pipeline to make sure the configs are handled correctly pipe_index = self.component_names.index(name) self.remove_pipe(name) if not len(self._components) or pipe_index == len(self._components): # we have no components to insert before/after, or we're replacing the last component return self.add_pipe( factory_name, name=name, config=config, validate=validate ) else: return self.add_pipe( factory_name, name=name, before=pipe_index, config=config, validate=validate, ) def rename_pipe(self, old_name: str, new_name: str) -> None: """Rename a pipeline component. old_name (str): Name of the component to rename. new_name (str): New name of the component. DOCS: https://spacy.io/api/language#rename_pipe """ if old_name not in self.component_names: raise ValueError( Errors.E001.format(name=old_name, opts=self.component_names) ) if new_name in self.component_names: raise ValueError( Errors.E007.format(name=new_name, opts=self.component_names) ) i = self.component_names.index(old_name) self._components[i] = (new_name, self._components[i][1]) self._pipe_meta[new_name] = self._pipe_meta.pop(old_name) self._pipe_configs[new_name] = self._pipe_configs.pop(old_name) # Make sure [initialize] config is adjusted if old_name in self._config["initialize"]["components"]: init_cfg = self._config["initialize"]["components"].pop(old_name) self._config["initialize"]["components"][new_name] = init_cfg def remove_pipe(self, name: str) -> Tuple[str, "Pipe"]: """Remove a component from the pipeline. name (str): Name of the component to remove. RETURNS (tuple): A `(name, component)` tuple of the removed component. DOCS: https://spacy.io/api/language#remove_pipe """ if name not in self.component_names: raise ValueError(Errors.E001.format(name=name, opts=self.component_names)) removed = self._components.pop(self.component_names.index(name)) # We're only removing the component itself from the metas/configs here # because factory may be used for something else self._pipe_meta.pop(name) self._pipe_configs.pop(name) self.meta.get("_sourced_vectors_hashes", {}).pop(name, None) # Make sure name is removed from the [initialize] config if name in self._config["initialize"]["components"]: self._config["initialize"]["components"].pop(name) # Make sure the name is also removed from the set of disabled components if name in self.disabled: self._disabled.remove(name) return removed def disable_pipe(self, name: str) -> None: """Disable a pipeline component. The component will still exist on the nlp object, but it won't be run as part of the pipeline. Does nothing if the component is already disabled. name (str): The name of the component to disable. """ if name not in self.component_names: raise ValueError(Errors.E001.format(name=name, opts=self.component_names)) self._disabled.add(name) def enable_pipe(self, name: str) -> None: """Enable a previously disabled pipeline component so it's run as part of the pipeline. Does nothing if the component is already enabled. name (str): The name of the component to enable. """ if name not in self.component_names: raise ValueError(Errors.E001.format(name=name, opts=self.component_names)) if name in self.disabled: self._disabled.remove(name) def __call__( self, text: Union[str, Doc], *, disable: Iterable[str] = SimpleFrozenList(), component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, ) -> Doc: """Apply the pipeline to some text. The text can span multiple sentences, and can contain arbitrary whitespace. Alignment into the original string is preserved. text (Union[str, Doc]): If `str`, the text to be processed. If `Doc`, the doc will be passed directly to the pipeline, skipping `Language.make_doc`. disable (List[str]): Names of the pipeline components to disable. component_cfg (Dict[str, dict]): An optional dictionary with extra keyword arguments for specific components. RETURNS (Doc): A container for accessing the annotations. DOCS: https://spacy.io/api/language#call """ doc = self._ensure_doc(text) if component_cfg is None: component_cfg = {} for name, proc in self.pipeline: if name in disable: continue if not hasattr(proc, "__call__"): raise ValueError(Errors.E003.format(component=type(proc), name=name)) error_handler = self.default_error_handler if hasattr(proc, "get_error_handler"): error_handler = proc.get_error_handler() try: doc = proc(doc, **component_cfg.get(name, {})) # type: ignore[call-arg] except KeyError as e: # This typically happens if a component is not initialized raise ValueError(Errors.E109.format(name=name)) from e except Exception as e: error_handler(name, proc, [doc], e) if doc is None: raise ValueError(Errors.E005.format(name=name)) return doc def disable_pipes(self, *names) -> "DisabledPipes": """Disable one or more pipeline components. If used as a context manager, the pipeline will be restored to the initial state at the end of the block. Otherwise, a DisabledPipes object is returned, that has a `.restore()` method you can use to undo your changes. This method has been deprecated since 3.0 """ warnings.warn(Warnings.W096, DeprecationWarning) if len(names) == 1 and isinstance(names[0], (list, tuple)): names = names[0] # type: ignore[assignment] # support list of names instead of spread return self.select_pipes(disable=names) def select_pipes( self, *, disable: Optional[Union[str, Iterable[str]]] = None, enable: Optional[Union[str, Iterable[str]]] = None, ) -> "DisabledPipes": """Disable one or more pipeline components. If used as a context manager, the pipeline will be restored to the initial state at the end of the block. Otherwise, a DisabledPipes object is returned, that has a `.restore()` method you can use to undo your changes. disable (str or iterable): The name(s) of the pipes to disable enable (str or iterable): The name(s) of the pipes to enable - all others will be disabled DOCS: https://spacy.io/api/language#select_pipes """ if enable is None and disable is None: raise ValueError(Errors.E991) if disable is not None and isinstance(disable, str): disable = [disable] if enable is not None: if isinstance(enable, str): enable = [enable] to_disable = [pipe for pipe in self.pipe_names if pipe not in enable] # raise an error if the enable and disable keywords are not consistent if disable is not None and disable != to_disable: raise ValueError( Errors.E992.format( enable=enable, disable=disable, names=self.pipe_names ) ) disable = to_disable assert disable is not None # DisabledPipes will restore the pipes in 'disable' when it's done, so we need to exclude # those pipes that were already disabled. disable = [d for d in disable if d not in self._disabled] return DisabledPipes(self, disable) def make_doc(self, text: str) -> Doc: """Turn a text into a Doc object. text (str): The text to process. RETURNS (Doc): The processed doc. """ if len(text) > self.max_length: raise ValueError( Errors.E088.format(length=len(text), max_length=self.max_length) ) return self.tokenizer(text) def _ensure_doc(self, doc_like: Union[str, Doc]) -> Doc: """Create a Doc if need be, or raise an error if the input is not a Doc or a string.""" if isinstance(doc_like, Doc): return doc_like if isinstance(doc_like, str): return self.make_doc(doc_like) raise ValueError(Errors.E866.format(type=type(doc_like))) def _ensure_doc_with_context(self, doc_like: Union[str, Doc], context: Any) -> Doc: """Create a Doc if need be and add as_tuples context, or raise an error if the input is not a Doc or a string.""" doc = self._ensure_doc(doc_like) doc._context = context return doc def update( self, examples: Iterable[Example], _: Optional[Any] = None, *, drop: float = 0.0, sgd: Optional[Optimizer] = None, losses: Optional[Dict[str, float]] = None, component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, exclude: Iterable[str] = SimpleFrozenList(), annotates: Iterable[str] = SimpleFrozenList(), ): """Update the models in the pipeline. examples (Iterable[Example]): A batch of examples _: Should not be set - serves to catch backwards-incompatible scripts. drop (float): The dropout rate. sgd (Optimizer): An optimizer. losses (Dict[str, float]): Dictionary to update with the loss, keyed by component. component_cfg (Dict[str, Dict]): Config parameters for specific pipeline components, keyed by component name. exclude (Iterable[str]): Names of components that shouldn't be updated. annotates (Iterable[str]): Names of components that should set annotations on the predicted examples after updating. RETURNS (Dict[str, float]): The updated losses dictionary DOCS: https://spacy.io/api/language#update """ if _ is not None: raise ValueError(Errors.E989) if losses is None: losses = {} if isinstance(examples, list) and len(examples) == 0: return losses validate_examples(examples, "Language.update") examples = _copy_examples(examples) if sgd is None: if self._optimizer is None: self._optimizer = self.create_optimizer() sgd = self._optimizer if component_cfg is None: component_cfg = {} pipe_kwargs = {} for i, (name, proc) in enumerate(self.pipeline): component_cfg.setdefault(name, {}) pipe_kwargs[name] = deepcopy(component_cfg[name]) component_cfg[name].setdefault("drop", drop) pipe_kwargs[name].setdefault("batch_size", self.batch_size) for name, proc in self.pipeline: # ignore statements are used here because mypy ignores hasattr if name not in exclude and hasattr(proc, "update"): proc.update(examples, sgd=None, losses=losses, **component_cfg[name]) # type: ignore if sgd not in (None, False): if ( name not in exclude and isinstance(proc, ty.TrainableComponent) and proc.is_trainable and proc.model not in (True, False, None) ): proc.finish_update(sgd) if name in annotates: for doc, eg in zip( _pipe( (eg.predicted for eg in examples), proc=proc, name=name, default_error_handler=self.default_error_handler, kwargs=pipe_kwargs[name], ), examples, ): eg.predicted = doc return losses def rehearse( self, examples: Iterable[Example], *, sgd: Optional[Optimizer] = None, losses: Optional[Dict[str, float]] = None, component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, exclude: Iterable[str] = SimpleFrozenList(), ) -> Dict[str, float]: """Make a "rehearsal" update to the models in the pipeline, to prevent forgetting. Rehearsal updates run an initial copy of the model over some data, and update the model so its current predictions are more like the initial ones. This is useful for keeping a pretrained model on-track, even if you're updating it with a smaller set of examples. examples (Iterable[Example]): A batch of `Example` objects. sgd (Optional[Optimizer]): An optimizer. component_cfg (Dict[str, Dict]): Config parameters for specific pipeline components, keyed by component name. exclude (Iterable[str]): Names of components that shouldn't be updated. RETURNS (dict): Results from the update. EXAMPLE: >>> raw_text_batches = minibatch(raw_texts) >>> for labelled_batch in minibatch(examples): >>> nlp.update(labelled_batch) >>> raw_batch = [Example.from_dict(nlp.make_doc(text), {}) for text in next(raw_text_batches)] >>> nlp.rehearse(raw_batch) DOCS: https://spacy.io/api/language#rehearse """ if losses is None: losses = {} if isinstance(examples, list) and len(examples) == 0: return losses validate_examples(examples, "Language.rehearse") if sgd is None: if self._optimizer is None: self._optimizer = self.create_optimizer() sgd = self._optimizer pipes = list(self.pipeline) random.shuffle(pipes) if component_cfg is None: component_cfg = {} grads = {} def get_grads(W, dW, key=None): grads[key] = (W, dW) get_grads.learn_rate = sgd.learn_rate # type: ignore[attr-defined, union-attr] get_grads.b1 = sgd.b1 # type: ignore[attr-defined, union-attr] get_grads.b2 = sgd.b2 # type: ignore[attr-defined, union-attr] for name, proc in pipes: if name in exclude or not hasattr(proc, "rehearse"): continue grads = {} proc.rehearse( # type: ignore[attr-defined] examples, sgd=get_grads, losses=losses, **component_cfg.get(name, {}) ) for key, (W, dW) in grads.items(): sgd(W, dW, key=key) # type: ignore[call-arg, misc] return losses def begin_training( self, get_examples: Optional[Callable[[], Iterable[Example]]] = None, *, sgd: Optional[Optimizer] = None, ) -> Optimizer: warnings.warn(Warnings.W089, DeprecationWarning) return self.initialize(get_examples, sgd=sgd) def initialize( self, get_examples: Optional[Callable[[], Iterable[Example]]] = None, *, sgd: Optional[Optimizer] = None, ) -> Optimizer: """Initialize the pipe for training, using data examples if available. get_examples (Callable[[], Iterable[Example]]): Optional function that returns gold-standard Example objects. sgd (Optional[Optimizer]): An optimizer to use for updates. If not provided, will be created using the .create_optimizer() method. RETURNS (thinc.api.Optimizer): The optimizer. DOCS: https://spacy.io/api/language#initialize """ if get_examples is None: util.logger.debug( "No 'get_examples' callback provided to 'Language.initialize', creating dummy examples" ) doc = Doc(self.vocab, words=["x", "y", "z"]) get_examples = lambda: [Example.from_dict(doc, {})] if not hasattr(get_examples, "__call__"): err = Errors.E930.format( method="Language.initialize", obj=type(get_examples) ) raise TypeError(err) # Make sure the config is interpolated so we can resolve subsections config = self.config.interpolate() # These are the settings provided in the [initialize] block in the config I = registry.resolve(config["initialize"], schema=ConfigSchemaInit) before_init = I["before_init"] if before_init is not None: before_init(self) try: init_vocab( self, data=I["vocab_data"], lookups=I["lookups"], vectors=I["vectors"] ) except IOError: raise IOError(Errors.E884.format(vectors=I["vectors"])) if self.vocab.vectors.shape[1] >= 1: ops = get_current_ops() self.vocab.vectors.to_ops(ops) if hasattr(self.tokenizer, "initialize"): tok_settings = validate_init_settings( self.tokenizer.initialize, # type: ignore[union-attr] I["tokenizer"], section="tokenizer", name="tokenizer", ) self.tokenizer.initialize(get_examples, nlp=self, **tok_settings) # type: ignore[union-attr] for name, proc in self.pipeline: if isinstance(proc, ty.InitializableComponent): p_settings = I["components"].get(name, {}) p_settings = validate_init_settings( proc.initialize, p_settings, section="components", name=name ) proc.initialize(get_examples, nlp=self, **p_settings) pretrain_cfg = config.get("pretraining") if pretrain_cfg: P = registry.resolve(pretrain_cfg, schema=ConfigSchemaPretrain) init_tok2vec(self, P, I) self._link_components() self._optimizer = sgd if sgd is not None: self._optimizer = sgd elif self._optimizer is None: self._optimizer = self.create_optimizer() after_init = I["after_init"] if after_init is not None: after_init(self) return self._optimizer def resume_training(self, *, sgd: Optional[Optimizer] = None) -> Optimizer: """Continue training a pretrained model. Create and return an optimizer, and initialize "rehearsal" for any pipeline component that has a .rehearse() method. Rehearsal is used to prevent models from "forgetting" their initialized "knowledge". To perform rehearsal, collect samples of text you want the models to retain performance on, and call nlp.rehearse() with a batch of Example objects. RETURNS (Optimizer): The optimizer. DOCS: https://spacy.io/api/language#resume_training """ ops = get_current_ops() if self.vocab.vectors.shape[1] >= 1: self.vocab.vectors.to_ops(ops) for name, proc in self.pipeline: if hasattr(proc, "_rehearsal_model"): proc._rehearsal_model = deepcopy(proc.model) # type: ignore[attr-defined] if sgd is not None: self._optimizer = sgd elif self._optimizer is None: self._optimizer = self.create_optimizer() return self._optimizer def set_error_handler( self, error_handler: Callable[[str, "Pipe", List[Doc], Exception], NoReturn], ): """Set an error handler object for all the components in the pipeline that implement a set_error_handler function. error_handler (Callable[[str, Pipe, List[Doc], Exception], NoReturn]): Function that deals with a failing batch of documents. This callable function should take in the component's name, the component itself, the offending batch of documents, and the exception that was thrown. DOCS: https://spacy.io/api/language#set_error_handler """ self.default_error_handler = error_handler for name, pipe in self.pipeline: if hasattr(pipe, "set_error_handler"): pipe.set_error_handler(error_handler) def evaluate( self, examples: Iterable[Example], *, batch_size: Optional[int] = None, scorer: Optional[Scorer] = None, component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, scorer_cfg: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """Evaluate a model's pipeline components. examples (Iterable[Example]): `Example` objects. batch_size (Optional[int]): Batch size to use. scorer (Optional[Scorer]): Scorer to use. If not passed in, a new one will be created. component_cfg (dict): An optional dictionary with extra keyword arguments for specific components. scorer_cfg (dict): An optional dictionary with extra keyword arguments for the scorer. RETURNS (Scorer): The scorer containing the evaluation results. DOCS: https://spacy.io/api/language#evaluate """ examples = list(examples) validate_examples(examples, "Language.evaluate") examples = _copy_examples(examples) if batch_size is None: batch_size = self.batch_size if component_cfg is None: component_cfg = {} if scorer_cfg is None: scorer_cfg = {} if scorer is None: kwargs = dict(scorer_cfg) kwargs.setdefault("nlp", self) scorer = Scorer(**kwargs) # reset annotation in predicted docs and time tokenization start_time = timer() # this is purely for timing for eg in examples: self.make_doc(eg.reference.text) # apply all pipeline components docs = self.pipe( (eg.predicted for eg in examples), batch_size=batch_size, component_cfg=component_cfg, ) for eg, doc in zip(examples, docs): eg.predicted = doc end_time = timer() results = scorer.score(examples) n_words = sum(len(eg.predicted) for eg in examples) results["speed"] = n_words / (end_time - start_time) return results def create_optimizer(self): """Create an optimizer, usually using the [training.optimizer] config.""" subconfig = {"optimizer": self.config["training"]["optimizer"]} return registry.resolve(subconfig)["optimizer"] @contextmanager def use_params(self, params: Optional[dict]): """Replace weights of models in the pipeline with those provided in the params dictionary. Can be used as a contextmanager, in which case, models go back to their original weights after the block. params (dict): A dictionary of parameters keyed by model ID. EXAMPLE: >>> with nlp.use_params(optimizer.averages): >>> nlp.to_disk("/tmp/checkpoint") DOCS: https://spacy.io/api/language#use_params """ if not params: yield else: contexts = [ pipe.use_params(params) # type: ignore[attr-defined] for name, pipe in self.pipeline if hasattr(pipe, "use_params") and hasattr(pipe, "model") ] # TODO: Having trouble with contextlib # Workaround: these aren't actually context managers atm. for context in contexts: try: next(context) except StopIteration: pass yield for context in contexts: try: next(context) except StopIteration: pass @overload def pipe( self, texts: Iterable[Union[str, Doc]], *, as_tuples: Literal[False] = ..., batch_size: Optional[int] = ..., disable: Iterable[str] = ..., component_cfg: Optional[Dict[str, Dict[str, Any]]] = ..., n_process: int = ..., ) -> Iterator[Doc]: ... @overload def pipe( # noqa: F811 self, texts: Iterable[Tuple[Union[str, Doc], _AnyContext]], *, as_tuples: Literal[True] = ..., batch_size: Optional[int] = ..., disable: Iterable[str] = ..., component_cfg: Optional[Dict[str, Dict[str, Any]]] = ..., n_process: int = ..., ) -> Iterator[Tuple[Doc, _AnyContext]]: ... def pipe( # noqa: F811 self, texts: Union[ Iterable[Union[str, Doc]], Iterable[Tuple[Union[str, Doc], _AnyContext]] ], *, as_tuples: bool = False, batch_size: Optional[int] = None, disable: Iterable[str] = SimpleFrozenList(), component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, n_process: int = 1, ) -> Union[Iterator[Doc], Iterator[Tuple[Doc, _AnyContext]]]: """Process texts as a stream, and yield `Doc` objects in order. texts (Iterable[Union[str, Doc]]): A sequence of texts or docs to process. as_tuples (bool): If set to True, inputs should be a sequence of (text, context) tuples. Output will then be a sequence of (doc, context) tuples. Defaults to False. batch_size (Optional[int]): The number of texts to buffer. disable (List[str]): Names of the pipeline components to disable. component_cfg (Dict[str, Dict]): An optional dictionary with extra keyword arguments for specific components. n_process (int): Number of processors to process texts. If -1, set `multiprocessing.cpu_count()`. YIELDS (Doc): Documents in the order of the original text. DOCS: https://spacy.io/api/language#pipe """ # Handle texts with context as tuples if as_tuples: texts = cast(Iterable[Tuple[Union[str, Doc], _AnyContext]], texts) docs_with_contexts = ( self._ensure_doc_with_context(text, context) for text, context in texts ) docs = self.pipe( docs_with_contexts, batch_size=batch_size, disable=disable, n_process=n_process, component_cfg=component_cfg, ) for doc in docs: context = doc._context doc._context = None yield (doc, context) return texts = cast(Iterable[Union[str, Doc]], texts) # Set argument defaults if n_process == -1: n_process = mp.cpu_count() if component_cfg is None: component_cfg = {} if batch_size is None: batch_size = self.batch_size pipes = ( [] ) # contains functools.partial objects to easily create multiprocess worker. for name, proc in self.pipeline: if name in disable: continue kwargs = component_cfg.get(name, {}) # Allow component_cfg to overwrite the top-level kwargs. kwargs.setdefault("batch_size", batch_size) f = functools.partial( _pipe, proc=proc, name=name, kwargs=kwargs, default_error_handler=self.default_error_handler, ) pipes.append(f) if n_process != 1: if self._has_gpu_model(disable): warnings.warn(Warnings.W114) docs = self._multiprocessing_pipe(texts, pipes, n_process, batch_size) else: # if n_process == 1, no processes are forked. docs = (self._ensure_doc(text) for text in texts) for pipe in pipes: docs = pipe(docs) for doc in docs: yield doc def _has_gpu_model(self, disable: Iterable[str]): for name, proc in self.pipeline: is_trainable = hasattr(proc, "is_trainable") and proc.is_trainable # type: ignore if name in disable or not is_trainable: continue if hasattr(proc, "model") and hasattr(proc.model, "ops") and isinstance(proc.model.ops, CupyOps): # type: ignore return True return False def _multiprocessing_pipe( self, texts: Iterable[Union[str, Doc]], pipes: Iterable[Callable[..., Iterator[Doc]]], n_process: int, batch_size: int, ) -> Iterator[Doc]: # raw_texts is used later to stop iteration. texts, raw_texts = itertools.tee(texts) # for sending texts to worker texts_q: List[mp.Queue] = [mp.Queue() for _ in range(n_process)] # for receiving byte-encoded docs from worker bytedocs_recv_ch, bytedocs_send_ch = zip( *[mp.Pipe(False) for _ in range(n_process)] ) batch_texts = util.minibatch(texts, batch_size) # Sender sends texts to the workers. # This is necessary to properly handle infinite length of texts. # (In this case, all data cannot be sent to the workers at once) sender = _Sender(batch_texts, texts_q, chunk_size=n_process) # send twice to make process busy sender.send() sender.send() procs = [ mp.Process( target=_apply_pipes, args=(self._ensure_doc, pipes, rch, sch, Underscore.get_state()), ) for rch, sch in zip(texts_q, bytedocs_send_ch) ] for proc in procs: proc.start() # Cycle channels not to break the order of docs. # The received object is a batch of byte-encoded docs, so flatten them with chain.from_iterable. byte_tuples = chain.from_iterable( recv.recv() for recv in cycle(bytedocs_recv_ch) ) try: for i, (_, (byte_doc, byte_context, byte_error)) in enumerate( zip(raw_texts, byte_tuples), 1 ): if byte_doc is not None: doc = Doc(self.vocab).from_bytes(byte_doc) doc._context = byte_context yield doc elif byte_error is not None: error = srsly.msgpack_loads(byte_error) self.default_error_handler( None, None, None, ValueError(Errors.E871.format(error=error)) ) if i % batch_size == 0: # tell `sender` that one batch was consumed. sender.step() finally: for proc in procs: proc.terminate() def _link_components(self) -> None: """Register 'listeners' within pipeline components, to allow them to effectively share weights. """ # I had thought, "Why do we do this inside the Language object? Shouldn't # it be the tok2vec/transformer/etc's job? # The problem is we need to do it during deserialization...And the # components don't receive the pipeline then. So this does have to be # here :( for i, (name1, proc1) in enumerate(self.pipeline): if isinstance(proc1, ty.ListenedToComponent): for name2, proc2 in self.pipeline[i + 1 :]: proc1.find_listeners(proc2) @classmethod def from_config( cls, config: Union[Dict[str, Any], Config] = {}, *, vocab: Union[Vocab, bool] = True, disable: Iterable[str] = SimpleFrozenList(), exclude: Iterable[str] = SimpleFrozenList(), meta: Dict[str, Any] = SimpleFrozenDict(), auto_fill: bool = True, validate: bool = True, ) -> "Language": """Create the nlp object from a loaded config. Will set up the tokenizer and language data, add pipeline components etc. If no config is provided, the default config of the given language is used. config (Dict[str, Any] / Config): The loaded config. vocab (Vocab): A Vocab object. If True, a vocab is created. disable (Iterable[str]): Names of pipeline components to disable. Disabled pipes will be loaded but they won't be run unless you explicitly enable them by calling nlp.enable_pipe. exclude (Iterable[str]): Names of pipeline components to exclude. Excluded components won't be loaded. meta (Dict[str, Any]): Meta overrides for nlp.meta. auto_fill (bool): Automatically fill in missing values in config based on defaults and function argument annotations. validate (bool): Validate the component config and arguments against the types expected by the factory. RETURNS (Language): The initialized Language class. DOCS: https://spacy.io/api/language#from_config """ if auto_fill: config = Config( cls.default_config, section_order=CONFIG_SECTION_ORDER ).merge(config) if "nlp" not in config: raise ValueError(Errors.E985.format(config=config)) config_lang = config["nlp"].get("lang") if config_lang is not None and config_lang != cls.lang: raise ValueError( Errors.E958.format( bad_lang_code=config["nlp"]["lang"], lang_code=cls.lang, lang=util.get_object_name(cls), ) ) config["nlp"]["lang"] = cls.lang # This isn't very elegant, but we remove the [components] block here to prevent # it from getting resolved (causes problems because we expect to pass in # the nlp and name args for each component). If we're auto-filling, we're # using the nlp.config with all defaults. config = util.copy_config(config) orig_pipeline = config.pop("components", {}) orig_pretraining = config.pop("pretraining", None) config["components"] = {} if auto_fill: filled = registry.fill(config, validate=validate, schema=ConfigSchema) else: filled = config filled["components"] = orig_pipeline config["components"] = orig_pipeline if orig_pretraining is not None: filled["pretraining"] = orig_pretraining config["pretraining"] = orig_pretraining resolved_nlp = registry.resolve( filled["nlp"], validate=validate, schema=ConfigSchemaNlp ) create_tokenizer = resolved_nlp["tokenizer"] before_creation = resolved_nlp["before_creation"] after_creation = resolved_nlp["after_creation"] after_pipeline_creation = resolved_nlp["after_pipeline_creation"] lang_cls = cls if before_creation is not None: lang_cls = before_creation(cls) if ( not isinstance(lang_cls, type) or not issubclass(lang_cls, cls) or lang_cls is not cls ): raise ValueError(Errors.E943.format(value=type(lang_cls))) # Warn about require_gpu usage in jupyter notebook warn_if_jupyter_cupy() # Note that we don't load vectors here, instead they get loaded explicitly # inside stuff like the spacy train function. If we loaded them here, # then we would load them twice at runtime: once when we make from config, # and then again when we load from disk. nlp = lang_cls(vocab=vocab, create_tokenizer=create_tokenizer, meta=meta) if after_creation is not None: nlp = after_creation(nlp) if not isinstance(nlp, cls): raise ValueError(Errors.E942.format(name="creation", value=type(nlp))) # To create the components we need to use the final interpolated config # so all values are available (if component configs use variables). # Later we replace the component config with the raw config again. interpolated = filled.interpolate() if not filled.is_interpolated else filled pipeline = interpolated.get("components", {}) sourced = util.get_sourced_components(interpolated) # If components are loaded from a source (existing models), we cache # them here so they're only loaded once source_nlps = {} source_nlp_vectors_hashes = {} vocab_b = None for pipe_name in config["nlp"]["pipeline"]: if pipe_name not in pipeline: opts = ", ".join(pipeline.keys()) raise ValueError(Errors.E956.format(name=pipe_name, opts=opts)) pipe_cfg = util.copy_config(pipeline[pipe_name]) raw_config = Config(filled["components"][pipe_name]) if pipe_name not in exclude: if "factory" not in pipe_cfg and "source" not in pipe_cfg: err = Errors.E984.format(name=pipe_name, config=pipe_cfg) raise ValueError(err) if "factory" in pipe_cfg: factory = pipe_cfg.pop("factory") # The pipe name (key in the config) here is the unique name # of the component, not necessarily the factory nlp.add_pipe( factory, name=pipe_name, config=pipe_cfg, validate=validate, raw_config=raw_config, ) else: # We need the sourced components to reference the same # vocab without modifying the current vocab state **AND** # we still want to load the source model vectors to perform # the vectors check. Since the source vectors clobber the # current ones, we save the original vocab state and # restore after this loop. Existing strings are preserved # during deserialization, so they do not need any # additional handling. if vocab_b is None: vocab_b = nlp.vocab.to_bytes(exclude=["lookups", "strings"]) model = pipe_cfg["source"] if model not in source_nlps: # Load with the same vocab, adding any strings source_nlps[model] = util.load_model( model, vocab=nlp.vocab, exclude=["lookups"] ) source_name = pipe_cfg.get("component", pipe_name) listeners_replaced = False if "replace_listeners" in pipe_cfg: for name, proc in source_nlps[model].pipeline: if source_name in getattr(proc, "listening_components", []): source_nlps[model].replace_listeners( name, source_name, pipe_cfg["replace_listeners"] ) listeners_replaced = True with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="\\[W113\\]") nlp.add_pipe( source_name, source=source_nlps[model], name=pipe_name ) if model not in source_nlp_vectors_hashes: source_nlp_vectors_hashes[model] = hash( source_nlps[model].vocab.vectors.to_bytes( exclude=["strings"] ) ) if "_sourced_vectors_hashes" not in nlp.meta: nlp.meta["_sourced_vectors_hashes"] = {} nlp.meta["_sourced_vectors_hashes"][ pipe_name ] = source_nlp_vectors_hashes[model] # Delete from cache if listeners were replaced if listeners_replaced: del source_nlps[model] # Restore the original vocab after sourcing if necessary if vocab_b is not None: nlp.vocab.from_bytes(vocab_b) disabled_pipes = [*config["nlp"]["disabled"], *disable] nlp._disabled = set(p for p in disabled_pipes if p not in exclude) nlp.batch_size = config["nlp"]["batch_size"] nlp.config = filled if auto_fill else config if after_pipeline_creation is not None: nlp = after_pipeline_creation(nlp) if not isinstance(nlp, cls): raise ValueError( Errors.E942.format(name="pipeline_creation", value=type(nlp)) ) # Detect components with listeners that are not frozen consistently for name, proc in nlp.pipeline: if isinstance(proc, ty.ListenedToComponent): # Remove listeners not in the pipeline listener_names = proc.listening_components unused_listener_names = [ ll for ll in listener_names if ll not in nlp.pipe_names ] for listener_name in unused_listener_names: for listener in proc.listener_map.get(listener_name, []): proc.remove_listener(listener, listener_name) for listener_name in proc.listening_components: # e.g. tok2vec/transformer # If it's a component sourced from another pipeline, we check if # the tok2vec listeners should be replaced with standalone tok2vec # models (e.g. so component can be frozen without its performance # degrading when other components/tok2vec are updated) paths = sourced.get(listener_name, {}).get("replace_listeners", []) if paths: nlp.replace_listeners(name, listener_name, paths) return nlp def replace_listeners( self, tok2vec_name: str, pipe_name: str, listeners: Iterable[str], ) -> None: """Find listener layers (connecting to a token-to-vector embedding component) of a given pipeline component model and replace them with a standalone copy of the token-to-vector layer. This can be useful when training a pipeline with components sourced from an existing pipeline: if multiple components (e.g. tagger, parser, NER) listen to the same tok2vec component, but some of them are frozen and not updated, their performance may degrade significally as the tok2vec component is updated with new data. To prevent this, listeners can be replaced with a standalone tok2vec layer that is owned by the component and doesn't change if the component isn't updated. tok2vec_name (str): Name of the token-to-vector component, typically "tok2vec" or "transformer". pipe_name (str): Name of pipeline component to replace listeners for. listeners (Iterable[str]): The paths to the listeners, relative to the component config, e.g. ["model.tok2vec"]. Typically, implementations will only connect to one tok2vec component, [model.tok2vec], but in theory, custom models can use multiple listeners. The value here can either be an empty list to not replace any listeners, or a complete (!) list of the paths to all listener layers used by the model. DOCS: https://spacy.io/api/language#replace_listeners """ if tok2vec_name not in self.pipe_names: err = Errors.E889.format( tok2vec=tok2vec_name, name=pipe_name, unknown=tok2vec_name, opts=", ".join(self.pipe_names), ) raise ValueError(err) if pipe_name not in self.pipe_names: err = Errors.E889.format( tok2vec=tok2vec_name, name=pipe_name, unknown=pipe_name, opts=", ".join(self.pipe_names), ) raise ValueError(err) tok2vec = self.get_pipe(tok2vec_name) tok2vec_cfg = self.get_pipe_config(tok2vec_name) if not isinstance(tok2vec, ty.ListenedToComponent): raise ValueError(Errors.E888.format(name=tok2vec_name, pipe=type(tok2vec))) tok2vec_model = tok2vec.model pipe_listeners = tok2vec.listener_map.get(pipe_name, []) pipe = self.get_pipe(pipe_name) pipe_cfg = self._pipe_configs[pipe_name] if listeners: util.logger.debug(f"Replacing listeners of component '{pipe_name}'") if len(list(listeners)) != len(pipe_listeners): # The number of listeners defined in the component model doesn't # match the listeners to replace, so we won't be able to update # the nodes and generate a matching config err = Errors.E887.format( name=pipe_name, tok2vec=tok2vec_name, paths=listeners, n_listeners=len(pipe_listeners), ) raise ValueError(err) # Update the config accordingly by copying the tok2vec model to all # sections defined in the listener paths for listener_path in listeners: # Check if the path actually exists in the config try: util.dot_to_object(pipe_cfg, listener_path) except KeyError: err = Errors.E886.format( name=pipe_name, tok2vec=tok2vec_name, path=listener_path ) raise ValueError(err) new_config = tok2vec_cfg["model"] if "replace_listener_cfg" in tok2vec_model.attrs: replace_func = tok2vec_model.attrs["replace_listener_cfg"] new_config = replace_func( tok2vec_cfg["model"], pipe_cfg["model"]["tok2vec"] ) util.set_dot_to_object(pipe_cfg, listener_path, new_config) # Go over the listener layers and replace them for listener in pipe_listeners: new_model = tok2vec_model.copy() if "replace_listener" in tok2vec_model.attrs: new_model = tok2vec_model.attrs["replace_listener"](new_model) util.replace_model_node(pipe.model, listener, new_model) # type: ignore[attr-defined] tok2vec.remove_listener(listener, pipe_name) def to_disk( self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList() ) -> None: """Save the current state to a directory. If a model is loaded, this will include the model. path (str / Path): Path to a directory, which will be created if it doesn't exist. exclude (Iterable[str]): Names of components or serialization fields to exclude. DOCS: https://spacy.io/api/language#to_disk """ path = util.ensure_path(path) serializers = {} serializers["tokenizer"] = lambda p: self.tokenizer.to_disk( # type: ignore[union-attr] p, exclude=["vocab"] ) serializers["meta.json"] = lambda p: srsly.write_json(p, self.meta) serializers["config.cfg"] = lambda p: self.config.to_disk(p) for name, proc in self._components: if name in exclude: continue if not hasattr(proc, "to_disk"): continue serializers[name] = lambda p, proc=proc: proc.to_disk(p, exclude=["vocab"]) # type: ignore[misc] serializers["vocab"] = lambda p: self.vocab.to_disk(p, exclude=exclude) util.to_disk(path, serializers, exclude) def from_disk( self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList(), overrides: Dict[str, Any] = SimpleFrozenDict(), ) -> "Language": """Loads state from a directory. Modifies the object in place and returns it. If the saved `Language` object contains a model, the model will be loaded. path (str / Path): A path to a directory. exclude (Iterable[str]): Names of components or serialization fields to exclude. RETURNS (Language): The modified `Language` object. DOCS: https://spacy.io/api/language#from_disk """ def deserialize_meta(path: Path) -> None: if path.exists(): data = srsly.read_json(path) self.meta.update(data) # self.meta always overrides meta["vectors"] with the metadata # from self.vocab.vectors, so set the name directly self.vocab.vectors.name = data.get("vectors", {}).get("name") def deserialize_vocab(path: Path) -> None: if path.exists(): self.vocab.from_disk(path, exclude=exclude) path = util.ensure_path(path) deserializers = {} if Path(path / "config.cfg").exists(): # type: ignore[operator] deserializers["config.cfg"] = lambda p: self.config.from_disk( p, interpolate=False, overrides=overrides ) deserializers["meta.json"] = deserialize_meta # type: ignore[assignment] deserializers["vocab"] = deserialize_vocab # type: ignore[assignment] deserializers["tokenizer"] = lambda p: self.tokenizer.from_disk( # type: ignore[union-attr] p, exclude=["vocab"] ) for name, proc in self._components: if name in exclude: continue if not hasattr(proc, "from_disk"): continue deserializers[name] = lambda p, proc=proc: proc.from_disk( # type: ignore[misc] p, exclude=["vocab"] ) if not (path / "vocab").exists() and "vocab" not in exclude: # type: ignore[operator] # Convert to list here in case exclude is (default) tuple exclude = list(exclude) + ["vocab"] util.from_disk(path, deserializers, exclude) # type: ignore[arg-type] self._path = path # type: ignore[assignment] self._link_components() return self def to_bytes(self, *, exclude: Iterable[str] = SimpleFrozenList()) -> bytes: """Serialize the current state to a binary string. exclude (Iterable[str]): Names of components or serialization fields to exclude. RETURNS (bytes): The serialized form of the `Language` object. DOCS: https://spacy.io/api/language#to_bytes """ serializers: Dict[str, Callable[[], bytes]] = {} serializers["vocab"] = lambda: self.vocab.to_bytes(exclude=exclude) serializers["tokenizer"] = lambda: self.tokenizer.to_bytes(exclude=["vocab"]) # type: ignore[union-attr] serializers["meta.json"] = lambda: srsly.json_dumps(self.meta) serializers["config.cfg"] = lambda: self.config.to_bytes() for name, proc in self._components: if name in exclude: continue if not hasattr(proc, "to_bytes"): continue serializers[name] = lambda proc=proc: proc.to_bytes(exclude=["vocab"]) # type: ignore[misc] return util.to_bytes(serializers, exclude) def from_bytes( self, bytes_data: bytes, *, exclude: Iterable[str] = SimpleFrozenList() ) -> "Language": """Load state from a binary string. bytes_data (bytes): The data to load from. exclude (Iterable[str]): Names of components or serialization fields to exclude. RETURNS (Language): The `Language` object. DOCS: https://spacy.io/api/language#from_bytes """ def deserialize_meta(b): data = srsly.json_loads(b) self.meta.update(data) # self.meta always overrides meta["vectors"] with the metadata # from self.vocab.vectors, so set the name directly self.vocab.vectors.name = data.get("vectors", {}).get("name") deserializers: Dict[str, Callable[[bytes], Any]] = {} deserializers["config.cfg"] = lambda b: self.config.from_bytes( b, interpolate=False ) deserializers["meta.json"] = deserialize_meta deserializers["vocab"] = lambda b: self.vocab.from_bytes(b, exclude=exclude) deserializers["tokenizer"] = lambda b: self.tokenizer.from_bytes( # type: ignore[union-attr] b, exclude=["vocab"] ) for name, proc in self._components: if name in exclude: continue if not hasattr(proc, "from_bytes"): continue deserializers[name] = lambda b, proc=proc: proc.from_bytes( # type: ignore[misc] b, exclude=["vocab"] ) util.from_bytes(bytes_data, deserializers, exclude) self._link_components() return self @dataclass class FactoryMeta: """Dataclass containing information about a component and its defaults provided by the @Language.component or @Language.factory decorator. It's created whenever a component is defined and stored on the Language class for each component instance and factory instance. """ factory: str default_config: Optional[Dict[str, Any]] = None # noqa: E704 assigns: Iterable[str] = tuple() requires: Iterable[str] = tuple() retokenizes: bool = False scores: Iterable[str] = tuple() default_score_weights: Optional[Dict[str, Optional[float]]] = None # noqa: E704 class DisabledPipes(list): """Manager for temporary pipeline disabling.""" def __init__(self, nlp: Language, names: List[str]) -> None: self.nlp = nlp self.names = names for name in self.names: self.nlp.disable_pipe(name) list.__init__(self) self.extend(self.names) def __enter__(self): return self def __exit__(self, *args): self.restore() def restore(self) -> None: """Restore the pipeline to its state when DisabledPipes was created.""" for name in self.names: if name not in self.nlp.component_names: raise ValueError(Errors.E008.format(name=name)) self.nlp.enable_pipe(name) self[:] = [] def _copy_examples(examples: Iterable[Example]) -> List[Example]: """Make a copy of a batch of examples, copying the predicted Doc as well. This is used in contexts where we need to take ownership of the examples so that they can be mutated, for instance during Language.evaluate and Language.update. """ return [Example(eg.x.copy(), eg.y) for eg in examples] def _apply_pipes( ensure_doc: Callable[[Union[str, Doc]], Doc], pipes: Iterable[Callable[..., Iterator[Doc]]], receiver, sender, underscore_state: Tuple[dict, dict, dict], ) -> None: """Worker for Language.pipe ensure_doc (Callable[[Union[str, Doc]], Doc]): Function to create Doc from text or raise an error if the input is neither a Doc nor a string. pipes (Iterable[Pipe]): The components to apply. receiver (multiprocessing.Connection): Pipe to receive text. Usually created by `multiprocessing.Pipe()` sender (multiprocessing.Connection): Pipe to send doc. Usually created by `multiprocessing.Pipe()` underscore_state (Tuple[dict, dict, dict]): The data in the Underscore class of the parent. """ Underscore.load_state(underscore_state) while True: try: texts = receiver.get() docs = (ensure_doc(text) for text in texts) for pipe in pipes: docs = pipe(docs) # type: ignore[arg-type, assignment] # Connection does not accept unpickable objects, so send list. byte_docs = [(doc.to_bytes(), doc._context, None) for doc in docs] padding = [(None, None, None)] * (len(texts) - len(byte_docs)) sender.send(byte_docs + padding) # type: ignore[operator] except Exception: error_msg = [(None, None, srsly.msgpack_dumps(traceback.format_exc()))] padding = [(None, None, None)] * (len(texts) - 1) sender.send(error_msg + padding) class _Sender: """Util for sending data to multiprocessing workers in Language.pipe""" def __init__( self, data: Iterable[Any], queues: List[mp.Queue], chunk_size: int ) -> None: self.data = iter(data) self.queues = iter(cycle(queues)) self.chunk_size = chunk_size self.count = 0 def send(self) -> None: """Send chunk_size items from self.data to channels.""" for item, q in itertools.islice( zip(self.data, cycle(self.queues)), self.chunk_size ): # cycle channels so that distribute the texts evenly q.put(item) def step(self) -> None: """Tell sender that comsumed one item. Data is sent to the workers after every chunk_size calls. """ self.count += 1 if self.count >= self.chunk_size: self.count = 0 self.send()
from typing import Iterator, Optional, Any, Dict, Callable, Iterable from typing import Union, Tuple, List, Set, Pattern, Sequence from typing import NoReturn, TYPE_CHECKING, TypeVar, cast, overload from dataclasses import dataclass import random import itertools import functools from contextlib import contextmanager from copy import deepcopy from pathlib import Path import warnings from thinc.api import get_current_ops, Config, CupyOps, Optimizer import srsly import multiprocessing as mp from itertools import chain, cycle from timeit import default_timer as timer import traceback from . import ty from .tokens.underscore import Underscore from .vocab import Vocab, create_vocab from .pipe_analysis import validate_attrs, analyze_pipes, print_pipe_analysis from .training import Example, validate_examples from .training.initialize import init_vocab, init_tok2vec from .scorer import Scorer from .util import registry, SimpleFrozenList, _pipe, raise_error from .util import SimpleFrozenDict, combine_score_weights, CONFIG_SECTION_ORDER from .util import warn_if_jupyter_cupy from .lang.tokenizer_exceptions import URL_MATCH, BASE_EXCEPTIONS from .lang.punctuation import TOKENIZER_PREFIXES, TOKENIZER_SUFFIXES from .lang.punctuation import TOKENIZER_INFIXES from .tokens import Doc from .tokenizer import Tokenizer from .errors import Errors, Warnings from .schemas import ConfigSchema, ConfigSchemaNlp, ConfigSchemaInit from .schemas import ConfigSchemaPretrain, validate_init_settings from .git_info import GIT_VERSION from . import util from . import about from .lookups import load_lookups from .compat import Literal if TYPE_CHECKING: from .pipeline import Pipe # noqa: F401 # This is the base config will all settings (training etc.) DEFAULT_CONFIG_PATH = Path(__file__).parent / "default_config.cfg" DEFAULT_CONFIG = util.load_config(DEFAULT_CONFIG_PATH) # This is the base config for the [pretraining] block and currently not included # in the main config and only added via the 'init fill-config' command DEFAULT_CONFIG_PRETRAIN_PATH = Path(__file__).parent / "default_config_pretraining.cfg" # Type variable for contexts piped with documents _AnyContext = TypeVar("_AnyContext") class BaseDefaults: """Language data defaults, available via Language.Defaults. Can be overwritten by language subclasses by defining their own subclasses of Language.Defaults. """ config: Config = Config(section_order=CONFIG_SECTION_ORDER) tokenizer_exceptions: Dict[str, List[dict]] = BASE_EXCEPTIONS prefixes: Optional[Sequence[Union[str, Pattern]]] = TOKENIZER_PREFIXES suffixes: Optional[Sequence[Union[str, Pattern]]] = TOKENIZER_SUFFIXES infixes: Optional[Sequence[Union[str, Pattern]]] = TOKENIZER_INFIXES token_match: Optional[Callable] = None url_match: Optional[Callable] = URL_MATCH syntax_iterators: Dict[str, Callable] = {} lex_attr_getters: Dict[int, Callable[[str], Any]] = {} stop_words: Set[str] = set() writing_system = {"direction": "ltr", "has_case": True, "has_letters": True} @registry.tokenizers("spacy.Tokenizer.v1") def create_tokenizer() -> Callable[["Language"], Tokenizer]: """Registered function to create a tokenizer. Returns a factory that takes the nlp object and returns a Tokenizer instance using the language detaults. """ def tokenizer_factory(nlp: "Language") -> Tokenizer: prefixes = nlp.Defaults.prefixes suffixes = nlp.Defaults.suffixes infixes = nlp.Defaults.infixes prefix_search = util.compile_prefix_regex(prefixes).search if prefixes else None suffix_search = util.compile_suffix_regex(suffixes).search if suffixes else None infix_finditer = util.compile_infix_regex(infixes).finditer if infixes else None return Tokenizer( nlp.vocab, rules=nlp.Defaults.tokenizer_exceptions, prefix_search=prefix_search, suffix_search=suffix_search, infix_finditer=infix_finditer, token_match=nlp.Defaults.token_match, url_match=nlp.Defaults.url_match, ) return tokenizer_factory @registry.misc("spacy.LookupsDataLoader.v1") def load_lookups_data(lang, tables): util.logger.debug(f"Loading lookups from spacy-lookups-data: {tables}") lookups = load_lookups(lang=lang, tables=tables) return lookups class Language: """A text-processing pipeline. Usually you'll load this once per process, and pass the instance around your application. Defaults (class): Settings, data and factory methods for creating the `nlp` object and processing pipeline. lang (str): IETF language code, such as 'en'. DOCS: https://spacy.io/api/language """ Defaults = BaseDefaults lang: Optional[str] = None default_config = DEFAULT_CONFIG factories = SimpleFrozenDict(error=Errors.E957) _factory_meta: Dict[str, "FactoryMeta"] = {} # meta by factory def __init__( self, vocab: Union[Vocab, bool] = True, *, max_length: int = 10 ** 6, meta: Dict[str, Any] = {}, create_tokenizer: Optional[Callable[["Language"], Callable[[str], Doc]]] = None, batch_size: int = 1000, **kwargs, ) -> None: """Initialise a Language object. vocab (Vocab): A `Vocab` object. If `True`, a vocab is created. meta (dict): Custom meta data for the Language class. Is written to by models to add model meta data. max_length (int): Maximum number of characters in a single text. The current models may run out memory on extremely long texts, due to large internal allocations. You should segment these texts into meaningful units, e.g. paragraphs, subsections etc, before passing them to spaCy. Default maximum length is 1,000,000 charas (1mb). As a rule of thumb, if all pipeline components are enabled, spaCy's default models currently requires roughly 1GB of temporary memory per 100,000 characters in one text. create_tokenizer (Callable): Function that takes the nlp object and returns a tokenizer. batch_size (int): Default batch size for pipe and evaluate. DOCS: https://spacy.io/api/language#init """ # We're only calling this to import all factories provided via entry # points. The factory decorator applied to these functions takes care # of the rest. util.registry._entry_point_factories.get_all() self._config = DEFAULT_CONFIG.merge(self.default_config) self._meta = dict(meta) self._path = None self._optimizer: Optional[Optimizer] = None # Component meta and configs are only needed on the instance self._pipe_meta: Dict[str, "FactoryMeta"] = {} # meta by component self._pipe_configs: Dict[str, Config] = {} # config by component if not isinstance(vocab, Vocab) and vocab is not True: raise ValueError(Errors.E918.format(vocab=vocab, vocab_type=type(Vocab))) if vocab is True: vectors_name = meta.get("vectors", {}).get("name") vocab = create_vocab(self.lang, self.Defaults, vectors_name=vectors_name) else: if (self.lang and vocab.lang) and (self.lang != vocab.lang): raise ValueError(Errors.E150.format(nlp=self.lang, vocab=vocab.lang)) self.vocab: Vocab = vocab if self.lang is None: self.lang = self.vocab.lang self._components: List[Tuple[str, "Pipe"]] = [] self._disabled: Set[str] = set() self.max_length = max_length # Create the default tokenizer from the default config if not create_tokenizer: tokenizer_cfg = {"tokenizer": self._config["nlp"]["tokenizer"]} create_tokenizer = registry.resolve(tokenizer_cfg)["tokenizer"] self.tokenizer = create_tokenizer(self) self.batch_size = batch_size self.default_error_handler = raise_error def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) cls.default_config = DEFAULT_CONFIG.merge(cls.Defaults.config) cls.default_config["nlp"]["lang"] = cls.lang @property def path(self): return self._path @property def meta(self) -> Dict[str, Any]: """Custom meta data of the language class. If a model is loaded, this includes details from the model's meta.json. RETURNS (Dict[str, Any]): The meta. DOCS: https://spacy.io/api/language#meta """ spacy_version = util.get_minor_version_range(about.__version__) if self.vocab.lang: self._meta.setdefault("lang", self.vocab.lang) else: self._meta.setdefault("lang", self.lang) self._meta.setdefault("name", "pipeline") self._meta.setdefault("version", "0.0.0") self._meta.setdefault("spacy_version", spacy_version) self._meta.setdefault("description", "") self._meta.setdefault("author", "") self._meta.setdefault("email", "") self._meta.setdefault("url", "") self._meta.setdefault("license", "") self._meta.setdefault("spacy_git_version", GIT_VERSION) self._meta["vectors"] = { "width": self.vocab.vectors_length, "vectors": len(self.vocab.vectors), "keys": self.vocab.vectors.n_keys, "name": self.vocab.vectors.name, "mode": self.vocab.vectors.mode, } self._meta["labels"] = dict(self.pipe_labels) # TODO: Adding this back to prevent breaking people's code etc., but # we should consider removing it self._meta["pipeline"] = list(self.pipe_names) self._meta["components"] = list(self.component_names) self._meta["disabled"] = list(self.disabled) return self._meta @meta.setter def meta(self, value: Dict[str, Any]) -> None: self._meta = value @property def config(self) -> Config: """Trainable config for the current language instance. Includes the current pipeline components, as well as default training config. RETURNS (thinc.api.Config): The config. DOCS: https://spacy.io/api/language#config """ self._config.setdefault("nlp", {}) self._config.setdefault("training", {}) self._config["nlp"]["lang"] = self.lang # We're storing the filled config for each pipeline component and so # we can populate the config again later pipeline = {} score_weights = [] for pipe_name in self.component_names: pipe_meta = self.get_pipe_meta(pipe_name) pipe_config = self.get_pipe_config(pipe_name) pipeline[pipe_name] = {"factory": pipe_meta.factory, **pipe_config} if pipe_meta.default_score_weights: score_weights.append(pipe_meta.default_score_weights) self._config["nlp"]["pipeline"] = list(self.component_names) self._config["nlp"]["disabled"] = list(self.disabled) self._config["components"] = pipeline # We're merging the existing score weights back into the combined # weights to make sure we're preserving custom settings in the config # but also reflect updates (e.g. new components added) prev_weights = self._config["training"].get("score_weights", {}) combined_score_weights = combine_score_weights(score_weights, prev_weights) self._config["training"]["score_weights"] = combined_score_weights if not srsly.is_json_serializable(self._config): raise ValueError(Errors.E961.format(config=self._config)) return self._config @config.setter def config(self, value: Config) -> None: self._config = value @property def disabled(self) -> List[str]: """Get the names of all disabled components. RETURNS (List[str]): The disabled components. """ # Make sure the disabled components are returned in the order they # appear in the pipeline (which isn't guaranteed by the set) names = [name for name, _ in self._components if name in self._disabled] return SimpleFrozenList(names, error=Errors.E926.format(attr="disabled")) @property def factory_names(self) -> List[str]: """Get names of all available factories. RETURNS (List[str]): The factory names. """ names = list(self.factories.keys()) return SimpleFrozenList(names) @property def components(self) -> List[Tuple[str, "Pipe"]]: """Get all (name, component) tuples in the pipeline, including the currently disabled components. """ return SimpleFrozenList( self._components, error=Errors.E926.format(attr="components") ) @property def component_names(self) -> List[str]: """Get the names of the available pipeline components. Includes all active and inactive pipeline components. RETURNS (List[str]): List of component name strings, in order. """ names = [pipe_name for pipe_name, _ in self._components] return SimpleFrozenList(names, error=Errors.E926.format(attr="component_names")) @property def pipeline(self) -> List[Tuple[str, "Pipe"]]: """The processing pipeline consisting of (name, component) tuples. The components are called on the Doc in order as it passes through the pipeline. RETURNS (List[Tuple[str, Pipe]]): The pipeline. """ pipes = [(n, p) for n, p in self._components if n not in self._disabled] return SimpleFrozenList(pipes, error=Errors.E926.format(attr="pipeline")) @property def pipe_names(self) -> List[str]: """Get names of available active pipeline components. RETURNS (List[str]): List of component name strings, in order. """ names = [pipe_name for pipe_name, _ in self.pipeline] return SimpleFrozenList(names, error=Errors.E926.format(attr="pipe_names")) @property def pipe_factories(self) -> Dict[str, str]: """Get the component factories for the available pipeline components. RETURNS (Dict[str, str]): Factory names, keyed by component names. """ factories = {} for pipe_name, pipe in self._components: factories[pipe_name] = self.get_pipe_meta(pipe_name).factory return SimpleFrozenDict(factories) @property def pipe_labels(self) -> Dict[str, List[str]]: """Get the labels set by the pipeline components, if available (if the component exposes a labels property). RETURNS (Dict[str, List[str]]): Labels keyed by component name. """ labels = {} for name, pipe in self._components: if hasattr(pipe, "labels"): labels[name] = list(pipe.labels) return SimpleFrozenDict(labels) @classmethod def has_factory(cls, name: str) -> bool: """RETURNS (bool): Whether a factory of that name is registered.""" internal_name = cls.get_factory_name(name) return name in registry.factories or internal_name in registry.factories @classmethod def get_factory_name(cls, name: str) -> str: """Get the internal factory name based on the language subclass. name (str): The factory name. RETURNS (str): The internal factory name. """ if cls.lang is None: return name return f"{cls.lang}.{name}" @classmethod def get_factory_meta(cls, name: str) -> "FactoryMeta": """Get the meta information for a given factory name. name (str): The component factory name. RETURNS (FactoryMeta): The meta for the given factory name. """ internal_name = cls.get_factory_name(name) if internal_name in cls._factory_meta: return cls._factory_meta[internal_name] if name in cls._factory_meta: return cls._factory_meta[name] raise ValueError(Errors.E967.format(meta="factory", name=name)) @classmethod def set_factory_meta(cls, name: str, value: "FactoryMeta") -> None: """Set the meta information for a given factory name. name (str): The component factory name. value (FactoryMeta): The meta to set. """ cls._factory_meta[cls.get_factory_name(name)] = value def get_pipe_meta(self, name: str) -> "FactoryMeta": """Get the meta information for a given component name. name (str): The component name. RETURNS (FactoryMeta): The meta for the given component name. """ if name not in self._pipe_meta: raise ValueError(Errors.E967.format(meta="component", name=name)) return self._pipe_meta[name] def get_pipe_config(self, name: str) -> Config: """Get the config used to create a pipeline component. name (str): The component name. RETURNS (Config): The config used to create the pipeline component. """ if name not in self._pipe_configs: raise ValueError(Errors.E960.format(name=name)) pipe_config = self._pipe_configs[name] return pipe_config @classmethod def factory( cls, name: str, *, default_config: Dict[str, Any] = SimpleFrozenDict(), assigns: Iterable[str] = SimpleFrozenList(), requires: Iterable[str] = SimpleFrozenList(), retokenizes: bool = False, default_score_weights: Dict[str, Optional[float]] = SimpleFrozenDict(), func: Optional[Callable] = None, ) -> Callable: """Register a new pipeline component factory. Can be used as a decorator on a function or classmethod, or called as a function with the factory provided as the func keyword argument. To create a component and add it to the pipeline, you can use nlp.add_pipe(name). name (str): The name of the component factory. default_config (Dict[str, Any]): Default configuration, describing the default values of the factory arguments. assigns (Iterable[str]): Doc/Token attributes assigned by this component, e.g. "token.ent_id". Used for pipeline analysis. requires (Iterable[str]): Doc/Token attributes required by this component, e.g. "token.ent_id". Used for pipeline analysis. retokenizes (bool): Whether the component changes the tokenization. Used for pipeline analysis. default_score_weights (Dict[str, Optional[float]]): The scores to report during training, and their default weight towards the final score used to select the best model. Weights should sum to 1.0 per component and will be combined and normalized for the whole pipeline. If None, the score won't be shown in the logs or be weighted. func (Optional[Callable]): Factory function if not used as a decorator. DOCS: https://spacy.io/api/language#factory """ if not isinstance(name, str): raise ValueError(Errors.E963.format(decorator="factory")) if not isinstance(default_config, dict): err = Errors.E962.format( style="default config", name=name, cfg_type=type(default_config) ) raise ValueError(err) def add_factory(factory_func: Callable) -> Callable: internal_name = cls.get_factory_name(name) if internal_name in registry.factories: # We only check for the internal name here – it's okay if it's a # subclass and the base class has a factory of the same name. We # also only raise if the function is different to prevent raising # if module is reloaded. existing_func = registry.factories.get(internal_name) if not util.is_same_func(factory_func, existing_func): err = Errors.E004.format( name=name, func=existing_func, new_func=factory_func ) raise ValueError(err) arg_names = util.get_arg_names(factory_func) if "nlp" not in arg_names or "name" not in arg_names: raise ValueError(Errors.E964.format(name=name)) # Officially register the factory so we can later call # registry.resolve and refer to it in the config as # @factories = "spacy.Language.xyz". We use the class name here so # different classes can have different factories. registry.factories.register(internal_name, func=factory_func) factory_meta = FactoryMeta( factory=name, default_config=default_config, assigns=validate_attrs(assigns), requires=validate_attrs(requires), scores=list(default_score_weights.keys()), default_score_weights=default_score_weights, retokenizes=retokenizes, ) cls.set_factory_meta(name, factory_meta) # We're overwriting the class attr with a frozen dict to handle # backwards-compat (writing to Language.factories directly). This # wouldn't work with an instance property and just produce a # confusing error – here we can show a custom error cls.factories = SimpleFrozenDict( registry.factories.get_all(), error=Errors.E957 ) return factory_func if func is not None: # Support non-decorator use cases return add_factory(func) return add_factory @classmethod def component( cls, name: str, *, assigns: Iterable[str] = SimpleFrozenList(), requires: Iterable[str] = SimpleFrozenList(), retokenizes: bool = False, func: Optional["Pipe"] = None, ) -> Callable: """Register a new pipeline component. Can be used for stateless function components that don't require a separate factory. Can be used as a decorator on a function or classmethod, or called as a function with the factory provided as the func keyword argument. To create a component and add it to the pipeline, you can use nlp.add_pipe(name). name (str): The name of the component factory. assigns (Iterable[str]): Doc/Token attributes assigned by this component, e.g. "token.ent_id". Used for pipeline analysis. requires (Iterable[str]): Doc/Token attributes required by this component, e.g. "token.ent_id". Used for pipeline analysis. retokenizes (bool): Whether the component changes the tokenization. Used for pipeline analysis. func (Optional[Callable]): Factory function if not used as a decorator. DOCS: https://spacy.io/api/language#component """ if name is not None and not isinstance(name, str): raise ValueError(Errors.E963.format(decorator="component")) component_name = name if name is not None else util.get_object_name(func) def add_component(component_func: "Pipe") -> Callable: if isinstance(func, type): # function is a class raise ValueError(Errors.E965.format(name=component_name)) def factory_func(nlp, name: str) -> "Pipe": return component_func internal_name = cls.get_factory_name(name) if internal_name in registry.factories: # We only check for the internal name here – it's okay if it's a # subclass and the base class has a factory of the same name. We # also only raise if the function is different to prevent raising # if module is reloaded. It's hacky, but we need to check the # existing functure for a closure and whether that's identical # to the component function (because factory_func created above # will always be different, even for the same function) existing_func = registry.factories.get(internal_name) closure = existing_func.__closure__ wrapped = [c.cell_contents for c in closure][0] if closure else None if util.is_same_func(wrapped, component_func): factory_func = existing_func # noqa: F811 cls.factory( component_name, assigns=assigns, requires=requires, retokenizes=retokenizes, func=factory_func, ) return component_func if func is not None: # Support non-decorator use cases return add_component(func) return add_component def analyze_pipes( self, *, keys: List[str] = ["assigns", "requires", "scores", "retokenizes"], pretty: bool = False, ) -> Optional[Dict[str, Any]]: """Analyze the current pipeline components, print a summary of what they assign or require and check that all requirements are met. keys (List[str]): The meta values to display in the table. Corresponds to values in FactoryMeta, defined by @Language.factory decorator. pretty (bool): Pretty-print the results. RETURNS (dict): The data. """ analysis = analyze_pipes(self, keys=keys) if pretty: print_pipe_analysis(analysis, keys=keys) return analysis def get_pipe(self, name: str) -> "Pipe": """Get a pipeline component for a given component name. name (str): Name of pipeline component to get. RETURNS (callable): The pipeline component. DOCS: https://spacy.io/api/language#get_pipe """ for pipe_name, component in self._components: if pipe_name == name: return component raise KeyError(Errors.E001.format(name=name, opts=self.component_names)) def create_pipe( self, factory_name: str, name: Optional[str] = None, *, config: Dict[str, Any] = SimpleFrozenDict(), raw_config: Optional[Config] = None, validate: bool = True, ) -> "Pipe": """Create a pipeline component. Mostly used internally. To create and add a component to the pipeline, you can use nlp.add_pipe. factory_name (str): Name of component factory. name (Optional[str]): Optional name to assign to component instance. Defaults to factory name if not set. config (Dict[str, Any]): Config parameters to use for this component. Will be merged with default config, if available. raw_config (Optional[Config]): Internals: the non-interpolated config. validate (bool): Whether to validate the component config against the arguments and types expected by the factory. RETURNS (Pipe): The pipeline component. DOCS: https://spacy.io/api/language#create_pipe """ name = name if name is not None else factory_name if not isinstance(config, dict): err = Errors.E962.format(style="config", name=name, cfg_type=type(config)) raise ValueError(err) if not srsly.is_json_serializable(config): raise ValueError(Errors.E961.format(config=config)) if not self.has_factory(factory_name): err = Errors.E002.format( name=factory_name, opts=", ".join(self.factory_names), method="create_pipe", lang=util.get_object_name(self), lang_code=self.lang, ) raise ValueError(err) pipe_meta = self.get_factory_meta(factory_name) # This is unideal, but the alternative would mean you always need to # specify the full config settings, which is not really viable. if pipe_meta.default_config: config = Config(pipe_meta.default_config).merge(config) internal_name = self.get_factory_name(factory_name) # If the language-specific factory doesn't exist, try again with the # not-specific name if internal_name not in registry.factories: internal_name = factory_name # The name allows components to know their pipe name and use it in the # losses etc. (even if multiple instances of the same factory are used) config = {"nlp": self, "name": name, **config, "@factories": internal_name} # We need to create a top-level key because Thinc doesn't allow resolving # top-level references to registered functions. Also gives nicer errors. cfg = {factory_name: config} # We're calling the internal _fill here to avoid constructing the # registered functions twice resolved = registry.resolve(cfg, validate=validate) filled = registry.fill({"cfg": cfg[factory_name]}, validate=validate)["cfg"] filled = Config(filled) filled["factory"] = factory_name filled.pop("@factories", None) # Remove the extra values we added because we don't want to keep passing # them around, copying them etc. filled.pop("nlp", None) filled.pop("name", None) # Merge the final filled config with the raw config (including non- # interpolated variables) if raw_config: filled = filled.merge(raw_config) self._pipe_configs[name] = filled return resolved[factory_name] def create_pipe_from_source( self, source_name: str, source: "Language", *, name: str ) -> Tuple["Pipe", str]: """Create a pipeline component by copying it from an existing model. source_name (str): Name of the component in the source pipeline. source (Language): The source nlp object to copy from. name (str): Optional alternative name to use in current pipeline. RETURNS (Tuple[Callable, str]): The component and its factory name. """ # Check source type if not isinstance(source, Language): raise ValueError(Errors.E945.format(name=source_name, source=type(source))) # Check vectors, with faster checks first if ( self.vocab.vectors.shape != source.vocab.vectors.shape or self.vocab.vectors.key2row != source.vocab.vectors.key2row or self.vocab.vectors.to_bytes(exclude=["strings"]) != source.vocab.vectors.to_bytes(exclude=["strings"]) ): warnings.warn(Warnings.W113.format(name=source_name)) if source_name not in source.component_names: raise KeyError( Errors.E944.format( name=source_name, model=f"{source.meta['lang']}_{source.meta['name']}", opts=", ".join(source.component_names), ) ) pipe = source.get_pipe(source_name) # Make sure the source config is interpolated so we don't end up with # orphaned variables in our final config source_config = source.config.interpolate() pipe_config = util.copy_config(source_config["components"][source_name]) self._pipe_configs[name] = pipe_config if self.vocab.strings != source.vocab.strings: for s in source.vocab.strings: self.vocab.strings.add(s) return pipe, pipe_config["factory"] def add_pipe( self, factory_name: str, name: Optional[str] = None, *, before: Optional[Union[str, int]] = None, after: Optional[Union[str, int]] = None, first: Optional[bool] = None, last: Optional[bool] = None, source: Optional["Language"] = None, config: Dict[str, Any] = SimpleFrozenDict(), raw_config: Optional[Config] = None, validate: bool = True, ) -> "Pipe": """Add a component to the processing pipeline. Valid components are callables that take a `Doc` object, modify it and return it. Only one of before/after/first/last can be set. Default behaviour is "last". factory_name (str): Name of the component factory. name (str): Name of pipeline component. Overwrites existing component.name attribute if available. If no name is set and the component exposes no name attribute, component.__name__ is used. An error is raised if a name already exists in the pipeline. before (Union[str, int]): Name or index of the component to insert new component directly before. after (Union[str, int]): Name or index of the component to insert new component directly after. first (bool): If True, insert component first in the pipeline. last (bool): If True, insert component last in the pipeline. source (Language): Optional loaded nlp object to copy the pipeline component from. config (Dict[str, Any]): Config parameters to use for this component. Will be merged with default config, if available. raw_config (Optional[Config]): Internals: the non-interpolated config. validate (bool): Whether to validate the component config against the arguments and types expected by the factory. RETURNS (Pipe): The pipeline component. DOCS: https://spacy.io/api/language#add_pipe """ if not isinstance(factory_name, str): bad_val = repr(factory_name) err = Errors.E966.format(component=bad_val, name=name) raise ValueError(err) name = name if name is not None else factory_name if name in self.component_names: raise ValueError(Errors.E007.format(name=name, opts=self.component_names)) if source is not None: # We're loading the component from a model. After loading the # component, we know its real factory name pipe_component, factory_name = self.create_pipe_from_source( factory_name, source, name=name ) else: if not self.has_factory(factory_name): err = Errors.E002.format( name=factory_name, opts=", ".join(self.factory_names), method="add_pipe", lang=util.get_object_name(self), lang_code=self.lang, ) pipe_component = self.create_pipe( factory_name, name=name, config=config, raw_config=raw_config, validate=validate, ) pipe_index = self._get_pipe_index(before, after, first, last) self._pipe_meta[name] = self.get_factory_meta(factory_name) self._components.insert(pipe_index, (name, pipe_component)) return pipe_component def _get_pipe_index( self, before: Optional[Union[str, int]] = None, after: Optional[Union[str, int]] = None, first: Optional[bool] = None, last: Optional[bool] = None, ) -> int: """Determine where to insert a pipeline component based on the before/ after/first/last values. before (str): Name or index of the component to insert directly before. after (str): Name or index of component to insert directly after. first (bool): If True, insert component first in the pipeline. last (bool): If True, insert component last in the pipeline. RETURNS (int): The index of the new pipeline component. """ all_args = {"before": before, "after": after, "first": first, "last": last} if sum(arg is not None for arg in [before, after, first, last]) >= 2: raise ValueError( Errors.E006.format(args=all_args, opts=self.component_names) ) if last or not any(value is not None for value in [first, before, after]): return len(self._components) elif first: return 0 elif isinstance(before, str): if before not in self.component_names: raise ValueError( Errors.E001.format(name=before, opts=self.component_names) ) return self.component_names.index(before) elif isinstance(after, str): if after not in self.component_names: raise ValueError( Errors.E001.format(name=after, opts=self.component_names) ) return self.component_names.index(after) + 1 # We're only accepting indices referring to components that exist # (can't just do isinstance here because bools are instance of int, too) elif type(before) == int: if before >= len(self._components) or before < 0: err = Errors.E959.format( dir="before", idx=before, opts=self.component_names ) raise ValueError(err) return before elif type(after) == int: if after >= len(self._components) or after < 0: err = Errors.E959.format( dir="after", idx=after, opts=self.component_names ) raise ValueError(err) return after + 1 raise ValueError(Errors.E006.format(args=all_args, opts=self.component_names)) def has_pipe(self, name: str) -> bool: """Check if a component name is present in the pipeline. Equivalent to `name in nlp.pipe_names`. name (str): Name of the component. RETURNS (bool): Whether a component of the name exists in the pipeline. DOCS: https://spacy.io/api/language#has_pipe """ return name in self.pipe_names def replace_pipe( self, name: str, factory_name: str, *, config: Dict[str, Any] = SimpleFrozenDict(), validate: bool = True, ) -> "Pipe": """Replace a component in the pipeline. name (str): Name of the component to replace. factory_name (str): Factory name of replacement component. config (Optional[Dict[str, Any]]): Config parameters to use for this component. Will be merged with default config, if available. validate (bool): Whether to validate the component config against the arguments and types expected by the factory. RETURNS (Pipe): The new pipeline component. DOCS: https://spacy.io/api/language#replace_pipe """ if name not in self.component_names: raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names)) if hasattr(factory_name, "__call__"): err = Errors.E968.format(component=repr(factory_name), name=name) raise ValueError(err) # We need to delegate to Language.add_pipe here instead of just writing # to Language.pipeline to make sure the configs are handled correctly pipe_index = self.component_names.index(name) self.remove_pipe(name) if not len(self._components) or pipe_index == len(self._components): # we have no components to insert before/after, or we're replacing the last component return self.add_pipe( factory_name, name=name, config=config, validate=validate ) else: return self.add_pipe( factory_name, name=name, before=pipe_index, config=config, validate=validate, ) def rename_pipe(self, old_name: str, new_name: str) -> None: """Rename a pipeline component. old_name (str): Name of the component to rename. new_name (str): New name of the component. DOCS: https://spacy.io/api/language#rename_pipe """ if old_name not in self.component_names: raise ValueError( Errors.E001.format(name=old_name, opts=self.component_names) ) if new_name in self.component_names: raise ValueError( Errors.E007.format(name=new_name, opts=self.component_names) ) i = self.component_names.index(old_name) self._components[i] = (new_name, self._components[i][1]) self._pipe_meta[new_name] = self._pipe_meta.pop(old_name) self._pipe_configs[new_name] = self._pipe_configs.pop(old_name) # Make sure [initialize] config is adjusted if old_name in self._config["initialize"]["components"]: init_cfg = self._config["initialize"]["components"].pop(old_name) self._config["initialize"]["components"][new_name] = init_cfg def remove_pipe(self, name: str) -> Tuple[str, "Pipe"]: """Remove a component from the pipeline. name (str): Name of the component to remove. RETURNS (tuple): A `(name, component)` tuple of the removed component. DOCS: https://spacy.io/api/language#remove_pipe """ if name not in self.component_names: raise ValueError(Errors.E001.format(name=name, opts=self.component_names)) removed = self._components.pop(self.component_names.index(name)) # We're only removing the component itself from the metas/configs here # because factory may be used for something else self._pipe_meta.pop(name) self._pipe_configs.pop(name) self.meta.get("_sourced_vectors_hashes", {}).pop(name, None) # Make sure name is removed from the [initialize] config if name in self._config["initialize"]["components"]: self._config["initialize"]["components"].pop(name) # Make sure the name is also removed from the set of disabled components if name in self.disabled: self._disabled.remove(name) return removed def disable_pipe(self, name: str) -> None: """Disable a pipeline component. The component will still exist on the nlp object, but it won't be run as part of the pipeline. Does nothing if the component is already disabled. name (str): The name of the component to disable. """ if name not in self.component_names: raise ValueError(Errors.E001.format(name=name, opts=self.component_names)) self._disabled.add(name) def enable_pipe(self, name: str) -> None: """Enable a previously disabled pipeline component so it's run as part of the pipeline. Does nothing if the component is already enabled. name (str): The name of the component to enable. """ if name not in self.component_names: raise ValueError(Errors.E001.format(name=name, opts=self.component_names)) if name in self.disabled: self._disabled.remove(name) def __call__( self, text: Union[str, Doc], *, disable: Iterable[str] = SimpleFrozenList(), component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, ) -> Doc: """Apply the pipeline to some text. The text can span multiple sentences, and can contain arbitrary whitespace. Alignment into the original string is preserved. text (Union[str, Doc]): If `str`, the text to be processed. If `Doc`, the doc will be passed directly to the pipeline, skipping `Language.make_doc`. disable (List[str]): Names of the pipeline components to disable. component_cfg (Dict[str, dict]): An optional dictionary with extra keyword arguments for specific components. RETURNS (Doc): A container for accessing the annotations. DOCS: https://spacy.io/api/language#call """ doc = self._ensure_doc(text) if component_cfg is None: component_cfg = {} for name, proc in self.pipeline: if name in disable: continue if not hasattr(proc, "__call__"): raise ValueError(Errors.E003.format(component=type(proc), name=name)) error_handler = self.default_error_handler if hasattr(proc, "get_error_handler"): error_handler = proc.get_error_handler() try: doc = proc(doc, **component_cfg.get(name, {})) # type: ignore[call-arg] except KeyError as e: # This typically happens if a component is not initialized raise ValueError(Errors.E109.format(name=name)) from e except Exception as e: error_handler(name, proc, [doc], e) if doc is None: raise ValueError(Errors.E005.format(name=name)) return doc def disable_pipes(self, *names) -> "DisabledPipes": """Disable one or more pipeline components. If used as a context manager, the pipeline will be restored to the initial state at the end of the block. Otherwise, a DisabledPipes object is returned, that has a `.restore()` method you can use to undo your changes. This method has been deprecated since 3.0 """ warnings.warn(Warnings.W096, DeprecationWarning) if len(names) == 1 and isinstance(names[0], (list, tuple)): names = names[0] # type: ignore[assignment] # support list of names instead of spread return self.select_pipes(disable=names) def select_pipes( self, *, disable: Optional[Union[str, Iterable[str]]] = None, enable: Optional[Union[str, Iterable[str]]] = None, ) -> "DisabledPipes": """Disable one or more pipeline components. If used as a context manager, the pipeline will be restored to the initial state at the end of the block. Otherwise, a DisabledPipes object is returned, that has a `.restore()` method you can use to undo your changes. disable (str or iterable): The name(s) of the pipes to disable enable (str or iterable): The name(s) of the pipes to enable - all others will be disabled DOCS: https://spacy.io/api/language#select_pipes """ if enable is None and disable is None: raise ValueError(Errors.E991) if disable is not None and isinstance(disable, str): disable = [disable] if enable is not None: if isinstance(enable, str): enable = [enable] to_disable = [pipe for pipe in self.pipe_names if pipe not in enable] # raise an error if the enable and disable keywords are not consistent if disable is not None and disable != to_disable: raise ValueError( Errors.E992.format( enable=enable, disable=disable, names=self.pipe_names ) ) disable = to_disable assert disable is not None # DisabledPipes will restore the pipes in 'disable' when it's done, so we need to exclude # those pipes that were already disabled. disable = [d for d in disable if d not in self._disabled] return DisabledPipes(self, disable) def make_doc(self, text: str) -> Doc: """Turn a text into a Doc object. text (str): The text to process. RETURNS (Doc): The processed doc. """ if len(text) > self.max_length: raise ValueError( Errors.E088.format(length=len(text), max_length=self.max_length) ) return self.tokenizer(text) def _ensure_doc(self, doc_like: Union[str, Doc]) -> Doc: """Create a Doc if need be, or raise an error if the input is not a Doc or a string.""" if isinstance(doc_like, Doc): return doc_like if isinstance(doc_like, str): return self.make_doc(doc_like) raise ValueError(Errors.E866.format(type=type(doc_like))) def _ensure_doc_with_context(self, doc_like: Union[str, Doc], context: Any) -> Doc: """Create a Doc if need be and add as_tuples context, or raise an error if the input is not a Doc or a string.""" doc = self._ensure_doc(doc_like) doc._context = context return doc def update( self, examples: Iterable[Example], _: Optional[Any] = None, *, drop: float = 0.0, sgd: Optional[Optimizer] = None, losses: Optional[Dict[str, float]] = None, component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, exclude: Iterable[str] = SimpleFrozenList(), annotates: Iterable[str] = SimpleFrozenList(), ): """Update the models in the pipeline. examples (Iterable[Example]): A batch of examples _: Should not be set - serves to catch backwards-incompatible scripts. drop (float): The dropout rate. sgd (Optimizer): An optimizer. losses (Dict[str, float]): Dictionary to update with the loss, keyed by component. component_cfg (Dict[str, Dict]): Config parameters for specific pipeline components, keyed by component name. exclude (Iterable[str]): Names of components that shouldn't be updated. annotates (Iterable[str]): Names of components that should set annotations on the predicted examples after updating. RETURNS (Dict[str, float]): The updated losses dictionary DOCS: https://spacy.io/api/language#update """ if _ is not None: raise ValueError(Errors.E989) if losses is None: losses = {} if isinstance(examples, list) and len(examples) == 0: return losses validate_examples(examples, "Language.update") examples = _copy_examples(examples) if sgd is None: if self._optimizer is None: self._optimizer = self.create_optimizer() sgd = self._optimizer if component_cfg is None: component_cfg = {} pipe_kwargs = {} for i, (name, proc) in enumerate(self.pipeline): component_cfg.setdefault(name, {}) pipe_kwargs[name] = deepcopy(component_cfg[name]) component_cfg[name].setdefault("drop", drop) pipe_kwargs[name].setdefault("batch_size", self.batch_size) for name, proc in self.pipeline: # ignore statements are used here because mypy ignores hasattr if name not in exclude and hasattr(proc, "update"): proc.update(examples, sgd=None, losses=losses, **component_cfg[name]) # type: ignore if sgd not in (None, False): if ( name not in exclude and isinstance(proc, ty.TrainableComponent) and proc.is_trainable and proc.model not in (True, False, None) ): proc.finish_update(sgd) if name in annotates: for doc, eg in zip( _pipe( (eg.predicted for eg in examples), proc=proc, name=name, default_error_handler=self.default_error_handler, kwargs=pipe_kwargs[name], ), examples, ): eg.predicted = doc return losses def rehearse( self, examples: Iterable[Example], *, sgd: Optional[Optimizer] = None, losses: Optional[Dict[str, float]] = None, component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, exclude: Iterable[str] = SimpleFrozenList(), ) -> Dict[str, float]: """Make a "rehearsal" update to the models in the pipeline, to prevent forgetting. Rehearsal updates run an initial copy of the model over some data, and update the model so its current predictions are more like the initial ones. This is useful for keeping a pretrained model on-track, even if you're updating it with a smaller set of examples. examples (Iterable[Example]): A batch of `Example` objects. sgd (Optional[Optimizer]): An optimizer. component_cfg (Dict[str, Dict]): Config parameters for specific pipeline components, keyed by component name. exclude (Iterable[str]): Names of components that shouldn't be updated. RETURNS (dict): Results from the update. EXAMPLE: >>> raw_text_batches = minibatch(raw_texts) >>> for labelled_batch in minibatch(examples): >>> nlp.update(labelled_batch) >>> raw_batch = [Example.from_dict(nlp.make_doc(text), {}) for text in next(raw_text_batches)] >>> nlp.rehearse(raw_batch) DOCS: https://spacy.io/api/language#rehearse """ if losses is None: losses = {} if isinstance(examples, list) and len(examples) == 0: return losses validate_examples(examples, "Language.rehearse") if sgd is None: if self._optimizer is None: self._optimizer = self.create_optimizer() sgd = self._optimizer pipes = list(self.pipeline) random.shuffle(pipes) if component_cfg is None: component_cfg = {} grads = {} def get_grads(W, dW, key=None): grads[key] = (W, dW) get_grads.learn_rate = sgd.learn_rate # type: ignore[attr-defined, union-attr] get_grads.b1 = sgd.b1 # type: ignore[attr-defined, union-attr] get_grads.b2 = sgd.b2 # type: ignore[attr-defined, union-attr] for name, proc in pipes: if name in exclude or not hasattr(proc, "rehearse"): continue grads = {} proc.rehearse( # type: ignore[attr-defined] examples, sgd=get_grads, losses=losses, **component_cfg.get(name, {}) ) for key, (W, dW) in grads.items(): sgd(W, dW, key=key) # type: ignore[call-arg, misc] return losses def begin_training( self, get_examples: Optional[Callable[[], Iterable[Example]]] = None, *, sgd: Optional[Optimizer] = None, ) -> Optimizer: warnings.warn(Warnings.W089, DeprecationWarning) return self.initialize(get_examples, sgd=sgd) def initialize( self, get_examples: Optional[Callable[[], Iterable[Example]]] = None, *, sgd: Optional[Optimizer] = None, ) -> Optimizer: """Initialize the pipe for training, using data examples if available. get_examples (Callable[[], Iterable[Example]]): Optional function that returns gold-standard Example objects. sgd (Optional[Optimizer]): An optimizer to use for updates. If not provided, will be created using the .create_optimizer() method. RETURNS (thinc.api.Optimizer): The optimizer. DOCS: https://spacy.io/api/language#initialize """ if get_examples is None: util.logger.debug( "No 'get_examples' callback provided to 'Language.initialize', creating dummy examples" ) doc = Doc(self.vocab, words=["x", "y", "z"]) get_examples = lambda: [Example.from_dict(doc, {})] if not hasattr(get_examples, "__call__"): err = Errors.E930.format( method="Language.initialize", obj=type(get_examples) ) raise TypeError(err) # Make sure the config is interpolated so we can resolve subsections config = self.config.interpolate() # These are the settings provided in the [initialize] block in the config I = registry.resolve(config["initialize"], schema=ConfigSchemaInit) before_init = I["before_init"] if before_init is not None: before_init(self) try: init_vocab( self, data=I["vocab_data"], lookups=I["lookups"], vectors=I["vectors"] ) except IOError: raise IOError(Errors.E884.format(vectors=I["vectors"])) if self.vocab.vectors.shape[1] >= 1: ops = get_current_ops() self.vocab.vectors.to_ops(ops) if hasattr(self.tokenizer, "initialize"): tok_settings = validate_init_settings( self.tokenizer.initialize, # type: ignore[union-attr] I["tokenizer"], section="tokenizer", name="tokenizer", ) self.tokenizer.initialize(get_examples, nlp=self, **tok_settings) # type: ignore[union-attr] for name, proc in self.pipeline: if isinstance(proc, ty.InitializableComponent): p_settings = I["components"].get(name, {}) p_settings = validate_init_settings( proc.initialize, p_settings, section="components", name=name ) proc.initialize(get_examples, nlp=self, **p_settings) pretrain_cfg = config.get("pretraining") if pretrain_cfg: P = registry.resolve(pretrain_cfg, schema=ConfigSchemaPretrain) init_tok2vec(self, P, I) self._link_components() self._optimizer = sgd if sgd is not None: self._optimizer = sgd elif self._optimizer is None: self._optimizer = self.create_optimizer() after_init = I["after_init"] if after_init is not None: after_init(self) return self._optimizer def resume_training(self, *, sgd: Optional[Optimizer] = None) -> Optimizer: """Continue training a pretrained model. Create and return an optimizer, and initialize "rehearsal" for any pipeline component that has a .rehearse() method. Rehearsal is used to prevent models from "forgetting" their initialized "knowledge". To perform rehearsal, collect samples of text you want the models to retain performance on, and call nlp.rehearse() with a batch of Example objects. RETURNS (Optimizer): The optimizer. DOCS: https://spacy.io/api/language#resume_training """ ops = get_current_ops() if self.vocab.vectors.shape[1] >= 1: self.vocab.vectors.to_ops(ops) for name, proc in self.pipeline: if hasattr(proc, "_rehearsal_model"): proc._rehearsal_model = deepcopy(proc.model) # type: ignore[attr-defined] if sgd is not None: self._optimizer = sgd elif self._optimizer is None: self._optimizer = self.create_optimizer() return self._optimizer def set_error_handler( self, error_handler: Callable[[str, "Pipe", List[Doc], Exception], NoReturn], ): """Set an error handler object for all the components in the pipeline that implement a set_error_handler function. error_handler (Callable[[str, Pipe, List[Doc], Exception], NoReturn]): Function that deals with a failing batch of documents. This callable function should take in the component's name, the component itself, the offending batch of documents, and the exception that was thrown. DOCS: https://spacy.io/api/language#set_error_handler """ self.default_error_handler = error_handler for name, pipe in self.pipeline: if hasattr(pipe, "set_error_handler"): pipe.set_error_handler(error_handler) def evaluate( self, examples: Iterable[Example], *, batch_size: Optional[int] = None, scorer: Optional[Scorer] = None, component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, scorer_cfg: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """Evaluate a model's pipeline components. examples (Iterable[Example]): `Example` objects. batch_size (Optional[int]): Batch size to use. scorer (Optional[Scorer]): Scorer to use. If not passed in, a new one will be created. component_cfg (dict): An optional dictionary with extra keyword arguments for specific components. scorer_cfg (dict): An optional dictionary with extra keyword arguments for the scorer. RETURNS (Scorer): The scorer containing the evaluation results. DOCS: https://spacy.io/api/language#evaluate """ examples = list(examples) validate_examples(examples, "Language.evaluate") examples = _copy_examples(examples) if batch_size is None: batch_size = self.batch_size if component_cfg is None: component_cfg = {} if scorer_cfg is None: scorer_cfg = {} if scorer is None: kwargs = dict(scorer_cfg) kwargs.setdefault("nlp", self) scorer = Scorer(**kwargs) # reset annotation in predicted docs and time tokenization start_time = timer() # this is purely for timing for eg in examples: self.make_doc(eg.reference.text) # apply all pipeline components docs = self.pipe( (eg.predicted for eg in examples), batch_size=batch_size, component_cfg=component_cfg, ) for eg, doc in zip(examples, docs): eg.predicted = doc end_time = timer() results = scorer.score(examples) n_words = sum(len(eg.predicted) for eg in examples) results["speed"] = n_words / (end_time - start_time) return results def create_optimizer(self): """Create an optimizer, usually using the [training.optimizer] config.""" subconfig = {"optimizer": self.config["training"]["optimizer"]} return registry.resolve(subconfig)["optimizer"] @contextmanager def use_params(self, params: Optional[dict]): """Replace weights of models in the pipeline with those provided in the params dictionary. Can be used as a contextmanager, in which case, models go back to their original weights after the block. params (dict): A dictionary of parameters keyed by model ID. EXAMPLE: >>> with nlp.use_params(optimizer.averages): >>> nlp.to_disk("/tmp/checkpoint") DOCS: https://spacy.io/api/language#use_params """ if not params: yield else: contexts = [ pipe.use_params(params) # type: ignore[attr-defined] for name, pipe in self.pipeline if hasattr(pipe, "use_params") and hasattr(pipe, "model") ] # TODO: Having trouble with contextlib # Workaround: these aren't actually context managers atm. for context in contexts: try: next(context) except StopIteration: pass yield for context in contexts: try: next(context) except StopIteration: pass @overload def pipe( self, texts: Iterable[Union[str, Doc]], *, as_tuples: Literal[False] = ..., batch_size: Optional[int] = ..., disable: Iterable[str] = ..., component_cfg: Optional[Dict[str, Dict[str, Any]]] = ..., n_process: int = ..., ) -> Iterator[Doc]: ... @overload def pipe( # noqa: F811 self, texts: Iterable[Tuple[Union[str, Doc], _AnyContext]], *, as_tuples: Literal[True] = ..., batch_size: Optional[int] = ..., disable: Iterable[str] = ..., component_cfg: Optional[Dict[str, Dict[str, Any]]] = ..., n_process: int = ..., ) -> Iterator[Tuple[Doc, _AnyContext]]: ... def pipe( # noqa: F811 self, texts: Union[ Iterable[Union[str, Doc]], Iterable[Tuple[Union[str, Doc], _AnyContext]] ], *, as_tuples: bool = False, batch_size: Optional[int] = None, disable: Iterable[str] = SimpleFrozenList(), component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, n_process: int = 1, ) -> Union[Iterator[Doc], Iterator[Tuple[Doc, _AnyContext]]]: """Process texts as a stream, and yield `Doc` objects in order. texts (Iterable[Union[str, Doc]]): A sequence of texts or docs to process. as_tuples (bool): If set to True, inputs should be a sequence of (text, context) tuples. Output will then be a sequence of (doc, context) tuples. Defaults to False. batch_size (Optional[int]): The number of texts to buffer. disable (List[str]): Names of the pipeline components to disable. component_cfg (Dict[str, Dict]): An optional dictionary with extra keyword arguments for specific components. n_process (int): Number of processors to process texts. If -1, set `multiprocessing.cpu_count()`. YIELDS (Doc): Documents in the order of the original text. DOCS: https://spacy.io/api/language#pipe """ # Handle texts with context as tuples if as_tuples: texts = cast(Iterable[Tuple[Union[str, Doc], _AnyContext]], texts) docs_with_contexts = ( self._ensure_doc_with_context(text, context) for text, context in texts ) docs = self.pipe( docs_with_contexts, batch_size=batch_size, disable=disable, n_process=n_process, component_cfg=component_cfg, ) for doc in docs: context = doc._context doc._context = None yield (doc, context) return texts = cast(Iterable[Union[str, Doc]], texts) # Set argument defaults if n_process == -1: n_process = mp.cpu_count() if component_cfg is None: component_cfg = {} if batch_size is None: batch_size = self.batch_size pipes = ( [] ) # contains functools.partial objects to easily create multiprocess worker. for name, proc in self.pipeline: if name in disable: continue kwargs = component_cfg.get(name, {}) # Allow component_cfg to overwrite the top-level kwargs. kwargs.setdefault("batch_size", batch_size) f = functools.partial( _pipe, proc=proc, name=name, kwargs=kwargs, default_error_handler=self.default_error_handler, ) pipes.append(f) if n_process != 1: if self._has_gpu_model(disable): warnings.warn(Warnings.W114) docs = self._multiprocessing_pipe(texts, pipes, n_process, batch_size) else: # if n_process == 1, no processes are forked. docs = (self._ensure_doc(text) for text in texts) for pipe in pipes: docs = pipe(docs) for doc in docs: yield doc def _has_gpu_model(self, disable: Iterable[str]): for name, proc in self.pipeline: is_trainable = hasattr(proc, "is_trainable") and proc.is_trainable # type: ignore if name in disable or not is_trainable: continue if hasattr(proc, "model") and hasattr(proc.model, "ops") and isinstance(proc.model.ops, CupyOps): # type: ignore return True return False def _multiprocessing_pipe( self, texts: Iterable[Union[str, Doc]], pipes: Iterable[Callable[..., Iterator[Doc]]], n_process: int, batch_size: int, ) -> Iterator[Doc]: # raw_texts is used later to stop iteration. texts, raw_texts = itertools.tee(texts) # for sending texts to worker texts_q: List[mp.Queue] = [mp.Queue() for _ in range(n_process)] # for receiving byte-encoded docs from worker bytedocs_recv_ch, bytedocs_send_ch = zip( *[mp.Pipe(False) for _ in range(n_process)] ) batch_texts = util.minibatch(texts, batch_size) # Sender sends texts to the workers. # This is necessary to properly handle infinite length of texts. # (In this case, all data cannot be sent to the workers at once) sender = _Sender(batch_texts, texts_q, chunk_size=n_process) # send twice to make process busy sender.send() sender.send() procs = [ mp.Process( target=_apply_pipes, args=(self._ensure_doc, pipes, rch, sch, Underscore.get_state()), ) for rch, sch in zip(texts_q, bytedocs_send_ch) ] for proc in procs: proc.start() # Cycle channels not to break the order of docs. # The received object is a batch of byte-encoded docs, so flatten them with chain.from_iterable. byte_tuples = chain.from_iterable( recv.recv() for recv in cycle(bytedocs_recv_ch) ) try: for i, (_, (byte_doc, byte_context, byte_error)) in enumerate( zip(raw_texts, byte_tuples), 1 ): if byte_doc is not None: doc = Doc(self.vocab).from_bytes(byte_doc) doc._context = byte_context yield doc elif byte_error is not None: error = srsly.msgpack_loads(byte_error) self.default_error_handler( None, None, None, ValueError(Errors.E871.format(error=error)) ) if i % batch_size == 0: # tell `sender` that one batch was consumed. sender.step() finally: for proc in procs: proc.terminate() def _link_components(self) -> None: """Register 'listeners' within pipeline components, to allow them to effectively share weights. """ # I had thought, "Why do we do this inside the Language object? Shouldn't # it be the tok2vec/transformer/etc's job? # The problem is we need to do it during deserialization...And the # components don't receive the pipeline then. So this does have to be # here :( for i, (name1, proc1) in enumerate(self.pipeline): if isinstance(proc1, ty.ListenedToComponent): for name2, proc2 in self.pipeline[i + 1 :]: proc1.find_listeners(proc2) @classmethod def from_config( cls, config: Union[Dict[str, Any], Config] = {}, *, vocab: Union[Vocab, bool] = True, disable: Iterable[str] = SimpleFrozenList(), exclude: Iterable[str] = SimpleFrozenList(), meta: Dict[str, Any] = SimpleFrozenDict(), auto_fill: bool = True, validate: bool = True, ) -> "Language": """Create the nlp object from a loaded config. Will set up the tokenizer and language data, add pipeline components etc. If no config is provided, the default config of the given language is used. config (Dict[str, Any] / Config): The loaded config. vocab (Vocab): A Vocab object. If True, a vocab is created. disable (Iterable[str]): Names of pipeline components to disable. Disabled pipes will be loaded but they won't be run unless you explicitly enable them by calling nlp.enable_pipe. exclude (Iterable[str]): Names of pipeline components to exclude. Excluded components won't be loaded. meta (Dict[str, Any]): Meta overrides for nlp.meta. auto_fill (bool): Automatically fill in missing values in config based on defaults and function argument annotations. validate (bool): Validate the component config and arguments against the types expected by the factory. RETURNS (Language): The initialized Language class. DOCS: https://spacy.io/api/language#from_config """ if auto_fill: config = Config( cls.default_config, section_order=CONFIG_SECTION_ORDER ).merge(config) if "nlp" not in config: raise ValueError(Errors.E985.format(config=config)) config_lang = config["nlp"].get("lang") if config_lang is not None and config_lang != cls.lang: raise ValueError( Errors.E958.format( bad_lang_code=config["nlp"]["lang"], lang_code=cls.lang, lang=util.get_object_name(cls), ) ) config["nlp"]["lang"] = cls.lang # This isn't very elegant, but we remove the [components] block here to prevent # it from getting resolved (causes problems because we expect to pass in # the nlp and name args for each component). If we're auto-filling, we're # using the nlp.config with all defaults. config = util.copy_config(config) orig_pipeline = config.pop("components", {}) orig_pretraining = config.pop("pretraining", None) config["components"] = {} if auto_fill: filled = registry.fill(config, validate=validate, schema=ConfigSchema) else: filled = config filled["components"] = orig_pipeline config["components"] = orig_pipeline if orig_pretraining is not None: filled["pretraining"] = orig_pretraining config["pretraining"] = orig_pretraining resolved_nlp = registry.resolve( filled["nlp"], validate=validate, schema=ConfigSchemaNlp ) create_tokenizer = resolved_nlp["tokenizer"] before_creation = resolved_nlp["before_creation"] after_creation = resolved_nlp["after_creation"] after_pipeline_creation = resolved_nlp["after_pipeline_creation"] lang_cls = cls if before_creation is not None: lang_cls = before_creation(cls) if ( not isinstance(lang_cls, type) or not issubclass(lang_cls, cls) or lang_cls is not cls ): raise ValueError(Errors.E943.format(value=type(lang_cls))) # Warn about require_gpu usage in jupyter notebook warn_if_jupyter_cupy() # Note that we don't load vectors here, instead they get loaded explicitly # inside stuff like the spacy train function. If we loaded them here, # then we would load them twice at runtime: once when we make from config, # and then again when we load from disk. nlp = lang_cls(vocab=vocab, create_tokenizer=create_tokenizer, meta=meta) if after_creation is not None: nlp = after_creation(nlp) if not isinstance(nlp, cls): raise ValueError(Errors.E942.format(name="creation", value=type(nlp))) # To create the components we need to use the final interpolated config # so all values are available (if component configs use variables). # Later we replace the component config with the raw config again. interpolated = filled.interpolate() if not filled.is_interpolated else filled pipeline = interpolated.get("components", {}) sourced = util.get_sourced_components(interpolated) # If components are loaded from a source (existing models), we cache # them here so they're only loaded once source_nlps = {} source_nlp_vectors_hashes = {} vocab_b = None for pipe_name in config["nlp"]["pipeline"]: if pipe_name not in pipeline: opts = ", ".join(pipeline.keys()) raise ValueError(Errors.E956.format(name=pipe_name, opts=opts)) pipe_cfg = util.copy_config(pipeline[pipe_name]) raw_config = Config(filled["components"][pipe_name]) if pipe_name not in exclude: if "factory" not in pipe_cfg and "source" not in pipe_cfg: err = Errors.E984.format(name=pipe_name, config=pipe_cfg) raise ValueError(err) if "factory" in pipe_cfg: factory = pipe_cfg.pop("factory") # The pipe name (key in the config) here is the unique name # of the component, not necessarily the factory nlp.add_pipe( factory, name=pipe_name, config=pipe_cfg, validate=validate, raw_config=raw_config, ) else: # We need the sourced components to reference the same # vocab without modifying the current vocab state **AND** # we still want to load the source model vectors to perform # the vectors check. Since the source vectors clobber the # current ones, we save the original vocab state and # restore after this loop. Existing strings are preserved # during deserialization, so they do not need any # additional handling. if vocab_b is None: vocab_b = nlp.vocab.to_bytes(exclude=["lookups", "strings"]) model = pipe_cfg["source"] if model not in source_nlps: # Load with the same vocab, adding any strings source_nlps[model] = util.load_model( model, vocab=nlp.vocab, exclude=["lookups"] ) source_name = pipe_cfg.get("component", pipe_name) listeners_replaced = False if "replace_listeners" in pipe_cfg: for name, proc in source_nlps[model].pipeline: if source_name in getattr(proc, "listening_components", []): source_nlps[model].replace_listeners( name, source_name, pipe_cfg["replace_listeners"] ) listeners_replaced = True with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="\\[W113\\]") nlp.add_pipe( source_name, source=source_nlps[model], name=pipe_name ) if model not in source_nlp_vectors_hashes: source_nlp_vectors_hashes[model] = hash( source_nlps[model].vocab.vectors.to_bytes( exclude=["strings"] ) ) if "_sourced_vectors_hashes" not in nlp.meta: nlp.meta["_sourced_vectors_hashes"] = {} nlp.meta["_sourced_vectors_hashes"][ pipe_name ] = source_nlp_vectors_hashes[model] # Delete from cache if listeners were replaced if listeners_replaced: del source_nlps[model] # Restore the original vocab after sourcing if necessary if vocab_b is not None: nlp.vocab.from_bytes(vocab_b) disabled_pipes = [*config["nlp"]["disabled"], *disable] nlp._disabled = set(p for p in disabled_pipes if p not in exclude) nlp.batch_size = config["nlp"]["batch_size"] nlp.config = filled if auto_fill else config if after_pipeline_creation is not None: nlp = after_pipeline_creation(nlp) if not isinstance(nlp, cls): raise ValueError( Errors.E942.format(name="pipeline_creation", value=type(nlp)) ) # Detect components with listeners that are not frozen consistently for name, proc in nlp.pipeline: if isinstance(proc, ty.ListenedToComponent): # Remove listeners not in the pipeline listener_names = proc.listening_components unused_listener_names = [ ll for ll in listener_names if ll not in nlp.pipe_names ] for listener_name in unused_listener_names: for listener in proc.listener_map.get(listener_name, []): proc.remove_listener(listener, listener_name) for listener_name in proc.listening_components: # e.g. tok2vec/transformer # If it's a component sourced from another pipeline, we check if # the tok2vec listeners should be replaced with standalone tok2vec # models (e.g. so component can be frozen without its performance # degrading when other components/tok2vec are updated) paths = sourced.get(listener_name, {}).get("replace_listeners", []) if paths: nlp.replace_listeners(name, listener_name, paths) return nlp def replace_listeners( self, tok2vec_name: str, pipe_name: str, listeners: Iterable[str], ) -> None: """Find listener layers (connecting to a token-to-vector embedding component) of a given pipeline component model and replace them with a standalone copy of the token-to-vector layer. This can be useful when training a pipeline with components sourced from an existing pipeline: if multiple components (e.g. tagger, parser, NER) listen to the same tok2vec component, but some of them are frozen and not updated, their performance may degrade significally as the tok2vec component is updated with new data. To prevent this, listeners can be replaced with a standalone tok2vec layer that is owned by the component and doesn't change if the component isn't updated. tok2vec_name (str): Name of the token-to-vector component, typically "tok2vec" or "transformer". pipe_name (str): Name of pipeline component to replace listeners for. listeners (Iterable[str]): The paths to the listeners, relative to the component config, e.g. ["model.tok2vec"]. Typically, implementations will only connect to one tok2vec component, [model.tok2vec], but in theory, custom models can use multiple listeners. The value here can either be an empty list to not replace any listeners, or a complete (!) list of the paths to all listener layers used by the model. DOCS: https://spacy.io/api/language#replace_listeners """ if tok2vec_name not in self.pipe_names: err = Errors.E889.format( tok2vec=tok2vec_name, name=pipe_name, unknown=tok2vec_name, opts=", ".join(self.pipe_names), ) raise ValueError(err) if pipe_name not in self.pipe_names: err = Errors.E889.format( tok2vec=tok2vec_name, name=pipe_name, unknown=pipe_name, opts=", ".join(self.pipe_names), ) raise ValueError(err) tok2vec = self.get_pipe(tok2vec_name) tok2vec_cfg = self.get_pipe_config(tok2vec_name) if not isinstance(tok2vec, ty.ListenedToComponent): raise ValueError(Errors.E888.format(name=tok2vec_name, pipe=type(tok2vec))) tok2vec_model = tok2vec.model pipe_listeners = tok2vec.listener_map.get(pipe_name, []) pipe = self.get_pipe(pipe_name) pipe_cfg = self._pipe_configs[pipe_name] if listeners: util.logger.debug(f"Replacing listeners of component '{pipe_name}'") if len(list(listeners)) != len(pipe_listeners): # The number of listeners defined in the component model doesn't # match the listeners to replace, so we won't be able to update # the nodes and generate a matching config err = Errors.E887.format( name=pipe_name, tok2vec=tok2vec_name, paths=listeners, n_listeners=len(pipe_listeners), ) raise ValueError(err) # Update the config accordingly by copying the tok2vec model to all # sections defined in the listener paths for listener_path in listeners: # Check if the path actually exists in the config try: util.dot_to_object(pipe_cfg, listener_path) except KeyError: err = Errors.E886.format( name=pipe_name, tok2vec=tok2vec_name, path=listener_path ) raise ValueError(err) new_config = tok2vec_cfg["model"] if "replace_listener_cfg" in tok2vec_model.attrs: replace_func = tok2vec_model.attrs["replace_listener_cfg"] new_config = replace_func( tok2vec_cfg["model"], pipe_cfg["model"]["tok2vec"] ) util.set_dot_to_object(pipe_cfg, listener_path, new_config) # Go over the listener layers and replace them for listener in pipe_listeners: new_model = tok2vec_model.copy() if "replace_listener" in tok2vec_model.attrs: new_model = tok2vec_model.attrs["replace_listener"](new_model) util.replace_model_node(pipe.model, listener, new_model) # type: ignore[attr-defined] tok2vec.remove_listener(listener, pipe_name) def to_disk( self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList() ) -> None: """Save the current state to a directory. If a model is loaded, this will include the model. path (str / Path): Path to a directory, which will be created if it doesn't exist. exclude (Iterable[str]): Names of components or serialization fields to exclude. DOCS: https://spacy.io/api/language#to_disk """ path = util.ensure_path(path) serializers = {} serializers["tokenizer"] = lambda p: self.tokenizer.to_disk( # type: ignore[union-attr] p, exclude=["vocab"] ) serializers["meta.json"] = lambda p: srsly.write_json(p, self.meta) serializers["config.cfg"] = lambda p: self.config.to_disk(p) for name, proc in self._components: if name in exclude: continue if not hasattr(proc, "to_disk"): continue serializers[name] = lambda p, proc=proc: proc.to_disk(p, exclude=["vocab"]) # type: ignore[misc] serializers["vocab"] = lambda p: self.vocab.to_disk(p, exclude=exclude) util.to_disk(path, serializers, exclude) def from_disk( self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList(), overrides: Dict[str, Any] = SimpleFrozenDict(), ) -> "Language": """Loads state from a directory. Modifies the object in place and returns it. If the saved `Language` object contains a model, the model will be loaded. path (str / Path): A path to a directory. exclude (Iterable[str]): Names of components or serialization fields to exclude. RETURNS (Language): The modified `Language` object. DOCS: https://spacy.io/api/language#from_disk """ def deserialize_meta(path: Path) -> None: if path.exists(): data = srsly.read_json(path) self.meta.update(data) # self.meta always overrides meta["vectors"] with the metadata # from self.vocab.vectors, so set the name directly self.vocab.vectors.name = data.get("vectors", {}).get("name") def deserialize_vocab(path: Path) -> None: if path.exists(): self.vocab.from_disk(path, exclude=exclude) path = util.ensure_path(path) deserializers = {} if Path(path / "config.cfg").exists(): # type: ignore[operator] deserializers["config.cfg"] = lambda p: self.config.from_disk( p, interpolate=False, overrides=overrides ) deserializers["meta.json"] = deserialize_meta # type: ignore[assignment] deserializers["vocab"] = deserialize_vocab # type: ignore[assignment] deserializers["tokenizer"] = lambda p: self.tokenizer.from_disk( # type: ignore[union-attr] p, exclude=["vocab"] ) for name, proc in self._components: if name in exclude: continue if not hasattr(proc, "from_disk"): continue deserializers[name] = lambda p, proc=proc: proc.from_disk( # type: ignore[misc] p, exclude=["vocab"] ) if not (path / "vocab").exists() and "vocab" not in exclude: # type: ignore[operator] # Convert to list here in case exclude is (default) tuple exclude = list(exclude) + ["vocab"] util.from_disk(path, deserializers, exclude) # type: ignore[arg-type] self._path = path # type: ignore[assignment] self._link_components() return self def to_bytes(self, *, exclude: Iterable[str] = SimpleFrozenList()) -> bytes: """Serialize the current state to a binary string. exclude (Iterable[str]): Names of components or serialization fields to exclude. RETURNS (bytes): The serialized form of the `Language` object. DOCS: https://spacy.io/api/language#to_bytes """ serializers: Dict[str, Callable[[], bytes]] = {} serializers["vocab"] = lambda: self.vocab.to_bytes(exclude=exclude) serializers["tokenizer"] = lambda: self.tokenizer.to_bytes(exclude=["vocab"]) # type: ignore[union-attr] serializers["meta.json"] = lambda: srsly.json_dumps(self.meta) serializers["config.cfg"] = lambda: self.config.to_bytes() for name, proc in self._components: if name in exclude: continue if not hasattr(proc, "to_bytes"): continue serializers[name] = lambda proc=proc: proc.to_bytes(exclude=["vocab"]) # type: ignore[misc] return util.to_bytes(serializers, exclude) def from_bytes( self, bytes_data: bytes, *, exclude: Iterable[str] = SimpleFrozenList() ) -> "Language": """Load state from a binary string. bytes_data (bytes): The data to load from. exclude (Iterable[str]): Names of components or serialization fields to exclude. RETURNS (Language): The `Language` object. DOCS: https://spacy.io/api/language#from_bytes """ def deserialize_meta(b): data = srsly.json_loads(b) self.meta.update(data) # self.meta always overrides meta["vectors"] with the metadata # from self.vocab.vectors, so set the name directly self.vocab.vectors.name = data.get("vectors", {}).get("name") deserializers: Dict[str, Callable[[bytes], Any]] = {} deserializers["config.cfg"] = lambda b: self.config.from_bytes( b, interpolate=False ) deserializers["meta.json"] = deserialize_meta deserializers["vocab"] = lambda b: self.vocab.from_bytes(b, exclude=exclude) deserializers["tokenizer"] = lambda b: self.tokenizer.from_bytes( # type: ignore[union-attr] b, exclude=["vocab"] ) for name, proc in self._components: if name in exclude: continue if not hasattr(proc, "from_bytes"): continue deserializers[name] = lambda b, proc=proc: proc.from_bytes( # type: ignore[misc] b, exclude=["vocab"] ) util.from_bytes(bytes_data, deserializers, exclude) self._link_components() return self @dataclass class FactoryMeta: """Dataclass containing information about a component and its defaults provided by the @Language.component or @Language.factory decorator. It's created whenever a component is defined and stored on the Language class for each component instance and factory instance. """ factory: str default_config: Optional[Dict[str, Any]] = None # noqa: E704 assigns: Iterable[str] = tuple() requires: Iterable[str] = tuple() retokenizes: bool = False scores: Iterable[str] = tuple() default_score_weights: Optional[Dict[str, Optional[float]]] = None # noqa: E704 class DisabledPipes(list): """Manager for temporary pipeline disabling.""" def __init__(self, nlp: Language, names: List[str]) -> None: self.nlp = nlp self.names = names for name in self.names: self.nlp.disable_pipe(name) list.__init__(self) self.extend(self.names) def __enter__(self): return self def __exit__(self, *args): self.restore() def restore(self) -> None: """Restore the pipeline to its state when DisabledPipes was created.""" for name in self.names: if name not in self.nlp.component_names: raise ValueError(Errors.E008.format(name=name)) self.nlp.enable_pipe(name) self[:] = [] def _copy_examples(examples: Iterable[Example]) -> List[Example]: """Make a copy of a batch of examples, copying the predicted Doc as well. This is used in contexts where we need to take ownership of the examples so that they can be mutated, for instance during Language.evaluate and Language.update. """ return [Example(eg.x.copy(), eg.y) for eg in examples] def _apply_pipes( ensure_doc: Callable[[Union[str, Doc]], Doc], pipes: Iterable[Callable[..., Iterator[Doc]]], receiver, sender, underscore_state: Tuple[dict, dict, dict], ) -> None: """Worker for Language.pipe ensure_doc (Callable[[Union[str, Doc]], Doc]): Function to create Doc from text or raise an error if the input is neither a Doc nor a string. pipes (Iterable[Pipe]): The components to apply. receiver (multiprocessing.Connection): Pipe to receive text. Usually created by `multiprocessing.Pipe()` sender (multiprocessing.Connection): Pipe to send doc. Usually created by `multiprocessing.Pipe()` underscore_state (Tuple[dict, dict, dict]): The data in the Underscore class of the parent. """ Underscore.load_state(underscore_state) while True: try: texts = receiver.get() docs = (ensure_doc(text) for text in texts) for pipe in pipes: docs = pipe(docs) # type: ignore[arg-type, assignment] # Connection does not accept unpickable objects, so send list. byte_docs = [(doc.to_bytes(), doc._context, None) for doc in docs] padding = [(None, None, None)] * (len(texts) - len(byte_docs)) sender.send(byte_docs + padding) # type: ignore[operator] except Exception: error_msg = [(None, None, srsly.msgpack_dumps(traceback.format_exc()))] padding = [(None, None, None)] * (len(texts) - 1) sender.send(error_msg + padding) class _Sender: """Util for sending data to multiprocessing workers in Language.pipe""" def __init__( self, data: Iterable[Any], queues: List[mp.Queue], chunk_size: int ) -> None: self.data = iter(data) self.queues = iter(cycle(queues)) self.chunk_size = chunk_size self.count = 0 def send(self) -> None: """Send chunk_size items from self.data to channels.""" for item, q in itertools.islice( zip(self.data, cycle(self.queues)), self.chunk_size ): # cycle channels so that distribute the texts evenly q.put(item) def step(self) -> None: """Tell sender that comsumed one item. Data is sent to the workers after every chunk_size calls. """ self.count += 1 if self.count >= self.chunk_size: self.count = 0 self.send()
from __future__ import annotations __copyright__ = "Copyright (C) 2021 Kaushik Kulkarni" __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. """ import numpy as np import islpy as isl import pymbolic.primitives as prim from typing import (Tuple, List, Union, Callable, Any, Sequence, Dict, Optional, Iterable, TypeVar) from pytato.array import (Array, ShapeType, IndexLambda, SizeParam, ShapeComponent, DtypeOrScalar, ArrayOrScalar, BasicIndex, AdvancedIndexInContiguousAxes, AdvancedIndexInNoncontiguousAxes, ConvertibleToIndexExpr, IndexExpr, NormalizedSlice) from pytato.scalar_expr import (ScalarExpression, IntegralScalarExpression, SCALAR_CLASSES, INT_CLASSES, BoolT) from pytools import UniqueNameGenerator from pytato.transform import Mapper __doc__ = """ Helper routines --------------- .. autofunction:: are_shape_components_equal .. autofunction:: are_shapes_equal .. autofunction:: get_shape_after_broadcasting .. autofunction:: dim_to_index_lambda_components """ # {{{ partition Tpart = TypeVar("Tpart") def partition(pred: Callable[[Tpart], bool], iterable: Iterable[Tpart]) -> Tuple[List[Tpart], List[Tpart]]: """ Use a predicate to partition entries into false entries and true entries """ # Inspired from https://docs.python.org/3/library/itertools.html # partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 from itertools import tee, filterfalse t1, t2 = tee(iterable) return list(filterfalse(pred, t1)), list(filter(pred, t2)) # }}} def get_shape_after_broadcasting( exprs: Iterable[Union[Array, ScalarExpression]]) -> ShapeType: """ Returns the shape after broadcasting *exprs* in an operation. """ from pytato.diagnostic import CannotBroadcastError shapes = [expr.shape if isinstance(expr, Array) else () for expr in exprs] result_dim = max((len(s) for s in shapes), default=0) # append leading dimensions of all the shapes with 1's to match result_dim. augmented_shapes = [((1,)*(result_dim-len(s)) + s) for s in shapes] def _get_result_axis_length(axis_lengths: List[IntegralScalarExpression] ) -> IntegralScalarExpression: result_axis_len = axis_lengths[0] for axis_len in axis_lengths[1:]: if are_shape_components_equal(axis_len, result_axis_len): pass elif are_shape_components_equal(axis_len, 1): pass elif are_shape_components_equal(result_axis_len, 1): result_axis_len = axis_len else: raise CannotBroadcastError("operands could not be broadcasted " "together with shapes " f"{" ".join(str(s) for s in shapes)}.") return result_axis_len return tuple(_get_result_axis_length([s[i] for s in augmented_shapes]) for i in range(result_dim)) def get_indexing_expression(shape: ShapeType, result_shape: ShapeType) -> Tuple[ScalarExpression, ...]: """ Returns the indices while broadcasting an array of shape *shape* into one of shape *result_shape*. """ assert len(shape) <= len(result_shape) i_start = len(result_shape) - len(shape) indices = [] for i, (dim1, dim2) in enumerate(zip(shape, result_shape[i_start:])): if not are_shape_components_equal(dim1, dim2): assert are_shape_components_equal(dim1, 1) indices.append(0) else: indices.append(prim.Variable(f"_{i+i_start}")) return tuple(indices) def with_indices_for_broadcasted_shape(val: prim.Variable, shape: ShapeType, result_shape: ShapeType) -> prim.Expression: if len(shape) == 0: # scalar expr => do not index return val else: return val[get_indexing_expression(shape, result_shape)] def extract_dtypes_or_scalars( exprs: Sequence[ArrayOrScalar]) -> List[DtypeOrScalar]: dtypes: List[DtypeOrScalar] = [] for expr in exprs: if isinstance(expr, Array): dtypes.append(expr.dtype) else: assert isinstance(expr, SCALAR_CLASSES) dtypes.append(expr) return dtypes def update_bindings_and_get_broadcasted_expr(arr: ArrayOrScalar, bnd_name: str, bindings: Dict[str, Array], result_shape: ShapeType ) -> ScalarExpression: """ Returns an instance of :class:`~pytato.scalar_expr.ScalarExpression` to address *arr* in a :class:`pytato.array.IndexLambda` of shape *result_shape*. """ if isinstance(arr, SCALAR_CLASSES): return arr assert isinstance(arr, Array) bindings[bnd_name] = arr return with_indices_for_broadcasted_shape(prim.Variable(bnd_name), arr.shape, result_shape) def broadcast_binary_op(a1: ArrayOrScalar, a2: ArrayOrScalar, op: Callable[[ScalarExpression, ScalarExpression], ScalarExpression], # noqa:E501 get_result_type: Callable[[DtypeOrScalar, DtypeOrScalar], np.dtype[Any]], # noqa:E501 ) -> ArrayOrScalar: from pytato.array import _get_default_axes if isinstance(a1, SCALAR_CLASSES): a1 = np.dtype(type(a1)).type(a1) if isinstance(a2, SCALAR_CLASSES): a2 = np.dtype(type(a2)).type(a2) if np.isscalar(a1) and np.isscalar(a2): from pytato.scalar_expr import evaluate return evaluate(op(a1, a2)) # type: ignore result_shape = get_shape_after_broadcasting([a1, a2]) dtypes = extract_dtypes_or_scalars([a1, a2]) result_dtype = get_result_type(*dtypes) bindings: Dict[str, Array] = {} expr1 = update_bindings_and_get_broadcasted_expr(a1, "_in0", bindings, result_shape) expr2 = update_bindings_and_get_broadcasted_expr(a2, "_in1", bindings, result_shape) return IndexLambda(op(expr1, expr2), shape=result_shape, dtype=result_dtype, bindings=bindings, axes=_get_default_axes(len(result_shape))) # {{{ dim_to_index_lambda_components class ShapeExpressionMapper(Mapper): """ Mapper that takes a shape component and returns it as a scalar expression. """ def __init__(self, var_name_gen: UniqueNameGenerator): self.cache: Dict[Array, ScalarExpression] = {} self.var_name_gen = var_name_gen self.bindings: Dict[str, SizeParam] = {} def rec(self, expr: Array) -> ScalarExpression: # type: ignore if expr in self.cache: return self.cache[expr] result: Array = super().rec(expr) self.cache[expr] = result return result def map_index_lambda(self, expr: IndexLambda) -> ScalarExpression: from pytato.scalar_expr import substitute return substitute(expr.expr, {name: self.rec(val) for name, val in expr.bindings.items()}) def map_size_param(self, expr: SizeParam) -> ScalarExpression: name = self.var_name_gen("_in") self.bindings[name] = expr return prim.Variable(name) def dim_to_index_lambda_components(expr: ShapeComponent, vng: Optional[UniqueNameGenerator] = None, ) -> Tuple[ScalarExpression, Dict[str, SizeParam]]: """ Returns the scalar expressions and bindings to use the shape component within an index lambda. .. testsetup:: >>> import pytato as pt >>> from pytato.utils import dim_to_index_lambda_components >>> from pytools import UniqueNameGenerator .. doctest:: >>> n = pt.make_size_param("n") >>> expr, bnds = dim_to_index_lambda_components(3*n+8, UniqueNameGenerator()) >>> print(expr) 3*_in + 8 >>> bnds {'_in': SizeParam(name='n')} """ if isinstance(expr, INT_CLASSES): return expr, {} if vng is None: vng = UniqueNameGenerator() assert isinstance(vng, UniqueNameGenerator) assert isinstance(expr, Array) mapper = ShapeExpressionMapper(vng) result = mapper(expr) return result, mapper.bindings # }}} def are_shape_components_equal(dim1: ShapeComponent, dim2: ShapeComponent) -> bool: """ Returns *True* iff *dim1* and *dim2* are have equal :class:`~pytato.array.SizeParam` coefficients in their expressions. """ if isinstance(dim1, INT_CLASSES) and isinstance(dim2, INT_CLASSES): return dim1 == dim2 dim1_minus_dim2 = dim1 - dim2 assert isinstance(dim1_minus_dim2, Array) from pytato.transform import InputGatherer # type-ignore reason: not all InputArgumentBase have a name attr. space = _create_size_param_space({expr.name # type: ignore[attr-defined] for expr in InputGatherer()(dim1_minus_dim2)}) # pytato requires the shape expressions be affine expressions of the size # params, so converting them to ISL expressions. aff = ShapeToISLExpressionMapper(space)(dim1_minus_dim2) return (aff.is_cst() # type: ignore[no-any-return] and aff.get_constant_val().is_zero()) def are_shapes_equal(shape1: ShapeType, shape2: ShapeType) -> bool: """ Returns *True* iff *shape1* and *shape2* have the same dimensionality and the correpsonding components are equal as defined by :func:`~pytato.utils.are_shape_components_equal`. """ return ((len(shape1) == len(shape2)) and all(are_shape_components_equal(dim1, dim2) for dim1, dim2 in zip(shape1, shape2))) # {{{ ShapeToISLExpressionMapper class ShapeToISLExpressionMapper(Mapper): """ Mapper that takes a shape component and returns it as :class:`isl.Aff`. """ def __init__(self, space: isl.Space): self.cache: Dict[Array, isl.Aff] = {} self.space = space # type-ignore reason: incompatible return type with super class def rec(self, expr: Array) -> isl.Aff: # type: ignore[override] if expr in self.cache: return self.cache[expr] result: Array = super().rec(expr) self.cache[expr] = result return result def map_index_lambda(self, expr: IndexLambda) -> isl.Aff: from pytato.scalar_expr import evaluate return evaluate(expr.expr, {name: self.rec(val) for name, val in expr.bindings.items()}) def map_size_param(self, expr: SizeParam) -> isl.Aff: dt, pos = self.space.get_var_dict()[expr.name] return isl.Aff.var_on_domain(self.space, dt, pos) # }}} def _create_size_param_space(names: Iterable[str]) -> isl.Space: return isl.Space.create_from_names(isl.DEFAULT_CONTEXT, set=[], params=sorted(names)).params() def _get_size_params_assumptions_bset(space: isl.Space) -> isl.BasicSet: bset = isl.BasicSet.universe(space) for name in bset.get_var_dict(): bset = bset.add_constraint(isl.Constraint.ineq_from_names(space, {name: 1})) return bset def _is_non_negative(expr: ShapeComponent) -> BoolT: """ Returns *True* iff it can be proven that ``expr >= 0``. """ if isinstance(expr, INT_CLASSES): return expr >= 0 assert isinstance(expr, Array) and expr.shape == () from pytato.transform import InputGatherer # type-ignore reason: passed Set[Optional[str]]; function expects Set[str] space = _create_size_param_space({expr.name # type: ignore for expr in InputGatherer()(expr)}) aff = ShapeToISLExpressionMapper(space)(expr) # type-ignore reason: mypy doesn't know comparing isl.Sets returns bool return (aff.ge_set(aff * 0) # type: ignore[no-any-return] <= _get_size_params_assumptions_bset(space)) def _is_non_positive(expr: ShapeComponent) -> BoolT: """ Returns *True* iff it can be proven that ``expr <= 0``. """ return _is_non_negative(-expr) # {{{ _index_into # {{{ normalized slice def _normalize_slice(slice_: slice, axis_len: ShapeComponent) -> NormalizedSlice: start, stop, step = slice_.start, slice_.stop, slice_.step if step is None: step = 1 if not isinstance(step, INT_CLASSES): raise ValueError(f"slice step must be an int or 'None' (got a {type(step)})") if step == 0: raise ValueError("slice step cannot be zero") if step > 0: default_start: ShapeComponent = 0 default_stop: ShapeComponent = axis_len else: default_start = axis_len - 1 default_stop = -1 if start is None: start = default_start else: if isinstance(axis_len, INT_CLASSES): if -axis_len <= start < axis_len: start = start % axis_len elif start >= axis_len: if step > 0: start = axis_len else: start = axis_len - 1 else: if step > 0: start = 0 else: start = -1 else: raise NotImplementedError if stop is None: stop = default_stop else: if isinstance(axis_len, INT_CLASSES): if -axis_len <= stop < axis_len: stop = stop % axis_len elif stop >= axis_len: if step > 0: stop = axis_len else: stop = axis_len - 1 else: if step > 0: stop = 0 else: stop = -1 else: raise NotImplementedError return NormalizedSlice(start, stop, step) def _normalized_slice_len(slice_: NormalizedSlice) -> ShapeComponent: start, stop, step = slice_.start, slice_.stop, slice_.step if step > 0: if _is_non_negative(stop - start): return (stop - start + step - 1) // step elif _is_non_positive(stop - start): return 0 else: # ISL could not ascertain the expression's sign raise NotImplementedError("could not ascertain the sign of " f"{stop-start} while computing the axis" " length.") else: if _is_non_negative(start - stop): return (start - stop - step - 1) // (-step) elif _is_non_positive(start - stop): return 0 else: # ISL could not ascertain the expression's sign raise NotImplementedError("could not ascertain the sign of " f"{start-stop} while computing the axis" " length.") # }}} def _index_into(ary: Array, indices: Tuple[ConvertibleToIndexExpr, ...]) -> Array: from pytato.diagnostic import CannotBroadcastError from pytato.array import _get_default_axes # {{{ handle ellipsis if indices.count(...) > 1: raise IndexError("an index can only have a single ellipsis ('...')") if indices.count(...): ellipsis_pos = indices.index(...) indices = (indices[:ellipsis_pos] + (slice(None, None, None),) * (ary.ndim - len(indices) + 1) + indices[ellipsis_pos+1:]) # }}} # {{{ "pad" index with complete slices to match ary's ndim if len(indices) < ary.ndim: indices = indices + (slice(None, None, None),) * (ary.ndim - len(indices)) # }}} if len(indices) != ary.ndim: raise IndexError(f"Too many indices (expected {ary.ndim}" f", got {len(indices)})") if any(idx is None for idx in indices): raise NotImplementedError("newaxis is not supported") # {{{ validate broadcastability of the array indices try: array_idx_shape = get_shape_after_broadcasting( [idx for idx in indices if isinstance(idx, Array)]) except CannotBroadcastError as e: raise IndexError(str(e)) # }}} # {{{ validate index for i, idx in enumerate(indices): if isinstance(idx, slice): pass elif isinstance(idx, INT_CLASSES): if not (_is_non_negative(idx + ary.shape[i]) and _is_non_negative(ary.shape[i] - 1 - idx)): raise IndexError(f"{idx} is out of bounds for axis {i}") elif isinstance(idx, Array): if idx.dtype.kind != "i": raise IndexError("only integer arrays are valid array indices") else: raise IndexError("only integers, slices, ellipsis and integer arrays" " are valid indices") # }}} # {{{ normalize slices normalized_indices: List[IndexExpr] = [_normalize_slice(idx, axis_len) if isinstance(idx, slice) else idx for idx, axis_len in zip(indices, ary.shape)] del indices # }}} if any(isinstance(idx, Array) for idx in normalized_indices): # advanced indexing expression i_adv_indices, i_basic_indices = partition( lambda idx: isinstance( normalized_indices[idx], NormalizedSlice), range(len(normalized_indices))) if any(i_adv_indices[0] < i_basic_idx < i_adv_indices[-1] for i_basic_idx in i_basic_indices): # non contiguous advanced indices return AdvancedIndexInNoncontiguousAxes( ary, tuple(normalized_indices), axes=_get_default_axes(len(array_idx_shape) + len(i_basic_indices))) else: return AdvancedIndexInContiguousAxes( ary, tuple(normalized_indices), axes=_get_default_axes(len(array_idx_shape) + len(i_basic_indices))) else: # basic indexing expression return BasicIndex(ary, tuple(normalized_indices), axes=_get_default_axes( len([idx for idx in normalized_indices if isinstance(idx, NormalizedSlice)]))) # }}}
from __future__ import annotations __copyright__ = "Copyright (C) 2021 Kaushik Kulkarni" __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. """ import numpy as np import islpy as isl import pymbolic.primitives as prim from typing import (Tuple, List, Union, Callable, Any, Sequence, Dict, Optional, Iterable, TypeVar) from pytato.array import (Array, ShapeType, IndexLambda, SizeParam, ShapeComponent, DtypeOrScalar, ArrayOrScalar, BasicIndex, AdvancedIndexInContiguousAxes, AdvancedIndexInNoncontiguousAxes, ConvertibleToIndexExpr, IndexExpr, NormalizedSlice) from pytato.scalar_expr import (ScalarExpression, IntegralScalarExpression, SCALAR_CLASSES, INT_CLASSES, BoolT) from pytools import UniqueNameGenerator from pytato.transform import Mapper __doc__ = """ Helper routines --------------- .. autofunction:: are_shape_components_equal .. autofunction:: are_shapes_equal .. autofunction:: get_shape_after_broadcasting .. autofunction:: dim_to_index_lambda_components """ # {{{ partition Tpart = TypeVar("Tpart") def partition(pred: Callable[[Tpart], bool], iterable: Iterable[Tpart]) -> Tuple[List[Tpart], List[Tpart]]: """ Use a predicate to partition entries into false entries and true entries """ # Inspired from https://docs.python.org/3/library/itertools.html # partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 from itertools import tee, filterfalse t1, t2 = tee(iterable) return list(filterfalse(pred, t1)), list(filter(pred, t2)) # }}} def get_shape_after_broadcasting( exprs: Iterable[Union[Array, ScalarExpression]]) -> ShapeType: """ Returns the shape after broadcasting *exprs* in an operation. """ from pytato.diagnostic import CannotBroadcastError shapes = [expr.shape if isinstance(expr, Array) else () for expr in exprs] result_dim = max((len(s) for s in shapes), default=0) # append leading dimensions of all the shapes with 1's to match result_dim. augmented_shapes = [((1,)*(result_dim-len(s)) + s) for s in shapes] def _get_result_axis_length(axis_lengths: List[IntegralScalarExpression] ) -> IntegralScalarExpression: result_axis_len = axis_lengths[0] for axis_len in axis_lengths[1:]: if are_shape_components_equal(axis_len, result_axis_len): pass elif are_shape_components_equal(axis_len, 1): pass elif are_shape_components_equal(result_axis_len, 1): result_axis_len = axis_len else: raise CannotBroadcastError("operands could not be broadcasted " "together with shapes " f"{' '.join(str(s) for s in shapes)}.") return result_axis_len return tuple(_get_result_axis_length([s[i] for s in augmented_shapes]) for i in range(result_dim)) def get_indexing_expression(shape: ShapeType, result_shape: ShapeType) -> Tuple[ScalarExpression, ...]: """ Returns the indices while broadcasting an array of shape *shape* into one of shape *result_shape*. """ assert len(shape) <= len(result_shape) i_start = len(result_shape) - len(shape) indices = [] for i, (dim1, dim2) in enumerate(zip(shape, result_shape[i_start:])): if not are_shape_components_equal(dim1, dim2): assert are_shape_components_equal(dim1, 1) indices.append(0) else: indices.append(prim.Variable(f"_{i+i_start}")) return tuple(indices) def with_indices_for_broadcasted_shape(val: prim.Variable, shape: ShapeType, result_shape: ShapeType) -> prim.Expression: if len(shape) == 0: # scalar expr => do not index return val else: return val[get_indexing_expression(shape, result_shape)] def extract_dtypes_or_scalars( exprs: Sequence[ArrayOrScalar]) -> List[DtypeOrScalar]: dtypes: List[DtypeOrScalar] = [] for expr in exprs: if isinstance(expr, Array): dtypes.append(expr.dtype) else: assert isinstance(expr, SCALAR_CLASSES) dtypes.append(expr) return dtypes def update_bindings_and_get_broadcasted_expr(arr: ArrayOrScalar, bnd_name: str, bindings: Dict[str, Array], result_shape: ShapeType ) -> ScalarExpression: """ Returns an instance of :class:`~pytato.scalar_expr.ScalarExpression` to address *arr* in a :class:`pytato.array.IndexLambda` of shape *result_shape*. """ if isinstance(arr, SCALAR_CLASSES): return arr assert isinstance(arr, Array) bindings[bnd_name] = arr return with_indices_for_broadcasted_shape(prim.Variable(bnd_name), arr.shape, result_shape) def broadcast_binary_op(a1: ArrayOrScalar, a2: ArrayOrScalar, op: Callable[[ScalarExpression, ScalarExpression], ScalarExpression], # noqa:E501 get_result_type: Callable[[DtypeOrScalar, DtypeOrScalar], np.dtype[Any]], # noqa:E501 ) -> ArrayOrScalar: from pytato.array import _get_default_axes if isinstance(a1, SCALAR_CLASSES): a1 = np.dtype(type(a1)).type(a1) if isinstance(a2, SCALAR_CLASSES): a2 = np.dtype(type(a2)).type(a2) if np.isscalar(a1) and np.isscalar(a2): from pytato.scalar_expr import evaluate return evaluate(op(a1, a2)) # type: ignore result_shape = get_shape_after_broadcasting([a1, a2]) dtypes = extract_dtypes_or_scalars([a1, a2]) result_dtype = get_result_type(*dtypes) bindings: Dict[str, Array] = {} expr1 = update_bindings_and_get_broadcasted_expr(a1, "_in0", bindings, result_shape) expr2 = update_bindings_and_get_broadcasted_expr(a2, "_in1", bindings, result_shape) return IndexLambda(op(expr1, expr2), shape=result_shape, dtype=result_dtype, bindings=bindings, axes=_get_default_axes(len(result_shape))) # {{{ dim_to_index_lambda_components class ShapeExpressionMapper(Mapper): """ Mapper that takes a shape component and returns it as a scalar expression. """ def __init__(self, var_name_gen: UniqueNameGenerator): self.cache: Dict[Array, ScalarExpression] = {} self.var_name_gen = var_name_gen self.bindings: Dict[str, SizeParam] = {} def rec(self, expr: Array) -> ScalarExpression: # type: ignore if expr in self.cache: return self.cache[expr] result: Array = super().rec(expr) self.cache[expr] = result return result def map_index_lambda(self, expr: IndexLambda) -> ScalarExpression: from pytato.scalar_expr import substitute return substitute(expr.expr, {name: self.rec(val) for name, val in expr.bindings.items()}) def map_size_param(self, expr: SizeParam) -> ScalarExpression: name = self.var_name_gen("_in") self.bindings[name] = expr return prim.Variable(name) def dim_to_index_lambda_components(expr: ShapeComponent, vng: Optional[UniqueNameGenerator] = None, ) -> Tuple[ScalarExpression, Dict[str, SizeParam]]: """ Returns the scalar expressions and bindings to use the shape component within an index lambda. .. testsetup:: >>> import pytato as pt >>> from pytato.utils import dim_to_index_lambda_components >>> from pytools import UniqueNameGenerator .. doctest:: >>> n = pt.make_size_param("n") >>> expr, bnds = dim_to_index_lambda_components(3*n+8, UniqueNameGenerator()) >>> print(expr) 3*_in + 8 >>> bnds {'_in': SizeParam(name='n')} """ if isinstance(expr, INT_CLASSES): return expr, {} if vng is None: vng = UniqueNameGenerator() assert isinstance(vng, UniqueNameGenerator) assert isinstance(expr, Array) mapper = ShapeExpressionMapper(vng) result = mapper(expr) return result, mapper.bindings # }}} def are_shape_components_equal(dim1: ShapeComponent, dim2: ShapeComponent) -> bool: """ Returns *True* iff *dim1* and *dim2* are have equal :class:`~pytato.array.SizeParam` coefficients in their expressions. """ if isinstance(dim1, INT_CLASSES) and isinstance(dim2, INT_CLASSES): return dim1 == dim2 dim1_minus_dim2 = dim1 - dim2 assert isinstance(dim1_minus_dim2, Array) from pytato.transform import InputGatherer # type-ignore reason: not all InputArgumentBase have a name attr. space = _create_size_param_space({expr.name # type: ignore[attr-defined] for expr in InputGatherer()(dim1_minus_dim2)}) # pytato requires the shape expressions be affine expressions of the size # params, so converting them to ISL expressions. aff = ShapeToISLExpressionMapper(space)(dim1_minus_dim2) return (aff.is_cst() # type: ignore[no-any-return] and aff.get_constant_val().is_zero()) def are_shapes_equal(shape1: ShapeType, shape2: ShapeType) -> bool: """ Returns *True* iff *shape1* and *shape2* have the same dimensionality and the correpsonding components are equal as defined by :func:`~pytato.utils.are_shape_components_equal`. """ return ((len(shape1) == len(shape2)) and all(are_shape_components_equal(dim1, dim2) for dim1, dim2 in zip(shape1, shape2))) # {{{ ShapeToISLExpressionMapper class ShapeToISLExpressionMapper(Mapper): """ Mapper that takes a shape component and returns it as :class:`isl.Aff`. """ def __init__(self, space: isl.Space): self.cache: Dict[Array, isl.Aff] = {} self.space = space # type-ignore reason: incompatible return type with super class def rec(self, expr: Array) -> isl.Aff: # type: ignore[override] if expr in self.cache: return self.cache[expr] result: Array = super().rec(expr) self.cache[expr] = result return result def map_index_lambda(self, expr: IndexLambda) -> isl.Aff: from pytato.scalar_expr import evaluate return evaluate(expr.expr, {name: self.rec(val) for name, val in expr.bindings.items()}) def map_size_param(self, expr: SizeParam) -> isl.Aff: dt, pos = self.space.get_var_dict()[expr.name] return isl.Aff.var_on_domain(self.space, dt, pos) # }}} def _create_size_param_space(names: Iterable[str]) -> isl.Space: return isl.Space.create_from_names(isl.DEFAULT_CONTEXT, set=[], params=sorted(names)).params() def _get_size_params_assumptions_bset(space: isl.Space) -> isl.BasicSet: bset = isl.BasicSet.universe(space) for name in bset.get_var_dict(): bset = bset.add_constraint(isl.Constraint.ineq_from_names(space, {name: 1})) return bset def _is_non_negative(expr: ShapeComponent) -> BoolT: """ Returns *True* iff it can be proven that ``expr >= 0``. """ if isinstance(expr, INT_CLASSES): return expr >= 0 assert isinstance(expr, Array) and expr.shape == () from pytato.transform import InputGatherer # type-ignore reason: passed Set[Optional[str]]; function expects Set[str] space = _create_size_param_space({expr.name # type: ignore for expr in InputGatherer()(expr)}) aff = ShapeToISLExpressionMapper(space)(expr) # type-ignore reason: mypy doesn't know comparing isl.Sets returns bool return (aff.ge_set(aff * 0) # type: ignore[no-any-return] <= _get_size_params_assumptions_bset(space)) def _is_non_positive(expr: ShapeComponent) -> BoolT: """ Returns *True* iff it can be proven that ``expr <= 0``. """ return _is_non_negative(-expr) # {{{ _index_into # {{{ normalized slice def _normalize_slice(slice_: slice, axis_len: ShapeComponent) -> NormalizedSlice: start, stop, step = slice_.start, slice_.stop, slice_.step if step is None: step = 1 if not isinstance(step, INT_CLASSES): raise ValueError(f"slice step must be an int or 'None' (got a {type(step)})") if step == 0: raise ValueError("slice step cannot be zero") if step > 0: default_start: ShapeComponent = 0 default_stop: ShapeComponent = axis_len else: default_start = axis_len - 1 default_stop = -1 if start is None: start = default_start else: if isinstance(axis_len, INT_CLASSES): if -axis_len <= start < axis_len: start = start % axis_len elif start >= axis_len: if step > 0: start = axis_len else: start = axis_len - 1 else: if step > 0: start = 0 else: start = -1 else: raise NotImplementedError if stop is None: stop = default_stop else: if isinstance(axis_len, INT_CLASSES): if -axis_len <= stop < axis_len: stop = stop % axis_len elif stop >= axis_len: if step > 0: stop = axis_len else: stop = axis_len - 1 else: if step > 0: stop = 0 else: stop = -1 else: raise NotImplementedError return NormalizedSlice(start, stop, step) def _normalized_slice_len(slice_: NormalizedSlice) -> ShapeComponent: start, stop, step = slice_.start, slice_.stop, slice_.step if step > 0: if _is_non_negative(stop - start): return (stop - start + step - 1) // step elif _is_non_positive(stop - start): return 0 else: # ISL could not ascertain the expression's sign raise NotImplementedError("could not ascertain the sign of " f"{stop-start} while computing the axis" " length.") else: if _is_non_negative(start - stop): return (start - stop - step - 1) // (-step) elif _is_non_positive(start - stop): return 0 else: # ISL could not ascertain the expression's sign raise NotImplementedError("could not ascertain the sign of " f"{start-stop} while computing the axis" " length.") # }}} def _index_into(ary: Array, indices: Tuple[ConvertibleToIndexExpr, ...]) -> Array: from pytato.diagnostic import CannotBroadcastError from pytato.array import _get_default_axes # {{{ handle ellipsis if indices.count(...) > 1: raise IndexError("an index can only have a single ellipsis ('...')") if indices.count(...): ellipsis_pos = indices.index(...) indices = (indices[:ellipsis_pos] + (slice(None, None, None),) * (ary.ndim - len(indices) + 1) + indices[ellipsis_pos+1:]) # }}} # {{{ "pad" index with complete slices to match ary's ndim if len(indices) < ary.ndim: indices = indices + (slice(None, None, None),) * (ary.ndim - len(indices)) # }}} if len(indices) != ary.ndim: raise IndexError(f"Too many indices (expected {ary.ndim}" f", got {len(indices)})") if any(idx is None for idx in indices): raise NotImplementedError("newaxis is not supported") # {{{ validate broadcastability of the array indices try: array_idx_shape = get_shape_after_broadcasting( [idx for idx in indices if isinstance(idx, Array)]) except CannotBroadcastError as e: raise IndexError(str(e)) # }}} # {{{ validate index for i, idx in enumerate(indices): if isinstance(idx, slice): pass elif isinstance(idx, INT_CLASSES): if not (_is_non_negative(idx + ary.shape[i]) and _is_non_negative(ary.shape[i] - 1 - idx)): raise IndexError(f"{idx} is out of bounds for axis {i}") elif isinstance(idx, Array): if idx.dtype.kind != "i": raise IndexError("only integer arrays are valid array indices") else: raise IndexError("only integers, slices, ellipsis and integer arrays" " are valid indices") # }}} # {{{ normalize slices normalized_indices: List[IndexExpr] = [_normalize_slice(idx, axis_len) if isinstance(idx, slice) else idx for idx, axis_len in zip(indices, ary.shape)] del indices # }}} if any(isinstance(idx, Array) for idx in normalized_indices): # advanced indexing expression i_adv_indices, i_basic_indices = partition( lambda idx: isinstance( normalized_indices[idx], NormalizedSlice), range(len(normalized_indices))) if any(i_adv_indices[0] < i_basic_idx < i_adv_indices[-1] for i_basic_idx in i_basic_indices): # non contiguous advanced indices return AdvancedIndexInNoncontiguousAxes( ary, tuple(normalized_indices), axes=_get_default_axes(len(array_idx_shape) + len(i_basic_indices))) else: return AdvancedIndexInContiguousAxes( ary, tuple(normalized_indices), axes=_get_default_axes(len(array_idx_shape) + len(i_basic_indices))) else: # basic indexing expression return BasicIndex(ary, tuple(normalized_indices), axes=_get_default_axes( len([idx for idx in normalized_indices if isinstance(idx, NormalizedSlice)]))) # }}}
from typing import Union, Tuple, Callable, Any import torch import copy import numpy as np class Point(torch.Tensor): """ A point has a variable number of coordinates specified in the constructor. Each point is immutable. """ __values: Union[Tuple[float, ...], Tuple[int, ...]] __is_float: bool def __new__(cls, *ords, **kwargs): return torch.Tensor.__new__(cls, len(ords)) def __init__(self, *ords, **kwargs): if ("x" in kwargs and "y" in kwargs): ords = (kwargs["x"], kwargs["y"]) if ("z" in kwargs): ords = (*ords, kwargs["z"]) assert (len(ords) > 1), "Needs at least two dimensions" super().__init__() all_integers = all(map(lambda x: float(x).is_integer(), ords)) self.__is_float = not all_integers cast_type = int if all_integers else float self.__values = tuple(cast_type(i) for i in ords) self.data = torch.FloatTensor(self.__values) @property def x(self) -> Union[float, int]: return self.__values[0] @property def y(self) -> Union[float, int]: return self.__values[1] @property def z(self) -> Union[float, int]: assert len(self.__values) > 2, "Point has no Z-coordinate" return self.__values[2] @property def n_dim(self) -> int: return len(self.__values) @property def values(self) -> Union[Tuple[float, ...], Tuple[int, ...]]: return self.__values @property def is_float(self) -> bool: return self.__is_float def __getitem__(self, idx) -> Union[float, int]: return self.__values[idx] def __iter__(self) -> Union[Tuple[float, ...], Tuple[int, ...]]: return iter(self.__values) def to_tensor(self) -> torch.Tensor: return torch.Tensor([float(c) for c in self.__values]) @staticmethod def from_tensor(inp: torch.Tensor) -> 'Point': assert len(list(inp.size())) == 1 return Point(*[int(torch.round(inp[i])) for i in range(list(inp.size())[0])]) def __add__(self, other: Any) -> 'Point': return Point(*np.add(self.__values, other.__values if type(other) is Point else other)) def __sub__(self, other: Any) -> 'Point': return Point(*np.subtract(self.__values, other.__values if type(other) is Point else other)) def __mul__(self, other: Any) -> 'Point': return Point(*np.multiply(self.__values, other.__values if type(other) is Point else other)) def __truediv__(self, other: Any) -> 'Point': return Point(*np.divide(self.__values, other.__values if type(other) is Point else other)) def __eq__(self, other: object) -> bool: return isinstance(other, Point) and (self.__values == other.__values) def __ne__(self, other: object) -> bool: return not (self == other) def __lt__(self, other: object) -> bool: assert isinstance(other, Point), "Must compare with another point" return self.__values < other.__values def __hash__(self) -> int: return hash(self.__values) def __repr__(self) -> str: # want to print floats as ints for test, if doing so wouldn't change them return f"Point({", ".join(str(i) for i in self.__values)})" def __copy__(self) -> 'Point': return copy.deepcopy(self) def __deepcopy__(self, memo: dict) -> 'Point': return Point(*self.__values)
from typing import Union, Tuple, Callable, Any import torch import copy import numpy as np class Point(torch.Tensor): """ A point has a variable number of coordinates specified in the constructor. Each point is immutable. """ __values: Union[Tuple[float, ...], Tuple[int, ...]] __is_float: bool def __new__(cls, *ords, **kwargs): return torch.Tensor.__new__(cls, len(ords)) def __init__(self, *ords, **kwargs): if ("x" in kwargs and "y" in kwargs): ords = (kwargs["x"], kwargs["y"]) if ("z" in kwargs): ords = (*ords, kwargs["z"]) assert (len(ords) > 1), "Needs at least two dimensions" super().__init__() all_integers = all(map(lambda x: float(x).is_integer(), ords)) self.__is_float = not all_integers cast_type = int if all_integers else float self.__values = tuple(cast_type(i) for i in ords) self.data = torch.FloatTensor(self.__values) @property def x(self) -> Union[float, int]: return self.__values[0] @property def y(self) -> Union[float, int]: return self.__values[1] @property def z(self) -> Union[float, int]: assert len(self.__values) > 2, "Point has no Z-coordinate" return self.__values[2] @property def n_dim(self) -> int: return len(self.__values) @property def values(self) -> Union[Tuple[float, ...], Tuple[int, ...]]: return self.__values @property def is_float(self) -> bool: return self.__is_float def __getitem__(self, idx) -> Union[float, int]: return self.__values[idx] def __iter__(self) -> Union[Tuple[float, ...], Tuple[int, ...]]: return iter(self.__values) def to_tensor(self) -> torch.Tensor: return torch.Tensor([float(c) for c in self.__values]) @staticmethod def from_tensor(inp: torch.Tensor) -> 'Point': assert len(list(inp.size())) == 1 return Point(*[int(torch.round(inp[i])) for i in range(list(inp.size())[0])]) def __add__(self, other: Any) -> 'Point': return Point(*np.add(self.__values, other.__values if type(other) is Point else other)) def __sub__(self, other: Any) -> 'Point': return Point(*np.subtract(self.__values, other.__values if type(other) is Point else other)) def __mul__(self, other: Any) -> 'Point': return Point(*np.multiply(self.__values, other.__values if type(other) is Point else other)) def __truediv__(self, other: Any) -> 'Point': return Point(*np.divide(self.__values, other.__values if type(other) is Point else other)) def __eq__(self, other: object) -> bool: return isinstance(other, Point) and (self.__values == other.__values) def __ne__(self, other: object) -> bool: return not (self == other) def __lt__(self, other: object) -> bool: assert isinstance(other, Point), "Must compare with another point" return self.__values < other.__values def __hash__(self) -> int: return hash(self.__values) def __repr__(self) -> str: # want to print floats as ints for test, if doing so wouldn't change them return f"Point({', '.join(str(i) for i in self.__values)})" def __copy__(self) -> 'Point': return copy.deepcopy(self) def __deepcopy__(self, memo: dict) -> 'Point': return Point(*self.__values)
import gspread import json import re import string import pandas as pd import datetime from spacectl.command.execute import _check_api_permissions, _get_service_and_resource, _get_client,_call_api, \ _parse_parameter from spacectl.conf.my_conf import get_config, get_endpoint, get_template from spacectl.lib.apply.task import Task from spacectl.lib.apply.task import execute_wrapper from spacectl.modules.resource import validate from spacectl.lib.output import echo DEFAULT_HEADER_CELL = 'A4' GOOGLE_SERVICE_ACCOUNT_JSON_DEFAULT_PATH = '~/.config/gspread/service_account.json' class ExportGoogleSheetsTask(Task): def __init__(self, task_dict, silent): super().__init__(task_dict, silent) def set_spec(self, spec_dict): self.spec = spec_dict @execute_wrapper def execute(self): google_sheets = self._init_google_sheets() sheet = self._get_sheets(google_sheets) self.clear_all_worksheet(sheet) self.export_data(sheet) def export_data(self, sheet): for _index, raw_data in enumerate(self.spec.get('data', [])): task = self._convert_json(raw_data.get('input', {})) worksheet_name = self.set_worksheet_name(task, _index) echo(f"Export Worksheet: {worksheet_name}", flag=not self.silent) worksheet = self.select_worksheet(sheet, _index, worksheet_name) self.write_update_time(worksheet) self.export_worksheet(worksheet, task.get('output', [])) def select_worksheet(self, sheet, index, worksheet_title): try: worksheet = sheet.get_worksheet(index) worksheet.update_title(worksheet_title) return worksheet except Exception: return sheet.add_worksheet(title=worksheet_title, rows=1000, cols=26) def export_worksheet(self, worksheet, data): df = pd.DataFrame(data) headers = df.columns.values.tolist() self._format_header(worksheet, DEFAULT_HEADER_CELL, headers) worksheet.update(DEFAULT_HEADER_CELL, [headers] + df.values.tolist()) def write_update_time(self, worksheet): worksheet.update('A1', 'Update Time (UTC)') worksheet.update('B1', str(datetime.datetime.utcnow())) def _init_google_sheets(self): echo("Access Google Sheets..", flag=not self.silent) service_account = self.spec.get('service_account_json', GOOGLE_SERVICE_ACCOUNT_JSON_DEFAULT_PATH) return gspread.service_account(filename=service_account) def _get_sheets(self, google_sheets): echo(f"Open Sheets : {self.spec.get("sheet_id")}", flag=not self.silent) return google_sheets.open_by_key(self.spec.get('sheet_id')) def clear_all_worksheet(self, sheet): echo(f"Clear All Worksheet in selected sheet..", flag=not self.silent) sheet.add_worksheet(title='', rows=1000, cols=26) for worksheet in sheet.worksheets()[:-1]: sheet.del_worksheet(worksheet) @staticmethod def set_worksheet_name(task, index): return f'{index}. {task.get('name', '')}' @staticmethod def _convert_json(data): data = data.replace("'", "\"") data = data.replace("None", "null") data = data.replace("True", "true") data = data.replace("False", "false") return json.loads(data) @staticmethod def _format_header(worksheet, start_at, headers): header_format = { 'horizontalAlignment': 'CENTER', 'borders': { 'top': {'style': 'SOLID'}, 'bottom': {'style': 'SOLID'}, 'left': {'style': 'SOLID'}, 'right': {'style': 'SOLID'} }, 'textFormat': {'bold': True} } try: header_length = len(headers) _header_split = re.split('(\d+)', start_at) _col = _header_split[0] _col_idx = string.ascii_uppercase.index(_col) _chr_index = 64 + _col_idx + header_length if 64 + _col_idx + header_length <= 90 else 90 _num = _header_split[1] header_cells = f'{start_at}:{chr(_chr_index)}{_num}' worksheet.format(header_cells, header_format) except Exception as e: echo(f'e => {e}') pass
import gspread import json import re import string import pandas as pd import datetime from spacectl.command.execute import _check_api_permissions, _get_service_and_resource, _get_client,_call_api, \ _parse_parameter from spacectl.conf.my_conf import get_config, get_endpoint, get_template from spacectl.lib.apply.task import Task from spacectl.lib.apply.task import execute_wrapper from spacectl.modules.resource import validate from spacectl.lib.output import echo DEFAULT_HEADER_CELL = 'A4' GOOGLE_SERVICE_ACCOUNT_JSON_DEFAULT_PATH = '~/.config/gspread/service_account.json' class ExportGoogleSheetsTask(Task): def __init__(self, task_dict, silent): super().__init__(task_dict, silent) def set_spec(self, spec_dict): self.spec = spec_dict @execute_wrapper def execute(self): google_sheets = self._init_google_sheets() sheet = self._get_sheets(google_sheets) self.clear_all_worksheet(sheet) self.export_data(sheet) def export_data(self, sheet): for _index, raw_data in enumerate(self.spec.get('data', [])): task = self._convert_json(raw_data.get('input', {})) worksheet_name = self.set_worksheet_name(task, _index) echo(f"Export Worksheet: {worksheet_name}", flag=not self.silent) worksheet = self.select_worksheet(sheet, _index, worksheet_name) self.write_update_time(worksheet) self.export_worksheet(worksheet, task.get('output', [])) def select_worksheet(self, sheet, index, worksheet_title): try: worksheet = sheet.get_worksheet(index) worksheet.update_title(worksheet_title) return worksheet except Exception: return sheet.add_worksheet(title=worksheet_title, rows=1000, cols=26) def export_worksheet(self, worksheet, data): df = pd.DataFrame(data) headers = df.columns.values.tolist() self._format_header(worksheet, DEFAULT_HEADER_CELL, headers) worksheet.update(DEFAULT_HEADER_CELL, [headers] + df.values.tolist()) def write_update_time(self, worksheet): worksheet.update('A1', 'Update Time (UTC)') worksheet.update('B1', str(datetime.datetime.utcnow())) def _init_google_sheets(self): echo("Access Google Sheets..", flag=not self.silent) service_account = self.spec.get('service_account_json', GOOGLE_SERVICE_ACCOUNT_JSON_DEFAULT_PATH) return gspread.service_account(filename=service_account) def _get_sheets(self, google_sheets): echo(f"Open Sheets : {self.spec.get('sheet_id')}", flag=not self.silent) return google_sheets.open_by_key(self.spec.get('sheet_id')) def clear_all_worksheet(self, sheet): echo(f"Clear All Worksheet in selected sheet..", flag=not self.silent) sheet.add_worksheet(title='', rows=1000, cols=26) for worksheet in sheet.worksheets()[:-1]: sheet.del_worksheet(worksheet) @staticmethod def set_worksheet_name(task, index): return f'{index}. {task.get("name", "")}' @staticmethod def _convert_json(data): data = data.replace("'", "\"") data = data.replace("None", "null") data = data.replace("True", "true") data = data.replace("False", "false") return json.loads(data) @staticmethod def _format_header(worksheet, start_at, headers): header_format = { 'horizontalAlignment': 'CENTER', 'borders': { 'top': {'style': 'SOLID'}, 'bottom': {'style': 'SOLID'}, 'left': {'style': 'SOLID'}, 'right': {'style': 'SOLID'} }, 'textFormat': {'bold': True} } try: header_length = len(headers) _header_split = re.split('(\d+)', start_at) _col = _header_split[0] _col_idx = string.ascii_uppercase.index(_col) _chr_index = 64 + _col_idx + header_length if 64 + _col_idx + header_length <= 90 else 90 _num = _header_split[1] header_cells = f'{start_at}:{chr(_chr_index)}{_num}' worksheet.format(header_cells, header_format) except Exception as e: echo(f'e => {e}') pass
class ActionBatchSwitch(object): def __init__(self): super(ActionBatchSwitch, self).__init__() def cycleDeviceSwitchPorts(self, serial: str, ports: list): """ **Cycle a set of switch ports** https://developer.cisco.com/meraki/api-v1/#!cycle-device-switch-ports - serial (string): (required) - ports (array): List of switch ports. Example: [1, 2-5, 1_MA-MOD-8X10G_1, 1_MA-MOD-8X10G_2-1_MA-MOD-8X10G_8] """ kwargs = locals() metadata = { 'tags': ['switch', 'liveTools', 'ports'], 'operation': 'cycleDeviceSwitchPorts' } resource = f'/devices/{serial}/switch/ports/cycle' body_params = ['ports', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateDeviceSwitchPort(self, serial: str, portId: str, **kwargs): """ **Update a switch port** https://developer.cisco.com/meraki/api-v1/#!update-device-switch-port - serial (string): (required) - portId (string): (required) - name (string): The name of the switch port - tags (array): The list of tags of the switch port - enabled (boolean): The status of the switch port - type (string): The type of the switch port ('trunk' or 'access') - vlan (integer): The VLAN of the switch port. A null value will clear the value set for trunk ports. - voiceVlan (integer): The voice VLAN of the switch port. Only applicable to access ports. - allowedVlans (string): The VLANs allowed on the switch port. Only applicable to trunk ports. - poeEnabled (boolean): The PoE status of the switch port - isolationEnabled (boolean): The isolation status of the switch port - rstpEnabled (boolean): The rapid spanning tree protocol status - stpGuard (string): The state of the STP guard ('disabled', 'root guard', 'bpdu guard' or 'loop guard') - linkNegotiation (string): The link speed for the switch port - portScheduleId (string): The ID of the port schedule. A value of null will clear the port schedule. - udld (string): The action to take when Unidirectional Link is detected (Alert only, Enforce). Default configuration is Alert only. - accessPolicyType (string): The type of the access policy of the switch port. Only applicable to access ports. Can be one of 'Open', 'Custom access policy', 'MAC allow list' or 'Sticky MAC allow list' - accessPolicyNumber (integer): The number of a custom access policy to configure on the switch port. Only applicable when 'accessPolicyType' is 'Custom access policy' - macAllowList (array): Only devices with MAC addresses specified in this list will have access to this port. Up to 20 MAC addresses can be defined. Only applicable when 'accessPolicyType' is 'MAC allow list' - stickyMacAllowList (array): The initial list of MAC addresses for sticky Mac allow list. Only applicable when 'accessPolicyType' is 'Sticky MAC allow list' - stickyMacAllowListLimit (integer): The maximum number of MAC addresses for sticky MAC allow list. Only applicable when 'accessPolicyType' is 'Sticky MAC allow list' - stormControlEnabled (boolean): The storm control status of the switch port - flexibleStackingEnabled (boolean): For supported switches (e.g. MS420/MS425), whether or not the port has flexible stacking enabled. """ kwargs.update(locals()) if 'type' in kwargs: options = ['trunk', 'access'] assert kwargs['type'] in options, f'''"type" cannot be "{kwargs['type']}", & must be set to one of: {options}''' if 'stpGuard' in kwargs: options = ['disabled', 'root guard', 'bpdu guard', 'loop guard'] assert kwargs['stpGuard'] in options, f'''"stpGuard" cannot be "{kwargs['stpGuard']}", & must be set to one of: {options}''' if 'udld' in kwargs: options = ['Alert only', 'Enforce'] assert kwargs['udld'] in options, f'''"udld" cannot be "{kwargs['udld']}", & must be set to one of: {options}''' if 'accessPolicyType' in kwargs: options = ['Open', 'Custom access policy', 'MAC allow list', 'Sticky MAC allow list'] assert kwargs['accessPolicyType'] in options, f'''"accessPolicyType" cannot be "{kwargs['accessPolicyType']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'ports'], 'operation': 'updateDeviceSwitchPort' } resource = f'/devices/{serial}/switch/ports/{portId}' body_params = ['name', 'tags', 'enabled', 'type', 'vlan', 'voiceVlan', 'allowedVlans', 'poeEnabled', 'isolationEnabled', 'rstpEnabled', 'stpGuard', 'linkNegotiation', 'portScheduleId', 'udld', 'accessPolicyType', 'accessPolicyNumber', 'macAllowList', 'stickyMacAllowList', 'stickyMacAllowListLimit', 'stormControlEnabled', 'flexibleStackingEnabled', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createDeviceSwitchRoutingInterface(self, serial: str, name: str, interfaceIp: str, vlanId: int, **kwargs): """ **Create a layer 3 interface for a switch** https://developer.cisco.com/meraki/api-v1/#!create-device-switch-routing-interface - serial (string): (required) - name (string): A friendly name or description for the interface or VLAN. - interfaceIp (string): The IP address this switch will use for layer 3 routing on this VLAN or subnet. This cannot be the same as the switch's management IP. - vlanId (integer): The VLAN this routed interface is on. VLAN must be between 1 and 4094. - subnet (string): The network that this routed interface is on, in CIDR notation (ex. 10.1.1.0/24). - multicastRouting (string): Enable multicast support if, multicast routing between VLANs is required. Options are, 'disabled', 'enabled' or 'IGMP snooping querier'. Default is 'disabled'. - defaultGateway (string): The next hop for any traffic that isn't going to a directly connected subnet or over a static route. This IP address must exist in a subnet with a routed interface. - ospfSettings (object): The OSPF routing settings of the interface. """ kwargs.update(locals()) if 'multicastRouting' in kwargs: options = ['disabled', 'enabled', 'IGMP snooping querier'] assert kwargs['multicastRouting'] in options, f'''"multicastRouting" cannot be "{kwargs['multicastRouting']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'routing', 'interfaces'], 'operation': 'createDeviceSwitchRoutingInterface' } resource = f'/devices/{serial}/switch/routing/interfaces' body_params = ['name', 'subnet', 'interfaceIp', 'multicastRouting', 'vlanId', 'defaultGateway', 'ospfSettings', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateDeviceSwitchRoutingInterface(self, serial: str, interfaceId: str, **kwargs): """ **Update a layer 3 interface for a switch** https://developer.cisco.com/meraki/api-v1/#!update-device-switch-routing-interface - serial (string): (required) - interfaceId (string): (required) - name (string): A friendly name or description for the interface or VLAN. - subnet (string): The network that this routed interface is on, in CIDR notation (ex. 10.1.1.0/24). - interfaceIp (string): The IP address this switch will use for layer 3 routing on this VLAN or subnet. This cannot be the same as the switch's management IP. - multicastRouting (string): Enable multicast support if, multicast routing between VLANs is required. Options are, 'disabled', 'enabled' or 'IGMP snooping querier'. - vlanId (integer): The VLAN this routed interface is on. VLAN must be between 1 and 4094. - ospfSettings (object): The OSPF routing settings of the interface. """ kwargs.update(locals()) if 'multicastRouting' in kwargs: options = ['disabled', 'enabled', 'IGMP snooping querier'] assert kwargs['multicastRouting'] in options, f'''"multicastRouting" cannot be "{kwargs['multicastRouting']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'routing', 'interfaces'], 'operation': 'updateDeviceSwitchRoutingInterface' } resource = f'/devices/{serial}/switch/routing/interfaces/{interfaceId}' body_params = ['name', 'subnet', 'interfaceIp', 'multicastRouting', 'vlanId', 'ospfSettings', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteDeviceSwitchRoutingInterface(self, serial: str, interfaceId: str): """ **Delete a layer 3 interface from the switch** https://developer.cisco.com/meraki/api-v1/#!delete-device-switch-routing-interface - serial (string): (required) - interfaceId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'routing', 'interfaces'], 'operation': 'deleteDeviceSwitchRoutingInterface' } resource = f'/devices/{serial}/switch/routing/interfaces/{interfaceId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateDeviceSwitchRoutingInterfaceDhcp(self, serial: str, interfaceId: str, **kwargs): """ **Update a layer 3 interface DHCP configuration for a switch** https://developer.cisco.com/meraki/api-v1/#!update-device-switch-routing-interface-dhcp - serial (string): (required) - interfaceId (string): (required) - dhcpMode (string): The DHCP mode options for the switch interface ('dhcpDisabled', 'dhcpRelay' or 'dhcpServer') - dhcpRelayServerIps (array): The DHCP relay server IPs to which DHCP packets would get relayed for the switch interface - dhcpLeaseTime (string): The DHCP lease time config for the dhcp server running on switch interface ('30 minutes', '1 hour', '4 hours', '12 hours', '1 day' or '1 week') - dnsNameserversOption (string): The DHCP name server option for the dhcp server running on the switch interface ('googlePublicDns', 'openDns' or 'custom') - dnsCustomNameservers (array): The DHCP name server IPs when DHCP name server option is 'custom' - bootOptionsEnabled (boolean): Enable DHCP boot options to provide PXE boot options configs for the dhcp server running on the switch interface - bootNextServer (string): The PXE boot server IP for the DHCP server running on the switch interface - bootFileName (string): The PXE boot server filename for the DHCP server running on the switch interface - dhcpOptions (array): Array of DHCP options consisting of code, type and value for the DHCP server running on the switch interface - reservedIpRanges (array): Array of DHCP reserved IP assignments for the DHCP server running on the switch interface - fixedIpAssignments (array): Array of DHCP fixed IP assignments for the DHCP server running on the switch interface """ kwargs.update(locals()) if 'dhcpMode' in kwargs: options = ['dhcpDisabled', 'dhcpRelay', 'dhcpServer'] assert kwargs['dhcpMode'] in options, f'''"dhcpMode" cannot be "{kwargs['dhcpMode']}", & must be set to one of: {options}''' if 'dhcpLeaseTime' in kwargs: options = ['30 minutes', '1 hour', '4 hours', '12 hours', '1 day', '1 week'] assert kwargs['dhcpLeaseTime'] in options, f'''"dhcpLeaseTime" cannot be "{kwargs['dhcpLeaseTime']}", & must be set to one of: {options}''' if 'dnsNameserversOption' in kwargs: options = ['googlePublicDns', 'openDns', 'custom'] assert kwargs['dnsNameserversOption'] in options, f'''"dnsNameserversOption" cannot be "{kwargs['dnsNameserversOption']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'routing', 'interfaces', 'dhcp'], 'operation': 'updateDeviceSwitchRoutingInterfaceDhcp' } resource = f'/devices/{serial}/switch/routing/interfaces/{interfaceId}/dhcp' body_params = ['dhcpMode', 'dhcpRelayServerIps', 'dhcpLeaseTime', 'dnsNameserversOption', 'dnsCustomNameservers', 'bootOptionsEnabled', 'bootNextServer', 'bootFileName', 'dhcpOptions', 'reservedIpRanges', 'fixedIpAssignments', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createDeviceSwitchRoutingStaticRoute(self, serial: str, subnet: str, nextHopIp: str, **kwargs): """ **Create a layer 3 static route for a switch** https://developer.cisco.com/meraki/api-v1/#!create-device-switch-routing-static-route - serial (string): (required) - subnet (string): The subnet which is routed via this static route and should be specified in CIDR notation (ex. 1.2.3.0/24) - nextHopIp (string): IP address of the next hop device to which the device sends its traffic for the subnet - name (string): Name or description for layer 3 static route - advertiseViaOspfEnabled (boolean): Option to advertise static route via OSPF - preferOverOspfRoutesEnabled (boolean): Option to prefer static route over OSPF routes """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'routing', 'staticRoutes'], 'operation': 'createDeviceSwitchRoutingStaticRoute' } resource = f'/devices/{serial}/switch/routing/staticRoutes' body_params = ['name', 'subnet', 'nextHopIp', 'advertiseViaOspfEnabled', 'preferOverOspfRoutesEnabled', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateDeviceSwitchRoutingStaticRoute(self, serial: str, staticRouteId: str, **kwargs): """ **Update a layer 3 static route for a switch** https://developer.cisco.com/meraki/api-v1/#!update-device-switch-routing-static-route - serial (string): (required) - staticRouteId (string): (required) - name (string): Name or description for layer 3 static route - subnet (string): The subnet which is routed via this static route and should be specified in CIDR notation (ex. 1.2.3.0/24) - nextHopIp (string): IP address of the next hop device to which the device sends its traffic for the subnet - advertiseViaOspfEnabled (boolean): Option to advertise static route via OSPF - preferOverOspfRoutesEnabled (boolean): Option to prefer static route over OSPF routes """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'routing', 'staticRoutes'], 'operation': 'updateDeviceSwitchRoutingStaticRoute' } resource = f'/devices/{serial}/switch/routing/staticRoutes/{staticRouteId}' body_params = ['name', 'subnet', 'nextHopIp', 'advertiseViaOspfEnabled', 'preferOverOspfRoutesEnabled', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteDeviceSwitchRoutingStaticRoute(self, serial: str, staticRouteId: str): """ **Delete a layer 3 static route for a switch** https://developer.cisco.com/meraki/api-v1/#!delete-device-switch-routing-static-route - serial (string): (required) - staticRouteId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'routing', 'staticRoutes'], 'operation': 'deleteDeviceSwitchRoutingStaticRoute' } resource = f'/devices/{serial}/switch/routing/staticRoutes/{staticRouteId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateDeviceSwitchWarmSpare(self, serial: str, enabled: bool, **kwargs): """ **Update warm spare configuration for a switch** https://developer.cisco.com/meraki/api-v1/#!update-device-switch-warm-spare - serial (string): (required) - enabled (boolean): Enable or disable warm spare for a switch - spareSerial (string): Serial number of the warm spare switch """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'warmSpare'], 'operation': 'updateDeviceSwitchWarmSpare' } resource = f'/devices/{serial}/switch/warmSpare' body_params = ['enabled', 'spareSerial', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createNetworkSwitchAccessPolicy(self, networkId: str, name: str, radiusServers: list, radiusTestingEnabled: bool, radiusCoaSupportEnabled: bool, radiusAccountingEnabled: bool, hostMode: str, urlRedirectWalledGardenEnabled: bool, **kwargs): """ **Create an access policy for a switch network** https://developer.cisco.com/meraki/api-v1/#!create-network-switch-access-policy - networkId (string): (required) - name (string): Name of the access policy - radiusServers (array): List of RADIUS servers to require connecting devices to authenticate against before granting network access - radiusTestingEnabled (boolean): If enabled, Meraki devices will periodically send access-request messages to these RADIUS servers - radiusCoaSupportEnabled (boolean): Change of authentication for RADIUS re-authentication and disconnection - radiusAccountingEnabled (boolean): Enable to send start, interim-update and stop messages to a configured RADIUS accounting server for tracking connected clients - hostMode (string): Choose the Host Mode for the access policy. - urlRedirectWalledGardenEnabled (boolean): Enable to restrict access for clients to a specific set of IP addresses or hostnames prior to authentication - radiusAccountingServers (array): List of RADIUS accounting servers to require connecting devices to authenticate against before granting network access - radiusGroupAttribute (string): Acceptable values are `""` for None, or `"11"` for Group Policies ACL - accessPolicyType (string): Access Type of the policy. Automatically 'Hybrid authentication' when hostMode is 'Multi-Domain'. - increaseAccessSpeed (boolean): Enabling this option will make switches execute 802.1X and MAC-bypass authentication simultaneously so that clients authenticate faster. Only required when accessPolicyType is 'Hybrid Authentication. - guestVlanId (integer): ID for the guest VLAN allow unauthorized devices access to limited network resources - voiceVlanClients (boolean): CDP/LLDP capable voice clients will be able to use this VLAN. Automatically true when hostMode is 'Multi-Domain'. - urlRedirectWalledGardenRanges (array): IP address ranges, in CIDR notation, to restrict access for clients to a specific set of IP addresses or hostnames prior to authentication """ kwargs.update(locals()) if 'hostMode' in kwargs: options = ['Single-Host', 'Multi-Domain', 'Multi-Host', 'Multi-Auth'] assert kwargs['hostMode'] in options, f'''"hostMode" cannot be "{kwargs['hostMode']}", & must be set to one of: {options}''' if 'accessPolicyType' in kwargs: options = ['802.1x', 'MAC authentication bypass', 'Hybrid authentication'] assert kwargs['accessPolicyType'] in options, f'''"accessPolicyType" cannot be "{kwargs['accessPolicyType']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'accessPolicies'], 'operation': 'createNetworkSwitchAccessPolicy' } resource = f'/networks/{networkId}/switch/accessPolicies' body_params = ['name', 'radiusServers', 'radiusTestingEnabled', 'radiusCoaSupportEnabled', 'radiusAccountingEnabled', 'radiusAccountingServers', 'radiusGroupAttribute', 'hostMode', 'accessPolicyType', 'increaseAccessSpeed', 'guestVlanId', 'voiceVlanClients', 'urlRedirectWalledGardenEnabled', 'urlRedirectWalledGardenRanges', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateNetworkSwitchAccessPolicy(self, networkId: str, accessPolicyNumber: str, **kwargs): """ **Update an access policy for a switch network** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-access-policy - networkId (string): (required) - accessPolicyNumber (string): (required) - name (string): Name of the access policy - radiusServers (array): List of RADIUS servers to require connecting devices to authenticate against before granting network access - radiusTestingEnabled (boolean): If enabled, Meraki devices will periodically send access-request messages to these RADIUS servers - radiusCoaSupportEnabled (boolean): Change of authentication for RADIUS re-authentication and disconnection - radiusAccountingEnabled (boolean): Enable to send start, interim-update and stop messages to a configured RADIUS accounting server for tracking connected clients - radiusAccountingServers (array): List of RADIUS accounting servers to require connecting devices to authenticate against before granting network access - radiusGroupAttribute (string): Can be either `""`, which means `None` on Dashboard, or `"11"`, which means `Filter-Id` on Dashboard and will use Group Policy ACLs when supported (firmware 14+) - hostMode (string): Choose the Host Mode for the access policy. - accessPolicyType (string): Access Type of the policy. Automatically 'Hybrid authentication' when hostMode is 'Multi-Domain'. - increaseAccessSpeed (boolean): Enabling this option will make switches execute 802.1X and MAC-bypass authentication simultaneously so that clients authenticate faster. Only required when accessPolicyType is 'Hybrid Authentication. - guestVlanId (integer): ID for the guest VLAN allow unauthorized devices access to limited network resources - voiceVlanClients (boolean): CDP/LLDP capable voice clients will be able to use this VLAN. Automatically true when hostMode is 'Multi-Domain'. - urlRedirectWalledGardenEnabled (boolean): Enable to restrict access for clients to a specific set of IP addresses or hostnames prior to authentication - urlRedirectWalledGardenRanges (array): IP address ranges, in CIDR notation, to restrict access for clients to a specific set of IP addresses or hostnames prior to authentication """ kwargs.update(locals()) if 'hostMode' in kwargs: options = ['Single-Host', 'Multi-Domain', 'Multi-Host', 'Multi-Auth'] assert kwargs['hostMode'] in options, f'''"hostMode" cannot be "{kwargs['hostMode']}", & must be set to one of: {options}''' if 'accessPolicyType' in kwargs: options = ['802.1x', 'MAC authentication bypass', 'Hybrid authentication'] assert kwargs['accessPolicyType'] in options, f'''"accessPolicyType" cannot be "{kwargs['accessPolicyType']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'accessPolicies'], 'operation': 'updateNetworkSwitchAccessPolicy' } resource = f'/networks/{networkId}/switch/accessPolicies/{accessPolicyNumber}' body_params = ['name', 'radiusServers', 'radiusTestingEnabled', 'radiusCoaSupportEnabled', 'radiusAccountingEnabled', 'radiusAccountingServers', 'radiusGroupAttribute', 'hostMode', 'accessPolicyType', 'increaseAccessSpeed', 'guestVlanId', 'voiceVlanClients', 'urlRedirectWalledGardenEnabled', 'urlRedirectWalledGardenRanges', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteNetworkSwitchAccessPolicy(self, networkId: str, accessPolicyNumber: str): """ **Delete an access policy for a switch network** https://developer.cisco.com/meraki/api-v1/#!delete-network-switch-access-policy - networkId (string): (required) - accessPolicyNumber (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'accessPolicies'], 'operation': 'deleteNetworkSwitchAccessPolicy' } resource = f'/networks/{networkId}/switch/accessPolicies/{accessPolicyNumber}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateNetworkSwitchAlternateManagementInterface(self, networkId: str, **kwargs): """ **Update the switch alternate management interface for the network** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-alternate-management-interface - networkId (string): (required) - enabled (boolean): Boolean value to enable or disable AMI configuration. If enabled, VLAN and protocols must be set - vlanId (integer): Alternate management VLAN, must be between 1 and 4094 - protocols (array): Can be one or more of the following values: 'radius', 'snmp' or 'syslog' - switches (array): Array of switch serial number and IP assignment. If parameter is present, it cannot have empty body. Note: switches parameter is not applicable for template networks, in other words, do not put 'switches' in the body when updating template networks. Also, an empty 'switches' array will remove all previous assignments """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'alternateManagementInterface'], 'operation': 'updateNetworkSwitchAlternateManagementInterface' } resource = f'/networks/{networkId}/switch/alternateManagementInterface' body_params = ['enabled', 'vlanId', 'protocols', 'switches', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateNetworkSwitchDhcpServerPolicy(self, networkId: str, **kwargs): """ **Update the DHCP server policy** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-dhcp-server-policy - networkId (string): (required) - defaultPolicy (string): 'allow' or 'block' new DHCP servers. Default value is 'allow'. - allowedServers (array): List the MAC addresses of DHCP servers to permit on the network. Applicable only if defaultPolicy is set to block. An empty array will clear the entries. - blockedServers (array): List the MAC addresses of DHCP servers to block on the network. Applicable only if defaultPolicy is set to allow. An empty array will clear the entries. """ kwargs.update(locals()) if 'defaultPolicy' in kwargs: options = ['allow', 'block'] assert kwargs['defaultPolicy'] in options, f'''"defaultPolicy" cannot be "{kwargs['defaultPolicy']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'dhcpServerPolicy'], 'operation': 'updateNetworkSwitchDhcpServerPolicy' } resource = f'/networks/{networkId}/switch/dhcpServerPolicy' body_params = ['defaultPolicy', 'allowedServers', 'blockedServers', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateNetworkSwitchDscpToCosMappings(self, networkId: str, mappings: list): """ **Update the DSCP to CoS mappings** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-dscp-to-cos-mappings - networkId (string): (required) - mappings (array): An array of DSCP to CoS mappings. An empty array will reset the mappings to default. """ kwargs = locals() metadata = { 'tags': ['switch', 'configure', 'dscpToCosMappings'], 'operation': 'updateNetworkSwitchDscpToCosMappings' } resource = f'/networks/{networkId}/switch/dscpToCosMappings' body_params = ['mappings', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createNetworkSwitchLinkAggregation(self, networkId: str, **kwargs): """ **Create a link aggregation group** https://developer.cisco.com/meraki/api-v1/#!create-network-switch-link-aggregation - networkId (string): (required) - switchPorts (array): Array of switch or stack ports for creating aggregation group. Minimum 2 and maximum 8 ports are supported. - switchProfilePorts (array): Array of switch profile ports for creating aggregation group. Minimum 2 and maximum 8 ports are supported. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'linkAggregations'], 'operation': 'createNetworkSwitchLinkAggregation' } resource = f'/networks/{networkId}/switch/linkAggregations' body_params = ['switchPorts', 'switchProfilePorts', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateNetworkSwitchLinkAggregation(self, networkId: str, linkAggregationId: str, **kwargs): """ **Update a link aggregation group** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-link-aggregation - networkId (string): (required) - linkAggregationId (string): (required) - switchPorts (array): Array of switch or stack ports for updating aggregation group. Minimum 2 and maximum 8 ports are supported. - switchProfilePorts (array): Array of switch profile ports for updating aggregation group. Minimum 2 and maximum 8 ports are supported. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'linkAggregations'], 'operation': 'updateNetworkSwitchLinkAggregation' } resource = f'/networks/{networkId}/switch/linkAggregations/{linkAggregationId}' body_params = ['switchPorts', 'switchProfilePorts', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteNetworkSwitchLinkAggregation(self, networkId: str, linkAggregationId: str): """ **Split a link aggregation group into separate ports** https://developer.cisco.com/meraki/api-v1/#!delete-network-switch-link-aggregation - networkId (string): (required) - linkAggregationId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'linkAggregations'], 'operation': 'deleteNetworkSwitchLinkAggregation' } resource = f'/networks/{networkId}/switch/linkAggregations/{linkAggregationId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateNetworkSwitchMtu(self, networkId: str, **kwargs): """ **Update the MTU configuration** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-mtu - networkId (string): (required) - defaultMtuSize (integer): MTU size for the entire network. Default value is 9578. - overrides (array): Override MTU size for individual switches or switch profiles. An empty array will clear overrides. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'mtu'], 'operation': 'updateNetworkSwitchMtu' } resource = f'/networks/{networkId}/switch/mtu' body_params = ['defaultMtuSize', 'overrides', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateNetworkSwitchPortSchedule(self, networkId: str, portScheduleId: str, **kwargs): """ **Update a switch port schedule** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-port-schedule - networkId (string): (required) - portScheduleId (string): (required) - name (string): The name for your port schedule. - portSchedule (object): The schedule for switch port scheduling. Schedules are applied to days of the week. When it's empty, default schedule with all days of a week are configured. Any unspecified day in the schedule is added as a default schedule configuration of the day. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'portSchedules'], 'operation': 'updateNetworkSwitchPortSchedule' } resource = f'/networks/{networkId}/switch/portSchedules/{portScheduleId}' body_params = ['name', 'portSchedule', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createNetworkSwitchQosRule(self, networkId: str, vlan: int, **kwargs): """ **Add a quality of service rule** https://developer.cisco.com/meraki/api-v1/#!create-network-switch-qos-rule - networkId (string): (required) - vlan (integer): The VLAN of the incoming packet. A null value will match any VLAN. - protocol (string): The protocol of the incoming packet. Can be one of "ANY", "TCP" or "UDP". Default value is "ANY" - srcPort (integer): The source port of the incoming packet. Applicable only if protocol is TCP or UDP. - srcPortRange (string): The source port range of the incoming packet. Applicable only if protocol is set to TCP or UDP. Example: 70-80 - dstPort (integer): The destination port of the incoming packet. Applicable only if protocol is TCP or UDP. - dstPortRange (string): The destination port range of the incoming packet. Applicable only if protocol is set to TCP or UDP. Example: 70-80 - dscp (integer): DSCP tag. Set this to -1 to trust incoming DSCP. Default value is 0 """ kwargs.update(locals()) if 'protocol' in kwargs: options = ['ANY', 'TCP', 'UDP'] assert kwargs['protocol'] in options, f'''"protocol" cannot be "{kwargs['protocol']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'qosRules'], 'operation': 'createNetworkSwitchQosRule' } resource = f'/networks/{networkId}/switch/qosRules' body_params = ['vlan', 'protocol', 'srcPort', 'srcPortRange', 'dstPort', 'dstPortRange', 'dscp', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateNetworkSwitchQosRulesOrder(self, networkId: str, ruleIds: list): """ **Update the order in which the rules should be processed by the switch** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-qos-rules-order - networkId (string): (required) - ruleIds (array): A list of quality of service rule IDs arranged in order in which they should be processed by the switch. """ kwargs = locals() metadata = { 'tags': ['switch', 'configure', 'qosRules', 'order'], 'operation': 'updateNetworkSwitchQosRulesOrder' } resource = f'/networks/{networkId}/switch/qosRules/order' body_params = ['ruleIds', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteNetworkSwitchQosRule(self, networkId: str, qosRuleId: str): """ **Delete a quality of service rule** https://developer.cisco.com/meraki/api-v1/#!delete-network-switch-qos-rule - networkId (string): (required) - qosRuleId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'qosRules'], 'operation': 'deleteNetworkSwitchQosRule' } resource = f'/networks/{networkId}/switch/qosRules/{qosRuleId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateNetworkSwitchQosRule(self, networkId: str, qosRuleId: str, **kwargs): """ **Update a quality of service rule** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-qos-rule - networkId (string): (required) - qosRuleId (string): (required) - vlan (integer): The VLAN of the incoming packet. A null value will match any VLAN. - protocol (string): The protocol of the incoming packet. Can be one of "ANY", "TCP" or "UDP". Default value is "ANY". - srcPort (integer): The source port of the incoming packet. Applicable only if protocol is TCP or UDP. - srcPortRange (string): The source port range of the incoming packet. Applicable only if protocol is set to TCP or UDP. Example: 70-80 - dstPort (integer): The destination port of the incoming packet. Applicable only if protocol is TCP or UDP. - dstPortRange (string): The destination port range of the incoming packet. Applicable only if protocol is set to TCP or UDP. Example: 70-80 - dscp (integer): DSCP tag that should be assigned to incoming packet. Set this to -1 to trust incoming DSCP. Default value is 0. """ kwargs.update(locals()) if 'protocol' in kwargs: options = ['ANY', 'TCP', 'UDP'] assert kwargs['protocol'] in options, f'''"protocol" cannot be "{kwargs['protocol']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'qosRules'], 'operation': 'updateNetworkSwitchQosRule' } resource = f'/networks/{networkId}/switch/qosRules/{qosRuleId}' body_params = ['vlan', 'protocol', 'srcPort', 'srcPortRange', 'dstPort', 'dstPortRange', 'dscp', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateNetworkSwitchRoutingMulticast(self, networkId: str, **kwargs): """ **Update multicast settings for a network** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-routing-multicast - networkId (string): (required) - defaultSettings (object): Default multicast setting for entire network. IGMP snooping and Flood unknown multicast traffic settings are enabled by default. - overrides (array): Array of paired switches/stacks/profiles and corresponding multicast settings. An empty array will clear the multicast settings. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'routing', 'multicast'], 'operation': 'updateNetworkSwitchRoutingMulticast' } resource = f'/networks/{networkId}/switch/routing/multicast' body_params = ['defaultSettings', 'overrides', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createNetworkSwitchRoutingMulticastRendezvousPoint(self, networkId: str, interfaceIp: str, multicastGroup: str): """ **Create a multicast rendezvous point** https://developer.cisco.com/meraki/api-v1/#!create-network-switch-routing-multicast-rendezvous-point - networkId (string): (required) - interfaceIp (string): The IP address of the interface where the RP needs to be created. - multicastGroup (string): 'Any', or the IP address of a multicast group """ kwargs = locals() metadata = { 'tags': ['switch', 'configure', 'routing', 'multicast', 'rendezvousPoints'], 'operation': 'createNetworkSwitchRoutingMulticastRendezvousPoint' } resource = f'/networks/{networkId}/switch/routing/multicast/rendezvousPoints' body_params = ['interfaceIp', 'multicastGroup', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def deleteNetworkSwitchRoutingMulticastRendezvousPoint(self, networkId: str, rendezvousPointId: str): """ **Delete a multicast rendezvous point** https://developer.cisco.com/meraki/api-v1/#!delete-network-switch-routing-multicast-rendezvous-point - networkId (string): (required) - rendezvousPointId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'routing', 'multicast', 'rendezvousPoints'], 'operation': 'deleteNetworkSwitchRoutingMulticastRendezvousPoint' } resource = f'/networks/{networkId}/switch/routing/multicast/rendezvousPoints/{rendezvousPointId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateNetworkSwitchRoutingMulticastRendezvousPoint(self, networkId: str, rendezvousPointId: str, interfaceIp: str, multicastGroup: str): """ **Update a multicast rendezvous point** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-routing-multicast-rendezvous-point - networkId (string): (required) - rendezvousPointId (string): (required) - interfaceIp (string): The IP address of the interface to use - multicastGroup (string): 'Any', or the IP address of a multicast group """ kwargs = locals() metadata = { 'tags': ['switch', 'configure', 'routing', 'multicast', 'rendezvousPoints'], 'operation': 'updateNetworkSwitchRoutingMulticastRendezvousPoint' } resource = f'/networks/{networkId}/switch/routing/multicast/rendezvousPoints/{rendezvousPointId}' body_params = ['interfaceIp', 'multicastGroup', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateNetworkSwitchRoutingOspf(self, networkId: str, **kwargs): """ **Update layer 3 OSPF routing configuration** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-routing-ospf - networkId (string): (required) - enabled (boolean): Boolean value to enable or disable OSPF routing. OSPF routing is disabled by default. - helloTimerInSeconds (integer): Time interval in seconds at which hello packet will be sent to OSPF neighbors to maintain connectivity. Value must be between 1 and 255. Default is 10 seconds - deadTimerInSeconds (integer): Time interval to determine when the peer will be declare inactive/dead. Value must be between 1 and 65535 - areas (array): OSPF areas - md5AuthenticationEnabled (boolean): Boolean value to enable or disable MD5 authentication. MD5 authentication is disabled by default. - md5AuthenticationKey (object): MD5 authentication credentials. This param is only relevant if md5AuthenticationEnabled is true """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'routing', 'ospf'], 'operation': 'updateNetworkSwitchRoutingOspf' } resource = f'/networks/{networkId}/switch/routing/ospf' body_params = ['enabled', 'helloTimerInSeconds', 'deadTimerInSeconds', 'areas', 'md5AuthenticationEnabled', 'md5AuthenticationKey', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createNetworkSwitchStackRoutingInterface(self, networkId: str, switchStackId: str, name: str, subnet: str, interfaceIp: str, vlanId: int, **kwargs): """ **Create a layer 3 interface for a switch stack** https://developer.cisco.com/meraki/api-v1/#!create-network-switch-stack-routing-interface - networkId (string): (required) - switchStackId (string): (required) - name (string): A friendly name or description for the interface or VLAN. - subnet (string): The network that this routed interface is on, in CIDR notation (ex. 10.1.1.0/24). - interfaceIp (string): The IP address this switch stack will use for layer 3 routing on this VLAN or subnet. This cannot be the same as the switch's management IP. - vlanId (integer): The VLAN this routed interface is on. VLAN must be between 1 and 4094. - multicastRouting (string): Enable multicast support if, multicast routing between VLANs is required. Options are, 'disabled', 'enabled' or 'IGMP snooping querier'. Default is 'disabled'. - defaultGateway (string): The next hop for any traffic that isn't going to a directly connected subnet or over a static route. This IP address must exist in a subnet with a routed interface. - ospfSettings (object): The OSPF routing settings of the interface. """ kwargs.update(locals()) if 'multicastRouting' in kwargs: options = ['disabled', 'enabled', 'IGMP snooping querier'] assert kwargs['multicastRouting'] in options, f'''"multicastRouting" cannot be "{kwargs['multicastRouting']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'interfaces'], 'operation': 'createNetworkSwitchStackRoutingInterface' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/interfaces' body_params = ['name', 'subnet', 'interfaceIp', 'multicastRouting', 'vlanId', 'defaultGateway', 'ospfSettings', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateNetworkSwitchStackRoutingInterface(self, networkId: str, switchStackId: str, interfaceId: str, **kwargs): """ **Update a layer 3 interface for a switch stack** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-stack-routing-interface - networkId (string): (required) - switchStackId (string): (required) - interfaceId (string): (required) - name (string): A friendly name or description for the interface or VLAN. - subnet (string): The network that this routed interface is on, in CIDR notation (ex. 10.1.1.0/24). - interfaceIp (string): The IP address this switch stack will use for layer 3 routing on this VLAN or subnet. This cannot be the same as the switch's management IP. - multicastRouting (string): Enable multicast support if, multicast routing between VLANs is required. Options are, 'disabled', 'enabled' or 'IGMP snooping querier'. - vlanId (integer): The VLAN this routed interface is on. VLAN must be between 1 and 4094. - ospfSettings (object): The OSPF routing settings of the interface. """ kwargs.update(locals()) if 'multicastRouting' in kwargs: options = ['disabled', 'enabled', 'IGMP snooping querier'] assert kwargs['multicastRouting'] in options, f'''"multicastRouting" cannot be "{kwargs['multicastRouting']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'interfaces'], 'operation': 'updateNetworkSwitchStackRoutingInterface' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/interfaces/{interfaceId}' body_params = ['name', 'subnet', 'interfaceIp', 'multicastRouting', 'vlanId', 'ospfSettings', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteNetworkSwitchStackRoutingInterface(self, networkId: str, switchStackId: str, interfaceId: str): """ **Delete a layer 3 interface from a switch stack** https://developer.cisco.com/meraki/api-v1/#!delete-network-switch-stack-routing-interface - networkId (string): (required) - switchStackId (string): (required) - interfaceId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'interfaces'], 'operation': 'deleteNetworkSwitchStackRoutingInterface' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/interfaces/{interfaceId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateNetworkSwitchStackRoutingInterfaceDhcp(self, networkId: str, switchStackId: str, interfaceId: str, **kwargs): """ **Update a layer 3 interface DHCP configuration for a switch stack** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-stack-routing-interface-dhcp - networkId (string): (required) - switchStackId (string): (required) - interfaceId (string): (required) - dhcpMode (string): The DHCP mode options for the switch stack interface ('dhcpDisabled', 'dhcpRelay' or 'dhcpServer') - dhcpRelayServerIps (array): The DHCP relay server IPs to which DHCP packets would get relayed for the switch stack interface - dhcpLeaseTime (string): The DHCP lease time config for the dhcp server running on switch stack interface ('30 minutes', '1 hour', '4 hours', '12 hours', '1 day' or '1 week') - dnsNameserversOption (string): The DHCP name server option for the dhcp server running on the switch stack interface ('googlePublicDns', 'openDns' or 'custom') - dnsCustomNameservers (array): The DHCP name server IPs when DHCP name server option is 'custom' - bootOptionsEnabled (boolean): Enable DHCP boot options to provide PXE boot options configs for the dhcp server running on the switch stack interface - bootNextServer (string): The PXE boot server IP for the DHCP server running on the switch stack interface - bootFileName (string): The PXE boot server file name for the DHCP server running on the switch stack interface - dhcpOptions (array): Array of DHCP options consisting of code, type and value for the DHCP server running on the switch stack interface - reservedIpRanges (array): Array of DHCP reserved IP assignments for the DHCP server running on the switch stack interface - fixedIpAssignments (array): Array of DHCP fixed IP assignments for the DHCP server running on the switch stack interface """ kwargs.update(locals()) if 'dhcpMode' in kwargs: options = ['dhcpDisabled', 'dhcpRelay', 'dhcpServer'] assert kwargs['dhcpMode'] in options, f'''"dhcpMode" cannot be "{kwargs['dhcpMode']}", & must be set to one of: {options}''' if 'dhcpLeaseTime' in kwargs: options = ['30 minutes', '1 hour', '4 hours', '12 hours', '1 day', '1 week'] assert kwargs['dhcpLeaseTime'] in options, f'''"dhcpLeaseTime" cannot be "{kwargs['dhcpLeaseTime']}", & must be set to one of: {options}''' if 'dnsNameserversOption' in kwargs: options = ['googlePublicDns', 'openDns', 'custom'] assert kwargs['dnsNameserversOption'] in options, f'''"dnsNameserversOption" cannot be "{kwargs['dnsNameserversOption']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'interfaces', 'dhcp'], 'operation': 'updateNetworkSwitchStackRoutingInterfaceDhcp' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/interfaces/{interfaceId}/dhcp' body_params = ['dhcpMode', 'dhcpRelayServerIps', 'dhcpLeaseTime', 'dnsNameserversOption', 'dnsCustomNameservers', 'bootOptionsEnabled', 'bootNextServer', 'bootFileName', 'dhcpOptions', 'reservedIpRanges', 'fixedIpAssignments', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createNetworkSwitchStackRoutingStaticRoute(self, networkId: str, switchStackId: str, subnet: str, nextHopIp: str, **kwargs): """ **Create a layer 3 static route for a switch stack** https://developer.cisco.com/meraki/api-v1/#!create-network-switch-stack-routing-static-route - networkId (string): (required) - switchStackId (string): (required) - subnet (string): The subnet which is routed via this static route and should be specified in CIDR notation (ex. 1.2.3.0/24) - nextHopIp (string): IP address of the next hop device to which the device sends its traffic for the subnet - name (string): Name or description for layer 3 static route - advertiseViaOspfEnabled (boolean): Option to advertise static route via OSPF - preferOverOspfRoutesEnabled (boolean): Option to prefer static route over OSPF routes """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'staticRoutes'], 'operation': 'createNetworkSwitchStackRoutingStaticRoute' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/staticRoutes' body_params = ['name', 'subnet', 'nextHopIp', 'advertiseViaOspfEnabled', 'preferOverOspfRoutesEnabled', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateNetworkSwitchStackRoutingStaticRoute(self, networkId: str, switchStackId: str, staticRouteId: str, **kwargs): """ **Update a layer 3 static route for a switch stack** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-stack-routing-static-route - networkId (string): (required) - switchStackId (string): (required) - staticRouteId (string): (required) - name (string): Name or description for layer 3 static route - subnet (string): The subnet which is routed via this static route and should be specified in CIDR notation (ex. 1.2.3.0/24) - nextHopIp (string): IP address of the next hop device to which the device sends its traffic for the subnet - advertiseViaOspfEnabled (boolean): Option to advertise static route via OSPF - preferOverOspfRoutesEnabled (boolean): Option to prefer static route over OSPF routes """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'staticRoutes'], 'operation': 'updateNetworkSwitchStackRoutingStaticRoute' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/staticRoutes/{staticRouteId}' body_params = ['name', 'subnet', 'nextHopIp', 'advertiseViaOspfEnabled', 'preferOverOspfRoutesEnabled', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteNetworkSwitchStackRoutingStaticRoute(self, networkId: str, switchStackId: str, staticRouteId: str): """ **Delete a layer 3 static route for a switch stack** https://developer.cisco.com/meraki/api-v1/#!delete-network-switch-stack-routing-static-route - networkId (string): (required) - switchStackId (string): (required) - staticRouteId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'staticRoutes'], 'operation': 'deleteNetworkSwitchStackRoutingStaticRoute' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/staticRoutes/{staticRouteId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateNetworkSwitchStormControl(self, networkId: str, **kwargs): """ **Update the storm control configuration for a switch network** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-storm-control - networkId (string): (required) - broadcastThreshold (integer): Percentage (1 to 99) of total available port bandwidth for broadcast traffic type. Default value 100 percent rate is to clear the configuration. - multicastThreshold (integer): Percentage (1 to 99) of total available port bandwidth for multicast traffic type. Default value 100 percent rate is to clear the configuration. - unknownUnicastThreshold (integer): Percentage (1 to 99) of total available port bandwidth for unknown unicast (dlf-destination lookup failure) traffic type. Default value 100 percent rate is to clear the configuration. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'stormControl'], 'operation': 'updateNetworkSwitchStormControl' } resource = f'/networks/{networkId}/switch/stormControl' body_params = ['broadcastThreshold', 'multicastThreshold', 'unknownUnicastThreshold', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateNetworkSwitchStp(self, networkId: str, **kwargs): """ **Updates STP settings** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-stp - networkId (string): (required) - rstpEnabled (boolean): The spanning tree protocol status in network - stpBridgePriority (array): STP bridge priority for switches/stacks or switch profiles. An empty array will clear the STP bridge priority settings. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'stp'], 'operation': 'updateNetworkSwitchStp' } resource = f'/networks/{networkId}/switch/stp' body_params = ['rstpEnabled', 'stpBridgePriority', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateOrganizationConfigTemplateSwitchProfilePort(self, organizationId: str, configTemplateId: str, profileId: str, portId: str, **kwargs): """ **Update a switch profile port** https://developer.cisco.com/meraki/api-v1/#!update-organization-config-template-switch-profile-port - organizationId (string): (required) - configTemplateId (string): (required) - profileId (string): (required) - portId (string): (required) - name (string): The name of the switch profile port - tags (array): The list of tags of the switch profile port - enabled (boolean): The status of the switch profile port - type (string): The type of the switch profile port ('trunk' or 'access') - vlan (integer): The VLAN of the switch profile port. A null value will clear the value set for trunk ports. - voiceVlan (integer): The voice VLAN of the switch profile port. Only applicable to access ports - allowedVlans (string): The VLANs allowed on the switch profile port. Only applicable to trunk ports - poeEnabled (boolean): The PoE status of the switch profile port - isolationEnabled (boolean): The isolation status of the switch profile port - rstpEnabled (boolean): The rapid spanning tree protocol status - stpGuard (string): The state of the STP guard ('disabled', 'root guard', 'bpdu guard' or 'loop guard') - linkNegotiation (string): The link speed for the switch profile port - portScheduleId (string): The ID of the port schedule. A value of null will clear the port schedule. - udld (string): The action to take when Unidirectional Link is detected (Alert only, Enforce). Default configuration is Alert only. - accessPolicyType (string): The type of the access policy of the switch profile port. Only applicable to access ports. Can be one of 'Open', 'Custom access policy', 'MAC allow list' or 'Sticky MAC allow list' - accessPolicyNumber (integer): The number of a custom access policy to configure on the switch profile port. Only applicable when 'accessPolicyType' is 'Custom access policy' - macAllowList (array): Only devices with MAC addresses specified in this list will have access to this port. Up to 20 MAC addresses can be defined. Only applicable when 'accessPolicyType' is 'MAC allow list' - stickyMacAllowList (array): The initial list of MAC addresses for sticky Mac allow list. Only applicable when 'accessPolicyType' is 'Sticky MAC allow list' - stickyMacAllowListLimit (integer): The maximum number of MAC addresses for sticky MAC allow list. Only applicable when 'accessPolicyType' is 'Sticky MAC allow list' - stormControlEnabled (boolean): The storm control status of the switch profile port - flexibleStackingEnabled (boolean): For supported switches (e.g. MS420/MS425), whether or not the port has flexible stacking enabled. """ kwargs.update(locals()) if 'type' in kwargs: options = ['trunk', 'access'] assert kwargs['type'] in options, f'''"type" cannot be "{kwargs['type']}", & must be set to one of: {options}''' if 'stpGuard' in kwargs: options = ['disabled', 'root guard', 'bpdu guard', 'loop guard'] assert kwargs['stpGuard'] in options, f'''"stpGuard" cannot be "{kwargs['stpGuard']}", & must be set to one of: {options}''' if 'udld' in kwargs: options = ['Alert only', 'Enforce'] assert kwargs['udld'] in options, f'''"udld" cannot be "{kwargs['udld']}", & must be set to one of: {options}''' if 'accessPolicyType' in kwargs: options = ['Open', 'Custom access policy', 'MAC allow list', 'Sticky MAC allow list'] assert kwargs['accessPolicyType'] in options, f'''"accessPolicyType" cannot be "{kwargs['accessPolicyType']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'configTemplates', 'profiles', 'ports'], 'operation': 'updateOrganizationConfigTemplateSwitchProfilePort' } resource = f'/organizations/{organizationId}/configTemplates/{configTemplateId}/switch/profiles/{profileId}/ports/{portId}' body_params = ['name', 'tags', 'enabled', 'type', 'vlan', 'voiceVlan', 'allowedVlans', 'poeEnabled', 'isolationEnabled', 'rstpEnabled', 'stpGuard', 'linkNegotiation', 'portScheduleId', 'udld', 'accessPolicyType', 'accessPolicyNumber', 'macAllowList', 'stickyMacAllowList', 'stickyMacAllowListLimit', 'stormControlEnabled', 'flexibleStackingEnabled', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def cloneOrganizationSwitchDevices(self, organizationId: str, sourceSerial: str, targetSerials: list): """ **Clone port-level and some switch-level configuration settings from a source switch to one or more target switches** https://developer.cisco.com/meraki/api-v1/#!clone-organization-switch-devices - organizationId (string): (required) - sourceSerial (string): Serial number of the source switch (must be on a network not bound to a template) - targetSerials (array): Array of serial numbers of one or more target switches (must be on a network not bound to a template) """ kwargs = locals() metadata = { 'tags': ['switch', 'configure', 'devices'], 'operation': 'cloneOrganizationSwitchDevices' } resource = f'/organizations/{organizationId}/switch/devices/clone' body_params = ['sourceSerial', 'targetSerials', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action
class ActionBatchSwitch(object): def __init__(self): super(ActionBatchSwitch, self).__init__() def cycleDeviceSwitchPorts(self, serial: str, ports: list): """ **Cycle a set of switch ports** https://developer.cisco.com/meraki/api-v1/#!cycle-device-switch-ports - serial (string): (required) - ports (array): List of switch ports. Example: [1, 2-5, 1_MA-MOD-8X10G_1, 1_MA-MOD-8X10G_2-1_MA-MOD-8X10G_8] """ kwargs = locals() metadata = { 'tags': ['switch', 'liveTools', 'ports'], 'operation': 'cycleDeviceSwitchPorts' } resource = f'/devices/{serial}/switch/ports/cycle' body_params = ['ports', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateDeviceSwitchPort(self, serial: str, portId: str, **kwargs): """ **Update a switch port** https://developer.cisco.com/meraki/api-v1/#!update-device-switch-port - serial (string): (required) - portId (string): (required) - name (string): The name of the switch port - tags (array): The list of tags of the switch port - enabled (boolean): The status of the switch port - type (string): The type of the switch port ('trunk' or 'access') - vlan (integer): The VLAN of the switch port. A null value will clear the value set for trunk ports. - voiceVlan (integer): The voice VLAN of the switch port. Only applicable to access ports. - allowedVlans (string): The VLANs allowed on the switch port. Only applicable to trunk ports. - poeEnabled (boolean): The PoE status of the switch port - isolationEnabled (boolean): The isolation status of the switch port - rstpEnabled (boolean): The rapid spanning tree protocol status - stpGuard (string): The state of the STP guard ('disabled', 'root guard', 'bpdu guard' or 'loop guard') - linkNegotiation (string): The link speed for the switch port - portScheduleId (string): The ID of the port schedule. A value of null will clear the port schedule. - udld (string): The action to take when Unidirectional Link is detected (Alert only, Enforce). Default configuration is Alert only. - accessPolicyType (string): The type of the access policy of the switch port. Only applicable to access ports. Can be one of 'Open', 'Custom access policy', 'MAC allow list' or 'Sticky MAC allow list' - accessPolicyNumber (integer): The number of a custom access policy to configure on the switch port. Only applicable when 'accessPolicyType' is 'Custom access policy' - macAllowList (array): Only devices with MAC addresses specified in this list will have access to this port. Up to 20 MAC addresses can be defined. Only applicable when 'accessPolicyType' is 'MAC allow list' - stickyMacAllowList (array): The initial list of MAC addresses for sticky Mac allow list. Only applicable when 'accessPolicyType' is 'Sticky MAC allow list' - stickyMacAllowListLimit (integer): The maximum number of MAC addresses for sticky MAC allow list. Only applicable when 'accessPolicyType' is 'Sticky MAC allow list' - stormControlEnabled (boolean): The storm control status of the switch port - flexibleStackingEnabled (boolean): For supported switches (e.g. MS420/MS425), whether or not the port has flexible stacking enabled. """ kwargs.update(locals()) if 'type' in kwargs: options = ['trunk', 'access'] assert kwargs['type'] in options, f'''"type" cannot be "{kwargs['type']}", & must be set to one of: {options}''' if 'stpGuard' in kwargs: options = ['disabled', 'root guard', 'bpdu guard', 'loop guard'] assert kwargs['stpGuard'] in options, f'''"stpGuard" cannot be "{kwargs['stpGuard']}", & must be set to one of: {options}''' if 'udld' in kwargs: options = ['Alert only', 'Enforce'] assert kwargs['udld'] in options, f'''"udld" cannot be "{kwargs['udld']}", & must be set to one of: {options}''' if 'accessPolicyType' in kwargs: options = ['Open', 'Custom access policy', 'MAC allow list', 'Sticky MAC allow list'] assert kwargs['accessPolicyType'] in options, f'''"accessPolicyType" cannot be "{kwargs['accessPolicyType']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'ports'], 'operation': 'updateDeviceSwitchPort' } resource = f'/devices/{serial}/switch/ports/{portId}' body_params = ['name', 'tags', 'enabled', 'type', 'vlan', 'voiceVlan', 'allowedVlans', 'poeEnabled', 'isolationEnabled', 'rstpEnabled', 'stpGuard', 'linkNegotiation', 'portScheduleId', 'udld', 'accessPolicyType', 'accessPolicyNumber', 'macAllowList', 'stickyMacAllowList', 'stickyMacAllowListLimit', 'stormControlEnabled', 'flexibleStackingEnabled', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createDeviceSwitchRoutingInterface(self, serial: str, name: str, interfaceIp: str, vlanId: int, **kwargs): """ **Create a layer 3 interface for a switch** https://developer.cisco.com/meraki/api-v1/#!create-device-switch-routing-interface - serial (string): (required) - name (string): A friendly name or description for the interface or VLAN. - interfaceIp (string): The IP address this switch will use for layer 3 routing on this VLAN or subnet. This cannot be the same as the switch's management IP. - vlanId (integer): The VLAN this routed interface is on. VLAN must be between 1 and 4094. - subnet (string): The network that this routed interface is on, in CIDR notation (ex. 10.1.1.0/24). - multicastRouting (string): Enable multicast support if, multicast routing between VLANs is required. Options are, 'disabled', 'enabled' or 'IGMP snooping querier'. Default is 'disabled'. - defaultGateway (string): The next hop for any traffic that isn't going to a directly connected subnet or over a static route. This IP address must exist in a subnet with a routed interface. - ospfSettings (object): The OSPF routing settings of the interface. """ kwargs.update(locals()) if 'multicastRouting' in kwargs: options = ['disabled', 'enabled', 'IGMP snooping querier'] assert kwargs['multicastRouting'] in options, f'''"multicastRouting" cannot be "{kwargs['multicastRouting']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'routing', 'interfaces'], 'operation': 'createDeviceSwitchRoutingInterface' } resource = f'/devices/{serial}/switch/routing/interfaces' body_params = ['name', 'subnet', 'interfaceIp', 'multicastRouting', 'vlanId', 'defaultGateway', 'ospfSettings', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateDeviceSwitchRoutingInterface(self, serial: str, interfaceId: str, **kwargs): """ **Update a layer 3 interface for a switch** https://developer.cisco.com/meraki/api-v1/#!update-device-switch-routing-interface - serial (string): (required) - interfaceId (string): (required) - name (string): A friendly name or description for the interface or VLAN. - subnet (string): The network that this routed interface is on, in CIDR notation (ex. 10.1.1.0/24). - interfaceIp (string): The IP address this switch will use for layer 3 routing on this VLAN or subnet. This cannot be the same as the switch's management IP. - multicastRouting (string): Enable multicast support if, multicast routing between VLANs is required. Options are, 'disabled', 'enabled' or 'IGMP snooping querier'. - vlanId (integer): The VLAN this routed interface is on. VLAN must be between 1 and 4094. - ospfSettings (object): The OSPF routing settings of the interface. """ kwargs.update(locals()) if 'multicastRouting' in kwargs: options = ['disabled', 'enabled', 'IGMP snooping querier'] assert kwargs['multicastRouting'] in options, f'''"multicastRouting" cannot be "{kwargs['multicastRouting']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'routing', 'interfaces'], 'operation': 'updateDeviceSwitchRoutingInterface' } resource = f'/devices/{serial}/switch/routing/interfaces/{interfaceId}' body_params = ['name', 'subnet', 'interfaceIp', 'multicastRouting', 'vlanId', 'ospfSettings', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteDeviceSwitchRoutingInterface(self, serial: str, interfaceId: str): """ **Delete a layer 3 interface from the switch** https://developer.cisco.com/meraki/api-v1/#!delete-device-switch-routing-interface - serial (string): (required) - interfaceId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'routing', 'interfaces'], 'operation': 'deleteDeviceSwitchRoutingInterface' } resource = f'/devices/{serial}/switch/routing/interfaces/{interfaceId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateDeviceSwitchRoutingInterfaceDhcp(self, serial: str, interfaceId: str, **kwargs): """ **Update a layer 3 interface DHCP configuration for a switch** https://developer.cisco.com/meraki/api-v1/#!update-device-switch-routing-interface-dhcp - serial (string): (required) - interfaceId (string): (required) - dhcpMode (string): The DHCP mode options for the switch interface ('dhcpDisabled', 'dhcpRelay' or 'dhcpServer') - dhcpRelayServerIps (array): The DHCP relay server IPs to which DHCP packets would get relayed for the switch interface - dhcpLeaseTime (string): The DHCP lease time config for the dhcp server running on switch interface ('30 minutes', '1 hour', '4 hours', '12 hours', '1 day' or '1 week') - dnsNameserversOption (string): The DHCP name server option for the dhcp server running on the switch interface ('googlePublicDns', 'openDns' or 'custom') - dnsCustomNameservers (array): The DHCP name server IPs when DHCP name server option is 'custom' - bootOptionsEnabled (boolean): Enable DHCP boot options to provide PXE boot options configs for the dhcp server running on the switch interface - bootNextServer (string): The PXE boot server IP for the DHCP server running on the switch interface - bootFileName (string): The PXE boot server filename for the DHCP server running on the switch interface - dhcpOptions (array): Array of DHCP options consisting of code, type and value for the DHCP server running on the switch interface - reservedIpRanges (array): Array of DHCP reserved IP assignments for the DHCP server running on the switch interface - fixedIpAssignments (array): Array of DHCP fixed IP assignments for the DHCP server running on the switch interface """ kwargs.update(locals()) if 'dhcpMode' in kwargs: options = ['dhcpDisabled', 'dhcpRelay', 'dhcpServer'] assert kwargs['dhcpMode'] in options, f'''"dhcpMode" cannot be "{kwargs['dhcpMode']}", & must be set to one of: {options}''' if 'dhcpLeaseTime' in kwargs: options = ['30 minutes', '1 hour', '4 hours', '12 hours', '1 day', '1 week'] assert kwargs['dhcpLeaseTime'] in options, f'''"dhcpLeaseTime" cannot be "{kwargs['dhcpLeaseTime']}", & must be set to one of: {options}''' if 'dnsNameserversOption' in kwargs: options = ['googlePublicDns', 'openDns', 'custom'] assert kwargs['dnsNameserversOption'] in options, f'''"dnsNameserversOption" cannot be "{kwargs['dnsNameserversOption']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'routing', 'interfaces', 'dhcp'], 'operation': 'updateDeviceSwitchRoutingInterfaceDhcp' } resource = f'/devices/{serial}/switch/routing/interfaces/{interfaceId}/dhcp' body_params = ['dhcpMode', 'dhcpRelayServerIps', 'dhcpLeaseTime', 'dnsNameserversOption', 'dnsCustomNameservers', 'bootOptionsEnabled', 'bootNextServer', 'bootFileName', 'dhcpOptions', 'reservedIpRanges', 'fixedIpAssignments', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createDeviceSwitchRoutingStaticRoute(self, serial: str, subnet: str, nextHopIp: str, **kwargs): """ **Create a layer 3 static route for a switch** https://developer.cisco.com/meraki/api-v1/#!create-device-switch-routing-static-route - serial (string): (required) - subnet (string): The subnet which is routed via this static route and should be specified in CIDR notation (ex. 1.2.3.0/24) - nextHopIp (string): IP address of the next hop device to which the device sends its traffic for the subnet - name (string): Name or description for layer 3 static route - advertiseViaOspfEnabled (boolean): Option to advertise static route via OSPF - preferOverOspfRoutesEnabled (boolean): Option to prefer static route over OSPF routes """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'routing', 'staticRoutes'], 'operation': 'createDeviceSwitchRoutingStaticRoute' } resource = f'/devices/{serial}/switch/routing/staticRoutes' body_params = ['name', 'subnet', 'nextHopIp', 'advertiseViaOspfEnabled', 'preferOverOspfRoutesEnabled', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateDeviceSwitchRoutingStaticRoute(self, serial: str, staticRouteId: str, **kwargs): """ **Update a layer 3 static route for a switch** https://developer.cisco.com/meraki/api-v1/#!update-device-switch-routing-static-route - serial (string): (required) - staticRouteId (string): (required) - name (string): Name or description for layer 3 static route - subnet (string): The subnet which is routed via this static route and should be specified in CIDR notation (ex. 1.2.3.0/24) - nextHopIp (string): IP address of the next hop device to which the device sends its traffic for the subnet - advertiseViaOspfEnabled (boolean): Option to advertise static route via OSPF - preferOverOspfRoutesEnabled (boolean): Option to prefer static route over OSPF routes """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'routing', 'staticRoutes'], 'operation': 'updateDeviceSwitchRoutingStaticRoute' } resource = f'/devices/{serial}/switch/routing/staticRoutes/{staticRouteId}' body_params = ['name', 'subnet', 'nextHopIp', 'advertiseViaOspfEnabled', 'preferOverOspfRoutesEnabled', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteDeviceSwitchRoutingStaticRoute(self, serial: str, staticRouteId: str): """ **Delete a layer 3 static route for a switch** https://developer.cisco.com/meraki/api-v1/#!delete-device-switch-routing-static-route - serial (string): (required) - staticRouteId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'routing', 'staticRoutes'], 'operation': 'deleteDeviceSwitchRoutingStaticRoute' } resource = f'/devices/{serial}/switch/routing/staticRoutes/{staticRouteId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateDeviceSwitchWarmSpare(self, serial: str, enabled: bool, **kwargs): """ **Update warm spare configuration for a switch** https://developer.cisco.com/meraki/api-v1/#!update-device-switch-warm-spare - serial (string): (required) - enabled (boolean): Enable or disable warm spare for a switch - spareSerial (string): Serial number of the warm spare switch """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'warmSpare'], 'operation': 'updateDeviceSwitchWarmSpare' } resource = f'/devices/{serial}/switch/warmSpare' body_params = ['enabled', 'spareSerial', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createNetworkSwitchAccessPolicy(self, networkId: str, name: str, radiusServers: list, radiusTestingEnabled: bool, radiusCoaSupportEnabled: bool, radiusAccountingEnabled: bool, hostMode: str, urlRedirectWalledGardenEnabled: bool, **kwargs): """ **Create an access policy for a switch network** https://developer.cisco.com/meraki/api-v1/#!create-network-switch-access-policy - networkId (string): (required) - name (string): Name of the access policy - radiusServers (array): List of RADIUS servers to require connecting devices to authenticate against before granting network access - radiusTestingEnabled (boolean): If enabled, Meraki devices will periodically send access-request messages to these RADIUS servers - radiusCoaSupportEnabled (boolean): Change of authentication for RADIUS re-authentication and disconnection - radiusAccountingEnabled (boolean): Enable to send start, interim-update and stop messages to a configured RADIUS accounting server for tracking connected clients - hostMode (string): Choose the Host Mode for the access policy. - urlRedirectWalledGardenEnabled (boolean): Enable to restrict access for clients to a specific set of IP addresses or hostnames prior to authentication - radiusAccountingServers (array): List of RADIUS accounting servers to require connecting devices to authenticate against before granting network access - radiusGroupAttribute (string): Acceptable values are `""` for None, or `"11"` for Group Policies ACL - accessPolicyType (string): Access Type of the policy. Automatically 'Hybrid authentication' when hostMode is 'Multi-Domain'. - increaseAccessSpeed (boolean): Enabling this option will make switches execute 802.1X and MAC-bypass authentication simultaneously so that clients authenticate faster. Only required when accessPolicyType is 'Hybrid Authentication. - guestVlanId (integer): ID for the guest VLAN allow unauthorized devices access to limited network resources - voiceVlanClients (boolean): CDP/LLDP capable voice clients will be able to use this VLAN. Automatically true when hostMode is 'Multi-Domain'. - urlRedirectWalledGardenRanges (array): IP address ranges, in CIDR notation, to restrict access for clients to a specific set of IP addresses or hostnames prior to authentication """ kwargs.update(locals()) if 'hostMode' in kwargs: options = ['Single-Host', 'Multi-Domain', 'Multi-Host', 'Multi-Auth'] assert kwargs['hostMode'] in options, f'''"hostMode" cannot be "{kwargs['hostMode']}", & must be set to one of: {options}''' if 'accessPolicyType' in kwargs: options = ['802.1x', 'MAC authentication bypass', 'Hybrid authentication'] assert kwargs['accessPolicyType'] in options, f'''"accessPolicyType" cannot be "{kwargs['accessPolicyType']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'accessPolicies'], 'operation': 'createNetworkSwitchAccessPolicy' } resource = f'/networks/{networkId}/switch/accessPolicies' body_params = ['name', 'radiusServers', 'radiusTestingEnabled', 'radiusCoaSupportEnabled', 'radiusAccountingEnabled', 'radiusAccountingServers', 'radiusGroupAttribute', 'hostMode', 'accessPolicyType', 'increaseAccessSpeed', 'guestVlanId', 'voiceVlanClients', 'urlRedirectWalledGardenEnabled', 'urlRedirectWalledGardenRanges', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateNetworkSwitchAccessPolicy(self, networkId: str, accessPolicyNumber: str, **kwargs): """ **Update an access policy for a switch network** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-access-policy - networkId (string): (required) - accessPolicyNumber (string): (required) - name (string): Name of the access policy - radiusServers (array): List of RADIUS servers to require connecting devices to authenticate against before granting network access - radiusTestingEnabled (boolean): If enabled, Meraki devices will periodically send access-request messages to these RADIUS servers - radiusCoaSupportEnabled (boolean): Change of authentication for RADIUS re-authentication and disconnection - radiusAccountingEnabled (boolean): Enable to send start, interim-update and stop messages to a configured RADIUS accounting server for tracking connected clients - radiusAccountingServers (array): List of RADIUS accounting servers to require connecting devices to authenticate against before granting network access - radiusGroupAttribute (string): Can be either `""`, which means `None` on Dashboard, or `"11"`, which means `Filter-Id` on Dashboard and will use Group Policy ACLs when supported (firmware 14+) - hostMode (string): Choose the Host Mode for the access policy. - accessPolicyType (string): Access Type of the policy. Automatically 'Hybrid authentication' when hostMode is 'Multi-Domain'. - increaseAccessSpeed (boolean): Enabling this option will make switches execute 802.1X and MAC-bypass authentication simultaneously so that clients authenticate faster. Only required when accessPolicyType is 'Hybrid Authentication. - guestVlanId (integer): ID for the guest VLAN allow unauthorized devices access to limited network resources - voiceVlanClients (boolean): CDP/LLDP capable voice clients will be able to use this VLAN. Automatically true when hostMode is 'Multi-Domain'. - urlRedirectWalledGardenEnabled (boolean): Enable to restrict access for clients to a specific set of IP addresses or hostnames prior to authentication - urlRedirectWalledGardenRanges (array): IP address ranges, in CIDR notation, to restrict access for clients to a specific set of IP addresses or hostnames prior to authentication """ kwargs.update(locals()) if 'hostMode' in kwargs: options = ['Single-Host', 'Multi-Domain', 'Multi-Host', 'Multi-Auth'] assert kwargs['hostMode'] in options, f'''"hostMode" cannot be "{kwargs['hostMode']}", & must be set to one of: {options}''' if 'accessPolicyType' in kwargs: options = ['802.1x', 'MAC authentication bypass', 'Hybrid authentication'] assert kwargs['accessPolicyType'] in options, f'''"accessPolicyType" cannot be "{kwargs['accessPolicyType']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'accessPolicies'], 'operation': 'updateNetworkSwitchAccessPolicy' } resource = f'/networks/{networkId}/switch/accessPolicies/{accessPolicyNumber}' body_params = ['name', 'radiusServers', 'radiusTestingEnabled', 'radiusCoaSupportEnabled', 'radiusAccountingEnabled', 'radiusAccountingServers', 'radiusGroupAttribute', 'hostMode', 'accessPolicyType', 'increaseAccessSpeed', 'guestVlanId', 'voiceVlanClients', 'urlRedirectWalledGardenEnabled', 'urlRedirectWalledGardenRanges', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteNetworkSwitchAccessPolicy(self, networkId: str, accessPolicyNumber: str): """ **Delete an access policy for a switch network** https://developer.cisco.com/meraki/api-v1/#!delete-network-switch-access-policy - networkId (string): (required) - accessPolicyNumber (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'accessPolicies'], 'operation': 'deleteNetworkSwitchAccessPolicy' } resource = f'/networks/{networkId}/switch/accessPolicies/{accessPolicyNumber}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateNetworkSwitchAlternateManagementInterface(self, networkId: str, **kwargs): """ **Update the switch alternate management interface for the network** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-alternate-management-interface - networkId (string): (required) - enabled (boolean): Boolean value to enable or disable AMI configuration. If enabled, VLAN and protocols must be set - vlanId (integer): Alternate management VLAN, must be between 1 and 4094 - protocols (array): Can be one or more of the following values: 'radius', 'snmp' or 'syslog' - switches (array): Array of switch serial number and IP assignment. If parameter is present, it cannot have empty body. Note: switches parameter is not applicable for template networks, in other words, do not put 'switches' in the body when updating template networks. Also, an empty 'switches' array will remove all previous assignments """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'alternateManagementInterface'], 'operation': 'updateNetworkSwitchAlternateManagementInterface' } resource = f'/networks/{networkId}/switch/alternateManagementInterface' body_params = ['enabled', 'vlanId', 'protocols', 'switches', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateNetworkSwitchDhcpServerPolicy(self, networkId: str, **kwargs): """ **Update the DHCP server policy** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-dhcp-server-policy - networkId (string): (required) - defaultPolicy (string): 'allow' or 'block' new DHCP servers. Default value is 'allow'. - allowedServers (array): List the MAC addresses of DHCP servers to permit on the network. Applicable only if defaultPolicy is set to block. An empty array will clear the entries. - blockedServers (array): List the MAC addresses of DHCP servers to block on the network. Applicable only if defaultPolicy is set to allow. An empty array will clear the entries. """ kwargs.update(locals()) if 'defaultPolicy' in kwargs: options = ['allow', 'block'] assert kwargs['defaultPolicy'] in options, f'''"defaultPolicy" cannot be "{kwargs['defaultPolicy']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'dhcpServerPolicy'], 'operation': 'updateNetworkSwitchDhcpServerPolicy' } resource = f'/networks/{networkId}/switch/dhcpServerPolicy' body_params = ['defaultPolicy', 'allowedServers', 'blockedServers', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateNetworkSwitchDscpToCosMappings(self, networkId: str, mappings: list): """ **Update the DSCP to CoS mappings** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-dscp-to-cos-mappings - networkId (string): (required) - mappings (array): An array of DSCP to CoS mappings. An empty array will reset the mappings to default. """ kwargs = locals() metadata = { 'tags': ['switch', 'configure', 'dscpToCosMappings'], 'operation': 'updateNetworkSwitchDscpToCosMappings' } resource = f'/networks/{networkId}/switch/dscpToCosMappings' body_params = ['mappings', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createNetworkSwitchLinkAggregation(self, networkId: str, **kwargs): """ **Create a link aggregation group** https://developer.cisco.com/meraki/api-v1/#!create-network-switch-link-aggregation - networkId (string): (required) - switchPorts (array): Array of switch or stack ports for creating aggregation group. Minimum 2 and maximum 8 ports are supported. - switchProfilePorts (array): Array of switch profile ports for creating aggregation group. Minimum 2 and maximum 8 ports are supported. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'linkAggregations'], 'operation': 'createNetworkSwitchLinkAggregation' } resource = f'/networks/{networkId}/switch/linkAggregations' body_params = ['switchPorts', 'switchProfilePorts', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateNetworkSwitchLinkAggregation(self, networkId: str, linkAggregationId: str, **kwargs): """ **Update a link aggregation group** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-link-aggregation - networkId (string): (required) - linkAggregationId (string): (required) - switchPorts (array): Array of switch or stack ports for updating aggregation group. Minimum 2 and maximum 8 ports are supported. - switchProfilePorts (array): Array of switch profile ports for updating aggregation group. Minimum 2 and maximum 8 ports are supported. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'linkAggregations'], 'operation': 'updateNetworkSwitchLinkAggregation' } resource = f'/networks/{networkId}/switch/linkAggregations/{linkAggregationId}' body_params = ['switchPorts', 'switchProfilePorts', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteNetworkSwitchLinkAggregation(self, networkId: str, linkAggregationId: str): """ **Split a link aggregation group into separate ports** https://developer.cisco.com/meraki/api-v1/#!delete-network-switch-link-aggregation - networkId (string): (required) - linkAggregationId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'linkAggregations'], 'operation': 'deleteNetworkSwitchLinkAggregation' } resource = f'/networks/{networkId}/switch/linkAggregations/{linkAggregationId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateNetworkSwitchMtu(self, networkId: str, **kwargs): """ **Update the MTU configuration** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-mtu - networkId (string): (required) - defaultMtuSize (integer): MTU size for the entire network. Default value is 9578. - overrides (array): Override MTU size for individual switches or switch profiles. An empty array will clear overrides. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'mtu'], 'operation': 'updateNetworkSwitchMtu' } resource = f'/networks/{networkId}/switch/mtu' body_params = ['defaultMtuSize', 'overrides', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateNetworkSwitchPortSchedule(self, networkId: str, portScheduleId: str, **kwargs): """ **Update a switch port schedule** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-port-schedule - networkId (string): (required) - portScheduleId (string): (required) - name (string): The name for your port schedule. - portSchedule (object): The schedule for switch port scheduling. Schedules are applied to days of the week. When it's empty, default schedule with all days of a week are configured. Any unspecified day in the schedule is added as a default schedule configuration of the day. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'portSchedules'], 'operation': 'updateNetworkSwitchPortSchedule' } resource = f'/networks/{networkId}/switch/portSchedules/{portScheduleId}' body_params = ['name', 'portSchedule', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createNetworkSwitchQosRule(self, networkId: str, vlan: int, **kwargs): """ **Add a quality of service rule** https://developer.cisco.com/meraki/api-v1/#!create-network-switch-qos-rule - networkId (string): (required) - vlan (integer): The VLAN of the incoming packet. A null value will match any VLAN. - protocol (string): The protocol of the incoming packet. Can be one of "ANY", "TCP" or "UDP". Default value is "ANY" - srcPort (integer): The source port of the incoming packet. Applicable only if protocol is TCP or UDP. - srcPortRange (string): The source port range of the incoming packet. Applicable only if protocol is set to TCP or UDP. Example: 70-80 - dstPort (integer): The destination port of the incoming packet. Applicable only if protocol is TCP or UDP. - dstPortRange (string): The destination port range of the incoming packet. Applicable only if protocol is set to TCP or UDP. Example: 70-80 - dscp (integer): DSCP tag. Set this to -1 to trust incoming DSCP. Default value is 0 """ kwargs.update(locals()) if 'protocol' in kwargs: options = ['ANY', 'TCP', 'UDP'] assert kwargs['protocol'] in options, f'''"protocol" cannot be "{kwargs['protocol']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'qosRules'], 'operation': 'createNetworkSwitchQosRule' } resource = f'/networks/{networkId}/switch/qosRules' body_params = ['vlan', 'protocol', 'srcPort', 'srcPortRange', 'dstPort', 'dstPortRange', 'dscp', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateNetworkSwitchQosRulesOrder(self, networkId: str, ruleIds: list): """ **Update the order in which the rules should be processed by the switch** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-qos-rules-order - networkId (string): (required) - ruleIds (array): A list of quality of service rule IDs arranged in order in which they should be processed by the switch. """ kwargs = locals() metadata = { 'tags': ['switch', 'configure', 'qosRules', 'order'], 'operation': 'updateNetworkSwitchQosRulesOrder' } resource = f'/networks/{networkId}/switch/qosRules/order' body_params = ['ruleIds', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteNetworkSwitchQosRule(self, networkId: str, qosRuleId: str): """ **Delete a quality of service rule** https://developer.cisco.com/meraki/api-v1/#!delete-network-switch-qos-rule - networkId (string): (required) - qosRuleId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'qosRules'], 'operation': 'deleteNetworkSwitchQosRule' } resource = f'/networks/{networkId}/switch/qosRules/{qosRuleId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateNetworkSwitchQosRule(self, networkId: str, qosRuleId: str, **kwargs): """ **Update a quality of service rule** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-qos-rule - networkId (string): (required) - qosRuleId (string): (required) - vlan (integer): The VLAN of the incoming packet. A null value will match any VLAN. - protocol (string): The protocol of the incoming packet. Can be one of "ANY", "TCP" or "UDP". Default value is "ANY". - srcPort (integer): The source port of the incoming packet. Applicable only if protocol is TCP or UDP. - srcPortRange (string): The source port range of the incoming packet. Applicable only if protocol is set to TCP or UDP. Example: 70-80 - dstPort (integer): The destination port of the incoming packet. Applicable only if protocol is TCP or UDP. - dstPortRange (string): The destination port range of the incoming packet. Applicable only if protocol is set to TCP or UDP. Example: 70-80 - dscp (integer): DSCP tag that should be assigned to incoming packet. Set this to -1 to trust incoming DSCP. Default value is 0. """ kwargs.update(locals()) if 'protocol' in kwargs: options = ['ANY', 'TCP', 'UDP'] assert kwargs['protocol'] in options, f'''"protocol" cannot be "{kwargs['protocol']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'qosRules'], 'operation': 'updateNetworkSwitchQosRule' } resource = f'/networks/{networkId}/switch/qosRules/{qosRuleId}' body_params = ['vlan', 'protocol', 'srcPort', 'srcPortRange', 'dstPort', 'dstPortRange', 'dscp', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateNetworkSwitchRoutingMulticast(self, networkId: str, **kwargs): """ **Update multicast settings for a network** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-routing-multicast - networkId (string): (required) - defaultSettings (object): Default multicast setting for entire network. IGMP snooping and Flood unknown multicast traffic settings are enabled by default. - overrides (array): Array of paired switches/stacks/profiles and corresponding multicast settings. An empty array will clear the multicast settings. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'routing', 'multicast'], 'operation': 'updateNetworkSwitchRoutingMulticast' } resource = f'/networks/{networkId}/switch/routing/multicast' body_params = ['defaultSettings', 'overrides', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createNetworkSwitchRoutingMulticastRendezvousPoint(self, networkId: str, interfaceIp: str, multicastGroup: str): """ **Create a multicast rendezvous point** https://developer.cisco.com/meraki/api-v1/#!create-network-switch-routing-multicast-rendezvous-point - networkId (string): (required) - interfaceIp (string): The IP address of the interface where the RP needs to be created. - multicastGroup (string): 'Any', or the IP address of a multicast group """ kwargs = locals() metadata = { 'tags': ['switch', 'configure', 'routing', 'multicast', 'rendezvousPoints'], 'operation': 'createNetworkSwitchRoutingMulticastRendezvousPoint' } resource = f'/networks/{networkId}/switch/routing/multicast/rendezvousPoints' body_params = ['interfaceIp', 'multicastGroup', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def deleteNetworkSwitchRoutingMulticastRendezvousPoint(self, networkId: str, rendezvousPointId: str): """ **Delete a multicast rendezvous point** https://developer.cisco.com/meraki/api-v1/#!delete-network-switch-routing-multicast-rendezvous-point - networkId (string): (required) - rendezvousPointId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'routing', 'multicast', 'rendezvousPoints'], 'operation': 'deleteNetworkSwitchRoutingMulticastRendezvousPoint' } resource = f'/networks/{networkId}/switch/routing/multicast/rendezvousPoints/{rendezvousPointId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateNetworkSwitchRoutingMulticastRendezvousPoint(self, networkId: str, rendezvousPointId: str, interfaceIp: str, multicastGroup: str): """ **Update a multicast rendezvous point** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-routing-multicast-rendezvous-point - networkId (string): (required) - rendezvousPointId (string): (required) - interfaceIp (string): The IP address of the interface to use - multicastGroup (string): 'Any', or the IP address of a multicast group """ kwargs = locals() metadata = { 'tags': ['switch', 'configure', 'routing', 'multicast', 'rendezvousPoints'], 'operation': 'updateNetworkSwitchRoutingMulticastRendezvousPoint' } resource = f'/networks/{networkId}/switch/routing/multicast/rendezvousPoints/{rendezvousPointId}' body_params = ['interfaceIp', 'multicastGroup', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateNetworkSwitchRoutingOspf(self, networkId: str, **kwargs): """ **Update layer 3 OSPF routing configuration** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-routing-ospf - networkId (string): (required) - enabled (boolean): Boolean value to enable or disable OSPF routing. OSPF routing is disabled by default. - helloTimerInSeconds (integer): Time interval in seconds at which hello packet will be sent to OSPF neighbors to maintain connectivity. Value must be between 1 and 255. Default is 10 seconds - deadTimerInSeconds (integer): Time interval to determine when the peer will be declare inactive/dead. Value must be between 1 and 65535 - areas (array): OSPF areas - md5AuthenticationEnabled (boolean): Boolean value to enable or disable MD5 authentication. MD5 authentication is disabled by default. - md5AuthenticationKey (object): MD5 authentication credentials. This param is only relevant if md5AuthenticationEnabled is true """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'routing', 'ospf'], 'operation': 'updateNetworkSwitchRoutingOspf' } resource = f'/networks/{networkId}/switch/routing/ospf' body_params = ['enabled', 'helloTimerInSeconds', 'deadTimerInSeconds', 'areas', 'md5AuthenticationEnabled', 'md5AuthenticationKey', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createNetworkSwitchStackRoutingInterface(self, networkId: str, switchStackId: str, name: str, subnet: str, interfaceIp: str, vlanId: int, **kwargs): """ **Create a layer 3 interface for a switch stack** https://developer.cisco.com/meraki/api-v1/#!create-network-switch-stack-routing-interface - networkId (string): (required) - switchStackId (string): (required) - name (string): A friendly name or description for the interface or VLAN. - subnet (string): The network that this routed interface is on, in CIDR notation (ex. 10.1.1.0/24). - interfaceIp (string): The IP address this switch stack will use for layer 3 routing on this VLAN or subnet. This cannot be the same as the switch's management IP. - vlanId (integer): The VLAN this routed interface is on. VLAN must be between 1 and 4094. - multicastRouting (string): Enable multicast support if, multicast routing between VLANs is required. Options are, 'disabled', 'enabled' or 'IGMP snooping querier'. Default is 'disabled'. - defaultGateway (string): The next hop for any traffic that isn't going to a directly connected subnet or over a static route. This IP address must exist in a subnet with a routed interface. - ospfSettings (object): The OSPF routing settings of the interface. """ kwargs.update(locals()) if 'multicastRouting' in kwargs: options = ['disabled', 'enabled', 'IGMP snooping querier'] assert kwargs['multicastRouting'] in options, f'''"multicastRouting" cannot be "{kwargs['multicastRouting']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'interfaces'], 'operation': 'createNetworkSwitchStackRoutingInterface' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/interfaces' body_params = ['name', 'subnet', 'interfaceIp', 'multicastRouting', 'vlanId', 'defaultGateway', 'ospfSettings', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateNetworkSwitchStackRoutingInterface(self, networkId: str, switchStackId: str, interfaceId: str, **kwargs): """ **Update a layer 3 interface for a switch stack** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-stack-routing-interface - networkId (string): (required) - switchStackId (string): (required) - interfaceId (string): (required) - name (string): A friendly name or description for the interface or VLAN. - subnet (string): The network that this routed interface is on, in CIDR notation (ex. 10.1.1.0/24). - interfaceIp (string): The IP address this switch stack will use for layer 3 routing on this VLAN or subnet. This cannot be the same as the switch's management IP. - multicastRouting (string): Enable multicast support if, multicast routing between VLANs is required. Options are, 'disabled', 'enabled' or 'IGMP snooping querier'. - vlanId (integer): The VLAN this routed interface is on. VLAN must be between 1 and 4094. - ospfSettings (object): The OSPF routing settings of the interface. """ kwargs.update(locals()) if 'multicastRouting' in kwargs: options = ['disabled', 'enabled', 'IGMP snooping querier'] assert kwargs['multicastRouting'] in options, f'''"multicastRouting" cannot be "{kwargs['multicastRouting']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'interfaces'], 'operation': 'updateNetworkSwitchStackRoutingInterface' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/interfaces/{interfaceId}' body_params = ['name', 'subnet', 'interfaceIp', 'multicastRouting', 'vlanId', 'ospfSettings', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteNetworkSwitchStackRoutingInterface(self, networkId: str, switchStackId: str, interfaceId: str): """ **Delete a layer 3 interface from a switch stack** https://developer.cisco.com/meraki/api-v1/#!delete-network-switch-stack-routing-interface - networkId (string): (required) - switchStackId (string): (required) - interfaceId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'interfaces'], 'operation': 'deleteNetworkSwitchStackRoutingInterface' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/interfaces/{interfaceId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateNetworkSwitchStackRoutingInterfaceDhcp(self, networkId: str, switchStackId: str, interfaceId: str, **kwargs): """ **Update a layer 3 interface DHCP configuration for a switch stack** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-stack-routing-interface-dhcp - networkId (string): (required) - switchStackId (string): (required) - interfaceId (string): (required) - dhcpMode (string): The DHCP mode options for the switch stack interface ('dhcpDisabled', 'dhcpRelay' or 'dhcpServer') - dhcpRelayServerIps (array): The DHCP relay server IPs to which DHCP packets would get relayed for the switch stack interface - dhcpLeaseTime (string): The DHCP lease time config for the dhcp server running on switch stack interface ('30 minutes', '1 hour', '4 hours', '12 hours', '1 day' or '1 week') - dnsNameserversOption (string): The DHCP name server option for the dhcp server running on the switch stack interface ('googlePublicDns', 'openDns' or 'custom') - dnsCustomNameservers (array): The DHCP name server IPs when DHCP name server option is 'custom' - bootOptionsEnabled (boolean): Enable DHCP boot options to provide PXE boot options configs for the dhcp server running on the switch stack interface - bootNextServer (string): The PXE boot server IP for the DHCP server running on the switch stack interface - bootFileName (string): The PXE boot server file name for the DHCP server running on the switch stack interface - dhcpOptions (array): Array of DHCP options consisting of code, type and value for the DHCP server running on the switch stack interface - reservedIpRanges (array): Array of DHCP reserved IP assignments for the DHCP server running on the switch stack interface - fixedIpAssignments (array): Array of DHCP fixed IP assignments for the DHCP server running on the switch stack interface """ kwargs.update(locals()) if 'dhcpMode' in kwargs: options = ['dhcpDisabled', 'dhcpRelay', 'dhcpServer'] assert kwargs['dhcpMode'] in options, f'''"dhcpMode" cannot be "{kwargs['dhcpMode']}", & must be set to one of: {options}''' if 'dhcpLeaseTime' in kwargs: options = ['30 minutes', '1 hour', '4 hours', '12 hours', '1 day', '1 week'] assert kwargs['dhcpLeaseTime'] in options, f'''"dhcpLeaseTime" cannot be "{kwargs['dhcpLeaseTime']}", & must be set to one of: {options}''' if 'dnsNameserversOption' in kwargs: options = ['googlePublicDns', 'openDns', 'custom'] assert kwargs['dnsNameserversOption'] in options, f'''"dnsNameserversOption" cannot be "{kwargs['dnsNameserversOption']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'interfaces', 'dhcp'], 'operation': 'updateNetworkSwitchStackRoutingInterfaceDhcp' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/interfaces/{interfaceId}/dhcp' body_params = ['dhcpMode', 'dhcpRelayServerIps', 'dhcpLeaseTime', 'dnsNameserversOption', 'dnsCustomNameservers', 'bootOptionsEnabled', 'bootNextServer', 'bootFileName', 'dhcpOptions', 'reservedIpRanges', 'fixedIpAssignments', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def createNetworkSwitchStackRoutingStaticRoute(self, networkId: str, switchStackId: str, subnet: str, nextHopIp: str, **kwargs): """ **Create a layer 3 static route for a switch stack** https://developer.cisco.com/meraki/api-v1/#!create-network-switch-stack-routing-static-route - networkId (string): (required) - switchStackId (string): (required) - subnet (string): The subnet which is routed via this static route and should be specified in CIDR notation (ex. 1.2.3.0/24) - nextHopIp (string): IP address of the next hop device to which the device sends its traffic for the subnet - name (string): Name or description for layer 3 static route - advertiseViaOspfEnabled (boolean): Option to advertise static route via OSPF - preferOverOspfRoutesEnabled (boolean): Option to prefer static route over OSPF routes """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'staticRoutes'], 'operation': 'createNetworkSwitchStackRoutingStaticRoute' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/staticRoutes' body_params = ['name', 'subnet', 'nextHopIp', 'advertiseViaOspfEnabled', 'preferOverOspfRoutesEnabled', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action def updateNetworkSwitchStackRoutingStaticRoute(self, networkId: str, switchStackId: str, staticRouteId: str, **kwargs): """ **Update a layer 3 static route for a switch stack** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-stack-routing-static-route - networkId (string): (required) - switchStackId (string): (required) - staticRouteId (string): (required) - name (string): Name or description for layer 3 static route - subnet (string): The subnet which is routed via this static route and should be specified in CIDR notation (ex. 1.2.3.0/24) - nextHopIp (string): IP address of the next hop device to which the device sends its traffic for the subnet - advertiseViaOspfEnabled (boolean): Option to advertise static route via OSPF - preferOverOspfRoutesEnabled (boolean): Option to prefer static route over OSPF routes """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'staticRoutes'], 'operation': 'updateNetworkSwitchStackRoutingStaticRoute' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/staticRoutes/{staticRouteId}' body_params = ['name', 'subnet', 'nextHopIp', 'advertiseViaOspfEnabled', 'preferOverOspfRoutesEnabled', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def deleteNetworkSwitchStackRoutingStaticRoute(self, networkId: str, switchStackId: str, staticRouteId: str): """ **Delete a layer 3 static route for a switch stack** https://developer.cisco.com/meraki/api-v1/#!delete-network-switch-stack-routing-static-route - networkId (string): (required) - switchStackId (string): (required) - staticRouteId (string): (required) """ metadata = { 'tags': ['switch', 'configure', 'stacks', 'routing', 'staticRoutes'], 'operation': 'deleteNetworkSwitchStackRoutingStaticRoute' } resource = f'/networks/{networkId}/switch/stacks/{switchStackId}/routing/staticRoutes/{staticRouteId}' action = { "resource": resource, "operation": "destroy", "body": payload } return action def updateNetworkSwitchStormControl(self, networkId: str, **kwargs): """ **Update the storm control configuration for a switch network** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-storm-control - networkId (string): (required) - broadcastThreshold (integer): Percentage (1 to 99) of total available port bandwidth for broadcast traffic type. Default value 100 percent rate is to clear the configuration. - multicastThreshold (integer): Percentage (1 to 99) of total available port bandwidth for multicast traffic type. Default value 100 percent rate is to clear the configuration. - unknownUnicastThreshold (integer): Percentage (1 to 99) of total available port bandwidth for unknown unicast (dlf-destination lookup failure) traffic type. Default value 100 percent rate is to clear the configuration. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'stormControl'], 'operation': 'updateNetworkSwitchStormControl' } resource = f'/networks/{networkId}/switch/stormControl' body_params = ['broadcastThreshold', 'multicastThreshold', 'unknownUnicastThreshold', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateNetworkSwitchStp(self, networkId: str, **kwargs): """ **Updates STP settings** https://developer.cisco.com/meraki/api-v1/#!update-network-switch-stp - networkId (string): (required) - rstpEnabled (boolean): The spanning tree protocol status in network - stpBridgePriority (array): STP bridge priority for switches/stacks or switch profiles. An empty array will clear the STP bridge priority settings. """ kwargs.update(locals()) metadata = { 'tags': ['switch', 'configure', 'stp'], 'operation': 'updateNetworkSwitchStp' } resource = f'/networks/{networkId}/switch/stp' body_params = ['rstpEnabled', 'stpBridgePriority', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def updateOrganizationConfigTemplateSwitchProfilePort(self, organizationId: str, configTemplateId: str, profileId: str, portId: str, **kwargs): """ **Update a switch profile port** https://developer.cisco.com/meraki/api-v1/#!update-organization-config-template-switch-profile-port - organizationId (string): (required) - configTemplateId (string): (required) - profileId (string): (required) - portId (string): (required) - name (string): The name of the switch profile port - tags (array): The list of tags of the switch profile port - enabled (boolean): The status of the switch profile port - type (string): The type of the switch profile port ('trunk' or 'access') - vlan (integer): The VLAN of the switch profile port. A null value will clear the value set for trunk ports. - voiceVlan (integer): The voice VLAN of the switch profile port. Only applicable to access ports - allowedVlans (string): The VLANs allowed on the switch profile port. Only applicable to trunk ports - poeEnabled (boolean): The PoE status of the switch profile port - isolationEnabled (boolean): The isolation status of the switch profile port - rstpEnabled (boolean): The rapid spanning tree protocol status - stpGuard (string): The state of the STP guard ('disabled', 'root guard', 'bpdu guard' or 'loop guard') - linkNegotiation (string): The link speed for the switch profile port - portScheduleId (string): The ID of the port schedule. A value of null will clear the port schedule. - udld (string): The action to take when Unidirectional Link is detected (Alert only, Enforce). Default configuration is Alert only. - accessPolicyType (string): The type of the access policy of the switch profile port. Only applicable to access ports. Can be one of 'Open', 'Custom access policy', 'MAC allow list' or 'Sticky MAC allow list' - accessPolicyNumber (integer): The number of a custom access policy to configure on the switch profile port. Only applicable when 'accessPolicyType' is 'Custom access policy' - macAllowList (array): Only devices with MAC addresses specified in this list will have access to this port. Up to 20 MAC addresses can be defined. Only applicable when 'accessPolicyType' is 'MAC allow list' - stickyMacAllowList (array): The initial list of MAC addresses for sticky Mac allow list. Only applicable when 'accessPolicyType' is 'Sticky MAC allow list' - stickyMacAllowListLimit (integer): The maximum number of MAC addresses for sticky MAC allow list. Only applicable when 'accessPolicyType' is 'Sticky MAC allow list' - stormControlEnabled (boolean): The storm control status of the switch profile port - flexibleStackingEnabled (boolean): For supported switches (e.g. MS420/MS425), whether or not the port has flexible stacking enabled. """ kwargs.update(locals()) if 'type' in kwargs: options = ['trunk', 'access'] assert kwargs['type'] in options, f'''"type" cannot be "{kwargs['type']}", & must be set to one of: {options}''' if 'stpGuard' in kwargs: options = ['disabled', 'root guard', 'bpdu guard', 'loop guard'] assert kwargs['stpGuard'] in options, f'''"stpGuard" cannot be "{kwargs['stpGuard']}", & must be set to one of: {options}''' if 'udld' in kwargs: options = ['Alert only', 'Enforce'] assert kwargs['udld'] in options, f'''"udld" cannot be "{kwargs['udld']}", & must be set to one of: {options}''' if 'accessPolicyType' in kwargs: options = ['Open', 'Custom access policy', 'MAC allow list', 'Sticky MAC allow list'] assert kwargs['accessPolicyType'] in options, f'''"accessPolicyType" cannot be "{kwargs['accessPolicyType']}", & must be set to one of: {options}''' metadata = { 'tags': ['switch', 'configure', 'configTemplates', 'profiles', 'ports'], 'operation': 'updateOrganizationConfigTemplateSwitchProfilePort' } resource = f'/organizations/{organizationId}/configTemplates/{configTemplateId}/switch/profiles/{profileId}/ports/{portId}' body_params = ['name', 'tags', 'enabled', 'type', 'vlan', 'voiceVlan', 'allowedVlans', 'poeEnabled', 'isolationEnabled', 'rstpEnabled', 'stpGuard', 'linkNegotiation', 'portScheduleId', 'udld', 'accessPolicyType', 'accessPolicyNumber', 'macAllowList', 'stickyMacAllowList', 'stickyMacAllowListLimit', 'stormControlEnabled', 'flexibleStackingEnabled', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "update", "body": payload } return action def cloneOrganizationSwitchDevices(self, organizationId: str, sourceSerial: str, targetSerials: list): """ **Clone port-level and some switch-level configuration settings from a source switch to one or more target switches** https://developer.cisco.com/meraki/api-v1/#!clone-organization-switch-devices - organizationId (string): (required) - sourceSerial (string): Serial number of the source switch (must be on a network not bound to a template) - targetSerials (array): Array of serial numbers of one or more target switches (must be on a network not bound to a template) """ kwargs = locals() metadata = { 'tags': ['switch', 'configure', 'devices'], 'operation': 'cloneOrganizationSwitchDevices' } resource = f'/organizations/{organizationId}/switch/devices/clone' body_params = ['sourceSerial', 'targetSerials', ] payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params} action = { "resource": resource, "operation": "create", "body": payload } return action
import configparser import logging import sys from pymongo import MongoClient config_path = 'config/settings.conf' config = configparser.ConfigParser() config.read(config_path) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class TradeAnalyzer: def __init__(self): self.mongo_client = MongoClient( f"mongodb://{config["mongodb"]["host"]}:{config["mongodb"]["port"]}/") self.trade_collection = mongo_client[ config['mongodb']['database']][config['mongodb']['collection']] if __name__ == '__main__': print(f"Selected collection \"{config["mongodb"]["collection"]}\" in database \"{config["mongodb"]["database"]}\" for analysis.\n") user_selection = input('Is this correct? [Y/n]\n') if user_selection.lower() == 'y' or user_selection == '': print('Trade collection confirmed. Beginning analysis.') elif user_selection.lower() == 'n': print('User cancelled analysis. Exiting.') sys.exit() else: print('Unrecognized input. Exiting.') sys.exit(1) analyze = TradeAnalyzer()
import configparser import logging import sys from pymongo import MongoClient config_path = 'config/settings.conf' config = configparser.ConfigParser() config.read(config_path) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class TradeAnalyzer: def __init__(self): self.mongo_client = MongoClient( f"mongodb://{config['mongodb']['host']}:{config['mongodb']['port']}/") self.trade_collection = mongo_client[ config['mongodb']['database']][config['mongodb']['collection']] if __name__ == '__main__': print(f"Selected collection \"{config['mongodb']['collection']}\" in database \"{config['mongodb']['database']}\" for analysis.\n") user_selection = input('Is this correct? [Y/n]\n') if user_selection.lower() == 'y' or user_selection == '': print('Trade collection confirmed. Beginning analysis.') elif user_selection.lower() == 'n': print('User cancelled analysis. Exiting.') sys.exit() else: print('Unrecognized input. Exiting.') sys.exit(1) analyze = TradeAnalyzer()
"""Definition of Snoop Task System. This is a simple set of wrappers around Celery functions to afford them stability, reproductability and result storage. Even while Celery has support for using "result backends" to store the task results, we didn't enjoy the fact that a power failure or unexpected server restart would wipe out our progress and be hard to predict. The solution is to mirror all information about running Tasks in a dedicated database, and use that as the source of thuth. We also gain something else by mirroring Tasks inside a database table: the ability to de-duplicate running them, through locking their correspondent rows when running (SQL `SELECT FOR UPDATE`). Another requirement for this system is the building of Directed Acyclic Graphs (DAGs) of Tasks. The edges of this graph should carry Task result data from parent task to child task. As far as alternatives go: Apache Airflow is too slow (takes a few seconds just to run a simple task), Spotify Luigi does all the scheduling in memory (and can't scale to our needs for persistent de-duplication), and other K8s-oriented container-native solutions were not investigated. But as a rule of thumb, if it can't run 1000-5000 idle (no-op) Tasks per minute per CPU, it's too slow for our use. """ import random from contextlib import contextmanager from io import StringIO import json import logging from time import time, sleep from datetime import timedelta from functools import wraps from django.conf import settings from django.db import transaction, DatabaseError from django.utils import timezone from . import collections from . import celery from . import models from ..profiler import profile from .utils import run_once from requests.exceptions import ConnectionError from snoop import tracing logger = logging.getLogger(__name__) task_map = {} ALWAYS_QUEUE_NOW = settings.ALWAYS_QUEUE_NOW class SnoopTaskError(Exception): """Thrown by Task when died and should set status = "error". This is be used from inside a Task function to mark unexpected or temporary errors. These tasks will be retried after a while until finished. """ def __init__(self, message, details): super().__init__(message) self.details = details class SnoopTaskBroken(Exception): """Thrown by Task when died and should set status = "broken". This is to be used from inside a Task function to mark permanent problems. """ def __init__(self, message, reason): super().__init__(message) self.reason = reason class MissingDependency(Exception): """Thrown by Task when it depends on another Task that is not finished. """ def __init__(self, name, task): self.name = name self.task = task class ExtraDependency(Exception): """Thrown by Task when it no longer depends on another Task it used to depend on. This happens when a File was not identified correctly and now is; different parts of the Task graph must run on it. """ def __init__(self, name): self.name = name def queue_task(task): """Queue given Task with Celery to run on a worker. If called from inside a transaction, queueing will be done after the transaction is finished succesfully. Args: task: task to be queued in Celery """ import_snoop_tasks() def send_to_celery(): """This does the actual queueing operation. This is wrapped in `transactions.on_commit` to avoid running it if wrapping transaction fails. """ col = collections.from_object(task) try: laterz_snoop_task.apply_async( (col.name, task.pk,), queue=col.queue_name, priority=task_map[task.func].priority, retry=False, ) logger.debug(f'queued task {task.func}(pk {task.pk})') except laterz_snoop_task.OperationalError as e: logger.error(f'failed to submit {task.func}(pk {task.pk}): {e}') transaction.on_commit(send_to_celery) def queue_next_tasks(task, reset=False): """Queues all Tasks that directly depend on this one. Args: task: will queue running all Tasks in `task.next_set` reset: if set, will set next Tasks status to "pending" before queueing it """ with tracing.span('queue_next_tasks'): for next_dependency in task.next_set.all(): next_task = next_dependency.next if reset: next_task.update( status=models.Task.STATUS_PENDING, error='', broken_reason='', log='', ) next_task.save() logger.info("Queueing %r after %r", next_task, task) queue_task(next_task) @run_once def import_snoop_tasks(): """Imports task functions from various modules. This is required to avoid import loop problems; it should be called just before queueing a Task in Celery. """ from . import filesystem # noqa from .analyzers import archives # noqa from .analyzers import text # noqa def is_completed(task): """Returns True if Task is in the "success" or "broken" states. Args: task: will check `task.status` for values listed above """ COMPLETED = [models.Task.STATUS_SUCCESS, models.Task.STATUS_BROKEN] return task.status in COMPLETED @contextmanager def snoop_task_log_handler(level=logging.DEBUG): """Context manager for a text log handler. This captures in memory the entire log of running its context. It's used to capture Task logs in the database. Args: level: log level, by default logging.DEBUG """ stream = StringIO() handler = logging.StreamHandler(stream) handler.setLevel(level) root_logger = logging.getLogger() root_logger.addHandler(handler) try: yield handler finally: handler.flush() root_logger.removeHandler(handler) @celery.app.task def laterz_snoop_task(col_name, task_pk, raise_exceptions=False): """Celery task used to run snoop Tasks without duplication. This function is using Django's `select_for_update` to ensure only one instance of a Task is running at one time. After running `select_for_update` to lock the row, this function will directly call into the main Task switch: `run_task`. Args: col_name: name of collection where Task is found task_pk: primary key of Task raise_exceptions: if set, will propagate any Exceptions after Task.status is set to "error" """ import_snoop_tasks() col = collections.ALL[col_name] with transaction.atomic(using=col.db_alias), col.set_current(): with snoop_task_log_handler() as handler: try: task = ( models.Task.objects .select_for_update(nowait=True) .get(pk=task_pk) ) except DatabaseError as e: logger.error("task %r already running, locked in the database: %s", task_pk, e) return run_task(task, handler, raise_exceptions) @profile() def run_task(task, log_handler, raise_exceptions=False): """Runs the main Task switch: get dependencies, run code, react to `SnoopTaskError`s, save state and logs, queue next tasks. Args: task: Task instance to run log_handler: instance of log handler to dump results raise_exceptions: if set, will propagate any Exceptions after Task.status is set to "error" """ with tracing.trace('run_task'): tracing.add_attribute('func', task.func) with tracing.span('check task'): if is_completed(task): logger.info("%r already completed", task) tracing.add_annotation('already completed') queue_next_tasks(task) return args = task.args if task.blob_arg: assert args[0] == task.blob_arg.pk args = [task.blob_arg] + args[1:] with tracing.span('check dependencies'): depends_on = {} all_prev_deps = list(task.prev_set.all()) if any(dep.prev.status == models.Task.STATUS_ERROR for dep in all_prev_deps): logger.info("%r has a dependency in the ERROR state.", task) task.update( status=models.Task.STATUS_BROKEN, error='', broken_reason='has a dependency in the ERROR state', log=log_handler.stream.getvalue(), ) task.save() return for dep in all_prev_deps: prev_task = dep.prev if not is_completed(prev_task): task.update( status=models.Task.STATUS_DEFERRED, error='', broken_reason='', log=log_handler.stream.getvalue(), ) task.save() logger.info("%r missing dependency %r", task, prev_task) tracing.add_annotation("%r missing dependency %r" % (task, prev_task)) queue_task(prev_task) return if prev_task.status == models.Task.STATUS_SUCCESS: prev_result = prev_task.result elif prev_task.status == models.Task.STATUS_BROKEN: prev_result = SnoopTaskBroken( prev_task.error, prev_task.broken_reason ) else: raise RuntimeError(f"Unexpected status {prev_task.status}") depends_on[dep.name] = prev_result with tracing.span('save state before run'): task.status = models.Task.STATUS_PENDING task.date_started = timezone.now() task.date_finished = None task.save() with tracing.span('run'): logger.info("Running %r", task) t0 = time() try: func = task_map[task.func] with tracing.span('call func'): with tracing.trace(name=task.func, service_name='func'): result = func(*args, **depends_on) tracing.add_annotation('success') if result is not None: assert isinstance(result, models.Blob) task.result = result except MissingDependency as dep: with tracing.span('missing dependency'): msg = '%r requests an extra dependency: %r [%.03f s]' % (task, dep, time() - t0) logger.info(msg) tracing.add_annotation(msg) task.update( status=models.Task.STATUS_DEFERRED, error='', broken_reason='', log=log_handler.stream.getvalue(), ) task.prev_set.get_or_create( prev=dep.task, name=dep.name, ) queue_task(task) except ExtraDependency as dep: with tracing.span('extra dependency'): msg = '%r requests to remove a dependency: %r [%.03f s]' % (task, dep, time() - t0) logger.info(msg) tracing.add_annotation(msg) task.prev_set.filter( name=dep.name, ).delete() task.update( status=models.Task.STATUS_PENDING, error='', broken_reason='', log=log_handler.stream.getvalue(), ) queue_task(task) except SnoopTaskBroken as e: task.update( status=models.Task.STATUS_BROKEN, error="{}: {}".format(e.reason, e.args[0]), broken_reason=e.reason, log=log_handler.stream.getvalue(), ) msg = '%r broken: %s [%.03f s]' % (task, task.broken_reason, time() - t0) logger.exception(msg) tracing.add_annotation(msg) except ConnectionError as e: tracing.add_annotation(repr(e)) logger.exception(repr(e)) task.update( status=models.Task.STATUS_DEFERRED, error=repr(e), broken_reason='', log=log_handler.stream.getvalue(), ) except Exception as e: if isinstance(e, SnoopTaskError): error = "{} ({})".format(e.args[0], e.details) else: error = repr(e) task.update( status=models.Task.STATUS_ERROR, error=error, broken_reason='', log=log_handler.stream.getvalue(), ) msg = '%r failed: %s [%.03f s]' % (task, task.error, time() - t0) tracing.add_annotation(msg) logger.exception(msg) if raise_exceptions: raise else: logger.info("%r succeeded [%.03f s]", task, time() - t0) task.update( status=models.Task.STATUS_SUCCESS, error='', broken_reason='', log=log_handler.stream.getvalue(), ) finally: with tracing.span('save state after run'): task.date_finished = timezone.now() task.save() if is_completed(task): queue_next_tasks(task, reset=True) def snoop_task(name, priority=5): """Decorator marking a snoop Task function. Args: name: qualified name of the function, not required to be equal to Python module or function name (but recommended) priority: int in range [1,9] inclusive, higher is more urgent. Passed to celery when queueing. """ def decorator(func): def laterz(*args, depends_on={}, retry=False, queue_now=True, delete_extra_deps=False): """Actual function doing dependency checking and queueing. Args: args: positional function arguments depends_on: dict with strings mapping to Task instances that this one depends on (and uses their results as keyword arguments) when calling the wrapped function. retry: if set, will reset this function even if it's been finished. Otherwise, this doesn't re-trigger a finished function. queue_now: If set, will queue this task immediately (the default). Otherwise, tasks will not be left on the queue, and they'll be picked up by the periodic task `run_dispatcher()` in this module. delete_extra_deps: If set, will remove any dependencies that are not listed in `depends_on`. Used for fixing dependency graph after its structure or the data evaluation changed. """ if args and isinstance(args[0], models.Blob): blob_arg = args[0] args = (blob_arg.pk,) + args[1:] else: blob_arg = None task, created = models.Task.objects.get_or_create( func=name, args=args, blob_arg=blob_arg, ) if depends_on: for dep_name, dep in depends_on.items(): _, created = task.prev_set.get_or_create( prev=dep, name=dep_name, ) if created: retry = True if delete_extra_deps: task.prev_set.exclude(name__in=depends_on.keys()).delete() if task.date_finished: if retry: retry_task(task) return task if queue_now or ALWAYS_QUEUE_NOW: queue_task(task) return task def delete(*args): """Delete the Task instance with given positional arguments. The Task arguments (the dependencies) are not used as primary keys for the Tasks, so they can't be used to filter for the Task to delete. Args: args: the positional arguemts used to fetch the Task. """ if args and isinstance(args[0], models.Blob): blob_arg = args[0] args = (blob_arg.pk,) + args[1:] else: blob_arg = None task = models.Task.objects.get( func=name, args=args, blob_arg=blob_arg, ) task.delete() func.laterz = laterz func.delete = delete func.priority = priority task_map[name] = func return func return decorator def dispatch_tasks(status): """Dispatches (queues) a limited number of Task instances of each type. Requires a collection to be selected. Queues one batch of `settings.DISPATCH_QUEUE_LIMIT` Tasks for every function type. The function types are shuffled before queuing, in an attempt to equalize the processing cycles for different collections running at the same time. This is not optional since the message queue has to rearrange these in priority order, with only 10 priority levels (and RabbitMQ is very optimized for this task), there isn't considerable overhead here. Args: status: the status used to filter Tasks to dispatch Returns: bool: True if any tasks have been queued, False if none matching status have been found in current collection. """ all_functions = [x['func'] for x in models.Task.objects.values('func').distinct()] random.shuffle(all_functions) found_something = False for func in all_functions: task_query = ( models.Task.objects .filter(status=status, func=func) .order_by('-date_modified') # newest pending tasks first )[:settings.DISPATCH_QUEUE_LIMIT] task_count = task_query.count() if not task_count: logger.info(f'collection "{collections.current().name}": No {status} {func} tasks to dispatch') # noqa: E501 continue logger.info(f'collection "{collections.current().name}": Dispatching {task_count} {status} {func} tasks') # noqa: E501 for task in task_query.iterator(): queue_task(task) found_something = True return found_something def retry_task(task, fg=False): """Resets task status, logs and error messages to their blank value, then re-queues the Task. """ task.update( status=models.Task.STATUS_PENDING, error='', broken_reason='', log='', ) logger.info("Retrying %r", task) task.save() if fg: col = collections.from_object(task) laterz_snoop_task(col.name, task.pk, raise_exceptions=True) else: queue_task(task) def retry_tasks(queryset): """Efficient re-queueing of an entire QuerySet pointing to Tasks. This is using bulk_update to reset the status, logs and error messages on the table; then only queues the first `settings.DISPATCH_QUEUE_LIMIT` tasks.""" logger.info('Retrying %s tasks...', queryset.count()) all_tasks = queryset.all() first_batch = [] for i in range(0, len(all_tasks), settings.DISPATCH_QUEUE_LIMIT): batch = all_tasks[i:i + settings.DISPATCH_QUEUE_LIMIT] now = timezone.now() fields = ['status', 'error', 'broken_reason', 'log', 'date_modified'] for task in batch: task.status = models.Task.STATUS_PENDING task.error = '' task.broken_reason = '' task.log = '' task.date_modified = now models.Task.objects.bulk_update(batch, fields, batch_size=2000) if not first_batch: first_batch = batch[:5000] logger.info('Queueing first %s tasks...', len(first_batch)) for task in first_batch: queue_task(task) progress = int(100.0 * (i / len(all_tasks))) logger.info('%s%% done' % (progress,)) logger.info('100% done submitting tasks.') def require_dependency(name, depends_on, callback): """Dynamically adds a dependency to running task. Use this when a Task requires the result of another Task, but this is not known when queueing it. Args: name: name of dependency depends_on: current kwargs dict of function. If the name given is missing from this dict, then execution will be aborted (by throwing a MissingDependency error), and this Task will have its status set to "deferred". When the required task finishes running, this one will be re-queued. callback: function that returns Task instance. Will only be called if the dependency was not found. """ if name in depends_on: result = depends_on[name] if isinstance(result, Exception): raise result return result task = callback() raise MissingDependency(name, task) def remove_dependency(name, depends_on): """Dynamically removes a dependency from running task. This stops execution, removes the extra dependency in the Task loop and eventually executes this task again. """ if name not in depends_on: return raise ExtraDependency(name) @snoop_task('do_nothing') def do_nothing(name): """No-op task, here for demonstration purposes. """ pass def returns_json_blob(func): """Function decorator that returns a Blob with the JSON-encoded return value of the wrapped function. Used in various Task functions to return results in JSON format, while also respecting the fact that Task results are always Blobs. Warning: This function dumps the whole JSON at once, from memory, so this may have problems with very large JSON result sizes (>1GB) or dynamically generated results (from a generator). """ @wraps(func) def wrapper(*args, **kwargs): rv = func(*args, **kwargs) data = json.dumps(rv, indent=2).encode('utf8') with models.Blob.create() as output: output.write(data) return output.blob return wrapper def dispatch_walk_tasks(): """Trigger processing of a collection, starting with its root directory. """ from .filesystem import walk root = models.Directory.root() assert root, "root document not created" walk.laterz(root.pk) def save_collection_stats(): """Run the expensive computations to get collection stats, then save result in database. """ from snoop.data.admin import get_stats t0 = time() s, _ = models.Statistics.objects.get_or_create(key='stats') stats = get_stats() for row in stats['task_matrix']: for stat in row[1]: row[1][stat] = str(row[1][stat]) s.value = stats s.save() logger.info('stats for collection {} saved in {} seconds'.format(collections.current().name, time() - t0)) # noqa: E501 def get_rabbitmq_queue_length(q): """Fetch queue length from RabbitMQ for a given queue. Used periodically to decide if we want to queue more functions or not. Uses the Management HTTP API of RabbitMQ, since the Celery client doesn not have access to these counts. """ from pyrabbit.api import Client cl = Client(settings.SNOOP_RABBITMQ_HTTP_URL, 'guest', 'guest') return cl.get_queue_depth('/', q) def single_task_running(key): """Queries both Celery and RabbitMQ to find out if the queue is completely idle. Used by all periodic tasks to make sure only one instance is running at any given time. Tasks earlier in the queue will exit to make way for the ones that are later in the queue, to make sure the queue will never grow unbounded in size if the Task takes more time to run than its execution interval. """ def count_tasks(method, routing_key): count = 0 inspector = celery.app.control.inspect() task_list_map = getattr(inspector, method)() if task_list_map is None: logger.warning('no workers present!') return 0 for tasks in task_list_map.values(): for task in tasks: task_key = task['delivery_info']['routing_key'] if task_key != routing_key: continue count += 1 logger.info(f'counting {method} task: {str(task)}') return count if get_rabbitmq_queue_length(key) > 0: return False return 1 >= count_tasks('active', routing_key=key) and \ 0 == count_tasks('scheduled', routing_key=key) and \ 0 == count_tasks('reserved', routing_key=key) @celery.app.task def save_stats(): """Periodic Celery task used to save stats for all collections. """ if not single_task_running('save_stats'): logger.warning('save_stats function already running, exiting') return for collection in collections.ALL.values(): with collection.set_current(): try: if collection.process or \ not models.Statistics.objects.filter(key='stats').exists(): save_collection_stats() except Exception as e: logger.exception(e) # Kill a little bit of time, in case there are a lot of older # messages queued up, they have time to fail in the above # check. sleep(3) @celery.app.task def run_dispatcher(): """Periodic Celery task used to queue next batches of Tasks for each collection. We limit the total size of each queue on the message queue, since too many messages on the queue at the same time creates performance issues (because the message queue will need to use Disk instead of storing everything in memory, thus becoming very slow). """ if not single_task_running('run_dispatcher'): logger.warning('run_dispatcher function already running, exiting') return collection_list = list(collections.ALL.values()) random.shuffle(collection_list) for collection in collection_list: logger.info(f'{'=' * 10} collection "{collection.name}' {'=' * 10}') try: dispatch_for(collection) except Exception as e: logger.exception(e) sleep(3) @celery.app.task def update_all_tags(): """Periodic Celery task used to re-index documents with changed Tags. This task ensures tag editing conflicts (multiple users editing tags for the same document at the same time) are fixed in a short time after indexing. """ # circular import from . import digests if not single_task_running('update_all_tags'): logger.warning('run_all_tags function already running, exiting') return collection_list = list(collections.ALL.values()) random.shuffle(collection_list) for collection in collection_list: with collection.set_current(): logger.info('collection "%r": updating tags', collection) digests.update_all_tags() def dispatch_for(collection): """Queue the next batches of Tasks for a given collection. This is used to periodically look for new Tasks that must be executed. This queues: "pending" and "deferred" tasks left over from previous batches; then adds some Directories to revisit if the collection "sync" configuration is set. Finally, tasks that finished with a temporary error more than a predefined number of days ago are also re-queued with the intent of them succeeding. The function tends to exit early if any Tasks were found to be queued, as to make sure the Tasks run in their natural order (and we're running dependencies before the tasks that require them). The tasks are queued by newest first, to make sure the tasks left over from previous batches are being finished first (again, to keep the natural order between batches). """ if not collection.process: logger.info(f'dispatch: skipping "{collection}", configured with "process = False"') return queue_len = get_rabbitmq_queue_length(collection.queue_name) if queue_len > 0: logger.info(f'dispatch: skipping "{collection}", already has {queue_len} queued tasks') return logger.info('Dispatching for %r', collection) from .ocr import dispatch_ocr_tasks with collection.set_current(): if dispatch_tasks(models.Task.STATUS_PENDING): logger.info('%r found PENDING tasks, exiting...', collection) return True if dispatch_tasks(models.Task.STATUS_DEFERRED): logger.info('%r found DEFERRED tasks, exiting...', collection) return True count_before = models.Task.objects.count() dispatch_walk_tasks() dispatch_ocr_tasks() count_after = models.Task.objects.count() if count_before != count_after: logger.info('%r initial dispatch added new tasks, exiting...', collection) return True if collection.sync: logger.info("sync: retrying all walk tasks") # retry up oldest non-pending walk tasks that are older than 1 min retry_tasks( models.Task.objects .filter(func__in=['filesystem.walk', 'ocr.walk_source']) .filter(date_modified__lt=timezone.now() - timedelta(minutes=1)) .exclude(status=models.Task.STATUS_PENDING) .order_by('date_modified')[:settings.SYNC_RETRY_LIMIT] ) # retry old errors, don't exit before running sync too error_date = timezone.now() - timedelta(days=settings.TASK_RETRY_AFTER_DAYS) old_error_qs = ( models.Task.objects .filter(status__in=[models.Task.STATUS_BROKEN, models.Task.STATUS_ERROR]) .filter(date_modified__lt=error_date) .order_by('date_modified')[:settings.SYNC_RETRY_LIMIT] ) if old_error_qs.exists(): logger.info(f'{collection} found {old_error_qs.count()} ERROR|BROKEN tasks to retry') retry_tasks(old_error_qs) logger.info(f'dispatch for collection "{collection.name}" done\n')
"""Definition of Snoop Task System. This is a simple set of wrappers around Celery functions to afford them stability, reproductability and result storage. Even while Celery has support for using "result backends" to store the task results, we didn't enjoy the fact that a power failure or unexpected server restart would wipe out our progress and be hard to predict. The solution is to mirror all information about running Tasks in a dedicated database, and use that as the source of thuth. We also gain something else by mirroring Tasks inside a database table: the ability to de-duplicate running them, through locking their correspondent rows when running (SQL `SELECT FOR UPDATE`). Another requirement for this system is the building of Directed Acyclic Graphs (DAGs) of Tasks. The edges of this graph should carry Task result data from parent task to child task. As far as alternatives go: Apache Airflow is too slow (takes a few seconds just to run a simple task), Spotify Luigi does all the scheduling in memory (and can't scale to our needs for persistent de-duplication), and other K8s-oriented container-native solutions were not investigated. But as a rule of thumb, if it can't run 1000-5000 idle (no-op) Tasks per minute per CPU, it's too slow for our use. """ import random from contextlib import contextmanager from io import StringIO import json import logging from time import time, sleep from datetime import timedelta from functools import wraps from django.conf import settings from django.db import transaction, DatabaseError from django.utils import timezone from . import collections from . import celery from . import models from ..profiler import profile from .utils import run_once from requests.exceptions import ConnectionError from snoop import tracing logger = logging.getLogger(__name__) task_map = {} ALWAYS_QUEUE_NOW = settings.ALWAYS_QUEUE_NOW class SnoopTaskError(Exception): """Thrown by Task when died and should set status = "error". This is be used from inside a Task function to mark unexpected or temporary errors. These tasks will be retried after a while until finished. """ def __init__(self, message, details): super().__init__(message) self.details = details class SnoopTaskBroken(Exception): """Thrown by Task when died and should set status = "broken". This is to be used from inside a Task function to mark permanent problems. """ def __init__(self, message, reason): super().__init__(message) self.reason = reason class MissingDependency(Exception): """Thrown by Task when it depends on another Task that is not finished. """ def __init__(self, name, task): self.name = name self.task = task class ExtraDependency(Exception): """Thrown by Task when it no longer depends on another Task it used to depend on. This happens when a File was not identified correctly and now is; different parts of the Task graph must run on it. """ def __init__(self, name): self.name = name def queue_task(task): """Queue given Task with Celery to run on a worker. If called from inside a transaction, queueing will be done after the transaction is finished succesfully. Args: task: task to be queued in Celery """ import_snoop_tasks() def send_to_celery(): """This does the actual queueing operation. This is wrapped in `transactions.on_commit` to avoid running it if wrapping transaction fails. """ col = collections.from_object(task) try: laterz_snoop_task.apply_async( (col.name, task.pk,), queue=col.queue_name, priority=task_map[task.func].priority, retry=False, ) logger.debug(f'queued task {task.func}(pk {task.pk})') except laterz_snoop_task.OperationalError as e: logger.error(f'failed to submit {task.func}(pk {task.pk}): {e}') transaction.on_commit(send_to_celery) def queue_next_tasks(task, reset=False): """Queues all Tasks that directly depend on this one. Args: task: will queue running all Tasks in `task.next_set` reset: if set, will set next Tasks status to "pending" before queueing it """ with tracing.span('queue_next_tasks'): for next_dependency in task.next_set.all(): next_task = next_dependency.next if reset: next_task.update( status=models.Task.STATUS_PENDING, error='', broken_reason='', log='', ) next_task.save() logger.info("Queueing %r after %r", next_task, task) queue_task(next_task) @run_once def import_snoop_tasks(): """Imports task functions from various modules. This is required to avoid import loop problems; it should be called just before queueing a Task in Celery. """ from . import filesystem # noqa from .analyzers import archives # noqa from .analyzers import text # noqa def is_completed(task): """Returns True if Task is in the "success" or "broken" states. Args: task: will check `task.status` for values listed above """ COMPLETED = [models.Task.STATUS_SUCCESS, models.Task.STATUS_BROKEN] return task.status in COMPLETED @contextmanager def snoop_task_log_handler(level=logging.DEBUG): """Context manager for a text log handler. This captures in memory the entire log of running its context. It's used to capture Task logs in the database. Args: level: log level, by default logging.DEBUG """ stream = StringIO() handler = logging.StreamHandler(stream) handler.setLevel(level) root_logger = logging.getLogger() root_logger.addHandler(handler) try: yield handler finally: handler.flush() root_logger.removeHandler(handler) @celery.app.task def laterz_snoop_task(col_name, task_pk, raise_exceptions=False): """Celery task used to run snoop Tasks without duplication. This function is using Django's `select_for_update` to ensure only one instance of a Task is running at one time. After running `select_for_update` to lock the row, this function will directly call into the main Task switch: `run_task`. Args: col_name: name of collection where Task is found task_pk: primary key of Task raise_exceptions: if set, will propagate any Exceptions after Task.status is set to "error" """ import_snoop_tasks() col = collections.ALL[col_name] with transaction.atomic(using=col.db_alias), col.set_current(): with snoop_task_log_handler() as handler: try: task = ( models.Task.objects .select_for_update(nowait=True) .get(pk=task_pk) ) except DatabaseError as e: logger.error("task %r already running, locked in the database: %s", task_pk, e) return run_task(task, handler, raise_exceptions) @profile() def run_task(task, log_handler, raise_exceptions=False): """Runs the main Task switch: get dependencies, run code, react to `SnoopTaskError`s, save state and logs, queue next tasks. Args: task: Task instance to run log_handler: instance of log handler to dump results raise_exceptions: if set, will propagate any Exceptions after Task.status is set to "error" """ with tracing.trace('run_task'): tracing.add_attribute('func', task.func) with tracing.span('check task'): if is_completed(task): logger.info("%r already completed", task) tracing.add_annotation('already completed') queue_next_tasks(task) return args = task.args if task.blob_arg: assert args[0] == task.blob_arg.pk args = [task.blob_arg] + args[1:] with tracing.span('check dependencies'): depends_on = {} all_prev_deps = list(task.prev_set.all()) if any(dep.prev.status == models.Task.STATUS_ERROR for dep in all_prev_deps): logger.info("%r has a dependency in the ERROR state.", task) task.update( status=models.Task.STATUS_BROKEN, error='', broken_reason='has a dependency in the ERROR state', log=log_handler.stream.getvalue(), ) task.save() return for dep in all_prev_deps: prev_task = dep.prev if not is_completed(prev_task): task.update( status=models.Task.STATUS_DEFERRED, error='', broken_reason='', log=log_handler.stream.getvalue(), ) task.save() logger.info("%r missing dependency %r", task, prev_task) tracing.add_annotation("%r missing dependency %r" % (task, prev_task)) queue_task(prev_task) return if prev_task.status == models.Task.STATUS_SUCCESS: prev_result = prev_task.result elif prev_task.status == models.Task.STATUS_BROKEN: prev_result = SnoopTaskBroken( prev_task.error, prev_task.broken_reason ) else: raise RuntimeError(f"Unexpected status {prev_task.status}") depends_on[dep.name] = prev_result with tracing.span('save state before run'): task.status = models.Task.STATUS_PENDING task.date_started = timezone.now() task.date_finished = None task.save() with tracing.span('run'): logger.info("Running %r", task) t0 = time() try: func = task_map[task.func] with tracing.span('call func'): with tracing.trace(name=task.func, service_name='func'): result = func(*args, **depends_on) tracing.add_annotation('success') if result is not None: assert isinstance(result, models.Blob) task.result = result except MissingDependency as dep: with tracing.span('missing dependency'): msg = '%r requests an extra dependency: %r [%.03f s]' % (task, dep, time() - t0) logger.info(msg) tracing.add_annotation(msg) task.update( status=models.Task.STATUS_DEFERRED, error='', broken_reason='', log=log_handler.stream.getvalue(), ) task.prev_set.get_or_create( prev=dep.task, name=dep.name, ) queue_task(task) except ExtraDependency as dep: with tracing.span('extra dependency'): msg = '%r requests to remove a dependency: %r [%.03f s]' % (task, dep, time() - t0) logger.info(msg) tracing.add_annotation(msg) task.prev_set.filter( name=dep.name, ).delete() task.update( status=models.Task.STATUS_PENDING, error='', broken_reason='', log=log_handler.stream.getvalue(), ) queue_task(task) except SnoopTaskBroken as e: task.update( status=models.Task.STATUS_BROKEN, error="{}: {}".format(e.reason, e.args[0]), broken_reason=e.reason, log=log_handler.stream.getvalue(), ) msg = '%r broken: %s [%.03f s]' % (task, task.broken_reason, time() - t0) logger.exception(msg) tracing.add_annotation(msg) except ConnectionError as e: tracing.add_annotation(repr(e)) logger.exception(repr(e)) task.update( status=models.Task.STATUS_DEFERRED, error=repr(e), broken_reason='', log=log_handler.stream.getvalue(), ) except Exception as e: if isinstance(e, SnoopTaskError): error = "{} ({})".format(e.args[0], e.details) else: error = repr(e) task.update( status=models.Task.STATUS_ERROR, error=error, broken_reason='', log=log_handler.stream.getvalue(), ) msg = '%r failed: %s [%.03f s]' % (task, task.error, time() - t0) tracing.add_annotation(msg) logger.exception(msg) if raise_exceptions: raise else: logger.info("%r succeeded [%.03f s]", task, time() - t0) task.update( status=models.Task.STATUS_SUCCESS, error='', broken_reason='', log=log_handler.stream.getvalue(), ) finally: with tracing.span('save state after run'): task.date_finished = timezone.now() task.save() if is_completed(task): queue_next_tasks(task, reset=True) def snoop_task(name, priority=5): """Decorator marking a snoop Task function. Args: name: qualified name of the function, not required to be equal to Python module or function name (but recommended) priority: int in range [1,9] inclusive, higher is more urgent. Passed to celery when queueing. """ def decorator(func): def laterz(*args, depends_on={}, retry=False, queue_now=True, delete_extra_deps=False): """Actual function doing dependency checking and queueing. Args: args: positional function arguments depends_on: dict with strings mapping to Task instances that this one depends on (and uses their results as keyword arguments) when calling the wrapped function. retry: if set, will reset this function even if it's been finished. Otherwise, this doesn't re-trigger a finished function. queue_now: If set, will queue this task immediately (the default). Otherwise, tasks will not be left on the queue, and they'll be picked up by the periodic task `run_dispatcher()` in this module. delete_extra_deps: If set, will remove any dependencies that are not listed in `depends_on`. Used for fixing dependency graph after its structure or the data evaluation changed. """ if args and isinstance(args[0], models.Blob): blob_arg = args[0] args = (blob_arg.pk,) + args[1:] else: blob_arg = None task, created = models.Task.objects.get_or_create( func=name, args=args, blob_arg=blob_arg, ) if depends_on: for dep_name, dep in depends_on.items(): _, created = task.prev_set.get_or_create( prev=dep, name=dep_name, ) if created: retry = True if delete_extra_deps: task.prev_set.exclude(name__in=depends_on.keys()).delete() if task.date_finished: if retry: retry_task(task) return task if queue_now or ALWAYS_QUEUE_NOW: queue_task(task) return task def delete(*args): """Delete the Task instance with given positional arguments. The Task arguments (the dependencies) are not used as primary keys for the Tasks, so they can't be used to filter for the Task to delete. Args: args: the positional arguemts used to fetch the Task. """ if args and isinstance(args[0], models.Blob): blob_arg = args[0] args = (blob_arg.pk,) + args[1:] else: blob_arg = None task = models.Task.objects.get( func=name, args=args, blob_arg=blob_arg, ) task.delete() func.laterz = laterz func.delete = delete func.priority = priority task_map[name] = func return func return decorator def dispatch_tasks(status): """Dispatches (queues) a limited number of Task instances of each type. Requires a collection to be selected. Queues one batch of `settings.DISPATCH_QUEUE_LIMIT` Tasks for every function type. The function types are shuffled before queuing, in an attempt to equalize the processing cycles for different collections running at the same time. This is not optional since the message queue has to rearrange these in priority order, with only 10 priority levels (and RabbitMQ is very optimized for this task), there isn't considerable overhead here. Args: status: the status used to filter Tasks to dispatch Returns: bool: True if any tasks have been queued, False if none matching status have been found in current collection. """ all_functions = [x['func'] for x in models.Task.objects.values('func').distinct()] random.shuffle(all_functions) found_something = False for func in all_functions: task_query = ( models.Task.objects .filter(status=status, func=func) .order_by('-date_modified') # newest pending tasks first )[:settings.DISPATCH_QUEUE_LIMIT] task_count = task_query.count() if not task_count: logger.info(f'collection "{collections.current().name}": No {status} {func} tasks to dispatch') # noqa: E501 continue logger.info(f'collection "{collections.current().name}": Dispatching {task_count} {status} {func} tasks') # noqa: E501 for task in task_query.iterator(): queue_task(task) found_something = True return found_something def retry_task(task, fg=False): """Resets task status, logs and error messages to their blank value, then re-queues the Task. """ task.update( status=models.Task.STATUS_PENDING, error='', broken_reason='', log='', ) logger.info("Retrying %r", task) task.save() if fg: col = collections.from_object(task) laterz_snoop_task(col.name, task.pk, raise_exceptions=True) else: queue_task(task) def retry_tasks(queryset): """Efficient re-queueing of an entire QuerySet pointing to Tasks. This is using bulk_update to reset the status, logs and error messages on the table; then only queues the first `settings.DISPATCH_QUEUE_LIMIT` tasks.""" logger.info('Retrying %s tasks...', queryset.count()) all_tasks = queryset.all() first_batch = [] for i in range(0, len(all_tasks), settings.DISPATCH_QUEUE_LIMIT): batch = all_tasks[i:i + settings.DISPATCH_QUEUE_LIMIT] now = timezone.now() fields = ['status', 'error', 'broken_reason', 'log', 'date_modified'] for task in batch: task.status = models.Task.STATUS_PENDING task.error = '' task.broken_reason = '' task.log = '' task.date_modified = now models.Task.objects.bulk_update(batch, fields, batch_size=2000) if not first_batch: first_batch = batch[:5000] logger.info('Queueing first %s tasks...', len(first_batch)) for task in first_batch: queue_task(task) progress = int(100.0 * (i / len(all_tasks))) logger.info('%s%% done' % (progress,)) logger.info('100% done submitting tasks.') def require_dependency(name, depends_on, callback): """Dynamically adds a dependency to running task. Use this when a Task requires the result of another Task, but this is not known when queueing it. Args: name: name of dependency depends_on: current kwargs dict of function. If the name given is missing from this dict, then execution will be aborted (by throwing a MissingDependency error), and this Task will have its status set to "deferred". When the required task finishes running, this one will be re-queued. callback: function that returns Task instance. Will only be called if the dependency was not found. """ if name in depends_on: result = depends_on[name] if isinstance(result, Exception): raise result return result task = callback() raise MissingDependency(name, task) def remove_dependency(name, depends_on): """Dynamically removes a dependency from running task. This stops execution, removes the extra dependency in the Task loop and eventually executes this task again. """ if name not in depends_on: return raise ExtraDependency(name) @snoop_task('do_nothing') def do_nothing(name): """No-op task, here for demonstration purposes. """ pass def returns_json_blob(func): """Function decorator that returns a Blob with the JSON-encoded return value of the wrapped function. Used in various Task functions to return results in JSON format, while also respecting the fact that Task results are always Blobs. Warning: This function dumps the whole JSON at once, from memory, so this may have problems with very large JSON result sizes (>1GB) or dynamically generated results (from a generator). """ @wraps(func) def wrapper(*args, **kwargs): rv = func(*args, **kwargs) data = json.dumps(rv, indent=2).encode('utf8') with models.Blob.create() as output: output.write(data) return output.blob return wrapper def dispatch_walk_tasks(): """Trigger processing of a collection, starting with its root directory. """ from .filesystem import walk root = models.Directory.root() assert root, "root document not created" walk.laterz(root.pk) def save_collection_stats(): """Run the expensive computations to get collection stats, then save result in database. """ from snoop.data.admin import get_stats t0 = time() s, _ = models.Statistics.objects.get_or_create(key='stats') stats = get_stats() for row in stats['task_matrix']: for stat in row[1]: row[1][stat] = str(row[1][stat]) s.value = stats s.save() logger.info('stats for collection {} saved in {} seconds'.format(collections.current().name, time() - t0)) # noqa: E501 def get_rabbitmq_queue_length(q): """Fetch queue length from RabbitMQ for a given queue. Used periodically to decide if we want to queue more functions or not. Uses the Management HTTP API of RabbitMQ, since the Celery client doesn not have access to these counts. """ from pyrabbit.api import Client cl = Client(settings.SNOOP_RABBITMQ_HTTP_URL, 'guest', 'guest') return cl.get_queue_depth('/', q) def single_task_running(key): """Queries both Celery and RabbitMQ to find out if the queue is completely idle. Used by all periodic tasks to make sure only one instance is running at any given time. Tasks earlier in the queue will exit to make way for the ones that are later in the queue, to make sure the queue will never grow unbounded in size if the Task takes more time to run than its execution interval. """ def count_tasks(method, routing_key): count = 0 inspector = celery.app.control.inspect() task_list_map = getattr(inspector, method)() if task_list_map is None: logger.warning('no workers present!') return 0 for tasks in task_list_map.values(): for task in tasks: task_key = task['delivery_info']['routing_key'] if task_key != routing_key: continue count += 1 logger.info(f'counting {method} task: {str(task)}') return count if get_rabbitmq_queue_length(key) > 0: return False return 1 >= count_tasks('active', routing_key=key) and \ 0 == count_tasks('scheduled', routing_key=key) and \ 0 == count_tasks('reserved', routing_key=key) @celery.app.task def save_stats(): """Periodic Celery task used to save stats for all collections. """ if not single_task_running('save_stats'): logger.warning('save_stats function already running, exiting') return for collection in collections.ALL.values(): with collection.set_current(): try: if collection.process or \ not models.Statistics.objects.filter(key='stats').exists(): save_collection_stats() except Exception as e: logger.exception(e) # Kill a little bit of time, in case there are a lot of older # messages queued up, they have time to fail in the above # check. sleep(3) @celery.app.task def run_dispatcher(): """Periodic Celery task used to queue next batches of Tasks for each collection. We limit the total size of each queue on the message queue, since too many messages on the queue at the same time creates performance issues (because the message queue will need to use Disk instead of storing everything in memory, thus becoming very slow). """ if not single_task_running('run_dispatcher'): logger.warning('run_dispatcher function already running, exiting') return collection_list = list(collections.ALL.values()) random.shuffle(collection_list) for collection in collection_list: logger.info(f'{"=" * 10} collection "{collection.name}" {"=" * 10}') try: dispatch_for(collection) except Exception as e: logger.exception(e) sleep(3) @celery.app.task def update_all_tags(): """Periodic Celery task used to re-index documents with changed Tags. This task ensures tag editing conflicts (multiple users editing tags for the same document at the same time) are fixed in a short time after indexing. """ # circular import from . import digests if not single_task_running('update_all_tags'): logger.warning('run_all_tags function already running, exiting') return collection_list = list(collections.ALL.values()) random.shuffle(collection_list) for collection in collection_list: with collection.set_current(): logger.info('collection "%r": updating tags', collection) digests.update_all_tags() def dispatch_for(collection): """Queue the next batches of Tasks for a given collection. This is used to periodically look for new Tasks that must be executed. This queues: "pending" and "deferred" tasks left over from previous batches; then adds some Directories to revisit if the collection "sync" configuration is set. Finally, tasks that finished with a temporary error more than a predefined number of days ago are also re-queued with the intent of them succeeding. The function tends to exit early if any Tasks were found to be queued, as to make sure the Tasks run in their natural order (and we're running dependencies before the tasks that require them). The tasks are queued by newest first, to make sure the tasks left over from previous batches are being finished first (again, to keep the natural order between batches). """ if not collection.process: logger.info(f'dispatch: skipping "{collection}", configured with "process = False"') return queue_len = get_rabbitmq_queue_length(collection.queue_name) if queue_len > 0: logger.info(f'dispatch: skipping "{collection}", already has {queue_len} queued tasks') return logger.info('Dispatching for %r', collection) from .ocr import dispatch_ocr_tasks with collection.set_current(): if dispatch_tasks(models.Task.STATUS_PENDING): logger.info('%r found PENDING tasks, exiting...', collection) return True if dispatch_tasks(models.Task.STATUS_DEFERRED): logger.info('%r found DEFERRED tasks, exiting...', collection) return True count_before = models.Task.objects.count() dispatch_walk_tasks() dispatch_ocr_tasks() count_after = models.Task.objects.count() if count_before != count_after: logger.info('%r initial dispatch added new tasks, exiting...', collection) return True if collection.sync: logger.info("sync: retrying all walk tasks") # retry up oldest non-pending walk tasks that are older than 1 min retry_tasks( models.Task.objects .filter(func__in=['filesystem.walk', 'ocr.walk_source']) .filter(date_modified__lt=timezone.now() - timedelta(minutes=1)) .exclude(status=models.Task.STATUS_PENDING) .order_by('date_modified')[:settings.SYNC_RETRY_LIMIT] ) # retry old errors, don't exit before running sync too error_date = timezone.now() - timedelta(days=settings.TASK_RETRY_AFTER_DAYS) old_error_qs = ( models.Task.objects .filter(status__in=[models.Task.STATUS_BROKEN, models.Task.STATUS_ERROR]) .filter(date_modified__lt=error_date) .order_by('date_modified')[:settings.SYNC_RETRY_LIMIT] ) if old_error_qs.exists(): logger.info(f'{collection} found {old_error_qs.count()} ERROR|BROKEN tasks to retry') retry_tasks(old_error_qs) logger.info(f'dispatch for collection "{collection.name}" done\n')
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/13_learner.ipynb (unless otherwise specified). __all__ = ['CancelFitException', 'CancelEpochException', 'CancelTrainException', 'CancelValidException', 'CancelBatchException', 'Callback', 'TrainEvalCallback', 'GatherPredsCallback', 'event', 'replacing_yield', 'mk_metric', 'save_model', 'load_model', 'Learner', 'VerboseCallback', 'Metric', 'AvgMetric', 'AvgLoss', 'AvgSmoothLoss', 'Recorder'] #Cell from .test import * from .data.all import * from .optimizer import * #Cell class Callback(GetAttr): "Basic class handling tweaks of the training loop by changing a `Learner` in various events" _default,learn,run = 'learn',None,True def __repr__(self): return type(self).__name__ def __call__(self, event_name): "Call `self.{event_name}` if it's defined" if self.run: getattr(self, event_name, noop)() @property def name(self): "Name of the `Callback`, camel-cased and with '*Callback*' removed" return class2attr(self, 'Callback') #Cell class TrainEvalCallback(Callback): "`Callback` that tracks the number of iterations done and properly sets training/eval mode" def begin_fit(self): "Set the iter and epoch counters to 0, put the model and the right device" self.learn.train_iter,self.learn.pct_train = 0,0. self.model.to(self.dbunch.device) def after_batch(self): "Update the iter counter (in training mode)" if not self.training: return self.learn.pct_train += 1./(self.n_iter*self.n_epoch) self.learn.train_iter += 1 def begin_train(self): "Set the model in training mode" self.learn.pct_train=self.epoch/self.n_epoch self.model.train() self.learn.training=True def begin_validate(self): "Set the model in validation mode" self.model.eval() self.learn.training=False #Cell #TODO: save_targs and save_preds only handle preds/targets that have one tensor, not tuples of tensors. class GatherPredsCallback(Callback): "`Callback` that saves the predictions and targets, optionally `with_loss`" def __init__(self, with_input=False, with_loss=False, save_preds=None, save_targs=None): store_attr(self, "with_input,with_loss,save_preds,save_targs") def begin_batch(self): if self.with_input: self.inputs.append((to_detach(self.xb))) def begin_validate(self): "Initialize containers" self.preds,self.targets = [],[] if self.with_input: self.inputs = [] if self.with_loss: self.losses = [] def after_batch(self): "Save predictions, targets and potentially losses" preds,targs = to_detach(self.pred),to_detach(self.yb) if self.save_preds is None: self.preds.append(preds) else: (self.save_preds/str(self.iter)).save_array(preds) if self.save_targs is None: self.targets.append(targs) else: (self.save_targs/str(self.iter)).save_array(targs[0]) if self.with_loss: bs = find_bs(self.yb) loss = self.loss if self.loss.numel() == bs else self.loss.view(bs,-1).mean(1) self.losses.append(to_detach(loss)) def after_fit(self): "Concatenate all recorded tensors" if self.with_input: self.inputs = detuplify(to_concat(self.inputs)) if not self.save_preds: self.preds = detuplify(to_concat(self.preds)) if not self.save_targs: self.targets = detuplify(to_concat(self.targets)) if self.with_loss: self.losses = to_concat(self.losses) def all_tensors(self): res = [None if self.save_preds else self.preds, None if self.save_targs else self.targets] if self.with_input: res = [self.inputs] + res if self.with_loss: res.append(self.losses) return res #Cell _ex_docs = dict( CancelFitException="Skip the rest of this batch and go to `after_batch`", CancelEpochException="Skip the rest of the training part of the epoch and go to `after_train`", CancelTrainException="Skip the rest of the validation part of the epoch and go to `after_validate`", CancelValidException="Skip the rest of this epoch and go to `after_epoch`", CancelBatchException="Interrupts training and go to `after_fit`") for c,d in _ex_docs.items(): mk_class(c,sup=Exception,doc=d) #Cell _events = L.split('begin_fit begin_epoch begin_train begin_batch after_pred after_loss \ after_backward after_step after_cancel_batch after_batch after_cancel_train \ after_train begin_validate after_cancel_validate after_validate after_cancel_epoch \ after_epoch after_cancel_fit after_fit') mk_class('event', **_events.map_dict(), doc="All possible events as attributes to get tab-completion and typo-proofing") _before_epoch = [event.begin_fit, event.begin_epoch] _after_epoch = [event.after_epoch, event.after_fit] #Cell _loop = ['Start Fit', 'begin_fit', 'Start Epoch Loop', 'begin_epoch', 'Start Train', 'begin_train', 'Start Batch Loop', 'begin_batch', 'after_pred', 'after_loss', 'after_backward', 'after_step', 'after_cancel_batch', 'after_batch','End Batch Loop','End Train', 'after_cancel_train', 'after_train', 'Start Valid', 'begin_validate','Start Batch Loop', '**CBs same as train batch**', 'End Batch Loop', 'End Valid', 'after_cancel_validate', 'after_validate', 'End Epoch Loop', 'after_cancel_epoch', 'after_epoch', 'End Fit', 'after_cancel_fit', 'after_fit'] #Cell defaults.lr = slice(3e-3) defaults.wd = 1e-2 defaults.callbacks = [TrainEvalCallback] #Cell def replacing_yield(o, attr, val): "Context manager to temporarily replace an attribute" old = getattr(o,attr) try: yield setattr(o,attr,val) finally: setattr(o,attr,old) #Cell def mk_metric(m): "Convert `m` to an `AvgMetric`, unless it's already a `Metric`" return m if isinstance(m, Metric) else AvgMetric(m) #Cell def save_model(file, model, opt, with_opt=True): "Save `model` to `file` along with `opt` (if available, and if `with_opt`)" if opt is None: with_opt=False state = get_model(model).state_dict() if with_opt: state = {'model': state, 'opt':opt.state_dict()} torch.save(state, file) #Cell def load_model(file, model, opt, with_opt=None, device=None, strict=True): "Load `model` from `file` along with `opt` (if available, and if `with_opt`)" if isinstance(device, int): device = torch.device('cuda', device) elif device is None: device = 'cpu' state = torch.load(file, map_location=device) hasopt = set(state)=={'model', 'opt'} model_state = state['model'] if hasopt else state get_model(model).load_state_dict(model_state, strict=strict) if hasopt and ifnone(with_opt,True): try: opt.load_state_dict(state['opt']) except: if with_opt: warn("Could not load the optimizer state.") elif with_opt: warn("Saved filed doesn't contain an optimizer state.") #Cell def _try_concat(o): try: return torch.cat(o) except: return sum([L(o_[i,:] for i in range_of(o_)) for o_ in o], L()) #Cell class Learner(): def __init__(self, dbunch, model, loss_func=None, opt_func=Adam, lr=defaults.lr, splitter=trainable_params, cbs=None, cb_funcs=None, metrics=None, path=None, model_dir='models', wd_bn_bias=False, train_bn=True): store_attr(self, "dbunch,model,opt_func,lr,splitter,model_dir,wd_bn_bias,train_bn,metrics") self.training,self.create_mbar,self.logger,self.opt,self.cbs = False,True,print,None,L() #TODO: infer loss_func from data if loss_func is None: loss_func = getattr(dbunch.train_ds, 'loss_func', None) assert loss_func is not None, "Could not infer loss function from the data, please pass a loss function." self.loss_func = loss_func self.path = path if path is not None else getattr(dbunch, 'path', Path('.')) self.add_cbs(cbf() for cbf in L(defaults.callbacks)+L(cb_funcs)) self.add_cbs(cbs) self.model.to(self.dbunch.device) self.epoch,self.n_epoch,self.loss = 0,1,tensor(0.) @property def metrics(self): return self._metrics @metrics.setter def metrics(self,v): self._metrics = L(v).map(mk_metric) def add_cbs(self, cbs): L(cbs).map(self.add_cb) def remove_cbs(self, cbs): L(cbs).map(self.remove_cb) def add_cb(self, cb): old = getattr(self, cb.name, None) assert not old or isinstance(old, type(cb)), f"self.{cb.name} already registered" cb.learn = self setattr(self, cb.name, cb) self.cbs.append(cb) return self def remove_cb(self, cb): cb.learn = None if hasattr(self, cb.name): delattr(self, cb.name) if cb in self.cbs: self.cbs.remove(cb) @contextmanager def added_cbs(self, cbs): self.add_cbs(cbs) yield self.remove_cbs(cbs) def ordered_cbs(self, cb_func:str): return [cb for cb in sort_by_run(self.cbs) if hasattr(cb, cb_func)] def __call__(self, event_name): L(event_name).map(self._call_one) def _call_one(self, event_name): assert hasattr(event, event_name) [cb(event_name) for cb in sort_by_run(self.cbs)] def _bn_bias_state(self, with_bias): return bn_bias_params(self.model, with_bias).map(self.opt.state) def create_opt(self): self.opt = self.opt_func(self.splitter(self.model), lr=self.lr) if not self.wd_bn_bias: for p in self._bn_bias_state(True ): p['do_wd'] = False if self.train_bn: for p in self._bn_bias_state(False): p['force_train'] = True def _split(self, b): i = getattr(self.dbunch, 'n_inp', 1 if len(b)==1 else len(b)-1) self.xb,self.yb = b[:i],b[i:] def all_batches(self): self.n_iter = len(self.dl) for o in enumerate(self.dl): self.one_batch(*o) def one_batch(self, i, b): self.iter = i try: self._split(b); self('begin_batch') self.pred = self.model(*self.xb); self('after_pred') if len(self.yb) == 0: return self.loss = self.loss_func(self.pred, *self.yb); self('after_loss') if not self.training: return self.loss.backward(); self('after_backward') self.opt.step(); self('after_step') self.opt.zero_grad() except CancelBatchException: self('after_cancel_batch') finally: self('after_batch') def _do_begin_fit(self, n_epoch): self.n_epoch,self.loss = n_epoch,tensor(0.); self('begin_fit') def _do_epoch_train(self): try: self.dl = self.dbunch.train_dl; self('begin_train') self.all_batches() except CancelTrainException: self('after_cancel_train') finally: self('after_train') def _do_epoch_validate(self, ds_idx=1, dl=None): if dl is None: dl = self.dbunch.dls[ds_idx] names = ['shuffle', 'drop_last'] try: dl,old,has = change_attrs(dl, names, [False,False]) self.dl = dl; self('begin_validate') with torch.no_grad(): self.all_batches() except CancelValidException: self('after_cancel_validate') finally: dl,*_ = change_attrs(dl, names, old, has); self('after_validate') def fit(self, n_epoch, lr=None, wd=defaults.wd, cbs=None, reset_opt=False): with self.added_cbs(cbs): if reset_opt or not self.opt: self.create_opt() self.opt.set_hypers(wd=wd, lr=self.lr if lr is None else lr) try: self._do_begin_fit(n_epoch) for epoch in range(n_epoch): try: self.epoch=epoch; self('begin_epoch') self._do_epoch_train() self._do_epoch_validate() except CancelEpochException: self('after_cancel_epoch') finally: self('after_epoch') except CancelFitException: self('after_cancel_fit') finally: self('after_fit') def validate(self, ds_idx=1, dl=None, cbs=None): if dl is None: dl = self.dbunch.dls[ds_idx] with self.added_cbs(cbs), self.no_logging(), self.no_mbar(): self(_before_epoch) self._do_epoch_validate(ds_idx, dl) self(_after_epoch) return self.recorder.values[-1] @delegates(GatherPredsCallback.__init__) def get_preds(self, ds_idx=1, dl=None, with_input=False, with_decoded=False, act=None, **kwargs): cb = GatherPredsCallback(with_input=with_input, **kwargs) with self.no_logging(), self.added_cbs(cb), self.loss_not_reduced(), self.no_mbar(): self(_before_epoch) self._do_epoch_validate(ds_idx, dl) self(_after_epoch) if act is None: act = getattr(self.loss_func, 'activation', noop) res = cb.all_tensors() pred_i = 1 if with_input else 0 if res[pred_i] is not None: res[pred_i] = act(res[pred_i]) if with_decoded: res.insert(pred_i+2, getattr(self.loss_func, 'decodes', noop)(res[pred_i])) return tuple(res) def predict(self, item, rm_type_tfms=0): dl = test_dl(self.dbunch, [item], rm_type_tfms=rm_type_tfms) inp,preds,_,dec_preds = self.get_preds(dl=dl, with_input=True, with_decoded=True) i = getattr(self.dbunch, 'n_inp', -1) full_dec = self.dbunch.decode_batch((*tuplify(inp),*tuplify(dec_preds)))[0][i:] return detuplify(full_dec),dec_preds[0],preds[0] def show_results(self, ds_idx=0, dl=None, max_n=10, **kwargs): if dl is None: dl = self.dbunch.dls[ds_idx] b = dl.one_batch() _,_,preds = self.get_preds(dl=[b], with_decoded=True) self.dbunch.show_results(b, preds, max_n=max_n, **kwargs) def show_training_loop(self): indent = 0 for s in _loop: if s.startswith('Start'): print(f'{' '*indent}{s}'); indent += 2 elif s.startswith('End'): indent -= 2; print(f'{' '*indent}{s}') else: print(f'{' '*indent} - {s:15}:', self.ordered_cbs(s)) @contextmanager def no_logging(self): return replacing_yield(self, 'logger', noop) @contextmanager def no_mbar(self): return replacing_yield(self, 'create_mbar', False) @contextmanager def loss_not_reduced(self): if hasattr(self.loss_func, 'reduction'): return replacing_yield(self.loss_func, 'reduction', 'none') else: return replacing_yield(self, 'loss_func', partial(self.loss_func, reduction='none')) def save(self, file, with_opt=True): if rank_distrib(): return # don't save if slave proc file = join_path_file(file, self.path/self.model_dir, ext='.pth') save_model(file, self.model, getattr(self,'opt',None), with_opt) def load(self, file, with_opt=None, device=None, strict=True): if device is None: device = self.dbunch.device if self.opt is None: self.create_opt() distrib_barrier() file = join_path_file(file, self.path/self.model_dir, ext='.pth') load_model(file, self.model, self.opt, with_opt=with_opt, device=device, strict=strict) return self Learner.x,Learner.y = add_props(lambda i,x: detuplify((x.xb,x.yb)[i])) #Cell add_docs(Learner, "Group together a `model`, some `dbunch` and a `loss_func` to handle training", add_cbs="Add `cbs` to the list of `Callback` and register `self` as their learner", add_cb="Add `cb` to the list of `Callback` and register `self` as their learner", remove_cbs="Remove `cbs` from the list of `Callback` and deregister `self` as their learner", remove_cb="Add `cb` from the list of `Callback` and deregister `self` as their learner", added_cbs="Context manage that temporarily adds `cbs`", ordered_cbs="Return a list of `Callback` for one step `cb_func` in the training loop", create_opt="Create an optimizer with `lr`", one_batch="Train or evaluate `self.model` on batch `(xb,yb)`", all_batches="Train or evaluate `self.model` on all batches of `self.dl`", fit="Fit `self.model` for `n_epoch` using `cbs`. Optionally `reset_opt`.", validate="Validate on `dl` with potential new `cbs`.", get_preds="Get the predictions and targets on the `ds_idx`-th dbunchset or `dl`, optionally `with_input` and `with_loss`", predict="Return the prediction on `item`, fully decoded, loss function decoded and probabilities", show_results="Show some predictions on `ds_idx`-th dbunchset or `dl`", show_training_loop="Show each step in the training loop", no_logging="Context manager to temporarily remove `logger`", no_mbar="Context manager to temporarily prevent the master progress bar from being created", loss_not_reduced="A context manager to evaluate `loss_func` with reduction set to none.", save="Save model and optimizer state (if `with_opt`) to `self.path/self.model_dir/file`", load="Load model and optimizer state (if `with_opt`) from `self.path/self.model_dir/file` using `device`" ) #Cell class VerboseCallback(Callback): "Callback that prints the name of each event called" def __call__(self, event_name): print(event_name) super().__call__(event_name) #Cell @docs class Metric(): "Blueprint for defining a metric" def reset(self): pass def accumulate(self, learn): pass @property def value(self): raise NotImplementedError @property def name(self): return class2attr(self, 'Metric') _docs = dict( reset="Reset inner state to prepare for new computation", name="Name of the `Metric`, camel-cased and with Metric removed", accumulate="Use `learn` to update the state with new results", value="The value of the metric") #Cell def _maybe_reduce(val): if num_distrib()>1: val = val.clone() torch.distributed.all_reduce(val, op=torch.distributed.ReduceOp.SUM) val /= num_distrib() return val #Cell class AvgMetric(Metric): "Average the values of `func` taking into account potential different batch sizes" def __init__(self, func): self.func = func def reset(self): self.total,self.count = 0.,0 def accumulate(self, learn): bs = find_bs(learn.yb) self.total += to_detach(self.func(learn.pred, *learn.yb))*bs self.count += bs @property def value(self): return self.total/self.count if self.count != 0 else None @property def name(self): return self.func.func.__name__ if hasattr(self.func, 'func') else self.func.__name__ #Cell class AvgLoss(Metric): "Average the losses taking into account potential different batch sizes" def reset(self): self.total,self.count = 0.,0 def accumulate(self, learn): bs = find_bs(learn.yb) self.total += to_detach(learn.loss.mean())*bs self.count += bs @property def value(self): return self.total/self.count if self.count != 0 else None @property def name(self): return "loss" #Cell class AvgSmoothLoss(Metric): "Smooth average of the losses (exponentially weighted with `beta`)" def __init__(self, beta=0.98): self.beta = beta def reset(self): self.count,self.val = 0,tensor(0.) def accumulate(self, learn): self.count += 1 self.val = torch.lerp(to_detach(learn.loss.mean(), gather=False), self.val, self.beta) @property def value(self): return self.val/(1-self.beta**self.count) #Cell from fastprogress.fastprogress import format_time def _maybe_item(t): t = t.value return t.item() if isinstance(t, Tensor) and t.numel()==1 else t #Cell class Recorder(Callback): "Callback that registers statistics (lr, loss and metrics) during training" run_after = TrainEvalCallback def __init__(self, add_time=True, train_metrics=False, beta=0.98): self.add_time,self.train_metrics = add_time,train_metrics self.loss,self.smooth_loss = AvgLoss(),AvgSmoothLoss(beta=beta) def begin_fit(self): "Prepare state for training" self.lrs,self.iters,self.losses,self.values = [],[],[],[] names = self._valid_mets.attrgot('name') if self.train_metrics: names = names.map('train_{}') + names.map('valid_{}') else: names = L('train_loss', 'valid_loss') + names[1:] if self.add_time: names.append('time') self.metric_names = 'epoch'+names self.smooth_loss.reset() def after_batch(self): "Update all metrics and records lr and smooth loss in training" if len(self.yb) == 0: return mets = self._train_mets if self.training else self._valid_mets for met in mets: met.accumulate(self.learn) if not self.training: return self.lrs.append(self.opt.hypers[-1]['lr']) self.losses.append(self.smooth_loss.value) self.learn.smooth_loss = self.smooth_loss.value def begin_epoch(self): "Set timer if `self.add_time=True`" self.cancel_train,self.cancel_valid = False,False if self.add_time: self.start_epoch = time.time() self.log = L(getattr(self, 'epoch', 0)) def begin_train (self): self._train_mets[1:].map(Self.reset()) def begin_validate(self): self._valid_mets.map(Self.reset()) def after_train (self): self.log += self._train_mets.map(_maybe_item) def after_validate(self): self.log += self._valid_mets.map(_maybe_item) def after_cancel_train(self): self.cancel_train = True def after_cancel_validate(self): self.cancel_valid = True def after_epoch(self): "Store and log the loss/metric values" self.values.append(self.log[1:].copy()) if self.add_time: self.log.append(format_time(time.time() - self.start_epoch)) self.logger(self.log) self.iters.append(self.smooth_loss.count) @property def _train_mets(self): if getattr(self, 'cancel_train', False): return L() return L(self.smooth_loss) + (self.metrics if self.train_metrics else L()) @property def _valid_mets(self): if getattr(self, 'cancel_valid', False): return L() return L(self.loss) + self.metrics def plot_loss(self, skip_start=5, with_valid=True): plt.plot(list(range(skip_start, len(self.losses))), self.losses[skip_start:], label='train') if with_valid: idx = (np.array(self.iters)<skip_start).sum() plt.plot(self.iters[idx:], L(self.values[idx:]).itemgot(1), label='valid') plt.legend() #Cell add_docs(Recorder, begin_train = "Reset loss and metrics state", after_train = "Log loss and metric values on the training set (if `self.training_metrics=True`)", begin_validate = "Reset loss and metrics state", after_validate = "Log loss and metric values on the validation set", after_cancel_train = "Ignore training metrics for this epoch", after_cancel_validate = "Ignore validation metrics for this epoch", plot_loss = "Plot the losses from `skip_start` and onward") defaults.callbacks = [TrainEvalCallback, Recorder] #Cell @patch def freeze_to(self:Learner, n): if self.opt is None: self.create_opt() self.opt.freeze_to(n) self.opt.clear_state() @patch def freeze(self:Learner): self.freeze_to(-1) @patch def unfreeze(self:Learner): self.freeze_to(0) add_docs(Learner, freeze_to="Freeze parameter groups up to `n`", freeze="Freeze up to last parameter group", unfreeze="Unfreeze the entire model") #Cell @patch def export(self:Learner, fname='export.pkl'): "Export the content of `self` without the items and the optimizer state for inference" if rank_distrib(): return # don't export if slave proc old_dbunch = self.dbunch self.dbunch = self.dbunch.new_empty() state = self.opt.state_dict() self.opt = None with warnings.catch_warnings(): #To avoid the warning that come from PyTorch about model not being checked warnings.simplefilter("ignore") torch.save(self, self.path/fname) self.create_opt() self.opt.load_state_dict(state) self.dbunch = old_dbunch #Cell @patch def tta(self:Learner, ds_idx=1, dl=None, n=4, item_tfms=None, batch_tfms=None, beta=0.25): "Return predictions on the `ds_idx` dataset or `dl` using Test Time Augmentation" if dl is None: dl = self.dbunch.dls[ds_idx] if item_tfms is not None or batch_tfms is not None: dl = dl.new(after_item=item_tfms, after_batch=batch_tfms) with dl.dataset.set_split_idx(0), self.no_mbar(): if hasattr(self,'progress'): self.progress.mbar = master_bar(list(range(n))) aug_preds = [] for i in self.progress.mbar if hasattr(self,'progress') else range(n): self.epoch = i #To keep track of progress on mbar since the progress callback will use self.epoch # aug_preds.append(self.get_preds(dl=dl)[0][None]) aug_preds.append(self.get_preds(ds_idx)[0][None]) aug_preds = torch.cat(aug_preds).mean(0) self.epoch = n with dl.dataset.set_split_idx(1): preds,targs = self.get_preds(ds_idx) preds = (aug_preds,preds) if beta is None else torch.lerp(aug_preds, preds, beta) return preds,targs
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/13_learner.ipynb (unless otherwise specified). __all__ = ['CancelFitException', 'CancelEpochException', 'CancelTrainException', 'CancelValidException', 'CancelBatchException', 'Callback', 'TrainEvalCallback', 'GatherPredsCallback', 'event', 'replacing_yield', 'mk_metric', 'save_model', 'load_model', 'Learner', 'VerboseCallback', 'Metric', 'AvgMetric', 'AvgLoss', 'AvgSmoothLoss', 'Recorder'] #Cell from .test import * from .data.all import * from .optimizer import * #Cell class Callback(GetAttr): "Basic class handling tweaks of the training loop by changing a `Learner` in various events" _default,learn,run = 'learn',None,True def __repr__(self): return type(self).__name__ def __call__(self, event_name): "Call `self.{event_name}` if it's defined" if self.run: getattr(self, event_name, noop)() @property def name(self): "Name of the `Callback`, camel-cased and with '*Callback*' removed" return class2attr(self, 'Callback') #Cell class TrainEvalCallback(Callback): "`Callback` that tracks the number of iterations done and properly sets training/eval mode" def begin_fit(self): "Set the iter and epoch counters to 0, put the model and the right device" self.learn.train_iter,self.learn.pct_train = 0,0. self.model.to(self.dbunch.device) def after_batch(self): "Update the iter counter (in training mode)" if not self.training: return self.learn.pct_train += 1./(self.n_iter*self.n_epoch) self.learn.train_iter += 1 def begin_train(self): "Set the model in training mode" self.learn.pct_train=self.epoch/self.n_epoch self.model.train() self.learn.training=True def begin_validate(self): "Set the model in validation mode" self.model.eval() self.learn.training=False #Cell #TODO: save_targs and save_preds only handle preds/targets that have one tensor, not tuples of tensors. class GatherPredsCallback(Callback): "`Callback` that saves the predictions and targets, optionally `with_loss`" def __init__(self, with_input=False, with_loss=False, save_preds=None, save_targs=None): store_attr(self, "with_input,with_loss,save_preds,save_targs") def begin_batch(self): if self.with_input: self.inputs.append((to_detach(self.xb))) def begin_validate(self): "Initialize containers" self.preds,self.targets = [],[] if self.with_input: self.inputs = [] if self.with_loss: self.losses = [] def after_batch(self): "Save predictions, targets and potentially losses" preds,targs = to_detach(self.pred),to_detach(self.yb) if self.save_preds is None: self.preds.append(preds) else: (self.save_preds/str(self.iter)).save_array(preds) if self.save_targs is None: self.targets.append(targs) else: (self.save_targs/str(self.iter)).save_array(targs[0]) if self.with_loss: bs = find_bs(self.yb) loss = self.loss if self.loss.numel() == bs else self.loss.view(bs,-1).mean(1) self.losses.append(to_detach(loss)) def after_fit(self): "Concatenate all recorded tensors" if self.with_input: self.inputs = detuplify(to_concat(self.inputs)) if not self.save_preds: self.preds = detuplify(to_concat(self.preds)) if not self.save_targs: self.targets = detuplify(to_concat(self.targets)) if self.with_loss: self.losses = to_concat(self.losses) def all_tensors(self): res = [None if self.save_preds else self.preds, None if self.save_targs else self.targets] if self.with_input: res = [self.inputs] + res if self.with_loss: res.append(self.losses) return res #Cell _ex_docs = dict( CancelFitException="Skip the rest of this batch and go to `after_batch`", CancelEpochException="Skip the rest of the training part of the epoch and go to `after_train`", CancelTrainException="Skip the rest of the validation part of the epoch and go to `after_validate`", CancelValidException="Skip the rest of this epoch and go to `after_epoch`", CancelBatchException="Interrupts training and go to `after_fit`") for c,d in _ex_docs.items(): mk_class(c,sup=Exception,doc=d) #Cell _events = L.split('begin_fit begin_epoch begin_train begin_batch after_pred after_loss \ after_backward after_step after_cancel_batch after_batch after_cancel_train \ after_train begin_validate after_cancel_validate after_validate after_cancel_epoch \ after_epoch after_cancel_fit after_fit') mk_class('event', **_events.map_dict(), doc="All possible events as attributes to get tab-completion and typo-proofing") _before_epoch = [event.begin_fit, event.begin_epoch] _after_epoch = [event.after_epoch, event.after_fit] #Cell _loop = ['Start Fit', 'begin_fit', 'Start Epoch Loop', 'begin_epoch', 'Start Train', 'begin_train', 'Start Batch Loop', 'begin_batch', 'after_pred', 'after_loss', 'after_backward', 'after_step', 'after_cancel_batch', 'after_batch','End Batch Loop','End Train', 'after_cancel_train', 'after_train', 'Start Valid', 'begin_validate','Start Batch Loop', '**CBs same as train batch**', 'End Batch Loop', 'End Valid', 'after_cancel_validate', 'after_validate', 'End Epoch Loop', 'after_cancel_epoch', 'after_epoch', 'End Fit', 'after_cancel_fit', 'after_fit'] #Cell defaults.lr = slice(3e-3) defaults.wd = 1e-2 defaults.callbacks = [TrainEvalCallback] #Cell def replacing_yield(o, attr, val): "Context manager to temporarily replace an attribute" old = getattr(o,attr) try: yield setattr(o,attr,val) finally: setattr(o,attr,old) #Cell def mk_metric(m): "Convert `m` to an `AvgMetric`, unless it's already a `Metric`" return m if isinstance(m, Metric) else AvgMetric(m) #Cell def save_model(file, model, opt, with_opt=True): "Save `model` to `file` along with `opt` (if available, and if `with_opt`)" if opt is None: with_opt=False state = get_model(model).state_dict() if with_opt: state = {'model': state, 'opt':opt.state_dict()} torch.save(state, file) #Cell def load_model(file, model, opt, with_opt=None, device=None, strict=True): "Load `model` from `file` along with `opt` (if available, and if `with_opt`)" if isinstance(device, int): device = torch.device('cuda', device) elif device is None: device = 'cpu' state = torch.load(file, map_location=device) hasopt = set(state)=={'model', 'opt'} model_state = state['model'] if hasopt else state get_model(model).load_state_dict(model_state, strict=strict) if hasopt and ifnone(with_opt,True): try: opt.load_state_dict(state['opt']) except: if with_opt: warn("Could not load the optimizer state.") elif with_opt: warn("Saved filed doesn't contain an optimizer state.") #Cell def _try_concat(o): try: return torch.cat(o) except: return sum([L(o_[i,:] for i in range_of(o_)) for o_ in o], L()) #Cell class Learner(): def __init__(self, dbunch, model, loss_func=None, opt_func=Adam, lr=defaults.lr, splitter=trainable_params, cbs=None, cb_funcs=None, metrics=None, path=None, model_dir='models', wd_bn_bias=False, train_bn=True): store_attr(self, "dbunch,model,opt_func,lr,splitter,model_dir,wd_bn_bias,train_bn,metrics") self.training,self.create_mbar,self.logger,self.opt,self.cbs = False,True,print,None,L() #TODO: infer loss_func from data if loss_func is None: loss_func = getattr(dbunch.train_ds, 'loss_func', None) assert loss_func is not None, "Could not infer loss function from the data, please pass a loss function." self.loss_func = loss_func self.path = path if path is not None else getattr(dbunch, 'path', Path('.')) self.add_cbs(cbf() for cbf in L(defaults.callbacks)+L(cb_funcs)) self.add_cbs(cbs) self.model.to(self.dbunch.device) self.epoch,self.n_epoch,self.loss = 0,1,tensor(0.) @property def metrics(self): return self._metrics @metrics.setter def metrics(self,v): self._metrics = L(v).map(mk_metric) def add_cbs(self, cbs): L(cbs).map(self.add_cb) def remove_cbs(self, cbs): L(cbs).map(self.remove_cb) def add_cb(self, cb): old = getattr(self, cb.name, None) assert not old or isinstance(old, type(cb)), f"self.{cb.name} already registered" cb.learn = self setattr(self, cb.name, cb) self.cbs.append(cb) return self def remove_cb(self, cb): cb.learn = None if hasattr(self, cb.name): delattr(self, cb.name) if cb in self.cbs: self.cbs.remove(cb) @contextmanager def added_cbs(self, cbs): self.add_cbs(cbs) yield self.remove_cbs(cbs) def ordered_cbs(self, cb_func:str): return [cb for cb in sort_by_run(self.cbs) if hasattr(cb, cb_func)] def __call__(self, event_name): L(event_name).map(self._call_one) def _call_one(self, event_name): assert hasattr(event, event_name) [cb(event_name) for cb in sort_by_run(self.cbs)] def _bn_bias_state(self, with_bias): return bn_bias_params(self.model, with_bias).map(self.opt.state) def create_opt(self): self.opt = self.opt_func(self.splitter(self.model), lr=self.lr) if not self.wd_bn_bias: for p in self._bn_bias_state(True ): p['do_wd'] = False if self.train_bn: for p in self._bn_bias_state(False): p['force_train'] = True def _split(self, b): i = getattr(self.dbunch, 'n_inp', 1 if len(b)==1 else len(b)-1) self.xb,self.yb = b[:i],b[i:] def all_batches(self): self.n_iter = len(self.dl) for o in enumerate(self.dl): self.one_batch(*o) def one_batch(self, i, b): self.iter = i try: self._split(b); self('begin_batch') self.pred = self.model(*self.xb); self('after_pred') if len(self.yb) == 0: return self.loss = self.loss_func(self.pred, *self.yb); self('after_loss') if not self.training: return self.loss.backward(); self('after_backward') self.opt.step(); self('after_step') self.opt.zero_grad() except CancelBatchException: self('after_cancel_batch') finally: self('after_batch') def _do_begin_fit(self, n_epoch): self.n_epoch,self.loss = n_epoch,tensor(0.); self('begin_fit') def _do_epoch_train(self): try: self.dl = self.dbunch.train_dl; self('begin_train') self.all_batches() except CancelTrainException: self('after_cancel_train') finally: self('after_train') def _do_epoch_validate(self, ds_idx=1, dl=None): if dl is None: dl = self.dbunch.dls[ds_idx] names = ['shuffle', 'drop_last'] try: dl,old,has = change_attrs(dl, names, [False,False]) self.dl = dl; self('begin_validate') with torch.no_grad(): self.all_batches() except CancelValidException: self('after_cancel_validate') finally: dl,*_ = change_attrs(dl, names, old, has); self('after_validate') def fit(self, n_epoch, lr=None, wd=defaults.wd, cbs=None, reset_opt=False): with self.added_cbs(cbs): if reset_opt or not self.opt: self.create_opt() self.opt.set_hypers(wd=wd, lr=self.lr if lr is None else lr) try: self._do_begin_fit(n_epoch) for epoch in range(n_epoch): try: self.epoch=epoch; self('begin_epoch') self._do_epoch_train() self._do_epoch_validate() except CancelEpochException: self('after_cancel_epoch') finally: self('after_epoch') except CancelFitException: self('after_cancel_fit') finally: self('after_fit') def validate(self, ds_idx=1, dl=None, cbs=None): if dl is None: dl = self.dbunch.dls[ds_idx] with self.added_cbs(cbs), self.no_logging(), self.no_mbar(): self(_before_epoch) self._do_epoch_validate(ds_idx, dl) self(_after_epoch) return self.recorder.values[-1] @delegates(GatherPredsCallback.__init__) def get_preds(self, ds_idx=1, dl=None, with_input=False, with_decoded=False, act=None, **kwargs): cb = GatherPredsCallback(with_input=with_input, **kwargs) with self.no_logging(), self.added_cbs(cb), self.loss_not_reduced(), self.no_mbar(): self(_before_epoch) self._do_epoch_validate(ds_idx, dl) self(_after_epoch) if act is None: act = getattr(self.loss_func, 'activation', noop) res = cb.all_tensors() pred_i = 1 if with_input else 0 if res[pred_i] is not None: res[pred_i] = act(res[pred_i]) if with_decoded: res.insert(pred_i+2, getattr(self.loss_func, 'decodes', noop)(res[pred_i])) return tuple(res) def predict(self, item, rm_type_tfms=0): dl = test_dl(self.dbunch, [item], rm_type_tfms=rm_type_tfms) inp,preds,_,dec_preds = self.get_preds(dl=dl, with_input=True, with_decoded=True) i = getattr(self.dbunch, 'n_inp', -1) full_dec = self.dbunch.decode_batch((*tuplify(inp),*tuplify(dec_preds)))[0][i:] return detuplify(full_dec),dec_preds[0],preds[0] def show_results(self, ds_idx=0, dl=None, max_n=10, **kwargs): if dl is None: dl = self.dbunch.dls[ds_idx] b = dl.one_batch() _,_,preds = self.get_preds(dl=[b], with_decoded=True) self.dbunch.show_results(b, preds, max_n=max_n, **kwargs) def show_training_loop(self): indent = 0 for s in _loop: if s.startswith('Start'): print(f'{" "*indent}{s}'); indent += 2 elif s.startswith('End'): indent -= 2; print(f'{" "*indent}{s}') else: print(f'{" "*indent} - {s:15}:', self.ordered_cbs(s)) @contextmanager def no_logging(self): return replacing_yield(self, 'logger', noop) @contextmanager def no_mbar(self): return replacing_yield(self, 'create_mbar', False) @contextmanager def loss_not_reduced(self): if hasattr(self.loss_func, 'reduction'): return replacing_yield(self.loss_func, 'reduction', 'none') else: return replacing_yield(self, 'loss_func', partial(self.loss_func, reduction='none')) def save(self, file, with_opt=True): if rank_distrib(): return # don't save if slave proc file = join_path_file(file, self.path/self.model_dir, ext='.pth') save_model(file, self.model, getattr(self,'opt',None), with_opt) def load(self, file, with_opt=None, device=None, strict=True): if device is None: device = self.dbunch.device if self.opt is None: self.create_opt() distrib_barrier() file = join_path_file(file, self.path/self.model_dir, ext='.pth') load_model(file, self.model, self.opt, with_opt=with_opt, device=device, strict=strict) return self Learner.x,Learner.y = add_props(lambda i,x: detuplify((x.xb,x.yb)[i])) #Cell add_docs(Learner, "Group together a `model`, some `dbunch` and a `loss_func` to handle training", add_cbs="Add `cbs` to the list of `Callback` and register `self` as their learner", add_cb="Add `cb` to the list of `Callback` and register `self` as their learner", remove_cbs="Remove `cbs` from the list of `Callback` and deregister `self` as their learner", remove_cb="Add `cb` from the list of `Callback` and deregister `self` as their learner", added_cbs="Context manage that temporarily adds `cbs`", ordered_cbs="Return a list of `Callback` for one step `cb_func` in the training loop", create_opt="Create an optimizer with `lr`", one_batch="Train or evaluate `self.model` on batch `(xb,yb)`", all_batches="Train or evaluate `self.model` on all batches of `self.dl`", fit="Fit `self.model` for `n_epoch` using `cbs`. Optionally `reset_opt`.", validate="Validate on `dl` with potential new `cbs`.", get_preds="Get the predictions and targets on the `ds_idx`-th dbunchset or `dl`, optionally `with_input` and `with_loss`", predict="Return the prediction on `item`, fully decoded, loss function decoded and probabilities", show_results="Show some predictions on `ds_idx`-th dbunchset or `dl`", show_training_loop="Show each step in the training loop", no_logging="Context manager to temporarily remove `logger`", no_mbar="Context manager to temporarily prevent the master progress bar from being created", loss_not_reduced="A context manager to evaluate `loss_func` with reduction set to none.", save="Save model and optimizer state (if `with_opt`) to `self.path/self.model_dir/file`", load="Load model and optimizer state (if `with_opt`) from `self.path/self.model_dir/file` using `device`" ) #Cell class VerboseCallback(Callback): "Callback that prints the name of each event called" def __call__(self, event_name): print(event_name) super().__call__(event_name) #Cell @docs class Metric(): "Blueprint for defining a metric" def reset(self): pass def accumulate(self, learn): pass @property def value(self): raise NotImplementedError @property def name(self): return class2attr(self, 'Metric') _docs = dict( reset="Reset inner state to prepare for new computation", name="Name of the `Metric`, camel-cased and with Metric removed", accumulate="Use `learn` to update the state with new results", value="The value of the metric") #Cell def _maybe_reduce(val): if num_distrib()>1: val = val.clone() torch.distributed.all_reduce(val, op=torch.distributed.ReduceOp.SUM) val /= num_distrib() return val #Cell class AvgMetric(Metric): "Average the values of `func` taking into account potential different batch sizes" def __init__(self, func): self.func = func def reset(self): self.total,self.count = 0.,0 def accumulate(self, learn): bs = find_bs(learn.yb) self.total += to_detach(self.func(learn.pred, *learn.yb))*bs self.count += bs @property def value(self): return self.total/self.count if self.count != 0 else None @property def name(self): return self.func.func.__name__ if hasattr(self.func, 'func') else self.func.__name__ #Cell class AvgLoss(Metric): "Average the losses taking into account potential different batch sizes" def reset(self): self.total,self.count = 0.,0 def accumulate(self, learn): bs = find_bs(learn.yb) self.total += to_detach(learn.loss.mean())*bs self.count += bs @property def value(self): return self.total/self.count if self.count != 0 else None @property def name(self): return "loss" #Cell class AvgSmoothLoss(Metric): "Smooth average of the losses (exponentially weighted with `beta`)" def __init__(self, beta=0.98): self.beta = beta def reset(self): self.count,self.val = 0,tensor(0.) def accumulate(self, learn): self.count += 1 self.val = torch.lerp(to_detach(learn.loss.mean(), gather=False), self.val, self.beta) @property def value(self): return self.val/(1-self.beta**self.count) #Cell from fastprogress.fastprogress import format_time def _maybe_item(t): t = t.value return t.item() if isinstance(t, Tensor) and t.numel()==1 else t #Cell class Recorder(Callback): "Callback that registers statistics (lr, loss and metrics) during training" run_after = TrainEvalCallback def __init__(self, add_time=True, train_metrics=False, beta=0.98): self.add_time,self.train_metrics = add_time,train_metrics self.loss,self.smooth_loss = AvgLoss(),AvgSmoothLoss(beta=beta) def begin_fit(self): "Prepare state for training" self.lrs,self.iters,self.losses,self.values = [],[],[],[] names = self._valid_mets.attrgot('name') if self.train_metrics: names = names.map('train_{}') + names.map('valid_{}') else: names = L('train_loss', 'valid_loss') + names[1:] if self.add_time: names.append('time') self.metric_names = 'epoch'+names self.smooth_loss.reset() def after_batch(self): "Update all metrics and records lr and smooth loss in training" if len(self.yb) == 0: return mets = self._train_mets if self.training else self._valid_mets for met in mets: met.accumulate(self.learn) if not self.training: return self.lrs.append(self.opt.hypers[-1]['lr']) self.losses.append(self.smooth_loss.value) self.learn.smooth_loss = self.smooth_loss.value def begin_epoch(self): "Set timer if `self.add_time=True`" self.cancel_train,self.cancel_valid = False,False if self.add_time: self.start_epoch = time.time() self.log = L(getattr(self, 'epoch', 0)) def begin_train (self): self._train_mets[1:].map(Self.reset()) def begin_validate(self): self._valid_mets.map(Self.reset()) def after_train (self): self.log += self._train_mets.map(_maybe_item) def after_validate(self): self.log += self._valid_mets.map(_maybe_item) def after_cancel_train(self): self.cancel_train = True def after_cancel_validate(self): self.cancel_valid = True def after_epoch(self): "Store and log the loss/metric values" self.values.append(self.log[1:].copy()) if self.add_time: self.log.append(format_time(time.time() - self.start_epoch)) self.logger(self.log) self.iters.append(self.smooth_loss.count) @property def _train_mets(self): if getattr(self, 'cancel_train', False): return L() return L(self.smooth_loss) + (self.metrics if self.train_metrics else L()) @property def _valid_mets(self): if getattr(self, 'cancel_valid', False): return L() return L(self.loss) + self.metrics def plot_loss(self, skip_start=5, with_valid=True): plt.plot(list(range(skip_start, len(self.losses))), self.losses[skip_start:], label='train') if with_valid: idx = (np.array(self.iters)<skip_start).sum() plt.plot(self.iters[idx:], L(self.values[idx:]).itemgot(1), label='valid') plt.legend() #Cell add_docs(Recorder, begin_train = "Reset loss and metrics state", after_train = "Log loss and metric values on the training set (if `self.training_metrics=True`)", begin_validate = "Reset loss and metrics state", after_validate = "Log loss and metric values on the validation set", after_cancel_train = "Ignore training metrics for this epoch", after_cancel_validate = "Ignore validation metrics for this epoch", plot_loss = "Plot the losses from `skip_start` and onward") defaults.callbacks = [TrainEvalCallback, Recorder] #Cell @patch def freeze_to(self:Learner, n): if self.opt is None: self.create_opt() self.opt.freeze_to(n) self.opt.clear_state() @patch def freeze(self:Learner): self.freeze_to(-1) @patch def unfreeze(self:Learner): self.freeze_to(0) add_docs(Learner, freeze_to="Freeze parameter groups up to `n`", freeze="Freeze up to last parameter group", unfreeze="Unfreeze the entire model") #Cell @patch def export(self:Learner, fname='export.pkl'): "Export the content of `self` without the items and the optimizer state for inference" if rank_distrib(): return # don't export if slave proc old_dbunch = self.dbunch self.dbunch = self.dbunch.new_empty() state = self.opt.state_dict() self.opt = None with warnings.catch_warnings(): #To avoid the warning that come from PyTorch about model not being checked warnings.simplefilter("ignore") torch.save(self, self.path/fname) self.create_opt() self.opt.load_state_dict(state) self.dbunch = old_dbunch #Cell @patch def tta(self:Learner, ds_idx=1, dl=None, n=4, item_tfms=None, batch_tfms=None, beta=0.25): "Return predictions on the `ds_idx` dataset or `dl` using Test Time Augmentation" if dl is None: dl = self.dbunch.dls[ds_idx] if item_tfms is not None or batch_tfms is not None: dl = dl.new(after_item=item_tfms, after_batch=batch_tfms) with dl.dataset.set_split_idx(0), self.no_mbar(): if hasattr(self,'progress'): self.progress.mbar = master_bar(list(range(n))) aug_preds = [] for i in self.progress.mbar if hasattr(self,'progress') else range(n): self.epoch = i #To keep track of progress on mbar since the progress callback will use self.epoch # aug_preds.append(self.get_preds(dl=dl)[0][None]) aug_preds.append(self.get_preds(ds_idx)[0][None]) aug_preds = torch.cat(aug_preds).mean(0) self.epoch = n with dl.dataset.set_split_idx(1): preds,targs = self.get_preds(ds_idx) preds = (aug_preds,preds) if beta is None else torch.lerp(aug_preds, preds, beta) return preds,targs
from brownie import DeepFreezeFactory, Contract from scripts.helpful_scripts import get_account from web3 import Web3 from sys import exit import json HINT = "Hello" ETH = Web3.toWei(0.1, "Ether") def createFreezer(): if len(DeepFreezeFactory) == 0: print("You need to deploy the contract first") exit(0) factory = DeepFreezeFactory[-1] factory.createDeepFreeze(HINT, Web3.keccak(text="Toto"), {"from": get_account()}) return factory.userFreezer(get_account(), 0, {"from": get_account()}) def send_Fund(freezer): freezer.deposit({"from": get_account(), "value": ETH}) print( f"Send {Web3.fromWei(freezer.balance(),"Ether")} ETH, balance of {freezer.address} : {Web3.fromWei(freezer.balance(),"Ether")} ETH" ) def withdraw_Fund(freezer): freezer.withdraw("Toto", {"from": get_account()}) print( f"Withdrawing fund, balance of {freezer.address} : {Web3.fromWei(freezer.balance(),"Ether")} ETH" ) def main(): freezer_address = createFreezer() with open("DeepFreeze_abi.json") as f: abi = json.load(f) freezer = Contract.from_abi("freezer", freezer_address, abi) send_Fund(freezer) # withdraw_Fund(freezer)
from brownie import DeepFreezeFactory, Contract from scripts.helpful_scripts import get_account from web3 import Web3 from sys import exit import json HINT = "Hello" ETH = Web3.toWei(0.1, "Ether") def createFreezer(): if len(DeepFreezeFactory) == 0: print("You need to deploy the contract first") exit(0) factory = DeepFreezeFactory[-1] factory.createDeepFreeze(HINT, Web3.keccak(text="Toto"), {"from": get_account()}) return factory.userFreezer(get_account(), 0, {"from": get_account()}) def send_Fund(freezer): freezer.deposit({"from": get_account(), "value": ETH}) print( f"Send {Web3.fromWei(freezer.balance(),'Ether')} ETH, balance of {freezer.address} : {Web3.fromWei(freezer.balance(),'Ether')} ETH" ) def withdraw_Fund(freezer): freezer.withdraw("Toto", {"from": get_account()}) print( f"Withdrawing fund, balance of {freezer.address} : {Web3.fromWei(freezer.balance(),'Ether')} ETH" ) def main(): freezer_address = createFreezer() with open("DeepFreeze_abi.json") as f: abi = json.load(f) freezer = Contract.from_abi("freezer", freezer_address, abi) send_Fund(freezer) # withdraw_Fund(freezer)
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT import sys, pathlib sys.path.append(str(pathlib.Path(__file__).resolve().parents[1])) from m1n1.setup import * from m1n1 import asm code_len = 12 * 16 * 8 + 4 data_len = 8 * 16 * 8 if u.mrs(SPRR_CONFIG_EL1): u.msr(GXF_CONFIG_EL12, 0) u.msr(SPRR_CONFIG_EL12, 0) u.msr(GXF_CONFIG_EL1, 0) u.msr(SPRR_CONFIG_EL1, 0) u.msr(HACR_EL2, 0) hcr = HCR(u.mrs(HCR_EL2)) hcr.TIDCP = 0 hcr.TGE = 0 u.msr(HCR_EL2, hcr.value) u.inst(0xd5033fdf) # isb ACTLR_DEFAULT = 0xc00 ACTLR_AFP = 1 << 5 u.msr(ACTLR_EL1, ACTLR_DEFAULT | ACTLR_AFP) code_buffer = p.malloc(code_len) data_buffer = p.malloc(data_len) template = asm.ARMAsm(""" mov x2, x0 mrs x2, s3_0_c0_c0_0 str x2, [x1], #8 ret """, code_buffer) mov, mrs, st, ret = struct.unpack("4I", template.data) data = [] BAD = 0xacce5515abad1dea AUX = [ ACTLR_EL1, ACTLR_EL2, AFSR0_EL1, AFSR0_EL2, AFSR1_EL1, AFSR1_EL2, AIDR_EL1, AIDR2_EL1, AMAIR_EL1, AMAIR_EL2, APCTL_EL1, APSTS_EL1, ] def test(): u.msr(SPRR_CONFIG_EL1, 1) u.msr(GXF_CONFIG_EL1, 1) u.msr(SPRR_CONFIG_EL12, 1) u.msr(GXF_CONFIG_EL12, 1) for op1 in range(1 << 3): for CRn in (0b1011, 0b1111): mrs0 = mrs | (op1 << 16) | (CRn << 12) insns = [] for CRm in range(1 << 4): for op2 in range(1 << 3): insns.extend((mov, mrs0 | (CRm << 8) | (op2 << 5), st)) insns.append(ret) iface.writemem(code_buffer, struct.pack("<385I", *insns)) p.dc_cvau(code_buffer, code_len) p.ic_ivau(code_buffer, code_len) p.set_exc_guard(GUARD.SILENT | GUARD.SKIP) p.el1_call(code_buffer, BAD, data_buffer) cnt = p.get_exc_count() data = iface.readmem(data_buffer, data_len) d = struct.unpack("<128Q", data) i = 0 for CRm in range(1 << 4): for op2 in range(1 << 3): v = d[i] if v != BAD: yield (3, op1, CRn, CRm, op2) i += 1 for enc in AUX: try: v = u.mrs(enc, call="el1", silent=True) if v != BAD: yield enc except: continue u.msr(GXF_CONFIG_EL12, 0) u.msr(SPRR_CONFIG_EL12, 0) u.msr(GXF_CONFIG_EL1, 0) u.msr(SPRR_CONFIG_EL1, 0) baseline = set(test()) for bit in range(64): print() print ("## HACR_EL2[%d]" % bit) u.msr(HACR_EL2, 1<<bit) u.inst(0xd5033fdf) # isb new = set(test()) added = new - baseline removed = baseline - new if added: print("Untraps:") for enc in sorted(added): print(f"{sysreg_name(enc)} ({", ".join(str(i) for i in enc)})") if removed: print("Traps:") for enc in sorted(removed): print(f"{sysreg_name(enc)} ({", ".join(str(i) for i in enc)})") p.set_exc_guard(GUARD.OFF)
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT import sys, pathlib sys.path.append(str(pathlib.Path(__file__).resolve().parents[1])) from m1n1.setup import * from m1n1 import asm code_len = 12 * 16 * 8 + 4 data_len = 8 * 16 * 8 if u.mrs(SPRR_CONFIG_EL1): u.msr(GXF_CONFIG_EL12, 0) u.msr(SPRR_CONFIG_EL12, 0) u.msr(GXF_CONFIG_EL1, 0) u.msr(SPRR_CONFIG_EL1, 0) u.msr(HACR_EL2, 0) hcr = HCR(u.mrs(HCR_EL2)) hcr.TIDCP = 0 hcr.TGE = 0 u.msr(HCR_EL2, hcr.value) u.inst(0xd5033fdf) # isb ACTLR_DEFAULT = 0xc00 ACTLR_AFP = 1 << 5 u.msr(ACTLR_EL1, ACTLR_DEFAULT | ACTLR_AFP) code_buffer = p.malloc(code_len) data_buffer = p.malloc(data_len) template = asm.ARMAsm(""" mov x2, x0 mrs x2, s3_0_c0_c0_0 str x2, [x1], #8 ret """, code_buffer) mov, mrs, st, ret = struct.unpack("4I", template.data) data = [] BAD = 0xacce5515abad1dea AUX = [ ACTLR_EL1, ACTLR_EL2, AFSR0_EL1, AFSR0_EL2, AFSR1_EL1, AFSR1_EL2, AIDR_EL1, AIDR2_EL1, AMAIR_EL1, AMAIR_EL2, APCTL_EL1, APSTS_EL1, ] def test(): u.msr(SPRR_CONFIG_EL1, 1) u.msr(GXF_CONFIG_EL1, 1) u.msr(SPRR_CONFIG_EL12, 1) u.msr(GXF_CONFIG_EL12, 1) for op1 in range(1 << 3): for CRn in (0b1011, 0b1111): mrs0 = mrs | (op1 << 16) | (CRn << 12) insns = [] for CRm in range(1 << 4): for op2 in range(1 << 3): insns.extend((mov, mrs0 | (CRm << 8) | (op2 << 5), st)) insns.append(ret) iface.writemem(code_buffer, struct.pack("<385I", *insns)) p.dc_cvau(code_buffer, code_len) p.ic_ivau(code_buffer, code_len) p.set_exc_guard(GUARD.SILENT | GUARD.SKIP) p.el1_call(code_buffer, BAD, data_buffer) cnt = p.get_exc_count() data = iface.readmem(data_buffer, data_len) d = struct.unpack("<128Q", data) i = 0 for CRm in range(1 << 4): for op2 in range(1 << 3): v = d[i] if v != BAD: yield (3, op1, CRn, CRm, op2) i += 1 for enc in AUX: try: v = u.mrs(enc, call="el1", silent=True) if v != BAD: yield enc except: continue u.msr(GXF_CONFIG_EL12, 0) u.msr(SPRR_CONFIG_EL12, 0) u.msr(GXF_CONFIG_EL1, 0) u.msr(SPRR_CONFIG_EL1, 0) baseline = set(test()) for bit in range(64): print() print ("## HACR_EL2[%d]" % bit) u.msr(HACR_EL2, 1<<bit) u.inst(0xd5033fdf) # isb new = set(test()) added = new - baseline removed = baseline - new if added: print("Untraps:") for enc in sorted(added): print(f"{sysreg_name(enc)} ({', '.join(str(i) for i in enc)})") if removed: print("Traps:") for enc in sorted(removed): print(f"{sysreg_name(enc)} ({', '.join(str(i) for i in enc)})") p.set_exc_guard(GUARD.OFF)
"""Service calling related helpers.""" from __future__ import annotations import asyncio import dataclasses from functools import partial, wraps import logging from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, Dict, Iterable, List, Optional, Set, Tuple, TypedDict, Union, cast, ) import voluptuous as vol from homeassistant.auth.permissions.const import CAT_ENTITIES, POLICY_CONTROL from homeassistant.const import ( ATTR_AREA_ID, ATTR_DEVICE_ID, ATTR_ENTITY_ID, CONF_SERVICE, CONF_SERVICE_DATA, CONF_SERVICE_TEMPLATE, CONF_TARGET, ENTITY_MATCH_ALL, ENTITY_MATCH_NONE, ) import homeassistant.core as ha from homeassistant.exceptions import ( HomeAssistantError, TemplateError, Unauthorized, UnknownUser, ) from homeassistant.helpers import ( area_registry, config_validation as cv, device_registry, entity_registry, template, ) from homeassistant.helpers.typing import ConfigType, HomeAssistantType, TemplateVarsType from homeassistant.loader import ( MAX_LOAD_CONCURRENTLY, Integration, async_get_integration, bind_hass, ) from homeassistant.util.async_ import gather_with_concurrency from homeassistant.util.yaml import load_yaml from homeassistant.util.yaml.loader import JSON_TYPE if TYPE_CHECKING: from homeassistant.helpers.entity import Entity # noqa from homeassistant.helpers.entity_platform import EntityPlatform CONF_SERVICE_ENTITY_ID = "entity_id" CONF_SERVICE_DATA_TEMPLATE = "data_template" _LOGGER = logging.getLogger(__name__) SERVICE_DESCRIPTION_CACHE = "service_description_cache" class ServiceParams(TypedDict): """Type for service call parameters.""" domain: str service: str service_data: Dict[str, Any] target: Optional[Dict] @dataclasses.dataclass class SelectedEntities: """Class to hold the selected entities.""" # Entities that were explicitly mentioned. referenced: Set[str] = dataclasses.field(default_factory=set) # Entities that were referenced via device/area ID. # Should not trigger a warning when they don't exist. indirectly_referenced: Set[str] = dataclasses.field(default_factory=set) # Referenced items that could not be found. missing_devices: Set[str] = dataclasses.field(default_factory=set) missing_areas: Set[str] = dataclasses.field(default_factory=set) def log_missing(self, missing_entities: Set[str]) -> None: """Log about missing items.""" parts = [] for label, items in ( ("areas", self.missing_areas), ("devices", self.missing_devices), ("entities", missing_entities), ): if items: parts.append(f"{label} {", ".join(sorted(items))}") if not parts: return _LOGGER.warning("Unable to find referenced %s", ", ".join(parts)) @bind_hass def call_from_config( hass: HomeAssistantType, config: ConfigType, blocking: bool = False, variables: TemplateVarsType = None, validate_config: bool = True, ) -> None: """Call a service based on a config hash.""" asyncio.run_coroutine_threadsafe( async_call_from_config(hass, config, blocking, variables, validate_config), hass.loop, ).result() @bind_hass async def async_call_from_config( hass: HomeAssistantType, config: ConfigType, blocking: bool = False, variables: TemplateVarsType = None, validate_config: bool = True, context: Optional[ha.Context] = None, ) -> None: """Call a service based on a config hash.""" try: params = async_prepare_call_from_config( hass, config, variables, validate_config ) except HomeAssistantError as ex: if blocking: raise _LOGGER.error(ex) else: await hass.services.async_call(**params, blocking=blocking, context=context) @ha.callback @bind_hass def async_prepare_call_from_config( hass: HomeAssistantType, config: ConfigType, variables: TemplateVarsType = None, validate_config: bool = False, ) -> ServiceParams: """Prepare to call a service based on a config hash.""" if validate_config: try: config = cv.SERVICE_SCHEMA(config) except vol.Invalid as ex: raise HomeAssistantError( f"Invalid config for calling service: {ex}" ) from ex if CONF_SERVICE in config: domain_service = config[CONF_SERVICE] else: domain_service = config[CONF_SERVICE_TEMPLATE] if isinstance(domain_service, template.Template): try: domain_service.hass = hass domain_service = domain_service.async_render(variables) domain_service = cv.service(domain_service) except TemplateError as ex: raise HomeAssistantError( f"Error rendering service name template: {ex}" ) from ex except vol.Invalid as ex: raise HomeAssistantError( f"Template rendered invalid service: {domain_service}" ) from ex domain, service = domain_service.split(".", 1) target = config.get(CONF_TARGET) service_data = {} for conf in [CONF_SERVICE_DATA, CONF_SERVICE_DATA_TEMPLATE]: if conf not in config: continue try: template.attach(hass, config[conf]) service_data.update(template.render_complex(config[conf], variables)) except TemplateError as ex: raise HomeAssistantError(f"Error rendering data template: {ex}") from ex if CONF_SERVICE_ENTITY_ID in config: if target: target[ATTR_ENTITY_ID] = config[CONF_SERVICE_ENTITY_ID] else: target = {ATTR_ENTITY_ID: config[CONF_SERVICE_ENTITY_ID]} return { "domain": domain, "service": service, "service_data": service_data, "target": target, } @bind_hass def extract_entity_ids( hass: HomeAssistantType, service_call: ha.ServiceCall, expand_group: bool = True ) -> Set[str]: """Extract a list of entity ids from a service call. Will convert group entity ids to the entity ids it represents. """ return asyncio.run_coroutine_threadsafe( async_extract_entity_ids(hass, service_call, expand_group), hass.loop ).result() @bind_hass async def async_extract_entities( hass: HomeAssistantType, entities: Iterable[Entity], service_call: ha.ServiceCall, expand_group: bool = True, ) -> List[Entity]: """Extract a list of entity objects from a service call. Will convert group entity ids to the entity ids it represents. """ data_ent_id = service_call.data.get(ATTR_ENTITY_ID) if data_ent_id == ENTITY_MATCH_ALL: return [entity for entity in entities if entity.available] referenced = await async_extract_referenced_entity_ids( hass, service_call, expand_group ) combined = referenced.referenced | referenced.indirectly_referenced found = [] for entity in entities: if entity.entity_id not in combined: continue combined.remove(entity.entity_id) if not entity.available: continue found.append(entity) referenced.log_missing(referenced.referenced & combined) return found @bind_hass async def async_extract_entity_ids( hass: HomeAssistantType, service_call: ha.ServiceCall, expand_group: bool = True ) -> Set[str]: """Extract a set of entity ids from a service call. Will convert group entity ids to the entity ids it represents. """ referenced = await async_extract_referenced_entity_ids( hass, service_call, expand_group ) return referenced.referenced | referenced.indirectly_referenced @bind_hass async def async_extract_referenced_entity_ids( hass: HomeAssistantType, service_call: ha.ServiceCall, expand_group: bool = True ) -> SelectedEntities: """Extract referenced entity IDs from a service call.""" entity_ids = service_call.data.get(ATTR_ENTITY_ID) device_ids = service_call.data.get(ATTR_DEVICE_ID) area_ids = service_call.data.get(ATTR_AREA_ID) selects_entity_ids = entity_ids not in (None, ENTITY_MATCH_NONE) selects_device_ids = device_ids not in (None, ENTITY_MATCH_NONE) selects_area_ids = area_ids not in (None, ENTITY_MATCH_NONE) selected = SelectedEntities() if not selects_entity_ids and not selects_device_ids and not selects_area_ids: return selected if selects_entity_ids: assert entity_ids is not None # Entity ID attr can be a list or a string if isinstance(entity_ids, str): entity_ids = [entity_ids] if expand_group: entity_ids = hass.components.group.expand_entity_ids(entity_ids) selected.referenced.update(entity_ids) if not selects_device_ids and not selects_area_ids: return selected area_reg, dev_reg, ent_reg = cast( Tuple[ area_registry.AreaRegistry, device_registry.DeviceRegistry, entity_registry.EntityRegistry, ], await asyncio.gather( area_registry.async_get_registry(hass), device_registry.async_get_registry(hass), entity_registry.async_get_registry(hass), ), ) picked_devices = set() if selects_device_ids: if isinstance(device_ids, str): picked_devices = {device_ids} else: assert isinstance(device_ids, list) picked_devices = set(device_ids) for device_id in picked_devices: if device_id not in dev_reg.devices: selected.missing_devices.add(device_id) if selects_area_ids: assert area_ids is not None if isinstance(area_ids, str): area_lookup = {area_ids} else: area_lookup = set(area_ids) for area_id in area_lookup: if area_id not in area_reg.areas: selected.missing_areas.add(area_id) continue # Find entities tied to an area for entity_entry in ent_reg.entities.values(): if entity_entry.area_id in area_lookup: selected.indirectly_referenced.add(entity_entry.entity_id) # Find devices for this area for device_entry in dev_reg.devices.values(): if device_entry.area_id in area_lookup: picked_devices.add(device_entry.id) if not picked_devices: return selected for entity_entry in ent_reg.entities.values(): if not entity_entry.area_id and entity_entry.device_id in picked_devices: selected.indirectly_referenced.add(entity_entry.entity_id) return selected def _load_services_file(hass: HomeAssistantType, integration: Integration) -> JSON_TYPE: """Load services file for an integration.""" try: return load_yaml(str(integration.file_path / "services.yaml")) except FileNotFoundError: _LOGGER.warning( "Unable to find services.yaml for the %s integration", integration.domain ) return {} except HomeAssistantError: _LOGGER.warning( "Unable to parse services.yaml for the %s integration", integration.domain ) return {} def _load_services_files( hass: HomeAssistantType, integrations: Iterable[Integration] ) -> List[JSON_TYPE]: """Load service files for multiple intergrations.""" return [_load_services_file(hass, integration) for integration in integrations] @bind_hass async def async_get_all_descriptions( hass: HomeAssistantType, ) -> Dict[str, Dict[str, Any]]: """Return descriptions (i.e. user documentation) for all service calls.""" descriptions_cache = hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {}) format_cache_key = "{}.{}".format services = hass.services.async_services() # See if there are new services not seen before. # Any service that we saw before already has an entry in description_cache. missing = set() for domain in services: for service in services[domain]: if format_cache_key(domain, service) not in descriptions_cache: missing.add(domain) break # Files we loaded for missing descriptions loaded = {} if missing: integrations = await gather_with_concurrency( MAX_LOAD_CONCURRENTLY, *(async_get_integration(hass, domain) for domain in missing), ) contents = await hass.async_add_executor_job( _load_services_files, hass, integrations ) for domain, content in zip(missing, contents): loaded[domain] = content # Build response descriptions: Dict[str, Dict[str, Any]] = {} for domain in services: descriptions[domain] = {} for service in services[domain]: cache_key = format_cache_key(domain, service) description = descriptions_cache.get(cache_key) # Cache missing descriptions if description is None: domain_yaml = loaded[domain] yaml_description = domain_yaml.get(service, {}) # type: ignore # Don't warn for missing services, because it triggers false # positives for things like scripts, that register as a service description = { "name": yaml_description.get("name", ""), "description": yaml_description.get("description", ""), "fields": yaml_description.get("fields", {}), } if "target" in yaml_description: description["target"] = yaml_description["target"] descriptions_cache[cache_key] = description descriptions[domain][service] = description return descriptions @ha.callback @bind_hass def async_set_service_schema( hass: HomeAssistantType, domain: str, service: str, schema: Dict[str, Any] ) -> None: """Register a description for a service.""" hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {}) description = { "name": schema.get("name", ""), "description": schema.get("description", ""), "fields": schema.get("fields", {}), } if "target" in schema: description["target"] = schema["target"] hass.data[SERVICE_DESCRIPTION_CACHE][f"{domain}.{service}"] = description @bind_hass async def entity_service_call( hass: HomeAssistantType, platforms: Iterable["EntityPlatform"], func: Union[str, Callable[..., Any]], call: ha.ServiceCall, required_features: Optional[Iterable[int]] = None, ) -> None: """Handle an entity service call. Calls all platforms simultaneously. """ if call.context.user_id: user = await hass.auth.async_get_user(call.context.user_id) if user is None: raise UnknownUser(context=call.context) entity_perms: Optional[ Callable[[str, str], bool] ] = user.permissions.check_entity else: entity_perms = None target_all_entities = call.data.get(ATTR_ENTITY_ID) == ENTITY_MATCH_ALL if target_all_entities: referenced: Optional[SelectedEntities] = None all_referenced: Optional[Set[str]] = None else: # A set of entities we're trying to target. referenced = await async_extract_referenced_entity_ids(hass, call, True) all_referenced = referenced.referenced | referenced.indirectly_referenced # If the service function is a string, we'll pass it the service call data if isinstance(func, str): data: Union[Dict, ha.ServiceCall] = { key: val for key, val in call.data.items() if key not in cv.ENTITY_SERVICE_FIELDS } # If the service function is not a string, we pass the service call else: data = call # Check the permissions # A list with entities to call the service on. entity_candidates: List["Entity"] = [] if entity_perms is None: for platform in platforms: if target_all_entities: entity_candidates.extend(platform.entities.values()) else: assert all_referenced is not None entity_candidates.extend( [ entity for entity in platform.entities.values() if entity.entity_id in all_referenced ] ) elif target_all_entities: # If we target all entities, we will select all entities the user # is allowed to control. for platform in platforms: entity_candidates.extend( [ entity for entity in platform.entities.values() if entity_perms(entity.entity_id, POLICY_CONTROL) ] ) else: assert all_referenced is not None for platform in platforms: platform_entities = [] for entity in platform.entities.values(): if entity.entity_id not in all_referenced: continue if not entity_perms(entity.entity_id, POLICY_CONTROL): raise Unauthorized( context=call.context, entity_id=entity.entity_id, permission=POLICY_CONTROL, ) platform_entities.append(entity) entity_candidates.extend(platform_entities) if not target_all_entities: assert referenced is not None # Only report on explicit referenced entities missing = set(referenced.referenced) for entity in entity_candidates: missing.discard(entity.entity_id) referenced.log_missing(missing) entities = [] for entity in entity_candidates: if not entity.available: continue # Skip entities that don't have the required feature. if required_features is not None and ( entity.supported_features is None or not any( entity.supported_features & feature_set == feature_set for feature_set in required_features ) ): continue entities.append(entity) if not entities: return done, pending = await asyncio.wait( [ asyncio.create_task( entity.async_request_call( _handle_entity_call(hass, entity, func, data, call.context) ) ) for entity in entities ] ) assert not pending for future in done: future.result() # pop exception if have tasks = [] for entity in entities: if not entity.should_poll: continue # Context expires if the turn on commands took a long time. # Set context again so it's there when we update entity.async_set_context(call.context) tasks.append(asyncio.create_task(entity.async_update_ha_state(True))) if tasks: done, pending = await asyncio.wait(tasks) assert not pending for future in done: future.result() # pop exception if have async def _handle_entity_call( hass: HomeAssistantType, entity: Entity, func: Union[str, Callable[..., Any]], data: Union[Dict, ha.ServiceCall], context: ha.Context, ) -> None: """Handle calling service method.""" entity.async_set_context(context) if isinstance(func, str): result = hass.async_run_job(partial(getattr(entity, func), **data)) # type: ignore else: result = hass.async_run_job(func, entity, data) # Guard because callback functions do not return a task when passed to async_run_job. if result is not None: await result if asyncio.iscoroutine(result): _LOGGER.error( "Service %s for %s incorrectly returns a coroutine object. Await result instead in service handler. Report bug to integration author", func, entity.entity_id, ) await result # type: ignore @bind_hass @ha.callback def async_register_admin_service( hass: HomeAssistantType, domain: str, service: str, service_func: Callable[[ha.ServiceCall], Optional[Awaitable]], schema: vol.Schema = vol.Schema({}, extra=vol.PREVENT_EXTRA), ) -> None: """Register a service that requires admin access.""" @wraps(service_func) async def admin_handler(call: ha.ServiceCall) -> None: if call.context.user_id: user = await hass.auth.async_get_user(call.context.user_id) if user is None: raise UnknownUser(context=call.context) if not user.is_admin: raise Unauthorized(context=call.context) result = hass.async_run_job(service_func, call) if result is not None: await result hass.services.async_register(domain, service, admin_handler, schema) @bind_hass @ha.callback def verify_domain_control( hass: HomeAssistantType, domain: str ) -> Callable[[Callable[[ha.ServiceCall], Any]], Callable[[ha.ServiceCall], Any]]: """Ensure permission to access any entity under domain in service call.""" def decorator( service_handler: Callable[[ha.ServiceCall], Any] ) -> Callable[[ha.ServiceCall], Any]: """Decorate.""" if not asyncio.iscoroutinefunction(service_handler): raise HomeAssistantError("Can only decorate async functions.") async def check_permissions(call: ha.ServiceCall) -> Any: """Check user permission and raise before call if unauthorized.""" if not call.context.user_id: return await service_handler(call) user = await hass.auth.async_get_user(call.context.user_id) if user is None: raise UnknownUser( context=call.context, permission=POLICY_CONTROL, user_id=call.context.user_id, ) reg = await hass.helpers.entity_registry.async_get_registry() authorized = False for entity in reg.entities.values(): if entity.platform != domain: continue if user.permissions.check_entity(entity.entity_id, POLICY_CONTROL): authorized = True break if not authorized: raise Unauthorized( context=call.context, permission=POLICY_CONTROL, user_id=call.context.user_id, perm_category=CAT_ENTITIES, ) return await service_handler(call) return check_permissions return decorator
"""Service calling related helpers.""" from __future__ import annotations import asyncio import dataclasses from functools import partial, wraps import logging from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, Dict, Iterable, List, Optional, Set, Tuple, TypedDict, Union, cast, ) import voluptuous as vol from homeassistant.auth.permissions.const import CAT_ENTITIES, POLICY_CONTROL from homeassistant.const import ( ATTR_AREA_ID, ATTR_DEVICE_ID, ATTR_ENTITY_ID, CONF_SERVICE, CONF_SERVICE_DATA, CONF_SERVICE_TEMPLATE, CONF_TARGET, ENTITY_MATCH_ALL, ENTITY_MATCH_NONE, ) import homeassistant.core as ha from homeassistant.exceptions import ( HomeAssistantError, TemplateError, Unauthorized, UnknownUser, ) from homeassistant.helpers import ( area_registry, config_validation as cv, device_registry, entity_registry, template, ) from homeassistant.helpers.typing import ConfigType, HomeAssistantType, TemplateVarsType from homeassistant.loader import ( MAX_LOAD_CONCURRENTLY, Integration, async_get_integration, bind_hass, ) from homeassistant.util.async_ import gather_with_concurrency from homeassistant.util.yaml import load_yaml from homeassistant.util.yaml.loader import JSON_TYPE if TYPE_CHECKING: from homeassistant.helpers.entity import Entity # noqa from homeassistant.helpers.entity_platform import EntityPlatform CONF_SERVICE_ENTITY_ID = "entity_id" CONF_SERVICE_DATA_TEMPLATE = "data_template" _LOGGER = logging.getLogger(__name__) SERVICE_DESCRIPTION_CACHE = "service_description_cache" class ServiceParams(TypedDict): """Type for service call parameters.""" domain: str service: str service_data: Dict[str, Any] target: Optional[Dict] @dataclasses.dataclass class SelectedEntities: """Class to hold the selected entities.""" # Entities that were explicitly mentioned. referenced: Set[str] = dataclasses.field(default_factory=set) # Entities that were referenced via device/area ID. # Should not trigger a warning when they don't exist. indirectly_referenced: Set[str] = dataclasses.field(default_factory=set) # Referenced items that could not be found. missing_devices: Set[str] = dataclasses.field(default_factory=set) missing_areas: Set[str] = dataclasses.field(default_factory=set) def log_missing(self, missing_entities: Set[str]) -> None: """Log about missing items.""" parts = [] for label, items in ( ("areas", self.missing_areas), ("devices", self.missing_devices), ("entities", missing_entities), ): if items: parts.append(f"{label} {', '.join(sorted(items))}") if not parts: return _LOGGER.warning("Unable to find referenced %s", ", ".join(parts)) @bind_hass def call_from_config( hass: HomeAssistantType, config: ConfigType, blocking: bool = False, variables: TemplateVarsType = None, validate_config: bool = True, ) -> None: """Call a service based on a config hash.""" asyncio.run_coroutine_threadsafe( async_call_from_config(hass, config, blocking, variables, validate_config), hass.loop, ).result() @bind_hass async def async_call_from_config( hass: HomeAssistantType, config: ConfigType, blocking: bool = False, variables: TemplateVarsType = None, validate_config: bool = True, context: Optional[ha.Context] = None, ) -> None: """Call a service based on a config hash.""" try: params = async_prepare_call_from_config( hass, config, variables, validate_config ) except HomeAssistantError as ex: if blocking: raise _LOGGER.error(ex) else: await hass.services.async_call(**params, blocking=blocking, context=context) @ha.callback @bind_hass def async_prepare_call_from_config( hass: HomeAssistantType, config: ConfigType, variables: TemplateVarsType = None, validate_config: bool = False, ) -> ServiceParams: """Prepare to call a service based on a config hash.""" if validate_config: try: config = cv.SERVICE_SCHEMA(config) except vol.Invalid as ex: raise HomeAssistantError( f"Invalid config for calling service: {ex}" ) from ex if CONF_SERVICE in config: domain_service = config[CONF_SERVICE] else: domain_service = config[CONF_SERVICE_TEMPLATE] if isinstance(domain_service, template.Template): try: domain_service.hass = hass domain_service = domain_service.async_render(variables) domain_service = cv.service(domain_service) except TemplateError as ex: raise HomeAssistantError( f"Error rendering service name template: {ex}" ) from ex except vol.Invalid as ex: raise HomeAssistantError( f"Template rendered invalid service: {domain_service}" ) from ex domain, service = domain_service.split(".", 1) target = config.get(CONF_TARGET) service_data = {} for conf in [CONF_SERVICE_DATA, CONF_SERVICE_DATA_TEMPLATE]: if conf not in config: continue try: template.attach(hass, config[conf]) service_data.update(template.render_complex(config[conf], variables)) except TemplateError as ex: raise HomeAssistantError(f"Error rendering data template: {ex}") from ex if CONF_SERVICE_ENTITY_ID in config: if target: target[ATTR_ENTITY_ID] = config[CONF_SERVICE_ENTITY_ID] else: target = {ATTR_ENTITY_ID: config[CONF_SERVICE_ENTITY_ID]} return { "domain": domain, "service": service, "service_data": service_data, "target": target, } @bind_hass def extract_entity_ids( hass: HomeAssistantType, service_call: ha.ServiceCall, expand_group: bool = True ) -> Set[str]: """Extract a list of entity ids from a service call. Will convert group entity ids to the entity ids it represents. """ return asyncio.run_coroutine_threadsafe( async_extract_entity_ids(hass, service_call, expand_group), hass.loop ).result() @bind_hass async def async_extract_entities( hass: HomeAssistantType, entities: Iterable[Entity], service_call: ha.ServiceCall, expand_group: bool = True, ) -> List[Entity]: """Extract a list of entity objects from a service call. Will convert group entity ids to the entity ids it represents. """ data_ent_id = service_call.data.get(ATTR_ENTITY_ID) if data_ent_id == ENTITY_MATCH_ALL: return [entity for entity in entities if entity.available] referenced = await async_extract_referenced_entity_ids( hass, service_call, expand_group ) combined = referenced.referenced | referenced.indirectly_referenced found = [] for entity in entities: if entity.entity_id not in combined: continue combined.remove(entity.entity_id) if not entity.available: continue found.append(entity) referenced.log_missing(referenced.referenced & combined) return found @bind_hass async def async_extract_entity_ids( hass: HomeAssistantType, service_call: ha.ServiceCall, expand_group: bool = True ) -> Set[str]: """Extract a set of entity ids from a service call. Will convert group entity ids to the entity ids it represents. """ referenced = await async_extract_referenced_entity_ids( hass, service_call, expand_group ) return referenced.referenced | referenced.indirectly_referenced @bind_hass async def async_extract_referenced_entity_ids( hass: HomeAssistantType, service_call: ha.ServiceCall, expand_group: bool = True ) -> SelectedEntities: """Extract referenced entity IDs from a service call.""" entity_ids = service_call.data.get(ATTR_ENTITY_ID) device_ids = service_call.data.get(ATTR_DEVICE_ID) area_ids = service_call.data.get(ATTR_AREA_ID) selects_entity_ids = entity_ids not in (None, ENTITY_MATCH_NONE) selects_device_ids = device_ids not in (None, ENTITY_MATCH_NONE) selects_area_ids = area_ids not in (None, ENTITY_MATCH_NONE) selected = SelectedEntities() if not selects_entity_ids and not selects_device_ids and not selects_area_ids: return selected if selects_entity_ids: assert entity_ids is not None # Entity ID attr can be a list or a string if isinstance(entity_ids, str): entity_ids = [entity_ids] if expand_group: entity_ids = hass.components.group.expand_entity_ids(entity_ids) selected.referenced.update(entity_ids) if not selects_device_ids and not selects_area_ids: return selected area_reg, dev_reg, ent_reg = cast( Tuple[ area_registry.AreaRegistry, device_registry.DeviceRegistry, entity_registry.EntityRegistry, ], await asyncio.gather( area_registry.async_get_registry(hass), device_registry.async_get_registry(hass), entity_registry.async_get_registry(hass), ), ) picked_devices = set() if selects_device_ids: if isinstance(device_ids, str): picked_devices = {device_ids} else: assert isinstance(device_ids, list) picked_devices = set(device_ids) for device_id in picked_devices: if device_id not in dev_reg.devices: selected.missing_devices.add(device_id) if selects_area_ids: assert area_ids is not None if isinstance(area_ids, str): area_lookup = {area_ids} else: area_lookup = set(area_ids) for area_id in area_lookup: if area_id not in area_reg.areas: selected.missing_areas.add(area_id) continue # Find entities tied to an area for entity_entry in ent_reg.entities.values(): if entity_entry.area_id in area_lookup: selected.indirectly_referenced.add(entity_entry.entity_id) # Find devices for this area for device_entry in dev_reg.devices.values(): if device_entry.area_id in area_lookup: picked_devices.add(device_entry.id) if not picked_devices: return selected for entity_entry in ent_reg.entities.values(): if not entity_entry.area_id and entity_entry.device_id in picked_devices: selected.indirectly_referenced.add(entity_entry.entity_id) return selected def _load_services_file(hass: HomeAssistantType, integration: Integration) -> JSON_TYPE: """Load services file for an integration.""" try: return load_yaml(str(integration.file_path / "services.yaml")) except FileNotFoundError: _LOGGER.warning( "Unable to find services.yaml for the %s integration", integration.domain ) return {} except HomeAssistantError: _LOGGER.warning( "Unable to parse services.yaml for the %s integration", integration.domain ) return {} def _load_services_files( hass: HomeAssistantType, integrations: Iterable[Integration] ) -> List[JSON_TYPE]: """Load service files for multiple intergrations.""" return [_load_services_file(hass, integration) for integration in integrations] @bind_hass async def async_get_all_descriptions( hass: HomeAssistantType, ) -> Dict[str, Dict[str, Any]]: """Return descriptions (i.e. user documentation) for all service calls.""" descriptions_cache = hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {}) format_cache_key = "{}.{}".format services = hass.services.async_services() # See if there are new services not seen before. # Any service that we saw before already has an entry in description_cache. missing = set() for domain in services: for service in services[domain]: if format_cache_key(domain, service) not in descriptions_cache: missing.add(domain) break # Files we loaded for missing descriptions loaded = {} if missing: integrations = await gather_with_concurrency( MAX_LOAD_CONCURRENTLY, *(async_get_integration(hass, domain) for domain in missing), ) contents = await hass.async_add_executor_job( _load_services_files, hass, integrations ) for domain, content in zip(missing, contents): loaded[domain] = content # Build response descriptions: Dict[str, Dict[str, Any]] = {} for domain in services: descriptions[domain] = {} for service in services[domain]: cache_key = format_cache_key(domain, service) description = descriptions_cache.get(cache_key) # Cache missing descriptions if description is None: domain_yaml = loaded[domain] yaml_description = domain_yaml.get(service, {}) # type: ignore # Don't warn for missing services, because it triggers false # positives for things like scripts, that register as a service description = { "name": yaml_description.get("name", ""), "description": yaml_description.get("description", ""), "fields": yaml_description.get("fields", {}), } if "target" in yaml_description: description["target"] = yaml_description["target"] descriptions_cache[cache_key] = description descriptions[domain][service] = description return descriptions @ha.callback @bind_hass def async_set_service_schema( hass: HomeAssistantType, domain: str, service: str, schema: Dict[str, Any] ) -> None: """Register a description for a service.""" hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {}) description = { "name": schema.get("name", ""), "description": schema.get("description", ""), "fields": schema.get("fields", {}), } if "target" in schema: description["target"] = schema["target"] hass.data[SERVICE_DESCRIPTION_CACHE][f"{domain}.{service}"] = description @bind_hass async def entity_service_call( hass: HomeAssistantType, platforms: Iterable["EntityPlatform"], func: Union[str, Callable[..., Any]], call: ha.ServiceCall, required_features: Optional[Iterable[int]] = None, ) -> None: """Handle an entity service call. Calls all platforms simultaneously. """ if call.context.user_id: user = await hass.auth.async_get_user(call.context.user_id) if user is None: raise UnknownUser(context=call.context) entity_perms: Optional[ Callable[[str, str], bool] ] = user.permissions.check_entity else: entity_perms = None target_all_entities = call.data.get(ATTR_ENTITY_ID) == ENTITY_MATCH_ALL if target_all_entities: referenced: Optional[SelectedEntities] = None all_referenced: Optional[Set[str]] = None else: # A set of entities we're trying to target. referenced = await async_extract_referenced_entity_ids(hass, call, True) all_referenced = referenced.referenced | referenced.indirectly_referenced # If the service function is a string, we'll pass it the service call data if isinstance(func, str): data: Union[Dict, ha.ServiceCall] = { key: val for key, val in call.data.items() if key not in cv.ENTITY_SERVICE_FIELDS } # If the service function is not a string, we pass the service call else: data = call # Check the permissions # A list with entities to call the service on. entity_candidates: List["Entity"] = [] if entity_perms is None: for platform in platforms: if target_all_entities: entity_candidates.extend(platform.entities.values()) else: assert all_referenced is not None entity_candidates.extend( [ entity for entity in platform.entities.values() if entity.entity_id in all_referenced ] ) elif target_all_entities: # If we target all entities, we will select all entities the user # is allowed to control. for platform in platforms: entity_candidates.extend( [ entity for entity in platform.entities.values() if entity_perms(entity.entity_id, POLICY_CONTROL) ] ) else: assert all_referenced is not None for platform in platforms: platform_entities = [] for entity in platform.entities.values(): if entity.entity_id not in all_referenced: continue if not entity_perms(entity.entity_id, POLICY_CONTROL): raise Unauthorized( context=call.context, entity_id=entity.entity_id, permission=POLICY_CONTROL, ) platform_entities.append(entity) entity_candidates.extend(platform_entities) if not target_all_entities: assert referenced is not None # Only report on explicit referenced entities missing = set(referenced.referenced) for entity in entity_candidates: missing.discard(entity.entity_id) referenced.log_missing(missing) entities = [] for entity in entity_candidates: if not entity.available: continue # Skip entities that don't have the required feature. if required_features is not None and ( entity.supported_features is None or not any( entity.supported_features & feature_set == feature_set for feature_set in required_features ) ): continue entities.append(entity) if not entities: return done, pending = await asyncio.wait( [ asyncio.create_task( entity.async_request_call( _handle_entity_call(hass, entity, func, data, call.context) ) ) for entity in entities ] ) assert not pending for future in done: future.result() # pop exception if have tasks = [] for entity in entities: if not entity.should_poll: continue # Context expires if the turn on commands took a long time. # Set context again so it's there when we update entity.async_set_context(call.context) tasks.append(asyncio.create_task(entity.async_update_ha_state(True))) if tasks: done, pending = await asyncio.wait(tasks) assert not pending for future in done: future.result() # pop exception if have async def _handle_entity_call( hass: HomeAssistantType, entity: Entity, func: Union[str, Callable[..., Any]], data: Union[Dict, ha.ServiceCall], context: ha.Context, ) -> None: """Handle calling service method.""" entity.async_set_context(context) if isinstance(func, str): result = hass.async_run_job(partial(getattr(entity, func), **data)) # type: ignore else: result = hass.async_run_job(func, entity, data) # Guard because callback functions do not return a task when passed to async_run_job. if result is not None: await result if asyncio.iscoroutine(result): _LOGGER.error( "Service %s for %s incorrectly returns a coroutine object. Await result instead in service handler. Report bug to integration author", func, entity.entity_id, ) await result # type: ignore @bind_hass @ha.callback def async_register_admin_service( hass: HomeAssistantType, domain: str, service: str, service_func: Callable[[ha.ServiceCall], Optional[Awaitable]], schema: vol.Schema = vol.Schema({}, extra=vol.PREVENT_EXTRA), ) -> None: """Register a service that requires admin access.""" @wraps(service_func) async def admin_handler(call: ha.ServiceCall) -> None: if call.context.user_id: user = await hass.auth.async_get_user(call.context.user_id) if user is None: raise UnknownUser(context=call.context) if not user.is_admin: raise Unauthorized(context=call.context) result = hass.async_run_job(service_func, call) if result is not None: await result hass.services.async_register(domain, service, admin_handler, schema) @bind_hass @ha.callback def verify_domain_control( hass: HomeAssistantType, domain: str ) -> Callable[[Callable[[ha.ServiceCall], Any]], Callable[[ha.ServiceCall], Any]]: """Ensure permission to access any entity under domain in service call.""" def decorator( service_handler: Callable[[ha.ServiceCall], Any] ) -> Callable[[ha.ServiceCall], Any]: """Decorate.""" if not asyncio.iscoroutinefunction(service_handler): raise HomeAssistantError("Can only decorate async functions.") async def check_permissions(call: ha.ServiceCall) -> Any: """Check user permission and raise before call if unauthorized.""" if not call.context.user_id: return await service_handler(call) user = await hass.auth.async_get_user(call.context.user_id) if user is None: raise UnknownUser( context=call.context, permission=POLICY_CONTROL, user_id=call.context.user_id, ) reg = await hass.helpers.entity_registry.async_get_registry() authorized = False for entity in reg.entities.values(): if entity.platform != domain: continue if user.permissions.check_entity(entity.entity_id, POLICY_CONTROL): authorized = True break if not authorized: raise Unauthorized( context=call.context, permission=POLICY_CONTROL, user_id=call.context.user_id, perm_category=CAT_ENTITIES, ) return await service_handler(call) return check_permissions return decorator
import json import pathlib import re import time import bs4 import os import data_models import requests from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec GOOGLE_CHROME_PATH = os.environ.get('GOOGLE_CHROME_BIN') CHROMEDRIVER_PATH = os.environ.get('CHROMEDRIVER_PATH') chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-dev-shm-usage') browser = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options) def get_program_info(url: str): browser.get(url) el = browser.find_element_by_id('student-status') for option in el.find_elements_by_tag_name('option'): if option.text == 'Attending / Recently Graduated from a Canadian Secondary School': option.click() # select() in earlier versions of webdriver break el = browser.find_element_by_id('provinces') for option in el.find_elements_by_tag_name('option'): if option.text == 'Ontario': option.click() # select() in earlier versions of webdriver break element = WebDriverWait(browser, 10).until( ec.presence_of_element_located( (By.ID, 'submit')) ) browser.execute_script("arguments[0].scrollIntoView();", element) element.click() browser.implicitly_wait(1) prog_info = browser.find_element_by_id('program-1').text prog_infos = prog_info.split('\n') # print(prog_infos) name = prog_infos[0].split('Program ')[1].strip() province = prog_infos[1].split('Province')[1].strip() ouac_code = prog_infos[2].split('OUAC Code: ')[1].strip() degrees = [degree.strip() for degree in prog_infos[3].split('Degrees ')[1].split(',')] coop_option = False if 'no' in prog_infos[4].split('Co-op/Internship: ')[ 1].strip().lower() else True req_courses = browser.find_element_by_xpath( '//*[@id="program-1"]/table/tbody/tr[8]/td/ul[1]').text.strip().split( '\n') try: admission_range = browser.find_element_by_xpath( '//*[@id="program-1"]/table/tbody/tr[12]/td').text.strip() except: admission_range = browser.find_element_by_xpath( '//*[@id="program-1"]/table/tbody/tr[11]/td').text.strip() try: enrolment = int(re.findall(r'\d+', browser.find_element_by_xpath( '//*[@id="program-1"]/table/tbody/tr[16]/td').text.strip())[0]) except: enrolment = int(re.findall(r'\d+', browser.find_element_by_xpath( '//*[@id="program-1"]/table/tbody/tr[15]/td').text.strip())[0]) return data_models.ScrapingData(name, province, 'McMaster University', ouac_code, degrees, coop_option, req_courses, admission_range, enrolment) def remove_consecutive_duplicates(s): if len(s)<2: return s if s[0] == '_' and s[0]==s[1]: return remove_consecutive_duplicates(s[1:]) else: return s[0]+remove_consecutive_duplicates(s[1:]) def legal_name(name: str) -> str: valids = list("abcdefghijklmnopqrstuvwxyz1234567890") name_to_return = [] for char in name: if char in valids: name_to_return.append(char) else: name_to_return.append('_') name = "".join(name_to_return) return remove_consecutive_duplicates(name) def fetch_programs(url: str): programs = requests.get(url).text soup = bs4.BeautifulSoup(programs, features="html.parser") program_divs = soup.find_all("div", {"class": "row row-eq-height center-content"})[0].find_all('div') programs = [] for program_div in program_divs: try: time.sleep(1) programs.append(data_models.Program( program_div.find('a').text, program_div.find('a').get('href'), get_program_info(program_div.find('a').get('href')) )) except Exception as e: print(f'Error on website: {program_div.find('a').get('href')}') return programs def mcmaster_programs(): return fetch_programs('https://future.mcmaster.ca/programs/') # progs = mcmaster_programs() # for prog in progs: # output_file = f'programs/{legal_name(prog.name.lower())}_program.json' # with open(output_file, 'w') as outfile: # json.dump(prog.__dict__(), outfile) path = pathlib.Path('programs') files = os.listdir(path) for file in files: os.rename(f'{path}/{file}', f'{path}/{file.replace('_program', '')}')
import json import pathlib import re import time import bs4 import os import data_models import requests from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec GOOGLE_CHROME_PATH = os.environ.get('GOOGLE_CHROME_BIN') CHROMEDRIVER_PATH = os.environ.get('CHROMEDRIVER_PATH') chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-dev-shm-usage') browser = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options) def get_program_info(url: str): browser.get(url) el = browser.find_element_by_id('student-status') for option in el.find_elements_by_tag_name('option'): if option.text == 'Attending / Recently Graduated from a Canadian Secondary School': option.click() # select() in earlier versions of webdriver break el = browser.find_element_by_id('provinces') for option in el.find_elements_by_tag_name('option'): if option.text == 'Ontario': option.click() # select() in earlier versions of webdriver break element = WebDriverWait(browser, 10).until( ec.presence_of_element_located( (By.ID, 'submit')) ) browser.execute_script("arguments[0].scrollIntoView();", element) element.click() browser.implicitly_wait(1) prog_info = browser.find_element_by_id('program-1').text prog_infos = prog_info.split('\n') # print(prog_infos) name = prog_infos[0].split('Program ')[1].strip() province = prog_infos[1].split('Province')[1].strip() ouac_code = prog_infos[2].split('OUAC Code: ')[1].strip() degrees = [degree.strip() for degree in prog_infos[3].split('Degrees ')[1].split(',')] coop_option = False if 'no' in prog_infos[4].split('Co-op/Internship: ')[ 1].strip().lower() else True req_courses = browser.find_element_by_xpath( '//*[@id="program-1"]/table/tbody/tr[8]/td/ul[1]').text.strip().split( '\n') try: admission_range = browser.find_element_by_xpath( '//*[@id="program-1"]/table/tbody/tr[12]/td').text.strip() except: admission_range = browser.find_element_by_xpath( '//*[@id="program-1"]/table/tbody/tr[11]/td').text.strip() try: enrolment = int(re.findall(r'\d+', browser.find_element_by_xpath( '//*[@id="program-1"]/table/tbody/tr[16]/td').text.strip())[0]) except: enrolment = int(re.findall(r'\d+', browser.find_element_by_xpath( '//*[@id="program-1"]/table/tbody/tr[15]/td').text.strip())[0]) return data_models.ScrapingData(name, province, 'McMaster University', ouac_code, degrees, coop_option, req_courses, admission_range, enrolment) def remove_consecutive_duplicates(s): if len(s)<2: return s if s[0] == '_' and s[0]==s[1]: return remove_consecutive_duplicates(s[1:]) else: return s[0]+remove_consecutive_duplicates(s[1:]) def legal_name(name: str) -> str: valids = list("abcdefghijklmnopqrstuvwxyz1234567890") name_to_return = [] for char in name: if char in valids: name_to_return.append(char) else: name_to_return.append('_') name = "".join(name_to_return) return remove_consecutive_duplicates(name) def fetch_programs(url: str): programs = requests.get(url).text soup = bs4.BeautifulSoup(programs, features="html.parser") program_divs = soup.find_all("div", {"class": "row row-eq-height center-content"})[0].find_all('div') programs = [] for program_div in program_divs: try: time.sleep(1) programs.append(data_models.Program( program_div.find('a').text, program_div.find('a').get('href'), get_program_info(program_div.find('a').get('href')) )) except Exception as e: print(f'Error on website: {program_div.find("a").get("href")}') return programs def mcmaster_programs(): return fetch_programs('https://future.mcmaster.ca/programs/') # progs = mcmaster_programs() # for prog in progs: # output_file = f'programs/{legal_name(prog.name.lower())}_program.json' # with open(output_file, 'w') as outfile: # json.dump(prog.__dict__(), outfile) path = pathlib.Path('programs') files = os.listdir(path) for file in files: os.rename(f'{path}/{file}', f'{path}/{file.replace("_program", "")}')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @trojanzhex import re import pyrogram from pyrogram import ( filters, Client ) from pyrogram.types import ( InlineKeyboardButton, InlineKeyboardMarkup, Message, CallbackQuery ) from bot import Bot from script import script from database.mdb import searchquery from plugins.channel import deleteallfilters from config import AUTH_USERS BUTTONS = {} @Client.on_message(filters.group & filters.text) async def filter(client: Bot, message: Message): if re.findall("((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text): return if 2 < len(message.text) < 50: btn = [] group_id = message.chat.id name = message.text filenames, links = await searchquery(group_id, name) if filenames and links: for filename, link in zip(filenames, links): btn.append( [InlineKeyboardButton(text=f"{filename}",url=f"{link}")] ) else: return if not btn: return if len(btn) > 10: btns = list(split_list(btn, 10)) keyword = f"{message.chat.id}-{message.message_id}" BUTTONS[keyword] = { "total" : len(btns), "buttons" : btns } else: buttons = btn buttons.append( [InlineKeyboardButton(text="📃 Pages 1/1",callback_data="pages")] ) await message.reply_text( f"<b> Here is the result for {message.text}</b>", reply_markup=InlineKeyboardMarkup(buttons) ) return data = BUTTONS[keyword] buttons = data['buttons'][0].copy() buttons.append( [InlineKeyboardButton(text="ඊළඟ ⏩",callback_data=f"next_0_{keyword}")] ) buttons.append( [InlineKeyboardButton(text=f"📃 Pages 1/{data["total"]}",callback_data="pages")] ) await message.reply_text( f"<b> Here is the result for {message.text}</b>", reply_markup=InlineKeyboardMarkup(buttons) ) @Client.on_callback_query() async def cb_handler(client: Bot, query: CallbackQuery): clicked = query.from_user.id typed = query.message.reply_to_message.from_user.id if (clicked == typed) or (clicked in AUTH_USERS): if query.data.startswith("next"): await query.answer() ident, index, keyword = query.data.split("_") try: data = BUTTONS[keyword] except KeyError: await query.answer("You are using this for one of my old message, please send the request again.",show_alert=True) return if int(index) == int(data["total"]) - 2: buttons = data['buttons'][int(index)+1].copy() buttons.append( [InlineKeyboardButton("⏪ ආපහු", callback_data=f"back_{int(index)+1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data["total"]}", callback_data="pages")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return else: buttons = data['buttons'][int(index)+1].copy() buttons.append( [InlineKeyboardButton("⏪ ආපහු", callback_data=f"back_{int(index)+1}_{keyword}"),InlineKeyboardButton("NEXT ⏩", callback_data=f"next_{int(index)+1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data["total"]}", callback_data="pages")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return elif query.data.startswith("back"): await query.answer() ident, index, keyword = query.data.split("_") try: data = BUTTONS[keyword] except KeyError: await query.answer("You are using this for one of my old message, please send the request again.",show_alert=True) return if int(index) == 1: buttons = data['buttons'][int(index)-1].copy() buttons.append( [InlineKeyboardButton("ඊළඟ ⏩", callback_data=f"next_{int(index)-1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)}/{data["total"]}", callback_data="pages")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return else: buttons = data['buttons'][int(index)-1].copy() buttons.append( [InlineKeyboardButton("⏪ ආපහු", callback_data=f"back_{int(index)-1}_{keyword}"),InlineKeyboardButton("NEXT ⏩", callback_data=f"next_{int(index)-1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)}/{data["total"]}", callback_data="pages")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return elif query.data == "pages": await query.answer() elif query.data == "start_data": await query.answer() keyboard = InlineKeyboardMarkup([ [InlineKeyboardButton("HELP", callback_data="help_data"), InlineKeyboardButton("ABOUT", callback_data="about_data")], [InlineKeyboardButton("⭕️ JOIN OUR group ⭕️", url="https://t.me/joinchat/Q1uroGQ645U1OTg1")] ]) await query.message.edit_text( script.START_MSG.format(query.from_user.mention), reply_markup=keyboard, disable_web_page_preview=True ) elif query.data == "help_data": await query.answer() keyboard = InlineKeyboardMarkup([ [InlineKeyboardButton("BACK", callback_data="start_data"), InlineKeyboardButton("ABOUT", callback_data="about_data")], [InlineKeyboardButton("⭕️ අපේ group එක ⭕️", url="https://t.me/joinchat/Q1uroGQ645U1OTg1")] ]) await query.message.edit_text( script.HELP_MSG, reply_markup=keyboard, disable_web_page_preview=True ) elif query.data == "about_data": await query.answer() keyboard = InlineKeyboardMarkup([ [InlineKeyboardButton("BACK", callback_data="help_data"), InlineKeyboardButton("START", callback_data="start_data")], [InlineKeyboardButton("SOURCE CODE", url="https://t.me/joinchat/Q1uroGQ645U1OTg1")] ]) await query.message.edit_text( script.ABOUT_MSG, reply_markup=keyboard, disable_web_page_preview=True ) elif query.data == "delallconfirm": await query.message.delete() await deleteallfilters(client, query.message) elif query.data == "delallcancel": await query.message.reply_to_message.delete() await query.message.delete() else: await query.answer("එක ඔයාට නෙවේ කොල්ලෝ,ඔයාට ඕනනම් ඔය වෙනම එකක් දාන්න!!",show_alert=True) def split_list(l, n): for i in range(0, len(l), n): yield l[i:i + n]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @trojanzhex import re import pyrogram from pyrogram import ( filters, Client ) from pyrogram.types import ( InlineKeyboardButton, InlineKeyboardMarkup, Message, CallbackQuery ) from bot import Bot from script import script from database.mdb import searchquery from plugins.channel import deleteallfilters from config import AUTH_USERS BUTTONS = {} @Client.on_message(filters.group & filters.text) async def filter(client: Bot, message: Message): if re.findall("((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text): return if 2 < len(message.text) < 50: btn = [] group_id = message.chat.id name = message.text filenames, links = await searchquery(group_id, name) if filenames and links: for filename, link in zip(filenames, links): btn.append( [InlineKeyboardButton(text=f"{filename}",url=f"{link}")] ) else: return if not btn: return if len(btn) > 10: btns = list(split_list(btn, 10)) keyword = f"{message.chat.id}-{message.message_id}" BUTTONS[keyword] = { "total" : len(btns), "buttons" : btns } else: buttons = btn buttons.append( [InlineKeyboardButton(text="📃 Pages 1/1",callback_data="pages")] ) await message.reply_text( f"<b> Here is the result for {message.text}</b>", reply_markup=InlineKeyboardMarkup(buttons) ) return data = BUTTONS[keyword] buttons = data['buttons'][0].copy() buttons.append( [InlineKeyboardButton(text="ඊළඟ ⏩",callback_data=f"next_0_{keyword}")] ) buttons.append( [InlineKeyboardButton(text=f"📃 Pages 1/{data['total']}",callback_data="pages")] ) await message.reply_text( f"<b> Here is the result for {message.text}</b>", reply_markup=InlineKeyboardMarkup(buttons) ) @Client.on_callback_query() async def cb_handler(client: Bot, query: CallbackQuery): clicked = query.from_user.id typed = query.message.reply_to_message.from_user.id if (clicked == typed) or (clicked in AUTH_USERS): if query.data.startswith("next"): await query.answer() ident, index, keyword = query.data.split("_") try: data = BUTTONS[keyword] except KeyError: await query.answer("You are using this for one of my old message, please send the request again.",show_alert=True) return if int(index) == int(data["total"]) - 2: buttons = data['buttons'][int(index)+1].copy() buttons.append( [InlineKeyboardButton("⏪ ආපහු", callback_data=f"back_{int(index)+1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data['total']}", callback_data="pages")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return else: buttons = data['buttons'][int(index)+1].copy() buttons.append( [InlineKeyboardButton("⏪ ආපහු", callback_data=f"back_{int(index)+1}_{keyword}"),InlineKeyboardButton("NEXT ⏩", callback_data=f"next_{int(index)+1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data['total']}", callback_data="pages")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return elif query.data.startswith("back"): await query.answer() ident, index, keyword = query.data.split("_") try: data = BUTTONS[keyword] except KeyError: await query.answer("You are using this for one of my old message, please send the request again.",show_alert=True) return if int(index) == 1: buttons = data['buttons'][int(index)-1].copy() buttons.append( [InlineKeyboardButton("ඊළඟ ⏩", callback_data=f"next_{int(index)-1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)}/{data['total']}", callback_data="pages")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return else: buttons = data['buttons'][int(index)-1].copy() buttons.append( [InlineKeyboardButton("⏪ ආපහු", callback_data=f"back_{int(index)-1}_{keyword}"),InlineKeyboardButton("NEXT ⏩", callback_data=f"next_{int(index)-1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)}/{data['total']}", callback_data="pages")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return elif query.data == "pages": await query.answer() elif query.data == "start_data": await query.answer() keyboard = InlineKeyboardMarkup([ [InlineKeyboardButton("HELP", callback_data="help_data"), InlineKeyboardButton("ABOUT", callback_data="about_data")], [InlineKeyboardButton("⭕️ JOIN OUR group ⭕️", url="https://t.me/joinchat/Q1uroGQ645U1OTg1")] ]) await query.message.edit_text( script.START_MSG.format(query.from_user.mention), reply_markup=keyboard, disable_web_page_preview=True ) elif query.data == "help_data": await query.answer() keyboard = InlineKeyboardMarkup([ [InlineKeyboardButton("BACK", callback_data="start_data"), InlineKeyboardButton("ABOUT", callback_data="about_data")], [InlineKeyboardButton("⭕️ අපේ group එක ⭕️", url="https://t.me/joinchat/Q1uroGQ645U1OTg1")] ]) await query.message.edit_text( script.HELP_MSG, reply_markup=keyboard, disable_web_page_preview=True ) elif query.data == "about_data": await query.answer() keyboard = InlineKeyboardMarkup([ [InlineKeyboardButton("BACK", callback_data="help_data"), InlineKeyboardButton("START", callback_data="start_data")], [InlineKeyboardButton("SOURCE CODE", url="https://t.me/joinchat/Q1uroGQ645U1OTg1")] ]) await query.message.edit_text( script.ABOUT_MSG, reply_markup=keyboard, disable_web_page_preview=True ) elif query.data == "delallconfirm": await query.message.delete() await deleteallfilters(client, query.message) elif query.data == "delallcancel": await query.message.reply_to_message.delete() await query.message.delete() else: await query.answer("එක ඔයාට නෙවේ කොල්ලෝ,ඔයාට ඕනනම් ඔය වෙනම එකක් දාන්න!!",show_alert=True) def split_list(l, n): for i in range(0, len(l), n): yield l[i:i + n]
from textwrap import dedent class VkErr(Exception): """ Errors from response from vk """ lp_faileds = { 1: "The event history went out of date or was partially lost", 2: "The key’s active period expired", 3: "Information was lost", 4: "Invalid version number was passed" } lp_handler_text = dedent(""" . \033[33mYou can use auto LP faileds handler in LongPoll class\033[0m """) def __init__(self, text) -> None: self.text = text @staticmethod def text_init(text) -> str: if isinstance(text, dict): if "failed" in text: return VkErr.lp_faileds[text["failed"]] + VkErr.lp_handler_text elif 'error' in text: error_code = text['error']['error_code'] error_msg = text['error']['error_msg'] head_msg = dedent(f""" \n\033[31m[{error_code}] {error_msg}\033[0m\n """) content = "Request params:" for pair in text["error"]["request_params"]: key = f"\n\033[33m{pair["key"]}\033[0m" value = f"\033[36m{pair["value"]}\033[0m" content += f"{key} = {value}" return head_msg + content return text return text
from textwrap import dedent class VkErr(Exception): """ Errors from response from vk """ lp_faileds = { 1: "The event history went out of date or was partially lost", 2: "The key’s active period expired", 3: "Information was lost", 4: "Invalid version number was passed" } lp_handler_text = dedent(""" . \033[33mYou can use auto LP faileds handler in LongPoll class\033[0m """) def __init__(self, text) -> None: self.text = text @staticmethod def text_init(text) -> str: if isinstance(text, dict): if "failed" in text: return VkErr.lp_faileds[text["failed"]] + VkErr.lp_handler_text elif 'error' in text: error_code = text['error']['error_code'] error_msg = text['error']['error_msg'] head_msg = dedent(f""" \n\033[31m[{error_code}] {error_msg}\033[0m\n """) content = "Request params:" for pair in text["error"]["request_params"]: key = f"\n\033[33m{pair['key']}\033[0m" value = f"\033[36m{pair['value']}\033[0m" content += f"{key} = {value}" return head_msg + content return text return text
import psycopg2 import os import logging import requests import json import redis from requests.exceptions import HTTPError from dotenv import load_dotenv load_dotenv() logFormatter = '%(asctime)s - %(levelname)s - %(message)s' logging.basicConfig(format=logFormatter, level=logging.INFO) logger = logging.getLogger(__name__) conn = redis.Redis('redis') debug = False def get_interaction_data(): try: connection = psycopg2.connect(user=os.getenv("user"), password=os.getenv("password"), host=os.getenv("host"), port=os.getenv("port"), database=os.getenv("database")) logger.info("Succesfully Connected to Database") cursor = connection.cursor() # we assume that the interactions are stored in a database postgreSQL_select_Query = "select * from --" cursor.execute(postgreSQL_select_Query) mobile_records = cursor.fetchall() if(len(mobile_records) == 0): logger.warning("No Database Records!") logger.debug("Database results length: " + str(len(mobile_records))) user_inter_dict = {} org_id = [] asset_id = [] score = [] for row in mobile_records: org_id.append(row[0]) asset_id.append(row[1]) score.append(row[2]) user_inter_dict["org_id"] = org_id user_inter_dict["asset_id"] = asset_id user_inter_dict["score"] = score logger.debug(user_inter_dict) conn.set("user-interaction", json.dumps(user_inter_dict)) with open('/code/src/models_training/interaction_size', 'w') as f: f.write(str(len(user_inter_dict["org_id"]))) connection.close() return user_inter_dict except (Exception, psycopg2.Error) as error: logger.error(f'Error while fetching data from Database: {error}') def get_data_assets(): try: logger.info("Trying to access data assets") data_assets = requests.get("http://" + os.getenv("icarus_internal")).json() if ('status' in data_assets) and ('error' in data_assets): if data_assets['status'] != 200: logger.error( f'Error on data assets retrieval: {data_assets['error']}') return None data_asset_list = [] data_asset_dict = {} for data in data_assets: data_asset_list.append(data["id"]) data_asset_dict["data-asset-list"] = data_asset_list conn.set("data-assets", json.dumps(data_asset_dict)) return data_asset_list except HTTPError as http_err: logger.error(f'HTTP error occurred: {http_err}') return None except Exception as err: logger.error(f'Other error occurred: {err}') return None def get_organizations(): try: logger.info("Trying to access organizations") organizations = requests.get("http://" + os.getenv("icarus_internal")).json() if ('status' in organizations) and ('error' in organizations): if organizations['status'] != 200: logger.error( f'Error on organizations retrieval: {organizations['error']}') return None organziations_list = [] organziations_dict = {} for org in organizations: organziations_list.append(org["id"]) organziations_dict["organization-list"] = organziations_list conn.set("organizations", json.dumps(organziations_dict)) return organziations_list except HTTPError as http_err: logger.error(f'HTTP error occurred: {http_err}') return None except Exception as err: logger.error(f'Other error occurred: {err}') return None # get_interaction_data() get_data_assets() get_organizations()
import psycopg2 import os import logging import requests import json import redis from requests.exceptions import HTTPError from dotenv import load_dotenv load_dotenv() logFormatter = '%(asctime)s - %(levelname)s - %(message)s' logging.basicConfig(format=logFormatter, level=logging.INFO) logger = logging.getLogger(__name__) conn = redis.Redis('redis') debug = False def get_interaction_data(): try: connection = psycopg2.connect(user=os.getenv("user"), password=os.getenv("password"), host=os.getenv("host"), port=os.getenv("port"), database=os.getenv("database")) logger.info("Succesfully Connected to Database") cursor = connection.cursor() # we assume that the interactions are stored in a database postgreSQL_select_Query = "select * from --" cursor.execute(postgreSQL_select_Query) mobile_records = cursor.fetchall() if(len(mobile_records) == 0): logger.warning("No Database Records!") logger.debug("Database results length: " + str(len(mobile_records))) user_inter_dict = {} org_id = [] asset_id = [] score = [] for row in mobile_records: org_id.append(row[0]) asset_id.append(row[1]) score.append(row[2]) user_inter_dict["org_id"] = org_id user_inter_dict["asset_id"] = asset_id user_inter_dict["score"] = score logger.debug(user_inter_dict) conn.set("user-interaction", json.dumps(user_inter_dict)) with open('/code/src/models_training/interaction_size', 'w') as f: f.write(str(len(user_inter_dict["org_id"]))) connection.close() return user_inter_dict except (Exception, psycopg2.Error) as error: logger.error(f'Error while fetching data from Database: {error}') def get_data_assets(): try: logger.info("Trying to access data assets") data_assets = requests.get("http://" + os.getenv("icarus_internal")).json() if ('status' in data_assets) and ('error' in data_assets): if data_assets['status'] != 200: logger.error( f'Error on data assets retrieval: {data_assets["error"]}') return None data_asset_list = [] data_asset_dict = {} for data in data_assets: data_asset_list.append(data["id"]) data_asset_dict["data-asset-list"] = data_asset_list conn.set("data-assets", json.dumps(data_asset_dict)) return data_asset_list except HTTPError as http_err: logger.error(f'HTTP error occurred: {http_err}') return None except Exception as err: logger.error(f'Other error occurred: {err}') return None def get_organizations(): try: logger.info("Trying to access organizations") organizations = requests.get("http://" + os.getenv("icarus_internal")).json() if ('status' in organizations) and ('error' in organizations): if organizations['status'] != 200: logger.error( f'Error on organizations retrieval: {organizations["error"]}') return None organziations_list = [] organziations_dict = {} for org in organizations: organziations_list.append(org["id"]) organziations_dict["organization-list"] = organziations_list conn.set("organizations", json.dumps(organziations_dict)) return organziations_list except HTTPError as http_err: logger.error(f'HTTP error occurred: {http_err}') return None except Exception as err: logger.error(f'Other error occurred: {err}') return None # get_interaction_data() get_data_assets() get_organizations()
# -*- coding: utf-8 -*- # pylint: disable=line-too-long,missing-docstring,reimported,unused-import,unused-variable import orjson import pytest from pydantic.error_wrappers import ValidationError import turvallisuusneuvonta.csaf.document as document from tests import conftest def _subs(count: int) -> str: """DRY.""" return f'{count} validation error{'' if count == 1 else 's'} for Document' def test_meta_doc_none(): with pytest.raises(ValidationError, match=_subs(5)) as err: _ = document.Document() # type: ignore for prop in ('category', 'csaf_version', 'publisher', 'title', 'tracking'): assert f'\n{prop}\n field required' in str(err.value) def test_meta_doc_category_empty(): with pytest.raises(ValidationError, match=_subs(5)) as err: _ = document.Document(category='') # type: ignore hint = 'ensure this value has at least 1 character' assert f'\ncategory\n {hint}' in str(err.value) for prop in ('csaf_version', 'publisher', 'title', 'tracking'): assert f'\n{prop}\n field required' in str(err.value) def test_meta_doc_csaf_version_wrong(): with pytest.raises(ValidationError, match=_subs(4)) as err: _ = document.Document(**conftest.META_WRONG_VERSION) # type: ignore hint = "value is not a valid enumeration member; permitted: '2.0'" assert f'\ncsaf_version\n {hint}' in str(err.value) for prop in ('publisher', 'title', 'tracking'): assert f'\n{prop}\n field required' in str(err.value) def test_meta_doc_publisher_empty(): with pytest.raises(ValidationError, match=_subs(5)) as err: _ = document.Document(**conftest.META_EMPTY_PUBLISHER) # type: ignore for prop in ('publisher -> category', 'publisher -> name', 'publisher -> namespace', 'title', 'tracking'): assert f'\n{prop}\n field required' in str(err.value) def test_meta_doc_title_empty(): with pytest.raises(ValidationError, match=_subs(2)) as err: _ = document.Document(**conftest.META_EMPTY_TITLE) # type: ignore hint = 'ensure this value has at least 1 character' assert f'\ntitle\n {hint}' in str(err.value) for prop in ('tracking',): assert f'\n{prop}\n field required' in str(err.value) def test_meta_doc_tracking_empty(): with pytest.raises(ValidationError, match=_subs(6)) as err: _ = document.Document(**conftest.META_EMPTY_TRACKING) # type: ignore host = 'tracking' for prop in ('current_release_date', 'id', 'initial_release_date', 'revision_history', 'status', 'version'): assert f'\n{host} -> {prop}\n field required' in str(err.value) def test_meta_doc_ok_if_spammy(): meta_doc = document.Document(**conftest.META_OK) # type: ignore strip_me = orjson.loads(meta_doc.json()) conftest._strip_and_iso_grace(strip_me) assert strip_me == conftest.META_OK
# -*- coding: utf-8 -*- # pylint: disable=line-too-long,missing-docstring,reimported,unused-import,unused-variable import orjson import pytest from pydantic.error_wrappers import ValidationError import turvallisuusneuvonta.csaf.document as document from tests import conftest def _subs(count: int) -> str: """DRY.""" return f'{count} validation error{"" if count == 1 else "s"} for Document' def test_meta_doc_none(): with pytest.raises(ValidationError, match=_subs(5)) as err: _ = document.Document() # type: ignore for prop in ('category', 'csaf_version', 'publisher', 'title', 'tracking'): assert f'\n{prop}\n field required' in str(err.value) def test_meta_doc_category_empty(): with pytest.raises(ValidationError, match=_subs(5)) as err: _ = document.Document(category='') # type: ignore hint = 'ensure this value has at least 1 character' assert f'\ncategory\n {hint}' in str(err.value) for prop in ('csaf_version', 'publisher', 'title', 'tracking'): assert f'\n{prop}\n field required' in str(err.value) def test_meta_doc_csaf_version_wrong(): with pytest.raises(ValidationError, match=_subs(4)) as err: _ = document.Document(**conftest.META_WRONG_VERSION) # type: ignore hint = "value is not a valid enumeration member; permitted: '2.0'" assert f'\ncsaf_version\n {hint}' in str(err.value) for prop in ('publisher', 'title', 'tracking'): assert f'\n{prop}\n field required' in str(err.value) def test_meta_doc_publisher_empty(): with pytest.raises(ValidationError, match=_subs(5)) as err: _ = document.Document(**conftest.META_EMPTY_PUBLISHER) # type: ignore for prop in ('publisher -> category', 'publisher -> name', 'publisher -> namespace', 'title', 'tracking'): assert f'\n{prop}\n field required' in str(err.value) def test_meta_doc_title_empty(): with pytest.raises(ValidationError, match=_subs(2)) as err: _ = document.Document(**conftest.META_EMPTY_TITLE) # type: ignore hint = 'ensure this value has at least 1 character' assert f'\ntitle\n {hint}' in str(err.value) for prop in ('tracking',): assert f'\n{prop}\n field required' in str(err.value) def test_meta_doc_tracking_empty(): with pytest.raises(ValidationError, match=_subs(6)) as err: _ = document.Document(**conftest.META_EMPTY_TRACKING) # type: ignore host = 'tracking' for prop in ('current_release_date', 'id', 'initial_release_date', 'revision_history', 'status', 'version'): assert f'\n{host} -> {prop}\n field required' in str(err.value) def test_meta_doc_ok_if_spammy(): meta_doc = document.Document(**conftest.META_OK) # type: ignore strip_me = orjson.loads(meta_doc.json()) conftest._strip_and_iso_grace(strip_me) assert strip_me == conftest.META_OK
""" Module holding transformer functions. Transformer functions take an input data structure, make a change, and return an output of the same type. They are commonly used to perform operations on cytoscape graph elements. """ import copy import datetime as dt import uuid from collections import defaultdict, deque from typing import Any, Dict, List, Optional, Tuple from graph_structures_pb2 import SLI, NodeType, Status from . import compute_status, constants, state, utils def apply_node_property_classes( elements, node_name_message_map, client_name_message_map, virtual_node_map ): """Adds classes to elements based on the properties of their corresponding nodes. Currently, these properties include: if the element corresponds to a client the overall status of a node or virtual node the override status of a node or virtual node Args: elements: A list of cytoscape elements node_name_message_map: A dictionary mapping node names to Node protos. client_name_message_map: A dictionary mapping client names to Client protos. virtual_node_map: A dictionary mapping virtual node names to VirtualNode protos. Returns: a new list of elements with appropriate cytoscape classes. """ out_elements = [] for element in elements: new_element = copy.deepcopy(element) # edge element if not utils.is_node_element(new_element): out_elements.append(new_element) continue element_ujt_id = new_element["data"]["ujt_id"] # client if element_ujt_id in client_name_message_map: utils.add_class_mutable(new_element, [constants.CLIENT_CLASS]) out_elements.append(new_element) continue # nodes if element_ujt_id in node_name_message_map: node = node_name_message_map[element_ujt_id] elif element_ujt_id in virtual_node_map: node = virtual_node_map[element_ujt_id] else: raise ValueError( "Cytoscape element not found in node maps -- some data is corrupt!" ) class_list = [NodeType.Name(node.node_type)] if node.override_status != Status.STATUS_UNSPECIFIED: class_list += [Status.Name(node.override_status), constants.OVERRIDE_CLASS] else: class_list.append(Status.Name(node.status)) utils.add_class_mutable(new_element, class_list) out_elements.append(new_element) return out_elements def apply_view_classes(elements, tag_map, view_list): """Applies classes to elements based on the user defined tags and views. The stylesheet is updated upon every style update. Given a view composed of a tag and style name, we change the actual appearance of elements, by appending the style name to all elements tagged with the tag. Notice that the tag name itself is not appended to the class list. Args: elements: A list of cytoscape elements. tag_map: A dictionary mapping element_ujt_ids to a list of applied tags view_list: The list of user defined views. Returns: a list of cytoscape elements with view classes applied. """ out_elements = [] for element in elements: new_element = copy.deepcopy(element) element_ujt_id = new_element["data"]["ujt_id"] class_list = [] if element_ujt_id in tag_map: tags = tag_map[element_ujt_id] # The following is an O(len(tags) * len(view_list)) operation. # Should be okay if these are small lists. We're limited to using lists over dicts or sets # since we need to keep a consistent order in the UI. # Of course, we could do some preprocessing here to convert them to intermediate dicts. # Let's make that optimization later if this turns out to be excessively slow. for tag in tags: for view_tag, view_style_name in view_list: if tag == view_tag and tag != "" and view_style_name != "": class_list.append(view_style_name) utils.add_class_mutable(new_element, class_list) out_elements.append(new_element) return out_elements def apply_change_over_time_classes( elements: List[Dict[str, Any]], slis: List[SLI], start_time: dt.datetime, end_time: dt.datetime, ) -> List[Dict[str, Any]]: """Applies classes to elements based on the change in SLIs over the time range. Args: elements: A list of cytoscape elements. slis: A list of SLI protos. start_time: The start time of the time range to compute aggregate status over. end_time: The end time of the time range to compute aggregate status over. sli_type: The SLI type of interest. Returns: A new list of elements with the change over time classes applied. """ node_name_sli_map = defaultdict(list) for sli in slis: node_name_sli_map[sli.node_name].append(sli) out_elements = [] for element in elements: new_element = copy.deepcopy(element) ujt_id = new_element["data"]["ujt_id"] if ujt_id in node_name_sli_map: ( before_composite_sli, after_composite_sli, ) = generate_before_after_composite_slis( node_name_sli_map[ujt_id], start_time, end_time, ) change_over_time_class = ( utils.get_change_over_time_class_from_composite_slis( before_composite_sli, after_composite_sli, ) ) utils.add_class_mutable(new_element, [change_over_time_class]) out_elements.append(new_element) return out_elements def generate_before_after_composite_slis( slis: List[SLI], start_time: dt.datetime, end_time: dt.datetime ) -> Tuple[Optional[SLI], Optional[SLI]]: """Generates two composite SLIs from the slis in each half of the specified time range. The composite SLI's value is the average of the individual SLI values in the appropriate range. Args: slis: A list of SLIs within the tine range start_time: The start of the time range end_time: The end of the time range Returns: A tuple of two composite SLIs. It will never return (None, None) """ if slis == []: raise ValueError mid_time = start_time + (end_time - start_time) / 2 slis_before, slis_after = [], [] for sli in slis: if sli.timestamp.ToDatetime() < mid_time: slis_before.append(sli) else: slis_after.append(sli) # Compute the average value before and after min_time, and note the appropriate class composite_slis: List[Optional[SLI]] = [None, None] for idx, sli_sublist in enumerate([slis_before, slis_after]): if sli_sublist != []: composite_sli = SLI() # copy the slo bound/target values from the input, # these should be constant across all slis in the input list composite_sli.CopyFrom(sli_sublist[0]) # compute the average value, this can be more sophisticated composite_sli.sli_value = sum([sli.sli_value for sli in sli_sublist]) / len( sli_sublist ) compute_status.compute_sli_status(composite_sli) composite_slis[idx] = composite_sli return (composite_slis[0], composite_slis[1]) # explicitly return as a tuple def apply_highlighted_edge_class_to_elements(elements, user_journey_name): """Applies the highlighted edge class to elements based on the selected user journey. Args: elements: a list of cytoscape elements user_journey_name: the user journey to highlight Returns: a list of cytoscape elements with the highlighted class on the appropriate edges """ edges_map = defaultdict(list) # map from edge source to edge elements nodes_list = [] for element in elements: new_element = copy.deepcopy(element) if utils.is_node_element(new_element): nodes_list.append(new_element) else: if "user_journey_name" in new_element["data"].keys(): # treat the user journey name as the edge source edges_map[new_element["data"]["user_journey_name"]].append(new_element) else: edges_map[new_element["data"]["source"]].append(new_element) # do a bfs traversal and highlight the appropriate edges node_frontier_names = deque([user_journey_name]) while node_frontier_names: source_name = node_frontier_names.popleft() for edge in edges_map[source_name]: utils.add_class_mutable(edge, [constants.HIGHLIGHTED_UJ_EDGE_CLASS]) node_frontier_names.append(edge["data"]["target"]) out_elements = nodes_list for edges in edges_map.values(): out_elements += edges return out_elements def apply_virtual_nodes_to_elements(elements): """Applies the virtual node transformation to elements. This is done in two steps: 1. modifying the existing elements by: a. removing the elements that should be hidden by a collapsed virtual node b. adding the parent property to elements that are in an expanded virtual node c. modifying edges to connect collapsed virtual nodes 2. adding in the expanded or top-level virtual nodes that should be visible Args: elements: a list of cytoscape elements """ virtual_node_map = state.get_virtual_node_map() parent_virtual_node_map = state.get_parent_virtual_node_map() out_elements = [] # 1. modify existing elements for element in elements: new_element = copy.deepcopy(element) if utils.is_node_element(new_element): highest_collapsed_virtual_node_name = ( utils.get_highest_collapsed_virtual_node_name( new_element["data"]["ujt_id"], virtual_node_map, parent_virtual_node_map, ) ) # this condition checks if the node should be visible if highest_collapsed_virtual_node_name is None: # this condition checks if the current node is not within # a compound node, but should be contained within a virutal node. if ( new_element["data"]["ujt_id"] in parent_virtual_node_map and "parent" not in new_element["data"] ): new_element["data"]["parent"] = parent_virtual_node_map[ new_element["data"]["ujt_id"] ] out_elements.append(new_element) else: new_source = utils.get_highest_collapsed_virtual_node_name( element["data"]["source"], virtual_node_map, parent_virtual_node_map ) new_target = utils.get_highest_collapsed_virtual_node_name( element["data"]["target"], virtual_node_map, parent_virtual_node_map ) if new_source is not None: new_element["data"]["source"] = new_source if new_target is not None: new_element["data"]["target"] = new_target new_element["data"][ "id" ] = f"{new_element["data"]["source"]}/{new_element["data"]["target"]}" # avoid adding: # edges between nodes within the same virtual nodes # duplicate edges if ( new_element["data"]["source"] != new_element["data"]["target"] and new_element not in out_elements ): out_elements.append(new_element) # 2. add visible virtual nodes for virtual_node_name in virtual_node_map: highest_collapsed_virtual_node_name = ( utils.get_highest_collapsed_virtual_node_name( virtual_node_name, virtual_node_map, parent_virtual_node_map ) ) if ( highest_collapsed_virtual_node_name is None or highest_collapsed_virtual_node_name == virtual_node_name ): # This condition determines if the virtual node should be visible # first condition: entire stack of virtual nodes is expanded # second condition: the virtual node itself is the toplevel, collapsed node new_element = { "data": { "label": virtual_node_name, "id": virtual_node_name, "ujt_id": virtual_node_name, }, "classes": "", } if virtual_node_name in parent_virtual_node_map: new_element["data"]["parent"] = parent_virtual_node_map[ virtual_node_name ] out_elements.append(new_element) return out_elements def apply_uuid_to_elements(elements, uuid_to_apply=None): """Append a new UUID to the id of each cytoscape element This is used as a workaround to update the source/target of edges, and the parent/child relatioship of nodes. In Cytoscape.js, these relationships are immutable, and a move() function has to be called on the element to update the aforementioned properties. However, Dash Cytoscape doesn't expose this functionality. See https://github.com/plotly/dash-cytoscape/issues/106. By providing a new ID, we can avoid this restriction. Args: elements: a list of Cytoscape elements uuid_to_apply: a UUID to append. Defaults to None. If None is provided, this function generates a new UUID. Returns: A list of Cytoscape elements with an UUID appended to their ID fields. """ if uuid_to_apply is None: uuid_to_apply = uuid.uuid4() out_elements = [] # the properties of the element that need to have a UUID # appended UUID_KEYS = ["id", "source", "target", "parent"] for element in elements: new_element = copy.deepcopy(element) for key in UUID_KEYS: if key in new_element["data"]: new_element["data"][key] += f"#{uuid_to_apply}" out_elements.append(new_element) return out_elements def apply_slis_to_node_map(sli_list, node_map): """Updates the nodes in the node map with the slis from the sli list. Args: sli_list: A list of SLIs to add to the nodes node_map: A dict mapping node names to nodes Returns: a dict mapping node names to nodes, with updated SLIs """ out_node_map = copy.deepcopy(node_map) for sli in sli_list: node = out_node_map[sli.node_name] # find the index of the node's SLI with the same SLI type as the SLI from sli_list new_node_slis = [] for node_sli in node.slis: if node_sli.sli_type == sli.sli_type: new_node_slis.append(sli) else: new_node_slis.append(node_sli) del node.slis[:] node.slis.extend(new_node_slis) return out_node_map def sort_nodes_by_parent_relationship(elements): """Returns a list of elements where node parents always appear before node children. This method essentially performs a topological sort on the trees formed from parent-child relationships between nodes. For context, see https://github.com/plotly/dash-cytoscape/issues/112 and https://github.com/googleinterns/userjourneytool/issues/63 Args: elements: a list of cytoscape elements. Returns: a list of cytoscape where node parents always appear before node children. """ edges = [] node_id_element_map = {} for element in elements: new_element = copy.deepcopy(element) if utils.is_node_element(new_element): node_id_element_map[element["data"]["id"]] = new_element else: edges.append(new_element) parent_child_map = defaultdict(list) bfs_queue = deque() lexicographically_sorted_edges = sorted(edges, key=lambda edge: edge["data"]["id"]) # initially sort the nodes to ensure a consistent traversal order, for a consistent layout lexicographically_sorted_nodes = sorted( node_id_element_map.values(), key=lambda node: node["data"]["id"] ) # build a tree from parents to children (parent_child_map) # (reversing the edge direction of cytoscape format) for node in lexicographically_sorted_nodes: node_id = node["data"]["id"] if "parent" in node["data"]: parent_id = node["data"]["parent"] parent_child_map[parent_id].append(node_id) else: bfs_queue.append(node_id) topologically_sorted_nodes = [] visited_node_ids = set() while bfs_queue: node_id = bfs_queue.popleft() if node_id in visited_node_ids: raise ValueError("Circular parent/child relationship detected!") else: visited_node_ids.add(node_id) bfs_queue.extend(parent_child_map[node_id]) topologically_sorted_nodes.append(node_id_element_map[node_id]) return lexicographically_sorted_edges + topologically_sorted_nodes
""" Module holding transformer functions. Transformer functions take an input data structure, make a change, and return an output of the same type. They are commonly used to perform operations on cytoscape graph elements. """ import copy import datetime as dt import uuid from collections import defaultdict, deque from typing import Any, Dict, List, Optional, Tuple from graph_structures_pb2 import SLI, NodeType, Status from . import compute_status, constants, state, utils def apply_node_property_classes( elements, node_name_message_map, client_name_message_map, virtual_node_map ): """Adds classes to elements based on the properties of their corresponding nodes. Currently, these properties include: if the element corresponds to a client the overall status of a node or virtual node the override status of a node or virtual node Args: elements: A list of cytoscape elements node_name_message_map: A dictionary mapping node names to Node protos. client_name_message_map: A dictionary mapping client names to Client protos. virtual_node_map: A dictionary mapping virtual node names to VirtualNode protos. Returns: a new list of elements with appropriate cytoscape classes. """ out_elements = [] for element in elements: new_element = copy.deepcopy(element) # edge element if not utils.is_node_element(new_element): out_elements.append(new_element) continue element_ujt_id = new_element["data"]["ujt_id"] # client if element_ujt_id in client_name_message_map: utils.add_class_mutable(new_element, [constants.CLIENT_CLASS]) out_elements.append(new_element) continue # nodes if element_ujt_id in node_name_message_map: node = node_name_message_map[element_ujt_id] elif element_ujt_id in virtual_node_map: node = virtual_node_map[element_ujt_id] else: raise ValueError( "Cytoscape element not found in node maps -- some data is corrupt!" ) class_list = [NodeType.Name(node.node_type)] if node.override_status != Status.STATUS_UNSPECIFIED: class_list += [Status.Name(node.override_status), constants.OVERRIDE_CLASS] else: class_list.append(Status.Name(node.status)) utils.add_class_mutable(new_element, class_list) out_elements.append(new_element) return out_elements def apply_view_classes(elements, tag_map, view_list): """Applies classes to elements based on the user defined tags and views. The stylesheet is updated upon every style update. Given a view composed of a tag and style name, we change the actual appearance of elements, by appending the style name to all elements tagged with the tag. Notice that the tag name itself is not appended to the class list. Args: elements: A list of cytoscape elements. tag_map: A dictionary mapping element_ujt_ids to a list of applied tags view_list: The list of user defined views. Returns: a list of cytoscape elements with view classes applied. """ out_elements = [] for element in elements: new_element = copy.deepcopy(element) element_ujt_id = new_element["data"]["ujt_id"] class_list = [] if element_ujt_id in tag_map: tags = tag_map[element_ujt_id] # The following is an O(len(tags) * len(view_list)) operation. # Should be okay if these are small lists. We're limited to using lists over dicts or sets # since we need to keep a consistent order in the UI. # Of course, we could do some preprocessing here to convert them to intermediate dicts. # Let's make that optimization later if this turns out to be excessively slow. for tag in tags: for view_tag, view_style_name in view_list: if tag == view_tag and tag != "" and view_style_name != "": class_list.append(view_style_name) utils.add_class_mutable(new_element, class_list) out_elements.append(new_element) return out_elements def apply_change_over_time_classes( elements: List[Dict[str, Any]], slis: List[SLI], start_time: dt.datetime, end_time: dt.datetime, ) -> List[Dict[str, Any]]: """Applies classes to elements based on the change in SLIs over the time range. Args: elements: A list of cytoscape elements. slis: A list of SLI protos. start_time: The start time of the time range to compute aggregate status over. end_time: The end time of the time range to compute aggregate status over. sli_type: The SLI type of interest. Returns: A new list of elements with the change over time classes applied. """ node_name_sli_map = defaultdict(list) for sli in slis: node_name_sli_map[sli.node_name].append(sli) out_elements = [] for element in elements: new_element = copy.deepcopy(element) ujt_id = new_element["data"]["ujt_id"] if ujt_id in node_name_sli_map: ( before_composite_sli, after_composite_sli, ) = generate_before_after_composite_slis( node_name_sli_map[ujt_id], start_time, end_time, ) change_over_time_class = ( utils.get_change_over_time_class_from_composite_slis( before_composite_sli, after_composite_sli, ) ) utils.add_class_mutable(new_element, [change_over_time_class]) out_elements.append(new_element) return out_elements def generate_before_after_composite_slis( slis: List[SLI], start_time: dt.datetime, end_time: dt.datetime ) -> Tuple[Optional[SLI], Optional[SLI]]: """Generates two composite SLIs from the slis in each half of the specified time range. The composite SLI's value is the average of the individual SLI values in the appropriate range. Args: slis: A list of SLIs within the tine range start_time: The start of the time range end_time: The end of the time range Returns: A tuple of two composite SLIs. It will never return (None, None) """ if slis == []: raise ValueError mid_time = start_time + (end_time - start_time) / 2 slis_before, slis_after = [], [] for sli in slis: if sli.timestamp.ToDatetime() < mid_time: slis_before.append(sli) else: slis_after.append(sli) # Compute the average value before and after min_time, and note the appropriate class composite_slis: List[Optional[SLI]] = [None, None] for idx, sli_sublist in enumerate([slis_before, slis_after]): if sli_sublist != []: composite_sli = SLI() # copy the slo bound/target values from the input, # these should be constant across all slis in the input list composite_sli.CopyFrom(sli_sublist[0]) # compute the average value, this can be more sophisticated composite_sli.sli_value = sum([sli.sli_value for sli in sli_sublist]) / len( sli_sublist ) compute_status.compute_sli_status(composite_sli) composite_slis[idx] = composite_sli return (composite_slis[0], composite_slis[1]) # explicitly return as a tuple def apply_highlighted_edge_class_to_elements(elements, user_journey_name): """Applies the highlighted edge class to elements based on the selected user journey. Args: elements: a list of cytoscape elements user_journey_name: the user journey to highlight Returns: a list of cytoscape elements with the highlighted class on the appropriate edges """ edges_map = defaultdict(list) # map from edge source to edge elements nodes_list = [] for element in elements: new_element = copy.deepcopy(element) if utils.is_node_element(new_element): nodes_list.append(new_element) else: if "user_journey_name" in new_element["data"].keys(): # treat the user journey name as the edge source edges_map[new_element["data"]["user_journey_name"]].append(new_element) else: edges_map[new_element["data"]["source"]].append(new_element) # do a bfs traversal and highlight the appropriate edges node_frontier_names = deque([user_journey_name]) while node_frontier_names: source_name = node_frontier_names.popleft() for edge in edges_map[source_name]: utils.add_class_mutable(edge, [constants.HIGHLIGHTED_UJ_EDGE_CLASS]) node_frontier_names.append(edge["data"]["target"]) out_elements = nodes_list for edges in edges_map.values(): out_elements += edges return out_elements def apply_virtual_nodes_to_elements(elements): """Applies the virtual node transformation to elements. This is done in two steps: 1. modifying the existing elements by: a. removing the elements that should be hidden by a collapsed virtual node b. adding the parent property to elements that are in an expanded virtual node c. modifying edges to connect collapsed virtual nodes 2. adding in the expanded or top-level virtual nodes that should be visible Args: elements: a list of cytoscape elements """ virtual_node_map = state.get_virtual_node_map() parent_virtual_node_map = state.get_parent_virtual_node_map() out_elements = [] # 1. modify existing elements for element in elements: new_element = copy.deepcopy(element) if utils.is_node_element(new_element): highest_collapsed_virtual_node_name = ( utils.get_highest_collapsed_virtual_node_name( new_element["data"]["ujt_id"], virtual_node_map, parent_virtual_node_map, ) ) # this condition checks if the node should be visible if highest_collapsed_virtual_node_name is None: # this condition checks if the current node is not within # a compound node, but should be contained within a virutal node. if ( new_element["data"]["ujt_id"] in parent_virtual_node_map and "parent" not in new_element["data"] ): new_element["data"]["parent"] = parent_virtual_node_map[ new_element["data"]["ujt_id"] ] out_elements.append(new_element) else: new_source = utils.get_highest_collapsed_virtual_node_name( element["data"]["source"], virtual_node_map, parent_virtual_node_map ) new_target = utils.get_highest_collapsed_virtual_node_name( element["data"]["target"], virtual_node_map, parent_virtual_node_map ) if new_source is not None: new_element["data"]["source"] = new_source if new_target is not None: new_element["data"]["target"] = new_target new_element["data"][ "id" ] = f"{new_element['data']['source']}/{new_element['data']['target']}" # avoid adding: # edges between nodes within the same virtual nodes # duplicate edges if ( new_element["data"]["source"] != new_element["data"]["target"] and new_element not in out_elements ): out_elements.append(new_element) # 2. add visible virtual nodes for virtual_node_name in virtual_node_map: highest_collapsed_virtual_node_name = ( utils.get_highest_collapsed_virtual_node_name( virtual_node_name, virtual_node_map, parent_virtual_node_map ) ) if ( highest_collapsed_virtual_node_name is None or highest_collapsed_virtual_node_name == virtual_node_name ): # This condition determines if the virtual node should be visible # first condition: entire stack of virtual nodes is expanded # second condition: the virtual node itself is the toplevel, collapsed node new_element = { "data": { "label": virtual_node_name, "id": virtual_node_name, "ujt_id": virtual_node_name, }, "classes": "", } if virtual_node_name in parent_virtual_node_map: new_element["data"]["parent"] = parent_virtual_node_map[ virtual_node_name ] out_elements.append(new_element) return out_elements def apply_uuid_to_elements(elements, uuid_to_apply=None): """Append a new UUID to the id of each cytoscape element This is used as a workaround to update the source/target of edges, and the parent/child relatioship of nodes. In Cytoscape.js, these relationships are immutable, and a move() function has to be called on the element to update the aforementioned properties. However, Dash Cytoscape doesn't expose this functionality. See https://github.com/plotly/dash-cytoscape/issues/106. By providing a new ID, we can avoid this restriction. Args: elements: a list of Cytoscape elements uuid_to_apply: a UUID to append. Defaults to None. If None is provided, this function generates a new UUID. Returns: A list of Cytoscape elements with an UUID appended to their ID fields. """ if uuid_to_apply is None: uuid_to_apply = uuid.uuid4() out_elements = [] # the properties of the element that need to have a UUID # appended UUID_KEYS = ["id", "source", "target", "parent"] for element in elements: new_element = copy.deepcopy(element) for key in UUID_KEYS: if key in new_element["data"]: new_element["data"][key] += f"#{uuid_to_apply}" out_elements.append(new_element) return out_elements def apply_slis_to_node_map(sli_list, node_map): """Updates the nodes in the node map with the slis from the sli list. Args: sli_list: A list of SLIs to add to the nodes node_map: A dict mapping node names to nodes Returns: a dict mapping node names to nodes, with updated SLIs """ out_node_map = copy.deepcopy(node_map) for sli in sli_list: node = out_node_map[sli.node_name] # find the index of the node's SLI with the same SLI type as the SLI from sli_list new_node_slis = [] for node_sli in node.slis: if node_sli.sli_type == sli.sli_type: new_node_slis.append(sli) else: new_node_slis.append(node_sli) del node.slis[:] node.slis.extend(new_node_slis) return out_node_map def sort_nodes_by_parent_relationship(elements): """Returns a list of elements where node parents always appear before node children. This method essentially performs a topological sort on the trees formed from parent-child relationships between nodes. For context, see https://github.com/plotly/dash-cytoscape/issues/112 and https://github.com/googleinterns/userjourneytool/issues/63 Args: elements: a list of cytoscape elements. Returns: a list of cytoscape where node parents always appear before node children. """ edges = [] node_id_element_map = {} for element in elements: new_element = copy.deepcopy(element) if utils.is_node_element(new_element): node_id_element_map[element["data"]["id"]] = new_element else: edges.append(new_element) parent_child_map = defaultdict(list) bfs_queue = deque() lexicographically_sorted_edges = sorted(edges, key=lambda edge: edge["data"]["id"]) # initially sort the nodes to ensure a consistent traversal order, for a consistent layout lexicographically_sorted_nodes = sorted( node_id_element_map.values(), key=lambda node: node["data"]["id"] ) # build a tree from parents to children (parent_child_map) # (reversing the edge direction of cytoscape format) for node in lexicographically_sorted_nodes: node_id = node["data"]["id"] if "parent" in node["data"]: parent_id = node["data"]["parent"] parent_child_map[parent_id].append(node_id) else: bfs_queue.append(node_id) topologically_sorted_nodes = [] visited_node_ids = set() while bfs_queue: node_id = bfs_queue.popleft() if node_id in visited_node_ids: raise ValueError("Circular parent/child relationship detected!") else: visited_node_ids.add(node_id) bfs_queue.extend(parent_child_map[node_id]) topologically_sorted_nodes.append(node_id_element_map[node_id]) return lexicographically_sorted_edges + topologically_sorted_nodes
#!/usr/bin/env python3 # # Copyright (C) 2018 The Electrum developers # Distributed under the MIT software license, see the accompanying # file LICENCE or http://www.opensource.org/licenses/mit-license.php import zlib from collections import OrderedDict, defaultdict import asyncio import os import time from typing import Tuple, Dict, TYPE_CHECKING, Optional, Union, Set from datetime import datetime import functools import aiorpcx from aiorpcx import TaskGroup from .crypto import sha256, sha256d from . import bitcoin, util from . import ecc from .ecc import sig_string_from_r_and_s, der_sig_from_sig_string from . import constants from .util import (bh2u, bfh, log_exceptions, ignore_exceptions, chunks, SilentTaskGroup, UnrelatedTransactionException) from . import transaction from .bitcoin import make_op_return from .transaction import PartialTxOutput, match_script_against_template from .logging import Logger from .lnonion import (new_onion_packet, OnionFailureCode, calc_hops_data_for_payment, process_onion_packet, OnionPacket, construct_onion_error, OnionRoutingFailure, ProcessedOnionPacket, UnsupportedOnionPacketVersion, InvalidOnionMac, InvalidOnionPubkey, OnionFailureCodeMetaFlag) from .lnchannel import Channel, RevokeAndAck, RemoteCtnTooFarInFuture, ChannelState, PeerState from . import lnutil from .lnutil import (Outpoint, LocalConfig, RECEIVED, UpdateAddHtlc, ChannelConfig, RemoteConfig, OnlyPubkeyKeypair, ChannelConstraints, RevocationStore, funding_output_script, get_per_commitment_secret_from_seed, secret_to_pubkey, PaymentFailure, LnFeatures, LOCAL, REMOTE, HTLCOwner, ln_compare_features, privkey_to_pubkey, MIN_FINAL_CLTV_EXPIRY_ACCEPTED, LightningPeerConnectionClosed, HandshakeFailed, RemoteMisbehaving, ShortChannelID, IncompatibleLightningFeatures, derive_payment_secret_from_payment_preimage, UpfrontShutdownScriptViolation) from .lnutil import FeeUpdate, channel_id_from_funding_tx from .lntransport import LNTransport, LNTransportBase from .lnmsg import encode_msg, decode_msg, UnknownOptionalMsgType from .interface import GracefulDisconnect from .lnrouter import fee_for_edge_msat from .lnutil import ln_dummy_address from .json_db import StoredDict from .invoices import PR_PAID if TYPE_CHECKING: from .lnworker import LNGossip, LNWallet from .lnrouter import LNPaymentRoute from .transaction import PartialTransaction LN_P2P_NETWORK_TIMEOUT = 20 class Peer(Logger): LOGGING_SHORTCUT = 'P' ORDERED_MESSAGES = ( 'accept_channel', 'funding_signed', 'funding_created', 'accept_channel', 'channel_reestablish', 'closing_signed') SPAMMY_MESSAGES = ( 'ping', 'pong', 'channel_announcement', 'node_announcement', 'channel_update',) def __init__( self, lnworker: Union['LNGossip', 'LNWallet'], pubkey: bytes, transport: LNTransportBase, *, is_channel_backup= False): self.is_channel_backup = is_channel_backup self._sent_init = False # type: bool self._received_init = False # type: bool self.initialized = asyncio.Future() self.got_disconnected = asyncio.Event() self.querying = asyncio.Event() self.transport = transport self.pubkey = pubkey # remote pubkey self.lnworker = lnworker self.privkey = self.transport.privkey # local privkey self.features = self.lnworker.features # type: LnFeatures self.their_features = LnFeatures(0) # type: LnFeatures self.node_ids = [self.pubkey, privkey_to_pubkey(self.privkey)] assert self.node_ids[0] != self.node_ids[1] self.network = lnworker.network self.ping_time = 0 self.reply_channel_range = asyncio.Queue() # gossip uses a single queue to preserve message order self.gossip_queue = asyncio.Queue() self.ordered_message_queues = defaultdict(asyncio.Queue) # for messsage that are ordered self.temp_id_to_id = {} # to forward error messages self.funding_created_sent = set() # for channels in PREOPENING self.funding_signed_sent = set() # for channels in PREOPENING self.shutdown_received = {} # chan_id -> asyncio.Future() self.announcement_signatures = defaultdict(asyncio.Queue) self.orphan_channel_updates = OrderedDict() # type: OrderedDict[ShortChannelID, dict] Logger.__init__(self) self.taskgroup = SilentTaskGroup() # HTLCs offered by REMOTE, that we started removing but are still active: self.received_htlcs_pending_removal = set() # type: Set[Tuple[Channel, int]] self.received_htlc_removed_event = asyncio.Event() self._htlc_switch_iterstart_event = asyncio.Event() self._htlc_switch_iterdone_event = asyncio.Event() def send_message(self, message_name: str, **kwargs): assert type(message_name) is str if message_name not in self.SPAMMY_MESSAGES: self.logger.debug(f"Sending {message_name.upper()}") if message_name.upper() != "INIT" and not self.is_initialized(): raise Exception("tried to send message before we are initialized") raw_msg = encode_msg(message_name, **kwargs) self._store_raw_msg_if_local_update(raw_msg, message_name=message_name, channel_id=kwargs.get("channel_id")) self.transport.send_bytes(raw_msg) def _store_raw_msg_if_local_update(self, raw_msg: bytes, *, message_name: str, channel_id: Optional[bytes]): is_commitment_signed = message_name == "commitment_signed" if not (message_name.startswith("update_") or is_commitment_signed): return assert channel_id chan = self.get_channel_by_id(channel_id) if not chan: raise Exception(f"channel {channel_id.hex()} not found for peer {self.pubkey.hex()}") chan.hm.store_local_update_raw_msg(raw_msg, is_commitment_signed=is_commitment_signed) if is_commitment_signed: # saving now, to ensure replaying updates works (in case of channel reestablishment) self.lnworker.save_channel(chan) def maybe_set_initialized(self): if self.initialized.done(): return if self._sent_init and self._received_init: self.initialized.set_result(True) def is_initialized(self) -> bool: return (self.initialized.done() and not self.initialized.cancelled() and self.initialized.exception() is None and self.initialized.result() is True) async def initialize(self): if isinstance(self.transport, LNTransport): await self.transport.handshake() features = self.features.for_init_message() b = int.bit_length(features) flen = b // 8 + int(bool(b % 8)) self.send_message( "init", gflen=0, flen=flen, features=features, init_tlvs={ 'networks': {'chains': constants.net.rev_genesis_bytes()} }) self._sent_init = True self.maybe_set_initialized() @property def channels(self) -> Dict[bytes, Channel]: return self.lnworker.channels_for_peer(self.pubkey) def get_channel_by_id(self, channel_id: bytes) -> Optional[Channel]: # note: this is faster than self.channels.get(channel_id) chan = self.lnworker.get_channel_by_id(channel_id) if not chan: return None if chan.node_id != self.pubkey: return None return chan def diagnostic_name(self): return self.lnworker.__class__.__name__ + ', ' + self.transport.name() def ping_if_required(self): if time.time() - self.ping_time > 120: self.send_message('ping', num_pong_bytes=4, byteslen=4) self.ping_time = time.time() def process_message(self, message): try: message_type, payload = decode_msg(message) except UnknownOptionalMsgType as e: self.logger.info(f"received unknown message from peer. ignoring: {e!r}") return if message_type not in self.SPAMMY_MESSAGES: self.logger.debug(f"Received {message_type.upper()}") # only process INIT if we are a backup if self.is_channel_backup is True and message_type != 'init': return if message_type in self.ORDERED_MESSAGES: chan_id = payload.get('channel_id') or payload["temporary_channel_id"] self.ordered_message_queues[chan_id].put_nowait((message_type, payload)) else: if message_type != 'error' and 'channel_id' in payload: chan = self.get_channel_by_id(payload['channel_id']) if chan is None: raise Exception('Got unknown '+ message_type) args = (chan, payload) else: args = (payload,) try: f = getattr(self, 'on_' + message_type) except AttributeError: #self.logger.info("Received '%s'" % message_type.upper(), payload) return # raw message is needed to check signature if message_type in ['node_announcement', 'channel_announcement', 'channel_update']: payload['raw'] = message execution_result = f(*args) if asyncio.iscoroutinefunction(f): asyncio.ensure_future(self.taskgroup.spawn(execution_result)) def on_error(self, payload): self.logger.info(f"remote peer sent error [DO NOT TRUST THIS MESSAGE]: {payload["data"].decode("ascii")}") chan_id = payload.get("channel_id") if chan_id in self.temp_id_to_id: chan_id = self.temp_id_to_id[chan_id] self.ordered_message_queues[chan_id].put_nowait((None, {'error':payload['data']})) def on_ping(self, payload): l = payload['num_pong_bytes'] self.send_message('pong', byteslen=l) def on_pong(self, payload): pass async def wait_for_message(self, expected_name, channel_id): q = self.ordered_message_queues[channel_id] name, payload = await asyncio.wait_for(q.get(), LN_P2P_NETWORK_TIMEOUT) if payload.get('error'): raise Exception('Remote peer reported error [DO NOT TRUST THIS MESSAGE]: ' + repr(payload.get('error'))) if name != expected_name: raise Exception(f"Received unexpected '{name}'") return payload def on_init(self, payload): if self._received_init: self.logger.info("ALREADY INITIALIZED BUT RECEIVED INIT") return self.their_features = LnFeatures(int.from_bytes(payload['features'], byteorder="big")) their_globalfeatures = int.from_bytes(payload['globalfeatures'], byteorder="big") self.their_features |= their_globalfeatures # check transitive dependencies for received features if not self.their_features.validate_transitive_dependencies(): raise GracefulDisconnect("remote did not set all dependencies for the features they sent") # check if features are compatible, and set self.features to what we negotiated try: self.features = ln_compare_features(self.features, self.their_features) except IncompatibleLightningFeatures as e: self.initialized.set_exception(e) raise GracefulDisconnect(f"{str(e)}") # check that they are on the same chain as us, if provided their_networks = payload["init_tlvs"].get("networks") if their_networks: their_chains = list(chunks(their_networks["chains"], 32)) if constants.net.rev_genesis_bytes() not in their_chains: raise GracefulDisconnect(f"no common chain found with remote. (they sent: {their_chains})") # all checks passed self.lnworker.on_peer_successfully_established(self) self._received_init = True self.maybe_set_initialized() def on_node_announcement(self, payload): if self.lnworker.channel_db: self.gossip_queue.put_nowait(('node_announcement', payload)) def on_channel_announcement(self, payload): if self.lnworker.channel_db: self.gossip_queue.put_nowait(('channel_announcement', payload)) def on_channel_update(self, payload): self.maybe_save_remote_update(payload) if self.lnworker.channel_db: self.gossip_queue.put_nowait(('channel_update', payload)) def maybe_save_remote_update(self, payload): if not self.channels: return for chan in self.channels.values(): if chan.short_channel_id == payload['short_channel_id']: chan.set_remote_update(payload) self.logger.info("saved remote_update") break else: # Save (some bounded number of) orphan channel updates for later # as it might be for our own direct channel with this peer # (and we might not yet know the short channel id for that) # Background: this code is here to deal with a bug in LND, # see https://github.com/lightningnetwork/lnd/issues/3651 # and https://github.com/lightningnetwork/lightning-rfc/pull/657 # This code assumes gossip_queries is set. BOLT7: "if the # gossip_queries feature is negotiated, [a node] MUST NOT # send gossip it did not generate itself" short_channel_id = ShortChannelID(payload['short_channel_id']) self.logger.info(f'received orphan channel update {short_channel_id}') self.orphan_channel_updates[short_channel_id] = payload while len(self.orphan_channel_updates) > 25: self.orphan_channel_updates.popitem(last=False) def on_announcement_signatures(self, chan: Channel, payload): if chan.config[LOCAL].was_announced: h, local_node_sig, local_bitcoin_sig = self.send_announcement_signatures(chan) else: self.announcement_signatures[chan.channel_id].put_nowait(payload) def handle_disconnect(func): @functools.wraps(func) async def wrapper_func(self, *args, **kwargs): try: return await func(self, *args, **kwargs) except GracefulDisconnect as e: self.logger.log(e.log_level, f"Disconnecting: {repr(e)}") except (LightningPeerConnectionClosed, IncompatibleLightningFeatures, aiorpcx.socks.SOCKSError) as e: self.logger.info(f"Disconnecting: {repr(e)}") finally: self.close_and_cleanup() return wrapper_func @ignore_exceptions # do not kill outer taskgroup @log_exceptions @handle_disconnect async def main_loop(self): async with self.taskgroup as group: await group.spawn(self._message_loop()) await group.spawn(self.htlc_switch()) await group.spawn(self.query_gossip()) await group.spawn(self.process_gossip()) async def process_gossip(self): while True: await asyncio.sleep(5) if not self.network.lngossip: continue chan_anns = [] chan_upds = [] node_anns = [] while True: name, payload = await self.gossip_queue.get() if name == 'channel_announcement': chan_anns.append(payload) elif name == 'channel_update': chan_upds.append(payload) elif name == 'node_announcement': node_anns.append(payload) else: raise Exception('unknown message') if self.gossip_queue.empty(): break if self.network.lngossip: await self.network.lngossip.process_gossip(chan_anns, node_anns, chan_upds) async def query_gossip(self): try: await asyncio.wait_for(self.initialized, LN_P2P_NETWORK_TIMEOUT) except Exception as e: raise GracefulDisconnect(f"Failed to initialize: {e!r}") from e if self.lnworker == self.lnworker.network.lngossip: try: ids, complete = await asyncio.wait_for(self.get_channel_range(), LN_P2P_NETWORK_TIMEOUT) except asyncio.TimeoutError as e: raise GracefulDisconnect("query_channel_range timed out") from e self.logger.info('Received {} channel ids. (complete: {})'.format(len(ids), complete)) await self.lnworker.add_new_ids(ids) while True: todo = self.lnworker.get_ids_to_query() if not todo: await asyncio.sleep(1) continue await self.get_short_channel_ids(todo) async def get_channel_range(self): first_block = constants.net.BLOCK_HEIGHT_FIRST_LIGHTNING_CHANNELS num_blocks = self.lnworker.network.get_local_height() - first_block self.query_channel_range(first_block, num_blocks) intervals = [] ids = set() # note: implementations behave differently... # "sane implementation that follows BOLT-07" example: # query_channel_range. <<< first_block 497000, num_blocks 79038 # on_reply_channel_range. >>> first_block 497000, num_blocks 39516, num_ids 4648, complete True # on_reply_channel_range. >>> first_block 536516, num_blocks 19758, num_ids 5734, complete True # on_reply_channel_range. >>> first_block 556274, num_blocks 9879, num_ids 13712, complete True # on_reply_channel_range. >>> first_block 566153, num_blocks 9885, num_ids 18114, complete True # lnd example: # query_channel_range. <<< first_block 497000, num_blocks 79038 # on_reply_channel_range. >>> first_block 497000, num_blocks 79038, num_ids 8000, complete False # on_reply_channel_range. >>> first_block 497000, num_blocks 79038, num_ids 8000, complete False # on_reply_channel_range. >>> first_block 497000, num_blocks 79038, num_ids 8000, complete False # on_reply_channel_range. >>> first_block 497000, num_blocks 79038, num_ids 8000, complete False # on_reply_channel_range. >>> first_block 497000, num_blocks 79038, num_ids 5344, complete True while True: index, num, complete, _ids = await self.reply_channel_range.get() ids.update(_ids) intervals.append((index, index+num)) intervals.sort() while len(intervals) > 1: a,b = intervals[0] c,d = intervals[1] if not (a <= c and a <= b and c <= d): raise Exception(f"insane reply_channel_range intervals {(a,b,c,d)}") if b >= c: intervals = [(a,d)] + intervals[2:] else: break if len(intervals) == 1 and complete: a, b = intervals[0] if a <= first_block and b >= first_block + num_blocks: break return ids, complete def request_gossip(self, timestamp=0): if timestamp == 0: self.logger.info('requesting whole channel graph') else: self.logger.info(f'requesting channel graph since {datetime.fromtimestamp(timestamp).ctime()}') self.send_message( 'gossip_timestamp_filter', chain_hash=constants.net.rev_genesis_bytes(), first_timestamp=timestamp, timestamp_range=b'\xff'*4) def query_channel_range(self, first_block, num_blocks): self.logger.info(f'query channel range {first_block} {num_blocks}') self.send_message( 'query_channel_range', chain_hash=constants.net.rev_genesis_bytes(), first_blocknum=first_block, number_of_blocks=num_blocks) def decode_short_ids(self, encoded): if encoded[0] == 0: decoded = encoded[1:] elif encoded[0] == 1: decoded = zlib.decompress(encoded[1:]) else: raise Exception(f'decode_short_ids: unexpected first byte: {encoded[0]}') ids = [decoded[i:i+8] for i in range(0, len(decoded), 8)] return ids def on_reply_channel_range(self, payload): first = payload['first_blocknum'] num = payload['number_of_blocks'] complete = bool(int.from_bytes(payload['complete'], 'big')) encoded = payload['encoded_short_ids'] ids = self.decode_short_ids(encoded) #self.logger.info(f"on_reply_channel_range. >>> first_block {first}, num_blocks {num}, num_ids {len(ids)}, complete {repr(payload["complete"])}") self.reply_channel_range.put_nowait((first, num, complete, ids)) async def get_short_channel_ids(self, ids): self.logger.info(f'Querying {len(ids)} short_channel_ids') assert not self.querying.is_set() self.query_short_channel_ids(ids) await self.querying.wait() self.querying.clear() def query_short_channel_ids(self, ids, compressed=True): ids = sorted(ids) s = b''.join(ids) encoded = zlib.compress(s) if compressed else s prefix = b'\x01' if compressed else b'\x00' self.send_message( 'query_short_channel_ids', chain_hash=constants.net.rev_genesis_bytes(), len=1+len(encoded), encoded_short_ids=prefix+encoded) async def _message_loop(self): try: await asyncio.wait_for(self.initialize(), LN_P2P_NETWORK_TIMEOUT) except (OSError, asyncio.TimeoutError, HandshakeFailed) as e: raise GracefulDisconnect(f'initialize failed: {repr(e)}') from e async for msg in self.transport.read_messages(): self.process_message(msg) await asyncio.sleep(.01) def on_reply_short_channel_ids_end(self, payload): self.querying.set() def close_and_cleanup(self): # note: This method might get called multiple times! # E.g. if you call close_and_cleanup() to cause a disconnection from the peer, # it will get called a second time in handle_disconnect(). try: if self.transport: self.transport.close() except: pass self.lnworker.peer_closed(self) self.got_disconnected.set() def is_static_remotekey(self): return self.features.supports(LnFeatures.OPTION_STATIC_REMOTEKEY_OPT) def is_upfront_shutdown_script(self): return self.features.supports(LnFeatures.OPTION_UPFRONT_SHUTDOWN_SCRIPT_OPT) def upfront_shutdown_script_from_payload(self, payload, msg_identifier: str) -> Optional[bytes]: if msg_identifier not in ['accept', 'open']: raise ValueError("msg_identifier must be either 'accept' or 'open'") uss_tlv = payload[msg_identifier + '_channel_tlvs'].get( 'upfront_shutdown_script') if uss_tlv and self.is_upfront_shutdown_script(): upfront_shutdown_script = uss_tlv['shutdown_scriptpubkey'] else: upfront_shutdown_script = b'' self.logger.info(f"upfront shutdown script received: {upfront_shutdown_script}") return upfront_shutdown_script def make_local_config(self, funding_sat: int, push_msat: int, initiator: HTLCOwner) -> LocalConfig: channel_seed = os.urandom(32) initial_msat = funding_sat * 1000 - push_msat if initiator == LOCAL else push_msat static_remotekey = None # sending empty bytes as the upfront_shutdown_script will give us the # flexibility to decide an address at closing time upfront_shutdown_script = b'' if self.is_static_remotekey(): wallet = self.lnworker.wallet assert wallet.txin_type == 'p2wpkh' addr = wallet.get_new_sweep_address_for_channel() static_remotekey = bfh(wallet.get_public_key(addr)) else: static_remotekey = None dust_limit_sat = bitcoin.DUST_LIMIT_DEFAULT_SAT_LEGACY reserve_sat = max(funding_sat // 100, dust_limit_sat) # for comparison of defaults, see # https://github.com/ACINQ/eclair/blob/afa378fbb73c265da44856b4ad0f2128a88ae6c6/eclair-core/src/main/resources/reference.conf#L66 # https://github.com/ElementsProject/lightning/blob/0056dd75572a8857cff36fcbdb1a2295a1ac9253/lightningd/options.c#L657 # https://github.com/lightningnetwork/lnd/blob/56b61078c5b2be007d318673a5f3b40c6346883a/config.go#L81 local_config = LocalConfig.from_seed( channel_seed=channel_seed, static_remotekey=static_remotekey, upfront_shutdown_script=upfront_shutdown_script, to_self_delay=self.network.config.get('lightning_to_self_delay', 7 * 144), dust_limit_sat=dust_limit_sat, max_htlc_value_in_flight_msat=funding_sat * 1000, max_accepted_htlcs=30, initial_msat=initial_msat, reserve_sat=reserve_sat, funding_locked_received=False, was_announced=False, current_commitment_signature=None, current_htlc_signatures=b'', htlc_minimum_msat=1, ) local_config.validate_params(funding_sat=funding_sat) return local_config def temporarily_reserve_funding_tx_change_address(func): # During the channel open flow, if we initiated, we might have used a change address # of ours in the funding tx. The funding tx is not part of the wallet history # at that point yet, but we should already consider this change address as 'used'. @functools.wraps(func) async def wrapper(self: 'Peer', *args, **kwargs): funding_tx = kwargs['funding_tx'] # type: PartialTransaction wallet = self.lnworker.wallet change_addresses = [txout.address for txout in funding_tx.outputs() if wallet.is_change(txout.address)] for addr in change_addresses: wallet.set_reserved_state_of_address(addr, reserved=True) try: return await func(self, *args, **kwargs) finally: for addr in change_addresses: self.lnworker.wallet.set_reserved_state_of_address(addr, reserved=False) return wrapper @log_exceptions @temporarily_reserve_funding_tx_change_address async def channel_establishment_flow( self, *, funding_tx: 'PartialTransaction', funding_sat: int, push_msat: int, temp_channel_id: bytes ) -> Tuple[Channel, 'PartialTransaction']: """Implements the channel opening flow. -> open_channel message <- accept_channel message -> funding_created message <- funding_signed message Channel configurations are initialized in this method. """ # will raise if init fails await asyncio.wait_for(self.initialized, LN_P2P_NETWORK_TIMEOUT) # trampoline is not yet in features if not self.lnworker.channel_db and not self.lnworker.is_trampoline_peer(self.pubkey): raise Exception('Not a trampoline node: ' + str(self.their_features)) feerate = self.lnworker.current_feerate_per_kw() local_config = self.make_local_config(funding_sat, push_msat, LOCAL) # for the first commitment transaction per_commitment_secret_first = get_per_commitment_secret_from_seed( local_config.per_commitment_secret_seed, RevocationStore.START_INDEX ) per_commitment_point_first = secret_to_pubkey( int.from_bytes(per_commitment_secret_first, 'big')) self.send_message( "open_channel", temporary_channel_id=temp_channel_id, chain_hash=constants.net.rev_genesis_bytes(), funding_satoshis=funding_sat, push_msat=push_msat, dust_limit_satoshis=local_config.dust_limit_sat, feerate_per_kw=feerate, max_accepted_htlcs=local_config.max_accepted_htlcs, funding_pubkey=local_config.multisig_key.pubkey, revocation_basepoint=local_config.revocation_basepoint.pubkey, htlc_basepoint=local_config.htlc_basepoint.pubkey, payment_basepoint=local_config.payment_basepoint.pubkey, delayed_payment_basepoint=local_config.delayed_basepoint.pubkey, first_per_commitment_point=per_commitment_point_first, to_self_delay=local_config.to_self_delay, max_htlc_value_in_flight_msat=local_config.max_htlc_value_in_flight_msat, channel_flags=0x00, # not willing to announce channel channel_reserve_satoshis=local_config.reserve_sat, htlc_minimum_msat=local_config.htlc_minimum_msat, open_channel_tlvs={ 'upfront_shutdown_script': {'shutdown_scriptpubkey': local_config.upfront_shutdown_script} } ) # <- accept_channel payload = await self.wait_for_message('accept_channel', temp_channel_id) remote_per_commitment_point = payload['first_per_commitment_point'] funding_txn_minimum_depth = payload['minimum_depth'] if funding_txn_minimum_depth <= 0: raise Exception(f"minimum depth too low, {funding_txn_minimum_depth}") if funding_txn_minimum_depth > 30: raise Exception(f"minimum depth too high, {funding_txn_minimum_depth}") upfront_shutdown_script = self.upfront_shutdown_script_from_payload( payload, 'accept') remote_config = RemoteConfig( payment_basepoint=OnlyPubkeyKeypair(payload['payment_basepoint']), multisig_key=OnlyPubkeyKeypair(payload["funding_pubkey"]), htlc_basepoint=OnlyPubkeyKeypair(payload['htlc_basepoint']), delayed_basepoint=OnlyPubkeyKeypair(payload['delayed_payment_basepoint']), revocation_basepoint=OnlyPubkeyKeypair(payload['revocation_basepoint']), to_self_delay=payload['to_self_delay'], dust_limit_sat=payload['dust_limit_satoshis'], max_htlc_value_in_flight_msat=payload['max_htlc_value_in_flight_msat'], max_accepted_htlcs=payload["max_accepted_htlcs"], initial_msat=push_msat, reserve_sat=payload["channel_reserve_satoshis"], htlc_minimum_msat=payload['htlc_minimum_msat'], next_per_commitment_point=remote_per_commitment_point, current_per_commitment_point=None, upfront_shutdown_script=upfront_shutdown_script ) ChannelConfig.cross_validate_params( local_config=local_config, remote_config=remote_config, funding_sat=funding_sat, is_local_initiator=True, initial_feerate_per_kw=feerate, ) # -> funding created # replace dummy output in funding tx redeem_script = funding_output_script(local_config, remote_config) funding_address = bitcoin.redeem_script_to_address('p2wsh', redeem_script) funding_output = PartialTxOutput.from_address_and_value(funding_address, funding_sat) dummy_output = PartialTxOutput.from_address_and_value(ln_dummy_address(), funding_sat) if dummy_output not in funding_tx.outputs(): raise Exception("LN dummy output (err 1)") funding_tx._outputs.remove(dummy_output) if dummy_output in funding_tx.outputs(): raise Exception("LN dummy output (err 2)") funding_tx.add_outputs([funding_output]) # find and encrypt op_return data associated to funding_address has_onchain_backup = self.lnworker and self.lnworker.has_recoverable_channels() if has_onchain_backup: backup_data = self.lnworker.cb_data(self.pubkey) dummy_scriptpubkey = make_op_return(backup_data) for o in funding_tx.outputs(): if o.scriptpubkey == dummy_scriptpubkey: encrypted_data = self.lnworker.encrypt_cb_data(backup_data, funding_address) assert len(encrypted_data) == len(backup_data) o.scriptpubkey = make_op_return(encrypted_data) break else: raise Exception('op_return output not found in funding tx') # must not be malleable funding_tx.set_rbf(False) if not funding_tx.is_segwit(): raise Exception('Funding transaction is not segwit') funding_txid = funding_tx.txid() assert funding_txid funding_index = funding_tx.outputs().index(funding_output) # build remote commitment transaction channel_id, funding_txid_bytes = channel_id_from_funding_tx(funding_txid, funding_index) outpoint = Outpoint(funding_txid, funding_index) constraints = ChannelConstraints( capacity=funding_sat, is_initiator=True, funding_txn_minimum_depth=funding_txn_minimum_depth ) storage = self.create_channel_storage( channel_id, outpoint, local_config, remote_config, constraints) chan = Channel( storage, sweep_address=self.lnworker.sweep_address, lnworker=self.lnworker, initial_feerate=feerate ) chan.storage['funding_inputs'] = [txin.prevout.to_json() for txin in funding_tx.inputs()] chan.storage['has_onchain_backup'] = has_onchain_backup if isinstance(self.transport, LNTransport): chan.add_or_update_peer_addr(self.transport.peer_addr) sig_64, _ = chan.sign_next_commitment() self.temp_id_to_id[temp_channel_id] = channel_id self.send_message("funding_created", temporary_channel_id=temp_channel_id, funding_txid=funding_txid_bytes, funding_output_index=funding_index, signature=sig_64) self.funding_created_sent.add(channel_id) # <- funding signed payload = await self.wait_for_message('funding_signed', channel_id) self.logger.info('received funding_signed') remote_sig = payload['signature'] chan.receive_new_commitment(remote_sig, []) chan.open_with_first_pcp(remote_per_commitment_point, remote_sig) chan.set_state(ChannelState.OPENING) self.lnworker.add_new_channel(chan) return chan, funding_tx def create_channel_storage(self, channel_id, outpoint, local_config, remote_config, constraints): chan_dict = { "node_id": self.pubkey.hex(), "channel_id": channel_id.hex(), "short_channel_id": None, "funding_outpoint": outpoint, "remote_config": remote_config, "local_config": local_config, "constraints": constraints, "remote_update": None, "state": ChannelState.PREOPENING.name, 'onion_keys': {}, 'data_loss_protect_remote_pcp': {}, "log": {}, "fail_htlc_reasons": {}, # htlc_id -> onion_packet "unfulfilled_htlcs": {}, # htlc_id -> error_bytes, failure_message "revocation_store": {}, "static_remotekey_enabled": self.is_static_remotekey(), # stored because it cannot be "downgraded", per BOLT2 } return StoredDict(chan_dict, self.lnworker.db if self.lnworker else None, []) async def on_open_channel(self, payload): """Implements the channel acceptance flow. <- open_channel message -> accept_channel message <- funding_created message -> funding_signed message Channel configurations are initialized in this method. """ if self.lnworker.has_recoverable_channels(): # FIXME: we might want to keep the connection open raise Exception('not accepting channels') # <- open_channel if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception('wrong chain_hash') funding_sat = payload['funding_satoshis'] push_msat = payload['push_msat'] feerate = payload['feerate_per_kw'] # note: we are not validating this temp_chan_id = payload['temporary_channel_id'] local_config = self.make_local_config(funding_sat, push_msat, REMOTE) upfront_shutdown_script = self.upfront_shutdown_script_from_payload( payload, 'open') remote_config = RemoteConfig( payment_basepoint=OnlyPubkeyKeypair(payload['payment_basepoint']), multisig_key=OnlyPubkeyKeypair(payload['funding_pubkey']), htlc_basepoint=OnlyPubkeyKeypair(payload['htlc_basepoint']), delayed_basepoint=OnlyPubkeyKeypair(payload['delayed_payment_basepoint']), revocation_basepoint=OnlyPubkeyKeypair(payload['revocation_basepoint']), to_self_delay=payload['to_self_delay'], dust_limit_sat=payload['dust_limit_satoshis'], max_htlc_value_in_flight_msat=payload['max_htlc_value_in_flight_msat'], max_accepted_htlcs=payload['max_accepted_htlcs'], initial_msat=funding_sat * 1000 - push_msat, reserve_sat=payload['channel_reserve_satoshis'], htlc_minimum_msat=payload['htlc_minimum_msat'], next_per_commitment_point=payload['first_per_commitment_point'], current_per_commitment_point=None, upfront_shutdown_script=upfront_shutdown_script, ) ChannelConfig.cross_validate_params( local_config=local_config, remote_config=remote_config, funding_sat=funding_sat, is_local_initiator=False, initial_feerate_per_kw=feerate, ) # note: we ignore payload['channel_flags'], which e.g. contains 'announce_channel'. # Notably if the remote sets 'announce_channel' to True, we will ignore that too, # but we will not play along with actually announcing the channel (so we keep it private). # -> accept channel # for the first commitment transaction per_commitment_secret_first = get_per_commitment_secret_from_seed( local_config.per_commitment_secret_seed, RevocationStore.START_INDEX ) per_commitment_point_first = secret_to_pubkey( int.from_bytes(per_commitment_secret_first, 'big')) min_depth = 3 self.send_message( 'accept_channel', temporary_channel_id=temp_chan_id, dust_limit_satoshis=local_config.dust_limit_sat, max_htlc_value_in_flight_msat=local_config.max_htlc_value_in_flight_msat, channel_reserve_satoshis=local_config.reserve_sat, htlc_minimum_msat=local_config.htlc_minimum_msat, minimum_depth=min_depth, to_self_delay=local_config.to_self_delay, max_accepted_htlcs=local_config.max_accepted_htlcs, funding_pubkey=local_config.multisig_key.pubkey, revocation_basepoint=local_config.revocation_basepoint.pubkey, payment_basepoint=local_config.payment_basepoint.pubkey, delayed_payment_basepoint=local_config.delayed_basepoint.pubkey, htlc_basepoint=local_config.htlc_basepoint.pubkey, first_per_commitment_point=per_commitment_point_first, accept_channel_tlvs={ 'upfront_shutdown_script': {'shutdown_scriptpubkey': local_config.upfront_shutdown_script} } ) # <- funding created funding_created = await self.wait_for_message('funding_created', temp_chan_id) # -> funding signed funding_idx = funding_created['funding_output_index'] funding_txid = bh2u(funding_created['funding_txid'][::-1]) channel_id, funding_txid_bytes = channel_id_from_funding_tx(funding_txid, funding_idx) constraints = ChannelConstraints( capacity=funding_sat, is_initiator=False, funding_txn_minimum_depth=min_depth ) outpoint = Outpoint(funding_txid, funding_idx) chan_dict = self.create_channel_storage( channel_id, outpoint, local_config, remote_config, constraints) chan = Channel( chan_dict, sweep_address=self.lnworker.sweep_address, lnworker=self.lnworker, initial_feerate=feerate ) chan.storage['init_timestamp'] = int(time.time()) if isinstance(self.transport, LNTransport): chan.add_or_update_peer_addr(self.transport.peer_addr) remote_sig = funding_created['signature'] chan.receive_new_commitment(remote_sig, []) sig_64, _ = chan.sign_next_commitment() self.send_message('funding_signed', channel_id=channel_id, signature=sig_64, ) self.funding_signed_sent.add(chan.channel_id) chan.open_with_first_pcp(payload['first_per_commitment_point'], remote_sig) chan.set_state(ChannelState.OPENING) self.lnworker.add_new_channel(chan) async def trigger_force_close(self, channel_id: bytes): await self.initialized latest_point = secret_to_pubkey(42) # we need a valid point (BOLT2) self.send_message( "channel_reestablish", channel_id=channel_id, next_commitment_number=0, next_revocation_number=0, your_last_per_commitment_secret=0, my_current_per_commitment_point=latest_point) async def reestablish_channel(self, chan: Channel): await self.initialized chan_id = chan.channel_id if chan.should_request_force_close: await self.trigger_force_close(chan_id) chan.should_request_force_close = False return assert ChannelState.PREOPENING < chan.get_state() < ChannelState.FORCE_CLOSING if chan.peer_state != PeerState.DISCONNECTED: self.logger.info(f'reestablish_channel was called but channel {chan.get_id_for_log()} ' f'already in peer_state {chan.peer_state!r}') return chan.peer_state = PeerState.REESTABLISHING util.trigger_callback('channel', self.lnworker.wallet, chan) # BOLT-02: "A node [...] upon disconnection [...] MUST reverse any uncommitted updates sent by the other side" chan.hm.discard_unsigned_remote_updates() # ctns oldest_unrevoked_local_ctn = chan.get_oldest_unrevoked_ctn(LOCAL) latest_local_ctn = chan.get_latest_ctn(LOCAL) next_local_ctn = chan.get_next_ctn(LOCAL) oldest_unrevoked_remote_ctn = chan.get_oldest_unrevoked_ctn(REMOTE) latest_remote_ctn = chan.get_latest_ctn(REMOTE) next_remote_ctn = chan.get_next_ctn(REMOTE) assert self.features.supports(LnFeatures.OPTION_DATA_LOSS_PROTECT_OPT) # send message if chan.is_static_remotekey_enabled(): latest_secret, latest_point = chan.get_secret_and_point(LOCAL, 0) else: latest_secret, latest_point = chan.get_secret_and_point(LOCAL, latest_local_ctn) if oldest_unrevoked_remote_ctn == 0: last_rev_secret = 0 else: last_rev_index = oldest_unrevoked_remote_ctn - 1 last_rev_secret = chan.revocation_store.retrieve_secret(RevocationStore.START_INDEX - last_rev_index) self.send_message( "channel_reestablish", channel_id=chan_id, next_commitment_number=next_local_ctn, next_revocation_number=oldest_unrevoked_remote_ctn, your_last_per_commitment_secret=last_rev_secret, my_current_per_commitment_point=latest_point) self.logger.info(f'channel_reestablish ({chan.get_id_for_log()}): sent channel_reestablish with ' f'(next_local_ctn={next_local_ctn}, ' f'oldest_unrevoked_remote_ctn={oldest_unrevoked_remote_ctn})') while True: try: msg = await self.wait_for_message('channel_reestablish', chan_id) break except asyncio.TimeoutError: self.logger.info('waiting to receive channel_reestablish...') continue except Exception as e: # do not kill connection, because we might have other channels with that peer self.logger.info(f'channel_reestablish failed, {e}') return their_next_local_ctn = msg["next_commitment_number"] their_oldest_unrevoked_remote_ctn = msg["next_revocation_number"] their_local_pcp = msg.get("my_current_per_commitment_point") their_claim_of_our_last_per_commitment_secret = msg.get("your_last_per_commitment_secret") self.logger.info(f'channel_reestablish ({chan.get_id_for_log()}): received channel_reestablish with ' f'(their_next_local_ctn={their_next_local_ctn}, ' f'their_oldest_unrevoked_remote_ctn={their_oldest_unrevoked_remote_ctn})') # sanity checks of received values if their_next_local_ctn < 0: raise RemoteMisbehaving(f"channel reestablish: their_next_local_ctn < 0") if their_oldest_unrevoked_remote_ctn < 0: raise RemoteMisbehaving(f"channel reestablish: their_oldest_unrevoked_remote_ctn < 0") # Replay un-acked local updates (including commitment_signed) byte-for-byte. # If we have sent them a commitment signature that they "lost" (due to disconnect), # we need to make sure we replay the same local updates, as otherwise they could # end up with two (or more) signed valid commitment transactions at the same ctn. # Multiple valid ctxs at the same ctn is a major headache for pre-signing spending txns, # e.g. for watchtowers, hence we must ensure these ctxs coincide. # We replay the local updates even if they were not yet committed. unacked = chan.hm.get_unacked_local_updates() n_replayed_msgs = 0 for ctn, messages in unacked.items(): if ctn < their_next_local_ctn: # They claim to have received these messages and the corresponding # commitment_signed, hence we must not replay them. continue for raw_upd_msg in messages: self.transport.send_bytes(raw_upd_msg) n_replayed_msgs += 1 self.logger.info(f'channel_reestablish ({chan.get_id_for_log()}): replayed {n_replayed_msgs} unacked messages') we_are_ahead = False they_are_ahead = False # compare remote ctns if next_remote_ctn != their_next_local_ctn: if their_next_local_ctn == latest_remote_ctn and chan.hm.is_revack_pending(REMOTE): # We replayed the local updates (see above), which should have contained a commitment_signed # (due to is_revack_pending being true), and this should have remedied this situation. pass else: self.logger.warning(f"channel_reestablish ({chan.get_id_for_log()}): " f"expected remote ctn {next_remote_ctn}, got {their_next_local_ctn}") if their_next_local_ctn < next_remote_ctn: we_are_ahead = True else: they_are_ahead = True # compare local ctns if oldest_unrevoked_local_ctn != their_oldest_unrevoked_remote_ctn: if oldest_unrevoked_local_ctn - 1 == their_oldest_unrevoked_remote_ctn: # A node: # if next_revocation_number is equal to the commitment number of the last revoke_and_ack # the receiving node sent, AND the receiving node hasn't already received a closing_signed: # MUST re-send the revoke_and_ack. last_secret, last_point = chan.get_secret_and_point(LOCAL, oldest_unrevoked_local_ctn - 1) next_secret, next_point = chan.get_secret_and_point(LOCAL, oldest_unrevoked_local_ctn + 1) self.send_message( "revoke_and_ack", channel_id=chan.channel_id, per_commitment_secret=last_secret, next_per_commitment_point=next_point) else: self.logger.warning(f"channel_reestablish ({chan.get_id_for_log()}): " f"expected local ctn {oldest_unrevoked_local_ctn}, got {their_oldest_unrevoked_remote_ctn}") if their_oldest_unrevoked_remote_ctn < oldest_unrevoked_local_ctn: we_are_ahead = True else: they_are_ahead = True # option_data_loss_protect def are_datalossprotect_fields_valid() -> bool: if their_local_pcp is None or their_claim_of_our_last_per_commitment_secret is None: return False if their_oldest_unrevoked_remote_ctn > 0: our_pcs, __ = chan.get_secret_and_point(LOCAL, their_oldest_unrevoked_remote_ctn - 1) else: assert their_oldest_unrevoked_remote_ctn == 0 our_pcs = bytes(32) if our_pcs != their_claim_of_our_last_per_commitment_secret: self.logger.error(f"channel_reestablish ({chan.get_id_for_log()}): " f"(DLP) local PCS mismatch: {bh2u(our_pcs)} != {bh2u(their_claim_of_our_last_per_commitment_secret)}") return False if chan.is_static_remotekey_enabled(): return True try: __, our_remote_pcp = chan.get_secret_and_point(REMOTE, their_next_local_ctn - 1) except RemoteCtnTooFarInFuture: pass else: if our_remote_pcp != their_local_pcp: self.logger.error(f"channel_reestablish ({chan.get_id_for_log()}): " f"(DLP) remote PCP mismatch: {bh2u(our_remote_pcp)} != {bh2u(their_local_pcp)}") return False return True if not are_datalossprotect_fields_valid(): raise RemoteMisbehaving("channel_reestablish: data loss protect fields invalid") if they_are_ahead: self.logger.warning(f"channel_reestablish ({chan.get_id_for_log()}): " f"remote is ahead of us! They should force-close. Remote PCP: {bh2u(their_local_pcp)}") # data_loss_protect_remote_pcp is used in lnsweep chan.set_data_loss_protect_remote_pcp(their_next_local_ctn - 1, their_local_pcp) self.lnworker.save_channel(chan) chan.peer_state = PeerState.BAD return elif we_are_ahead: self.logger.warning(f"channel_reestablish ({chan.get_id_for_log()}): we are ahead of remote! trying to force-close.") await self.lnworker.try_force_closing(chan_id) return chan.peer_state = PeerState.GOOD if chan.is_funded() and their_next_local_ctn == next_local_ctn == 1: self.send_funding_locked(chan) # checks done if chan.is_funded() and chan.config[LOCAL].funding_locked_received: self.mark_open(chan) util.trigger_callback('channel', self.lnworker.wallet, chan) # if we have sent a previous shutdown, it must be retransmitted (Bolt2) if chan.get_state() == ChannelState.SHUTDOWN: await self.send_shutdown(chan) def send_funding_locked(self, chan: Channel): channel_id = chan.channel_id per_commitment_secret_index = RevocationStore.START_INDEX - 1 per_commitment_point_second = secret_to_pubkey(int.from_bytes( get_per_commitment_secret_from_seed(chan.config[LOCAL].per_commitment_secret_seed, per_commitment_secret_index), 'big')) # note: if funding_locked was not yet received, we might send it multiple times self.send_message("funding_locked", channel_id=channel_id, next_per_commitment_point=per_commitment_point_second) if chan.is_funded() and chan.config[LOCAL].funding_locked_received: self.mark_open(chan) def on_funding_locked(self, chan: Channel, payload): self.logger.info(f"on_funding_locked. channel: {bh2u(chan.channel_id)}") if not chan.config[LOCAL].funding_locked_received: their_next_point = payload["next_per_commitment_point"] chan.config[REMOTE].next_per_commitment_point = their_next_point chan.config[LOCAL].funding_locked_received = True self.lnworker.save_channel(chan) if chan.is_funded(): self.mark_open(chan) def on_network_update(self, chan: Channel, funding_tx_depth: int): """ Only called when the channel is OPEN. Runs on the Network thread. """ if not chan.config[LOCAL].was_announced and funding_tx_depth >= 6: # don't announce our channels # FIXME should this be a field in chan.local_state maybe? return chan.config[LOCAL].was_announced = True self.lnworker.save_channel(chan) coro = self.handle_announcements(chan) asyncio.run_coroutine_threadsafe(coro, self.network.asyncio_loop) @log_exceptions async def handle_announcements(self, chan: Channel): h, local_node_sig, local_bitcoin_sig = self.send_announcement_signatures(chan) announcement_signatures_msg = await self.announcement_signatures[chan.channel_id].get() remote_node_sig = announcement_signatures_msg["node_signature"] remote_bitcoin_sig = announcement_signatures_msg["bitcoin_signature"] if not ecc.verify_signature(chan.config[REMOTE].multisig_key.pubkey, remote_bitcoin_sig, h): raise Exception("bitcoin_sig invalid in announcement_signatures") if not ecc.verify_signature(self.pubkey, remote_node_sig, h): raise Exception("node_sig invalid in announcement_signatures") node_sigs = [remote_node_sig, local_node_sig] bitcoin_sigs = [remote_bitcoin_sig, local_bitcoin_sig] bitcoin_keys = [chan.config[REMOTE].multisig_key.pubkey, chan.config[LOCAL].multisig_key.pubkey] if self.node_ids[0] > self.node_ids[1]: node_sigs.reverse() bitcoin_sigs.reverse() node_ids = list(reversed(self.node_ids)) bitcoin_keys.reverse() else: node_ids = self.node_ids self.send_message("channel_announcement", node_signatures_1=node_sigs[0], node_signatures_2=node_sigs[1], bitcoin_signature_1=bitcoin_sigs[0], bitcoin_signature_2=bitcoin_sigs[1], len=0, #features not set (defaults to zeros) chain_hash=constants.net.rev_genesis_bytes(), short_channel_id=chan.short_channel_id, node_id_1=node_ids[0], node_id_2=node_ids[1], bitcoin_key_1=bitcoin_keys[0], bitcoin_key_2=bitcoin_keys[1] ) def mark_open(self, chan: Channel): assert chan.is_funded() # only allow state transition from "FUNDED" to "OPEN" old_state = chan.get_state() if old_state == ChannelState.OPEN: return if old_state != ChannelState.FUNDED: self.logger.info(f"cannot mark open ({chan.get_id_for_log()}), current state: {repr(old_state)}") return assert chan.config[LOCAL].funding_locked_received chan.set_state(ChannelState.OPEN) util.trigger_callback('channel', self.lnworker.wallet, chan) # peer may have sent us a channel update for the incoming direction previously pending_channel_update = self.orphan_channel_updates.get(chan.short_channel_id) if pending_channel_update: chan.set_remote_update(pending_channel_update) self.logger.info(f"CHANNEL OPENING COMPLETED ({chan.get_id_for_log()})") forwarding_enabled = self.network.config.get('lightning_forward_payments', False) if forwarding_enabled: # send channel_update of outgoing edge to peer, # so that channel can be used to to receive payments self.logger.info(f"sending channel update for outgoing edge ({chan.get_id_for_log()})") chan_upd = chan.get_outgoing_gossip_channel_update() self.transport.send_bytes(chan_upd) def send_announcement_signatures(self, chan: Channel): chan_ann = chan.construct_channel_announcement_without_sigs() preimage = chan_ann[256+2:] msg_hash = sha256(preimage) bitcoin_signature = ecc.ECPrivkey(chan.config[LOCAL].multisig_key.privkey).sign(msg_hash, sig_string_from_r_and_s) node_signature = ecc.ECPrivkey(self.privkey).sign(msg_hash, sig_string_from_r_and_s) self.send_message("announcement_signatures", channel_id=chan.channel_id, short_channel_id=chan.short_channel_id, node_signature=node_signature, bitcoin_signature=bitcoin_signature ) return msg_hash, node_signature, bitcoin_signature def on_update_fail_htlc(self, chan: Channel, payload): htlc_id = payload["id"] reason = payload["reason"] self.logger.info(f"on_update_fail_htlc. chan {chan.short_channel_id}. htlc_id {htlc_id}") chan.receive_fail_htlc(htlc_id, error_bytes=reason) # TODO handle exc and maybe fail channel (e.g. bad htlc_id) self.maybe_send_commitment(chan) def maybe_send_commitment(self, chan: Channel): # REMOTE should revoke first before we can sign a new ctx if chan.hm.is_revack_pending(REMOTE): return # if there are no changes, we will not (and must not) send a new commitment if not chan.has_pending_changes(REMOTE): return self.logger.info(f'send_commitment. chan {chan.short_channel_id}. ctn: {chan.get_next_ctn(REMOTE)}.') sig_64, htlc_sigs = chan.sign_next_commitment() self.send_message("commitment_signed", channel_id=chan.channel_id, signature=sig_64, num_htlcs=len(htlc_sigs), htlc_signature=b"".join(htlc_sigs)) def pay(self, *, route: 'LNPaymentRoute', chan: Channel, amount_msat: int, total_msat: int, payment_hash: bytes, min_final_cltv_expiry: int, payment_secret: bytes = None, trampoline_onion=None) -> UpdateAddHtlc: assert amount_msat > 0, "amount_msat is not greater zero" assert len(route) > 0 if not chan.can_send_update_add_htlc(): raise PaymentFailure("Channel cannot send update_add_htlc") # add features learned during "init" for direct neighbour: route[0].node_features |= self.features local_height = self.network.get_local_height() final_cltv = local_height + min_final_cltv_expiry hops_data, amount_msat, cltv = calc_hops_data_for_payment( route, amount_msat, final_cltv, total_msat=total_msat, payment_secret=payment_secret) num_hops = len(hops_data) self.logger.info(f"lnpeer.pay len(route)={len(route)}") for i in range(len(route)): self.logger.info(f" {i}: edge={route[i].short_channel_id} hop_data={hops_data[i]!r}") assert final_cltv <= cltv, (final_cltv, cltv) session_key = os.urandom(32) # session_key # if we are forwarding a trampoline payment, add trampoline onion if trampoline_onion: self.logger.info(f'adding trampoline onion to final payload') trampoline_payload = hops_data[num_hops-2].payload trampoline_payload["trampoline_onion_packet"] = { "version": trampoline_onion.version, "public_key": trampoline_onion.public_key, "hops_data": trampoline_onion.hops_data, "hmac": trampoline_onion.hmac } # create onion packet payment_path_pubkeys = [x.node_id for x in route] onion = new_onion_packet(payment_path_pubkeys, session_key, hops_data, associated_data=payment_hash) # must use another sessionkey self.logger.info(f"starting payment. len(route)={len(hops_data)}.") # create htlc if cltv > local_height + lnutil.NBLOCK_CLTV_EXPIRY_TOO_FAR_INTO_FUTURE: raise PaymentFailure(f"htlc expiry too far into future. (in {cltv-local_height} blocks)") htlc = UpdateAddHtlc(amount_msat=amount_msat, payment_hash=payment_hash, cltv_expiry=cltv, timestamp=int(time.time())) htlc = chan.add_htlc(htlc) chan.set_onion_key(htlc.htlc_id, session_key) # should it be the outer onion secret? self.logger.info(f"starting payment. htlc: {htlc}") self.send_message( "update_add_htlc", channel_id=chan.channel_id, id=htlc.htlc_id, cltv_expiry=htlc.cltv_expiry, amount_msat=htlc.amount_msat, payment_hash=htlc.payment_hash, onion_routing_packet=onion.to_bytes()) self.maybe_send_commitment(chan) return htlc def send_revoke_and_ack(self, chan: Channel): self.logger.info(f'send_revoke_and_ack. chan {chan.short_channel_id}. ctn: {chan.get_oldest_unrevoked_ctn(LOCAL)}') rev = chan.revoke_current_commitment() self.lnworker.save_channel(chan) self.send_message("revoke_and_ack", channel_id=chan.channel_id, per_commitment_secret=rev.per_commitment_secret, next_per_commitment_point=rev.next_per_commitment_point) self.maybe_send_commitment(chan) def on_commitment_signed(self, chan: Channel, payload): if chan.peer_state == PeerState.BAD: return self.logger.info(f'on_commitment_signed. chan {chan.short_channel_id}. ctn: {chan.get_next_ctn(LOCAL)}.') # make sure there were changes to the ctx, otherwise the remote peer is misbehaving if not chan.has_pending_changes(LOCAL): # TODO if feerate changed A->B->A; so there were updates but the value is identical, # then it might be legal to send a commitment_signature # see https://github.com/lightningnetwork/lightning-rfc/pull/618 raise RemoteMisbehaving('received commitment_signed without pending changes') # REMOTE should wait until we have revoked if chan.hm.is_revack_pending(LOCAL): raise RemoteMisbehaving('received commitment_signed before we revoked previous ctx') data = payload["htlc_signature"] htlc_sigs = list(chunks(data, 64)) chan.receive_new_commitment(payload["signature"], htlc_sigs) self.send_revoke_and_ack(chan) def on_update_fulfill_htlc(self, chan: Channel, payload): preimage = payload["payment_preimage"] payment_hash = sha256(preimage) htlc_id = payload["id"] self.logger.info(f"on_update_fulfill_htlc. chan {chan.short_channel_id}. htlc_id {htlc_id}") chan.receive_htlc_settle(preimage, htlc_id) # TODO handle exc and maybe fail channel (e.g. bad htlc_id) self.lnworker.save_preimage(payment_hash, preimage) self.maybe_send_commitment(chan) def on_update_fail_malformed_htlc(self, chan: Channel, payload): htlc_id = payload["id"] failure_code = payload["failure_code"] self.logger.info(f"on_update_fail_malformed_htlc. chan {chan.get_id_for_log()}. " f"htlc_id {htlc_id}. failure_code={failure_code}") if failure_code & OnionFailureCodeMetaFlag.BADONION == 0: asyncio.ensure_future(self.lnworker.try_force_closing(chan.channel_id)) raise RemoteMisbehaving(f"received update_fail_malformed_htlc with unexpected failure code: {failure_code}") reason = OnionRoutingFailure(code=failure_code, data=payload["sha256_of_onion"]) chan.receive_fail_htlc(htlc_id, error_bytes=None, reason=reason) self.maybe_send_commitment(chan) def on_update_add_htlc(self, chan: Channel, payload): payment_hash = payload["payment_hash"] htlc_id = payload["id"] cltv_expiry = payload["cltv_expiry"] amount_msat_htlc = payload["amount_msat"] onion_packet = payload["onion_routing_packet"] htlc = UpdateAddHtlc( amount_msat=amount_msat_htlc, payment_hash=payment_hash, cltv_expiry=cltv_expiry, timestamp=int(time.time()), htlc_id=htlc_id) self.logger.info(f"on_update_add_htlc. chan {chan.short_channel_id}. htlc={str(htlc)}") if chan.get_state() != ChannelState.OPEN: raise RemoteMisbehaving(f"received update_add_htlc while chan.get_state() != OPEN. state was {chan.get_state()!r}") if cltv_expiry > bitcoin.NLOCKTIME_BLOCKHEIGHT_MAX: asyncio.ensure_future(self.lnworker.try_force_closing(chan.channel_id)) raise RemoteMisbehaving(f"received update_add_htlc with cltv_expiry > BLOCKHEIGHT_MAX. value was {cltv_expiry}") # add htlc chan.receive_htlc(htlc, onion_packet) util.trigger_callback('htlc_added', chan, htlc, RECEIVED) def maybe_forward_htlc( self, *, htlc: UpdateAddHtlc, processed_onion: ProcessedOnionPacket) -> Tuple[bytes, int]: # Forward HTLC # FIXME: there are critical safety checks MISSING here # - for example; atm we forward first and then persist "forwarding_info", # so if we segfault in-between and restart, we might forward an HTLC twice... # (same for trampoline forwarding) forwarding_enabled = self.network.config.get('lightning_forward_payments', False) if not forwarding_enabled: self.logger.info(f"forwarding is disabled. failing htlc.") raise OnionRoutingFailure(code=OnionFailureCode.PERMANENT_CHANNEL_FAILURE, data=b'') chain = self.network.blockchain() if chain.is_tip_stale(): raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_NODE_FAILURE, data=b'') try: next_chan_scid = processed_onion.hop_data.payload["short_channel_id"]["short_channel_id"] except: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') next_chan = self.lnworker.get_channel_by_short_id(next_chan_scid) local_height = chain.height() if next_chan is None: self.logger.info(f"cannot forward htlc. cannot find next_chan {next_chan_scid}") raise OnionRoutingFailure(code=OnionFailureCode.UNKNOWN_NEXT_PEER, data=b'') outgoing_chan_upd = next_chan.get_outgoing_gossip_channel_update()[2:] outgoing_chan_upd_len = len(outgoing_chan_upd).to_bytes(2, byteorder="big") outgoing_chan_upd_message = outgoing_chan_upd_len + outgoing_chan_upd if not next_chan.can_send_update_add_htlc(): self.logger.info(f"cannot forward htlc. next_chan {next_chan_scid} cannot send ctx updates. " f"chan state {next_chan.get_state()!r}, peer state: {next_chan.peer_state!r}") raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=outgoing_chan_upd_message) try: next_amount_msat_htlc = processed_onion.hop_data.payload["amt_to_forward"]["amt_to_forward"] except: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') if not next_chan.can_pay(next_amount_msat_htlc): self.logger.info(f"cannot forward htlc due to transient errors (likely due to insufficient funds)") raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=outgoing_chan_upd_message) try: next_cltv_expiry = processed_onion.hop_data.payload["outgoing_cltv_value"]["outgoing_cltv_value"] except: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') if htlc.cltv_expiry - next_cltv_expiry < next_chan.forwarding_cltv_expiry_delta: data = htlc.cltv_expiry.to_bytes(4, byteorder="big") + outgoing_chan_upd_message raise OnionRoutingFailure(code=OnionFailureCode.INCORRECT_CLTV_EXPIRY, data=data) if htlc.cltv_expiry - lnutil.MIN_FINAL_CLTV_EXPIRY_ACCEPTED <= local_height \ or next_cltv_expiry <= local_height: raise OnionRoutingFailure(code=OnionFailureCode.EXPIRY_TOO_SOON, data=outgoing_chan_upd_message) if max(htlc.cltv_expiry, next_cltv_expiry) > local_height + lnutil.NBLOCK_CLTV_EXPIRY_TOO_FAR_INTO_FUTURE: raise OnionRoutingFailure(code=OnionFailureCode.EXPIRY_TOO_FAR, data=b'') forwarding_fees = fee_for_edge_msat( forwarded_amount_msat=next_amount_msat_htlc, fee_base_msat=next_chan.forwarding_fee_base_msat, fee_proportional_millionths=next_chan.forwarding_fee_proportional_millionths) if htlc.amount_msat - next_amount_msat_htlc < forwarding_fees: data = next_amount_msat_htlc.to_bytes(8, byteorder="big") + outgoing_chan_upd_message raise OnionRoutingFailure(code=OnionFailureCode.FEE_INSUFFICIENT, data=data) self.logger.info(f'forwarding htlc to {next_chan.node_id}') next_htlc = UpdateAddHtlc( amount_msat=next_amount_msat_htlc, payment_hash=htlc.payment_hash, cltv_expiry=next_cltv_expiry, timestamp=int(time.time())) next_htlc = next_chan.add_htlc(next_htlc) next_peer = self.lnworker.peers[next_chan.node_id] try: next_peer.send_message( "update_add_htlc", channel_id=next_chan.channel_id, id=next_htlc.htlc_id, cltv_expiry=next_cltv_expiry, amount_msat=next_amount_msat_htlc, payment_hash=next_htlc.payment_hash, onion_routing_packet=processed_onion.next_packet.to_bytes() ) except BaseException as e: self.logger.info(f"failed to forward htlc: error sending message. {e}") raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=outgoing_chan_upd_message) return next_chan_scid, next_htlc.htlc_id def maybe_forward_trampoline( self, *, chan: Channel, htlc: UpdateAddHtlc, trampoline_onion: ProcessedOnionPacket): forwarding_enabled = self.network.config.get('lightning_forward_payments', False) forwarding_trampoline_enabled = self.network.config.get('lightning_forward_trampoline_payments', False) if not (forwarding_enabled and forwarding_trampoline_enabled): self.logger.info(f"trampoline forwarding is disabled. failing htlc.") raise OnionRoutingFailure(code=OnionFailureCode.PERMANENT_CHANNEL_FAILURE, data=b'') payload = trampoline_onion.hop_data.payload payment_hash = htlc.payment_hash payment_secret = os.urandom(32) try: outgoing_node_id = payload["outgoing_node_id"]["outgoing_node_id"] amt_to_forward = payload["amt_to_forward"]["amt_to_forward"] cltv_from_onion = payload["outgoing_cltv_value"]["outgoing_cltv_value"] if "invoice_features" in payload: self.logger.info('forward_trampoline: legacy') next_trampoline_onion = None invoice_features = payload["invoice_features"]["invoice_features"] invoice_routing_info = payload["invoice_routing_info"]["invoice_routing_info"] # TODO use invoice_routing_info else: self.logger.info('forward_trampoline: end-to-end') invoice_features = LnFeatures.BASIC_MPP_OPT next_trampoline_onion = trampoline_onion.next_packet except Exception as e: self.logger.exception('') raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') # these are the fee/cltv paid by the sender # pay_to_node will raise if they are not sufficient trampoline_cltv_delta = htlc.cltv_expiry - cltv_from_onion trampoline_fee = htlc.amount_msat - amt_to_forward @log_exceptions async def forward_trampoline_payment(): try: await self.lnworker.pay_to_node( node_pubkey=outgoing_node_id, payment_hash=payment_hash, payment_secret=payment_secret, amount_to_pay=amt_to_forward, min_cltv_expiry=cltv_from_onion, r_tags=[], invoice_features=invoice_features, fwd_trampoline_onion=next_trampoline_onion, fwd_trampoline_fee=trampoline_fee, fwd_trampoline_cltv_delta=trampoline_cltv_delta, attempts=1) except OnionRoutingFailure as e: # FIXME: cannot use payment_hash as key self.lnworker.trampoline_forwarding_failures[payment_hash] = e except PaymentFailure as e: # FIXME: adapt the error code error_reason = OnionRoutingFailure(code=OnionFailureCode.UNKNOWN_NEXT_PEER, data=b'') self.lnworker.trampoline_forwarding_failures[payment_hash] = error_reason asyncio.ensure_future(forward_trampoline_payment()) def maybe_fulfill_htlc( self, *, chan: Channel, htlc: UpdateAddHtlc, processed_onion: ProcessedOnionPacket, is_trampoline: bool = False) -> Tuple[Optional[bytes], Optional[OnionPacket]]: """As a final recipient of an HTLC, decide if we should fulfill it. Return (preimage, trampoline_onion_packet) with at most a single element not None """ def log_fail_reason(reason: str): self.logger.info(f"maybe_fulfill_htlc. will FAIL HTLC: chan {chan.short_channel_id}. " f"{reason}. htlc={str(htlc)}. onion_payload={processed_onion.hop_data.payload}") try: amt_to_forward = processed_onion.hop_data.payload["amt_to_forward"]["amt_to_forward"] except: log_fail_reason(f"'amt_to_forward' missing from onion") raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') # Check that our blockchain tip is sufficiently recent so that we have an approx idea of the height. # We should not release the preimage for an HTLC that its sender could already time out as # then they might try to force-close and it becomes a race. chain = self.network.blockchain() if chain.is_tip_stale(): log_fail_reason(f"our chain tip is stale") raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_NODE_FAILURE, data=b'') local_height = chain.height() exc_incorrect_or_unknown_pd = OnionRoutingFailure( code=OnionFailureCode.INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS, data=amt_to_forward.to_bytes(8, byteorder="big") + local_height.to_bytes(4, byteorder="big")) if local_height + MIN_FINAL_CLTV_EXPIRY_ACCEPTED > htlc.cltv_expiry: log_fail_reason(f"htlc.cltv_expiry is unreasonably close") raise exc_incorrect_or_unknown_pd try: cltv_from_onion = processed_onion.hop_data.payload["outgoing_cltv_value"]["outgoing_cltv_value"] except: log_fail_reason(f"'outgoing_cltv_value' missing from onion") raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') if not is_trampoline: if cltv_from_onion != htlc.cltv_expiry: log_fail_reason(f"cltv_from_onion != htlc.cltv_expiry") raise OnionRoutingFailure( code=OnionFailureCode.FINAL_INCORRECT_CLTV_EXPIRY, data=htlc.cltv_expiry.to_bytes(4, byteorder="big")) try: total_msat = processed_onion.hop_data.payload["payment_data"]["total_msat"] except: total_msat = amt_to_forward # fall back to "amt_to_forward" if not is_trampoline and amt_to_forward != htlc.amount_msat: log_fail_reason(f"amt_to_forward != htlc.amount_msat") raise OnionRoutingFailure( code=OnionFailureCode.FINAL_INCORRECT_HTLC_AMOUNT, data=htlc.amount_msat.to_bytes(8, byteorder="big")) try: payment_secret_from_onion = processed_onion.hop_data.payload["payment_data"]["payment_secret"] except: if total_msat > amt_to_forward: # payment_secret is required for MPP log_fail_reason(f"'payment_secret' missing from onion") raise exc_incorrect_or_unknown_pd # TODO fail here if invoice has set PAYMENT_SECRET_REQ payment_secret_from_onion = None if total_msat > amt_to_forward: mpp_status = self.lnworker.check_received_mpp_htlc(payment_secret_from_onion, chan.short_channel_id, htlc, total_msat) if mpp_status is None: return None, None if mpp_status is False: log_fail_reason(f"MPP_TIMEOUT") raise OnionRoutingFailure(code=OnionFailureCode.MPP_TIMEOUT, data=b'') assert mpp_status is True # if there is a trampoline_onion, maybe_fulfill_htlc will be called again if processed_onion.trampoline_onion_packet: # TODO: we should check that all trampoline_onions are the same return None, processed_onion.trampoline_onion_packet # TODO don't accept payments twice for same invoice # TODO check invoice expiry info = self.lnworker.get_payment_info(htlc.payment_hash) if info is None: log_fail_reason(f"no payment_info found for RHASH {htlc.payment_hash.hex()}") raise exc_incorrect_or_unknown_pd preimage = self.lnworker.get_preimage(htlc.payment_hash) if payment_secret_from_onion: if payment_secret_from_onion != derive_payment_secret_from_payment_preimage(preimage): log_fail_reason(f'incorrect payment secret {payment_secret_from_onion.hex()} != {derive_payment_secret_from_payment_preimage(preimage).hex()}') raise exc_incorrect_or_unknown_pd invoice_msat = info.amount_msat if not (invoice_msat is None or invoice_msat <= total_msat <= 2 * invoice_msat): log_fail_reason(f"total_msat={total_msat} too different from invoice_msat={invoice_msat}") raise exc_incorrect_or_unknown_pd self.logger.info(f"maybe_fulfill_htlc. will FULFILL HTLC: chan {chan.short_channel_id}. htlc={str(htlc)}") self.lnworker.set_request_status(htlc.payment_hash, PR_PAID) return preimage, None def fulfill_htlc(self, chan: Channel, htlc_id: int, preimage: bytes): self.logger.info(f"_fulfill_htlc. chan {chan.short_channel_id}. htlc_id {htlc_id}") assert chan.can_send_ctx_updates(), f"cannot send updates: {chan.short_channel_id}" assert chan.hm.is_htlc_irrevocably_added_yet(htlc_proposer=REMOTE, htlc_id=htlc_id) self.received_htlcs_pending_removal.add((chan, htlc_id)) chan.settle_htlc(preimage, htlc_id) self.send_message( "update_fulfill_htlc", channel_id=chan.channel_id, id=htlc_id, payment_preimage=preimage) def fail_htlc(self, *, chan: Channel, htlc_id: int, error_bytes: bytes): self.logger.info(f"fail_htlc. chan {chan.short_channel_id}. htlc_id {htlc_id}.") assert chan.can_send_ctx_updates(), f"cannot send updates: {chan.short_channel_id}" self.received_htlcs_pending_removal.add((chan, htlc_id)) chan.fail_htlc(htlc_id) self.send_message( "update_fail_htlc", channel_id=chan.channel_id, id=htlc_id, len=len(error_bytes), reason=error_bytes) def fail_malformed_htlc(self, *, chan: Channel, htlc_id: int, reason: OnionRoutingFailure): self.logger.info(f"fail_malformed_htlc. chan {chan.short_channel_id}. htlc_id {htlc_id}.") assert chan.can_send_ctx_updates(), f"cannot send updates: {chan.short_channel_id}" if not (reason.code & OnionFailureCodeMetaFlag.BADONION and len(reason.data) == 32): raise Exception(f"unexpected reason when sending 'update_fail_malformed_htlc': {reason!r}") self.received_htlcs_pending_removal.add((chan, htlc_id)) chan.fail_htlc(htlc_id) self.send_message( "update_fail_malformed_htlc", channel_id=chan.channel_id, id=htlc_id, sha256_of_onion=reason.data, failure_code=reason.code) def on_revoke_and_ack(self, chan: Channel, payload): if chan.peer_state == PeerState.BAD: return self.logger.info(f'on_revoke_and_ack. chan {chan.short_channel_id}. ctn: {chan.get_oldest_unrevoked_ctn(REMOTE)}') rev = RevokeAndAck(payload["per_commitment_secret"], payload["next_per_commitment_point"]) chan.receive_revocation(rev) self.lnworker.save_channel(chan) self.maybe_send_commitment(chan) def on_update_fee(self, chan: Channel, payload): feerate = payload["feerate_per_kw"] chan.update_fee(feerate, False) async def maybe_update_fee(self, chan: Channel): """ called when our fee estimates change """ if not chan.can_send_ctx_updates(): return feerate_per_kw = self.lnworker.current_feerate_per_kw() if not chan.constraints.is_initiator: if constants.net is not constants.BitcoinRegtest: chan_feerate = chan.get_latest_feerate(LOCAL) ratio = chan_feerate / feerate_per_kw if ratio < 0.5: # Note that we trust the Electrum server about fee rates # Thus, automated force-closing might not be a good idea # Maybe we should display something in the GUI instead self.logger.warning( f"({chan.get_id_for_log()}) feerate is {chan_feerate} gro/kw, " f"current recommended feerate is {feerate_per_kw} gro/kw, consider force closing!") return chan_fee = chan.get_next_feerate(REMOTE) if feerate_per_kw < chan_fee / 2: self.logger.info("FEES HAVE FALLEN") elif feerate_per_kw > chan_fee * 2: self.logger.info("FEES HAVE RISEN") elif chan.get_oldest_unrevoked_ctn(REMOTE) == 0: # workaround eclair issue https://github.com/ACINQ/eclair/issues/1730 self.logger.info("updating fee to bump remote ctn") if feerate_per_kw == chan_fee: feerate_per_kw += 1 else: return self.logger.info(f"(chan: {chan.get_id_for_log()}) current pending feerate {chan_fee}. " f"new feerate {feerate_per_kw}") chan.update_fee(feerate_per_kw, True) self.send_message( "update_fee", channel_id=chan.channel_id, feerate_per_kw=feerate_per_kw) self.maybe_send_commitment(chan) @log_exceptions async def close_channel(self, chan_id: bytes): chan = self.channels[chan_id] self.shutdown_received[chan_id] = asyncio.Future() await self.send_shutdown(chan) payload = await self.shutdown_received[chan_id] try: txid = await self._shutdown(chan, payload, is_local=True) self.logger.info(f'({chan.get_id_for_log()}) Channel closed {txid}') except asyncio.TimeoutError: txid = chan.unconfirmed_closing_txid self.logger.info(f'({chan.get_id_for_log()}) did not send closing_signed, {txid}') if txid is None: raise Exception('The remote peer did not send their final signature. The channel may not have been be closed') return txid async def on_shutdown(self, chan: Channel, payload): their_scriptpubkey = payload['scriptpubkey'] their_upfront_scriptpubkey = chan.config[REMOTE].upfront_shutdown_script # BOLT-02 check if they use the upfront shutdown script they advertized if their_upfront_scriptpubkey: if not (their_scriptpubkey == their_upfront_scriptpubkey): raise UpfrontShutdownScriptViolation("remote didn't use upfront shutdown script it commited to in channel opening") # BOLT-02 restrict the scriptpubkey to some templates: if not (match_script_against_template(their_scriptpubkey, transaction.SCRIPTPUBKEY_TEMPLATE_WITNESS_V0) or match_script_against_template(their_scriptpubkey, transaction.SCRIPTPUBKEY_TEMPLATE_P2SH) or match_script_against_template(their_scriptpubkey, transaction.SCRIPTPUBKEY_TEMPLATE_P2PKH)): raise Exception(f'scriptpubkey in received shutdown message does not conform to any template: {their_scriptpubkey.hex()}') chan_id = chan.channel_id if chan_id in self.shutdown_received: self.shutdown_received[chan_id].set_result(payload) else: chan = self.channels[chan_id] await self.send_shutdown(chan) txid = await self._shutdown(chan, payload, is_local=False) self.logger.info(f'({chan.get_id_for_log()}) Channel closed by remote peer {txid}') def can_send_shutdown(self, chan: Channel): if chan.get_state() >= ChannelState.OPENING: return True if chan.constraints.is_initiator and chan.channel_id in self.funding_created_sent: return True if not chan.constraints.is_initiator and chan.channel_id in self.funding_signed_sent: return True return False async def send_shutdown(self, chan: Channel): if not self.can_send_shutdown(chan): raise Exception('cannot send shutdown') if chan.config[LOCAL].upfront_shutdown_script: scriptpubkey = chan.config[LOCAL].upfront_shutdown_script else: scriptpubkey = bfh(bitcoin.address_to_script(chan.sweep_address)) assert scriptpubkey # wait until no more pending updates (bolt2) chan.set_can_send_ctx_updates(False) while chan.has_pending_changes(REMOTE): await asyncio.sleep(0.1) self.send_message('shutdown', channel_id=chan.channel_id, len=len(scriptpubkey), scriptpubkey=scriptpubkey) chan.set_state(ChannelState.SHUTDOWN) # can fullfill or fail htlcs. cannot add htlcs, because state != OPEN chan.set_can_send_ctx_updates(True) @log_exceptions async def _shutdown(self, chan: Channel, payload, *, is_local: bool): # wait until no HTLCs remain in either commitment transaction while len(chan.hm.htlcs(LOCAL)) + len(chan.hm.htlcs(REMOTE)) > 0: self.logger.info(f'(chan: {chan.short_channel_id}) waiting for htlcs to settle...') await asyncio.sleep(1) # if no HTLCs remain, we must not send updates chan.set_can_send_ctx_updates(False) their_scriptpubkey = payload['scriptpubkey'] if chan.config[LOCAL].upfront_shutdown_script: our_scriptpubkey = chan.config[LOCAL].upfront_shutdown_script else: our_scriptpubkey = bfh(bitcoin.address_to_script(chan.sweep_address)) assert our_scriptpubkey # estimate fee of closing tx our_sig, closing_tx = chan.make_closing_tx(our_scriptpubkey, their_scriptpubkey, fee_sat=0) fee_rate = self.network.config.fee_per_kb() our_fee = fee_rate * closing_tx.estimated_size() // 1000 # BOLT2: The sending node MUST set fee less than or equal to the base fee of the final ctx max_fee = chan.get_latest_fee(LOCAL if is_local else REMOTE) our_fee = min(our_fee, max_fee) drop_remote = False def send_closing_signed(): our_sig, closing_tx = chan.make_closing_tx(our_scriptpubkey, their_scriptpubkey, fee_sat=our_fee, drop_remote=drop_remote) self.send_message('closing_signed', channel_id=chan.channel_id, fee_satoshis=our_fee, signature=our_sig) def verify_signature(tx, sig): their_pubkey = chan.config[REMOTE].multisig_key.pubkey preimage_hex = tx.serialize_preimage(0) pre_hash = sha256(bfh(preimage_hex)) return ecc.verify_signature(their_pubkey, sig, pre_hash) # the funder sends the first 'closing_signed' message if chan.constraints.is_initiator: send_closing_signed() # negotiate fee while True: # FIXME: the remote SHOULD send closing_signed, but some don't. cs_payload = await self.wait_for_message('closing_signed', chan.channel_id) their_fee = cs_payload['fee_satoshis'] if their_fee > max_fee: raise Exception(f'the proposed fee exceeds the base fee of the latest commitment transaction {is_local, their_fee, max_fee}') their_sig = cs_payload['signature'] # verify their sig: they might have dropped their output our_sig, closing_tx = chan.make_closing_tx(our_scriptpubkey, their_scriptpubkey, fee_sat=their_fee, drop_remote=False) if verify_signature(closing_tx, their_sig): drop_remote = False else: our_sig, closing_tx = chan.make_closing_tx(our_scriptpubkey, their_scriptpubkey, fee_sat=their_fee, drop_remote=True) if verify_signature(closing_tx, their_sig): drop_remote = True else: raise Exception('failed to verify their signature') # Agree if difference is lower or equal to one (see below) if abs(our_fee - their_fee) < 2: our_fee = their_fee break # this will be "strictly between" (as in BOLT2) previous values because of the above our_fee = (our_fee + their_fee) // 2 # another round send_closing_signed() # the non-funder replies if not chan.constraints.is_initiator: send_closing_signed() # add signatures closing_tx.add_signature_to_txin( txin_idx=0, signing_pubkey=chan.config[LOCAL].multisig_key.pubkey.hex(), sig=bh2u(der_sig_from_sig_string(our_sig) + b'\x01')) closing_tx.add_signature_to_txin( txin_idx=0, signing_pubkey=chan.config[REMOTE].multisig_key.pubkey.hex(), sig=bh2u(der_sig_from_sig_string(their_sig) + b'\x01')) # save local transaction and set state try: self.lnworker.wallet.add_transaction(closing_tx) except UnrelatedTransactionException: pass # this can happen if (~all the balance goes to REMOTE) chan.set_state(ChannelState.CLOSING) # broadcast await self.network.try_broadcasting(closing_tx, 'closing') return closing_tx.txid() async def htlc_switch(self): await self.initialized while True: self._htlc_switch_iterdone_event.set() self._htlc_switch_iterdone_event.clear() await asyncio.sleep(0.1) # TODO maybe make this partly event-driven self._htlc_switch_iterstart_event.set() self._htlc_switch_iterstart_event.clear() self.ping_if_required() self._maybe_cleanup_received_htlcs_pending_removal() for chan_id, chan in self.channels.items(): if not chan.can_send_ctx_updates(): continue self.maybe_send_commitment(chan) done = set() unfulfilled = chan.unfulfilled_htlcs for htlc_id, (local_ctn, remote_ctn, onion_packet_hex, forwarding_info) in unfulfilled.items(): if not chan.hm.is_htlc_irrevocably_added_yet(htlc_proposer=REMOTE, htlc_id=htlc_id): continue htlc = chan.hm.get_htlc_by_id(REMOTE, htlc_id) error_reason = None # type: Optional[OnionRoutingFailure] error_bytes = None # type: Optional[bytes] preimage = None fw_info = None onion_packet_bytes = bytes.fromhex(onion_packet_hex) onion_packet = None try: onion_packet = OnionPacket.from_bytes(onion_packet_bytes) except OnionRoutingFailure as e: error_reason = e else: try: preimage, fw_info, error_bytes = self.process_unfulfilled_htlc( chan=chan, htlc=htlc, forwarding_info=forwarding_info, onion_packet_bytes=onion_packet_bytes, onion_packet=onion_packet) except OnionRoutingFailure as e: error_bytes = construct_onion_error(e, onion_packet, our_onion_private_key=self.privkey) if fw_info: unfulfilled[htlc_id] = local_ctn, remote_ctn, onion_packet_hex, fw_info elif preimage or error_reason or error_bytes: if preimage: if not self.lnworker.enable_htlc_settle: continue self.fulfill_htlc(chan, htlc.htlc_id, preimage) elif error_bytes: self.fail_htlc( chan=chan, htlc_id=htlc.htlc_id, error_bytes=error_bytes) else: self.fail_malformed_htlc( chan=chan, htlc_id=htlc.htlc_id, reason=error_reason) done.add(htlc_id) # cleanup for htlc_id in done: unfulfilled.pop(htlc_id) def _maybe_cleanup_received_htlcs_pending_removal(self) -> None: done = set() for chan, htlc_id in self.received_htlcs_pending_removal: if chan.hm.is_htlc_irrevocably_removed_yet(htlc_proposer=REMOTE, htlc_id=htlc_id): done.add((chan, htlc_id)) if done: for key in done: self.received_htlcs_pending_removal.remove(key) self.received_htlc_removed_event.set() self.received_htlc_removed_event.clear() async def wait_one_htlc_switch_iteration(self) -> None: """Waits until the HTLC switch does a full iteration or the peer disconnects, whichever happens first. """ async def htlc_switch_iteration(): await self._htlc_switch_iterstart_event.wait() await self._htlc_switch_iterdone_event.wait() async with TaskGroup(wait=any) as group: await group.spawn(htlc_switch_iteration()) await group.spawn(self.got_disconnected.wait()) def process_unfulfilled_htlc( self, *, chan: Channel, htlc: UpdateAddHtlc, forwarding_info: Tuple[str, int], onion_packet_bytes: bytes, onion_packet: OnionPacket) -> Tuple[Optional[bytes], Union[bool, None, Tuple[str, int]], Optional[bytes]]: """ return (preimage, fw_info, error_bytes) with at most a single element that is not None raise an OnionRoutingFailure if we need to fail the htlc """ payment_hash = htlc.payment_hash processed_onion = self.process_onion_packet( onion_packet, payment_hash=payment_hash, onion_packet_bytes=onion_packet_bytes) if processed_onion.are_we_final: # either we are final recipient; or if trampoline, see cases below preimage, trampoline_onion_packet = self.maybe_fulfill_htlc( chan=chan, htlc=htlc, processed_onion=processed_onion) if trampoline_onion_packet: # trampoline- recipient or forwarding if not forwarding_info: trampoline_onion = self.process_onion_packet( trampoline_onion_packet, payment_hash=htlc.payment_hash, onion_packet_bytes=onion_packet_bytes, is_trampoline=True) if trampoline_onion.are_we_final: # trampoline- we are final recipient of HTLC preimage, _ = self.maybe_fulfill_htlc( chan=chan, htlc=htlc, processed_onion=trampoline_onion, is_trampoline=True) else: # trampoline- HTLC we are supposed to forward, but haven't forwarded yet if not self.lnworker.enable_htlc_forwarding: return None, None, None self.maybe_forward_trampoline( chan=chan, htlc=htlc, trampoline_onion=trampoline_onion) # return True so that this code gets executed only once return None, True, None else: # trampoline- HTLC we are supposed to forward, and have already forwarded preimage = self.lnworker.get_preimage(payment_hash) error_reason = self.lnworker.trampoline_forwarding_failures.pop(payment_hash, None) if error_reason: self.logger.info(f'trampoline forwarding failure: {error_reason.code_name()}') raise error_reason elif not forwarding_info: # HTLC we are supposed to forward, but haven't forwarded yet if not self.lnworker.enable_htlc_forwarding: return None, None, None next_chan_id, next_htlc_id = self.maybe_forward_htlc( htlc=htlc, processed_onion=processed_onion) fw_info = (next_chan_id.hex(), next_htlc_id) return None, fw_info, None else: # HTLC we are supposed to forward, and have already forwarded preimage = self.lnworker.get_preimage(payment_hash) next_chan_id_hex, htlc_id = forwarding_info next_chan = self.lnworker.get_channel_by_short_id(bytes.fromhex(next_chan_id_hex)) if next_chan: error_bytes, error_reason = next_chan.pop_fail_htlc_reason(htlc_id) if error_bytes: return None, None, error_bytes if error_reason: raise error_reason if preimage: return preimage, None, None return None, None, None def process_onion_packet( self, onion_packet: OnionPacket, *, payment_hash: bytes, onion_packet_bytes: bytes, is_trampoline: bool = False) -> ProcessedOnionPacket: failure_data = sha256(onion_packet_bytes) try: processed_onion = process_onion_packet( onion_packet, associated_data=payment_hash, our_onion_private_key=self.privkey, is_trampoline=is_trampoline) except UnsupportedOnionPacketVersion: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_VERSION, data=failure_data) except InvalidOnionPubkey: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_KEY, data=failure_data) except InvalidOnionMac: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_HMAC, data=failure_data) except Exception as e: self.logger.info(f"error processing onion packet: {e!r}") raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_VERSION, data=failure_data) if self.network.config.get('test_fail_malformed_htlc'): raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_VERSION, data=failure_data) if self.network.config.get('test_fail_htlcs_with_temp_node_failure'): raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_NODE_FAILURE, data=b'') return processed_onion
#!/usr/bin/env python3 # # Copyright (C) 2018 The Electrum developers # Distributed under the MIT software license, see the accompanying # file LICENCE or http://www.opensource.org/licenses/mit-license.php import zlib from collections import OrderedDict, defaultdict import asyncio import os import time from typing import Tuple, Dict, TYPE_CHECKING, Optional, Union, Set from datetime import datetime import functools import aiorpcx from aiorpcx import TaskGroup from .crypto import sha256, sha256d from . import bitcoin, util from . import ecc from .ecc import sig_string_from_r_and_s, der_sig_from_sig_string from . import constants from .util import (bh2u, bfh, log_exceptions, ignore_exceptions, chunks, SilentTaskGroup, UnrelatedTransactionException) from . import transaction from .bitcoin import make_op_return from .transaction import PartialTxOutput, match_script_against_template from .logging import Logger from .lnonion import (new_onion_packet, OnionFailureCode, calc_hops_data_for_payment, process_onion_packet, OnionPacket, construct_onion_error, OnionRoutingFailure, ProcessedOnionPacket, UnsupportedOnionPacketVersion, InvalidOnionMac, InvalidOnionPubkey, OnionFailureCodeMetaFlag) from .lnchannel import Channel, RevokeAndAck, RemoteCtnTooFarInFuture, ChannelState, PeerState from . import lnutil from .lnutil import (Outpoint, LocalConfig, RECEIVED, UpdateAddHtlc, ChannelConfig, RemoteConfig, OnlyPubkeyKeypair, ChannelConstraints, RevocationStore, funding_output_script, get_per_commitment_secret_from_seed, secret_to_pubkey, PaymentFailure, LnFeatures, LOCAL, REMOTE, HTLCOwner, ln_compare_features, privkey_to_pubkey, MIN_FINAL_CLTV_EXPIRY_ACCEPTED, LightningPeerConnectionClosed, HandshakeFailed, RemoteMisbehaving, ShortChannelID, IncompatibleLightningFeatures, derive_payment_secret_from_payment_preimage, UpfrontShutdownScriptViolation) from .lnutil import FeeUpdate, channel_id_from_funding_tx from .lntransport import LNTransport, LNTransportBase from .lnmsg import encode_msg, decode_msg, UnknownOptionalMsgType from .interface import GracefulDisconnect from .lnrouter import fee_for_edge_msat from .lnutil import ln_dummy_address from .json_db import StoredDict from .invoices import PR_PAID if TYPE_CHECKING: from .lnworker import LNGossip, LNWallet from .lnrouter import LNPaymentRoute from .transaction import PartialTransaction LN_P2P_NETWORK_TIMEOUT = 20 class Peer(Logger): LOGGING_SHORTCUT = 'P' ORDERED_MESSAGES = ( 'accept_channel', 'funding_signed', 'funding_created', 'accept_channel', 'channel_reestablish', 'closing_signed') SPAMMY_MESSAGES = ( 'ping', 'pong', 'channel_announcement', 'node_announcement', 'channel_update',) def __init__( self, lnworker: Union['LNGossip', 'LNWallet'], pubkey: bytes, transport: LNTransportBase, *, is_channel_backup= False): self.is_channel_backup = is_channel_backup self._sent_init = False # type: bool self._received_init = False # type: bool self.initialized = asyncio.Future() self.got_disconnected = asyncio.Event() self.querying = asyncio.Event() self.transport = transport self.pubkey = pubkey # remote pubkey self.lnworker = lnworker self.privkey = self.transport.privkey # local privkey self.features = self.lnworker.features # type: LnFeatures self.their_features = LnFeatures(0) # type: LnFeatures self.node_ids = [self.pubkey, privkey_to_pubkey(self.privkey)] assert self.node_ids[0] != self.node_ids[1] self.network = lnworker.network self.ping_time = 0 self.reply_channel_range = asyncio.Queue() # gossip uses a single queue to preserve message order self.gossip_queue = asyncio.Queue() self.ordered_message_queues = defaultdict(asyncio.Queue) # for messsage that are ordered self.temp_id_to_id = {} # to forward error messages self.funding_created_sent = set() # for channels in PREOPENING self.funding_signed_sent = set() # for channels in PREOPENING self.shutdown_received = {} # chan_id -> asyncio.Future() self.announcement_signatures = defaultdict(asyncio.Queue) self.orphan_channel_updates = OrderedDict() # type: OrderedDict[ShortChannelID, dict] Logger.__init__(self) self.taskgroup = SilentTaskGroup() # HTLCs offered by REMOTE, that we started removing but are still active: self.received_htlcs_pending_removal = set() # type: Set[Tuple[Channel, int]] self.received_htlc_removed_event = asyncio.Event() self._htlc_switch_iterstart_event = asyncio.Event() self._htlc_switch_iterdone_event = asyncio.Event() def send_message(self, message_name: str, **kwargs): assert type(message_name) is str if message_name not in self.SPAMMY_MESSAGES: self.logger.debug(f"Sending {message_name.upper()}") if message_name.upper() != "INIT" and not self.is_initialized(): raise Exception("tried to send message before we are initialized") raw_msg = encode_msg(message_name, **kwargs) self._store_raw_msg_if_local_update(raw_msg, message_name=message_name, channel_id=kwargs.get("channel_id")) self.transport.send_bytes(raw_msg) def _store_raw_msg_if_local_update(self, raw_msg: bytes, *, message_name: str, channel_id: Optional[bytes]): is_commitment_signed = message_name == "commitment_signed" if not (message_name.startswith("update_") or is_commitment_signed): return assert channel_id chan = self.get_channel_by_id(channel_id) if not chan: raise Exception(f"channel {channel_id.hex()} not found for peer {self.pubkey.hex()}") chan.hm.store_local_update_raw_msg(raw_msg, is_commitment_signed=is_commitment_signed) if is_commitment_signed: # saving now, to ensure replaying updates works (in case of channel reestablishment) self.lnworker.save_channel(chan) def maybe_set_initialized(self): if self.initialized.done(): return if self._sent_init and self._received_init: self.initialized.set_result(True) def is_initialized(self) -> bool: return (self.initialized.done() and not self.initialized.cancelled() and self.initialized.exception() is None and self.initialized.result() is True) async def initialize(self): if isinstance(self.transport, LNTransport): await self.transport.handshake() features = self.features.for_init_message() b = int.bit_length(features) flen = b // 8 + int(bool(b % 8)) self.send_message( "init", gflen=0, flen=flen, features=features, init_tlvs={ 'networks': {'chains': constants.net.rev_genesis_bytes()} }) self._sent_init = True self.maybe_set_initialized() @property def channels(self) -> Dict[bytes, Channel]: return self.lnworker.channels_for_peer(self.pubkey) def get_channel_by_id(self, channel_id: bytes) -> Optional[Channel]: # note: this is faster than self.channels.get(channel_id) chan = self.lnworker.get_channel_by_id(channel_id) if not chan: return None if chan.node_id != self.pubkey: return None return chan def diagnostic_name(self): return self.lnworker.__class__.__name__ + ', ' + self.transport.name() def ping_if_required(self): if time.time() - self.ping_time > 120: self.send_message('ping', num_pong_bytes=4, byteslen=4) self.ping_time = time.time() def process_message(self, message): try: message_type, payload = decode_msg(message) except UnknownOptionalMsgType as e: self.logger.info(f"received unknown message from peer. ignoring: {e!r}") return if message_type not in self.SPAMMY_MESSAGES: self.logger.debug(f"Received {message_type.upper()}") # only process INIT if we are a backup if self.is_channel_backup is True and message_type != 'init': return if message_type in self.ORDERED_MESSAGES: chan_id = payload.get('channel_id') or payload["temporary_channel_id"] self.ordered_message_queues[chan_id].put_nowait((message_type, payload)) else: if message_type != 'error' and 'channel_id' in payload: chan = self.get_channel_by_id(payload['channel_id']) if chan is None: raise Exception('Got unknown '+ message_type) args = (chan, payload) else: args = (payload,) try: f = getattr(self, 'on_' + message_type) except AttributeError: #self.logger.info("Received '%s'" % message_type.upper(), payload) return # raw message is needed to check signature if message_type in ['node_announcement', 'channel_announcement', 'channel_update']: payload['raw'] = message execution_result = f(*args) if asyncio.iscoroutinefunction(f): asyncio.ensure_future(self.taskgroup.spawn(execution_result)) def on_error(self, payload): self.logger.info(f"remote peer sent error [DO NOT TRUST THIS MESSAGE]: {payload['data'].decode('ascii')}") chan_id = payload.get("channel_id") if chan_id in self.temp_id_to_id: chan_id = self.temp_id_to_id[chan_id] self.ordered_message_queues[chan_id].put_nowait((None, {'error':payload['data']})) def on_ping(self, payload): l = payload['num_pong_bytes'] self.send_message('pong', byteslen=l) def on_pong(self, payload): pass async def wait_for_message(self, expected_name, channel_id): q = self.ordered_message_queues[channel_id] name, payload = await asyncio.wait_for(q.get(), LN_P2P_NETWORK_TIMEOUT) if payload.get('error'): raise Exception('Remote peer reported error [DO NOT TRUST THIS MESSAGE]: ' + repr(payload.get('error'))) if name != expected_name: raise Exception(f"Received unexpected '{name}'") return payload def on_init(self, payload): if self._received_init: self.logger.info("ALREADY INITIALIZED BUT RECEIVED INIT") return self.their_features = LnFeatures(int.from_bytes(payload['features'], byteorder="big")) their_globalfeatures = int.from_bytes(payload['globalfeatures'], byteorder="big") self.their_features |= their_globalfeatures # check transitive dependencies for received features if not self.their_features.validate_transitive_dependencies(): raise GracefulDisconnect("remote did not set all dependencies for the features they sent") # check if features are compatible, and set self.features to what we negotiated try: self.features = ln_compare_features(self.features, self.their_features) except IncompatibleLightningFeatures as e: self.initialized.set_exception(e) raise GracefulDisconnect(f"{str(e)}") # check that they are on the same chain as us, if provided their_networks = payload["init_tlvs"].get("networks") if their_networks: their_chains = list(chunks(their_networks["chains"], 32)) if constants.net.rev_genesis_bytes() not in their_chains: raise GracefulDisconnect(f"no common chain found with remote. (they sent: {their_chains})") # all checks passed self.lnworker.on_peer_successfully_established(self) self._received_init = True self.maybe_set_initialized() def on_node_announcement(self, payload): if self.lnworker.channel_db: self.gossip_queue.put_nowait(('node_announcement', payload)) def on_channel_announcement(self, payload): if self.lnworker.channel_db: self.gossip_queue.put_nowait(('channel_announcement', payload)) def on_channel_update(self, payload): self.maybe_save_remote_update(payload) if self.lnworker.channel_db: self.gossip_queue.put_nowait(('channel_update', payload)) def maybe_save_remote_update(self, payload): if not self.channels: return for chan in self.channels.values(): if chan.short_channel_id == payload['short_channel_id']: chan.set_remote_update(payload) self.logger.info("saved remote_update") break else: # Save (some bounded number of) orphan channel updates for later # as it might be for our own direct channel with this peer # (and we might not yet know the short channel id for that) # Background: this code is here to deal with a bug in LND, # see https://github.com/lightningnetwork/lnd/issues/3651 # and https://github.com/lightningnetwork/lightning-rfc/pull/657 # This code assumes gossip_queries is set. BOLT7: "if the # gossip_queries feature is negotiated, [a node] MUST NOT # send gossip it did not generate itself" short_channel_id = ShortChannelID(payload['short_channel_id']) self.logger.info(f'received orphan channel update {short_channel_id}') self.orphan_channel_updates[short_channel_id] = payload while len(self.orphan_channel_updates) > 25: self.orphan_channel_updates.popitem(last=False) def on_announcement_signatures(self, chan: Channel, payload): if chan.config[LOCAL].was_announced: h, local_node_sig, local_bitcoin_sig = self.send_announcement_signatures(chan) else: self.announcement_signatures[chan.channel_id].put_nowait(payload) def handle_disconnect(func): @functools.wraps(func) async def wrapper_func(self, *args, **kwargs): try: return await func(self, *args, **kwargs) except GracefulDisconnect as e: self.logger.log(e.log_level, f"Disconnecting: {repr(e)}") except (LightningPeerConnectionClosed, IncompatibleLightningFeatures, aiorpcx.socks.SOCKSError) as e: self.logger.info(f"Disconnecting: {repr(e)}") finally: self.close_and_cleanup() return wrapper_func @ignore_exceptions # do not kill outer taskgroup @log_exceptions @handle_disconnect async def main_loop(self): async with self.taskgroup as group: await group.spawn(self._message_loop()) await group.spawn(self.htlc_switch()) await group.spawn(self.query_gossip()) await group.spawn(self.process_gossip()) async def process_gossip(self): while True: await asyncio.sleep(5) if not self.network.lngossip: continue chan_anns = [] chan_upds = [] node_anns = [] while True: name, payload = await self.gossip_queue.get() if name == 'channel_announcement': chan_anns.append(payload) elif name == 'channel_update': chan_upds.append(payload) elif name == 'node_announcement': node_anns.append(payload) else: raise Exception('unknown message') if self.gossip_queue.empty(): break if self.network.lngossip: await self.network.lngossip.process_gossip(chan_anns, node_anns, chan_upds) async def query_gossip(self): try: await asyncio.wait_for(self.initialized, LN_P2P_NETWORK_TIMEOUT) except Exception as e: raise GracefulDisconnect(f"Failed to initialize: {e!r}") from e if self.lnworker == self.lnworker.network.lngossip: try: ids, complete = await asyncio.wait_for(self.get_channel_range(), LN_P2P_NETWORK_TIMEOUT) except asyncio.TimeoutError as e: raise GracefulDisconnect("query_channel_range timed out") from e self.logger.info('Received {} channel ids. (complete: {})'.format(len(ids), complete)) await self.lnworker.add_new_ids(ids) while True: todo = self.lnworker.get_ids_to_query() if not todo: await asyncio.sleep(1) continue await self.get_short_channel_ids(todo) async def get_channel_range(self): first_block = constants.net.BLOCK_HEIGHT_FIRST_LIGHTNING_CHANNELS num_blocks = self.lnworker.network.get_local_height() - first_block self.query_channel_range(first_block, num_blocks) intervals = [] ids = set() # note: implementations behave differently... # "sane implementation that follows BOLT-07" example: # query_channel_range. <<< first_block 497000, num_blocks 79038 # on_reply_channel_range. >>> first_block 497000, num_blocks 39516, num_ids 4648, complete True # on_reply_channel_range. >>> first_block 536516, num_blocks 19758, num_ids 5734, complete True # on_reply_channel_range. >>> first_block 556274, num_blocks 9879, num_ids 13712, complete True # on_reply_channel_range. >>> first_block 566153, num_blocks 9885, num_ids 18114, complete True # lnd example: # query_channel_range. <<< first_block 497000, num_blocks 79038 # on_reply_channel_range. >>> first_block 497000, num_blocks 79038, num_ids 8000, complete False # on_reply_channel_range. >>> first_block 497000, num_blocks 79038, num_ids 8000, complete False # on_reply_channel_range. >>> first_block 497000, num_blocks 79038, num_ids 8000, complete False # on_reply_channel_range. >>> first_block 497000, num_blocks 79038, num_ids 8000, complete False # on_reply_channel_range. >>> first_block 497000, num_blocks 79038, num_ids 5344, complete True while True: index, num, complete, _ids = await self.reply_channel_range.get() ids.update(_ids) intervals.append((index, index+num)) intervals.sort() while len(intervals) > 1: a,b = intervals[0] c,d = intervals[1] if not (a <= c and a <= b and c <= d): raise Exception(f"insane reply_channel_range intervals {(a,b,c,d)}") if b >= c: intervals = [(a,d)] + intervals[2:] else: break if len(intervals) == 1 and complete: a, b = intervals[0] if a <= first_block and b >= first_block + num_blocks: break return ids, complete def request_gossip(self, timestamp=0): if timestamp == 0: self.logger.info('requesting whole channel graph') else: self.logger.info(f'requesting channel graph since {datetime.fromtimestamp(timestamp).ctime()}') self.send_message( 'gossip_timestamp_filter', chain_hash=constants.net.rev_genesis_bytes(), first_timestamp=timestamp, timestamp_range=b'\xff'*4) def query_channel_range(self, first_block, num_blocks): self.logger.info(f'query channel range {first_block} {num_blocks}') self.send_message( 'query_channel_range', chain_hash=constants.net.rev_genesis_bytes(), first_blocknum=first_block, number_of_blocks=num_blocks) def decode_short_ids(self, encoded): if encoded[0] == 0: decoded = encoded[1:] elif encoded[0] == 1: decoded = zlib.decompress(encoded[1:]) else: raise Exception(f'decode_short_ids: unexpected first byte: {encoded[0]}') ids = [decoded[i:i+8] for i in range(0, len(decoded), 8)] return ids def on_reply_channel_range(self, payload): first = payload['first_blocknum'] num = payload['number_of_blocks'] complete = bool(int.from_bytes(payload['complete'], 'big')) encoded = payload['encoded_short_ids'] ids = self.decode_short_ids(encoded) #self.logger.info(f"on_reply_channel_range. >>> first_block {first}, num_blocks {num}, num_ids {len(ids)}, complete {repr(payload['complete'])}") self.reply_channel_range.put_nowait((first, num, complete, ids)) async def get_short_channel_ids(self, ids): self.logger.info(f'Querying {len(ids)} short_channel_ids') assert not self.querying.is_set() self.query_short_channel_ids(ids) await self.querying.wait() self.querying.clear() def query_short_channel_ids(self, ids, compressed=True): ids = sorted(ids) s = b''.join(ids) encoded = zlib.compress(s) if compressed else s prefix = b'\x01' if compressed else b'\x00' self.send_message( 'query_short_channel_ids', chain_hash=constants.net.rev_genesis_bytes(), len=1+len(encoded), encoded_short_ids=prefix+encoded) async def _message_loop(self): try: await asyncio.wait_for(self.initialize(), LN_P2P_NETWORK_TIMEOUT) except (OSError, asyncio.TimeoutError, HandshakeFailed) as e: raise GracefulDisconnect(f'initialize failed: {repr(e)}') from e async for msg in self.transport.read_messages(): self.process_message(msg) await asyncio.sleep(.01) def on_reply_short_channel_ids_end(self, payload): self.querying.set() def close_and_cleanup(self): # note: This method might get called multiple times! # E.g. if you call close_and_cleanup() to cause a disconnection from the peer, # it will get called a second time in handle_disconnect(). try: if self.transport: self.transport.close() except: pass self.lnworker.peer_closed(self) self.got_disconnected.set() def is_static_remotekey(self): return self.features.supports(LnFeatures.OPTION_STATIC_REMOTEKEY_OPT) def is_upfront_shutdown_script(self): return self.features.supports(LnFeatures.OPTION_UPFRONT_SHUTDOWN_SCRIPT_OPT) def upfront_shutdown_script_from_payload(self, payload, msg_identifier: str) -> Optional[bytes]: if msg_identifier not in ['accept', 'open']: raise ValueError("msg_identifier must be either 'accept' or 'open'") uss_tlv = payload[msg_identifier + '_channel_tlvs'].get( 'upfront_shutdown_script') if uss_tlv and self.is_upfront_shutdown_script(): upfront_shutdown_script = uss_tlv['shutdown_scriptpubkey'] else: upfront_shutdown_script = b'' self.logger.info(f"upfront shutdown script received: {upfront_shutdown_script}") return upfront_shutdown_script def make_local_config(self, funding_sat: int, push_msat: int, initiator: HTLCOwner) -> LocalConfig: channel_seed = os.urandom(32) initial_msat = funding_sat * 1000 - push_msat if initiator == LOCAL else push_msat static_remotekey = None # sending empty bytes as the upfront_shutdown_script will give us the # flexibility to decide an address at closing time upfront_shutdown_script = b'' if self.is_static_remotekey(): wallet = self.lnworker.wallet assert wallet.txin_type == 'p2wpkh' addr = wallet.get_new_sweep_address_for_channel() static_remotekey = bfh(wallet.get_public_key(addr)) else: static_remotekey = None dust_limit_sat = bitcoin.DUST_LIMIT_DEFAULT_SAT_LEGACY reserve_sat = max(funding_sat // 100, dust_limit_sat) # for comparison of defaults, see # https://github.com/ACINQ/eclair/blob/afa378fbb73c265da44856b4ad0f2128a88ae6c6/eclair-core/src/main/resources/reference.conf#L66 # https://github.com/ElementsProject/lightning/blob/0056dd75572a8857cff36fcbdb1a2295a1ac9253/lightningd/options.c#L657 # https://github.com/lightningnetwork/lnd/blob/56b61078c5b2be007d318673a5f3b40c6346883a/config.go#L81 local_config = LocalConfig.from_seed( channel_seed=channel_seed, static_remotekey=static_remotekey, upfront_shutdown_script=upfront_shutdown_script, to_self_delay=self.network.config.get('lightning_to_self_delay', 7 * 144), dust_limit_sat=dust_limit_sat, max_htlc_value_in_flight_msat=funding_sat * 1000, max_accepted_htlcs=30, initial_msat=initial_msat, reserve_sat=reserve_sat, funding_locked_received=False, was_announced=False, current_commitment_signature=None, current_htlc_signatures=b'', htlc_minimum_msat=1, ) local_config.validate_params(funding_sat=funding_sat) return local_config def temporarily_reserve_funding_tx_change_address(func): # During the channel open flow, if we initiated, we might have used a change address # of ours in the funding tx. The funding tx is not part of the wallet history # at that point yet, but we should already consider this change address as 'used'. @functools.wraps(func) async def wrapper(self: 'Peer', *args, **kwargs): funding_tx = kwargs['funding_tx'] # type: PartialTransaction wallet = self.lnworker.wallet change_addresses = [txout.address for txout in funding_tx.outputs() if wallet.is_change(txout.address)] for addr in change_addresses: wallet.set_reserved_state_of_address(addr, reserved=True) try: return await func(self, *args, **kwargs) finally: for addr in change_addresses: self.lnworker.wallet.set_reserved_state_of_address(addr, reserved=False) return wrapper @log_exceptions @temporarily_reserve_funding_tx_change_address async def channel_establishment_flow( self, *, funding_tx: 'PartialTransaction', funding_sat: int, push_msat: int, temp_channel_id: bytes ) -> Tuple[Channel, 'PartialTransaction']: """Implements the channel opening flow. -> open_channel message <- accept_channel message -> funding_created message <- funding_signed message Channel configurations are initialized in this method. """ # will raise if init fails await asyncio.wait_for(self.initialized, LN_P2P_NETWORK_TIMEOUT) # trampoline is not yet in features if not self.lnworker.channel_db and not self.lnworker.is_trampoline_peer(self.pubkey): raise Exception('Not a trampoline node: ' + str(self.their_features)) feerate = self.lnworker.current_feerate_per_kw() local_config = self.make_local_config(funding_sat, push_msat, LOCAL) # for the first commitment transaction per_commitment_secret_first = get_per_commitment_secret_from_seed( local_config.per_commitment_secret_seed, RevocationStore.START_INDEX ) per_commitment_point_first = secret_to_pubkey( int.from_bytes(per_commitment_secret_first, 'big')) self.send_message( "open_channel", temporary_channel_id=temp_channel_id, chain_hash=constants.net.rev_genesis_bytes(), funding_satoshis=funding_sat, push_msat=push_msat, dust_limit_satoshis=local_config.dust_limit_sat, feerate_per_kw=feerate, max_accepted_htlcs=local_config.max_accepted_htlcs, funding_pubkey=local_config.multisig_key.pubkey, revocation_basepoint=local_config.revocation_basepoint.pubkey, htlc_basepoint=local_config.htlc_basepoint.pubkey, payment_basepoint=local_config.payment_basepoint.pubkey, delayed_payment_basepoint=local_config.delayed_basepoint.pubkey, first_per_commitment_point=per_commitment_point_first, to_self_delay=local_config.to_self_delay, max_htlc_value_in_flight_msat=local_config.max_htlc_value_in_flight_msat, channel_flags=0x00, # not willing to announce channel channel_reserve_satoshis=local_config.reserve_sat, htlc_minimum_msat=local_config.htlc_minimum_msat, open_channel_tlvs={ 'upfront_shutdown_script': {'shutdown_scriptpubkey': local_config.upfront_shutdown_script} } ) # <- accept_channel payload = await self.wait_for_message('accept_channel', temp_channel_id) remote_per_commitment_point = payload['first_per_commitment_point'] funding_txn_minimum_depth = payload['minimum_depth'] if funding_txn_minimum_depth <= 0: raise Exception(f"minimum depth too low, {funding_txn_minimum_depth}") if funding_txn_minimum_depth > 30: raise Exception(f"minimum depth too high, {funding_txn_minimum_depth}") upfront_shutdown_script = self.upfront_shutdown_script_from_payload( payload, 'accept') remote_config = RemoteConfig( payment_basepoint=OnlyPubkeyKeypair(payload['payment_basepoint']), multisig_key=OnlyPubkeyKeypair(payload["funding_pubkey"]), htlc_basepoint=OnlyPubkeyKeypair(payload['htlc_basepoint']), delayed_basepoint=OnlyPubkeyKeypair(payload['delayed_payment_basepoint']), revocation_basepoint=OnlyPubkeyKeypair(payload['revocation_basepoint']), to_self_delay=payload['to_self_delay'], dust_limit_sat=payload['dust_limit_satoshis'], max_htlc_value_in_flight_msat=payload['max_htlc_value_in_flight_msat'], max_accepted_htlcs=payload["max_accepted_htlcs"], initial_msat=push_msat, reserve_sat=payload["channel_reserve_satoshis"], htlc_minimum_msat=payload['htlc_minimum_msat'], next_per_commitment_point=remote_per_commitment_point, current_per_commitment_point=None, upfront_shutdown_script=upfront_shutdown_script ) ChannelConfig.cross_validate_params( local_config=local_config, remote_config=remote_config, funding_sat=funding_sat, is_local_initiator=True, initial_feerate_per_kw=feerate, ) # -> funding created # replace dummy output in funding tx redeem_script = funding_output_script(local_config, remote_config) funding_address = bitcoin.redeem_script_to_address('p2wsh', redeem_script) funding_output = PartialTxOutput.from_address_and_value(funding_address, funding_sat) dummy_output = PartialTxOutput.from_address_and_value(ln_dummy_address(), funding_sat) if dummy_output not in funding_tx.outputs(): raise Exception("LN dummy output (err 1)") funding_tx._outputs.remove(dummy_output) if dummy_output in funding_tx.outputs(): raise Exception("LN dummy output (err 2)") funding_tx.add_outputs([funding_output]) # find and encrypt op_return data associated to funding_address has_onchain_backup = self.lnworker and self.lnworker.has_recoverable_channels() if has_onchain_backup: backup_data = self.lnworker.cb_data(self.pubkey) dummy_scriptpubkey = make_op_return(backup_data) for o in funding_tx.outputs(): if o.scriptpubkey == dummy_scriptpubkey: encrypted_data = self.lnworker.encrypt_cb_data(backup_data, funding_address) assert len(encrypted_data) == len(backup_data) o.scriptpubkey = make_op_return(encrypted_data) break else: raise Exception('op_return output not found in funding tx') # must not be malleable funding_tx.set_rbf(False) if not funding_tx.is_segwit(): raise Exception('Funding transaction is not segwit') funding_txid = funding_tx.txid() assert funding_txid funding_index = funding_tx.outputs().index(funding_output) # build remote commitment transaction channel_id, funding_txid_bytes = channel_id_from_funding_tx(funding_txid, funding_index) outpoint = Outpoint(funding_txid, funding_index) constraints = ChannelConstraints( capacity=funding_sat, is_initiator=True, funding_txn_minimum_depth=funding_txn_minimum_depth ) storage = self.create_channel_storage( channel_id, outpoint, local_config, remote_config, constraints) chan = Channel( storage, sweep_address=self.lnworker.sweep_address, lnworker=self.lnworker, initial_feerate=feerate ) chan.storage['funding_inputs'] = [txin.prevout.to_json() for txin in funding_tx.inputs()] chan.storage['has_onchain_backup'] = has_onchain_backup if isinstance(self.transport, LNTransport): chan.add_or_update_peer_addr(self.transport.peer_addr) sig_64, _ = chan.sign_next_commitment() self.temp_id_to_id[temp_channel_id] = channel_id self.send_message("funding_created", temporary_channel_id=temp_channel_id, funding_txid=funding_txid_bytes, funding_output_index=funding_index, signature=sig_64) self.funding_created_sent.add(channel_id) # <- funding signed payload = await self.wait_for_message('funding_signed', channel_id) self.logger.info('received funding_signed') remote_sig = payload['signature'] chan.receive_new_commitment(remote_sig, []) chan.open_with_first_pcp(remote_per_commitment_point, remote_sig) chan.set_state(ChannelState.OPENING) self.lnworker.add_new_channel(chan) return chan, funding_tx def create_channel_storage(self, channel_id, outpoint, local_config, remote_config, constraints): chan_dict = { "node_id": self.pubkey.hex(), "channel_id": channel_id.hex(), "short_channel_id": None, "funding_outpoint": outpoint, "remote_config": remote_config, "local_config": local_config, "constraints": constraints, "remote_update": None, "state": ChannelState.PREOPENING.name, 'onion_keys': {}, 'data_loss_protect_remote_pcp': {}, "log": {}, "fail_htlc_reasons": {}, # htlc_id -> onion_packet "unfulfilled_htlcs": {}, # htlc_id -> error_bytes, failure_message "revocation_store": {}, "static_remotekey_enabled": self.is_static_remotekey(), # stored because it cannot be "downgraded", per BOLT2 } return StoredDict(chan_dict, self.lnworker.db if self.lnworker else None, []) async def on_open_channel(self, payload): """Implements the channel acceptance flow. <- open_channel message -> accept_channel message <- funding_created message -> funding_signed message Channel configurations are initialized in this method. """ if self.lnworker.has_recoverable_channels(): # FIXME: we might want to keep the connection open raise Exception('not accepting channels') # <- open_channel if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception('wrong chain_hash') funding_sat = payload['funding_satoshis'] push_msat = payload['push_msat'] feerate = payload['feerate_per_kw'] # note: we are not validating this temp_chan_id = payload['temporary_channel_id'] local_config = self.make_local_config(funding_sat, push_msat, REMOTE) upfront_shutdown_script = self.upfront_shutdown_script_from_payload( payload, 'open') remote_config = RemoteConfig( payment_basepoint=OnlyPubkeyKeypair(payload['payment_basepoint']), multisig_key=OnlyPubkeyKeypair(payload['funding_pubkey']), htlc_basepoint=OnlyPubkeyKeypair(payload['htlc_basepoint']), delayed_basepoint=OnlyPubkeyKeypair(payload['delayed_payment_basepoint']), revocation_basepoint=OnlyPubkeyKeypair(payload['revocation_basepoint']), to_self_delay=payload['to_self_delay'], dust_limit_sat=payload['dust_limit_satoshis'], max_htlc_value_in_flight_msat=payload['max_htlc_value_in_flight_msat'], max_accepted_htlcs=payload['max_accepted_htlcs'], initial_msat=funding_sat * 1000 - push_msat, reserve_sat=payload['channel_reserve_satoshis'], htlc_minimum_msat=payload['htlc_minimum_msat'], next_per_commitment_point=payload['first_per_commitment_point'], current_per_commitment_point=None, upfront_shutdown_script=upfront_shutdown_script, ) ChannelConfig.cross_validate_params( local_config=local_config, remote_config=remote_config, funding_sat=funding_sat, is_local_initiator=False, initial_feerate_per_kw=feerate, ) # note: we ignore payload['channel_flags'], which e.g. contains 'announce_channel'. # Notably if the remote sets 'announce_channel' to True, we will ignore that too, # but we will not play along with actually announcing the channel (so we keep it private). # -> accept channel # for the first commitment transaction per_commitment_secret_first = get_per_commitment_secret_from_seed( local_config.per_commitment_secret_seed, RevocationStore.START_INDEX ) per_commitment_point_first = secret_to_pubkey( int.from_bytes(per_commitment_secret_first, 'big')) min_depth = 3 self.send_message( 'accept_channel', temporary_channel_id=temp_chan_id, dust_limit_satoshis=local_config.dust_limit_sat, max_htlc_value_in_flight_msat=local_config.max_htlc_value_in_flight_msat, channel_reserve_satoshis=local_config.reserve_sat, htlc_minimum_msat=local_config.htlc_minimum_msat, minimum_depth=min_depth, to_self_delay=local_config.to_self_delay, max_accepted_htlcs=local_config.max_accepted_htlcs, funding_pubkey=local_config.multisig_key.pubkey, revocation_basepoint=local_config.revocation_basepoint.pubkey, payment_basepoint=local_config.payment_basepoint.pubkey, delayed_payment_basepoint=local_config.delayed_basepoint.pubkey, htlc_basepoint=local_config.htlc_basepoint.pubkey, first_per_commitment_point=per_commitment_point_first, accept_channel_tlvs={ 'upfront_shutdown_script': {'shutdown_scriptpubkey': local_config.upfront_shutdown_script} } ) # <- funding created funding_created = await self.wait_for_message('funding_created', temp_chan_id) # -> funding signed funding_idx = funding_created['funding_output_index'] funding_txid = bh2u(funding_created['funding_txid'][::-1]) channel_id, funding_txid_bytes = channel_id_from_funding_tx(funding_txid, funding_idx) constraints = ChannelConstraints( capacity=funding_sat, is_initiator=False, funding_txn_minimum_depth=min_depth ) outpoint = Outpoint(funding_txid, funding_idx) chan_dict = self.create_channel_storage( channel_id, outpoint, local_config, remote_config, constraints) chan = Channel( chan_dict, sweep_address=self.lnworker.sweep_address, lnworker=self.lnworker, initial_feerate=feerate ) chan.storage['init_timestamp'] = int(time.time()) if isinstance(self.transport, LNTransport): chan.add_or_update_peer_addr(self.transport.peer_addr) remote_sig = funding_created['signature'] chan.receive_new_commitment(remote_sig, []) sig_64, _ = chan.sign_next_commitment() self.send_message('funding_signed', channel_id=channel_id, signature=sig_64, ) self.funding_signed_sent.add(chan.channel_id) chan.open_with_first_pcp(payload['first_per_commitment_point'], remote_sig) chan.set_state(ChannelState.OPENING) self.lnworker.add_new_channel(chan) async def trigger_force_close(self, channel_id: bytes): await self.initialized latest_point = secret_to_pubkey(42) # we need a valid point (BOLT2) self.send_message( "channel_reestablish", channel_id=channel_id, next_commitment_number=0, next_revocation_number=0, your_last_per_commitment_secret=0, my_current_per_commitment_point=latest_point) async def reestablish_channel(self, chan: Channel): await self.initialized chan_id = chan.channel_id if chan.should_request_force_close: await self.trigger_force_close(chan_id) chan.should_request_force_close = False return assert ChannelState.PREOPENING < chan.get_state() < ChannelState.FORCE_CLOSING if chan.peer_state != PeerState.DISCONNECTED: self.logger.info(f'reestablish_channel was called but channel {chan.get_id_for_log()} ' f'already in peer_state {chan.peer_state!r}') return chan.peer_state = PeerState.REESTABLISHING util.trigger_callback('channel', self.lnworker.wallet, chan) # BOLT-02: "A node [...] upon disconnection [...] MUST reverse any uncommitted updates sent by the other side" chan.hm.discard_unsigned_remote_updates() # ctns oldest_unrevoked_local_ctn = chan.get_oldest_unrevoked_ctn(LOCAL) latest_local_ctn = chan.get_latest_ctn(LOCAL) next_local_ctn = chan.get_next_ctn(LOCAL) oldest_unrevoked_remote_ctn = chan.get_oldest_unrevoked_ctn(REMOTE) latest_remote_ctn = chan.get_latest_ctn(REMOTE) next_remote_ctn = chan.get_next_ctn(REMOTE) assert self.features.supports(LnFeatures.OPTION_DATA_LOSS_PROTECT_OPT) # send message if chan.is_static_remotekey_enabled(): latest_secret, latest_point = chan.get_secret_and_point(LOCAL, 0) else: latest_secret, latest_point = chan.get_secret_and_point(LOCAL, latest_local_ctn) if oldest_unrevoked_remote_ctn == 0: last_rev_secret = 0 else: last_rev_index = oldest_unrevoked_remote_ctn - 1 last_rev_secret = chan.revocation_store.retrieve_secret(RevocationStore.START_INDEX - last_rev_index) self.send_message( "channel_reestablish", channel_id=chan_id, next_commitment_number=next_local_ctn, next_revocation_number=oldest_unrevoked_remote_ctn, your_last_per_commitment_secret=last_rev_secret, my_current_per_commitment_point=latest_point) self.logger.info(f'channel_reestablish ({chan.get_id_for_log()}): sent channel_reestablish with ' f'(next_local_ctn={next_local_ctn}, ' f'oldest_unrevoked_remote_ctn={oldest_unrevoked_remote_ctn})') while True: try: msg = await self.wait_for_message('channel_reestablish', chan_id) break except asyncio.TimeoutError: self.logger.info('waiting to receive channel_reestablish...') continue except Exception as e: # do not kill connection, because we might have other channels with that peer self.logger.info(f'channel_reestablish failed, {e}') return their_next_local_ctn = msg["next_commitment_number"] their_oldest_unrevoked_remote_ctn = msg["next_revocation_number"] their_local_pcp = msg.get("my_current_per_commitment_point") their_claim_of_our_last_per_commitment_secret = msg.get("your_last_per_commitment_secret") self.logger.info(f'channel_reestablish ({chan.get_id_for_log()}): received channel_reestablish with ' f'(their_next_local_ctn={their_next_local_ctn}, ' f'their_oldest_unrevoked_remote_ctn={their_oldest_unrevoked_remote_ctn})') # sanity checks of received values if their_next_local_ctn < 0: raise RemoteMisbehaving(f"channel reestablish: their_next_local_ctn < 0") if their_oldest_unrevoked_remote_ctn < 0: raise RemoteMisbehaving(f"channel reestablish: their_oldest_unrevoked_remote_ctn < 0") # Replay un-acked local updates (including commitment_signed) byte-for-byte. # If we have sent them a commitment signature that they "lost" (due to disconnect), # we need to make sure we replay the same local updates, as otherwise they could # end up with two (or more) signed valid commitment transactions at the same ctn. # Multiple valid ctxs at the same ctn is a major headache for pre-signing spending txns, # e.g. for watchtowers, hence we must ensure these ctxs coincide. # We replay the local updates even if they were not yet committed. unacked = chan.hm.get_unacked_local_updates() n_replayed_msgs = 0 for ctn, messages in unacked.items(): if ctn < their_next_local_ctn: # They claim to have received these messages and the corresponding # commitment_signed, hence we must not replay them. continue for raw_upd_msg in messages: self.transport.send_bytes(raw_upd_msg) n_replayed_msgs += 1 self.logger.info(f'channel_reestablish ({chan.get_id_for_log()}): replayed {n_replayed_msgs} unacked messages') we_are_ahead = False they_are_ahead = False # compare remote ctns if next_remote_ctn != their_next_local_ctn: if their_next_local_ctn == latest_remote_ctn and chan.hm.is_revack_pending(REMOTE): # We replayed the local updates (see above), which should have contained a commitment_signed # (due to is_revack_pending being true), and this should have remedied this situation. pass else: self.logger.warning(f"channel_reestablish ({chan.get_id_for_log()}): " f"expected remote ctn {next_remote_ctn}, got {their_next_local_ctn}") if their_next_local_ctn < next_remote_ctn: we_are_ahead = True else: they_are_ahead = True # compare local ctns if oldest_unrevoked_local_ctn != their_oldest_unrevoked_remote_ctn: if oldest_unrevoked_local_ctn - 1 == their_oldest_unrevoked_remote_ctn: # A node: # if next_revocation_number is equal to the commitment number of the last revoke_and_ack # the receiving node sent, AND the receiving node hasn't already received a closing_signed: # MUST re-send the revoke_and_ack. last_secret, last_point = chan.get_secret_and_point(LOCAL, oldest_unrevoked_local_ctn - 1) next_secret, next_point = chan.get_secret_and_point(LOCAL, oldest_unrevoked_local_ctn + 1) self.send_message( "revoke_and_ack", channel_id=chan.channel_id, per_commitment_secret=last_secret, next_per_commitment_point=next_point) else: self.logger.warning(f"channel_reestablish ({chan.get_id_for_log()}): " f"expected local ctn {oldest_unrevoked_local_ctn}, got {their_oldest_unrevoked_remote_ctn}") if their_oldest_unrevoked_remote_ctn < oldest_unrevoked_local_ctn: we_are_ahead = True else: they_are_ahead = True # option_data_loss_protect def are_datalossprotect_fields_valid() -> bool: if their_local_pcp is None or their_claim_of_our_last_per_commitment_secret is None: return False if their_oldest_unrevoked_remote_ctn > 0: our_pcs, __ = chan.get_secret_and_point(LOCAL, their_oldest_unrevoked_remote_ctn - 1) else: assert their_oldest_unrevoked_remote_ctn == 0 our_pcs = bytes(32) if our_pcs != their_claim_of_our_last_per_commitment_secret: self.logger.error(f"channel_reestablish ({chan.get_id_for_log()}): " f"(DLP) local PCS mismatch: {bh2u(our_pcs)} != {bh2u(their_claim_of_our_last_per_commitment_secret)}") return False if chan.is_static_remotekey_enabled(): return True try: __, our_remote_pcp = chan.get_secret_and_point(REMOTE, their_next_local_ctn - 1) except RemoteCtnTooFarInFuture: pass else: if our_remote_pcp != their_local_pcp: self.logger.error(f"channel_reestablish ({chan.get_id_for_log()}): " f"(DLP) remote PCP mismatch: {bh2u(our_remote_pcp)} != {bh2u(their_local_pcp)}") return False return True if not are_datalossprotect_fields_valid(): raise RemoteMisbehaving("channel_reestablish: data loss protect fields invalid") if they_are_ahead: self.logger.warning(f"channel_reestablish ({chan.get_id_for_log()}): " f"remote is ahead of us! They should force-close. Remote PCP: {bh2u(their_local_pcp)}") # data_loss_protect_remote_pcp is used in lnsweep chan.set_data_loss_protect_remote_pcp(their_next_local_ctn - 1, their_local_pcp) self.lnworker.save_channel(chan) chan.peer_state = PeerState.BAD return elif we_are_ahead: self.logger.warning(f"channel_reestablish ({chan.get_id_for_log()}): we are ahead of remote! trying to force-close.") await self.lnworker.try_force_closing(chan_id) return chan.peer_state = PeerState.GOOD if chan.is_funded() and their_next_local_ctn == next_local_ctn == 1: self.send_funding_locked(chan) # checks done if chan.is_funded() and chan.config[LOCAL].funding_locked_received: self.mark_open(chan) util.trigger_callback('channel', self.lnworker.wallet, chan) # if we have sent a previous shutdown, it must be retransmitted (Bolt2) if chan.get_state() == ChannelState.SHUTDOWN: await self.send_shutdown(chan) def send_funding_locked(self, chan: Channel): channel_id = chan.channel_id per_commitment_secret_index = RevocationStore.START_INDEX - 1 per_commitment_point_second = secret_to_pubkey(int.from_bytes( get_per_commitment_secret_from_seed(chan.config[LOCAL].per_commitment_secret_seed, per_commitment_secret_index), 'big')) # note: if funding_locked was not yet received, we might send it multiple times self.send_message("funding_locked", channel_id=channel_id, next_per_commitment_point=per_commitment_point_second) if chan.is_funded() and chan.config[LOCAL].funding_locked_received: self.mark_open(chan) def on_funding_locked(self, chan: Channel, payload): self.logger.info(f"on_funding_locked. channel: {bh2u(chan.channel_id)}") if not chan.config[LOCAL].funding_locked_received: their_next_point = payload["next_per_commitment_point"] chan.config[REMOTE].next_per_commitment_point = their_next_point chan.config[LOCAL].funding_locked_received = True self.lnworker.save_channel(chan) if chan.is_funded(): self.mark_open(chan) def on_network_update(self, chan: Channel, funding_tx_depth: int): """ Only called when the channel is OPEN. Runs on the Network thread. """ if not chan.config[LOCAL].was_announced and funding_tx_depth >= 6: # don't announce our channels # FIXME should this be a field in chan.local_state maybe? return chan.config[LOCAL].was_announced = True self.lnworker.save_channel(chan) coro = self.handle_announcements(chan) asyncio.run_coroutine_threadsafe(coro, self.network.asyncio_loop) @log_exceptions async def handle_announcements(self, chan: Channel): h, local_node_sig, local_bitcoin_sig = self.send_announcement_signatures(chan) announcement_signatures_msg = await self.announcement_signatures[chan.channel_id].get() remote_node_sig = announcement_signatures_msg["node_signature"] remote_bitcoin_sig = announcement_signatures_msg["bitcoin_signature"] if not ecc.verify_signature(chan.config[REMOTE].multisig_key.pubkey, remote_bitcoin_sig, h): raise Exception("bitcoin_sig invalid in announcement_signatures") if not ecc.verify_signature(self.pubkey, remote_node_sig, h): raise Exception("node_sig invalid in announcement_signatures") node_sigs = [remote_node_sig, local_node_sig] bitcoin_sigs = [remote_bitcoin_sig, local_bitcoin_sig] bitcoin_keys = [chan.config[REMOTE].multisig_key.pubkey, chan.config[LOCAL].multisig_key.pubkey] if self.node_ids[0] > self.node_ids[1]: node_sigs.reverse() bitcoin_sigs.reverse() node_ids = list(reversed(self.node_ids)) bitcoin_keys.reverse() else: node_ids = self.node_ids self.send_message("channel_announcement", node_signatures_1=node_sigs[0], node_signatures_2=node_sigs[1], bitcoin_signature_1=bitcoin_sigs[0], bitcoin_signature_2=bitcoin_sigs[1], len=0, #features not set (defaults to zeros) chain_hash=constants.net.rev_genesis_bytes(), short_channel_id=chan.short_channel_id, node_id_1=node_ids[0], node_id_2=node_ids[1], bitcoin_key_1=bitcoin_keys[0], bitcoin_key_2=bitcoin_keys[1] ) def mark_open(self, chan: Channel): assert chan.is_funded() # only allow state transition from "FUNDED" to "OPEN" old_state = chan.get_state() if old_state == ChannelState.OPEN: return if old_state != ChannelState.FUNDED: self.logger.info(f"cannot mark open ({chan.get_id_for_log()}), current state: {repr(old_state)}") return assert chan.config[LOCAL].funding_locked_received chan.set_state(ChannelState.OPEN) util.trigger_callback('channel', self.lnworker.wallet, chan) # peer may have sent us a channel update for the incoming direction previously pending_channel_update = self.orphan_channel_updates.get(chan.short_channel_id) if pending_channel_update: chan.set_remote_update(pending_channel_update) self.logger.info(f"CHANNEL OPENING COMPLETED ({chan.get_id_for_log()})") forwarding_enabled = self.network.config.get('lightning_forward_payments', False) if forwarding_enabled: # send channel_update of outgoing edge to peer, # so that channel can be used to to receive payments self.logger.info(f"sending channel update for outgoing edge ({chan.get_id_for_log()})") chan_upd = chan.get_outgoing_gossip_channel_update() self.transport.send_bytes(chan_upd) def send_announcement_signatures(self, chan: Channel): chan_ann = chan.construct_channel_announcement_without_sigs() preimage = chan_ann[256+2:] msg_hash = sha256(preimage) bitcoin_signature = ecc.ECPrivkey(chan.config[LOCAL].multisig_key.privkey).sign(msg_hash, sig_string_from_r_and_s) node_signature = ecc.ECPrivkey(self.privkey).sign(msg_hash, sig_string_from_r_and_s) self.send_message("announcement_signatures", channel_id=chan.channel_id, short_channel_id=chan.short_channel_id, node_signature=node_signature, bitcoin_signature=bitcoin_signature ) return msg_hash, node_signature, bitcoin_signature def on_update_fail_htlc(self, chan: Channel, payload): htlc_id = payload["id"] reason = payload["reason"] self.logger.info(f"on_update_fail_htlc. chan {chan.short_channel_id}. htlc_id {htlc_id}") chan.receive_fail_htlc(htlc_id, error_bytes=reason) # TODO handle exc and maybe fail channel (e.g. bad htlc_id) self.maybe_send_commitment(chan) def maybe_send_commitment(self, chan: Channel): # REMOTE should revoke first before we can sign a new ctx if chan.hm.is_revack_pending(REMOTE): return # if there are no changes, we will not (and must not) send a new commitment if not chan.has_pending_changes(REMOTE): return self.logger.info(f'send_commitment. chan {chan.short_channel_id}. ctn: {chan.get_next_ctn(REMOTE)}.') sig_64, htlc_sigs = chan.sign_next_commitment() self.send_message("commitment_signed", channel_id=chan.channel_id, signature=sig_64, num_htlcs=len(htlc_sigs), htlc_signature=b"".join(htlc_sigs)) def pay(self, *, route: 'LNPaymentRoute', chan: Channel, amount_msat: int, total_msat: int, payment_hash: bytes, min_final_cltv_expiry: int, payment_secret: bytes = None, trampoline_onion=None) -> UpdateAddHtlc: assert amount_msat > 0, "amount_msat is not greater zero" assert len(route) > 0 if not chan.can_send_update_add_htlc(): raise PaymentFailure("Channel cannot send update_add_htlc") # add features learned during "init" for direct neighbour: route[0].node_features |= self.features local_height = self.network.get_local_height() final_cltv = local_height + min_final_cltv_expiry hops_data, amount_msat, cltv = calc_hops_data_for_payment( route, amount_msat, final_cltv, total_msat=total_msat, payment_secret=payment_secret) num_hops = len(hops_data) self.logger.info(f"lnpeer.pay len(route)={len(route)}") for i in range(len(route)): self.logger.info(f" {i}: edge={route[i].short_channel_id} hop_data={hops_data[i]!r}") assert final_cltv <= cltv, (final_cltv, cltv) session_key = os.urandom(32) # session_key # if we are forwarding a trampoline payment, add trampoline onion if trampoline_onion: self.logger.info(f'adding trampoline onion to final payload') trampoline_payload = hops_data[num_hops-2].payload trampoline_payload["trampoline_onion_packet"] = { "version": trampoline_onion.version, "public_key": trampoline_onion.public_key, "hops_data": trampoline_onion.hops_data, "hmac": trampoline_onion.hmac } # create onion packet payment_path_pubkeys = [x.node_id for x in route] onion = new_onion_packet(payment_path_pubkeys, session_key, hops_data, associated_data=payment_hash) # must use another sessionkey self.logger.info(f"starting payment. len(route)={len(hops_data)}.") # create htlc if cltv > local_height + lnutil.NBLOCK_CLTV_EXPIRY_TOO_FAR_INTO_FUTURE: raise PaymentFailure(f"htlc expiry too far into future. (in {cltv-local_height} blocks)") htlc = UpdateAddHtlc(amount_msat=amount_msat, payment_hash=payment_hash, cltv_expiry=cltv, timestamp=int(time.time())) htlc = chan.add_htlc(htlc) chan.set_onion_key(htlc.htlc_id, session_key) # should it be the outer onion secret? self.logger.info(f"starting payment. htlc: {htlc}") self.send_message( "update_add_htlc", channel_id=chan.channel_id, id=htlc.htlc_id, cltv_expiry=htlc.cltv_expiry, amount_msat=htlc.amount_msat, payment_hash=htlc.payment_hash, onion_routing_packet=onion.to_bytes()) self.maybe_send_commitment(chan) return htlc def send_revoke_and_ack(self, chan: Channel): self.logger.info(f'send_revoke_and_ack. chan {chan.short_channel_id}. ctn: {chan.get_oldest_unrevoked_ctn(LOCAL)}') rev = chan.revoke_current_commitment() self.lnworker.save_channel(chan) self.send_message("revoke_and_ack", channel_id=chan.channel_id, per_commitment_secret=rev.per_commitment_secret, next_per_commitment_point=rev.next_per_commitment_point) self.maybe_send_commitment(chan) def on_commitment_signed(self, chan: Channel, payload): if chan.peer_state == PeerState.BAD: return self.logger.info(f'on_commitment_signed. chan {chan.short_channel_id}. ctn: {chan.get_next_ctn(LOCAL)}.') # make sure there were changes to the ctx, otherwise the remote peer is misbehaving if not chan.has_pending_changes(LOCAL): # TODO if feerate changed A->B->A; so there were updates but the value is identical, # then it might be legal to send a commitment_signature # see https://github.com/lightningnetwork/lightning-rfc/pull/618 raise RemoteMisbehaving('received commitment_signed without pending changes') # REMOTE should wait until we have revoked if chan.hm.is_revack_pending(LOCAL): raise RemoteMisbehaving('received commitment_signed before we revoked previous ctx') data = payload["htlc_signature"] htlc_sigs = list(chunks(data, 64)) chan.receive_new_commitment(payload["signature"], htlc_sigs) self.send_revoke_and_ack(chan) def on_update_fulfill_htlc(self, chan: Channel, payload): preimage = payload["payment_preimage"] payment_hash = sha256(preimage) htlc_id = payload["id"] self.logger.info(f"on_update_fulfill_htlc. chan {chan.short_channel_id}. htlc_id {htlc_id}") chan.receive_htlc_settle(preimage, htlc_id) # TODO handle exc and maybe fail channel (e.g. bad htlc_id) self.lnworker.save_preimage(payment_hash, preimage) self.maybe_send_commitment(chan) def on_update_fail_malformed_htlc(self, chan: Channel, payload): htlc_id = payload["id"] failure_code = payload["failure_code"] self.logger.info(f"on_update_fail_malformed_htlc. chan {chan.get_id_for_log()}. " f"htlc_id {htlc_id}. failure_code={failure_code}") if failure_code & OnionFailureCodeMetaFlag.BADONION == 0: asyncio.ensure_future(self.lnworker.try_force_closing(chan.channel_id)) raise RemoteMisbehaving(f"received update_fail_malformed_htlc with unexpected failure code: {failure_code}") reason = OnionRoutingFailure(code=failure_code, data=payload["sha256_of_onion"]) chan.receive_fail_htlc(htlc_id, error_bytes=None, reason=reason) self.maybe_send_commitment(chan) def on_update_add_htlc(self, chan: Channel, payload): payment_hash = payload["payment_hash"] htlc_id = payload["id"] cltv_expiry = payload["cltv_expiry"] amount_msat_htlc = payload["amount_msat"] onion_packet = payload["onion_routing_packet"] htlc = UpdateAddHtlc( amount_msat=amount_msat_htlc, payment_hash=payment_hash, cltv_expiry=cltv_expiry, timestamp=int(time.time()), htlc_id=htlc_id) self.logger.info(f"on_update_add_htlc. chan {chan.short_channel_id}. htlc={str(htlc)}") if chan.get_state() != ChannelState.OPEN: raise RemoteMisbehaving(f"received update_add_htlc while chan.get_state() != OPEN. state was {chan.get_state()!r}") if cltv_expiry > bitcoin.NLOCKTIME_BLOCKHEIGHT_MAX: asyncio.ensure_future(self.lnworker.try_force_closing(chan.channel_id)) raise RemoteMisbehaving(f"received update_add_htlc with cltv_expiry > BLOCKHEIGHT_MAX. value was {cltv_expiry}") # add htlc chan.receive_htlc(htlc, onion_packet) util.trigger_callback('htlc_added', chan, htlc, RECEIVED) def maybe_forward_htlc( self, *, htlc: UpdateAddHtlc, processed_onion: ProcessedOnionPacket) -> Tuple[bytes, int]: # Forward HTLC # FIXME: there are critical safety checks MISSING here # - for example; atm we forward first and then persist "forwarding_info", # so if we segfault in-between and restart, we might forward an HTLC twice... # (same for trampoline forwarding) forwarding_enabled = self.network.config.get('lightning_forward_payments', False) if not forwarding_enabled: self.logger.info(f"forwarding is disabled. failing htlc.") raise OnionRoutingFailure(code=OnionFailureCode.PERMANENT_CHANNEL_FAILURE, data=b'') chain = self.network.blockchain() if chain.is_tip_stale(): raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_NODE_FAILURE, data=b'') try: next_chan_scid = processed_onion.hop_data.payload["short_channel_id"]["short_channel_id"] except: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') next_chan = self.lnworker.get_channel_by_short_id(next_chan_scid) local_height = chain.height() if next_chan is None: self.logger.info(f"cannot forward htlc. cannot find next_chan {next_chan_scid}") raise OnionRoutingFailure(code=OnionFailureCode.UNKNOWN_NEXT_PEER, data=b'') outgoing_chan_upd = next_chan.get_outgoing_gossip_channel_update()[2:] outgoing_chan_upd_len = len(outgoing_chan_upd).to_bytes(2, byteorder="big") outgoing_chan_upd_message = outgoing_chan_upd_len + outgoing_chan_upd if not next_chan.can_send_update_add_htlc(): self.logger.info(f"cannot forward htlc. next_chan {next_chan_scid} cannot send ctx updates. " f"chan state {next_chan.get_state()!r}, peer state: {next_chan.peer_state!r}") raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=outgoing_chan_upd_message) try: next_amount_msat_htlc = processed_onion.hop_data.payload["amt_to_forward"]["amt_to_forward"] except: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') if not next_chan.can_pay(next_amount_msat_htlc): self.logger.info(f"cannot forward htlc due to transient errors (likely due to insufficient funds)") raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=outgoing_chan_upd_message) try: next_cltv_expiry = processed_onion.hop_data.payload["outgoing_cltv_value"]["outgoing_cltv_value"] except: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') if htlc.cltv_expiry - next_cltv_expiry < next_chan.forwarding_cltv_expiry_delta: data = htlc.cltv_expiry.to_bytes(4, byteorder="big") + outgoing_chan_upd_message raise OnionRoutingFailure(code=OnionFailureCode.INCORRECT_CLTV_EXPIRY, data=data) if htlc.cltv_expiry - lnutil.MIN_FINAL_CLTV_EXPIRY_ACCEPTED <= local_height \ or next_cltv_expiry <= local_height: raise OnionRoutingFailure(code=OnionFailureCode.EXPIRY_TOO_SOON, data=outgoing_chan_upd_message) if max(htlc.cltv_expiry, next_cltv_expiry) > local_height + lnutil.NBLOCK_CLTV_EXPIRY_TOO_FAR_INTO_FUTURE: raise OnionRoutingFailure(code=OnionFailureCode.EXPIRY_TOO_FAR, data=b'') forwarding_fees = fee_for_edge_msat( forwarded_amount_msat=next_amount_msat_htlc, fee_base_msat=next_chan.forwarding_fee_base_msat, fee_proportional_millionths=next_chan.forwarding_fee_proportional_millionths) if htlc.amount_msat - next_amount_msat_htlc < forwarding_fees: data = next_amount_msat_htlc.to_bytes(8, byteorder="big") + outgoing_chan_upd_message raise OnionRoutingFailure(code=OnionFailureCode.FEE_INSUFFICIENT, data=data) self.logger.info(f'forwarding htlc to {next_chan.node_id}') next_htlc = UpdateAddHtlc( amount_msat=next_amount_msat_htlc, payment_hash=htlc.payment_hash, cltv_expiry=next_cltv_expiry, timestamp=int(time.time())) next_htlc = next_chan.add_htlc(next_htlc) next_peer = self.lnworker.peers[next_chan.node_id] try: next_peer.send_message( "update_add_htlc", channel_id=next_chan.channel_id, id=next_htlc.htlc_id, cltv_expiry=next_cltv_expiry, amount_msat=next_amount_msat_htlc, payment_hash=next_htlc.payment_hash, onion_routing_packet=processed_onion.next_packet.to_bytes() ) except BaseException as e: self.logger.info(f"failed to forward htlc: error sending message. {e}") raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=outgoing_chan_upd_message) return next_chan_scid, next_htlc.htlc_id def maybe_forward_trampoline( self, *, chan: Channel, htlc: UpdateAddHtlc, trampoline_onion: ProcessedOnionPacket): forwarding_enabled = self.network.config.get('lightning_forward_payments', False) forwarding_trampoline_enabled = self.network.config.get('lightning_forward_trampoline_payments', False) if not (forwarding_enabled and forwarding_trampoline_enabled): self.logger.info(f"trampoline forwarding is disabled. failing htlc.") raise OnionRoutingFailure(code=OnionFailureCode.PERMANENT_CHANNEL_FAILURE, data=b'') payload = trampoline_onion.hop_data.payload payment_hash = htlc.payment_hash payment_secret = os.urandom(32) try: outgoing_node_id = payload["outgoing_node_id"]["outgoing_node_id"] amt_to_forward = payload["amt_to_forward"]["amt_to_forward"] cltv_from_onion = payload["outgoing_cltv_value"]["outgoing_cltv_value"] if "invoice_features" in payload: self.logger.info('forward_trampoline: legacy') next_trampoline_onion = None invoice_features = payload["invoice_features"]["invoice_features"] invoice_routing_info = payload["invoice_routing_info"]["invoice_routing_info"] # TODO use invoice_routing_info else: self.logger.info('forward_trampoline: end-to-end') invoice_features = LnFeatures.BASIC_MPP_OPT next_trampoline_onion = trampoline_onion.next_packet except Exception as e: self.logger.exception('') raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') # these are the fee/cltv paid by the sender # pay_to_node will raise if they are not sufficient trampoline_cltv_delta = htlc.cltv_expiry - cltv_from_onion trampoline_fee = htlc.amount_msat - amt_to_forward @log_exceptions async def forward_trampoline_payment(): try: await self.lnworker.pay_to_node( node_pubkey=outgoing_node_id, payment_hash=payment_hash, payment_secret=payment_secret, amount_to_pay=amt_to_forward, min_cltv_expiry=cltv_from_onion, r_tags=[], invoice_features=invoice_features, fwd_trampoline_onion=next_trampoline_onion, fwd_trampoline_fee=trampoline_fee, fwd_trampoline_cltv_delta=trampoline_cltv_delta, attempts=1) except OnionRoutingFailure as e: # FIXME: cannot use payment_hash as key self.lnworker.trampoline_forwarding_failures[payment_hash] = e except PaymentFailure as e: # FIXME: adapt the error code error_reason = OnionRoutingFailure(code=OnionFailureCode.UNKNOWN_NEXT_PEER, data=b'') self.lnworker.trampoline_forwarding_failures[payment_hash] = error_reason asyncio.ensure_future(forward_trampoline_payment()) def maybe_fulfill_htlc( self, *, chan: Channel, htlc: UpdateAddHtlc, processed_onion: ProcessedOnionPacket, is_trampoline: bool = False) -> Tuple[Optional[bytes], Optional[OnionPacket]]: """As a final recipient of an HTLC, decide if we should fulfill it. Return (preimage, trampoline_onion_packet) with at most a single element not None """ def log_fail_reason(reason: str): self.logger.info(f"maybe_fulfill_htlc. will FAIL HTLC: chan {chan.short_channel_id}. " f"{reason}. htlc={str(htlc)}. onion_payload={processed_onion.hop_data.payload}") try: amt_to_forward = processed_onion.hop_data.payload["amt_to_forward"]["amt_to_forward"] except: log_fail_reason(f"'amt_to_forward' missing from onion") raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') # Check that our blockchain tip is sufficiently recent so that we have an approx idea of the height. # We should not release the preimage for an HTLC that its sender could already time out as # then they might try to force-close and it becomes a race. chain = self.network.blockchain() if chain.is_tip_stale(): log_fail_reason(f"our chain tip is stale") raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_NODE_FAILURE, data=b'') local_height = chain.height() exc_incorrect_or_unknown_pd = OnionRoutingFailure( code=OnionFailureCode.INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS, data=amt_to_forward.to_bytes(8, byteorder="big") + local_height.to_bytes(4, byteorder="big")) if local_height + MIN_FINAL_CLTV_EXPIRY_ACCEPTED > htlc.cltv_expiry: log_fail_reason(f"htlc.cltv_expiry is unreasonably close") raise exc_incorrect_or_unknown_pd try: cltv_from_onion = processed_onion.hop_data.payload["outgoing_cltv_value"]["outgoing_cltv_value"] except: log_fail_reason(f"'outgoing_cltv_value' missing from onion") raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') if not is_trampoline: if cltv_from_onion != htlc.cltv_expiry: log_fail_reason(f"cltv_from_onion != htlc.cltv_expiry") raise OnionRoutingFailure( code=OnionFailureCode.FINAL_INCORRECT_CLTV_EXPIRY, data=htlc.cltv_expiry.to_bytes(4, byteorder="big")) try: total_msat = processed_onion.hop_data.payload["payment_data"]["total_msat"] except: total_msat = amt_to_forward # fall back to "amt_to_forward" if not is_trampoline and amt_to_forward != htlc.amount_msat: log_fail_reason(f"amt_to_forward != htlc.amount_msat") raise OnionRoutingFailure( code=OnionFailureCode.FINAL_INCORRECT_HTLC_AMOUNT, data=htlc.amount_msat.to_bytes(8, byteorder="big")) try: payment_secret_from_onion = processed_onion.hop_data.payload["payment_data"]["payment_secret"] except: if total_msat > amt_to_forward: # payment_secret is required for MPP log_fail_reason(f"'payment_secret' missing from onion") raise exc_incorrect_or_unknown_pd # TODO fail here if invoice has set PAYMENT_SECRET_REQ payment_secret_from_onion = None if total_msat > amt_to_forward: mpp_status = self.lnworker.check_received_mpp_htlc(payment_secret_from_onion, chan.short_channel_id, htlc, total_msat) if mpp_status is None: return None, None if mpp_status is False: log_fail_reason(f"MPP_TIMEOUT") raise OnionRoutingFailure(code=OnionFailureCode.MPP_TIMEOUT, data=b'') assert mpp_status is True # if there is a trampoline_onion, maybe_fulfill_htlc will be called again if processed_onion.trampoline_onion_packet: # TODO: we should check that all trampoline_onions are the same return None, processed_onion.trampoline_onion_packet # TODO don't accept payments twice for same invoice # TODO check invoice expiry info = self.lnworker.get_payment_info(htlc.payment_hash) if info is None: log_fail_reason(f"no payment_info found for RHASH {htlc.payment_hash.hex()}") raise exc_incorrect_or_unknown_pd preimage = self.lnworker.get_preimage(htlc.payment_hash) if payment_secret_from_onion: if payment_secret_from_onion != derive_payment_secret_from_payment_preimage(preimage): log_fail_reason(f'incorrect payment secret {payment_secret_from_onion.hex()} != {derive_payment_secret_from_payment_preimage(preimage).hex()}') raise exc_incorrect_or_unknown_pd invoice_msat = info.amount_msat if not (invoice_msat is None or invoice_msat <= total_msat <= 2 * invoice_msat): log_fail_reason(f"total_msat={total_msat} too different from invoice_msat={invoice_msat}") raise exc_incorrect_or_unknown_pd self.logger.info(f"maybe_fulfill_htlc. will FULFILL HTLC: chan {chan.short_channel_id}. htlc={str(htlc)}") self.lnworker.set_request_status(htlc.payment_hash, PR_PAID) return preimage, None def fulfill_htlc(self, chan: Channel, htlc_id: int, preimage: bytes): self.logger.info(f"_fulfill_htlc. chan {chan.short_channel_id}. htlc_id {htlc_id}") assert chan.can_send_ctx_updates(), f"cannot send updates: {chan.short_channel_id}" assert chan.hm.is_htlc_irrevocably_added_yet(htlc_proposer=REMOTE, htlc_id=htlc_id) self.received_htlcs_pending_removal.add((chan, htlc_id)) chan.settle_htlc(preimage, htlc_id) self.send_message( "update_fulfill_htlc", channel_id=chan.channel_id, id=htlc_id, payment_preimage=preimage) def fail_htlc(self, *, chan: Channel, htlc_id: int, error_bytes: bytes): self.logger.info(f"fail_htlc. chan {chan.short_channel_id}. htlc_id {htlc_id}.") assert chan.can_send_ctx_updates(), f"cannot send updates: {chan.short_channel_id}" self.received_htlcs_pending_removal.add((chan, htlc_id)) chan.fail_htlc(htlc_id) self.send_message( "update_fail_htlc", channel_id=chan.channel_id, id=htlc_id, len=len(error_bytes), reason=error_bytes) def fail_malformed_htlc(self, *, chan: Channel, htlc_id: int, reason: OnionRoutingFailure): self.logger.info(f"fail_malformed_htlc. chan {chan.short_channel_id}. htlc_id {htlc_id}.") assert chan.can_send_ctx_updates(), f"cannot send updates: {chan.short_channel_id}" if not (reason.code & OnionFailureCodeMetaFlag.BADONION and len(reason.data) == 32): raise Exception(f"unexpected reason when sending 'update_fail_malformed_htlc': {reason!r}") self.received_htlcs_pending_removal.add((chan, htlc_id)) chan.fail_htlc(htlc_id) self.send_message( "update_fail_malformed_htlc", channel_id=chan.channel_id, id=htlc_id, sha256_of_onion=reason.data, failure_code=reason.code) def on_revoke_and_ack(self, chan: Channel, payload): if chan.peer_state == PeerState.BAD: return self.logger.info(f'on_revoke_and_ack. chan {chan.short_channel_id}. ctn: {chan.get_oldest_unrevoked_ctn(REMOTE)}') rev = RevokeAndAck(payload["per_commitment_secret"], payload["next_per_commitment_point"]) chan.receive_revocation(rev) self.lnworker.save_channel(chan) self.maybe_send_commitment(chan) def on_update_fee(self, chan: Channel, payload): feerate = payload["feerate_per_kw"] chan.update_fee(feerate, False) async def maybe_update_fee(self, chan: Channel): """ called when our fee estimates change """ if not chan.can_send_ctx_updates(): return feerate_per_kw = self.lnworker.current_feerate_per_kw() if not chan.constraints.is_initiator: if constants.net is not constants.BitcoinRegtest: chan_feerate = chan.get_latest_feerate(LOCAL) ratio = chan_feerate / feerate_per_kw if ratio < 0.5: # Note that we trust the Electrum server about fee rates # Thus, automated force-closing might not be a good idea # Maybe we should display something in the GUI instead self.logger.warning( f"({chan.get_id_for_log()}) feerate is {chan_feerate} gro/kw, " f"current recommended feerate is {feerate_per_kw} gro/kw, consider force closing!") return chan_fee = chan.get_next_feerate(REMOTE) if feerate_per_kw < chan_fee / 2: self.logger.info("FEES HAVE FALLEN") elif feerate_per_kw > chan_fee * 2: self.logger.info("FEES HAVE RISEN") elif chan.get_oldest_unrevoked_ctn(REMOTE) == 0: # workaround eclair issue https://github.com/ACINQ/eclair/issues/1730 self.logger.info("updating fee to bump remote ctn") if feerate_per_kw == chan_fee: feerate_per_kw += 1 else: return self.logger.info(f"(chan: {chan.get_id_for_log()}) current pending feerate {chan_fee}. " f"new feerate {feerate_per_kw}") chan.update_fee(feerate_per_kw, True) self.send_message( "update_fee", channel_id=chan.channel_id, feerate_per_kw=feerate_per_kw) self.maybe_send_commitment(chan) @log_exceptions async def close_channel(self, chan_id: bytes): chan = self.channels[chan_id] self.shutdown_received[chan_id] = asyncio.Future() await self.send_shutdown(chan) payload = await self.shutdown_received[chan_id] try: txid = await self._shutdown(chan, payload, is_local=True) self.logger.info(f'({chan.get_id_for_log()}) Channel closed {txid}') except asyncio.TimeoutError: txid = chan.unconfirmed_closing_txid self.logger.info(f'({chan.get_id_for_log()}) did not send closing_signed, {txid}') if txid is None: raise Exception('The remote peer did not send their final signature. The channel may not have been be closed') return txid async def on_shutdown(self, chan: Channel, payload): their_scriptpubkey = payload['scriptpubkey'] their_upfront_scriptpubkey = chan.config[REMOTE].upfront_shutdown_script # BOLT-02 check if they use the upfront shutdown script they advertized if their_upfront_scriptpubkey: if not (their_scriptpubkey == their_upfront_scriptpubkey): raise UpfrontShutdownScriptViolation("remote didn't use upfront shutdown script it commited to in channel opening") # BOLT-02 restrict the scriptpubkey to some templates: if not (match_script_against_template(their_scriptpubkey, transaction.SCRIPTPUBKEY_TEMPLATE_WITNESS_V0) or match_script_against_template(their_scriptpubkey, transaction.SCRIPTPUBKEY_TEMPLATE_P2SH) or match_script_against_template(their_scriptpubkey, transaction.SCRIPTPUBKEY_TEMPLATE_P2PKH)): raise Exception(f'scriptpubkey in received shutdown message does not conform to any template: {their_scriptpubkey.hex()}') chan_id = chan.channel_id if chan_id in self.shutdown_received: self.shutdown_received[chan_id].set_result(payload) else: chan = self.channels[chan_id] await self.send_shutdown(chan) txid = await self._shutdown(chan, payload, is_local=False) self.logger.info(f'({chan.get_id_for_log()}) Channel closed by remote peer {txid}') def can_send_shutdown(self, chan: Channel): if chan.get_state() >= ChannelState.OPENING: return True if chan.constraints.is_initiator and chan.channel_id in self.funding_created_sent: return True if not chan.constraints.is_initiator and chan.channel_id in self.funding_signed_sent: return True return False async def send_shutdown(self, chan: Channel): if not self.can_send_shutdown(chan): raise Exception('cannot send shutdown') if chan.config[LOCAL].upfront_shutdown_script: scriptpubkey = chan.config[LOCAL].upfront_shutdown_script else: scriptpubkey = bfh(bitcoin.address_to_script(chan.sweep_address)) assert scriptpubkey # wait until no more pending updates (bolt2) chan.set_can_send_ctx_updates(False) while chan.has_pending_changes(REMOTE): await asyncio.sleep(0.1) self.send_message('shutdown', channel_id=chan.channel_id, len=len(scriptpubkey), scriptpubkey=scriptpubkey) chan.set_state(ChannelState.SHUTDOWN) # can fullfill or fail htlcs. cannot add htlcs, because state != OPEN chan.set_can_send_ctx_updates(True) @log_exceptions async def _shutdown(self, chan: Channel, payload, *, is_local: bool): # wait until no HTLCs remain in either commitment transaction while len(chan.hm.htlcs(LOCAL)) + len(chan.hm.htlcs(REMOTE)) > 0: self.logger.info(f'(chan: {chan.short_channel_id}) waiting for htlcs to settle...') await asyncio.sleep(1) # if no HTLCs remain, we must not send updates chan.set_can_send_ctx_updates(False) their_scriptpubkey = payload['scriptpubkey'] if chan.config[LOCAL].upfront_shutdown_script: our_scriptpubkey = chan.config[LOCAL].upfront_shutdown_script else: our_scriptpubkey = bfh(bitcoin.address_to_script(chan.sweep_address)) assert our_scriptpubkey # estimate fee of closing tx our_sig, closing_tx = chan.make_closing_tx(our_scriptpubkey, their_scriptpubkey, fee_sat=0) fee_rate = self.network.config.fee_per_kb() our_fee = fee_rate * closing_tx.estimated_size() // 1000 # BOLT2: The sending node MUST set fee less than or equal to the base fee of the final ctx max_fee = chan.get_latest_fee(LOCAL if is_local else REMOTE) our_fee = min(our_fee, max_fee) drop_remote = False def send_closing_signed(): our_sig, closing_tx = chan.make_closing_tx(our_scriptpubkey, their_scriptpubkey, fee_sat=our_fee, drop_remote=drop_remote) self.send_message('closing_signed', channel_id=chan.channel_id, fee_satoshis=our_fee, signature=our_sig) def verify_signature(tx, sig): their_pubkey = chan.config[REMOTE].multisig_key.pubkey preimage_hex = tx.serialize_preimage(0) pre_hash = sha256(bfh(preimage_hex)) return ecc.verify_signature(their_pubkey, sig, pre_hash) # the funder sends the first 'closing_signed' message if chan.constraints.is_initiator: send_closing_signed() # negotiate fee while True: # FIXME: the remote SHOULD send closing_signed, but some don't. cs_payload = await self.wait_for_message('closing_signed', chan.channel_id) their_fee = cs_payload['fee_satoshis'] if their_fee > max_fee: raise Exception(f'the proposed fee exceeds the base fee of the latest commitment transaction {is_local, their_fee, max_fee}') their_sig = cs_payload['signature'] # verify their sig: they might have dropped their output our_sig, closing_tx = chan.make_closing_tx(our_scriptpubkey, their_scriptpubkey, fee_sat=their_fee, drop_remote=False) if verify_signature(closing_tx, their_sig): drop_remote = False else: our_sig, closing_tx = chan.make_closing_tx(our_scriptpubkey, their_scriptpubkey, fee_sat=their_fee, drop_remote=True) if verify_signature(closing_tx, their_sig): drop_remote = True else: raise Exception('failed to verify their signature') # Agree if difference is lower or equal to one (see below) if abs(our_fee - their_fee) < 2: our_fee = their_fee break # this will be "strictly between" (as in BOLT2) previous values because of the above our_fee = (our_fee + their_fee) // 2 # another round send_closing_signed() # the non-funder replies if not chan.constraints.is_initiator: send_closing_signed() # add signatures closing_tx.add_signature_to_txin( txin_idx=0, signing_pubkey=chan.config[LOCAL].multisig_key.pubkey.hex(), sig=bh2u(der_sig_from_sig_string(our_sig) + b'\x01')) closing_tx.add_signature_to_txin( txin_idx=0, signing_pubkey=chan.config[REMOTE].multisig_key.pubkey.hex(), sig=bh2u(der_sig_from_sig_string(their_sig) + b'\x01')) # save local transaction and set state try: self.lnworker.wallet.add_transaction(closing_tx) except UnrelatedTransactionException: pass # this can happen if (~all the balance goes to REMOTE) chan.set_state(ChannelState.CLOSING) # broadcast await self.network.try_broadcasting(closing_tx, 'closing') return closing_tx.txid() async def htlc_switch(self): await self.initialized while True: self._htlc_switch_iterdone_event.set() self._htlc_switch_iterdone_event.clear() await asyncio.sleep(0.1) # TODO maybe make this partly event-driven self._htlc_switch_iterstart_event.set() self._htlc_switch_iterstart_event.clear() self.ping_if_required() self._maybe_cleanup_received_htlcs_pending_removal() for chan_id, chan in self.channels.items(): if not chan.can_send_ctx_updates(): continue self.maybe_send_commitment(chan) done = set() unfulfilled = chan.unfulfilled_htlcs for htlc_id, (local_ctn, remote_ctn, onion_packet_hex, forwarding_info) in unfulfilled.items(): if not chan.hm.is_htlc_irrevocably_added_yet(htlc_proposer=REMOTE, htlc_id=htlc_id): continue htlc = chan.hm.get_htlc_by_id(REMOTE, htlc_id) error_reason = None # type: Optional[OnionRoutingFailure] error_bytes = None # type: Optional[bytes] preimage = None fw_info = None onion_packet_bytes = bytes.fromhex(onion_packet_hex) onion_packet = None try: onion_packet = OnionPacket.from_bytes(onion_packet_bytes) except OnionRoutingFailure as e: error_reason = e else: try: preimage, fw_info, error_bytes = self.process_unfulfilled_htlc( chan=chan, htlc=htlc, forwarding_info=forwarding_info, onion_packet_bytes=onion_packet_bytes, onion_packet=onion_packet) except OnionRoutingFailure as e: error_bytes = construct_onion_error(e, onion_packet, our_onion_private_key=self.privkey) if fw_info: unfulfilled[htlc_id] = local_ctn, remote_ctn, onion_packet_hex, fw_info elif preimage or error_reason or error_bytes: if preimage: if not self.lnworker.enable_htlc_settle: continue self.fulfill_htlc(chan, htlc.htlc_id, preimage) elif error_bytes: self.fail_htlc( chan=chan, htlc_id=htlc.htlc_id, error_bytes=error_bytes) else: self.fail_malformed_htlc( chan=chan, htlc_id=htlc.htlc_id, reason=error_reason) done.add(htlc_id) # cleanup for htlc_id in done: unfulfilled.pop(htlc_id) def _maybe_cleanup_received_htlcs_pending_removal(self) -> None: done = set() for chan, htlc_id in self.received_htlcs_pending_removal: if chan.hm.is_htlc_irrevocably_removed_yet(htlc_proposer=REMOTE, htlc_id=htlc_id): done.add((chan, htlc_id)) if done: for key in done: self.received_htlcs_pending_removal.remove(key) self.received_htlc_removed_event.set() self.received_htlc_removed_event.clear() async def wait_one_htlc_switch_iteration(self) -> None: """Waits until the HTLC switch does a full iteration or the peer disconnects, whichever happens first. """ async def htlc_switch_iteration(): await self._htlc_switch_iterstart_event.wait() await self._htlc_switch_iterdone_event.wait() async with TaskGroup(wait=any) as group: await group.spawn(htlc_switch_iteration()) await group.spawn(self.got_disconnected.wait()) def process_unfulfilled_htlc( self, *, chan: Channel, htlc: UpdateAddHtlc, forwarding_info: Tuple[str, int], onion_packet_bytes: bytes, onion_packet: OnionPacket) -> Tuple[Optional[bytes], Union[bool, None, Tuple[str, int]], Optional[bytes]]: """ return (preimage, fw_info, error_bytes) with at most a single element that is not None raise an OnionRoutingFailure if we need to fail the htlc """ payment_hash = htlc.payment_hash processed_onion = self.process_onion_packet( onion_packet, payment_hash=payment_hash, onion_packet_bytes=onion_packet_bytes) if processed_onion.are_we_final: # either we are final recipient; or if trampoline, see cases below preimage, trampoline_onion_packet = self.maybe_fulfill_htlc( chan=chan, htlc=htlc, processed_onion=processed_onion) if trampoline_onion_packet: # trampoline- recipient or forwarding if not forwarding_info: trampoline_onion = self.process_onion_packet( trampoline_onion_packet, payment_hash=htlc.payment_hash, onion_packet_bytes=onion_packet_bytes, is_trampoline=True) if trampoline_onion.are_we_final: # trampoline- we are final recipient of HTLC preimage, _ = self.maybe_fulfill_htlc( chan=chan, htlc=htlc, processed_onion=trampoline_onion, is_trampoline=True) else: # trampoline- HTLC we are supposed to forward, but haven't forwarded yet if not self.lnworker.enable_htlc_forwarding: return None, None, None self.maybe_forward_trampoline( chan=chan, htlc=htlc, trampoline_onion=trampoline_onion) # return True so that this code gets executed only once return None, True, None else: # trampoline- HTLC we are supposed to forward, and have already forwarded preimage = self.lnworker.get_preimage(payment_hash) error_reason = self.lnworker.trampoline_forwarding_failures.pop(payment_hash, None) if error_reason: self.logger.info(f'trampoline forwarding failure: {error_reason.code_name()}') raise error_reason elif not forwarding_info: # HTLC we are supposed to forward, but haven't forwarded yet if not self.lnworker.enable_htlc_forwarding: return None, None, None next_chan_id, next_htlc_id = self.maybe_forward_htlc( htlc=htlc, processed_onion=processed_onion) fw_info = (next_chan_id.hex(), next_htlc_id) return None, fw_info, None else: # HTLC we are supposed to forward, and have already forwarded preimage = self.lnworker.get_preimage(payment_hash) next_chan_id_hex, htlc_id = forwarding_info next_chan = self.lnworker.get_channel_by_short_id(bytes.fromhex(next_chan_id_hex)) if next_chan: error_bytes, error_reason = next_chan.pop_fail_htlc_reason(htlc_id) if error_bytes: return None, None, error_bytes if error_reason: raise error_reason if preimage: return preimage, None, None return None, None, None def process_onion_packet( self, onion_packet: OnionPacket, *, payment_hash: bytes, onion_packet_bytes: bytes, is_trampoline: bool = False) -> ProcessedOnionPacket: failure_data = sha256(onion_packet_bytes) try: processed_onion = process_onion_packet( onion_packet, associated_data=payment_hash, our_onion_private_key=self.privkey, is_trampoline=is_trampoline) except UnsupportedOnionPacketVersion: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_VERSION, data=failure_data) except InvalidOnionPubkey: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_KEY, data=failure_data) except InvalidOnionMac: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_HMAC, data=failure_data) except Exception as e: self.logger.info(f"error processing onion packet: {e!r}") raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_VERSION, data=failure_data) if self.network.config.get('test_fail_malformed_htlc'): raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_VERSION, data=failure_data) if self.network.config.get('test_fail_htlcs_with_temp_node_failure'): raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_NODE_FAILURE, data=b'') return processed_onion
import itertools import sys import torch from torch import nn import unittest from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from torch.nn import CrossEntropyLoss from torch.optim import SGD from torch.optim.lr_scheduler import MultiStepLR, ReduceLROnPlateau from torch.utils.data import TensorDataset from torch.utils.data.dataloader import DataLoader from avalanche.benchmarks import nc_benchmark, GenericCLScenario, \ benchmark_with_validation_stream from avalanche.benchmarks.utils.data_loader import TaskBalancedDataLoader from avalanche.evaluation.metric_results import MetricValue from avalanche.evaluation.metrics import Mean from avalanche.logging import TextLogger from avalanche.models import BaseModel from avalanche.training.plugins import StrategyPlugin, EvaluationPlugin from avalanche.training.plugins.lr_scheduling import LRSchedulerPlugin from avalanche.training.strategies import Naive class MockPlugin(StrategyPlugin): def __init__(self): super().__init__() self.count = 0 self.activated = [False for _ in range(22)] def before_training_exp(self, strategy, **kwargs): self.activated[0] = True def after_train_dataset_adaptation(self, strategy, **kwargs): self.activated[1] = True def before_training_epoch(self, strategy, **kwargs): self.activated[2] = True def before_training_iteration(self, strategy, **kwargs): self.activated[3] = True def before_forward(self, strategy, **kwargs): self.activated[4] = True def after_forward(self, strategy, **kwargs): self.activated[5] = True def before_backward(self, strategy, **kwargs): self.activated[6] = True def after_backward(self, strategy, **kwargs): self.activated[7] = True def after_training_iteration(self, strategy, **kwargs): self.activated[8] = True def before_update(self, strategy, **kwargs): self.activated[9] = True def after_update(self, strategy, **kwargs): self.activated[10] = True def after_training_epoch(self, strategy, **kwargs): self.activated[11] = True def after_training_exp(self, strategy, **kwargs): self.activated[12] = True def before_eval(self, strategy, **kwargs): self.activated[13] = True def after_eval_dataset_adaptation(self, strategy, **kwargs): self.activated[14] = True def before_eval_exp(self, strategy, **kwargs): self.activated[15] = True def after_eval_exp(self, strategy, **kwargs): self.activated[16] = True def after_eval(self, strategy, **kwargs): self.activated[17] = True def before_eval_iteration(self, strategy, **kwargs): self.activated[18] = True def before_eval_forward(self, strategy, **kwargs): self.activated[19] = True def after_eval_forward(self, strategy, **kwargs): self.activated[20] = True def after_eval_iteration(self, strategy, **kwargs): self.activated[21] = True class PluginTests(unittest.TestCase): def test_callback_reachability(self): # Check that all the callbacks are called during # training and test loops. model = _PlainMLP(input_size=6, hidden_size=10) optimizer = SGD(model.parameters(), lr=1e-3) criterion = CrossEntropyLoss() benchmark = PluginTests.create_benchmark() plug = MockPlugin() strategy = Naive(model, optimizer, criterion, train_mb_size=100, train_epochs=1, eval_mb_size=100, device='cpu', plugins=[plug] ) strategy.evaluator.loggers = [TextLogger(sys.stdout)] strategy.train(benchmark.train_stream[0], num_workers=4) strategy.eval([benchmark.test_stream[0]], num_workers=4) assert all(plug.activated) @staticmethod def create_benchmark(task_labels=False, seed=None): n_samples_per_class = 20 dataset = make_classification( n_samples=10 * n_samples_per_class, n_classes=10, n_features=6, n_informative=6, n_redundant=0, random_state=seed) X = torch.from_numpy(dataset[0]).float() y = torch.from_numpy(dataset[1]).long() train_X, test_X, train_y, test_y = train_test_split( X, y, train_size=0.6, shuffle=True, stratify=y, random_state=seed) train_dataset = TensorDataset(train_X, train_y) test_dataset = TensorDataset(test_X, test_y) return nc_benchmark(train_dataset, test_dataset, 5, task_labels=task_labels, fixed_class_order=list(range(10))) def test_scheduler_plugin(self): PluginTests._test_scheduler_multi_step_lr_plugin( gamma=1 / 2., milestones=[2, 3], base_lr=4., epochs=3, reset_lr=True, reset_scheduler=True, expected=[[4., 2., 1.], [4., 2., 1.]]) PluginTests._test_scheduler_multi_step_lr_plugin( gamma=1 / 2., milestones=[2, 3], base_lr=4., epochs=3, reset_lr=False, reset_scheduler=True, expected=[[4., 2., 1.], [1., .5, .25]]) PluginTests._test_scheduler_multi_step_lr_plugin( gamma=1 / 2., milestones=[2, 3], base_lr=4., epochs=3, reset_lr=True, reset_scheduler=False, expected=[[4., 2., 1.], [4., 4., 4.]]) PluginTests._test_scheduler_multi_step_lr_plugin( gamma=1 / 2., milestones=[2, 3], base_lr=4., epochs=3, reset_lr=False, reset_scheduler=False, expected=[[4., 2., 1.], [1., 1., 1.]]) @staticmethod def _test_scheduler_multi_step_lr_plugin( gamma, milestones, base_lr, epochs, reset_lr, reset_scheduler, expected): benchmark = PluginTests.create_benchmark() model = _PlainMLP(input_size=6, hidden_size=10) optim = SGD(model.parameters(), lr=base_lr) scheduler = MultiStepLR(optim, milestones=milestones, gamma=gamma) PluginTests._test_scheduler_plugin( benchmark, model, optim, scheduler, epochs, reset_lr, reset_scheduler, expected) def assert_model_equals(self, model1, model2): dict1 = model1.state_dict() dict2 = model2.state_dict() # compare keys self.assertSetEqual(set(dict1.keys()), set(dict2.keys())) # compare params for (k, v) in dict1.items(): self.assertTrue(torch.equal(v, dict2[k])) def assert_benchmark_equals( self, bench1: GenericCLScenario, bench2: GenericCLScenario): self.assertSetEqual(set(bench1.streams.keys()), set(bench2.streams.keys())) for stream_name in list(bench1.streams.keys()): for exp1, exp2 in zip(bench1.streams[stream_name], bench2.streams[stream_name]): dataset1 = exp1.dataset dataset2 = exp2.dataset for t_idx in range(3): dataset1_content = dataset1[:][t_idx] dataset2_content = dataset2[:][t_idx] self.assertTrue(torch.equal(dataset1_content, dataset2_content)) def _verify_rop_tests_reproducibility( self, init_strategy, n_epochs, criterion): # This doesn't actually test the support for the specific scheduler # (ReduceLROnPlateau), but it's only used to check if: # - the same model+benchmark pair can be instantiated in a # deterministic way. # - the same results could be obtained in a standard training loop in a # deterministic way. models_rnd = [] benchmarks_rnd = [] for _ in range(2): benchmark, model = init_strategy() models_rnd.append(model) benchmarks_rnd.append(benchmark) self.assert_model_equals(*models_rnd) self.assert_benchmark_equals(*benchmarks_rnd) expected_lrs_rnd = [] for _ in range(2): benchmark, model = init_strategy() expected_lrs = [] model.train() for exp in benchmark.train_stream: optimizer = SGD(model.parameters(), lr=0.001) scheduler = ReduceLROnPlateau(optimizer) expected_lrs.append([]) train_loss = Mean() for epoch in range(n_epochs): train_loss.reset() for x, y, t in TaskBalancedDataLoader( exp.dataset, oversample_small_groups=True, num_workers=0, batch_size=32, shuffle=False, pin_memory=False): optimizer.zero_grad() outputs = model(x) loss = criterion(outputs, y) train_loss.update(loss, weight=len(x)) loss.backward() optimizer.step() scheduler.step(train_loss.result()) for group in optimizer.param_groups: expected_lrs[-1].append(group['lr']) break expected_lrs_rnd.append(expected_lrs) self.assertEqual(expected_lrs_rnd[0], expected_lrs_rnd[1]) def test_scheduler_reduce_on_plateau_plugin(self): # Regression test for issue #858 n_epochs = 20 criterion = CrossEntropyLoss() def _prepare_rng_critical_parts(seed=1234): torch.random.manual_seed(seed) return (PluginTests.create_benchmark(seed=seed), _PlainMLP(input_size=6, hidden_size=10)) self._verify_rop_tests_reproducibility( _prepare_rng_critical_parts, n_epochs, criterion) # Everything is in order, now we can test the plugin support for the # ReduceLROnPlateau scheduler! for reset_lr, reset_scheduler in itertools.product( (True, False), (True, False)): with self.subTest(reset_lr=reset_lr, reset_scheduler=reset_scheduler): # First, obtain the reference (expected) lr timeline by running # a plain PyTorch training loop with ReduceLROnPlateau. benchmark, model = _prepare_rng_critical_parts() model.train() expected_lrs = [] optimizer = SGD(model.parameters(), lr=0.001) scheduler = ReduceLROnPlateau(optimizer) for exp in benchmark.train_stream: if reset_lr: for group in optimizer.param_groups: group['lr'] = 0.001 if reset_scheduler: scheduler = ReduceLROnPlateau(optimizer) expected_lrs.append([]) train_loss = Mean() for epoch in range(n_epochs): train_loss.reset() for x, y, t in TaskBalancedDataLoader( exp.dataset, oversample_small_groups=True, num_workers=0, batch_size=32, shuffle=False, pin_memory=False): optimizer.zero_grad() outputs = model(x) loss = criterion(outputs, y) train_loss.update(loss, weight=len(x)) loss.backward() optimizer.step() scheduler.step(train_loss.result()) for group in optimizer.param_groups: expected_lrs[-1].append(group['lr']) break # Now we have the correct timeline stored in expected_lrs. # Let's test the plugin! benchmark, model = _prepare_rng_critical_parts() optimizer = SGD(model.parameters(), lr=0.001) scheduler = ReduceLROnPlateau(optimizer) PluginTests._test_scheduler_plugin( benchmark, model, optimizer, scheduler, n_epochs, reset_lr, reset_scheduler, expected_lrs, criterion=criterion, metric='train_loss') # Other tests benchmark, model = _prepare_rng_critical_parts() optimizer = SGD(model.parameters(), lr=0.001) scheduler = ReduceLROnPlateau(optimizer) scheduler2 = MultiStepLR(optimizer, [1, 2, 3]) # The metric must be set with self.assertRaises(Exception): LRSchedulerPlugin( scheduler, metric=None) # Doesn't make sense to set the metric when using a non-metric # based scheduler (should warn) with self.assertWarns(Warning): LRSchedulerPlugin( scheduler2, metric='train_loss') # Must raise an error on unsupported metric with self.assertRaises(Exception): LRSchedulerPlugin( scheduler, metric='cuteness') def test_scheduler_reduce_on_plateau_plugin_with_val_stream(self): # Regression test for issue #858 (part 2) n_epochs = 20 criterion = CrossEntropyLoss() def _prepare_rng_critical_parts(seed=1234): torch.random.manual_seed(seed) initial_benchmark = PluginTests.create_benchmark(seed=seed) val_benchmark = benchmark_with_validation_stream( initial_benchmark, 0.3, shuffle=True) return (val_benchmark, _PlainMLP(input_size=6, hidden_size=10)) self._verify_rop_tests_reproducibility( _prepare_rng_critical_parts, n_epochs, criterion) # Everything is in order, now we can test the plugin support for the # ReduceLROnPlateau scheduler! for reset_lr, reset_scheduler in itertools.product( (True, False), (True, False)): with self.subTest(reset_lr=reset_lr, reset_scheduler=reset_scheduler): # First, obtain the reference (expected) lr timeline by running # a plain PyTorch training loop with ReduceLROnPlateau. benchmark, model = _prepare_rng_critical_parts() expected_lrs = [] optimizer = SGD(model.parameters(), lr=0.001) scheduler = ReduceLROnPlateau(optimizer) for exp_idx, exp in enumerate(benchmark.train_stream): expected_lrs.append([]) model.train() if reset_lr: for group in optimizer.param_groups: group['lr'] = 0.001 if reset_scheduler: scheduler = ReduceLROnPlateau(optimizer) for epoch in range(n_epochs): for x, y, t in TaskBalancedDataLoader( exp.dataset, oversample_small_groups=True, num_workers=0, batch_size=32, shuffle=False, pin_memory=False): optimizer.zero_grad() outputs = model(x) loss = criterion(outputs, y) loss.backward() optimizer.step() for group in optimizer.param_groups: expected_lrs[-1].append(group['lr']) break val_loss = Mean() val_exp = benchmark.valid_stream[exp_idx] model.eval() with torch.no_grad(): for x, y, t in DataLoader( val_exp.dataset, num_workers=0, batch_size=100, pin_memory=False): outputs = model(x) loss = criterion(outputs, y) val_loss.update(loss, weight=len(x)) scheduler.step(val_loss.result()) # Now we have the correct timeline stored in expected_lrs # Let's test the plugin! benchmark, model = _prepare_rng_critical_parts() optimizer = SGD(model.parameters(), lr=0.001) scheduler = ReduceLROnPlateau(optimizer) PluginTests._test_scheduler_plugin( benchmark, model, optimizer, scheduler, n_epochs, reset_lr, reset_scheduler, expected_lrs, criterion=criterion, metric='val_loss', eval_on_valid_stream=True) @staticmethod def _test_scheduler_plugin( benchmark, model, optim, scheduler, epochs, reset_lr, reset_scheduler, expected, criterion=None, metric=None, eval_on_valid_stream=False): lr_scheduler_plugin = LRSchedulerPlugin( scheduler, reset_lr=reset_lr, reset_scheduler=reset_scheduler, metric=metric) verifier_plugin = SchedulerPluginTestPlugin(expected) if criterion is None: criterion = CrossEntropyLoss() if eval_on_valid_stream: cl_strategy = Naive( model, optim, criterion, train_mb_size=32, train_epochs=epochs, eval_mb_size=100, plugins=[lr_scheduler_plugin, verifier_plugin], eval_every=1, evaluator=None) cl_strategy.train(benchmark.train_stream[0], shuffle=False, eval_streams=[benchmark.valid_stream[0]]) cl_strategy.train(benchmark.train_stream[1], shuffle=False, eval_streams=[benchmark.valid_stream[1]]) else: cl_strategy = Naive( model, optim, criterion, train_mb_size=32, train_epochs=epochs, eval_mb_size=100, plugins=[lr_scheduler_plugin, verifier_plugin], evaluator=None) cl_strategy.train(benchmark.train_stream[0], shuffle=False) cl_strategy.train(benchmark.train_stream[1], shuffle=False) class SchedulerPluginTestPlugin(StrategyPlugin): def __init__(self, expected_lrs): super().__init__() self.expected_lrs = expected_lrs def after_training_epoch(self, strategy, **kwargs): exp_id = strategy.clock.train_exp_counter curr_epoch = strategy.clock.train_exp_epochs expected_lr = self.expected_lrs[exp_id][curr_epoch] for group in strategy.optimizer.param_groups: assert group['lr'] == expected_lr,\ f"LR mismatch: {group["lr"]} vs {expected_lr}" class _PlainMLP(nn.Module, BaseModel): """ An internal MLP implementation without Dropout. Needed to reproduce tests for the ReduceLROnPlateau scheduler """ def __init__(self, num_classes=10, input_size=28 * 28, hidden_size=512, hidden_layers=1): super().__init__() layers = nn.Sequential(*(nn.Linear(input_size, hidden_size), nn.ReLU(inplace=True))) for layer_idx in range(hidden_layers - 1): layers.add_module( f"fc{layer_idx + 1}", nn.Sequential( *(nn.Linear(hidden_size, hidden_size), nn.ReLU(inplace=True)))) self.features = nn.Sequential(*layers) self.classifier = nn.Linear(hidden_size, num_classes) self._input_size = input_size def forward(self, x): x = x.contiguous() x = x.view(x.size(0), self._input_size) x = self.features(x) x = self.classifier(x) return x def get_features(self, x): x = x.contiguous() x = x.view(x.size(0), self._input_size) x = self.features(x) return x class EvaluationPluginTest(unittest.TestCase): def test_publish_metric(self): ep = EvaluationPlugin() mval = MetricValue(self, 'metric', 1.0, 0) ep.publish_metric_value(mval) # check key exists assert len(ep.get_all_metrics()['metric'][1]) == 1 if __name__ == '__main__': unittest.main()
import itertools import sys import torch from torch import nn import unittest from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from torch.nn import CrossEntropyLoss from torch.optim import SGD from torch.optim.lr_scheduler import MultiStepLR, ReduceLROnPlateau from torch.utils.data import TensorDataset from torch.utils.data.dataloader import DataLoader from avalanche.benchmarks import nc_benchmark, GenericCLScenario, \ benchmark_with_validation_stream from avalanche.benchmarks.utils.data_loader import TaskBalancedDataLoader from avalanche.evaluation.metric_results import MetricValue from avalanche.evaluation.metrics import Mean from avalanche.logging import TextLogger from avalanche.models import BaseModel from avalanche.training.plugins import StrategyPlugin, EvaluationPlugin from avalanche.training.plugins.lr_scheduling import LRSchedulerPlugin from avalanche.training.strategies import Naive class MockPlugin(StrategyPlugin): def __init__(self): super().__init__() self.count = 0 self.activated = [False for _ in range(22)] def before_training_exp(self, strategy, **kwargs): self.activated[0] = True def after_train_dataset_adaptation(self, strategy, **kwargs): self.activated[1] = True def before_training_epoch(self, strategy, **kwargs): self.activated[2] = True def before_training_iteration(self, strategy, **kwargs): self.activated[3] = True def before_forward(self, strategy, **kwargs): self.activated[4] = True def after_forward(self, strategy, **kwargs): self.activated[5] = True def before_backward(self, strategy, **kwargs): self.activated[6] = True def after_backward(self, strategy, **kwargs): self.activated[7] = True def after_training_iteration(self, strategy, **kwargs): self.activated[8] = True def before_update(self, strategy, **kwargs): self.activated[9] = True def after_update(self, strategy, **kwargs): self.activated[10] = True def after_training_epoch(self, strategy, **kwargs): self.activated[11] = True def after_training_exp(self, strategy, **kwargs): self.activated[12] = True def before_eval(self, strategy, **kwargs): self.activated[13] = True def after_eval_dataset_adaptation(self, strategy, **kwargs): self.activated[14] = True def before_eval_exp(self, strategy, **kwargs): self.activated[15] = True def after_eval_exp(self, strategy, **kwargs): self.activated[16] = True def after_eval(self, strategy, **kwargs): self.activated[17] = True def before_eval_iteration(self, strategy, **kwargs): self.activated[18] = True def before_eval_forward(self, strategy, **kwargs): self.activated[19] = True def after_eval_forward(self, strategy, **kwargs): self.activated[20] = True def after_eval_iteration(self, strategy, **kwargs): self.activated[21] = True class PluginTests(unittest.TestCase): def test_callback_reachability(self): # Check that all the callbacks are called during # training and test loops. model = _PlainMLP(input_size=6, hidden_size=10) optimizer = SGD(model.parameters(), lr=1e-3) criterion = CrossEntropyLoss() benchmark = PluginTests.create_benchmark() plug = MockPlugin() strategy = Naive(model, optimizer, criterion, train_mb_size=100, train_epochs=1, eval_mb_size=100, device='cpu', plugins=[plug] ) strategy.evaluator.loggers = [TextLogger(sys.stdout)] strategy.train(benchmark.train_stream[0], num_workers=4) strategy.eval([benchmark.test_stream[0]], num_workers=4) assert all(plug.activated) @staticmethod def create_benchmark(task_labels=False, seed=None): n_samples_per_class = 20 dataset = make_classification( n_samples=10 * n_samples_per_class, n_classes=10, n_features=6, n_informative=6, n_redundant=0, random_state=seed) X = torch.from_numpy(dataset[0]).float() y = torch.from_numpy(dataset[1]).long() train_X, test_X, train_y, test_y = train_test_split( X, y, train_size=0.6, shuffle=True, stratify=y, random_state=seed) train_dataset = TensorDataset(train_X, train_y) test_dataset = TensorDataset(test_X, test_y) return nc_benchmark(train_dataset, test_dataset, 5, task_labels=task_labels, fixed_class_order=list(range(10))) def test_scheduler_plugin(self): PluginTests._test_scheduler_multi_step_lr_plugin( gamma=1 / 2., milestones=[2, 3], base_lr=4., epochs=3, reset_lr=True, reset_scheduler=True, expected=[[4., 2., 1.], [4., 2., 1.]]) PluginTests._test_scheduler_multi_step_lr_plugin( gamma=1 / 2., milestones=[2, 3], base_lr=4., epochs=3, reset_lr=False, reset_scheduler=True, expected=[[4., 2., 1.], [1., .5, .25]]) PluginTests._test_scheduler_multi_step_lr_plugin( gamma=1 / 2., milestones=[2, 3], base_lr=4., epochs=3, reset_lr=True, reset_scheduler=False, expected=[[4., 2., 1.], [4., 4., 4.]]) PluginTests._test_scheduler_multi_step_lr_plugin( gamma=1 / 2., milestones=[2, 3], base_lr=4., epochs=3, reset_lr=False, reset_scheduler=False, expected=[[4., 2., 1.], [1., 1., 1.]]) @staticmethod def _test_scheduler_multi_step_lr_plugin( gamma, milestones, base_lr, epochs, reset_lr, reset_scheduler, expected): benchmark = PluginTests.create_benchmark() model = _PlainMLP(input_size=6, hidden_size=10) optim = SGD(model.parameters(), lr=base_lr) scheduler = MultiStepLR(optim, milestones=milestones, gamma=gamma) PluginTests._test_scheduler_plugin( benchmark, model, optim, scheduler, epochs, reset_lr, reset_scheduler, expected) def assert_model_equals(self, model1, model2): dict1 = model1.state_dict() dict2 = model2.state_dict() # compare keys self.assertSetEqual(set(dict1.keys()), set(dict2.keys())) # compare params for (k, v) in dict1.items(): self.assertTrue(torch.equal(v, dict2[k])) def assert_benchmark_equals( self, bench1: GenericCLScenario, bench2: GenericCLScenario): self.assertSetEqual(set(bench1.streams.keys()), set(bench2.streams.keys())) for stream_name in list(bench1.streams.keys()): for exp1, exp2 in zip(bench1.streams[stream_name], bench2.streams[stream_name]): dataset1 = exp1.dataset dataset2 = exp2.dataset for t_idx in range(3): dataset1_content = dataset1[:][t_idx] dataset2_content = dataset2[:][t_idx] self.assertTrue(torch.equal(dataset1_content, dataset2_content)) def _verify_rop_tests_reproducibility( self, init_strategy, n_epochs, criterion): # This doesn't actually test the support for the specific scheduler # (ReduceLROnPlateau), but it's only used to check if: # - the same model+benchmark pair can be instantiated in a # deterministic way. # - the same results could be obtained in a standard training loop in a # deterministic way. models_rnd = [] benchmarks_rnd = [] for _ in range(2): benchmark, model = init_strategy() models_rnd.append(model) benchmarks_rnd.append(benchmark) self.assert_model_equals(*models_rnd) self.assert_benchmark_equals(*benchmarks_rnd) expected_lrs_rnd = [] for _ in range(2): benchmark, model = init_strategy() expected_lrs = [] model.train() for exp in benchmark.train_stream: optimizer = SGD(model.parameters(), lr=0.001) scheduler = ReduceLROnPlateau(optimizer) expected_lrs.append([]) train_loss = Mean() for epoch in range(n_epochs): train_loss.reset() for x, y, t in TaskBalancedDataLoader( exp.dataset, oversample_small_groups=True, num_workers=0, batch_size=32, shuffle=False, pin_memory=False): optimizer.zero_grad() outputs = model(x) loss = criterion(outputs, y) train_loss.update(loss, weight=len(x)) loss.backward() optimizer.step() scheduler.step(train_loss.result()) for group in optimizer.param_groups: expected_lrs[-1].append(group['lr']) break expected_lrs_rnd.append(expected_lrs) self.assertEqual(expected_lrs_rnd[0], expected_lrs_rnd[1]) def test_scheduler_reduce_on_plateau_plugin(self): # Regression test for issue #858 n_epochs = 20 criterion = CrossEntropyLoss() def _prepare_rng_critical_parts(seed=1234): torch.random.manual_seed(seed) return (PluginTests.create_benchmark(seed=seed), _PlainMLP(input_size=6, hidden_size=10)) self._verify_rop_tests_reproducibility( _prepare_rng_critical_parts, n_epochs, criterion) # Everything is in order, now we can test the plugin support for the # ReduceLROnPlateau scheduler! for reset_lr, reset_scheduler in itertools.product( (True, False), (True, False)): with self.subTest(reset_lr=reset_lr, reset_scheduler=reset_scheduler): # First, obtain the reference (expected) lr timeline by running # a plain PyTorch training loop with ReduceLROnPlateau. benchmark, model = _prepare_rng_critical_parts() model.train() expected_lrs = [] optimizer = SGD(model.parameters(), lr=0.001) scheduler = ReduceLROnPlateau(optimizer) for exp in benchmark.train_stream: if reset_lr: for group in optimizer.param_groups: group['lr'] = 0.001 if reset_scheduler: scheduler = ReduceLROnPlateau(optimizer) expected_lrs.append([]) train_loss = Mean() for epoch in range(n_epochs): train_loss.reset() for x, y, t in TaskBalancedDataLoader( exp.dataset, oversample_small_groups=True, num_workers=0, batch_size=32, shuffle=False, pin_memory=False): optimizer.zero_grad() outputs = model(x) loss = criterion(outputs, y) train_loss.update(loss, weight=len(x)) loss.backward() optimizer.step() scheduler.step(train_loss.result()) for group in optimizer.param_groups: expected_lrs[-1].append(group['lr']) break # Now we have the correct timeline stored in expected_lrs. # Let's test the plugin! benchmark, model = _prepare_rng_critical_parts() optimizer = SGD(model.parameters(), lr=0.001) scheduler = ReduceLROnPlateau(optimizer) PluginTests._test_scheduler_plugin( benchmark, model, optimizer, scheduler, n_epochs, reset_lr, reset_scheduler, expected_lrs, criterion=criterion, metric='train_loss') # Other tests benchmark, model = _prepare_rng_critical_parts() optimizer = SGD(model.parameters(), lr=0.001) scheduler = ReduceLROnPlateau(optimizer) scheduler2 = MultiStepLR(optimizer, [1, 2, 3]) # The metric must be set with self.assertRaises(Exception): LRSchedulerPlugin( scheduler, metric=None) # Doesn't make sense to set the metric when using a non-metric # based scheduler (should warn) with self.assertWarns(Warning): LRSchedulerPlugin( scheduler2, metric='train_loss') # Must raise an error on unsupported metric with self.assertRaises(Exception): LRSchedulerPlugin( scheduler, metric='cuteness') def test_scheduler_reduce_on_plateau_plugin_with_val_stream(self): # Regression test for issue #858 (part 2) n_epochs = 20 criterion = CrossEntropyLoss() def _prepare_rng_critical_parts(seed=1234): torch.random.manual_seed(seed) initial_benchmark = PluginTests.create_benchmark(seed=seed) val_benchmark = benchmark_with_validation_stream( initial_benchmark, 0.3, shuffle=True) return (val_benchmark, _PlainMLP(input_size=6, hidden_size=10)) self._verify_rop_tests_reproducibility( _prepare_rng_critical_parts, n_epochs, criterion) # Everything is in order, now we can test the plugin support for the # ReduceLROnPlateau scheduler! for reset_lr, reset_scheduler in itertools.product( (True, False), (True, False)): with self.subTest(reset_lr=reset_lr, reset_scheduler=reset_scheduler): # First, obtain the reference (expected) lr timeline by running # a plain PyTorch training loop with ReduceLROnPlateau. benchmark, model = _prepare_rng_critical_parts() expected_lrs = [] optimizer = SGD(model.parameters(), lr=0.001) scheduler = ReduceLROnPlateau(optimizer) for exp_idx, exp in enumerate(benchmark.train_stream): expected_lrs.append([]) model.train() if reset_lr: for group in optimizer.param_groups: group['lr'] = 0.001 if reset_scheduler: scheduler = ReduceLROnPlateau(optimizer) for epoch in range(n_epochs): for x, y, t in TaskBalancedDataLoader( exp.dataset, oversample_small_groups=True, num_workers=0, batch_size=32, shuffle=False, pin_memory=False): optimizer.zero_grad() outputs = model(x) loss = criterion(outputs, y) loss.backward() optimizer.step() for group in optimizer.param_groups: expected_lrs[-1].append(group['lr']) break val_loss = Mean() val_exp = benchmark.valid_stream[exp_idx] model.eval() with torch.no_grad(): for x, y, t in DataLoader( val_exp.dataset, num_workers=0, batch_size=100, pin_memory=False): outputs = model(x) loss = criterion(outputs, y) val_loss.update(loss, weight=len(x)) scheduler.step(val_loss.result()) # Now we have the correct timeline stored in expected_lrs # Let's test the plugin! benchmark, model = _prepare_rng_critical_parts() optimizer = SGD(model.parameters(), lr=0.001) scheduler = ReduceLROnPlateau(optimizer) PluginTests._test_scheduler_plugin( benchmark, model, optimizer, scheduler, n_epochs, reset_lr, reset_scheduler, expected_lrs, criterion=criterion, metric='val_loss', eval_on_valid_stream=True) @staticmethod def _test_scheduler_plugin( benchmark, model, optim, scheduler, epochs, reset_lr, reset_scheduler, expected, criterion=None, metric=None, eval_on_valid_stream=False): lr_scheduler_plugin = LRSchedulerPlugin( scheduler, reset_lr=reset_lr, reset_scheduler=reset_scheduler, metric=metric) verifier_plugin = SchedulerPluginTestPlugin(expected) if criterion is None: criterion = CrossEntropyLoss() if eval_on_valid_stream: cl_strategy = Naive( model, optim, criterion, train_mb_size=32, train_epochs=epochs, eval_mb_size=100, plugins=[lr_scheduler_plugin, verifier_plugin], eval_every=1, evaluator=None) cl_strategy.train(benchmark.train_stream[0], shuffle=False, eval_streams=[benchmark.valid_stream[0]]) cl_strategy.train(benchmark.train_stream[1], shuffle=False, eval_streams=[benchmark.valid_stream[1]]) else: cl_strategy = Naive( model, optim, criterion, train_mb_size=32, train_epochs=epochs, eval_mb_size=100, plugins=[lr_scheduler_plugin, verifier_plugin], evaluator=None) cl_strategy.train(benchmark.train_stream[0], shuffle=False) cl_strategy.train(benchmark.train_stream[1], shuffle=False) class SchedulerPluginTestPlugin(StrategyPlugin): def __init__(self, expected_lrs): super().__init__() self.expected_lrs = expected_lrs def after_training_epoch(self, strategy, **kwargs): exp_id = strategy.clock.train_exp_counter curr_epoch = strategy.clock.train_exp_epochs expected_lr = self.expected_lrs[exp_id][curr_epoch] for group in strategy.optimizer.param_groups: assert group['lr'] == expected_lr,\ f"LR mismatch: {group['lr']} vs {expected_lr}" class _PlainMLP(nn.Module, BaseModel): """ An internal MLP implementation without Dropout. Needed to reproduce tests for the ReduceLROnPlateau scheduler """ def __init__(self, num_classes=10, input_size=28 * 28, hidden_size=512, hidden_layers=1): super().__init__() layers = nn.Sequential(*(nn.Linear(input_size, hidden_size), nn.ReLU(inplace=True))) for layer_idx in range(hidden_layers - 1): layers.add_module( f"fc{layer_idx + 1}", nn.Sequential( *(nn.Linear(hidden_size, hidden_size), nn.ReLU(inplace=True)))) self.features = nn.Sequential(*layers) self.classifier = nn.Linear(hidden_size, num_classes) self._input_size = input_size def forward(self, x): x = x.contiguous() x = x.view(x.size(0), self._input_size) x = self.features(x) x = self.classifier(x) return x def get_features(self, x): x = x.contiguous() x = x.view(x.size(0), self._input_size) x = self.features(x) return x class EvaluationPluginTest(unittest.TestCase): def test_publish_metric(self): ep = EvaluationPlugin() mval = MetricValue(self, 'metric', 1.0, 0) ep.publish_metric_value(mval) # check key exists assert len(ep.get_all_metrics()['metric'][1]) == 1 if __name__ == '__main__': unittest.main()
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/05_data.transforms.ipynb (unless otherwise specified). __all__ = ['get_files', 'FileGetter', 'image_extensions', 'get_image_files', 'ImageGetter', 'get_text_files', 'RandomSplitter', 'IndexSplitter', 'GrandparentSplitter', 'FuncSplitter', 'MaskSplitter', 'FileSplitter', 'ColSplitter', 'parent_label', 'RegexLabeller', 'ColReader', 'CategoryMap', 'Categorize', 'Category', 'MultiCategorize', 'MultiCategory', 'OneHotEncode', 'EncodedMultiCategorize', 'get_c', 'ToTensor', 'IntToFloatTensor', 'broadcast_vec', 'Normalize'] # Cell from ..torch_basics import * from .core import * from .load import * from .external import * # Cell def _get_files(p, fs, extensions=None): p = Path(p) res = [p/f for f in fs if not f.startswith('.') and ((not extensions) or f'.{f.split('.')[-1].lower()}' in extensions)] return res # Cell def get_files(path, extensions=None, recurse=True, folders=None): "Get all the files in `path` with optional `extensions`, optionally with `recurse`, only in `folders`, if specified." path = Path(path) folders=L(folders) extensions = setify(extensions) extensions = {e.lower() for e in extensions} if recurse: res = [] for i,(p,d,f) in enumerate(os.walk(path)): # returns (dirpath, dirnames, filenames) if len(folders) !=0 and i==0: d[:] = [o for o in d if o in folders] else: d[:] = [o for o in d if not o.startswith('.')] res += _get_files(p, f, extensions) else: f = [o.name for o in os.scandir(path) if o.is_file()] res = _get_files(path, f, extensions) return L(res) # Cell def FileGetter(suf='', extensions=None, recurse=True, folders=None): "Create `get_files` partial function that searches path suffix `suf`, only in `folders`, if specified, and passes along args" def _inner(o, extensions=extensions, recurse=recurse, folders=folders): return get_files(o/suf, extensions, recurse, folders) return _inner # Cell image_extensions = set(k for k,v in mimetypes.types_map.items() if v.startswith('image/')) # Cell def get_image_files(path, recurse=True, folders=None): "Get image files in `path` recursively, only in `folders`, if specified." return get_files(path, extensions=image_extensions, recurse=recurse, folders=folders) # Cell def ImageGetter(suf='', recurse=True, folders=None): "Create `get_image_files` partial function that searches path suffix `suf` and passes along `kwargs`, only in `folders`, if specified." def _inner(o, recurse=recurse, folders=folders): return get_image_files(o/suf, recurse, folders) return _inner # Cell def get_text_files(path, recurse=True, folders=None): "Get text files in `path` recursively, only in `folders`, if specified." return get_files(path, extensions=['.txt'], recurse=recurse, folders=folders) # Cell def RandomSplitter(valid_pct=0.2, seed=None, **kwargs): "Create function that splits `items` between train/val with `valid_pct` randomly." def _inner(o, **kwargs): if seed is not None: torch.manual_seed(seed) rand_idx = L(int(i) for i in torch.randperm(len(o))) cut = int(valid_pct * len(o)) return rand_idx[cut:],rand_idx[:cut] return _inner # Cell def IndexSplitter(valid_idx): "Split `items` so that `val_idx` are in the validation set and the others in the training set" def _inner(o, **kwargs): train_idx = np.setdiff1d(np.array(range_of(o)), np.array(valid_idx)) return L(train_idx, use_list=True), L(valid_idx, use_list=True) return _inner # Cell def _grandparent_idxs(items, name): return mask2idxs(Path(o).parent.parent.name == name for o in items) # Cell def GrandparentSplitter(train_name='train', valid_name='valid'): "Split `items` from the grand parent folder names (`train_name` and `valid_name`)." def _inner(o, **kwargs): return _grandparent_idxs(o, train_name),_grandparent_idxs(o, valid_name) return _inner # Cell def FuncSplitter(func): "Split `items` by result of `func` (`True` for validation, `False` for training set)." def _inner(o, **kwargs): val_idx = mask2idxs(func(o_) for o_ in o) return IndexSplitter(val_idx)(o) return _inner # Cell def MaskSplitter(mask): "Split `items` depending on the value of `mask`." def _inner(o, **kwargs): return IndexSplitter(mask2idxs(mask))(o) return _inner # Cell def FileSplitter(fname): "Split `items`, taking validation indexes from `fname`." valid = Path(fname).read().split('\n') def _func(x): return x.name in valid def _inner(o, **kwargs): return FuncSplitter(_func)(o) return _inner # Cell def ColSplitter(col='is_valid'): "Split `items` (supposed to be a dataframe) by value in `col`" def _inner(o, **kwargs): assert isinstance(o, pd.DataFrame), "ColSplitter only works when your items are a pandas DataFrame" valid_idx = o[col].values return IndexSplitter(mask2idxs(valid_idx))(o) return _inner # Cell def parent_label(o, **kwargs): "Label `item` with the parent folder name." return Path(o).parent.name # Cell class RegexLabeller(): "Label `item` with regex `pat`." def __init__(self, pat, match=False): self.pat = re.compile(pat) self.matcher = self.pat.match if match else self.pat.search def __call__(self, o, **kwargs): res = self.matcher(str(o)) assert res,f'Failed to find "{self.pat}" in "{o}"' return res.group(1) # Cell class ColReader(): "Read `cols` in `row` with potential `pref` and `suff`" def __init__(self, cols, pref='', suff='', label_delim=None): store_attr(self, 'suff,label_delim') self.pref = str(pref) + os.path.sep if isinstance(pref, Path) else pref self.cols = L(cols) def _do_one(self, r, c): o = r[c] if isinstance(c, int) else getattr(r, c) if len(self.pref)==0 and len(self.suff)==0 and self.label_delim is None: return o if self.label_delim is None: return f'{self.pref}{o}{self.suff}' else: return o.split(self.label_delim) if len(o)>0 else [] def __call__(self, o, **kwargs): return detuplify(tuple(self._do_one(o, c) for c in self.cols)) # Cell class CategoryMap(CollBase): "Collection of categories with the reverse mapping in `o2i`" def __init__(self, col, sort=True, add_na=False): if is_categorical_dtype(col): items = L(col.cat.categories, use_list=True) else: if not hasattr(col,'unique'): col = L(col, use_list=True) # `o==o` is the generalized definition of non-NaN used by Pandas items = L(o for o in col.unique() if o==o) if sort: items = items.sorted() self.items = '#na#' + items if add_na else items self.o2i = defaultdict(int, self.items.val2idx()) if add_na else dict(self.items.val2idx()) def __eq__(self,b): return all_equal(b,self) # Cell class Categorize(Transform): "Reversible transform of category string to `vocab` id" loss_func,order=CrossEntropyLossFlat(),1 def __init__(self, vocab=None, add_na=False): self.add_na = add_na self.vocab = None if vocab is None else CategoryMap(vocab, add_na=add_na) def setups(self, dsrc): if self.vocab is None and dsrc is not None: self.vocab = CategoryMap(dsrc, add_na=self.add_na) self.c = len(self.vocab) def encodes(self, o): return TensorCategory(self.vocab.o2i[o]) def decodes(self, o): return Category (self.vocab [o]) # Cell class Category(str, ShowTitle): _show_args = {'label': 'category'} # Cell class MultiCategorize(Categorize): "Reversible transform of multi-category strings to `vocab` id" loss_func,order=BCEWithLogitsLossFlat(),1 def __init__(self, vocab=None, add_na=False): self.add_na = add_na self.vocab = None if vocab is None else CategoryMap(vocab, add_na=add_na) def setups(self, dsrc): if not dsrc: return if self.vocab is None: vals = set() for b in dsrc: vals = vals.union(set(b)) self.vocab = CategoryMap(list(vals), add_na=self.add_na) def encodes(self, o): return TensorMultiCategory([self.vocab.o2i[o_] for o_ in o]) def decodes(self, o): return MultiCategory ([self.vocab [o_] for o_ in o]) # Cell class MultiCategory(L): def show(self, ctx=None, sep=';', color='black', **kwargs): return show_title(sep.join(self.map(str)), ctx=ctx, color=color, **kwargs) # Cell class OneHotEncode(Transform): "One-hot encodes targets" order=2 def __init__(self, c=None): self.c = c def setups(self, dsrc): if self.c is None: self.c = len(L(getattr(dsrc, 'vocab', None))) if not self.c: warn("Couldn't infer the number of classes, please pass a value for `c` at init") def encodes(self, o): return TensorMultiCategory(one_hot(o, self.c).float()) def decodes(self, o): return one_hot_decode(o, None) # Cell class EncodedMultiCategorize(Categorize): "Transform of one-hot encoded multi-category that decodes with `vocab`" loss_func,order=BCEWithLogitsLossFlat(),1 def __init__(self, vocab): self.vocab,self.c = vocab,len(vocab) def encodes(self, o): return TensorCategory(tensor(o).float()) def decodes(self, o): return MultiCategory (one_hot_decode(o, self.vocab)) # Cell def get_c(dbunch): if getattr(dbunch, 'c', False): return dbunch.c vocab = getattr(dbunch, 'vocab', []) if len(vocab) > 0 and is_listy(vocab[-1]): vocab = vocab[-1] return len(vocab) # Cell class ToTensor(Transform): "Convert item to appropriate tensor class" order = 5 # Cell class IntToFloatTensor(Transform): "Transform image to float tensor, optionally dividing by 255 (e.g. for images)." order = 10 #Need to run after PIL transforms on the GPU def __init__(self, div=255., div_mask=1, split_idx=None, as_item=True): super().__init__(split_idx=split_idx,as_item=as_item) self.div,self.div_mask = div,div_mask def encodes(self, o:TensorImage): return o.float().div_(self.div) def encodes(self, o:TensorMask ): return o.div_(self.div_mask).long() def decodes(self, o:TensorImage): return o.clamp(0., 1.) if self.div else o # Cell def broadcast_vec(dim, ndim, *t, cuda=True): "Make a vector broadcastable over `dim` (out of `ndim` total) by prepending and appending unit axes" v = [1]*ndim v[dim] = -1 f = to_device if cuda else noop return [f(tensor(o).view(*v)) for o in t] # Cell @docs class Normalize(Transform): "Normalize/denorm batch of `TensorImage`" order=99 def __init__(self, mean=None, std=None, axes=(0,2,3)): self.mean,self.std,self.axes = mean,std,axes @classmethod def from_stats(cls, mean, std, dim=1, ndim=4, cuda=True): return cls(*broadcast_vec(dim, ndim, mean, std, cuda=cuda)) def setups(self, dl:DataLoader): if self.mean is None or self.std is None: x,*_ = dl.one_batch() self.mean,self.std = x.mean(self.axes, keepdim=True),x.std(self.axes, keepdim=True)+1e-7 def encodes(self, x:TensorImage): return (x-self.mean) / self.std def decodes(self, x:TensorImage): f = to_cpu if x.device.type=='cpu' else noop return (x*f(self.std) + f(self.mean)) _docs=dict(encodes="Normalize batch", decodes="Denormalize batch")
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/05_data.transforms.ipynb (unless otherwise specified). __all__ = ['get_files', 'FileGetter', 'image_extensions', 'get_image_files', 'ImageGetter', 'get_text_files', 'RandomSplitter', 'IndexSplitter', 'GrandparentSplitter', 'FuncSplitter', 'MaskSplitter', 'FileSplitter', 'ColSplitter', 'parent_label', 'RegexLabeller', 'ColReader', 'CategoryMap', 'Categorize', 'Category', 'MultiCategorize', 'MultiCategory', 'OneHotEncode', 'EncodedMultiCategorize', 'get_c', 'ToTensor', 'IntToFloatTensor', 'broadcast_vec', 'Normalize'] # Cell from ..torch_basics import * from .core import * from .load import * from .external import * # Cell def _get_files(p, fs, extensions=None): p = Path(p) res = [p/f for f in fs if not f.startswith('.') and ((not extensions) or f'.{f.split(".")[-1].lower()}' in extensions)] return res # Cell def get_files(path, extensions=None, recurse=True, folders=None): "Get all the files in `path` with optional `extensions`, optionally with `recurse`, only in `folders`, if specified." path = Path(path) folders=L(folders) extensions = setify(extensions) extensions = {e.lower() for e in extensions} if recurse: res = [] for i,(p,d,f) in enumerate(os.walk(path)): # returns (dirpath, dirnames, filenames) if len(folders) !=0 and i==0: d[:] = [o for o in d if o in folders] else: d[:] = [o for o in d if not o.startswith('.')] res += _get_files(p, f, extensions) else: f = [o.name for o in os.scandir(path) if o.is_file()] res = _get_files(path, f, extensions) return L(res) # Cell def FileGetter(suf='', extensions=None, recurse=True, folders=None): "Create `get_files` partial function that searches path suffix `suf`, only in `folders`, if specified, and passes along args" def _inner(o, extensions=extensions, recurse=recurse, folders=folders): return get_files(o/suf, extensions, recurse, folders) return _inner # Cell image_extensions = set(k for k,v in mimetypes.types_map.items() if v.startswith('image/')) # Cell def get_image_files(path, recurse=True, folders=None): "Get image files in `path` recursively, only in `folders`, if specified." return get_files(path, extensions=image_extensions, recurse=recurse, folders=folders) # Cell def ImageGetter(suf='', recurse=True, folders=None): "Create `get_image_files` partial function that searches path suffix `suf` and passes along `kwargs`, only in `folders`, if specified." def _inner(o, recurse=recurse, folders=folders): return get_image_files(o/suf, recurse, folders) return _inner # Cell def get_text_files(path, recurse=True, folders=None): "Get text files in `path` recursively, only in `folders`, if specified." return get_files(path, extensions=['.txt'], recurse=recurse, folders=folders) # Cell def RandomSplitter(valid_pct=0.2, seed=None, **kwargs): "Create function that splits `items` between train/val with `valid_pct` randomly." def _inner(o, **kwargs): if seed is not None: torch.manual_seed(seed) rand_idx = L(int(i) for i in torch.randperm(len(o))) cut = int(valid_pct * len(o)) return rand_idx[cut:],rand_idx[:cut] return _inner # Cell def IndexSplitter(valid_idx): "Split `items` so that `val_idx` are in the validation set and the others in the training set" def _inner(o, **kwargs): train_idx = np.setdiff1d(np.array(range_of(o)), np.array(valid_idx)) return L(train_idx, use_list=True), L(valid_idx, use_list=True) return _inner # Cell def _grandparent_idxs(items, name): return mask2idxs(Path(o).parent.parent.name == name for o in items) # Cell def GrandparentSplitter(train_name='train', valid_name='valid'): "Split `items` from the grand parent folder names (`train_name` and `valid_name`)." def _inner(o, **kwargs): return _grandparent_idxs(o, train_name),_grandparent_idxs(o, valid_name) return _inner # Cell def FuncSplitter(func): "Split `items` by result of `func` (`True` for validation, `False` for training set)." def _inner(o, **kwargs): val_idx = mask2idxs(func(o_) for o_ in o) return IndexSplitter(val_idx)(o) return _inner # Cell def MaskSplitter(mask): "Split `items` depending on the value of `mask`." def _inner(o, **kwargs): return IndexSplitter(mask2idxs(mask))(o) return _inner # Cell def FileSplitter(fname): "Split `items`, taking validation indexes from `fname`." valid = Path(fname).read().split('\n') def _func(x): return x.name in valid def _inner(o, **kwargs): return FuncSplitter(_func)(o) return _inner # Cell def ColSplitter(col='is_valid'): "Split `items` (supposed to be a dataframe) by value in `col`" def _inner(o, **kwargs): assert isinstance(o, pd.DataFrame), "ColSplitter only works when your items are a pandas DataFrame" valid_idx = o[col].values return IndexSplitter(mask2idxs(valid_idx))(o) return _inner # Cell def parent_label(o, **kwargs): "Label `item` with the parent folder name." return Path(o).parent.name # Cell class RegexLabeller(): "Label `item` with regex `pat`." def __init__(self, pat, match=False): self.pat = re.compile(pat) self.matcher = self.pat.match if match else self.pat.search def __call__(self, o, **kwargs): res = self.matcher(str(o)) assert res,f'Failed to find "{self.pat}" in "{o}"' return res.group(1) # Cell class ColReader(): "Read `cols` in `row` with potential `pref` and `suff`" def __init__(self, cols, pref='', suff='', label_delim=None): store_attr(self, 'suff,label_delim') self.pref = str(pref) + os.path.sep if isinstance(pref, Path) else pref self.cols = L(cols) def _do_one(self, r, c): o = r[c] if isinstance(c, int) else getattr(r, c) if len(self.pref)==0 and len(self.suff)==0 and self.label_delim is None: return o if self.label_delim is None: return f'{self.pref}{o}{self.suff}' else: return o.split(self.label_delim) if len(o)>0 else [] def __call__(self, o, **kwargs): return detuplify(tuple(self._do_one(o, c) for c in self.cols)) # Cell class CategoryMap(CollBase): "Collection of categories with the reverse mapping in `o2i`" def __init__(self, col, sort=True, add_na=False): if is_categorical_dtype(col): items = L(col.cat.categories, use_list=True) else: if not hasattr(col,'unique'): col = L(col, use_list=True) # `o==o` is the generalized definition of non-NaN used by Pandas items = L(o for o in col.unique() if o==o) if sort: items = items.sorted() self.items = '#na#' + items if add_na else items self.o2i = defaultdict(int, self.items.val2idx()) if add_na else dict(self.items.val2idx()) def __eq__(self,b): return all_equal(b,self) # Cell class Categorize(Transform): "Reversible transform of category string to `vocab` id" loss_func,order=CrossEntropyLossFlat(),1 def __init__(self, vocab=None, add_na=False): self.add_na = add_na self.vocab = None if vocab is None else CategoryMap(vocab, add_na=add_na) def setups(self, dsrc): if self.vocab is None and dsrc is not None: self.vocab = CategoryMap(dsrc, add_na=self.add_na) self.c = len(self.vocab) def encodes(self, o): return TensorCategory(self.vocab.o2i[o]) def decodes(self, o): return Category (self.vocab [o]) # Cell class Category(str, ShowTitle): _show_args = {'label': 'category'} # Cell class MultiCategorize(Categorize): "Reversible transform of multi-category strings to `vocab` id" loss_func,order=BCEWithLogitsLossFlat(),1 def __init__(self, vocab=None, add_na=False): self.add_na = add_na self.vocab = None if vocab is None else CategoryMap(vocab, add_na=add_na) def setups(self, dsrc): if not dsrc: return if self.vocab is None: vals = set() for b in dsrc: vals = vals.union(set(b)) self.vocab = CategoryMap(list(vals), add_na=self.add_na) def encodes(self, o): return TensorMultiCategory([self.vocab.o2i[o_] for o_ in o]) def decodes(self, o): return MultiCategory ([self.vocab [o_] for o_ in o]) # Cell class MultiCategory(L): def show(self, ctx=None, sep=';', color='black', **kwargs): return show_title(sep.join(self.map(str)), ctx=ctx, color=color, **kwargs) # Cell class OneHotEncode(Transform): "One-hot encodes targets" order=2 def __init__(self, c=None): self.c = c def setups(self, dsrc): if self.c is None: self.c = len(L(getattr(dsrc, 'vocab', None))) if not self.c: warn("Couldn't infer the number of classes, please pass a value for `c` at init") def encodes(self, o): return TensorMultiCategory(one_hot(o, self.c).float()) def decodes(self, o): return one_hot_decode(o, None) # Cell class EncodedMultiCategorize(Categorize): "Transform of one-hot encoded multi-category that decodes with `vocab`" loss_func,order=BCEWithLogitsLossFlat(),1 def __init__(self, vocab): self.vocab,self.c = vocab,len(vocab) def encodes(self, o): return TensorCategory(tensor(o).float()) def decodes(self, o): return MultiCategory (one_hot_decode(o, self.vocab)) # Cell def get_c(dbunch): if getattr(dbunch, 'c', False): return dbunch.c vocab = getattr(dbunch, 'vocab', []) if len(vocab) > 0 and is_listy(vocab[-1]): vocab = vocab[-1] return len(vocab) # Cell class ToTensor(Transform): "Convert item to appropriate tensor class" order = 5 # Cell class IntToFloatTensor(Transform): "Transform image to float tensor, optionally dividing by 255 (e.g. for images)." order = 10 #Need to run after PIL transforms on the GPU def __init__(self, div=255., div_mask=1, split_idx=None, as_item=True): super().__init__(split_idx=split_idx,as_item=as_item) self.div,self.div_mask = div,div_mask def encodes(self, o:TensorImage): return o.float().div_(self.div) def encodes(self, o:TensorMask ): return o.div_(self.div_mask).long() def decodes(self, o:TensorImage): return o.clamp(0., 1.) if self.div else o # Cell def broadcast_vec(dim, ndim, *t, cuda=True): "Make a vector broadcastable over `dim` (out of `ndim` total) by prepending and appending unit axes" v = [1]*ndim v[dim] = -1 f = to_device if cuda else noop return [f(tensor(o).view(*v)) for o in t] # Cell @docs class Normalize(Transform): "Normalize/denorm batch of `TensorImage`" order=99 def __init__(self, mean=None, std=None, axes=(0,2,3)): self.mean,self.std,self.axes = mean,std,axes @classmethod def from_stats(cls, mean, std, dim=1, ndim=4, cuda=True): return cls(*broadcast_vec(dim, ndim, mean, std, cuda=cuda)) def setups(self, dl:DataLoader): if self.mean is None or self.std is None: x,*_ = dl.one_batch() self.mean,self.std = x.mean(self.axes, keepdim=True),x.std(self.axes, keepdim=True)+1e-7 def encodes(self, x:TensorImage): return (x-self.mean) / self.std def decodes(self, x:TensorImage): f = to_cpu if x.device.type=='cpu' else noop return (x*f(self.std) + f(self.mean)) _docs=dict(encodes="Normalize batch", decodes="Denormalize batch")
import math import os from enum import IntEnum from typing import Dict, Union, Callable, List, Optional from cereal import log, car import cereal.messaging as messaging from common.conversions import Conversions as CV from common.realtime import DT_CTRL from selfdrive.locationd.calibrationd import MIN_SPEED_FILTER from system.version import get_short_branch AlertSize = log.ControlsState.AlertSize AlertStatus = log.ControlsState.AlertStatus VisualAlert = car.CarControl.HUDControl.VisualAlert AudibleAlert = car.CarControl.HUDControl.AudibleAlert EventName = car.CarEvent.EventName # Alert priorities class Priority(IntEnum): LOWEST = 0 LOWER = 1 LOW = 2 MID = 3 HIGH = 4 HIGHEST = 5 # Event types class ET: ENABLE = 'enable' PRE_ENABLE = 'preEnable' OVERRIDE = 'override' NO_ENTRY = 'noEntry' WARNING = 'warning' USER_DISABLE = 'userDisable' SOFT_DISABLE = 'softDisable' IMMEDIATE_DISABLE = 'immediateDisable' PERMANENT = 'permanent' # get event name from enum EVENT_NAME = {v: k for k, v in EventName.schema.enumerants.items()} class Events: def __init__(self): self.events: List[int] = [] self.static_events: List[int] = [] self.events_prev = dict.fromkeys(EVENTS.keys(), 0) @property def names(self) -> List[int]: return self.events def __len__(self) -> int: return len(self.events) def add(self, event_name: int, static: bool=False) -> None: if static: self.static_events.append(event_name) self.events.append(event_name) def clear(self) -> None: self.events_prev = {k: (v + 1 if k in self.events else 0) for k, v in self.events_prev.items()} self.events = self.static_events.copy() def any(self, event_type: str) -> bool: return any(event_type in EVENTS.get(e, {}) for e in self.events) def create_alerts(self, event_types: List[str], callback_args=None): if callback_args is None: callback_args = [] ret = [] for e in self.events: types = EVENTS[e].keys() for et in event_types: if et in types: alert = EVENTS[e][et] if not isinstance(alert, Alert): alert = alert(*callback_args) if DT_CTRL * (self.events_prev[e] + 1) >= alert.creation_delay: alert.alert_type = f"{EVENT_NAME[e]}/{et}" alert.event_type = et ret.append(alert) return ret def add_from_msg(self, events): for e in events: self.events.append(e.name.raw) def to_msg(self): ret = [] for event_name in self.events: event = car.CarEvent.new_message() event.name = event_name for event_type in EVENTS.get(event_name, {}): setattr(event, event_type, True) ret.append(event) return ret class Alert: def __init__(self, alert_text_1: str, alert_text_2: str, alert_status: log.ControlsState.AlertStatus, alert_size: log.ControlsState.AlertSize, priority: Priority, visual_alert: car.CarControl.HUDControl.VisualAlert, audible_alert: car.CarControl.HUDControl.AudibleAlert, duration: float, alert_rate: float = 0., creation_delay: float = 0.): self.alert_text_1 = alert_text_1 self.alert_text_2 = alert_text_2 self.alert_status = alert_status self.alert_size = alert_size self.priority = priority self.visual_alert = visual_alert self.audible_alert = audible_alert self.duration = int(duration / DT_CTRL) self.alert_rate = alert_rate self.creation_delay = creation_delay self.alert_type = "" self.event_type: Optional[str] = None def __str__(self) -> str: return f"{self.alert_text_1}/{self.alert_text_2} {self.priority} {self.visual_alert} {self.audible_alert}" def __gt__(self, alert2) -> bool: if not isinstance(alert2, Alert): return False return self.priority > alert2.priority class NoEntryAlert(Alert): def __init__(self, alert_text_2: str, alert_text_1: str = "openpilot Unavailable", visual_alert: car.CarControl.HUDControl.VisualAlert=VisualAlert.none): super().__init__(alert_text_1, alert_text_2, AlertStatus.normal, AlertSize.mid, Priority.LOW, visual_alert, AudibleAlert.refuse, 3.) class SoftDisableAlert(Alert): def __init__(self, alert_text_2: str): super().__init__("TAKE CONTROL IMMEDIATELY", alert_text_2, AlertStatus.userPrompt, AlertSize.full, Priority.MID, VisualAlert.steerRequired, AudibleAlert.warningSoft, 2.), # less harsh version of SoftDisable, where the condition is user-triggered class UserSoftDisableAlert(SoftDisableAlert): def __init__(self, alert_text_2: str): super().__init__(alert_text_2), self.alert_text_1 = "openpilot will disengage" class ImmediateDisableAlert(Alert): def __init__(self, alert_text_2: str): super().__init__("TAKE CONTROL IMMEDIATELY", alert_text_2, AlertStatus.critical, AlertSize.full, Priority.HIGHEST, VisualAlert.steerRequired, AudibleAlert.warningImmediate, 4.), class EngagementAlert(Alert): def __init__(self, audible_alert: car.CarControl.HUDControl.AudibleAlert): super().__init__("", "", AlertStatus.normal, AlertSize.none, Priority.MID, VisualAlert.none, audible_alert, .2), class NormalPermanentAlert(Alert): def __init__(self, alert_text_1: str, alert_text_2: str = "", duration: float = 0.2, priority: Priority = Priority.LOWER, creation_delay: float = 0.): super().__init__(alert_text_1, alert_text_2, AlertStatus.normal, AlertSize.mid if len(alert_text_2) else AlertSize.small, priority, VisualAlert.none, AudibleAlert.none, duration, creation_delay=creation_delay), class StartupAlert(Alert): def __init__(self, alert_text_1: str, alert_text_2: str = "Always keep hands on wheel and eyes on road", alert_status=AlertStatus.normal): super().__init__(alert_text_1, alert_text_2, alert_status, AlertSize.mid, Priority.LOWER, VisualAlert.none, AudibleAlert.none, 10.), # ********** helper functions ********** def get_display_speed(speed_ms: float, metric: bool) -> str: speed = int(round(speed_ms * (CV.MS_TO_KPH if metric else CV.MS_TO_MPH))) unit = 'km/h' if metric else 'mph' return f"{speed} {unit}" # ********** alert callback functions ********** AlertCallbackType = Callable[[car.CarParams, car.CarState, messaging.SubMaster, bool, int], Alert] def soft_disable_alert(alert_text_2: str) -> AlertCallbackType: def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: if soft_disable_time < int(0.5 / DT_CTRL): return ImmediateDisableAlert(alert_text_2) return SoftDisableAlert(alert_text_2) return func def user_soft_disable_alert(alert_text_2: str) -> AlertCallbackType: def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: if soft_disable_time < int(0.5 / DT_CTRL): return ImmediateDisableAlert(alert_text_2) return UserSoftDisableAlert(alert_text_2) return func def startup_master_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: branch = get_short_branch("") if "REPLAY" in os.environ: branch = "replay" return StartupAlert("MechTechTeam 08.15 061822", branch, alert_status=AlertStatus.userPrompt) def below_engage_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return NoEntryAlert(f"Speed Below {get_display_speed(CP.minEnableSpeed, metric)}") def below_steer_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return Alert( f"Steer Unavailable Below {get_display_speed(CP.minSteerSpeed, metric)}", "", AlertStatus.userPrompt, AlertSize.small, Priority.MID, VisualAlert.steerRequired, AudibleAlert.prompt, 0.4) def calibration_incomplete_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return Alert( "Calibration in Progress: %d%%" % sm['liveCalibration'].calPerc, f"Drive Above {get_display_speed(MIN_SPEED_FILTER, metric)}", AlertStatus.normal, AlertSize.mid, Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2) def no_gps_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: gps_integrated = sm['peripheralState'].pandaType in (log.PandaState.PandaType.uno, log.PandaState.PandaType.dos) return Alert( "Poor GPS reception", "Hardware malfunctioning if sky is visible" if gps_integrated else "Check GPS antenna placement", AlertStatus.normal, AlertSize.mid, Priority.LOWER, VisualAlert.none, AudibleAlert.none, .2, creation_delay=300.) # *** debug alerts *** def out_of_space_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: full_perc = round(100. - sm['deviceState'].freeSpacePercent) return NormalPermanentAlert("Out of Storage", f"{full_perc}% full") def posenet_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: mdl = sm['modelV2'].velocity.x[0] if len(sm['modelV2'].velocity.x) else math.nan err = CS.vEgo - mdl msg = f"Speed Error: {err:.1f} m/s" return NoEntryAlert(msg, alert_text_1="Posenet Speed Invalid") def process_not_running_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: not_running = [p.name for p in sm['managerState'].processes if not p.running and p.shouldBeRunning] msg = ', '.join(not_running) return NoEntryAlert(msg, alert_text_1="Process Not Running") def comm_issue_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: bs = [s for s in sm.data.keys() if not sm.all_checks([s, ])] msg = ', '.join(bs[:4]) # can't fit too many on one line return NoEntryAlert(msg, alert_text_1="Communication Issue Between Processes") def camera_malfunction_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: all_cams = ('roadCameraState', 'driverCameraState', 'wideRoadCameraState') bad_cams = [s.replace('State', '') for s in all_cams if s in sm.data.keys() and not sm.all_checks([s, ])] return NormalPermanentAlert("Camera Malfunction", ', '.join(bad_cams)) def calibration_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: rpy = sm['liveCalibration'].rpyCalib yaw = math.degrees(rpy[2] if len(rpy) == 3 else math.nan) pitch = math.degrees(rpy[1] if len(rpy) == 3 else math.nan) angles = f"Pitch: {pitch:.1f}°, Yaw: {yaw:.1f}°" return NormalPermanentAlert("Calibration Invalid", angles) def overheat_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: cpu = max(sm['deviceState'].cpuTempC, default=0.) gpu = max(sm['deviceState'].gpuTempC, default=0.) temp = max((cpu, gpu, sm['deviceState'].memoryTempC)) return NormalPermanentAlert("System Overheated", f"{temp:.0f} °C") def low_memory_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return NormalPermanentAlert("Low Memory", f"{sm["deviceState"].memoryUsagePercent}% used") def high_cpu_usage_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: x = max(sm['deviceState'].cpuUsagePercent, default=0.) return NormalPermanentAlert("High CPU Usage", f"{x}% used") def modeld_lagging_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return NormalPermanentAlert("Driving Model Lagging", f"{sm["modelV2"].frameDropPerc:.1f}% frames dropped") def wrong_car_mode_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: text = "Cruise Mode Disabled" if CP.carName == "honda": text = "Main Switch Off" return NoEntryAlert(text) def joystick_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: axes = sm['testJoystick'].axes gb, steer = list(axes)[:2] if len(axes) else (0., 0.) vals = f"Gas: {round(gb * 100.)}%, Steer: {round(steer * 100.)}%" return NormalPermanentAlert("Joystick Mode", vals) EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { # ********** events with no alerts ********** EventName.stockFcw: {}, # ********** events only containing alerts displayed in all states ********** EventName.joystickDebug: { ET.WARNING: joystick_alert, ET.PERMANENT: NormalPermanentAlert("Joystick Mode"), }, EventName.controlsInitializing: { ET.NO_ENTRY: NoEntryAlert("System Initializing"), }, EventName.startup: { ET.PERMANENT: StartupAlert("Be ready to take over at any time") }, EventName.startupMaster: { ET.PERMANENT: startup_master_alert, }, # Car is recognized, but marked as dashcam only EventName.startupNoControl: { ET.PERMANENT: StartupAlert("Dashcam mode"), }, # Car is not recognized EventName.startupNoCar: { ET.PERMANENT: StartupAlert("Dashcam mode for unsupported car"), }, EventName.startupNoFw: { ET.PERMANENT: StartupAlert("Car Unrecognized", "Check comma power connections", alert_status=AlertStatus.userPrompt), }, EventName.dashcamMode: { ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", priority=Priority.LOWEST), }, EventName.invalidLkasSetting: { ET.PERMANENT: NormalPermanentAlert("Stock LKAS is on", "Turn off stock LKAS to engage"), }, EventName.cruiseMismatch: { #ET.PERMANENT: ImmediateDisableAlert("openpilot failed to cancel cruise"), }, # openpilot doesn't recognize the car. This switches openpilot into a # read-only mode. This can be solved by adding your fingerprint. # See https://github.com/commaai/openpilot/wiki/Fingerprinting for more information EventName.carUnrecognized: { ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", "Car Unrecognized", priority=Priority.LOWEST), }, EventName.stockAeb: { ET.PERMANENT: Alert( "BRAKE!", "Stock AEB: Risk of Collision", AlertStatus.critical, AlertSize.full, Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.none, 2.), ET.NO_ENTRY: NoEntryAlert("Stock AEB: Risk of Collision"), }, EventName.fcw: { ET.PERMANENT: Alert( "BRAKE!", "Risk of Collision", AlertStatus.critical, AlertSize.full, Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.warningSoft, 2.), }, EventName.ldw: { ET.PERMANENT: Alert( "Lane Departure Detected", "", AlertStatus.userPrompt, AlertSize.small, Priority.LOW, VisualAlert.ldw, AudibleAlert.prompt, 3.), }, # ********** events only containing alerts that display while engaged ********** # openpilot tries to learn certain parameters about your car by observing # how the car behaves to steering inputs from both human and openpilot driving. # This includes: # - steer ratio: gear ratio of the steering rack. Steering angle divided by tire angle # - tire stiffness: how much grip your tires have # - angle offset: most steering angle sensors are offset and measure a non zero angle when driving straight # This alert is thrown when any of these values exceed a sanity check. This can be caused by # bad alignment or bad sensor data. If this happens consistently consider creating an issue on GitHub EventName.vehicleModelInvalid: { ET.NO_ENTRY: NoEntryAlert("Vehicle Parameter Identification Failed"), ET.SOFT_DISABLE: soft_disable_alert("Vehicle Parameter Identification Failed"), }, EventName.steerTempUnavailableSilent: { ET.WARNING: Alert( "Steering Temporarily Unavailable", "", AlertStatus.userPrompt, AlertSize.small, Priority.LOW, VisualAlert.steerRequired, AudibleAlert.prompt, 1.), }, EventName.preDriverDistracted: { ET.WARNING: Alert( "Pay Attention", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), }, EventName.promptDriverDistracted: { ET.WARNING: Alert( "Pay Attention", "Driver Distracted", AlertStatus.userPrompt, AlertSize.mid, Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, .1), }, EventName.driverDistracted: { ET.WARNING: Alert( "DISENGAGE IMMEDIATELY", "Driver Distracted", AlertStatus.critical, AlertSize.full, Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.warningImmediate, .1), }, EventName.preDriverUnresponsive: { ET.WARNING: Alert( "Touch Steering Wheel: No Face Detected", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.steerRequired, AudibleAlert.none, .1, alert_rate=0.75), }, EventName.promptDriverUnresponsive: { ET.WARNING: Alert( "Touch Steering Wheel", "Driver Unresponsive", AlertStatus.userPrompt, AlertSize.mid, Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, .1), }, EventName.driverUnresponsive: { ET.WARNING: Alert( "DISENGAGE IMMEDIATELY", "Driver Unresponsive", AlertStatus.critical, AlertSize.full, Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.warningImmediate, .1), }, EventName.manualRestart: { ET.WARNING: Alert( "TAKE CONTROL", "Resume Driving Manually", AlertStatus.userPrompt, AlertSize.mid, Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), }, EventName.resumeRequired: { ET.WARNING: Alert( "STOPPED", "Press Resume to Go", AlertStatus.userPrompt, AlertSize.mid, Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), }, EventName.belowSteerSpeed: { ET.WARNING: below_steer_speed_alert, }, EventName.preLaneChangeLeft: { ET.WARNING: Alert( "Steer Left to Start Lane Change Once Safe", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.none, .1, alert_rate=0.75), }, EventName.preLaneChangeRight: { ET.WARNING: Alert( "Steer Right to Start Lane Change Once Safe", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.none, .1, alert_rate=0.75), }, EventName.laneChangeBlocked: { ET.WARNING: Alert( "Car Detected in Blindspot", "", AlertStatus.userPrompt, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.prompt, .1), }, EventName.laneChange: { ET.WARNING: Alert( "Changing Lanes", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), }, EventName.steerSaturated: { ET.WARNING: Alert( "Take Control", "Turn Exceeds Steering Limit", AlertStatus.userPrompt, AlertSize.mid, Priority.LOW, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 1.), }, # Thrown when the fan is driven at >50% but is not rotating EventName.fanMalfunction: { ET.PERMANENT: NormalPermanentAlert("Fan Malfunction", "Likely Hardware Issue"), }, # Camera is not outputting frames EventName.cameraMalfunction: { ET.PERMANENT: camera_malfunction_alert, ET.SOFT_DISABLE: soft_disable_alert("Camera Malfunction"), ET.NO_ENTRY: NoEntryAlert("Camera Malfunction: Reboot Your Device"), }, # Camera framerate too low EventName.cameraFrameRate: { ET.PERMANENT: NormalPermanentAlert("Camera Frame Rate Low", "Reboot your Device"), ET.SOFT_DISABLE: soft_disable_alert("Camera Frame Rate Low"), ET.NO_ENTRY: NoEntryAlert("Camera Frame Rate Low: Reboot Your Device"), }, # Unused EventName.gpsMalfunction: { ET.PERMANENT: NormalPermanentAlert("GPS Malfunction", "Likely Hardware Issue"), }, # When the GPS position and localizer diverge the localizer is reset to the # current GPS position. This alert is thrown when the localizer is reset # more often than expected. EventName.localizerMalfunction: { # ET.PERMANENT: NormalPermanentAlert("Sensor Malfunction", "Hardware Malfunction"), }, # ********** events that affect controls state transitions ********** EventName.pcmEnable: { ET.ENABLE: EngagementAlert(AudibleAlert.engage), }, EventName.buttonEnable: { ET.ENABLE: EngagementAlert(AudibleAlert.engage), }, EventName.pcmDisable: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), }, EventName.buttonCancel: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), }, EventName.brakeHold: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), ET.NO_ENTRY: NoEntryAlert("Brake Hold Active"), }, EventName.parkBrake: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), ET.NO_ENTRY: NoEntryAlert("Parking Brake Engaged"), }, EventName.pedalPressed: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), ET.NO_ENTRY: NoEntryAlert("Pedal Pressed", visual_alert=VisualAlert.brakePressed), }, EventName.pedalPressedPreEnable: { ET.PRE_ENABLE: Alert( "Release Pedal to Engage", "", AlertStatus.normal, AlertSize.small, Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1, creation_delay=1.), }, EventName.gasPressedOverride: { ET.OVERRIDE: Alert( "", "", AlertStatus.normal, AlertSize.none, Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1), }, EventName.wrongCarMode: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), ET.NO_ENTRY: wrong_car_mode_alert, }, EventName.wrongCruiseMode: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), ET.NO_ENTRY: NoEntryAlert("Adaptive Cruise Disabled"), }, EventName.steerTempUnavailable: { ET.SOFT_DISABLE: soft_disable_alert("Steering Temporarily Unavailable"), ET.NO_ENTRY: NoEntryAlert("Steering Temporarily Unavailable"), }, EventName.outOfSpace: { ET.PERMANENT: out_of_space_alert, ET.NO_ENTRY: NoEntryAlert("Out of Storage"), }, EventName.belowEngageSpeed: { ET.NO_ENTRY: below_engage_speed_alert, }, EventName.sensorDataInvalid: { ET.PERMANENT: Alert( "No Data from Device Sensors", "Reboot your Device", AlertStatus.normal, AlertSize.mid, Priority.LOWER, VisualAlert.none, AudibleAlert.none, .2, creation_delay=1.), ET.NO_ENTRY: NoEntryAlert("No Data from Device Sensors"), }, EventName.noGps: { ET.PERMANENT: no_gps_alert, }, EventName.soundsUnavailable: { ET.PERMANENT: NormalPermanentAlert("Speaker not found", "Reboot your Device"), ET.NO_ENTRY: NoEntryAlert("Speaker not found"), }, EventName.tooDistracted: { ET.NO_ENTRY: NoEntryAlert("Distraction Level Too High"), }, EventName.overheat: { ET.PERMANENT: overheat_alert, ET.SOFT_DISABLE: soft_disable_alert("System Overheated"), ET.NO_ENTRY: NoEntryAlert("System Overheated"), }, EventName.wrongGear: { ET.SOFT_DISABLE: user_soft_disable_alert("Gear not D"), ET.NO_ENTRY: NoEntryAlert("Gear not D"), }, # This alert is thrown when the calibration angles are outside of the acceptable range. # For example if the device is pointed too much to the left or the right. # Usually this can only be solved by removing the mount from the windshield completely, # and attaching while making sure the device is pointed straight forward and is level. # See https://comma.ai/setup for more information EventName.calibrationInvalid: { ET.PERMANENT: calibration_invalid_alert, ET.SOFT_DISABLE: soft_disable_alert("Calibration Invalid: Remount Device & Recalibrate"), ET.NO_ENTRY: NoEntryAlert("Calibration Invalid: Remount Device & Recalibrate"), }, EventName.calibrationIncomplete: { ET.PERMANENT: calibration_incomplete_alert, ET.SOFT_DISABLE: soft_disable_alert("Calibration in Progress"), ET.NO_ENTRY: NoEntryAlert("Calibration in Progress"), }, EventName.doorOpen: { ET.SOFT_DISABLE: user_soft_disable_alert("Door Open"), ET.NO_ENTRY: NoEntryAlert("Door Open"), }, EventName.seatbeltNotLatched: { ET.SOFT_DISABLE: user_soft_disable_alert("Seatbelt Unlatched"), ET.NO_ENTRY: NoEntryAlert("Seatbelt Unlatched"), }, EventName.espDisabled: { ET.SOFT_DISABLE: soft_disable_alert("ESP Off"), ET.NO_ENTRY: NoEntryAlert("ESP Off"), }, EventName.lowBattery: { ET.SOFT_DISABLE: soft_disable_alert("Low Battery"), ET.NO_ENTRY: NoEntryAlert("Low Battery"), }, # Different openpilot services communicate between each other at a certain # interval. If communication does not follow the regular schedule this alert # is thrown. This can mean a service crashed, did not broadcast a message for # ten times the regular interval, or the average interval is more than 10% too high. EventName.commIssue: { ET.SOFT_DISABLE: soft_disable_alert("Communication Issue between Processes"), ET.NO_ENTRY: comm_issue_alert, }, EventName.commIssueAvgFreq: { ET.SOFT_DISABLE: soft_disable_alert("Low Communication Rate between Processes"), ET.NO_ENTRY: NoEntryAlert("Low Communication Rate between Processes"), }, EventName.controlsdLagging: { ET.SOFT_DISABLE: soft_disable_alert("Controls Lagging"), ET.NO_ENTRY: NoEntryAlert("Controls Process Lagging: Reboot Your Device"), }, # Thrown when manager detects a service exited unexpectedly while driving EventName.processNotRunning: { ET.NO_ENTRY: process_not_running_alert, ET.SOFT_DISABLE: soft_disable_alert("Process Not Running"), }, EventName.radarFault: { ET.SOFT_DISABLE: soft_disable_alert("Radar Error: Restart the Car"), ET.NO_ENTRY: NoEntryAlert("Radar Error: Restart the Car"), }, # Every frame from the camera should be processed by the model. If modeld # is not processing frames fast enough they have to be dropped. This alert is # thrown when over 20% of frames are dropped. EventName.modeldLagging: { ET.SOFT_DISABLE: soft_disable_alert("Driving Model Lagging"), ET.NO_ENTRY: NoEntryAlert("Driving Model Lagging"), ET.PERMANENT: modeld_lagging_alert, }, # Besides predicting the path, lane lines and lead car data the model also # predicts the current velocity and rotation speed of the car. If the model is # very uncertain about the current velocity while the car is moving, this # usually means the model has trouble understanding the scene. This is used # as a heuristic to warn the driver. EventName.posenetInvalid: { ET.SOFT_DISABLE: soft_disable_alert("Posenet Speed Invalid"), ET.NO_ENTRY: posenet_invalid_alert, }, # When the localizer detects an acceleration of more than 40 m/s^2 (~4G) we # alert the driver the device might have fallen from the windshield. EventName.deviceFalling: { ET.SOFT_DISABLE: soft_disable_alert("Device Fell Off Mount"), ET.NO_ENTRY: NoEntryAlert("Device Fell Off Mount"), }, EventName.lowMemory: { ET.SOFT_DISABLE: soft_disable_alert("Low Memory: Reboot Your Device"), ET.PERMANENT: low_memory_alert, ET.NO_ENTRY: NoEntryAlert("Low Memory: Reboot Your Device"), }, EventName.highCpuUsage: { #ET.SOFT_DISABLE: soft_disable_alert("System Malfunction: Reboot Your Device"), #ET.PERMANENT: NormalPermanentAlert("System Malfunction", "Reboot your Device"), ET.NO_ENTRY: high_cpu_usage_alert, }, EventName.accFaulted: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Faulted"), ET.PERMANENT: NormalPermanentAlert("Cruise Faulted", ""), ET.NO_ENTRY: NoEntryAlert("Cruise Faulted"), }, EventName.controlsMismatch: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Controls Mismatch"), ET.NO_ENTRY: NoEntryAlert("Controls Mismatch"), }, EventName.roadCameraError: { ET.PERMANENT: NormalPermanentAlert("Camera CRC Error - Road", duration=1., creation_delay=30.), }, EventName.wideRoadCameraError: { ET.PERMANENT: NormalPermanentAlert("Camera CRC Error - Road Fisheye", duration=1., creation_delay=30.), }, EventName.driverCameraError: { ET.PERMANENT: NormalPermanentAlert("Camera CRC Error - Driver", duration=1., creation_delay=30.), }, # Sometimes the USB stack on the device can get into a bad state # causing the connection to the panda to be lost EventName.usbError: { ET.SOFT_DISABLE: soft_disable_alert("USB Error: Reboot Your Device"), ET.PERMANENT: NormalPermanentAlert("USB Error: Reboot Your Device", ""), ET.NO_ENTRY: NoEntryAlert("USB Error: Reboot Your Device"), }, # This alert can be thrown for the following reasons: # - No CAN data received at all # - CAN data is received, but some message are not received at the right frequency # If you're not writing a new car port, this is usually cause by faulty wiring EventName.canError: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Error"), ET.PERMANENT: Alert( "CAN Error: Check Connections", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), ET.NO_ENTRY: NoEntryAlert("CAN Error: Check Connections"), }, EventName.canBusMissing: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Bus Disconnected"), ET.PERMANENT: Alert( "CAN Bus Disconnected: Likely Faulty Cable", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), ET.NO_ENTRY: NoEntryAlert("CAN Bus Disconnected: Check Connections"), }, EventName.steerUnavailable: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("LKAS Fault: Restart the Car"), ET.PERMANENT: NormalPermanentAlert("LKAS Fault: Restart the car to engage"), ET.NO_ENTRY: NoEntryAlert("LKAS Fault: Restart the Car"), }, EventName.brakeUnavailable: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Fault: Restart the Car"), ET.PERMANENT: NormalPermanentAlert("Cruise Fault: Restart the car to engage"), ET.NO_ENTRY: NoEntryAlert("Cruise Fault: Restart the Car"), }, EventName.reverseGear: { ET.PERMANENT: Alert( "Reverse\nGear", "", AlertStatus.normal, AlertSize.full, Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2, creation_delay=0.5), ET.USER_DISABLE: ImmediateDisableAlert("Reverse Gear"), ET.NO_ENTRY: NoEntryAlert("Reverse Gear"), }, # On cars that use stock ACC the car can decide to cancel ACC for various reasons. # When this happens we can no long control the car so the user needs to be warned immediately. EventName.cruiseDisabled: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Is Off"), }, # For planning the trajectory Model Predictive Control (MPC) is used. This is # an optimization algorithm that is not guaranteed to find a feasible solution. # If no solution is found or the solution has a very high cost this alert is thrown. EventName.plannerError: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Planner Solution Error"), ET.NO_ENTRY: NoEntryAlert("Planner Solution Error"), }, # When the relay in the harness box opens the CAN bus between the LKAS camera # and the rest of the car is separated. When messages from the LKAS camera # are received on the car side this usually means the relay hasn't opened correctly # and this alert is thrown. EventName.relayMalfunction: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Harness Relay Malfunction"), ET.PERMANENT: NormalPermanentAlert("Harness Relay Malfunction", "Check Hardware"), ET.NO_ENTRY: NoEntryAlert("Harness Relay Malfunction"), }, EventName.noTarget: { ET.IMMEDIATE_DISABLE: Alert( "openpilot Canceled", "No close lead car", AlertStatus.normal, AlertSize.mid, Priority.HIGH, VisualAlert.none, AudibleAlert.disengage, 3.), ET.NO_ENTRY: NoEntryAlert("No Close Lead Car"), }, EventName.speedTooLow: { ET.IMMEDIATE_DISABLE: Alert( "openpilot Canceled", "Speed too low", AlertStatus.normal, AlertSize.mid, Priority.HIGH, VisualAlert.none, AudibleAlert.disengage, 3.), }, # When the car is driving faster than most cars in the training data, the model outputs can be unpredictable. EventName.speedTooHigh: { ET.WARNING: Alert( "Speed Too High", "Model uncertain at this speed", AlertStatus.userPrompt, AlertSize.mid, Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 4.), ET.NO_ENTRY: NoEntryAlert("Slow down to engage"), }, EventName.lowSpeedLockout: { ET.PERMANENT: NormalPermanentAlert("Cruise Fault: Restart the car to engage"), ET.NO_ENTRY: NoEntryAlert("Cruise Fault: Restart the Car"), }, EventName.lkasDisabled: { ET.PERMANENT: NormalPermanentAlert("LKAS Disabled: Enable LKAS to engage"), ET.NO_ENTRY: NoEntryAlert("LKAS Disabled"), }, }
import math import os from enum import IntEnum from typing import Dict, Union, Callable, List, Optional from cereal import log, car import cereal.messaging as messaging from common.conversions import Conversions as CV from common.realtime import DT_CTRL from selfdrive.locationd.calibrationd import MIN_SPEED_FILTER from system.version import get_short_branch AlertSize = log.ControlsState.AlertSize AlertStatus = log.ControlsState.AlertStatus VisualAlert = car.CarControl.HUDControl.VisualAlert AudibleAlert = car.CarControl.HUDControl.AudibleAlert EventName = car.CarEvent.EventName # Alert priorities class Priority(IntEnum): LOWEST = 0 LOWER = 1 LOW = 2 MID = 3 HIGH = 4 HIGHEST = 5 # Event types class ET: ENABLE = 'enable' PRE_ENABLE = 'preEnable' OVERRIDE = 'override' NO_ENTRY = 'noEntry' WARNING = 'warning' USER_DISABLE = 'userDisable' SOFT_DISABLE = 'softDisable' IMMEDIATE_DISABLE = 'immediateDisable' PERMANENT = 'permanent' # get event name from enum EVENT_NAME = {v: k for k, v in EventName.schema.enumerants.items()} class Events: def __init__(self): self.events: List[int] = [] self.static_events: List[int] = [] self.events_prev = dict.fromkeys(EVENTS.keys(), 0) @property def names(self) -> List[int]: return self.events def __len__(self) -> int: return len(self.events) def add(self, event_name: int, static: bool=False) -> None: if static: self.static_events.append(event_name) self.events.append(event_name) def clear(self) -> None: self.events_prev = {k: (v + 1 if k in self.events else 0) for k, v in self.events_prev.items()} self.events = self.static_events.copy() def any(self, event_type: str) -> bool: return any(event_type in EVENTS.get(e, {}) for e in self.events) def create_alerts(self, event_types: List[str], callback_args=None): if callback_args is None: callback_args = [] ret = [] for e in self.events: types = EVENTS[e].keys() for et in event_types: if et in types: alert = EVENTS[e][et] if not isinstance(alert, Alert): alert = alert(*callback_args) if DT_CTRL * (self.events_prev[e] + 1) >= alert.creation_delay: alert.alert_type = f"{EVENT_NAME[e]}/{et}" alert.event_type = et ret.append(alert) return ret def add_from_msg(self, events): for e in events: self.events.append(e.name.raw) def to_msg(self): ret = [] for event_name in self.events: event = car.CarEvent.new_message() event.name = event_name for event_type in EVENTS.get(event_name, {}): setattr(event, event_type, True) ret.append(event) return ret class Alert: def __init__(self, alert_text_1: str, alert_text_2: str, alert_status: log.ControlsState.AlertStatus, alert_size: log.ControlsState.AlertSize, priority: Priority, visual_alert: car.CarControl.HUDControl.VisualAlert, audible_alert: car.CarControl.HUDControl.AudibleAlert, duration: float, alert_rate: float = 0., creation_delay: float = 0.): self.alert_text_1 = alert_text_1 self.alert_text_2 = alert_text_2 self.alert_status = alert_status self.alert_size = alert_size self.priority = priority self.visual_alert = visual_alert self.audible_alert = audible_alert self.duration = int(duration / DT_CTRL) self.alert_rate = alert_rate self.creation_delay = creation_delay self.alert_type = "" self.event_type: Optional[str] = None def __str__(self) -> str: return f"{self.alert_text_1}/{self.alert_text_2} {self.priority} {self.visual_alert} {self.audible_alert}" def __gt__(self, alert2) -> bool: if not isinstance(alert2, Alert): return False return self.priority > alert2.priority class NoEntryAlert(Alert): def __init__(self, alert_text_2: str, alert_text_1: str = "openpilot Unavailable", visual_alert: car.CarControl.HUDControl.VisualAlert=VisualAlert.none): super().__init__(alert_text_1, alert_text_2, AlertStatus.normal, AlertSize.mid, Priority.LOW, visual_alert, AudibleAlert.refuse, 3.) class SoftDisableAlert(Alert): def __init__(self, alert_text_2: str): super().__init__("TAKE CONTROL IMMEDIATELY", alert_text_2, AlertStatus.userPrompt, AlertSize.full, Priority.MID, VisualAlert.steerRequired, AudibleAlert.warningSoft, 2.), # less harsh version of SoftDisable, where the condition is user-triggered class UserSoftDisableAlert(SoftDisableAlert): def __init__(self, alert_text_2: str): super().__init__(alert_text_2), self.alert_text_1 = "openpilot will disengage" class ImmediateDisableAlert(Alert): def __init__(self, alert_text_2: str): super().__init__("TAKE CONTROL IMMEDIATELY", alert_text_2, AlertStatus.critical, AlertSize.full, Priority.HIGHEST, VisualAlert.steerRequired, AudibleAlert.warningImmediate, 4.), class EngagementAlert(Alert): def __init__(self, audible_alert: car.CarControl.HUDControl.AudibleAlert): super().__init__("", "", AlertStatus.normal, AlertSize.none, Priority.MID, VisualAlert.none, audible_alert, .2), class NormalPermanentAlert(Alert): def __init__(self, alert_text_1: str, alert_text_2: str = "", duration: float = 0.2, priority: Priority = Priority.LOWER, creation_delay: float = 0.): super().__init__(alert_text_1, alert_text_2, AlertStatus.normal, AlertSize.mid if len(alert_text_2) else AlertSize.small, priority, VisualAlert.none, AudibleAlert.none, duration, creation_delay=creation_delay), class StartupAlert(Alert): def __init__(self, alert_text_1: str, alert_text_2: str = "Always keep hands on wheel and eyes on road", alert_status=AlertStatus.normal): super().__init__(alert_text_1, alert_text_2, alert_status, AlertSize.mid, Priority.LOWER, VisualAlert.none, AudibleAlert.none, 10.), # ********** helper functions ********** def get_display_speed(speed_ms: float, metric: bool) -> str: speed = int(round(speed_ms * (CV.MS_TO_KPH if metric else CV.MS_TO_MPH))) unit = 'km/h' if metric else 'mph' return f"{speed} {unit}" # ********** alert callback functions ********** AlertCallbackType = Callable[[car.CarParams, car.CarState, messaging.SubMaster, bool, int], Alert] def soft_disable_alert(alert_text_2: str) -> AlertCallbackType: def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: if soft_disable_time < int(0.5 / DT_CTRL): return ImmediateDisableAlert(alert_text_2) return SoftDisableAlert(alert_text_2) return func def user_soft_disable_alert(alert_text_2: str) -> AlertCallbackType: def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: if soft_disable_time < int(0.5 / DT_CTRL): return ImmediateDisableAlert(alert_text_2) return UserSoftDisableAlert(alert_text_2) return func def startup_master_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: branch = get_short_branch("") if "REPLAY" in os.environ: branch = "replay" return StartupAlert("MechTechTeam 08.15 061822", branch, alert_status=AlertStatus.userPrompt) def below_engage_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return NoEntryAlert(f"Speed Below {get_display_speed(CP.minEnableSpeed, metric)}") def below_steer_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return Alert( f"Steer Unavailable Below {get_display_speed(CP.minSteerSpeed, metric)}", "", AlertStatus.userPrompt, AlertSize.small, Priority.MID, VisualAlert.steerRequired, AudibleAlert.prompt, 0.4) def calibration_incomplete_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return Alert( "Calibration in Progress: %d%%" % sm['liveCalibration'].calPerc, f"Drive Above {get_display_speed(MIN_SPEED_FILTER, metric)}", AlertStatus.normal, AlertSize.mid, Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2) def no_gps_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: gps_integrated = sm['peripheralState'].pandaType in (log.PandaState.PandaType.uno, log.PandaState.PandaType.dos) return Alert( "Poor GPS reception", "Hardware malfunctioning if sky is visible" if gps_integrated else "Check GPS antenna placement", AlertStatus.normal, AlertSize.mid, Priority.LOWER, VisualAlert.none, AudibleAlert.none, .2, creation_delay=300.) # *** debug alerts *** def out_of_space_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: full_perc = round(100. - sm['deviceState'].freeSpacePercent) return NormalPermanentAlert("Out of Storage", f"{full_perc}% full") def posenet_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: mdl = sm['modelV2'].velocity.x[0] if len(sm['modelV2'].velocity.x) else math.nan err = CS.vEgo - mdl msg = f"Speed Error: {err:.1f} m/s" return NoEntryAlert(msg, alert_text_1="Posenet Speed Invalid") def process_not_running_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: not_running = [p.name for p in sm['managerState'].processes if not p.running and p.shouldBeRunning] msg = ', '.join(not_running) return NoEntryAlert(msg, alert_text_1="Process Not Running") def comm_issue_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: bs = [s for s in sm.data.keys() if not sm.all_checks([s, ])] msg = ', '.join(bs[:4]) # can't fit too many on one line return NoEntryAlert(msg, alert_text_1="Communication Issue Between Processes") def camera_malfunction_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: all_cams = ('roadCameraState', 'driverCameraState', 'wideRoadCameraState') bad_cams = [s.replace('State', '') for s in all_cams if s in sm.data.keys() and not sm.all_checks([s, ])] return NormalPermanentAlert("Camera Malfunction", ', '.join(bad_cams)) def calibration_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: rpy = sm['liveCalibration'].rpyCalib yaw = math.degrees(rpy[2] if len(rpy) == 3 else math.nan) pitch = math.degrees(rpy[1] if len(rpy) == 3 else math.nan) angles = f"Pitch: {pitch:.1f}°, Yaw: {yaw:.1f}°" return NormalPermanentAlert("Calibration Invalid", angles) def overheat_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: cpu = max(sm['deviceState'].cpuTempC, default=0.) gpu = max(sm['deviceState'].gpuTempC, default=0.) temp = max((cpu, gpu, sm['deviceState'].memoryTempC)) return NormalPermanentAlert("System Overheated", f"{temp:.0f} °C") def low_memory_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return NormalPermanentAlert("Low Memory", f"{sm['deviceState'].memoryUsagePercent}% used") def high_cpu_usage_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: x = max(sm['deviceState'].cpuUsagePercent, default=0.) return NormalPermanentAlert("High CPU Usage", f"{x}% used") def modeld_lagging_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return NormalPermanentAlert("Driving Model Lagging", f"{sm['modelV2'].frameDropPerc:.1f}% frames dropped") def wrong_car_mode_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: text = "Cruise Mode Disabled" if CP.carName == "honda": text = "Main Switch Off" return NoEntryAlert(text) def joystick_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: axes = sm['testJoystick'].axes gb, steer = list(axes)[:2] if len(axes) else (0., 0.) vals = f"Gas: {round(gb * 100.)}%, Steer: {round(steer * 100.)}%" return NormalPermanentAlert("Joystick Mode", vals) EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { # ********** events with no alerts ********** EventName.stockFcw: {}, # ********** events only containing alerts displayed in all states ********** EventName.joystickDebug: { ET.WARNING: joystick_alert, ET.PERMANENT: NormalPermanentAlert("Joystick Mode"), }, EventName.controlsInitializing: { ET.NO_ENTRY: NoEntryAlert("System Initializing"), }, EventName.startup: { ET.PERMANENT: StartupAlert("Be ready to take over at any time") }, EventName.startupMaster: { ET.PERMANENT: startup_master_alert, }, # Car is recognized, but marked as dashcam only EventName.startupNoControl: { ET.PERMANENT: StartupAlert("Dashcam mode"), }, # Car is not recognized EventName.startupNoCar: { ET.PERMANENT: StartupAlert("Dashcam mode for unsupported car"), }, EventName.startupNoFw: { ET.PERMANENT: StartupAlert("Car Unrecognized", "Check comma power connections", alert_status=AlertStatus.userPrompt), }, EventName.dashcamMode: { ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", priority=Priority.LOWEST), }, EventName.invalidLkasSetting: { ET.PERMANENT: NormalPermanentAlert("Stock LKAS is on", "Turn off stock LKAS to engage"), }, EventName.cruiseMismatch: { #ET.PERMANENT: ImmediateDisableAlert("openpilot failed to cancel cruise"), }, # openpilot doesn't recognize the car. This switches openpilot into a # read-only mode. This can be solved by adding your fingerprint. # See https://github.com/commaai/openpilot/wiki/Fingerprinting for more information EventName.carUnrecognized: { ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", "Car Unrecognized", priority=Priority.LOWEST), }, EventName.stockAeb: { ET.PERMANENT: Alert( "BRAKE!", "Stock AEB: Risk of Collision", AlertStatus.critical, AlertSize.full, Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.none, 2.), ET.NO_ENTRY: NoEntryAlert("Stock AEB: Risk of Collision"), }, EventName.fcw: { ET.PERMANENT: Alert( "BRAKE!", "Risk of Collision", AlertStatus.critical, AlertSize.full, Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.warningSoft, 2.), }, EventName.ldw: { ET.PERMANENT: Alert( "Lane Departure Detected", "", AlertStatus.userPrompt, AlertSize.small, Priority.LOW, VisualAlert.ldw, AudibleAlert.prompt, 3.), }, # ********** events only containing alerts that display while engaged ********** # openpilot tries to learn certain parameters about your car by observing # how the car behaves to steering inputs from both human and openpilot driving. # This includes: # - steer ratio: gear ratio of the steering rack. Steering angle divided by tire angle # - tire stiffness: how much grip your tires have # - angle offset: most steering angle sensors are offset and measure a non zero angle when driving straight # This alert is thrown when any of these values exceed a sanity check. This can be caused by # bad alignment or bad sensor data. If this happens consistently consider creating an issue on GitHub EventName.vehicleModelInvalid: { ET.NO_ENTRY: NoEntryAlert("Vehicle Parameter Identification Failed"), ET.SOFT_DISABLE: soft_disable_alert("Vehicle Parameter Identification Failed"), }, EventName.steerTempUnavailableSilent: { ET.WARNING: Alert( "Steering Temporarily Unavailable", "", AlertStatus.userPrompt, AlertSize.small, Priority.LOW, VisualAlert.steerRequired, AudibleAlert.prompt, 1.), }, EventName.preDriverDistracted: { ET.WARNING: Alert( "Pay Attention", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), }, EventName.promptDriverDistracted: { ET.WARNING: Alert( "Pay Attention", "Driver Distracted", AlertStatus.userPrompt, AlertSize.mid, Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, .1), }, EventName.driverDistracted: { ET.WARNING: Alert( "DISENGAGE IMMEDIATELY", "Driver Distracted", AlertStatus.critical, AlertSize.full, Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.warningImmediate, .1), }, EventName.preDriverUnresponsive: { ET.WARNING: Alert( "Touch Steering Wheel: No Face Detected", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.steerRequired, AudibleAlert.none, .1, alert_rate=0.75), }, EventName.promptDriverUnresponsive: { ET.WARNING: Alert( "Touch Steering Wheel", "Driver Unresponsive", AlertStatus.userPrompt, AlertSize.mid, Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, .1), }, EventName.driverUnresponsive: { ET.WARNING: Alert( "DISENGAGE IMMEDIATELY", "Driver Unresponsive", AlertStatus.critical, AlertSize.full, Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.warningImmediate, .1), }, EventName.manualRestart: { ET.WARNING: Alert( "TAKE CONTROL", "Resume Driving Manually", AlertStatus.userPrompt, AlertSize.mid, Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), }, EventName.resumeRequired: { ET.WARNING: Alert( "STOPPED", "Press Resume to Go", AlertStatus.userPrompt, AlertSize.mid, Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), }, EventName.belowSteerSpeed: { ET.WARNING: below_steer_speed_alert, }, EventName.preLaneChangeLeft: { ET.WARNING: Alert( "Steer Left to Start Lane Change Once Safe", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.none, .1, alert_rate=0.75), }, EventName.preLaneChangeRight: { ET.WARNING: Alert( "Steer Right to Start Lane Change Once Safe", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.none, .1, alert_rate=0.75), }, EventName.laneChangeBlocked: { ET.WARNING: Alert( "Car Detected in Blindspot", "", AlertStatus.userPrompt, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.prompt, .1), }, EventName.laneChange: { ET.WARNING: Alert( "Changing Lanes", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), }, EventName.steerSaturated: { ET.WARNING: Alert( "Take Control", "Turn Exceeds Steering Limit", AlertStatus.userPrompt, AlertSize.mid, Priority.LOW, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 1.), }, # Thrown when the fan is driven at >50% but is not rotating EventName.fanMalfunction: { ET.PERMANENT: NormalPermanentAlert("Fan Malfunction", "Likely Hardware Issue"), }, # Camera is not outputting frames EventName.cameraMalfunction: { ET.PERMANENT: camera_malfunction_alert, ET.SOFT_DISABLE: soft_disable_alert("Camera Malfunction"), ET.NO_ENTRY: NoEntryAlert("Camera Malfunction: Reboot Your Device"), }, # Camera framerate too low EventName.cameraFrameRate: { ET.PERMANENT: NormalPermanentAlert("Camera Frame Rate Low", "Reboot your Device"), ET.SOFT_DISABLE: soft_disable_alert("Camera Frame Rate Low"), ET.NO_ENTRY: NoEntryAlert("Camera Frame Rate Low: Reboot Your Device"), }, # Unused EventName.gpsMalfunction: { ET.PERMANENT: NormalPermanentAlert("GPS Malfunction", "Likely Hardware Issue"), }, # When the GPS position and localizer diverge the localizer is reset to the # current GPS position. This alert is thrown when the localizer is reset # more often than expected. EventName.localizerMalfunction: { # ET.PERMANENT: NormalPermanentAlert("Sensor Malfunction", "Hardware Malfunction"), }, # ********** events that affect controls state transitions ********** EventName.pcmEnable: { ET.ENABLE: EngagementAlert(AudibleAlert.engage), }, EventName.buttonEnable: { ET.ENABLE: EngagementAlert(AudibleAlert.engage), }, EventName.pcmDisable: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), }, EventName.buttonCancel: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), }, EventName.brakeHold: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), ET.NO_ENTRY: NoEntryAlert("Brake Hold Active"), }, EventName.parkBrake: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), ET.NO_ENTRY: NoEntryAlert("Parking Brake Engaged"), }, EventName.pedalPressed: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), ET.NO_ENTRY: NoEntryAlert("Pedal Pressed", visual_alert=VisualAlert.brakePressed), }, EventName.pedalPressedPreEnable: { ET.PRE_ENABLE: Alert( "Release Pedal to Engage", "", AlertStatus.normal, AlertSize.small, Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1, creation_delay=1.), }, EventName.gasPressedOverride: { ET.OVERRIDE: Alert( "", "", AlertStatus.normal, AlertSize.none, Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1), }, EventName.wrongCarMode: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), ET.NO_ENTRY: wrong_car_mode_alert, }, EventName.wrongCruiseMode: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), ET.NO_ENTRY: NoEntryAlert("Adaptive Cruise Disabled"), }, EventName.steerTempUnavailable: { ET.SOFT_DISABLE: soft_disable_alert("Steering Temporarily Unavailable"), ET.NO_ENTRY: NoEntryAlert("Steering Temporarily Unavailable"), }, EventName.outOfSpace: { ET.PERMANENT: out_of_space_alert, ET.NO_ENTRY: NoEntryAlert("Out of Storage"), }, EventName.belowEngageSpeed: { ET.NO_ENTRY: below_engage_speed_alert, }, EventName.sensorDataInvalid: { ET.PERMANENT: Alert( "No Data from Device Sensors", "Reboot your Device", AlertStatus.normal, AlertSize.mid, Priority.LOWER, VisualAlert.none, AudibleAlert.none, .2, creation_delay=1.), ET.NO_ENTRY: NoEntryAlert("No Data from Device Sensors"), }, EventName.noGps: { ET.PERMANENT: no_gps_alert, }, EventName.soundsUnavailable: { ET.PERMANENT: NormalPermanentAlert("Speaker not found", "Reboot your Device"), ET.NO_ENTRY: NoEntryAlert("Speaker not found"), }, EventName.tooDistracted: { ET.NO_ENTRY: NoEntryAlert("Distraction Level Too High"), }, EventName.overheat: { ET.PERMANENT: overheat_alert, ET.SOFT_DISABLE: soft_disable_alert("System Overheated"), ET.NO_ENTRY: NoEntryAlert("System Overheated"), }, EventName.wrongGear: { ET.SOFT_DISABLE: user_soft_disable_alert("Gear not D"), ET.NO_ENTRY: NoEntryAlert("Gear not D"), }, # This alert is thrown when the calibration angles are outside of the acceptable range. # For example if the device is pointed too much to the left or the right. # Usually this can only be solved by removing the mount from the windshield completely, # and attaching while making sure the device is pointed straight forward and is level. # See https://comma.ai/setup for more information EventName.calibrationInvalid: { ET.PERMANENT: calibration_invalid_alert, ET.SOFT_DISABLE: soft_disable_alert("Calibration Invalid: Remount Device & Recalibrate"), ET.NO_ENTRY: NoEntryAlert("Calibration Invalid: Remount Device & Recalibrate"), }, EventName.calibrationIncomplete: { ET.PERMANENT: calibration_incomplete_alert, ET.SOFT_DISABLE: soft_disable_alert("Calibration in Progress"), ET.NO_ENTRY: NoEntryAlert("Calibration in Progress"), }, EventName.doorOpen: { ET.SOFT_DISABLE: user_soft_disable_alert("Door Open"), ET.NO_ENTRY: NoEntryAlert("Door Open"), }, EventName.seatbeltNotLatched: { ET.SOFT_DISABLE: user_soft_disable_alert("Seatbelt Unlatched"), ET.NO_ENTRY: NoEntryAlert("Seatbelt Unlatched"), }, EventName.espDisabled: { ET.SOFT_DISABLE: soft_disable_alert("ESP Off"), ET.NO_ENTRY: NoEntryAlert("ESP Off"), }, EventName.lowBattery: { ET.SOFT_DISABLE: soft_disable_alert("Low Battery"), ET.NO_ENTRY: NoEntryAlert("Low Battery"), }, # Different openpilot services communicate between each other at a certain # interval. If communication does not follow the regular schedule this alert # is thrown. This can mean a service crashed, did not broadcast a message for # ten times the regular interval, or the average interval is more than 10% too high. EventName.commIssue: { ET.SOFT_DISABLE: soft_disable_alert("Communication Issue between Processes"), ET.NO_ENTRY: comm_issue_alert, }, EventName.commIssueAvgFreq: { ET.SOFT_DISABLE: soft_disable_alert("Low Communication Rate between Processes"), ET.NO_ENTRY: NoEntryAlert("Low Communication Rate between Processes"), }, EventName.controlsdLagging: { ET.SOFT_DISABLE: soft_disable_alert("Controls Lagging"), ET.NO_ENTRY: NoEntryAlert("Controls Process Lagging: Reboot Your Device"), }, # Thrown when manager detects a service exited unexpectedly while driving EventName.processNotRunning: { ET.NO_ENTRY: process_not_running_alert, ET.SOFT_DISABLE: soft_disable_alert("Process Not Running"), }, EventName.radarFault: { ET.SOFT_DISABLE: soft_disable_alert("Radar Error: Restart the Car"), ET.NO_ENTRY: NoEntryAlert("Radar Error: Restart the Car"), }, # Every frame from the camera should be processed by the model. If modeld # is not processing frames fast enough they have to be dropped. This alert is # thrown when over 20% of frames are dropped. EventName.modeldLagging: { ET.SOFT_DISABLE: soft_disable_alert("Driving Model Lagging"), ET.NO_ENTRY: NoEntryAlert("Driving Model Lagging"), ET.PERMANENT: modeld_lagging_alert, }, # Besides predicting the path, lane lines and lead car data the model also # predicts the current velocity and rotation speed of the car. If the model is # very uncertain about the current velocity while the car is moving, this # usually means the model has trouble understanding the scene. This is used # as a heuristic to warn the driver. EventName.posenetInvalid: { ET.SOFT_DISABLE: soft_disable_alert("Posenet Speed Invalid"), ET.NO_ENTRY: posenet_invalid_alert, }, # When the localizer detects an acceleration of more than 40 m/s^2 (~4G) we # alert the driver the device might have fallen from the windshield. EventName.deviceFalling: { ET.SOFT_DISABLE: soft_disable_alert("Device Fell Off Mount"), ET.NO_ENTRY: NoEntryAlert("Device Fell Off Mount"), }, EventName.lowMemory: { ET.SOFT_DISABLE: soft_disable_alert("Low Memory: Reboot Your Device"), ET.PERMANENT: low_memory_alert, ET.NO_ENTRY: NoEntryAlert("Low Memory: Reboot Your Device"), }, EventName.highCpuUsage: { #ET.SOFT_DISABLE: soft_disable_alert("System Malfunction: Reboot Your Device"), #ET.PERMANENT: NormalPermanentAlert("System Malfunction", "Reboot your Device"), ET.NO_ENTRY: high_cpu_usage_alert, }, EventName.accFaulted: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Faulted"), ET.PERMANENT: NormalPermanentAlert("Cruise Faulted", ""), ET.NO_ENTRY: NoEntryAlert("Cruise Faulted"), }, EventName.controlsMismatch: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Controls Mismatch"), ET.NO_ENTRY: NoEntryAlert("Controls Mismatch"), }, EventName.roadCameraError: { ET.PERMANENT: NormalPermanentAlert("Camera CRC Error - Road", duration=1., creation_delay=30.), }, EventName.wideRoadCameraError: { ET.PERMANENT: NormalPermanentAlert("Camera CRC Error - Road Fisheye", duration=1., creation_delay=30.), }, EventName.driverCameraError: { ET.PERMANENT: NormalPermanentAlert("Camera CRC Error - Driver", duration=1., creation_delay=30.), }, # Sometimes the USB stack on the device can get into a bad state # causing the connection to the panda to be lost EventName.usbError: { ET.SOFT_DISABLE: soft_disable_alert("USB Error: Reboot Your Device"), ET.PERMANENT: NormalPermanentAlert("USB Error: Reboot Your Device", ""), ET.NO_ENTRY: NoEntryAlert("USB Error: Reboot Your Device"), }, # This alert can be thrown for the following reasons: # - No CAN data received at all # - CAN data is received, but some message are not received at the right frequency # If you're not writing a new car port, this is usually cause by faulty wiring EventName.canError: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Error"), ET.PERMANENT: Alert( "CAN Error: Check Connections", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), ET.NO_ENTRY: NoEntryAlert("CAN Error: Check Connections"), }, EventName.canBusMissing: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Bus Disconnected"), ET.PERMANENT: Alert( "CAN Bus Disconnected: Likely Faulty Cable", "", AlertStatus.normal, AlertSize.small, Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), ET.NO_ENTRY: NoEntryAlert("CAN Bus Disconnected: Check Connections"), }, EventName.steerUnavailable: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("LKAS Fault: Restart the Car"), ET.PERMANENT: NormalPermanentAlert("LKAS Fault: Restart the car to engage"), ET.NO_ENTRY: NoEntryAlert("LKAS Fault: Restart the Car"), }, EventName.brakeUnavailable: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Fault: Restart the Car"), ET.PERMANENT: NormalPermanentAlert("Cruise Fault: Restart the car to engage"), ET.NO_ENTRY: NoEntryAlert("Cruise Fault: Restart the Car"), }, EventName.reverseGear: { ET.PERMANENT: Alert( "Reverse\nGear", "", AlertStatus.normal, AlertSize.full, Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2, creation_delay=0.5), ET.USER_DISABLE: ImmediateDisableAlert("Reverse Gear"), ET.NO_ENTRY: NoEntryAlert("Reverse Gear"), }, # On cars that use stock ACC the car can decide to cancel ACC for various reasons. # When this happens we can no long control the car so the user needs to be warned immediately. EventName.cruiseDisabled: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Is Off"), }, # For planning the trajectory Model Predictive Control (MPC) is used. This is # an optimization algorithm that is not guaranteed to find a feasible solution. # If no solution is found or the solution has a very high cost this alert is thrown. EventName.plannerError: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Planner Solution Error"), ET.NO_ENTRY: NoEntryAlert("Planner Solution Error"), }, # When the relay in the harness box opens the CAN bus between the LKAS camera # and the rest of the car is separated. When messages from the LKAS camera # are received on the car side this usually means the relay hasn't opened correctly # and this alert is thrown. EventName.relayMalfunction: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Harness Relay Malfunction"), ET.PERMANENT: NormalPermanentAlert("Harness Relay Malfunction", "Check Hardware"), ET.NO_ENTRY: NoEntryAlert("Harness Relay Malfunction"), }, EventName.noTarget: { ET.IMMEDIATE_DISABLE: Alert( "openpilot Canceled", "No close lead car", AlertStatus.normal, AlertSize.mid, Priority.HIGH, VisualAlert.none, AudibleAlert.disengage, 3.), ET.NO_ENTRY: NoEntryAlert("No Close Lead Car"), }, EventName.speedTooLow: { ET.IMMEDIATE_DISABLE: Alert( "openpilot Canceled", "Speed too low", AlertStatus.normal, AlertSize.mid, Priority.HIGH, VisualAlert.none, AudibleAlert.disengage, 3.), }, # When the car is driving faster than most cars in the training data, the model outputs can be unpredictable. EventName.speedTooHigh: { ET.WARNING: Alert( "Speed Too High", "Model uncertain at this speed", AlertStatus.userPrompt, AlertSize.mid, Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 4.), ET.NO_ENTRY: NoEntryAlert("Slow down to engage"), }, EventName.lowSpeedLockout: { ET.PERMANENT: NormalPermanentAlert("Cruise Fault: Restart the car to engage"), ET.NO_ENTRY: NoEntryAlert("Cruise Fault: Restart the Car"), }, EventName.lkasDisabled: { ET.PERMANENT: NormalPermanentAlert("LKAS Disabled: Enable LKAS to engage"), ET.NO_ENTRY: NoEntryAlert("LKAS Disabled"), }, }
# Copyright (c) MONAI Consortium # 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 collections import OrderedDict from typing import TYPE_CHECKING, Dict, Optional, Sequence, Union import numpy as np import torch from monai.config import IgniteInfo, KeysCollection, PathLike from monai.utils import ensure_tuple, look_up_option, min_version, optional_import idist, _ = optional_import("ignite", IgniteInfo.OPT_IMPORT_VERSION, min_version, "distributed") if TYPE_CHECKING: from ignite.engine import Engine else: Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") __all__ = ["stopping_fn_from_metric", "stopping_fn_from_loss", "write_metrics_reports", "from_engine"] def stopping_fn_from_metric(metric_name: str): """ Returns a stopping function for ignite.handlers.EarlyStopping using the given metric name. """ def stopping_fn(engine: Engine): return engine.state.metrics[metric_name] return stopping_fn def stopping_fn_from_loss(): """ Returns a stopping function for ignite.handlers.EarlyStopping using the loss value. """ def stopping_fn(engine: Engine): return -engine.state.output # type:ignore return stopping_fn def write_metrics_reports( save_dir: PathLike, images: Optional[Sequence[str]], metrics: Optional[Dict[str, Union[torch.Tensor, np.ndarray]]], metric_details: Optional[Dict[str, Union[torch.Tensor, np.ndarray]]], summary_ops: Optional[Union[str, Sequence[str]]], deli: str = ",", output_type: str = "csv", ): """ Utility function to write the metrics into files, contains 3 parts: 1. if `metrics` dict is not None, write overall metrics into file, every line is a metric name and value pair. 2. if `metric_details` dict is not None, write raw metric data of every image into file, every line for 1 image. 3. if `summary_ops` is not None, compute summary based on operations on `metric_details` and write to file. Args: save_dir: directory to save all the metrics reports. images: name or path of every input image corresponding to the metric_details data. if None, will use index number as the filename of every input image. metrics: a dictionary of (metric name, metric value) pairs. metric_details: a dictionary of (metric name, metric raw values) pairs, usually, it comes from metrics computation, for example, the raw value can be the mean_dice of every channel of every input image. summary_ops: expected computation operations to generate the summary report. it can be: None, "*" or list of strings, default to None. None - don't generate summary report for every expected metric_details. "*" - generate summary report for every metric_details with all the supported operations. list of strings - generate summary report for every metric_details with specified operations, they should be within list: ["mean", "median", "max", "min", "<int>percentile", "std", "notnans"]. the number in "<int>percentile" should be [0, 100], like: "15percentile". default: "90percentile". for more details, please check: https://numpy.org/doc/stable/reference/generated/numpy.nanpercentile.html. note that: for the overall summary, it computes `nanmean` of all classes for each image first, then compute summary. example of the generated summary report:: class mean median max 5percentile 95percentile notnans class0 6.0000 6.0000 7.0000 5.1000 6.9000 2.0000 class1 6.0000 6.0000 6.0000 6.0000 6.0000 1.0000 mean 6.2500 6.2500 7.0000 5.5750 6.9250 2.0000 deli: the delimiter character in the saved file, default to "," as the default output type is `csv`. to be consistent with: https://docs.python.org/3/library/csv.html#csv.Dialect.delimiter. output_type: expected output file type, supported types: ["csv"], default to "csv". """ if output_type.lower() != "csv": raise ValueError(f"unsupported output type: {output_type}.") if not os.path.exists(save_dir): os.makedirs(save_dir) if metrics is not None and len(metrics) > 0: with open(os.path.join(save_dir, "metrics.csv"), "w") as f: for k, v in metrics.items(): f.write(f"{k}{deli}{str(v)}\n") if metric_details is not None and len(metric_details) > 0: for k, v in metric_details.items(): if isinstance(v, torch.Tensor): v = v.cpu().numpy() if v.ndim == 0: # reshape to [1, 1] if no batch and class dims v = v.reshape((1, 1)) elif v.ndim == 1: # reshape to [N, 1] if no class dim v = v.reshape((-1, 1)) # add the average value of all classes to v class_labels = ["class" + str(i) for i in range(v.shape[1])] + ["mean"] v = np.concatenate([v, np.nanmean(v, axis=1, keepdims=True)], axis=1) with open(os.path.join(save_dir, f"{k}_raw.csv"), "w") as f: f.write(f"filename{deli}{deli.join(class_labels)}\n") for i, b in enumerate(v): f.write(f"{images[i] if images is not None else str(i)}{deli}{deli.join([str(c) for c in b])}\n") if summary_ops is not None: supported_ops = OrderedDict( { "mean": np.nanmean, "median": np.nanmedian, "max": np.nanmax, "min": np.nanmin, "90percentile": lambda x: np.nanpercentile(x[0], x[1]), "std": np.nanstd, "notnans": lambda x: (~np.isnan(x)).sum(), } ) ops = ensure_tuple(summary_ops) if "*" in ops: ops = tuple(supported_ops.keys()) def _compute_op(op: str, d: np.ndarray): if not op.endswith("percentile"): c_op = look_up_option(op, supported_ops) return c_op(d) threshold = int(op.split("percentile")[0]) return supported_ops["90percentile"]((d, threshold)) # type: ignore with open(os.path.join(save_dir, f"{k}_summary.csv"), "w") as f: f.write(f"class{deli}{deli.join(ops)}\n") for i, c in enumerate(np.transpose(v)): f.write(f"{class_labels[i]}{deli}{deli.join([f"{_compute_op(k, c):.4f}" for k in ops])}\n") def from_engine(keys: KeysCollection, first: bool = False): """ Utility function to simplify the `batch_transform` or `output_transform` args of ignite components when handling dictionary or list of dictionaries(for example: `engine.state.batch` or `engine.state.output`). Users only need to set the expected keys, then it will return a callable function to extract data from dictionary and construct a tuple respectively. If data is a list of dictionaries after decollating, extract expected keys and construct lists respectively, for example, if data is `[{"A": 1, "B": 2}, {"A": 3, "B": 4}]`, from_engine(["A", "B"]): `([1, 3], [2, 4])`. It can help avoid a complicated `lambda` function and make the arg of metrics more straight-forward. For example, set the first key as the prediction and the second key as label to get the expected data from `engine.state.output` for a metric:: from monai.handlers import MeanDice, from_engine metric = MeanDice( include_background=False, output_transform=from_engine(["pred", "label"]) ) Args: keys: specified keys to extract data from dictionary or decollated list of dictionaries. first: whether only extract specified keys from the first item if input data is a list of dictionaries, it's used to extract the scalar data which doesn't have batch dim and was replicated into every dictionary when decollating, like `loss`, etc. """ keys = ensure_tuple(keys) def _wrapper(data): if isinstance(data, dict): return tuple(data[k] for k in keys) if isinstance(data, list) and isinstance(data[0], dict): # if data is a list of dictionaries, extract expected keys and construct lists, # if `first=True`, only extract keys from the first item of the list ret = [data[0][k] if first else [i[k] for i in data] for k in keys] return tuple(ret) if len(ret) > 1 else ret[0] return _wrapper
# Copyright (c) MONAI Consortium # 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 collections import OrderedDict from typing import TYPE_CHECKING, Dict, Optional, Sequence, Union import numpy as np import torch from monai.config import IgniteInfo, KeysCollection, PathLike from monai.utils import ensure_tuple, look_up_option, min_version, optional_import idist, _ = optional_import("ignite", IgniteInfo.OPT_IMPORT_VERSION, min_version, "distributed") if TYPE_CHECKING: from ignite.engine import Engine else: Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") __all__ = ["stopping_fn_from_metric", "stopping_fn_from_loss", "write_metrics_reports", "from_engine"] def stopping_fn_from_metric(metric_name: str): """ Returns a stopping function for ignite.handlers.EarlyStopping using the given metric name. """ def stopping_fn(engine: Engine): return engine.state.metrics[metric_name] return stopping_fn def stopping_fn_from_loss(): """ Returns a stopping function for ignite.handlers.EarlyStopping using the loss value. """ def stopping_fn(engine: Engine): return -engine.state.output # type:ignore return stopping_fn def write_metrics_reports( save_dir: PathLike, images: Optional[Sequence[str]], metrics: Optional[Dict[str, Union[torch.Tensor, np.ndarray]]], metric_details: Optional[Dict[str, Union[torch.Tensor, np.ndarray]]], summary_ops: Optional[Union[str, Sequence[str]]], deli: str = ",", output_type: str = "csv", ): """ Utility function to write the metrics into files, contains 3 parts: 1. if `metrics` dict is not None, write overall metrics into file, every line is a metric name and value pair. 2. if `metric_details` dict is not None, write raw metric data of every image into file, every line for 1 image. 3. if `summary_ops` is not None, compute summary based on operations on `metric_details` and write to file. Args: save_dir: directory to save all the metrics reports. images: name or path of every input image corresponding to the metric_details data. if None, will use index number as the filename of every input image. metrics: a dictionary of (metric name, metric value) pairs. metric_details: a dictionary of (metric name, metric raw values) pairs, usually, it comes from metrics computation, for example, the raw value can be the mean_dice of every channel of every input image. summary_ops: expected computation operations to generate the summary report. it can be: None, "*" or list of strings, default to None. None - don't generate summary report for every expected metric_details. "*" - generate summary report for every metric_details with all the supported operations. list of strings - generate summary report for every metric_details with specified operations, they should be within list: ["mean", "median", "max", "min", "<int>percentile", "std", "notnans"]. the number in "<int>percentile" should be [0, 100], like: "15percentile". default: "90percentile". for more details, please check: https://numpy.org/doc/stable/reference/generated/numpy.nanpercentile.html. note that: for the overall summary, it computes `nanmean` of all classes for each image first, then compute summary. example of the generated summary report:: class mean median max 5percentile 95percentile notnans class0 6.0000 6.0000 7.0000 5.1000 6.9000 2.0000 class1 6.0000 6.0000 6.0000 6.0000 6.0000 1.0000 mean 6.2500 6.2500 7.0000 5.5750 6.9250 2.0000 deli: the delimiter character in the saved file, default to "," as the default output type is `csv`. to be consistent with: https://docs.python.org/3/library/csv.html#csv.Dialect.delimiter. output_type: expected output file type, supported types: ["csv"], default to "csv". """ if output_type.lower() != "csv": raise ValueError(f"unsupported output type: {output_type}.") if not os.path.exists(save_dir): os.makedirs(save_dir) if metrics is not None and len(metrics) > 0: with open(os.path.join(save_dir, "metrics.csv"), "w") as f: for k, v in metrics.items(): f.write(f"{k}{deli}{str(v)}\n") if metric_details is not None and len(metric_details) > 0: for k, v in metric_details.items(): if isinstance(v, torch.Tensor): v = v.cpu().numpy() if v.ndim == 0: # reshape to [1, 1] if no batch and class dims v = v.reshape((1, 1)) elif v.ndim == 1: # reshape to [N, 1] if no class dim v = v.reshape((-1, 1)) # add the average value of all classes to v class_labels = ["class" + str(i) for i in range(v.shape[1])] + ["mean"] v = np.concatenate([v, np.nanmean(v, axis=1, keepdims=True)], axis=1) with open(os.path.join(save_dir, f"{k}_raw.csv"), "w") as f: f.write(f"filename{deli}{deli.join(class_labels)}\n") for i, b in enumerate(v): f.write(f"{images[i] if images is not None else str(i)}{deli}{deli.join([str(c) for c in b])}\n") if summary_ops is not None: supported_ops = OrderedDict( { "mean": np.nanmean, "median": np.nanmedian, "max": np.nanmax, "min": np.nanmin, "90percentile": lambda x: np.nanpercentile(x[0], x[1]), "std": np.nanstd, "notnans": lambda x: (~np.isnan(x)).sum(), } ) ops = ensure_tuple(summary_ops) if "*" in ops: ops = tuple(supported_ops.keys()) def _compute_op(op: str, d: np.ndarray): if not op.endswith("percentile"): c_op = look_up_option(op, supported_ops) return c_op(d) threshold = int(op.split("percentile")[0]) return supported_ops["90percentile"]((d, threshold)) # type: ignore with open(os.path.join(save_dir, f"{k}_summary.csv"), "w") as f: f.write(f"class{deli}{deli.join(ops)}\n") for i, c in enumerate(np.transpose(v)): f.write(f"{class_labels[i]}{deli}{deli.join([f'{_compute_op(k, c):.4f}' for k in ops])}\n") def from_engine(keys: KeysCollection, first: bool = False): """ Utility function to simplify the `batch_transform` or `output_transform` args of ignite components when handling dictionary or list of dictionaries(for example: `engine.state.batch` or `engine.state.output`). Users only need to set the expected keys, then it will return a callable function to extract data from dictionary and construct a tuple respectively. If data is a list of dictionaries after decollating, extract expected keys and construct lists respectively, for example, if data is `[{"A": 1, "B": 2}, {"A": 3, "B": 4}]`, from_engine(["A", "B"]): `([1, 3], [2, 4])`. It can help avoid a complicated `lambda` function and make the arg of metrics more straight-forward. For example, set the first key as the prediction and the second key as label to get the expected data from `engine.state.output` for a metric:: from monai.handlers import MeanDice, from_engine metric = MeanDice( include_background=False, output_transform=from_engine(["pred", "label"]) ) Args: keys: specified keys to extract data from dictionary or decollated list of dictionaries. first: whether only extract specified keys from the first item if input data is a list of dictionaries, it's used to extract the scalar data which doesn't have batch dim and was replicated into every dictionary when decollating, like `loss`, etc. """ keys = ensure_tuple(keys) def _wrapper(data): if isinstance(data, dict): return tuple(data[k] for k in keys) if isinstance(data, list) and isinstance(data[0], dict): # if data is a list of dictionaries, extract expected keys and construct lists, # if `first=True`, only extract keys from the first item of the list ret = [data[0][k] if first else [i[k] for i in data] for k in keys] return tuple(ret) if len(ret) > 1 else ret[0] return _wrapper
import json import os import pandas as pd from dagster_dbt import dbt_cli_resource from dagster_dbt.asset_defs import load_assets_from_dbt_manifest from hacker_news_assets.resources.snowflake_io_manager import ( SHARED_SNOWFLAKE_CONF, connect_snowflake, ) from dagster import MetadataValue from dagster.utils import file_relative_path DBT_PROJECT_DIR = file_relative_path(__file__, "../../hacker_news_dbt") DBT_PROFILES_DIR = DBT_PROJECT_DIR + "/config" dbt_staging_resource = dbt_cli_resource.configured( {"profiles-dir": DBT_PROFILES_DIR, "project-dir": DBT_PROJECT_DIR, "target": "staging"} ) dbt_prod_resource = dbt_cli_resource.configured( {"profiles_dir": DBT_PROFILES_DIR, "project_dir": DBT_PROJECT_DIR, "target": "prod"} ) def asset_metadata(_context, model_info): config = dict(SHARED_SNOWFLAKE_CONF) config["schema"] = model_info["schema"] with connect_snowflake(config=config) as con: df = pd.read_sql(f"SELECT * FROM {model_info["name"]} LIMIT 5", con=con) num_rows = con.execute(f"SELECT COUNT(*) FROM {model_info["name"]}").fetchone() return {"Data sample": MetadataValue.md(df.to_markdown()), "Rows": num_rows[0]} assets = load_assets_from_dbt_manifest( json.load(open(os.path.join(DBT_PROJECT_DIR, "target", "manifest.json"))), runtime_metadata_fn=asset_metadata, io_manager_key="warehouse_io_manager", )
import json import os import pandas as pd from dagster_dbt import dbt_cli_resource from dagster_dbt.asset_defs import load_assets_from_dbt_manifest from hacker_news_assets.resources.snowflake_io_manager import ( SHARED_SNOWFLAKE_CONF, connect_snowflake, ) from dagster import MetadataValue from dagster.utils import file_relative_path DBT_PROJECT_DIR = file_relative_path(__file__, "../../hacker_news_dbt") DBT_PROFILES_DIR = DBT_PROJECT_DIR + "/config" dbt_staging_resource = dbt_cli_resource.configured( {"profiles-dir": DBT_PROFILES_DIR, "project-dir": DBT_PROJECT_DIR, "target": "staging"} ) dbt_prod_resource = dbt_cli_resource.configured( {"profiles_dir": DBT_PROFILES_DIR, "project_dir": DBT_PROJECT_DIR, "target": "prod"} ) def asset_metadata(_context, model_info): config = dict(SHARED_SNOWFLAKE_CONF) config["schema"] = model_info["schema"] with connect_snowflake(config=config) as con: df = pd.read_sql(f"SELECT * FROM {model_info['name']} LIMIT 5", con=con) num_rows = con.execute(f"SELECT COUNT(*) FROM {model_info['name']}").fetchone() return {"Data sample": MetadataValue.md(df.to_markdown()), "Rows": num_rows[0]} assets = load_assets_from_dbt_manifest( json.load(open(os.path.join(DBT_PROJECT_DIR, "target", "manifest.json"))), runtime_metadata_fn=asset_metadata, io_manager_key="warehouse_io_manager", )
import logging import os from pathlib import Path from shutil import copyfile from fashiondatasets.deepfashion1.DeepFashion1 import DeepFashion1Dataset from fashiondatasets.deepfashion2.DeepFashion2Quadruplets import DeepFashion2Quadruplets from fashiondatasets.deepfashion2.helper.pairs.deep_fashion_2_pairs_generator import DeepFashion2PairsGenerator from fashiondatasets.own.Quadruplets import Quadruplets from fashiondatasets.own.helper.mappings import preprocess_image import tensorflow as tf from fashionnets.train_jobs.settings.default_settings import base_settings from fashionscrapper.utils.io import time_logger from fashionnets.callbacks.garabe_collector.delete_checkpoints import DeleteOldModel from fashionnets.models.embedding.resnet50 import EMBEDDING_DIM from fashionnets.models.embedding.simple_cnn import SimpleCNN from fashionnets.models.layer.Augmentation import compose_augmentations from fashionnets.train_jobs.loader.path_loader import _load_dataset_base_path, _load_embedding_base_path, \ _load_centroid_base_path from fashionnets.util.io import all_paths_exist import numpy as np from fashiondatasets.utils.logger.defaultLogger import defaultLogger logger = defaultLogger("deepfashion_data_builder", level=logging.INFO) def loader_info(name, variation=""): if "deep_fashion_2" in name: return deep_fashion_2_loader_info(variation) if "deep_fashion_1" in name: return deep_fashion_1_loader_info() if "own" in name: return own_loader_info() raise Exception(f"Unknown Loader Information {name} {variation}") def own_loader_info(): return { "name": "own_256", "variation": "own_256", # "df_quad_3", "preprocess": { "commands": [ "mkdir -p ./own_256", "mv asos ./own_256", "mv hm ./own_256", "mv mango ./own_256", "mv entries.json ./own_256", "mv entries_test.json ./own_256", "mv entries_train.json ./own_256", "mv entries_validation.json ./own_256", "mv quadruplet.csv ./own_256", "mv test.csv ./own_256", "mv validation.csv ./own_256", ], "check_existence": lambda: all_paths_exist(["./own_256"]) } } # print("Warning! " * 72) # print("Dataset Loader Implement own Loader") # print("#TODO Implement") # return { # "name": "own_256", # } def deep_fashion_2_loader_info(variation): variation_commands = variation.replace("-", "_") return { "name": "deep_fashion_256", "variation": variation, # "df_quad_3", "preprocess": { "commands": [ "mkdir -p ./deep_fashion_256", "mv ./train_256 ./deep_fashion_256", "mv ./validation_256 ./deep_fashion_256", f"mv ./{variation_commands}/train ./deep_fashion_256", f"mv ./{variation_commands}/validation ./deep_fashion_256", f"rmdir ./{variation_commands}" ], "check_existence": lambda: all_paths_exist(["./deep_fashion_256"]) } } def deep_fashion_1_loader_info(): return { "name": "deep_fashion_1_256", "variation": "deepfashion1info", # "df_quad_3", "preprocess": { "commands": [ "mkdir -p ./deep_fashion_1_256", "mv splits.json ./deep_fashion_1_256", "mv val.csv ./deep_fashion_1_256", "mv cat_idx_by_name.json ./deep_fashion_1_256", "mv ids_by_cat_idx.json ./deep_fashion_1_256", "mv test.csv ./deep_fashion_1_256", "mv cat_name_by_idxs.json ./deep_fashion_1_256", "mv train.csv ./deep_fashion_1_256", "mv README.txt ./deep_fashion_1_256", "mv img_256 ./deep_fashion_1_256", "mv ./deepfashion1-info/* ./deep_fashion_1_256", "rm -rf ./deepfashion1-info" ], "check_existence": lambda: all_paths_exist(["./deep_fashion_1_256"]) } } def load_dataset_loader(**settings): ds_name = settings["dataset"]["name"] if ds_name == "own" or ds_name == "own_256": settings["dataset_hard_pairs_fn"] = build_dataset_hard_pairs_own return lambda: load_own_dataset(**settings) if ds_name == "deep_fashion_2_256": settings["dataset_hard_pairs_fn"] = build_dataset_hard_pairs_deep_fashion_2 return lambda: load_deepfashion_2(**settings) if "deep_fashion_1_256" in ds_name: settings["dataset_hard_pairs_fn"] = build_dataset_hard_pairs_deep_fashion_1 return lambda: load_deepfashion_1(**settings) raise Exception(f'Unknown Dataset {ds_name}') def _fill_ds_settings(**settings): keys = ["format", "nrows", "target_shape", "batch_size", "buffer_size"] missing_keys = list(filter(lambda k: k not in settings.keys(), keys)) assert len(missing_keys) == 0, f"Missing Keys: {missing_keys}" return { "map_full_paths": settings.get("map_full_paths", True), "validate_paths": settings.get("validate_paths", False), # "format": settings.get("format", "triplet"), # "quadruplet", # triplet # "nrows": settings.get("nrows", None), # "target_shape": settings.get("target_shape", (144, 144)), # "batch_size": settings.get("batch_size", 32), # "buffer_size": settings.get("buffer_size", 1024), "train_split": settings.get("train_split", 0.8), "preprocess_input": settings.get("preprocess_input", None) } def _print_ds_settings(verbose, **ds_settings): if verbose: header_str = "*" * 24 + " Settings " + "*" * 24 logger.debug(header_str) logger.debug("{") for k, v in ds_settings.items(): tab = " " * 8 k_str = f"{tab}'{k}':" v_str = f"'{v}'" padding_len = len(header_str) - len(k_str) - len(v_str) - len(tab) padding = max(padding_len, 0) pad_str = " " * padding logger.debug(f"{k_str}{pad_str}{v_str}") logger.debug("}") logger.debug("*" * len(header_str)) def load_deepfashion_2(**settings): logger.debug(f"Load own DeepFashion {settings["batch_size"]} Batch Size") ds_settings = _fill_ds_settings(**settings) _print_ds_settings(settings.get("verbose", False), **ds_settings) base_path = _load_dataset_base_path(**settings) datasets = DeepFashion2Quadruplets(base_path=base_path, split_suffix="_256", format=settings["format"], nrows=settings["nrows"]) \ .load_as_datasets(validate_paths=False) train_ds_info, val_ds_info = datasets["train"], datasets["validation"] train_ds, val_ds = train_ds_info["dataset"], val_ds_info["dataset"] settings["_dataset"] = settings.pop("dataset") # <- otherwise kwargs conflict 2x ds train_ds, val_ds = prepare_ds(train_ds, is_train=True, **settings), prepare_ds(val_ds, is_train=False, **settings) n_train, n_val = train_ds_info["n_items"], val_ds_info["n_items"] return { "type": "deepfashion_2", "train": train_ds, "val": val_ds, "shape": ds_settings.get("target_shape"), "n_items": { "total": n_val + n_train, "validation": n_val, "train": n_train } } @time_logger(name="DS-Loader::Load", header="Dataset-Loader", padding_length=50, logger=defaultLogger("fashiondataset_time_logger"), log_debug=False) def load_deepfashion_1(**settings): ds_settings = _fill_ds_settings(**settings) _print_ds_settings(settings.get("verbose", False), **ds_settings) base_path = _load_dataset_base_path(**settings) embedding_base_path = _load_embedding_base_path(**settings) logger.debug("load_deepfashion_1 2") if settings["is_ctl"] or settings["sampling"] == "hard": model = settings["back_bone"]["embedding_model"] assert model is not None else: model = None # back_bone dataframes = settings.get("dataframes", None) ds_loader = DeepFashion1Dataset(base_path=base_path, image_suffix="_256", model=model, nrows=settings["nrows"], augmentation=compose_augmentations()(False), generator_type=settings["generator_type"], embedding_path=embedding_base_path, batch_size=settings["batch_size"], skip_build=dataframes is not None) datasets = ds_loader.load(splits=["train", "val"], is_triplet=settings["is_triplet"], force=settings.get("ds_load_force", False), force_hard_sampling=settings["sampling"] == "hard", embedding_path=embedding_base_path, nrows=settings["nrows"], dataframes=dataframes) logger.debug("load_deepfashion_1 6") train_ds_info, val_ds_info = datasets["train"], datasets["validation"] train_ds, val_ds = train_ds_info["dataset"], val_ds_info["dataset"] settings["_dataset"] = settings.pop("dataset") # <- otherwise kwargs conflict 2x ds train_ds, val_ds = prepare_ds(train_ds, is_train=True, **settings), prepare_ds(val_ds, is_train=False, **settings) n_train, n_val = train_ds_info["n_items"], val_ds_info["n_items"] return { "type": "deepfashion_1", "train": train_ds, "val": val_ds, "shape": ds_settings.get("target_shape"), "n_items": { "total": n_val + n_train, "validation": n_val, "train": n_train } } def load_own_dataset(**settings): train_df, val_df, n_train_items, n_val_items = _load_own_dataset(load_df=True, **settings) return load_deepfashion_1(dataframes=[train_df, val_df], **settings) # ds_settings = _fill_ds_settings(**settings) # _print_ds_settings(**settings) # train_dataset, val_dataset, n_train, n_val = _load_own_dataset(**settings) # return { # "train": train_dataset, # "val": val_dataset, # "shape": ds_settings.get("target_shape"), # "n_items": { # "total": n_val + n_train, # "validation": n_val, # "train": n_train # } # } def _load_own_dataset(**settings): # logger.debug(f"Load own DS {batch_size} Batch Size") # split = train_split # settings["format"] = format # settings["batch_size"] = batch_size base_path = _load_dataset_base_path(**settings) quad = Quadruplets(base_path=base_path, split=None, map_full_paths=True, **settings) if settings.get("load_df", False): train_dataset = quad.load_as_df(split="train", **settings) # "train val_dataset = quad.load_as_df(split="validation", **settings) n_train_items, n_val_items = len(train_dataset), len(val_dataset) return train_dataset, val_dataset, n_train_items, n_val_items n_train_items, train_dataset = quad.load_as_dataset(split="train") # "train n_val_items, val_dataset = quad.load_as_dataset(split="validation") settings["_dataset"] = settings.pop("dataset") train_dataset, val_dataset = prepare_ds(train_dataset, is_train=True, **settings), \ prepare_ds(val_dataset, is_train=False, **settings) return train_dataset, val_dataset, n_train_items, n_val_items def filter_ds_not_nan(x): return not tf.reduce_any(tf.reduce_any(tf.math.is_nan(x))) def prepare_ds(dataset, batch_size, is_triplet, is_train, **settings): target_shape = settings["input_shape"] augmentation = settings.get("augmentation", None) if augmentation: augmentation = augmentation(is_train) if settings.get("verbose", False): logger.debug(f"Augmentation {augmentation}, IS_Train {is_train}") n1_sample = settings.get("n1_sample", None) generator_type = settings["generator_type"] if generator_type == "ctl": assert n1_sample, "n1_sample need to be set if ctl is used" return dataset.map(_load_image_preprocessor(target_shape=target_shape, is_triplet=is_triplet, augmentation=augmentation, generator_type=settings["generator_type"], n1_sample=n1_sample)) \ .batch(batch_size, drop_remainder=False) \ .prefetch(tf.data.AUTOTUNE) def np_load(feature_path): return np.load(feature_path).astype(np.float64) def load_npy(p): d = tf.numpy_function(np_load, [p], tf.float64) return tf.convert_to_tensor(d, dtype=tf.float64) def _load_image_preprocessor(is_triplet, target_shape, generator_type, n1_sample=None, preprocess_img=None, augmentation=None): prep_image = preprocess_image(target_shape, preprocess_img=preprocess_img, augmentation=augmentation) assert not preprocess_img, "None of the two Datasets needs further Preprocessing!" if "ctl" == generator_type: if is_triplet: # Tripl -> A::jpg_path Cp::npy_path Cn::npy_path return lambda a, p_ctl, n_ctl: (prep_image(a), load_npy(p_ctl), load_npy(n_ctl)) else: # Quad -> A::jpg_path N1::npy_path Cp::npy_path C_n1::npy_path C_n2::npy_path if n1_sample == "centroid": return lambda a, n1, p_ctl, n1_ctl, n2_ctl: (prep_image(a), load_npy(p_ctl), load_npy(n1_ctl), load_npy(n2_ctl), ) raise Exception("Quadtruplet / Triplet-net currently only supports N1 to be of C_N1") # if n1_sample == "instance": # print("INSTANCE BASED\n" * 5) # return lambda a, n1, p_ctl, n1_ctl, n2_ctl: (prep_image(a), # load_npy(p_ctl), # prep_image(n1), # load_npy(n2_ctl), # ) if "apn" == generator_type: if is_triplet: return lambda a, p, n: (prep_image(a), prep_image(p), prep_image(n)) else: return lambda a, p, n1, n2: (prep_image(a), prep_image(p), prep_image(n1), prep_image(n2)) def build_dataset_hard_pairs_deep_fashion_2(model, job_settings): if Path("./deep_fashion_256/train/quadruplets.csv").exists(): Path("./deep_fashion_256/train/quadruplets.csv").unlink() embedding_model = model.siamese_network.feature_extractor generator = DeepFashion2PairsGenerator(r"./deep_fashion_256", embedding_model, split_suffix="_256", number_possibilites=256) apnn = generator.build_anchor_positive_negative1_negative2("train") DeepFashion2PairsGenerator.save_pairs_to_csv(generator.base_path, "train", apnn) return load_dataset_loader(**job_settings)() def build_dataset_hard_pairs_deep_fashion_1(model, job_settings, init_epoch, build_frequency, move=True): job_settings["force_ctl"] = init_epoch > 0 if init_epoch == 0 and not job_settings["is_ctl"] and not job_settings["sampling"] == "hard": print("build_dataset_hard_pairs_deep_fashion_1", 2) return load_dataset_loader(**job_settings)() result = __download_hard_pairs(job_settings, init_epoch, build_frequency) if result is not None: return result if (init_epoch % build_frequency) == 0: return __build_move_deepfashion_hard_pairs(model, job_settings, init_epoch, move=move) raise Exception("Could not Download Train.csv.") def build_dataset_hard_pairs_own(model, job_settings, init_epoch, build_frequency): job_settings["force_ctl"] = init_epoch > 0 if init_epoch == 0 and not job_settings["is_ctl"] and not job_settings["sampling"] == "hard": return load_dataset_loader(**job_settings)() result = __download_hard_pairs(job_settings, init_epoch, build_frequency, ds_name="own_256") if result is not None: return result if (init_epoch % build_frequency) == 0: return __build_move_deepfashion_hard_pairs(model, job_settings, init_epoch, ds_name="own_256") raise Exception("Could not Download Train.csv.") def __build_move_deepfashion_hard_pairs(model, job_settings, init_epoch, ds_name="deep_fashion_1_256", move=True): if Path(f"./{ds_name}/train.csv").exists(): Path(f"./{ds_name}/train.csv").unlink() # train_ctl, val_ctl # if model: # embedding_model = model.siamese_network.feature_extractor # else: # embedding_model = None embedding_base_path = _load_embedding_base_path(**job_settings) if job_settings["is_ctl"] or \ job_settings["sampling"] == "hard" else None if embedding_base_path and job_settings["force_ctl"] or job_settings["sampling"] == "hard": DeleteOldModel.delete_path(embedding_base_path) DeleteOldModel.delete_path(_load_centroid_base_path(**job_settings)) job_settings["ds_load_force"] = True datasets = load_dataset_loader(**job_settings)() src = f"./{ds_name}/train.csv" dst = f"./{ds_name}/train_{init_epoch:04d}.csv" copyfile(src, dst) result_uploader = job_settings["environment"].webdav if move: result_uploader.move(dst, _async=False) return datasets def __download_hard_pairs(job_settings, init_epoch, build_frequency, ds_name="deep_fashion_1_256"): if Path(f"./{ds_name}/train.csv").exists(): Path(f"./{ds_name}/train.csv").unlink() last_epoch = total_epochs(init_epoch, build_frequency) - build_frequency dst_name = f"train_{last_epoch:04d}.csv" remote = job_settings["environment"].webdav csv = filter(lambda d: dst_name in d, remote.list(remote.base_path)) csv = list(csv) if not len(csv) == 1: return None csv = csv[0] csv_path = os.path.join(remote.base_path, csv) _callback = lambda: logger.info(f"{csv} downloaded!") remote.download(csv_path, f"./{ds_name}/train.csv", callback=_callback, _async=False) return load_dataset_loader(**job_settings)() def total_epochs(init_epoch, build_frequency): max_epochs = init_epoch + build_frequency if max_epochs % build_frequency == 0: return max_epochs dif = max_epochs % build_frequency return max_epochs - dif
import logging import os from pathlib import Path from shutil import copyfile from fashiondatasets.deepfashion1.DeepFashion1 import DeepFashion1Dataset from fashiondatasets.deepfashion2.DeepFashion2Quadruplets import DeepFashion2Quadruplets from fashiondatasets.deepfashion2.helper.pairs.deep_fashion_2_pairs_generator import DeepFashion2PairsGenerator from fashiondatasets.own.Quadruplets import Quadruplets from fashiondatasets.own.helper.mappings import preprocess_image import tensorflow as tf from fashionnets.train_jobs.settings.default_settings import base_settings from fashionscrapper.utils.io import time_logger from fashionnets.callbacks.garabe_collector.delete_checkpoints import DeleteOldModel from fashionnets.models.embedding.resnet50 import EMBEDDING_DIM from fashionnets.models.embedding.simple_cnn import SimpleCNN from fashionnets.models.layer.Augmentation import compose_augmentations from fashionnets.train_jobs.loader.path_loader import _load_dataset_base_path, _load_embedding_base_path, \ _load_centroid_base_path from fashionnets.util.io import all_paths_exist import numpy as np from fashiondatasets.utils.logger.defaultLogger import defaultLogger logger = defaultLogger("deepfashion_data_builder", level=logging.INFO) def loader_info(name, variation=""): if "deep_fashion_2" in name: return deep_fashion_2_loader_info(variation) if "deep_fashion_1" in name: return deep_fashion_1_loader_info() if "own" in name: return own_loader_info() raise Exception(f"Unknown Loader Information {name} {variation}") def own_loader_info(): return { "name": "own_256", "variation": "own_256", # "df_quad_3", "preprocess": { "commands": [ "mkdir -p ./own_256", "mv asos ./own_256", "mv hm ./own_256", "mv mango ./own_256", "mv entries.json ./own_256", "mv entries_test.json ./own_256", "mv entries_train.json ./own_256", "mv entries_validation.json ./own_256", "mv quadruplet.csv ./own_256", "mv test.csv ./own_256", "mv validation.csv ./own_256", ], "check_existence": lambda: all_paths_exist(["./own_256"]) } } # print("Warning! " * 72) # print("Dataset Loader Implement own Loader") # print("#TODO Implement") # return { # "name": "own_256", # } def deep_fashion_2_loader_info(variation): variation_commands = variation.replace("-", "_") return { "name": "deep_fashion_256", "variation": variation, # "df_quad_3", "preprocess": { "commands": [ "mkdir -p ./deep_fashion_256", "mv ./train_256 ./deep_fashion_256", "mv ./validation_256 ./deep_fashion_256", f"mv ./{variation_commands}/train ./deep_fashion_256", f"mv ./{variation_commands}/validation ./deep_fashion_256", f"rmdir ./{variation_commands}" ], "check_existence": lambda: all_paths_exist(["./deep_fashion_256"]) } } def deep_fashion_1_loader_info(): return { "name": "deep_fashion_1_256", "variation": "deepfashion1info", # "df_quad_3", "preprocess": { "commands": [ "mkdir -p ./deep_fashion_1_256", "mv splits.json ./deep_fashion_1_256", "mv val.csv ./deep_fashion_1_256", "mv cat_idx_by_name.json ./deep_fashion_1_256", "mv ids_by_cat_idx.json ./deep_fashion_1_256", "mv test.csv ./deep_fashion_1_256", "mv cat_name_by_idxs.json ./deep_fashion_1_256", "mv train.csv ./deep_fashion_1_256", "mv README.txt ./deep_fashion_1_256", "mv img_256 ./deep_fashion_1_256", "mv ./deepfashion1-info/* ./deep_fashion_1_256", "rm -rf ./deepfashion1-info" ], "check_existence": lambda: all_paths_exist(["./deep_fashion_1_256"]) } } def load_dataset_loader(**settings): ds_name = settings["dataset"]["name"] if ds_name == "own" or ds_name == "own_256": settings["dataset_hard_pairs_fn"] = build_dataset_hard_pairs_own return lambda: load_own_dataset(**settings) if ds_name == "deep_fashion_2_256": settings["dataset_hard_pairs_fn"] = build_dataset_hard_pairs_deep_fashion_2 return lambda: load_deepfashion_2(**settings) if "deep_fashion_1_256" in ds_name: settings["dataset_hard_pairs_fn"] = build_dataset_hard_pairs_deep_fashion_1 return lambda: load_deepfashion_1(**settings) raise Exception(f'Unknown Dataset {ds_name}') def _fill_ds_settings(**settings): keys = ["format", "nrows", "target_shape", "batch_size", "buffer_size"] missing_keys = list(filter(lambda k: k not in settings.keys(), keys)) assert len(missing_keys) == 0, f"Missing Keys: {missing_keys}" return { "map_full_paths": settings.get("map_full_paths", True), "validate_paths": settings.get("validate_paths", False), # "format": settings.get("format", "triplet"), # "quadruplet", # triplet # "nrows": settings.get("nrows", None), # "target_shape": settings.get("target_shape", (144, 144)), # "batch_size": settings.get("batch_size", 32), # "buffer_size": settings.get("buffer_size", 1024), "train_split": settings.get("train_split", 0.8), "preprocess_input": settings.get("preprocess_input", None) } def _print_ds_settings(verbose, **ds_settings): if verbose: header_str = "*" * 24 + " Settings " + "*" * 24 logger.debug(header_str) logger.debug("{") for k, v in ds_settings.items(): tab = " " * 8 k_str = f"{tab}'{k}':" v_str = f"'{v}'" padding_len = len(header_str) - len(k_str) - len(v_str) - len(tab) padding = max(padding_len, 0) pad_str = " " * padding logger.debug(f"{k_str}{pad_str}{v_str}") logger.debug("}") logger.debug("*" * len(header_str)) def load_deepfashion_2(**settings): logger.debug(f"Load own DeepFashion {settings['batch_size']} Batch Size") ds_settings = _fill_ds_settings(**settings) _print_ds_settings(settings.get("verbose", False), **ds_settings) base_path = _load_dataset_base_path(**settings) datasets = DeepFashion2Quadruplets(base_path=base_path, split_suffix="_256", format=settings["format"], nrows=settings["nrows"]) \ .load_as_datasets(validate_paths=False) train_ds_info, val_ds_info = datasets["train"], datasets["validation"] train_ds, val_ds = train_ds_info["dataset"], val_ds_info["dataset"] settings["_dataset"] = settings.pop("dataset") # <- otherwise kwargs conflict 2x ds train_ds, val_ds = prepare_ds(train_ds, is_train=True, **settings), prepare_ds(val_ds, is_train=False, **settings) n_train, n_val = train_ds_info["n_items"], val_ds_info["n_items"] return { "type": "deepfashion_2", "train": train_ds, "val": val_ds, "shape": ds_settings.get("target_shape"), "n_items": { "total": n_val + n_train, "validation": n_val, "train": n_train } } @time_logger(name="DS-Loader::Load", header="Dataset-Loader", padding_length=50, logger=defaultLogger("fashiondataset_time_logger"), log_debug=False) def load_deepfashion_1(**settings): ds_settings = _fill_ds_settings(**settings) _print_ds_settings(settings.get("verbose", False), **ds_settings) base_path = _load_dataset_base_path(**settings) embedding_base_path = _load_embedding_base_path(**settings) logger.debug("load_deepfashion_1 2") if settings["is_ctl"] or settings["sampling"] == "hard": model = settings["back_bone"]["embedding_model"] assert model is not None else: model = None # back_bone dataframes = settings.get("dataframes", None) ds_loader = DeepFashion1Dataset(base_path=base_path, image_suffix="_256", model=model, nrows=settings["nrows"], augmentation=compose_augmentations()(False), generator_type=settings["generator_type"], embedding_path=embedding_base_path, batch_size=settings["batch_size"], skip_build=dataframes is not None) datasets = ds_loader.load(splits=["train", "val"], is_triplet=settings["is_triplet"], force=settings.get("ds_load_force", False), force_hard_sampling=settings["sampling"] == "hard", embedding_path=embedding_base_path, nrows=settings["nrows"], dataframes=dataframes) logger.debug("load_deepfashion_1 6") train_ds_info, val_ds_info = datasets["train"], datasets["validation"] train_ds, val_ds = train_ds_info["dataset"], val_ds_info["dataset"] settings["_dataset"] = settings.pop("dataset") # <- otherwise kwargs conflict 2x ds train_ds, val_ds = prepare_ds(train_ds, is_train=True, **settings), prepare_ds(val_ds, is_train=False, **settings) n_train, n_val = train_ds_info["n_items"], val_ds_info["n_items"] return { "type": "deepfashion_1", "train": train_ds, "val": val_ds, "shape": ds_settings.get("target_shape"), "n_items": { "total": n_val + n_train, "validation": n_val, "train": n_train } } def load_own_dataset(**settings): train_df, val_df, n_train_items, n_val_items = _load_own_dataset(load_df=True, **settings) return load_deepfashion_1(dataframes=[train_df, val_df], **settings) # ds_settings = _fill_ds_settings(**settings) # _print_ds_settings(**settings) # train_dataset, val_dataset, n_train, n_val = _load_own_dataset(**settings) # return { # "train": train_dataset, # "val": val_dataset, # "shape": ds_settings.get("target_shape"), # "n_items": { # "total": n_val + n_train, # "validation": n_val, # "train": n_train # } # } def _load_own_dataset(**settings): # logger.debug(f"Load own DS {batch_size} Batch Size") # split = train_split # settings["format"] = format # settings["batch_size"] = batch_size base_path = _load_dataset_base_path(**settings) quad = Quadruplets(base_path=base_path, split=None, map_full_paths=True, **settings) if settings.get("load_df", False): train_dataset = quad.load_as_df(split="train", **settings) # "train val_dataset = quad.load_as_df(split="validation", **settings) n_train_items, n_val_items = len(train_dataset), len(val_dataset) return train_dataset, val_dataset, n_train_items, n_val_items n_train_items, train_dataset = quad.load_as_dataset(split="train") # "train n_val_items, val_dataset = quad.load_as_dataset(split="validation") settings["_dataset"] = settings.pop("dataset") train_dataset, val_dataset = prepare_ds(train_dataset, is_train=True, **settings), \ prepare_ds(val_dataset, is_train=False, **settings) return train_dataset, val_dataset, n_train_items, n_val_items def filter_ds_not_nan(x): return not tf.reduce_any(tf.reduce_any(tf.math.is_nan(x))) def prepare_ds(dataset, batch_size, is_triplet, is_train, **settings): target_shape = settings["input_shape"] augmentation = settings.get("augmentation", None) if augmentation: augmentation = augmentation(is_train) if settings.get("verbose", False): logger.debug(f"Augmentation {augmentation}, IS_Train {is_train}") n1_sample = settings.get("n1_sample", None) generator_type = settings["generator_type"] if generator_type == "ctl": assert n1_sample, "n1_sample need to be set if ctl is used" return dataset.map(_load_image_preprocessor(target_shape=target_shape, is_triplet=is_triplet, augmentation=augmentation, generator_type=settings["generator_type"], n1_sample=n1_sample)) \ .batch(batch_size, drop_remainder=False) \ .prefetch(tf.data.AUTOTUNE) def np_load(feature_path): return np.load(feature_path).astype(np.float64) def load_npy(p): d = tf.numpy_function(np_load, [p], tf.float64) return tf.convert_to_tensor(d, dtype=tf.float64) def _load_image_preprocessor(is_triplet, target_shape, generator_type, n1_sample=None, preprocess_img=None, augmentation=None): prep_image = preprocess_image(target_shape, preprocess_img=preprocess_img, augmentation=augmentation) assert not preprocess_img, "None of the two Datasets needs further Preprocessing!" if "ctl" == generator_type: if is_triplet: # Tripl -> A::jpg_path Cp::npy_path Cn::npy_path return lambda a, p_ctl, n_ctl: (prep_image(a), load_npy(p_ctl), load_npy(n_ctl)) else: # Quad -> A::jpg_path N1::npy_path Cp::npy_path C_n1::npy_path C_n2::npy_path if n1_sample == "centroid": return lambda a, n1, p_ctl, n1_ctl, n2_ctl: (prep_image(a), load_npy(p_ctl), load_npy(n1_ctl), load_npy(n2_ctl), ) raise Exception("Quadtruplet / Triplet-net currently only supports N1 to be of C_N1") # if n1_sample == "instance": # print("INSTANCE BASED\n" * 5) # return lambda a, n1, p_ctl, n1_ctl, n2_ctl: (prep_image(a), # load_npy(p_ctl), # prep_image(n1), # load_npy(n2_ctl), # ) if "apn" == generator_type: if is_triplet: return lambda a, p, n: (prep_image(a), prep_image(p), prep_image(n)) else: return lambda a, p, n1, n2: (prep_image(a), prep_image(p), prep_image(n1), prep_image(n2)) def build_dataset_hard_pairs_deep_fashion_2(model, job_settings): if Path("./deep_fashion_256/train/quadruplets.csv").exists(): Path("./deep_fashion_256/train/quadruplets.csv").unlink() embedding_model = model.siamese_network.feature_extractor generator = DeepFashion2PairsGenerator(r"./deep_fashion_256", embedding_model, split_suffix="_256", number_possibilites=256) apnn = generator.build_anchor_positive_negative1_negative2("train") DeepFashion2PairsGenerator.save_pairs_to_csv(generator.base_path, "train", apnn) return load_dataset_loader(**job_settings)() def build_dataset_hard_pairs_deep_fashion_1(model, job_settings, init_epoch, build_frequency, move=True): job_settings["force_ctl"] = init_epoch > 0 if init_epoch == 0 and not job_settings["is_ctl"] and not job_settings["sampling"] == "hard": print("build_dataset_hard_pairs_deep_fashion_1", 2) return load_dataset_loader(**job_settings)() result = __download_hard_pairs(job_settings, init_epoch, build_frequency) if result is not None: return result if (init_epoch % build_frequency) == 0: return __build_move_deepfashion_hard_pairs(model, job_settings, init_epoch, move=move) raise Exception("Could not Download Train.csv.") def build_dataset_hard_pairs_own(model, job_settings, init_epoch, build_frequency): job_settings["force_ctl"] = init_epoch > 0 if init_epoch == 0 and not job_settings["is_ctl"] and not job_settings["sampling"] == "hard": return load_dataset_loader(**job_settings)() result = __download_hard_pairs(job_settings, init_epoch, build_frequency, ds_name="own_256") if result is not None: return result if (init_epoch % build_frequency) == 0: return __build_move_deepfashion_hard_pairs(model, job_settings, init_epoch, ds_name="own_256") raise Exception("Could not Download Train.csv.") def __build_move_deepfashion_hard_pairs(model, job_settings, init_epoch, ds_name="deep_fashion_1_256", move=True): if Path(f"./{ds_name}/train.csv").exists(): Path(f"./{ds_name}/train.csv").unlink() # train_ctl, val_ctl # if model: # embedding_model = model.siamese_network.feature_extractor # else: # embedding_model = None embedding_base_path = _load_embedding_base_path(**job_settings) if job_settings["is_ctl"] or \ job_settings["sampling"] == "hard" else None if embedding_base_path and job_settings["force_ctl"] or job_settings["sampling"] == "hard": DeleteOldModel.delete_path(embedding_base_path) DeleteOldModel.delete_path(_load_centroid_base_path(**job_settings)) job_settings["ds_load_force"] = True datasets = load_dataset_loader(**job_settings)() src = f"./{ds_name}/train.csv" dst = f"./{ds_name}/train_{init_epoch:04d}.csv" copyfile(src, dst) result_uploader = job_settings["environment"].webdav if move: result_uploader.move(dst, _async=False) return datasets def __download_hard_pairs(job_settings, init_epoch, build_frequency, ds_name="deep_fashion_1_256"): if Path(f"./{ds_name}/train.csv").exists(): Path(f"./{ds_name}/train.csv").unlink() last_epoch = total_epochs(init_epoch, build_frequency) - build_frequency dst_name = f"train_{last_epoch:04d}.csv" remote = job_settings["environment"].webdav csv = filter(lambda d: dst_name in d, remote.list(remote.base_path)) csv = list(csv) if not len(csv) == 1: return None csv = csv[0] csv_path = os.path.join(remote.base_path, csv) _callback = lambda: logger.info(f"{csv} downloaded!") remote.download(csv_path, f"./{ds_name}/train.csv", callback=_callback, _async=False) return load_dataset_loader(**job_settings)() def total_epochs(init_epoch, build_frequency): max_epochs = init_epoch + build_frequency if max_epochs % build_frequency == 0: return max_epochs dif = max_epochs % build_frequency return max_epochs - dif
from InquirerPy import prompt, inquirer from InquirerPy.separator import Separator from ...flair_management.skin_manager.skin_manager import Skin_Manager from .weapon_config_prompts import Prompts class Randomizer_Editor: ''' this flows through 4 stages weapon type -> weapon -> skins -> skin preferences ''' @staticmethod def randomizer_entrypoint(): weapon_data, skin_data, skin_choice, weapon_choice, weapon_skin_data = Prompts.select_weapon_type(change_all=True,weights=False, change_all_method=Randomizer_Editor.change_all_skins_by_weapon) while weapon_data is not None: weapon_data['skins'][skin_choice] = Randomizer_Editor.set_skin_preferences(weapon_skin_data) Skin_Manager.modify_skin_data(skin_data) weapon_data, skin_data, skin_choice, weapon_choice, weapon_skin_data = Prompts.select_skin(skin_data, weapon_choice, change_all=True, weights=False, change_all_method=Randomizer_Editor.change_all_skins_by_weapon) @staticmethod def change_all_skins_by_weapon(weapon_data,disable): for uuid, skin in weapon_data["skins"].items(): if not "Standard" in skin["display_name"]: skin["enabled"] = not disable # disable all levels except for max level for uuid, level in skin["levels"].items(): level["enabled"] = False skin['levels'][list(skin['levels'].keys())[-1]]['enabled'] = True for uuid, chroma in skin["chromas"].items(): chroma["enabled"] = not disable # make sure theres still at least 1 chroma enabled (on disable) enabled_chromas = [chroma for _, chroma in skin['chromas'].items() if chroma['enabled']] if len(enabled_chromas) == 0: skin['chromas'][list(skin['chromas'].keys())[-1]]['enabled'] = True @staticmethod def set_skin_preferences(skin_data): preferences = [ {'name': 'skin enabled', 'value': 'skin_enabled', 'enabled': skin_data['enabled']}, Separator(), ] # append skin levels if len(skin_data['levels']) > 1: levels = [{'name': f"[LEVEL] {data["display_name"]}", 'value': f"level_{uuid}", 'enabled': data['enabled']} for uuid, data in skin_data['levels'].items()] preferences.extend(levels) preferences.append(Separator()) # append chromas if len(skin_data['chromas']) > 1: chromas = [ {'name': f"[CHROMA] {data["display_name"]}", 'value': f"chroma_{uuid}", 'enabled': data['enabled']} for uuid, data in skin_data['chromas'].items()] preferences.extend(chromas) # preferences prompt skin_preferences = inquirer.checkbox( message=f"Modificar configurações de skin para: {skin_data["display_name"]}", choices=preferences, instruction='(space - toggle, enter - finish)', pointer='>', enabled_symbol='√ ', disabled_symbol='x ' ).execute() # clear out all old preferences skin_data['enabled'] = False if len(skin_data['levels']) > 1: for uuid, level in skin_data['levels'].items(): level['enabled'] = False if len(skin_data['chromas']) > 1: for uuid, chroma in skin_data['chromas'].items(): chroma['enabled'] = False # update skin data with new preferences for preference in skin_preferences: if "level_" in preference or "chroma_" in preference: if "level_" in preference: skin_data['levels'][preference[len('level_'):]]['enabled'] = True if "chroma_" in preference: skin_data['chromas'][preference[len('chroma_'):]]['enabled'] = True if preference == "skin_enabled": skin_data['enabled'] = True # check if any have 0 chromas/levels enabled then enable the top level enabled_levels = [ level for _, level in skin_data['levels'].items() if level['enabled']] enabled_chromas = [ chroma for _, chroma in skin_data['chromas'].items() if chroma['enabled']] if len(enabled_levels) == 0: skin_data['levels'][list( skin_data['levels'].keys())[-1]]['enabled'] = True if len(enabled_chromas) == 0: skin_data['chromas'][list( skin_data['chromas'].keys())[-1]]['enabled'] = True return skin_data
from InquirerPy import prompt, inquirer from InquirerPy.separator import Separator from ...flair_management.skin_manager.skin_manager import Skin_Manager from .weapon_config_prompts import Prompts class Randomizer_Editor: ''' this flows through 4 stages weapon type -> weapon -> skins -> skin preferences ''' @staticmethod def randomizer_entrypoint(): weapon_data, skin_data, skin_choice, weapon_choice, weapon_skin_data = Prompts.select_weapon_type(change_all=True,weights=False, change_all_method=Randomizer_Editor.change_all_skins_by_weapon) while weapon_data is not None: weapon_data['skins'][skin_choice] = Randomizer_Editor.set_skin_preferences(weapon_skin_data) Skin_Manager.modify_skin_data(skin_data) weapon_data, skin_data, skin_choice, weapon_choice, weapon_skin_data = Prompts.select_skin(skin_data, weapon_choice, change_all=True, weights=False, change_all_method=Randomizer_Editor.change_all_skins_by_weapon) @staticmethod def change_all_skins_by_weapon(weapon_data,disable): for uuid, skin in weapon_data["skins"].items(): if not "Standard" in skin["display_name"]: skin["enabled"] = not disable # disable all levels except for max level for uuid, level in skin["levels"].items(): level["enabled"] = False skin['levels'][list(skin['levels'].keys())[-1]]['enabled'] = True for uuid, chroma in skin["chromas"].items(): chroma["enabled"] = not disable # make sure theres still at least 1 chroma enabled (on disable) enabled_chromas = [chroma for _, chroma in skin['chromas'].items() if chroma['enabled']] if len(enabled_chromas) == 0: skin['chromas'][list(skin['chromas'].keys())[-1]]['enabled'] = True @staticmethod def set_skin_preferences(skin_data): preferences = [ {'name': 'skin enabled', 'value': 'skin_enabled', 'enabled': skin_data['enabled']}, Separator(), ] # append skin levels if len(skin_data['levels']) > 1: levels = [{'name': f"[LEVEL] {data['display_name']}", 'value': f"level_{uuid}", 'enabled': data['enabled']} for uuid, data in skin_data['levels'].items()] preferences.extend(levels) preferences.append(Separator()) # append chromas if len(skin_data['chromas']) > 1: chromas = [ {'name': f"[CHROMA] {data['display_name']}", 'value': f"chroma_{uuid}", 'enabled': data['enabled']} for uuid, data in skin_data['chromas'].items()] preferences.extend(chromas) # preferences prompt skin_preferences = inquirer.checkbox( message=f"Modificar configurações de skin para: {skin_data['display_name']}", choices=preferences, instruction='(space - toggle, enter - finish)', pointer='>', enabled_symbol='√ ', disabled_symbol='x ' ).execute() # clear out all old preferences skin_data['enabled'] = False if len(skin_data['levels']) > 1: for uuid, level in skin_data['levels'].items(): level['enabled'] = False if len(skin_data['chromas']) > 1: for uuid, chroma in skin_data['chromas'].items(): chroma['enabled'] = False # update skin data with new preferences for preference in skin_preferences: if "level_" in preference or "chroma_" in preference: if "level_" in preference: skin_data['levels'][preference[len('level_'):]]['enabled'] = True if "chroma_" in preference: skin_data['chromas'][preference[len('chroma_'):]]['enabled'] = True if preference == "skin_enabled": skin_data['enabled'] = True # check if any have 0 chromas/levels enabled then enable the top level enabled_levels = [ level for _, level in skin_data['levels'].items() if level['enabled']] enabled_chromas = [ chroma for _, chroma in skin_data['chromas'].items() if chroma['enabled']] if len(enabled_levels) == 0: skin_data['levels'][list( skin_data['levels'].keys())[-1]]['enabled'] = True if len(enabled_chromas) == 0: skin_data['chromas'][list( skin_data['chromas'].keys())[-1]]['enabled'] = True return skin_data
""" Core dataset implementation. BaseCore may be inherhit to create a new DatasetCore """ import os from abc import ABC, abstractmethod import cv2 import numpy as np import torch from scipy import io from experimenting.utils import Skeleton from ..utils import get_file_paths from .base import BaseCore class DHP19Core(BaseCore): """ DHP19 dataset core class. It provides implementation to load frames, heatmaps, 2D joints, 3D joints """ MOVEMENTS_PER_SESSION = {1: 8, 2: 6, 3: 6, 4: 6, 5: 7} MAX_WIDTH = 346 MAX_HEIGHT = 260 N_JOINTS = 13 N_MOVEMENTS = 33 DEFAULT_TEST_SUBJECTS = [1, 2, 3, 4, 5] DEFAULT_TEST_VIEW = [1, 2] TORSO_LENGTH = 453.5242317 def __init__( self, name, data_dir, cams, movements, joints_dir, n_classes, n_joints, partition, n_channels, test_subjects=None, test_cams=None, avg_torso_length=TORSO_LENGTH, *args, **kwargs, ): super(DHP19Core, self).__init__(name, partition) self.file_paths = DHP19Core._get_file_paths_with_cam_and_mov( data_dir, cams, movements ) self.in_shape = (DHP19Core.MAX_HEIGHT, DHP19Core.MAX_WIDTH) self.n_channels = n_channels self.n_joints = n_joints self.avg_torso_length = avg_torso_length self.classification_labels = [ DHP19Core.get_label_from_filename(x_path) for x_path in self.file_paths ] self.frames_info = [DHP19Core.get_frame_info(x) for x in self.file_paths] self.joints = self._retrieve_data_files(joints_dir, f"_2dhm.npz") # retrieve content of files self.test_subjects = test_subjects if test_cams is None: self.test_cams = DHP19Core.DEFAULT_TEST_VIEW else: self.test_cams = test_cams @staticmethod def get_standard_path(subject, session, movement, frame, cam, postfix=""): return "S{}_session_{}_mov_{}_frame_{}_cam_{}{}.npy".format( subject, session, movement, frame, cam, postfix ) @staticmethod def load_frame(path): ext = os.path.splitext(path)[1] if ext == ".mat": x = DHP19Core._load_matlab_frame(path) elif ext == ".npy": x = np.load(path, allow_pickle=True) / 255.0 if len(x.shape) == 2: x = np.expand_dims(x, -1) return x @staticmethod def _load_matlab_frame(path): """ Matlab files contain voxelgrid frames and must be loaded properly. Information is contained respectiely in attributes: V1n, V2n, V3n, V4n Examples: S1_.mat """ info = DHP19Core.get_frame_info(path) x = np.swapaxes(io.loadmat(path)[f'V{info['cam'] + 1}n'], 0, 1) return x def get_frame_from_id(self, idx): return DHP19Core.load_frame(self.file_paths[idx]) def get_cam_from_id(self, idx): filepath = self.file_paths[idx] info = DHP19Core.get_frame_info(filepath) return info["cam"] def get_label_from_id(self, idx): return self.classification_labels[idx] def get_joint_from_id(self, idx): try: joints_file = np.load(self.joints[idx]) except IOError: return 0 xyz = joints_file["xyz"].swapaxes(0, 1) intrinsic_matrix = torch.tensor(joints_file["camera"]) extrinsic_matrix = torch.tensor(joints_file["M"]) return Skeleton(xyz), intrinsic_matrix, extrinsic_matrix def get_heatmap_from_id(self, idx): hm_path = self.heatmaps[idx] return load_heatmap(hm_path, self.N_JOINTS) @staticmethod def _get_file_paths_with_cam_and_mov(data_dir, cams=None, movs=None): if cams is None: cams = [3] file_paths = np.array(get_file_paths(data_dir, extensions=[".npy", ".mat"])) cam_mask = np.zeros(len(file_paths)) for c in cams: cam_mask += [f"cam_{c}" in x for x in file_paths] file_paths = file_paths[cam_mask > 0] if movs is not None: mov_mask = [ DHP19Core.get_label_from_filename(x) in movs for x in file_paths ] file_paths = file_paths[mov_mask] return file_paths @staticmethod def get_frame_info(filename): filename = os.path.splitext(os.path.basename(filename))[0] result = { "subject": int( filename[filename.find("S") + 1 : filename.find("S") + 4].split("_")[0] ), "session": int(DHP19Core._get_info_from_string(filename, "session")), "mov": int(DHP19Core._get_info_from_string(filename, "mov")), "cam": int(DHP19Core._get_info_from_string(filename, "cam")), "frame": DHP19Core._get_info_from_string(filename, "frame"), } return result def get_test_subjects(self): return self.test_subjects def get_test_view(self): return self.test_cams @staticmethod def _get_info_from_string(filename, info, split_symbol="_"): return int(filename[filename.find(info) :].split(split_symbol)[1]) @staticmethod def get_label_from_filename(filepath) -> int: """Given the filepath, return the correspondent movement label (range [0, 32]) Args: filepath (str): frame absolute filepath Returns: Frame label Examples: >>> DHP19Core.get_label_from_filename("S1_session_2_mov_1_frame_249_cam_2.npy") 8 """ label = 0 info = DHP19Core.get_frame_info(filepath) for i in range(1, info["session"]): label += DHP19Core.MOVEMENTS_PER_SESSION[i] return label + info["mov"] - 1 # label in range [0, max_label) def _retrieve_data_files(self, labels_dir, suffix): labels_hm = [ os.path.join( labels_dir, os.path.basename(x).split(".")[0] + suffix ) for x in self.file_paths ] return labels_hm def train_partition_function(self, x): return self.frames_info[x]['subject'] not in self.test_subjects and self.frames_info[x]['cam'] not in self.test_cams def load_heatmap(path, n_joints): joints = np.load(path) h, w = joints.shape y = np.zeros((h, w, n_joints)) for joint_id in range(1, n_joints + 1): heatmap = (joints == joint_id).astype('float') if heatmap.sum() > 0: y[:, :, joint_id - 1] = decay_heatmap(heatmap) return y def decay_heatmap(heatmap, sigma2=10): """ Args heatmap : WxH matrix to decay sigma2 : (Default value = 1) Returns Heatmap obtained by gaussian-blurring the input """ heatmap = cv2.GaussianBlur(heatmap, (0, 0), sigma2) heatmap /= np.max(heatmap) # keep the max to 1 return heatmap
""" Core dataset implementation. BaseCore may be inherhit to create a new DatasetCore """ import os from abc import ABC, abstractmethod import cv2 import numpy as np import torch from scipy import io from experimenting.utils import Skeleton from ..utils import get_file_paths from .base import BaseCore class DHP19Core(BaseCore): """ DHP19 dataset core class. It provides implementation to load frames, heatmaps, 2D joints, 3D joints """ MOVEMENTS_PER_SESSION = {1: 8, 2: 6, 3: 6, 4: 6, 5: 7} MAX_WIDTH = 346 MAX_HEIGHT = 260 N_JOINTS = 13 N_MOVEMENTS = 33 DEFAULT_TEST_SUBJECTS = [1, 2, 3, 4, 5] DEFAULT_TEST_VIEW = [1, 2] TORSO_LENGTH = 453.5242317 def __init__( self, name, data_dir, cams, movements, joints_dir, n_classes, n_joints, partition, n_channels, test_subjects=None, test_cams=None, avg_torso_length=TORSO_LENGTH, *args, **kwargs, ): super(DHP19Core, self).__init__(name, partition) self.file_paths = DHP19Core._get_file_paths_with_cam_and_mov( data_dir, cams, movements ) self.in_shape = (DHP19Core.MAX_HEIGHT, DHP19Core.MAX_WIDTH) self.n_channels = n_channels self.n_joints = n_joints self.avg_torso_length = avg_torso_length self.classification_labels = [ DHP19Core.get_label_from_filename(x_path) for x_path in self.file_paths ] self.frames_info = [DHP19Core.get_frame_info(x) for x in self.file_paths] self.joints = self._retrieve_data_files(joints_dir, f"_2dhm.npz") # retrieve content of files self.test_subjects = test_subjects if test_cams is None: self.test_cams = DHP19Core.DEFAULT_TEST_VIEW else: self.test_cams = test_cams @staticmethod def get_standard_path(subject, session, movement, frame, cam, postfix=""): return "S{}_session_{}_mov_{}_frame_{}_cam_{}{}.npy".format( subject, session, movement, frame, cam, postfix ) @staticmethod def load_frame(path): ext = os.path.splitext(path)[1] if ext == ".mat": x = DHP19Core._load_matlab_frame(path) elif ext == ".npy": x = np.load(path, allow_pickle=True) / 255.0 if len(x.shape) == 2: x = np.expand_dims(x, -1) return x @staticmethod def _load_matlab_frame(path): """ Matlab files contain voxelgrid frames and must be loaded properly. Information is contained respectiely in attributes: V1n, V2n, V3n, V4n Examples: S1_.mat """ info = DHP19Core.get_frame_info(path) x = np.swapaxes(io.loadmat(path)[f'V{info["cam"] + 1}n'], 0, 1) return x def get_frame_from_id(self, idx): return DHP19Core.load_frame(self.file_paths[idx]) def get_cam_from_id(self, idx): filepath = self.file_paths[idx] info = DHP19Core.get_frame_info(filepath) return info["cam"] def get_label_from_id(self, idx): return self.classification_labels[idx] def get_joint_from_id(self, idx): try: joints_file = np.load(self.joints[idx]) except IOError: return 0 xyz = joints_file["xyz"].swapaxes(0, 1) intrinsic_matrix = torch.tensor(joints_file["camera"]) extrinsic_matrix = torch.tensor(joints_file["M"]) return Skeleton(xyz), intrinsic_matrix, extrinsic_matrix def get_heatmap_from_id(self, idx): hm_path = self.heatmaps[idx] return load_heatmap(hm_path, self.N_JOINTS) @staticmethod def _get_file_paths_with_cam_and_mov(data_dir, cams=None, movs=None): if cams is None: cams = [3] file_paths = np.array(get_file_paths(data_dir, extensions=[".npy", ".mat"])) cam_mask = np.zeros(len(file_paths)) for c in cams: cam_mask += [f"cam_{c}" in x for x in file_paths] file_paths = file_paths[cam_mask > 0] if movs is not None: mov_mask = [ DHP19Core.get_label_from_filename(x) in movs for x in file_paths ] file_paths = file_paths[mov_mask] return file_paths @staticmethod def get_frame_info(filename): filename = os.path.splitext(os.path.basename(filename))[0] result = { "subject": int( filename[filename.find("S") + 1 : filename.find("S") + 4].split("_")[0] ), "session": int(DHP19Core._get_info_from_string(filename, "session")), "mov": int(DHP19Core._get_info_from_string(filename, "mov")), "cam": int(DHP19Core._get_info_from_string(filename, "cam")), "frame": DHP19Core._get_info_from_string(filename, "frame"), } return result def get_test_subjects(self): return self.test_subjects def get_test_view(self): return self.test_cams @staticmethod def _get_info_from_string(filename, info, split_symbol="_"): return int(filename[filename.find(info) :].split(split_symbol)[1]) @staticmethod def get_label_from_filename(filepath) -> int: """Given the filepath, return the correspondent movement label (range [0, 32]) Args: filepath (str): frame absolute filepath Returns: Frame label Examples: >>> DHP19Core.get_label_from_filename("S1_session_2_mov_1_frame_249_cam_2.npy") 8 """ label = 0 info = DHP19Core.get_frame_info(filepath) for i in range(1, info["session"]): label += DHP19Core.MOVEMENTS_PER_SESSION[i] return label + info["mov"] - 1 # label in range [0, max_label) def _retrieve_data_files(self, labels_dir, suffix): labels_hm = [ os.path.join( labels_dir, os.path.basename(x).split(".")[0] + suffix ) for x in self.file_paths ] return labels_hm def train_partition_function(self, x): return self.frames_info[x]['subject'] not in self.test_subjects and self.frames_info[x]['cam'] not in self.test_cams def load_heatmap(path, n_joints): joints = np.load(path) h, w = joints.shape y = np.zeros((h, w, n_joints)) for joint_id in range(1, n_joints + 1): heatmap = (joints == joint_id).astype('float') if heatmap.sum() > 0: y[:, :, joint_id - 1] = decay_heatmap(heatmap) return y def decay_heatmap(heatmap, sigma2=10): """ Args heatmap : WxH matrix to decay sigma2 : (Default value = 1) Returns Heatmap obtained by gaussian-blurring the input """ heatmap = cv2.GaussianBlur(heatmap, (0, 0), sigma2) heatmap /= np.max(heatmap) # keep the max to 1 return heatmap
import sys from datetime import datetime import kfp import kfp.dsl as dsl from kfp.components import create_component_from_func import requests # (1) import the user-defined Python function from # download_file.py # ignore linting; separated from other imports for clarity from download_file import download # noqa I100 # (2) create factory for imported function from user-provided input: # - container/base image (optional) # - packages to install (optional) # Perhaps use generated output_component_file to avoid the need for source code parsing? # https://kubeflow-pipelines.readthedocs.io/en/latest/source/kfp.components.html#kfp.components.create_component_from_func download_op = create_component_from_func( func=download, base_image=None, packages_to_install=['requests'], output_component_file='download_file_component.yaml') # # create pipeline # @dsl.pipeline( name='download file pipeline', description='An example pipeline that downloads a file.' ) def download_pipeline(url): # Passes a pipeline parameterto the `download_op` factory # function. download_task = download_op(url) # noqa F841 # # housekeeping # def get_user_auth_session_cookie(url, username=None, password=None) -> dict: # Return data structure auth_info = { 'endpoint': url, # KF endpoint URL 'endpoint_response_url': None, # KF redirect URL, if applicable 'endpoint_secured': False, # True if KF is secured [by dex] 'authservice_session_cookie': None # Set if KF secured & user auth'd } # Obtain redirect URL get_response = requests.get(url) auth_info['endpoint_response_url'] = get_response.url # If KF redirected to '/dex/auth/local?req=REQ_VALUE' # try to authenticate using the provided credentials if 'dex/auth' in get_response.url: auth_info['endpoint_secured'] = True # KF is secured # Try to authenticate user by sending a request to the # Dex redirect URL session = requests.Session() session.post(get_response.url, data={'login': username, 'password': password}) # Capture authservice_session cookie, if one was returned # in the response cookie_auth_key = 'authservice_session' cookie_auth_value = session.cookies.get(cookie_auth_key) if cookie_auth_value: auth_info['authservice_session_cookie'] = \ f"{cookie_auth_key}={cookie_auth_value}" return auth_info if __name__ == "__main__": if len(sys.argv) < 2: print(f'Invocation {sys.argv[0]} <KFP-API-URL> [<namespace>] [<kf-uid> <kf-password>]') sys.exit(1) print('Trying to authenticate with Kubeflow server ...') auth_endpoint = sys.argv[1].rstrip('/').replace('/pipeline', '') namespace = None id = None password = None if len(sys.argv) == 2: namespace = sys.argv[2] elif len(sys.argv) == 4: namespace = None id = sys.argv[2] password = sys.argv[3] elif len(sys.argv) == 5: namespace = sys.argv[2] id = sys.argv[3] password = sys.argv[4] # authenticate auth_info = get_user_auth_session_cookie(auth_endpoint, id, password) if auth_info['endpoint_secured'] and \ auth_info['authservice_session_cookie'] is None: print('Authentication failed. Check your credentials.') sys.exit(1) auth_cookie = auth_info['authservice_session_cookie'] client = kfp.Client(host=sys.argv[1], cookies=auth_cookie) run_name = f'download-file-python-func-run-{datetime.now().strftime('%m%d%H%M%S')}' print(f'Creating run {run_name} from pipeline...') # Specify argument values for your pipeline run. arguments = {'url': 'https://raw.githubusercontent.com/ptitzler/kfp-component-tests/' 'main/download-file/tests/file-in.txt'} # Compile, upload, and submit this pipeline for execution. run = client.create_run_from_pipeline_func(download_pipeline, run_name=run_name, namespace=namespace, arguments=arguments) print(run)
import sys from datetime import datetime import kfp import kfp.dsl as dsl from kfp.components import create_component_from_func import requests # (1) import the user-defined Python function from # download_file.py # ignore linting; separated from other imports for clarity from download_file import download # noqa I100 # (2) create factory for imported function from user-provided input: # - container/base image (optional) # - packages to install (optional) # Perhaps use generated output_component_file to avoid the need for source code parsing? # https://kubeflow-pipelines.readthedocs.io/en/latest/source/kfp.components.html#kfp.components.create_component_from_func download_op = create_component_from_func( func=download, base_image=None, packages_to_install=['requests'], output_component_file='download_file_component.yaml') # # create pipeline # @dsl.pipeline( name='download file pipeline', description='An example pipeline that downloads a file.' ) def download_pipeline(url): # Passes a pipeline parameterto the `download_op` factory # function. download_task = download_op(url) # noqa F841 # # housekeeping # def get_user_auth_session_cookie(url, username=None, password=None) -> dict: # Return data structure auth_info = { 'endpoint': url, # KF endpoint URL 'endpoint_response_url': None, # KF redirect URL, if applicable 'endpoint_secured': False, # True if KF is secured [by dex] 'authservice_session_cookie': None # Set if KF secured & user auth'd } # Obtain redirect URL get_response = requests.get(url) auth_info['endpoint_response_url'] = get_response.url # If KF redirected to '/dex/auth/local?req=REQ_VALUE' # try to authenticate using the provided credentials if 'dex/auth' in get_response.url: auth_info['endpoint_secured'] = True # KF is secured # Try to authenticate user by sending a request to the # Dex redirect URL session = requests.Session() session.post(get_response.url, data={'login': username, 'password': password}) # Capture authservice_session cookie, if one was returned # in the response cookie_auth_key = 'authservice_session' cookie_auth_value = session.cookies.get(cookie_auth_key) if cookie_auth_value: auth_info['authservice_session_cookie'] = \ f"{cookie_auth_key}={cookie_auth_value}" return auth_info if __name__ == "__main__": if len(sys.argv) < 2: print(f'Invocation {sys.argv[0]} <KFP-API-URL> [<namespace>] [<kf-uid> <kf-password>]') sys.exit(1) print('Trying to authenticate with Kubeflow server ...') auth_endpoint = sys.argv[1].rstrip('/').replace('/pipeline', '') namespace = None id = None password = None if len(sys.argv) == 2: namespace = sys.argv[2] elif len(sys.argv) == 4: namespace = None id = sys.argv[2] password = sys.argv[3] elif len(sys.argv) == 5: namespace = sys.argv[2] id = sys.argv[3] password = sys.argv[4] # authenticate auth_info = get_user_auth_session_cookie(auth_endpoint, id, password) if auth_info['endpoint_secured'] and \ auth_info['authservice_session_cookie'] is None: print('Authentication failed. Check your credentials.') sys.exit(1) auth_cookie = auth_info['authservice_session_cookie'] client = kfp.Client(host=sys.argv[1], cookies=auth_cookie) run_name = f'download-file-python-func-run-{datetime.now().strftime("%m%d%H%M%S")}' print(f'Creating run {run_name} from pipeline...') # Specify argument values for your pipeline run. arguments = {'url': 'https://raw.githubusercontent.com/ptitzler/kfp-component-tests/' 'main/download-file/tests/file-in.txt'} # Compile, upload, and submit this pipeline for execution. run = client.create_run_from_pipeline_func(download_pipeline, run_name=run_name, namespace=namespace, arguments=arguments) print(run)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import configparser import json import os import re import sys if os.name != "nt": from blessings import Terminal OS_IS_NT = False TERM = Terminal() else: OS_IS_NT = True from instabot_py import InstaBot python_version_test = f"If you are reading this error, you are not running Python 3.6 or greater. Check 'python --version' or 'python3 --version'." config_location = "instabot.config.ini" config = configparser.ConfigParser() def ask_question(_q, label="", tip="", prepend="", header=" Instabot Configurator "): if OS_IS_NT: print(f"\n") print(f"=============\n{label}") print(f"{tip}") return input(f"{_q} : {prepend}") with TERM.fullscreen(): with TERM.location(int((TERM.width / 2) - (len(header) / 2)), 1): print(TERM.white_on_blue(header)) with TERM.location(1, TERM.height - 5): print(TERM.italic(TERM.white_on_black(label))) with TERM.location( int((TERM.width / 2) - (len(tip) / 2)), int((TERM.height / 2) + 3) ): print(TERM.italic(TERM.white_on_black(tip))) with TERM.location( int(TERM.width - ((TERM.width / 2) + (len(_q) / 2))), int(TERM.height / 2) - 2, ): print(TERM.bold(_q)) with TERM.location( int((TERM.width / 2) - (len(_q) / 2)), int(TERM.height / 2) + 1 ): print("-" * len(_q), end="") with TERM.location( int(TERM.width - ((TERM.width / 2) + (len(_q) / 2))), int((TERM.height / 2)) ): print(prepend, end="") _input = input() TERM.clear_eos() return _input def setupinteractive(config, config_location="instabot.config.ini"): if os.path.isfile(config_location): config.read(config_location) elif os.path.isfile("config.ini"): config.read("config.ini") configsettings = { "password": "req", "like_per_day": "opt", "comments_per_day": "opt", "max_like_for_one_tag": "opt", "follow_per_day": "opt", "follow_time": "opt", "unfollow_per_day": "opt", "tag_list": "opt", "unfollow_selebgram": "opt", "unfollow_probably_fake": "opt", "unfollow_inactive": "opt", "unfollow_recent_feed": "opt", } configsettings_labels = { "like_per_day": "The bot will adjust its speed to LIKE this amount of posts in a 24H period (max ~1200, new accounts accounts ~250)", "follow_per_day": "The bot will adjust its speed to FOLLOW this amount of accounts in a 24H period (max ~290)", "follow_time": "After following an account, the bot will wait this amount of SECONDS before it checks if an account should be unfollowed (if it meets the unfollow criteria)", "unfollow_per_day": "The bot will adjust its speed to UNFOLLOW this amount of accounts in a 24H period (max ~250)", "unfollow_selebgram": "(Unfollow Criteria) Unfollow accounts that are possibly celebrities/influencers (True/False)", "unfollow_probably_fake": "(Unfollow Criteria) Unfollow accounts w/ few followers and high following (True/False)", "unfollow_inactive": "(Unfollow Criteria) Unfollow accounts that seem to be inactive (True/False)", "unfollow_recent_feed": "Fetches acounts from your recent feed and queues them for unfollow if they meet the (Unfollow Criteria) (True/False)", } config["DEFAULT"] = { "username": "none", "password": "none", "like_per_day": 709, "comments_per_day": 31, "max_like_for_one_tag": 36, "follow_per_day": 260, "follow_time": 36000, "unfollow_per_day": 247, "unfollow_break_min": 3, "unfollow_break_max": 17, "log_mod": 0, "proxy": "", "unfollow_selebgram": "False", "unfollow_probably_fake": "True", "unfollow_inactive": "True", "unfollow_recent_feed": "False", } config["DEFAULT"]["comment_list"] = json.dumps( [ ["this", "the", "your"], ["photo", "picture", "pic", "shot", "snapshot"], ["is", "looks", "feels", "is really"], [ "great", "super", "good", "very good", "good", "wow", "WOW", "cool", "GREAT", "magnificent", "magical", "very cool", "stylish", "beautiful", "so beautiful", "so stylish", "so professional", "lovely", "so lovely", "very lovely", "glorious", "so glorious", "very glorious", "adorable", "excellent", "amazing", ], [".", "..", "...", "!", "!!", "!!!"], ] ) config["DEFAULT"]["tag_list"] = json.dumps( ["follow4follow", "f4f", "cute", "l:212999109", "entekeralam", "godsowncountry", "mallureposts", "romanticmalayalam", "motionpicture", "kiduvibesonly", "inspirationalquotes", "braanthan", "positive", "malayalam", "lovemalayalam", "crazymalayalam", "mallutraveller", "romanticsongs", "malayalamquotes", "moodygramskerala", "typogram", "malayalamcinema", "varietymedia", "malayalammedia", "malayalamstatus", "whatsappstatus", "malayalamsongs", "malayalamlovequotes", "malayalamtypography", "mallugram", "motionattraction", "typographyinspired", "imalayali", "kannurdiaries", "haztorobo", "trandez_f_kerla1", "maharashtra_clickers", "otheryouphotography", "nashik#gujjus", "gujjugram", "kutch", "shoutouter", "gujjujalso", "gujjuquotes", "gujjurocks", "freak_of_kerala", "gujaratiwedding", "gujrati", "ahmedabad_instagram", "mahesana", "kathiyawadi", "botad", "shout_outshoutouts_", "rajkot_diaries", "navsari", "bhuro", "sayings", "gujjuthings", "gujarat", "gujjugotada", "ahmedabad", "chhel6abilo", "gappa"] ) config["DEFAULT"]["tag_blacklist"] = json.dumps(["rain", "thunderstorm"]) config["DEFAULT"]["unwanted_username_list"] = json.dumps( [ "second", "stuff", "art", "project", "love", "life", "food", "blog", "free", "keren", "photo", "graphy", "indo", "travel", "art", "shop", "store", "sex", "toko", "jual", "online", "murah", "jam", "kaos", "case", "baju", "fashion", "corp", "tas", "butik", "grosir", "karpet", "sosis", "salon", "skin", "care", "cloth", "tech", "rental", "kamera", "beauty", "express", "kredit", "collection", "impor", "preloved", "follow", "follower", "gain", ".id", "_id", "bags", ] ) config["DEFAULT"]["unfollow_whitelist"] = json.dumps( ["example_user_1", "example_user_2"] ) confusername = None while confusername is None or len(confusername) < 3: confusername = str( ask_question( "Please enter the username you wish to configure:", prepend="@", tip="Your username is NOT your email or your phone number!", ) ) confusername.lower() if confusername[0] == "@": confusername = confusername[1:] # if confusername is None or len(confusername) < 3: # print("This field is required.") if confusername in config: # print("User already configured. Modifying...") existing_user = True else: config.add_section(confusername) existing_user = False config[confusername]["username"] = confusername # print(" >>> TIP: Press Enter to skip and set default values") for setting, reqset in configsettings.items(): requiredset = None if existing_user: prompt_text = f"Press Enter for previous value: " section = confusername else: prompt_text = f"Press Enter for default: " section = "DEFAULT" while requiredset is None: if reqset is "req": confvar = ask_question( f"Enter value for '{setting}':", tip="This field is required" ) if confvar == "" or len(confvar) < 3: print("This field is required") else: config[confusername][setting] = str(confvar) requiredset = "done" else: if setting == "tag_list": confvar = ask_question( "Enter tags (or skip to defaults):", tip="Enter the hashtags you would like to target separated with commas", label="Example: follow4follow, instagood, f2f, instalifo", ) else: if setting in configsettings_labels: if OS_IS_NT: _label = f"{setting} : {configsettings_labels[setting]}" else: _label = f"{TERM.underline(setting)} : {configsettings_labels[setting]}" else: _label = "" confvar = ask_question( f"Enter value for '{setting}':", label=_label, tip=f"{prompt_text}{config[section][setting]}", ) if setting == "tag_list" and confvar != "": confvar = re.sub(r"\s+", "", confvar) confvar = re.sub(r"#", "", confvar) tags_list = confvar.split(",") config[confusername][setting] = str(json.dumps(tags_list)) elif confvar == "": # print('Entering default: '+ config[section][setting]) if setting != "tag_list": config[confusername][setting] = config[section][setting] else: config[confusername][setting] = str(confvar) requiredset = "done" print("\nWriting to file...") with open(config_location, "w") as configfile: config.write(configfile) print("Config updated! Re-run script to login.") exit() def interactive(askusername=None, loaded_with_argv=False): if not os.path.isfile(config_location) and not os.path.isfile("config.ini"): overwrite_answer = None while overwrite_answer not in ("yes", "no", "n", "y"): overwrite_answer = ask_question( "Config file does not exist. Would you like to setup now? (yes/no): " ) overwrite_answer = overwrite_answer.lower() if overwrite_answer == "no" or overwrite_answer == "n": exit() setupinteractive(config, config_location) if os.path.isfile(config_location): config.read(config_location) elif os.path.isfile("config.ini"): config.read("config.ini") while askusername is None: askusername = ask_question( "Please enter your username:", tip='To change user settings, type "config"', header=" Instabot Login", prepend="@", ) askusername = askusername.lower() if len(askusername) < 3: askusername = None if askusername[0] == "@": askusername = askusername[1:] if askusername == "config": setupinteractive(config, config_location) elif askusername in config: print(f" Loading settings for {askusername}!") if os.path.isfile(config_location): print(f" Config: {os.path.abspath(config_location)} ") else: print(f" Config: {os.path.abspath("config.ini")} ") if loaded_with_argv is False: print( f" (Tip: Log in directly by running 'instabot-py {askusername}')'" ) else: if "yes" in ask_question( "Could not find user in settings. Would you like to add now? (yes/no): " ): setupinteractive(config, config_location) else: exit() print("\n ______Starting bot_____") configdict = dict(config.items(askusername)) for _setting, _value in configdict.items(): try: if "{" in _value or "[" in _value: json.loads(_value) configdict[_setting] = json.loads(_value) else: raise ValueError except ValueError: if _value.isdigit() is True: configdict[_setting] = int(_value) if _value.lower == "true": configdict[_setting] = True if _value.lower == "false": configdict[_setting] = False if _value.lower == "none": configdict[_setting] = None pass configdict["login"] = configdict.pop("username") return configdict def main(): if len(sys.argv) > 1: param = sys.argv[1].lower() if param == "--": configdict = {} else: configdict = interactive(param, loaded_with_argv=True) else: configdict = interactive() bot = InstaBot(**configdict) bot.mainloop() if __name__ == "__main__": main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import configparser import json import os import re import sys if os.name != "nt": from blessings import Terminal OS_IS_NT = False TERM = Terminal() else: OS_IS_NT = True from instabot_py import InstaBot python_version_test = f"If you are reading this error, you are not running Python 3.6 or greater. Check 'python --version' or 'python3 --version'." config_location = "instabot.config.ini" config = configparser.ConfigParser() def ask_question(_q, label="", tip="", prepend="", header=" Instabot Configurator "): if OS_IS_NT: print(f"\n") print(f"=============\n{label}") print(f"{tip}") return input(f"{_q} : {prepend}") with TERM.fullscreen(): with TERM.location(int((TERM.width / 2) - (len(header) / 2)), 1): print(TERM.white_on_blue(header)) with TERM.location(1, TERM.height - 5): print(TERM.italic(TERM.white_on_black(label))) with TERM.location( int((TERM.width / 2) - (len(tip) / 2)), int((TERM.height / 2) + 3) ): print(TERM.italic(TERM.white_on_black(tip))) with TERM.location( int(TERM.width - ((TERM.width / 2) + (len(_q) / 2))), int(TERM.height / 2) - 2, ): print(TERM.bold(_q)) with TERM.location( int((TERM.width / 2) - (len(_q) / 2)), int(TERM.height / 2) + 1 ): print("-" * len(_q), end="") with TERM.location( int(TERM.width - ((TERM.width / 2) + (len(_q) / 2))), int((TERM.height / 2)) ): print(prepend, end="") _input = input() TERM.clear_eos() return _input def setupinteractive(config, config_location="instabot.config.ini"): if os.path.isfile(config_location): config.read(config_location) elif os.path.isfile("config.ini"): config.read("config.ini") configsettings = { "password": "req", "like_per_day": "opt", "comments_per_day": "opt", "max_like_for_one_tag": "opt", "follow_per_day": "opt", "follow_time": "opt", "unfollow_per_day": "opt", "tag_list": "opt", "unfollow_selebgram": "opt", "unfollow_probably_fake": "opt", "unfollow_inactive": "opt", "unfollow_recent_feed": "opt", } configsettings_labels = { "like_per_day": "The bot will adjust its speed to LIKE this amount of posts in a 24H period (max ~1200, new accounts accounts ~250)", "follow_per_day": "The bot will adjust its speed to FOLLOW this amount of accounts in a 24H period (max ~290)", "follow_time": "After following an account, the bot will wait this amount of SECONDS before it checks if an account should be unfollowed (if it meets the unfollow criteria)", "unfollow_per_day": "The bot will adjust its speed to UNFOLLOW this amount of accounts in a 24H period (max ~250)", "unfollow_selebgram": "(Unfollow Criteria) Unfollow accounts that are possibly celebrities/influencers (True/False)", "unfollow_probably_fake": "(Unfollow Criteria) Unfollow accounts w/ few followers and high following (True/False)", "unfollow_inactive": "(Unfollow Criteria) Unfollow accounts that seem to be inactive (True/False)", "unfollow_recent_feed": "Fetches acounts from your recent feed and queues them for unfollow if they meet the (Unfollow Criteria) (True/False)", } config["DEFAULT"] = { "username": "none", "password": "none", "like_per_day": 709, "comments_per_day": 31, "max_like_for_one_tag": 36, "follow_per_day": 260, "follow_time": 36000, "unfollow_per_day": 247, "unfollow_break_min": 3, "unfollow_break_max": 17, "log_mod": 0, "proxy": "", "unfollow_selebgram": "False", "unfollow_probably_fake": "True", "unfollow_inactive": "True", "unfollow_recent_feed": "False", } config["DEFAULT"]["comment_list"] = json.dumps( [ ["this", "the", "your"], ["photo", "picture", "pic", "shot", "snapshot"], ["is", "looks", "feels", "is really"], [ "great", "super", "good", "very good", "good", "wow", "WOW", "cool", "GREAT", "magnificent", "magical", "very cool", "stylish", "beautiful", "so beautiful", "so stylish", "so professional", "lovely", "so lovely", "very lovely", "glorious", "so glorious", "very glorious", "adorable", "excellent", "amazing", ], [".", "..", "...", "!", "!!", "!!!"], ] ) config["DEFAULT"]["tag_list"] = json.dumps( ["follow4follow", "f4f", "cute", "l:212999109", "entekeralam", "godsowncountry", "mallureposts", "romanticmalayalam", "motionpicture", "kiduvibesonly", "inspirationalquotes", "braanthan", "positive", "malayalam", "lovemalayalam", "crazymalayalam", "mallutraveller", "romanticsongs", "malayalamquotes", "moodygramskerala", "typogram", "malayalamcinema", "varietymedia", "malayalammedia", "malayalamstatus", "whatsappstatus", "malayalamsongs", "malayalamlovequotes", "malayalamtypography", "mallugram", "motionattraction", "typographyinspired", "imalayali", "kannurdiaries", "haztorobo", "trandez_f_kerla1", "maharashtra_clickers", "otheryouphotography", "nashik#gujjus", "gujjugram", "kutch", "shoutouter", "gujjujalso", "gujjuquotes", "gujjurocks", "freak_of_kerala", "gujaratiwedding", "gujrati", "ahmedabad_instagram", "mahesana", "kathiyawadi", "botad", "shout_outshoutouts_", "rajkot_diaries", "navsari", "bhuro", "sayings", "gujjuthings", "gujarat", "gujjugotada", "ahmedabad", "chhel6abilo", "gappa"] ) config["DEFAULT"]["tag_blacklist"] = json.dumps(["rain", "thunderstorm"]) config["DEFAULT"]["unwanted_username_list"] = json.dumps( [ "second", "stuff", "art", "project", "love", "life", "food", "blog", "free", "keren", "photo", "graphy", "indo", "travel", "art", "shop", "store", "sex", "toko", "jual", "online", "murah", "jam", "kaos", "case", "baju", "fashion", "corp", "tas", "butik", "grosir", "karpet", "sosis", "salon", "skin", "care", "cloth", "tech", "rental", "kamera", "beauty", "express", "kredit", "collection", "impor", "preloved", "follow", "follower", "gain", ".id", "_id", "bags", ] ) config["DEFAULT"]["unfollow_whitelist"] = json.dumps( ["example_user_1", "example_user_2"] ) confusername = None while confusername is None or len(confusername) < 3: confusername = str( ask_question( "Please enter the username you wish to configure:", prepend="@", tip="Your username is NOT your email or your phone number!", ) ) confusername.lower() if confusername[0] == "@": confusername = confusername[1:] # if confusername is None or len(confusername) < 3: # print("This field is required.") if confusername in config: # print("User already configured. Modifying...") existing_user = True else: config.add_section(confusername) existing_user = False config[confusername]["username"] = confusername # print(" >>> TIP: Press Enter to skip and set default values") for setting, reqset in configsettings.items(): requiredset = None if existing_user: prompt_text = f"Press Enter for previous value: " section = confusername else: prompt_text = f"Press Enter for default: " section = "DEFAULT" while requiredset is None: if reqset is "req": confvar = ask_question( f"Enter value for '{setting}':", tip="This field is required" ) if confvar == "" or len(confvar) < 3: print("This field is required") else: config[confusername][setting] = str(confvar) requiredset = "done" else: if setting == "tag_list": confvar = ask_question( "Enter tags (or skip to defaults):", tip="Enter the hashtags you would like to target separated with commas", label="Example: follow4follow, instagood, f2f, instalifo", ) else: if setting in configsettings_labels: if OS_IS_NT: _label = f"{setting} : {configsettings_labels[setting]}" else: _label = f"{TERM.underline(setting)} : {configsettings_labels[setting]}" else: _label = "" confvar = ask_question( f"Enter value for '{setting}':", label=_label, tip=f"{prompt_text}{config[section][setting]}", ) if setting == "tag_list" and confvar != "": confvar = re.sub(r"\s+", "", confvar) confvar = re.sub(r"#", "", confvar) tags_list = confvar.split(",") config[confusername][setting] = str(json.dumps(tags_list)) elif confvar == "": # print('Entering default: '+ config[section][setting]) if setting != "tag_list": config[confusername][setting] = config[section][setting] else: config[confusername][setting] = str(confvar) requiredset = "done" print("\nWriting to file...") with open(config_location, "w") as configfile: config.write(configfile) print("Config updated! Re-run script to login.") exit() def interactive(askusername=None, loaded_with_argv=False): if not os.path.isfile(config_location) and not os.path.isfile("config.ini"): overwrite_answer = None while overwrite_answer not in ("yes", "no", "n", "y"): overwrite_answer = ask_question( "Config file does not exist. Would you like to setup now? (yes/no): " ) overwrite_answer = overwrite_answer.lower() if overwrite_answer == "no" or overwrite_answer == "n": exit() setupinteractive(config, config_location) if os.path.isfile(config_location): config.read(config_location) elif os.path.isfile("config.ini"): config.read("config.ini") while askusername is None: askusername = ask_question( "Please enter your username:", tip='To change user settings, type "config"', header=" Instabot Login", prepend="@", ) askusername = askusername.lower() if len(askusername) < 3: askusername = None if askusername[0] == "@": askusername = askusername[1:] if askusername == "config": setupinteractive(config, config_location) elif askusername in config: print(f" Loading settings for {askusername}!") if os.path.isfile(config_location): print(f" Config: {os.path.abspath(config_location)} ") else: print(f" Config: {os.path.abspath('config.ini')} ") if loaded_with_argv is False: print( f" (Tip: Log in directly by running 'instabot-py {askusername}')'" ) else: if "yes" in ask_question( "Could not find user in settings. Would you like to add now? (yes/no): " ): setupinteractive(config, config_location) else: exit() print("\n ______Starting bot_____") configdict = dict(config.items(askusername)) for _setting, _value in configdict.items(): try: if "{" in _value or "[" in _value: json.loads(_value) configdict[_setting] = json.loads(_value) else: raise ValueError except ValueError: if _value.isdigit() is True: configdict[_setting] = int(_value) if _value.lower == "true": configdict[_setting] = True if _value.lower == "false": configdict[_setting] = False if _value.lower == "none": configdict[_setting] = None pass configdict["login"] = configdict.pop("username") return configdict def main(): if len(sys.argv) > 1: param = sys.argv[1].lower() if param == "--": configdict = {} else: configdict = interactive(param, loaded_with_argv=True) else: configdict = interactive() bot = InstaBot(**configdict) bot.mainloop() if __name__ == "__main__": main()
# # SymbiYosys (sby) -- Front-end for Yosys-based formal verification flows # # Copyright (C) 2016 Claire Xenia Wolf <claire@yosyshq.com> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # import re, os, getopt from types import SimpleNamespace from sby_core import SbyProc def run(mode, task, engine_idx, engine): random_seed = None opts, solver_args = getopt.getopt(engine[1:], "", ["seed="]) if len(solver_args) == 0: task.error("Missing solver command.") for o, a in opts: if o == "--seed": random_seed = a else: task.error("Unexpected BTOR engine options.") if solver_args[0] == "btormc": solver_cmd = "" if random_seed: solver_cmd += f"BTORSEED={random_seed} " solver_cmd += task.exe_paths["btormc"] + f""" --stop-first {0 if mode == "cover" else 1} -v 1 -kmax {task.opt_depth - 1}""" if task.opt_skip is not None: solver_cmd += f" -kmin {task.opt_skip}" solver_cmd += " ".join([""] + solver_args[1:]) elif solver_args[0] == "pono": if random_seed: task.error("Setting the random seed is not available for the pono solver.") solver_cmd = task.exe_paths["pono"] + f" --witness -v 1 -e bmc -k {task.opt_depth - 1}" else: task.error(f"Invalid solver command {solver_args[0]}.") common_state = SimpleNamespace() common_state.solver_status = None common_state.produced_cex = 0 common_state.expected_cex = 1 common_state.wit_file = None common_state.assert_fail = False common_state.produced_traces = [] common_state.print_traces_max = 5 common_state.running_procs = 0 def print_traces_and_terminate(): if mode == "cover": if common_state.assert_fail: proc_status = "FAIL" elif common_state.expected_cex == 0: proc_status = "pass" elif common_state.solver_status == "sat": proc_status = "pass" elif common_state.solver_status == "unsat": proc_status = "FAIL" else: task.error(f"engine_{engine_idx}: Engine terminated without status.") else: if common_state.expected_cex == 0: proc_status = "pass" elif common_state.solver_status == "sat": proc_status = "FAIL" elif common_state.solver_status == "unsat": proc_status = "pass" else: task.error(f"engine_{engine_idx}: Engine terminated without status.") task.update_status(proc_status.upper()) task.log(f"engine_{engine_idx}: Status returned by engine: {proc_status}") task.summary.append(f"""engine_{engine_idx} ({" ".join(engine)}) returned {proc_status}""") if len(common_state.produced_traces) == 0: task.log(f"""engine_{engine_idx}: Engine did not produce a{" counter" if mode != "cover" else "n "}example.""") elif len(common_state.produced_traces) <= common_state.print_traces_max: task.summary.extend(common_state.produced_traces) else: task.summary.extend(common_state.produced_traces[:common_state.print_traces_max]) excess_traces = len(common_state.produced_traces) - common_state.print_traces_max task.summary.append(f"""and {excess_traces} further trace{"s" if excess_traces > 1 else ""}""") task.terminate() if mode == "cover": def output_callback2(line): match = re.search(r"Assert failed in test", line) if match: common_state.assert_fail = True return line else: def output_callback2(line): return line def make_exit_callback(suffix): def exit_callback2(retcode): assert retcode == 0 vcdpath = f"{task.workdir}/engine_{engine_idx}/trace{suffix}.vcd" if os.path.exists(vcdpath): common_state.produced_traces.append(f"""{"" if mode == "cover" else "counterexample "}trace: {vcdpath}""") common_state.running_procs -= 1 if (common_state.running_procs == 0): print_traces_and_terminate() return exit_callback2 def output_callback(line): if mode == "cover": if solver_args[0] == "btormc": match = re.search(r"calling BMC on ([0-9]+) properties", line) if match: common_state.expected_cex = int(match[1]) assert common_state.produced_cex == 0 else: task.error(f"engine_{engine_idx}: BTOR solver '{solver_args[0]}' is currently not supported in cover mode.") if (common_state.produced_cex < common_state.expected_cex) and line == "sat": assert common_state.wit_file == None if common_state.expected_cex == 1: common_state.wit_file = open(f"{task.workdir}/engine_{engine_idx}/trace.wit", "w") else: common_state.wit_file = open(f"""{task.workdir}/engine_{engine_idx}/trace{common_state.produced_cex}.wit""", "w") if solver_args[0] != "btormc": proc.log("Found satisfiability witness.") if common_state.wit_file: print(line, file=common_state.wit_file) if line == ".": if common_state.expected_cex == 1: suffix = "" else: suffix = common_state.produced_cex proc2 = SbyProc( task, f"engine_{engine_idx}_{common_state.produced_cex}", task.model("btor"), "cd {dir} ; btorsim -c --vcd engine_{idx}/trace{i}.vcd --hierarchical-symbols --info model/design_btor{s}.info model/design_btor{s}.btor engine_{idx}/trace{i}.wit".format(dir=task.workdir, idx=engine_idx, i=suffix, s='_single' if solver_args[0] == 'pono' else ''), logfile=open(f"{task.workdir}/engine_{engine_idx}/logfile2.txt", "w") ) proc2.output_callback = output_callback2 proc2.exit_callback = make_exit_callback(suffix) proc2.checkretcode = True common_state.running_procs += 1 common_state.produced_cex += 1 common_state.wit_file.close() common_state.wit_file = None if common_state.produced_cex == common_state.expected_cex: common_state.solver_status = "sat" else: if solver_args[0] == "btormc": if "calling BMC on" in line: return line if "SATISFIABLE" in line: return line if "bad state properties at bound" in line: return line if "deleting model checker:" in line: if common_state.solver_status is None: common_state.solver_status = "unsat" return line elif solver_args[0] == "pono": if line == "unknown": if common_state.solver_status is None: common_state.solver_status = "unsat" return "No CEX found." if line not in ["b0"]: return line print(line, file=proc.logfile) return None def exit_callback(retcode): if solver_args[0] == "pono": assert retcode in [0, 1, 255] # UNKNOWN = -1, FALSE = 0, TRUE = 1, ERROR = 2 else: assert retcode == 0 if common_state.expected_cex != 0: assert common_state.solver_status is not None if common_state.solver_status == "unsat": if common_state.expected_cex == 1: with open(f"""{task.workdir}/engine_{engine_idx}/trace.wit""", "w") as wit_file: print("unsat", file=wit_file) else: for i in range(common_state.produced_cex, common_state.expected_cex): with open(f"{task.workdir}/engine_{engine_idx}/trace{i}.wit", "w") as wit_file: print("unsat", file=wit_file) common_state.running_procs -= 1 if (common_state.running_procs == 0): print_traces_and_terminate() proc = SbyProc( task, f"engine_{engine_idx}", task.model("btor"), f"cd {task.workdir}; {solver_cmd} model/design_btor{"_single" if solver_args[0]=="pono" else ""}.btor", logfile=open(f"{task.workdir}/engine_{engine_idx}/logfile.txt", "w") ) proc.output_callback = output_callback proc.exit_callback = exit_callback common_state.running_procs += 1
# # SymbiYosys (sby) -- Front-end for Yosys-based formal verification flows # # Copyright (C) 2016 Claire Xenia Wolf <claire@yosyshq.com> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # import re, os, getopt from types import SimpleNamespace from sby_core import SbyProc def run(mode, task, engine_idx, engine): random_seed = None opts, solver_args = getopt.getopt(engine[1:], "", ["seed="]) if len(solver_args) == 0: task.error("Missing solver command.") for o, a in opts: if o == "--seed": random_seed = a else: task.error("Unexpected BTOR engine options.") if solver_args[0] == "btormc": solver_cmd = "" if random_seed: solver_cmd += f"BTORSEED={random_seed} " solver_cmd += task.exe_paths["btormc"] + f""" --stop-first {0 if mode == "cover" else 1} -v 1 -kmax {task.opt_depth - 1}""" if task.opt_skip is not None: solver_cmd += f" -kmin {task.opt_skip}" solver_cmd += " ".join([""] + solver_args[1:]) elif solver_args[0] == "pono": if random_seed: task.error("Setting the random seed is not available for the pono solver.") solver_cmd = task.exe_paths["pono"] + f" --witness -v 1 -e bmc -k {task.opt_depth - 1}" else: task.error(f"Invalid solver command {solver_args[0]}.") common_state = SimpleNamespace() common_state.solver_status = None common_state.produced_cex = 0 common_state.expected_cex = 1 common_state.wit_file = None common_state.assert_fail = False common_state.produced_traces = [] common_state.print_traces_max = 5 common_state.running_procs = 0 def print_traces_and_terminate(): if mode == "cover": if common_state.assert_fail: proc_status = "FAIL" elif common_state.expected_cex == 0: proc_status = "pass" elif common_state.solver_status == "sat": proc_status = "pass" elif common_state.solver_status == "unsat": proc_status = "FAIL" else: task.error(f"engine_{engine_idx}: Engine terminated without status.") else: if common_state.expected_cex == 0: proc_status = "pass" elif common_state.solver_status == "sat": proc_status = "FAIL" elif common_state.solver_status == "unsat": proc_status = "pass" else: task.error(f"engine_{engine_idx}: Engine terminated without status.") task.update_status(proc_status.upper()) task.log(f"engine_{engine_idx}: Status returned by engine: {proc_status}") task.summary.append(f"""engine_{engine_idx} ({" ".join(engine)}) returned {proc_status}""") if len(common_state.produced_traces) == 0: task.log(f"""engine_{engine_idx}: Engine did not produce a{" counter" if mode != "cover" else "n "}example.""") elif len(common_state.produced_traces) <= common_state.print_traces_max: task.summary.extend(common_state.produced_traces) else: task.summary.extend(common_state.produced_traces[:common_state.print_traces_max]) excess_traces = len(common_state.produced_traces) - common_state.print_traces_max task.summary.append(f"""and {excess_traces} further trace{"s" if excess_traces > 1 else ""}""") task.terminate() if mode == "cover": def output_callback2(line): match = re.search(r"Assert failed in test", line) if match: common_state.assert_fail = True return line else: def output_callback2(line): return line def make_exit_callback(suffix): def exit_callback2(retcode): assert retcode == 0 vcdpath = f"{task.workdir}/engine_{engine_idx}/trace{suffix}.vcd" if os.path.exists(vcdpath): common_state.produced_traces.append(f"""{"" if mode == "cover" else "counterexample "}trace: {vcdpath}""") common_state.running_procs -= 1 if (common_state.running_procs == 0): print_traces_and_terminate() return exit_callback2 def output_callback(line): if mode == "cover": if solver_args[0] == "btormc": match = re.search(r"calling BMC on ([0-9]+) properties", line) if match: common_state.expected_cex = int(match[1]) assert common_state.produced_cex == 0 else: task.error(f"engine_{engine_idx}: BTOR solver '{solver_args[0]}' is currently not supported in cover mode.") if (common_state.produced_cex < common_state.expected_cex) and line == "sat": assert common_state.wit_file == None if common_state.expected_cex == 1: common_state.wit_file = open(f"{task.workdir}/engine_{engine_idx}/trace.wit", "w") else: common_state.wit_file = open(f"""{task.workdir}/engine_{engine_idx}/trace{common_state.produced_cex}.wit""", "w") if solver_args[0] != "btormc": proc.log("Found satisfiability witness.") if common_state.wit_file: print(line, file=common_state.wit_file) if line == ".": if common_state.expected_cex == 1: suffix = "" else: suffix = common_state.produced_cex proc2 = SbyProc( task, f"engine_{engine_idx}_{common_state.produced_cex}", task.model("btor"), "cd {dir} ; btorsim -c --vcd engine_{idx}/trace{i}.vcd --hierarchical-symbols --info model/design_btor{s}.info model/design_btor{s}.btor engine_{idx}/trace{i}.wit".format(dir=task.workdir, idx=engine_idx, i=suffix, s='_single' if solver_args[0] == 'pono' else ''), logfile=open(f"{task.workdir}/engine_{engine_idx}/logfile2.txt", "w") ) proc2.output_callback = output_callback2 proc2.exit_callback = make_exit_callback(suffix) proc2.checkretcode = True common_state.running_procs += 1 common_state.produced_cex += 1 common_state.wit_file.close() common_state.wit_file = None if common_state.produced_cex == common_state.expected_cex: common_state.solver_status = "sat" else: if solver_args[0] == "btormc": if "calling BMC on" in line: return line if "SATISFIABLE" in line: return line if "bad state properties at bound" in line: return line if "deleting model checker:" in line: if common_state.solver_status is None: common_state.solver_status = "unsat" return line elif solver_args[0] == "pono": if line == "unknown": if common_state.solver_status is None: common_state.solver_status = "unsat" return "No CEX found." if line not in ["b0"]: return line print(line, file=proc.logfile) return None def exit_callback(retcode): if solver_args[0] == "pono": assert retcode in [0, 1, 255] # UNKNOWN = -1, FALSE = 0, TRUE = 1, ERROR = 2 else: assert retcode == 0 if common_state.expected_cex != 0: assert common_state.solver_status is not None if common_state.solver_status == "unsat": if common_state.expected_cex == 1: with open(f"""{task.workdir}/engine_{engine_idx}/trace.wit""", "w") as wit_file: print("unsat", file=wit_file) else: for i in range(common_state.produced_cex, common_state.expected_cex): with open(f"{task.workdir}/engine_{engine_idx}/trace{i}.wit", "w") as wit_file: print("unsat", file=wit_file) common_state.running_procs -= 1 if (common_state.running_procs == 0): print_traces_and_terminate() proc = SbyProc( task, f"engine_{engine_idx}", task.model("btor"), f"cd {task.workdir}; {solver_cmd} model/design_btor{'_single' if solver_args[0]=='pono' else ''}.btor", logfile=open(f"{task.workdir}/engine_{engine_idx}/logfile.txt", "w") ) proc.output_callback = output_callback proc.exit_callback = exit_callback common_state.running_procs += 1
from typing import Any, Iterable from types_extensions import const, void, list_type, tuple_type class ExceptionLevels: RAISE: const(int) = 1 WARN: const(int) = 2 SILENT: const(int) = 3 class InvalidArgumentException(Exception): def __init__(self, given_argument: Any, allowed_arguments: Iterable[Any]) -> void: self.given_argument = given_argument self.given_argument_type = type(given_argument) self.allowed_arguments: list_type[tuple_type[Any, type]] = [(x, type(x)) for x in allowed_arguments] def __str__(self) -> str: msg = f"Invalid argument ({self.given_argument}) of type ({self.given_argument_type}) given." \ f"The allowed arguments are {", ".join((f"({x}) of type ({y})' for x, y in self.allowed_arguments))}" return msg class BucketNotEmptyException(Exception): ...
from typing import Any, Iterable from types_extensions import const, void, list_type, tuple_type class ExceptionLevels: RAISE: const(int) = 1 WARN: const(int) = 2 SILENT: const(int) = 3 class InvalidArgumentException(Exception): def __init__(self, given_argument: Any, allowed_arguments: Iterable[Any]) -> void: self.given_argument = given_argument self.given_argument_type = type(given_argument) self.allowed_arguments: list_type[tuple_type[Any, type]] = [(x, type(x)) for x in allowed_arguments] def __str__(self) -> str: msg = f"Invalid argument ({self.given_argument}) of type ({self.given_argument_type}) given." \ f"The allowed arguments are {', '.join((f'({x}) of type ({y})' for x, y in self.allowed_arguments))}" return msg class BucketNotEmptyException(Exception): ...
#!/bin/python3 import requests import json from time import sleep import zipfile import io from datetime import * from dateutil import tz import sys import os from .dryrun import _make_fake_fetchers BASE_URL="https://ca1.qualtrics.com/API" TIMEZONE = "America/Los_Angeles" TZ = tz.gettz(TIMEZONE) def progress(t): n=2*(t+1) return '.'*min(10,n),pow(2,max(0,t-4)) def dicta(*dcts): ret = dict() for d in dcts: ret.update(d) return ret def _make_url(endpoint): return f'{BASE_URL}/v3/{endpoint}' def make_fetchers(params): header = {'X-API-TOKEN': params['token']} if not params['token']: return _make_fake_fetchers(params,header,_make_url) def g(endpoint,**kw): url = _make_url(endpoint) r = requests.get(url,params=kw,headers=header) return r def p(endpoint,data): url = _make_url(endpoint) r = requests.post(url,json=data,headers=header) return r return g,p def get(fetch,post,params): resp=fetch("whoami") if not resp.ok: return resp resp=fetch("surveys") if not resp.ok: return resp results=[] for surv in resp.json()['result']['elements']: if not surv['isActive']: continue if not surv['name'] in params['surveys']['active']: continue print(json.dumps(surv,sort_keys=True,indent=3)) base = f"surveys/{surv["id"]}/export-responses/" # Fully cumulative: #start = datetime.combine(date(2020,4,6),time(00,00,00),tzinfo=TZ) # Transitional period: # place starter files for DEPLOY and US EXPANSION from 4-6 to 4-19 in qualtrics folder # subsequent downloads will start at 19 morning # revisit when we shift to fully incremental mode #start = datetime.combine(date(2020,4,19),time(00,00,00),tzinfo=TZ) # Fully incremental: 7 days to capture backfill start = datetime.combine(date.today()-timedelta(days=7),time(00,00,00),tzinfo=TZ) # Account for StartDate->RecordedDate lag: end = datetime.combine(date.today(),time(4,00,00),tzinfo=TZ) r = post(base,{ "format":"csv", "timeZone":TIMEZONE, "startDate":start.isoformat(), "endDate":end.isoformat(), "breakoutSets":"false", }) if not r.ok: return r progressId = r.json()['result']['progressId'] print(r.text) progressStatus = "inProgress" t=0 wait,waitt = progress(t) while progressStatus != "complete" and progressStatus != "failed": t+=1 r = fetch(f"{base}{progressId}") if not r.ok: return r progressStatus = r.json()['result']['status'] pct = r.json()['result']['percentComplete'] print(f"{progressStatus}: {pct}") if pct<100: for i in wait: sleep(waitt) print(i,end="",flush=True) sleep(waitt) print() wait,waitt = progress(t) if progressStatus=="failed": raise Exception(f"ERROR: could not download \"{surv["name"]}\"\n{json.dumps(r.json(),sort_keys=True,indent=2)}") fileId = r.json()['result']['fileId'] r = fetch(f"{base}{fileId}/file") if not r.ok: return r outfilename=f"{date.today()}.{start.date()}.{end.date()}.{surv["name"].replace(" ","_")}.csv" if r.ok == "dry-run": print(f"SAVE {outfilename}") else: z = zipfile.ZipFile(io.BytesIO(r.content)) for n in z.namelist(): with open(os.path.join(params['qualtrics_dir'], outfilename),'wb') as out: out.write(z.read(n)) break results.append(r) return results
#!/bin/python3 import requests import json from time import sleep import zipfile import io from datetime import * from dateutil import tz import sys import os from .dryrun import _make_fake_fetchers BASE_URL="https://ca1.qualtrics.com/API" TIMEZONE = "America/Los_Angeles" TZ = tz.gettz(TIMEZONE) def progress(t): n=2*(t+1) return '.'*min(10,n),pow(2,max(0,t-4)) def dicta(*dcts): ret = dict() for d in dcts: ret.update(d) return ret def _make_url(endpoint): return f'{BASE_URL}/v3/{endpoint}' def make_fetchers(params): header = {'X-API-TOKEN': params['token']} if not params['token']: return _make_fake_fetchers(params,header,_make_url) def g(endpoint,**kw): url = _make_url(endpoint) r = requests.get(url,params=kw,headers=header) return r def p(endpoint,data): url = _make_url(endpoint) r = requests.post(url,json=data,headers=header) return r return g,p def get(fetch,post,params): resp=fetch("whoami") if not resp.ok: return resp resp=fetch("surveys") if not resp.ok: return resp results=[] for surv in resp.json()['result']['elements']: if not surv['isActive']: continue if not surv['name'] in params['surveys']['active']: continue print(json.dumps(surv,sort_keys=True,indent=3)) base = f"surveys/{surv['id']}/export-responses/" # Fully cumulative: #start = datetime.combine(date(2020,4,6),time(00,00,00),tzinfo=TZ) # Transitional period: # place starter files for DEPLOY and US EXPANSION from 4-6 to 4-19 in qualtrics folder # subsequent downloads will start at 19 morning # revisit when we shift to fully incremental mode #start = datetime.combine(date(2020,4,19),time(00,00,00),tzinfo=TZ) # Fully incremental: 7 days to capture backfill start = datetime.combine(date.today()-timedelta(days=7),time(00,00,00),tzinfo=TZ) # Account for StartDate->RecordedDate lag: end = datetime.combine(date.today(),time(4,00,00),tzinfo=TZ) r = post(base,{ "format":"csv", "timeZone":TIMEZONE, "startDate":start.isoformat(), "endDate":end.isoformat(), "breakoutSets":"false", }) if not r.ok: return r progressId = r.json()['result']['progressId'] print(r.text) progressStatus = "inProgress" t=0 wait,waitt = progress(t) while progressStatus != "complete" and progressStatus != "failed": t+=1 r = fetch(f"{base}{progressId}") if not r.ok: return r progressStatus = r.json()['result']['status'] pct = r.json()['result']['percentComplete'] print(f"{progressStatus}: {pct}") if pct<100: for i in wait: sleep(waitt) print(i,end="",flush=True) sleep(waitt) print() wait,waitt = progress(t) if progressStatus=="failed": raise Exception(f"ERROR: could not download \"{surv['name']}\"\n{json.dumps(r.json(),sort_keys=True,indent=2)}") fileId = r.json()['result']['fileId'] r = fetch(f"{base}{fileId}/file") if not r.ok: return r outfilename=f"{date.today()}.{start.date()}.{end.date()}.{surv['name'].replace(' ','_')}.csv" if r.ok == "dry-run": print(f"SAVE {outfilename}") else: z = zipfile.ZipFile(io.BytesIO(r.content)) for n in z.namelist(): with open(os.path.join(params['qualtrics_dir'], outfilename),'wb') as out: out.write(z.read(n)) break results.append(r) return results
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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. """ PyTorch Transformer XL model. Adapted from https://github.com/kimiyoung/transformer-xl. In particular https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/mem_transformer.py """ import warnings from dataclasses import dataclass from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...modeling_utils import PreTrainedModel from ...utils import ( ModelOutput, add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, ) from .configuration_transfo_xl import TransfoXLConfig from .modeling_transfo_xl_utilities import ProjectedAdaptiveLogSoftmax logger = logging.get_logger(__name__) _CHECKPOINT_FOR_DOC = "transfo-xl-wt103" _CONFIG_FOR_DOC = "TransfoXLConfig" _TOKENIZER_FOR_DOC = "TransfoXLTokenizer" TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST = [ "transfo-xl-wt103", # See all Transformer XL models at https://huggingface.co/models?filter=transfo-xl ] def build_tf_to_pytorch_map(model, config): """ A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible. """ tf_to_pt_map = {} if hasattr(model, "transformer"): # We are loading in a TransfoXLLMHeadModel => we will load also the Adaptive Softmax tf_to_pt_map.update( { "transformer/adaptive_softmax/cutoff_0/cluster_W": model.crit.cluster_weight, "transformer/adaptive_softmax/cutoff_0/cluster_b": model.crit.cluster_bias, } ) for i, (out_l, proj_l, tie_proj) in enumerate( zip(model.crit.out_layers, model.crit.out_projs, config.tie_projs) ): layer_str = f"transformer/adaptive_softmax/cutoff_{i}/" if config.tie_word_embeddings: tf_to_pt_map.update({layer_str + "b": out_l.bias}) else: raise NotImplementedError # I don't think this is implemented in the TF code tf_to_pt_map.update({layer_str + "lookup_table": out_l.weight, layer_str + "b": out_l.bias}) if not tie_proj: tf_to_pt_map.update({layer_str + "proj": proj_l}) # Now load the rest of the transformer model = model.transformer # Embeddings for i, (embed_l, proj_l) in enumerate(zip(model.word_emb.emb_layers, model.word_emb.emb_projs)): layer_str = f"transformer/adaptive_embed/cutoff_{i}/" tf_to_pt_map.update({layer_str + "lookup_table": embed_l.weight, layer_str + "proj_W": proj_l}) # Transformer blocks for i, b in enumerate(model.layers): layer_str = f"transformer/layer_{i}/" tf_to_pt_map.update( { layer_str + "rel_attn/LayerNorm/gamma": b.dec_attn.layer_norm.weight, layer_str + "rel_attn/LayerNorm/beta": b.dec_attn.layer_norm.bias, layer_str + "rel_attn/o/kernel": b.dec_attn.o_net.weight, layer_str + "rel_attn/qkv/kernel": b.dec_attn.qkv_net.weight, layer_str + "rel_attn/r/kernel": b.dec_attn.r_net.weight, layer_str + "ff/LayerNorm/gamma": b.pos_ff.layer_norm.weight, layer_str + "ff/LayerNorm/beta": b.pos_ff.layer_norm.bias, layer_str + "ff/layer_1/kernel": b.pos_ff.CoreNet[0].weight, layer_str + "ff/layer_1/bias": b.pos_ff.CoreNet[0].bias, layer_str + "ff/layer_2/kernel": b.pos_ff.CoreNet[3].weight, layer_str + "ff/layer_2/bias": b.pos_ff.CoreNet[3].bias, } ) # Relative positioning biases if config.untie_r: r_r_list = [] r_w_list = [] for b in model.layers: r_r_list.append(b.dec_attn.r_r_bias) r_w_list.append(b.dec_attn.r_w_bias) else: r_r_list = [model.r_r_bias] r_w_list = [model.r_w_bias] tf_to_pt_map.update({"transformer/r_r_bias": r_r_list, "transformer/r_w_bias": r_w_list}) return tf_to_pt_map def load_tf_weights_in_transfo_xl(model, config, tf_path): """Load tf checkpoints in a pytorch model""" try: import numpy as np import tensorflow as tf except ImportError: logger.error( "Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions." ) raise # Build TF to PyTorch weights loading map tf_to_pt_map = build_tf_to_pytorch_map(model, config) # Load weights from TF model init_vars = tf.train.list_variables(tf_path) tf_weights = {} for name, shape in init_vars: logger.info(f"Loading TF weight {name} with shape {shape}") array = tf.train.load_variable(tf_path, name) tf_weights[name] = array for name, pointer in tf_to_pt_map.items(): assert name in tf_weights array = tf_weights[name] # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v # which are not required for using pretrained model if "kernel" in name or "proj" in name: array = np.transpose(array) if ("r_r_bias" in name or "r_w_bias" in name) and len(pointer) > 1: # Here we will split the TF weights assert len(pointer) == array.shape[0] for i, p_i in enumerate(pointer): arr_i = array[i, ...] try: assert p_i.shape == arr_i.shape except AssertionError as e: e.args += (p_i.shape, arr_i.shape) raise logger.info(f"Initialize PyTorch weight {name} for layer {i}") p_i.data = torch.from_numpy(arr_i) else: try: assert ( pointer.shape == array.shape ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" except AssertionError as e: e.args += (pointer.shape, array.shape) raise logger.info(f"Initialize PyTorch weight {name}") pointer.data = torch.from_numpy(array) tf_weights.pop(name, None) tf_weights.pop(name + "/Adam", None) tf_weights.pop(name + "/Adam_1", None) logger.info(f"Weights not copied to PyTorch model: {", ".join(tf_weights.keys())}") return model class PositionalEmbedding(nn.Module): def __init__(self, demb): super().__init__() self.demb = demb inv_freq = 1 / (10000 ** (torch.arange(0.0, demb, 2.0) / demb)) self.register_buffer("inv_freq", inv_freq) def forward(self, pos_seq, bsz=None): sinusoid_inp = torch.ger(pos_seq, self.inv_freq) pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1) if bsz is not None: return pos_emb[:, None, :].expand(-1, bsz, -1) else: return pos_emb[:, None, :] class PositionwiseFF(nn.Module): def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5): super().__init__() self.d_model = d_model self.d_inner = d_inner self.dropout = dropout self.CoreNet = nn.Sequential( nn.Linear(d_model, d_inner), nn.ReLU(inplace=True), nn.Dropout(dropout), nn.Linear(d_inner, d_model), nn.Dropout(dropout), ) self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon) self.pre_lnorm = pre_lnorm def forward(self, inp): if self.pre_lnorm: # layer normalization + positionwise feed-forward core_out = self.CoreNet(self.layer_norm(inp)) # residual connection output = core_out + inp else: # positionwise feed-forward core_out = self.CoreNet(inp) # residual connection + layer normalization output = self.layer_norm(inp + core_out) return output class RelPartialLearnableMultiHeadAttn(nn.Module): def __init__( self, n_head, d_model, d_head, dropout, dropatt=0, pre_lnorm=False, r_r_bias=None, r_w_bias=None, layer_norm_epsilon=1e-5, ): super().__init__() self.n_head = n_head self.d_model = d_model self.d_head = d_head self.dropout = dropout self.qkv_net = nn.Linear(d_model, 3 * n_head * d_head, bias=False) self.drop = nn.Dropout(dropout) self.dropatt = nn.Dropout(dropatt) self.o_net = nn.Linear(n_head * d_head, d_model, bias=False) self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon) self.scale = 1 / (d_head**0.5) self.pre_lnorm = pre_lnorm if r_r_bias is None or r_w_bias is None: # Biases are not shared self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) else: self.r_r_bias = r_r_bias self.r_w_bias = r_w_bias self.r_net = nn.Linear(self.d_model, self.n_head * self.d_head, bias=False) def _rel_shift(self, x): zero_pad_shape = (x.size(0), 1) + x.size()[2:] zero_pad = torch.zeros(zero_pad_shape, device=x.device, dtype=x.dtype) x_padded = torch.cat([zero_pad, x], dim=1) x_padded_shape = (x.size(1) + 1, x.size(0)) + x.size()[2:] x_padded = x_padded.view(*x_padded_shape) x = x_padded[1:].view_as(x) return x def forward(self, w, r, attn_mask=None, mems=None, head_mask=None, output_attentions=False): qlen, rlen, bsz = w.size(0), r.size(0), w.size(1) if mems is not None: cat = torch.cat([mems, w], 0) if self.pre_lnorm: w_heads = self.qkv_net(self.layer_norm(cat)) else: w_heads = self.qkv_net(cat) r_head_k = self.r_net(r) w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1) w_head_q = w_head_q[-qlen:] else: if self.pre_lnorm: w_heads = self.qkv_net(self.layer_norm(w)) else: w_heads = self.qkv_net(w) r_head_k = self.r_net(r) w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1) klen = w_head_k.size(0) w_head_q = w_head_q.view(qlen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head w_head_k = w_head_k.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head w_head_v = w_head_v.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head r_head_k = r_head_k.view(rlen, self.n_head, self.d_head) # qlen x n_head x d_head # compute attention score rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head AC = torch.einsum("ibnd,jbnd->ijbn", (rw_head_q, w_head_k)) # qlen x klen x bsz x n_head rr_head_q = w_head_q + self.r_r_bias BD = torch.einsum("ibnd,jnd->ijbn", (rr_head_q, r_head_k)) # qlen x klen x bsz x n_head BD = self._rel_shift(BD) # [qlen x klen x bsz x n_head] attn_score = AC + BD attn_score.mul_(self.scale) # compute attention probability if attn_mask is not None and torch.sum(attn_mask).item(): attn_mask = attn_mask == 1 # Switch to bool if attn_mask.dim() == 2: if next(self.parameters()).dtype == torch.float16: attn_score = ( attn_score.float().masked_fill(attn_mask[None, :, :, None], -65000).type_as(attn_score) ) else: attn_score = attn_score.float().masked_fill(attn_mask[None, :, :, None], -1e30).type_as(attn_score) elif attn_mask.dim() == 3: if next(self.parameters()).dtype == torch.float16: attn_score = attn_score.float().masked_fill(attn_mask[:, :, :, None], -65000).type_as(attn_score) else: attn_score = attn_score.float().masked_fill(attn_mask[:, :, :, None], -1e30).type_as(attn_score) # [qlen x klen x bsz x n_head] attn_prob = nn.functional.softmax(attn_score, dim=1) attn_prob = self.dropatt(attn_prob) # Mask heads if we want to if head_mask is not None: attn_prob = attn_prob * head_mask # compute attention vector attn_vec = torch.einsum("ijbn,jbnd->ibnd", (attn_prob, w_head_v)) # [qlen x bsz x n_head x d_head] attn_vec = attn_vec.contiguous().view(attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head) # linear projection attn_out = self.o_net(attn_vec) attn_out = self.drop(attn_out) if self.pre_lnorm: # residual connection outputs = [w + attn_out] else: # residual connection + layer normalization outputs = [self.layer_norm(w + attn_out)] if output_attentions: outputs.append(attn_prob) return outputs class RelPartialLearnableDecoderLayer(nn.Module): def __init__(self, n_head, d_model, d_head, d_inner, dropout, layer_norm_epsilon=1e-5, **kwargs): super().__init__() self.dec_attn = RelPartialLearnableMultiHeadAttn( n_head, d_model, d_head, dropout, layer_norm_epsilon=layer_norm_epsilon, **kwargs ) self.pos_ff = PositionwiseFF( d_model, d_inner, dropout, pre_lnorm=kwargs.get("pre_lnorm"), layer_norm_epsilon=layer_norm_epsilon ) def forward(self, dec_inp, r, dec_attn_mask=None, mems=None, head_mask=None, output_attentions=False): attn_outputs = self.dec_attn( dec_inp, r, attn_mask=dec_attn_mask, mems=mems, head_mask=head_mask, output_attentions=output_attentions, ) ff_output = self.pos_ff(attn_outputs[0]) outputs = [ff_output] + attn_outputs[1:] return outputs class AdaptiveEmbedding(nn.Module): def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, sample_softmax=False): super().__init__() self.n_token = n_token self.d_embed = d_embed self.cutoffs = cutoffs + [n_token] self.div_val = div_val self.d_proj = d_proj self.emb_scale = d_proj**0.5 self.cutoff_ends = [0] + self.cutoffs self.emb_layers = nn.ModuleList() self.emb_projs = nn.ParameterList() if div_val == 1: self.emb_layers.append(nn.Embedding(n_token, d_embed, sparse=sample_softmax > 0)) if d_proj != d_embed: self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed))) else: for i in range(len(self.cutoffs)): l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] d_emb_i = d_embed // (div_val**i) self.emb_layers.append(nn.Embedding(r_idx - l_idx, d_emb_i)) self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i))) def forward(self, inp): if self.div_val == 1: embed = self.emb_layers[0](inp) if self.d_proj != self.d_embed: embed = nn.functional.linear(embed, self.emb_projs[0]) else: param = next(self.parameters()) inp_flat = inp.view(-1) emb_flat = torch.zeros([inp_flat.size(0), self.d_proj], dtype=param.dtype, device=param.device) for i in range(len(self.cutoffs)): l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx) indices_i = mask_i.nonzero().squeeze() if indices_i.numel() == 0: continue inp_i = inp_flat.index_select(0, indices_i) - l_idx emb_i = self.emb_layers[i](inp_i) emb_i = nn.functional.linear(emb_i, self.emb_projs[i]) emb_flat.index_copy_(0, indices_i, emb_i) embed_shape = inp.size() + (self.d_proj,) embed = emb_flat.view(embed_shape) embed.mul_(self.emb_scale) return embed class TransfoXLPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = TransfoXLConfig load_tf_weights = load_tf_weights_in_transfo_xl base_model_prefix = "transformer" def _init_weight(self, weight): if self.config.init == "uniform": nn.init.uniform_(weight, -self.config.init_range, self.config.init_range) elif self.config.init == "normal": nn.init.normal_(weight, 0.0, self.config.init_std) def _init_bias(self, bias): nn.init.constant_(bias, 0.0) def _init_weights(self, m): """Initialize the weights.""" classname = m.__class__.__name__ if classname.find("Linear") != -1: if hasattr(m, "weight") and m.weight is not None: self._init_weight(m.weight) if hasattr(m, "bias") and m.bias is not None: self._init_bias(m.bias) elif classname.find("AdaptiveEmbedding") != -1: if hasattr(m, "emb_projs"): for i in range(len(m.emb_projs)): if m.emb_projs[i] is not None: nn.init.normal_(m.emb_projs[i], 0.0, self.config.proj_init_std) elif classname.find("Embedding") != -1: if hasattr(m, "weight"): self._init_weight(m.weight) elif classname.find("ProjectedAdaptiveLogSoftmax") != -1: if hasattr(m, "cluster_weight") and m.cluster_weight is not None: self._init_weight(m.cluster_weight) if hasattr(m, "cluster_bias") and m.cluster_bias is not None: self._init_bias(m.cluster_bias) if hasattr(m, "out_projs"): for i in range(len(m.out_projs)): if m.out_projs[i] is not None: nn.init.normal_(m.out_projs[i], 0.0, self.config.proj_init_std) elif classname.find("LayerNorm") != -1: if hasattr(m, "weight"): nn.init.normal_(m.weight, 1.0, self.config.init_std) if hasattr(m, "bias") and m.bias is not None: self._init_bias(m.bias) else: if hasattr(m, "r_emb"): self._init_weight(m.r_emb) if hasattr(m, "r_w_bias"): self._init_weight(m.r_w_bias) if hasattr(m, "r_r_bias"): self._init_weight(m.r_r_bias) if hasattr(m, "r_bias"): self._init_bias(m.r_bias) def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, layer: Optional[int] = -1): """ Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. Take care of tying weights embeddings afterwards if the model class has a *tie_weights()* method. Arguments: new_num_tokens: (*optional*) int: New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or None: does nothing and just returns a pointer to the input tokens `torch.nn.Embeddings` Module of the model. layer: (*optional*) int: Layer of the *AdaptiveEmbedding* where the resizing should be done. Per default the last layer will be resized. Be aware that when resizing other than the last layer, you have to ensure that the new token(s) in the tokenizer are at the corresponding position. Return: `torch.nn.Embeddings` Pointer to the input tokens Embeddings Module of the model """ base_model = getattr(self, self.base_model_prefix, self) # get the base model if needed if new_num_tokens is None: return self.get_input_embeddings() new_num_tokens_layer, layer = self._get_new_num_tokens_layer(new_num_tokens, layer) assert new_num_tokens_layer > 0, "The size of the new embedding layer cannot be 0 or less" model_embeds = base_model._resize_token_embeddings(new_num_tokens_layer, layer) # Update base model and current model config self.config.vocab_size = new_num_tokens base_model.vocab_size = new_num_tokens base_model.n_token = new_num_tokens new_embedding_shapes = self._get_embedding_shapes() self._resize_cutoffs(new_num_tokens, new_num_tokens_layer, new_embedding_shapes, layer) # Tie weights again if needed self.tie_weights() return model_embeds def _get_new_num_tokens_layer(self, new_num_tokens, layer): embeddings = self.get_input_embeddings() if layer == -1: layer = len(embeddings.emb_layers) - 1 assert 0 <= layer <= len(embeddings.emb_layers) - 1 new_num_tokens_layer = ( new_num_tokens - sum([emb.weight.shape[0] for emb in embeddings.emb_layers[:layer]]) - sum([emb.weight.shape[0] for emb in embeddings.emb_layers[layer + 1 :]]) ) return new_num_tokens_layer, layer def _get_embedding_shapes(self): embeddings = self.get_input_embeddings() return [emb.weight.shape[0] for emb in embeddings.emb_layers] def _resize_token_embeddings(self, new_num_tokens, layer=-1): embeddings = self.get_input_embeddings() if new_num_tokens is None: return embeddings new_embeddings_layer = self._get_resized_embeddings(embeddings.emb_layers[layer], new_num_tokens) embeddings.emb_layers[layer] = new_embeddings_layer self.set_input_embeddings(embeddings) return self.get_input_embeddings() def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer): embeddings = self.get_input_embeddings() for i in range(layer, len(embeddings.cutoffs)): embeddings.cutoffs[i] = sum(new_embedding_shapes[: i + 1]) embeddings.cutoff_ends = [0] + embeddings.cutoffs embeddings.n_token = new_num_tokens self.config.cutoffs = embeddings.cutoffs[:-1] return embeddings.cutoffs @dataclass class TransfoXLModelOutput(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. mems (`List[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ last_hidden_state: torch.FloatTensor mems: List[torch.FloatTensor] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None @dataclass class TransfoXLSequenceClassifierOutputWithPast(ModelOutput): """ Base class for outputs of sentence classification models. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (before SoftMax). mems (`List[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None mems: List[torch.FloatTensor] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None @dataclass class TransfoXLLMHeadModelOutput(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: losses (`torch.FloatTensor` of shape *(batch_size, sequence_length-1)*, *optional*, returned when `labels` is provided): Language modeling losses (not reduced). prediction_scores (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token after SoftMax). mems (`List[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. loss (`torch.FloatTensor` of shape `()`, *optional*, returned when `labels` is provided) Reduced language modeling loss. """ losses: Optional[torch.FloatTensor] = None prediction_scores: torch.FloatTensor = None mems: List[torch.FloatTensor] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None loss: Optional[torch.FloatTensor] = None @property def logits(self): # prediction scores are the output of the adaptive softmax, see # the file `modeling_transfo_xl_utilities`. Since the adaptive # softmax returns the log softmax value, `self.prediction_scores` # are strictly speaking not exactly `logits`, but behave the same # way logits do. return self.prediction_scores TRANSFO_XL_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`TransfoXLConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ TRANSFO_XL_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`TransfoXLTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) mems (`List[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see `mems` output below). Can be used to speed up sequential decoding. The token ids which have their mems given to this model should not be passed as `input_ids` as they have already been computed. head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.", TRANSFO_XL_START_DOCSTRING, ) class TransfoXLModel(TransfoXLPreTrainedModel): def __init__(self, config): super().__init__(config) self.n_token = config.vocab_size self.d_embed = config.d_embed self.d_model = config.d_model self.n_head = config.n_head self.d_head = config.d_head self.word_emb = AdaptiveEmbedding( config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val ) self.drop = nn.Dropout(config.dropout) self.n_layer = config.n_layer self.mem_len = config.mem_len self.attn_type = config.attn_type if not config.untie_r: self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) self.layers = nn.ModuleList() if config.attn_type == 0: # the default attention for i in range(config.n_layer): self.layers.append( RelPartialLearnableDecoderLayer( config.n_head, config.d_model, config.d_head, config.d_inner, config.dropout, dropatt=config.dropatt, pre_lnorm=config.pre_lnorm, r_w_bias=None if config.untie_r else self.r_w_bias, r_r_bias=None if config.untie_r else self.r_r_bias, layer_norm_epsilon=config.layer_norm_epsilon, ) ) else: # learnable embeddings and absolute embeddings are not used in our pretrained checkpoints raise NotImplementedError # Removed them to avoid maintaining dead code self.same_length = config.same_length self.clamp_len = config.clamp_len if self.attn_type == 0: # default attention self.pos_emb = PositionalEmbedding(self.d_model) else: # learnable embeddings and absolute embeddings raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.word_emb def set_input_embeddings(self, new_embeddings): self.word_emb = new_embeddings def backward_compatible(self): self.sample_softmax = -1 def reset_memory_length(self, mem_len): self.mem_len = mem_len def _prune_heads(self, heads): logger.info("Head pruning is not implemented for Transformer-XL model") pass def init_mems(self, bsz): if self.mem_len > 0: mems = [] param = next(self.parameters()) for i in range(self.n_layer): empty = torch.zeros(self.mem_len, bsz, self.config.d_model, dtype=param.dtype, device=param.device) mems.append(empty) return mems else: return None def _update_mems(self, hids, mems, mlen, qlen): # does not deal with None if mems is None: return None # mems is not None assert len(hids) == len(mems), "len(hids) != len(mems)" # There are `mlen + qlen` steps that can be cached into mems with torch.no_grad(): new_mems = [] end_idx = mlen + max(0, qlen) beg_idx = max(0, end_idx - self.mem_len) for i in range(len(hids)): cat = torch.cat([mems[i], hids[i]], dim=0) new_mems.append(cat[beg_idx:end_idx].detach()) return new_mems @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=TransfoXLModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.LongTensor] = None, mems: Optional[List[torch.FloatTensor]] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, TransfoXLModelOutput]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict # the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library # so we transpose here from shape [bsz, len] to shape [len, bsz] if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_ids = input_ids.transpose(0, 1).contiguous() qlen, bsz = input_ids.size() elif inputs_embeds is not None: inputs_embeds = inputs_embeds.transpose(0, 1).contiguous() qlen, bsz = inputs_embeds.shape[0], inputs_embeds.shape[1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") if mems is None: mems = self.init_mems(bsz) # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer) # and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head] if head_mask is not None: if head_mask.dim() == 1: head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(0).unsqueeze(0) head_mask = head_mask.expand(self.n_layer, -1, -1, -1, -1) elif head_mask.dim() == 2: head_mask = head_mask.unsqueeze(1).unsqueeze(1).unsqueeze(1) head_mask = head_mask.to( dtype=next(self.parameters()).dtype ) # switch to float if need + fp16 compatibility else: head_mask = [None] * self.n_layer if inputs_embeds is not None: word_emb = inputs_embeds else: word_emb = self.word_emb(input_ids) mlen = mems[0].size(0) if mems is not None else 0 klen = mlen + qlen if self.same_length: all_ones = word_emb.new_ones((qlen, klen), dtype=torch.uint8) mask_len = klen - self.mem_len if mask_len > 0: mask_shift_len = qlen - mask_len else: mask_shift_len = qlen dec_attn_mask = (torch.triu(all_ones, 1 + mlen) + torch.tril(all_ones, -mask_shift_len))[:, :, None] # -1 else: dec_attn_mask = torch.triu(word_emb.new_ones((qlen, klen), dtype=torch.uint8), diagonal=1 + mlen)[ :, :, None ] hids = [] attentions = [] if output_attentions else None if self.attn_type == 0: # default pos_seq = torch.arange(klen - 1, -1, -1.0, device=word_emb.device, dtype=word_emb.dtype) if self.clamp_len > 0: pos_seq.clamp_(max=self.clamp_len) pos_emb = self.pos_emb(pos_seq) core_out = self.drop(word_emb) pos_emb = self.drop(pos_emb) for i, layer in enumerate(self.layers): hids.append(core_out) mems_i = None if mems is None else mems[i] layer_outputs = layer( core_out, pos_emb, dec_attn_mask=dec_attn_mask, mems=mems_i, head_mask=head_mask[i], output_attentions=output_attentions, ) core_out = layer_outputs[0] if output_attentions: attentions.append(layer_outputs[1]) else: # learnable embeddings and absolute embeddings raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint core_out = self.drop(core_out) new_mems = self._update_mems(hids, mems, mlen, qlen) if output_hidden_states: # Add last layer and transpose to library standard shape [bsz, len, hidden_dim] hids.append(core_out) hids = tuple(t.transpose(0, 1).contiguous() for t in hids) else: hids = None if output_attentions: # Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len] attentions = tuple(t.permute(2, 3, 0, 1).contiguous() for t in attentions) # We transpose back here to shape [bsz, len, hidden_dim] core_out = core_out.transpose(0, 1).contiguous() if not return_dict: return tuple(v for v in [core_out, new_mems, hids, attentions] if v is not None) return TransfoXLModelOutput( last_hidden_state=core_out, mems=new_mems, hidden_states=hids, attentions=attentions, ) @add_start_docstrings( """ The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive input embeddings) """, TRANSFO_XL_START_DOCSTRING, ) class TransfoXLLMHeadModel(TransfoXLPreTrainedModel): def __init__(self, config): super().__init__(config) self.transformer = TransfoXLModel(config) self.sample_softmax = config.sample_softmax self.trainer_compatible = getattr(config, "trainer_compatible", False) if not self.trainer_compatible: warnings.warn( "The output of TransfoXL will be updated in v5 to support a single loss as first argument. In order" "to use that updated output, please specify `trainer_compatible=True` as your configuration" " attribute.", DeprecationWarning, ) assert self.sample_softmax <= 0, ( "Sampling from the softmax is not implemented yet. Please look at issue: #3310:" " https://github.com/huggingface/transformers/issues/3310" ) self.crit = ProjectedAdaptiveLogSoftmax( config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val ) # Initialize weights and apply final processing self.post_init() def tie_weights(self): """ Run this to be sure output and input (adaptive) softmax weights are tied """ if self.config.tie_word_embeddings: for i in range(len(self.crit.out_layers)): self._tie_or_clone_weights(self.crit.out_layers[i], self.transformer.word_emb.emb_layers[i]) if self.config.tie_projs: for i, tie_proj in enumerate(self.config.tie_projs): if tie_proj and self.config.div_val == 1 and self.config.d_model != self.config.d_embed: if self.config.torchscript: self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[0].clone()) else: self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[0] elif tie_proj and self.config.div_val != 1: if self.config.torchscript: self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[i].clone()) else: self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[i] def reset_memory_length(self, mem_len): self.transformer.reset_memory_length(mem_len) def init_mems(self, bsz): return self.transformer.init_mems(bsz) @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=TransfoXLLMHeadModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.LongTensor] = None, mems: Optional[List[torch.FloatTensor]] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, TransfoXLLMHeadModelOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None: bsz, tgt_len = input_ids.size(0), input_ids.size(1) elif inputs_embeds is not None: bsz, tgt_len = inputs_embeds.size(0), inputs_embeds.size(1) else: raise ValueError("You have to specify either input_ids or inputs_embeds") transformer_outputs = self.transformer( input_ids, mems=mems, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) last_hidden = transformer_outputs[0] pred_hid = last_hidden[:, -tgt_len:] if labels is not None: # Prevents all labels being -100 and throwing an error # when backwarding the loss miss_valid_label = labels[0, 1:].sum() == (labels.size(1) - 1) * -100 if miss_valid_label: # Sets an <EOS> token, just to prevent loss from being NaN labels[0, 1] = self.config.eos_token_id softmax_output = self.crit(pred_hid, labels) prediction_scores = softmax_output.view(bsz, tgt_len, -1) if labels is None else () if labels is not None: losses = softmax_output.view(bsz, tgt_len - 1) # Avoids from incorporating padding (-100) tokens into loss value loss = losses[losses != 0].mean() else: losses, loss = None, None if not return_dict: if self.trainer_compatible: output = (prediction_scores, losses) if losses is not None else (prediction_scores,) output += transformer_outputs[1:] return ((loss,) + output) if loss is not None else output else: output = (prediction_scores, *transformer_outputs[1:]) output = ((losses,) + output) if losses is not None else output return (output + (loss,)) if loss is not None else output return TransfoXLLMHeadModelOutput( loss=loss, prediction_scores=prediction_scores, losses=losses, mems=transformer_outputs.mems, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) def get_output_embeddings(self): """Double-check if you are using adaptive softmax.""" if self.sample_softmax > 0: return self.out_layer else: return self.crit.out_layers[-1] def prepare_inputs_for_generation(self, input_ids, past=None, **model_kwargs): inputs = {} # if past is defined in model kwargs then use it for faster decoding if past: inputs["mems"] = past inputs["input_ids"] = input_ids[:, -1].unsqueeze(-1) else: inputs["input_ids"] = input_ids return inputs def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer): new_cutoffs = super()._resize_cutoffs(new_num_tokens, new_emb_size, new_embedding_shapes, layer) self.crit.cutoffs = new_cutoffs self.crit.cutoff_ends = [0] + new_cutoffs self.crit.n_token = new_num_tokens @staticmethod def _reorder_cache(mems: List[torch.Tensor], beam_idx: torch.Tensor) -> List[torch.Tensor]: """ This function is used to re-order the `mems` cache if [`~PreTrainedModel.beam_search`] or [`~PreTrainedModel.beam_sample`] is called. This is required to match `mems` with the correct beam_idx at every generation step. """ return [layer_past.index_select(1, beam_idx.to(layer_past.device)) for layer_past in mems] @add_start_docstrings( """ The Transformer-XL Model transformer with a sequence classification head on top (linear layer). [`TransfoXLForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-1) do. Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch). """, TRANSFO_XL_START_DOCSTRING, ) class TransfoXLForSequenceClassification(TransfoXLPreTrainedModel): _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head.weight"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.transformer = TransfoXLModel(config) self.score = nn.Linear(config.d_embed, self.num_labels, bias=False) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=TransfoXLSequenceClassifierOutputWithPast, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.LongTensor] = None, mems: Optional[List[torch.FloatTensor]] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, TransfoXLSequenceClassifierOutputWithPast]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict transformer_outputs = self.transformer( input_ids, mems=mems, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = transformer_outputs[0] logits = self.score(hidden_states) if input_ids is not None: batch_size, sequence_length = input_ids.shape[:2] else: batch_size, sequence_length = inputs_embeds.shape[:2] assert ( self.config.pad_token_id is not None or batch_size == 1 ), "Cannot handle batch sizes > 1 if no padding token is defined." if self.config.pad_token_id is None: sequence_lengths = -1 else: if input_ids is not None: sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1 else: sequence_lengths = -1 logger.warning( f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " "unexpected if using padding tokens in conjunction with `inputs_embeds.`" ) pooled_logits = logits[range(batch_size), sequence_lengths] loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification" if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) else: loss = loss_fct(pooled_logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(pooled_logits, labels) if not return_dict: output = (pooled_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output return TransfoXLSequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, mems=transformer_outputs.mems, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, )
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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. """ PyTorch Transformer XL model. Adapted from https://github.com/kimiyoung/transformer-xl. In particular https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/mem_transformer.py """ import warnings from dataclasses import dataclass from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...modeling_utils import PreTrainedModel from ...utils import ( ModelOutput, add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, ) from .configuration_transfo_xl import TransfoXLConfig from .modeling_transfo_xl_utilities import ProjectedAdaptiveLogSoftmax logger = logging.get_logger(__name__) _CHECKPOINT_FOR_DOC = "transfo-xl-wt103" _CONFIG_FOR_DOC = "TransfoXLConfig" _TOKENIZER_FOR_DOC = "TransfoXLTokenizer" TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST = [ "transfo-xl-wt103", # See all Transformer XL models at https://huggingface.co/models?filter=transfo-xl ] def build_tf_to_pytorch_map(model, config): """ A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible. """ tf_to_pt_map = {} if hasattr(model, "transformer"): # We are loading in a TransfoXLLMHeadModel => we will load also the Adaptive Softmax tf_to_pt_map.update( { "transformer/adaptive_softmax/cutoff_0/cluster_W": model.crit.cluster_weight, "transformer/adaptive_softmax/cutoff_0/cluster_b": model.crit.cluster_bias, } ) for i, (out_l, proj_l, tie_proj) in enumerate( zip(model.crit.out_layers, model.crit.out_projs, config.tie_projs) ): layer_str = f"transformer/adaptive_softmax/cutoff_{i}/" if config.tie_word_embeddings: tf_to_pt_map.update({layer_str + "b": out_l.bias}) else: raise NotImplementedError # I don't think this is implemented in the TF code tf_to_pt_map.update({layer_str + "lookup_table": out_l.weight, layer_str + "b": out_l.bias}) if not tie_proj: tf_to_pt_map.update({layer_str + "proj": proj_l}) # Now load the rest of the transformer model = model.transformer # Embeddings for i, (embed_l, proj_l) in enumerate(zip(model.word_emb.emb_layers, model.word_emb.emb_projs)): layer_str = f"transformer/adaptive_embed/cutoff_{i}/" tf_to_pt_map.update({layer_str + "lookup_table": embed_l.weight, layer_str + "proj_W": proj_l}) # Transformer blocks for i, b in enumerate(model.layers): layer_str = f"transformer/layer_{i}/" tf_to_pt_map.update( { layer_str + "rel_attn/LayerNorm/gamma": b.dec_attn.layer_norm.weight, layer_str + "rel_attn/LayerNorm/beta": b.dec_attn.layer_norm.bias, layer_str + "rel_attn/o/kernel": b.dec_attn.o_net.weight, layer_str + "rel_attn/qkv/kernel": b.dec_attn.qkv_net.weight, layer_str + "rel_attn/r/kernel": b.dec_attn.r_net.weight, layer_str + "ff/LayerNorm/gamma": b.pos_ff.layer_norm.weight, layer_str + "ff/LayerNorm/beta": b.pos_ff.layer_norm.bias, layer_str + "ff/layer_1/kernel": b.pos_ff.CoreNet[0].weight, layer_str + "ff/layer_1/bias": b.pos_ff.CoreNet[0].bias, layer_str + "ff/layer_2/kernel": b.pos_ff.CoreNet[3].weight, layer_str + "ff/layer_2/bias": b.pos_ff.CoreNet[3].bias, } ) # Relative positioning biases if config.untie_r: r_r_list = [] r_w_list = [] for b in model.layers: r_r_list.append(b.dec_attn.r_r_bias) r_w_list.append(b.dec_attn.r_w_bias) else: r_r_list = [model.r_r_bias] r_w_list = [model.r_w_bias] tf_to_pt_map.update({"transformer/r_r_bias": r_r_list, "transformer/r_w_bias": r_w_list}) return tf_to_pt_map def load_tf_weights_in_transfo_xl(model, config, tf_path): """Load tf checkpoints in a pytorch model""" try: import numpy as np import tensorflow as tf except ImportError: logger.error( "Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions." ) raise # Build TF to PyTorch weights loading map tf_to_pt_map = build_tf_to_pytorch_map(model, config) # Load weights from TF model init_vars = tf.train.list_variables(tf_path) tf_weights = {} for name, shape in init_vars: logger.info(f"Loading TF weight {name} with shape {shape}") array = tf.train.load_variable(tf_path, name) tf_weights[name] = array for name, pointer in tf_to_pt_map.items(): assert name in tf_weights array = tf_weights[name] # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v # which are not required for using pretrained model if "kernel" in name or "proj" in name: array = np.transpose(array) if ("r_r_bias" in name or "r_w_bias" in name) and len(pointer) > 1: # Here we will split the TF weights assert len(pointer) == array.shape[0] for i, p_i in enumerate(pointer): arr_i = array[i, ...] try: assert p_i.shape == arr_i.shape except AssertionError as e: e.args += (p_i.shape, arr_i.shape) raise logger.info(f"Initialize PyTorch weight {name} for layer {i}") p_i.data = torch.from_numpy(arr_i) else: try: assert ( pointer.shape == array.shape ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" except AssertionError as e: e.args += (pointer.shape, array.shape) raise logger.info(f"Initialize PyTorch weight {name}") pointer.data = torch.from_numpy(array) tf_weights.pop(name, None) tf_weights.pop(name + "/Adam", None) tf_weights.pop(name + "/Adam_1", None) logger.info(f"Weights not copied to PyTorch model: {', '.join(tf_weights.keys())}") return model class PositionalEmbedding(nn.Module): def __init__(self, demb): super().__init__() self.demb = demb inv_freq = 1 / (10000 ** (torch.arange(0.0, demb, 2.0) / demb)) self.register_buffer("inv_freq", inv_freq) def forward(self, pos_seq, bsz=None): sinusoid_inp = torch.ger(pos_seq, self.inv_freq) pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1) if bsz is not None: return pos_emb[:, None, :].expand(-1, bsz, -1) else: return pos_emb[:, None, :] class PositionwiseFF(nn.Module): def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5): super().__init__() self.d_model = d_model self.d_inner = d_inner self.dropout = dropout self.CoreNet = nn.Sequential( nn.Linear(d_model, d_inner), nn.ReLU(inplace=True), nn.Dropout(dropout), nn.Linear(d_inner, d_model), nn.Dropout(dropout), ) self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon) self.pre_lnorm = pre_lnorm def forward(self, inp): if self.pre_lnorm: # layer normalization + positionwise feed-forward core_out = self.CoreNet(self.layer_norm(inp)) # residual connection output = core_out + inp else: # positionwise feed-forward core_out = self.CoreNet(inp) # residual connection + layer normalization output = self.layer_norm(inp + core_out) return output class RelPartialLearnableMultiHeadAttn(nn.Module): def __init__( self, n_head, d_model, d_head, dropout, dropatt=0, pre_lnorm=False, r_r_bias=None, r_w_bias=None, layer_norm_epsilon=1e-5, ): super().__init__() self.n_head = n_head self.d_model = d_model self.d_head = d_head self.dropout = dropout self.qkv_net = nn.Linear(d_model, 3 * n_head * d_head, bias=False) self.drop = nn.Dropout(dropout) self.dropatt = nn.Dropout(dropatt) self.o_net = nn.Linear(n_head * d_head, d_model, bias=False) self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon) self.scale = 1 / (d_head**0.5) self.pre_lnorm = pre_lnorm if r_r_bias is None or r_w_bias is None: # Biases are not shared self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) else: self.r_r_bias = r_r_bias self.r_w_bias = r_w_bias self.r_net = nn.Linear(self.d_model, self.n_head * self.d_head, bias=False) def _rel_shift(self, x): zero_pad_shape = (x.size(0), 1) + x.size()[2:] zero_pad = torch.zeros(zero_pad_shape, device=x.device, dtype=x.dtype) x_padded = torch.cat([zero_pad, x], dim=1) x_padded_shape = (x.size(1) + 1, x.size(0)) + x.size()[2:] x_padded = x_padded.view(*x_padded_shape) x = x_padded[1:].view_as(x) return x def forward(self, w, r, attn_mask=None, mems=None, head_mask=None, output_attentions=False): qlen, rlen, bsz = w.size(0), r.size(0), w.size(1) if mems is not None: cat = torch.cat([mems, w], 0) if self.pre_lnorm: w_heads = self.qkv_net(self.layer_norm(cat)) else: w_heads = self.qkv_net(cat) r_head_k = self.r_net(r) w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1) w_head_q = w_head_q[-qlen:] else: if self.pre_lnorm: w_heads = self.qkv_net(self.layer_norm(w)) else: w_heads = self.qkv_net(w) r_head_k = self.r_net(r) w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1) klen = w_head_k.size(0) w_head_q = w_head_q.view(qlen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head w_head_k = w_head_k.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head w_head_v = w_head_v.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head r_head_k = r_head_k.view(rlen, self.n_head, self.d_head) # qlen x n_head x d_head # compute attention score rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head AC = torch.einsum("ibnd,jbnd->ijbn", (rw_head_q, w_head_k)) # qlen x klen x bsz x n_head rr_head_q = w_head_q + self.r_r_bias BD = torch.einsum("ibnd,jnd->ijbn", (rr_head_q, r_head_k)) # qlen x klen x bsz x n_head BD = self._rel_shift(BD) # [qlen x klen x bsz x n_head] attn_score = AC + BD attn_score.mul_(self.scale) # compute attention probability if attn_mask is not None and torch.sum(attn_mask).item(): attn_mask = attn_mask == 1 # Switch to bool if attn_mask.dim() == 2: if next(self.parameters()).dtype == torch.float16: attn_score = ( attn_score.float().masked_fill(attn_mask[None, :, :, None], -65000).type_as(attn_score) ) else: attn_score = attn_score.float().masked_fill(attn_mask[None, :, :, None], -1e30).type_as(attn_score) elif attn_mask.dim() == 3: if next(self.parameters()).dtype == torch.float16: attn_score = attn_score.float().masked_fill(attn_mask[:, :, :, None], -65000).type_as(attn_score) else: attn_score = attn_score.float().masked_fill(attn_mask[:, :, :, None], -1e30).type_as(attn_score) # [qlen x klen x bsz x n_head] attn_prob = nn.functional.softmax(attn_score, dim=1) attn_prob = self.dropatt(attn_prob) # Mask heads if we want to if head_mask is not None: attn_prob = attn_prob * head_mask # compute attention vector attn_vec = torch.einsum("ijbn,jbnd->ibnd", (attn_prob, w_head_v)) # [qlen x bsz x n_head x d_head] attn_vec = attn_vec.contiguous().view(attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head) # linear projection attn_out = self.o_net(attn_vec) attn_out = self.drop(attn_out) if self.pre_lnorm: # residual connection outputs = [w + attn_out] else: # residual connection + layer normalization outputs = [self.layer_norm(w + attn_out)] if output_attentions: outputs.append(attn_prob) return outputs class RelPartialLearnableDecoderLayer(nn.Module): def __init__(self, n_head, d_model, d_head, d_inner, dropout, layer_norm_epsilon=1e-5, **kwargs): super().__init__() self.dec_attn = RelPartialLearnableMultiHeadAttn( n_head, d_model, d_head, dropout, layer_norm_epsilon=layer_norm_epsilon, **kwargs ) self.pos_ff = PositionwiseFF( d_model, d_inner, dropout, pre_lnorm=kwargs.get("pre_lnorm"), layer_norm_epsilon=layer_norm_epsilon ) def forward(self, dec_inp, r, dec_attn_mask=None, mems=None, head_mask=None, output_attentions=False): attn_outputs = self.dec_attn( dec_inp, r, attn_mask=dec_attn_mask, mems=mems, head_mask=head_mask, output_attentions=output_attentions, ) ff_output = self.pos_ff(attn_outputs[0]) outputs = [ff_output] + attn_outputs[1:] return outputs class AdaptiveEmbedding(nn.Module): def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, sample_softmax=False): super().__init__() self.n_token = n_token self.d_embed = d_embed self.cutoffs = cutoffs + [n_token] self.div_val = div_val self.d_proj = d_proj self.emb_scale = d_proj**0.5 self.cutoff_ends = [0] + self.cutoffs self.emb_layers = nn.ModuleList() self.emb_projs = nn.ParameterList() if div_val == 1: self.emb_layers.append(nn.Embedding(n_token, d_embed, sparse=sample_softmax > 0)) if d_proj != d_embed: self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed))) else: for i in range(len(self.cutoffs)): l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] d_emb_i = d_embed // (div_val**i) self.emb_layers.append(nn.Embedding(r_idx - l_idx, d_emb_i)) self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i))) def forward(self, inp): if self.div_val == 1: embed = self.emb_layers[0](inp) if self.d_proj != self.d_embed: embed = nn.functional.linear(embed, self.emb_projs[0]) else: param = next(self.parameters()) inp_flat = inp.view(-1) emb_flat = torch.zeros([inp_flat.size(0), self.d_proj], dtype=param.dtype, device=param.device) for i in range(len(self.cutoffs)): l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx) indices_i = mask_i.nonzero().squeeze() if indices_i.numel() == 0: continue inp_i = inp_flat.index_select(0, indices_i) - l_idx emb_i = self.emb_layers[i](inp_i) emb_i = nn.functional.linear(emb_i, self.emb_projs[i]) emb_flat.index_copy_(0, indices_i, emb_i) embed_shape = inp.size() + (self.d_proj,) embed = emb_flat.view(embed_shape) embed.mul_(self.emb_scale) return embed class TransfoXLPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = TransfoXLConfig load_tf_weights = load_tf_weights_in_transfo_xl base_model_prefix = "transformer" def _init_weight(self, weight): if self.config.init == "uniform": nn.init.uniform_(weight, -self.config.init_range, self.config.init_range) elif self.config.init == "normal": nn.init.normal_(weight, 0.0, self.config.init_std) def _init_bias(self, bias): nn.init.constant_(bias, 0.0) def _init_weights(self, m): """Initialize the weights.""" classname = m.__class__.__name__ if classname.find("Linear") != -1: if hasattr(m, "weight") and m.weight is not None: self._init_weight(m.weight) if hasattr(m, "bias") and m.bias is not None: self._init_bias(m.bias) elif classname.find("AdaptiveEmbedding") != -1: if hasattr(m, "emb_projs"): for i in range(len(m.emb_projs)): if m.emb_projs[i] is not None: nn.init.normal_(m.emb_projs[i], 0.0, self.config.proj_init_std) elif classname.find("Embedding") != -1: if hasattr(m, "weight"): self._init_weight(m.weight) elif classname.find("ProjectedAdaptiveLogSoftmax") != -1: if hasattr(m, "cluster_weight") and m.cluster_weight is not None: self._init_weight(m.cluster_weight) if hasattr(m, "cluster_bias") and m.cluster_bias is not None: self._init_bias(m.cluster_bias) if hasattr(m, "out_projs"): for i in range(len(m.out_projs)): if m.out_projs[i] is not None: nn.init.normal_(m.out_projs[i], 0.0, self.config.proj_init_std) elif classname.find("LayerNorm") != -1: if hasattr(m, "weight"): nn.init.normal_(m.weight, 1.0, self.config.init_std) if hasattr(m, "bias") and m.bias is not None: self._init_bias(m.bias) else: if hasattr(m, "r_emb"): self._init_weight(m.r_emb) if hasattr(m, "r_w_bias"): self._init_weight(m.r_w_bias) if hasattr(m, "r_r_bias"): self._init_weight(m.r_r_bias) if hasattr(m, "r_bias"): self._init_bias(m.r_bias) def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, layer: Optional[int] = -1): """ Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. Take care of tying weights embeddings afterwards if the model class has a *tie_weights()* method. Arguments: new_num_tokens: (*optional*) int: New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or None: does nothing and just returns a pointer to the input tokens `torch.nn.Embeddings` Module of the model. layer: (*optional*) int: Layer of the *AdaptiveEmbedding* where the resizing should be done. Per default the last layer will be resized. Be aware that when resizing other than the last layer, you have to ensure that the new token(s) in the tokenizer are at the corresponding position. Return: `torch.nn.Embeddings` Pointer to the input tokens Embeddings Module of the model """ base_model = getattr(self, self.base_model_prefix, self) # get the base model if needed if new_num_tokens is None: return self.get_input_embeddings() new_num_tokens_layer, layer = self._get_new_num_tokens_layer(new_num_tokens, layer) assert new_num_tokens_layer > 0, "The size of the new embedding layer cannot be 0 or less" model_embeds = base_model._resize_token_embeddings(new_num_tokens_layer, layer) # Update base model and current model config self.config.vocab_size = new_num_tokens base_model.vocab_size = new_num_tokens base_model.n_token = new_num_tokens new_embedding_shapes = self._get_embedding_shapes() self._resize_cutoffs(new_num_tokens, new_num_tokens_layer, new_embedding_shapes, layer) # Tie weights again if needed self.tie_weights() return model_embeds def _get_new_num_tokens_layer(self, new_num_tokens, layer): embeddings = self.get_input_embeddings() if layer == -1: layer = len(embeddings.emb_layers) - 1 assert 0 <= layer <= len(embeddings.emb_layers) - 1 new_num_tokens_layer = ( new_num_tokens - sum([emb.weight.shape[0] for emb in embeddings.emb_layers[:layer]]) - sum([emb.weight.shape[0] for emb in embeddings.emb_layers[layer + 1 :]]) ) return new_num_tokens_layer, layer def _get_embedding_shapes(self): embeddings = self.get_input_embeddings() return [emb.weight.shape[0] for emb in embeddings.emb_layers] def _resize_token_embeddings(self, new_num_tokens, layer=-1): embeddings = self.get_input_embeddings() if new_num_tokens is None: return embeddings new_embeddings_layer = self._get_resized_embeddings(embeddings.emb_layers[layer], new_num_tokens) embeddings.emb_layers[layer] = new_embeddings_layer self.set_input_embeddings(embeddings) return self.get_input_embeddings() def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer): embeddings = self.get_input_embeddings() for i in range(layer, len(embeddings.cutoffs)): embeddings.cutoffs[i] = sum(new_embedding_shapes[: i + 1]) embeddings.cutoff_ends = [0] + embeddings.cutoffs embeddings.n_token = new_num_tokens self.config.cutoffs = embeddings.cutoffs[:-1] return embeddings.cutoffs @dataclass class TransfoXLModelOutput(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. mems (`List[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ last_hidden_state: torch.FloatTensor mems: List[torch.FloatTensor] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None @dataclass class TransfoXLSequenceClassifierOutputWithPast(ModelOutput): """ Base class for outputs of sentence classification models. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (before SoftMax). mems (`List[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None mems: List[torch.FloatTensor] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None @dataclass class TransfoXLLMHeadModelOutput(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: losses (`torch.FloatTensor` of shape *(batch_size, sequence_length-1)*, *optional*, returned when `labels` is provided): Language modeling losses (not reduced). prediction_scores (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token after SoftMax). mems (`List[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. loss (`torch.FloatTensor` of shape `()`, *optional*, returned when `labels` is provided) Reduced language modeling loss. """ losses: Optional[torch.FloatTensor] = None prediction_scores: torch.FloatTensor = None mems: List[torch.FloatTensor] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None loss: Optional[torch.FloatTensor] = None @property def logits(self): # prediction scores are the output of the adaptive softmax, see # the file `modeling_transfo_xl_utilities`. Since the adaptive # softmax returns the log softmax value, `self.prediction_scores` # are strictly speaking not exactly `logits`, but behave the same # way logits do. return self.prediction_scores TRANSFO_XL_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`TransfoXLConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ TRANSFO_XL_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`TransfoXLTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) mems (`List[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see `mems` output below). Can be used to speed up sequential decoding. The token ids which have their mems given to this model should not be passed as `input_ids` as they have already been computed. head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.", TRANSFO_XL_START_DOCSTRING, ) class TransfoXLModel(TransfoXLPreTrainedModel): def __init__(self, config): super().__init__(config) self.n_token = config.vocab_size self.d_embed = config.d_embed self.d_model = config.d_model self.n_head = config.n_head self.d_head = config.d_head self.word_emb = AdaptiveEmbedding( config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val ) self.drop = nn.Dropout(config.dropout) self.n_layer = config.n_layer self.mem_len = config.mem_len self.attn_type = config.attn_type if not config.untie_r: self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) self.layers = nn.ModuleList() if config.attn_type == 0: # the default attention for i in range(config.n_layer): self.layers.append( RelPartialLearnableDecoderLayer( config.n_head, config.d_model, config.d_head, config.d_inner, config.dropout, dropatt=config.dropatt, pre_lnorm=config.pre_lnorm, r_w_bias=None if config.untie_r else self.r_w_bias, r_r_bias=None if config.untie_r else self.r_r_bias, layer_norm_epsilon=config.layer_norm_epsilon, ) ) else: # learnable embeddings and absolute embeddings are not used in our pretrained checkpoints raise NotImplementedError # Removed them to avoid maintaining dead code self.same_length = config.same_length self.clamp_len = config.clamp_len if self.attn_type == 0: # default attention self.pos_emb = PositionalEmbedding(self.d_model) else: # learnable embeddings and absolute embeddings raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.word_emb def set_input_embeddings(self, new_embeddings): self.word_emb = new_embeddings def backward_compatible(self): self.sample_softmax = -1 def reset_memory_length(self, mem_len): self.mem_len = mem_len def _prune_heads(self, heads): logger.info("Head pruning is not implemented for Transformer-XL model") pass def init_mems(self, bsz): if self.mem_len > 0: mems = [] param = next(self.parameters()) for i in range(self.n_layer): empty = torch.zeros(self.mem_len, bsz, self.config.d_model, dtype=param.dtype, device=param.device) mems.append(empty) return mems else: return None def _update_mems(self, hids, mems, mlen, qlen): # does not deal with None if mems is None: return None # mems is not None assert len(hids) == len(mems), "len(hids) != len(mems)" # There are `mlen + qlen` steps that can be cached into mems with torch.no_grad(): new_mems = [] end_idx = mlen + max(0, qlen) beg_idx = max(0, end_idx - self.mem_len) for i in range(len(hids)): cat = torch.cat([mems[i], hids[i]], dim=0) new_mems.append(cat[beg_idx:end_idx].detach()) return new_mems @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=TransfoXLModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.LongTensor] = None, mems: Optional[List[torch.FloatTensor]] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, TransfoXLModelOutput]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict # the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library # so we transpose here from shape [bsz, len] to shape [len, bsz] if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_ids = input_ids.transpose(0, 1).contiguous() qlen, bsz = input_ids.size() elif inputs_embeds is not None: inputs_embeds = inputs_embeds.transpose(0, 1).contiguous() qlen, bsz = inputs_embeds.shape[0], inputs_embeds.shape[1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") if mems is None: mems = self.init_mems(bsz) # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer) # and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head] if head_mask is not None: if head_mask.dim() == 1: head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(0).unsqueeze(0) head_mask = head_mask.expand(self.n_layer, -1, -1, -1, -1) elif head_mask.dim() == 2: head_mask = head_mask.unsqueeze(1).unsqueeze(1).unsqueeze(1) head_mask = head_mask.to( dtype=next(self.parameters()).dtype ) # switch to float if need + fp16 compatibility else: head_mask = [None] * self.n_layer if inputs_embeds is not None: word_emb = inputs_embeds else: word_emb = self.word_emb(input_ids) mlen = mems[0].size(0) if mems is not None else 0 klen = mlen + qlen if self.same_length: all_ones = word_emb.new_ones((qlen, klen), dtype=torch.uint8) mask_len = klen - self.mem_len if mask_len > 0: mask_shift_len = qlen - mask_len else: mask_shift_len = qlen dec_attn_mask = (torch.triu(all_ones, 1 + mlen) + torch.tril(all_ones, -mask_shift_len))[:, :, None] # -1 else: dec_attn_mask = torch.triu(word_emb.new_ones((qlen, klen), dtype=torch.uint8), diagonal=1 + mlen)[ :, :, None ] hids = [] attentions = [] if output_attentions else None if self.attn_type == 0: # default pos_seq = torch.arange(klen - 1, -1, -1.0, device=word_emb.device, dtype=word_emb.dtype) if self.clamp_len > 0: pos_seq.clamp_(max=self.clamp_len) pos_emb = self.pos_emb(pos_seq) core_out = self.drop(word_emb) pos_emb = self.drop(pos_emb) for i, layer in enumerate(self.layers): hids.append(core_out) mems_i = None if mems is None else mems[i] layer_outputs = layer( core_out, pos_emb, dec_attn_mask=dec_attn_mask, mems=mems_i, head_mask=head_mask[i], output_attentions=output_attentions, ) core_out = layer_outputs[0] if output_attentions: attentions.append(layer_outputs[1]) else: # learnable embeddings and absolute embeddings raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint core_out = self.drop(core_out) new_mems = self._update_mems(hids, mems, mlen, qlen) if output_hidden_states: # Add last layer and transpose to library standard shape [bsz, len, hidden_dim] hids.append(core_out) hids = tuple(t.transpose(0, 1).contiguous() for t in hids) else: hids = None if output_attentions: # Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len] attentions = tuple(t.permute(2, 3, 0, 1).contiguous() for t in attentions) # We transpose back here to shape [bsz, len, hidden_dim] core_out = core_out.transpose(0, 1).contiguous() if not return_dict: return tuple(v for v in [core_out, new_mems, hids, attentions] if v is not None) return TransfoXLModelOutput( last_hidden_state=core_out, mems=new_mems, hidden_states=hids, attentions=attentions, ) @add_start_docstrings( """ The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive input embeddings) """, TRANSFO_XL_START_DOCSTRING, ) class TransfoXLLMHeadModel(TransfoXLPreTrainedModel): def __init__(self, config): super().__init__(config) self.transformer = TransfoXLModel(config) self.sample_softmax = config.sample_softmax self.trainer_compatible = getattr(config, "trainer_compatible", False) if not self.trainer_compatible: warnings.warn( "The output of TransfoXL will be updated in v5 to support a single loss as first argument. In order" "to use that updated output, please specify `trainer_compatible=True` as your configuration" " attribute.", DeprecationWarning, ) assert self.sample_softmax <= 0, ( "Sampling from the softmax is not implemented yet. Please look at issue: #3310:" " https://github.com/huggingface/transformers/issues/3310" ) self.crit = ProjectedAdaptiveLogSoftmax( config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val ) # Initialize weights and apply final processing self.post_init() def tie_weights(self): """ Run this to be sure output and input (adaptive) softmax weights are tied """ if self.config.tie_word_embeddings: for i in range(len(self.crit.out_layers)): self._tie_or_clone_weights(self.crit.out_layers[i], self.transformer.word_emb.emb_layers[i]) if self.config.tie_projs: for i, tie_proj in enumerate(self.config.tie_projs): if tie_proj and self.config.div_val == 1 and self.config.d_model != self.config.d_embed: if self.config.torchscript: self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[0].clone()) else: self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[0] elif tie_proj and self.config.div_val != 1: if self.config.torchscript: self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[i].clone()) else: self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[i] def reset_memory_length(self, mem_len): self.transformer.reset_memory_length(mem_len) def init_mems(self, bsz): return self.transformer.init_mems(bsz) @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=TransfoXLLMHeadModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.LongTensor] = None, mems: Optional[List[torch.FloatTensor]] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, TransfoXLLMHeadModelOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None: bsz, tgt_len = input_ids.size(0), input_ids.size(1) elif inputs_embeds is not None: bsz, tgt_len = inputs_embeds.size(0), inputs_embeds.size(1) else: raise ValueError("You have to specify either input_ids or inputs_embeds") transformer_outputs = self.transformer( input_ids, mems=mems, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) last_hidden = transformer_outputs[0] pred_hid = last_hidden[:, -tgt_len:] if labels is not None: # Prevents all labels being -100 and throwing an error # when backwarding the loss miss_valid_label = labels[0, 1:].sum() == (labels.size(1) - 1) * -100 if miss_valid_label: # Sets an <EOS> token, just to prevent loss from being NaN labels[0, 1] = self.config.eos_token_id softmax_output = self.crit(pred_hid, labels) prediction_scores = softmax_output.view(bsz, tgt_len, -1) if labels is None else () if labels is not None: losses = softmax_output.view(bsz, tgt_len - 1) # Avoids from incorporating padding (-100) tokens into loss value loss = losses[losses != 0].mean() else: losses, loss = None, None if not return_dict: if self.trainer_compatible: output = (prediction_scores, losses) if losses is not None else (prediction_scores,) output += transformer_outputs[1:] return ((loss,) + output) if loss is not None else output else: output = (prediction_scores, *transformer_outputs[1:]) output = ((losses,) + output) if losses is not None else output return (output + (loss,)) if loss is not None else output return TransfoXLLMHeadModelOutput( loss=loss, prediction_scores=prediction_scores, losses=losses, mems=transformer_outputs.mems, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) def get_output_embeddings(self): """Double-check if you are using adaptive softmax.""" if self.sample_softmax > 0: return self.out_layer else: return self.crit.out_layers[-1] def prepare_inputs_for_generation(self, input_ids, past=None, **model_kwargs): inputs = {} # if past is defined in model kwargs then use it for faster decoding if past: inputs["mems"] = past inputs["input_ids"] = input_ids[:, -1].unsqueeze(-1) else: inputs["input_ids"] = input_ids return inputs def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer): new_cutoffs = super()._resize_cutoffs(new_num_tokens, new_emb_size, new_embedding_shapes, layer) self.crit.cutoffs = new_cutoffs self.crit.cutoff_ends = [0] + new_cutoffs self.crit.n_token = new_num_tokens @staticmethod def _reorder_cache(mems: List[torch.Tensor], beam_idx: torch.Tensor) -> List[torch.Tensor]: """ This function is used to re-order the `mems` cache if [`~PreTrainedModel.beam_search`] or [`~PreTrainedModel.beam_sample`] is called. This is required to match `mems` with the correct beam_idx at every generation step. """ return [layer_past.index_select(1, beam_idx.to(layer_past.device)) for layer_past in mems] @add_start_docstrings( """ The Transformer-XL Model transformer with a sequence classification head on top (linear layer). [`TransfoXLForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-1) do. Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch). """, TRANSFO_XL_START_DOCSTRING, ) class TransfoXLForSequenceClassification(TransfoXLPreTrainedModel): _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head.weight"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.transformer = TransfoXLModel(config) self.score = nn.Linear(config.d_embed, self.num_labels, bias=False) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=TransfoXLSequenceClassifierOutputWithPast, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.LongTensor] = None, mems: Optional[List[torch.FloatTensor]] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, TransfoXLSequenceClassifierOutputWithPast]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict transformer_outputs = self.transformer( input_ids, mems=mems, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = transformer_outputs[0] logits = self.score(hidden_states) if input_ids is not None: batch_size, sequence_length = input_ids.shape[:2] else: batch_size, sequence_length = inputs_embeds.shape[:2] assert ( self.config.pad_token_id is not None or batch_size == 1 ), "Cannot handle batch sizes > 1 if no padding token is defined." if self.config.pad_token_id is None: sequence_lengths = -1 else: if input_ids is not None: sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1 else: sequence_lengths = -1 logger.warning( f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " "unexpected if using padding tokens in conjunction with `inputs_embeds.`" ) pooled_logits = logits[range(batch_size), sequence_lengths] loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification" if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) else: loss = loss_fct(pooled_logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(pooled_logits, labels) if not return_dict: output = (pooled_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output return TransfoXLSequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, mems=transformer_outputs.mems, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, )
""" Module for formatting output data in HTML. """ from textwrap import dedent from typing import ( Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union, cast, ) from pandas._config import get_option from pandas._libs import lib from pandas import ( MultiIndex, option_context, ) from pandas.io.common import is_url from pandas.io.formats.format import ( DataFrameFormatter, get_level_lengths, ) from pandas.io.formats.printing import pprint_thing class HTMLFormatter: """ Internal class for formatting output data in html. This class is intended for shared functionality between DataFrame.to_html() and DataFrame._repr_html_(). Any logic in common with other output formatting methods should ideally be inherited from classes in format.py and this class responsible for only producing html markup. """ indent_delta = 2 def __init__( self, formatter: DataFrameFormatter, classes: Optional[Union[str, List[str], Tuple[str, ...]]] = None, border: Optional[int] = None, table_id: Optional[str] = None, render_links: bool = False, ) -> None: self.fmt = formatter self.classes = classes self.frame = self.fmt.frame self.columns = self.fmt.tr_frame.columns self.elements: List[str] = [] self.bold_rows = self.fmt.bold_rows self.escape = self.fmt.escape self.show_dimensions = self.fmt.show_dimensions if border is None: border = cast(int, get_option("display.html.border")) self.border = border self.table_id = table_id self.render_links = render_links self.col_space = { column: f"{value}px" if isinstance(value, int) else value for column, value in self.fmt.col_space.items() } def to_string(self) -> str: lines = self.render() if any(isinstance(x, str) for x in lines): lines = [str(x) for x in lines] return "\n".join(lines) def render(self) -> List[str]: self._write_table() if self.should_show_dimensions: by = chr(215) # × self.write( f"<p>{len(self.frame)} rows {by} {len(self.frame.columns)} columns</p>" ) return self.elements @property def should_show_dimensions(self): return self.fmt.should_show_dimensions @property def show_row_idx_names(self) -> bool: return self.fmt.show_row_idx_names @property def show_col_idx_names(self) -> bool: return self.fmt.show_col_idx_names @property def row_levels(self) -> int: if self.fmt.index: # showing (row) index return self.frame.index.nlevels elif self.show_col_idx_names: # see gh-22579 # Column misalignment also occurs for # a standard index when the columns index is named. # If the row index is not displayed a column of # blank cells need to be included before the DataFrame values. return 1 # not showing (row) index return 0 def _get_columns_formatted_values(self) -> Iterable: return self.columns @property def is_truncated(self) -> bool: return self.fmt.is_truncated @property def ncols(self) -> int: return len(self.fmt.tr_frame.columns) def write(self, s: Any, indent: int = 0) -> None: rs = pprint_thing(s) self.elements.append(" " * indent + rs) def write_th( self, s: Any, header: bool = False, indent: int = 0, tags: Optional[str] = None ) -> None: """ Method for writing a formatted <th> cell. If col_space is set on the formatter then that is used for the value of min-width. Parameters ---------- s : object The data to be written inside the cell. header : bool, default False Set to True if the <th> is for use inside <thead>. This will cause min-width to be set if there is one. indent : int, default 0 The indentation level of the cell. tags : str, default None Tags to include in the cell. Returns ------- A written <th> cell. """ col_space = self.col_space.get(s, None) if header and col_space is not None: tags = tags or "" tags += f'style="min-width: {col_space};"' self._write_cell(s, kind="th", indent=indent, tags=tags) def write_td(self, s: Any, indent: int = 0, tags: Optional[str] = None) -> None: self._write_cell(s, kind="td", indent=indent, tags=tags) def _write_cell( self, s: Any, kind: str = "td", indent: int = 0, tags: Optional[str] = None ) -> None: if tags is not None: start_tag = f"<{kind} {tags}>" else: start_tag = f"<{kind}>" if self.escape: # escape & first to prevent double escaping of & esc = {"&": r"&amp;", "<": r"&lt;", ">": r"&gt;"} else: esc = {} rs = pprint_thing(s, escape_chars=esc).strip() if self.render_links and is_url(rs): rs_unescaped = pprint_thing(s, escape_chars={}).strip() start_tag += f'<a href="{rs_unescaped}" target="_blank">' end_a = "</a>" else: end_a = "" self.write(f"{start_tag}{rs}{end_a}</{kind}>", indent) def write_tr( self, line: Iterable, indent: int = 0, indent_delta: int = 0, header: bool = False, align: Optional[str] = None, tags: Optional[Dict[int, str]] = None, nindex_levels: int = 0, ) -> None: if tags is None: tags = {} if align is None: self.write("<tr>", indent) else: self.write(f'<tr style="text-align: {align};">', indent) indent += indent_delta for i, s in enumerate(line): val_tag = tags.get(i, None) if header or (self.bold_rows and i < nindex_levels): self.write_th(s, indent=indent, header=header, tags=val_tag) else: self.write_td(s, indent, tags=val_tag) indent -= indent_delta self.write("</tr>", indent) def _write_table(self, indent: int = 0) -> None: _classes = ["dataframe"] # Default class. use_mathjax = get_option("display.html.use_mathjax") if not use_mathjax: _classes.append("tex2jax_ignore") if self.classes is not None: if isinstance(self.classes, str): self.classes = self.classes.split() if not isinstance(self.classes, (list, tuple)): raise TypeError( "classes must be a string, list, " f"or tuple, not {type(self.classes)}" ) _classes.extend(self.classes) if self.table_id is None: id_section = "" else: id_section = f' id="{self.table_id}"' self.write( f'<table border="{self.border}' class='{' '.join(_classes)}"{id_section}>', indent, ) if self.fmt.header or self.show_row_idx_names: self._write_header(indent + self.indent_delta) self._write_body(indent + self.indent_delta) self.write("</table>", indent) def _write_col_header(self, indent: int) -> None: is_truncated_horizontally = self.fmt.is_truncated_horizontally if isinstance(self.columns, MultiIndex): template = 'colspan="{span:d}" halign="left"' sentinel: lib.NoDefault | bool if self.fmt.sparsify: # GH3547 sentinel = lib.no_default else: sentinel = False levels = self.columns.format(sparsify=sentinel, adjoin=False, names=False) level_lengths = get_level_lengths(levels, sentinel) inner_lvl = len(level_lengths) - 1 for lnum, (records, values) in enumerate(zip(level_lengths, levels)): if is_truncated_horizontally: # modify the header lines ins_col = self.fmt.tr_col_num if self.fmt.sparsify: recs_new = {} # Increment tags after ... col. for tag, span in list(records.items()): if tag >= ins_col: recs_new[tag + 1] = span elif tag + span > ins_col: recs_new[tag] = span + 1 if lnum == inner_lvl: values = ( values[:ins_col] + ("...",) + values[ins_col:] ) else: # sparse col headers do not receive a ... values = ( values[:ins_col] + (values[ins_col - 1],) + values[ins_col:] ) else: recs_new[tag] = span # if ins_col lies between tags, all col headers # get ... if tag + span == ins_col: recs_new[ins_col] = 1 values = values[:ins_col] + ("...",) + values[ins_col:] records = recs_new inner_lvl = len(level_lengths) - 1 if lnum == inner_lvl: records[ins_col] = 1 else: recs_new = {} for tag, span in list(records.items()): if tag >= ins_col: recs_new[tag + 1] = span else: recs_new[tag] = span recs_new[ins_col] = 1 records = recs_new values = values[:ins_col] + ["..."] + values[ins_col:] # see gh-22579 # Column Offset Bug with to_html(index=False) with # MultiIndex Columns and Index. # Initially fill row with blank cells before column names. # TODO: Refactor to remove code duplication with code # block below for standard columns index. row = [""] * (self.row_levels - 1) if self.fmt.index or self.show_col_idx_names: # see gh-22747 # If to_html(index_names=False) do not show columns # index names. # TODO: Refactor to use _get_column_name_list from # DataFrameFormatter class and create a # _get_formatted_column_labels function for code # parity with DataFrameFormatter class. if self.fmt.show_index_names: name = self.columns.names[lnum] row.append(pprint_thing(name or "")) else: row.append("") tags = {} j = len(row) for i, v in enumerate(values): if i in records: if records[i] > 1: tags[j] = template.format(span=records[i]) else: continue j += 1 row.append(v) self.write_tr(row, indent, self.indent_delta, tags=tags, header=True) else: # see gh-22579 # Column misalignment also occurs for # a standard index when the columns index is named. # Initially fill row with blank cells before column names. # TODO: Refactor to remove code duplication with code block # above for columns MultiIndex. row = [""] * (self.row_levels - 1) if self.fmt.index or self.show_col_idx_names: # see gh-22747 # If to_html(index_names=False) do not show columns # index names. # TODO: Refactor to use _get_column_name_list from # DataFrameFormatter class. if self.fmt.show_index_names: row.append(self.columns.name or "") else: row.append("") row.extend(self._get_columns_formatted_values()) align = self.fmt.justify if is_truncated_horizontally: ins_col = self.row_levels + self.fmt.tr_col_num row.insert(ins_col, "...") self.write_tr(row, indent, self.indent_delta, header=True, align=align) def _write_row_header(self, indent: int) -> None: is_truncated_horizontally = self.fmt.is_truncated_horizontally row = [x if x is not None else "" for x in self.frame.index.names] + [""] * ( self.ncols + (1 if is_truncated_horizontally else 0) ) self.write_tr(row, indent, self.indent_delta, header=True) def _write_header(self, indent: int) -> None: self.write("<thead>", indent) if self.fmt.header: self._write_col_header(indent + self.indent_delta) if self.show_row_idx_names: self._write_row_header(indent + self.indent_delta) self.write("</thead>", indent) def _get_formatted_values(self) -> Dict[int, List[str]]: with option_context("display.max_colwidth", None): fmt_values = {i: self.fmt.format_col(i) for i in range(self.ncols)} return fmt_values def _write_body(self, indent: int) -> None: self.write("<tbody>", indent) fmt_values = self._get_formatted_values() # write values if self.fmt.index and isinstance(self.frame.index, MultiIndex): self._write_hierarchical_rows(fmt_values, indent + self.indent_delta) else: self._write_regular_rows(fmt_values, indent + self.indent_delta) self.write("</tbody>", indent) def _write_regular_rows( self, fmt_values: Mapping[int, List[str]], indent: int ) -> None: is_truncated_horizontally = self.fmt.is_truncated_horizontally is_truncated_vertically = self.fmt.is_truncated_vertically nrows = len(self.fmt.tr_frame) if self.fmt.index: fmt = self.fmt._get_formatter("__index__") if fmt is not None: index_values = self.fmt.tr_frame.index.map(fmt) else: index_values = self.fmt.tr_frame.index.format() row: List[str] = [] for i in range(nrows): if is_truncated_vertically and i == (self.fmt.tr_row_num): str_sep_row = ["..."] * len(row) self.write_tr( str_sep_row, indent, self.indent_delta, tags=None, nindex_levels=self.row_levels, ) row = [] if self.fmt.index: row.append(index_values[i]) # see gh-22579 # Column misalignment also occurs for # a standard index when the columns index is named. # Add blank cell before data cells. elif self.show_col_idx_names: row.append("") row.extend(fmt_values[j][i] for j in range(self.ncols)) if is_truncated_horizontally: dot_col_ix = self.fmt.tr_col_num + self.row_levels row.insert(dot_col_ix, "...") self.write_tr( row, indent, self.indent_delta, tags=None, nindex_levels=self.row_levels ) def _write_hierarchical_rows( self, fmt_values: Mapping[int, List[str]], indent: int ) -> None: template = 'rowspan="{span}" valign="top"' is_truncated_horizontally = self.fmt.is_truncated_horizontally is_truncated_vertically = self.fmt.is_truncated_vertically frame = self.fmt.tr_frame nrows = len(frame) assert isinstance(frame.index, MultiIndex) idx_values = frame.index.format(sparsify=False, adjoin=False, names=False) idx_values = list(zip(*idx_values)) if self.fmt.sparsify: # GH3547 sentinel = lib.no_default levels = frame.index.format(sparsify=sentinel, adjoin=False, names=False) level_lengths = get_level_lengths(levels, sentinel) inner_lvl = len(level_lengths) - 1 if is_truncated_vertically: # Insert ... row and adjust idx_values and # level_lengths to take this into account. ins_row = self.fmt.tr_row_num inserted = False for lnum, records in enumerate(level_lengths): rec_new = {} for tag, span in list(records.items()): if tag >= ins_row: rec_new[tag + 1] = span elif tag + span > ins_row: rec_new[tag] = span + 1 # GH 14882 - Make sure insertion done once if not inserted: dot_row = list(idx_values[ins_row - 1]) dot_row[-1] = "..." idx_values.insert(ins_row, tuple(dot_row)) inserted = True else: dot_row = list(idx_values[ins_row]) dot_row[inner_lvl - lnum] = "..." idx_values[ins_row] = tuple(dot_row) else: rec_new[tag] = span # If ins_row lies between tags, all cols idx cols # receive ... if tag + span == ins_row: rec_new[ins_row] = 1 if lnum == 0: idx_values.insert( ins_row, tuple(["..."] * len(level_lengths)) ) # GH 14882 - Place ... in correct level elif inserted: dot_row = list(idx_values[ins_row]) dot_row[inner_lvl - lnum] = "..." idx_values[ins_row] = tuple(dot_row) level_lengths[lnum] = rec_new level_lengths[inner_lvl][ins_row] = 1 for ix_col in range(len(fmt_values)): fmt_values[ix_col].insert(ins_row, "...") nrows += 1 for i in range(nrows): row = [] tags = {} sparse_offset = 0 j = 0 for records, v in zip(level_lengths, idx_values[i]): if i in records: if records[i] > 1: tags[j] = template.format(span=records[i]) else: sparse_offset += 1 continue j += 1 row.append(v) row.extend(fmt_values[j][i] for j in range(self.ncols)) if is_truncated_horizontally: row.insert( self.row_levels - sparse_offset + self.fmt.tr_col_num, "..." ) self.write_tr( row, indent, self.indent_delta, tags=tags, nindex_levels=len(levels) - sparse_offset, ) else: row = [] for i in range(len(frame)): if is_truncated_vertically and i == (self.fmt.tr_row_num): str_sep_row = ["..."] * len(row) self.write_tr( str_sep_row, indent, self.indent_delta, tags=None, nindex_levels=self.row_levels, ) idx_values = list( zip(*frame.index.format(sparsify=False, adjoin=False, names=False)) ) row = [] row.extend(idx_values[i]) row.extend(fmt_values[j][i] for j in range(self.ncols)) if is_truncated_horizontally: row.insert(self.row_levels + self.fmt.tr_col_num, "...") self.write_tr( row, indent, self.indent_delta, tags=None, nindex_levels=frame.index.nlevels, ) class NotebookFormatter(HTMLFormatter): """ Internal class for formatting output data in html for display in Jupyter Notebooks. This class is intended for functionality specific to DataFrame._repr_html_() and DataFrame.to_html(notebook=True) """ def _get_formatted_values(self) -> Dict[int, List[str]]: return {i: self.fmt.format_col(i) for i in range(self.ncols)} def _get_columns_formatted_values(self) -> List[str]: return self.columns.format() def write_style(self) -> None: # We use the "scoped" attribute here so that the desired # style properties for the data frame are not then applied # throughout the entire notebook. template_first = """\ <style scoped>""" template_last = """\ </style>""" template_select = """\ .dataframe %s { %s: %s; }""" element_props = [ ("tbody tr th:only-of-type", "vertical-align", "middle"), ("tbody tr th", "vertical-align", "top"), ] if isinstance(self.columns, MultiIndex): element_props.append(("thead tr th", "text-align", "left")) if self.show_row_idx_names: element_props.append( ("thead tr:last-of-type th", "text-align", "right") ) else: element_props.append(("thead th", "text-align", "right")) template_mid = "\n\n".join(map(lambda t: template_select % t, element_props)) template = dedent("\n".join((template_first, template_mid, template_last))) self.write(template) def render(self) -> List[str]: self.write("<div>") self.write_style() super().render() self.write("</div>") return self.elements
""" Module for formatting output data in HTML. """ from textwrap import dedent from typing import ( Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union, cast, ) from pandas._config import get_option from pandas._libs import lib from pandas import ( MultiIndex, option_context, ) from pandas.io.common import is_url from pandas.io.formats.format import ( DataFrameFormatter, get_level_lengths, ) from pandas.io.formats.printing import pprint_thing class HTMLFormatter: """ Internal class for formatting output data in html. This class is intended for shared functionality between DataFrame.to_html() and DataFrame._repr_html_(). Any logic in common with other output formatting methods should ideally be inherited from classes in format.py and this class responsible for only producing html markup. """ indent_delta = 2 def __init__( self, formatter: DataFrameFormatter, classes: Optional[Union[str, List[str], Tuple[str, ...]]] = None, border: Optional[int] = None, table_id: Optional[str] = None, render_links: bool = False, ) -> None: self.fmt = formatter self.classes = classes self.frame = self.fmt.frame self.columns = self.fmt.tr_frame.columns self.elements: List[str] = [] self.bold_rows = self.fmt.bold_rows self.escape = self.fmt.escape self.show_dimensions = self.fmt.show_dimensions if border is None: border = cast(int, get_option("display.html.border")) self.border = border self.table_id = table_id self.render_links = render_links self.col_space = { column: f"{value}px" if isinstance(value, int) else value for column, value in self.fmt.col_space.items() } def to_string(self) -> str: lines = self.render() if any(isinstance(x, str) for x in lines): lines = [str(x) for x in lines] return "\n".join(lines) def render(self) -> List[str]: self._write_table() if self.should_show_dimensions: by = chr(215) # × self.write( f"<p>{len(self.frame)} rows {by} {len(self.frame.columns)} columns</p>" ) return self.elements @property def should_show_dimensions(self): return self.fmt.should_show_dimensions @property def show_row_idx_names(self) -> bool: return self.fmt.show_row_idx_names @property def show_col_idx_names(self) -> bool: return self.fmt.show_col_idx_names @property def row_levels(self) -> int: if self.fmt.index: # showing (row) index return self.frame.index.nlevels elif self.show_col_idx_names: # see gh-22579 # Column misalignment also occurs for # a standard index when the columns index is named. # If the row index is not displayed a column of # blank cells need to be included before the DataFrame values. return 1 # not showing (row) index return 0 def _get_columns_formatted_values(self) -> Iterable: return self.columns @property def is_truncated(self) -> bool: return self.fmt.is_truncated @property def ncols(self) -> int: return len(self.fmt.tr_frame.columns) def write(self, s: Any, indent: int = 0) -> None: rs = pprint_thing(s) self.elements.append(" " * indent + rs) def write_th( self, s: Any, header: bool = False, indent: int = 0, tags: Optional[str] = None ) -> None: """ Method for writing a formatted <th> cell. If col_space is set on the formatter then that is used for the value of min-width. Parameters ---------- s : object The data to be written inside the cell. header : bool, default False Set to True if the <th> is for use inside <thead>. This will cause min-width to be set if there is one. indent : int, default 0 The indentation level of the cell. tags : str, default None Tags to include in the cell. Returns ------- A written <th> cell. """ col_space = self.col_space.get(s, None) if header and col_space is not None: tags = tags or "" tags += f'style="min-width: {col_space};"' self._write_cell(s, kind="th", indent=indent, tags=tags) def write_td(self, s: Any, indent: int = 0, tags: Optional[str] = None) -> None: self._write_cell(s, kind="td", indent=indent, tags=tags) def _write_cell( self, s: Any, kind: str = "td", indent: int = 0, tags: Optional[str] = None ) -> None: if tags is not None: start_tag = f"<{kind} {tags}>" else: start_tag = f"<{kind}>" if self.escape: # escape & first to prevent double escaping of & esc = {"&": r"&amp;", "<": r"&lt;", ">": r"&gt;"} else: esc = {} rs = pprint_thing(s, escape_chars=esc).strip() if self.render_links and is_url(rs): rs_unescaped = pprint_thing(s, escape_chars={}).strip() start_tag += f'<a href="{rs_unescaped}" target="_blank">' end_a = "</a>" else: end_a = "" self.write(f"{start_tag}{rs}{end_a}</{kind}>", indent) def write_tr( self, line: Iterable, indent: int = 0, indent_delta: int = 0, header: bool = False, align: Optional[str] = None, tags: Optional[Dict[int, str]] = None, nindex_levels: int = 0, ) -> None: if tags is None: tags = {} if align is None: self.write("<tr>", indent) else: self.write(f'<tr style="text-align: {align};">', indent) indent += indent_delta for i, s in enumerate(line): val_tag = tags.get(i, None) if header or (self.bold_rows and i < nindex_levels): self.write_th(s, indent=indent, header=header, tags=val_tag) else: self.write_td(s, indent, tags=val_tag) indent -= indent_delta self.write("</tr>", indent) def _write_table(self, indent: int = 0) -> None: _classes = ["dataframe"] # Default class. use_mathjax = get_option("display.html.use_mathjax") if not use_mathjax: _classes.append("tex2jax_ignore") if self.classes is not None: if isinstance(self.classes, str): self.classes = self.classes.split() if not isinstance(self.classes, (list, tuple)): raise TypeError( "classes must be a string, list, " f"or tuple, not {type(self.classes)}" ) _classes.extend(self.classes) if self.table_id is None: id_section = "" else: id_section = f' id="{self.table_id}"' self.write( f'<table border="{self.border}" class="{" ".join(_classes)}"{id_section}>', indent, ) if self.fmt.header or self.show_row_idx_names: self._write_header(indent + self.indent_delta) self._write_body(indent + self.indent_delta) self.write("</table>", indent) def _write_col_header(self, indent: int) -> None: is_truncated_horizontally = self.fmt.is_truncated_horizontally if isinstance(self.columns, MultiIndex): template = 'colspan="{span:d}" halign="left"' sentinel: lib.NoDefault | bool if self.fmt.sparsify: # GH3547 sentinel = lib.no_default else: sentinel = False levels = self.columns.format(sparsify=sentinel, adjoin=False, names=False) level_lengths = get_level_lengths(levels, sentinel) inner_lvl = len(level_lengths) - 1 for lnum, (records, values) in enumerate(zip(level_lengths, levels)): if is_truncated_horizontally: # modify the header lines ins_col = self.fmt.tr_col_num if self.fmt.sparsify: recs_new = {} # Increment tags after ... col. for tag, span in list(records.items()): if tag >= ins_col: recs_new[tag + 1] = span elif tag + span > ins_col: recs_new[tag] = span + 1 if lnum == inner_lvl: values = ( values[:ins_col] + ("...",) + values[ins_col:] ) else: # sparse col headers do not receive a ... values = ( values[:ins_col] + (values[ins_col - 1],) + values[ins_col:] ) else: recs_new[tag] = span # if ins_col lies between tags, all col headers # get ... if tag + span == ins_col: recs_new[ins_col] = 1 values = values[:ins_col] + ("...",) + values[ins_col:] records = recs_new inner_lvl = len(level_lengths) - 1 if lnum == inner_lvl: records[ins_col] = 1 else: recs_new = {} for tag, span in list(records.items()): if tag >= ins_col: recs_new[tag + 1] = span else: recs_new[tag] = span recs_new[ins_col] = 1 records = recs_new values = values[:ins_col] + ["..."] + values[ins_col:] # see gh-22579 # Column Offset Bug with to_html(index=False) with # MultiIndex Columns and Index. # Initially fill row with blank cells before column names. # TODO: Refactor to remove code duplication with code # block below for standard columns index. row = [""] * (self.row_levels - 1) if self.fmt.index or self.show_col_idx_names: # see gh-22747 # If to_html(index_names=False) do not show columns # index names. # TODO: Refactor to use _get_column_name_list from # DataFrameFormatter class and create a # _get_formatted_column_labels function for code # parity with DataFrameFormatter class. if self.fmt.show_index_names: name = self.columns.names[lnum] row.append(pprint_thing(name or "")) else: row.append("") tags = {} j = len(row) for i, v in enumerate(values): if i in records: if records[i] > 1: tags[j] = template.format(span=records[i]) else: continue j += 1 row.append(v) self.write_tr(row, indent, self.indent_delta, tags=tags, header=True) else: # see gh-22579 # Column misalignment also occurs for # a standard index when the columns index is named. # Initially fill row with blank cells before column names. # TODO: Refactor to remove code duplication with code block # above for columns MultiIndex. row = [""] * (self.row_levels - 1) if self.fmt.index or self.show_col_idx_names: # see gh-22747 # If to_html(index_names=False) do not show columns # index names. # TODO: Refactor to use _get_column_name_list from # DataFrameFormatter class. if self.fmt.show_index_names: row.append(self.columns.name or "") else: row.append("") row.extend(self._get_columns_formatted_values()) align = self.fmt.justify if is_truncated_horizontally: ins_col = self.row_levels + self.fmt.tr_col_num row.insert(ins_col, "...") self.write_tr(row, indent, self.indent_delta, header=True, align=align) def _write_row_header(self, indent: int) -> None: is_truncated_horizontally = self.fmt.is_truncated_horizontally row = [x if x is not None else "" for x in self.frame.index.names] + [""] * ( self.ncols + (1 if is_truncated_horizontally else 0) ) self.write_tr(row, indent, self.indent_delta, header=True) def _write_header(self, indent: int) -> None: self.write("<thead>", indent) if self.fmt.header: self._write_col_header(indent + self.indent_delta) if self.show_row_idx_names: self._write_row_header(indent + self.indent_delta) self.write("</thead>", indent) def _get_formatted_values(self) -> Dict[int, List[str]]: with option_context("display.max_colwidth", None): fmt_values = {i: self.fmt.format_col(i) for i in range(self.ncols)} return fmt_values def _write_body(self, indent: int) -> None: self.write("<tbody>", indent) fmt_values = self._get_formatted_values() # write values if self.fmt.index and isinstance(self.frame.index, MultiIndex): self._write_hierarchical_rows(fmt_values, indent + self.indent_delta) else: self._write_regular_rows(fmt_values, indent + self.indent_delta) self.write("</tbody>", indent) def _write_regular_rows( self, fmt_values: Mapping[int, List[str]], indent: int ) -> None: is_truncated_horizontally = self.fmt.is_truncated_horizontally is_truncated_vertically = self.fmt.is_truncated_vertically nrows = len(self.fmt.tr_frame) if self.fmt.index: fmt = self.fmt._get_formatter("__index__") if fmt is not None: index_values = self.fmt.tr_frame.index.map(fmt) else: index_values = self.fmt.tr_frame.index.format() row: List[str] = [] for i in range(nrows): if is_truncated_vertically and i == (self.fmt.tr_row_num): str_sep_row = ["..."] * len(row) self.write_tr( str_sep_row, indent, self.indent_delta, tags=None, nindex_levels=self.row_levels, ) row = [] if self.fmt.index: row.append(index_values[i]) # see gh-22579 # Column misalignment also occurs for # a standard index when the columns index is named. # Add blank cell before data cells. elif self.show_col_idx_names: row.append("") row.extend(fmt_values[j][i] for j in range(self.ncols)) if is_truncated_horizontally: dot_col_ix = self.fmt.tr_col_num + self.row_levels row.insert(dot_col_ix, "...") self.write_tr( row, indent, self.indent_delta, tags=None, nindex_levels=self.row_levels ) def _write_hierarchical_rows( self, fmt_values: Mapping[int, List[str]], indent: int ) -> None: template = 'rowspan="{span}" valign="top"' is_truncated_horizontally = self.fmt.is_truncated_horizontally is_truncated_vertically = self.fmt.is_truncated_vertically frame = self.fmt.tr_frame nrows = len(frame) assert isinstance(frame.index, MultiIndex) idx_values = frame.index.format(sparsify=False, adjoin=False, names=False) idx_values = list(zip(*idx_values)) if self.fmt.sparsify: # GH3547 sentinel = lib.no_default levels = frame.index.format(sparsify=sentinel, adjoin=False, names=False) level_lengths = get_level_lengths(levels, sentinel) inner_lvl = len(level_lengths) - 1 if is_truncated_vertically: # Insert ... row and adjust idx_values and # level_lengths to take this into account. ins_row = self.fmt.tr_row_num inserted = False for lnum, records in enumerate(level_lengths): rec_new = {} for tag, span in list(records.items()): if tag >= ins_row: rec_new[tag + 1] = span elif tag + span > ins_row: rec_new[tag] = span + 1 # GH 14882 - Make sure insertion done once if not inserted: dot_row = list(idx_values[ins_row - 1]) dot_row[-1] = "..." idx_values.insert(ins_row, tuple(dot_row)) inserted = True else: dot_row = list(idx_values[ins_row]) dot_row[inner_lvl - lnum] = "..." idx_values[ins_row] = tuple(dot_row) else: rec_new[tag] = span # If ins_row lies between tags, all cols idx cols # receive ... if tag + span == ins_row: rec_new[ins_row] = 1 if lnum == 0: idx_values.insert( ins_row, tuple(["..."] * len(level_lengths)) ) # GH 14882 - Place ... in correct level elif inserted: dot_row = list(idx_values[ins_row]) dot_row[inner_lvl - lnum] = "..." idx_values[ins_row] = tuple(dot_row) level_lengths[lnum] = rec_new level_lengths[inner_lvl][ins_row] = 1 for ix_col in range(len(fmt_values)): fmt_values[ix_col].insert(ins_row, "...") nrows += 1 for i in range(nrows): row = [] tags = {} sparse_offset = 0 j = 0 for records, v in zip(level_lengths, idx_values[i]): if i in records: if records[i] > 1: tags[j] = template.format(span=records[i]) else: sparse_offset += 1 continue j += 1 row.append(v) row.extend(fmt_values[j][i] for j in range(self.ncols)) if is_truncated_horizontally: row.insert( self.row_levels - sparse_offset + self.fmt.tr_col_num, "..." ) self.write_tr( row, indent, self.indent_delta, tags=tags, nindex_levels=len(levels) - sparse_offset, ) else: row = [] for i in range(len(frame)): if is_truncated_vertically and i == (self.fmt.tr_row_num): str_sep_row = ["..."] * len(row) self.write_tr( str_sep_row, indent, self.indent_delta, tags=None, nindex_levels=self.row_levels, ) idx_values = list( zip(*frame.index.format(sparsify=False, adjoin=False, names=False)) ) row = [] row.extend(idx_values[i]) row.extend(fmt_values[j][i] for j in range(self.ncols)) if is_truncated_horizontally: row.insert(self.row_levels + self.fmt.tr_col_num, "...") self.write_tr( row, indent, self.indent_delta, tags=None, nindex_levels=frame.index.nlevels, ) class NotebookFormatter(HTMLFormatter): """ Internal class for formatting output data in html for display in Jupyter Notebooks. This class is intended for functionality specific to DataFrame._repr_html_() and DataFrame.to_html(notebook=True) """ def _get_formatted_values(self) -> Dict[int, List[str]]: return {i: self.fmt.format_col(i) for i in range(self.ncols)} def _get_columns_formatted_values(self) -> List[str]: return self.columns.format() def write_style(self) -> None: # We use the "scoped" attribute here so that the desired # style properties for the data frame are not then applied # throughout the entire notebook. template_first = """\ <style scoped>""" template_last = """\ </style>""" template_select = """\ .dataframe %s { %s: %s; }""" element_props = [ ("tbody tr th:only-of-type", "vertical-align", "middle"), ("tbody tr th", "vertical-align", "top"), ] if isinstance(self.columns, MultiIndex): element_props.append(("thead tr th", "text-align", "left")) if self.show_row_idx_names: element_props.append( ("thead tr:last-of-type th", "text-align", "right") ) else: element_props.append(("thead th", "text-align", "right")) template_mid = "\n\n".join(map(lambda t: template_select % t, element_props)) template = dedent("\n".join((template_first, template_mid, template_last))) self.write(template) def render(self) -> List[str]: self.write("<div>") self.write_style() super().render() self.write("</div>") return self.elements
__all__ = ('ShowTestDescription', ) from .consoleHelper import * import unittest from typing import Callable, Any class ShowTestDescription(unittest.TestCase): def setUp(self) -> None: # print(self.__doc__) # class doc # print(self._testMethodName) # function name print_text('\n' + str(self), Fore.BLUE) document = self._testMethodDoc if self._testMethodDoc else 'No documents.' print(f"\t{text_color(document)}") # function doc def shortDescription(self) -> None: return super().shortDescription() def tearDown(self) -> None: super().shortDescription() # print('leave the function') class CLITestsBase(ShowTestDescription): def __init__(self, sub_cmd: str, cli_main: Callable[[list], Any], *args, **kwargs): super().__init__(*args, **kwargs) self.cli_main = cli_main self.cmd_list = [sub_cmd] self.__sub_cmd = sub_cmd self.start_run = self.decorator_run() def tearDown(self) -> None: self.cmd_list = [self.__sub_cmd] # reset cmd_list def decorator_run(self): def wrap(para_list: list): self.cmd_list.extend(para_list) self.cmd_list = [str(_) for _ in self.cmd_list] # .. important:: make sure all parameter is str for simulating the input from the command line print(f"Run command:{text_color(" ".join(self.cmd_list))}") return self.cli_main(self.cmd_list) return wrap
__all__ = ('ShowTestDescription', ) from .consoleHelper import * import unittest from typing import Callable, Any class ShowTestDescription(unittest.TestCase): def setUp(self) -> None: # print(self.__doc__) # class doc # print(self._testMethodName) # function name print_text('\n' + str(self), Fore.BLUE) document = self._testMethodDoc if self._testMethodDoc else 'No documents.' print(f"\t{text_color(document)}") # function doc def shortDescription(self) -> None: return super().shortDescription() def tearDown(self) -> None: super().shortDescription() # print('leave the function') class CLITestsBase(ShowTestDescription): def __init__(self, sub_cmd: str, cli_main: Callable[[list], Any], *args, **kwargs): super().__init__(*args, **kwargs) self.cli_main = cli_main self.cmd_list = [sub_cmd] self.__sub_cmd = sub_cmd self.start_run = self.decorator_run() def tearDown(self) -> None: self.cmd_list = [self.__sub_cmd] # reset cmd_list def decorator_run(self): def wrap(para_list: list): self.cmd_list.extend(para_list) self.cmd_list = [str(_) for _ in self.cmd_list] # .. important:: make sure all parameter is str for simulating the input from the command line print(f"Run command:{text_color(' '.join(self.cmd_list))}") return self.cli_main(self.cmd_list) return wrap
import ast import base64 import csv import json import logging import os import random import time from binascii import b2a_base64 from datetime import datetime from functools import wraps from io import StringIO from math import isnan from numbers import Number import requests from flask import Blueprint, Flask from flask import current_app as app from flask import flash, jsonify, redirect, render_template, request, url_for from flask_login import current_user, login_required from werkzeug.wrappers import Response from ..helpers import ( bcur2base64, get_devices_with_keys_by_type, get_txid, is_testnet, parse_wallet_data_import, ) from ..key import Key from ..persistence import delete_file from ..rpc import RpcError from ..specter import Specter from ..specter_error import SpecterError, handle_exception from ..util.base43 import b43_decode from ..util.descriptor import AddChecksum, Descriptor from ..util.fee_estimation import get_fees from ..util.price_providers import get_price_at from ..util.tx import decoderawtransaction from ..wallet_manager import purposes rand = random.randint(0, 1e32) # to force style refresh # Setup endpoint blueprint wallets_endpoint = Blueprint("wallets_endpoint", __name__) def handle_wallet_error(func_name, error): flash(f"SpecterError while {func_name}: {error}", "error") app.logger.error(f"SpecterError while {func_name}: {error}") app.specter.wallet_manager.update() return redirect(url_for("about")) def check_wallet(func): @wraps(func) def wrapper(*args, **kwargs): """checks the wallet for healthyness A wrapper function""" if kwargs["wallet_alias"]: wallet_alias = kwargs["wallet_alias"] print("--------------------checking wallet") wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) wallet.get_info() return func(*args, **kwargs) return wrapper ################## Wallet overview ####################### @wallets_endpoint.route("/wallets_overview/") @login_required def wallets_overview(): app.specter.check_blockheight() for wallet in list(app.specter.wallet_manager.wallets.values()): wallet.get_balance() wallet.check_utxo() return render_template( "wallet/wallets_overview.jinja", specter=app.specter, rand=rand, ) ################## Failed wallets fix ####################### @wallets_endpoint.route("/failed_wallets/", methods=["POST"]) @login_required def failed_wallets(): if request.method == "POST": action = request.form["action"] if action == "retry_loading_wallets": app.specter.wallet_manager.update() elif action == "delete_failed_wallet": try: wallet = json.loads(request.form["wallet_data"]) fullpath = wallet["fullpath"] delete_file(fullpath) delete_file(fullpath + ".bkp") delete_file(fullpath.replace(".json", "_addr.csv")) delete_file(fullpath.replace(".json", "_txs.csv")) app.specter.wallet_manager.update() except Exception as e: flash(f"Failed to delete failed wallet: {str(e)}", "error") return redirect("/") ################## New wallet ####################### @wallets_endpoint.route("/new_wallet/") @login_required def new_wallet_type(): err = None if app.specter.chain is None: err = "Configure Bitcoin Core to create wallets" return render_template("base.jinja", error=err, specter=app.specter, rand=rand) try: # Make sure wallet is enabled on Bitcoin Core app.specter.rpc.listwallets() except Exception: err = '<p><br>Configure Bitcoin Core is running with wallets disabled.<br><br>Please make sure disablewallet is off (set disablewallet=0 in your bitcoin.conf), then restart Bitcoin Core and try again.<br>See <a href="https://github.com/cryptoadvance/specter-desktop/blob/34ca139694ecafb2e7c2bd5ad5c4ac74c6d11501/docs/faq.md#im-not-sure-i-want-the-bitcoin-core-wallet-functionality-to-be-used-is-that-mandatory-if-so-is-it-considered-secure" target="_blank" style="color: white;">here</a> for more information.</p>' return render_template("base.jinja", error=err, specter=app.specter, rand=rand) return render_template( "wallet/new_wallet/new_wallet_type.jinja", specter=app.specter, rand=rand ) @wallets_endpoint.route("/new_wallet/<wallet_type>/", methods=["GET", "POST"]) @login_required def new_wallet(wallet_type): wallet_types = ["simple", "multisig", "import_wallet"] if wallet_type not in wallet_types: flash("Unknown wallet type requested", "error") return redirect(url_for("wallets_endpoint.new_wallet_type")) err = None if request.method == "POST": action = request.form["action"] if action == "importwallet": try: wallet_data = json.loads( request.form["wallet_data"].replace("\\'", "").replace("'", "h") ) ( wallet_name, recv_descriptor, cosigners_types, ) = parse_wallet_data_import(wallet_data) except Exception as e: flash(f"Unsupported wallet import format:{e}", "error") return redirect(url_for("wallets_endpoint.new_wallet_type")) # get min of the two # if the node is still syncing # and the first block with tx is not there yet startblock = min( wallet_data.get("blockheight", app.specter.info.get("blocks", 0)), app.specter.info.get("blocks", 0), ) # check if pruned if app.specter.info.get("pruned", False): newstartblock = max(startblock, app.specter.info.get("pruneheight", 0)) if newstartblock > startblock: flash( f"Using pruned node - we will only rescan from block {newstartblock}", "error", ) startblock = newstartblock try: descriptor = Descriptor.parse( AddChecksum(recv_descriptor.split("#")[0]), testnet=is_testnet(app.specter.chain), ) if descriptor is None: flash("Invalid wallet descriptor.", "error") return redirect(url_for("wallets_endpoint.new_wallet_type")) except: flash("Invalid wallet descriptor.", "error") return redirect(url_for("wallets_endpoint.new_wallet_type")) if wallet_name in app.specter.wallet_manager.wallets_names: flash("Wallet with the same name already exists", "error") return redirect(url_for("wallets_endpoint.new_wallet_type")) sigs_total = descriptor.multisig_N sigs_required = descriptor.multisig_M if descriptor.wpkh: address_type = "wpkh" elif descriptor.wsh: address_type = "wsh" elif descriptor.sh_wpkh: address_type = "sh-wpkh" elif descriptor.sh_wsh: address_type = "sh-wsh" elif descriptor.sh: address_type = "sh-wsh" else: address_type = "pkh" keys = [] cosigners = [] unknown_cosigners = [] unknown_cosigners_types = [] if sigs_total == None: sigs_total = 1 sigs_required = 1 descriptor.origin_fingerprint = [descriptor.origin_fingerprint] descriptor.origin_path = [descriptor.origin_path] descriptor.base_key = [descriptor.base_key] for i in range(sigs_total): cosigner_found = False for device in app.specter.device_manager.devices: cosigner = app.specter.device_manager.devices[device] if descriptor.origin_fingerprint[i] is None: descriptor.origin_fingerprint[i] = "" if descriptor.origin_path[i] is None: descriptor.origin_path[i] = descriptor.origin_fingerprint[i] for key in cosigner.keys: if key.fingerprint + key.derivation.replace( "m", "" ) == descriptor.origin_fingerprint[i] + descriptor.origin_path[ i ].replace( "'", "h" ): keys.append(key) cosigners.append(cosigner) cosigner_found = True break if cosigner_found: break if not cosigner_found: desc_key = Key.parse_xpub( "[{}{}]{}".format( descriptor.origin_fingerprint[i], descriptor.origin_path[i], descriptor.base_key[i], ) ) unknown_cosigners.append(desc_key) if len(unknown_cosigners) > len(cosigners_types): unknown_cosigners_types.append("other") else: unknown_cosigners_types.append(cosigners_types[i]) wallet_type = "multisig" if sigs_total > 1 else "simple" createwallet = "createwallet" in request.form if createwallet: wallet_name = request.form["wallet_name"] for i, unknown_cosigner in enumerate(unknown_cosigners): unknown_cosigner_name = request.form[ "unknown_cosigner_{}_name".format(i) ] unknown_cosigner_type = request.form.get( "unknown_cosigner_{}_type".format(i), "other" ) device = app.specter.device_manager.add_device( name=unknown_cosigner_name, device_type=unknown_cosigner_type, keys=[unknown_cosigner], ) keys.append(unknown_cosigner) cosigners.append(device) try: wallet = app.specter.wallet_manager.create_wallet( wallet_name, sigs_required, address_type, keys, cosigners ) except Exception as e: flash("Failed to create wallet: %r" % e, "error") return redirect(url_for("wallets_endpoint.new_wallet_type")) wallet.keypoolrefill(0, wallet.IMPORT_KEYPOOL, change=False) wallet.keypoolrefill(0, wallet.IMPORT_KEYPOOL, change=True) wallet.import_labels(wallet_data.get("labels", {})) flash("Wallet imported successfully", "info") try: wallet.rpc.rescanblockchain(startblock, timeout=1) app.logger.info("Rescanning Blockchain ...") except requests.exceptions.ReadTimeout: # this is normal behavior in our usecase pass except Exception as e: app.logger.error("Exception while rescanning blockchain: %r" % e) flash("Failed to perform rescan for wallet: %r" % e, "error") wallet.getdata() return redirect( url_for("wallets_endpoint.receive", wallet_alias=wallet.alias) + "?newwallet=true" ) else: return render_template( "wallet/new_wallet/import_wallet.jinja", wallet_data=json.dumps(wallet_data), wallet_type=wallet_type, wallet_name=wallet_name, cosigners=cosigners, unknown_cosigners=unknown_cosigners, unknown_cosigners_types=unknown_cosigners_types, sigs_required=sigs_required, sigs_total=sigs_total, specter=app.specter, rand=rand, ) if action == "device": cosigners = [ app.specter.device_manager.get_by_alias(alias) for alias in request.form.getlist("devices") ] devices = get_devices_with_keys_by_type(app, cosigners, wallet_type) for device in devices: if len(device.keys) == 0: err = ( "Device %s doesn't have keys matching this wallet type" % device.name ) break name = wallet_type.title() wallet_name = name i = 2 while wallet_name in app.specter.wallet_manager.wallets_names: wallet_name = "%s %d" % (name, i) i += 1 return render_template( "wallet/new_wallet/new_wallet_keys.jinja", cosigners=devices, wallet_type=wallet_type, sigs_total=len(devices), sigs_required=max(len(devices) * 2 // 3, 1), error=err, specter=app.specter, rand=rand, ) if action == "key" and err is None: wallet_name = request.form["wallet_name"] address_type = request.form["type"] sigs_total = int(request.form.get("sigs_total", 1)) sigs_required = int(request.form.get("sigs_required", 1)) if wallet_name in app.specter.wallet_manager.wallets_names: err = "Wallet already exists" if err: devices = [ app.specter.device_manager.get_by_alias( request.form.get("cosigner{}".format(i)) ) for i in range(0, sigs_total) ] return render_template( "wallet/new_wallet/new_wallet_keys.jinja", cosigners=devices, wallet_type=wallet_type, sigs_total=len(devices), sigs_required=max(len(devices) * 2 // 3, 1), error=err, specter=app.specter, rand=rand, ) keys = [] cosigners = [] devices = [] for i in range(sigs_total): try: key = request.form["key%d" % i] cosigner_name = request.form["cosigner%d" % i] cosigner = app.specter.device_manager.get_by_alias(cosigner_name) cosigners.append(cosigner) for k in cosigner.keys: if k.original == key: keys.append(k) break except: pass if len(keys) != sigs_total or len(cosigners) != sigs_total: err = "No keys were selected for device, please try adding keys first" devices = [ app.specter.device_manager.get_by_alias( request.form.get("cosigner{}".format(i)) ) for i in range(0, sigs_total) ] return render_template( "wallet/new_wallet/new_wallet_keys.jinja", cosigners=devices, wallet_type=wallet_type, sigs_total=len(devices), sigs_required=max(len(devices) * 2 // 3, 1), error=err, specter=app.specter, rand=rand, ) # create a wallet here try: wallet = app.specter.wallet_manager.create_wallet( wallet_name, sigs_required, address_type, keys, cosigners ) except Exception as e: err = f"Failed to create wallet. Error: {e}" return render_template( "wallet/new_wallet/new_wallet_keys.jinja", cosigners=cosigners, wallet_type=wallet_type, sigs_total=len(devices), sigs_required=max(len(devices) * 2 // 3, 1), error=err, specter=app.specter, rand=rand, ) app.logger.info("Created Wallet %s" % wallet_name) rescan_blockchain = "rescanblockchain" in request.form if rescan_blockchain: # old wallet - import more addresses wallet.keypoolrefill(0, wallet.IMPORT_KEYPOOL, change=False) wallet.keypoolrefill(0, wallet.IMPORT_KEYPOOL, change=True) if "utxo" in request.form.get("full_rescan_option"): explorer = None if "use_explorer" in request.form: if request.form["explorer"] == "CUSTOM": explorer = request.form["custom_explorer"] else: explorer = app.config["EXPLORERS_LIST"][ request.form["explorer"] ]["url"] wallet.rescanutxo( explorer, app.specter.requests_session(explorer), app.specter.only_tor, ) app.specter.info["utxorescan"] = 1 app.specter.utxorescanwallet = wallet.alias else: app.logger.info("Rescanning Blockchain ...") startblock = int(request.form["startblock"]) try: wallet.rpc.rescanblockchain(startblock, timeout=1) except requests.exceptions.ReadTimeout: # this is normal behavior in our usecase pass except Exception as e: app.logger.error( "Exception while rescanning blockchain: %e" % e ) err = "%r" % e wallet.getdata() return redirect( url_for("wallets_endpoint.receive", wallet_alias=wallet.alias) + "?newwallet=true" ) if action == "preselected_device": return render_template( "wallet/new_wallet/new_wallet_keys.jinja", cosigners=[ app.specter.device_manager.get_by_alias(request.form["device"]) ], wallet_type="simple", sigs_total=1, sigs_required=1, error=err, specter=app.specter, rand=rand, ) return render_template( "wallet/new_wallet/new_wallet.jinja", wallet_type=wallet_type, error=err, specter=app.specter, rand=rand, ) ################## Wallet pages ####################### ###### Wallet index page ###### @wallets_endpoint.route("/wallet/<wallet_alias>/") @login_required def wallet(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) if wallet.fullbalance > 0: return redirect(url_for("wallets_endpoint.history", wallet_alias=wallet_alias)) else: return redirect(url_for("wallets_endpoint.receive", wallet_alias=wallet_alias)) ###### Wallet transaction history ###### @wallets_endpoint.route("/wallet/<wallet_alias>/history/", methods=["GET", "POST"]) @login_required def history(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) tx_list_type = "txlist" if request.method == "POST": action = request.form["action"] if action == "freezeutxo": wallet.toggle_freeze_utxo(request.form.getlist("selected_utxo")) tx_list_type = "utxo" elif action == "abandon_tx": txid = request.form["txid"] try: wallet.abandontransaction(txid) except SpecterError as e: flash(str(e), "error") # update balances in the wallet app.specter.check_blockheight() wallet.get_balance() wallet.check_utxo() return render_template( "wallet/history/wallet_history.jinja", wallet_alias=wallet_alias, wallet=wallet, tx_list_type=tx_list_type, specter=app.specter, rand=rand, ) ###### Wallet receive ###### @wallets_endpoint.route("/wallet/<wallet_alias>/receive/", methods=["GET", "POST"]) @login_required @check_wallet def receive(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) if request.method == "POST": action = request.form["action"] if action == "newaddress": wallet.getnewaddress() elif action == "updatelabel": label = request.form["label"] wallet.setlabel(wallet.address, label) # check that current address is unused # and generate new one if it is wallet.check_unused() return render_template( "wallet/receive/wallet_receive.jinja", wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) ###### Wallet send ###### @wallets_endpoint.route("/wallet/<wallet_alias>/send") @login_required def send(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) if len(wallet.pending_psbts) > 0: return redirect( url_for("wallets_endpoint.send_pending", wallet_alias=wallet_alias) ) else: return redirect(url_for("wallets_endpoint.send_new", wallet_alias=wallet_alias)) @wallets_endpoint.route("/wallet/<wallet_alias>/send/new", methods=["GET", "POST"]) @login_required def send_new(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) # update balances in the wallet wallet.get_balance() # update utxo list for coin selection wallet.check_utxo() psbt = None addresses = [""] labels = [""] amounts = [0] amount_units = ["btc"] err = None ui_option = "ui" recipients_txt = "" subtract = False subtract_from = 1 fee_options = "dynamic" rbf = True rbf_utxo = [] rbf_tx_id = "" selected_coins = request.form.getlist("coinselect") fee_estimation_data = get_fees(app.specter, app.config) fee_rate = fee_estimation_data["hourFee"] if request.method == "POST": action = request.form.get("action") rbf_tx_id = request.form.get("rbf_tx_id", "") if action == "createpsbt": i = 0 addresses = [] labels = [] amounts = [] amount_units = [] ui_option = request.form.get("ui_option", "ui") if "ui" in ui_option: while "address_{}".format(i) in request.form: addresses.append(request.form["address_{}".format(i)]) amount = 0.0 try: amount = float(request.form["btc_amount_{}".format(i)]) except ValueError: pass if isnan(amount): amount = 0.0 amounts.append(amount) amount_units.append(request.form["amount_unit_{}".format(i)]) labels.append(request.form["label_{}".format(i)]) if request.form["label_{}".format(i)] != "": wallet.setlabel(addresses[i], labels[i]) i += 1 else: recipients_txt = request.form["recipients"] for output in recipients_txt.splitlines(): addresses.append(output.split(",")[0].strip()) if request.form.get("amount_unit_text") == "sat": amounts.append(float(output.split(",")[1].strip()) / 1e8) else: amounts.append(float(output.split(",")[1].strip())) labels.append("") addresses = [ address.lower() if address.startswith(("BC1", "TB1", "BCRT1")) else address for address in addresses ] subtract = bool(request.form.get("subtract", False)) subtract_from = int(request.form.get("subtract_from", 1)) fee_options = request.form.get("fee_options") if fee_options: if "dynamic" in fee_options: fee_rate = float(request.form.get("fee_rate_dynamic")) else: if request.form.get("fee_rate"): fee_rate = float(request.form.get("fee_rate")) rbf = bool(request.form.get("rbf", False)) selected_coins = request.form.getlist("coinselect") app.logger.info("selected coins: {}".format(selected_coins)) try: psbt = wallet.createpsbt( addresses, amounts, subtract=subtract, subtract_from=subtract_from - 1, fee_rate=fee_rate, rbf=rbf, selected_coins=selected_coins, readonly="estimate_fee" in request.form, rbf_edit_mode=(rbf_tx_id != ""), ) if psbt is None: err = "Probably you don't have enough funds, or something else..." else: # calculate new amount if we need to subtract if subtract: for v in psbt["tx"]["vout"]: if addresses[0] in v["scriptPubKey"]["addresses"]: amounts[0] = v["value"] except Exception as e: err = e app.logger.error(e) if err is None: if "estimate_fee" in request.form: return jsonify(success=True, psbt=psbt) return render_template( "wallet/send/sign/wallet_send_sign_psbt.jinja", psbt=psbt, labels=labels, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) else: if "estimate_fee" in request.form: return jsonify(success=False, error=str(err)) elif action == "rbf": try: rbf_tx_id = request.form["rbf_tx_id"] rbf_fee_rate = float(request.form["rbf_fee_rate"]) psbt = wallet.bumpfee(rbf_tx_id, rbf_fee_rate) return render_template( "wallet/send/sign/wallet_send_sign_psbt.jinja", psbt=psbt, labels=[], wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) except Exception as e: flash("Failed to perform RBF. Error: %s" % e, "error") elif action == "rbf_edit": try: decoded_tx = wallet.decode_tx(rbf_tx_id) addresses = decoded_tx["addresses"] amounts = decoded_tx["amounts"] selected_coins = [ f"{utxo["txid"]}, {utxo["vout"]}" for utxo in decoded_tx["used_utxo"] ] fee_rate = float(request.form["rbf_fee_rate"]) fee_options = "manual" rbf = True except Exception as e: flash("Failed to perform RBF. Error: %s" % e, "error") elif action == "signhotwallet": passphrase = request.form["passphrase"] psbt = ast.literal_eval(request.form["psbt"]) b64psbt = wallet.pending_psbts[psbt["tx"]["txid"]]["base64"] device = request.form["device"] if "devices_signed" not in psbt or device not in psbt["devices_signed"]: try: # get device and sign with it signed_psbt = app.specter.device_manager.get_by_alias( device ).sign_psbt(b64psbt, wallet, passphrase) if signed_psbt["complete"]: if "devices_signed" not in psbt: psbt["devices_signed"] = [] psbt["devices_signed"].append(device) psbt["sigs_count"] = len(psbt["devices_signed"]) raw = wallet.rpc.finalizepsbt(b64psbt) if "hex" in raw: psbt["raw"] = raw["hex"] signed_psbt = signed_psbt["psbt"] except Exception as e: signed_psbt = None flash("Failed to sign PSBT: %s" % e, "error") else: signed_psbt = None flash("Device already signed the PSBT", "error") return render_template( "wallet/send/sign/wallet_send_sign_psbt.jinja", signed_psbt=signed_psbt, psbt=psbt, labels=labels, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) if rbf_tx_id: try: rbf_utxo = wallet.get_rbf_utxo(rbf_tx_id) except Exception as e: flash("Failed to get RBF coins. Error: %s" % e, "error") show_advanced_settings = ( ui_option != "ui" or subtract or fee_options != "dynamic" or fee_estimation_data["hourFee"] != fee_rate or not rbf or selected_coins ) return render_template( "wallet/send/new/wallet_send.jinja", psbt=psbt, ui_option=ui_option, recipients_txt=recipients_txt, recipients=list(zip(addresses, amounts, amount_units, labels)), subtract=subtract, subtract_from=subtract_from, fee_options=fee_options, fee_rate=fee_rate, rbf=rbf, selected_coins=selected_coins, show_advanced_settings=show_advanced_settings, rbf_utxo=rbf_utxo, rbf_tx_id=rbf_tx_id, fee_estimation=fee_rate, fee_estimation_data=fee_estimation_data, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, error=err, ) @wallets_endpoint.route("/wallet/<wallet_alias>/send/pending/", methods=["GET", "POST"]) @login_required def send_pending(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) if request.method == "POST": action = request.form["action"] if action == "deletepsbt": try: wallet.delete_pending_psbt( ast.literal_eval(request.form["pending_psbt"])["tx"]["txid"] ) except Exception as e: app.logger.error("Could not delete Pending PSBT: %s" % e) flash("Could not delete Pending PSBT!", "error") elif action == "openpsbt": psbt = ast.literal_eval(request.form["pending_psbt"]) return render_template( "wallet/send/sign/wallet_send_sign_psbt.jinja", psbt=psbt, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) pending_psbts = wallet.pending_psbts ######## Migration to multiple recipients format ############### for psbt in pending_psbts: if not isinstance(pending_psbts[psbt]["address"], list): pending_psbts[psbt]["address"] = [pending_psbts[psbt]["address"]] pending_psbts[psbt]["amount"] = [pending_psbts[psbt]["amount"]] ############################################################### return render_template( "wallet/send/pending/wallet_sendpending.jinja", pending_psbts=pending_psbts, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, ) @wallets_endpoint.route("/wallet/<wallet_alias>/send/import", methods=["GET", "POST"]) @login_required def import_psbt(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) if request.method == "POST": action = request.form["action"] if action == "importpsbt": try: b64psbt = "".join(request.form["rawpsbt"].split()) psbt = wallet.importpsbt(b64psbt) except Exception as e: flash("Could not import PSBT: %s" % e, "error") return redirect( url_for("wallets_endpoint.import_psbt", wallet_alias=wallet_alias) ) return render_template( "wallet/send/sign/wallet_send_sign_psbt.jinja", psbt=psbt, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) err = None return render_template( "wallet/send/import/wallet_importpsbt.jinja", wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, error=err, ) ###### Wallet addresses ###### @wallets_endpoint.route("/wallet/<wallet_alias>/addresses/", methods=["GET"]) @login_required def addresses(wallet_alias): """Show informations about cached addresses (wallet._addresses) of the <wallet_alias>. It updates balances in the wallet before renderization in order to show updated UTXO and balance of each address.""" wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) # update balances in the wallet app.specter.check_blockheight() wallet.get_balance() wallet.check_utxo() return render_template( "wallet/addresses/wallet_addresses.jinja", wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) ###### Wallet settings ###### @wallets_endpoint.route("/wallet/<wallet_alias>/settings/", methods=["GET", "POST"]) @login_required def settings(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) error = None if request.method == "POST": action = request.form["action"] if action == "rescanblockchain": startblock = int(request.form["startblock"]) try: delete_file(wallet._transactions.path) wallet.fetch_transactions() res = wallet.rpc.rescanblockchain(startblock, timeout=1) except requests.exceptions.ReadTimeout: # this is normal behaviour in our usecase pass except Exception as e: app.logger.error("%s while rescanblockchain" % e) error = "%r" % e wallet.getdata() elif action == "abortrescan": res = wallet.rpc.abortrescan() if not res: error = "Failed to abort rescan. Maybe already complete?" wallet.getdata() elif action == "rescanutxo": explorer = None if "use_explorer" in request.form: if request.form["explorer"] == "CUSTOM": explorer = request.form["custom_explorer"] else: explorer = app.config["EXPLORERS_LIST"][request.form["explorer"]][ "url" ] wallet.rescanutxo( explorer, app.specter.requests_session(explorer), app.specter.only_tor ) app.specter.info["utxorescan"] = 1 app.specter.utxorescanwallet = wallet.alias elif action == "abortrescanutxo": app.specter.abortrescanutxo() app.specter.info["utxorescan"] = None app.specter.utxorescanwallet = None elif action == "keypoolrefill": delta = int(request.form["keypooladd"]) wallet.keypoolrefill(wallet.keypool, wallet.keypool + delta) wallet.keypoolrefill( wallet.change_keypool, wallet.change_keypool + delta, change=True ) wallet.getdata() elif action == "deletewallet": app.specter.wallet_manager.delete_wallet( wallet, app.specter.bitcoin_datadir, app.specter.chain ) response = redirect(url_for("index")) return response elif action == "rename": wallet_name = request.form["newtitle"] if not wallet_name: flash("Wallet name cannot be empty", "error") elif wallet_name == wallet.name: pass elif wallet_name in app.specter.wallet_manager.wallets_names: flash("Wallet already exists", "error") else: app.specter.wallet_manager.rename_wallet(wallet, wallet_name) return render_template( "wallet/settings/wallet_settings.jinja", purposes=purposes, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, error=error, ) ################## Wallet util endpoints ####################### # TODO: move these to an API endpoint @wallets_endpoint.route("/wallet/<wallet_alias>/combine/", methods=["POST"]) @login_required def combine(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) # only post requests # FIXME: ugly... txid = request.form.get("txid") psbts = [request.form.get("psbt0").strip(), request.form.get("psbt1").strip()] raw = {} combined = None for i, psbt in enumerate(psbts): if not psbt: return "Cannot parse empty data as PSBT", 500 if "UR:BYTES/" in psbt.upper(): psbt = bcur2base64(psbt).decode() # if electrum then it's base43 try: decoded = b43_decode(psbt) if decoded.startswith(b"psbt\xff"): psbt = b2a_base64(decoded).decode() else: psbt = decoded.hex() except: pass psbts[i] = psbt # psbt should start with cHNi # if not - maybe finalized hex tx if not psbt.startswith("cHNi"): raw["hex"] = psbt combined = psbts[1 - i] # check it's hex try: bytes.fromhex(psbt) except: return "Invalid transaction format", 500 try: if "hex" in raw: raw["complete"] = True raw["psbt"] = combined else: combined = app.specter.combine(psbts) raw = app.specter.finalize(combined) if "psbt" not in raw: raw["psbt"] = combined psbt = wallet.update_pending_psbt(combined, txid, raw) raw["devices"] = psbt["devices_signed"] except RpcError as e: return e.error_msg, e.status_code except Exception as e: return "Unknown error: %r" % e, 500 return json.dumps(raw) @wallets_endpoint.route("/wallet/<wallet_alias>/broadcast/", methods=["GET", "POST"]) @login_required def broadcast(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) if request.method == "POST": tx = request.form.get("tx") res = wallet.rpc.testmempoolaccept([tx])[0] if res["allowed"]: app.specter.broadcast(tx) wallet.delete_pending_psbt(get_txid(tx)) return jsonify(success=True) else: return jsonify( success=False, error="Failed to broadcast transaction: transaction is invalid\n%s" % res["reject-reason"], ) return jsonify(success=False, error="broadcast tx request must use POST") @wallets_endpoint.route("/wallet/<wallet_alias>/decoderawtx/", methods=["GET", "POST"]) @login_required @app.csrf.exempt def decoderawtx(wallet_alias): try: wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) txid = request.form.get("txid", "") if txid: tx = wallet.rpc.gettransaction(txid) # This is a fix for Bitcoin Core versions < v0.20 # These do not return the blockheight as part of the `gettransaction` command # So here we check if this property is lacking and if so # query the blockheader based on the transaction blockhash ##################### Remove from here after dropping Core v0.19 support ##################### if "blockhash" in tx and "blockheight" not in tx: tx["blockheight"] = wallet.rpc.getblockheader(tx["blockhash"])["height"] ##################### Remove until here after dropping Core v0.19 support ##################### if tx["confirmations"] == 0: tx["is_purged"] = wallet.is_tx_purged(txid) return { "success": True, "tx": tx, "rawtx": decoderawtransaction(tx["hex"], app.specter.chain), "walletName": wallet.name, } except Exception as e: app.logger.warning("Failed to fetch transaction data. Exception: {}".format(e)) return {"success": False} @wallets_endpoint.route( "/wallet/<wallet_alias>/rescan_progress", methods=["GET", "POST"] ) @login_required @app.csrf.exempt def rescan_progress(wallet_alias): try: wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) wallet.get_info() return { "active": wallet.rescan_progress is not None, "progress": wallet.rescan_progress, } except SpecterError as se: app.logger.error("SpecterError while get wallet rescan_progress: %s" % se) return {} @wallets_endpoint.route("/wallet/<wallet_alias>/get_label", methods=["POST"]) @login_required def get_label(wallet_alias): try: wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) address = request.form.get("address", "") label = wallet.getlabel(address) return { "address": address, "label": label, } except Exception as e: handle_exception(e) return { "success": False, "error": f"Exception trying to get address label: Error: {e}", } @wallets_endpoint.route("/wallet/<wallet_alias>/set_label", methods=["POST"]) @login_required def set_label(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) address = request.form["address"] label = request.form["label"] wallet.setlabel(address, label) return {"success": True} @wallets_endpoint.route("/wallet/<wallet_alias>/txlist", methods=["POST"]) @login_required @app.csrf.exempt def txlist(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) idx = int(request.form.get("idx", 0)) limit = int(request.form.get("limit", 100)) search = request.form.get("search", None) sortby = request.form.get("sortby", None) sortdir = request.form.get("sortdir", "asc") fetch_transactions = request.form.get("fetch_transactions", False) txlist = wallet.txlist( fetch_transactions=fetch_transactions, validate_merkle_proofs=app.specter.config.get("validate_merkle_proofs", False), current_blockheight=app.specter.info["blocks"], ) return process_txlist( txlist, idx=idx, limit=limit, search=search, sortby=sortby, sortdir=sortdir ) @wallets_endpoint.route("/wallet/<wallet_alias>/utxo_list", methods=["POST"]) @login_required @app.csrf.exempt def utxo_list(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) idx = int(request.form.get("idx", 0)) limit = int(request.form.get("limit", 100)) search = request.form.get("search", None) sortby = request.form.get("sortby", None) sortdir = request.form.get("sortdir", "asc") txlist = wallet.full_utxo for tx in txlist: if not tx.get("label", None): tx["label"] = wallet.getlabel(tx["address"]) return process_txlist( txlist, idx=idx, limit=limit, search=search, sortby=sortby, sortdir=sortdir ) @wallets_endpoint.route("/wallets_overview/txlist", methods=["POST"]) @login_required @app.csrf.exempt def wallets_overview_txlist(): idx = int(request.form.get("idx", 0)) limit = int(request.form.get("limit", 100)) search = request.form.get("search", None) sortby = request.form.get("sortby", None) sortdir = request.form.get("sortdir", "asc") fetch_transactions = request.form.get("fetch_transactions", False) txlist = app.specter.wallet_manager.full_txlist( fetch_transactions=fetch_transactions, validate_merkle_proofs=app.specter.config.get("validate_merkle_proofs", False), current_blockheight=app.specter.info["blocks"], ) return process_txlist( txlist, idx=idx, limit=limit, search=search, sortby=sortby, sortdir=sortdir ) @wallets_endpoint.route("/wallets_overview/utxo_list", methods=["POST"]) @login_required @app.csrf.exempt def wallets_overview_utxo_list(): idx = int(request.form.get("idx", 0)) limit = int(request.form.get("limit", 100)) search = request.form.get("search", None) sortby = request.form.get("sortby", None) sortdir = request.form.get("sortdir", "asc") fetch_transactions = request.form.get("fetch_transactions", False) txlist = app.specter.wallet_manager.full_utxo() return process_txlist( txlist, idx=idx, limit=limit, search=search, sortby=sortby, sortdir=sortdir ) @wallets_endpoint.route("/wallet/<wallet_alias>/addresses_list/", methods=["POST"]) @login_required @app.csrf.exempt def addresses_list(wallet_alias): """Return a JSON with keys: addressesList: list of addresses with the properties (index, address, label, used, utxo, amount) pageCount: total number of pages POST parameters: idx: pagination index (current page) limit: maximum number of items on the page sortby: field by which the list will be ordered (index, address, label, used, utxo, amount) sortdir: 'asc' (ascending) or 'desc' (descending) order addressType: the current tab address type ('receive' or 'change')""" wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) idx = int(request.form.get("idx", 0)) limit = int(request.form.get("limit", 100)) sortby = request.form.get("sortby", None) sortdir = request.form.get("sortdir", "asc") address_type = request.form.get("addressType", "receive") addresses_list = wallet.addresses_info(address_type == "change") result = process_addresses_list( addresses_list, idx=idx, limit=limit, sortby=sortby, sortdir=sortdir ) return { "addressesList": json.dumps(result["addressesList"]), "pageCount": result["pageCount"], } @wallets_endpoint.route("/wallet/<wallet_alias>/addressinfo/", methods=["POST"]) @login_required @app.csrf.exempt def addressinfo(wallet_alias): try: wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) address = request.form.get("address", "") if address: descriptor = wallet.get_descriptor(address=address) address_info = wallet.get_address_info(address=address) return { "success": True, "address": address, "descriptor": descriptor, "walletName": wallet.name, "isMine": not address_info.is_external, **address_info, } except Exception as e: app.logger.warning("Failed to fetch address data. Exception: {}".format(e)) return {"success": False} ################## Wallet CSV export data endpoints ####################### # Export wallet addresses list @wallets_endpoint.route("/wallet/<wallet_alias>/addresses_list.csv") @login_required def addresses_list_csv(wallet_alias): """Return a CSV with addresses of the <wallet_alias> containing the information: index, address, type, label, used, utxo and amount of each of them. GET parameters: sortby: field by which the CSV will be ordered (index, address, label, used, utxo, amount) sortdir: 'asc' (ascending) or 'desc' (descending) order address_type: the current tab address type ('receive' or 'change') onlyCurrentType: show all addresses (if false) or just the current type (address_type param)""" try: wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) sortby = request.args.get("sortby", "index") sortdir = request.args.get("sortdir", "asc") address_type = request.args.get("addressType", "receive") only_current_type = request.args.get("onlyCurrentType", "false") == "true" if not only_current_type: receive_list = wallet.addresses_info(False) change_list = wallet.addresses_info(True) receive_result = process_addresses_list( receive_list, idx=0, limit=0, sortby=sortby, sortdir=sortdir ) change_result = process_addresses_list( change_list, idx=0, limit=0, sortby=sortby, sortdir=sortdir ) addressesList = ( receive_result["addressesList"] + change_result["addressesList"] ) else: addresses_list = wallet.addresses_info(address_type == "change") result = process_addresses_list( addresses_list, idx=0, limit=0, sortby=sortby, sortdir=sortdir ) addressesList = result["addressesList"] # stream the response as the data is generated response = Response( wallet_addresses_list_to_csv(addressesList), mimetype="text/csv", ) # add a filename response.headers.set( "Content-Disposition", "attachment", filename="addresses_list.csv" ) return response except Exception as e: app.logger.error("Failed to export addresses list. Error: %s" % e) flash("Failed to export addresses list. Error: %s" % e, "error") return redirect(url_for("index")) # Export wallet transaction history @wallets_endpoint.route("/wallet/<wallet_alias>/transactions.csv") @login_required def tx_history_csv(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) validate_merkle_proofs = app.specter.config.get("validate_merkle_proofs", False) txlist = wallet.txlist(validate_merkle_proofs=validate_merkle_proofs) search = request.args.get("search", None) sortby = request.args.get("sortby", "time") sortdir = request.args.get("sortdir", "desc") txlist = json.loads( process_txlist( txlist, idx=0, limit=0, search=search, sortby=sortby, sortdir=sortdir )["txlist"] ) includePricesHistory = request.args.get("exportPrices", "false") == "true" # stream the response as the data is generated response = Response( txlist_to_csv(wallet, txlist, app.specter, current_user, includePricesHistory), mimetype="text/csv", ) # add a filename response.headers.set( "Content-Disposition", "attachment", filename="transactions.csv" ) return response # Export wallet UTXO list @wallets_endpoint.route("/wallet/<wallet_alias>/utxo.csv") @login_required def utxo_csv(wallet_alias): try: wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) includePricesHistory = request.args.get("exportPrices", "false") == "true" search = request.args.get("search", None) sortby = request.args.get("sortby", "time") sortdir = request.args.get("sortdir", "desc") txlist = json.loads( process_txlist( wallet.full_utxo, idx=0, limit=0, search=search, sortby=sortby, sortdir=sortdir, )["txlist"] ) # stream the response as the data is generated response = Response( txlist_to_csv( wallet, txlist, app.specter, current_user, includePricesHistory, ), mimetype="text/csv", ) # add a filename response.headers.set("Content-Disposition", "attachment", filename="utxo.csv") return response except Exception as e: logging.exception(e) return "Failed to export wallet utxo. Error: %s" % e, 500 # Export all wallets transaction history combined @wallets_endpoint.route("/wallets_overview/full_transactions.csv") @login_required def wallet_overview_txs_csv(): try: validate_merkle_proofs = app.specter.config.get("validate_merkle_proofs", False) txlist = app.specter.wallet_manager.full_txlist( validate_merkle_proofs=validate_merkle_proofs ) search = request.args.get("search", None) sortby = request.args.get("sortby", "time") sortdir = request.args.get("sortdir", "desc") txlist = json.loads( process_txlist( txlist, idx=0, limit=0, search=search, sortby=sortby, sortdir=sortdir )["txlist"] ) includePricesHistory = request.args.get("exportPrices", "false") == "true" # stream the response as the data is generated response = Response( txlist_to_csv( None, txlist, app.specter, current_user, includePricesHistory ), mimetype="text/csv", ) # add a filename response.headers.set( "Content-Disposition", "attachment", filename="full_transactions.csv" ) return response except Exception as e: logging.exception(e) return "Failed to export wallets overview history. Error: %s" % e, 500 # Export all wallets transaction history combined @wallets_endpoint.route("/wallets_overview/full_utxo.csv") @login_required def wallet_overview_utxo_csv(): try: txlist = app.specter.wallet_manager.full_utxo() search = request.args.get("search", None) sortby = request.args.get("sortby", "time") sortdir = request.args.get("sortdir", "desc") txlist = json.loads( process_txlist( txlist, idx=0, limit=0, search=search, sortby=sortby, sortdir=sortdir )["txlist"] ) includePricesHistory = request.args.get("exportPrices", "false") == "true" # stream the response as the data is generated response = Response( txlist_to_csv( None, txlist, app.specter, current_user, includePricesHistory ), mimetype="text/csv", ) # add a filename response.headers.set( "Content-Disposition", "attachment", filename="full_utxo.csv" ) return response except Exception as e: logging.exception(e) return "Failed to export wallets overview utxo. Error: %s" % e, 500 ################## Helpers ####################### # Transactions list to user-friendly CSV format def txlist_to_csv(wallet, _txlist, specter, current_user, includePricesHistory=False): txlist = [] for tx in _txlist: if isinstance(tx["address"], list): _tx = tx.copy() for i in range(0, len(tx["address"])): _tx["address"] = tx["address"][i] _tx["amount"] = tx["amount"][i] txlist.append(_tx.copy()) else: txlist.append(tx.copy()) data = StringIO() w = csv.writer(data) # write header symbol = "USD" if specter.price_provider.endswith("_eur"): symbol = "EUR" elif specter.price_provider.endswith("_gbp"): symbol = "GBP" row = ( "Date", "Label", "Category", "Amount ({})".format(specter.unit.upper()), "Value ({})".format(symbol), "Rate (BTC/{})".format(symbol) if specter.unit != "sat" else "Rate ({}/SAT)".format(symbol), "TxID", "Address", "Block Height", "Timestamp", "Raw Transaction", ) if not wallet: row = ("Wallet",) + row w.writerow(row) yield data.getvalue() data.seek(0) data.truncate(0) # write each log item _wallet = wallet for tx in txlist: if not wallet: wallet_alias = tx.get("wallet_alias", None) try: _wallet = specter.wallet_manager.get_by_alias(wallet_alias) except Exception as e: continue label = _wallet.getlabel(tx["address"]) if label == tx["address"]: label = "" tx_raw = _wallet.gettransaction(tx["txid"]) if tx_raw: tx_hex = tx_raw["hex"] else: tx_hex = "" if not tx.get("blockheight", None): if tx_raw.get("blockheight", None): tx["blockheight"] = tx_raw["blockheight"] else: tx["blockheight"] = "Unconfirmed" if specter.unit == "sat": value = float(tx["amount"]) tx["amount"] = round(value * 1e8) if includePricesHistory: success, rate, symbol = get_price_at( specter, current_user, timestamp=tx["time"] ) else: success = False if success: rate = float(rate) if specter.unit == "sat": rate = rate / 1e8 amount_price = float(tx["amount"]) * rate if specter.unit == "sat": rate = round(1 / rate) else: amount_price = None rate = "-" row = ( time.strftime("%Y-%m-%d", time.localtime(tx["time"])), label, tx["category"], round(tx["amount"], (0 if specter.unit == "sat" else 8)), round(amount_price * 100) / 100 if amount_price is not None else "-", rate, tx["txid"], tx["address"], tx["blockheight"], tx["time"], tx_hex, ) if not wallet: row = (tx.get("wallet_alias", ""),) + row w.writerow(row) yield data.getvalue() data.seek(0) data.truncate(0) # Addresses list to user-friendly CSV format def addresses_list_to_csv(wallet): data = StringIO() w = csv.writer(data) # write header row = ( "Address", "Label", "Index", "Used", "Current balance", ) w.writerow(row) yield data.getvalue() data.seek(0) data.truncate(0) # write each log item for address in wallet._addresses: address_info = wallet.get_address_info(address) if not address_info.is_labeled and not address_info.used: continue row = ( address, address_info.label, "(external)" if address_info.is_external else ( str(address_info.index) + (" (change)" if address_info.change else "") ), address_info.used, ) if address_info.is_external: balance_on_address = "unknown (external address)" else: balance_on_address = 0 if address_info.used: for tx in wallet.full_utxo: if tx.get("address", "") == address: balance_on_address += tx.get("amount", 0) row += (balance_on_address,) w.writerow(row) yield data.getvalue() data.seek(0) data.truncate(0) def wallet_addresses_list_to_csv(addresses_list): """Convert a list of the wallet addresses to user-friendly CSV format Parameters: addresses_list: a dict of addresses informations (index, address, type, label, used, utxo and amount)""" data = StringIO() w = csv.writer(data) # write header row = ( "Index", "Address", "Type", "Label", "Used", "UTXO", "Amount (BTC)", ) w.writerow(row) yield data.getvalue() data.seek(0) data.truncate(0) # write each log item for address_item in addresses_list: used = "Yes" if address_item["used"] else "No" row = ( address_item["index"], address_item["address"], address_item["type"], address_item["label"], used, address_item["utxo"], address_item["amount"], ) w.writerow(row) yield data.getvalue() data.seek(0) data.truncate(0) def process_txlist(txlist, idx=0, limit=100, search=None, sortby=None, sortdir="asc"): if search: txlist = [ tx for tx in txlist if search in tx["txid"] or ( any(search in address for address in tx["address"]) if isinstance(tx["address"], list) else search in tx["address"] ) or ( any(search in label for label in tx["label"]) if isinstance(tx["label"], list) else search in tx["label"] ) or ( any(search in str(amount) for amount in tx["amount"]) if isinstance(tx["amount"], list) else search in str(tx["amount"]) ) or search in str(tx["confirmations"]) or search in str(tx["time"]) or search in str(format(datetime.fromtimestamp(tx["time"]), "%d.%m.%Y %H:%M")) ] if sortby: def sort(tx): val = tx.get(sortby, None) final = val if val: if isinstance(val, list): if isinstance(val[0], Number): final = sum(val) elif isinstance(val[0], str): final = sorted( val, key=lambda s: s.lower(), reverse=sortdir != "asc" )[0].lower() elif isinstance(val, str): final = val.lower() return final txlist = sorted(txlist, key=sort, reverse=sortdir != "asc") if limit: page_count = (len(txlist) // limit) + (0 if len(txlist) % limit == 0 else 1) txlist = txlist[limit * idx : limit * (idx + 1)] else: page_count = 1 return {"txlist": json.dumps(txlist), "pageCount": page_count} def process_addresses_list( addresses_list, idx=0, limit=100, sortby=None, sortdir="asc" ): """Receive an address list as parameter and sort it or slice it for pagination. Parameters: addresses_list: list of dict with the keys (index, address, label, used, utxo, amount) idx: pagination index (current page) limit: maximum number of items on the page sortby: field by which the list will be ordered (index, address, label, used, utxo, amount) sortdir: 'asc' (ascending) or 'desc' (descending) order""" if sortby: def sort(addr): val = addr.get(sortby, None) final = val if val: if isinstance(val, str): final = val.lower() return final addresses_list = sorted(addresses_list, key=sort, reverse=sortdir != "asc") if limit: page_count = (len(addresses_list) // limit) + ( 0 if len(addresses_list) % limit == 0 else 1 ) addresses_list = addresses_list[limit * idx : limit * (idx + 1)] else: page_count = 1 return {"addressesList": addresses_list, "pageCount": page_count}
import ast import base64 import csv import json import logging import os import random import time from binascii import b2a_base64 from datetime import datetime from functools import wraps from io import StringIO from math import isnan from numbers import Number import requests from flask import Blueprint, Flask from flask import current_app as app from flask import flash, jsonify, redirect, render_template, request, url_for from flask_login import current_user, login_required from werkzeug.wrappers import Response from ..helpers import ( bcur2base64, get_devices_with_keys_by_type, get_txid, is_testnet, parse_wallet_data_import, ) from ..key import Key from ..persistence import delete_file from ..rpc import RpcError from ..specter import Specter from ..specter_error import SpecterError, handle_exception from ..util.base43 import b43_decode from ..util.descriptor import AddChecksum, Descriptor from ..util.fee_estimation import get_fees from ..util.price_providers import get_price_at from ..util.tx import decoderawtransaction from ..wallet_manager import purposes rand = random.randint(0, 1e32) # to force style refresh # Setup endpoint blueprint wallets_endpoint = Blueprint("wallets_endpoint", __name__) def handle_wallet_error(func_name, error): flash(f"SpecterError while {func_name}: {error}", "error") app.logger.error(f"SpecterError while {func_name}: {error}") app.specter.wallet_manager.update() return redirect(url_for("about")) def check_wallet(func): @wraps(func) def wrapper(*args, **kwargs): """checks the wallet for healthyness A wrapper function""" if kwargs["wallet_alias"]: wallet_alias = kwargs["wallet_alias"] print("--------------------checking wallet") wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) wallet.get_info() return func(*args, **kwargs) return wrapper ################## Wallet overview ####################### @wallets_endpoint.route("/wallets_overview/") @login_required def wallets_overview(): app.specter.check_blockheight() for wallet in list(app.specter.wallet_manager.wallets.values()): wallet.get_balance() wallet.check_utxo() return render_template( "wallet/wallets_overview.jinja", specter=app.specter, rand=rand, ) ################## Failed wallets fix ####################### @wallets_endpoint.route("/failed_wallets/", methods=["POST"]) @login_required def failed_wallets(): if request.method == "POST": action = request.form["action"] if action == "retry_loading_wallets": app.specter.wallet_manager.update() elif action == "delete_failed_wallet": try: wallet = json.loads(request.form["wallet_data"]) fullpath = wallet["fullpath"] delete_file(fullpath) delete_file(fullpath + ".bkp") delete_file(fullpath.replace(".json", "_addr.csv")) delete_file(fullpath.replace(".json", "_txs.csv")) app.specter.wallet_manager.update() except Exception as e: flash(f"Failed to delete failed wallet: {str(e)}", "error") return redirect("/") ################## New wallet ####################### @wallets_endpoint.route("/new_wallet/") @login_required def new_wallet_type(): err = None if app.specter.chain is None: err = "Configure Bitcoin Core to create wallets" return render_template("base.jinja", error=err, specter=app.specter, rand=rand) try: # Make sure wallet is enabled on Bitcoin Core app.specter.rpc.listwallets() except Exception: err = '<p><br>Configure Bitcoin Core is running with wallets disabled.<br><br>Please make sure disablewallet is off (set disablewallet=0 in your bitcoin.conf), then restart Bitcoin Core and try again.<br>See <a href="https://github.com/cryptoadvance/specter-desktop/blob/34ca139694ecafb2e7c2bd5ad5c4ac74c6d11501/docs/faq.md#im-not-sure-i-want-the-bitcoin-core-wallet-functionality-to-be-used-is-that-mandatory-if-so-is-it-considered-secure" target="_blank" style="color: white;">here</a> for more information.</p>' return render_template("base.jinja", error=err, specter=app.specter, rand=rand) return render_template( "wallet/new_wallet/new_wallet_type.jinja", specter=app.specter, rand=rand ) @wallets_endpoint.route("/new_wallet/<wallet_type>/", methods=["GET", "POST"]) @login_required def new_wallet(wallet_type): wallet_types = ["simple", "multisig", "import_wallet"] if wallet_type not in wallet_types: flash("Unknown wallet type requested", "error") return redirect(url_for("wallets_endpoint.new_wallet_type")) err = None if request.method == "POST": action = request.form["action"] if action == "importwallet": try: wallet_data = json.loads( request.form["wallet_data"].replace("\\'", "").replace("'", "h") ) ( wallet_name, recv_descriptor, cosigners_types, ) = parse_wallet_data_import(wallet_data) except Exception as e: flash(f"Unsupported wallet import format:{e}", "error") return redirect(url_for("wallets_endpoint.new_wallet_type")) # get min of the two # if the node is still syncing # and the first block with tx is not there yet startblock = min( wallet_data.get("blockheight", app.specter.info.get("blocks", 0)), app.specter.info.get("blocks", 0), ) # check if pruned if app.specter.info.get("pruned", False): newstartblock = max(startblock, app.specter.info.get("pruneheight", 0)) if newstartblock > startblock: flash( f"Using pruned node - we will only rescan from block {newstartblock}", "error", ) startblock = newstartblock try: descriptor = Descriptor.parse( AddChecksum(recv_descriptor.split("#")[0]), testnet=is_testnet(app.specter.chain), ) if descriptor is None: flash("Invalid wallet descriptor.", "error") return redirect(url_for("wallets_endpoint.new_wallet_type")) except: flash("Invalid wallet descriptor.", "error") return redirect(url_for("wallets_endpoint.new_wallet_type")) if wallet_name in app.specter.wallet_manager.wallets_names: flash("Wallet with the same name already exists", "error") return redirect(url_for("wallets_endpoint.new_wallet_type")) sigs_total = descriptor.multisig_N sigs_required = descriptor.multisig_M if descriptor.wpkh: address_type = "wpkh" elif descriptor.wsh: address_type = "wsh" elif descriptor.sh_wpkh: address_type = "sh-wpkh" elif descriptor.sh_wsh: address_type = "sh-wsh" elif descriptor.sh: address_type = "sh-wsh" else: address_type = "pkh" keys = [] cosigners = [] unknown_cosigners = [] unknown_cosigners_types = [] if sigs_total == None: sigs_total = 1 sigs_required = 1 descriptor.origin_fingerprint = [descriptor.origin_fingerprint] descriptor.origin_path = [descriptor.origin_path] descriptor.base_key = [descriptor.base_key] for i in range(sigs_total): cosigner_found = False for device in app.specter.device_manager.devices: cosigner = app.specter.device_manager.devices[device] if descriptor.origin_fingerprint[i] is None: descriptor.origin_fingerprint[i] = "" if descriptor.origin_path[i] is None: descriptor.origin_path[i] = descriptor.origin_fingerprint[i] for key in cosigner.keys: if key.fingerprint + key.derivation.replace( "m", "" ) == descriptor.origin_fingerprint[i] + descriptor.origin_path[ i ].replace( "'", "h" ): keys.append(key) cosigners.append(cosigner) cosigner_found = True break if cosigner_found: break if not cosigner_found: desc_key = Key.parse_xpub( "[{}{}]{}".format( descriptor.origin_fingerprint[i], descriptor.origin_path[i], descriptor.base_key[i], ) ) unknown_cosigners.append(desc_key) if len(unknown_cosigners) > len(cosigners_types): unknown_cosigners_types.append("other") else: unknown_cosigners_types.append(cosigners_types[i]) wallet_type = "multisig" if sigs_total > 1 else "simple" createwallet = "createwallet" in request.form if createwallet: wallet_name = request.form["wallet_name"] for i, unknown_cosigner in enumerate(unknown_cosigners): unknown_cosigner_name = request.form[ "unknown_cosigner_{}_name".format(i) ] unknown_cosigner_type = request.form.get( "unknown_cosigner_{}_type".format(i), "other" ) device = app.specter.device_manager.add_device( name=unknown_cosigner_name, device_type=unknown_cosigner_type, keys=[unknown_cosigner], ) keys.append(unknown_cosigner) cosigners.append(device) try: wallet = app.specter.wallet_manager.create_wallet( wallet_name, sigs_required, address_type, keys, cosigners ) except Exception as e: flash("Failed to create wallet: %r" % e, "error") return redirect(url_for("wallets_endpoint.new_wallet_type")) wallet.keypoolrefill(0, wallet.IMPORT_KEYPOOL, change=False) wallet.keypoolrefill(0, wallet.IMPORT_KEYPOOL, change=True) wallet.import_labels(wallet_data.get("labels", {})) flash("Wallet imported successfully", "info") try: wallet.rpc.rescanblockchain(startblock, timeout=1) app.logger.info("Rescanning Blockchain ...") except requests.exceptions.ReadTimeout: # this is normal behavior in our usecase pass except Exception as e: app.logger.error("Exception while rescanning blockchain: %r" % e) flash("Failed to perform rescan for wallet: %r" % e, "error") wallet.getdata() return redirect( url_for("wallets_endpoint.receive", wallet_alias=wallet.alias) + "?newwallet=true" ) else: return render_template( "wallet/new_wallet/import_wallet.jinja", wallet_data=json.dumps(wallet_data), wallet_type=wallet_type, wallet_name=wallet_name, cosigners=cosigners, unknown_cosigners=unknown_cosigners, unknown_cosigners_types=unknown_cosigners_types, sigs_required=sigs_required, sigs_total=sigs_total, specter=app.specter, rand=rand, ) if action == "device": cosigners = [ app.specter.device_manager.get_by_alias(alias) for alias in request.form.getlist("devices") ] devices = get_devices_with_keys_by_type(app, cosigners, wallet_type) for device in devices: if len(device.keys) == 0: err = ( "Device %s doesn't have keys matching this wallet type" % device.name ) break name = wallet_type.title() wallet_name = name i = 2 while wallet_name in app.specter.wallet_manager.wallets_names: wallet_name = "%s %d" % (name, i) i += 1 return render_template( "wallet/new_wallet/new_wallet_keys.jinja", cosigners=devices, wallet_type=wallet_type, sigs_total=len(devices), sigs_required=max(len(devices) * 2 // 3, 1), error=err, specter=app.specter, rand=rand, ) if action == "key" and err is None: wallet_name = request.form["wallet_name"] address_type = request.form["type"] sigs_total = int(request.form.get("sigs_total", 1)) sigs_required = int(request.form.get("sigs_required", 1)) if wallet_name in app.specter.wallet_manager.wallets_names: err = "Wallet already exists" if err: devices = [ app.specter.device_manager.get_by_alias( request.form.get("cosigner{}".format(i)) ) for i in range(0, sigs_total) ] return render_template( "wallet/new_wallet/new_wallet_keys.jinja", cosigners=devices, wallet_type=wallet_type, sigs_total=len(devices), sigs_required=max(len(devices) * 2 // 3, 1), error=err, specter=app.specter, rand=rand, ) keys = [] cosigners = [] devices = [] for i in range(sigs_total): try: key = request.form["key%d" % i] cosigner_name = request.form["cosigner%d" % i] cosigner = app.specter.device_manager.get_by_alias(cosigner_name) cosigners.append(cosigner) for k in cosigner.keys: if k.original == key: keys.append(k) break except: pass if len(keys) != sigs_total or len(cosigners) != sigs_total: err = "No keys were selected for device, please try adding keys first" devices = [ app.specter.device_manager.get_by_alias( request.form.get("cosigner{}".format(i)) ) for i in range(0, sigs_total) ] return render_template( "wallet/new_wallet/new_wallet_keys.jinja", cosigners=devices, wallet_type=wallet_type, sigs_total=len(devices), sigs_required=max(len(devices) * 2 // 3, 1), error=err, specter=app.specter, rand=rand, ) # create a wallet here try: wallet = app.specter.wallet_manager.create_wallet( wallet_name, sigs_required, address_type, keys, cosigners ) except Exception as e: err = f"Failed to create wallet. Error: {e}" return render_template( "wallet/new_wallet/new_wallet_keys.jinja", cosigners=cosigners, wallet_type=wallet_type, sigs_total=len(devices), sigs_required=max(len(devices) * 2 // 3, 1), error=err, specter=app.specter, rand=rand, ) app.logger.info("Created Wallet %s" % wallet_name) rescan_blockchain = "rescanblockchain" in request.form if rescan_blockchain: # old wallet - import more addresses wallet.keypoolrefill(0, wallet.IMPORT_KEYPOOL, change=False) wallet.keypoolrefill(0, wallet.IMPORT_KEYPOOL, change=True) if "utxo" in request.form.get("full_rescan_option"): explorer = None if "use_explorer" in request.form: if request.form["explorer"] == "CUSTOM": explorer = request.form["custom_explorer"] else: explorer = app.config["EXPLORERS_LIST"][ request.form["explorer"] ]["url"] wallet.rescanutxo( explorer, app.specter.requests_session(explorer), app.specter.only_tor, ) app.specter.info["utxorescan"] = 1 app.specter.utxorescanwallet = wallet.alias else: app.logger.info("Rescanning Blockchain ...") startblock = int(request.form["startblock"]) try: wallet.rpc.rescanblockchain(startblock, timeout=1) except requests.exceptions.ReadTimeout: # this is normal behavior in our usecase pass except Exception as e: app.logger.error( "Exception while rescanning blockchain: %e" % e ) err = "%r" % e wallet.getdata() return redirect( url_for("wallets_endpoint.receive", wallet_alias=wallet.alias) + "?newwallet=true" ) if action == "preselected_device": return render_template( "wallet/new_wallet/new_wallet_keys.jinja", cosigners=[ app.specter.device_manager.get_by_alias(request.form["device"]) ], wallet_type="simple", sigs_total=1, sigs_required=1, error=err, specter=app.specter, rand=rand, ) return render_template( "wallet/new_wallet/new_wallet.jinja", wallet_type=wallet_type, error=err, specter=app.specter, rand=rand, ) ################## Wallet pages ####################### ###### Wallet index page ###### @wallets_endpoint.route("/wallet/<wallet_alias>/") @login_required def wallet(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) if wallet.fullbalance > 0: return redirect(url_for("wallets_endpoint.history", wallet_alias=wallet_alias)) else: return redirect(url_for("wallets_endpoint.receive", wallet_alias=wallet_alias)) ###### Wallet transaction history ###### @wallets_endpoint.route("/wallet/<wallet_alias>/history/", methods=["GET", "POST"]) @login_required def history(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) tx_list_type = "txlist" if request.method == "POST": action = request.form["action"] if action == "freezeutxo": wallet.toggle_freeze_utxo(request.form.getlist("selected_utxo")) tx_list_type = "utxo" elif action == "abandon_tx": txid = request.form["txid"] try: wallet.abandontransaction(txid) except SpecterError as e: flash(str(e), "error") # update balances in the wallet app.specter.check_blockheight() wallet.get_balance() wallet.check_utxo() return render_template( "wallet/history/wallet_history.jinja", wallet_alias=wallet_alias, wallet=wallet, tx_list_type=tx_list_type, specter=app.specter, rand=rand, ) ###### Wallet receive ###### @wallets_endpoint.route("/wallet/<wallet_alias>/receive/", methods=["GET", "POST"]) @login_required @check_wallet def receive(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) if request.method == "POST": action = request.form["action"] if action == "newaddress": wallet.getnewaddress() elif action == "updatelabel": label = request.form["label"] wallet.setlabel(wallet.address, label) # check that current address is unused # and generate new one if it is wallet.check_unused() return render_template( "wallet/receive/wallet_receive.jinja", wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) ###### Wallet send ###### @wallets_endpoint.route("/wallet/<wallet_alias>/send") @login_required def send(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) if len(wallet.pending_psbts) > 0: return redirect( url_for("wallets_endpoint.send_pending", wallet_alias=wallet_alias) ) else: return redirect(url_for("wallets_endpoint.send_new", wallet_alias=wallet_alias)) @wallets_endpoint.route("/wallet/<wallet_alias>/send/new", methods=["GET", "POST"]) @login_required def send_new(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) # update balances in the wallet wallet.get_balance() # update utxo list for coin selection wallet.check_utxo() psbt = None addresses = [""] labels = [""] amounts = [0] amount_units = ["btc"] err = None ui_option = "ui" recipients_txt = "" subtract = False subtract_from = 1 fee_options = "dynamic" rbf = True rbf_utxo = [] rbf_tx_id = "" selected_coins = request.form.getlist("coinselect") fee_estimation_data = get_fees(app.specter, app.config) fee_rate = fee_estimation_data["hourFee"] if request.method == "POST": action = request.form.get("action") rbf_tx_id = request.form.get("rbf_tx_id", "") if action == "createpsbt": i = 0 addresses = [] labels = [] amounts = [] amount_units = [] ui_option = request.form.get("ui_option", "ui") if "ui" in ui_option: while "address_{}".format(i) in request.form: addresses.append(request.form["address_{}".format(i)]) amount = 0.0 try: amount = float(request.form["btc_amount_{}".format(i)]) except ValueError: pass if isnan(amount): amount = 0.0 amounts.append(amount) amount_units.append(request.form["amount_unit_{}".format(i)]) labels.append(request.form["label_{}".format(i)]) if request.form["label_{}".format(i)] != "": wallet.setlabel(addresses[i], labels[i]) i += 1 else: recipients_txt = request.form["recipients"] for output in recipients_txt.splitlines(): addresses.append(output.split(",")[0].strip()) if request.form.get("amount_unit_text") == "sat": amounts.append(float(output.split(",")[1].strip()) / 1e8) else: amounts.append(float(output.split(",")[1].strip())) labels.append("") addresses = [ address.lower() if address.startswith(("BC1", "TB1", "BCRT1")) else address for address in addresses ] subtract = bool(request.form.get("subtract", False)) subtract_from = int(request.form.get("subtract_from", 1)) fee_options = request.form.get("fee_options") if fee_options: if "dynamic" in fee_options: fee_rate = float(request.form.get("fee_rate_dynamic")) else: if request.form.get("fee_rate"): fee_rate = float(request.form.get("fee_rate")) rbf = bool(request.form.get("rbf", False)) selected_coins = request.form.getlist("coinselect") app.logger.info("selected coins: {}".format(selected_coins)) try: psbt = wallet.createpsbt( addresses, amounts, subtract=subtract, subtract_from=subtract_from - 1, fee_rate=fee_rate, rbf=rbf, selected_coins=selected_coins, readonly="estimate_fee" in request.form, rbf_edit_mode=(rbf_tx_id != ""), ) if psbt is None: err = "Probably you don't have enough funds, or something else..." else: # calculate new amount if we need to subtract if subtract: for v in psbt["tx"]["vout"]: if addresses[0] in v["scriptPubKey"]["addresses"]: amounts[0] = v["value"] except Exception as e: err = e app.logger.error(e) if err is None: if "estimate_fee" in request.form: return jsonify(success=True, psbt=psbt) return render_template( "wallet/send/sign/wallet_send_sign_psbt.jinja", psbt=psbt, labels=labels, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) else: if "estimate_fee" in request.form: return jsonify(success=False, error=str(err)) elif action == "rbf": try: rbf_tx_id = request.form["rbf_tx_id"] rbf_fee_rate = float(request.form["rbf_fee_rate"]) psbt = wallet.bumpfee(rbf_tx_id, rbf_fee_rate) return render_template( "wallet/send/sign/wallet_send_sign_psbt.jinja", psbt=psbt, labels=[], wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) except Exception as e: flash("Failed to perform RBF. Error: %s" % e, "error") elif action == "rbf_edit": try: decoded_tx = wallet.decode_tx(rbf_tx_id) addresses = decoded_tx["addresses"] amounts = decoded_tx["amounts"] selected_coins = [ f"{utxo['txid']}, {utxo['vout']}" for utxo in decoded_tx["used_utxo"] ] fee_rate = float(request.form["rbf_fee_rate"]) fee_options = "manual" rbf = True except Exception as e: flash("Failed to perform RBF. Error: %s" % e, "error") elif action == "signhotwallet": passphrase = request.form["passphrase"] psbt = ast.literal_eval(request.form["psbt"]) b64psbt = wallet.pending_psbts[psbt["tx"]["txid"]]["base64"] device = request.form["device"] if "devices_signed" not in psbt or device not in psbt["devices_signed"]: try: # get device and sign with it signed_psbt = app.specter.device_manager.get_by_alias( device ).sign_psbt(b64psbt, wallet, passphrase) if signed_psbt["complete"]: if "devices_signed" not in psbt: psbt["devices_signed"] = [] psbt["devices_signed"].append(device) psbt["sigs_count"] = len(psbt["devices_signed"]) raw = wallet.rpc.finalizepsbt(b64psbt) if "hex" in raw: psbt["raw"] = raw["hex"] signed_psbt = signed_psbt["psbt"] except Exception as e: signed_psbt = None flash("Failed to sign PSBT: %s" % e, "error") else: signed_psbt = None flash("Device already signed the PSBT", "error") return render_template( "wallet/send/sign/wallet_send_sign_psbt.jinja", signed_psbt=signed_psbt, psbt=psbt, labels=labels, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) if rbf_tx_id: try: rbf_utxo = wallet.get_rbf_utxo(rbf_tx_id) except Exception as e: flash("Failed to get RBF coins. Error: %s" % e, "error") show_advanced_settings = ( ui_option != "ui" or subtract or fee_options != "dynamic" or fee_estimation_data["hourFee"] != fee_rate or not rbf or selected_coins ) return render_template( "wallet/send/new/wallet_send.jinja", psbt=psbt, ui_option=ui_option, recipients_txt=recipients_txt, recipients=list(zip(addresses, amounts, amount_units, labels)), subtract=subtract, subtract_from=subtract_from, fee_options=fee_options, fee_rate=fee_rate, rbf=rbf, selected_coins=selected_coins, show_advanced_settings=show_advanced_settings, rbf_utxo=rbf_utxo, rbf_tx_id=rbf_tx_id, fee_estimation=fee_rate, fee_estimation_data=fee_estimation_data, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, error=err, ) @wallets_endpoint.route("/wallet/<wallet_alias>/send/pending/", methods=["GET", "POST"]) @login_required def send_pending(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) if request.method == "POST": action = request.form["action"] if action == "deletepsbt": try: wallet.delete_pending_psbt( ast.literal_eval(request.form["pending_psbt"])["tx"]["txid"] ) except Exception as e: app.logger.error("Could not delete Pending PSBT: %s" % e) flash("Could not delete Pending PSBT!", "error") elif action == "openpsbt": psbt = ast.literal_eval(request.form["pending_psbt"]) return render_template( "wallet/send/sign/wallet_send_sign_psbt.jinja", psbt=psbt, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) pending_psbts = wallet.pending_psbts ######## Migration to multiple recipients format ############### for psbt in pending_psbts: if not isinstance(pending_psbts[psbt]["address"], list): pending_psbts[psbt]["address"] = [pending_psbts[psbt]["address"]] pending_psbts[psbt]["amount"] = [pending_psbts[psbt]["amount"]] ############################################################### return render_template( "wallet/send/pending/wallet_sendpending.jinja", pending_psbts=pending_psbts, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, ) @wallets_endpoint.route("/wallet/<wallet_alias>/send/import", methods=["GET", "POST"]) @login_required def import_psbt(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) if request.method == "POST": action = request.form["action"] if action == "importpsbt": try: b64psbt = "".join(request.form["rawpsbt"].split()) psbt = wallet.importpsbt(b64psbt) except Exception as e: flash("Could not import PSBT: %s" % e, "error") return redirect( url_for("wallets_endpoint.import_psbt", wallet_alias=wallet_alias) ) return render_template( "wallet/send/sign/wallet_send_sign_psbt.jinja", psbt=psbt, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) err = None return render_template( "wallet/send/import/wallet_importpsbt.jinja", wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, error=err, ) ###### Wallet addresses ###### @wallets_endpoint.route("/wallet/<wallet_alias>/addresses/", methods=["GET"]) @login_required def addresses(wallet_alias): """Show informations about cached addresses (wallet._addresses) of the <wallet_alias>. It updates balances in the wallet before renderization in order to show updated UTXO and balance of each address.""" wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) # update balances in the wallet app.specter.check_blockheight() wallet.get_balance() wallet.check_utxo() return render_template( "wallet/addresses/wallet_addresses.jinja", wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, ) ###### Wallet settings ###### @wallets_endpoint.route("/wallet/<wallet_alias>/settings/", methods=["GET", "POST"]) @login_required def settings(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) error = None if request.method == "POST": action = request.form["action"] if action == "rescanblockchain": startblock = int(request.form["startblock"]) try: delete_file(wallet._transactions.path) wallet.fetch_transactions() res = wallet.rpc.rescanblockchain(startblock, timeout=1) except requests.exceptions.ReadTimeout: # this is normal behaviour in our usecase pass except Exception as e: app.logger.error("%s while rescanblockchain" % e) error = "%r" % e wallet.getdata() elif action == "abortrescan": res = wallet.rpc.abortrescan() if not res: error = "Failed to abort rescan. Maybe already complete?" wallet.getdata() elif action == "rescanutxo": explorer = None if "use_explorer" in request.form: if request.form["explorer"] == "CUSTOM": explorer = request.form["custom_explorer"] else: explorer = app.config["EXPLORERS_LIST"][request.form["explorer"]][ "url" ] wallet.rescanutxo( explorer, app.specter.requests_session(explorer), app.specter.only_tor ) app.specter.info["utxorescan"] = 1 app.specter.utxorescanwallet = wallet.alias elif action == "abortrescanutxo": app.specter.abortrescanutxo() app.specter.info["utxorescan"] = None app.specter.utxorescanwallet = None elif action == "keypoolrefill": delta = int(request.form["keypooladd"]) wallet.keypoolrefill(wallet.keypool, wallet.keypool + delta) wallet.keypoolrefill( wallet.change_keypool, wallet.change_keypool + delta, change=True ) wallet.getdata() elif action == "deletewallet": app.specter.wallet_manager.delete_wallet( wallet, app.specter.bitcoin_datadir, app.specter.chain ) response = redirect(url_for("index")) return response elif action == "rename": wallet_name = request.form["newtitle"] if not wallet_name: flash("Wallet name cannot be empty", "error") elif wallet_name == wallet.name: pass elif wallet_name in app.specter.wallet_manager.wallets_names: flash("Wallet already exists", "error") else: app.specter.wallet_manager.rename_wallet(wallet, wallet_name) return render_template( "wallet/settings/wallet_settings.jinja", purposes=purposes, wallet_alias=wallet_alias, wallet=wallet, specter=app.specter, rand=rand, error=error, ) ################## Wallet util endpoints ####################### # TODO: move these to an API endpoint @wallets_endpoint.route("/wallet/<wallet_alias>/combine/", methods=["POST"]) @login_required def combine(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) # only post requests # FIXME: ugly... txid = request.form.get("txid") psbts = [request.form.get("psbt0").strip(), request.form.get("psbt1").strip()] raw = {} combined = None for i, psbt in enumerate(psbts): if not psbt: return "Cannot parse empty data as PSBT", 500 if "UR:BYTES/" in psbt.upper(): psbt = bcur2base64(psbt).decode() # if electrum then it's base43 try: decoded = b43_decode(psbt) if decoded.startswith(b"psbt\xff"): psbt = b2a_base64(decoded).decode() else: psbt = decoded.hex() except: pass psbts[i] = psbt # psbt should start with cHNi # if not - maybe finalized hex tx if not psbt.startswith("cHNi"): raw["hex"] = psbt combined = psbts[1 - i] # check it's hex try: bytes.fromhex(psbt) except: return "Invalid transaction format", 500 try: if "hex" in raw: raw["complete"] = True raw["psbt"] = combined else: combined = app.specter.combine(psbts) raw = app.specter.finalize(combined) if "psbt" not in raw: raw["psbt"] = combined psbt = wallet.update_pending_psbt(combined, txid, raw) raw["devices"] = psbt["devices_signed"] except RpcError as e: return e.error_msg, e.status_code except Exception as e: return "Unknown error: %r" % e, 500 return json.dumps(raw) @wallets_endpoint.route("/wallet/<wallet_alias>/broadcast/", methods=["GET", "POST"]) @login_required def broadcast(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) if request.method == "POST": tx = request.form.get("tx") res = wallet.rpc.testmempoolaccept([tx])[0] if res["allowed"]: app.specter.broadcast(tx) wallet.delete_pending_psbt(get_txid(tx)) return jsonify(success=True) else: return jsonify( success=False, error="Failed to broadcast transaction: transaction is invalid\n%s" % res["reject-reason"], ) return jsonify(success=False, error="broadcast tx request must use POST") @wallets_endpoint.route("/wallet/<wallet_alias>/decoderawtx/", methods=["GET", "POST"]) @login_required @app.csrf.exempt def decoderawtx(wallet_alias): try: wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) txid = request.form.get("txid", "") if txid: tx = wallet.rpc.gettransaction(txid) # This is a fix for Bitcoin Core versions < v0.20 # These do not return the blockheight as part of the `gettransaction` command # So here we check if this property is lacking and if so # query the blockheader based on the transaction blockhash ##################### Remove from here after dropping Core v0.19 support ##################### if "blockhash" in tx and "blockheight" not in tx: tx["blockheight"] = wallet.rpc.getblockheader(tx["blockhash"])["height"] ##################### Remove until here after dropping Core v0.19 support ##################### if tx["confirmations"] == 0: tx["is_purged"] = wallet.is_tx_purged(txid) return { "success": True, "tx": tx, "rawtx": decoderawtransaction(tx["hex"], app.specter.chain), "walletName": wallet.name, } except Exception as e: app.logger.warning("Failed to fetch transaction data. Exception: {}".format(e)) return {"success": False} @wallets_endpoint.route( "/wallet/<wallet_alias>/rescan_progress", methods=["GET", "POST"] ) @login_required @app.csrf.exempt def rescan_progress(wallet_alias): try: wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) wallet.get_info() return { "active": wallet.rescan_progress is not None, "progress": wallet.rescan_progress, } except SpecterError as se: app.logger.error("SpecterError while get wallet rescan_progress: %s" % se) return {} @wallets_endpoint.route("/wallet/<wallet_alias>/get_label", methods=["POST"]) @login_required def get_label(wallet_alias): try: wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) address = request.form.get("address", "") label = wallet.getlabel(address) return { "address": address, "label": label, } except Exception as e: handle_exception(e) return { "success": False, "error": f"Exception trying to get address label: Error: {e}", } @wallets_endpoint.route("/wallet/<wallet_alias>/set_label", methods=["POST"]) @login_required def set_label(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) address = request.form["address"] label = request.form["label"] wallet.setlabel(address, label) return {"success": True} @wallets_endpoint.route("/wallet/<wallet_alias>/txlist", methods=["POST"]) @login_required @app.csrf.exempt def txlist(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) idx = int(request.form.get("idx", 0)) limit = int(request.form.get("limit", 100)) search = request.form.get("search", None) sortby = request.form.get("sortby", None) sortdir = request.form.get("sortdir", "asc") fetch_transactions = request.form.get("fetch_transactions", False) txlist = wallet.txlist( fetch_transactions=fetch_transactions, validate_merkle_proofs=app.specter.config.get("validate_merkle_proofs", False), current_blockheight=app.specter.info["blocks"], ) return process_txlist( txlist, idx=idx, limit=limit, search=search, sortby=sortby, sortdir=sortdir ) @wallets_endpoint.route("/wallet/<wallet_alias>/utxo_list", methods=["POST"]) @login_required @app.csrf.exempt def utxo_list(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) idx = int(request.form.get("idx", 0)) limit = int(request.form.get("limit", 100)) search = request.form.get("search", None) sortby = request.form.get("sortby", None) sortdir = request.form.get("sortdir", "asc") txlist = wallet.full_utxo for tx in txlist: if not tx.get("label", None): tx["label"] = wallet.getlabel(tx["address"]) return process_txlist( txlist, idx=idx, limit=limit, search=search, sortby=sortby, sortdir=sortdir ) @wallets_endpoint.route("/wallets_overview/txlist", methods=["POST"]) @login_required @app.csrf.exempt def wallets_overview_txlist(): idx = int(request.form.get("idx", 0)) limit = int(request.form.get("limit", 100)) search = request.form.get("search", None) sortby = request.form.get("sortby", None) sortdir = request.form.get("sortdir", "asc") fetch_transactions = request.form.get("fetch_transactions", False) txlist = app.specter.wallet_manager.full_txlist( fetch_transactions=fetch_transactions, validate_merkle_proofs=app.specter.config.get("validate_merkle_proofs", False), current_blockheight=app.specter.info["blocks"], ) return process_txlist( txlist, idx=idx, limit=limit, search=search, sortby=sortby, sortdir=sortdir ) @wallets_endpoint.route("/wallets_overview/utxo_list", methods=["POST"]) @login_required @app.csrf.exempt def wallets_overview_utxo_list(): idx = int(request.form.get("idx", 0)) limit = int(request.form.get("limit", 100)) search = request.form.get("search", None) sortby = request.form.get("sortby", None) sortdir = request.form.get("sortdir", "asc") fetch_transactions = request.form.get("fetch_transactions", False) txlist = app.specter.wallet_manager.full_utxo() return process_txlist( txlist, idx=idx, limit=limit, search=search, sortby=sortby, sortdir=sortdir ) @wallets_endpoint.route("/wallet/<wallet_alias>/addresses_list/", methods=["POST"]) @login_required @app.csrf.exempt def addresses_list(wallet_alias): """Return a JSON with keys: addressesList: list of addresses with the properties (index, address, label, used, utxo, amount) pageCount: total number of pages POST parameters: idx: pagination index (current page) limit: maximum number of items on the page sortby: field by which the list will be ordered (index, address, label, used, utxo, amount) sortdir: 'asc' (ascending) or 'desc' (descending) order addressType: the current tab address type ('receive' or 'change')""" wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) idx = int(request.form.get("idx", 0)) limit = int(request.form.get("limit", 100)) sortby = request.form.get("sortby", None) sortdir = request.form.get("sortdir", "asc") address_type = request.form.get("addressType", "receive") addresses_list = wallet.addresses_info(address_type == "change") result = process_addresses_list( addresses_list, idx=idx, limit=limit, sortby=sortby, sortdir=sortdir ) return { "addressesList": json.dumps(result["addressesList"]), "pageCount": result["pageCount"], } @wallets_endpoint.route("/wallet/<wallet_alias>/addressinfo/", methods=["POST"]) @login_required @app.csrf.exempt def addressinfo(wallet_alias): try: wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) address = request.form.get("address", "") if address: descriptor = wallet.get_descriptor(address=address) address_info = wallet.get_address_info(address=address) return { "success": True, "address": address, "descriptor": descriptor, "walletName": wallet.name, "isMine": not address_info.is_external, **address_info, } except Exception as e: app.logger.warning("Failed to fetch address data. Exception: {}".format(e)) return {"success": False} ################## Wallet CSV export data endpoints ####################### # Export wallet addresses list @wallets_endpoint.route("/wallet/<wallet_alias>/addresses_list.csv") @login_required def addresses_list_csv(wallet_alias): """Return a CSV with addresses of the <wallet_alias> containing the information: index, address, type, label, used, utxo and amount of each of them. GET parameters: sortby: field by which the CSV will be ordered (index, address, label, used, utxo, amount) sortdir: 'asc' (ascending) or 'desc' (descending) order address_type: the current tab address type ('receive' or 'change') onlyCurrentType: show all addresses (if false) or just the current type (address_type param)""" try: wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) sortby = request.args.get("sortby", "index") sortdir = request.args.get("sortdir", "asc") address_type = request.args.get("addressType", "receive") only_current_type = request.args.get("onlyCurrentType", "false") == "true" if not only_current_type: receive_list = wallet.addresses_info(False) change_list = wallet.addresses_info(True) receive_result = process_addresses_list( receive_list, idx=0, limit=0, sortby=sortby, sortdir=sortdir ) change_result = process_addresses_list( change_list, idx=0, limit=0, sortby=sortby, sortdir=sortdir ) addressesList = ( receive_result["addressesList"] + change_result["addressesList"] ) else: addresses_list = wallet.addresses_info(address_type == "change") result = process_addresses_list( addresses_list, idx=0, limit=0, sortby=sortby, sortdir=sortdir ) addressesList = result["addressesList"] # stream the response as the data is generated response = Response( wallet_addresses_list_to_csv(addressesList), mimetype="text/csv", ) # add a filename response.headers.set( "Content-Disposition", "attachment", filename="addresses_list.csv" ) return response except Exception as e: app.logger.error("Failed to export addresses list. Error: %s" % e) flash("Failed to export addresses list. Error: %s" % e, "error") return redirect(url_for("index")) # Export wallet transaction history @wallets_endpoint.route("/wallet/<wallet_alias>/transactions.csv") @login_required def tx_history_csv(wallet_alias): wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) validate_merkle_proofs = app.specter.config.get("validate_merkle_proofs", False) txlist = wallet.txlist(validate_merkle_proofs=validate_merkle_proofs) search = request.args.get("search", None) sortby = request.args.get("sortby", "time") sortdir = request.args.get("sortdir", "desc") txlist = json.loads( process_txlist( txlist, idx=0, limit=0, search=search, sortby=sortby, sortdir=sortdir )["txlist"] ) includePricesHistory = request.args.get("exportPrices", "false") == "true" # stream the response as the data is generated response = Response( txlist_to_csv(wallet, txlist, app.specter, current_user, includePricesHistory), mimetype="text/csv", ) # add a filename response.headers.set( "Content-Disposition", "attachment", filename="transactions.csv" ) return response # Export wallet UTXO list @wallets_endpoint.route("/wallet/<wallet_alias>/utxo.csv") @login_required def utxo_csv(wallet_alias): try: wallet = app.specter.wallet_manager.get_by_alias(wallet_alias) includePricesHistory = request.args.get("exportPrices", "false") == "true" search = request.args.get("search", None) sortby = request.args.get("sortby", "time") sortdir = request.args.get("sortdir", "desc") txlist = json.loads( process_txlist( wallet.full_utxo, idx=0, limit=0, search=search, sortby=sortby, sortdir=sortdir, )["txlist"] ) # stream the response as the data is generated response = Response( txlist_to_csv( wallet, txlist, app.specter, current_user, includePricesHistory, ), mimetype="text/csv", ) # add a filename response.headers.set("Content-Disposition", "attachment", filename="utxo.csv") return response except Exception as e: logging.exception(e) return "Failed to export wallet utxo. Error: %s" % e, 500 # Export all wallets transaction history combined @wallets_endpoint.route("/wallets_overview/full_transactions.csv") @login_required def wallet_overview_txs_csv(): try: validate_merkle_proofs = app.specter.config.get("validate_merkle_proofs", False) txlist = app.specter.wallet_manager.full_txlist( validate_merkle_proofs=validate_merkle_proofs ) search = request.args.get("search", None) sortby = request.args.get("sortby", "time") sortdir = request.args.get("sortdir", "desc") txlist = json.loads( process_txlist( txlist, idx=0, limit=0, search=search, sortby=sortby, sortdir=sortdir )["txlist"] ) includePricesHistory = request.args.get("exportPrices", "false") == "true" # stream the response as the data is generated response = Response( txlist_to_csv( None, txlist, app.specter, current_user, includePricesHistory ), mimetype="text/csv", ) # add a filename response.headers.set( "Content-Disposition", "attachment", filename="full_transactions.csv" ) return response except Exception as e: logging.exception(e) return "Failed to export wallets overview history. Error: %s" % e, 500 # Export all wallets transaction history combined @wallets_endpoint.route("/wallets_overview/full_utxo.csv") @login_required def wallet_overview_utxo_csv(): try: txlist = app.specter.wallet_manager.full_utxo() search = request.args.get("search", None) sortby = request.args.get("sortby", "time") sortdir = request.args.get("sortdir", "desc") txlist = json.loads( process_txlist( txlist, idx=0, limit=0, search=search, sortby=sortby, sortdir=sortdir )["txlist"] ) includePricesHistory = request.args.get("exportPrices", "false") == "true" # stream the response as the data is generated response = Response( txlist_to_csv( None, txlist, app.specter, current_user, includePricesHistory ), mimetype="text/csv", ) # add a filename response.headers.set( "Content-Disposition", "attachment", filename="full_utxo.csv" ) return response except Exception as e: logging.exception(e) return "Failed to export wallets overview utxo. Error: %s" % e, 500 ################## Helpers ####################### # Transactions list to user-friendly CSV format def txlist_to_csv(wallet, _txlist, specter, current_user, includePricesHistory=False): txlist = [] for tx in _txlist: if isinstance(tx["address"], list): _tx = tx.copy() for i in range(0, len(tx["address"])): _tx["address"] = tx["address"][i] _tx["amount"] = tx["amount"][i] txlist.append(_tx.copy()) else: txlist.append(tx.copy()) data = StringIO() w = csv.writer(data) # write header symbol = "USD" if specter.price_provider.endswith("_eur"): symbol = "EUR" elif specter.price_provider.endswith("_gbp"): symbol = "GBP" row = ( "Date", "Label", "Category", "Amount ({})".format(specter.unit.upper()), "Value ({})".format(symbol), "Rate (BTC/{})".format(symbol) if specter.unit != "sat" else "Rate ({}/SAT)".format(symbol), "TxID", "Address", "Block Height", "Timestamp", "Raw Transaction", ) if not wallet: row = ("Wallet",) + row w.writerow(row) yield data.getvalue() data.seek(0) data.truncate(0) # write each log item _wallet = wallet for tx in txlist: if not wallet: wallet_alias = tx.get("wallet_alias", None) try: _wallet = specter.wallet_manager.get_by_alias(wallet_alias) except Exception as e: continue label = _wallet.getlabel(tx["address"]) if label == tx["address"]: label = "" tx_raw = _wallet.gettransaction(tx["txid"]) if tx_raw: tx_hex = tx_raw["hex"] else: tx_hex = "" if not tx.get("blockheight", None): if tx_raw.get("blockheight", None): tx["blockheight"] = tx_raw["blockheight"] else: tx["blockheight"] = "Unconfirmed" if specter.unit == "sat": value = float(tx["amount"]) tx["amount"] = round(value * 1e8) if includePricesHistory: success, rate, symbol = get_price_at( specter, current_user, timestamp=tx["time"] ) else: success = False if success: rate = float(rate) if specter.unit == "sat": rate = rate / 1e8 amount_price = float(tx["amount"]) * rate if specter.unit == "sat": rate = round(1 / rate) else: amount_price = None rate = "-" row = ( time.strftime("%Y-%m-%d", time.localtime(tx["time"])), label, tx["category"], round(tx["amount"], (0 if specter.unit == "sat" else 8)), round(amount_price * 100) / 100 if amount_price is not None else "-", rate, tx["txid"], tx["address"], tx["blockheight"], tx["time"], tx_hex, ) if not wallet: row = (tx.get("wallet_alias", ""),) + row w.writerow(row) yield data.getvalue() data.seek(0) data.truncate(0) # Addresses list to user-friendly CSV format def addresses_list_to_csv(wallet): data = StringIO() w = csv.writer(data) # write header row = ( "Address", "Label", "Index", "Used", "Current balance", ) w.writerow(row) yield data.getvalue() data.seek(0) data.truncate(0) # write each log item for address in wallet._addresses: address_info = wallet.get_address_info(address) if not address_info.is_labeled and not address_info.used: continue row = ( address, address_info.label, "(external)" if address_info.is_external else ( str(address_info.index) + (" (change)" if address_info.change else "") ), address_info.used, ) if address_info.is_external: balance_on_address = "unknown (external address)" else: balance_on_address = 0 if address_info.used: for tx in wallet.full_utxo: if tx.get("address", "") == address: balance_on_address += tx.get("amount", 0) row += (balance_on_address,) w.writerow(row) yield data.getvalue() data.seek(0) data.truncate(0) def wallet_addresses_list_to_csv(addresses_list): """Convert a list of the wallet addresses to user-friendly CSV format Parameters: addresses_list: a dict of addresses informations (index, address, type, label, used, utxo and amount)""" data = StringIO() w = csv.writer(data) # write header row = ( "Index", "Address", "Type", "Label", "Used", "UTXO", "Amount (BTC)", ) w.writerow(row) yield data.getvalue() data.seek(0) data.truncate(0) # write each log item for address_item in addresses_list: used = "Yes" if address_item["used"] else "No" row = ( address_item["index"], address_item["address"], address_item["type"], address_item["label"], used, address_item["utxo"], address_item["amount"], ) w.writerow(row) yield data.getvalue() data.seek(0) data.truncate(0) def process_txlist(txlist, idx=0, limit=100, search=None, sortby=None, sortdir="asc"): if search: txlist = [ tx for tx in txlist if search in tx["txid"] or ( any(search in address for address in tx["address"]) if isinstance(tx["address"], list) else search in tx["address"] ) or ( any(search in label for label in tx["label"]) if isinstance(tx["label"], list) else search in tx["label"] ) or ( any(search in str(amount) for amount in tx["amount"]) if isinstance(tx["amount"], list) else search in str(tx["amount"]) ) or search in str(tx["confirmations"]) or search in str(tx["time"]) or search in str(format(datetime.fromtimestamp(tx["time"]), "%d.%m.%Y %H:%M")) ] if sortby: def sort(tx): val = tx.get(sortby, None) final = val if val: if isinstance(val, list): if isinstance(val[0], Number): final = sum(val) elif isinstance(val[0], str): final = sorted( val, key=lambda s: s.lower(), reverse=sortdir != "asc" )[0].lower() elif isinstance(val, str): final = val.lower() return final txlist = sorted(txlist, key=sort, reverse=sortdir != "asc") if limit: page_count = (len(txlist) // limit) + (0 if len(txlist) % limit == 0 else 1) txlist = txlist[limit * idx : limit * (idx + 1)] else: page_count = 1 return {"txlist": json.dumps(txlist), "pageCount": page_count} def process_addresses_list( addresses_list, idx=0, limit=100, sortby=None, sortdir="asc" ): """Receive an address list as parameter and sort it or slice it for pagination. Parameters: addresses_list: list of dict with the keys (index, address, label, used, utxo, amount) idx: pagination index (current page) limit: maximum number of items on the page sortby: field by which the list will be ordered (index, address, label, used, utxo, amount) sortdir: 'asc' (ascending) or 'desc' (descending) order""" if sortby: def sort(addr): val = addr.get(sortby, None) final = val if val: if isinstance(val, str): final = val.lower() return final addresses_list = sorted(addresses_list, key=sort, reverse=sortdir != "asc") if limit: page_count = (len(addresses_list) // limit) + ( 0 if len(addresses_list) % limit == 0 else 1 ) addresses_list = addresses_list[limit * idx : limit * (idx + 1)] else: page_count = 1 return {"addressesList": addresses_list, "pageCount": page_count}
""" HTTP REquest introspection """ import sys import logging import click import requests import pyld try: import orjson as json except ModuleNotFoundError: import json import opersist.rdfutils # import igsn_lib.link_requests LOG_LEVELS = { "DEBUG": logging.DEBUG, "INFO": logging.INFO, "WARNING": logging.WARNING, "WARN": logging.WARNING, "ERROR": logging.ERROR, "FATAL": logging.CRITICAL, "CRITICAL": logging.CRITICAL, } LOG_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S" LOG_FORMAT = "%(asctime)s %(name)s:%(levelname)s: %(message)s" TIMEOUT = 10.0 # seconds # https://tools.ietf.org/html/rfc7231#section-5.5.3 USER_AGENT = "curly/0.1;python/3.9" # "curl/7.64.1" # def loadJsonLD(response, normalize=True): jsonld = pyld.jsonld.load_html( response.content, response.url, profile=None, options={"extractAllScripts": True}, ) if normalize: return opersist.rdfutils.normalizeSONamespace(jsonld, base=response.url) return jsonld def getJsonLDChecksum(jsonld): pass def printResponseInfo(r, show_response=False, show_json=False, f=sys.stderr): l = [] l += f"{r.url}\n" l += f" status: {r.status_code}\n" l += f" date: {r.headers.get("Date", "-")}\n" l += f" last-modified: {r.headers.get("Last-Modified", "-")}\n" l += f" content-type: {r.headers.get("Content-Type", "-")}\n" l += f" link: {r.headers.get("Link", "-")}\n" l += f" elapsed: {r.elapsed}\n" f.writelines(l) if show_response: print(r.text) if show_json: jld = loadJsonLD(r) print(json.dumps(jld, indent=2)) def printResponse(response, show_response=False, show_json=False, f=sys.stderr): L = logging.getLogger("printResponse") L.debug(response.request.headers) i = 0 l = [] for r in response.history: f.write(f"Response {i}\n") printResponseInfo(r, f=f) i += 1 f.write(f"Response {i}\n") printResponseInfo(response, show_response=show_response, show_json=show_json, f=f) def printResponsePath(response): i = 0 status_code = "" content_type = "" for r in response.history: print(f"{i:02}:{status_code:>4} {content_type} {r.url}") status_code = r.status_code content_type = f"Content-Type: {r.headers.get("Content-Type", "-")}" i += 1 r = response print(f"{i:02}:{status_code:>4} {content_type} {r.url}") status_code = r.status_code content_type = f"Content-Type: {r.headers.get("Content-Type", "-")}" i += 1 print(f"{i:02}:{status_code:>4} {content_type}") @click.group() @click.option( "-V", "--verbosity", default="INFO", help="Specify logging level", show_default=True, ) @click.pass_context def main(ctx, verbosity): ctx.ensure_object(dict) verbosity = verbosity.upper() logging.basicConfig( level=LOG_LEVELS.get(verbosity, logging.INFO), format=LOG_FORMAT, datefmt=LOG_DATE_FORMAT, ) L = logging.getLogger("main") if verbosity not in LOG_LEVELS.keys(): L.warning("%s is not a log level, set to INFO", verbosity) # ctx.obj["folder"] = os.path.abspath(folder) @main.command("jsonld") @click.argument("url") @click.option("-a", "--accept", default="*/*", help="Value for request Accept header") @click.option( "-o", "--original", default=False, show_default=True, is_flag=True, help="Show JSON-LD as extracted with no transformation.", ) @click.option( "-c", "--checksum", default=False, show_default=True, is_flag=True, help="Compute SHA256 checksum.", ) @click.option( "-i", "--identifiers", default=False, show_default=True, is_flag=True, help="Extract identifiers.", ) @click.pass_context def getJsonLD(ctx, url, accept, original, checksum, identifiers): L = logging.getLogger("jsonld") # session = igsn_lib.link_requests.LinkSession() session = requests.Session() # accept = "application/ld+json" headers = { "Accept": accept, "User-Agent": USER_AGENT, } response = session.get(url, headers=headers, allow_redirects=True, timeout=TIMEOUT) for h in response.history: L.info(f"{h.status_code} {h.url}") L.info(f"{response.status_code} {response.url}") jsonld = loadJsonLD(response, normalize=not original) print(json.dumps(jsonld, indent=2)) if checksum: checksums = opersist.rdfutils.computeJSONLDChecksums(jsonld) for k, v in checksums.items(): print(f"{k}:{v}") if identifiers: ids = opersist.rdfutils.extractIdentifiers(jsonld) for g in ids: print(f"@id: {g["@id"]}") print(f" url: {g["url"]}") for i in g["identifier"]: print(f" identifier: {i}") @main.command("hops") @click.argument("url") @click.option("-a", "--accept", default="*/*", help="Value for request Accept header") @click.option( "-b", "--show-body", default=False, show_default=True, is_flag=True, help="Show response body.", ) @click.option( "--path-only", default=False, show_default=True, is_flag=True, help="Show path to resolution only", ) @click.pass_context def doResolve(ctx, url, accept, show_body, path_only): L = logging.getLogger("hops") # session = igsn_lib.link_requests.LinkSession() session = requests.Session() headers = { "Accept": accept, "User-Agent": USER_AGENT, } response = session.get(url, headers=headers, allow_redirects=True, timeout=TIMEOUT) if path_only: printResponsePath(response) else: printResponse(response, show_response=show_body, show_json=False) if __name__ == "__main__": main()
""" HTTP REquest introspection """ import sys import logging import click import requests import pyld try: import orjson as json except ModuleNotFoundError: import json import opersist.rdfutils # import igsn_lib.link_requests LOG_LEVELS = { "DEBUG": logging.DEBUG, "INFO": logging.INFO, "WARNING": logging.WARNING, "WARN": logging.WARNING, "ERROR": logging.ERROR, "FATAL": logging.CRITICAL, "CRITICAL": logging.CRITICAL, } LOG_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S" LOG_FORMAT = "%(asctime)s %(name)s:%(levelname)s: %(message)s" TIMEOUT = 10.0 # seconds # https://tools.ietf.org/html/rfc7231#section-5.5.3 USER_AGENT = "curly/0.1;python/3.9" # "curl/7.64.1" # def loadJsonLD(response, normalize=True): jsonld = pyld.jsonld.load_html( response.content, response.url, profile=None, options={"extractAllScripts": True}, ) if normalize: return opersist.rdfutils.normalizeSONamespace(jsonld, base=response.url) return jsonld def getJsonLDChecksum(jsonld): pass def printResponseInfo(r, show_response=False, show_json=False, f=sys.stderr): l = [] l += f"{r.url}\n" l += f" status: {r.status_code}\n" l += f" date: {r.headers.get('Date', '-')}\n" l += f" last-modified: {r.headers.get('Last-Modified', '-')}\n" l += f" content-type: {r.headers.get('Content-Type', '-')}\n" l += f" link: {r.headers.get('Link', '-')}\n" l += f" elapsed: {r.elapsed}\n" f.writelines(l) if show_response: print(r.text) if show_json: jld = loadJsonLD(r) print(json.dumps(jld, indent=2)) def printResponse(response, show_response=False, show_json=False, f=sys.stderr): L = logging.getLogger("printResponse") L.debug(response.request.headers) i = 0 l = [] for r in response.history: f.write(f"Response {i}\n") printResponseInfo(r, f=f) i += 1 f.write(f"Response {i}\n") printResponseInfo(response, show_response=show_response, show_json=show_json, f=f) def printResponsePath(response): i = 0 status_code = "" content_type = "" for r in response.history: print(f"{i:02}:{status_code:>4} {content_type} {r.url}") status_code = r.status_code content_type = f"Content-Type: {r.headers.get('Content-Type', '-')}" i += 1 r = response print(f"{i:02}:{status_code:>4} {content_type} {r.url}") status_code = r.status_code content_type = f"Content-Type: {r.headers.get('Content-Type', '-')}" i += 1 print(f"{i:02}:{status_code:>4} {content_type}") @click.group() @click.option( "-V", "--verbosity", default="INFO", help="Specify logging level", show_default=True, ) @click.pass_context def main(ctx, verbosity): ctx.ensure_object(dict) verbosity = verbosity.upper() logging.basicConfig( level=LOG_LEVELS.get(verbosity, logging.INFO), format=LOG_FORMAT, datefmt=LOG_DATE_FORMAT, ) L = logging.getLogger("main") if verbosity not in LOG_LEVELS.keys(): L.warning("%s is not a log level, set to INFO", verbosity) # ctx.obj["folder"] = os.path.abspath(folder) @main.command("jsonld") @click.argument("url") @click.option("-a", "--accept", default="*/*", help="Value for request Accept header") @click.option( "-o", "--original", default=False, show_default=True, is_flag=True, help="Show JSON-LD as extracted with no transformation.", ) @click.option( "-c", "--checksum", default=False, show_default=True, is_flag=True, help="Compute SHA256 checksum.", ) @click.option( "-i", "--identifiers", default=False, show_default=True, is_flag=True, help="Extract identifiers.", ) @click.pass_context def getJsonLD(ctx, url, accept, original, checksum, identifiers): L = logging.getLogger("jsonld") # session = igsn_lib.link_requests.LinkSession() session = requests.Session() # accept = "application/ld+json" headers = { "Accept": accept, "User-Agent": USER_AGENT, } response = session.get(url, headers=headers, allow_redirects=True, timeout=TIMEOUT) for h in response.history: L.info(f"{h.status_code} {h.url}") L.info(f"{response.status_code} {response.url}") jsonld = loadJsonLD(response, normalize=not original) print(json.dumps(jsonld, indent=2)) if checksum: checksums = opersist.rdfutils.computeJSONLDChecksums(jsonld) for k, v in checksums.items(): print(f"{k}:{v}") if identifiers: ids = opersist.rdfutils.extractIdentifiers(jsonld) for g in ids: print(f"@id: {g['@id']}") print(f" url: {g['url']}") for i in g["identifier"]: print(f" identifier: {i}") @main.command("hops") @click.argument("url") @click.option("-a", "--accept", default="*/*", help="Value for request Accept header") @click.option( "-b", "--show-body", default=False, show_default=True, is_flag=True, help="Show response body.", ) @click.option( "--path-only", default=False, show_default=True, is_flag=True, help="Show path to resolution only", ) @click.pass_context def doResolve(ctx, url, accept, show_body, path_only): L = logging.getLogger("hops") # session = igsn_lib.link_requests.LinkSession() session = requests.Session() headers = { "Accept": accept, "User-Agent": USER_AGENT, } response = session.get(url, headers=headers, allow_redirects=True, timeout=TIMEOUT) if path_only: printResponsePath(response) else: printResponse(response, show_response=show_body, show_json=False) if __name__ == "__main__": main()
import os import random from core.dm import csc, Pr, PTurn from core.reminder import REMINDER CODEWORD = os.environ.get('CODEWORD') or str(random.random()) @csc.add_handler(priority=Pr.STRONG_INTENT, regexp='.*выслать напоминание.*') def ask_for_reminders(turn: PTurn): turn.response_text = 'Чтобы разослать напоминания, пожалуйста, назовите кодовое слово.' turn.next_stage = 'send_reminders' @csc.add_handler(priority=Pr.STAGE, regexp=CODEWORD, stages=['send_reminders']) def send_reminders(turn: PTurn): if not REMINDER.bot: turn.response_text = 'У ремайндера не настроен бот, к сожалению.' return if not REMINDER.users_collection: turn.response_text = 'У ремайндера не настроена база данных, к сожалению.' return result = REMINDER.iterate_users() turn.response_text = f'Разослал уведомления! ' \ f'{result['half_forms']} - о незавершенных анкетах, {result['new_forms']} - о новых.' @csc.add_handler(priority=Pr.STRONG_INTENT, regexp='.*массов.. рассылк.*') def ask_for_sendout(turn: PTurn): turn.response_text = 'Чтобы сделать массовую рассылку, пожалуйста, назовите кодовое слово.' turn.next_stage = 'ask_sendout_codeword' @csc.add_handler(priority=Pr.STAGE, regexp=CODEWORD, stages=['ask_sendout_codeword']) def ask_sendout_codeword(turn: PTurn): turn.response_text = 'Кодовое слово принято! Теперь отправьте мне сообщение, которое вы хотите разослать ' \ 'ВСЕМ ПОДПИСЧИКАМ БОТА. Если вы передумали, скажите "нет".' turn.suggests.append('нет') turn.next_stage = 'sendout' @csc.add_handler(priority=Pr.STRONG_INTENT, stages=['sendout'], regexp='нет') def sendout_cancel(turn: PTurn): turn.next_stage = None turn.response_text = 'Окей, я не буду делать рассылку.' @csc.add_handler(priority=Pr.WEAK_STAGE, stages=['sendout']) def sendout(turn: PTurn): turn.next_stage = None if not REMINDER.bot: turn.response_text = 'У ремайндера не настроен бот, к сожалению.' return if not REMINDER.users_collection: turn.response_text = 'У ремайндера не настроена база данных, к сожалению.' return result = REMINDER.send_to_everyone(text=turn.text) turn.response_text = f'Разослал ваше сообщение! ' \ f'Оно было отправлено всем {result} пользователям (кроме тех, которые заблокировали бота). '
import os import random from core.dm import csc, Pr, PTurn from core.reminder import REMINDER CODEWORD = os.environ.get('CODEWORD') or str(random.random()) @csc.add_handler(priority=Pr.STRONG_INTENT, regexp='.*выслать напоминание.*') def ask_for_reminders(turn: PTurn): turn.response_text = 'Чтобы разослать напоминания, пожалуйста, назовите кодовое слово.' turn.next_stage = 'send_reminders' @csc.add_handler(priority=Pr.STAGE, regexp=CODEWORD, stages=['send_reminders']) def send_reminders(turn: PTurn): if not REMINDER.bot: turn.response_text = 'У ремайндера не настроен бот, к сожалению.' return if not REMINDER.users_collection: turn.response_text = 'У ремайндера не настроена база данных, к сожалению.' return result = REMINDER.iterate_users() turn.response_text = f'Разослал уведомления! ' \ f'{result["half_forms"]} - о незавершенных анкетах, {result["new_forms"]} - о новых.' @csc.add_handler(priority=Pr.STRONG_INTENT, regexp='.*массов.. рассылк.*') def ask_for_sendout(turn: PTurn): turn.response_text = 'Чтобы сделать массовую рассылку, пожалуйста, назовите кодовое слово.' turn.next_stage = 'ask_sendout_codeword' @csc.add_handler(priority=Pr.STAGE, regexp=CODEWORD, stages=['ask_sendout_codeword']) def ask_sendout_codeword(turn: PTurn): turn.response_text = 'Кодовое слово принято! Теперь отправьте мне сообщение, которое вы хотите разослать ' \ 'ВСЕМ ПОДПИСЧИКАМ БОТА. Если вы передумали, скажите "нет".' turn.suggests.append('нет') turn.next_stage = 'sendout' @csc.add_handler(priority=Pr.STRONG_INTENT, stages=['sendout'], regexp='нет') def sendout_cancel(turn: PTurn): turn.next_stage = None turn.response_text = 'Окей, я не буду делать рассылку.' @csc.add_handler(priority=Pr.WEAK_STAGE, stages=['sendout']) def sendout(turn: PTurn): turn.next_stage = None if not REMINDER.bot: turn.response_text = 'У ремайндера не настроен бот, к сожалению.' return if not REMINDER.users_collection: turn.response_text = 'У ремайндера не настроена база данных, к сожалению.' return result = REMINDER.send_to_everyone(text=turn.text) turn.response_text = f'Разослал ваше сообщение! ' \ f'Оно было отправлено всем {result} пользователям (кроме тех, которые заблокировали бота). '
import importlib import torch from collections import Counter from copy import deepcopy from os import path as osp from torch import distributed as dist from tqdm import tqdm from basicsr.models.sr_model import SRModel from basicsr.utils import get_root_logger, imwrite, tensor2img from basicsr.utils.dist_util import get_dist_info import pdb metric_module = importlib.import_module('basicsr.metrics') class VideoBaseModel(SRModel): """Base video SR model.""" def dist_validation(self, dataloader, current_iter, tb_logger, save_img): dataset = dataloader.dataset dataset_name = dataset.opt['name'] with_metrics = self.opt['val']['metrics'] is not None # initialize self.metric_results # It is a dict: { # 'folder1': tensor (num_frame x len(metrics)), # 'folder2': tensor (num_frame x len(metrics)) # } if with_metrics and not hasattr(self, 'metric_results'): self.metric_results = {} num_frame_each_folder = Counter(dataset.data_info['folder']) for folder, num_frame in num_frame_each_folder.items(): self.metric_results[folder] = torch.zeros( num_frame, len(self.opt['val']['metrics']), dtype=torch.float32, device='cuda') rank, world_size = get_dist_info() if with_metrics: for _, tensor in self.metric_results.items(): tensor.zero_() # record all frames (border and center frames) if rank == 0: pbar = tqdm(total=len(dataset), unit='frame') for idx in range(rank, len(dataset), world_size): val_data = dataset[idx] val_data['lq'].unsqueeze_(0) val_data['gt'].unsqueeze_(0) folder = val_data['folder'] frame_idx, max_idx = val_data['idx'].split('/') lq_path = val_data['lq_path'] self.feed_data(val_data) self.test() visuals = self.get_current_visuals() result_img = tensor2img([visuals['result']]) if 'gt' in visuals: gt_img = tensor2img([visuals['gt']]) del self.gt # tentative for out of GPU memory del self.lq del self.output torch.cuda.empty_cache() if save_img: if self.opt['is_train']: raise NotImplementedError( 'saving image is not supported during training.') else: if 'vimeo' in dataset_name.lower(): # vimeo90k dataset split_result = lq_path.split('/') img_name = (f'{split_result[-3]}_{split_result[-2]}_' f'{split_result[-1].split('.')[0]}') else: # other datasets, e.g., REDS, Vid4 img_name = osp.splitext(osp.basename(lq_path))[0] if self.opt['val']['suffix']: save_img_path = osp.join( self.opt['path']['visualization'], dataset_name, folder, f'{img_name}_{self.opt['val']['suffix']}.png') else: save_img_path = osp.join( self.opt['path']['visualization'], dataset_name, folder, f'{img_name}_{self.opt['name']}.png') imwrite(result_img, save_img_path) if with_metrics: # calculate metrics opt_metric = deepcopy(self.opt['val']['metrics']) for metric_idx, opt_ in enumerate(opt_metric.values()): metric_type = opt_.pop('type') result = getattr(metric_module, metric_type)(result_img, gt_img, **opt_) self.metric_results[folder][int(frame_idx), metric_idx] += result # progress bar if rank == 0: for _ in range(world_size): pbar.update(1) pbar.set_description( f'Test {folder}:' f'{int(frame_idx) + world_size}/{max_idx}') if rank == 0: pbar.close() if with_metrics: if self.opt['dist']: # collect data among GPUs for _, tensor in self.metric_results.items(): dist.reduce(tensor, 0) dist.barrier() else: pass # assume use one gpu in non-dist testing if rank == 0: self._log_validation_metric_values(current_iter, dataset_name, tb_logger) def nondist_validation(self, dataloader, current_iter, tb_logger, save_img): logger = get_root_logger() logger.warning( 'nondist_validation is not implemented. Run dist_validation.') self.dist_validation(dataloader, current_iter, tb_logger, save_img) def _log_validation_metric_values(self, current_iter, dataset_name, tb_logger): # average all frames for each sub-folder # metric_results_avg is a dict:{ # 'folder1': tensor (len(metrics)), # 'folder2': tensor (len(metrics)) # } metric_results_avg = { folder: torch.mean(tensor, dim=0).cpu() for (folder, tensor) in self.metric_results.items() } # total_avg_results is a dict: { # 'metric1': float, # 'metric2': float # } total_avg_results = { metric: 0 for metric in self.opt['val']['metrics'].keys() } for folder, tensor in metric_results_avg.items(): for idx, metric in enumerate(total_avg_results.keys()): total_avg_results[metric] += metric_results_avg[folder][ idx].item() # average among folders for metric in total_avg_results.keys(): total_avg_results[metric] /= len(metric_results_avg) log_str = f'Validation {dataset_name}\n' for metric_idx, (metric, value) in enumerate(total_avg_results.items()): log_str += f'\t # {metric}: {value:.4f}' for folder, tensor in metric_results_avg.items(): log_str += f'\t # {folder}: {tensor[metric_idx].item():.4f}' log_str += '\n' logger = get_root_logger() logger.info(log_str) if tb_logger: for metric_idx, (metric, value) in enumerate(total_avg_results.items()): tb_logger.add_scalar(f'metrics/{metric}', value, current_iter) for folder, tensor in metric_results_avg.items(): tb_logger.add_scalar(f'metrics/{metric}/{folder}', tensor[metric_idx].item(), current_iter)
import importlib import torch from collections import Counter from copy import deepcopy from os import path as osp from torch import distributed as dist from tqdm import tqdm from basicsr.models.sr_model import SRModel from basicsr.utils import get_root_logger, imwrite, tensor2img from basicsr.utils.dist_util import get_dist_info import pdb metric_module = importlib.import_module('basicsr.metrics') class VideoBaseModel(SRModel): """Base video SR model.""" def dist_validation(self, dataloader, current_iter, tb_logger, save_img): dataset = dataloader.dataset dataset_name = dataset.opt['name'] with_metrics = self.opt['val']['metrics'] is not None # initialize self.metric_results # It is a dict: { # 'folder1': tensor (num_frame x len(metrics)), # 'folder2': tensor (num_frame x len(metrics)) # } if with_metrics and not hasattr(self, 'metric_results'): self.metric_results = {} num_frame_each_folder = Counter(dataset.data_info['folder']) for folder, num_frame in num_frame_each_folder.items(): self.metric_results[folder] = torch.zeros( num_frame, len(self.opt['val']['metrics']), dtype=torch.float32, device='cuda') rank, world_size = get_dist_info() if with_metrics: for _, tensor in self.metric_results.items(): tensor.zero_() # record all frames (border and center frames) if rank == 0: pbar = tqdm(total=len(dataset), unit='frame') for idx in range(rank, len(dataset), world_size): val_data = dataset[idx] val_data['lq'].unsqueeze_(0) val_data['gt'].unsqueeze_(0) folder = val_data['folder'] frame_idx, max_idx = val_data['idx'].split('/') lq_path = val_data['lq_path'] self.feed_data(val_data) self.test() visuals = self.get_current_visuals() result_img = tensor2img([visuals['result']]) if 'gt' in visuals: gt_img = tensor2img([visuals['gt']]) del self.gt # tentative for out of GPU memory del self.lq del self.output torch.cuda.empty_cache() if save_img: if self.opt['is_train']: raise NotImplementedError( 'saving image is not supported during training.') else: if 'vimeo' in dataset_name.lower(): # vimeo90k dataset split_result = lq_path.split('/') img_name = (f'{split_result[-3]}_{split_result[-2]}_' f'{split_result[-1].split(".")[0]}') else: # other datasets, e.g., REDS, Vid4 img_name = osp.splitext(osp.basename(lq_path))[0] if self.opt['val']['suffix']: save_img_path = osp.join( self.opt['path']['visualization'], dataset_name, folder, f'{img_name}_{self.opt["val"]["suffix"]}.png') else: save_img_path = osp.join( self.opt['path']['visualization'], dataset_name, folder, f'{img_name}_{self.opt["name"]}.png') imwrite(result_img, save_img_path) if with_metrics: # calculate metrics opt_metric = deepcopy(self.opt['val']['metrics']) for metric_idx, opt_ in enumerate(opt_metric.values()): metric_type = opt_.pop('type') result = getattr(metric_module, metric_type)(result_img, gt_img, **opt_) self.metric_results[folder][int(frame_idx), metric_idx] += result # progress bar if rank == 0: for _ in range(world_size): pbar.update(1) pbar.set_description( f'Test {folder}:' f'{int(frame_idx) + world_size}/{max_idx}') if rank == 0: pbar.close() if with_metrics: if self.opt['dist']: # collect data among GPUs for _, tensor in self.metric_results.items(): dist.reduce(tensor, 0) dist.barrier() else: pass # assume use one gpu in non-dist testing if rank == 0: self._log_validation_metric_values(current_iter, dataset_name, tb_logger) def nondist_validation(self, dataloader, current_iter, tb_logger, save_img): logger = get_root_logger() logger.warning( 'nondist_validation is not implemented. Run dist_validation.') self.dist_validation(dataloader, current_iter, tb_logger, save_img) def _log_validation_metric_values(self, current_iter, dataset_name, tb_logger): # average all frames for each sub-folder # metric_results_avg is a dict:{ # 'folder1': tensor (len(metrics)), # 'folder2': tensor (len(metrics)) # } metric_results_avg = { folder: torch.mean(tensor, dim=0).cpu() for (folder, tensor) in self.metric_results.items() } # total_avg_results is a dict: { # 'metric1': float, # 'metric2': float # } total_avg_results = { metric: 0 for metric in self.opt['val']['metrics'].keys() } for folder, tensor in metric_results_avg.items(): for idx, metric in enumerate(total_avg_results.keys()): total_avg_results[metric] += metric_results_avg[folder][ idx].item() # average among folders for metric in total_avg_results.keys(): total_avg_results[metric] /= len(metric_results_avg) log_str = f'Validation {dataset_name}\n' for metric_idx, (metric, value) in enumerate(total_avg_results.items()): log_str += f'\t # {metric}: {value:.4f}' for folder, tensor in metric_results_avg.items(): log_str += f'\t # {folder}: {tensor[metric_idx].item():.4f}' log_str += '\n' logger = get_root_logger() logger.info(log_str) if tb_logger: for metric_idx, (metric, value) in enumerate(total_avg_results.items()): tb_logger.add_scalar(f'metrics/{metric}', value, current_iter) for folder, tensor in metric_results_avg.items(): tb_logger.add_scalar(f'metrics/{metric}/{folder}', tensor[metric_idx].item(), current_iter)